repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/LauraGentini/QRL
|
LauraGentini
|
__author__ = 'QRL_team'
import numpy as np
from gym import spaces
from itertools import permutations
from qiskit import (
QuantumCircuit,
execute,
Aer)
from qiskit.circuit.library import (
HGate,
XGate,
CXGate)
class QTicTacToeEnv:
def __init__(self, grid_size):
"""
Inits a QTTT environmen
:param grid_size: linear size of the board
"""
# select simulators
self.simulator = Aer.get_backend('qasm_simulator')
self.statevec_sim = Aer.get_backend('statevector_simulator')
# one qubit for each tile of the board
self.qnum = grid_size ** 2
# init board circuit
self.circuit = QuantumCircuit(self.qnum)
# init moves dictionary
self.moves = self._init_moves_dict()
# init action space as a gym space obj, so that agents can interpret it
self.action_space = spaces.Discrete(len(self.moves))
# init dictionary of possible final board configs
self.endings_lookuptable = self._init_outcomes_dict()
# not necessary, saves the moves
self.status_id = ""
def _init_moves_dict(self):
"""
Generates a dictionary with all possible moves.
Possible moves are: place H or X on a chosen qubit; apply a CNOT at chosen quibits pair
:return: a dict with int keys and tuples of (qubits, qiskit gates) as values
"""
mvs_dict = {}
mv_indx = 0
for q in range(self.qnum):
mvs_dict[mv_indx] = ([q], HGate())
mv_indx += 1
mvs_dict[mv_indx] = ([q], XGate())
mv_indx += 1
for (c, t) in permutations(list(range(self.qnum)), 2):
mvs_dict[mv_indx] = ([c, t], CXGate())
mv_indx += 1
return mvs_dict
def _win_check(self, board):
"""
Checks for game result
:param board: string representing the final state of the board
:return: winning player (1 or 2) or draw flag (0)
"""
d = int(np.sqrt(self.qnum))
# transofrm board string to rows, cols and diags
rows = [board[i*d:(i+1)*d] for i in range(d)]
cols = ["".join([rows[i][j] for i in range(d)]) for j in range(d)]
diags = ["".join([rows[i][i] for i in range(d)]), "".join([rows[i][d-i-1] for i in range(d)])]
winner = 0
# winning conditions for players 1 and 2
cond_1 = bin(0)[2:].zfill(d)
cond_2 = bin(2**d - 1)[2:].zfill(d)
# check each line and exit if both player win
for line in [*rows, *cols, *diags]:
if line == cond_1:
if winner == 0 or winner == 1:
winner = 1
elif winner == 2:
return 0 # because both players won
elif line == cond_2:
if winner == 0 or winner == 2:
winner = 2
elif winner == 1:
return 0 # because both players won
return winner
def _init_outcomes_dict(self):
"""
Inits a dictionary with all possible endings
:return: a dict whose keys are the winning player or a draw flag (0) and whose associated values
are all the final board configs leading to such outcome
"""
out_dict = {1: [], 2: [], 0: []}
# init all possible observed board states
all_states = [bin(x)[2:].zfill(self.qnum) for x in range(2**self.qnum)]
for state in all_states:
winner = self._win_check(state)
out_dict[winner].append(int(state, 2))
return out_dict
def move(self, action):
"""
Take the action by appending the associated gate to the board circ.
:param action: int, key of the moves dict
:return:
"""
self.status_id += "{}-".format(action)
self.circuit.append(self.moves[action][1], self.moves[action][0])
def _get_statevec(self):
"""
Quantumly observe the board, return the "percept" as the statevector of the board circuit
:return: rounded state vec of the board
"""
job = execute(self.circuit, self.statevec_sim)
result = job.result()
output_state = result.get_statevector()
return np.around(output_state, decimals=2)
def collapse_board(self):
"""
Final move, measure the board and observe final state
:return: final classical state of the board
"""
self.circuit.measure_all()
job = execute(self.circuit, backend=self.simulator, shots=1)
res = job.result()
counts = res.get_counts()
collapsed_state = int(list(counts.keys())[0][:self.qnum], 2)
return collapsed_state
def check_end(self, board_state):
"""
Check for ending
:param board_state: classical board state after collapse
:return: winning player (1 or 2) or draw flag (0)
"""
if board_state in self.endings_lookuptable[1]:
print("\nPlayer 1 wins!!!\n")
return 1
elif board_state in self.endings_lookuptable[2]:
print("\nPlayer 2 wins!!!\n")
return 2
else:
print("\nIt's a draw!\n")
return 0
def step(self, action):
"""
Perform the chosen action on the board
:param action: int representing the chosen action
:return: new_state of the board, reward (static), done=False
"""
self.move(action)
new_state = self._get_statevec()
reward = -0.1
return new_state, reward, False
def reset(self):
"""
Resets the board
:return:
"""
self.circuit = QuantumCircuit(self.qnum, self.qnum)
self.circuit.h(list(range(self.qnum)))
self.status_id = ""
return self._get_statevec()
def render(self):
# TODO: devise a render function
return 0
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
#Applying the CZ gate
qc.cz(0,1)
#Draw the circuit
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/abhishekchak52/quantum-computing-course
|
abhishekchak52
|
%matplotlib inline
import hashlib
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute
from qiskit.circuit import Parameter
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
from qiskit.visualization import *
from qiskit.quantum_info import *
from qiskit.circuit.library import HGate
success_msg = 'Your answer is correct and has been saved. Please continue to the next section.'
fail_msg = 'Your answer is not correct. Please try again.'
qc1 = QuantumCircuit(1)
# Insert gates below to create the state
# Insert the necessary gates to change to the Hadamard basis below and measure
# Do not change below this line
qc1.draw('mpl')
basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'barrier', 'measure']
assert list(qc1.count_ops()) != [], "Circuit cannot be empty"
assert set(qc1.count_ops().keys()).intersection(basis_gates) != set(), "Only basic gates are allowed"
job = execute(qc1, backend=QasmSimulator(), shots=1024, seed_simulator=0)
counts = job.result().get_counts()
sv_check = Statevector.from_instruction(qc1.remove_final_measurements(inplace=False)).evolve(HGate()).equiv(Statevector.from_label('r'))
op_check_dict = qc1.count_ops()
_ = op_check_dict.pop('measure', None)
_ = op_check_dict.pop('barrier', None)
op_check = len(op_check_dict) > 1
print(success_msg if (sv_check and op_check) else fail_msg)
answer1 = hashlib.sha256((str(counts)+str(sv_check and op_check)).encode()).hexdigest()
plot_histogram(counts)
from IPython.display import YouTubeVideo, display
polariser_exp = YouTubeVideo('6N3bJ7Uxpp0', end=93, height=405, width=720, modestbranding=1)
display(polariser_exp)
beta = Parameter('β')
qc2 = QuantumCircuit(1)
# Enter your code below this line
# Do not change below this line
qc2.draw(output='mpl')
def theoretical_prob(beta):
'''
Definition of theoretical transmission probability.
The expression for transmitted probability between two polarisers
with a relative angle `beta` given in radians
'''
# Fill in the correct expression for this probability and assign it to the variable tp below
# You may use numpy function like so: np.func_name()
tp =
return tp
beta_range = np.linspace(0, np.pi, 50)
num_shots = 1024
basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'barrier', 'measure']
assert set(qc2.count_ops().keys()).intersection(basis_gates) != set(), "Only basic gates are allowed"
job = execute(qc2,
backend=QasmSimulator(),
shots = num_shots,
parameter_binds=[{beta: beta_val} for beta_val in beta_range],
seed_simulator=0) # For consistent results
counts = job.result().get_counts()
# Calculating the probability of photons passing through
probabilities = list(map(lambda c: c.get('0', 0)/num_shots, counts))
pol_checks = [Statevector.from_instruction(qc2.bind_parameters({beta: beta_val})
.remove_final_measurements(inplace=False))
.equiv(Statevector([np.cos(-beta_val), np.sin(-beta_val)]))
for beta_val in beta_range]
print(success_msg if all(pol_checks) else fail_msg)
answer2 = hashlib.sha256((str(probabilities)+str(pol_checks)).encode()).hexdigest()
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
t_prob = np.vectorize(theoretical_prob)
ax.plot(beta_range, probabilities, 'o', label='Experimental')
ax.plot(beta_range, t_prob(beta_range), '-', label='Theoretical')
ax.set_xticks([i * np.pi / 4 for i in range(5)])
ax.set_xticklabels(['β', r'$\frac{\pi}{4}$', r'$\frac{\pi}{2}$', r'$\frac{3\pi}{4}$', r'$\pi$'], fontsize=14)
ax.set_xlabel('β', fontsize=14)
ax.set_ylabel('Probability of Transmission', fontsize=14)
ax.legend(fontsize=14)
print(f'Answer 1: {answer1}')
print(f'Answer 2: {answer2}')
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Expectation value: {result.values[0]}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job = estimator.run(circuits, observables)
result = job.result()
print(f">>> Expectation values: {result.values.tolist()}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
observable = SparsePauliOp("ZI")
parameter_values = [0, 1, 2, 3, 4, 5]
job = estimator.run(circuit, observable, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Parameter values: {parameter_values}")
print(f">>> Expectation value: {result.values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
# QiskitRuntimeService.save_account(channel="ibm_quantum", token="MY_API_TOKEN") was used to save account.
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Estimator
estimator = Estimator(session=backend)
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Metadata: {result.metadata[0]}")
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value: {result.values[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
estimator = Estimator()
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the first run: {result.values[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the second run: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(sampler_circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
|
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
header = ['instance','p','distance', 'mean']
length_p = 3
length_instances = 2
with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
instance_index = 0
for instance in range(length_instances):
instance_index += 1
first_p = False
UNIFORM_CONVERGENCE_P = []
UNIFORM_CONVERGENCE_SAMPLE = []
for p in range(length_p):
p = p+1
if first_p == False:
print("Vuelve a llamar a test_solution")
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p)
first_p = True
else:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p)
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0]
UNIFORM_CONVERGENCE_P.append({
"mean":convergence_min["mean"],
"probabilities": convergence_min["probabilities"]
})
cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1]
p_index = 0
for p_state in UNIFORM_CONVERGENCE_P:
p_index += 1
print(p_index)
mean = p_state["mean"]
print(p_state)
print(mean)
distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"]))
writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
import random
from qiskit import QuantumCircuit
from QiskitPBT.case_studies.deutsch_jozsa.deutsch_jozsa import deutsch_jozsa_circ
from QiskitPBT.case_studies.deutsch_jozsa.dj_helpers import RandomOracleInputGenerator
from QiskitPBT.property import Property
class DeutschJozsaLowerRegisterMinus(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
return [RandomOracleInputGenerator(3, 10)]
# specify the preconditions for the test
def preconditions(self, oracle):
return True
# specify the operations to be performed on the input
def operations(self, oracle: QuantumCircuit):
circ = deutsch_jozsa_circ(oracle)
# if oracle is constant this should be all 0
baseline = QuantumCircuit(1, 1)
baseline.x(0)
baseline.h(0)
self.statistical_analysis.assert_equal(self, [circ.num_qubits - 1], circ, [0], baseline)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import COBYLA
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE
from qiskit.primitives import Sampler
from qiskit_optimization.converters import LinearEqualityToPenalty
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from qiskit.utils import algorithm_globals
import numpy as np
import matplotlib.pyplot as plt
from docplex.mp.model import Model
algorithm_globals.random_seed = 123456
# prepare problem instance
n = 6 # number of assets
q = 0.5 # risk factor
budget = n // 2 # budget
penalty = 2 * n # scaling of penalty term
# instance from [1]
mu = np.array([0.7313, 0.9893, 0.2725, 0.8750, 0.7667, 0.3622])
sigma = np.array(
[
[0.7312, -0.6233, 0.4689, -0.5452, -0.0082, -0.3809],
[-0.6233, 2.4732, -0.7538, 2.4659, -0.0733, 0.8945],
[0.4689, -0.7538, 1.1543, -1.4095, 0.0007, -0.4301],
[-0.5452, 2.4659, -1.4095, 3.5067, 0.2012, 1.0922],
[-0.0082, -0.0733, 0.0007, 0.2012, 0.6231, 0.1509],
[-0.3809, 0.8945, -0.4301, 1.0922, 0.1509, 0.8992],
]
)
# or create random instance
# mu, sigma = portfolio.random_model(n, seed=123) # expected returns and covariance matrix
# create docplex model
mdl = Model("portfolio_optimization")
x = mdl.binary_var_list(range(n), name="x")
objective = mdl.sum([mu[i] * x[i] for i in range(n)])
objective -= q * mdl.sum([sigma[i, j] * x[i] * x[j] for i in range(n) for j in range(n)])
mdl.maximize(objective)
mdl.add_constraint(mdl.sum(x[i] for i in range(n)) == budget)
# case to
qp = from_docplex_mp(mdl)
# solve classically as reference
opt_result = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp)
print(opt_result.prettyprint())
# we convert the problem to an unconstrained problem for further analysis,
# otherwise this would not be necessary as the MinimumEigenSolver would do this
# translation automatically
linear2penalty = LinearEqualityToPenalty(penalty=penalty)
qp = linear2penalty.convert(qp)
_, offset = qp.to_ising()
# set classical optimizer
maxiter = 100
optimizer = COBYLA(maxiter=maxiter)
# set variational ansatz
ansatz = RealAmplitudes(n, reps=1)
m = ansatz.num_parameters
# set sampler
sampler = Sampler()
# run variational optimization for different values of alpha
alphas = [1.0, 0.50, 0.25] # confidence levels to be evaluated
# dictionaries to store optimization progress and results
objectives = {alpha: [] for alpha in alphas} # set of tested objective functions w.r.t. alpha
results = {} # results of minimum eigensolver w.r.t alpha
# callback to store intermediate results
def callback(i, params, obj, stddev, alpha):
# we translate the objective from the internal Ising representation
# to the original optimization problem
objectives[alpha].append(np.real_if_close(-(obj + offset)))
# loop over all given alpha values
for alpha in alphas:
# initialize SamplingVQE using CVaR
vqe = SamplingVQE(
sampler=sampler,
ansatz=ansatz,
optimizer=optimizer,
aggregation=alpha,
callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha),
)
# initialize optimization algorithm based on CVaR-SamplingVQE
opt_alg = MinimumEigenOptimizer(vqe)
# solve problem
results[alpha] = opt_alg.solve(qp)
# print results
print("alpha = {}:".format(alpha))
print(results[alpha].prettyprint())
print()
# plot resulting history of objective values
plt.figure(figsize=(10, 5))
plt.plot([0, maxiter], [opt_result.fval, opt_result.fval], "r--", linewidth=2, label="optimum")
for alpha in alphas:
plt.plot(objectives[alpha], label="alpha = %.2f" % alpha, linewidth=2)
plt.legend(loc="lower right", fontsize=14)
plt.xlim(0, maxiter)
plt.xticks(fontsize=14)
plt.xlabel("iterations", fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel("objective value", fontsize=14)
plt.show()
# evaluate and sort all objective values
objective_values = np.zeros(2**n)
for i in range(2**n):
x_bin = ("{0:0%sb}" % n).format(i)
x = [0 if x_ == "0" else 1 for x_ in reversed(x_bin)]
objective_values[i] = qp.objective.evaluate(x)
ind = np.argsort(objective_values)
# evaluate final optimal probability for each alpha
for alpha in alphas:
probabilities = np.fromiter(
results[alpha].min_eigen_solver_result.eigenstate.binary_probabilities().values(),
dtype=float,
)
print("optimal probability (alpha = %.2f): %.4f" % (alpha, probabilities[ind][-1:]))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ggridin/QiskitTests
|
ggridin
|
import qiskit
from qiskit.providers import JobStatus
from QCTest import get_test_qc, get_qc_random_generator
from QuantumPlatform import QuantumPlatform
def get_quantum_circuit():
return get_test_qc()
def main():
wait_for_results = True
try:
platform_backend = QuantumPlatform(qiskit.Aer, 'aer_simulator')
except Exception as e:
print(f'Error during quantum platform initialization: {e}')
exit(1)
qc = get_qc_random_generator(1024)
job = platform_backend.schedule_job(qc, shots=100, dry_run=False,
qc_filename='qc.qasm', qc_image_filename='qc.png',
transpiled_filename = 'transpiled.qasm', transpiled_image_filename='transpiled.png')
if job is None:
print('Job is not scheduled!')
exit(1)
print(f'Job id={job.job_id}')
print(f'Job={job}')
if wait_for_results is False:
exit(0)
job.wait_for_final_state()
print(f'Job status={job.status()}')
if job.status() == JobStatus.DONE:
print(f'Job result={job.result()}')
print(f'Counts={job.result().get_counts(qc)}')
main()
|
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/microsoft/qiskit-qir
|
microsoft
|
#--------------------------------------------------------------------------------------------------------------
# This module contains basic gates that can be used while developing circuits on IBM QExperience
#--------------------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------------------
# Import necessary modules
#--------------------------------------------------------------------------------------------------------------
from qiskit import QuantumProgram
import Qconfig
#--------------------------------------------------------------------------------------------------------------
# The CSWAP gate
# Input : Quantum program object, the Circuit name, the quantum register name, control bit number and target
# bit numbers.
# Output : Quantum_program_object with the relevant connections
# Circuit implemented - CSWAP
#--------------------------------------------------------------------------------------------------------------
def CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,Target_bit_numbers):
# Get the circuit and the quantum register by name
qc = Quantum_program_object.get_circuit(Circuit_name)
qr = Quantum_program_object.get_quantum_register(Quantum_register_name)
# Get control bit numbers and the target bit number for the addressing the qubits
Control = Control_bit_number
Target_1 = Target_bit_numbers[0]
Target_2 = Target_bit_numbers[1]
# Implement CSWAP using 3 CCNOT implementations
# Implement CCNOT on Control,Target_1 and Target_2 using decomposition given by Nelson and Chuang
qc.h(qr[Target_2])
qc.cx(qr[Target_1],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.t(qr[Target_2])
qc.cx(qr[Target_1],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.tdg(qr[Target_1])
qc.t(qr[Target_2])
qc.h(qr[Target_2])
qc.cx(qr[Control],qr[Target_1])
qc.tdg(qr[Target_1])
qc.cx(qr[Control],qr[Target_1])
qc.t(qr[Control])
qc.s(qr[Target_1])
# Implement CCNOT on Control,Target_2 and Target_1 using decomposition given by Nelson and Chuang
qc.h(qr[Target_1])
qc.cx(qr[Target_2],qr[Target_1])
qc.tdg(qr[Target_1])
qc.cx(qr[Control],qr[Target_1])
qc.t(qr[Target_1])
qc.cx(qr[Target_2],qr[Target_1])
qc.tdg(qr[Target_1])
qc.cx(qr[Control],qr[Target_1])
qc.tdg(qr[Target_2])
qc.t(qr[Target_1])
qc.h(qr[Target_1])
qc.cx(qr[Control],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.t(qr[Control])
qc.s(qr[Target_2])
# Implement CCNOT on Control,Target_1 and Target_2 using decomposition given by Nelson and Chuang
qc.h(qr[Target_2])
qc.cx(qr[Target_1],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.t(qr[Target_2])
qc.cx(qr[Target_1],qr[Target_2])
qc.tdg(qr[Target_2])
qc.cx(qr[Control],qr[Target_2])
qc.tdg(qr[Target_1])
qc.t(qr[Target_2])
qc.h(qr[Target_2])
qc.cx(qr[Control],qr[Target_1])
qc.tdg(qr[Target_1])
qc.cx(qr[Control],qr[Target_1])
qc.t(qr[Control])
qc.s(qr[Target_1])
# Return the program object
return Quantum_program_object
#--------------------------------------------------------------------------------------------------------------
# The CCNOT gate
# Input : Quantum program object, the Circuit name, the quantum register name, control bit numbers and target
# bit number.
# Output : Quantum_program_object with the relevant connections
# Circuit implemented - CCNOT
#--------------------------------------------------------------------------------------------------------------
def CCNOT(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_numbers,Target_bit_number):
# Get the circuit and the quantum register by name
qc = Quantum_program_object.get_circuit(Circuit_name)
qr = Quantum_program_object.get_quantum_register(Quantum_register_name)
# Get control bit numbers and the target bit number for the addressing the qubits
Control_1 = Control_bit_numbers[0]
Control_2 = Control_bit_numbers[1]
Target = Target_bit_number
# Implement Hadamard on target qubits
qc.h(qr[Target])
# Implement CNOT between Control_2 and Target
qc.cx(qr[Control_2],qr[Target])
# Implement T (dagger) on target qubits
qc.tdg(qr[Target])
# Implement CNOT between Control_1 and Target
qc.cx(qr[Control_1],qr[Target])
# Implement T on target qubits
qc.t(qr[Target])
# Implement CNOT between Control_2 and Target
qc.cx(qr[Control_2],qr[Target])
# Implement T (dagger) on target qubits
qc.tdg(qr[Target])
# Implement CNOT between Control_1 and Target
qc.cx(qr[Control_1],qr[Target])
# Implement T (dagger) on Control_2, T and H on Target
qc.tdg(qr[Control_2])
qc.t(qr[Target])
qc.h(qr[Target])
# Implement CNOT from Control_1 to Control_2 followed by T (dagger) on Control_2
qc.cx(qr[Control_1],qr[Control_2])
qc.tdg(qr[Control_2])
# Implement CNOT from Control_1 to Control_2 followed by T on Control_1 and S on Control_2
qc.cx(qr[Control_1],qr[Control_2])
qc.t(qr[Control_1])
qc.s(qr[Control_2])
# Return the program object
return Quantum_program_object
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
### Pauli Operators
from qiskit.opflow import I, X, Y, Z # Pauli operators
print(I,X,Y,Z)
print(1.5*I) # can carry a coefficient
print(2.5*X)
print(X+2.0*Y) # can be used in a sum
print(X ^ Y ^ Z) # tensor products use ^
print(X @ Y @ Z) # composition uses @
# complicated objects
print((X + Y) ^ (Y + Z)) # composing two sums
print((X + Y) ^ (Y + Z)) # tensoring two sums
print(I, X)
print(2.0 * X^Y^Z)
print(1.1 * ((1.2 * X)^(Y + (1.3 * Z))))
### Part 1: State Functions and Measurements
from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H, DictStateFn,
VectorStateFn, CircuitStateFn, OperatorStateFn)
print(Zero, One) # states |0> and |1>, respectively
print(Plus, Minus) # states |+> = 1/sqrt(2)*(|0> + |1>) and |-> = 1/sqrt(2)*(|0> - |1>), respectively
# the eval method returns the coefficients of hte 0 and 1 basis states
print(Zero.eval('0'))
print(Zero.eval('1'))
print(One.eval('1'))
print(Plus.eval('0'))
print(Minus.eval('1'))
# the adjoint method gives the dual vector of the quantum state (the bra of the ket, or vice versa)
print(One.adjoint())
print(~One)
## Algebraic operations and predicates
print((2.0 + 3.0j) * Zero) # construct (2 + 3i)|0>
print(Zero + One) # adding two DictStateFn returns an object of the same type
# you must normalize states by hand
import math
v_zero_one = (Zero + One) / math.sqrt(2)
print(v_zero_one)
# symbolic representation of a sum
print(Plus + Minus)
# composition operator used to perform an inner product
print(~One @ One)
# symbolic expressions may be evaluated with the eval method
print((~One @ One).eval())
print((~v_zero_one @ v_zero_one).eval())
print((~Minus @ One).eval())
# the composition operator @ is equivalent to calling the compose method
print((~One).compose(One))
assert (~One).compose(One) == ~One @ One
# inner products may also be computed using the eval method directly
print((~One).eval(One))
# symbolic tensor products are constructed as follows
print(Zero ^ Plus) # |0> + |+>
print((Zero ^ Plus).to_circuit_op()) # represented as a simple CircuitStateFn
# tensor powers can be constructed using the ^ operator
print(600 * ((One ^ 5) + (Zero ^ 5))) # 600(|11111> + |00000>)
print((One ^ Zero) ^ 3) #|10>^3
# the method to_matrix_op converts to VectorStateFn
print(((Plus^Minus)^2).to_matrix_op())
print(((Plus^One)^2).to_matrix_op())
print(((Plus^Minus)^2).to_matrix_op().sample())
# StateFn class serves as a factory and can take any applicable primitive in its constructor
print(StateFn({'0':1}))
print(StateFn({'0':1}) == Zero)
print(StateFn([0,1,1,0]))
from qiskit.circuit.library import RealAmplitudes
print(StateFn(RealAmplitudes(2)))
### Part 2: PrimitiveOp's
# the basic operators are sublclasses of PrimitiveOp
# like StateFn, PrimitiveOp is a factory and can take any applicable primitive in its constructor
from qiskit.opflow import X, Y, Z, I, CX, T, H, S, PrimitiveOp
## Matrix elements
print(X)
print(X.eval('0'))
print(X.eval('0').eval('1'))
print(CX)
print(CX.to_matrix().real) # remove imaginary part
print(CX.eval('01'))
print(CX.eval('01').eval('11'))
## Applying an operator to a state vector
print(X @ One) # X|1> = |0>
print((X @ One).eval())
print(X.eval(One))
# composition and tensor products of operators are effected with @ and ^
print(((~One^2) @ (CX.eval('01'))).eval())
print(((H^5) @ ((CX^2)^I) @ (I^CX^2))**2)
print((((H^5) @ ((CX^2)^I) @ (I^CX^2))**2) @ (Minus^5))
print(((H^I^I)@(X^I^I)@Zero))
print(~One @ Minus)
### Part 3: ListOp and subclasses
# ListOp is a container for effectivley vectorizing operations over a list of operators and states
from qiskit.opflow import ListOp
print((~ListOp([One, Zero]) @ ListOp([One, Zero])))
# distribute over lists using simplification method reduce
print((~ListOp([One, Zero]) @ ListOp([One, Zero])).reduce())
## OperatorStateFn
# construct observable corresponding to Pauli Z operator
print(StateFn(Z).adjoint())
StateFn(Z).adjoint()
# compute <0|Z|0>, <1|Z|1>, and <+|Z|+>
print(StateFn(Z).adjoint().eval(Zero))
print(StateFn(Z).adjoint().eval(One))
print(StateFn(Z).adjoint().eval(Plus))
### Part 4: Converters
# converters manipulate operators and states and perform building blocks of algorithms
import numpy as np
from qiskit.opflow import (I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation,
PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki)
from qiskit.circuit import Parameter
from qiskit import Aer
## Evolutions, exp_i(), and the EvolvedOP
# express hamiltonian as linear combination of multi-qubit Pauli operators
two_qubit_H2 = (-1.0523732 * I^I) + \
(0.39793742 * I^Z) + \
(-0.3979374 * Z^I) + \
(-0.0112801 * Z^Z) + \
(0.18093119 * X^X)
print(two_qubit_H2)
# multiply hamiltonian by a Parameter
evo_time = Parameter('θ')
evolution_op = (evo_time*two_qubit_H2).exp_i()
print(evolution_op) # Note: EvolvedOPs print as exponentiations
print(repr(evolution_op))
# construct observable for Hamiltonian
h2_measurement = StateFn(two_qubit_H2).adjoint()
print(h2_measurement)
# construct bell state via CX(H tensor I)|00>
bell = CX @ (I ^ H) @ Zero
print(bell)
# evolve bell state
evo_and_meas = h2_measurement @ evolution_op @ bell
print(evo_and_meas)
# approximate exponentiation with two-qubit gates using PauliTrotterEvolution
trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas)
print(trotterized_op)
# bind_parameters method traverses expression, binding values ot parameter names
bound = trotterized_op.bind_parameters({evo_time: .5})
bound[1].to_circuit().draw('mpl').show()
## Exppectations
# expectations are converters that enable the computation of expectation values and observables
# AerPauliExpectation converts an observable into a CircuitStateFn containin a special expectation snapshot
# which Aer can execute nativley with high performance
print(PauliExpectation(group_paulis=False).convert(h2_measurement))
# by default, group_paulis=True which uses the AbelianGrouper to convert the SummedOp into groups
# of mutually-qubit wise commuting Paulis, reducing circuit execution overhead
print(PauliExpectation().convert(h2_measurement))
# converters act recursivley, so we can convert our full evolution and measurement expression
diagonalized_meas_op = PauliExpectation().convert(trotterized_op)
print(diagonalized_meas_op)
evo_time_points = list(range(8))
h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time:evo_time_points})
print(h2_trotter_expectations.eval())
## Executing CircuitStateFn with the CircuitSampler
# CircuitSampler traverses an Operator and converts any CircuitStateFn into approximations of the
# resulting state function by a DictStateFn or VectorStateFn using a quantum backend.
sampler= CircuitSampler(backend=Aer.get_backend('aer_simulator'))
# sampler.quantum_instance.run_config.shots = 1000
sampled_trotter_exp_op = sampler.convert(h2_trotter_expectations)
sampled_trotter_energies = sampled_trotter_exp_op.eval()
print('Sampled Trotterized energies:\n{}'.format(np.real(sampled_trotter_energies)))
# note: circuits are replaced by dicts with square roots of the circuit sampling probablilities
print('Before:\n')
print(h2_trotter_expectations.reduce()[0][0])
print('After:\n')
print(sampled_trotter_exp_op.reduce()[0][0])
|
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
|
# 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/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Shor's Order Finding Algorithm Benchmark - QSim
"""
import math
import sys
import time
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
sys.path[1:1] = ["_common", "_common/qsim", "shors/_common", "quantum-fourier-transform/qsim"]
sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../shors/_common", "../../quantum-fourier-transform/qsim"]
import execute as ex
import metrics as metrics
from shors_utils import getAngles, getAngle, modinv, generate_base, verify_order
from qft_benchmark import inv_qft_gate
from qft_benchmark import qft_gate
from execute import BenchmarkResult
# Benchmark Name
benchmark_name = "Shor's Order Finding"
np.random.seed(0)
verbose = False
QC_ = None
PHIADD_ = None
CCPHIADDMODN_ = None
CMULTAMODN_ = None
CUA_ = None
QFT_ = None
############### Circuit Definition
#Creation of the circuit that performs addition by a in Fourier Space
#Can also be used for subtraction by setting the parameter inv to a value different from 0
def phiADD(num_qubits, a):
qc = QuantumCircuit(num_qubits, name = "\u03C6ADD")
angle = getAngles(a, num_qubits)
for i in range(0, num_qubits):
# addition
qc.p(angle[i], i)
global PHIADD_
if PHIADD_ == None or num_qubits <= 3:
if num_qubits < 4: PHIADD_ = qc
return qc
#Single controlled version of the phiADD circuit
def cphiADD(num_qubits, a):
phiadd_gate = phiADD(num_qubits,a).to_gate()
cphiadd_gate = phiadd_gate.control(1)
return cphiadd_gate
#Doubly controlled version of the phiADD circuit
def ccphiADD(num_qubits, a):
phiadd_gate = phiADD(num_qubits,a).to_gate()
ccphiadd_gate = phiadd_gate.control(2)
return ccphiadd_gate
# Circuit that implements doubly controlled modular addition by a (num qubits should be bit count for number N)
def ccphiADDmodN(num_qubits, a, N):
qr_ctl = QuantumRegister(2)
qr_main = QuantumRegister(num_qubits+1)
qr_ancilla = QuantumRegister(1)
qc = QuantumCircuit(qr_ctl, qr_main,qr_ancilla, name = "cc\u03C6ADDmodN")
# Generate relevant gates for circuit
ccphiadda_gate = ccphiADD(num_qubits+1, a)
ccphiadda_inv_gate = ccphiADD(num_qubits+1, a).inverse()
phiaddN_inv_gate = phiADD(num_qubits+1, N).inverse(); phiaddN_inv_gate.name = "inv_\u03C6ADD"
cphiaddN_gate = cphiADD(num_qubits+1, N)
# Create relevant temporary qubit lists
ctl_main_qubits = [i for i in qr_ctl]; ctl_main_qubits.extend([i for i in qr_main])
anc_main_qubits = [qr_ancilla[0]]; anc_main_qubits.extend([i for i in qr_main])
#Create circuit
qc.append(ccphiadda_gate, ctl_main_qubits)
qc.append(phiaddN_inv_gate, qr_main)
qc.append(inv_qft_gate(num_qubits+1), qr_main)
qc.cx(qr_main[-1], qr_ancilla[0])
qc.append(qft_gate(num_qubits+1), qr_main)
qc.append(cphiaddN_gate, anc_main_qubits)
qc.append(ccphiadda_inv_gate, ctl_main_qubits)
qc.append(inv_qft_gate(num_qubits+1), qr_main)
qc.x(qr_main[-1])
qc.cx(qr_main[-1], qr_ancilla[0])
qc.x(qr_main[-1])
qc.append(qft_gate(num_qubits+1), qr_main)
qc.append(ccphiadda_gate, ctl_main_qubits)
global CCPHIADDMODN_
if CCPHIADDMODN_ == None or num_qubits <= 2:
if num_qubits < 3: CCPHIADDMODN_ = qc
return qc
# Circuit that implements the inverse of doubly controlled modular addition by a
def ccphiADDmodN_inv(num_qubits, a, N):
cchpiAddmodN_circ = ccphiADDmodN(num_qubits, a, N)
cchpiAddmodN_inv_circ = cchpiAddmodN_circ.inverse()
cchpiAddmodN_inv_circ.name = "inv_cchpiAddmodN"
return cchpiAddmodN_inv_circ
# Creates circuit that implements single controlled modular multiplication by a. n represents the number of bits
# needed to represent the integer number N
def cMULTamodN(n, a, N):
qr_ctl = QuantumRegister(1)
qr_x = QuantumRegister(n)
qr_main = QuantumRegister(n+1)
qr_ancilla = QuantumRegister(1)
qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = "cMULTamodN")
# quantum Fourier transform only on auxillary qubits
qc.append(qft_gate(n+1), qr_main)
for i in range(n):
ccphiADDmodN_gate = ccphiADDmodN(n, (2**i)*a % N, N)
# Create relevant temporary qubit list
qubits = [qr_ctl[0]]; qubits.extend([qr_x[i]])
qubits.extend([i for i in qr_main]); qubits.extend([qr_ancilla[0]])
qc.append(ccphiADDmodN_gate, qubits)
# inverse quantum Fourier transform only on auxillary qubits
qc.append(inv_qft_gate(n+1), qr_main)
global CMULTAMODN_
if CMULTAMODN_ == None or n <= 2:
if n < 3: CMULTAMODN_ = qc
return qc
# Creates circuit that implements single controlled Ua gate. n represents the number of bits
# needed to represent the integer number N
def controlled_Ua(n,a,exponent,N):
qr_ctl = QuantumRegister(1)
qr_x = QuantumRegister(n)
qr_main = QuantumRegister(n)
qr_ancilla = QuantumRegister(2)
qc = QuantumCircuit(qr_ctl, qr_x, qr_main,qr_ancilla, name = f"C-U^{a**exponent}")
# Generate Gates
a_inv = modinv(a**exponent,N)
cMULTamodN_gate = cMULTamodN(n, a**exponent, N)
cMULTamodN_inv_gate = cMULTamodN(n, a_inv, N).inverse(); cMULTamodN_inv_gate.name = "inv_cMULTamodN"
# Create relevant temporary qubit list
qubits = [i for i in qr_ctl]; qubits.extend([i for i in qr_x]); qubits.extend([i for i in qr_main])
qubits.extend([i for i in qr_ancilla])
qc.append(cMULTamodN_gate, qubits)
for i in range(n):
qc.cswap(qr_ctl, qr_x[i], qr_main[i])
qc.append(cMULTamodN_inv_gate, qubits)
global CUA_
if CUA_ == None or n <= 2:
if n < 3: CUA_ = qc
return qc
# Execute Shor's Order Finding Algorithm given a 'number' to factor,
# the 'base' of exponentiation, and the number of qubits required 'input_size'
def ShorsAlgorithm(number, base, method, verbose=verbose):
# Create count of qubits to use to represent the number to factor
# NOTE: this should match the number of bits required to represent (number)
n = int(math.ceil(math.log(number, 2)))
# Standard Shors Algorithm
if method == 1:
num_qubits = 4*n + 2
if verbose:
print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}")
# Create a circuit and allocate necessary qubits
qr_counting = QuantumRegister(2*n) # Register for sequential QFT
qr_mult = QuantumRegister(n) # Register for multiplications
qr_aux = QuantumRegister(n+2) # Register for addition and multiplication
cr_data = ClassicalRegister(2*n) # Register for measured values of QFT
qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data,
name=f"qmc({method})-{num_qubits}-{number}")
# Initialize multiplication register to 1 and counting register to superposition state
qc.h(qr_counting)
qc.x(qr_mult[0])
qc.barrier()
# Apply Multiplication Gates for exponentiation
for i in reversed(range(2*n)):
cUa_gate = controlled_Ua(n,int(base),2**(2*n-1-i),number)
# Create relevant temporary qubit list
qubits = [qr_counting[i]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux])
qc.append(cUa_gate, qubits)
qc.barrier()
qc.append(inv_qft_gate(2*n),qr_counting)
# Measure counting register
qc.measure(qr_counting, cr_data)
elif method == 2:
# Create a circuit and allocate necessary qubits
num_qubits = 2*n + 3
if verbose:
print(f"... running Shors to find order of [ {base}^x mod {number} ] using num_qubits={num_qubits}")
qr_counting = QuantumRegister(1) # Single qubit for sequential QFT
qr_mult = QuantumRegister(n) # Register for multiplications
qr_aux = QuantumRegister(n+2) # Register for addition and multiplication
cr_data = ClassicalRegister(2*n) # Register for measured values of QFT
cr_aux = ClassicalRegister(1) # Register to reset the state of the up register based on previous measurements
qc = QuantumCircuit(qr_counting, qr_mult, qr_aux, cr_data, cr_aux, name="main")
# Initialize mult register to 1
qc.x(qr_mult[0])
# perform modular exponentiation 2*n times
for k in range(2*n):
qc.barrier()
# Reset the counting qubit to 0 if the previous measurement was 1
qc.x(qr_counting).c_if(cr_aux,1)
qc.h(qr_counting)
cUa_gate = controlled_Ua(n, base,2**(2*n-1-k), number)
# Create relevant temporary qubit list
qubits = [qr_counting[0]]; qubits.extend([i for i in qr_mult]);qubits.extend([i for i in qr_aux])
qc.append(cUa_gate, qubits)
# perform inverse QFT --> Rotations conditioned on previous outcomes
for i in range(2**k):
qc.p(getAngle(i, k), qr_counting[0]).c_if(cr_data, i)
qc.h(qr_counting)
qc.measure(qr_counting[0], cr_data[k])
qc.measure(qr_counting[0], cr_aux[0])
global QC_, QFT_
if QC_ == None or n <= 2:
if n < 3: QC_ = qc
if QFT_ == None or n <= 2:
if n < 3: QFT_ = qft_gate(n+1)
return qc
############### Circuit end
def expected_shor_dist(num_bits, order, num_shots):
# num_bits represent the number of bits to represent the number N in question
# Qubits measureed always 2 * num_bits for the three methods implemented in this benchmark
qubits_measured = 2 * num_bits
dist = {}
#Conver float to int
r = int(order)
#Generate expected distribution
q = int(2 ** (qubits_measured))
for i in range(r):
key = bin(int(q*(i/r)))[2:].zfill(qubits_measured)
dist[key] = num_shots/r
'''
for c in range(2 ** qubits_measured):
key = bin(c)[2:].zfill(qubits_measured)
amp = 0
for i in range(int(q/r) - 1):
amp += np.exp(2*math.pi* 1j * i * (r * c % q)/q )
amp = amp * np.sqrt(r) / q
dist[key] = abs(amp) ** 2
'''
return dist
# Print analyzed results
# Analyze and print measured results
# Expected result is always the order r, so fidelity calc is simple
def analyze_and_print_result(qc, result, num_qubits, order, num_shots, method):
if method == 1:
num_bits = int((num_qubits - 2) / 4)
elif method == 2:
num_bits = int((num_qubits - 3) / 2)
elif method == 3:
num_bits = int((num_qubits - 2) / 2)
if result.backend_name == 'dm_simulator':
benchmark_result = BenchmarkResult(result, num_shots)
probs = benchmark_result.get_probs(num_shots) # get results as measured probability
else:
probs = result.get_counts(qc) # get results as measured counts
# Only classical data qubits are important and removing first auxiliary qubit from count
if method == 2:
temp_probs = {}
for key, item in probs.items():
temp_probs[key[2:]] = item
probs = temp_probs
# generate correct distribution
correct_dist = expected_shor_dist(num_bits, order, num_shots)
if verbose:
print(f"For order value {order}, measured: {probs}")
print(f"For order value {order}, correct_dist: {correct_dist}")
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(probs, correct_dist)
return probs, fidelity
#################### Benchmark Loop
# Execute program with default parameters
def run (min_qubits=3, max_circuits=1, max_qubits=10, num_shots=100, method = 1,
verbose=verbose, backend_id='dm_simulator', provider_backend=None,
#hub="ibm-q", group="open", project="main",
exec_options=None,
context=None):
print(f"{benchmark_name} ({method}) Benchmark - QSim")
# Each method has a different minimum amount of qubits to run and a certain multiple of qubits that can be run
qubit_multiple = 2 #Standard for Method 2 and 3
max_qubits = max(max_qubits, min_qubits) # max must be >= min
if method == 1:
min_qubits = max(min_qubits, 10) # need min of 10
qubit_multiple = 4
elif method ==2:
min_qubits = max(min_qubits, 7) # need min of 7
elif method == 3:
min_qubits = max(min_qubits,6) # need min of 6
#skip_qubits = max(1, skip_qubits)
if max_qubits < min_qubits:
print(f"Max number of qubits {max_qubits} is too low to run method {method} of {benchmark_name}")
return
# create context identifier
if context is None: context = f"{benchmark_name} ({method}) Benchmark"
##########
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler # number_order contains an array of length 2 with the number and order
def execution_handler(qc, result, num_qubits, number_order, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
#Must convert number_order from string to array
order = eval(number_order)[1]
probs, fidelity = analyze_and_print_result(qc, result, num_qubits, order, num_shots, method)
metrics.store_metric(num_qubits, number_order, 'fidelity', fidelity)
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
# hub=hub, group=group, project=project,
exec_options=exec_options,
context=context)
##########
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1, qubit_multiple):
input_size = num_qubits - 1
if method == 1: num_bits = int((num_qubits -2)/4)
elif method == 2: num_bits = int((num_qubits -3)/2)
elif method == 3: num_bits = int((num_qubits -2)/2)
# determine number of circuits to execute for this group
num_circuits = min(2 ** (input_size), max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
for _ in range(num_circuits):
base = 1
while base == 1:
# Ensure N is a number using the greatest bit
number = np.random.randint(2 ** (num_bits - 1) + 1, 2 ** num_bits)
order = np.random.randint(2, number)
base = generate_base(number, order)
# Checking if generated order can be reduced. Can also run through prime list in shors utils
if order % 2 == 0: order = 2
if order % 3 == 0: order = 3
number_order = (number, order)
if verbose: print(f"Generated {number=}, {base=}, {order=}")
# create the circuit for given qubit size and order, store time metric
ts = time.time()
qc = ShorsAlgorithm(number, base, method=method, verbose=verbose).reverse_bits() # reverse_bits() is applying to handle the change in endianness
metrics.store_metric(num_qubits, number_order, 'create_time', time.time()-ts)
# collapse the 4 sub-circuit levels used in this benchmark (for qiskit)
qc = qc.decompose().decompose().decompose().decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc, num_qubits, number_order, num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
# print the last circuit created
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nControlled Ua Operator 'cUa' ="); print(CUA_ if CUA_ != None else " ... too large!")
print("\nControlled Multiplier Operator 'cMULTamodN' ="); print(CMULTAMODN_ if CMULTAMODN_!= None else " ... too large!")
print("\nControlled Modular Adder Operator 'ccphiamodN' ="); print(CCPHIADDMODN_ if CCPHIADDMODN_ != None else " ... too large!")
print("\nPhi Adder Operator '\u03C6ADD' ="); print(PHIADD_ if PHIADD_ != None else " ... too large!")
print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!")
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim")
# if main, execute method
if __name__ == '__main__':
ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks)
run() #max_qubits = 6, max_circuits = 5, num_shots=100)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import Aer, IBMQ, execute
from qiskit import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram, plot_state_city
"""
Qiskit backends to execute the quantum circuit
"""
def simulator(qc):
"""
Run on local simulator
:param qc: quantum circuit
:return:
"""
backend = Aer.get_backend("qasm_simulator")
shots = 2048
tqc = transpile(qc, backend)
qobj = assemble(tqc, shots=shots)
job_sim = backend.run(qobj)
qc_results = job_sim.result()
return qc_results, shots
def simulator_state_vector(qc):
"""
Select the StatevectorSimulator from the Aer provider
:param qc: quantum circuit
:return:
statevector
"""
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
state_vector = result.get_statevector(qc)
return state_vector
def real_quantum_device(qc):
"""
Use the IBMQ essex device
:param qc: quantum circuit
:return:
"""
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_santiago')
shots = 2048
TQC = transpile(qc, backend)
qobj = assemble(TQC, shots=shots)
job_exp = backend.run(qobj)
job_monitor(job_exp)
QC_results = job_exp.result()
return QC_results, shots
def counts(qc_results):
"""
Get counts representing the wave-function amplitudes
:param qc_results:
:return: dict keys are bit_strings and their counting values
"""
return qc_results.get_counts()
def plot_results(qc_results):
"""
Visualizing wave-function amplitudes in a histogram
:param qc_results: quantum circuit
:return:
"""
plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False))
def plot_state_vector(state_vector):
"""Visualizing state vector in the density matrix representation"""
plt.show(plot_state_city(state_vector))
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test of scikit-quant optimizers."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import ddt, data, unpack
import numpy
from qiskit import BasicAer
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.exceptions import MissingOptionalLibraryError
from qiskit.opflow import PauliSumOp
from qiskit_algorithms import VQE
from qiskit_algorithms.optimizers import BOBYQA, SNOBFIT, IMFIL
@ddt
class TestOptimizers(QiskitAlgorithmsTestCase):
"""Test scikit-quant optimizers."""
def setUp(self):
"""Set the problem."""
super().setUp()
algorithm_globals.random_seed = 50
with self.assertWarns(DeprecationWarning):
self.qubit_op = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
def _optimize(self, optimizer):
"""launch vqe"""
with self.assertWarns(DeprecationWarning):
qe = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
with self.assertWarns(DeprecationWarning):
vqe = VQE(ansatz=RealAmplitudes(), optimizer=optimizer, quantum_instance=qe)
result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=1)
def test_bobyqa(self):
"""BOBYQA optimizer test."""
try:
optimizer = BOBYQA(maxiter=150)
self._optimize(optimizer)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
@unittest.skipIf(
tuple(map(int, numpy.__version__.split("."))) >= (1, 24, 0),
"scikit's SnobFit currently incompatible with NumPy 1.24.0.",
)
def test_snobfit(self):
"""SNOBFIT optimizer test."""
try:
optimizer = SNOBFIT(maxiter=100, maxfail=100, maxmp=20)
self._optimize(optimizer)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
@unittest.skipIf(
tuple(map(int, numpy.__version__.split("."))) >= (1, 24, 0),
"scikit's SnobFit currently incompatible with NumPy 1.24.0.",
)
@data((None,), ([(-1, 1), (None, None)],))
@unpack
def test_snobfit_missing_bounds(self, bounds):
"""SNOBFIT optimizer test with missing bounds."""
try:
optimizer = SNOBFIT()
with self.assertRaises(ValueError):
optimizer.minimize(
fun=lambda _: 1, # using dummy function (never called)
x0=[0.1, 0.1], # dummy initial point
bounds=bounds,
)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
def test_imfil(self):
"""IMFIL test."""
try:
optimizer = IMFIL(maxiter=100)
self._optimize(optimizer)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
if __name__ == "__main__":
unittest.main()
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Math;
operation GlobalPhaseI(q:Qubit):Unit is Adj+Ctl{
X(q);
Z(q);
Y(q);
}
namespace Quantum.Kata.SingleQubitGates{
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Math;
operation GlobalPhaseI(q:Qubit):Unit is Adj+Ctl{
X(q);
Z(q);
Y(q);
}
}
|
https://github.com/omarcostahamido/qiskit_app_carbon_design
|
omarcostahamido
|
import os
from flask import Flask, jsonify, request
import json
import requests
# New QISKit libraries
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute
from qiskit import IBMQ
from qiskit import BasicAer
from qiskit.providers.aer import noise
from noisedev import setup_noise,emo_noise
def generateCircuit():
#collect params
req_data = request.get_json()
sim=req_data['set']
if sim:
json_output = {"emo":emo_noise(),"shots":400}
print(json_output)
#return jsonify(json_output)
return json_output #jsonify put in main welcome.py file due to errors
else:
rawEmoticon = req_data['emo']
operation = req_data['operation']
print(rawEmoticon)
emoticon = []
# split each emoticon in a list of 1s and 0s
for string in rawEmoticon:
print(string)
print(list(string))
emoticon.append(list(string))
print(" ")
print(emoticon)
# ======= MICHELE =============
A = emoticon[0]
B = emoticon[1]
qasm = []
posizione = []
for i in range(len(A)):
print(len(A)-i-1, A[i], B[i])
if A[i] == '0' and B[i] == '0' :
print("ok 0")
if A[i] == '1' and B[i] == '1' :
print("ok 1")
qasm.append("qc.x(qr["+str(len(A)-i-1)+"])")
print("QASM", qasm, i)
if A[i] != B[i] :
posizione.append(i)
print("posizione",(len(A)-i-1))
print("pos, A, B")
for j in range(len(posizione)):
if j == 0 :
qasm.append("qc.h(qr["+str(len(A) - posizione[j] -1)+"])")
else:
if A[posizione[0]] == A[posizione[j]] :
qasm.append("qc.cx(qr["+str(len(A) - posizione[0] -1)+"],qr["+str(len(A) - posizione[j] -1)+"])")
else:
qasm.append("qc.cx(qr["+str(len(A) - posizione[0] -1)+"],qr["+str(len(A) - posizione[j] -1)+"])")
qasm.append("qc.x(qr["+str(len(A) - posizione[j] -1)+"])")
print("======== qasm ==========")
print(qasm)
print("============= ==========")
# ========= END ===============
r = sendQuantum(qasm,len(A),sim)
print("collecting execution results")
print(r)
array_output = []
shots = 0
for key in r.keys():
array_output.append({"value": key,"shots": r[key]})
shots += r[key]
json_output = {"emo": array_output,"shots":shots}
print(json_output)
#return jsonify(json_output)
return json_output #jsonify put in main welcome.py file due to errors
def sendQuantum(commandList,qubitNr,operation):
qr = QuantumRegister(qubitNr)
cr = ClassicalRegister(qubitNr)
qc = QuantumCircuit(qr, cr)
for command in commandList:
print(command)
# insert check on command received
exec(command)
for j in range(qubitNr):
qc.measure(qr[j], cr[j])
# check if request is for simulator or real hardware
#b = "ibmq_qasm_simulator"
#back=IBMQ.get_backend(b)
#backend=Aer.backends()[0].name() ## deprecated way to call backand
backend = Aer.get_backend('qasm_simulator')
shots_sim = 400
print("executing algorithm")
job_exp = execute(qc, backend, shots=shots_sim)
stats_sim = job_exp.result().get_counts()
print(stats_sim)
return stats_sim
# show available backends
# IBMQ.backends()
# # find least busy backend
# backend = least_busy(IBMQ.backends(simulator=False))
# print("The least busy backend is " + backend.name())
# # execute on hardware
# job_exp = execute(qc, backend=backend, shots=1024, max_credits=3)
#backend = "ibmq_qasm_simulator"
#backend = "ibmqx5"
#shots_sim = 256
#print("executing algorithm")
# job_sim = execute(qc, backend, shots=shots_sim)
#job_exp = execute(qc, backend=IBMQ.get_backend(backend), shots=shots_sim)
#stats_sim = job_exp.result().get_counts()
#print(stats_sim)
#return stats_sim
def executeCircuit():
#collect params
commandList =[]
qubitNr = 0
print("collecting params")
req_data = request.get_json()
commandList = req_data['command']
qubitNr = req_data['qubitNr']
# set up registers and program
qr = QuantumRegister(qubitNr)
cr = ClassicalRegister(qubitNr)
qc = QuantumCircuit(qr, cr)
return json.dumps({"results": sendQuantum(commandList,qubitNr)})
|
https://github.com/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/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import *
import matplotlib.pyplot as plt
from qiskit.extensions import UnitaryGate
from qiskit.circuit import add_control
from IPython.display import display
from qiskit.tools.visualization import plot_histogram
import numpy as np
import sys
sys.path.append("..")
from Modules.faster_basic_qpe import fast_QPE
U = np.array([[1, 0],
[0, np.exp(2*np.pi*1j*(1/5))]])
qpe_circ = fast_QPE(precision=4, unitary=U).get_QPE(show=True)
q = QuantumCircuit(5, 4)
q.x(4)
q.append(qpe_circ, qargs=[0, 1, 2, 3, 4])
# q = q.compose(qpe_circ,qubits = [0,1,2,3,4])
q.draw('mpl')
q.measure([0, 1, 2, 3], [0, 1, 2, 3])
q.draw('mpl')
count = execute(q, backend=Aer.get_backend(
'qasm_simulator')).result().get_counts()
plot_histogram(count)
q = QuantumCircuit(3,name = 'Unitary')
q.cp(2*np.pi*(1/7),1,2)
display(q.draw('mpl'))
# u = execute(q,backend = Aer.get_backend('unitary_simulator')).result().get_unitary()
qpe_circ = fast_QPE(precision=4,unitary=q).get_QPE(show=True,save = True)
q = QuantumCircuit(7,4)
q.x([5,6])
q.barrier()
q.append(qpe_circ, qargs = [0,1,2,3,4,5,6])
q.measure([0,1,2,3],[0,1,2,3])
q.draw('mpl')
count = execute(q,backend=Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(count)
q = QuantumCircuit(7, 4)
q.x([5,6])
q.append(qpe_circ, qargs=range(7))
# q = q.compose(qpe_circ,qubits = [0,1,2,3,4])
q.draw('mpl')
q.measure([0, 1, 2, 3], [0, 1, 2, 3])
q.draw('mpl')
count = execute(q, backend=Aer.get_backend(
'qasm_simulator')).result().get_counts()
plot_histogram(count)
|
https://github.com/HQSquantumsimulations/qoqo-qiskit
|
HQSquantumsimulations
|
from qiskit import Aer, IBMQ, execute
from qiskit import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram, plot_state_city
"""
Qiskit backends to execute the quantum circuit
"""
def simulator(qc):
"""
Run on local simulator
:param qc: quantum circuit
:return:
"""
backend = Aer.get_backend("qasm_simulator")
shots = 2048
tqc = transpile(qc, backend)
qobj = assemble(tqc, shots=shots)
job_sim = backend.run(qobj)
qc_results = job_sim.result()
return qc_results, shots
def simulator_state_vector(qc):
"""
Select the StatevectorSimulator from the Aer provider
:param qc: quantum circuit
:return:
statevector
"""
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
state_vector = result.get_statevector(qc)
return state_vector
def real_quantum_device(qc):
"""
Use the IBMQ essex device
:param qc: quantum circuit
:return:
"""
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_santiago')
shots = 2048
TQC = transpile(qc, backend)
qobj = assemble(TQC, shots=shots)
job_exp = backend.run(qobj)
job_monitor(job_exp)
QC_results = job_exp.result()
return QC_results, shots
def counts(qc_results):
"""
Get counts representing the wave-function amplitudes
:param qc_results:
:return: dict keys are bit_strings and their counting values
"""
return qc_results.get_counts()
def plot_results(qc_results):
"""
Visualizing wave-function amplitudes in a histogram
:param qc_results: quantum circuit
:return:
"""
plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False))
def plot_state_vector(state_vector):
"""Visualizing state vector in the density matrix representation"""
plt.show(plot_state_city(state_vector))
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
from qiskit import *
# Primeiramente vamos iniciar um circuito
circuitoQ = QuantumCircuit(1,1)
# No qiskit os qubits são inicializados por default com o estado |0>
# Podemos ver isso plotando a esfera de bloch que representa ele
from qiskit.tools.visualization import plot_bloch_multivector
simulator = Aer.get_backend('statevector_simulator')
result = execute(circuitoQ, backend = simulator).result()
statevector = result.get_statevector()
plot_bloch_multivector(statevector)
# As portas Rx,Ry,Rz servem para fazer rotações nos eixos X,Y,Z
# Para demonstrar vamos inicializar outro circuito de 1 qubit
circuito2 = QuantumCircuit(1)
# Agora para aplicar a porta usamos .rx(rotacao_em_radianos,qubit_a_passar_pela_porta)
# Nesse exemplo vamos rotacionar o qubit no eixo x em pi/2
# antes é importante importar o pi da biblioteca math
from math import pi
circuito2.rx(pi/2,0)
circuito2.draw(output = 'mpl')
# Vendo o resultado:
from qiskit.tools.visualization import plot_bloch_multivector
simulator = Aer.get_backend('statevector_simulator')
result = execute(circuito2, backend = simulator).result()
statevector = result.get_statevector()
plot_bloch_multivector(statevector)
|
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.
"""
Tests for uniformly controlled single-qubit unitaries.
"""
import unittest
from ddt import ddt
from test import combine # pylint: disable=wrong-import-order
import numpy as np
from scipy.linalg import block_diag
from qiskit.extensions.quantum_initializer.uc import UCGate
from qiskit import QuantumCircuit, QuantumRegister, BasicAer, execute
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.random import random_unitary
from qiskit.compiler import transpile
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.quantum_info import Operator
_id = np.eye(2, 2)
_not = np.matrix([[0, 1], [1, 0]])
@ddt
class TestUCGate(QiskitTestCase):
"""Qiskit UCGate tests."""
@combine(
squs=[
[_not],
[_id],
[_id, _id],
[_id, 1j * _id],
[_id, _not, _id, _not],
[random_unitary(2, seed=541234).data for _ in range(2**2)],
[random_unitary(2, seed=975163).data for _ in range(2**3)],
[random_unitary(2, seed=629462).data for _ in range(2**4)],
],
up_to_diagonal=[True, False],
)
def test_ucg(self, squs, up_to_diagonal):
"""Test uniformly controlled gates."""
num_con = int(np.log2(len(squs)))
q = QuantumRegister(num_con + 1)
qc = QuantumCircuit(q)
qc.uc(squs, q[1:], q[0], up_to_diagonal=up_to_diagonal)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
if up_to_diagonal:
ucg = UCGate(squs, up_to_diagonal=up_to_diagonal)
unitary = np.dot(np.diagflat(ucg._get_diagonal()), unitary)
unitary_desired = _get_ucg_matrix(squs)
self.assertTrue(matrix_equal(unitary_desired, unitary, ignore_phase=True))
def test_global_phase_ucg(self):
"""Test global phase of uniformly controlled gates"""
gates = [random_unitary(2).data for _ in range(2**2)]
num_con = int(np.log2(len(gates)))
q = QuantumRegister(num_con + 1)
qc = QuantumCircuit(q)
qc.uc(gates, q[1:], q[0], up_to_diagonal=False)
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
unitary_desired = _get_ucg_matrix(gates)
self.assertTrue(np.allclose(unitary_desired, unitary))
def test_inverse_ucg(self):
"""Test inverse function of uniformly controlled gates"""
gates = [random_unitary(2, seed=42 + s).data for s in range(2**2)]
num_con = int(np.log2(len(gates)))
q = QuantumRegister(num_con + 1)
qc = QuantumCircuit(q)
qc.uc(gates, q[1:], q[0], up_to_diagonal=False)
qc.append(qc.inverse(), qc.qubits)
unitary = Operator(qc).data
unitary_desired = np.identity(2**qc.num_qubits)
self.assertTrue(np.allclose(unitary_desired, unitary))
def _get_ucg_matrix(squs):
return block_diag(*squs)
if __name__ == "__main__":
unittest.main()
|
https://github.com/rishikhurana2/FourQuantumAlgorithms
|
rishikhurana2
|
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
#set b equal to '11'
b = '11'
#1) initialize qubits
n = 2
simon_circuit_2 = QuantumCircuit(n*2, n)
#2) Apply Hadamard gates before querying the oracle
simon_circuit_2.h(range(n))
#3) Query oracle
simon_circuit_2 += simon_oracle(b)
#5) Apply Hadamard gates to the input register
simon_circuit_2.h(range(n))
#3) and 6) Measure qubits
simon_circuit_2.measure(range(n), range(n))
# Load saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Execute and monitor the job
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
# Get results and plot counts
device_counts = job.result().get_counts()
plot_histogram(device_counts)
#additionally, function for calculating dot product of results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
print('b = ' + b)
for z in device_counts:
print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots))
#the most significant results are those for which b dot z=0(mod 2).
'''b = 11
11.00 = 0 (mod 2) (45.0%)
11.01 = 1 (mod 2) (6.2%)
11.10 = 1 (mod 2) (6.4%)
11.11 = 0 (mod 2) (42.4%)'''
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit
import numpy as np
qc = QuantumCircuit(3)
qc.ccx(0,1,2)
qc.draw(output="mpl")
qc.decompose().draw(output="mpl")
qc = QuantumCircuit(2)
qc.y(0)
qc.z(1)
qc.h(0)
qc.swap(0,1)
qc.draw(output="mpl")
qc.decompose().draw(output="mpl")
qc.decompose().decompose().draw(output="mpl")
qc = QuantumCircuit(1)
qc.initialize([1/np.sqrt(2), -1/np.sqrt(2)], 0)
qc.draw(output="mpl")
qc.decompose().draw(output="mpl")
qc.decompose().decompose().draw(output="mpl")
qc.decompose().decompose().decompose().draw(output="mpl")
qc.decompose().decompose().decompose().decompose().draw(output="mpl")
|
https://github.com/muehlhausen/vqls-bachelor-thesis
|
muehlhausen
|
"""
Import all required libraries.
"""
from qiskit import (
QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ,
Aer, execute, transpile, assemble
)
from qiskit.circuit import Gate, Instruction
from qiskit.quantum_info.operators import Operator
from qiskit.extensions import ZGate, YGate, XGate, IGate
from scipy.optimize import (
minimize, basinhopping, differential_evolution,
shgo, dual_annealing
)
import random
import numpy as np
import cmath
from typing import List, Set, Dict, Tuple, Optional, Union
# import the params object of the GlobalParameters class
# this provides the parameters used to desribed and model
# the problem the minimizer is supposed to use.
from GlobalParameters_IBMQ import params
"""
This program provides an implementation of the Variational Quantum Linear Solver
as presented by Bravo-Prieto et al. It is implemented for the QISKIT Quantum
SDK. This version of the program uses the local cost function.
Author: Alexander Cornelius Muehlhausen
#########################################################################
######### Core functions
The core functions of the VQLS algorithm.
"""
def generate_ansatz(alpha: List[float]) -> QuantumCircuit:
"""
This function returns a circuit that implements the Ansatz V(alpha).
"""
qr_ansatz = QuantumRegister(params.n_qubits)
circ_ansatz = QuantumCircuit(qr_ansatz)
if not any(isinstance(item, list) for item in alpha):
# this will reformat the list alpha to the required format (if needed)
# this is necessary as the minimizer returns a list without sublists
alpha = _format_alpha(alpha)
# 0th sublayer
for qubit in range(0, params.n_qubits):
circ_ansatz.ry(alpha[0][qubit], qr_ansatz[qubit])
if params.n_qubits % 2 == 0:
# all other sublayers
for sublayer in range(1, 2 * params.n_layers, 2):
# first sublayer of the current layer
# controlled Z-Gate pairs
for qubit_a, qubit_b in zip(qr_ansatz[::2], qr_ansatz[1::2]):
circ_ansatz.cz(qubit_a, qubit_b)
for rotation_param, qubit in zip(alpha[sublayer], qr_ansatz):
circ_ansatz.ry(rotation_param, qubit)
# second sublayer of the current layer
for qubit_a, qubit_b in zip(qr_ansatz[1::2], qr_ansatz[2::2]):
circ_ansatz.cz(qubit_a, qubit_b)
# and Ry to each qubit except the first and last one
for rotation_param, qubit in zip(alpha[sublayer+1], qr_ansatz[1::]):
circ_ansatz.ry(rotation_param, qubit)
else:
# all other sublayers
for sublayer in range(1, 2 * params.n_layers, 2):
# first sublayer of the current layer
for qubit_a, qubit_b in zip(qr_ansatz[:params.n_qubits-1:2],
qr_ansatz[1:params.n_qubits-1:2]):
circ_ansatz.cz(qubit_a, qubit_b)
for rotation_param, qubit in zip(alpha[sublayer],
qr_ansatz[:params.n_qubits-1:]):
circ_ansatz.ry(rotation_param, qubit)
# second sublayer
for qubit_a, qubit_b in zip(qr_ansatz[1::2], qr_ansatz[2::2]):
circ_ansatz.cz(qubit_a, qubit_b)
for rotation_param, qubit in zip(alpha[sublayer+1], qr_ansatz[1::]):
circ_ansatz.ry(rotation_param, qubit)
return circ_ansatz
def hadamard_test(
*, ansatz: Union[Gate, Operator] = None, first: Union[Gate, Operator]
= None, first_uncontrolled: Union[Gate, Operator] = None, j: int
= None, second_uncontrolled: Union[Gate, Operator] = None,
second: Union[Gate, Operator] = None, im=None
):
"""
This function returns a circuit that implements the Hadamard Test.
The ancilliary qubit is the last qubit; a measurement is applied to it.
"""
# prep of QuantumCircuit
qr_had = QuantumRegister(params.n_qubits)
circ_had = QuantumCircuit(qr_had)
ancilla = QuantumRegister(1, name="ancilla")
cr_had = ClassicalRegister(1)
circ_had.add_register(ancilla)
circ_had.add_register(cr_had)
qubits_designation_control = [i for i in range(params.n_qubits)]
qubits_designation_control.insert(0, params.n_qubits)
def append_ifExists(obj: Union[Gate, Operator], control=False):
"""
Append gates to a circuit. Convert them to instructions if necessary.
Control them if necessary.
"""
if isinstance(obj, (Gate, Operator, Instruction, QuantumCircuit)):
_obj = obj.copy()
if isinstance(_obj, Operator):
_obj = _obj.to_instruction()
if control is True:
_obj = _obj.control(1)
circ_had.append(_obj, qubits_designation_control)
else:
circ_had.append(_obj, qr_had)
# act on the ancilla
circ_had.h(ancilla)
# if Im(<>) shall be calculated
if im is not None:
circ_had.sdg(ancilla)
append_ifExists(ansatz)
# clean up the circuit
circ_had.barrier()
# use this for $A_l$
append_ifExists(first, True)
# use this for $U^{\dagger}
append_ifExists(first_uncontrolled)
# $Z_j$
if j is not None:
circ_had.cz(params.n_qubits, qr_had[j])
# use this for $U$
append_ifExists(second_uncontrolled)
# use this for $A^{\dagger}_m$
append_ifExists(second, True)
# clean up the circuit
circ_had.barrier()
# last operation on the ancilla & measurement
circ_had.h(ancilla)
circ_had.measure(ancilla, cr_had)
return circ_had
def calculate_beta(alpha: List[float]) -> List[List[complex]]:
"""
This function calculates all parameters $\beta_{lm}$ that are required,
i.e. all parameters with l, m so that $c_l$ and $c^{*}_m$ are not equal to 0.
"""
# preparation of the result list
beta = [[complex(0, 0) for _ in params.coefficients] for _
in params.coefficients_conjugate]
# generate Ansatz outside the loops for better performance
V = generate_ansatz(alpha).to_gate()
# $A_l, (l, c_l)$
for gate_l, (l, coeff_l) in zip(params.decomposition_asGate,
enumerate(params.coefficients)):
if coeff_l == 0:
continue # increase perfomance by ommiting unused $\beta$
# $A^{\dagger}_m, (m, c^{*}_m)$
for gate_m_adj, (m, coeff_m) in zip(params.decomposition_adjoint,
enumerate(params.coefficients_conjugate)):
if coeff_m == 0:
continue # increase perfomance by ommiting unused $\beta$
# circuit for Re ( <0| V(alpha)(+) A_m(+) A_l V(alpha) |0>)
circ_had_re = hadamard_test(ansatz=V, first=gate_l,
second=gate_m_adj)
# circuit for Im ( <0| V(alpha)(+) A_m(+) A_l V(alpha) |0>)
circ_had_im = hadamard_test(ansatz=V, first=gate_l,
second=gate_m_adj, im=1)
# calculate Re and Im of $\beta_{lm}$ / simulate circuits
expV_had_re = _calculate_expectationValue_HadamardTest(circ_had_re)
expV_had_im = _calculate_expectationValue_HadamardTest(circ_had_im)
# set together $\beta_{lm}$ from its real and imaginary part
expV_had = complex(expV_had_re, expV_had_im)
beta[l][m] = expV_had
return beta
def calculate_delta(alpha: List[float], beta: List[List[complex]]) -> List[List[complex]]:
"""
This function calculates all $\delta_{lm}$ that are required,
i.e. all parameters with l, m so that $c_l$ and $c^{*}_m$ are not equal to 0.
"""
# initialize the list for the results
delta = [[complex(0, 0) for _ in params.coefficients] for _
in params.coefficients_conjugate]
# prepare $V(\vec{alpha})$, $U$ and $U^{\dagger}$
V = generate_ansatz(alpha).to_gate()
U = _U_Id().to_gate()
U_dagger = _U_Id().to_gate()
# $A_l, (l, c_l)$
for gate_l, (l, coeff_l) in zip(params.decomposition_asGate,
enumerate(params.coefficients)):
if coeff_l == 0:
continue # increase perfomance by ommiting unused $\delta$
# $A^{\dagger}_m, (m, c^{*}_m)$
for gate_m_adj, (m, coeff_m) in zip(
params.decomposition_adjoint,
enumerate(params.coefficients_conjugate)
):
if coeff_m == 0:
continue # increase perfomance by ommiting unused $\delta$
temp = beta[l][m]
# 1/n_qubits sum_j <0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0>
for j in range(params.n_qubits):
# Re(<0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0>)
circ_had_re = hadamard_test(
ansatz=V, first=gate_l,
first_uncontrolled=U_dagger, j=j,
second_uncontrolled=U,
second=gate_m_adj)
# Im(<0| V(+) A_m(+) U (Z_j * 1_{j-bar}) U(+) A_l V |0>)
circ_had_im = hadamard_test(
ansatz=V, first=gate_l,
first_uncontrolled=U_dagger, j=j,
second_uncontrolled=U,
second=gate_m_adj, im=1)
# calculate Re and Im of $\delta_{lm}$ / simulate circuits
expV_had_re = _calculate_expectationValue_HadamardTest(circ_had_re)
expV_had_im = _calculate_expectationValue_HadamardTest(circ_had_im)
# set together $\delta_{lm}$ from its real and imaginary part
# and execute the summation
expV_had = complex(expV_had_re, expV_had_im)
temp += 1/params.n_qubits * expV_had
delta[l][m] = temp
return delta
def calculate_local_cost_function(alpha: List[float]) -> Union[complex, float]:
"""
returns
cost = <x| H_local |x> / <psi|psi>
with
<x| H_local |x> = Sum_l_m c_l c_m(*) delta
<psi|psi> = Sum_l_m c_l c_m(*) beta
"""
beta = calculate_beta(alpha)
delta = calculate_delta(alpha, beta)
xHx = 0
psipsi = 0
for l, coeff_l in enumerate(params.coefficients):
for m, coeff_m_conj in enumerate(params.coefficients_conjugate):
xHx += coeff_l * coeff_m_conj * delta[l][m]
psipsi += coeff_l * coeff_m_conj * beta[l][m]
# cost = xHx / psipsi
cost = abs(xHx/psipsi)
print(alpha)
print("local cost function " + str(cost))
return cost
def minimize_local_cost_function(method: str) -> List[float]:
"""
This function minimizes the local cost function.
It returns the alpha for which the approximation
A V(alpha_out) |0> approx |b>
is optimal.
Implements scipy.optimize.minimize .
"""
min = minimize(calculate_local_cost_function, x0=params.alpha_0,
method=method,
options={'maxiter': params.COBYLA_maxiter})
print(min)
alpha_out = min['x']
print(alpha_out)
return alpha_out
"""
Fix the result.
"""
def postCorrection(qc: QuantumCircuit) -> QuantumCircuit:
"""
This function is used to apply post correction to the circuit generated by
applying V(alpha) and A as the result is not identical to |b>. The result of
a circuit built using the functions presented above returns the reverse of b
with random sign errors.
"""
for i in range(params.n_qubits):
qc.x(i)
qc.z(i)
return qc
"""
######### Helper functions
Functions that do not add to the logic of the algorithm but instead implement
often used features or need to be changed sometimes.
"""
def _format_alpha(alpha_unformated: List[float]) -> List[List[float]]:
"""
This function formats a list to be in the correct form for the function that
builds V(alpha). This means it will format the list to be of the form:
[[0th sublayer], [1st sublayer], [2nd sublayer], ...]
So for e.g. 4 qubits it will return (- stands for some random value):
[[-,-,-,-],[-,-,-,-],[-,-],[-,-,-,-],[-,-]]
and for e.g. 3 qubits:
[[-,-],[-,-],[-,-],[-,-],[-,-]]
"""
alpha_formated = []
if any(isinstance(item, list) for item in alpha_unformated):
return alpha_unformated
else:
if (params.n_qubits % 2) == 0:
start = 0
end = params.n_qubits
alpha_formated.append(alpha_unformated[start:params.n_qubits])
for _ in range(params.n_layers):
start = end
end = start + params.n_qubits
alpha_formated.append(alpha_unformated[start:end])
start = end
end = start + params.n_qubits - 2
alpha_formated.append(alpha_unformated[start:end])
else:
start = 0
end = params.n_qubits
alpha_formated.append(alpha_unformated[start:end])
for _ in range(params.n_layers):
start = end
end = start + params.n_qubits-1
alpha_formated.append(alpha_unformated[start:end])
start = end
end = start + params.n_qubits - 1
alpha_formated.append(alpha_unformated[start:end])
return alpha_formated
def _calculate_expectationValue_HadamardTest(circ_had: QuantumCircuit) -> float:
"""
Will return the expectation value for a given circuit for a Hadamard test.
Supports different backends.
Based on the IBM Quantum and the Qiskit documentations.
"""
backend = params.IBMQ_backend
transpiled_circ = transpile(circ_had, backend)
job = backend.run(transpiled_circ)
result = job.result()
counts = result.get_counts(circ_had)
p_0 = counts.get('0', 0)
p_1 = counts.get('1', 0)
return ((p_0 - p_1) / params.IBMQ_shots)
def _U_YZ() -> QuantumCircuit:
"""
This function generates a circuit that resembles a U gate that fulfills:
U |0> = |b> .
Hadamard Gates on qubits 0, 2 and 3; y and then z Gate on qubit 2.
"""
qr_U_primitive = QuantumRegister(params.n_qubits)
circ_U_primitive = QuantumCircuit(qr_U_primitive)
circ_U_primitive.h(0)
# circ_U_primitive.h(1)
circ_U_primitive.h(2)
circ_U_primitive.h(3)
circ_U_primitive.y(2)
circ_U_primitive.z(2)
return circ_U_primitive
def _U_adjoint_YZ() -> QuantumCircuit:
"""
This function generates a circuit that resembles
$U^{\dagger}$ for:
U |0> = |b> .
U was:
Hadamard Gates on qubits 0, 2 and 3; y and then z Gate on qubit 2.
"""
qr_U_primitive = QuantumRegister(params.n_qubits)
circ_U_primitive = QuantumCircuit(qr_U_primitive)
circ_U_primitive.z(2)
circ_U_primitive.y(2)
circ_U_primitive.h(0)
# circ_U_primitive.h(1)
circ_U_primitive.h(2)
circ_U_primitive.h(3)
return circ_U_primitive
def _U_Id() -> QuantumCircuit:
"""
This function generates a circuit that resembles a U gate that fulfills:
U |0> = |b> .
Hadamard Gates on qubits 0, 2 and 3.
"""
qr_U_primitive = QuantumRegister(params.n_qubits)
circ_U_primitive = QuantumCircuit(qr_U_primitive)
circ_U_primitive.h(0)
# circ_U_primitive.h(1)
circ_U_primitive.h(2)
circ_U_primitive.h(3)
return circ_U_primitive
|
https://github.com/hritiksauw199/Optimized-Shor-Algorithm-for-factoring
|
hritiksauw199
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
import math
# importing Qiskit
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# import basic plot tools
from qiskit.visualization import plot_histogram
qpe = QuantumCircuit(4, 3)
qpe.x(3)
#Apply Hadamard gate
for qubit in range(3):
qpe.h(qubit)
qpe.draw()
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe.cp(math.pi/4, counting_qubit, 3); # This is CU # we use 2*pi*(1/theta)
repetitions *= 2
qpe.draw()
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(-math.pi/float(2**(j-m)), m, j)
qc.h(j)
qpe.barrier()
# Apply inverse QFT
qft_dagger(qpe, 3)
# Measure
qpe.barrier()
for n in range(3):
qpe.measure(n,n)
qpe.draw()
aer_sim = Aer.get_backend('aer_simulator')
shots = 2048
t_qpe = transpile(qpe, aer_sim)
qobj = assemble(t_qpe, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
# Create and set up circuit
qpe2 = QuantumCircuit(4, 3)
# Apply H-Gates to counting qubits:
for qubit in range(3):
qpe2.h(qubit)
# Prepare our eigenstate |psi>:
qpe2.x(3)
# Do the controlled-U operations:
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe2.cp(angle, counting_qubit, 3);
repetitions *= 2
# Do the inverse QFT:
qft_dagger(qpe2, 3)
# Measure of course!
for n in range(3):
qpe2.measure(n,n)
qpe2.draw()
# Let's see the results!
aer_sim = Aer.get_backend('aer_simulator')
shots = 4096
t_qpe2 = transpile(qpe2, aer_sim)
qobj = assemble(t_qpe2, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
# Create and set up circuit
qpe3 = QuantumCircuit(6, 5)
# Apply H-Gates to counting qubits:
for qubit in range(5):
qpe3.h(qubit)
# Prepare our eigenstate |psi>:
qpe3.x(5)
# Do the controlled-U operations:
angle = 2*math.pi/3
repetitions = 1
for counting_qubit in range(5):
for i in range(repetitions):
qpe3.cp(angle, counting_qubit, 5);
repetitions *= 2
# Do the inverse QFT:
qft_dagger(qpe3, 5)
# Measure of course!
qpe3.barrier()
for n in range(5):
qpe3.measure(n,n)
qpe3.draw()
# Let's see the results!
aer_sim = Aer.get_backend('aer_simulator')
shots = 4096
t_qpe3 = transpile(qpe3, aer_sim)
qobj = assemble(t_qpe3, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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 KAK over optimization"""
import unittest
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, transpile
from qiskit.circuit.library import CU1Gate
from qiskit.test import QiskitTestCase
class TestKAKOverOptim(QiskitTestCase):
"""Tests to verify that KAK decomposition
does not over optimize.
"""
def test_cz_optimization(self):
"""Test that KAK does not run on a cz gate"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.cz(qr[0], qr[1])
cz_circ = transpile(
qc,
None,
coupling_map=[[0, 1], [1, 0]],
basis_gates=["u1", "u2", "u3", "id", "cx"],
optimization_level=3,
)
ops = cz_circ.count_ops()
self.assertEqual(ops["u2"], 2)
self.assertEqual(ops["cx"], 1)
self.assertFalse("u3" in ops.keys())
def test_cu1_optimization(self):
"""Test that KAK does run on a cu1 gate and
reduces the cx count from two to one.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.append(CU1Gate(np.pi), [qr[0], qr[1]])
cu1_circ = transpile(
qc,
None,
coupling_map=[[0, 1], [1, 0]],
basis_gates=["u1", "u2", "u3", "id", "cx"],
optimization_level=3,
)
ops = cu1_circ.count_ops()
self.assertEqual(ops["cx"], 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from qiskit import compiler, BasicAer, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
def convert_to_basis_gates(circuit):
# unroll the circuit using the basis u1, u2, u3, cx, and id gates
unroller = Unroller(basis=['u1', 'u2', 'u3', 'cx', 'id'])
pm = PassManager(passes=[unroller])
qc = compiler.transpile(circuit, BasicAer.get_backend('qasm_simulator'), pass_manager=pm)
return qc
def is_qubit(qb):
# check if the input is a qubit, which is in the form (QuantumRegister, int)
return isinstance(qb, tuple) and isinstance(qb[0], QuantumRegister) and isinstance(qb[1], int)
def is_qubit_list(qbs):
# check if the input is a list of qubits
for qb in qbs:
if not is_qubit(qb):
return False
return True
def summarize_circuits(circuits):
"""Summarize circuits based on QuantumCircuit, and four metrics are summarized.
Number of qubits and classical bits, and number of operations and depth of circuits.
The average statistic is provided if multiple circuits are inputed.
Args:
circuits (QuantumCircuit or [QuantumCircuit]): the to-be-summarized circuits
"""
if not isinstance(circuits, list):
circuits = [circuits]
ret = ""
ret += "Submitting {} circuits.\n".format(len(circuits))
ret += "============================================================================\n"
stats = np.zeros(4)
for i, circuit in enumerate(circuits):
dag = circuit_to_dag(circuit)
depth = dag.depth()
width = dag.width()
size = dag.size()
classical_bits = dag.num_cbits()
op_counts = dag.count_ops()
stats[0] += width
stats[1] += classical_bits
stats[2] += size
stats[3] += depth
ret = ''.join([ret, "{}-th circuit: {} qubits, {} classical bits and {} operations with depth {}\n op_counts: {}\n".format(
i, width, classical_bits, size, depth, op_counts)])
if len(circuits) > 1:
stats /= len(circuits)
ret = ''.join([ret, "Average: {:.2f} qubits, {:.2f} classical bits and {:.2f} operations with depth {:.2f}\n".format(
stats[0], stats[1], stats[2], stats[3])])
ret += "============================================================================\n"
return ret
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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")
circ.draw(output='mpl')
|
https://github.com/maximusron/qgss_2021_labs
|
maximusron
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
encode_map = ZZFeatureMap(feature_dimension=2, reps=4, entanglement='linear', insert_barriers=True)
ex1_circuit = encode_map.bind_parameters(x)
ex1_circuit.draw(output='mpl')
# YOUR CODE HERE
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
zz_map = ZZFeatureMap(feature_dimension=2, reps=4, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit = zz_kernel.construct_circuit(x,y)
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
amplitude = counts['00']/sum(counts.values())
# YOUR CODE HERE
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/TanveshT/IBM-Quantum-Challenge
|
TanveshT
|
# Cell 1
import numpy as np
from qiskit import Aer, QuantumCircuit, execute
from qiskit.visualization import plot_histogram
from IPython.display import display, Math, Latex
from may4_challenge import plot_state_qsphere
from may4_challenge.ex1 import minicomposer
from may4_challenge.ex1 import check1, check2, check3, check4, check5, check6, check7, check8
from may4_challenge.ex1 import return_state, vec_in_braket, statevec
# Cell 2
# press shift + return to run this code cell
# then, click on the gate that you want to apply to your qubit
# next, you have to choos
# the qubit that you want to apply it to (choose '0' here)
# click on clear to restart
minicomposer(1, dirac=True, qsphere=True)
# Cell 3
def create_circuit():
qc = QuantumCircuit(1)
qc.x(0)
return qc
# check solution
qc = create_circuit()
state = statevec(qc)
check1(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 4
def create_circuit2():
qc = QuantumCircuit(1)
qc.h(0)
return qc
qc = create_circuit2()
state = statevec(qc)
check2(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 5
def create_circuit3():
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
return qc
qc = create_circuit3()
state = statevec(qc)
check3(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 6
def create_circuit4():
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
qc.s(0)
return qc
qc = create_circuit4()
state = statevec(qc)
check4(state)
plot_state_qsphere(state.data, show_state_labels=True, show_state_angles=True)
# Cell 7
# press shift + return to run this code cell
# then, click on the gate that you want to apply followed by the qubit(s) that you want it to apply to
# for controlled gates, the first qubit you choose is the control qubit and the second one the target qubit
# click on clear to restart
minicomposer(2, dirac = True, qsphere = True)
# Cell 8
def create_circuit():
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
return qc
qc = create_circuit()
state = statevec(qc) # determine final state after running the circuit
display(Math(vec_in_braket(state.data)))
check5(state)
qc.draw(output='mpl') # we draw the circuit
# Cell 9
def create_circuit6():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also
# two classical bits for the measurement later
qc.h(0)
qc.cx(0,1)
qc.y(1)
return qc
qc = create_circuit6()
state = statevec(qc) # determine final state after running the circuit
display(Math(vec_in_braket(state.data)))
check6(state)
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
qc.draw(output='mpl') # we draw the circuit
# Cell 10
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 1000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 1000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
check
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def create_circuit6():
qc = QuantumCircuit(3,3) # this time, we not only want two qubits, but also
# two classical bits for the measurement later
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
return qc
qc = create_circuit6()
state = statevec(qc)
display(Math(vec_in_braket(state.data)))
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1)
qc.measure(2,2)# we perform a measurement on qubit q_1 and store the information on the classical bit c_1
qc.draw(output='mpl') # we draw the circuit
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
check8(counts)
plot_histogram(counts)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import math
th = np.arange(0, 2*math.pi, 0.1)
prE3 = 2*(1-(math.sqrt(2)*(np.sin(th/2)**2))/(1+math.sqrt(2)))
matplotlib.rcParams.update({'font.size':10})
plt.figure(figsize = (5,3), dpi = 100)
plt.plot(th, prE3)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$Pr(E_{3})$')
plt.show()
|
https://github.com/trevorpiltch/Grovers-Algorithm
|
trevorpiltch
|
from qiskit import *
def oracle(n, target_binary):
"""Creates an oracle based on the implementation here: https://github.com/SaashaJoshi/grovers-algorithm"""
circuit = QuantumCircuit(n + 1)
for index, value in reversed(list(enumerate(target_binary))):
if value == '0':
circuit.x(n-1-index)
cbits = []
for i in range(n):
cbits.append(i)
circuit.mct(cbits, n, n)
for index, value in enumerate(target_binary):
if value == '0':
circuit.x(n-1-index)
gate = circuit.to_gate()
gate.name = 'Oracle'
return gate
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Alpine Quantum Technologies GmbH 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from math import pi
from typing import Union
import pytest
from hypothesis import assume, example, given
from hypothesis import strategies as st
from qiskit import QuantumCircuit, transpile
from qiskit.circuit.library import RXGate, RYGate
from qiskit_aqt_provider.aqt_resource import AQTResource
from qiskit_aqt_provider.test.circuits import (
assert_circuits_equal,
assert_circuits_equivalent,
qft_circuit,
)
from qiskit_aqt_provider.test.fixtures import MockSimulator
from qiskit_aqt_provider.transpiler_plugin import rewrite_rx_as_r, wrap_rxx_angle
@pytest.mark.parametrize(
("input_theta", "output_theta", "output_phi"),
[
(pi / 3, pi / 3, 0.0),
(-pi / 3, pi / 3, pi),
(7 * pi / 5, 3 * pi / 5, pi),
(25 * pi, pi, pi),
(22 * pi / 3, 2 * pi / 3, pi),
],
)
def test_rx_rewrite_example(
input_theta: float,
output_theta: float,
output_phi: float,
) -> None:
"""Snapshot test for the Rx(θ) → R(θ, φ) rule."""
result = QuantumCircuit(1)
result.append(rewrite_rx_as_r(input_theta), (0,))
expected = QuantumCircuit(1)
expected.r(output_theta, output_phi, 0)
reference = QuantumCircuit(1)
reference.rx(input_theta, 0)
assert_circuits_equal(result, expected)
assert_circuits_equivalent(result, reference)
@given(theta=st.floats(allow_nan=False, min_value=-1000 * pi, max_value=1000 * pi))
@pytest.mark.parametrize("optimization_level", [0, 1, 2, 3])
@pytest.mark.parametrize("test_gate", [RXGate, RYGate])
def test_rx_ry_rewrite_transpile(
theta: float,
optimization_level: int,
test_gate: Union[RXGate, RYGate],
) -> None:
"""Test the rewrite rule: Rx(θ), Ry(θ) → R(θ, φ), θ ∈ [0, π], φ ∈ [0, 2π]."""
assume(abs(theta) > pi / 200)
# we only need the backend's transpiler target for this test
backend = MockSimulator(noisy=False)
qc = QuantumCircuit(1)
qc.append(test_gate(theta), (0,))
trans_qc = transpile(qc, backend, optimization_level=optimization_level)
assert isinstance(trans_qc, QuantumCircuit)
assert_circuits_equivalent(trans_qc, qc)
assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates)
num_r = trans_qc.count_ops().get("r")
assume(num_r is not None)
assert num_r == 1
for operation in trans_qc.data:
instruction = operation[0]
if instruction.name == "r":
theta, phi = instruction.params
assert 0 <= float(theta) <= pi
assert 0 <= float(phi) <= 2 * pi
break
else: # pragma: no cover
pytest.fail("No R gates in transpiled circuit.")
def test_decompose_1q_rotations_example(offline_simulator_no_noise: AQTResource) -> None:
"""Snapshot test for the efficient rewrite of single-qubit rotation runs as ZXZ."""
qc = QuantumCircuit(1)
qc.rx(pi / 2, 0)
qc.ry(pi / 2, 0)
expected = QuantumCircuit(1)
expected.rz(-pi / 2, 0)
expected.r(pi / 2, 0, 0)
result = transpile(qc, offline_simulator_no_noise, optimization_level=3)
assert isinstance(result, QuantumCircuit) # only got one circuit back
assert_circuits_equal(result, expected)
assert_circuits_equivalent(result, expected)
def test_rxx_wrap_angle_case0() -> None:
"""Snapshot test for Rxx(θ) rewrite with 0 <= θ <= π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(pi / 2), (0, 1))
expected = QuantumCircuit(2)
expected.rxx(pi / 2, 0, 1)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case0_negative() -> None:
"""Snapshot test for Rxx(θ) rewrite with -π/2 <= θ < 0."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(-pi / 2), (0, 1))
expected = QuantumCircuit(2)
expected.rz(pi, 0)
expected.rxx(pi / 2, 0, 1)
expected.rz(pi, 0)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case1() -> None:
"""Snapshot test for Rxx(θ) rewrite with π/2 < θ <= 3π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(3 * pi / 2), (0, 1))
expected = QuantumCircuit(2)
expected.rx(pi, 0)
expected.rx(pi, 1)
expected.rxx(pi / 2, 0, 1)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case1_negative() -> None:
"""Snapshot test for Rxx(θ) rewrite with -3π/2 <= θ < -π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(-3 * pi / 2), (0, 1))
expected = QuantumCircuit(2)
expected.rxx(pi / 2, 0, 1)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case2() -> None:
"""Snapshot test for Rxx(θ) rewrite with θ > 3*π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(18 * pi / 10), (0, 1)) # mod 2π = 9π/5 → -π/5
expected = QuantumCircuit(2)
expected.rz(pi, 0)
expected.rxx(pi / 5, 0, 1)
expected.rz(pi, 0)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case2_negative() -> None:
"""Snapshot test for Rxx(θ) rewrite with θ < -3π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(-18 * pi / 10), (0, 1)) # mod 2π = π/5
expected = QuantumCircuit(2)
expected.rxx(pi / 5, 0, 1)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
@given(
angle=st.floats(
allow_nan=False,
allow_infinity=False,
min_value=-1000 * pi,
max_value=1000 * pi,
)
)
@pytest.mark.parametrize("qubits", [3])
@pytest.mark.parametrize("optimization_level", [0, 1, 2, 3])
def test_rxx_wrap_angle_transpile(angle: float, qubits: int, optimization_level: int) -> None:
"""Check that Rxx angles are wrapped by the transpiler."""
assume(abs(angle) > pi / 200)
qc = QuantumCircuit(qubits)
qc.rxx(angle, 0, 1)
# we only need the backend's transpilation target for this test
backend = MockSimulator(noisy=False)
trans_qc = transpile(qc, backend, optimization_level=optimization_level)
assert isinstance(trans_qc, QuantumCircuit)
assert_circuits_equivalent(trans_qc, qc)
assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates)
num_rxx = trans_qc.count_ops().get("rxx", 0)
# Higher optimization levels can optimize e.g. Rxx(2n*π) = Identity away.
assert num_rxx <= 1
# check that the Rxx gate has angle in [0, π/2]
for operation in trans_qc.data:
instruction = operation[0]
if instruction.name == "rxx":
(theta,) = instruction.params
assert 0 <= float(theta) <= pi / 2
break
else: # pragma: no cover
if num_rxx > 0:
pytest.fail("Transpiled circuit contains no Rxx gate.")
@example(angles_pi=[-582.16 / pi])
@given(
angles_pi=st.lists(
st.floats(min_value=-1000.0, max_value=1000.0, allow_nan=False),
min_size=1,
max_size=4,
)
)
@pytest.mark.parametrize("optimization_level", [0, 1, 2, 3])
def test_transpilation_preserves_or_decreases_number_of_rxx_gates(
angles_pi: list[float], optimization_level: int
) -> None:
"""Check that transpilation at least preserves the number of RXX gates."""
if optimization_level > 1:
# FIXME: remove once https://github.com/Qiskit/qiskit/issues/12051 is fixed.
assume(len(angles_pi) == 1)
qc = QuantumCircuit(2)
for angle_pi in angles_pi:
qc.rxx(angle_pi * pi, 0, 1)
# we only need the backend's transpilation target for this test
backend = MockSimulator(noisy=False)
tr_qc = transpile(qc, backend, optimization_level=optimization_level)
tr_qc_ops = tr_qc.count_ops()
assert set(tr_qc_ops) <= set(backend.configuration().basis_gates)
qc_rxx = qc.count_ops()["rxx"]
assert qc_rxx == len(angles_pi)
assert tr_qc_ops.get("rxx", 0) <= qc_rxx
@pytest.mark.parametrize("qubits", [1, 5, 10])
@pytest.mark.parametrize("optimization_level", [0, 1, 2, 3])
def test_qft_circuit_transpilation(
qubits: int, optimization_level: int, offline_simulator_no_noise: AQTResource
) -> None:
"""Transpile a N-qubit QFT circuit for an AQT backend. Check that the angles are properly
wrapped.
"""
qc = qft_circuit(qubits)
trans_qc = transpile(qc, offline_simulator_no_noise, optimization_level=optimization_level)
assert isinstance(trans_qc, QuantumCircuit)
assert set(trans_qc.count_ops()) <= set(offline_simulator_no_noise.configuration().basis_gates)
rxx_count = 0
r_count = 0
for operation in trans_qc.data:
instruction = operation[0]
if instruction.name == "rxx":
(theta,) = instruction.params
assert 0 <= float(theta) <= pi / 2
rxx_count += 1
if instruction.name == "r":
(theta, _) = instruction.params
assert abs(theta) <= pi
r_count += 1
assert r_count > 0
if qubits > 1:
assert rxx_count > 0
if optimization_level < 2 and qubits < 6:
assert_circuits_equivalent(qc, trans_qc)
|
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
|
gustavomirapalheta
|
# Setup básico
!pip install qiskit -q
!pip install qiskit[visualization] -q
import qiskit as qk
!pip install qiskit-aer -q
import qiskit_aer as qk_aer
import numpy as np
np.set_printoptions(precision=3, suppress=True)
from matplotlib import pyplot as plt
%matplotlib inline
import pandas as pd
import sklearn as sk
# Remember that qiskit has to be already installed in the Python environment.
# Otherwise the import command will fail
import qiskit as qk
print("A Qubit (initialized in the state |0> plus one classical bit")
qr = qk.QuantumRegister(1,'q')
cr = qk.ClassicalRegister(1,'c')
qc = qk.QuantumCircuit(qr, cr)
display(qc.draw('mpl', style = 'clifford', scale = 1))
print("A qubit forced initialized in the state |0>")
qc.initialize([1,0])
display(qc.draw('mpl', style = 'clifford', scale = 1))
print("A qubit forced initialized in |0> and a measurement")
qc.measure([0],[0])
display(qc.draw('mpl', style = 'clifford'))
import qiskit as qk
import qiskit_aer as qk_aer
# A list of possible measurements.
qk_aer.Aer.backends()[7:]
import qiskit as qk
# To simplify the code let's use the function QuantumCircuit(n,m)
# which creates n Qubits and m Classical Registers at once
qc = qk.QuantumCircuit(1,1)
# Also, it is not necessary to force initialize the qubits. Whenever
# they are created, they start from |0>.
qc.measure([0],[0])
display(qc.draw('mpl', style = 'clifford', scale=1))
# Let's choose a Aer backend with the aer_simulator
backend = qk_aer.Aer.get_backend('aer_simulator')
# Next we "transpile" the circuit through the backend chosen
qc_exe = qk.transpile(qc, backend)
# And execute the circuit qc in the simulator backend
# getting as final result the counts from 1.000 measures
# of the qubit state
result = backend.run(qc_exe, shots=1000).result().get_counts()
result
import qiskit as qk
import qiskit_aer as qk_aer
backend = qk_aer.Aer.get_backend('aer_simulator')
qc_exe = qk.transpile(qc, backend)
result = backend.run(qc, shots=1000).result().get_counts()
qk.visualization.plot_distribution(result)
def show_histogram(qc,shots=1000):
display(qc.draw('mpl', style = 'clifford', scale=1))
backend = qk_aer.Aer.get_backend('aer_simulator')
qc_exe = qk.transpile(qc, backend)
result = backend.run(qc, shots=1000).result().get_counts()
print(result)
grafico = qk.visualization.plot_distribution(result)
display(grafico)
return([result, grafico])
show_histogram(qc);
import numpy as np
v0 = np.array([[1],[0]]);v0
v1 = np.array([[0],[1]]); v1
X = np.array([[0,1],[1,0]]); X
X.dot(v0)
X.dot(v1)
import qiskit as qk
# Notice the compact way of creating a circuit. We indicate just the number of
# qubits and in the end we make a measurement of all qubits with measure_all()
# Also, when using measure_all(), Qiskit inserts a barrier between the Qubits
# and the measurements (classical bits)
qc = qk.QuantumCircuit(1)
qc.x(0)
qc.measure_all()
show_histogram(qc);
import numpy as np
# Notice that we are creating the v0 matrix using the transpose operation
v0 = np.array([[1,0]]).T; v0
# Here it is created again de X matrix
X = np.array([[0,1],[1,0]]); X
# Multiplying v0 by the X matrix twice you get again v0
X.dot(X).dot(v0)
# Multiplying the X matrix by itself you get the Identity matrix
X.dot(X)
import qiskit as qk
qc = qk.QuantumCircuit(1)
qc.x(0)
qc.x(0)
qc.measure_all()
show_histogram(qc);
import qiskit as qk
qc = qk.QuantumCircuit(1)
qc.initialize([2**-0.5,2**-0.5],0)
qc.measure_all()
show_histogram(qc);
import numpy as np
v0 = np.array([[1,0]]).T; v0
H = np.array([[1,1],[1,-1]])/np.sqrt(2); H
H.dot(v0)
import qiskit as qk
qc = qk.QuantumCircuit(1)
qc.h(0)
qc.measure_all()
show_histogram(qc);
import qiskit as qk
qc = qk.QuantumCircuit(1)
qc.initialize([2**-0.5,-(2**-0.5)],0)
qc.measure_all()
show_histogram(qc)
import qiskit as qk
qc = qk.QuantumCircuit(1)
qc.initialize([2**-0.5,-(2**-0.5)],0)
qc.h(0)
qc.measure_all()
show_histogram(qc);
import qiskit as qk
qc = qk.QuantumCircuit(1)
qc.x(0)
qc.h(0)
qc.h(0)
qc.measure_all()
show_histogram(qc);
import numpy as np
# First let's start with the qubit in the state |psi> = (|0> - |1>)/sqrt(2)
psi = np.array([[1,-1]]).T/(2**0.5); psi
H = np.array([[1,1],[1,-1]])/2**0.5; H
# Now let's pass the qubit Psi through an Hadamard gate.
# The result is a qubit in the state |1>
H.dot(psi)
# Let's start with a qubit in the state |1>, pass it through a
# a hadamard gate twice and check the result
v0 = np.array([[0,1]]).T; v0
H.dot(H).dot(v0)
# This means that if we multiply the H gate by itself the result
# will be an Identity matrix. Let's check it.
H.dot(H)
import qiskit as qk
qc = qk.QuantumCircuit(2)
qc.measure_all()
show_histogram(qc);
import numpy as np
psi1 = np.array([[1,0]]).T; psi1
psi2 = np.array([[1,0]]).T; psi2
# In numpy the tensor product is calculated with the function kron
np.kron(psi1,psi2)
import qiskit as qk
qc = qk.QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.measure_all()
show_histogram(qc);
import numpy as np
psi1 = np.array([[1,0]]).T;psi1
psi2 = np.array([[1,0]]).T;psi2
H = np.array([[1,1],[1,-1]])/2**0.5;H
# When we want to combine two vector states or gate matrices we tensor product them.
psi3 = np.kron(psi1,psi2);psi3
H2 = np.kron(H,H);H2
# When we want to pass a vetor through a gate we calculate the dot product
# of the total gate matrix with the total vector.
# As we have predicted, the resulting vector state has a=b=c=d=1/2
psi4 = H2.dot(psi3); psi4
import qiskit as qk
qc = qk.QuantumCircuit(2)
qc.x([0,1])
qc.h(0)
qc.h(1)
qc.measure_all()
show_histogram(qc);
import numpy as np
psi1 = np.array([[0,1]]).T;psi1
psi2 = np.array([[0,1]]).T;psi2
H = np.array([[1,1],[1,-1]])/2**0.5;H
# When we want to combine two vector states or gate matrices we tensor product them.
psi3 = np.kron(psi1,psi2);psi3
H2 = np.kron(H,H);H2
# When we want to pass a vetor through a gate we calculate the dot product
# of the total gate matrix with the total vector.
# As we have predicted, the resulting vector state has a=b=c=d=1/2
psi4 = H2.dot(psi3); psi4
import qiskit as qk
qc = qk.QuantumCircuit(2)
qc.cx(0,1)
qc.measure_all()
show_histogram(qc);
import numpy as np
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
v00 = np.array([[1,0,0,0]]).T;v00
# C.v00 = v00
C.dot(v00)
# Please notice that Qiskit's qubits presentation order is reversed.
# Therefore 10 in the histogram's x axis should be read as 01 (from
# inside out or right to left). This makes sense when pairing a
# a circuit with an histogram
import qiskit as qk
qc = qk.QuantumCircuit(2)
qc.x(1)
qc.cx(0,1)
qc.measure_all()
show_histogram(qc)
import numpy as np
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
v01 = np.array([[0,1,0,0]]).T;v01
# C.v01 = v01
C.dot(v01)
import qiskit as qk
qc = qk.QuantumCircuit(2)
qc.x(1)
qc.cx(0,1)
qc.measure_all()
show_histogram(qc);
import numpy as np
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
v10 = np.array([[0,0,1,0]]).T; v10
# C.v10 = v11
C.dot(v10)
# Again remember to read qiskit qubits state presentation order
# from right to left. Therefore 01 in the x axis is in fact 10
import qiskit as qk
qc = qk.QuantumCircuit(2)
qc.x([0,1])
qc.cx(0,1)
qc.measure_all()
show_histogram(qc);
import numpy as np
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
v11 = np.array([[0,0,0,1]]).T; v11
# C.v11 = v10
C.dot(v11)
import qiskit as qk
qc = qk.QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.measure_all()
show_histogram(qc);
import numpy as np
va = np.array([[1,0]]).T; va
vb = np.array([[1,0]]).T; vb
H = np.array([[1,1],[1,-1]])/2**0.5;H
vaH = H.dot(va); vaH
vaHvb = np.kron(vaH,vb); vaHvb
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
vout = C.dot(vaHvb); vout
import qiskit as qk
qc = qk.QuantumCircuit(2)
qc.x(0)
qc.h(0)
qc.cx(0,1)
qc.measure_all()
show_histogram(qc);
import numpy as np
va = np.array([[0,1]]).T; va
vb = np.array([[1,0]]).T; vb
H = np.array([[1,1],[1,-1]])/2**0.5;H
vaH = H.dot(va); vaH
vaHvb = np.kron(vaH,vb); vaHvb
C = np.array([[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]); C
vout = C.dot(vaHvb); vout
import qiskit as qk
qc = qk.QuantumCircuit(3,3)
for i in range(3):
qc.h(i)
qc.measure(i,i)
show_histogram(qc);
from qiskit import QuantumCircuit
qc = QuantumCircuit(4,4)
qc.x([0,1])
qc.cx([0,1],[2,2])
qc.ccx(0,1,3)
qc.measure([0,1,2,3],[0,1,2,3])
show_histogram(qc);
import qiskit as qk
qc = qk.QuantumCircuit(1)
qc.x(0)
qc.measure_all()
show_histogram(qc);
# To avoid modifying the original circuit, let's first copy it
qc2 = qc.copy()
qc2.remove_final_measurements()
qc2.draw('mpl', style='clifford', scale=1)
import qiskit as qk
sv = qk.quantum_info.Statevector(qc2); sv
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(sv)
from qiskit.quantum_info import Operator
Operator(qc2).data
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Fast benchmark via mirror circuits
"""
import argparse
import numpy as np
import rustworkx as rx
from qiskit_ibm_provider import IBMProvider
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit.transpiler import Target, CouplingMap
from qiskit_experiments.framework import (ParallelExperiment, BatchExperiment)
import qiskit_device_benchmarking.utilities.file_utils as fu
import qiskit_device_benchmarking.utilities.graph_utils as gu
from qiskit_device_benchmarking.bench_code.mrb import MirrorQuantumVolume
def run_bench(hgp, backends, depths=[8], trials=10,
nshots=100, he=True, dd=True, opt_level=3, act_name=''):
"""Run a benchmarking test (mirror QV) on a set of devices
Args:
hgp: hub/group/project
backends: list of backends
depths: list of mirror depths (square circuits)
trials: number of randomizations
nshots: number of shots
he: hardware efficient True/False (False is original QV circ all to all,
True assumes a line)
dd: add dynamic decoupling
opt_level: optimization level of the transpiler
act_name: account name to be passed to the runtime service
Returns:
flat list of lists of qubit chains
"""
#load the service
service = QiskitRuntimeService(name=act_name)
job_list = []
result_dict = {}
result_dict['config'] = {'hgp': hgp, 'depths': depths,
'trials': trials,
'nshots': nshots,
'dd': dd,
'he': he,
'pregenerated': False,
'opt_level': opt_level,
'act_name': act_name}
print('Running Fast Bench with options %s'%result_dict['config'])
#run all the circuits
for backend in backends:
print('Loading backend %s'%backend)
result_dict[backend] = {}
backend_real=service.backend(backend,instance=hgp)
mqv_exp_list_d = []
for depth in depths:
print('Generating Depth %d Circuits for Backend %s'%(depth, backend))
result_dict[backend][depth] = {}
#compute the sets for this
#NOTE: I want to replace this with fixed sets from
#a config file!!!
nq = backend_real.configuration().n_qubits
coupling_map = backend_real.configuration().coupling_map
G = gu.build_sys_graph(nq, coupling_map)
paths = rx.all_pairs_all_simple_paths(G,depth,depth)
paths = gu.paths_flatten(paths)
new_sets = gu.get_separated_sets(G,paths,min_sep=2,nsets=1)
mqv_exp_list = []
result_dict[backend][depth]['sets'] = new_sets[0]
#Construct mirror QV circuits on each parallel set
for qset in new_sets[0]:
#generate the circuits
mqv_exp = MirrorQuantumVolume(qubits=qset,backend=backend_real,trials=trials,
pauli_randomize=True, he = he)
mqv_exp.analysis.set_options(plot=False,
calc_hop=False,
analyzed_quantity='Success Probability')
#Do this so it won't compile outside the qubit sets
cust_map = []
for i in coupling_map:
if i[0] in qset and i[1] in qset:
cust_map.append(i)
cust_target = Target.from_configuration(basis_gates = backend_real.configuration().basis_gates,
num_qubits=nq,
coupling_map=CouplingMap(cust_map))
mqv_exp.set_transpile_options(target=cust_target, optimization_level=opt_level)
mqv_exp_list.append(mqv_exp)
new_exp_mqv = ParallelExperiment(mqv_exp_list, backend=backend_real, flatten_results=False)
if dd:
#this forces the circuits to have DD on them
print('Transpiling and DD')
for i in mqv_exp_list:
i.dd_circuits()
mqv_exp_list_d.append(new_exp_mqv)
new_exp_mqv = BatchExperiment(mqv_exp_list_d, backend=backend_real, flatten_results=False)
new_exp_mqv.set_run_options(shots=nshots)
job_list.append(new_exp_mqv.run())
result_dict[backend]['job_ids'] = job_list[-1].job_ids
#get the jobs back
for i, backend in enumerate(backends):
print('Loading results for backend: %s'%backend)
expdata = job_list[i]
try:
expdata.block_for_results()
except:
#remove backend from results
print('Error loading backend %s results'%backend)
result_dict.pop(backend)
continue
for j, depth in enumerate(depths):
result_dict[backend][depth]['data'] = []
result_dict[backend][depth]['mean'] = []
result_dict[backend][depth]['std'] = []
for k in range(len(result_dict[backend][depth]['sets'])):
result_dict[backend][depth]['data'].append([float(probi) for probi in list(expdata.child_data()[j].child_data()[k].artifacts()[0].data)])
result_dict[backend][depth]['mean'].append(float(np.mean(result_dict[backend][depth]['data'][-1])))
result_dict[backend][depth]['std'].append(float(np.std(result_dict[backend][depth]['data'][-1])))
fu.export_yaml('MQV_' + fu.timestamp_name() + '.yaml', result_dict)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = 'Run fast benchmark of '
+ 'devices using mirror. Specify a config '
+' yaml and override settings on the command line')
parser.add_argument('-c', '--config', help='config file name',
default='config.yaml')
parser.add_argument('-b', '--backend', help='Specify backend and override '
+ 'backend_group')
parser.add_argument('-bg', '--backend_group',
help='specify backend group in config file',
default='backends')
parser.add_argument('--hgp', help='specify hgp')
parser.add_argument('--he', help='Hardware efficient', action='store_true')
parser.add_argument('--name', help='Account name', default='')
args = parser.parse_args()
#import from config
config_dict = fu.import_yaml(args.config)
print('Config File Found')
print(config_dict)
#override from the command line
if args.backend is not None:
backends = [args.backend]
else:
backends = config_dict[args.backend_group]
if args.hgp is not None:
hgp = args.hgp
else:
hgp = config_dict['hgp']
if args.he is True:
he = True
else:
he = config_dict['he']
opt_level = config_dict['opt_level']
dd = config_dict['dd']
depths = config_dict['depths']
trials = config_dict['trials']
nshots = config_dict['shots']
#print(hgp, backends, he, opt_level, dd, depths, trials, nshots)
run_bench(hgp, backends, depths=depths, trials=trials,
nshots=nshots, he=he, dd=dd, opt_level=opt_level, act_name=args.name)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
from qiskit import Aer, execute, QuantumRegister, ClassicalRegister,\
QuantumCircuit
from qiskit.visualization import plot_bloch_multivector
from matplotlib.pyplot import plot, draw, show
# list all the available simulation environments
for backend in Aer.backends():
print(backend.name())
if(backend.name() == 'statevector_simulator'):
# load a arbitrary quantum circuit of your choice (here Bell state preparation)
for not0 in [False,True]:
for not1 in [False,True]:
print(not0, '\t', not1)
qr = QuantumRegister(2,name='q')
cr = ClassicalRegister(2, name='c')
qc = QuantumCircuit(qr, cr)
if(not0):
qc.x(qr[0])
if(not1):
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.measure(qr,cr)
result = execute(qc, backend).result()
stateVectorResult = result.get_statevector(qc)
plot_bloch_multivector(stateVectorResult)
qc.draw(output='mpl')
draw()
show(block=True)
if(backend.name() == 'pulse_simulator'):
print("I do not know how to deal with this yet :)")
else:
# load a arbitrary quantum circuit of your choice (here Bell state preparation)
for not0 in [False,True]:
for not1 in [False,True]:
print(not0, '\t', not1)
qr = QuantumRegister(2,name='q')
cr = ClassicalRegister(2, name='c')
qc = QuantumCircuit(qr, cr)
if(not0):
qc.x(qr[0])
if(not1):
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
if(backend.name() != 'aer_simulator_unitary'
and backend.name() != 'aer_simulator_superop'
and backend.name() != 'unitary_simulator'):
qc.measure(qr,cr)
job = execute(qc, backend, shots=1000)
result = job.result()
if(backend.name() != 'aer_simulator_unitary'
and backend.name() != 'aer_simulator_superop'
and backend.name() != 'unitary_simulator'):
count = result.get_counts()
print(count)
|
https://github.com/danieljaffe/quantum-algorithms-qiskit
|
danieljaffe
|
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
#set b equal to '11'
b = '11'
#1) initialize qubits
n = 2
simon_circuit_2 = QuantumCircuit(n*2, n)
#2) Apply Hadamard gates before querying the oracle
simon_circuit_2.h(range(n))
#3) Query oracle
simon_circuit_2 += simon_oracle(b)
#5) Apply Hadamard gates to the input register
simon_circuit_2.h(range(n))
#3) and 6) Measure qubits
simon_circuit_2.measure(range(n), range(n))
# Load saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Execute and monitor the job
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
# Get results and plot counts
device_counts = job.result().get_counts()
plot_histogram(device_counts)
#additionally, function for calculating dot product of results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
print('b = ' + b)
for z in device_counts:
print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots))
#the most significant results are those for which b dot z=0(mod 2).
'''b = 11
11.00 = 0 (mod 2) (45.0%)
11.01 = 1 (mod 2) (6.2%)
11.10 = 1 (mod 2) (6.4%)
11.11 = 0 (mod 2) (42.4%)'''
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.circuit import Gate
from qiskit.visualization import plot_histogram, plot_bloch_multivector
# Define no. of input qubits
n = 4
circ = QuantumCircuit(n+1, n)
circ.reset(range(n+1))
circ.x(0)
circ.barrier()
circ.h(range(n+1))
circ.barrier()
circ.append(Gate(name="$U_f$", num_qubits=n+1, params=[]), range(n+1))
circ.barrier()
circ.h(range(1, n+1))
circ.barrier()
circ.measure(range(1, n+1), range(n))
circ.draw('mpl', reverse_bits=True)
# Constant Function
constant = QuantumCircuit(n+1, name='Constant')
constant.x(0)
constant.draw('mpl', reverse_bits=True)
# Balanced Function
balanced = QuantumCircuit(n+1, name='Balanced')
for i in range(1, n+1):
balanced.cx(i, 0)
balanced.draw('mpl', reverse_bits=True)
circ = QuantumCircuit(n+1)
circ.x(0)
circ.barrier()
circ.h(range(n+1))
circ.append(constant.to_instruction(), range(n+1))
circ.h(range(1, n+1))
circ.draw(reverse_bits=True, plot_barriers=False)
simulator = Aer.get_backend('statevector_simulator')
result = execute(circ, simulator).result()
state = result.get_statevector(circ)
plot_bloch_multivector(state)
circ = QuantumCircuit(n+1)
circ.x(0)
circ.barrier()
circ.h(range(n+1))
circ.append(balanced.to_instruction(), range(n+1))
circ.h(range(1, n+1))
circ.draw(reverse_bits=True, plot_barriers=False)
simulator = Aer.get_backend('statevector_simulator')
result = execute(circ, simulator).result()
state = result.get_statevector(circ)
plot_bloch_multivector(state)
circ = QuantumCircuit(n+1, n)
circ.x(0)
circ.barrier()
circ.h(range(n+1))
circ.append(constant.to_instruction(), range(n+1))
circ.h(range(1, n+1))
circ.measure(range(1, n+1), range(n))
circ.draw(reverse_bits=True, plot_barriers=False)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator, shots=1000).result()
counts = result.get_counts(circ)
plot_histogram(counts)
|
https://github.com/JavaFXpert/qiskit-plotting-app
|
JavaFXpert
|
# Do the necessary import for our program
%matplotlib inline
from qiskit import *
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.tools.visualization import plot_histogram
import ipywidgets as widgets
import matplotlib.pyplot as plt
from IPython.display import clear_output
SHOW_CIRCUIT = True
def create_expanded_button(description, button_style):
return widgets.Button(description=description, button_style=button_style,
layout=widgets.Layout(height='auto', width='5%'))
header_button = create_expanded_button('Header', 'success')
left_button = create_expanded_button('Left', 'info')
center_button = create_expanded_button('Center', 'warning')
right_button = create_expanded_button('Right', 'info')
footer_button = create_expanded_button('Footer', 'success')
app_ui = widgets.AppLayout(header=None,
left_sidebar=None,
center=center_button,
right_sidebar=None,
footer=None)
display(app_ui)
log_expr_widget = widgets.Text(
value='',
description='Logical expression:',
disabled=True
)
out1 = widgets.Output()
out2 = widgets.Output()
rel_matrix = None
names = ["A", "B", "C", "D"]
num_names = len(names)
REL_NONE = ""
REL_GOOD = "good"
REL_BAD = "bad"
# Compute logical expression from dropdowns
def compute_log_expr():
log_expr_str = ""
good_rel_exist = False
bad_rel_exist = False
for col_num in range(num_names + 1):
for row_num in range(num_names + 1):
if col_num > row_num and row_num > 0:
if rel_matrix[col_num][row_num].value == 1: #1 is good
good_rel_exist = True
break
if good_rel_exist:
log_expr_str = "("
for col_idx in range(num_names + 1):
for row_idx in range(num_names + 1):
if col_idx > row_idx and row_idx > 0:
if rel_matrix[col_idx][row_idx].value == 1: #1 is good
log_expr_str += "("
log_expr_str += rel_matrix[0][row_idx].value
log_expr_str += " & "
log_expr_str += rel_matrix[col_idx][0].value
log_expr_str += ")|"
if log_expr_str[-1] == '|':
log_expr_str = log_expr_str[:-1]
log_expr_str += ")"
for col_num in range(num_names + 1):
for row_num in range(num_names + 1):
if col_num > row_num and row_num > 0:
if rel_matrix[col_num][row_num].value == 2: #2 is bad
bad_rel_exist = True
break
if bad_rel_exist:
if good_rel_exist:
log_expr_str += "&"
bad_log_expr_str = "("
for col_idx in range(num_names + 1):
for row_idx in range(num_names + 1):
if col_idx > row_idx and row_idx > 0:
if rel_matrix[col_idx][row_idx].value == 2: #2 is bad
bad_log_expr_str += "~("
bad_log_expr_str += rel_matrix[0][row_idx].value
bad_log_expr_str += " & "
bad_log_expr_str += rel_matrix[col_idx][0].value
bad_log_expr_str += ")&"
if bad_log_expr_str[-1] == '&':
bad_log_expr_str = bad_log_expr_str[:-1]
bad_log_expr_str += ")"
log_expr_str += bad_log_expr_str
log_expr_widget.value = log_expr_str
#def handle_log_expr_text_entered(text_widget):
def handle_log_expr_text_entered(some_widget):
with out1:
clear_output()
compute_log_expr()
algorithm = Grover(LogicalExpressionOracle(log_expr_widget.value))
# Run the algorithm on a QASM simulator, printing the most frequently occurring result
qasm_simulator_backend = BasicAer.get_backend('qasm_simulator')
qasm_simulator_result = algorithm.run(qasm_simulator_backend)
if SHOW_CIRCUIT:
circuit = qasm_simulator_result['circuit']
with out1:
display(plot_histogram(qasm_simulator_result['measurement']))
if SHOW_CIRCUIT:
with out2:
clear_output()
display(circuit.draw(output='mpl'))
log_expr_button = widgets.Button(
description = "Run",
)
# Relationship model for the grid
def compute_rel_matrix_entry(col_num, row_num):
entry = None
if col_num == 0:
if row_num > 0:
entry = widgets.Label(value=names[row_num - 1])
else:
entry = widgets.Label(value='')
elif row_num == 0:
entry = widgets.Label(value=names[col_num - 1])
elif col_num < row_num:
entry = widgets.Dropdown(
options=[('', 0), (REL_GOOD, 1), (REL_BAD, 2)],
value=0,
layout=widgets.Layout(width='auto', height='auto')
)
else:
entry = widgets.Label(value='')
return entry
rel_matrix = [[compute_rel_matrix_entry(i, j) for i in range(num_names + 1)] for j in range(num_names + 1)]
for col_num in range(num_names + 1):
for row_num in range(num_names + 1):
if col_num > row_num and row_num > 0:
rel_matrix[col_num][row_num].observe(handle_log_expr_text_entered, names='value')
# Make Grid with name headings and dropdown relationships
rel_gridbox = widgets.GridBox(children=[rel_matrix[col_idx][row_idx] for row_idx in [0, 1, 2, 3] for col_idx in [0, 2, 3, 4]],
layout=widgets.Layout(
width='100%',
grid_template_columns='70px ' * len(names),
grid_template_rows='30px ' * len(names),
grid_gap='10px 10px')
)
tab = widgets.Tab(children = [out1, out2], layout=widgets.Layout(height='auto', width='auto'))
tab.set_title(0, 'Probabilities')
if SHOW_CIRCUIT:
tab.set_title(1, 'Circuit')
app_header = widgets.Label(value = "Grover Search Party")
center_pane = widgets.VBox([app_header, rel_gridbox, widgets.VBox([log_expr_widget, tab])])
app_ui.center = center_pane
|
https://github.com/DanKim44/CodingWithQiskitS2
|
DanKim44
|
#Coding With Qiskit S2E7 Shor's Algorithm
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.tools.visualization import plot_histogram
from qiskit.visualization import *
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
import numpy as np
import pandas as pd
from fractions import Fraction
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor=Shor(N=15,a=2,quantum_instance=quantum_instance)
Shor.run(my_shor)
def c_amod15(a,power): #modular exponentiation function, hard coded for factorizing 15, guess number 7
U = QuantumCircuit(4)
for iteration in range(power):
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
for q in range(4):
U.x(q)
U=U.to_gate() #turns the circuit into a gate to use later
U.name="%i^%i mod 15" %(a,power)
c_U = U.control()
return c_U
n_count = 8
a = 7
def qft_dagger(n):
qc = QuantumCircuit(n)
for qubit in range(n//2):
qc.swap(qubit,n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-np.pi/float(2**(j-m)),m,j) #replaced cu1 with cp gate due to deprec warning
qc.h(j)
qc.name="QFT dagger"
return qc
qc = QuantumCircuit(n_count + 4, n_count) #4 ancilla
for q in range(n_count): #intialize counting qubits into superposition state
qc.h(q)
qc.x(3+n_count) #initialize first ancilla in the excited state
for q in range(n_count):
qc.append(c_amod15(a,2**q), [q]+[i+n_count for i in range(4) ])
qc.append(qft_dagger(n_count), range(n_count))
qc.measure(range(n_count), range(n_count))
qc.draw()
results = execute(qc, backend, shots=2048).result()
counts = results.get_counts()
plot_histogram(counts)
#phases of 0/256, 64/256, 128/256, 192/256
#gives guesses for r of 1,2,4
#plug into p=a^(r/2)-1, q=a^(r/2)+1
#for r = 4: p=48, q=50
#p has a common factor with N=15 of 3
#q has a common factor with of 5
#the rest is taken from the qiskit textbook https://qiskit.org/textbook/ch-algorithms/shor.html
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2) # Convert (base 2) string to decimal
phase = decimal/(2**n_count) # Find corresponding eigenvalue
measured_phases.append(phase)
# Add these values to the rows in our table:
rows.append(["%s(bin) = %i(dec)" % (output, decimal),
"%i/%i = %.2f" % (decimal, 2**n_count, phase)])
# Print the rows in a table
headers=["Register Output", "Phase"]
df = pd.DataFrame(rows, columns=headers)
print(df)
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(15)
rows.append([phase, "%i/%i" % (frac.numerator, frac.denominator), frac.denominator])
# Print as a table
headers=["Phase", "Fraction", "Guess for r"]
df = pd.DataFrame(rows, columns=headers)
print(df)
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test Probabilistic Quantum Memory"""
from unittest import TestCase
import numpy as np
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qclib.memory.pqm import initialize as pqm
from qclib.state_preparation import LowRankInitialize
from qclib.util import get_counts
class TestPQM(TestCase):
""" Testing qclib.memory.pqm"""
@staticmethod
def _run_pqm(is_classical_pattern):
""" run PQM with classical or quantum input"""
# pqm memory data
data = [0, 1, 0, 0]
data = data / np.linalg.norm(data)
# initialize quantum registers
memory = QuantumRegister(2, 'm')
aux = QuantumRegister(1, 'c')
output = ClassicalRegister(1)
circ = QuantumCircuit(memory, aux, output)
# initialize data
init_gate = LowRankInitialize(data)
circ.append(init_gate, memory)
# initialize input pattern
bin_input = [1, 0]
if is_classical_pattern:
# run pqm recovery algorithm
pqm(circ, bin_input, memory, aux, is_classical_pattern=True)
else:
q_bin_input = QuantumRegister(2)
circ.add_register(q_bin_input)
# Pattern basis encoding
for k, bit in enumerate(bin_input):
if bit == 1:
circ.x(q_bin_input[k])
# run pqm recovery algorithm
pqm(circ, q_bin_input, memory, aux, is_classical_pattern=False)
# measure output and verify results
circ.measure(aux, output) # pylint: disable=maybe-no-member
counts = get_counts(circ)
return counts
def test_classical_input(self):
""" Testing PQM with classical input """
# classical input pattern
counts = TestPQM._run_pqm(True)
self.assertTrue(counts['0'] / 1024 == 1)
def test_quantum_input(self):
""" Testing PQM with quantum input """
# quantum input pattern
counts = TestPQM._run_pqm(False)
self.assertTrue(counts['0'] / 1024 == 1)
|
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
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
G
labels = nx.get_edge_attributes(G,'weight')
labels
import json
# Array of JSON Objects
products = [{"name": "HDD", "brand": "Samsung", "price": "$100"},
{"name": "Monitor", "brand": "Dell", "price": "$120"},
{"name": "Mouse", "brand": "Logitech", "price": "$10"}]
# Print the original data
print("The original JSON data:\n{0}".format(products))
# Sort the JSON data based on the value of the brand key
products.sort(key=lambda x: x["price"])
# Print the sorted JSON data
print("The sorted JSON data based on the value of the brand:\n{0}".format(products))
_LAMBDA
UNIFORM_CONVERGENCE_SAMPLE
import json
# 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"])
# Print the sorted JSON data
UNIFORM_CONVERGENCE_SAMPLE
np.max(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - UNIFORM_CONVERGENCE_SAMPLE[220]["probabilities"])
# generamos las distancias entre para la convergencia uniforme
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
UNIFORM_CONVERGENCE_SAMPLE
import csv
header = ['iteration', 'state', 'probability', 'mean']
header_q = ['iteration', 'distance']
with open('qaoa_cu.csv', 'w', encoding='UTF8') as f:
with open('qaoa_distance.csv', 'w', encoding='UTF8') as q:
writer = csv.writer(f)
writer_q = csv.writer(q)
# write the header
writer.writerow(header)
writer_q.writerow(header_q)
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])
#plot_histogram(job_2, color='midnightblue', title=str(mean), figsize=(30, 5)).savefig(str(contador) + "_2.png")
#print(sample["mean"])
plot_histogram(job_2, color='midnightblue', title="New Histogram", figsize=(30, 5)).savefig('out.png')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
pip install qiskit
# Useful packages for the next gates experiments
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit import execute
from qiskit.tools.visualization import circuit_drawer
from qiskit import Aer
backend = Aer.get_backend('unitary_simulator')
# Pauli X : bit-flip gate
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.x(q)
im = circuit_drawer(qc)
im.save("GateX.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# Pauli Y : bit and phase-flip gate
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.y(q)
im = circuit_drawer(qc)
im.save("GateY.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# Pauli Z : phase-flip gate
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.z(q)
im = circuit_drawer(qc)
im.save("GateZ.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# Clifford Hadamard gate
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
im = circuit_drawer(qc)
im.save("GateH.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# Clifford S gate
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.s(q)
im = circuit_drawer(qc)
im.save("GateS.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# Clifford T gate
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.t(q)
im = circuit_drawer(qc)
im.save("GateT.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# Pauli Controlled-X (or, controlled-NOT) gate
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q)
im = circuit_drawer(qc)
im.save("GateCX.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# Pauli Controlled Z (or, controlled Phase) gate
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cz(q)
im = circuit_drawer(qc)
im.save("GateCZ.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# SWAP gate
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.swap(q)
im = circuit_drawer(qc)
im.save("GateSWAP.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
# Toffoli gate (ccx gate)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q)
im = circuit_drawer(qc)
im.save("GateCCX.png", "PNG")
job = execute(qc, backend)
print(np.round(job.result().get_data(qc)['unitary'], 3))
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram, circuit_drawer
# Create a Quantum Register called "qr" with 2 qubits.
qr = QuantumRegister(2)
# Create a Classical Register called "cr" with 2 bits.
cr = ClassicalRegister(2)
# Create a Quantum Circuit called "qc" with qr and cr.
qc = QuantumCircuit(qr, cr)
# Add the H gate in the Qubit 1, putting this qubit in superposition.
qc.h(qr[1])
# Add the CX gate on control qubit 1 and target qubit 0, putting the qubits in a Bell state i.e entanglement.
qc.cx(qr[1], qr[0])
# Add a Measure gate to see the state.
qc.measure(qr, cr)
# Compile and execute the quantum program in the local simulator.
job_sim = execute(qc, "qasm_simulator")
stats_sim = job_sim.result().get_counts()
# Plot and print results.
plot_histogram(stats_sim)
print(stats_sim)
im = circuit_drawer(qc)
im.save("circuit.png", "PNG")
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
import matplotlib.pyplot as plt
# 3 bitStrings, one for each symbol : )(
#":" 00111010 "(" 00101000 ")" 00101001
# Create a Quantum Register called "qr" with 16 qubits.
qr = QuantumRegister(16)
# Create a Classical Register called "cr" with 16 bits.
cr = ClassicalRegister(16)
# Create a Quantum Circuit called "qc" with qr and cr.
qc = QuantumCircuit(qr, cr)
# Add the H gate in the 0 Qubit, putting the qubit in superposition.
qc.h(qr[0])
qc.x(qr[3])
qc.x(qr[5])
qc.x(qr[9])
qc.x(qr[11])
qc.x(qr[12])
qc.x(qr[13])
for j in range(16):
qc.measure(qr[j], cr[j])
# Compile and execute the quantum program in the local simulator.
shots_sim = 128
job_sim = execute(qc, "qasm_simulator", shots=shots_sim)
stats_sim = job_sim.result().get_counts()
# Plot and print results.
plot_histogram(stats_sim)
print(stats_sim)
def plotSmiley (stats, shots):
for bitString in stats:
char = chr(int(bitString[0:8],2)) # 8 bits (left), convert to an ASCII character.
char += chr(int(bitString[8:16],2)) # 8 bits (right), add it to the previous character.
prob = stats[bitString]/shots # Fraction of shots the result occurred
plt.annotate(char, (0.5,0.5), va="center", ha="center", color = (0,0,0,prob), size = 300) # Create plot.
plt.axis("off")
plt.show()
plotSmiley(stats_sim, shots_sim)
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
# E.g. number 21 in binary.
number = "10101"
# Initializing the registers.
# Create a Quantum Register called "qr" with length number qubits.
qr = QuantumRegister(len(str(number)))
# Create a Classical Register called "cr" with length number bits.
cr = ClassicalRegister(len(str(number)))
# Create a Quantum Circuit called "qc" with qr and cr.
qc = QuantumCircuit(qr, cr)
# Setting up the registers using the value inputted.
for i in range(len(str(number))):
if number[i] == "1":
qc.x(qr[len(str(number)) - (i+1)]) #Flip the qubit from 0 to 1.
#Measure qubits and store results in classical register cr.
for i in range(len(str(number))):
qc.measure(qr[i], cr[i])
# Compile and execute the quantum program in the local simulator.
job_sim = execute(qc, "qasm_simulator")
stats_sim = job_sim.result().get_counts()
# Print number.
print(stats_sim)
# Boolean binary string adder.
def rjust_lenght(s1, s2, fill='0'):
l1, l2 = len(s1), len(s2)
if l1 > l2:
s2 = s2.rjust(l1, fill)
elif l2 > l1:
s1 = s1.rjust(l2, fill)
return (s1, s2)
def get_input():
bits_a = input('input your first binary string ')
bits_b = input('input your second binary string ')
return rjust_lenght(bits_a, bits_b)
def xor(bit_a, bit_b):
A1 = bit_a and (not bit_b)
A2 = (not bit_a) and bit_b
return int(A1 or A2)
def half_adder(bit_a, bit_b):
return (xor(bit_a, bit_b), bit_a and bit_b)
def full_adder(bit_a, bit_b, carry=0):
sum1, carry1 = half_adder(bit_a, bit_b)
sum2, carry2 = half_adder(sum1, carry)
return (sum2, carry1 or carry2)
def binary_string_adder(bits_a, bits_b):
carry = 0
result = ''
for i in range(len(bits_a)-1 , -1, -1):
summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry)
result += str(summ)
result += str(carry)
return result[::-1]
def main():
bits_a, bits_b = get_input()
print('1st string of bits is : {}, ({})'.format(bits_a, int(bits_a, 2)))
print('2nd string of bits is : {}, ({})'.format(bits_b, int(bits_b, 2)))
result = binary_string_adder(bits_a, bits_b)
print('summarized is : {}, ({})'.format(result, int(result, 2)))
if __name__ == '__main__':
main()
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import circuit_drawer
# Initializing the registers.
# Create a Quantum Registers.
cin = QuantumRegister(1)
a = QuantumRegister(4)
b = QuantumRegister(4)
cout = QuantumRegister(1)
# Create a Classical Registers.
ans = ClassicalRegister(5)
# Create a Quantum Circuit called "qc".
qc = QuantumCircuit(cin, a, b, cout, ans)
# Set input states.
x = "0001" #1
y = "1111" #15
# Setting up the registers using the value inputted.
for i in range(len(str(x))):
if x[i] == "1":
qc.x(a[len(str(x)) - (i+1)]) #Flip the qubit from 0 to 1.
for i in range(len(str(y))):
if y[i] == "1":
qc.x(b[len(str(y)) - (i+1)]) #Flip the qubit from 0 to 1.
def majority(circ, a, b, c):
circ.cx(c,b)
circ.cx(c,a)
circ.ccx(a,b,c)
def unmaj(circ, a, b, c):
circ.ccx(a,b,c)
circ.cx(c,a)
circ.cx(a,b)
# Add a to b, storing result in b
majority(qc,cin[0],b[0],a[0])
majority(qc,a[0],b[1],a[1])
majority(qc,a[1],b[2],a[2])
majority(qc,a[2],b[3],a[3])
qc.cx(a[3],cout[0])
unmaj(qc,a[2],b[3],a[3])
unmaj(qc,a[1],b[2],a[2])
unmaj(qc,a[0],b[1],a[1])
unmaj(qc,cin[0],b[0],a[0])
# Measure qubits and store results.
for i in range(0, 4):
qc.measure(b[i], ans[i])
qc.measure(cout[0], ans[4])
# Compile and execute the quantum program in the local simulator.
num_shots = 2 # Number of times to repeat measurement.
job = execute(qc, "qasm_simulator", shots=num_shots)
job_stats = job.result().get_counts()
# Print result number and circuit.
print(job_stats)
im = circuit_drawer(qc)
im.save("circuitSum.png", "PNG")
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import circuit_drawer
import numpy as np
n1 = '10011'
# E.g. number 19
n2 = '0011101'
# E.g. number 29
if len(str(n1)) > len(str(n2)):
n = len(str(n1))
else:
n = len(str(n2))
# Initializing the registers.
# Create a Quantum Registers called "qr1" and "qr2".
qr1 = QuantumRegister(n+1)
qr2 = QuantumRegister(n+1)
# The classical register.
cr = ClassicalRegister(n+1)
# Create a Quantum Circuit called "qc".
qc = QuantumCircuit(qr1, qr2, cr)
length1 = len(n1)
length2 = len(n2)
# Set same length.
if length2 > length1:
n1,n2 = n2, n1
length2, length1 = length1, length2
n2 = ("0")*(length1-length2) + n2
# Set registers qr1 and qr2 to hold the two numbers.
for i in range(len(str(n1))):
if n1[i] == "1":
qc.x(qr1[len(str(n1)) - (i+1)])
for i in range(len(str(n2))):
if n2[i] == "1":
qc.x(qr2[len(str(n2)) - (i+1)])
def qft(circ, q1, q2, n):
# n-qubit QFT on q in circ.
for i in range(0, n+1):
qc.cu1(np.math.pi/float(2**(i)), q2[n-i], q1[n])
def invqft(circ, q, n):
# Performs the inverse quantum Fourier transform.
for i in range(0, n):
qc.cu1(-np.math.pi/float(2**(n-i)), q[i], q[n])
qc.h(q[n])
def input_state(circ, q, n):
# n-qubit input state for QFT.
qc.h(q[n])
for i in range(0, n):
qc.cu1(np.math.pi/float(2**(i+1)), q[n-(i+1)], q[n])
for i in range(0, n+1):
input_state(qc, qr1, n-i)
qc.barrier()
for i in range(0, n+1):
qft(qc, qr1, qr2, n-i)
qc.barrier()
for i in range(0, n+1):
invqft(qc, qr1, i)
qc.barrier()
for i in range(0, n+1):
qc.cx(qr1[i],qr2[i])
for i in range(0, n+1):
qc.measure(qr1[i], cr[i])
# Compile and execute the quantum program in the local simulator.
num_shots = 2 # Number of times to repeat measurement.
job = execute(qc, "qasm_simulator", shots=num_shots)
job_stats = job.result().get_counts()
print(job_stats)
im = circuit_drawer(qc)
im.save("circuitAdderQFT.png", "PNG")
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import circuit_drawer
# Initializing the registers.
# Create a Quantum Registers.
cin = QuantumRegister(1)
a = QuantumRegister(2)
b = QuantumRegister(2)
cout = QuantumRegister(1)
# Create a Classical Registers.
ans = ClassicalRegister(3)
# Create a Quantum Circuit called "qc".
qc = QuantumCircuit(cin, a, b, cout, ans)
# Set input states.
x = "00" #0
y = "11" #3
# Setting up the registers using the value inputted.
for i in range(len(str(x))):
if x[i] == "1":
qc.x(a[len(str(x)) - (i+1)]) #Flip the qubit from 0 to 1.
for i in range(len(str(y))):
if y[i] == "1":
qc.x(b[len(str(y)) - (i+1)]) #Flip the qubit from 0 to 1.
# Add a to b, storing result in b
majority(qc,cin[0],b[0],a[0])
majority(qc,a[0],b[1],a[1])
qc.cx(a[1],cout[0])
unmaj(qc,a[0],b[1],a[1])
unmaj(qc,cin[0],b[0],a[0])
qc.cx(b[1],b[0])
qc.x(b[1])
# Measure qubits and store results.
for i in range(0, 1):
qc.measure(b[i], ans[i])
qc.measure(cout[0], ans[1])
# Compile and execute the quantum program in the local simulator.
num_shots = 2 # Number of times to repeat measurement.
job = execute(qc, "qasm_simulator", shots=num_shots)
job_stats = job.result().get_counts()
# Print result number and circuit.
print(job_stats)
im = circuit_drawer(qc)
im.save("circuitAverage.png", "PNG")
import matplotlib.pyplot as plt
import numpy as np
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram, circuit_drawer
n = 3
sat_formula = [[1,2,-3],[-1,-2,-3],[1,-2,3]]
f_in = QuantumRegister(n)
f_out = QuantumRegister(1)
aux = QuantumRegister(len(sat_formula)+1)
ans = ClassicalRegister(n)
qc = QuantumCircuit(f_in, f_out, aux, ans)
# Initializes all of the qbits.
def input_state(circuit, f_in, f_out, n):
for j in range(n):
circuit.h(f_in[j])
circuit.x(f_out)
circuit.h(f_out)
# The back box U function (Oracle).
def black_box_u_f(circuit, f_in, f_out, aux, n, sat_formula):
num_claus = len(sat_formula)
for(k,claus) in enumerate(sat_formula):
for literal in claus:
if literal > 0:
circuit.cx(f_in[literal-1],aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1],aux[k])
circuit.ccx(f_in[0],f_in[1],aux[num_claus])
circuit.ccx(f_in[2],aux[num_claus],aux[k])
circuit.ccx(f_in[0],f_in[1],aux[num_claus])
for literal in claus:
if literal < 0:
circuit.x(f_in[-literal-1])
if(num_claus == 1):
circuit.cx(aux[0], f_out[0])
elif(num_claus == 2):
circuit.ccx(aux[0],aux[1],f_out[0])
elif(num_claus == 3):
circuit.ccx(aux[0], aux[1], aux[num_claus])
circuit.ccx(aux[2], aux[num_claus], f_out[0])
circuit.ccx(aux[0], aux[1], aux[num_claus])
else:
raise ValueError('Apenas 3 clausulas pf :)')
for(k,claus) in enumerate(sat_formula):
for literal in claus:
if literal > 0:
circuit.cx(f_in[literal-1],aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1],aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_claus])
circuit.ccx(f_in[2], aux[num_claus], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_claus])
for literal in claus:
if literal < 0:
circuit.x(f_in[-literal-1])
# iInverts the qbit that was affected by the Oracle function.
def inversion_about_average(circuit,f_in,n):
for j in range(n):
circuit.h(f_in[j])
for j in range(n):
circuit.x(f_in[j])
n_controlled_z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1])
for j in range(n):
circuit.x(f_in[j])
for j in range(n):
circuit.h(f_in[j])
def n_controlled_z(circuit,controls,target):
if(len(controls) > 2):
raise ValueError('erro de control')
elif(len(controls) == 1):
circuit.h(target)
circuit.cx(controls[0],target)
circuit.h(target)
elif(len(controls) == 2):
circuit.h(target)
circuit.ccx(controls[0],controls[1],target)
circuit.h(target)
input_state(qc,f_in,f_out,n)
black_box_u_f(qc,f_in,f_out,aux,n,sat_formula)
inversion_about_average(qc,f_in,n)
black_box_u_f(qc,f_in,f_out,aux,n,sat_formula)
inversion_about_average(qc,f_in,n)
for j in range(n):
qc.measure(f_out[0],ans[j])
# Compile and execute the quantum program in the local simulator.
job_sim = execute(qc, "qasm_simulator")
stats_sim = job_sim.result().get_counts()
# Plot and print results.
print(stats_sim)
plot_histogram(stats_sim)
im = circuit_drawer(qc)
im.save("circuitGrover.pdf", "PDF")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# Build a quantum circuit
circuit = QuantumCircuit(3, 3)
circuit.x(1)
circuit.h(range(3))
circuit.cx(0, 1)
circuit.measure(range(3), range(3));
print(circuit)
circuit.draw()
# Matplotlib Drawing
circuit.draw(output='mpl')
# Draw a new circuit with barriers and more registers
q_a = QuantumRegister(3, name='qa')
q_b = QuantumRegister(5, name='qb')
c_a = ClassicalRegister(3)
c_b = ClassicalRegister(5)
circuit = QuantumCircuit(q_a, q_b, c_a, c_b)
circuit.x(q_a[1])
circuit.x(q_b[1])
circuit.x(q_b[2])
circuit.x(q_b[4])
circuit.barrier()
circuit.h(q_a)
circuit.barrier(q_a)
circuit.h(q_b)
circuit.cswap(q_b[0], q_b[1], q_b[2])
circuit.cswap(q_b[2], q_b[3], q_b[4])
circuit.cswap(q_b[3], q_b[4], q_b[0])
circuit.barrier(q_b)
circuit.measure(q_a, c_a)
circuit.measure(q_b, c_b);
# Draw the circuit
circuit.draw(output='mpl')
# Draw the circuit with reversed bit order
circuit.draw(output='mpl', reverse_bits=True)
# Draw the circuit without barriers
circuit.draw(output='mpl', plot_barriers=False)
# Draw the circuit without barriers and reverse bit order
circuit.draw(output='mpl', plot_barriers=False, reverse_bits=True)
# Set line length to 80 for above circuit
circuit.draw(output='text')
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circuit.draw(output='mpl', style=style)
# Scale the mpl output to 1/2 the normal size
circuit.draw(output='mpl', scale=0.5)
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit, output='mpl', plot_barriers=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_circuit_layout
from qiskit.tools.monitor import job_monitor
from qiskit.providers.fake_provider import FakeVigoV2
import matplotlib.pyplot as plt
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
backend = FakeVigoV2()
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub="ibm-q", group="open", project="main")
program_id = "qaoa"
qaoa_program = provider.runtime.program(program_id)
print(f"Program name: {qaoa_program.name}, Program id: {qaoa_program.program_id}")
print(qaoa_program.parameters())
import numpy as np
from qiskit.tools import job_monitor
from qiskit.opflow import PauliSumOp, Z, I
from qiskit.algorithms.optimizers import SPSA
# Define the cost operator to run.
op = (
(Z ^ Z ^ I ^ I ^ I)
- (I ^ I ^ Z ^ Z ^ I)
+ (I ^ I ^ Z ^ I ^ Z)
- (Z ^ I ^ Z ^ I ^ I)
- (I ^ Z ^ Z ^ I ^ I)
+ (I ^ Z ^ I ^ Z ^ I)
+ (I ^ I ^ I ^ Z ^ Z)
)
# SPSA helps deal with noisy environments.
optimizer = SPSA(maxiter=100)
# We will run a depth two QAOA.
reps = 2
# The initial point for the optimization, chosen at random.
initial_point = np.random.random(2 * reps)
# The backend that will run the programm.
options = {"backend_name": "ibmq_qasm_simulator"}
# The inputs of the program as described above.
runtime_inputs = {
"operator": op,
"reps": reps,
"optimizer": optimizer,
"initial_point": initial_point,
"shots": 2**13,
# Set to True when running on real backends to reduce circuit
# depth by leveraging swap strategies. If False the
# given optimization_level (default is 1) will be used.
"use_swap_strategies": False,
# Set to True when optimizing sparse problems.
"use_initial_mapping": False,
# Set to true when using echoed-cross-resonance hardware.
"use_pulse_efficient": False,
}
job = provider.runtime.run(
program_id=program_id,
options=options,
inputs=runtime_inputs,
)
job_monitor(job)
print(f"Job id: {job.job_id()}")
print(f"Job status: {job.status()}")
result = job.result()
from collections import defaultdict
def op_adj_mat(op: PauliSumOp) -> np.array:
"""Extract the adjacency matrix from the op."""
adj_mat = np.zeros((op.num_qubits, op.num_qubits))
for pauli, coeff in op.primitive.to_list():
idx = tuple([i for i, c in enumerate(pauli[::-1]) if c == "Z"]) # index of Z
adj_mat[idx[0], idx[1]], adj_mat[idx[1], idx[0]] = np.real(coeff), np.real(coeff)
return adj_mat
def get_cost(bit_str: str, adj_mat: np.array) -> float:
"""Return the cut value of the bit string."""
n, x = len(bit_str), [int(bit) for bit in bit_str[::-1]]
cost = 0
for i in range(n):
for j in range(n):
cost += adj_mat[i, j] * x[i] * (1 - x[j])
return cost
def get_cut_distribution(result) -> dict:
"""Extract the cut distribution from the result.
Returns:
A dict of cut value: probability.
"""
adj_mat = op_adj_mat(PauliSumOp.from_list(result["inputs"]["operator"]))
state_results = []
for bit_str, amp in result["eigenstate"].items():
state_results.append((bit_str, get_cost(bit_str, adj_mat), amp**2 * 100))
vals = defaultdict(int)
for res in state_results:
vals[res[1]] += res[2]
return dict(vals)
import matplotlib.pyplot as plt
cut_vals = get_cut_distribution(result)
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
axs[0].plot(result["optimizer_history"]["energy"])
axs[1].bar(list(cut_vals.keys()), list(cut_vals.values()))
axs[0].set_xlabel("Energy evaluation number")
axs[0].set_ylabel("Energy")
axs[1].set_xlabel("Cut value")
axs[1].set_ylabel("Probability")
from qiskit_optimization.runtime import QAOAClient
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization import QuadraticProgram
qubo = QuadraticProgram()
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
qaoa_mes = QAOAClient(
provider=provider, backend=provider.get_backend("ibmq_qasm_simulator"), reps=2, alpha=0.75
)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qubo)
print(result.prettyprint())
from qiskit.transpiler import PassManager
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
UnrollCustomDefinitions,
BasisTranslator,
Optimize1qGatesDecomposition,
)
from qiskit.transpiler.passes.calibration.builders import RZXCalibrationBuilderNoEcho
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import (
EchoRZXWeylDecomposition,
)
from qiskit.test.mock import FakeBelem
backend = FakeBelem()
inst_map = backend.defaults().instruction_schedule_map
channel_map = backend.configuration().qubit_channel_mapping
rzx_basis = ["rzx", "rz", "x", "sx"]
pulse_efficient = PassManager(
[
# Consolidate consecutive two-qubit operations.
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=["rz", "sx", "x", "rxx"]),
# Rewrite circuit in terms of Weyl-decomposed echoed RZX gates.
EchoRZXWeylDecomposition(backend.defaults().instruction_schedule_map),
# Attach scaled CR pulse schedules to the RZX gates.
RZXCalibrationBuilderNoEcho(
instruction_schedule_map=inst_map, qubit_channel_mapping=channel_map
),
# Simplify single-qubit gates.
UnrollCustomDefinitions(std_eqlib, rzx_basis),
BasisTranslator(std_eqlib, rzx_basis),
Optimize1qGatesDecomposition(rzx_basis),
]
)
from qiskit import QuantumCircuit
circ = QuantumCircuit(3)
circ.h([0, 1, 2])
circ.rzx(0.5, 0, 1)
circ.swap(0, 1)
circ.cx(2, 1)
circ.rz(0.4, 1)
circ.cx(2, 1)
circ.rx(1.23, 2)
circ.cx(2, 1)
circ.draw("mpl")
pulse_efficient.run(circ).draw("mpl", fold=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Alpine Quantum Technologies GmbH 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test helpers for quantum circuits."""
import math
import qiskit.circuit.random
from qiskit import QuantumCircuit
from qiskit.quantum_info.operators import Operator
def assert_circuits_equal(result: QuantumCircuit, expected: QuantumCircuit) -> None:
"""Assert result == expected, pretty-printing the circuits if they don't match."""
msg = f"\nexpected:\n{expected}\nresult:\n{result}"
assert result == expected, msg # noqa: S101
def assert_circuits_equal_ignore_global_phase(
result: QuantumCircuit, expected: QuantumCircuit
) -> None:
"""Assert result == expected, ignoring the value of the global phase."""
result_copy = result.copy()
result_copy.global_phase = 0.0
expected_copy = expected.copy()
expected_copy.global_phase = 0.0
assert_circuits_equal(result_copy, expected_copy)
def assert_circuits_equivalent(result: QuantumCircuit, expected: QuantumCircuit) -> None:
"""Assert that the passed circuits are equivalent up to a global phase."""
msg = f"\nexpected:\n{expected}\nresult:\n{result}"
assert Operator(expected).equiv(Operator(result)), msg # noqa: S101
def empty_circuit(num_qubits: int, with_final_measurement: bool = True) -> QuantumCircuit:
"""An empty circuit, with the given number of qubits."""
qc = QuantumCircuit(num_qubits)
if with_final_measurement:
qc.measure_all()
return qc
def random_circuit(
num_qubits: int, *, seed: int = 1234, with_final_measurement: bool = True
) -> QuantumCircuit:
"""A random circuit, with depth equal to the number of qubits."""
qc = qiskit.circuit.random.random_circuit(
num_qubits,
num_qubits,
seed=seed,
)
if with_final_measurement:
qc.measure_all()
return qc
def qft_circuit(num_qubits: int) -> QuantumCircuit:
"""N-qubits quantum Fourier transform.
Source: Nielsen & Chuang, Quantum Computation and Quantum Information.
"""
qc = QuantumCircuit(num_qubits)
for qubit in range(num_qubits - 1, -1, -1):
qc.h(qubit)
for k in range(1, qubit + 1):
qc.cp(math.pi / 2**k, qubit - k, qubit)
for qubit in range(num_qubits // 2):
qc.swap(qubit, (num_qubits - 1) - qubit)
return qc
|
https://github.com/rubenandrebarreiro/ibm-qiskit-quantum-explorers-2023-2024
|
rubenandrebarreiro
|
# build your code here
answer1 = [1]
# run this cell to submit your answer
# import the grader for the exercise 1 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex1
# expected result type: List
grade_badge5_ex1(answer1)
# build your code here
answer2 = [2]
# run this cell to submit your answer
# import the grader for the exercise 2 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex2
# expected result type: List
grade_badge5_ex2(answer2)
# build your code here
answer3 = [4]
# run this cell to submit your answer
# import the grader for the exercise 3 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex3
# expected result type: List
grade_badge5_ex3(answer3)
# build your code here
answer4 = [4]
# run this cell to submit your answer
# import the grader for the exercise 4 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex4
# expected result type: List
grade_badge5_ex4(answer4)
# build your code here
answer5 = [3]
# run this cell to submit your answer
# import the grader for the exercise 5 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex5
# expected result type: List
grade_badge5_ex5(answer5)
# build your code here
answer6 = [1]
# run this cell to submit your answer
# import the grader for the exercise 6 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex6
# expected result type: List
grade_badge5_ex6(answer6)
# build your code here
answer7 = [1]
# run this cell to submit your answer
# import the grader for the exercise 7 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex7
# expected result type: List
grade_badge5_ex7(answer7)
# build your code here
answer8 = [2]
# run this cell to submit your answer
# import the grader for the exercise 8 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex8
# expected result type: List
grade_badge5_ex8(answer8)
# build your code here
answer9 = [1]
# run this cell to submit your answer
# import the grader for the exercise 9 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex9
# expected result type: List
grade_badge5_ex9(answer9)
# build your code here
answer10 = [3]
# run this cell to submit your answer
# import the grader for the exercise 10 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex10
# expected result type: List
grade_badge5_ex10(answer10)
# build your code here
answer11 = [1]
# run this cell to submit your answer
# import the grader for the exercise 11 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex11
# expected result type: List
grade_badge5_ex11(answer11)
# build your code here
answer12 = [4]
# run this cell to submit your answer
# import the grader for the exercise 12 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex12
# expected result type: List
grade_badge5_ex12(answer12)
# import the NumPy library with 'np' alias
import numpy as np
# import the Quantum Support Vector Classifier (QSVC) from
# the Qiskit's Machine Learning - Algorithms module
from qiskit_machine_learning.algorithms import QSVC
# define the features X of the initial training dataset
x_train = np.array([
[1.25663706, 5.02654825, 3.76991118],
[3.76991118, 0. , 0.62831853],
[4.08407045, 3.76991118, 1.88495559],
[0.62831853, 2.82743339, 2.51327412],
[0.9424778 , 5.96902604, 5.02654825],
[5.02654825, 2.51327412, 0.31415927],
[5.34070751, 0.62831853, 3.45575192],
[0.31415927, 3.45575192, 3.76991118],
[1.25663706, 4.39822972, 5.96902604],
[3.76991118, 1.25663706, 2.82743339],
[3.14159265, 5.34070751, 1.88495559],
[3.45575192, 0.31415927, 1.57079633],
[1.57079633, 0. , 5.96902604],
[4.08407045, 3.14159265, 0. ],
[1.57079633, 4.39822972, 0.9424778 ],
[0. , 1.57079633, 0.31415927],
[5.02654825, 2.82743339, 4.71238898],
[2.51327412, 0.62831853, 0.62831853],
[3.14159265, 5.34070751, 1.88495559],
[5.65486678, 4.71238898, 4.08407045],
[0. , 2.19911486, 3.45575192],
[0.62831853, 0.31415927, 3.45575192],
[5.65486678, 2.51327412, 5.65486678],
[2.19911486, 0.62831853, 5.02654825],
[5.34070751, 3.45575192, 4.39822972],
[4.08407045, 2.51327412, 4.08407045],
[0.62831853, 5.65486678, 4.08407045],
[5.96902604, 4.39822972, 0.62831853],
[5.96902604, 4.39822972, 5.96902604],
[0. , 5.96902604, 4.08407045]
])
# define the labels Y of the initial training dataset
y_train = np.array([ 0, 0, 1, 1, 1, 1, 1, 0, 0, 0,
0, 0, 1, 0, 1, 1, 1, 1, 0, 0,
1, 1, 1, 0, 0, 0, 0, 1, 1, 0 ])
# compute the size of metric to
# split the initial training dataset into
# a final training set and a final test set,
# where 80% of the data will be used for training,
# and 20% of the data will be used for testing
train_size = int( 0.8 * len(x_train) )
# split the initial training dataset
# into a final training set,
# for the data features X
x_train_split = x_train[:train_size]
# split the initial training dataset
# into a final training set,
# for the data labels Y
y_train_split = y_train[:train_size]
# split the initial training dataset
# into a final testing set,
# for the data features X
x_test = x_train[train_size:]
# split the initial training dataset
# into a final testing set,
# for the data labels Y
y_test = y_train[train_size:]
####### build your code below #########
# import the Z Feature Map from
# the Qiskit's Circuit Library module
from qiskit.circuit.library import ZFeatureMap
# import the Sampler from
# the Qiskit's Primitives module
from qiskit.primitives import Sampler
# import the Compute-Uncompute method from
# the Qiskit's Algorithms - State Fidelities module
from qiskit.algorithms.state_fidelities import ComputeUncompute
# import the Fidelity Quantum Kernel from
# the Qiskit's Machine Learning - Kernels module
from qiskit_machine_learning.kernels import FidelityQuantumKernel
# compute the number of features X of
# the samples present in the final training set
num_features = x_train_split.shape[1]
# define the number of repetitions of
# the quantum circuits for the Z Feature Map
num_repetitions = 1
# create a Z Feature Map for the number of
# features X and number of repetitions defined before,
# to be used for the creation of the Quantum Kernel
feature_map = ZFeatureMap( feature_dimension=num_features, reps=num_repetitions )
# create the Sampler object
# for the Compute-Uncompute method
sampler = Sampler()
# create the Fidelity object object
# with the Sampler object defined before
fidelity = ComputeUncompute( sampler=sampler )
# create the Fidelity Quantum Kernel object
# with the Fidelity and the Z Feature Map defined before
quantum_kernel = FidelityQuantumKernel( fidelity=fidelity, feature_map=feature_map )
# create the Quantum Support Vector Classifier (QSVC)
# with the Fidelity Quantum Kernel defined before
qsvc = QSVC( quantum_kernel=quantum_kernel )
# fit the data features X and data labels Y of
# the final training dataset into the previously
# created Quantum Support Vector Classifier (QSVC)
qsvc.fit( x_train_split, y_train_split )
####### build your code above #########
# evaluate the performance score of
# the quantum learning model of
# the Quantum Support Vector Classifier (QSVC)
# note: you need achieve a score higher
# than 0.8 to pass the code question
qsvc_score = qsvc.score(x_test, y_test)
# print the performance score of
# the quantum learning model of
# the Quantum Support Vector Classifier (QSVC)
print(f"QSVC classification test score: {qsvc_score} ( { ( round( qsvc_score * 100 , 2 ) ) }% )")
# run this cell to submit your answer
# import the grader for the coding exercise of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_code
# expected result type: QSVC
answer_code = grade_badge5_code(qsvc)
# import the Qiskit Runtime Service
# from the Qiksit's IBM Runtime module
from qiskit_ibm_runtime import QiskitRuntimeService
# create a Qiskit's Runtime Service object,
# using the IBM Quantum channel
service = QiskitRuntimeService( channel="ibm_quantum" )
# compute the number of features X of
# the samples present in the final training set
num_features = x_train_split.shape[1]
# retrieve the least-busy backend
# with a minimum number of two qubits
# (this step can take a while)
real_backend = service.least_busy( min_num_qubits=num_features, simulator=False )
# print the information about the best (i.e., the least-busy)
# backend with a minimum number of two qubits, and an informative
# message about the job submission on this backend
print( "The best backend is " + real_backend.name + "!" )
# import the ZZ Feature Map from
# the Qiskit's Circuit Library module
from qiskit.circuit.library import ZZFeatureMap
# import the Quantum Support Vector Classifier (QSVC) from
# the Qiskit's Machine Learning - Algorithms module
from qiskit_machine_learning.algorithms import QSVC
# import the Session from
# the Qiksit's IBM Runtime module
from qiskit_ibm_runtime import Session
# import the Sampler from
# the Qiskit's Primitives module
from qiskit.primitives import Sampler
# import the Compute-Uncompute method from
# the Qiskit's Algorithms - State Fidelities module
from qiskit.algorithms.state_fidelities import ComputeUncompute
# import the Fidelity Quantum Kernel from
# the Qiskit's Machine Learning - Kernels module
from qiskit_machine_learning.kernels import FidelityQuantumKernel
# compute the number of features X of
# the samples present in the final training set
num_features = x_train_split.shape[1]
# create a ZZ Feature Map for
# the number of features X defined before,
# to be used for the creation of the Quantum Kernel
fm = feature_map = ZZFeatureMap( num_features )
# within the context of a Session configured
# with the Qiskit's Runtime Service object,
# created before, using the IBM Quantum channel,
# and also using the backend defined before
with Session( service=service, backend=real_backend ) as session:
# create the Sampler object
# for the Compute-Uncompute method
sampler = Sampler()
# create the Fidelity object,
# using the Compute-Uncompute method
# applied on the Sampler object defined before
fidelity = ComputeUncompute( sampler )
# create the Fidelity Quantum Kernel object
# with the Fidelity and the ZZ Feature Map defined before
quantum_kernel = FidelityQuantumKernel( feature_map=fm, fidelity=fidelity )
# create the Quantum Support Vector Classifier (QSVC)
# with the Fidelity Quantum Kernel defined before
qsvc = QSVC( quantum_kernel=quantum_kernel )
###### add your answers from above before running the cell #######
# fit the data features X and data labels Y of
# the final training dataset into the previously
# created Quantum Support Vector Classifier (QSVC)
qsvc.fit( x_train_split, y_train_split )
# evaluate the performance score of
# the quantum learning model of
# the Quantum Support Vector Classifier (QSVC)
qsvc_score = qsvc.score(x_test, y_test)
# print the performance score of
# the quantum learning model of
# the Quantum Support Vector Classifier (QSVC)
print(f"QSVC classification test score: {qsvc_score} ( { ( round( qsvc_score * 100 , 2 ) ) }% )")
# build your code here
answer13 = [4]
# run this cell to submit your answer
# import the grader for the exercise 13 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex13
# expected result type: List
grade_badge5_ex13(answer13)
# build your code here
answer14 = [3]
# run this cell to submit your answer
# import the grader for the exercise 14 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex14
# expected result type: List
grade_badge5_ex14(answer14)
# build your code here
answer15 = [2]
# run this cell to submit your answer
# import the grader for the exercise 15 of the lab/badge 5
from qc_grader.challenges.quantum_explorers23 import grade_badge5_ex15
# expected result type: List
grade_badge5_ex15(answer15)
# run this cell to check whether you have passed
# import the grader for the badge 5 of
# the IBM Qiskit's Quantum Explorers 2023-2024
from qc_grader.challenges.quantum_explorers23 import grade_badge5_score
# grade the score of the quiz of the lab for the badge 5
grade_badge5_score("en")
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit.circuit import Parameter
from qiskit import pulse
from qiskit.test.mock.backends.almaden import *
phase = Parameter('phase')
with pulse.build(FakeAlmaden()) as phase_test_sched:
pulse.shift_phase(phase, pulse.drive_channel(0))
phase_test_sched.instructions # ()
|
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
g_op = qi.Operator([[-1/2, 1/2, -1/2, 1/2],
[1/2, -1/2, -1/2, 1/2],
[1/2,1/2,1/2, 1/2],
[1/2, 1/2, -1/2, -1/2]])
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
import numpy as np
pi = np.pi
# IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circuit = QuantumCircuit(q, c)
circuit.h(q[2])
circuit.h(q[1])
circuit.h(q[0])
qft_gate = QFT(num_qubits=3, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=False, name='qft')
circuit.append(qft_gate, q)
circuit.measure(q, c)
circuit.draw(output='mpl', filename='qft1.png')
print(circuit)
job = execute(circuit, backend, shots=1000)
job_monitor(job)
counts = job.result().get_counts()
print("\n QFT Output")
print("-------------")
print(counts)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.visualization import plot_histogram
from math import pi
from qiskit.circuit.library import QFT
# Example usage
N = 15
t=4 # log_2(N) upper limit
n=t
# Create quantum registers
upper_register = QuantumRegister(n, 'upper')
bottom_register = QuantumRegister(t, 'bottom')
ancilla = QuantumRegister(1, 'ancilla')
classical_reg = ClassicalRegister(n, 'creg')
# Construct quantum circuit
qc = QuantumCircuit(upper_register, bottom_register, ancilla, classical_reg)
# Apply Hadamard gates on upper register
qc.h(upper_register)
qc.unitary(g_op, [0, 8], label='grover_op')
# Apply Inverse Quantum Fourier Transform (IQFT)
qc.append(QFT(n, inverse=True), upper_register)
# Measure upper register
qc.measure(upper_register, classical_reg)
print(qc)
sim_ideal = AerSimulator()
tbell_circ = transpile(qc, 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 gOp')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
import sys
sys.path.append('../')
from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\
sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\
sampleCircuitF
from entanglement import Ent
import warnings
warnings.filterwarnings('ignore')
labels = [
'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3',
'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F'
]
samplers = [
sampleCircuitA,
sampleCircuitB1,
sampleCircuitB2,
sampleCircuitB3,
sampleCircuitC,
sampleCircuitD,
sampleCircuitE,
sampleCircuitF
]
q = 4
for layer in range(1, 4):
print(f'qubtis: {q}')
print('-' * 25)
for (label, sampler) in zip(labels, samplers):
expr = Ent(sampler, layer=layer, epoch=3000)
print(f'{label}(layer={layer}): {expr}')
print()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Meta tests for mappers.
The test checks the output of the swapper to a ground truth DAG (one for each
test/swapper) saved in as a QASM (in `test/python/qasm/`). If they need
to be regenerated, the DAG candidate is compiled and run in a simulator and
the count is checked before being saved. This happens with (in the root
directory):
> python -m test.python.transpiler.test_mappers regenerate
To make a new swapper pass throw all the common tests, create a new class inside the file
`path/to/test_mappers.py` that:
* the class name should start with `Tests...`.
* inheriting from ``SwapperCommonTestCases, QiskitTestCase``
* overwrite the required attribute ``pass_class``
For example::
class TestsSomeSwap(SwapperCommonTestCases, QiskitTestCase):
pass_class = SomeSwap # The pass class
additional_args = {'seed_transpiler': 42} # In case SomeSwap.__init__ requires
# additional arguments
To **add a test for all the swappers**, add a new method ``test_foo``to the
``SwapperCommonTestCases`` class:
* defining the following required ``self`` attributes: ``self.count``,
``self.shots``, ``self.delta``. They are required for the regeneration of the
ground truth.
* use the ``self.assertResult`` assertion for comparing for regeneration of the
ground truth.
* explicitly set a unique ``name`` of the ``QuantumCircuit``, as it it used
for the name of the QASM file of the ground truth.
For example::
def test_a_common_test(self):
self.count = {'000': 512, '110': 512} # The expected count for this circuit
self.shots = 1024 # Shots to run in the backend.
self.delta = 5 # This is delta for the AlmostEqual during
# the count check
coupling_map = [[0, 1], [0, 2]] # The coupling map for this specific test
qr = QuantumRegister(3, 'q') #
cr = ClassicalRegister(3, 'c') # Set the circuit to test
circuit = QuantumCircuit(qr, cr, # and don't forget to put a name
name='some_name') # (it will be used to save the QASM
circuit.h(qr[1]) #
circuit.cx(qr[1], qr[2]) #
circuit.measure(qr, cr) #
result = transpile(circuit, self.create_backend(), coupling_map=coupling_map,
pass_manager=self.create_passmanager(coupling_map))
self.assertResult(result, circuit)
```
"""
# pylint: disable=attribute-defined-outside-init
import unittest
import os
import sys
from qiskit import execute
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, BasicAer
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap, SabreSwap
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler import CouplingMap, Layout
from qiskit.test import QiskitTestCase
class CommonUtilitiesMixin:
"""Utilities for meta testing.
Subclasses should redefine the ``pass_class`` argument, with a Swap Mapper
class.
Note: This class assumes that the subclass is also inheriting from
``QiskitTestCase``, and it uses ``QiskitTestCase`` methods directly.
"""
regenerate_expected = False
seed_simulator = 42
seed_transpiler = 42
additional_args = {}
pass_class = None
def create_passmanager(self, coupling_map, initial_layout=None):
"""Returns a PassManager using self.pass_class(coupling_map, initial_layout)"""
passmanager = PassManager()
if initial_layout:
passmanager.append(SetLayout(Layout(initial_layout)))
# pylint: disable=not-callable
passmanager.append(self.pass_class(CouplingMap(coupling_map), **self.additional_args))
return passmanager
def create_backend(self):
"""Returns a Backend."""
return BasicAer.get_backend("qasm_simulator")
def generate_ground_truth(self, transpiled_result, filename):
"""Generates the expected result into a file.
Checks if transpiled_result matches self.counts by running in a backend
(self.create_backend()). That's saved in a QASM in filename.
Args:
transpiled_result (DAGCircuit): The DAGCircuit to execute.
filename (string): Where the QASM is saved.
"""
sim_backend = self.create_backend()
job = execute(
transpiled_result,
sim_backend,
seed_simulator=self.seed_simulator,
seed_transpiler=self.seed_transpiler,
shots=self.shots,
)
self.assertDictAlmostEqual(self.counts, job.result().get_counts(), delta=self.delta)
transpiled_result.qasm(formatted=False, filename=filename)
def assertResult(self, result, circuit):
"""Fetches the QASM in circuit.name file and compares it with result."""
qasm_name = f"{type(self).__name__}_{circuit.name}.qasm"
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
filename = os.path.join(qasm_dir, qasm_name)
if self.regenerate_expected:
# Run result in backend to test that is valid.
self.generate_ground_truth(result, filename)
expected = QuantumCircuit.from_qasm_file(filename)
self.assertEqual(result, expected)
class SwapperCommonTestCases(CommonUtilitiesMixin):
"""Tests that are run in several mappers.
The tests here will be run in several mappers. When adding a test, please
ensure that the test:
* defines ``self.count``, ``self.shots``, ``self.delta``.
* uses the ``self.assertResult`` assertion for comparing for regeneration of
the ground truth.
* explicitly sets a unique ``name`` of the ``QuantumCircuit``.
See also ``CommonUtilitiesMixin`` and the module docstring.
"""
def test_a_cx_to_map(self):
"""A single CX needs to be remapped.
q0:----------m-----
|
q1:-[H]-(+)--|-m---
| | |
q2:------.---|-|-m-
| | |
c0:----------.-|-|-
c1:------------.-|-
c2:--------------.-
CouplingMap map: [1]<-[0]->[2]
expected count: '000': 50%
'110': 50%
"""
self.counts = {"000": 512, "110": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [0, 2]]
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr, name="a_cx_to_map")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.measure(qr, cr)
result = self.create_passmanager(coupling_map).run(circuit)
self.assertResult(result, circuit)
def test_initial_layout(self):
"""Using a non-trivial initial_layout.
q3:----------------m--
q0:----------m-----|--
| |
q1:-[H]-(+)--|-m---|--
| | | |
q2:------.---|-|-m-|--
| | | |
c0:----------.-|-|-|--
c1:------------.-|-|--
c2:--------------.-|--
c3:----------------.--
CouplingMap map: [1]<-[0]->[2]->[3]
expected count: '000': 50%
'110': 50%
"""
self.counts = {"0000": 512, "0110": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [0, 2], [2, 3]]
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr, name="initial_layout")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.measure(qr, cr)
layout = {qr[3]: 0, qr[0]: 1, qr[1]: 2, qr[2]: 3}
result = self.create_passmanager(coupling_map, layout).run(circuit)
self.assertResult(result, circuit)
def test_handle_measurement(self):
"""Handle measurement correctly.
q0:--.-----(+)-m-------
| | |
q1:-(+)-(+)-|--|-m-----
| | | |
q2:------|--|--|-|-m---
| | | | |
q3:-[H]--.--.--|-|-|-m-
| | | |
c0:------------.-|-|-|-
c1:--------------.-|-|-
c2:----------------.-|-
c3:------------------.-
CouplingMap map: [0]->[1]->[2]->[3]
expected count: '0000': 50%
'1011': 50%
"""
self.counts = {"1011": 512, "0000": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [1, 2], [2, 3]]
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr, name="handle_measurement")
circuit.h(qr[3])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[3], qr[0])
circuit.measure(qr, cr)
result = self.create_passmanager(coupling_map).run(circuit)
self.assertResult(result, circuit)
class TestsBasicSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using BasicSwap."""
pass_class = BasicSwap
class TestsLookaheadSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using LookaheadSwap."""
pass_class = LookaheadSwap
class TestsStochasticSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using StochasticSwap."""
pass_class = StochasticSwap
additional_args = {"seed": 0}
class TestsSabreSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using SabreSwap."""
pass_class = SabreSwap
additional_args = {"seed": 1242}
if __name__ == "__main__":
if len(sys.argv) >= 2 and sys.argv[1] == "regenerate":
CommonUtilitiesMixin.regenerate_expected = True
del sys.argv[1]
unittest.main()
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
# z measurement of qubit 0
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0);
# x measurement of qubit 0
measure_x = QuantumCircuit(1,1)
measure_x.h(0)
measure_x.measure(0,0);
qc = QuantumCircuit(1)
qc.h(0) # the hadamard
qc.x(0) # x gate
qc.y(0) # y gate
qc.z(0) # z gate
# for the following, replace theta by any number
theta = 3.14159/4
qc.ry(theta,0); # y axis rotation
shots = 2**14 # number of samples used for statistics
uncertainty = 0
for measure_circuit in [measure_z, measure_x]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts()
# calculate the probabilities for each bit value
probs = {}
for output in ['0','1']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
uncertainty += ( probs['0'] - probs['1'] )**2
# print the total uncertainty
print('The total uncertainty is',uncertainty )
# for the following, replace theta by any number
theta = 3.14159/2
qc.rx(theta,0); # x axis rotation
# y measurement of qubit 0
measure_y = QuantumCircuit(1,1)
measure_y.sdg(0)
measure_y.h(0)
measure_y.measure(0,0);
shots = 2**14 # number of samples used for statistics
uncertainty = 0
for measure_circuit in [measure_z, measure_x, measure_y]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
counts = execute(qc+measure_circuit,Aer.get_backend('qasm_simulator'),shots=shots).result().get_counts()
# calculate the probabilities for each bit value
probs = {}
for output in ['0','1']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
uncertainty += ( probs['0'] - probs['1'] )**2
# print the total uncertainty
print('The total uncertainty is',uncertainty )
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Choose the drawer you like best:
from qiskit.tools.visualization import matplotlib_circuit_drawer as draw
#from qiskit.tools.visualization import circuit_drawer as draw
from qiskit import IBMQ
IBMQ.load_accounts() # make sure you have setup your token locally to use this
%matplotlib inline
import matplotlib.pyplot as plt
def show_results(D):
# D is a dictionary with classical bits as keys and count as value
# example: D = {'000': 497, '001': 527}
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
from qiskit import Aer
# See a list of available local simulators
print("Aer backends: ", Aer.backends())
# see a list of available remote backends (these are freely given by IBM)
print("IBMQ Backends: ", IBMQ.backends())
# execute circuit and either display a histogram of the results
def execute_locally(qc, draw_circuit=False, show_results=False):
# Compile and run the Quantum circuit on a simulator backend
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
result_counts = result_sim.get_counts(qc)
if draw_circuit or show_results: # Print the results
print("simulation: ", result_sim, result_counts)
if draw_circuit: # draw the circuit
draw(qc)
elif show_results: # or show the results
show_results(result_counts)
return result_counts
from qiskit.backends.ibmq import least_busy
import time
# Compile and run on a real device backend
def execute_remotely(qc, draw_circuit=False, show_results=False):
if draw_circuit: # draw the circuit
draw(qc)
try:
# select least busy available device and execute.
least_busy_device = least_busy(IBMQ.backends(simulator=False))
print("Running on current least busy device: ", least_busy_device)
# running the job
job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10)
lapse, interval = 0, 10
while job_exp.status().name != 'DONE':
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status())
time.sleep(interval)
lapse += 1
print(job_exp.status())
exp_result = job_exp.result()
result_counts = exp_result.get_counts(qc)
# Show the results
print("experiment: ", exp_result, result_counts)
if show_results: # show the results
show_results(result_counts)
return result_counts
except:
print("All devices are currently unavailable.")
return {}
def new_circuit(size):
# Create a Quantum Register with size qubits
qr = QuantumRegister(size)
# Create a Classical Register with size bits
cr = ClassicalRegister(size)
# Create a Quantum Circuit acting on the qr and cr register
return qr, cr, QuantumCircuit(qr, cr)
ERROR_MESSAGE = "Looks like your Deutsch has a bug"
def quantum_oracle_1(qr, cr, circuit):
pass
def quantum_oracle_2(qr, cr, circuit):
circuit.cx(qr[0], qr[1])
def quantum_oracle_3(qr, cr, circuit):
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
def quantum_oracle_4(qr, cr, circuit):
circuit.z(qr[1])
circuit.cx(qr[0], qr[1])
def get_deutsch_verdict(res):
return "CONSTANT" or "BALANCED"
print(get_deutsch_verdict(results))
def deutsch(black_box):
# ...
black_box(circuit)
#...
return "CONSTANT" or "BALANCED"
assert deutsch(quantum_oracle_1) == 'CONSTANT', ERROR_MESSAGE
assert deutsch(quantum_oracle_2) == 'BALANCED', "Looks like your Deutsch has a bug"
assert deutsch(quantum_oracle_3) == 'BALANCED', "Looks like your Deutsch has a bug"
assert deutsch(quantum_oracle_4) == 'CONSTANT', "Looks like your Deutsch has a bug"
|
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 readout error NoiseModel integration tests
"""
from test.terra.utils.utils import list2dict
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors.standard_errors import pauli_error
# Backwards compatibility for Terra <= 0.13
if not hasattr(QuantumCircuit, 'i'):
QuantumCircuit.i = QuantumCircuit.iden
# ==========================================================================
# Pauli Gate Errors
# ==========================================================================
def pauli_gate_error_circuits():
"""Local Pauli gate error noise model circuits"""
circuits = []
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
# 100% all-qubit Pauli error on "id" gate
circuit = QuantumCircuit(qr, cr)
circuit.i(qr)
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
# 25% all-qubit Pauli error on "id" gates
circuit = QuantumCircuit(qr, cr)
circuit.i(qr)
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
# 100% Pauli error on "id" gates on qubit-1
circuit = QuantumCircuit(qr, cr)
circuit.i(qr)
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
# 25% all-qubit Pauli error on "id" gates on qubit-0
circuit = QuantumCircuit(qr, cr)
circuit.i(qr)
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
# 25% Pauli-X error on spectator for CX gate on [0, 1]
qr = QuantumRegister(3, 'qr')
cr = ClassicalRegister(3, 'cr')
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1])
circuit.barrier(qr)
circuit.cx(qr[1], qr[0])
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
return circuits
def pauli_gate_error_noise_models():
"""Local Pauli gate error noise models"""
noise_models = []
# 100% all-qubit Pauli error on "id" gates
error = pauli_error([('X', 1)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, 'id')
noise_models.append(noise_model)
# 25% all-qubit Pauli error on "id" gates
error = pauli_error([('X', 0.25), ('I', 0.75)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, 'id')
noise_models.append(noise_model)
# 100% Pauli error on "id" gates on qubit-1
error = pauli_error([('X', 1)])
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [1])
noise_models.append(noise_model)
# 25% all-qubit Pauli error on "id" gates on qubit-0
error = pauli_error([('X', 0.25), ('I', 0.75)])
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])
noise_models.append(noise_model)
# 25% Pauli-X error on spectator for CX gate on [0, 1]
error = pauli_error([('XII', 0.25), ('III', 0.75)])
noise_model = NoiseModel()
noise_model.add_nonlocal_quantum_error(error, 'cx', [0, 1], [0, 1, 2])
noise_models.append(noise_model)
return noise_models
def pauli_gate_error_counts(shots, hex_counts=True):
"""Pauli gate error circuits reference counts"""
counts_lists = []
# 100% all-qubit Pauli error on "id" gates
counts = [0, 0, 0, shots]
counts_lists.append(counts)
# 25% all-qubit Pauli error on "id" gates
counts = [9 * shots / 16, 3 * shots / 16, 3 * shots / 16, shots / 16]
counts_lists.append(counts)
# 100% Pauli error on "id" gates on qubit-1
counts = [0, 0, shots, 0]
counts_lists.append(counts)
# 25% all-qubit Pauli error on "id" gates on qubit-0
counts = [3 * shots / 4, shots / 4, 0, 0]
counts_lists.append(counts)
# 25% Pauli-X error on spectator for CX gate on [0, 1]
counts = [3 * shots / 4, 0, 0, 0, shots / 4, 0, 0, 0]
counts_lists.append(counts)
# Convert to counts dict
return [list2dict(i, hex_counts) for i in counts_lists]
# ==========================================================================
# Pauli Measure Errors
# ==========================================================================
def pauli_measure_error_circuits():
"""Local Pauli measure error noise model circuits"""
circuits = []
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
# 25% all-qubit Pauli error on measure
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
circuits.append(circuit)
# 25% local Pauli error on measure of qubit 1
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
circuits.append(circuit)
# 25 % non-local Pauli error on qubit 1 for measure of qubit-1
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
circuits.append(circuit)
return circuits
def pauli_measure_error_noise_models():
"""Local Pauli measure error noise models"""
noise_models = []
# 25% all-qubit Pauli error on measure
error = pauli_error([('X', 0.25), ('I', 0.75)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, 'measure')
noise_models.append(noise_model)
# 25% local Pauli error on measure of qubit 1
error = pauli_error([('X', 0.25), ('I', 0.75)])
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'measure', [1])
noise_models.append(noise_model)
# 25 % non-local Pauli error on qubit 1 for measure of qubit-1
error = pauli_error([('X', 0.25), ('I', 0.75)])
noise_model = NoiseModel()
noise_model.add_nonlocal_quantum_error(error, 'measure', [0], [1])
noise_models.append(noise_model)
return noise_models
def pauli_measure_error_counts(shots, hex_counts=True):
"""Local Pauli measure error circuits reference counts"""
counts_lists = []
# 25% all-qubit Pauli error on measure
counts = [9 * shots / 16, 3 * shots / 16, 3 * shots / 16, shots / 16]
counts_lists.append(counts)
# 25% local Pauli error on measure of qubit 1
counts = [3 * shots / 4, 0, shots / 4, 0]
counts_lists.append(counts)
# 25 % non-local Pauli error on qubit 1 for measure of qubit-1
counts = [3 * shots / 4, 0, shots / 4, 0]
counts_lists.append(counts)
# Convert to counts dict
return [list2dict(i, hex_counts) for i in counts_lists]
# ==========================================================================
# Pauli Reset Errors
# ==========================================================================
def pauli_reset_error_circuits():
"""Local Pauli reset error noise model circuits"""
circuits = []
qr = QuantumRegister(2, 'qr')
cr = ClassicalRegister(2, 'cr')
# 25% all-qubit Pauli error on reset
circuit = QuantumCircuit(qr, cr)
circuit.barrier(qr)
circuit.reset(qr)
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
# 25% local Pauli error on reset of qubit 1
circuit = QuantumCircuit(qr, cr)
circuit.barrier(qr)
circuit.reset(qr)
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
# 25 % non-local Pauli error on qubit 1 for reset of qubit-0
circuit = QuantumCircuit(qr, cr)
circuit.barrier(qr)
circuit.reset(qr[1])
circuit.barrier(qr)
circuit.reset(qr[0])
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
return circuits
def pauli_reset_error_noise_models():
"""Local Pauli reset error noise models"""
noise_models = []
# 25% all-qubit Pauli error on reset
error = pauli_error([('X', 0.25), ('I', 0.75)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, 'reset')
noise_models.append(noise_model)
# 25% local Pauli error on reset of qubit 1
error = pauli_error([('X', 0.25), ('I', 0.75)])
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'reset', [1])
noise_models.append(noise_model)
# 25 % non-local Pauli error on qubit 1 for reset of qubit-0
error = pauli_error([('X', 0.25), ('I', 0.75)])
noise_model = NoiseModel()
noise_model.add_nonlocal_quantum_error(error, 'reset', [0], [1])
noise_models.append(noise_model)
return noise_models
def pauli_reset_error_counts(shots, hex_counts=True):
"""Local Pauli reset error circuits reference counts"""
counts_lists = []
# 25% all-qubit Pauli error on reset
counts = [9 * shots / 16, 3 * shots / 16, 3 * shots / 16, shots / 16]
counts_lists.append(counts)
# 25% local Pauli error on reset of qubit 1
counts = [3 * shots / 4, 0, shots / 4, 0]
counts_lists.append(counts)
# 25 % non-local Pauli error on qubit 1 for reset of qubit-0
counts = [3 * shots / 4, 0, shots / 4, 0]
counts_lists.append(counts)
# Convert to counts dict
return [list2dict(i, hex_counts) for i in counts_lists]
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer
from qiskit.tools.visualization import plot_histogram
from math import pi
import matplotlib.pyplot as plt
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(c, 0)
qc.draw(output='mpl')
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.barrier()
qc.measure(q,c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.h(1)
qc.h(2)
qc.barrier()
qc.measure(q,c)
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw(output='mpl')
nq = 2
m = 2
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc_S = QuantumCircuit(q,c)
qc_S.h(0)
qc_S.x(1)
qc_S.draw('mpl')
cu_circ = QuantumCircuit(2)
cu_circ.cp(pi/2,0,1)
cu_circ.draw('mpl')
for _ in range(2**(m-1)):
qc_S.cp(pi/2,0,1)
qc_S.draw('mpl')
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, q[0], c[0])
qc_S.draw('mpl')
qc_S.reset(0)
qc_S.h(0)
qc_S.draw('mpl')
qc_S.p(-pi/2,0).c_if(c,1)
qc_S.draw('mpl')
## 2^t c-U operations (with t=m-2)
for _ in range(2**(m-2)):
qc_S.cp(pi/2,0,1)
x_measurement(qc_S, q[0], c[1])
qc_S.draw('mpl')
sim = Aer.get_backend('qasm_simulator')
count0 = execute(qc_S, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
plt.tight_layout()
nq = 3 # number of qubits
m = 3 # number of classical bits
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc = QuantumCircuit(q,c)
qc.h(0)
qc.x([1,2])
qc.draw('mpl')
cu_circ = QuantumCircuit(nq)
cu_circ.mcp(pi/4,[0,1],2)
cu_circ.draw('mpl')
for _ in range(2**(m-1)):
qc.mcp(pi/4,[0,1],2)
qc.draw('mpl')
x_measurement(qc, q[0], c[0])
qc.draw('mpl')
qc.reset(0)
qc.h(0)
qc.draw('mpl')
qc.p(-pi/2,0).c_if(c,1)
qc.draw('mpl')
for _ in range(2**(m-2)):
qc.mcp(pi/4,[0,1],2)
x_measurement(qc, q[0], c[1])
qc.draw('mpl')
# initialization of qubit q0
qc.reset(0)
qc.h(0)
# phase correction
qc.p(-pi/4,0).c_if(c,1)
qc.p(-pi/2,0).c_if(c,2)
qc.p(-3*pi/4,0).c_if(c,3)
# c-U operations
for _ in range(2**(m-3)):
qc.mcp(pi/4,[0,1],2)
# X measurement
qc.h(0)
qc.measure(0,2)
qc.draw('mpl')
count0 = execute(qc, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
fig.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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/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.
"""
DensityMatrix quantum state class.
"""
from __future__ import annotations
import copy as _copy
from numbers import Number
import numpy as np
from qiskit import _numpy_compat
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.instruction import Instruction
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.states.quantum_state import QuantumState
from qiskit.quantum_info.operators.mixins.tolerances import TolerancesMixin
from qiskit.quantum_info.operators.op_shape import OpShape
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp
from qiskit.quantum_info.operators.scalar_op import ScalarOp
from qiskit.quantum_info.operators.predicates import is_hermitian_matrix
from qiskit.quantum_info.operators.predicates import is_positive_semidefinite_matrix
from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel
from qiskit.quantum_info.operators.channel.superop import SuperOp
from qiskit._accelerate.pauli_expval import density_expval_pauli_no_x, density_expval_pauli_with_x
from qiskit.quantum_info.states.statevector import Statevector
class DensityMatrix(QuantumState, TolerancesMixin):
"""DensityMatrix class"""
def __init__(
self,
data: np.ndarray | list | QuantumCircuit | Instruction | QuantumState,
dims: int | tuple | list | None = None,
):
"""Initialize a density matrix object.
Args:
data (np.ndarray or list or matrix_like or QuantumCircuit or
qiskit.circuit.Instruction):
A statevector, quantum instruction or an object with a ``to_operator`` or
``to_matrix`` method from which the density matrix can be constructed.
If a vector the density matrix is constructed as the projector of that vector.
If a quantum instruction, the density matrix is constructed by assuming all
qubits are initialized in the zero state.
dims (int or tuple or list): Optional. The subsystem dimension
of the state (See additional information).
Raises:
QiskitError: if input data is not valid.
Additional Information:
The ``dims`` kwarg can be None, an integer, or an iterable of
integers.
* ``Iterable`` -- the subsystem dimensions are the values in the list
with the total number of subsystems given by the length of the list.
* ``Int`` or ``None`` -- the leading dimension of the input matrix
specifies the total dimension of the density matrix. If it is a
power of two the state will be initialized as an N-qubit state.
If it is not a power of two the state will have a single
d-dimensional subsystem.
"""
if isinstance(data, (list, np.ndarray)):
# Finally we check if the input is a raw matrix in either a
# python list or numpy array format.
self._data = np.asarray(data, dtype=complex)
elif isinstance(data, (QuantumCircuit, Instruction)):
# If the data is a circuit or an instruction use the classmethod
# to construct the DensityMatrix object
self._data = DensityMatrix.from_instruction(data)._data
elif hasattr(data, "to_operator"):
# If the data object has a 'to_operator' attribute this is given
# higher preference than the 'to_matrix' method for initializing
# an Operator object.
op = data.to_operator()
self._data = op.data
if dims is None:
dims = op.output_dims()
elif hasattr(data, "to_matrix"):
# If no 'to_operator' attribute exists we next look for a
# 'to_matrix' attribute to a matrix that will be cast into
# a complex numpy matrix.
self._data = np.asarray(data.to_matrix(), dtype=complex)
else:
raise QiskitError("Invalid input data format for DensityMatrix")
# Convert statevector into a density matrix
ndim = self._data.ndim
shape = self._data.shape
if ndim == 2 and shape[0] == shape[1]:
pass # We good
elif ndim == 1:
self._data = np.outer(self._data, np.conj(self._data))
elif ndim == 2 and shape[1] == 1:
self._data = np.reshape(self._data, shape[0])
else:
raise QiskitError("Invalid DensityMatrix input: not a square matrix.")
super().__init__(op_shape=OpShape.auto(shape=self._data.shape, dims_l=dims, dims_r=dims))
def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED):
dtype = self.data.dtype if dtype is None else dtype
return np.array(self.data, dtype=dtype, copy=copy)
def __eq__(self, other):
return super().__eq__(other) and np.allclose(
self._data, other._data, rtol=self.rtol, atol=self.atol
)
def __repr__(self):
prefix = "DensityMatrix("
pad = len(prefix) * " "
return "{}{},\n{}dims={})".format(
prefix,
np.array2string(self._data, separator=", ", prefix=prefix),
pad,
self._op_shape.dims_l(),
)
@property
def settings(self):
"""Return settings."""
return {"data": self.data, "dims": self._op_shape.dims_l()}
def draw(self, output: str | None = None, **drawer_args):
"""Return a visualization of the Statevector.
**repr**: ASCII TextMatrix of the state's ``__repr__``.
**text**: ASCII TextMatrix that can be printed in the console.
**latex**: An IPython Latex object for displaying in Jupyter Notebooks.
**latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX.
**qsphere**: Matplotlib figure, rendering of density matrix using `plot_state_qsphere()`.
**hinton**: Matplotlib figure, rendering of density matrix using `plot_state_hinton()`.
**bloch**: Matplotlib figure, rendering of density matrix using `plot_bloch_multivector()`.
Args:
output (str): Select the output method to use for drawing the
state. Valid choices are `repr`, `text`, `latex`, `latex_source`,
`qsphere`, `hinton`, or `bloch`. Default is `repr`. Default can
be changed by adding the line ``state_drawer = <default>`` to
``~/.qiskit/settings.conf`` under ``[default]``.
drawer_args: Arguments to be passed directly to the relevant drawing
function or constructor (`TextMatrix()`, `array_to_latex()`,
`plot_state_qsphere()`, `plot_state_hinton()` or `plot_bloch_multivector()`).
See the relevant function under `qiskit.visualization` for that function's
documentation.
Returns:
:class:`matplotlib.Figure` or :class:`str` or
:class:`TextMatrix` or :class:`IPython.display.Latex`:
Drawing of the Statevector.
Raises:
ValueError: when an invalid output method is selected.
"""
# pylint: disable=cyclic-import
from qiskit.visualization.state_visualization import state_drawer
return state_drawer(self, output=output, **drawer_args)
def _ipython_display_(self):
out = self.draw()
if isinstance(out, str):
print(out)
else:
from IPython.display import display
display(out)
@property
def data(self):
"""Return data."""
return self._data
def is_valid(self, atol=None, rtol=None):
"""Return True if trace 1 and positive semidefinite."""
if atol is None:
atol = self.atol
if rtol is None:
rtol = self.rtol
# Check trace == 1
if not np.allclose(self.trace(), 1, rtol=rtol, atol=atol):
return False
# Check Hermitian
if not is_hermitian_matrix(self.data, rtol=rtol, atol=atol):
return False
# Check positive semidefinite
return is_positive_semidefinite_matrix(self.data, rtol=rtol, atol=atol)
def to_operator(self) -> Operator:
"""Convert to Operator"""
dims = self.dims()
return Operator(self.data, input_dims=dims, output_dims=dims)
def conjugate(self):
"""Return the conjugate of the density matrix."""
return DensityMatrix(np.conj(self.data), dims=self.dims())
def trace(self):
"""Return the trace of the density matrix."""
return np.trace(self.data)
def purity(self):
"""Return the purity of the quantum state."""
# For a valid statevector the purity is always 1, however if we simply
# have an arbitrary vector (not correctly normalized) then the
# purity is equivalent to the trace squared:
# P(|psi>) = Tr[|psi><psi|psi><psi|] = |<psi|psi>|^2
return np.trace(np.dot(self.data, self.data))
def tensor(self, other: DensityMatrix) -> DensityMatrix:
"""Return the tensor product state self ⊗ other.
Args:
other (DensityMatrix): a quantum state object.
Returns:
DensityMatrix: the tensor product operator self ⊗ other.
Raises:
QiskitError: if other is not a quantum state.
"""
if not isinstance(other, DensityMatrix):
other = DensityMatrix(other)
ret = _copy.copy(self)
ret._data = np.kron(self._data, other._data)
ret._op_shape = self._op_shape.tensor(other._op_shape)
return ret
def expand(self, other: DensityMatrix) -> DensityMatrix:
"""Return the tensor product state other ⊗ self.
Args:
other (DensityMatrix): a quantum state object.
Returns:
DensityMatrix: the tensor product state other ⊗ self.
Raises:
QiskitError: if other is not a quantum state.
"""
if not isinstance(other, DensityMatrix):
other = DensityMatrix(other)
ret = _copy.copy(self)
ret._data = np.kron(other._data, self._data)
ret._op_shape = self._op_shape.expand(other._op_shape)
return ret
def _add(self, other):
"""Return the linear combination self + other.
Args:
other (DensityMatrix): a quantum state object.
Returns:
DensityMatrix: the linear combination self + other.
Raises:
QiskitError: if other is not a quantum state, or has
incompatible dimensions.
"""
if not isinstance(other, DensityMatrix):
other = DensityMatrix(other)
self._op_shape._validate_add(other._op_shape)
ret = _copy.copy(self)
ret._data = self.data + other.data
return ret
def _multiply(self, other):
"""Return the scalar multiplied state other * self.
Args:
other (complex): a complex number.
Returns:
DensityMatrix: the scalar multiplied state other * self.
Raises:
QiskitError: if other is not a valid complex number.
"""
if not isinstance(other, Number):
raise QiskitError("other is not a number")
ret = _copy.copy(self)
ret._data = other * self.data
return ret
def evolve(
self,
other: Operator | QuantumChannel | Instruction | QuantumCircuit,
qargs: list[int] | None = None,
) -> DensityMatrix:
"""Evolve a quantum state by an operator.
Args:
other (Operator or QuantumChannel
or Instruction or Circuit): The operator to evolve by.
qargs (list): a list of QuantumState subsystem positions to apply
the operator on.
Returns:
DensityMatrix: the output density matrix.
Raises:
QiskitError: if the operator dimension does not match the
specified QuantumState subsystem dimensions.
"""
if qargs is None:
qargs = getattr(other, "qargs", None)
# Evolution by a circuit or instruction
if isinstance(other, (QuantumCircuit, Instruction)):
return self._evolve_instruction(other, qargs=qargs)
# Evolution by a QuantumChannel
# Currently the class that has `to_quantumchannel` is QuantumError of Qiskit Aer, so we can't
# use QuantumError as a type hint.
if hasattr(other, "to_quantumchannel"):
return other.to_quantumchannel()._evolve(self, qargs=qargs)
if isinstance(other, QuantumChannel):
return other._evolve(self, qargs=qargs)
# Unitary evolution by an Operator
if not isinstance(other, Operator):
dims = self.dims(qargs=qargs)
other = Operator(other, input_dims=dims, output_dims=dims)
return self._evolve_operator(other, qargs=qargs)
def reverse_qargs(self) -> DensityMatrix:
r"""Return a DensityMatrix with reversed subsystem ordering.
For a tensor product state this is equivalent to reversing the order
of tensor product subsystems. For a density matrix
:math:`\rho = \rho_{n-1} \otimes ... \otimes \rho_0`
the returned state will be
:math:`\rho_0 \otimes ... \otimes \rho_{n-1}`.
Returns:
DensityMatrix: the state with reversed subsystem order.
"""
ret = _copy.copy(self)
axes = tuple(range(self._op_shape._num_qargs_l - 1, -1, -1))
axes = axes + tuple(len(axes) + i for i in axes)
ret._data = np.reshape(
np.transpose(np.reshape(self.data, self._op_shape.tensor_shape), axes),
self._op_shape.shape,
)
ret._op_shape = self._op_shape.reverse()
return ret
def _expectation_value_pauli(self, pauli, qargs=None):
"""Compute the expectation value of a Pauli.
Args:
pauli (Pauli): a Pauli operator to evaluate expval of.
qargs (None or list): subsystems to apply operator on.
Returns:
complex: the expectation value.
"""
n_pauli = len(pauli)
if qargs is None:
qubits = np.arange(n_pauli)
else:
qubits = np.array(qargs)
x_mask = np.dot(1 << qubits, pauli.x)
z_mask = np.dot(1 << qubits, pauli.z)
pauli_phase = (-1j) ** pauli.phase if pauli.phase else 1
if x_mask + z_mask == 0:
return pauli_phase * self.trace()
data = np.ravel(self.data, order="F")
if x_mask == 0:
return pauli_phase * density_expval_pauli_no_x(data, self.num_qubits, z_mask)
x_max = qubits[pauli.x][-1]
y_phase = (-1j) ** pauli._count_y()
y_phase = y_phase[0]
return pauli_phase * density_expval_pauli_with_x(
data, self.num_qubits, z_mask, x_mask, y_phase, x_max
)
def expectation_value(self, oper: Operator, qargs: None | list[int] = None) -> complex:
"""Compute the expectation value of an operator.
Args:
oper (Operator): an operator to evaluate expval.
qargs (None or list): subsystems to apply the operator on.
Returns:
complex: the expectation value.
"""
if isinstance(oper, Pauli):
return self._expectation_value_pauli(oper, qargs)
if isinstance(oper, SparsePauliOp):
return sum(
coeff * self._expectation_value_pauli(Pauli((z, x)), qargs)
for z, x, coeff in zip(oper.paulis.z, oper.paulis.x, oper.coeffs)
)
if not isinstance(oper, Operator):
oper = Operator(oper)
return np.trace(Operator(self).dot(oper, qargs=qargs).data)
def probabilities(
self, qargs: None | list[int] = None, decimals: None | int = None
) -> np.ndarray:
"""Return the subsystem measurement probability vector.
Measurement probabilities are with respect to measurement in the
computation (diagonal) basis.
Args:
qargs (None or list): subsystems to return probabilities for,
if None return for all subsystems (Default: None).
decimals (None or int): the number of decimal places to round
values. If None no rounding is done (Default: None).
Returns:
np.array: The Numpy vector array of probabilities.
Examples:
Consider a 2-qubit product state :math:`\\rho=\\rho_1\\otimes\\rho_0`
with :math:`\\rho_1=|+\\rangle\\!\\langle+|`,
:math:`\\rho_0=|0\\rangle\\!\\langle0|`.
.. code-block::
from qiskit.quantum_info import DensityMatrix
rho = DensityMatrix.from_label('+0')
# Probabilities for measuring both qubits
probs = rho.probabilities()
print('probs: {}'.format(probs))
# Probabilities for measuring only qubit-0
probs_qubit_0 = rho.probabilities([0])
print('Qubit-0 probs: {}'.format(probs_qubit_0))
# Probabilities for measuring only qubit-1
probs_qubit_1 = rho.probabilities([1])
print('Qubit-1 probs: {}'.format(probs_qubit_1))
.. parsed-literal::
probs: [0.5 0. 0.5 0. ]
Qubit-0 probs: [1. 0.]
Qubit-1 probs: [0.5 0.5]
We can also permute the order of qubits in the ``qargs`` list
to change the qubit position in the probabilities output
.. code-block::
from qiskit.quantum_info import DensityMatrix
rho = DensityMatrix.from_label('+0')
# Probabilities for measuring both qubits
probs = rho.probabilities([0, 1])
print('probs: {}'.format(probs))
# Probabilities for measuring both qubits
# but swapping qubits 0 and 1 in output
probs_swapped = rho.probabilities([1, 0])
print('Swapped probs: {}'.format(probs_swapped))
.. parsed-literal::
probs: [0.5 0. 0.5 0. ]
Swapped probs: [0.5 0.5 0. 0. ]
"""
probs = self._subsystem_probabilities(
np.abs(self.data.diagonal()), self._op_shape.dims_l(), qargs=qargs
)
# to account for roundoff errors, we clip
probs = np.clip(probs, a_min=0, a_max=1)
if decimals is not None:
probs = probs.round(decimals=decimals)
return probs
def reset(self, qargs: list[int] | None = None) -> DensityMatrix:
"""Reset state or subsystems to the 0-state.
Args:
qargs (list or None): subsystems to reset, if None all
subsystems will be reset to their 0-state
(Default: None).
Returns:
DensityMatrix: the reset state.
Additional Information:
If all subsystems are reset this will return the ground state
on all subsystems. If only a some subsystems are reset this
function will perform evolution by the reset
:class:`~qiskit.quantum_info.SuperOp` of the reset subsystems.
"""
if qargs is None:
# Resetting all qubits does not require sampling or RNG
ret = _copy.copy(self)
state = np.zeros(self._op_shape.shape, dtype=complex)
state[0, 0] = 1
ret._data = state
return ret
# Reset by evolving by reset SuperOp
dims = self.dims(qargs)
reset_superop = SuperOp(ScalarOp(dims, coeff=0))
reset_superop.data[0] = Operator(ScalarOp(dims)).data.ravel()
return self.evolve(reset_superop, qargs=qargs)
@classmethod
def from_label(cls, label: str) -> DensityMatrix:
r"""Return a tensor product of Pauli X,Y,Z eigenstates.
.. list-table:: Single-qubit state labels
:header-rows: 1
* - Label
- Statevector
* - ``"0"``
- :math:`\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}`
* - ``"1"``
- :math:`\begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}`
* - ``"+"``
- :math:`\frac{1}{2}\begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}`
* - ``"-"``
- :math:`\frac{1}{2}\begin{pmatrix} 1 & -1 \\ -1 & 1 \end{pmatrix}`
* - ``"r"``
- :math:`\frac{1}{2}\begin{pmatrix} 1 & -i \\ i & 1 \end{pmatrix}`
* - ``"l"``
- :math:`\frac{1}{2}\begin{pmatrix} 1 & i \\ -i & 1 \end{pmatrix}`
Args:
label (string): a eigenstate string ket label (see table for
allowed values).
Returns:
DensityMatrix: The N-qubit basis state density matrix.
Raises:
QiskitError: if the label contains invalid characters, or the length
of the label is larger than an explicitly specified num_qubits.
"""
return DensityMatrix(Statevector.from_label(label))
@staticmethod
def from_int(i: int, dims: int | tuple | list) -> DensityMatrix:
"""Return a computational basis state density matrix.
Args:
i (int): the basis state element.
dims (int or tuple or list): The subsystem dimensions of the statevector
(See additional information).
Returns:
DensityMatrix: The computational basis state :math:`|i\\rangle\\!\\langle i|`.
Additional Information:
The ``dims`` kwarg can be an integer or an iterable of integers.
* ``Iterable`` -- the subsystem dimensions are the values in the list
with the total number of subsystems given by the length of the list.
* ``Int`` -- the integer specifies the total dimension of the
state. If it is a power of two the state will be initialized
as an N-qubit state. If it is not a power of two the state
will have a single d-dimensional subsystem.
"""
size = np.prod(dims)
state = np.zeros((size, size), dtype=complex)
state[i, i] = 1.0
return DensityMatrix(state, dims=dims)
@classmethod
def from_instruction(cls, instruction: Instruction | QuantumCircuit) -> DensityMatrix:
"""Return the output density matrix of an instruction.
The statevector is initialized in the state :math:`|{0,\\ldots,0}\\rangle` of
the same number of qubits as the input instruction or circuit, evolved
by the input instruction, and the output statevector returned.
Args:
instruction (qiskit.circuit.Instruction or QuantumCircuit): instruction or circuit
Returns:
DensityMatrix: the final density matrix.
Raises:
QiskitError: if the instruction contains invalid instructions for
density matrix simulation.
"""
# Convert circuit to an instruction
if isinstance(instruction, QuantumCircuit):
instruction = instruction.to_instruction()
# Initialize an the statevector in the all |0> state
num_qubits = instruction.num_qubits
init = np.zeros((2**num_qubits, 2**num_qubits), dtype=complex)
init[0, 0] = 1
vec = DensityMatrix(init, dims=num_qubits * (2,))
vec._append_instruction(instruction)
return vec
def to_dict(self, decimals: None | int = None) -> dict:
r"""Convert the density matrix to dictionary form.
This dictionary representation uses a Ket-like notation where the
dictionary keys are qudit strings for the subsystem basis vectors.
If any subsystem has a dimension greater than 10 comma delimiters are
inserted between integers so that subsystems can be distinguished.
Args:
decimals (None or int): the number of decimal places to round
values. If None no rounding is done
(Default: None).
Returns:
dict: the dictionary form of the DensityMatrix.
Examples:
The ket-form of a 2-qubit density matrix
:math:`rho = |-\rangle\!\langle -|\otimes |0\rangle\!\langle 0|`
.. code-block::
from qiskit.quantum_info import DensityMatrix
rho = DensityMatrix.from_label('-0')
print(rho.to_dict())
.. parsed-literal::
{
'00|00': (0.4999999999999999+0j),
'10|00': (-0.4999999999999999-0j),
'00|10': (-0.4999999999999999+0j),
'10|10': (0.4999999999999999+0j)
}
For non-qubit subsystems the integer range can go from 0 to 9. For
example in a qutrit system
.. code-block::
import numpy as np
from qiskit.quantum_info import DensityMatrix
mat = np.zeros((9, 9))
mat[0, 0] = 0.25
mat[3, 3] = 0.25
mat[6, 6] = 0.25
mat[-1, -1] = 0.25
rho = DensityMatrix(mat, dims=(3, 3))
print(rho.to_dict())
.. parsed-literal::
{'00|00': (0.25+0j), '10|10': (0.25+0j), '20|20': (0.25+0j), '22|22': (0.25+0j)}
For large subsystem dimensions delimiters are required. The
following example is for a 20-dimensional system consisting of
a qubit and 10-dimensional qudit.
.. code-block::
import numpy as np
from qiskit.quantum_info import DensityMatrix
mat = np.zeros((2 * 10, 2 * 10))
mat[0, 0] = 0.5
mat[-1, -1] = 0.5
rho = DensityMatrix(mat, dims=(2, 10))
print(rho.to_dict())
.. parsed-literal::
{'00|00': (0.5+0j), '91|91': (0.5+0j)}
"""
return self._matrix_to_dict(
self.data, self._op_shape.dims_l(), decimals=decimals, string_labels=True
)
def _evolve_operator(self, other, qargs=None):
"""Evolve density matrix by an operator"""
# Get shape of output density matrix
new_shape = self._op_shape.compose(other._op_shape, qargs=qargs)
new_shape._dims_r = new_shape._dims_l
new_shape._num_qargs_r = new_shape._num_qargs_l
ret = _copy.copy(self)
if qargs is None:
# Evolution on full matrix
op_mat = other.data
ret._data = np.dot(op_mat, self.data).dot(op_mat.T.conj())
ret._op_shape = new_shape
return ret
# Reshape statevector and operator
tensor = np.reshape(self.data, self._op_shape.tensor_shape)
# Construct list of tensor indices of statevector to be contracted
num_indices = len(self.dims())
indices = [num_indices - 1 - qubit for qubit in qargs]
# Left multiple by mat
mat = np.reshape(other.data, other._op_shape.tensor_shape)
tensor = Operator._einsum_matmul(tensor, mat, indices)
# Right multiply by mat ** dagger
adj = other.adjoint()
mat_adj = np.reshape(adj.data, adj._op_shape.tensor_shape)
tensor = Operator._einsum_matmul(tensor, mat_adj, indices, num_indices, True)
# Replace evolved dimensions
ret._data = np.reshape(tensor, new_shape.shape)
ret._op_shape = new_shape
return ret
def _append_instruction(self, other, qargs=None):
"""Update the current Statevector by applying an instruction."""
from qiskit.circuit.reset import Reset
from qiskit.circuit.barrier import Barrier
# Try evolving by a matrix operator (unitary-like evolution)
mat = Operator._instruction_to_matrix(other)
if mat is not None:
self._data = self._evolve_operator(Operator(mat), qargs=qargs).data
return
# Special instruction types
if isinstance(other, Reset):
self._data = self.reset(qargs)._data
return
if isinstance(other, Barrier):
return
# Otherwise try evolving by a Superoperator
chan = SuperOp._instruction_to_superop(other)
if chan is not None:
# Evolve current state by the superoperator
self._data = chan._evolve(self, qargs=qargs).data
return
# If the instruction doesn't have a matrix defined we use its
# circuit decomposition definition if it exists, otherwise we
# cannot compose this gate and raise an error.
if other.definition is None:
raise QiskitError(f"Cannot apply Instruction: {other.name}")
if not isinstance(other.definition, QuantumCircuit):
raise QiskitError(
"{} instruction definition is {}; expected QuantumCircuit".format(
other.name, type(other.definition)
)
)
qubit_indices = {bit: idx for idx, bit in enumerate(other.definition.qubits)}
for instruction in other.definition:
if instruction.clbits:
raise QiskitError(
f"Cannot apply instruction with classical bits: {instruction.operation.name}"
)
# Get the integer position of the flat register
if qargs is None:
new_qargs = [qubit_indices[tup] for tup in instruction.qubits]
else:
new_qargs = [qargs[qubit_indices[tup]] for tup in instruction.qubits]
self._append_instruction(instruction.operation, qargs=new_qargs)
def _evolve_instruction(self, obj, qargs=None):
"""Return a new statevector by applying an instruction."""
if isinstance(obj, QuantumCircuit):
obj = obj.to_instruction()
vec = _copy.copy(self)
vec._append_instruction(obj, qargs=qargs)
return vec
def to_statevector(self, atol: float | None = None, rtol: float | None = None) -> Statevector:
"""Return a statevector from a pure density matrix.
Args:
atol (float): Absolute tolerance for checking operation validity.
rtol (float): Relative tolerance for checking operation validity.
Returns:
Statevector: The pure density matrix's corresponding statevector.
Corresponds to the eigenvector of the only non-zero eigenvalue.
Raises:
QiskitError: if the state is not pure.
"""
if atol is None:
atol = self.atol
if rtol is None:
rtol = self.rtol
if not is_hermitian_matrix(self._data, atol=atol, rtol=rtol):
raise QiskitError("Not a valid density matrix (non-hermitian).")
evals, evecs = np.linalg.eig(self._data)
nonzero_evals = evals[abs(evals) > atol]
if len(nonzero_evals) != 1 or not np.isclose(nonzero_evals[0], 1, atol=atol, rtol=rtol):
raise QiskitError("Density matrix is not a pure state")
psi = evecs[:, np.argmax(evals)] # eigenvectors returned in columns.
return Statevector(psi)
def partial_transpose(self, qargs: list[int]) -> DensityMatrix:
"""Return partially transposed density matrix.
Args:
qargs (list): The subsystems to be transposed.
Returns:
DensityMatrix: The partially transposed density matrix.
"""
arr = self._data.reshape(self._op_shape.tensor_shape)
qargs = len(self._op_shape.dims_l()) - 1 - np.array(qargs)
n = len(self.dims())
lst = list(range(2 * n))
for i in qargs:
lst[i], lst[i + n] = lst[i + n], lst[i]
rho = np.transpose(arr, lst)
rho = np.reshape(rho, self._op_shape.shape)
return DensityMatrix(rho, dims=self.dims())
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import sympy
from sympy import *
import numpy as np
from numpy import random
import math
import scipy
init_printing(use_unicode=True)
from matplotlib import pyplot as plt
%matplotlib inline
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum import TensorProduct as tp
from mpmath import factorial as fact
import io
import base64
#from IPython.core.display import display, HTML, clear_output
from IPython import *
from ipywidgets import interactive, interact, fixed, interact_manual, widgets
import csv
import importlib
import scipy.interpolate
from mpl_toolkits.mplot3d import Axes3D, proj3d
from itertools import product, combinations
from matplotlib.patches import FancyArrowPatch
from matplotlib import cm, colors
from sympy.functions.special.tensor_functions import KroneckerDelta
from scipy.linalg import polar, lapack
import mpmath
# constantes físicas
e = 1.60217662*10**-19 # C (carga elementar)
k = 8.9875517923*10**9 # Nm^2/C^2 (constante de Coulomb)
eps0 = 8.8541878128*10**-12 #F/m (permissividade do vácuo)
mu0 = 1.25663706212*10**-6 # N/A^2 (permeabilidade do vácuo)
h = 6.626069*10**-34 # Js (constante de Planck)
heV = h/e # em eV
hb = h/(2*math.pi) # hbar
hbeV = hb/e # em eV
c = 2.99792458*10**8 # m/s (velocidade da luz no vácuo)
G = 6.6742*10**-11 # Nm^2/kg^2 (constante gravitacional)
kB = 1.38065*10**-23 # J/K (constante de Boltzmann)
me = 9.109382*10**-31 # kg (massa do elétron)
mp = 1.6726219*10**-27 # kg (massa do próton)
mn = 1.67492749804*10**-27 # kg (massa do nêutron)
mT = 5.9722*10**24 # kg (massa da Terra)
mS = 1.98847*10**30 # kg (massa do Sol)
u = 1.660538921*10**-27 # kg (unidade de massa atômica)
dTS = 1.496*10**11 # m (distância Terra-Sol)
rT = 6.3781*10**6 # m (raio da Terra)
sSB = 5.670374419*10**-8 # W⋅m−2⋅K−4 (constante de Stefan-Boltzmann)
Ri = 10973734.848575922 # m^-1 (constante de Rydberg)
al = (k*e**2)/(hb*c) # ~1/137.035999084 (constante de estrutura fina)
a0=(hb**2)/(me*k*e**2) # ~ 0.52917710^-10 m (raio de Bohr)
ge = 2 # (fator giromagnetico do eletron)
gp = 5.58 # (fator giromagnetico do proton)
def id(n):
'''retorna a matriz identidade nxn'''
id = zeros(n,n)
for j in range(0,n):
id[j,j] = 1
return id
#id(2)
def pauli(j):
'''retorna as matrizes de Pauli'''
if j == 1:
return Matrix([[0,1],[1,0]])
elif j == 2:
return Matrix([[0,-1j],[1j,0]])
elif j == 3:
return Matrix([[1,0],[0,-1]])
#pauli(1), pauli(2), pauli(3)
def tr(A):
'''retorna o traço de uma matriz'''
d = A.shape[0]
tr = 0
for j in range(0,d):
tr += A[j,j]
return tr
#tr(pauli(1))
def comm(A,B):
'''retorna a função comutador'''
return A*B-B*A
#comm(pauli(1),pauli(2))
def acomm(A,B):
'''retorna a função anti-comutador'''
return A*B+B*A
#acomm(pauli(1),pauli(2))
def cb(n,j):
'''retorna um vetor da base padrão de C^n'''
vec = zeros(n,1)
vec[j] = 1
return vec
#cb(2,0)
def proj(psi):
'''retorna o projeto no vetor psi'''
d = psi.shape[0]
P = zeros(d,d)
for j in range(0,d):
for k in range(0,d):
P[j,k] = psi[j]*conjugate(psi[k])
return P
#proj(cb(2,0))
def bell(j,k):
if j == 0 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))+tp(cb(2,1),cb(2,1)))
elif j == 0 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))+tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 0:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,1))-tp(cb(2,1),cb(2,0)))
elif j == 1 and k == 1:
return (1/sqrt(2))*(tp(cb(2,0),cb(2,0))-tp(cb(2,1),cb(2,1)))
#bell(0,0), bell(0,1), bell(1,0), bell(1,1)
def inner_product(v,w):
d = len(v); ip = 0
for j in range(0,d):
ip += conjugate(v[j])*w[j]
return ip
#a,b,c,d = symbols("a b c d"); v = [b,a]; w = [c,d]; inner_product(v,w)
def norm(v):
d = len(v)
return sqrt(inner_product(v,v))
#v = [2,2]; norm(v)
def tp(x,y):
return tensorproduct(x,y)
A = tp(pauli(3),pauli(1)); A
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
from numpy.random import rand
from qiskit import transpile
## The Receiver entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Receiver(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Decode the message measuring the circuit (density-dependent)
def decode_quantum_message(self, message, density, backend):
## The values of the participant
self.values = []
for i, qc in enumerate(message):
qc.barrier()
if rand() < density:
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
qc.measure(0, 0)
transpiled_qc = transpile(qc, backend=backend)
result = backend.run(transpiled_qc, shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
self.values.append(measured_bit)
else:
self.values.append(-1)
return message
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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 registerless QuantumCircuit and Gates on wires"""
import numpy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit, AncillaQubit
from qiskit.circuit.exceptions import CircuitError
from qiskit.test import QiskitTestCase
class TestRegisterlessCircuit(QiskitTestCase):
"""Test registerless QuantumCircuit."""
def test_circuit_constructor_qwires(self):
"""Create a QuantumCircuit directly with quantum wires"""
circuit = QuantumCircuit(2)
expected = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(circuit, expected)
def test_circuit_constructor_wires_wrong(self):
"""Create a registerless QuantumCircuit wrongly"""
self.assertRaises(CircuitError, QuantumCircuit, 1, 2, 3) # QuantumCircuit(1, 2, 3)
def test_circuit_constructor_wires_wrong_mix(self):
"""Create an almost-registerless QuantumCircuit"""
# QuantumCircuit(1, ClassicalRegister(2))
self.assertRaises(CircuitError, QuantumCircuit, 1, ClassicalRegister(2))
class TestAddingBitsWithoutRegisters(QiskitTestCase):
"""Test adding Bit instances outside of Registers."""
def test_circuit_constructor_on_bits(self):
"""Verify we can add bits directly to a circuit."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit()]
ancillas = [AncillaQubit(), AncillaQubit()]
qc = QuantumCircuit(qubits, clbits, ancillas)
self.assertEqual(qc.qubits, qubits + ancillas)
self.assertEqual(qc.clbits, clbits)
self.assertEqual(qc.ancillas, ancillas)
self.assertEqual(qc.qregs, [])
self.assertEqual(qc.cregs, [])
def test_circuit_constructor_on_invalid_bits(self):
"""Verify we raise if passed not a Bit."""
with self.assertRaisesRegex(CircuitError, "Expected an instance of"):
_ = QuantumCircuit([3.14])
def test_raise_if_bits_already_present(self):
"""Verify we raise when attempting to add a Bit already in the circuit."""
qubits = [Qubit()]
with self.assertRaisesRegex(CircuitError, "bits found already"):
_ = QuantumCircuit(qubits, qubits)
qc = QuantumCircuit(qubits)
with self.assertRaisesRegex(CircuitError, "bits found already"):
qc.add_bits(qubits)
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
with self.assertRaisesRegex(CircuitError, "bits found already"):
qc.add_bits(qr[:])
def test_addding_individual_bit(self):
"""Verify we can add a single bit to a circuit."""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
new_bit = Qubit()
qc.add_bits([new_bit])
self.assertEqual(qc.qubits, list(qr) + [new_bit])
self.assertEqual(qc.qregs, [qr])
def test_inserted_ancilla_bits_are_added_to_qubits(self):
"""Verify AncillaQubits added via .add_bits are added to .qubits."""
anc = AncillaQubit()
qb = Qubit()
qc = QuantumCircuit()
qc.add_bits([anc, qb])
self.assertEqual(qc.qubits, [anc, qb])
class TestGatesOnWires(QiskitTestCase):
"""Test gates on wires."""
def test_circuit_single_wire_h(self):
"""Test circuit on wire (H gate)."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.h(1)
expected = QuantumCircuit(qreg)
expected.h(qreg[1])
self.assertEqual(circuit, expected)
def test_circuit_two_wire_cx(self):
"""Test circuit two wires (CX gate)."""
qreg = QuantumRegister(2)
expected = QuantumCircuit(qreg)
expected.cx(qreg[0], qreg[1])
circuit = QuantumCircuit(qreg)
circuit.cx(0, 1)
self.assertEqual(circuit, expected)
def test_circuit_single_wire_measure(self):
"""Test circuit on wire (measure gate)."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
circuit.measure(1, 1)
expected = QuantumCircuit(qreg, creg)
expected.measure(qreg[1], creg[1])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs and wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(0)
circuit.h(2)
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs/cregs and wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(0, 2)
circuit.measure(2, 1)
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[0], creg1[0])
expected.measure(qreg1[0], creg0[1])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on wires."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(0)
circuit.barrier(2)
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier(qreg01[0])
expected.barrier(qreg23[0])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(4)
circuit = QuantumCircuit(qreg, creg)
circuit.h(0).c_if(creg, 3)
expected = QuantumCircuit(qreg, creg)
expected.h(qreg[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, 99) # circuit.h(99)
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
self.assertRaises(CircuitError, circuit.measure, 1, 99) # circuit.measure(1, 99)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, [0, 2])
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[0], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_initialize_single_qubit(self):
"""Test initialize on single qubit."""
init_vector = [numpy.sqrt(0.5), numpy.sqrt(0.5)]
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.initialize(init_vector, qreg[0])
expected = QuantumCircuit(qreg)
expected.initialize(init_vector, [qreg[0]])
self.assertEqual(circuit, expected)
def test_mixed_register_and_registerless_indexing(self):
"""Test indexing if circuit contains bits in and out of registers."""
bits = [Qubit(), Qubit()]
qreg = QuantumRegister(3, "q")
circuit = QuantumCircuit(bits, qreg)
for i in range(len(circuit.qubits)):
circuit.rz(i, i)
expected_qubit_order = bits + qreg[:]
expected_circuit = QuantumCircuit(bits, qreg)
for i in range(len(expected_circuit.qubits)):
expected_circuit.rz(i, expected_qubit_order[i])
self.assertEqual(circuit.data, expected_circuit.data)
class TestGatesOnWireRange(QiskitTestCase):
"""Test gates on wire range."""
def test_wire_range(self):
"""Test gate wire range"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(range(0, 2))
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs in range of wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(range(0, 3))
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg0[1])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs in range of wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(range(1, 3), range(0, 4, 2))
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[1], creg0[0])
expected.measure(qreg1[0], creg1[0])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on range of wires with multi regs."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(range(0, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier(qreg01[0], qreg01[1], qreg23[0])
self.assertEqual(circuit, expected)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, range(1, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg)
circuit.h(range(1, 3)).c_if(creg, 3)
expected = QuantumCircuit(qreg0, qreg1, creg)
expected.h(qreg0[1]).c_if(creg, 3)
expected.h(qreg1[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, range(9, 99)) # circuit.h(range(9,99))
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
# circuit.measure(1, range(9,99))
self.assertRaises(CircuitError, circuit.measure, 1, range(9, 99))
class TestGatesOnWireSlice(QiskitTestCase):
"""Test gates on wire slice."""
def test_wire_slice(self):
"""Test gate wire slice"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(slice(0, 2))
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_wire_list(self):
"""Test gate wire list of integers"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h([0, 1])
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_wire_np_int(self):
"""Test gate wire with numpy int"""
numpy_int = numpy.dtype("int").type(2)
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(numpy_int)
expected = QuantumCircuit(qreg)
expected.h(qreg[2])
self.assertEqual(circuit, expected)
def test_wire_np_1d_array(self):
"""Test gate wire with numpy array (one-dimensional)"""
numpy_arr = numpy.array([0, 1])
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(numpy_arr)
expected = QuantumCircuit(qreg)
expected.h(qreg[0])
expected.h(qreg[1])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs in slices of wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(slice(0, 3))
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg0[1])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs in slices of wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(slice(1, 3), slice(0, 4, 2))
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[1], creg0[0])
expected.measure(qreg1[0], creg1[0])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on slice of wires with multi regs."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(slice(0, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier([qreg01[0], qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, slice(1, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg)
circuit.h(slice(1, 3)).c_if(creg, 3)
expected = QuantumCircuit(qreg0, qreg1, creg)
expected.h(qreg0[1]).c_if(creg, 3)
expected.h(qreg1[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, slice(9, 99)) # circuit.h(slice(9,99))
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
# circuit.measure(1, slice(9,99))
self.assertRaises(CircuitError, circuit.measure, 1, slice(9, 99))
def test_wire_np_2d_array(self):
"""Test gate wire with numpy array (two-dimensional). Raises."""
numpy_arr = numpy.array([[0, 1], [2, 3]])
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, numpy_arr) # circuit.h(numpy_arr)
class TestBitConditional(QiskitTestCase):
"""Test gates with single bit conditionals."""
def test_bit_conditional_single_gate(self):
"""Test circuit with a single gate conditioned on a bit."""
qreg = QuantumRegister(1)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
circuit.h(0).c_if(0, True)
expected = QuantumCircuit(qreg, creg)
expected.h(qreg[0]).c_if(creg[0], True)
self.assertEqual(circuit, expected)
def test_bit_conditional_multiple_gates(self):
"""Test circuit with multiple gates conditioned on individual bits."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
creg1 = ClassicalRegister(1)
circuit = QuantumCircuit(qreg, creg, creg1)
circuit.h(0).c_if(0, True)
circuit.h(1).c_if(1, False)
circuit.cx(1, 0).c_if(2, True)
expected = QuantumCircuit(qreg, creg, creg1)
expected.h(qreg[0]).c_if(creg[0], True)
expected.h(qreg[1]).c_if(creg[1], False)
expected.cx(qreg[1], qreg[0]).c_if(creg1[0], True)
self.assertEqual(circuit, expected)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/magn5452/QiskitQaoa
|
magn5452
|
#------------------------------------------------------------------------------
# Qaoa.py
#
# Implementation of the Quantum Approximate Optimization Algorithm (QAOA) [1],[2]
# specifically tailored for solving the MaxCut problem on graphs [3].
# This class facilitates the creation of QAOA circuits with
# various types of mixer operators and allows execution on a quantum simulator
# backend provided by Qiskit.
#
# The `Qaoa` class provides methods to:
# - Initialize with QAOA parameters, graph instance, mixer type, and backend settings
# - Create cost operator and various mixer operators (x, xx, y, yy, xy)
# - Generate the complete QAOA circuit
#
# Initialization parameters include the number of QAOA layers, angles for the
# mixer and cost operators, and options for setting verbosity, measurement, and
# random seed. The class checks for consistency in the provided parameters and
# supports visualizing the graph and QAOA circuit.
#
# Refs.
# [1] https://arxiv.org/abs/1411.4028
# [2] https://learning.quantum.ibm.com/tutorial/quantum-approximate-optimization-algorithm
# [3] https://en.wikipedia.org/wiki/Maximum_cut
#
# © Leonardo Lavagna 2024
# @ NESYA https://github.com/NesyaLab
#------------------------------------------------------------------------------
import numpy as np
from matplotlib import pyplot as plt
from classes import Problems as P
from functions import qaoa_utilities as utils
from qiskit import QuantumCircuit
from qiskit_aer import Aer
from typing import List, Tuple
from networkx import Graph
from qiskit.circuit import ParameterVector
class Qaoa:
def __init__(self, p: int = 0, G: Graph = None, betas: List[float] = None, gammas: List[float] = None,
mixer: str = "x", backend = Aer.get_backend('qasm_simulator'), measure: bool = True,
seed: int = None, verbose: bool = True):
"""Initialize class QAOA.
Args:
p (int): Positive number of QAOA layers. The default is 0.
G (Graph): A graph created with the Problem class used as MaxCut problem instance. The default is None.
betas (float): Angles for the mixer operator.
gammas (float): Angles for the cost operator.
mixer (str): Type of mixer operator to be used. The default is "x".
backend (Qiskit backend): Qiskit backend to execute the code on a quantum simulator.
The default is Aer.get_backend('qasm_simulator').
measure (bool): If True measure the qaoa circuit. The default is True.
seed (int): Seed for a pseudo-random number generator. The default is None.
verbose (bool): If True enters in debugging mode. The default is True.
"""
# Setup
self.p = p
self.G = G
self.mixer = mixer
self.backend = backend
self.measure = measure
self.verbose = verbose
self.seed = seed
self.problems_class = P.Problems(p_type="custom", G=self.G)
if self.seed is not None:
np.random.seed(self.seed)
if self.G is None:
self.N = 0
self.w = [[]]
self.betas = []
self.gammas = []
if self.G is not None:
self.N = G.get_number_of_nodes()
self.w = G.get_adjacency_matrix()
if betas is None or gammas is None:
self.betas = utils.generate_parameters(n=self.p, k=1)
self.gammas = utils.generate_parameters(n=self.p, k=2)
if betas is not None and gammas is not None:
self.betas = betas
self.gammas = gammas
# Checking...
if self.problems_class.__class__.__name__ != self.G.__class__.__name__ and G is not None:
raise Exception("Invalid parameters. The graph G should be created with the Problems class.")
if (self.p == 0 and self.G is not None) or (self.p > 0 and G is None):
raise ValueError("If G is not the empty graph p should be a strictly positive integer, and viceversa.")
if len(self.betas) != p or len(self.gammas) != p or len(self.betas) != len(self.gammas):
raise ValueError("Invalid angles list. The length of betas and gammas should be equal to p.")
# Initializing...
if self.verbose is True:
print(" --------------------------- ")
print("| Intializing Qaoa class... |".upper())
print(" --------------------------- ")
print("-> Getting problem instance...".upper())
if self.G is not None:
self.G.get_draw()
plt.show()
if self.G is None:
print("\t * G = ø")
if self.betas is None and self.G is not None:
print("-> Beta angles not provided. Generating angles...".upper())
print(f"\t * betas = {self.betas}")
if self.gammas is None and self.G is not None:
print("-> Gamma angles not provided. Generating angles...".upper())
print(f"\t * gammas = {self.gammas}")
print("-> Getting the ansatz...".upper())
if self.G is not None:
print(self.get_circuit())
if self.G is None:
print("\t * Qaoa circuit = ø")
print("-> The Qaoa class was initialized with the following parameters.".upper())
print(f"\t * Number of layers: p = {self.p};")
if self.G is None:
print(f"\t * Graph: G = ø;")
if self.G is not None:
print(f"\t * Graph: G = {self.G.p_type};")
print("\t * Angles:")
print(f"\t\t - betas = {self.betas};")
print(f"\t\t - gammas = {self.gammas};")
print(f"\t * Mixer Hamiltonian type: '{self.mixer}';")
print(f"\t * Random seed: seed = {self.seed};")
print(f"\t * Measurement setting: measure = {self.measure}.")
def cost_operator(self, gamma: float) -> QuantumCircuit:
"""Create an instance of the cost operator with angle 'gamma'.
Args:
gamma (float): Angle for the cost operator.
Returns:
QuantumCircuit: Circuit representing the cost operator.
"""
qc = QuantumCircuit(self.N, self.N)
for i,j in self.G.get_edges():
qc.cx(i, j)
qc.rz(gamma, j)
qc.cx(i, j)
return qc
def x_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the x-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for v in self.G.get_nodes():
qc.rx(beta, v)
return qc
def xx_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the xx-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.rxx(beta, i, j)
return qc
def y_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the y-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for v in self.G.get_nodes():
qc.ry(2 * beta, v)
return qc
def yy_mixer_operator(self, beta: float) -> QuantumCircuit:
"""Create an instance of the yy-mixer operator with angle 'beta'.
Args:
beta (float): Time-slice angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.ryy(beta / 2, i, j)
return qc
def xy_mixer_operator(self, phi: float, psi: float) -> QuantumCircuit:
"""Create an instance of the xy-mixer operator with angle 'beta'.
Args:
beta (float): Angle for the mixer operator.
Returns:
QuantumCircuit: Circuit representing the mixer operator.
"""
qc = QuantumCircuit(self.N, self.N)
# X_iX_j
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.rxx(phi / 2, i, j)
# Y_iY_j
for i, j in self.G.get_edges():
if self.w[i, j] > 0:
qc.ryy(psi / 2, i, j)
return qc
def get_circuit(self) -> QuantumCircuit:
"""Create an instance of the Qaoa circuit with given parameters.
Returns:
QuantumCircuit: Circuit representing the Qaoa.
"""
qc = QuantumCircuit(self.N, self.N)
params = ParameterVector("params", 2 * self.p)
betas = params[0 : self.p]
gammas = params[self.p : 2 * self.p]
qc.h(range(self.N))
qc.barrier(range(self.N))
for i in range(self.p):
qc = qc.compose(self.cost_operator(gammas[i]))
qc.barrier(range(self.N))
if self.mixer == "x":
qc = qc.compose(self.x_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "xx":
qc = qc.compose(self.xx_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "y":
qc = qc.compose(self.y_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "yy":
qc = qc.compose(self.yy_mixer_operator(betas[i]))
qc.barrier(range(self.N))
elif self.mixer == "xy":
qc = qc.compose(self.xy_mixer_operator(betas[i],betas[i]))
qc.barrier(range(self.N))
qc.barrier(range(self.N))
if self.measure:
qc.measure(range(self.N), range(self.N))
return qc
|
https://github.com/nicomeyer96/qiskit-torch-module
|
nicomeyer96
|
# This code is part of Qiskit-Torch-Module.
#
# If used in your project please cite this work as described in the README file.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from collections.abc import Sequence
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter, ParameterExpression, ParameterVector
from qiskit.quantum_info import SparsePauliOp
from qiskit.quantum_info.operators.base_operator import BaseOperator
from .utils import generate_alphabetically_ordered_circuit
from ..fast_primitives import FastEstimator
from ..fast_gradients import FastReverseGradientEstimator
class QNN:
""" This class implements a quantum neural network, which combines forward and backward class for a given setup.
Args:
circuit: Quantum circuit ansatz
encoding_params: Parameters used for data encoding, must be present in circuit | None if the circuit does
not use data encoding
variational_params: Parameters used for training, must be present in circuit
observables: Observables to evaluate, corresponds to output of QNN (default: Pauli-Z on all qubits)
num_threads_forward: Number of parallel threads for forward computation (default: all available threads)
num_threads_backward: Number of parallel threads for backward computation (default: all available threads)
"""
def __init__(
self,
circuit: QuantumCircuit,
encoding_params: Sequence[Parameter] | ParameterVector | None,
variational_params: Sequence[Sequence[Parameter]] | Sequence[ParameterVector] | Sequence[Parameter] | ParameterVector,
observables: Sequence[BaseOperator] | BaseOperator | str = 'individualZ',
num_threads_forward: int = 0,
num_threads_backward: int = 0,
):
# singleton variational parameter set
if (isinstance(variational_params[0], (Parameter, ParameterExpression))
or isinstance(variational_params, ParameterVector)):
variational_params = (variational_params, )
self._circuit, self._encoding_params, self._variational_params =\
generate_alphabetically_ordered_circuit(circuit, encoding_params, variational_params)
# Estimators for estimation of expectation values and gradients
self._estimator_expval = FastEstimator(self._circuit)
self._estimator_gradient = FastReverseGradientEstimator(self._circuit)
self._num_qubits = self._circuit.num_qubits
self._observables = self._validate_and_preprocess_observables(observables)
self._num_threads_forward = num_threads_forward
self._num_threads_backward = num_threads_backward
self._num_encoding_params = len(self._encoding_params)
self._num_variational_params = [len(_vp) for _vp in self._variational_params]
self._num_variational_param_sets = len(self._num_variational_params)
def forward(
self,
encoding_data: Sequence[Sequence[float]] | Sequence[float] | None,
variational_weights: Sequence[Sequence[float]] | Sequence[float],
) -> Sequence[Sequence[float]]:
""" Realizes forward pass of QNN, i.e. computation of expectation values
Args:
encoding_data: Input to the QNN
variational_weights: Values for trainable weights of the QNN
Returns:
Result of forward pass (i.e. expectation values)
"""
combined_data = self._validate_and_preprocess_data(encoding_data, variational_weights)
job = self._estimator_expval.run(
observables=self._observables,
parameter_values=combined_data,
num_threads=self._num_threads_forward
)
return job.result().values
def backward(
self,
encoding_data: Sequence[Sequence[float]] | Sequence[float] | None,
variational_weights: Sequence[Sequence[float]] | Sequence[float],
encoding_gradients: bool = False,
variational_gradients: Sequence[bool] | bool = True
) -> tuple[Sequence[Sequence[Sequence[float]]] | None,
Sequence[Sequence[Sequence[Sequence[float]]] | None] | Sequence[Sequence[Sequence[float]]] | None]:
""" Realizes backward pass of QNN, i.e. computation of gradients w.r.t. variational parameters
Args:
encoding_data: Input to the QNN
variational_weights: Values for trainable weights of the QNN
encoding_gradients: Whether to compute gradients w.r.t. input parameters (default: False)
variational_gradients: Whether to compute gradients w.r.t. trainable parameter sets (default: all True)
Returns:
Result of backward pass (i.e. gradients w.r.t. variational parameters)
"""
combined_data = self._validate_and_preprocess_data(encoding_data, variational_weights)
parameters = self._validate_and_preprocess_parameters(encoding_gradients, variational_gradients)
job = self._estimator_gradient.run(
observables=self._observables,
parameter_values=combined_data,
parameters=parameters,
num_threads=self._num_threads_backward
)
gradients = job.result().gradients
# cut into gradients w.r.t. input and variational parameters
return self._postprocess_gradients(gradients, encoding_gradients, variational_gradients)
def circuit(self) -> QuantumCircuit:
""" Return (pre-processed, i.e. alphabetically ordered) quantum circuit
"""
return self._circuit
def parameters(self) -> tuple[Sequence[Parameter], Sequence[Sequence[Parameter]]]:
""" Return (pre-processed, i.e. alphabetically ordered) encoding and variational parameters
"""
return self._encoding_params, self._variational_params
def input_parameters(self) -> Sequence[Parameter]:
""" Return (pre-processed, i.e. alphabetically ordered) encoding parameters
"""
return self._encoding_params
def trainable_parameters(self) -> Sequence[Sequence[Parameter]]:
""" Return (pre-processed, i.e. alphabetically ordered) variational parameters
"""
return self._variational_params
def num_parameters(self) -> tuple[int, Sequence[int]]:
""" Return number of encoding and variational parameters (per parameter set)
"""
return self._num_encoding_params, self._num_variational_params
def num_input_parameters(self) -> int:
""" Return number of encoding parameters
"""
return self._num_encoding_params
def num_trainable_parameters(self) -> Sequence[int]:
""" Return number of variational parameters (per parameter set)
"""
return self._num_variational_params
def observables(self) -> Sequence[BaseOperator]:
""" Return observables
"""
return self._observables
def num_observables(self) -> int:
""" Return number of observables
"""
return len(self._observables)
def num_threads_forward(self) -> int:
""" Return number of threads used for forward pass (`0` means all available)
"""
return self._num_threads_forward
def num_threads_backward(self) -> int:
""" Return number of threads used for backward pass (`0` means all available)
"""
return self._num_threads_backward
def set_num_threads_forward(self, num_threads_forward: int):
""" Set number of threads used for forward pass (`0` means all available)
"""
self._num_threads_forward = num_threads_forward
def set_num_threads_backward(self, num_threads_backward: int):
""" Set number of threads used for backward pass (`0` means all available)
"""
self._num_threads_backward = num_threads_backward
def _validate_and_preprocess_data(
self,
encoding_data: Sequence[Sequence[float]] | Sequence[float] | None,
variational_weights: Sequence[Sequence[float]] | Sequence[float]
) -> Sequence[Sequence[float]]:
""" Validate shape etc. of input, preprocess for forward and backward pass
Args:
encoding_data: Input to the QNN
variational_weights: Values for trainable weights of the QNN
Returns:
Concatenated input data to be bound to encoding and variational parameters
Raises:
ValueError: Mismatch of size / dimensions for provided input and underlying circuit
"""
# handle case of no input data
if encoding_data is None:
_encoding_data = np.array([[None]])
# handle singleton encoding data set
elif isinstance(encoding_data[0], (float, np.floating)):
_encoding_data = np.array((encoding_data, ))
else:
_encoding_data = np.array(encoding_data)
# validate encoding data
if encoding_data is not None and not self._num_encoding_params == _encoding_data.shape[1]:
raise ValueError(
"The size of the provided encoding data ({}) does not correspond to the number of encoding parameters "
"in the circuit ({}).".format(len(encoding_data), self._num_encoding_params))
# validate variational parameters and potentially do some re-shaping
if isinstance(variational_weights[0], (float, np.floating)):
# all variational parameters are given in one Sequence
if not sum(self._num_variational_params) == len(variational_weights):
raise ValueError(
"The size of the provided variational data ({}) does not correspond to the number of variational "
"parameters in the circuit ({}).".format(len(variational_weights), sum(self._num_variational_params)))
_variational_weights = np.array(variational_weights)
else:
# the variational parameters are given in per-parameter-set form
for set_index, (variational_weights_, num_variational_params_) in enumerate(zip(variational_weights, self._num_variational_params)):
if not num_variational_params_ == len(variational_weights_):
raise ValueError(
"The size of the provided variational data ({}) for parameter set #{} does not correspond "
"to the number of variational parameters for this set in the circuit ({})."
.format(len(variational_weights), set_index, sum(self._num_variational_params)))
# reshape in case variational data is given in per-parameter-set form
_variational_weights = np.concatenate(variational_weights).ravel()
# stack variational parameters a sufficient number of times and concatenate
return np.concatenate((_encoding_data, np.tile(_variational_weights, (len(_encoding_data), 1))), axis=1)
def _validate_and_preprocess_observables(
self,
observables: Sequence[BaseOperator] | BaseOperator | str
) -> Sequence[BaseOperator]:
""" Validate shape etc. of observables, preprocess for forward and backward pass
Args:
observables: Observables to evaluate on the circuit
Returns:
Pre-processed list of observables
Raises:
Value Error: Invalid observable was provided
"""
if isinstance(observables, str):
if 'individualZ' == observables:
return [SparsePauliOp(i*'I' + 'Z' + (self._num_qubits-i-1)*'I') for i in range(self._num_qubits)]
elif 'tensoredZ' == observables:
return (SparsePauliOp(self._num_qubits * 'Z'), )
else:
raise ValueError('The observable `{}` is not implemented. '
'Choose either `individualZ` for single-qubit Pauli-Z observables on all qubits,'
'`tensoredZ` for a tensored Pauli-Z observable on all qubits,'
'or explicitly provide an observable / a list of observables.'.format(observables))
elif isinstance(observables, BaseOperator):
# singleton observable
return (observables, )
else:
return observables
def _validate_and_preprocess_parameters(
self,
encoding_gradients: bool,
variational_gradients: Sequence[bool] | bool
) -> Sequence[Parameter]:
""" Validate shape etc. of gradient computation flags, preprocess for forward and backward pass
Args:
encoding_gradients: Whether to compute gradients w.r.t. input parameters
variational_gradients: Whether to compute gradients w.r.t. trainable parameter sets
Returns:
List of parameters of which to compute the gradients of
Raises:
ValueError: Trying to acquire gradients w.r.t. zero variational parameters
"""
if isinstance(variational_gradients, bool):
# singleton variational_gradients flag
if not (encoding_gradients or variational_gradients):
raise ValueError('The gradients of at least one set of parameters have to be computed.')
variational_gradients = [True for _ in range(self._num_variational_param_sets)]
else:
if not (encoding_gradients or any(variational_gradients)):
raise ValueError('The gradients of at least one set of parameters have to be computed.')
# determine the set of parameters to take gradients of
parameters = []
if encoding_gradients:
parameters.extend(self._encoding_params)
for index_set, variational_gradients_ in enumerate(variational_gradients):
if variational_gradients_:
parameters.extend(self._variational_params[index_set])
return parameters
def _postprocess_gradients(
self,
gradients: Sequence[Sequence[Sequence[float]]],
encoding_gradients: bool,
variational_gradients: Sequence[bool] | bool
) -> tuple[Sequence[Sequence[Sequence[float]]] | None,
Sequence[Sequence[Sequence[Sequence[float]]] | None] | Sequence[Sequence[Sequence[float]]] | None]:
""" Postprocess gradients from backward pass, potentially reshape
Args:
gradients: Gradient values from backward pass
encoding_gradients: Whether to compute gradients w.r.t. input parameters
variational_gradients: Whether to compute gradients w.r.t. trainable parameter sets
Note: If given as a single value, the gradients w.r.t. all trainable parameters will be returned in
flattened version. If given as a list, the same gradients are given as list with set-associated elements.
Returns:
Gradients w.r.t. encoding parameters, gradients w.r.t. variational parameters either in flattened or per-parameter form.
"""
cutting_index = 0
if encoding_gradients:
gradients_encoding = gradients[:, :, :self._num_encoding_params]
cutting_index += self._num_encoding_params
else:
gradients_encoding = None
if isinstance(variational_gradients, bool):
# singleton variational_gradients flag -> return computed gradients in flattened form
if variational_gradients:
gradients_variational = gradients[:, :, cutting_index:]
else:
gradients_variational = None
else:
# variational_gradients flag were give parameter-set-wise -> return gradients also in this form
gradients_variational = []
for index_set, variational_gradients_ in enumerate(variational_gradients):
if variational_gradients_:
gradients_variational.append(gradients[:, :, cutting_index:cutting_index+self._num_variational_params[index_set]])
cutting_index += self._num_variational_params[index_set]
else:
gradients_variational.append(None)
return gradients_encoding, gradients_variational
|
https://github.com/quantumjim/pewpew_qiskit_workshops
|
quantumjim
|
%matplotlib notebook
import pew
pew.init()
screen = pew.Pix()
# create a border of B=2 pixels
for A in range(8):
for B in [0,7]:
screen.pixel(A,B,2)
screen.pixel(B,A,2)
# the player is a B=3 pixel
X,Y = 4,6
screen.pixel(X,Y,3)
while True: # loop which checks for user input and responds
# use key presses to determine how the player moves
dX,dY = 0,1 # default is to fall
keys = pew.keys()
if keys!=0:
if keys&pew.K_O: # fly up with O
dY = -1
# just left and right
if keys&pew.K_LEFT:
dX = -1
dY = 0
if keys&pew.K_RIGHT:
dX = +1
dY = 0
# blank player pixel at old pos
screen.pixel(X,Y,0)
# change pos
if Y+dY in range(1,7):
Y+=dY
if X+dX in range(1,7):
X+=dX
# put player pixel at new pos
screen.pixel(X,Y,3)
pew.show(screen)
pew.tick(1/6)
import pew
from microqiskit import *
pew.init()
screen = pew.Pix()
# set positions of doors
l = (0,4)
r = (7,4)
u = (3,0)
d = (3,7)
doors = [l,r,u,d]
# create a border of B=2 pixels
for A in range(8):
for B in [0,7]:
screen.pixel(A,B,2)
screen.pixel(B,A,2)
# the player is a B=3 pixel
X,Y = 4,6
screen.pixel(X,Y,3)
# set up the circuit that decides whether doors are open
qc = QuantumCircuit(2,2)
# and those for measurement
meas_zz = QuantumCircuit(2,2)
meas_zz.measure(0,0)
meas_zz.measure(1,1)
meas_xx = QuantumCircuit(2,2)
meas_xx.h(0)
meas_xx.h(1)
meas_xx.measure(0,0)
meas_xx.measure(1,1)
# use the results to set which doors are open
m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0]
m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0]
opened = []
if m_zz[0]=='0':
opened.append(l)
if m_zz[1]=='0':
opened.append(r)
if m_xx[0]=='0':
opened.append(u)
if m_xx[1]=='0':
opened.append(d)
# set open door pixels to B=0
for door in doors:
screen.pixel(door[0],door[1],2)
for door in opened:
screen.pixel(door[0],door[1],0)
while (X,Y) not in opened:
# use key presses to determine how the player moves
dX,dY = 0,1 # default is to fall
keys = pew.keys()
if keys!=0:
if keys&pew.K_O: # fly up with O
dY = -1
# just left and right
if keys&pew.K_LEFT:
dX = -1
dY = 0
if keys&pew.K_RIGHT:
dX = +1
dY = 0
# blank player pixel at old pos
screen.pixel(X,Y,0)
# change pos
if ( Y+dY in range(1,7) and X+dX in range(1,7) ) or ( (X+dX,Y+dY) in opened ):
X+=dX
Y+=dY
# put player pixel at new pos
screen.pixel(X,Y,3)
pew.show(screen)
pew.tick(1/6)
import pew
from microqiskit import *
pew.init()
screen = pew.Pix()
# set positions of doors
l = (0,4)
r = (7,4)
u = (3,0)
d = (3,7)
doors = [l,r,u,d]
# create a border of B=2 pixels
for A in range(8):
for B in [0,7]:
screen.pixel(A,B,2)
screen.pixel(B,A,2)
# the player is a B=3 pixel
X,Y = 4,6
screen.pixel(X,Y,3)
# set up the circuit that decides whether doors are open
qc = QuantumCircuit(2,2)
# and those for measurement
meas_zz = QuantumCircuit(2,2)
meas_zz.measure(0,0)
meas_zz.measure(1,1)
meas_xx = QuantumCircuit(2,2)
meas_xx.h(0)
meas_xx.h(1)
meas_xx.measure(0,0)
meas_xx.measure(1,1)
while True:
# use the results to set which doors are open
m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0]
m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0]
opened = []
if m_zz[0]=='0':
opened.append(l)
if m_zz[1]=='0':
opened.append(r)
if m_xx[0]=='0':
opened.append(u)
if m_xx[1]=='0':
opened.append(d)
# set open door pixels to B=0
for door in doors:
screen.pixel(door[0],door[1],2)
for door in opened:
screen.pixel(door[0],door[1],0)
while (X,Y) not in opened:
# use key presses to determine how the player moves
dX,dY = 0,1 # default is to fall
keys = pew.keys()
if keys!=0:
if keys&pew.K_O: # fly up with O
dY = -1
# just left and right
if keys&pew.K_LEFT:
dX = -1
dY = 0
if keys&pew.K_RIGHT:
dX = +1
dY = 0
# blank player pixel at old pos
screen.pixel(X,Y,0)
# change pos
if ( Y+dY in range(1,7) and X+dX in range(1,7) ) or ( (X+dX,Y+dY) in opened ):
X+=dX
Y+=dY
# put player pixel at new pos
screen.pixel(X,Y,3)
pew.show(screen)
pew.tick(1/6)
if (X,Y)==u:
X,Y = 3,6
if (X,Y)==d:
X,Y = 3,1
if (X,Y)==l:
X,Y = 6,4
if (X,Y)==r:
X,Y = 1,4
import pew
from microqiskit import *
pew.init()
screen = pew.Pix()
# set positions of doors
l = (0,4)
r = (7,4)
u = (3,0)
d = (3,7)
doors = [l,r,u,d]
# create a border of B=2 pixels
for A in range(8):
for B in [0,7]:
screen.pixel(A,B,2)
screen.pixel(B,A,2)
# the player is a B=3 pixel
X,Y = 4,6
screen.pixel(X,Y,3)
# set positions of the hadamard objects
H = [[],[]]
H[0] = [6,6]
H[1] = [1,1]
# set up the circuit that decides whether doors are open
qc = QuantumCircuit(2,2)
# and those for measurement
meas_zz = QuantumCircuit(2,2)
meas_zz.measure(0,0)
meas_zz.measure(1,1)
meas_xx = QuantumCircuit(2,2)
meas_xx.h(0)
meas_xx.h(1)
meas_xx.measure(0,0)
meas_xx.measure(1,1)
qrng = QuantumCircuit(2,2)
while True:
# use the results to set which doors are open
m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0]
m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0]
opened = []
if m_zz[0]=='0':
opened.append(l)
if m_zz[1]=='0':
opened.append(r)
if m_xx[0]=='0':
opened.append(u)
if m_xx[1]=='0':
opened.append(d)
# set open door pixels to B=0
for door in doors:
screen.pixel(door[0],door[1],2)
for door in opened:
screen.pixel(door[0],door[1],0)
frame = 0
while (X,Y) not in opened:
# randomly move the positions of H[0] and H[1]
for j in range(2):
screen.pixel(H[j][0],H[j][1],0)
m = simulate(qrng+meas_xx,shots=1,get='memory')[0]
for j in range(2):
dH = (m[j]=='0') - (m[j]=='1')
if H[j][0]+dH in range(1,7):
H[j][0]+=dH
frame += 1 # brightness flashes, and so depends on frame
for j in range(2):
screen.pixel(H[j][0],H[j][1],1+(frame%2))
# use key presses to determine how the player moves
dX,dY = 0,1 # default is to fall
keys = pew.keys()
if keys!=0:
if keys&pew.K_O: # fly up with O
dY = -1
# just left and right
if keys&pew.K_LEFT:
dX = -1
dY = 0
if keys&pew.K_RIGHT:
dX = +1
dY = 0
# blank player pixel at old pos
screen.pixel(X,Y,0)
# change pos
if ( Y+dY in range(1,7) and X+dX in range(1,7) ) or ( (X+dX,Y+dY) in opened ):
X+=dX
Y+=dY
# put player pixel at new pos
screen.pixel(X,Y,3)
# if the player is at the same pos as H[0] or H[1]
# apply the corresponding Hadamard
for j in range(2):
if (X,Y)==(H[j][0],H[j][1]):
qc.h(j)
pew.show(screen)
pew.tick(1/6)
if (X,Y)==u:
X,Y = 3,6
if (X,Y)==d:
X,Y = 3,1
if (X,Y)==l:
X,Y = 6,4
if (X,Y)==r:
X,Y = 1,4
import pew
from microqiskit import *
pew.init()
screen = pew.Pix()
# set positions of doors
l = (0,4)
r = (7,4)
u = (3,0)
d = (3,7)
doors = [l,r,u,d]
# create a border of B=2 pixels
for A in range(8):
for B in [0,7]:
screen.pixel(A,B,2)
screen.pixel(B,A,2)
# the player is a B=3 pixel
X,Y = 4,6
screen.pixel(X,Y,3)
# set how high the player has gone up the tower
height = 0
# set positions of the hadamard objects
H = [[],[]]
H[0] = [6,6]
H[1] = [1,1]
# set up the circuit that decides whether doors are open
qc = QuantumCircuit(2,2)
# and those for measurement
meas_zz = QuantumCircuit(2,2)
meas_zz.measure(0,0)
meas_zz.measure(1,1)
meas_xx = QuantumCircuit(2,2)
meas_xx.h(0)
meas_xx.h(1)
meas_xx.measure(0,0)
meas_xx.measure(1,1)
qrng = QuantumCircuit(2,2)
while height<10:
# use the results to set which doors are open
m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0]
m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0]
opened = []
if m_zz[0]=='0':
opened.append(l)
if m_zz[1]=='0':
opened.append(r)
if m_xx[0]=='0':
opened.append(u)
if m_xx[1]=='0':
opened.append(d)
# set open door pixels to B=0
for door in doors:
screen.pixel(door[0],door[1],2)
for door in opened:
screen.pixel(door[0],door[1],0)
frame = 0
while (X,Y) not in opened:
# randomly move the positions of H[0] and H[1]
for j in range(2):
screen.pixel(H[j][0],H[j][1],0)
m = simulate(qrng+meas_xx,shots=1,get='memory')[0]
for j in range(2):
dH = (m[j]=='0') - (m[j]=='1')
if H[j][0]+dH in range(1,7):
H[j][0]+=dH
frame += 1 # brightness flashes, and so depends on frame
for j in range(2):
screen.pixel(H[j][0],H[j][1],1+(frame%2))
# use key presses to determine how the player moves
dX,dY = 0,1 # default is to fall
keys = pew.keys()
if keys!=0:
if keys&pew.K_O: # fly up with O
dY = -1
# just left and right
if keys&pew.K_LEFT:
dX = -1
dY = 0
if keys&pew.K_RIGHT:
dX = +1
dY = 0
# blank player pixel at old pos
screen.pixel(X,Y,0)
# change pos
if ( Y+dY in range(1,7) and X+dX in range(1,7) ) or ( (X+dX,Y+dY) in opened ):
X+=dX
Y+=dY
# put player pixel at new pos
screen.pixel(X,Y,3)
# if the player is at the same pos as H[0] or H[1]
# apply the corresponding Hadamard
for j in range(2):
if (X,Y)==(H[j][0],H[j][1]):
qc.h(j)
pew.show(screen)
pew.tick(1/6)
if (X,Y)==u:
X,Y = 3,6
height += 1
if (X,Y)==d:
X,Y = 3,1
height -= 1
if (X,Y)==l:
X,Y = 6,4
if (X,Y)==r:
X,Y = 1,4
while True:
for x in range(4):
for y in range(4):
m_zz = simulate(qc+meas_zz,shots=1,get='memory')[0]
m_xx = simulate(qc+meas_xx,shots=1,get='memory')[0]
screen.pixel(x,y,1+2*(m_zz[0]=='0'))
screen.pixel(x+4,y,1+2*(m_zz[1]=='0'))
screen.pixel(x,y+4,1+2*(m_xx[0]=='0'))
screen.pixel(x+4,y+4,1+2*(m_xx[1]=='0'))
pew.show(screen)
pew.tick(1/6)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
pip install qiskit
pip install qiskit-ignis
import qiskit
qiskit.IBMQ.save_account('17efde49764005e8eeb00dd065d44bc208778be72d44b475e508d20504818786f842988b0e506515c78debdd1b0c4b570717863db5e4f85569fb43c4c8626b8a',
overwrite = True)
qiskit.IBMQ.load_account()
import numpy as np
import math
from qiskit import *
nshots = 8192
IBMQ.load_account()
#provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_quito')
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
def coh_l1(rho):
d = rho.shape[0]; C = 0
for j in range(0,d-1):
for k in range(j+1,d):
C += np.abs(rho[j,k])
return 2*C
def predict_jb(rho):
return abs(rho[0,0]-rho[1,1])
r00 = 2/3; r01 = 1.33/3; r10 = 1.33/3; r11 = 1/3 # initial state
r = math.sqrt((r00-r11)**2 + abs(2*r01)**2) # raio de Bloch
th = math.acos((r00-r11)/r)
ph = math.acos(2*r01.real/(r*math.sin(th))) # angulos de Bloch
r0 = (1+r)/2.; r1 = (1-r)/2. # autovetores
print(r, th, ph, r0, r1)
# simulation
p = np.arange(0,1.1,0.1)
d = len(p)
Csim = np.zeros(d); Psim = np.zeros(d)
for j in range(0,d):
pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4 # depolarizing
# sequencia: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
# = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2),
math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2),
math.sqrt(r0*pZ)*math.cos(th/2),
-1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2),
math.sqrt(r1*pI)*math.sin(th/2),
-math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2),
math.sqrt(r1*pZ)*math.sin(th/2),
1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2),
math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2),
math.sqrt(r0*pX)*math.cos(th/2),
-math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2),
1j*math.sqrt(r0*pY)*math.cos(th/2),
-math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2),
math.sqrt(r1*pX)*math.sin(th/2),
math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2),
1j*math.sqrt(r1*pY)*math.sin(th/2)]
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
qc.initialize(Phi_ABCD, [qr[0],qr[3],qr[2],qr[1]])
qstc = state_tomography_circuits(qc, [qr[1]])
job = qiskit.execute(qstc, backend = simulator, shots=nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_sim = qstf.fit(method='lstsq')
Csim[j] = coh_l1(rho_sim)
Psim[j] = predict_jb(rho_sim)
# theoretical
pt = np.arange(0,1.01,0.01)
Ct = (1-pt)*(2*1.33/3)
Pt = (1-pt)*(1/3)
# experiment
p = np.arange(0,1.1,0.1); d = len(p)
Cexp = np.zeros(d); Pexp = np.zeros(d)
jobs_ids = []
for j in range(0,d):
pI = (4-3*p[j])/4; pX = p[j]/4; pZ = p[j]/4; pY = p[j]/4
Phi_ABCD = [math.sqrt(r0*pI)*math.cos(th/2),
math.sqrt(r0*pX)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2),
math.sqrt(r0*pZ)*math.cos(th/2),
-1j*math.sqrt(r0*pY)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2),
math.sqrt(r1*pI)*math.sin(th/2),
-math.sqrt(r1*pX)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2),
math.sqrt(r1*pZ)*math.sin(th/2),
1j*math.sqrt(r1*pY)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2),
math.sqrt(r0*pI)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2),
math.sqrt(r0*pX)*math.cos(th/2),
-math.sqrt(r0*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.sin(th/2),
1j*math.sqrt(r0*pY)*math.cos(th/2),
-math.sqrt(r1*pI)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2),
math.sqrt(r1*pX)*math.sin(th/2),
math.sqrt(r1*pZ)*(math.cos(ph)+1j*math.sin(ph))*math.cos(th/2),
1j*math.sqrt(r1*pY)*math.sin(th/2)]
qr = QuantumRegister(4); qc = QuantumCircuit(qr)
qc.initialize(Phi_ABCD, [qr[0],qr[3],qr[2],qr[1]])
qstc = state_tomography_circuits(qc, [qr[1]])
job = qiskit.execute(qstc, backend = device, shots=nshots)
jobs_ids.append(job.job_id())
print(job.job_id())
job_monitor(job)
qstf = StateTomographyFitter(job.result(), qstc)
rho_exp = qstf.fit(method='lstsq')
Cexp[j] = coh_l1(rho_exp)
#Pexp[j] = predict_jb(rho_exp)
# sem mitigacao, chip quito, qr[1]
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'font.size':12})
plt.figure(figsize = (6,4), dpi = 100)
plt.plot(pt,Ct,label=r'$C_{l_1}^{the}$')
#plt.plot(pt,Pt,label=r'$P_{jb}^{the}$')
plt.plot(p,Csim,'*',label=r'$C_{l_1}^{sim}$')
#plt.plot(p,Psim,'o',label=r'$P_{jb}^{sim}$')
plt.plot(p,Cexp,'^',label=r'$C_{l_1}^{exp}$')
#plt.plot(p,Pexp,'+',label=r'$P_{jb}^{exp}$')
plt.xlabel(r'$p$')
plt.legend()
plt.show()
# sem mitigacao, chip belem
# sem mitigacao, chip manila
# sem mitigacao, chip quito, qr[0]
f = open("jobs_ids_CS_rho.txt", "w")
f.write(str(jobs_ids))
f.close()
f = open("jobs_ids_CS_rho.txt","r")
list_ids = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
print(list_ids)
# error mitigation
qr = QuantumRegister(4); qubit_list = [1]
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = qiskit.execute(meas_calibs, backend = device, shots = nshots)
print(job.job_id())
job_monitor(job)
job = device.retrieve_job('63a124fa05888e2fcb99ab6e')
meas_fitter = CompleteMeasFitter(job.result(), state_labels)
p = np.arange(0,1.1,0.1); d = len(p)
Cexp = np.zeros(d); Pexp = np.zeros(d)
for j in range(0,d):
job = device.retrieve_job(list_ids[j])
mitigated_results = meas_fitter.filter.apply(job.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method='lstsq')
Cexp[j] = coh_l1(rho_exp)
Pexp[j] = predict_jb(rho_exp)
# com mitigacao, chip quito, qr[1]
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'font.size':12})
plt.figure(figsize = (6,4), dpi = 100)
plt.plot(pt,Ct,label=r'$C_{l_1}^{the}$')#,color='green')
plt.plot(p,Csim,'o',label=r'$C_{l_1}^{sim}$')#,color='blue')
plt.plot(p,Cexp,'*',label=r'$C_{l_1}^{exp}$')#,color='orange')
#plt.plot(pt,Pt,label=r'$P_{jb}^{the}$')
#plt.plot(p,Psim,'o',label=r'$P_{jb}^{sim}$')
#plt.plot(p,Pexp,'+',label=r'$P_{jb}^{exp}$')
plt.xlabel(r'$p$')
plt.legend()
plt.savefig('fig_QCS_mixed.pdf')
plt.show()
# com mitigacao, chip belem
# com mitigacao, chip manila
# com mitigacao, chip quito, qr[0]
# com mitigacao, chip quito
# sem mitigacao, chip quito
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
# Import requisite modules
import math
import operator
import logging
import traceback
import datetime
import sys
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Import Qiskit packages
import qiskit
from qiskit import Aer
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
# setup aqua logging
from qiskit.aqua._logging import set_logging_config, build_logging_config
# set_logging_config(build_logging_config(logging.DEBUG)) # choose INFO, DEBUG to see the log
# The data providers of stock-market data
from qiskit.finance.data_providers import *
from qiskit.finance.applications.ising import portfolio_diversification
# Generate a pairwise time-series similarity matrix
n = 3
stocks = [("TICKER%s" % i) for i in range(n)]
## if loading fails, a constant matrix instead
# rho = np.ones((n,n))
# rho[0,1] = 0.8
# rho[1,0] = 0.8
data = RandomDataProvider(tickers = stocks,
start = datetime.datetime(2016,1,1),
end = datetime.datetime(2016,1,30))
data.run()
rho = data.get_similarity_matrix() # using dynamic time warping
# Actually, we consider the additive inverse to invert the direction of optimisation.
rho = -1 * rho
plt.imshow(rho)
plt.show()
print(rho)
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.show()
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. 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()
# y_j : which stocks j are in the index fund
for ii in range(n ** 2, n **2 + n):
if x[ii] > 0:
# plot coordinate of the stocks in the index fund
plt.plot(xc[ii-n**2], yc[ii-n**2], 'r*', ms=20)
# x_ij
for ii in range(0, n ** 2):
if x[ii] > 0:
iy = ii // n # i
ix = ii % n # j
plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], 'C2')
plt.title(title_str +' cost = ' + str(int(C * 100) / 100.))
plt.show()
from qiskit.aqua.operators import StateFn
class QuantumOptimizer:
def __init__(self, rho, n, q):
self.rho = rho
self.n = n
self.q = q
# Obtains the least eigenvalue of the Hamiltonian classically
def exact_solution(self):
qubitOp = portfolio_diversification.get_operator(self.rho, self.n, self.q)
result = NumPyMinimumEigensolver(qubitOp).run()
return self.decode_result(result)
def vqe_solution(self):
qubitOp = portfolio_diversification.get_operator(self.rho, self.n, self.q)
backend = Aer.get_backend('statevector_simulator')
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='full')
vqe = VQE(qubitOp, ry, cobyla)
vqe.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
result = vqe.run(quantum_instance)
return self.decode_result(result)
def qaoa_solution(self):
qubitOp = portfolio_diversification.get_operator(self.rho, self.n, self.q)
backend = Aer.get_backend('statevector_simulator')
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa = QAOA(qubitOp, cobyla, 3, 'matrix')
qaoa.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
result = qaoa.run(quantum_instance)
return self.decode_result(result)
def get_portfoliodiversification_solution(self, n, result):
v = result.eigenstate
if isinstance(v, StateFn):
v = v.to_matrix()
N = n ** 2 + n
index_value = [x for x in range(len(v)) if v[x] == max(v)][0]
string_value = "{0:b}".format(index_value)
while len(string_value) < N:
string_value = '0' + string_value
x_state = list()
for elements in string_value:
if elements == '0':
x_state.append(0)
else:
x_state.append(1)
x_state = np.flip(x_state, axis=0)
return x_state
def decode_result(self, result, offset = 0):
quantum_solution = self.get_portfoliodiversification_solution(self.n, result)
ground_level = portfolio_diversification.get_portfoliodiversification_value(self.rho, self.n, self.q, quantum_solution)
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()
classical_solution, classical_cost = classical_optimizer.cplex_solution()
print(quantum_cost, 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, ground_level)
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('VQE produces the same solution as the exact eigensolver.')
else: print('VQE does not produce the same solution as the exact eigensolver, but that is to be expected.')
except Exception as ex:
print(ex)
# qaoa_state, qaoa_level = quantum_optimizer.qaoa_solution()
# print(qaoa_state)
# try:
# if np.linalg.norm(ground_state - qaoa_state)<0.01:
# print('QAOA produces the same solution as the exact eigensolver.')
# else: print('QAOA 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() # generate random coordinate
visualize_solution(xc, yc, ground_state, ground_level, n, q, 'Classical')
visualize_solution(xc, yc, vqe_state, vqe_level, n, q, 'VQE')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.x(0).c_if(cr, 0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
|
hamburgerguy
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
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.
"""Test Operator construction, including OpPrimitives and singletons."""
import itertools
import unittest
from math import pi
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
import scipy
from ddt import data, ddt, unpack
from scipy.sparse import csr_matrix
from scipy.stats import unitary_group
from qiskit import QiskitError, transpile
from qiskit.circuit import (
Instruction,
Parameter,
ParameterVector,
QuantumCircuit,
QuantumRegister,
)
from qiskit.circuit.library import CZGate, ZGate
from qiskit.extensions.exceptions import ExtensionError
from qiskit.opflow import (
CX,
CircuitOp,
CircuitStateFn,
ComposedOp,
DictStateFn,
EvolvedOp,
H,
I,
ListOp,
MatrixOp,
Minus,
OperatorBase,
OperatorStateFn,
OpflowError,
PauliOp,
PrimitiveOp,
SparseVectorStateFn,
StateFn,
SummedOp,
T,
TensoredOp,
VectorStateFn,
X,
Y,
Z,
Zero,
)
from qiskit.quantum_info import Operator, Pauli, Statevector
# pylint: disable=invalid-name
@ddt
class TestOpConstruction(QiskitOpflowTestCase):
"""Operator Construction tests."""
def test_pauli_primitives(self):
"""from to file test"""
newop = X ^ Y ^ Z ^ I
self.assertEqual(newop.primitive, Pauli("XYZI"))
kpower_op = (Y ^ 5) ^ (I ^ 3)
self.assertEqual(kpower_op.primitive, Pauli("YYYYYIII"))
kpower_op2 = (Y ^ I) ^ 4
self.assertEqual(kpower_op2.primitive, Pauli("YIYIYIYI"))
# Check immutability
self.assertEqual(X.primitive, Pauli("X"))
self.assertEqual(Y.primitive, Pauli("Y"))
self.assertEqual(Z.primitive, Pauli("Z"))
self.assertEqual(I.primitive, Pauli("I"))
def test_composed_eval(self):
"""Test eval of ComposedOp"""
self.assertAlmostEqual(Minus.eval("1"), -(0.5**0.5))
def test_xz_compose_phase(self):
"""Test phase composition"""
self.assertEqual((-1j * Y).eval("0").eval("0"), 0)
self.assertEqual((-1j * Y).eval("0").eval("1"), 1)
self.assertEqual((-1j * Y).eval("1").eval("0"), -1)
self.assertEqual((-1j * Y).eval("1").eval("1"), 0)
self.assertEqual((X @ Z).eval("0").eval("0"), 0)
self.assertEqual((X @ Z).eval("0").eval("1"), 1)
self.assertEqual((X @ Z).eval("1").eval("0"), -1)
self.assertEqual((X @ Z).eval("1").eval("1"), 0)
self.assertEqual((1j * Y).eval("0").eval("0"), 0)
self.assertEqual((1j * Y).eval("0").eval("1"), -1)
self.assertEqual((1j * Y).eval("1").eval("0"), 1)
self.assertEqual((1j * Y).eval("1").eval("1"), 0)
self.assertEqual((Z @ X).eval("0").eval("0"), 0)
self.assertEqual((Z @ X).eval("0").eval("1"), -1)
self.assertEqual((Z @ X).eval("1").eval("0"), 1)
self.assertEqual((Z @ X).eval("1").eval("1"), 0)
def test_evals(self):
"""evals test"""
# TODO: Think about eval names
self.assertEqual(Z.eval("0").eval("0"), 1)
self.assertEqual(Z.eval("1").eval("0"), 0)
self.assertEqual(Z.eval("0").eval("1"), 0)
self.assertEqual(Z.eval("1").eval("1"), -1)
self.assertEqual(X.eval("0").eval("0"), 0)
self.assertEqual(X.eval("1").eval("0"), 1)
self.assertEqual(X.eval("0").eval("1"), 1)
self.assertEqual(X.eval("1").eval("1"), 0)
self.assertEqual(Y.eval("0").eval("0"), 0)
self.assertEqual(Y.eval("1").eval("0"), -1j)
self.assertEqual(Y.eval("0").eval("1"), 1j)
self.assertEqual(Y.eval("1").eval("1"), 0)
with self.assertRaises(ValueError):
Y.eval("11")
with self.assertRaises(ValueError):
(X ^ Y).eval("1111")
with self.assertRaises(ValueError):
Y.eval((X ^ X).to_matrix_op())
# Check that Pauli logic eval returns same as matrix logic
self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("0").eval("0"), 1)
self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("1").eval("0"), 0)
self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("0").eval("1"), 0)
self.assertEqual(PrimitiveOp(Z.to_matrix()).eval("1").eval("1"), -1)
self.assertEqual(PrimitiveOp(X.to_matrix()).eval("0").eval("0"), 0)
self.assertEqual(PrimitiveOp(X.to_matrix()).eval("1").eval("0"), 1)
self.assertEqual(PrimitiveOp(X.to_matrix()).eval("0").eval("1"), 1)
self.assertEqual(PrimitiveOp(X.to_matrix()).eval("1").eval("1"), 0)
self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("0").eval("0"), 0)
self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("1").eval("0"), -1j)
self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("0").eval("1"), 1j)
self.assertEqual(PrimitiveOp(Y.to_matrix()).eval("1").eval("1"), 0)
pauli_op = Z ^ I ^ X ^ Y
mat_op = PrimitiveOp(pauli_op.to_matrix())
full_basis = list(map("".join, itertools.product("01", repeat=pauli_op.num_qubits)))
for bstr1, bstr2 in itertools.product(full_basis, full_basis):
# print('{} {} {} {}'.format(bstr1, bstr2, pauli_op.eval(bstr1, bstr2),
# mat_op.eval(bstr1, bstr2)))
np.testing.assert_array_almost_equal(
pauli_op.eval(bstr1).eval(bstr2), mat_op.eval(bstr1).eval(bstr2)
)
gnarly_op = SummedOp(
[
(H ^ I ^ Y).compose(X ^ X ^ Z).tensor(Z),
PrimitiveOp(Operator.from_label("+r0I")),
3 * (X ^ CX ^ T),
],
coeff=3 + 0.2j,
)
gnarly_mat_op = PrimitiveOp(gnarly_op.to_matrix())
full_basis = list(map("".join, itertools.product("01", repeat=gnarly_op.num_qubits)))
for bstr1, bstr2 in itertools.product(full_basis, full_basis):
np.testing.assert_array_almost_equal(
gnarly_op.eval(bstr1).eval(bstr2), gnarly_mat_op.eval(bstr1).eval(bstr2)
)
def test_circuit_construction(self):
"""circuit construction test"""
hadq2 = H ^ I
cz = hadq2.compose(CX).compose(hadq2)
qc = QuantumCircuit(2)
qc.append(cz.primitive, qargs=range(2))
ref_cz_mat = PrimitiveOp(CZGate()).to_matrix()
np.testing.assert_array_almost_equal(cz.to_matrix(), ref_cz_mat)
def test_io_consistency(self):
"""consistency test"""
new_op = X ^ Y ^ I
label = "XYI"
# label = new_op.primitive.to_label()
self.assertEqual(str(new_op.primitive), label)
np.testing.assert_array_almost_equal(
new_op.primitive.to_matrix(), Operator.from_label(label).data
)
self.assertEqual(new_op.primitive, Pauli(label))
x_mat = X.primitive.to_matrix()
y_mat = Y.primitive.to_matrix()
i_mat = np.eye(2, 2)
np.testing.assert_array_almost_equal(
new_op.primitive.to_matrix(), np.kron(np.kron(x_mat, y_mat), i_mat)
)
hi = np.kron(H.to_matrix(), I.to_matrix())
hi2 = Operator.from_label("HI").data
hi3 = (H ^ I).to_matrix()
np.testing.assert_array_almost_equal(hi, hi2)
np.testing.assert_array_almost_equal(hi2, hi3)
xy = np.kron(X.to_matrix(), Y.to_matrix())
xy2 = Operator.from_label("XY").data
xy3 = (X ^ Y).to_matrix()
np.testing.assert_array_almost_equal(xy, xy2)
np.testing.assert_array_almost_equal(xy2, xy3)
# Check if numpy array instantiation is the same as from Operator
matrix_op = Operator.from_label("+r")
np.testing.assert_array_almost_equal(
PrimitiveOp(matrix_op).to_matrix(), PrimitiveOp(matrix_op.data).to_matrix()
)
# Ditto list of lists
np.testing.assert_array_almost_equal(
PrimitiveOp(matrix_op.data.tolist()).to_matrix(),
PrimitiveOp(matrix_op.data).to_matrix(),
)
# TODO make sure this works once we resolve endianness mayhem
# qc = QuantumCircuit(3)
# qc.x(2)
# qc.y(1)
# from qiskit import BasicAer, QuantumCircuit, execute
# unitary = execute(qc, BasicAer.get_backend('unitary_simulator')).result().get_unitary()
# np.testing.assert_array_almost_equal(new_op.primitive.to_matrix(), unitary)
def test_to_matrix(self):
"""to matrix text"""
np.testing.assert_array_equal(X.to_matrix(), Operator.from_label("X").data)
np.testing.assert_array_equal(Y.to_matrix(), Operator.from_label("Y").data)
np.testing.assert_array_equal(Z.to_matrix(), Operator.from_label("Z").data)
op1 = Y + H
np.testing.assert_array_almost_equal(op1.to_matrix(), Y.to_matrix() + H.to_matrix())
op2 = op1 * 0.5
np.testing.assert_array_almost_equal(op2.to_matrix(), op1.to_matrix() * 0.5)
op3 = (4 - 0.6j) * op2
np.testing.assert_array_almost_equal(op3.to_matrix(), op2.to_matrix() * (4 - 0.6j))
op4 = op3.tensor(X)
np.testing.assert_array_almost_equal(
op4.to_matrix(), np.kron(op3.to_matrix(), X.to_matrix())
)
op5 = op4.compose(H ^ I)
np.testing.assert_array_almost_equal(
op5.to_matrix(), np.dot(op4.to_matrix(), (H ^ I).to_matrix())
)
op6 = op5 + PrimitiveOp(Operator.from_label("+r").data)
np.testing.assert_array_almost_equal(
op6.to_matrix(), op5.to_matrix() + Operator.from_label("+r").data
)
param = Parameter("α")
m = np.array([[0, -1j], [1j, 0]])
op7 = MatrixOp(m, param)
np.testing.assert_array_equal(op7.to_matrix(), m * param)
param = Parameter("β")
op8 = PauliOp(primitive=Pauli("Y"), coeff=param)
np.testing.assert_array_equal(op8.to_matrix(), m * param)
param = Parameter("γ")
qc = QuantumCircuit(1)
qc.h(0)
op9 = CircuitOp(qc, coeff=param)
m = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
np.testing.assert_array_equal(op9.to_matrix(), m * param)
def test_circuit_op_to_matrix(self):
"""test CircuitOp.to_matrix"""
qc = QuantumCircuit(1)
qc.rz(1.0, 0)
qcop = CircuitOp(qc)
np.testing.assert_array_almost_equal(
qcop.to_matrix(), scipy.linalg.expm(-0.5j * Z.to_matrix())
)
def test_matrix_to_instruction(self):
"""Test MatrixOp.to_instruction yields an Instruction object."""
matop = (H ^ 3).to_matrix_op()
with self.subTest("assert to_instruction returns Instruction"):
self.assertIsInstance(matop.to_instruction(), Instruction)
matop = ((H ^ 3) + (Z ^ 3)).to_matrix_op()
with self.subTest("matrix operator is not unitary"):
with self.assertRaises(ExtensionError):
matop.to_instruction()
def test_adjoint(self):
"""adjoint test"""
gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + PrimitiveOp(
Operator.from_label("+r0IX").data
)
np.testing.assert_array_almost_equal(
np.conj(np.transpose(gnarly_op.to_matrix())), gnarly_op.adjoint().to_matrix()
)
def test_primitive_strings(self):
"""get primitives test"""
self.assertEqual(X.primitive_strings(), {"Pauli"})
gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + PrimitiveOp(
Operator.from_label("+r0IX").data
)
self.assertEqual(gnarly_op.primitive_strings(), {"QuantumCircuit", "Matrix"})
def test_to_pauli_op(self):
"""Test to_pauli_op method"""
gnarly_op = 3 * (H ^ I ^ Y).compose(X ^ X ^ Z).tensor(T ^ Z) + PrimitiveOp(
Operator.from_label("+r0IX").data
)
mat_op = gnarly_op.to_matrix_op()
pauli_op = gnarly_op.to_pauli_op()
self.assertIsInstance(pauli_op, SummedOp)
for p in pauli_op:
self.assertIsInstance(p, PauliOp)
np.testing.assert_array_almost_equal(mat_op.to_matrix(), pauli_op.to_matrix())
def test_circuit_permute(self):
r"""Test the CircuitOp's .permute method"""
perm = range(7)[::-1]
c_op = (
((CX ^ 3) ^ X)
@ (H ^ 7)
@ (X ^ Y ^ Z ^ I ^ X ^ X ^ X)
@ (Y ^ (CX ^ 3))
@ (X ^ Y ^ Z ^ I ^ X ^ X ^ X)
)
c_op_perm = c_op.permute(perm)
self.assertNotEqual(c_op, c_op_perm)
c_op_id = c_op_perm.permute(perm)
self.assertEqual(c_op, c_op_id)
def test_summed_op_reduce(self):
"""Test SummedOp"""
sum_op = (X ^ X * 2) + (Y ^ Y) # type: PauliSumOp
sum_op = sum_op.to_pauli_op() # type: SummedOp[PauliOp]
with self.subTest("SummedOp test 1"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [2, 1])
sum_op = (X ^ X * 2) + (Y ^ Y)
sum_op += Y ^ Y
sum_op = sum_op.to_pauli_op() # type: SummedOp[PauliOp]
with self.subTest("SummedOp test 2-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [2, 1, 1])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 2-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [2, 2])
sum_op = (X ^ X * 2) + (Y ^ Y)
sum_op += (Y ^ Y) + (X ^ X * 2)
sum_op = sum_op.to_pauli_op() # type: SummedOp[PauliOp]
with self.subTest("SummedOp test 3-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "YY", "XX"])
self.assertListEqual([op.coeff for op in sum_op], [2, 1, 1, 2])
sum_op = sum_op.reduce().to_pauli_op()
with self.subTest("SummedOp test 3-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2)
with self.subTest("SummedOp test 4-a"):
self.assertEqual(sum_op.coeff, 2)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [2, 1])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 4-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2)
sum_op += Y ^ Y
with self.subTest("SummedOp test 5-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2, 1])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 5-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 3])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2)
sum_op += ((X ^ X) * 2 + (Y ^ Y)).to_pauli_op()
with self.subTest("SummedOp test 6-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2, 2, 1])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 6-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [6, 3])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2)
sum_op += sum_op
with self.subTest("SummedOp test 7-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2, 4, 2])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 7-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY"])
self.assertListEqual([op.coeff for op in sum_op], [8, 4])
sum_op = SummedOp([X ^ X * 2, Y ^ Y], 2) + SummedOp([X ^ X * 2, Z ^ Z], 3)
with self.subTest("SummedOp test 8-a"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "XX", "ZZ"])
self.assertListEqual([op.coeff for op in sum_op], [4, 2, 6, 3])
sum_op = sum_op.collapse_summands()
with self.subTest("SummedOp test 8-b"):
self.assertEqual(sum_op.coeff, 1)
self.assertListEqual([str(op.primitive) for op in sum_op], ["XX", "YY", "ZZ"])
self.assertListEqual([op.coeff for op in sum_op], [10, 2, 3])
sum_op = SummedOp([])
with self.subTest("SummedOp test 9"):
self.assertEqual(sum_op.reduce(), sum_op)
sum_op = ((Z + I) ^ Z) + (Z ^ X)
with self.subTest("SummedOp test 10"):
expected = SummedOp([PauliOp(Pauli("ZZ")), PauliOp(Pauli("IZ")), PauliOp(Pauli("ZX"))])
self.assertEqual(sum_op.to_pauli_op(), expected)
def test_compose_op_of_different_dim(self):
"""
Test if smaller operator expands to correct dim when composed with bigger operator.
Test if PrimitiveOps compose methods are consistent.
"""
# PauliOps of different dim
xy_p = X ^ Y
xyz_p = X ^ Y ^ Z
pauli_op = xy_p @ xyz_p
expected_result = I ^ I ^ Z
self.assertEqual(pauli_op, expected_result)
# MatrixOps of different dim
xy_m = xy_p.to_matrix_op()
xyz_m = xyz_p.to_matrix_op()
matrix_op = xy_m @ xyz_m
self.assertEqual(matrix_op, expected_result.to_matrix_op())
# CircuitOps of different dim
xy_c = xy_p.to_circuit_op()
xyz_c = xyz_p.to_circuit_op()
circuit_op = xy_c @ xyz_c
self.assertTrue(np.array_equal(pauli_op.to_matrix(), matrix_op.to_matrix()))
self.assertTrue(np.allclose(pauli_op.to_matrix(), circuit_op.to_matrix(), rtol=1e-14))
self.assertTrue(np.allclose(matrix_op.to_matrix(), circuit_op.to_matrix(), rtol=1e-14))
def test_permute_on_primitive_op(self):
"""Test if permute methods of PrimitiveOps are consistent and work as expected."""
indices = [1, 2, 4]
# PauliOp
pauli_op = X ^ Y ^ Z
permuted_pauli_op = pauli_op.permute(indices)
expected_pauli_op = X ^ I ^ Y ^ Z ^ I
self.assertEqual(permuted_pauli_op, expected_pauli_op)
# CircuitOp
circuit_op = pauli_op.to_circuit_op()
permuted_circuit_op = circuit_op.permute(indices)
expected_circuit_op = expected_pauli_op.to_circuit_op()
self.assertEqual(
Operator(permuted_circuit_op.primitive), Operator(expected_circuit_op.primitive)
)
# MatrixOp
matrix_op = pauli_op.to_matrix_op()
permuted_matrix_op = matrix_op.permute(indices)
expected_matrix_op = expected_pauli_op.to_matrix_op()
equal = np.allclose(permuted_matrix_op.to_matrix(), expected_matrix_op.to_matrix())
self.assertTrue(equal)
def test_permute_on_list_op(self):
"""Test if ListOp permute method is consistent with PrimitiveOps permute methods."""
op1 = (X ^ Y ^ Z).to_circuit_op()
op2 = Z ^ X ^ Y
# ComposedOp
indices = [1, 2, 0]
primitive_op = op1 @ op2
primitive_op_perm = primitive_op.permute(indices) # CircuitOp.permute
composed_op = ComposedOp([op1, op2])
composed_op_perm = composed_op.permute(indices)
# reduce the ListOp to PrimitiveOp
to_primitive = composed_op_perm.oplist[0] @ composed_op_perm.oplist[1]
# compare resulting PrimitiveOps
equal = np.allclose(primitive_op_perm.to_matrix(), to_primitive.to_matrix())
self.assertTrue(equal)
# TensoredOp
indices = [3, 5, 4, 0, 2, 1]
primitive_op = op1 ^ op2
primitive_op_perm = primitive_op.permute(indices)
tensored_op = TensoredOp([op1, op2])
tensored_op_perm = tensored_op.permute(indices)
# reduce the ListOp to PrimitiveOp
composed_oplist = tensored_op_perm.oplist
to_primitive = (
composed_oplist[0]
@ (composed_oplist[1].oplist[0] ^ composed_oplist[1].oplist[1])
@ composed_oplist[2]
)
# compare resulting PrimitiveOps
equal = np.allclose(primitive_op_perm.to_matrix(), to_primitive.to_matrix())
self.assertTrue(equal)
# SummedOp
primitive_op = X ^ Y ^ Z
summed_op = SummedOp([primitive_op])
indices = [1, 2, 0]
primitive_op_perm = primitive_op.permute(indices) # PauliOp.permute
summed_op_perm = summed_op.permute(indices)
# reduce the ListOp to PrimitiveOp
to_primitive = summed_op_perm.oplist[0] @ primitive_op @ summed_op_perm.oplist[2]
# compare resulting PrimitiveOps
equal = np.allclose(primitive_op_perm.to_matrix(), to_primitive.to_matrix())
self.assertTrue(equal)
def test_expand_on_list_op(self):
"""Test if expanded ListOp has expected num_qubits."""
add_qubits = 3
# ComposedOp
composed_op = ComposedOp([(X ^ Y ^ Z), (H ^ T), (Z ^ X ^ Y ^ Z).to_matrix_op()])
expanded = composed_op._expand_dim(add_qubits)
self.assertEqual(composed_op.num_qubits + add_qubits, expanded.num_qubits)
# TensoredOp
tensored_op = TensoredOp([(X ^ Y), (Z ^ I)])
expanded = tensored_op._expand_dim(add_qubits)
self.assertEqual(tensored_op.num_qubits + add_qubits, expanded.num_qubits)
# SummedOp
summed_op = SummedOp([(X ^ Y), (Z ^ I ^ Z)])
expanded = summed_op._expand_dim(add_qubits)
self.assertEqual(summed_op.num_qubits + add_qubits, expanded.num_qubits)
def test_expand_on_state_fn(self):
"""Test if expanded StateFn has expected num_qubits."""
num_qubits = 3
add_qubits = 2
# case CircuitStateFn, with primitive QuantumCircuit
qc2 = QuantumCircuit(num_qubits)
qc2.cx(0, 1)
cfn = CircuitStateFn(qc2, is_measurement=True)
cfn_exp = cfn._expand_dim(add_qubits)
self.assertEqual(cfn_exp.num_qubits, add_qubits + num_qubits)
# case OperatorStateFn, with OperatorBase primitive, in our case CircuitStateFn
osfn = OperatorStateFn(cfn)
osfn_exp = osfn._expand_dim(add_qubits)
self.assertEqual(osfn_exp.num_qubits, add_qubits + num_qubits)
# case DictStateFn
dsfn = DictStateFn("1" * num_qubits, is_measurement=True)
self.assertEqual(dsfn.num_qubits, num_qubits)
dsfn_exp = dsfn._expand_dim(add_qubits)
self.assertEqual(dsfn_exp.num_qubits, num_qubits + add_qubits)
# case VectorStateFn
vsfn = VectorStateFn(np.ones(2**num_qubits, dtype=complex))
self.assertEqual(vsfn.num_qubits, num_qubits)
vsfn_exp = vsfn._expand_dim(add_qubits)
self.assertEqual(vsfn_exp.num_qubits, num_qubits + add_qubits)
def test_permute_on_state_fn(self):
"""Test if StateFns permute are consistent."""
num_qubits = 4
dim = 2**num_qubits
primitive_list = [1.0 / (i + 1) for i in range(dim)]
primitive_dict = {format(i, "b").zfill(num_qubits): 1.0 / (i + 1) for i in range(dim)}
dict_fn = DictStateFn(primitive=primitive_dict, is_measurement=True)
vec_fn = VectorStateFn(primitive=primitive_list, is_measurement=True)
# check if dict_fn and vec_fn are equivalent
equivalent = np.allclose(dict_fn.to_matrix(), vec_fn.to_matrix())
self.assertTrue(equivalent)
# permute
indices = [2, 3, 0, 1]
permute_dict = dict_fn.permute(indices)
permute_vect = vec_fn.permute(indices)
equivalent = np.allclose(permute_dict.to_matrix(), permute_vect.to_matrix())
self.assertTrue(equivalent)
def test_compose_consistency(self):
"""Test if PrimitiveOp @ ComposedOp is consistent with ComposedOp @ PrimitiveOp."""
# PauliOp
op1 = X ^ Y ^ Z
op2 = X ^ Y ^ Z
op3 = (X ^ Y ^ Z).to_circuit_op()
comp1 = op1 @ ComposedOp([op2, op3])
comp2 = ComposedOp([op3, op2]) @ op1
self.assertListEqual(comp1.oplist, list(reversed(comp2.oplist)))
# CircitOp
op1 = op1.to_circuit_op()
op2 = op2.to_circuit_op()
op3 = op3.to_matrix_op()
comp1 = op1 @ ComposedOp([op2, op3])
comp2 = ComposedOp([op3, op2]) @ op1
self.assertListEqual(comp1.oplist, list(reversed(comp2.oplist)))
# MatrixOp
op1 = op1.to_matrix_op()
op2 = op2.to_matrix_op()
op3 = op3.to_pauli_op()
comp1 = op1 @ ComposedOp([op2, op3])
comp2 = ComposedOp([op3, op2]) @ op1
self.assertListEqual(comp1.oplist, list(reversed(comp2.oplist)))
def test_compose_with_indices(self):
"""Test compose method using its permutation feature."""
pauli_op = X ^ Y ^ Z
circuit_op = T ^ H
matrix_op = (X ^ Y ^ H ^ T).to_matrix_op()
evolved_op = EvolvedOp(matrix_op)
# composition of PrimitiveOps
num_qubits = 4
primitive_op = pauli_op @ circuit_op @ matrix_op
composed_op = pauli_op @ circuit_op @ evolved_op
self.assertEqual(primitive_op.num_qubits, num_qubits)
self.assertEqual(composed_op.num_qubits, num_qubits)
# with permutation
num_qubits = 5
indices = [1, 4]
permuted_primitive_op = evolved_op @ circuit_op.permute(indices) @ pauli_op @ matrix_op
composed_primitive_op = (
evolved_op @ pauli_op.compose(circuit_op, permutation=indices, front=True) @ matrix_op
)
self.assertTrue(
np.allclose(permuted_primitive_op.to_matrix(), composed_primitive_op.to_matrix())
)
self.assertEqual(num_qubits, permuted_primitive_op.num_qubits)
# ListOp
num_qubits = 6
tensored_op = TensoredOp([pauli_op, circuit_op])
summed_op = pauli_op + circuit_op.permute([2, 1])
composed_op = circuit_op @ evolved_op @ matrix_op
list_op = summed_op @ composed_op.compose(
tensored_op, permutation=[1, 2, 3, 5, 4], front=True
)
self.assertEqual(num_qubits, list_op.num_qubits)
num_qubits = 4
circuit_fn = CircuitStateFn(primitive=circuit_op.primitive, is_measurement=True)
operator_fn = OperatorStateFn(primitive=circuit_op ^ circuit_op, is_measurement=True)
no_perm_op = circuit_fn @ operator_fn
self.assertEqual(no_perm_op.num_qubits, num_qubits)
indices = [0, 4]
perm_op = operator_fn.compose(circuit_fn, permutation=indices, front=True)
self.assertEqual(perm_op.num_qubits, max(indices) + 1)
# StateFn
num_qubits = 3
dim = 2**num_qubits
vec = [1.0 / (i + 1) for i in range(dim)]
dic = {format(i, "b").zfill(num_qubits): 1.0 / (i + 1) for i in range(dim)}
is_measurement = True
op_state_fn = OperatorStateFn(matrix_op, is_measurement=is_measurement) # num_qubit = 4
vec_state_fn = VectorStateFn(vec, is_measurement=is_measurement) # 3
dic_state_fn = DictStateFn(dic, is_measurement=is_measurement) # 3
circ_state_fn = CircuitStateFn(circuit_op.to_circuit(), is_measurement=is_measurement) # 2
composed_op = op_state_fn @ vec_state_fn @ dic_state_fn @ circ_state_fn
self.assertEqual(composed_op.num_qubits, op_state_fn.num_qubits)
# with permutation
perm = [2, 4, 6]
composed = (
op_state_fn
@ dic_state_fn.compose(vec_state_fn, permutation=perm, front=True)
@ circ_state_fn
)
self.assertEqual(composed.num_qubits, max(perm) + 1)
def test_summed_op_equals(self):
"""Test corner cases of SummedOp's equals function."""
with self.subTest("multiplicative factor"):
self.assertEqual(2 * X, X + X)
with self.subTest("commutative"):
self.assertEqual(X + Z, Z + X)
with self.subTest("circuit and paulis"):
z = CircuitOp(ZGate())
self.assertEqual(Z + z, z + Z)
with self.subTest("matrix op and paulis"):
z = MatrixOp([[1, 0], [0, -1]])
self.assertEqual(Z + z, z + Z)
with self.subTest("matrix multiplicative"):
z = MatrixOp([[1, 0], [0, -1]])
self.assertEqual(2 * z, z + z)
with self.subTest("parameter coefficients"):
expr = Parameter("theta")
z = MatrixOp([[1, 0], [0, -1]])
self.assertEqual(expr * z, expr * z)
with self.subTest("different coefficient types"):
expr = Parameter("theta")
z = MatrixOp([[1, 0], [0, -1]])
self.assertNotEqual(expr * z, 2 * z)
with self.subTest("additions aggregation"):
z = MatrixOp([[1, 0], [0, -1]])
a = z + z + Z
b = 2 * z + Z
c = z + Z + z
self.assertEqual(a, b)
self.assertEqual(b, c)
self.assertEqual(a, c)
def test_circuit_compose_register_independent(self):
"""Test that CircuitOp uses combines circuits independent of the register.
I.e. that is uses ``QuantumCircuit.compose`` over ``combine`` or ``extend``.
"""
op = Z ^ 2
qr = QuantumRegister(2, "my_qr")
circuit = QuantumCircuit(qr)
composed = op.compose(CircuitOp(circuit))
self.assertEqual(composed.num_qubits, 2)
def test_matrix_op_conversions(self):
"""Test to reveal QiskitError when to_instruction or to_circuit method is called on
parameterized matrix op."""
m = np.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]])
matrix_op = MatrixOp(m, Parameter("beta"))
for method in ["to_instruction", "to_circuit"]:
with self.subTest(method):
# QiskitError: multiplication of Operator with ParameterExpression isn't implemented
self.assertRaises(QiskitError, getattr(matrix_op, method))
def test_list_op_to_circuit(self):
"""Test if unitary ListOps transpile to circuit."""
# generate unitary matrices of dimension 2,4,8, seed is fixed
np.random.seed(233423)
u2 = unitary_group.rvs(2)
u4 = unitary_group.rvs(4)
u8 = unitary_group.rvs(8)
# pauli matrices as numpy.arrays
x = np.array([[0.0, 1.0], [1.0, 0.0]])
y = np.array([[0.0, -1.0j], [1.0j, 0.0]])
z = np.array([[1.0, 0.0], [0.0, -1.0]])
# create MatrixOp and CircuitOp out of matrices
op2 = MatrixOp(u2)
op4 = MatrixOp(u4)
op8 = MatrixOp(u8)
c2 = op2.to_circuit_op()
# algorithm using only matrix operations on numpy.arrays
xu4 = np.kron(x, u4)
zc2 = np.kron(z, u2)
zc2y = np.kron(zc2, y)
matrix = np.matmul(xu4, zc2y)
matrix = np.matmul(matrix, u8)
matrix = np.kron(matrix, u2)
operator = Operator(matrix)
# same algorithm as above, but using PrimitiveOps
list_op = ((X ^ op4) @ (Z ^ c2 ^ Y) @ op8) ^ op2
circuit = list_op.to_circuit()
# verify that ListOp.to_circuit() outputs correct quantum circuit
self.assertTrue(operator.equiv(circuit), "ListOp.to_circuit() outputs wrong circuit!")
def test_composed_op_to_circuit(self):
"""
Test if unitary ComposedOp transpile to circuit and represents expected operator.
Test if to_circuit on non-unitary ListOp raises exception.
"""
x = np.array([[0.0, 1.0], [1.0, 0.0]]) # Pauli X as numpy array
y = np.array([[0.0, -1.0j], [1.0j, 0.0]]) # Pauli Y as numpy array
m1 = np.array([[0, 0, 1, 0], [0, 0, 0, -1], [0, 0, 0, 0], [0, 0, 0, 0]]) # non-unitary
m2 = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [0, -1, 0, 0]]) # non-unitary
m_op1 = MatrixOp(m1)
m_op2 = MatrixOp(m2)
pm1 = (X ^ Y) ^ m_op1 # non-unitary TensoredOp
pm2 = (X ^ Y) ^ m_op2 # non-unitary TensoredOp
self.assertRaises(ExtensionError, pm1.to_circuit)
self.assertRaises(ExtensionError, pm2.to_circuit)
summed_op = pm1 + pm2 # unitary SummedOp([TensoredOp, TensoredOp])
circuit = summed_op.to_circuit() # should transpile without any exception
# same algorithm that leads to summed_op above, but using only arrays and matrix operations
unitary = np.kron(np.kron(x, y), m1 + m2)
self.assertTrue(Operator(unitary).equiv(circuit))
def test_pauli_op_to_circuit(self):
"""Test PauliOp.to_circuit()"""
with self.subTest("single Pauli"):
pauli = PauliOp(Pauli("Y"))
expected = QuantumCircuit(1)
expected.y(0)
self.assertEqual(pauli.to_circuit(), expected)
with self.subTest("single Pauli with phase"):
pauli = PauliOp(Pauli("-iX"))
expected = QuantumCircuit(1)
expected.x(0)
expected.global_phase = -pi / 2
self.assertEqual(Operator(pauli.to_circuit()), Operator(expected))
with self.subTest("two qubit"):
pauli = PauliOp(Pauli("IX"))
expected = QuantumCircuit(2)
expected.pauli("IX", range(2))
self.assertEqual(pauli.to_circuit(), expected)
expected = QuantumCircuit(2)
expected.x(0)
self.assertEqual(pauli.to_circuit().decompose(), expected)
with self.subTest("Pauli identity"):
pauli = PauliOp(Pauli("I"))
expected = QuantumCircuit(1)
self.assertEqual(pauli.to_circuit(), expected)
with self.subTest("two qubit with phase"):
pauli = PauliOp(Pauli("iXZ"))
expected = QuantumCircuit(2)
expected.pauli("XZ", range(2))
expected.global_phase = pi / 2
self.assertEqual(pauli.to_circuit(), expected)
expected = QuantumCircuit(2)
expected.z(0)
expected.x(1)
expected.global_phase = pi / 2
self.assertEqual(pauli.to_circuit().decompose(), expected)
def test_op_to_circuit_with_parameters(self):
"""On parameterized SummedOp, to_matrix_op returns ListOp, instead of MatrixOp. To avoid
the infinite recursion, OpflowError is raised."""
m1 = np.array([[0, 0, 1, 0], [0, 0, 0, -1], [0, 0, 0, 0], [0, 0, 0, 0]]) # non-unitary
m2 = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [0, -1, 0, 0]]) # non-unitary
op1_with_param = MatrixOp(m1, Parameter("alpha")) # non-unitary
op2_with_param = MatrixOp(m2, Parameter("beta")) # non-unitary
summed_op_with_param = op1_with_param + op2_with_param # unitary
# should raise OpflowError error
self.assertRaises(OpflowError, summed_op_with_param.to_circuit)
def test_permute_list_op_with_inconsistent_num_qubits(self):
"""Test if permute raises error if ListOp contains operators with different num_qubits."""
list_op = ListOp([X, X ^ X])
self.assertRaises(OpflowError, list_op.permute, [0, 1])
@data(Z, CircuitOp(ZGate()), MatrixOp([[1, 0], [0, -1]]))
def test_op_indent(self, op):
"""Test that indentation correctly adds INDENTATION at the beginning of each line"""
initial_str = str(op)
indented_str = op._indent(initial_str)
starts_with_indent = indented_str.startswith(op.INDENTATION)
self.assertTrue(starts_with_indent)
indented_str_content = (indented_str[len(op.INDENTATION) :]).split(f"\n{op.INDENTATION}")
self.assertListEqual(indented_str_content, initial_str.split("\n"))
def test_composed_op_immutable_under_eval(self):
"""Test ``ComposedOp.eval`` does not change the operator instance."""
op = 2 * ComposedOp([X])
_ = op.eval()
# previous bug: after op.eval(), op was 2 * ComposedOp([2 * X])
self.assertEqual(op, 2 * ComposedOp([X]))
def test_op_parameters(self):
"""Test that Parameters are stored correctly"""
phi = Parameter("φ")
theta = ParameterVector(name="θ", length=2)
qc = QuantumCircuit(2)
qc.rz(phi, 0)
qc.rz(phi, 1)
for i in range(2):
qc.rx(theta[i], i)
qc.h(0)
qc.x(1)
l = Parameter("λ")
op = PrimitiveOp(qc, coeff=l)
params = {phi, l, *theta.params}
self.assertEqual(params, op.parameters)
self.assertEqual(params, StateFn(op).parameters)
self.assertEqual(params, StateFn(qc, coeff=l).parameters)
def test_list_op_parameters(self):
"""Test that Parameters are stored correctly in a List Operator"""
lam = Parameter("λ")
phi = Parameter("φ")
omega = Parameter("ω")
mat_op = PrimitiveOp([[0, 1], [1, 0]], coeff=omega)
qc = QuantumCircuit(1)
qc.rx(phi, 0)
qc_op = PrimitiveOp(qc)
op1 = SummedOp([mat_op, qc_op])
params = [phi, omega]
self.assertEqual(op1.parameters, set(params))
# check list nesting case
op2 = PrimitiveOp([[1, 0], [0, -1]], coeff=lam)
list_op = ListOp([op1, op2])
params.append(lam)
self.assertEqual(list_op.parameters, set(params))
@data(
VectorStateFn([1, 0]),
CircuitStateFn(QuantumCircuit(1)),
OperatorStateFn(I),
OperatorStateFn(MatrixOp([[1, 0], [0, 1]])),
OperatorStateFn(CircuitOp(QuantumCircuit(1))),
)
def test_statefn_eval(self, op):
"""Test calling eval on StateFn returns the statevector."""
expected = Statevector([1, 0])
self.assertEqual(op.eval().primitive, expected)
def test_sparse_eval(self):
"""Test calling eval on a DictStateFn returns a sparse statevector."""
op = DictStateFn({"0": 1})
expected = scipy.sparse.csr_matrix([[1, 0]])
self.assertFalse((op.eval().primitive != expected).toarray().any())
def test_sparse_to_dict(self):
"""Test converting a sparse vector state function to a dict state function."""
isqrt2 = 1 / np.sqrt(2)
sparse = scipy.sparse.csr_matrix([[0, isqrt2, 0, isqrt2]])
sparse_fn = SparseVectorStateFn(sparse)
dict_fn = DictStateFn({"01": isqrt2, "11": isqrt2})
with self.subTest("sparse to dict"):
self.assertEqual(dict_fn, sparse_fn.to_dict_fn())
with self.subTest("dict to sparse"):
self.assertEqual(dict_fn.to_spmatrix_op(), sparse_fn)
def test_to_circuit_op(self):
"""Test to_circuit_op method."""
vector = np.array([2, 2])
vsfn = VectorStateFn([1, 1], coeff=2)
dsfn = DictStateFn({"0": 1, "1": 1}, coeff=2)
for sfn in [vsfn, dsfn]:
np.testing.assert_array_almost_equal(sfn.to_circuit_op().eval().primitive.data, vector)
def test_invalid_primitive(self):
"""Test invalid MatrixOp construction"""
msg = (
"MatrixOp can only be instantiated with "
"['list', 'ndarray', 'spmatrix', 'Operator'], not "
)
with self.assertRaises(TypeError) as cm:
_ = MatrixOp("invalid")
self.assertEqual(str(cm.exception), msg + "'str'")
with self.assertRaises(TypeError) as cm:
_ = MatrixOp(None)
self.assertEqual(str(cm.exception), msg + "'NoneType'")
with self.assertRaises(TypeError) as cm:
_ = MatrixOp(2.0)
self.assertEqual(str(cm.exception), msg + "'float'")
def test_summedop_equals(self):
"""Test SummedOp.equals"""
ops = [Z, CircuitOp(ZGate()), MatrixOp([[1, 0], [0, -1]]), Zero, Minus]
sum_op = sum(ops + [ListOp(ops)])
self.assertEqual(sum_op, sum_op)
self.assertEqual(sum_op + sum_op, 2 * sum_op)
self.assertEqual(sum_op + sum_op + sum_op, 3 * sum_op)
ops2 = [Z, CircuitOp(ZGate()), MatrixOp([[1, 0], [0, 1]]), Zero, Minus]
sum_op2 = sum(ops2 + [ListOp(ops)])
self.assertNotEqual(sum_op, sum_op2)
self.assertEqual(sum_op2, sum_op2)
sum_op3 = sum(ops)
self.assertNotEqual(sum_op, sum_op3)
self.assertNotEqual(sum_op2, sum_op3)
self.assertEqual(sum_op3, sum_op3)
def test_empty_listops(self):
"""Test reduce and eval on ListOp with empty oplist."""
with self.subTest("reduce empty ComposedOp "):
self.assertEqual(ComposedOp([]).reduce(), ComposedOp([]))
with self.subTest("reduce empty TensoredOp "):
self.assertEqual(TensoredOp([]).reduce(), TensoredOp([]))
with self.subTest("eval empty ComposedOp "):
self.assertEqual(ComposedOp([]).eval(), 0.0)
with self.subTest("eval empty TensoredOp "):
self.assertEqual(TensoredOp([]).eval(), 0.0)
def test_composed_op_to_matrix_with_coeff(self):
"""Test coefficients are properly handled.
Regression test of Qiskit/qiskit-terra#9283.
"""
x = MatrixOp(X.to_matrix())
composed = 0.5 * (x @ X)
expected = 0.5 * np.eye(2)
np.testing.assert_almost_equal(composed.to_matrix(), expected)
def test_composed_op_to_matrix_with_vector(self):
"""Test a matrix-vector composed op can be cast to matrix.
Regression test of Qiskit/qiskit-terra#9283.
"""
x = MatrixOp(X.to_matrix())
composed = x @ Zero
expected = np.array([0, 1])
np.testing.assert_almost_equal(composed.to_matrix(), expected)
def test_tensored_op_to_matrix(self):
"""Test tensored operators to matrix works correctly with a global coefficient.
Regression test of Qiskit/qiskit-terra#9398.
"""
op = TensoredOp([X, I], coeff=0.5)
expected = 1 / 2 * np.kron(X.to_matrix(), I.to_matrix())
np.testing.assert_almost_equal(op.to_matrix(), expected)
class TestOpMethods(QiskitOpflowTestCase):
"""Basic method tests."""
def test_listop_num_qubits(self):
"""Test that ListOp.num_qubits checks that all operators have the same number of qubits."""
op = ListOp([X ^ Y, Y ^ Z])
with self.subTest("All operators have the same numbers of qubits"):
self.assertEqual(op.num_qubits, 2)
op = ListOp([X ^ Y, Y])
with self.subTest("Operators have different numbers of qubits"):
with self.assertRaises(ValueError):
op.num_qubits # pylint: disable=pointless-statement
with self.assertRaises(ValueError):
X @ op # pylint: disable=pointless-statement
def test_is_hermitian(self):
"""Test is_hermitian method."""
with self.subTest("I"):
self.assertTrue(I.is_hermitian())
with self.subTest("X"):
self.assertTrue(X.is_hermitian())
with self.subTest("Y"):
self.assertTrue(Y.is_hermitian())
with self.subTest("Z"):
self.assertTrue(Z.is_hermitian())
with self.subTest("XY"):
self.assertFalse((X @ Y).is_hermitian())
with self.subTest("CX"):
self.assertTrue(CX.is_hermitian())
with self.subTest("T"):
self.assertFalse(T.is_hermitian())
@ddt
class TestListOpMethods(QiskitOpflowTestCase):
"""Test ListOp accessing methods"""
@data(ListOp, SummedOp, ComposedOp, TensoredOp)
def test_indexing(self, list_op_type):
"""Test indexing and slicing"""
coeff = 3 + 0.2j
states_op = list_op_type([X, Y, Z, I], coeff=coeff)
single_op = states_op[1]
self.assertIsInstance(single_op, OperatorBase)
self.assertNotIsInstance(single_op, ListOp)
list_one_element = states_op[1:2]
self.assertIsInstance(list_one_element, list_op_type)
self.assertEqual(len(list_one_element), 1)
self.assertEqual(list_one_element[0], Y)
list_two_elements = states_op[::2]
self.assertIsInstance(list_two_elements, list_op_type)
self.assertEqual(len(list_two_elements), 2)
self.assertEqual(list_two_elements[0], X)
self.assertEqual(list_two_elements[1], Z)
self.assertEqual(list_one_element.coeff, coeff)
self.assertEqual(list_two_elements.coeff, coeff)
class TestListOpComboFn(QiskitOpflowTestCase):
"""Test combo fn is propagated."""
def setUp(self):
super().setUp()
self.combo_fn = lambda x: [x_i**2 for x_i in x]
self.listop = ListOp([X], combo_fn=self.combo_fn)
def assertComboFnPreserved(self, processed_op):
"""Assert the quadratic combo_fn is preserved."""
x = [1, 2, 3]
self.assertListEqual(processed_op.combo_fn(x), self.combo_fn(x))
def test_at_conversion(self):
"""Test after conversion the combo_fn is preserved."""
for method in ["to_matrix_op", "to_pauli_op", "to_circuit_op"]:
with self.subTest(method):
converted = getattr(self.listop, method)()
self.assertComboFnPreserved(converted)
def test_after_mul(self):
"""Test after multiplication the combo_fn is preserved."""
self.assertComboFnPreserved(2 * self.listop)
def test_at_traverse(self):
"""Test after traversing the combo_fn is preserved."""
def traverse_fn(op):
return -op
traversed = self.listop.traverse(traverse_fn)
self.assertComboFnPreserved(traversed)
def test_after_adjoint(self):
"""Test after traversing the combo_fn is preserved."""
self.assertComboFnPreserved(self.listop.adjoint())
def test_after_reduce(self):
"""Test after reducing the combo_fn is preserved."""
self.assertComboFnPreserved(self.listop.reduce())
def pauli_group_labels(nq, full_group=True):
"""Generate list of the N-qubit pauli group string labels"""
labels = ["".join(i) for i in itertools.product(("I", "X", "Y", "Z"), repeat=nq)]
if full_group:
labels = ["".join(i) for i in itertools.product(("", "-i", "-", "i"), labels)]
return labels
def operator_from_label(label):
"""Construct operator from full Pauli group label"""
return Operator(Pauli(label))
@ddt
class TestPauliOp(QiskitOpflowTestCase):
"""PauliOp tests."""
def test_construct(self):
"""constructor test"""
pauli = Pauli("XYZX")
coeff = 3.0
pauli_op = PauliOp(pauli, coeff)
self.assertIsInstance(pauli_op, PauliOp)
self.assertEqual(pauli_op.primitive, pauli)
self.assertEqual(pauli_op.coeff, coeff)
self.assertEqual(pauli_op.num_qubits, 4)
def test_add(self):
"""add test"""
pauli_sum = X + Y
summed_op = SummedOp([X, Y])
self.assertEqual(pauli_sum, summed_op)
a = Parameter("a")
b = Parameter("b")
actual = PauliOp(Pauli("X"), a) + PauliOp(Pauli("Y"), b)
expected = SummedOp([PauliOp(Pauli("X"), a), PauliOp(Pauli("Y"), b)])
self.assertEqual(actual, expected)
def test_adjoint(self):
"""adjoint test"""
pauli_op = PauliOp(Pauli("XYZX"), coeff=3)
expected = PauliOp(Pauli("XYZX"), coeff=3)
self.assertEqual(~pauli_op, expected)
pauli_op = PauliOp(Pauli("XXY"), coeff=2j)
expected = PauliOp(Pauli("XXY"), coeff=-2j)
self.assertEqual(~pauli_op, expected)
pauli_op = PauliOp(Pauli("XYZX"), coeff=2 + 3j)
expected = PauliOp(Pauli("XYZX"), coeff=2 - 3j)
self.assertEqual(~pauli_op, expected)
pauli_op = PauliOp(Pauli("iXYZX"), coeff=2 + 3j)
expected = PauliOp(Pauli("-iXYZX"), coeff=2 - 3j)
self.assertEqual(~pauli_op, expected)
@data(*itertools.product(pauli_group_labels(2, full_group=True), repeat=2))
@unpack
def test_compose(self, label1, label2):
"""compose test"""
p1 = PauliOp(Pauli(label1))
p2 = PauliOp(Pauli(label2))
value = Operator(p1 @ p2)
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1 @ op2
self.assertEqual(value, target)
def test_equals(self):
"""equality test"""
self.assertEqual(I @ X, X)
self.assertEqual(X, I @ X)
theta = Parameter("theta")
pauli_op = theta * X ^ Z
expected = PauliOp(
Pauli("XZ"),
coeff=1.0 * theta,
)
self.assertEqual(pauli_op, expected)
def test_eval(self):
"""eval test"""
target0 = (X ^ Y ^ Z).eval("000")
target1 = (X ^ Y ^ Z).eval(Zero ^ 3)
expected = DictStateFn({"110": 1j})
self.assertEqual(target0, expected)
self.assertEqual(target1, expected)
def test_exp_i(self):
"""exp_i test"""
target = (2 * X ^ Z).exp_i()
expected = EvolvedOp(PauliOp(Pauli("XZ"), coeff=2.0), coeff=1.0)
self.assertEqual(target, expected)
@data(([1, 2, 4], "XIYZI"), ([2, 1, 0], "ZYX"))
@unpack
def test_permute(self, permutation, expected_pauli):
"""Test the permute method."""
pauli_op = PauliOp(Pauli("XYZ"), coeff=1.0)
expected = PauliOp(Pauli(expected_pauli), coeff=1.0)
permuted = pauli_op.permute(permutation)
with self.subTest(msg="test permutated object"):
self.assertEqual(permuted, expected)
with self.subTest(msg="test original object is unchanged"):
original = PauliOp(Pauli("XYZ"))
self.assertEqual(pauli_op, original)
def test_primitive_strings(self):
"""primitive strings test"""
target = (2 * X ^ Z).primitive_strings()
expected = {"Pauli"}
self.assertEqual(target, expected)
def test_tensor(self):
"""tensor test"""
pauli_op = X ^ Y ^ Z
tensored_op = PauliOp(Pauli("XYZ"))
self.assertEqual(pauli_op, tensored_op)
def test_to_instruction(self):
"""to_instruction test"""
target = (X ^ Z).to_instruction()
qc = QuantumCircuit(2)
qc.u(0, 0, np.pi, 0)
qc.u(np.pi, 0, np.pi, 1)
qc_out = QuantumCircuit(2)
qc_out.append(target, qc_out.qubits)
qc_out = transpile(qc_out, basis_gates=["u"])
self.assertEqual(qc, qc_out)
def test_to_matrix(self):
"""to_matrix test"""
target = (X ^ Y).to_matrix()
expected = np.kron(np.array([[0.0, 1.0], [1.0, 0.0]]), np.array([[0.0, -1j], [1j, 0.0]]))
np.testing.assert_array_equal(target, expected)
def test_to_spmatrix(self):
"""to_spmatrix test"""
target = X ^ Y
expected = csr_matrix(
np.kron(np.array([[0.0, 1.0], [1.0, 0.0]]), np.array([[0.0, -1j], [1j, 0.0]]))
)
self.assertEqual((target.to_spmatrix() - expected).nnz, 0)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# Copyright 2022-2023 Ohad Lev.
# 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,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
`SATInterface` class.
"""
import os
import json
from typing import List, Tuple, Union, Optional, Dict, Any
from sys import stdout
from datetime import datetime
from hashlib import sha256
from qiskit import transpile, QuantumCircuit, qpy
from qiskit.result.counts import Counts
from qiskit.visualization.circuit.text import TextDrawing
from qiskit.providers.backend import Backend
from qiskit.transpiler.passes import RemoveBarriers
from IPython import display
from matplotlib.figure import Figure
from sat_circuits_engine.util import timer_dec, timestamp, flatten_circuit
from sat_circuits_engine.util.settings import DATA_PATH, TRANSPILE_KWARGS
from sat_circuits_engine.circuit import GroverConstraintsOperator, SATCircuit
from sat_circuits_engine.constraints_parse import ParsedConstraints
from sat_circuits_engine.interface.circuit_decomposition import decompose_operator
from sat_circuits_engine.interface.counts_visualization import plot_histogram
from sat_circuits_engine.interface.translator import ConstraintsTranslator
from sat_circuits_engine.classical_processing import (
find_iterations_unknown,
calc_iterations,
ClassicalVerifier,
)
from sat_circuits_engine.interface.interactive_inputs import (
interactive_operator_inputs,
interactive_solutions_num_input,
interactive_run_input,
interactive_backend_input,
interactive_shots_input,
)
# Local globlas for visualization of charts and diagrams
IFRAME_WIDTH = "100%"
IFRAME_HEIGHT = "700"
class SATInterface:
"""
An interface for building, running and mining data from n-SAT problems quantum circuits.
There are 2 options to use this class:
(1) Using an interactive interface (intuitive but somewhat limited) - for this
just initiate a bare instance of this class: `SATInterface()`.
(2) Using the API defined by this class, that includes the following methods:
* The following descriptions are partial, for full annotations see the methods' docstrings.
- `__init__`: an instance of `SATInterface must be initiated with exactly 1 combination:
(a) (high_level_constraints_string + high_level_vars) - for constraints
in a high-level format.
(b) (num_input_qubits + constraints_string) - for constraints
in a low-level foramt.
* For formats annotations see `constriants_format.ipynb` in the main directory.
- `obtain_grover_operator`: obtains the suitable grover operator for the constraints.
- `save_display_grover_operator`: saves and displays data generated
by the `obtain_grover_operator` method.
- `obtain_overall_circuit`: obtains the suitable overall SAT circuit.
- `save_display_overall_circuit: saves and displays data generated
by the `obtain_overall_circuit` method.
- `run_overall_circuit`: executes the overall SAT circuit.
- `save_display_results`: saves and displays data generated
by the `run_overall_circuit` method.
It is very recommended to go through `demos.ipynb` that demonstrates the various optional uses
of this class, in addition to reading `constraints_format.ipynb`, which is a must for using
this package properly. Both notebooks are in ther main directory.
"""
def __init__(
self,
num_input_qubits: Optional[int] = None,
constraints_string: Optional[str] = None,
high_level_constraints_string: Optional[str] = None,
high_level_vars: Optional[Dict[str, int]] = None,
name: Optional[str] = None,
save_data: Optional[bool] = True,
) -> None:
"""
Accepts the combination of paramters:
(high_level_constraints_string + high_level_vars) or (num_input_qubits + constraints_string).
Exactly one combination is accepted.
In other cases either an iteractive user interface will be called to take user's inputs,
or an exception will be raised due to misuse of the API.
Args:
num_input_qubits (Optional[int] = None): number of input qubits.
constraints_string (Optional[str] = None): a string of constraints in a low-level format.
high_level_constraints_string (Optional[str] = None): a string of constraints in a
high-level format.
high_level_vars (Optional[Dict[str, int]] = None): a dictionary that configures
the high-level variables - keys are names and values are bits-lengths.
name (Optional[str] = None): a name for this object, if None than the
generic name "SAT" is given automatically.
save_data (Optional[bool] = True): if True, saves all data and metadata generated by this
class to a unique data folder (by using the `save_XXX` methods of this class).
Raises:
SyntaxError - if a forbidden combination of arguments has been provided.
"""
if name is None:
name = "SAT"
self.name = name
# Creating a directory for data to be saved
if save_data:
self.time_created = timestamp(datetime.now())
self.dir_path = f"{DATA_PATH}{self.time_created}_{self.name}/"
os.mkdir(self.dir_path)
print(f"Data will be saved into '{self.dir_path}'.")
# Initial metadata, more to be added by this class' `save_XXX` methods
self.metadata = {
"name": self.name,
"datetime": self.time_created,
"num_input_qubits": num_input_qubits,
"constraints_string": constraints_string,
"high_level_constraints_string": high_level_constraints_string,
"high_level_vars": high_level_vars,
}
self.update_metadata()
# Identifying user's platform, for visualization purposes
self.identify_platform()
# In the case of low-level constraints format, that is the default value
self.high_to_low_map = None
# Case A - interactive interface
if (num_input_qubits is None or constraints_string is None) and (
high_level_constraints_string is None or high_level_vars is None
):
self.interactive_interface()
# Case B - API
else:
self.high_level_constraints_string = high_level_constraints_string
self.high_level_vars = high_level_vars
# Case B.1 - high-level format constraints inputs
if num_input_qubits is None or constraints_string is None:
self.num_input_qubits = sum(self.high_level_vars.values())
self.high_to_low_map, self.constraints_string = ConstraintsTranslator(
self.high_level_constraints_string, self.high_level_vars
).translate()
# Case B.2 - low-level format constraints inputs
elif num_input_qubits is not None and constraints_string is not None:
self.num_input_qubits = num_input_qubits
self.constraints_string = constraints_string
# Misuse
else:
raise SyntaxError(
"SATInterface accepts the combination of paramters:"
"(high_level_constraints_string + high_level_vars) or "
"(num_input_qubits + constraints_string). "
"Exactly one combination is accepted, not both."
)
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
def update_metadata(self, update_metadata: Optional[Dict[str, Any]] = None) -> None:
"""
Updates the metadata file (in the unique data folder of a given `SATInterface` instance).
Args:
update_metadata (Optional[Dict[str, Any]] = None):
- If None - just dumps `self.metadata` into the metadata JSON file.
- If defined - updates the `self.metadata` attribute and then dumps it.
"""
if update_metadata is not None:
self.metadata.update(update_metadata)
with open(f"{self.dir_path}metadata.json", "w") as metadata_file:
json.dump(self.metadata, metadata_file, indent=4)
def identify_platform(self) -> None:
"""
Identifies user's platform.
Writes True to `self.jupyter` for Jupyter notebook, False for terminal.
"""
# If True then the platform is a terminal/command line/shell
if stdout.isatty():
self.jupyter = False
# If False, we assume the platform is a Jupyter notebook
else:
self.jupyter = True
def output_to_platform(
self,
*,
title: str,
output_terminal: Union[TextDrawing, str],
output_jupyter: Union[Figure, str],
display_both_on_jupyter: Optional[bool] = False,
) -> None:
"""
Displays output to user's platform.
Args:
title (str): a title for the output.
output_terminal (Union[TextDrawing, str]): text to print for a terminal platform.
output_jupyter: (Union[Figure, str]): objects to display for a Jupyter notebook platform.
can handle `Figure` matplotlib objects or strings of paths to IFrame displayable file,
e.g PDF files.
display_both_on_jupyter (Optional[bool] = False): if True, displays both
`output_terminal` and `output_jupyter` in a Jupyter notebook platform.
Raises:
TypeError - in the case of misusing the `output_jupyter` argument.
"""
print()
print(title)
if self.jupyter:
if isinstance(output_jupyter, str):
display.display(display.IFrame(output_jupyter, width=IFRAME_WIDTH, height=IFRAME_HEIGHT))
elif isinstance(output_jupyter, Figure):
display.display(output_jupyter)
else:
raise TypeError("output_jupyter must be an str (path to image file) or a Figure object.")
if display_both_on_jupyter:
print(output_terminal)
else:
print(output_terminal)
def interactive_interface(self) -> None:
"""
An interactive CLI that allows exploiting most (but not all) of the package's features.
Uses functions of the form `interactive_XXX_inputs` from the `interactive_inputs.py` module.
Divided into 3 main stages:
1. Obtaining Grover's operator for the SAT problem.
2. Obtaining the overall SAT cirucit.
3. Executing the circuit and parsing the results.
The interface is built in a modular manner such that a user can halt at any stage.
The defualt settings for the interactive user intreface are:
1. `name = "SAT"`.
2. `save_data = True`.
3. `display = True`.
4. `transpile_kwargs = {'basis_gates': ['u', 'cx'], 'optimization_level': 3}`.
5. Backends are limited to those defined in the global-constant-like function `BACKENDS`:
- Those are the local `aer_simulator` and the remote `ibmq_qasm_simulator` for now.
Due to these default settings the interactive CLI is somewhat restrictive,
for full flexibility a user should use the API and not the CLI.
"""
# Handling operator part
operator_inputs = interactive_operator_inputs()
self.num_input_qubits = operator_inputs["num_input_qubits"]
self.high_to_low_map = operator_inputs["high_to_low_map"]
self.constraints_string = operator_inputs["constraints_string"]
self.high_level_constraints_string = operator_inputs["high_level_constraints_string"]
self.high_level_vars = operator_inputs["high_level_vars"]
self.parsed_constraints = ParsedConstraints(
self.constraints_string, self.high_level_constraints_string
)
self.update_metadata(
{
"num_input_qubits": self.num_input_qubits,
"constraints_string": self.constraints_string,
"high_level_constraints_string": self.high_level_constraints_string,
"high_level_vars": self.high_level_vars,
}
)
obtain_grover_operator_output = self.obtain_grover_operator()
self.save_display_grover_operator(obtain_grover_operator_output)
# Handling overall circuit part
solutions_num = interactive_solutions_num_input()
if solutions_num is not None:
backend = None
if solutions_num == -1:
backend = interactive_backend_input()
overall_circuit_data = self.obtain_overall_sat_circuit(
obtain_grover_operator_output["operator"], solutions_num, backend
)
self.save_display_overall_circuit(overall_circuit_data)
# Handling circuit execution part
if interactive_run_input():
if backend is None:
backend = interactive_backend_input()
shots = interactive_shots_input()
counts_parsed = self.run_overall_sat_circuit(
overall_circuit_data["circuit"], backend, shots
)
self.save_display_results(counts_parsed)
print()
print(f"Done saving data into '{self.dir_path}'.")
def obtain_grover_operator(
self, transpile_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]:
"""
Obtains the suitable `GroverConstraintsOperator` object for the constraints,
decomposes it using the `circuit_decomposition.py` module and transpiles it
according to `transpile_kwargs`.
Args:
transpile_kwargs (Optional[Dict[str, Any]]): kwargs for Qiskit's transpile function.
The defualt is set to the global constant `TRANSPILE_KWARGS`.
Returns:
(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit, Dict[str, List[int]]]]):
- 'operator' (GroverConstraintsOperator):the high-level blocks operator.
- 'decomposed_operator' (QuantumCircuit): decomposed to building-blocks operator.
* For annotations regarding the decomposition method see the
`circuit_decomposition` module.
- 'transpiled_operator' (QuantumCircuit): the transpiled operator.
*** The high-level operator and the decomposed operator are generated with barriers
between constraints as default for visualizations purposes. The barriers are stripped
off before transpiling so the the transpiled operator object contains no barriers. ***
- 'high_level_to_bit_indexes_map' (Optional[Dict[str, List[int]]] = None):
A map of high-level variables with their allocated bit-indexes in the input register.
"""
print()
print(
"The system synthesizes and transpiles a Grover's "
"operator for the given constraints. Please wait.."
)
if transpile_kwargs is None:
transpile_kwargs = TRANSPILE_KWARGS
self.transpile_kwargs = transpile_kwargs
operator = GroverConstraintsOperator(
self.parsed_constraints, self.num_input_qubits, insert_barriers=True
)
decomposed_operator = decompose_operator(operator)
no_baerriers_operator = RemoveBarriers()(operator)
transpiled_operator = transpile(no_baerriers_operator, **transpile_kwargs)
print("Done.")
return {
"operator": operator,
"decomposed_operator": decomposed_operator,
"transpiled_operator": transpiled_operator,
"high_level_to_bit_indexes_map": self.high_to_low_map,
}
def save_display_grover_operator(
self,
obtain_grover_operator_output: Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_grover_operator` method.
Args:
obtain_grover_operator_output(Dict[str, Union[GroverConstraintsOperator, QuantumCircuit]]):
the dictionary returned upon calling the `self.obtain_grover_operator` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
# Creating a directory to save operator's data
operator_dir_path = f"{self.dir_path}grover_operator/"
os.mkdir(operator_dir_path)
# Titles for displaying objects, by order of `obtain_grover_operator_output`
titles = [
"The operator diagram - high level blocks:",
"The operator diagram - decomposed:",
f"The transpiled operator diagram saved into '{operator_dir_path}'.\n"
f"It's not presented here due to its complexity.\n"
f"Please note that barriers appear in the high-level diagrams above only for convenient\n"
f"visual separation between constraints.\n"
f"Before transpilation all barriers are removed to avoid redundant inefficiencies.",
]
for index, (op_name, op_obj) in enumerate(obtain_grover_operator_output.items()):
# Generic path and name for files to be saved
files_path = f"{operator_dir_path}{op_name}"
# Generating a circuit diagrams figure
figure_path = f"{files_path}.pdf"
op_obj.draw("mpl", filename=figure_path, fold=-1)
# Generating a QPY serialization file for the circuit object
qpy_file_path = f"{files_path}.qpy"
with open(qpy_file_path, "wb") as qpy_file:
qpy.dump(op_obj, qpy_file)
# Original high-level operator and decomposed operator
if index < 2 and display:
# Displaying to user
self.output_to_platform(
title=titles[index], output_terminal=op_obj.draw("text"), output_jupyter=figure_path
)
# Transpiled operator
elif index == 2:
# Output to user, not including the circuit diagram
print()
print(titles[index])
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_operator_depth = op_obj.depth()
transpiled_operator_gates_count = op_obj.count_ops()
print(f"Transpiled operator depth: {transpiled_operator_depth}.")
print(f"Transpiled operator gates count: {transpiled_operator_gates_count}.")
print(f"Total number of qubits: {op_obj.num_qubits}.")
# Generating QASM 2.0 file only for the (flattened = no registers) tranpsiled operator
qasm_file_path = f"{files_path}.qasm"
flatten_circuit(op_obj).qasm(filename=qasm_file_path)
# Index 3 is 'high_level_to_bit_indexes_map' so it's time to break from the loop
break
# Mapping from high-level variables to bit-indexes will be displayed as well
mapping = obtain_grover_operator_output["high_level_to_bit_indexes_map"]
if mapping:
print()
print(f"The high-level variables mapping to bit-indexes:\n{mapping}")
print()
print(
f"Saved into '{operator_dir_path}':\n",
" Circuit diagrams for all levels.\n",
" QPY serialization exports for all levels.\n",
" QASM 2.0 export only for the transpiled level.",
)
with open(f"{operator_dir_path}operator.qpy", "rb") as qpy_file:
operator_qpy_sha256 = sha256(qpy_file.read()).hexdigest()
self.update_metadata(
{
"high_level_to_bit_indexes_map": self.high_to_low_map,
"transpile_kwargs": self.transpile_kwargs,
"transpiled_operator_depth": transpiled_operator_depth,
"transpiled_operator_gates_count": transpiled_operator_gates_count,
"operator_qpy_sha256": operator_qpy_sha256,
}
)
def obtain_overall_sat_circuit(
self,
grover_operator: GroverConstraintsOperator,
solutions_num: int,
backend: Optional[Backend] = None,
) -> Dict[str, SATCircuit]:
"""
Obtains the suitable `SATCircuit` object (= the overall SAT circuit) for the SAT problem.
Args:
grover_operator (GroverConstraintsOperator): Grover's operator for the SAT problem.
solutions_num (int): number of solutions for the SAT problem. In the case the number
of solutions is unknown, specific negative values are accepted:
* '-1' - for launching a classical iterative stochastic process that finds an adequate
number of iterations - by calling the `find_iterations_unknown` function (see its
docstrings for more information).
* '-2' - for generating a dynamic circuit that iterates over Grover's iterator until
a solution is obtained, using weak measurements. TODO - this feature isn't ready yet.
backend (Optional[Backend] = None): in the case of a '-1' value given to `solutions_num`,
a backend object to execute the depicted iterative prcess upon should be provided.
Returns:
(Dict[str, SATCircuit]):
- 'circuit' key for the overall SAT circuit.
- 'concise_circuit' key for the overall SAT circuit, with only 1 iteration over Grover's
iterator (operator + diffuser). Useful for visualization purposes.
*** The concise circuit is generated with barriers between segments as default
for visualizations purposes. In the actual circuit there no barriers. ***
"""
# -1 = Unknown number of solutions - iterative stochastic process
print()
if solutions_num == -1:
assert backend is not None, "Need to specify a backend if `solutions_num == -1`."
print("Please wait while the system checks various solutions..")
circuit, iterations = find_iterations_unknown(
self.num_input_qubits,
grover_operator,
self.parsed_constraints,
precision=10,
backend=backend,
)
print()
print(f"An adequate number of iterations found = {iterations}.")
# -2 = Unknown number of solutions - implement a dynamic circuit
# TODO this feature isn't fully implemented yet
elif solutions_num == -2:
print("The system builds a dynamic circuit..")
circuit = SATCircuit(self.num_input_qubits, grover_operator, iterations=None)
circuit.add_input_reg_measurement()
iterations = None
# Known number of solutions
else:
print("The system builds the overall circuit..")
iterations = calc_iterations(self.num_input_qubits, solutions_num)
print(f"\nFor {solutions_num} solutions, {iterations} iterations needed.")
circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations, insert_barriers=False
)
circuit.add_input_reg_measurement()
self.iterations = iterations
# Obtaining a SATCircuit object with one iteration for concise representation
concise_circuit = SATCircuit(
self.num_input_qubits, grover_operator, iterations=1, insert_barriers=True
)
concise_circuit.add_input_reg_measurement()
return {"circuit": circuit, "concise_circuit": concise_circuit}
def save_display_overall_circuit(
self, obtain_overall_sat_circuit_output: Dict[str, SATCircuit], display: Optional[bool] = True
) -> None:
"""
Handles saving and displaying data generated by the `self.obtain_overall_sat_circuit` method.
Args:
obtain_overall_sat_circuit_output(Dict[str, SATCircuit]):
the dictionary returned upon calling the `self.obtain_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
circuit = obtain_overall_sat_circuit_output["circuit"]
concise_circuit = obtain_overall_sat_circuit_output["concise_circuit"]
# Creating a directory to save overall circuit's data
overall_circuit_dir_path = f"{self.dir_path}overall_circuit/"
os.mkdir(overall_circuit_dir_path)
# Generating a figure of the overall SAT circuit with just 1 iteration (i.e "concise")
concise_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_1_iteration.pdf"
concise_circuit.draw("mpl", filename=concise_circuit_fig_path, fold=-1)
# Displaying the concise circuit to user
if display:
if self.iterations:
self.output_to_platform(
title=(
f"The high level circuit contains {self.iterations}"
f" iterations of the following form:"
),
output_terminal=concise_circuit.draw("text"),
output_jupyter=concise_circuit_fig_path,
)
# Dynamic circuit case - TODO NOT FULLY IMPLEMENTED YET
else:
dynamic_circuit_fig_path = f"{overall_circuit_dir_path}overall_circuit_dynamic.pdf"
circuit.draw("mpl", filename=dynamic_circuit_fig_path, fold=-1)
self.output_to_platform(
title="The dynamic circuit diagram:",
output_terminal=circuit.draw("text"),
output_jupyter=dynamic_circuit_fig_path,
)
if self.iterations:
transpiled_overall_circuit = transpile(flatten_circuit(circuit), **self.transpile_kwargs)
print()
print(f"The transpilation kwargs are: {self.transpile_kwargs}.")
transpiled_overall_circuit_depth = transpiled_overall_circuit.depth()
transpiled_overall_circuit_gates_count = transpiled_overall_circuit.count_ops()
print(f"Transpiled overall-circuit depth: {transpiled_overall_circuit_depth}.")
print(f"Transpiled overall-circuit gates count: {transpiled_overall_circuit_gates_count}.")
print(f"Total number of qubits: {transpiled_overall_circuit.num_qubits}.")
print()
print("Exporting the full overall SAT circuit object..")
export_files_path = f"{overall_circuit_dir_path}overall_circuit"
with open(f"{export_files_path}.qpy", "wb") as qpy_file:
qpy.dump(circuit, qpy_file)
if self.iterations:
transpiled_overall_circuit.qasm(filename=f"{export_files_path}.qasm")
print()
print(
f"Saved into '{overall_circuit_dir_path}':\n",
" A concised (1 iteration) circuit diagram of the high-level overall SAT circuit.\n",
" QPY serialization export for the full overall SAT circuit object.",
)
if self.iterations:
print(" QASM 2.0 export for the transpiled full overall SAT circuit object.")
metadata_update = {
"num_total_qubits": circuit.num_qubits,
"num_iterations": circuit.iterations,
}
if self.iterations:
metadata_update["transpiled_overall_circuit_depth"] = (transpiled_overall_circuit_depth,)
metadata_update[
"transpiled_overall_circuit_gates_count"
] = transpiled_overall_circuit_gates_count
self.update_metadata(metadata_update)
@timer_dec("Circuit simulation execution time = ")
def run_overall_sat_circuit(
self, circuit: QuantumCircuit, backend: Backend, shots: int
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Executes a `circuit` on `backend` transpiled w.r.t backend, `shots` times.
Args:
circuit (QuantumCircuit): `QuantumCircuit` object or child-object (a.k.a `SATCircuit`)
to execute.
backend (Backend): backend to execute `circuit` upon.
shots (int): number of execution shots.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
dict object returned by `self.parse_counts` - see this method's docstrings for annotations.
"""
# Defines also instance attributes to use in other methods
self.backend = backend
self.shots = shots
print()
print(f"The system is running the circuit {shots} times on {backend}, please wait..")
print("This process might take a while.")
job = backend.run(transpile(circuit, backend), shots=shots)
counts = job.result().get_counts()
print("Done.")
parsed_counts = self.parse_counts(counts)
return parsed_counts
def parse_counts(
self, counts: Counts
) -> Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]:
"""
Parses a `Counts` object into several desired datas (see 'Returns' section).
Args:
counts (Counts): the `Counts` object to parse.
Returns:
(Dict[str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]]):
'counts' (Counts) - the original `Counts` object.
'counts_sorted' (List[Tuple[Union[str, int]]]) - results sorted in a descending order.
'distilled_solutions' (List[str]): list of solutions (bitstrings).
'high_level_vars_values' (List[Dict[str, int]]): list of solutions (each solution is a
dictionary with variable-names as keys and their integer values as values).
"""
# Sorting results in an a descending order
counts_sorted = sorted(counts.items(), key=lambda x: x[1], reverse=True)
# Generating a set of distilled verified-only solutions
verifier = ClassicalVerifier(self.parsed_constraints)
distilled_solutions = set()
for count_item in counts_sorted:
if not verifier.verify(count_item[0]):
break
distilled_solutions.add(count_item[0])
# In the case of high-level format in use, translating `distilled_solutions` into integer values
high_level_vars_values = None
if self.high_level_constraints_string and self.high_level_vars:
# Container for dictionaries with variables integer values
high_level_vars_values = []
for solution in distilled_solutions:
# Keys are variable-names and values are their integer values
solution_vars = {}
for var, bits_bundle in self.high_to_low_map.items():
reversed_solution = solution[::-1]
var_bitstring = ""
for bit_index in bits_bundle:
var_bitstring += reversed_solution[bit_index]
# Translating to integer value
solution_vars[var] = int(var_bitstring, 2)
high_level_vars_values.append(solution_vars)
return {
"counts": counts,
"counts_sorted": counts_sorted,
"distilled_solutions": distilled_solutions,
"high_level_vars_values": high_level_vars_values,
}
def save_display_results(
self,
run_overall_sat_circuit_output: Dict[
str, Union[Counts, List[Tuple[Union[str, int]]], List[str], List[Dict[str, int]]]
],
display: Optional[bool] = True,
) -> None:
"""
Handles saving and displaying data generated by the `self.run_overall_sat_circuit` method.
Args:
run_overall_sat_circuit_output (Dict[str, Union[Counts, List[Tuple[Union[str, int]]],
List[str], List[Dict[str, int]]]]): the dictionary returned upon calling
the `self.run_overall_sat_circuit` method.
display (Optional[bool] = True) - If true, displays objects to user's platform.
"""
counts = run_overall_sat_circuit_output["counts"]
counts_sorted = run_overall_sat_circuit_output["counts_sorted"]
distilled_solutions = run_overall_sat_circuit_output["distilled_solutions"]
high_level_vars_values = run_overall_sat_circuit_output["high_level_vars_values"]
# Creating a directory to save results data
results_dir_path = f"{self.dir_path}results/"
os.mkdir(results_dir_path)
# Defining custom dimensions for the custom `plot_histogram` of this package
histogram_fig_width = max((len(counts) * self.num_input_qubits * (10 / 72)), 7)
histogram_fig_height = 5
histogram_figsize = (histogram_fig_width, histogram_fig_height)
histogram_path = f"{results_dir_path}histogram.pdf"
plot_histogram(counts, figsize=histogram_figsize, sort="value_desc", filename=histogram_path)
if display:
# Basic output text
output_text = (
f"All counts:\n{counts_sorted}\n"
f"\nDistilled solutions ({len(distilled_solutions)} total):\n"
f"{distilled_solutions}"
)
# Additional outputs for a high-level constraints format
if high_level_vars_values:
# Mapping from high-level variables to bit-indexes will be displayed as well
output_text += (
f"\n\nThe high-level variables mapping to bit-indexes:" f"\n{self.high_to_low_map}"
)
# Actual integer solutions will be displayed as well
additional_text = ""
for solution_index, solution in enumerate(high_level_vars_values):
additional_text += f"Solution {solution_index + 1}: "
for var_index, (var, value) in enumerate(solution.items()):
additional_text += f"{var} = {value}"
if var_index != len(solution) - 1:
additional_text += ", "
else:
additional_text += "\n"
output_text += f"\n\nHigh-level format solutions: \n{additional_text}"
self.output_to_platform(
title=f"The results for {self.shots} shots are:",
output_terminal=output_text,
output_jupyter=histogram_path,
display_both_on_jupyter=True,
)
results_dict = {
"high_level_to_bit_indexes_map": self.high_to_low_map,
"solutions": list(distilled_solutions),
"high_level_solutions": high_level_vars_values,
"counts": counts_sorted,
}
with open(f"{results_dir_path}results.json", "w") as results_file:
json.dump(results_dict, results_file, indent=4)
self.update_metadata(
{
"num_solutions": len(distilled_solutions),
"backend": str(self.backend),
"shots": self.shots,
}
)
|
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-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 = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/miamico/Quantum_Generative_Adversarial_Networks
|
miamico
|
%%capture
%pip install qiskit
%pip install qiskit_ibm_provider
%pip install qiskit-aer
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer
from qiskit_ibm_provider import IBMProvider
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import C3XGate
# Importing matplotlib
import matplotlib.pyplot as plt
# Importing Numpy, Cmath and math
import numpy as np
import os, math, cmath
from numpy import pi
# Other imports
from IPython.display import display, Math, Latex
# Specify the path to your env file
env_file_path = 'config.env'
# Load environment variables from the file
os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#'))
# Load IBM Provider API KEY
IBMP_API_KEY = os.environ.get('IBMP_API_KEY')
# Loading your IBM Quantum account(s)
IBMProvider.save_account(IBMP_API_KEY, overwrite=True)
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
qc_b1 = QuantumCircuit(2, 2)
qc_b1.h(0)
qc_b1.cx(0, 1)
qc_b1.draw(output='mpl', style="iqp")
sv = backend.run(qc_b1).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.x(0)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.z(0)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.x(1)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.x(0)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.x(0)
qc_b4.h(0)
qc_b4.x(1)
qc_b4.cx(0, 1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.h(0)
qc_b4.cx(0, 1)
qc_b4.x(0)
qc_b4.z(1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
def sv_latex_from_qc(qc, backend):
sv = backend.run(qc).result().get_statevector()
return sv.draw(output='latex')
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(3)
sv_latex_from_qc(qc_ej2, backend)
def circuit_adder (num):
if num<1 or num>8:
raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo.
# Definición del circuito base que vamos a construir
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
qbit_position = 0
for element in reversed(np.binary_repr(num)):
if (element=='1'):
circuit.barrier()
match qbit_position:
case 0: # +1
circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]])
circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
case 1: # +2
circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.x(qreg_q[1])
case 2: # +4
circuit.cx(qreg_q[2], qreg_q[3])
circuit.x(qreg_q[2])
case 3: # +8
circuit.x(qreg_q[3])
qbit_position+=1
return circuit
add_3 = circuit_adder(3)
add_3.draw(output='mpl', style="iqp")
qc_test_2 = QuantumCircuit(4, 4)
qc_test_2.x(1)
qc_test_2_plus_3 = qc_test_2.compose(add_3)
qc_test_2_plus_3.draw(output='mpl', style="iqp")
sv_latex_from_qc(qc_test_2_plus_3, backend)
qc_test_7 = QuantumCircuit(4, 4)
qc_test_7.x(0)
qc_test_7.x(1)
qc_test_7.x(2)
qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8))
sv_latex_from_qc(qc_test_7_plus_8, backend)
#qc_test_7_plus_8.draw()
theta = 6.544985
phi = 2.338741
lmbda = 0
alice_1 = 0
alice_2 = 1
bob_1 = 2
qr_alice = QuantumRegister(2, 'Alice')
qr_bob = QuantumRegister(1, 'Bob')
cr = ClassicalRegister(3, 'c')
qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr)
qc_ej3.barrier(label='1')
qc_ej3.u(theta, phi, lmbda, alice_1);
qc_ej3.barrier(label='2')
qc_ej3.h(alice_2)
qc_ej3.cx(alice_2, bob_1);
qc_ej3.barrier(label='3')
qc_ej3.cx(alice_1, alice_2)
qc_ej3.h(alice_1);
qc_ej3.barrier(label='4')
qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]);
qc_ej3.barrier(label='5')
qc_ej3.x(bob_1).c_if(alice_2, 1)
qc_ej3.z(bob_1).c_if(alice_1, 1)
qc_ej3.measure(bob_1, bob_1);
qc_ej3.draw(output='mpl', style="iqp")
result = backend.run(qc_ej3, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
sv_0 = np.array([1, 0])
sv_1 = np.array([0, 1])
def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10):
"""
Check if the given numerical value corresponds to a symbolic constant within a specified tolerance.
Parameters:
- value (float): The numerical value to check.
- symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations.
Defaults to {1/np.sqrt(2): '1/√2'}.
- tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10.
Returns:
str or float: If a match is found, returns the symbolic representation as a string
(prefixed with '-' if the value is negative); otherwise, returns the original value.
"""
for constant, symbol in symbolic_constants.items():
if np.isclose(abs(value), constant, atol=tolerance):
return symbol if value >= 0 else '-' + symbol
return value
def array_to_dirac_notation(array, tolerance=1e-10):
"""
Convert a complex-valued array representing a quantum state in superposition
to Dirac notation.
Parameters:
- array (numpy.ndarray): The complex-valued array representing
the quantum state in superposition.
- tolerance (float): Tolerance for considering amplitudes as negligible.
Returns:
str: The Dirac notation representation of the quantum state.
"""
# Ensure the statevector is normalized
array = array / np.linalg.norm(array)
# Get the number of qubits
num_qubits = int(np.log2(len(array)))
# Find indices where amplitude is not negligible
non_zero_indices = np.where(np.abs(array) > tolerance)[0]
# Generate Dirac notation terms
terms = [
(find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b"))
for i in non_zero_indices
]
# Format Dirac notation
dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms])
return dirac_notation
def array_to_matrix_representation(array):
"""
Convert a one-dimensional array to a column matrix representation.
Parameters:
- array (numpy.ndarray): The one-dimensional array to be converted.
Returns:
numpy.ndarray: The column matrix representation of the input array.
"""
# Replace symbolic constants with their representations
matrix_representation = np.array([find_symbolic_representation(value) or value for value in array])
# Return the column matrix representation
return matrix_representation.reshape((len(matrix_representation), 1))
def array_to_dirac_and_matrix_latex(array):
"""
Generate LaTeX code for displaying both the matrix representation and Dirac notation
of a quantum state.
Parameters:
- array (numpy.ndarray): The complex-valued array representing the quantum state.
Returns:
Latex: A Latex object containing LaTeX code for displaying both representations.
"""
matrix_representation = array_to_matrix_representation(array)
latex = "Matrix representation\n\\begin{bmatrix}\n" + \
"\\\\\n".join(map(str, matrix_representation.flatten())) + \
"\n\\end{bmatrix}\n"
latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}'
return Latex(latex)
sv_b1 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b2 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b3 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b4 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit.circuit import QuantumCircuit,\
ParameterVector
theta = ParameterVector('θ', 3)
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc.p(theta[0],0)
qc.p(theta[1],1)
qc.p(theta[2],2)
qc.draw()
import math
b_qc = qc.bind_parameters({theta: [math.pi/8,
math.pi/4,
math.pi/2]})
b_qc.draw()
|
https://github.com/AMevans12/Quantum-Codes-Qiskit-Module-
|
AMevans12
|
my_list = [1,3,5,2,4,2,5,8,0,7,6]
#classical computation method
def oracle(my_input):
winner =7
if my_input is winner:
response = True
else:
response = False
return response
for index, trial_number in enumerate(my_list):
if oracle(trial_number) is True:
print("Winner is found at index %i" %index)
print("%i calls to the oracle used " %(index +1))
break
#quantum implemenation
from qiskit import *
import matplotlib.pyplot as plt
import numpy as np
from qiskit.tools import job_monitor
# oracle circuit
oracle = QuantumCircuit(2, name='oracle')
oracle.cz(0,1)
oracle.to_gate()
oracle.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
grover_circuit = QuantumCircuit(2,2)
grover_circuit.h([0,1])
grover_circuit.append(oracle,[0,1])
grover_circuit.draw(output='mpl')
job= execute(grover_circuit, backend=backend)
result= job.result()
sv= result.get_statevector()
np.around(sv,2)
#amplitude amplification
reflection = QuantumCircuit(2, name='reflection')
reflection.h([0,1])
reflection.z([0,1])
reflection.cz(0,1)
reflection.h([0,1])
reflection.to_gate()
reflection.draw(output='mpl')
#testing circuit on simulator
simulator = Aer.get_backend('qasm_simulator')
grover_circuit = QuantumCircuit(2,2)
grover_circuit.h([0,1])
grover_circuit.append(oracle,[0,1])
grover_circuit.append(reflection, [0,1])
grover_circuit.barrier()
grover_circuit.measure([0,1],[0,1])
grover_circuit.draw(output='mpl')
job= execute(grover_circuit,backend=simulator,shots=1)
result=job.result()
result.get_counts()
#testing on real backend system
IBMQ.load_account()
provider= IBMQ.get_provider('ibm-q')
qcomp= provider.get_backend('ibmq_manila')
job = execute(grover_circuit,backend=qcomp)
job_monitor(job)
result=job.result()
counts=result.get_counts(grover_circuit)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
counts['11']
|
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 test.terra.utils.mock import FakeFailureQasmSimulator, FakeSuccessQasmSimulator
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler import transpile, assemble
from qiskit.providers.aer import AerError
class QasmBasicsTests:
"""QasmSimulator basic tests."""
def test_simulation_succeed(self):
"""Test the we properly manage simulation failures."""
mocked_backend = FakeSuccessQasmSimulator(time_alive=0)
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
succeed_circuit = QuantumCircuit(qr, cr)
quantum_circuit = transpile(succeed_circuit, mocked_backend)
qobj = assemble(quantum_circuit)
result = mocked_backend.run(qobj).result()
self.assertSuccess(result)
def test_simulation_failed(self):
"""Test the we properly manage simulation failures."""
mocked_backend = FakeFailureQasmSimulator(time_alive=0)
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
failed_circuit = QuantumCircuit(qr, cr)
quantum_circuit = transpile(failed_circuit, mocked_backend)
qobj = assemble(quantum_circuit)
job = mocked_backend.run(qobj)
self.assertRaises(AerError, job.result)
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
%%capture
%pip install qiskit
%pip install qiskit_ibm_provider
%pip install qiskit-aer
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer
from qiskit_ibm_provider import IBMProvider
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import C3XGate
# Importing matplotlib
import matplotlib.pyplot as plt
# Importing Numpy, Cmath and math
import numpy as np
import os, math, cmath
from numpy import pi
# Other imports
from IPython.display import display, Math, Latex
# Specify the path to your env file
env_file_path = 'config.env'
# Load environment variables from the file
os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#'))
# Load IBM Provider API KEY
IBMP_API_KEY = os.environ.get('IBMP_API_KEY')
# Loading your IBM Quantum account(s)
IBMProvider.save_account(IBMP_API_KEY, overwrite=True)
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
qc_b1 = QuantumCircuit(2, 2)
qc_b1.h(0)
qc_b1.cx(0, 1)
qc_b1.draw(output='mpl', style="iqp")
sv = backend.run(qc_b1).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.x(0)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.z(0)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.x(1)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.x(0)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.x(0)
qc_b4.h(0)
qc_b4.x(1)
qc_b4.cx(0, 1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.h(0)
qc_b4.cx(0, 1)
qc_b4.x(0)
qc_b4.z(1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
def sv_latex_from_qc(qc, backend):
sv = backend.run(qc).result().get_statevector()
return sv.draw(output='latex')
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(3)
sv_latex_from_qc(qc_ej2, backend)
def circuit_adder (num):
if num<1 or num>8:
raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo.
# Definición del circuito base que vamos a construir
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
qbit_position = 0
for element in reversed(np.binary_repr(num)):
if (element=='1'):
circuit.barrier()
match qbit_position:
case 0: # +1
circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]])
circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
case 1: # +2
circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.x(qreg_q[1])
case 2: # +4
circuit.cx(qreg_q[2], qreg_q[3])
circuit.x(qreg_q[2])
case 3: # +8
circuit.x(qreg_q[3])
qbit_position+=1
return circuit
add_3 = circuit_adder(3)
add_3.draw(output='mpl', style="iqp")
qc_test_2 = QuantumCircuit(4, 4)
qc_test_2.x(1)
qc_test_2_plus_3 = qc_test_2.compose(add_3)
qc_test_2_plus_3.draw(output='mpl', style="iqp")
sv_latex_from_qc(qc_test_2_plus_3, backend)
qc_test_7 = QuantumCircuit(4, 4)
qc_test_7.x(0)
qc_test_7.x(1)
qc_test_7.x(2)
qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8))
sv_latex_from_qc(qc_test_7_plus_8, backend)
#qc_test_7_plus_8.draw()
theta = 6.544985
phi = 2.338741
lmbda = 0
alice_1 = 0
alice_2 = 1
bob_1 = 2
qr_alice = QuantumRegister(2, 'Alice')
qr_bob = QuantumRegister(1, 'Bob')
cr = ClassicalRegister(3, 'c')
qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr)
qc_ej3.barrier(label='1')
qc_ej3.u(theta, phi, lmbda, alice_1);
qc_ej3.barrier(label='2')
qc_ej3.h(alice_2)
qc_ej3.cx(alice_2, bob_1);
qc_ej3.barrier(label='3')
qc_ej3.cx(alice_1, alice_2)
qc_ej3.h(alice_1);
qc_ej3.barrier(label='4')
qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]);
qc_ej3.barrier(label='5')
qc_ej3.x(bob_1).c_if(alice_2, 1)
qc_ej3.z(bob_1).c_if(alice_1, 1)
qc_ej3.measure(bob_1, bob_1);
qc_ej3.draw(output='mpl', style="iqp")
result = backend.run(qc_ej3, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
sv_0 = np.array([1, 0])
sv_1 = np.array([0, 1])
def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10):
"""
Check if the given numerical value corresponds to a symbolic constant within a specified tolerance.
Parameters:
- value (float): The numerical value to check.
- symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations.
Defaults to {1/np.sqrt(2): '1/√2'}.
- tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10.
Returns:
str or float: If a match is found, returns the symbolic representation as a string
(prefixed with '-' if the value is negative); otherwise, returns the original value.
"""
for constant, symbol in symbolic_constants.items():
if np.isclose(abs(value), constant, atol=tolerance):
return symbol if value >= 0 else '-' + symbol
return value
def array_to_dirac_notation(array, tolerance=1e-10):
"""
Convert a complex-valued array representing a quantum state in superposition
to Dirac notation.
Parameters:
- array (numpy.ndarray): The complex-valued array representing
the quantum state in superposition.
- tolerance (float): Tolerance for considering amplitudes as negligible.
Returns:
str: The Dirac notation representation of the quantum state.
"""
# Ensure the statevector is normalized
array = array / np.linalg.norm(array)
# Get the number of qubits
num_qubits = int(np.log2(len(array)))
# Find indices where amplitude is not negligible
non_zero_indices = np.where(np.abs(array) > tolerance)[0]
# Generate Dirac notation terms
terms = [
(find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b"))
for i in non_zero_indices
]
# Format Dirac notation
dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms])
return dirac_notation
def array_to_matrix_representation(array):
"""
Convert a one-dimensional array to a column matrix representation.
Parameters:
- array (numpy.ndarray): The one-dimensional array to be converted.
Returns:
numpy.ndarray: The column matrix representation of the input array.
"""
# Replace symbolic constants with their representations
matrix_representation = np.array([find_symbolic_representation(value) or value for value in array])
# Return the column matrix representation
return matrix_representation.reshape((len(matrix_representation), 1))
def array_to_dirac_and_matrix_latex(array):
"""
Generate LaTeX code for displaying both the matrix representation and Dirac notation
of a quantum state.
Parameters:
- array (numpy.ndarray): The complex-valued array representing the quantum state.
Returns:
Latex: A Latex object containing LaTeX code for displaying both representations.
"""
matrix_representation = array_to_matrix_representation(array)
latex = "Matrix representation\n\\begin{bmatrix}\n" + \
"\\\\\n".join(map(str, matrix_representation.flatten())) + \
"\n\\end{bmatrix}\n"
latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}'
return Latex(latex)
sv_b1 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b2 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b3 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b4 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
|
https://github.com/weiT1993/qiskit_helper_functions
|
weiT1993
|
import sys, math, logging
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError
class HWEA:
"""
Class to implement a hardware efficient ansatz for the QAOA algorithm.
Based on the community detection circuit implemented by Francois-Marie Le Régent.
This ansatz uses the entangler+rotation block structure like that described
in the paper by Nikolaj Moll et al. (http://iopscience.iop.org/article/10.1088/2058-9565/aab822)
A HW efficient ansatz circuit can be generated with an instance of this class
by calling its gen_circuit() method.
Attributes
----------
nq : int
number of qubits
d : int
number of layers to apply. Where a layer = rotation block + entangler block
This is also the same as the "P" value often referenced for QAOA.
parameters : str
optional string which changes the rotation angles in the rotation block
[optimal, random, seeded]
seed : int
a number to seed the number generator with
barriers : bool
should barriers be included in the generated circuit
measure : bool
should a classical register & measurement be added to the circuit
regname : str
optional string to name the quantum and classical registers. This
allows for the easy concatenation of multiple QuantumCircuits.
qr : QuantumRegister
Qiskit QuantumRegister holding all of the quantum bits
cr : ClassicalRegister
Qiskit ClassicalRegister holding all of the classical bits
circ : QuantumCircuit
Qiskit QuantumCircuit that represents the hardware-efficient ansatz
"""
def __init__(
self,
width,
depth,
parameters="optimal",
seed=None,
barriers=False,
measure=False,
regname=None,
):
# number of qubits
self.nq = width
# number of layers
self.d = depth
# set flags for circuit generation
self.parameters = parameters
self.seed = seed
self.barriers = barriers
self.measure = measure
# Create a Quantum and Classical Register.
if regname is None:
self.qr = QuantumRegister(self.nq)
self.cr = ClassicalRegister(self.nq)
else:
self.qr = QuantumRegister(self.nq, name=regname)
self.cr = ClassicalRegister(self.nq, name="c" + regname)
# It is easier for the circuit cutter to handle circuits
# without measurement or classical registers
if self.measure:
self.circ = QuantumCircuit(self.qr, self.cr)
else:
self.circ = QuantumCircuit(self.qr)
def get_noiseless_theta(self):
"""
Set the parameters to the optimal value which solves the community
detection problem.
This method returns a vector of length (1 + d)*2nq
The first gate on the first qubit is a pi/2 rotation (Hadamard)
After the entangler block, the first half of the qubits (round down for
odd n_qubits) receive a pi rotation (X gate)
Parameters
----------
nb_qubits : int
Number of qubits in the circuit
Returns
-------
list
vector of length 2*nq * (1+d)
"""
theta = np.zeros(2 * self.nq * (1 + self.d))
theta[0] = np.pi / 2
theta[2 * self.nq : 2 * self.nq + math.floor(self.nq / 2)] = np.pi
return theta
def get_random_theta(self):
if self.parameters == "seeded":
if self.seed is None:
raise Exception("A valid seed must be provided")
else:
np.random.seed(self.seed)
theta = np.random.uniform(-np.pi, np.pi, 4 * self.nq)
return theta
def gen_circuit(self):
"""
Create a circuit for the QAOA RyRz ansatz
This methods generates a circuit with repeated layers of an entangler
block sandwiched between parameterized rotation columns
Returns
-------
QuantumCircuit
QuantumCircuit of size nb_qubits with no ClassicalRegister
and no measurements
QiskitError
Prints the error in the circuit
"""
if self.parameters == "optimal":
theta = self.get_noiseless_theta()
elif self.parameters in ["random", "seeded"]:
theta = self.get_random_theta()
else:
raise Exception("Unknown parameter option: {}".format(self.parameters))
try:
# INITIAL PARAMETERIZER
# layer 1
# theta = np.arange(len(theta))
# print(len(theta))
p_idx = 0
for i in range(self.nq):
self.circ.u3(theta[i + p_idx], 0, 0, self.qr[i])
p_idx += self.nq
# layer 2
for i in range(self.nq):
self.circ.u3(0, 0, theta[i + p_idx], self.qr[i])
p_idx += self.nq
if self.barriers:
self.circ.barrier()
# For each layer, d, execute an entangler followed by a parameterizer block
for dd in range(self.d):
# ENTANGLER
for i in range(self.nq - 1):
# qc.h(q[i+1])
self.circ.cx(self.qr[i], self.qr[i + 1])
# qc.h(q[i+1])
if self.barriers:
self.circ.barrier()
# PARAMETERIZER
# layer 1
for i in range(self.nq):
self.circ.u3(theta[i + p_idx], 0, 0, self.qr[i])
p_idx += self.nq
# layer 2
for i in range(self.nq):
self.circ.u3(0, 0, theta[i + p_idx], self.qr[i])
p_idx += self.nq
# place measurements on the end of the circuit
if self.measure:
self.circ.barrier()
self.circ.measure(self.qr, self.cr)
return self.circ
except QiskitError as ex:
raise Exception("There was an error in the circuit!. Error = {}".format(ex))
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (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.
import json
from typing import Any, Callable, Optional, Tuple, Union
from urllib.parse import urljoin
from qiskit import QuantumCircuit, execute
from qiskit.providers import JobStatus
from qiskit.providers.ibmq.job import IBMQJob
from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint
from .exercises import get_question_id
from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate
def _circuit_criteria(
circuit: QuantumCircuit,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[int], Optional[int]]:
if max_qubits is not None and circuit.num_qubits > max_qubits:
print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.')
print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.')
return None, None
try:
if check_gates and not uses_multiqubit_gate(circuit):
print('Your circuit appears to not use any multi-quibit gates.')
print('Please review your circuit and try again.')
return None, None
cost = compute_cost(circuit)
if min_cost is not None and cost < min_cost:
print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n'
'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.')
return None, None
return circuit.num_qubits, cost
except Exception as err:
print(f'Unable to compute cost: {err}')
return None, None
def _circuit_grading(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
payload = None
server = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or '
'the grading servers are down right now.')
return None, None
else:
server = None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
payload = {
'answer': circuit_to_json(circuit)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _job_grading(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str):
print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}')
print(f'Please submit a job as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading '
'servers are down right now.')
return None, None
else:
server = None
job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id
if not job:
print('An invalid or non-existent job was specified.')
return None, None
job_status = job.status()
if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]:
print(f'Job did not successfully complete: {job_status.value}.')
return None, None
elif job_status is not JobStatus.DONE:
print(f'Job has not yet completed: {job_status.value}.')
print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.')
return None, None
header = job.result().header.to_dict()
if 'qc_cost' not in header:
if is_submit:
print('An unprepared answer was specified. '
'Please prepare() and grade() answer before submitting.')
else:
print('An unprepared answer was specified. Please prepare() answer before grading.')
return None, None
download_url, result_url = get_job_urls(job)
if not download_url or not result_url:
print('Unable to obtain job URLs')
return None, None
payload = {
'answer': json.dumps({
'download_url': download_url,
'result_url': result_url
})
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _number_grading(
answer: int,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(answer, int):
print(f'Expected a integer, but was given {type(answer)}')
print(f'Please provide a number as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server '
'or the grading servers are down right now.')
return None, None
else:
server = None
payload = {
'answer': str(answer)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def prepare_circuit(
circuit: QuantumCircuit,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit.')
return None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiment. Please wait...')
job = execute(
circuit,
qobj_header={
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def prepare_solver(
solver_func: Callable,
lab_id: str,
ex_id: str,
problem_set: Optional[Any] = None,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not callable(solver_func):
print(f'Expected a function, but was given {type(solver_func)}')
print(f'Please provide a function that returns a QuantumCircuit.')
return None
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading servers are down right now.')
return
endpoint = server + 'problem-set'
index, value = get_problem_set(lab_id, ex_id, endpoint)
print(f'Running {solver_func.__name__}...')
qc_1 = solver_func(problem_set)
_, cost = _circuit_criteria(
qc_1,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if value and index is not None and index >= 0 and cost is not None:
qc_2 = solver_func(value)
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiments. Please wait...')
job = execute(
[qc_1, qc_2],
qobj_header={
'qc_index': [None, index],
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def grade_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, server = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=False,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_job(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str
) -> bool:
payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def submit_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, _ = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=True,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_job(
job_or_id: IBMQJob,
lab_id: str,
ex_id: str,
) -> bool:
payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def get_problem_set(
lab_id: str, ex_id: str, endpoint: str
) -> Tuple[Optional[int], Optional[Any]]:
problem_set_response = None
try:
payload = {'question_id': get_question_id(lab_id, ex_id)}
problem_set_response = send_request(endpoint, query=payload, method='GET')
except Exception as err:
print('Unable to obtain the problem set')
if problem_set_response:
status = problem_set_response.get('status')
if status == 'valid':
try:
index = problem_set_response.get('index')
value = json.loads(problem_set_response.get('value'))
return index, value
except Exception as err:
print(f'Problem set could not be processed: {err}')
else:
cause = problem_set_response.get('cause')
print(f'Problem set failed: {cause}')
return None, None
def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool:
try:
answer_response = send_request(endpoint, body=payload)
status = answer_response.get('status', None)
cause = answer_response.get('cause', None)
score = cost if cost else answer_response.get('score', None)
handle_grade_response(status, score=score, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def submit_answer(payload: dict) -> bool:
try:
access_token = get_access_token()
baseurl = get_submission_endpoint()
endpoint = urljoin(baseurl, './challenges/answers')
submit_response = send_request(
endpoint,
body=payload,
query={'access_token': access_token}
)
status = submit_response.get('status', None)
if status is None:
status = submit_response.get('valid', None)
cause = submit_response.get('cause', None)
handle_submit_response(status, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def handle_grade_response(
status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None
) -> None:
if status == 'valid':
print('\nCongratulations 🎉! Your answer is correct.')
if score is not None:
print(f'Your score is {score}.')
elif status == 'invalid':
print(f'\nOops 😕! {cause}')
print('Please review your answer and try again.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete then try again.')
else:
print(f'Failed: {cause}')
print('Unable to grade your answer.')
def handle_submit_response(
status: Union[str, bool], cause: Optional[str] = None
) -> None:
if status == 'valid' or status is True:
print('\nSuccess 🎉! Your answer has been submitted.')
elif status == 'invalid' or status is False:
print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}')
print('Make sure your answer is correct and successfully graded before submitting.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete, grade it, and then try to submit again.')
else:
print(f'Failed: {cause}')
print('Unable to submit your answer at this time.')
|
https://github.com/JamesTheZhang/Qiskit2023
|
JamesTheZhang
|
from qiskit.circuit import ClassicalRegister, QuantumRegister, QuantumCircuit, Parameter
theta = Parameter('θ')
qr = QuantumRegister(1, 'q')
qc = QuantumCircuit(qr)
qc.ry(theta, 0)
qc.draw('mpl')
tele_qc = qc.copy()
bell = QuantumRegister(2, 'Bell')
alice = ClassicalRegister(2, 'Alice')
bob = ClassicalRegister(1, 'Bob')
tele_qc.add_register(bell, alice, bob)
tele_qc.draw('mpl')
# create Bell state with other two qubits
tele_qc.barrier()
tele_qc.h(1)
tele_qc.cx(1, 2)
tele_qc.barrier()
tele_qc.draw('mpl')
# alice operates on her qubits
tele_qc.cx(0, 1)
tele_qc.h(0)
tele_qc.barrier()
tele_qc.draw('mpl')
tele_qc.measure([qr[0], bell[0]], alice)
tele_qc.draw('mpl')
full_qc = tele_qc.copy()
#### ANSWER
# Bob's conditional operations
with full_qc.if_test((alice[1], 1)):
full_qc.x(bell[1])
with full_qc.if_test((alice[0], 1)):
full_qc.z(bell[1])
#### END ANSWER
full_qc.draw('mpl')
full_qc.barrier()
full_qc.measure(bell[1], bob)
full_qc.draw('mpl')
from qiskit_aer.primitives import Sampler
import numpy as np
angle = 5*np.pi/7
sampler = Sampler()
qc.measure_all()
job_static = sampler.run(qc.bind_parameters({theta: angle}))
job_dynamic = sampler.run(full_qc.bind_parameters({theta: angle}))
print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}")
print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}")
from qiskit.result import marginal_counts
from qiskit.visualization import *
# FILL IN CODE HERE
# noticed that the ratio between the teleported states with bob = 0 and bob = 1 is roughly what we expect for the original distribution, so we extracted it and passed in as a dictionary to marginalize counts
bob0 = job_dynamic.result().quasi_dists[0][0] + job_dynamic.result().quasi_dists[0][1] + job_dynamic.result().quasi_dists[0][2] + job_dynamic.result().quasi_dists[0][3]
bob1 = job_dynamic.result().quasi_dists[0][4] + job_dynamic.result().quasi_dists[0][5] + job_dynamic.result().quasi_dists[0][6] + job_dynamic.result().quasi_dists[0][7]
dictionary = {'0':bob0, '1':bob1}
tele_counts = marginal_counts(dictionary)
#### ANSWER
#### END ANSWER
legend = ['Original State', 'Teleported State']
plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test for the converter dag dependency to dag circuit and
dag circuit to dag dependency."""
import unittest
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.converters.dag_to_dagdependency import dag_to_dagdependency
from qiskit.converters.dagdependency_to_dag import dagdependency_to_dag
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestCircuitToDagDependency(QiskitTestCase):
"""Test DAGCircuit to DAGDependency."""
def test_circuit_and_dag_dependency(self):
"""Check convert to dag dependency and back"""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag_in = circuit_to_dag(circuit_in)
dag_dependency = dag_to_dagdependency(dag_in)
dag_out = dagdependency_to_dag(dag_dependency)
self.assertEqual(dag_out, dag_in)
def test_circuit_and_dag_dependency2(self):
"""Check convert to dag dependency and back
also when the option ``create_preds_and_succs`` is False."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit_in = QuantumCircuit(qr, cr)
circuit_in.h(qr[0])
circuit_in.h(qr[1])
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.x(qr[0]).c_if(cr, 0x3)
circuit_in.measure(qr[0], cr[0])
circuit_in.measure(qr[1], cr[1])
circuit_in.measure(qr[2], cr[2])
dag_in = circuit_to_dag(circuit_in)
dag_dependency = dag_to_dagdependency(dag_in, create_preds_and_succs=False)
dag_out = dagdependency_to_dag(dag_dependency)
self.assertEqual(dag_out, dag_in)
def test_metadata(self):
"""Test circuit metadata is preservered through conversion."""
meta_dict = {"experiment_id": "1234", "execution_number": 4}
qr = QuantumRegister(2)
circuit_in = QuantumCircuit(qr, metadata=meta_dict)
circuit_in.h(qr[0])
circuit_in.cx(qr[0], qr[1])
circuit_in.measure_all()
dag = circuit_to_dag(circuit_in)
self.assertEqual(dag.metadata, meta_dict)
dag_dependency = dag_to_dagdependency(dag)
self.assertEqual(dag_dependency.metadata, meta_dict)
dag_out = dagdependency_to_dag(dag_dependency)
self.assertEqual(dag_out.metadata, meta_dict)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/peiyong-addwater/Hackathon-QNLP
|
peiyong-addwater
|
import collections
import pickle
from tqdm.notebook import tqdm
import warnings
warnings.filterwarnings("ignore")
import os
from random import shuffle
import re
import spacy
from discopy.tensor import Tensor
from discopy import Word
from discopy.rigid import Functor
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from numpy import random, unique
from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader
from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser
from lambeq import Dataset
from lambeq import QuantumTrainer, SPSAOptimizer
from lambeq import TketModel
from lambeq import SpacyTokeniser
from pytket.extensions.qiskit import AerBackend
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer, PorterStemmer
from nltk import pos_tag, ne_chunk
from nltk.chunk import tree2conlltags
import seaborn as sns
import matplotlib.pyplot as plt
from collections import Counter
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')
nltk.download('omw-1.4')
pd.set_option('display.width', 1000)
pd.options.display.max_colwidth=80
print(os.getcwd())
warnings.filterwarnings("ignore")
os.environ["TOKENIZERS_PARALLELISM"] = "false"
spacy.load('en_core_web_sm')
TOTAL_DATA_RATIO = 0.1 # only use part of the data
MAX_LENGTH = 10 # only use short tweets
def get_sent_length(sent):
if type(sent) is not str:
return 9999999999999
word_list = sent.split(" ")
return len(word_list)
columns = ["Id","Entity","Target","Text"]
data = pd.read_csv(os.path.join(os.getcwd(),"data/twitter_training.csv"), names=columns,header=None)
#data = data.sample(frac=1).reset_index(drop=True)
data_val = pd.read_csv(os.path.join(os.getcwd(), "data/twitter_validation.csv"), names=columns,header=None)
#data_val = data.sample(frac=1).reset_index(drop=True)
df_train = data[["Text","Target"]]
df_train = df_train.loc[(df_train["Target"]=='Positive') | (df_train["Target"]=='Negative') & (df_train["Text"]!=np.nan)&(df_train["Text"].map(get_sent_length)<=MAX_LENGTH)]
df_train= df_train.drop_duplicates()
df_val = data_val[['Text', 'Target']]
df_val = df_val.loc[(df_val['Target'] == 'Positive') | (df_val['Target'] == 'Negative') & (df_val["Text"]!=np.nan)&(df_val["Text"].map(get_sent_length)<=MAX_LENGTH)]
text_cleaning_re = "@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+"
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
def preprocess(text):
text = re.sub(text_cleaning_re, ' ', str(text).lower()).strip()
without_emoji = emoji_pattern.sub(r'', text)
tokens = word_tokenize(str(without_emoji).replace("'", "").lower())
# Remove Puncs
without_punc = [w for w in tokens if w.isalpha()]
# Lemmatize
text_len = [WordNetLemmatizer().lemmatize(t) for t in without_punc]
# Stem
text_cleaned = [PorterStemmer().stem(w) for w in text_len]
return " ".join(text_cleaned)
df_train["Text"]= df_train["Text"].str.replace("im","i am")
df_train["Text"]= df_train["Text"].str.replace("i'm","i am")
df_train["Text"]= df_train["Text"].str.replace("I'm","i am")
df_train["Text"]= df_train["Text"].str.replace("it's","it is")
df_train["Text"]= df_train["Text"].str.replace("you're","you are")
df_train["Text"]= df_train["Text"].str.replace("hasn't","has not")
df_train["Text"]= df_train["Text"].str.replace("haven't","have not")
df_train["Text"]= df_train["Text"].str.replace("don't","do not")
df_train["Text"]= df_train["Text"].str.replace("doesn't","does not")
df_train["Text"]= df_train["Text"].str.replace("won't","will not")
df_train["Text"]= df_train["Text"].str.replace("shouldn't","should not")
df_train["Text"]= df_train["Text"].str.replace("can't","can not")
df_train["Text"]= df_train["Text"].str.replace("couldn't","could not")
df_val["Text"] = df_val["Text"].str.replace("im","i am")
df_val["Text"] = df_val["Text"].str.replace("i'm","i am")
df_val["Text"] = df_val["Text"].str.replace("I'm","i am")
df_val["Text"]= df_val["Text"].str.replace("it's","it is")
df_val["Text"]= df_val["Text"].str.replace("you're","you are")
df_val["Text"]= df_val["Text"].str.replace("hasn't","has not")
df_val["Text"]= df_val["Text"].str.replace("haven't","have not")
df_val["Text"] = df_val["Text"].str.replace("don't","do not")
df_val["Text"] = df_val["Text"].str.replace("doesn't","does not")
df_val["Text"] = df_val["Text"].str.replace("won't","will not")
df_val["Text"] = df_val["Text"].str.replace("shouldn't","should not")
df_val["Text"] = df_val["Text"].str.replace("can't","can not")
df_val["Text"] = df_val["Text"].str.replace("couldn't","could not")
df_train["Text"] = df_train["Text"].apply(preprocess)
df_val["Text"] = df_val["Text"].apply(preprocess)
df_train = df_train.dropna()
df_val = df_val.dropna()
# Positive sentiment to [0,1], negative sentiment to [1,0]
sentiment_train = []
sentiment_val = []
for i in df_train["Target"]:
if i == "Positive":
sentiment_train.append([0,1])
else:
sentiment_train.append([1,0])
df_train["Sentiment"] = sentiment_train
for i in df_val["Target"]:
if i == "Positive":
sentiment_val.append([0,1])
else:
sentiment_val.append([1,0])
df_val["Sentiment"] = sentiment_val
df_train.info()
df_val.info()
df_train.head()
df_val.head()
sns.countplot(x = "Target", data = df_train)
sns.countplot(x = "Target", data = df_val)
train_data_all, train_label_all, train_target_all = df_train["Text"].tolist(), df_train["Sentiment"].tolist(), df_train['Target'].tolist()
dev_data, dev_labels, dev_target = df_val["Text"].tolist(), df_val["Sentiment"].tolist(), df_val['Target'].tolist()
data = train_data_all+dev_data
labels = train_label_all+dev_labels
targets = train_target_all+dev_target
pairs = []
for c in zip(labels, data, targets):
if len(c[1]) > 0:
pairs.append(c)
random.seed(0)
random.shuffle(pairs)
N_EXAMPLES = len(pairs)
print("Total: {}".format(N_EXAMPLES))
parser = BobcatParser(verbose='text')
new_data = []
new_label = []
new_target = []
i = 0 # positive
j = 0 # negative
for label, sent, target in tqdm(pairs):
try:
diag = parser.sentence2diagram(sent)
except:
pass
else:
sent_length = len(sent.split(" "))
if i>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2 and j>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
break
if target == "Positive" and i<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
i = i + 1
if target == 'Negative' and j<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
j = j + 1
cleaned_qnlp_data = {"data":new_data, "label":new_label, "target":new_target}
pickle.dump(cleaned_qnlp_data, open("cleaned_qnlp_data_stem_lematize.pkl", "wb" ))
def get_sent_length(sent):
if type(sent) is not str:
return 9999999999999
word_list = sent.split(" ")
return len(word_list)
columns = ["Id","Entity","Target","Text"]
data = pd.read_csv(os.path.join(os.getcwd(),"data/twitter_training.csv"), names=columns,header=None)
#data = data.sample(frac=1).reset_index(drop=True)
data_val = pd.read_csv(os.path.join(os.getcwd(), "data/twitter_validation.csv"), names=columns,header=None)
#data_val = data.sample(frac=1).reset_index(drop=True)
df_train = data[["Text","Target"]]
df_train = df_train.loc[(df_train["Target"]=='Positive') | (df_train["Target"]=='Negative') & (df_train["Text"]!=np.nan)&(df_train["Text"].map(get_sent_length)<=MAX_LENGTH)]
df_train= df_train.drop_duplicates()
df_val = data_val[['Text', 'Target']]
df_val = df_val.loc[(df_val['Target'] == 'Positive') | (df_val['Target'] == 'Negative') & (df_val["Text"]!=np.nan)&(df_val["Text"].map(get_sent_length)<=MAX_LENGTH)]
text_cleaning_re = "@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+"
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
def preprocess(text):
text = re.sub(text_cleaning_re, ' ', str(text).lower()).strip()
without_emoji = emoji_pattern.sub(r'', text)
tokens = word_tokenize(str(without_emoji).replace("'", "").lower())
# Remove Puncs
without_punc = [w for w in tokens if w.isalpha()]
text_len = [WordNetLemmatizer().lemmatize(t) for t in without_punc]
return " ".join(text_len)
df_train["Text"]= df_train["Text"].str.replace("im","i am")
df_train["Text"]= df_train["Text"].str.replace("i'm","i am")
df_train["Text"]= df_train["Text"].str.replace("I'm","i am")
df_train["Text"]= df_train["Text"].str.replace("it's","it is")
df_train["Text"]= df_train["Text"].str.replace("you're","you are")
df_train["Text"]= df_train["Text"].str.replace("hasn't","has not")
df_train["Text"]= df_train["Text"].str.replace("haven't","have not")
df_train["Text"]= df_train["Text"].str.replace("don't","do not")
df_train["Text"]= df_train["Text"].str.replace("doesn't","does not")
df_train["Text"]= df_train["Text"].str.replace("won't","will not")
df_train["Text"]= df_train["Text"].str.replace("shouldn't","should not")
df_train["Text"]= df_train["Text"].str.replace("can't","can not")
df_train["Text"]= df_train["Text"].str.replace("couldn't","could not")
df_val["Text"] = df_val["Text"].str.replace("im","i am")
df_val["Text"] = df_val["Text"].str.replace("i'm","i am")
df_val["Text"] = df_val["Text"].str.replace("I'm","i am")
df_val["Text"]= df_val["Text"].str.replace("it's","it is")
df_val["Text"]= df_val["Text"].str.replace("you're","you are")
df_val["Text"]= df_val["Text"].str.replace("hasn't","has not")
df_val["Text"]= df_val["Text"].str.replace("haven't","have not")
df_val["Text"] = df_val["Text"].str.replace("don't","do not")
df_val["Text"] = df_val["Text"].str.replace("doesn't","does not")
df_val["Text"] = df_val["Text"].str.replace("won't","will not")
df_val["Text"] = df_val["Text"].str.replace("shouldn't","should not")
df_val["Text"] = df_val["Text"].str.replace("can't","can not")
df_val["Text"] = df_val["Text"].str.replace("couldn't","could not")
df_train["Text"] = df_train["Text"].apply(preprocess)
df_val["Text"] = df_val["Text"].apply(preprocess)
df_train = df_train.dropna()
df_val = df_val.dropna()
# Positive sentiment to [0,1], negative sentiment to [1,0]
sentiment_train = []
sentiment_val = []
for i in df_train["Target"]:
if i == "Positive":
sentiment_train.append([0,1])
else:
sentiment_train.append([1,0])
df_train["Sentiment"] = sentiment_train
for i in df_val["Target"]:
if i == "Positive":
sentiment_val.append([0,1])
else:
sentiment_val.append([1,0])
df_val["Sentiment"] = sentiment_val
train_data_all, train_label_all, train_target_all = df_train["Text"].tolist(), df_train["Sentiment"].tolist(), df_train['Target'].tolist()
dev_data, dev_labels, dev_target = df_val["Text"].tolist(), df_val["Sentiment"].tolist(), df_val['Target'].tolist()
data = train_data_all+dev_data
labels = train_label_all+dev_labels
targets = train_target_all+dev_target
pairs = []
for c in zip(labels, data, targets):
if len(c[1]) > 0:
pairs.append(c)
random.seed(0)
random.shuffle(pairs)
N_EXAMPLES = len(pairs)
print("Total: {}".format(N_EXAMPLES))
new_data = []
new_label = []
new_target = []
i = 0 # positive
j = 0 # negative
parser = BobcatParser(verbose='text')
for label, sent, target in tqdm(pairs):
try:
diag = parser.sentence2diagram(sent)
except:
pass
else:
sent_length = len(sent.split(" "))
if i>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2 and j>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
break
if target == "Positive" and i<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
i = i + 1
if target == 'Negative' and j<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
j = j + 1
cleaned_qnlp_data = {"data":new_data, "label":new_label, "target":new_target}
pickle.dump(cleaned_qnlp_data, open("cleaned_qnlp_data_lematize.pkl", "wb" ))
def get_sent_length(sent):
if type(sent) is not str:
return 9999999999999
word_list = sent.split(" ")
return len(word_list)
columns = ["Id","Entity","Target","Text"]
data = pd.read_csv(os.path.join(os.getcwd(),"data/twitter_training.csv"), names=columns,header=None)
#data = data.sample(frac=1).reset_index(drop=True)
data_val = pd.read_csv(os.path.join(os.getcwd(), "data/twitter_validation.csv"), names=columns,header=None)
#data_val = data.sample(frac=1).reset_index(drop=True)
df_train = data[["Text","Target"]]
df_train = df_train.loc[(df_train["Target"]=='Positive') | (df_train["Target"]=='Negative') & (df_train["Text"]!=np.nan)&(df_train["Text"].map(get_sent_length)<=MAX_LENGTH)]
df_train= df_train.drop_duplicates()
df_val = data_val[['Text', 'Target']]
df_val = df_val.loc[(df_val['Target'] == 'Positive') | (df_val['Target'] == 'Negative') & (df_val["Text"]!=np.nan)&(df_val["Text"].map(get_sent_length)<=MAX_LENGTH)]
text_cleaning_re = "@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+"
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
def preprocess(text):
text = re.sub(text_cleaning_re, ' ', str(text).lower()).strip()
without_emoji = emoji_pattern.sub(r'', text)
tokens = word_tokenize(str(without_emoji).replace("'", "").lower())
# Remove Puncs
without_punc = [w for w in tokens if w.isalpha()]
# text_len = [WordNetLemmatizer().lemmatize(t) for t in without_punc]
return " ".join(without_punc)
df_train["Text"]= df_train["Text"].str.replace("im","i am")
df_train["Text"]= df_train["Text"].str.replace("i'm","i am")
df_train["Text"]= df_train["Text"].str.replace("I'm","i am")
df_train["Text"]= df_train["Text"].str.replace("it's","it is")
df_train["Text"]= df_train["Text"].str.replace("you're","you are")
df_train["Text"]= df_train["Text"].str.replace("hasn't","has not")
df_train["Text"]= df_train["Text"].str.replace("haven't","have not")
df_train["Text"]= df_train["Text"].str.replace("don't","do not")
df_train["Text"]= df_train["Text"].str.replace("doesn't","does not")
df_train["Text"]= df_train["Text"].str.replace("won't","will not")
df_train["Text"]= df_train["Text"].str.replace("shouldn't","should not")
df_train["Text"]= df_train["Text"].str.replace("can't","can not")
df_train["Text"]= df_train["Text"].str.replace("couldn't","could not")
df_val["Text"] = df_val["Text"].str.replace("im","i am")
df_val["Text"] = df_val["Text"].str.replace("i'm","i am")
df_val["Text"] = df_val["Text"].str.replace("I'm","i am")
df_val["Text"]= df_val["Text"].str.replace("it's","it is")
df_val["Text"]= df_val["Text"].str.replace("you're","you are")
df_val["Text"]= df_val["Text"].str.replace("hasn't","has not")
df_val["Text"]= df_val["Text"].str.replace("haven't","have not")
df_val["Text"] = df_val["Text"].str.replace("don't","do not")
df_val["Text"] = df_val["Text"].str.replace("doesn't","does not")
df_val["Text"] = df_val["Text"].str.replace("won't","will not")
df_val["Text"] = df_val["Text"].str.replace("shouldn't","should not")
df_val["Text"] = df_val["Text"].str.replace("can't","can not")
df_val["Text"] = df_val["Text"].str.replace("couldn't","could not")
df_train["Text"] = df_train["Text"].apply(preprocess)
df_val["Text"] = df_val["Text"].apply(preprocess)
df_train = df_train.dropna()
df_val = df_val.dropna()
# Positive sentiment to [0,1], negative sentiment to [1,0]
sentiment_train = []
sentiment_val = []
for i in df_train["Target"]:
if i == "Positive":
sentiment_train.append([0,1])
else:
sentiment_train.append([1,0])
df_train["Sentiment"] = sentiment_train
for i in df_val["Target"]:
if i == "Positive":
sentiment_val.append([0,1])
else:
sentiment_val.append([1,0])
df_val["Sentiment"] = sentiment_val
train_data_all, train_label_all, train_target_all = df_train["Text"].tolist(), df_train["Sentiment"].tolist(), df_train['Target'].tolist()
dev_data, dev_labels, dev_target = df_val["Text"].tolist(), df_val["Sentiment"].tolist(), df_val['Target'].tolist()
data = train_data_all+dev_data
labels = train_label_all+dev_labels
targets = train_target_all+dev_target
pairs = []
for c in zip(labels, data, targets):
if len(c[1]) > 0:
pairs.append(c)
random.seed(0)
random.shuffle(pairs)
N_EXAMPLES = len(pairs)
print("Total: {}".format(N_EXAMPLES))
new_data = []
new_label = []
new_target = []
i = 0 # positive
j = 0 # negative
parser = BobcatParser(verbose='text')
for label, sent, target in tqdm(pairs):
try:
diag = parser.sentence2diagram(sent)
except:
pass
else:
sent_length = len(sent.split(" "))
if i>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2 and j>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
break
if target == "Positive" and i<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
i = i + 1
if target == 'Negative' and j<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
j = j + 1
cleaned_qnlp_data = {"data":new_data, "label":new_label, "target":new_target}
pickle.dump(cleaned_qnlp_data, open("cleaned_qnlp_data.pkl", "wb" ))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Kraus, SuperOp
from qiskit.visualization import plot_histogram
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_aer import AerSimulator
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (
NoiseModel,
QuantumError,
ReadoutError,
depolarizing_error,
pauli_error,
thermal_relaxation_error,
)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend("ibm_brisbane")
noise_model = NoiseModel.from_backend(backend)
# Construct a 1-qubit bit-flip and phase-flip errors
p_error = 0.05
bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])
phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])
print(bit_flip)
print(phase_flip)
# Compose two bit-flip and phase-flip errors
bitphase_flip = bit_flip.compose(phase_flip)
print(bitphase_flip)
# Tensor product two bit-flip and phase-flip errors with
# bit-flip on qubit-0, phase-flip on qubit-1
error2 = phase_flip.tensor(bit_flip)
print(error2)
# Convert to Kraus operator
bit_flip_kraus = Kraus(bit_flip)
print(bit_flip_kraus)
# Convert to Superoperator
phase_flip_sop = SuperOp(phase_flip)
print(phase_flip_sop)
# Convert back to a quantum error
print(QuantumError(bit_flip_kraus))
# Check conversion is equivalent to original error
QuantumError(bit_flip_kraus) == bit_flip
# Measurement misassignment probabilities
p0given1 = 0.1
p1given0 = 0.05
ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]])
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates
error = depolarizing_error(0.05, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
# Print noise model info
print(noise_model)
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only
error = depolarizing_error(0.05, 1)
noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0])
# Print noise model info
print(noise_model)
# System Specification
n_qubits = 4
circ = QuantumCircuit(n_qubits)
# Test Circuit
circ.h(0)
for qubit in range(n_qubits - 1):
circ.cx(qubit, qubit + 1)
circ.measure_all()
print(circ)
# Ideal simulator and execution
sim_ideal = AerSimulator()
result_ideal = sim_ideal.run(circ).result()
plot_histogram(result_ideal.get_counts(0))
# Example error probabilities
p_reset = 0.03
p_meas = 0.1
p_gate1 = 0.05
# QuantumError objects
error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)])
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)])
error_gate2 = error_gate1.tensor(error_gate1)
# Add errors to noise model
noise_bit_flip = NoiseModel()
noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset")
noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure")
noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"])
print(noise_bit_flip)
# Create noisy simulator backend
sim_noise = AerSimulator(noise_model=noise_bit_flip)
# Transpile circuit for noisy basis gates
passmanager = generate_preset_pass_manager(optimization_level=3, backend=sim_noise)
circ_tnoise = passmanager.run(circ)
# Run and get counts
result_bit_flip = sim_noise.run(circ_tnoise).result()
counts_bit_flip = result_bit_flip.get_counts(0)
# Plot noisy output
plot_histogram(counts_bit_flip)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
# Run the noisy simulation
sim_thermal = AerSimulator(noise_model=noise_thermal)
# Transpile circuit for noisy basis gates
passmanager = generate_preset_pass_manager(optimization_level=3, backend=sim_thermal)
circ_tthermal = passmanager.run(circ)
# Run and get counts
result_thermal = sim_thermal.run(circ_tthermal).result()
counts_thermal = result_thermal.get_counts(0)
# Plot noisy output
plot_histogram(counts_thermal)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Evaluator of observables for algorithms."""
from __future__ import annotations
from collections.abc import Sequence
from typing import Any
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import PauliSumOp
from qiskit.quantum_info import SparsePauliOp
from .exceptions import AlgorithmError
from .list_or_dict import ListOrDict
from ..primitives import BaseEstimator
from ..quantum_info.operators.base_operator import BaseOperator
def estimate_observables(
estimator: BaseEstimator,
quantum_state: QuantumCircuit,
observables: ListOrDict[BaseOperator | PauliSumOp],
parameter_values: Sequence[float] | None = None,
threshold: float = 1e-12,
) -> ListOrDict[tuple[complex, dict[str, Any]]]:
"""
Accepts a sequence of operators and calculates their expectation values - means
and metadata. They are calculated with respect to a quantum state provided. A user
can optionally provide a threshold value which filters mean values falling below the threshold.
Args:
estimator: An estimator primitive used for calculations.
quantum_state: A (parameterized) quantum circuit preparing a quantum state that expectation
values are computed against.
observables: A list or a dictionary of operators whose expectation values are to be
calculated.
parameter_values: Optional list of parameters values to evaluate the quantum circuit on.
threshold: A threshold value that defines which mean values should be neglected (helpful for
ignoring numerical instabilities close to 0).
Returns:
A list or a dictionary of tuples (mean, metadata).
Raises:
AlgorithmError: If a primitive job is not successful.
"""
if isinstance(observables, dict):
observables_list = list(observables.values())
else:
observables_list = observables
if len(observables_list) > 0:
observables_list = _handle_zero_ops(observables_list)
quantum_state = [quantum_state] * len(observables)
if parameter_values is not None:
parameter_values = [parameter_values] * len(observables)
try:
estimator_job = estimator.run(quantum_state, observables_list, parameter_values)
expectation_values = estimator_job.result().values
except Exception as exc:
raise AlgorithmError("The primitive job failed!") from exc
metadata = estimator_job.result().metadata
# Discard values below threshold
observables_means = expectation_values * (np.abs(expectation_values) > threshold)
# zip means and metadata into tuples
observables_results = list(zip(observables_means, metadata))
else:
observables_results = []
return _prepare_result(observables_results, observables)
def _handle_zero_ops(
observables_list: list[BaseOperator | PauliSumOp],
) -> list[BaseOperator | PauliSumOp]:
"""Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp``
operator."""
if observables_list:
zero_op = SparsePauliOp.from_list([("I" * observables_list[0].num_qubits, 0)])
for ind, observable in enumerate(observables_list):
if observable == 0:
observables_list[ind] = zero_op
return observables_list
def _prepare_result(
observables_results: list[tuple[complex, dict]],
observables: ListOrDict[BaseOperator | PauliSumOp],
) -> ListOrDict[tuple[complex, dict[str, Any]]]:
"""
Prepares a list of tuples of eigenvalues and metadata tuples from
``observables_results`` and ``observables``.
Args:
observables_results: A list of tuples (mean, metadata).
observables: A list or a dictionary of operators whose expectation values are to be
calculated.
Returns:
A list or a dictionary of tuples (mean, metadata).
"""
if isinstance(observables, list):
# by construction, all None values will be overwritten
observables_eigenvalues: ListOrDict[tuple[complex, complex]] = [None] * len(observables)
key_value_iterator = enumerate(observables_results)
else:
observables_eigenvalues = {}
key_value_iterator = zip(observables.keys(), observables_results)
for key, value in key_value_iterator:
observables_eigenvalues[key] = value
return observables_eigenvalues
|
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))
#retorna tamanho do tour apartir do stdout
def tamanho_tour(out):
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 = []
#Usando as mesmas entradas
for i in range(7):
print("Rodando entrada: "+str(i))
a = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '1')
b = roda_com_entrada('./busca-exaustiva/busca-exaustiva','busca-exaustiva/in-'+str(i)+'.txt', '1', '0')
tempos.append(a[1])
tempos_1.append(b[1])
tamanho_entradas.append(a[2])
plt.title("Comparacao Desempenho Busca Exaustiva")
plt.ylabel("Tempo (s)")
plt.xlabel("Tamanho entradas")
plt.plot(tamanho_entradas, tempos)
plt.plot(tamanho_entradas, tempos_1)
plt.legend(["Exaustivo Simples", "Exaustivo Branch and Bound"])
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_1)
df
|
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
|
alpine-quantum-technologies
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, Alpine Quantum Technologies 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from math import pi
import pytest
from pydantic import ValidationError
from qiskit import QuantumCircuit
from qiskit_aqt_provider import api_models
from qiskit_aqt_provider.circuit_to_aqt import circuits_to_aqt_job
def test_no_circuit() -> None:
"""Cannot convert an empty list of circuits to an AQT job request."""
with pytest.raises(ValidationError):
circuits_to_aqt_job([], shots=1)
def test_empty_circuit() -> None:
"""Circuits need at least one measurement operation."""
qc = QuantumCircuit(1)
with pytest.raises(ValueError):
circuits_to_aqt_job([qc], shots=1)
def test_just_measure_circuit() -> None:
"""Circuits with only measurement operations are valid."""
shots = 100
qc = QuantumCircuit(1)
qc.measure_all()
expected = api_models.JobSubmission(
job_type="quantum_circuit",
label="qiskit",
payload=api_models.QuantumCircuits(
circuits=[
api_models.QuantumCircuit(
repetitions=shots,
number_of_qubits=1,
quantum_circuit=api_models.Circuit(__root__=[api_models.Operation.measure()]),
),
]
),
)
result = circuits_to_aqt_job([qc], shots=shots)
assert result == expected
def test_valid_circuit() -> None:
"""A valid circuit with all supported basis gates."""
qc = QuantumCircuit(2)
qc.r(pi / 2, 0, 0)
qc.rz(pi / 5, 1)
qc.rxx(pi / 2, 0, 1)
qc.measure_all()
result = circuits_to_aqt_job([qc], shots=1)
expected = api_models.JobSubmission(
job_type="quantum_circuit",
label="qiskit",
payload=api_models.QuantumCircuits(
circuits=[
api_models.QuantumCircuit(
number_of_qubits=2,
repetitions=1,
quantum_circuit=api_models.Circuit(
__root__=[
api_models.Operation.r(theta=0.5, phi=0.0, qubit=0),
api_models.Operation.rz(phi=0.2, qubit=1),
api_models.Operation.rxx(theta=0.5, qubits=[0, 1]),
api_models.Operation.measure(),
]
),
),
]
),
)
assert result == expected
def test_invalid_gates_in_circuit() -> None:
"""Circuits must already be in the target basis when they are converted
to the AQT wire format.
"""
qc = QuantumCircuit(1)
qc.h(0) # not an AQT-resource basis gate
qc.measure_all()
with pytest.raises(ValueError, match="not in basis gate set"):
circuits_to_aqt_job([qc], shots=1)
def test_invalid_measurements() -> None:
"""Measurement operations can only be located at the end of the circuit."""
qc_invalid = QuantumCircuit(2, 2)
qc_invalid.r(pi / 2, 0.0, 0)
qc_invalid.measure([0], [0])
qc_invalid.r(pi / 2, 0.0, 1)
qc_invalid.measure([1], [1])
with pytest.raises(ValueError, match="at the end of the circuit"):
circuits_to_aqt_job([qc_invalid], shots=1)
# same circuit as above, but with the measurements at the end is valid
qc = QuantumCircuit(2, 2)
qc.r(pi / 2, 0.0, 0)
qc.r(pi / 2, 0.0, 1)
qc.measure([0], [0])
qc.measure([1], [1])
result = circuits_to_aqt_job([qc], shots=1)
expected = api_models.JobSubmission(
job_type="quantum_circuit",
label="qiskit",
payload=api_models.QuantumCircuits(
circuits=[
api_models.QuantumCircuit(
number_of_qubits=2,
repetitions=1,
quantum_circuit=api_models.Circuit(
__root__=[
api_models.Operation.r(theta=0.5, phi=0.0, qubit=0),
api_models.Operation.r(theta=0.5, phi=0.0, qubit=1),
api_models.Operation.measure(),
]
),
),
]
),
)
assert result == expected
def test_convert_multiple_circuits() -> None:
"""Convert multiple circuits. Check that the order is conserved."""
qc0 = QuantumCircuit(2)
qc0.r(pi / 2, 0.0, 0)
qc0.rxx(pi / 2, 0, 1)
qc0.measure_all()
qc1 = QuantumCircuit(1)
qc1.r(pi / 4, 0.0, 0)
qc1.measure_all()
result = circuits_to_aqt_job([qc0, qc1], shots=1)
expected = api_models.JobSubmission(
job_type="quantum_circuit",
label="qiskit",
payload=api_models.QuantumCircuits(
circuits=[
api_models.QuantumCircuit(
number_of_qubits=2,
repetitions=1,
quantum_circuit=api_models.Circuit(
__root__=[
api_models.Operation.r(theta=0.5, phi=0.0, qubit=0),
api_models.Operation.rxx(theta=0.5, qubits=[0, 1]),
api_models.Operation.measure(),
]
),
),
api_models.QuantumCircuit(
number_of_qubits=1,
repetitions=1,
quantum_circuit=api_models.Circuit(
__root__=[
api_models.Operation.r(theta=0.25, phi=0.0, qubit=0),
api_models.Operation.measure(),
]
),
),
],
),
)
assert result == expected
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.