repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
# qc-grader should be 0.18.11 (or higher)
import qc_grader
qc_grader.__version__
# Import all in one cell
import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer
import warnings
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.circuit.library import TwoLocal, EfficientSU2
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options
from qiskit_serverless import QiskitFunction, save_result, get_arguments, save_result, distribute_task, distribute_qiskit_function, IBMServerlessClient, QiskitFunction
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_transpiler_service.transpiler_service import TranspilerService
from qiskit_aer import AerSimulator
# Import for grader
from qc_grader.challenges.iqc_2024 import grade_lab3_qs_ex1, grade_lab3_qs_ex2
service = QiskitRuntimeService(channel="ibm_quantum")
# Specify a system to use for transpilation
real_backend = service.backend("ibm_brisbane")
# Qiskit Pattern Step 1: Map quantum circuits and operators (Define Ansatz and operators)
num_qubits = 3#Add your code here
rotation_blocks = ['ry','rz'] #Add your code here
entanglement_blocks = 'cz' #Add your code here
entanglement = 'full' #Add your code here
reps= 1
insert_barriers=True
# Define Ansatz
ansatz = TwoLocal(num_qubits= num_qubits, rotation_blocks= rotation_blocks, entanglement_blocks= entanglement_blocks, entanglement= entanglement, reps=reps , insert_barriers= insert_barriers) #Add your code here
# Define parameters
num_params = ansatz.num_parameters
# Qiskit Pattern Step 2: Optimize the circuit for quantum execution
optimization_level = 2
pm = generate_preset_pass_manager(backend=real_backend, optimization_level=optimization_level)
isa_circuit = pm.run(ansatz) # Add your code here
# Define Hamiltonian for VQE
pauli_op = SparsePauliOp(['ZII', 'IZI', 'IIZ'])
hamiltonian_isa = pauli_op.apply_layout(layout=isa_circuit.layout)
# Setup Qiskit Serverless Client and Qiskit Runtime client
client = IBMServerlessClient("hidden") # Add in your IBM Quantum Token to QiskitServerless Client
# For the challenge, we will be using QiskitRuntime Local testing mode. Change to True only if you wish to use real backend.
USE_RUNTIME_SERVICE = False
if USE_RUNTIME_SERVICE:
service = QiskitRuntimeService(
channel='ibm_quantum',
verify=False
)
else:
service = None
# Define the Qiskit Function
if USE_RUNTIME_SERVICE:
function = QiskitFunction(title= "vqe", entrypoint="vqe.py", working_dir="./vqe")
else:
function = QiskitFunction(title= "vqe" , entrypoint="vqe.py", working_dir="./vqe", dependencies=["qiskit_aer"])
# Upload the Qiskit Function using IBMServerlessClient
client.upload(function)
# Define input_arguments
input_arguments = {
"ansatz": isa_circuit, # Replace with your transpiled ansatz
"operator": hamiltonian_isa, # Replace with the hamiltonian operator
"method": "COBYLA", # Using COBYLA method for the optimizer
"service": service, # Add your code here
}
# Qiskit Pattern Step 3: Run the payload on backend
job = client.run("vqe", arguments= input_arguments) # Pass the arguments dict here)
# Submit your answer using following code
grade_lab3_qs_ex1(function, input_arguments, job)
# Expected result type: QiskitFunction, dict, Job
# Return jobid
job
# Check job completion status
job.status()
# Monitor log
logs = job.logs()
for log in logs.splitlines():
print(log)
# Return result from QiskitFunction job
job.result()
# Qiskit Pattern Step 4: Postprocess and analyze the Estimator V2 results
result = job.result()
plt.style.use('ggplot')
fig, ax = plt.subplots()
plt.plot(range(result["iters"]), result["cost_history"], ls='--', c='k')
plt.xlabel("Energy")
plt.ylabel("Cost")
plt.draw()
# Setup 3 circuits with Efficient SU2
num_qubits = [41, 51, 61]
circuits = [EfficientSU2(nq, su2_gates=["rz","ry"], entanglement="circular", reps=1).decompose() for nq in num_qubits]
# Setup Qiskit Runtime Service backend
# QiskitRuntimeService.save_account(
# channel="ibm_quantum",
# token="YOUR_IBM_QUANTUM_TOKEN",
# set_as_default=True,
# # Use 'overwrite=True' if you're updating your token.
# overwrite=True,
# )
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibm_brisbane")
# Define Configs
optimization_levels = [1,2,3] # Add your code here
pass_managers = [{'pass_manager': generate_preset_pass_manager(optimization_level=level, backend=backend), 'optimization_level': level} for level in optimization_levels]
transpiler_services = [
{'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': False, 'optimization_level': 3},
{'service': TranspilerService(backend_name="ibm_brisbane", ai="true", optimization_level=3,), 'ai': True, 'optimization_level': 3}
]
configs = pass_managers + transpiler_services
# Local transpilation setup
def transpile_parallel_local(circuit: QuantumCircuit, config):
"""Transpilation for an abstract circuit into an ISA circuit for a given config."""
transpiled_circuit = config.run(circuit)
return transpiled_circuit
# Run local transpilation
warnings.filterwarnings("ignore")
start = timer()
# Run transpilations locally for baseline
results = []
for circuit in circuits:
for config in configs:
if 'pass_manager' in config:
results.append(transpile_parallel_local(circuit, config['pass_manager']))
else:
results.append(transpile_parallel_local(circuit, config['service']))
end = timer()
# Record local execution time
execution_time_local = end - start
print("Execution time locally: ", execution_time_local)
# Authenticate to the remote cluster and submit the pattern for remote execution if not done in previous exercise
serverless = IBMServerlessClient("hidden")
transpile_parallel_function = QiskitFunction(
title="transpile_parallel",
entrypoint="transpile_parallel.py",
working_dir="./transpile_parallel",
dependencies=["qiskit-transpiler-service"]
)
serverless.upload(transpile_parallel_function) # Add your code here
# Get list of functions
serverless.list()
# Fetch the specific function titled "transpile_parallel"
transpile_parallel_serverless = serverless.get("transpile_parallel") # Add your code here
# Run the "transpile_parallel" function in the serverless environment
job = transpile_parallel_serverless.run(
circuits= circuits, # Add your code here,
backend_name= backend # Add your code here
)
# Submit your answer using following code
grade_lab3_qs_ex2(optimization_levels, transpiler_services, transpile_parallel_function, transpile_parallel_serverless, job)
# Expected result type: list, list, QiskitFunction, QiskitFunction, Job
job.status()
logs = job.logs()
for log in logs.splitlines():
print(log)
result = job.result()
result_transpiled = result["transpiled_circuits"]
# Compare execution times:
execution_time_serverless = result["execution_time"]
from utils import plot_execution_times
plot_execution_times(execution_time_serverless, execution_time_local)
from utils import process_transpiled_circuits
best_circuits, best_depths, best_methods = process_transpiled_circuits(configs, result_transpiled)
# Display the best circuits, depths, and methods
for i, (circuit, depth, method) in enumerate(zip(best_circuits, best_depths, best_methods)):
print(f"Best result for circuit {i + 1}:")
print(f" Depth: {depth}")
print(f" Method: {method}")
# Display or process the best circuit as needed
# e.g., circuit.draw(output="mpl")
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### removed cx gate ###
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### removed h gate ###
return qc
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.opflow import I, X, Y, Z
print(I, X, Y, Z)
print(1.5 * I)
print(2.5 * X)
print(X + 2.0 * Y)
print(X^Y^Z)
print(X @ Y @ Z)
print((X + Y) @ (Y + Z))
print((X + Y) ^ (Y + Z))
(I, X)
2.0 * X^Y^Z
print(1.1 * ((1.2 * X)^(Y + (1.3 * Z))))
from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H,
DictStateFn, VectorStateFn, CircuitStateFn, OperatorStateFn)
print(Zero, One)
print(Plus, Minus)
print(Zero.eval('0'))
print(Zero.eval('1'))
print(One.eval('1'))
print(Plus.eval('0'))
print(Minus.eval('1'))
One.adjoint()
~One
(2.0 + 3.0j) * Zero
print(Zero + One)
import math
v_zero_one = (Zero + One) / math.sqrt(2)
print(v_zero_one)
print(Plus + Minus)
print(~One @ One)
(~One @ One).eval()
(~v_zero_one @ v_zero_one).eval()
(~Minus @ One).eval()
print((~One).compose(One))
(~One).eval(One)
print(Zero^Plus)
print((Zero^Plus).to_circuit_op())
print(600 * ((One^5) + (Zero^5)))
print((One^Zero)^3)
print(((Plus^Minus)^2).to_matrix_op())
print(((Plus^One)^2).to_circuit_op())
print(((Plus^One)^2).to_matrix_op().sample())
print(StateFn({'0':1}))
print(StateFn({'0':1}) == Zero)
print(StateFn([0,1,1,0]))
from qiskit.circuit.library import RealAmplitudes
print(StateFn(RealAmplitudes(2)))
from qiskit.opflow import X, Y, Z, I, CX, T, H, S, PrimitiveOp
X
print(X.eval('0'))
X.eval('0').eval('1')
print(CX)
print(CX.to_matrix().real) # The imaginary part vanishes.
CX.eval('01') # 01 is the one in decimal. We get the first column.
CX.eval('01').eval('11') # This returns element with (zero-based) index (1, 3)
print(X @ One)
(X @ One).eval()
X.eval(One)
print(((~One^2) @ (CX.eval('01'))).eval())
print(((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2)
print((((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) @ (Minus^5))
print(((H^I^I)@(X^I^I)@Zero))
print(~One @ Minus)
from qiskit.opflow import ListOp
print((~ListOp([One, Zero]) @ ListOp([One, Zero])))
print((~ListOp([One, Zero]) @ ListOp([One, Zero])).reduce())
print(StateFn(Z).adjoint())
StateFn(Z).adjoint()
print(StateFn(Z).adjoint().eval(Zero))
print(StateFn(Z).adjoint().eval(One))
print(StateFn(Z).adjoint().eval(Plus))
import numpy as np
from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki
from qiskit.circuit import Parameter
from qiskit import Aer
two_qubit_H2 = (-1.0523732 * I^I) + \
(0.39793742 * I^Z) + \
(-0.3979374 * Z^I) + \
(-0.0112801 * Z^Z) + \
(0.18093119 * X^X)
print(two_qubit_H2)
evo_time = Parameter('θ')
evolution_op = (evo_time*two_qubit_H2).exp_i()
print(evolution_op) # Note, EvolvedOps print as exponentiations
print(repr(evolution_op))
h2_measurement = StateFn(two_qubit_H2).adjoint()
print(h2_measurement)
bell = CX @ (I ^ H) @ Zero
print(bell)
evo_and_meas = h2_measurement @ evolution_op @ bell
print(evo_and_meas)
trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas)
# We can also set trotter_mode='suzuki' or leave it empty to default to first order Trotterization.
print(trotterized_op)
bound = trotterized_op.bind_parameters({evo_time: .5})
bound[1].to_circuit().draw()
# Note that XX was the only non-diagonal measurement in our H2 Observable
print(PauliExpectation(group_paulis=False).convert(h2_measurement))
print(PauliExpectation().convert(h2_measurement))
diagonalized_meas_op = PauliExpectation().convert(trotterized_op)
print(diagonalized_meas_op)
evo_time_points = list(range(8))
h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points})
h2_trotter_expectations.eval()
sampler = CircuitSampler(backend=Aer.get_backend('aer_simulator'))
# sampler.quantum_instance.run_config.shots = 1000
sampled_trotter_exp_op = sampler.convert(h2_trotter_expectations)
sampled_trotter_energies = sampled_trotter_exp_op.eval()
print('Sampled Trotterized energies:\n {}'.format(np.real(sampled_trotter_energies)))
print('Before:\n')
print(h2_trotter_expectations.reduce()[0][0])
print('\nAfter:\n')
print(sampled_trotter_exp_op[0][0])
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/strangequarkkk/BB84-Protocol-for-QKD
|
strangequarkkk
|
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
qc.barrier()
# Alice now sends the qubit to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
# Alice now sends the qubit to Bob
# but Eve intercepts and tries to read it
qc.measure(0, 0)
qc.barrier()
# Eve then passes this on to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
n = 100
## Step 1
# Alice generates bits.
alice_bits = np.random.randint(0,2,n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = np.random.randint(0,2,n)
# Function to compare the bits & bases generated by alice, and then 'encode' the message. Basically determines the state of the qubit/photon to send.
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
# Alice computes the encoded message using the function defined above.
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = np.random.randint(0,2,n)
# Function to decode the message sent by alice by comparing qubit/photon states with Bob's generated bases.
def measure_message(message, bases):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(n):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
# Decode the message according to his bases
bob_results = measure_message(message, bob_bases)
## Step 4
# Function to perform sifting i.e. disregard the bits for which Bob's & A;ice's bases didnot match.
def remove_garbage(a_bases, b_bases, bits):
good_bits = []
for q in range(n):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
# Performing sifting for Alice's and Bob's bits.
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print("Alice's key after sifting (without interception)", alice_key)
print("Bob's key after sifting (without interception) ", bob_key)
# # Step 5
# # Function for parameter estimation i.e. determining the error rate by comparing subsets taen from both Alice's key & Bob's key.
# def sample_bits(bits, selection):
# sample = []
# for i in selection:
# # use np.mod to make sure the
# # bit we sample is always in
# # the list range
# i = np.mod(i, len(bits))
# # pop(i) removes the element of the
# # list at index 'i'
# sample.append(bits.pop(i))
# return sample
# # Performing parameter estimation & disregarding the bits used for comparison from Alice's & Bob's key.
# sample_size = 15
# bit_selection = np.random.randint(0,n,size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
## Step 1
alice_bits = np.random.randint(2, size=n)
## Step 2
alice_bases = np.random.randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = np.random.randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = np.random.randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print("Alice's key after sifting (with interception)", alice_key)
print("Bob's key after sifting (with interception) ", bob_key)
# ## Step 5
# sample_size = 15
# bit_selection = np.random.randint(n, size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
plt.rcParams['axes.linewidth'] = 2
mpl.rcParams['font.family'] = ['Georgia']
plt.figure(figsize=(10.5,6))
ax=plt.axes()
ax.set_title('')
ax.set_xlabel('$n$ (Number of bits drawn from the sifted keys for determining error rate)',fontsize = 18,labelpad=10)
ax.set_ylabel(r'$P(Eve\ detected)$',fontsize = 18,labelpad=10)
ax.xaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.yaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
ax. xaxis. label. set_size(20)
ax. yaxis. label. set_size(20)
n = 30
x = np.arange(n+1)
y = 1 - 0.75**x
ax.plot(x,y,color = plt.cm.rainbow(np.linspace(0, 1, 5))[0], marker = "s", markerfacecolor='r')
|
https://github.com/ughyper3/grover-quantum-algorithm
|
ughyper3
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/0tt3r/QuaC-qiskit
|
0tt3r
|
# -*- coding: utf-8 -*-
"""In this example, two-qubit Bell states are generated using the plugin. Additionally,
a Quac noise model is applied.
"""
import math
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit.visualization import plot_histogram
from quac_qiskit import Quac
from quac_qiskit.models import QuacNoiseModel
def main():
circuit = QuantumCircuit(2, 2)
circuit.u2(0, math.pi, 0)
circuit.cx(0, 1)
circuit.measure_all()
circuit2 = QuantumCircuit(2, 2)
circuit2.h(0)
circuit2.cx(0, 1)
circuit2.measure_all()
print("Available QuaC backends:")
print(Quac.backends())
simulator = Quac.get_backend('generic_counts_simulator',
n_qubits=2,
max_shots=10000,
max_exp=75,
basis_gates=['u1', 'u2', 'u3', 'cx']) # generic backends require extra parameters
# Noise model with T1, T2, and measurement error terms
noise_model = QuacNoiseModel(
[1000, 1000],
[50000, 50000],
[np.eye(2), np.array([[0.95, 0.1], [0.05, 0.9]])],
None
)
# Execute the circuit on the QuaC simulator
job = execute([circuit, circuit2], simulator, shots=1000, quac_noise_model=noise_model)
print(job.result())
print(job.result().get_counts())
plot_histogram(job.result().get_counts(), title="Bell States Example")
plt.show()
if __name__ == '__main__':
main()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (5,3), dpi = 100)
p = np.arange(0,1.01,0.01)
plt.plot(p, p, label = r'$p$'); plt.plot(p, 3*p**2-2*p**3, label = r'$p_{e}$')
plt.xlim(0,1); plt.ylim(-0.01,1.01); plt.legend(); plt.xlabel('p'); plt.show()
from qiskit import *
def qc_coding_bf(th, ph):
qc = QuantumCircuit(3, name = 'Coding BF')
qc.u(th, ph, 0, 0)
qc.barrier()
qc.cx(0,1); qc.cx(1,2)
return qc
qc_coding_bf_ = qc_coding_bf(math.pi, math.pi/4); qc_coding_bf_.draw(output = 'mpl')
qc = QuantumCircuit(3, 1); qc.cx([0], [2]); qc.cx([1], [2]); qc.measure([2], 0); qc.draw(output = 'mpl')
qc = QuantumCircuit(5, 2); qc.u(0.1, 0.2, 0.2, [0]); qc.cx([0], [1]); qc.cx([1], [2]); qc.barrier()
qc.cx([0], [3]); qc.cx([1], [3]); qc.cx([1], [4]); qc.cx([2], [4]); qc.barrier(); qc.measure([3, 4], [0, 1])
qc.draw(output = 'mpl')
def qc_ec_bf(th, ph, lb, j):
qc = QuantumCircuit(5, name = 'EC_BF')
qc.u(th, ph, lb, [0]) # qubit state preparation
qc.barrier()
qc.cx([0], [1]); qc.cx([1], [2]) # encoding
qc.barrier()
if j == 0 or j == 1 or j == 2: # error
qc.x([j])
qc.barrier()
qc.cx([0], [3]); qc.cx([1], [3]); qc.cx([1], [4]); qc.cx([2], [4]) # syndrome detection
qc.barrier()
qc.x([3]); qc.ccx([4], [3], [2]); qc.x([3]); qc.ccx([4], [3], [1]) # correction
qc.x([4]); qc.ccx([4], [3], [0]); qc.x([4]) # correction
qc.barrier()
return qc
th, ph, lb = math.pi, 0.0, 0.0; j = 2; qc_ec_bf_ = qc_ec_bf(th, ph, lb, j)
qc_ec_bf_.draw(output = 'mpl')
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
#provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
#device = provider.get_backend('ibmq_jakarta')
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_bogota')
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.tools.monitor import backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
qc = QuantumCircuit(5, 3);
j = 0 # sets the error
qc_ec_bf_ = qc_ec_bf(math.pi/2, 0.0, 0.0, j); qc.append(qc_ec_bf_, [0, 1, 2, 3, 4])
qc.measure([0, 1, 2], [0, 1, 2])
qc.decompose().draw(output = 'mpl')
job_sim = execute(qc, backend = simulator, shots = nshots).result()
plot_histogram(job_sim.get_counts(qc))
job_exp = execute(qc, backend = device, shots = nshots)
print(job_exp.job_id()); job_monitor(job_exp)
plot_histogram(job_exp.result().get_counts(qc))
qc = QuantumCircuit(2, 1)
qc.u(1,2,3, [1])
qc.barrier()
qc.h([0]); qc.cz(0, 1); qc.h([0]);
qc.measure(0,0); qc.draw(output = 'mpl')
qc = QuantumCircuit(2, 1);
qc.u(1,2,3, 1);
qc.barrier()
qc.cx(1,0); qc.measure(0,0); qc.draw(output = 'mpl')
qc = QuantumCircuit(2, 1);
qc.u(1,2,3, 1)
qc.barrier()
qc.h(0); qc.cx(0,1); qc.h(0); qc.measure(0,0);
qc.draw(output = 'mpl')
qc = QuantumCircuit(2, 1);
qc.u(1,2,3, [1]);
qc.barrier()
qc.h(1); qc.cx(1,0); qc.h(1); qc.measure(0,0);
qc.draw(output = 'mpl')
qc = QuantumCircuit(2, 1);
qc.u(0.1, 0.2, 0.3, [1])
qc.barrier()
qc.h(0); qc.cu(0.4, 0.5, 0.6, 0.0, [0], [1]); qc.h([0]); qc.measure([0], [0])
qc.draw(output = 'mpl')
qc = QuantumCircuit(2, 1)
th, ph, lb = math.pi, 0.0, 0.0; qc.u(th, ph, lb, [0]) # state preparation
qc.barrier(); qc.cx([0], [1]); qc.barrier()
qc.x([0]); qc.barrier()
qc.cx([0], [1]); qc.cx([1], [0])
qc.measure([0], [0])
qc.draw(output = 'mpl')
job = execute(qc, backend = simulator, shots = nshots)
plot_histogram(job.result().get_counts(qc))
job = execute(qc, backend = device, shots = nshots); job_monitor(job)
plot_histogram(job.result().get_counts(qc))
# quantum circuit for bit flip error mitigation
def qc_em_bf():
qc = QuantumCircuit(2, name = 'EM_BF')
qc.cx([0], [1]); qc.cx([0], [1]); qc.cx([1], [0]); qc.reset([1])
return qc
qc_em_bf_ = qc_em_bf(); qc_em_bf_.draw(output = 'mpl')
N = 5; qc = QuantumCircuit(1, N); qc.x([0]);
for j in range(0, N):
qc.id([0]); qc.measure([0],[j])
job = execute(qc, backend = simulator, shots = nshots)
qc.draw(output = 'mpl')
plot_histogram(job.result().get_counts(qc))
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
N = 5; qc = QuantumCircuit(2, N); qc.x([0]);
for j in range(0, N):
qc_em_bf_ = qc_em_bf(); qc.append(qc_em_bf_, [0, 1]); qc.measure([0],[j])
job = execute(qc, backend = simulator, shots = nshots)
qc.decompose().draw(output = 'mpl')
plot_histogram(job.result().get_counts(qc))
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
import math
qc = QuantumCircuit(2, 1)
th, ph, lb = math.pi, 0.0, 0.0; qc.u(th, ph, lb, [0]) # state preparation
qc.barrier(); qc.cx([0], [1]); qc.barrier()
qc.z([0]); qc.x([0]); qc.h([0]); qc.barrier()
qc.cx([0], [1]); qc.cx([1], [0]); qc.measure([0], [0])
qc.draw(output = 'mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.72" # Two Hydrogen atoms, 0.72 Angstrom apart
)
molecule = driver.run()
from qiskit_nature.second_q.mappers import QubitConverter, ParityMapper
qubit_converter = QubitConverter(ParityMapper())
hamiltonian = qubit_converter.convert(molecule.second_q_ops()[0])
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
sol = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian)
real_solution = molecule.interpret(sol)
real_solution.groundenergy
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator"
from qiskit.algorithms.minimum_eigensolvers import VQE
# Use RealAmplitudes circuit to create trial states
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=2)
# Search for better states using SPSA algorithm
from qiskit.algorithms.optimizers import SPSA
optimizer = SPSA(150)
# Set a starting point for reproduceability
import numpy as np
np.random.seed(6)
initial_point = np.random.uniform(-np.pi, np.pi, 12)
# Create an object to store intermediate results
from dataclasses import dataclass
@dataclass
class VQELog:
values: list
parameters: list
def update(self, count, parameters, mean, _metadata):
self.values.append(mean)
self.parameters.append(parameters)
print(f"Running circuit {count} of ~350", end="\r", flush=True)
log = VQELog([],[])
# Main calculation
with Session(service=service, backend=backend) as session:
options = Options()
options.optimization_level = 3
vqe = VQE(Estimator(session=session, options=options),
ansatz, optimizer, callback=log.update, initial_point=initial_point)
result = vqe.compute_minimum_eigenvalue(hamiltonian)
print("Experiment complete.".ljust(30))
print(f"Raw result: {result.optimal_value}")
if 'simulator' not in backend:
# Run once with ZNE error mitigation
options.resilience_level = 2
vqe = VQE(Estimator(session=session, options=options),
ansatz, SPSA(1), initial_point=result.optimal_point)
result = vqe.compute_minimum_eigenvalue(hamiltonian)
print(f"Mitigated result: {result.optimal_value}")
import matplotlib.pyplot as plt
plt.rcParams["font.size"] = 14
# Plot energy and reference value
plt.figure(figsize=(12, 6))
plt.plot(log.values, label="Estimator VQE")
plt.axhline(y=real_solution.groundenergy, color="tab:red", ls="--", label="Target")
plt.legend(loc="best")
plt.xlabel("Iteration")
plt.ylabel("Energy [H]")
plt.title("VQE energy")
plt.show()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Statevector
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.estimation import EuropeanCallPricing
from qiskit_finance.circuit.library import NormalDistribution
# Set upper and lower data values
bounds = np.array([0.0, 7.0])
# Set number of qubits used in the uncertainty model
num_qubits = 3
# Load the trained circuit parameters
g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]
# Set an initial state for the generator circuit
init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds)
# construct the variational form
var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1)
# keep a list of the parameters so we can associate them to the list of numerical values
# (otherwise we need a dictionary)
theta = var_form.ordered_parameters
# compose the generator circuit, this is the circuit loading the uncertainty model
g_circuit = init_dist.compose(var_form)
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2
# set the approximation scaling for the payoff function
c_approx = 0.25
# Evaluate trained probability distribution
values = [
bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits)
]
uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params)))
amplitudes = Statevector.from_instruction(uncertainty_model).data
x = np.array(values)
y = np.abs(amplitudes) ** 2
# Sample from target probability distribution
N = 100000
log_normal = np.random.lognormal(mean=1, sigma=1, size=N)
log_normal = np.round(log_normal)
log_normal = log_normal[log_normal <= 7]
log_normal_samples = []
for i in range(8):
log_normal_samples += [np.sum(log_normal == i)]
log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples))
# Plot distributions
plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue")
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.plot(
log_normal_samples,
"-o",
color="deepskyblue",
label="target distribution",
linewidth=4,
markersize=12,
)
plt.legend(loc="best")
plt.show()
# Evaluate payoff for different distributions
payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5])
ep = np.dot(log_normal_samples, payoff)
print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep)
ep_trained = np.dot(y, payoff)
print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained)
# Plot exact payoff function (evaluated on the grid of the trained uncertainty model)
x = np.array(values)
y_strike = np.maximum(0, x - strike_price)
plt.plot(x, y_strike, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# construct circuit for payoff function
european_call_pricing = EuropeanCallPricing(
num_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % ep_trained)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Exception for errors raised by Qiskit Aer simulators backends.
"""
from qiskit import QiskitError
class AerError(QiskitError):
"""Base class for errors raised by simulators."""
def __init__(self, *message):
"""Set the error message."""
super().__init__(*message)
self.message = ' '.join(message)
def __str__(self):
"""Return the message."""
return repr(self.message)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Unit tests for zero-noise extrapolation."""
import functools
from typing import List
import cirq
import numpy as np
import pytest
import qiskit
import qiskit.circuit
from qiskit_aer import AerSimulator
from mitiq import QPROGRAM, SUPPORTED_PROGRAM_TYPES
from mitiq.benchmarks.randomized_benchmarking import generate_rb_circuits
from mitiq.interface import accept_any_qprogram_as_input, convert_from_mitiq
from mitiq.interface.mitiq_cirq import (
compute_density_matrix,
sample_bitstrings,
)
from mitiq.interface.mitiq_qiskit import (
execute_with_shots_and_noise,
initialized_depolarizing_noise,
)
from mitiq.observable import Observable, PauliString
from mitiq.zne import (
execute_with_zne,
inference,
mitigate_executor,
scaling,
zne_decorator,
)
from mitiq.zne.inference import (
AdaExpFactory,
LinearFactory,
PolyFactory,
RichardsonFactory,
)
from mitiq.zne.scaling import (
fold_gates_at_random,
get_layer_folding,
insert_id_layers,
)
BASE_NOISE = 0.007
TEST_DEPTH = 30
ONE_QUBIT_GS_PROJECTOR = np.array([[1, 0], [0, 0]])
npX = np.array([[0, 1], [1, 0]])
"""Defines the sigma_x Pauli matrix in SU(2) algebra as a (2,2) `np.array`."""
npZ = np.array([[1, 0], [0, -1]])
"""Defines the sigma_z Pauli matrix in SU(2) algebra as a (2,2) `np.array`."""
# Default qubit register and circuit for unit tests
qreg = cirq.GridQubit.rect(2, 1)
circ = cirq.Circuit(cirq.ops.H.on_each(*qreg), cirq.measure_each(*qreg))
@accept_any_qprogram_as_input
def generic_executor(circuit, noise_level: float = 0.1) -> float:
"""Executor that simulates a circuit of any type and returns
the expectation value of the ground state projector."""
noisy_circuit = circuit.with_noise(cirq.depolarize(p=noise_level))
result = cirq.DensityMatrixSimulator().simulate(noisy_circuit)
return result.final_density_matrix[0, 0].real
# Default executor for unit tests
def executor(circuit) -> float:
wavefunction = circuit.final_state_vector(
ignore_terminal_measurements=True
)
return np.real(wavefunction.conj().T @ np.kron(npX, npZ) @ wavefunction)
@pytest.mark.parametrize(
"executor", (sample_bitstrings, compute_density_matrix)
)
def test_with_observable_batched_factory(executor):
observable = Observable(PauliString(spec="Z"))
circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0))) * 20
noisy_value = observable.expectation(circuit, sample_bitstrings)
zne_value = execute_with_zne(
circuit,
executor=functools.partial(
executor, noise_model_function=cirq.depolarize
),
observable=observable,
factory=PolyFactory(scale_factors=[1, 3, 5], order=2),
)
true_value = observable.expectation(
circuit, functools.partial(compute_density_matrix, noise_level=(0,))
)
assert abs(zne_value - true_value) <= abs(noisy_value - true_value)
@pytest.mark.parametrize(
"executor", (sample_bitstrings, compute_density_matrix)
)
def test_with_observable_adaptive_factory(executor):
observable = Observable(PauliString(spec="Z"))
circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0))) * 20
noisy_value = observable.expectation(circuit, sample_bitstrings)
zne_value = execute_with_zne(
circuit,
executor=functools.partial(
executor, noise_model_function=cirq.amplitude_damp
),
observable=observable,
factory=AdaExpFactory(steps=4, asymptote=0.5),
)
true_value = observable.expectation(
circuit, functools.partial(compute_density_matrix, noise_level=(0,))
)
assert abs(zne_value - true_value) <= abs(noisy_value - true_value)
def test_with_observable_two_qubits():
observable = Observable(
PauliString(spec="XX", coeff=-1.21), PauliString(spec="ZZ", coeff=0.7)
)
circuit = cirq.Circuit(
cirq.H.on(cirq.LineQubit(0)), cirq.CNOT.on(*cirq.LineQubit.range(2))
)
circuit += [circuit.copy(), cirq.inverse(circuit.copy())] * 20
executor = compute_density_matrix
noisy_value = observable.expectation(circuit, executor)
zne_value = execute_with_zne(
circuit,
executor=functools.partial(
executor, noise_model_function=cirq.depolarize
),
observable=observable,
factory=PolyFactory(scale_factors=[1, 3, 5], order=2),
)
true_value = observable.expectation(
circuit, functools.partial(executor, noise_level=(0,))
)
assert abs(zne_value - true_value) <= 3 * abs(noisy_value - true_value)
@pytest.mark.parametrize(
"fold_method",
[
fold_gates_at_random,
insert_id_layers,
],
)
@pytest.mark.parametrize("factory", [LinearFactory, RichardsonFactory])
@pytest.mark.parametrize("num_to_average", [1, 2, 5])
def test_execute_with_zne_no_noise(fold_method, factory, num_to_average):
"""Tests execute_with_zne with noiseless simulation."""
zne_value = execute_with_zne(
circ,
executor,
num_to_average=num_to_average,
scale_noise=fold_method,
factory=factory([1.0, 2.0, 3.0]),
)
assert np.isclose(zne_value, 0.0)
@pytest.mark.parametrize("factory", [LinearFactory, RichardsonFactory])
@pytest.mark.parametrize(
"fold_method",
[
fold_gates_at_random,
insert_id_layers,
],
)
def test_averaging_improves_zne_value_with_fake_noise(factory, fold_method):
"""Tests that averaging with Gaussian noise produces a better ZNE value
compared to not averaging with several folding methods.
For non-deterministic folding, the ZNE value with average should be better.
For deterministic folding, the ZNE value should be the same.
"""
for seed in range(5):
rng = np.random.RandomState(seed)
def noisy_executor(circuit) -> float:
return executor(circuit) + rng.randn()
zne_value_no_averaging = execute_with_zne(
circ,
noisy_executor,
num_to_average=1,
scale_noise=fold_gates_at_random,
factory=factory([1.0, 2.0, 3.0]),
)
zne_value_averaging = execute_with_zne(
circ,
noisy_executor,
num_to_average=10,
scale_noise=fold_method,
factory=factory([1.0, 2.0, 3.0]),
)
# True (noiseless) value is zero. Averaging should ==> closer to zero.
assert abs(zne_value_averaging) <= abs(zne_value_no_averaging)
def test_execute_with_zne_bad_arguments():
"""Tests errors are raised when execute_with_zne is called with bad
arguments.
"""
with pytest.raises(TypeError, match="Argument `factory` must be of type"):
execute_with_zne(circ, executor, factory=RichardsonFactory)
with pytest.raises(TypeError, match="Argument `scale_noise` must be"):
execute_with_zne(circ, executor, scale_noise=None)
def test_error_zne_decorator():
"""Tests that the proper error is raised if the decorator is
used without parenthesis.
"""
with pytest.raises(TypeError, match="Decorator must be used with paren"):
@zne_decorator
def test_executor(circuit):
return 0
def test_doc_is_preserved():
"""Tests that the doc of the original executor is preserved."""
def first_executor(circuit):
"""Doc of the original executor."""
return 0
mit_executor = mitigate_executor(first_executor)
assert mit_executor.__doc__ == first_executor.__doc__
@zne_decorator()
def second_executor(circuit):
"""Doc of the original executor."""
return 0
assert second_executor.__doc__ == first_executor.__doc__
def qiskit_measure(circuit, qid) -> qiskit.QuantumCircuit:
"""Helper function to measure one qubit."""
# Ensure that we have a classical register of enough size available
if len(circuit.clbits) == 0:
reg = qiskit.ClassicalRegister(qid + 1, "cbits")
circuit.add_register(reg)
circuit.measure(0, qid)
return circuit
def qiskit_executor(qp: QPROGRAM, shots: int = 10000) -> float:
# initialize a qiskit noise model
expectation = execute_with_shots_and_noise(
qp,
shots=shots,
obs=ONE_QUBIT_GS_PROJECTOR,
noise_model=initialized_depolarizing_noise(BASE_NOISE),
seed=1,
)
return expectation
def get_counts(circuit: qiskit.QuantumCircuit):
return AerSimulator().run(circuit, shots=100).result().get_counts()
def test_qiskit_execute_with_zne():
true_zne_value = 1.0
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
zne_value = execute_with_zne(circuit, qiskit_executor)
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
@zne_decorator()
def qiskit_decorated_executor(qp: QPROGRAM) -> float:
return qiskit_executor(qp)
def batched_qiskit_executor(circuits) -> List[float]:
return [qiskit_executor(circuit) for circuit in circuits]
def test_qiskit_mitigate_executor():
true_zne_value = 1.0
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
mitigated_executor = mitigate_executor(qiskit_executor)
zne_value = mitigated_executor(circuit)
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
batched_mitigated_executor = mitigate_executor(batched_qiskit_executor)
batched_zne_values = batched_mitigated_executor([circuit] * 3)
assert [
abs(true_zne_value - batched_zne_value) < abs(true_zne_value - base)
for batched_zne_value in batched_zne_values
]
def test_qiskit_zne_decorator():
true_zne_value = 1.0
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
zne_value = qiskit_decorated_executor(circuit)
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
def test_qiskit_run_factory_with_number_of_shots():
true_zne_value = 1.0
scale_factors = [1.0, 3.0]
shot_list = [10_000, 30_000]
fac = inference.ExpFactory(
scale_factors=scale_factors,
shot_list=shot_list,
asymptote=0.5,
)
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
zne_value = fac.run(
circuit,
qiskit_executor,
scale_noise=scaling.fold_gates_at_random,
).reduce()
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
for i in range(len(fac._instack)):
assert fac._instack[i] == {
"scale_factor": scale_factors[i],
"shots": shot_list[i],
}
def test_qiskit_mitigate_executor_with_shot_list():
true_zne_value = 1.0
scale_factors = [1.0, 3.0]
shot_list = [10_000, 30_000]
fac = inference.ExpFactory(
scale_factors=scale_factors,
shot_list=shot_list,
asymptote=0.5,
)
mitigated_executor = mitigate_executor(qiskit_executor, factory=fac)
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
zne_value = mitigated_executor(circuit)
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
for i in range(len(fac._instack)):
assert fac._instack[i] == {
"scale_factor": scale_factors[i],
"shots": shot_list[i],
}
@pytest.mark.parametrize("order", [(0, 1), (1, 0), (0, 1, 2), (1, 2, 0)])
def test_qiskit_measurement_order_is_preserved_single_register(order):
"""Tests measurement order is preserved when folding, i.e., the dictionary
of counts is the same as the original circuit on a noiseless simulator.
"""
qreg, creg = (
qiskit.QuantumRegister(len(order)),
qiskit.ClassicalRegister(len(order)),
)
circuit = qiskit.QuantumCircuit(qreg, creg)
circuit.x(qreg[0])
for i in order:
circuit.measure(qreg[i], creg[i])
folded = scaling.fold_gates_at_random(circuit, scale_factor=1.0)
assert get_counts(folded) == get_counts(circuit)
def test_qiskit_measurement_order_is_preserved_two_registers():
"""Tests measurement order is preserved when folding, i.e., the dictionary
of counts is the same as the original circuit on a noiseless simulator.
"""
n = 4
qreg = qiskit.QuantumRegister(n)
creg1, creg2 = (
qiskit.ClassicalRegister(n // 2),
qiskit.ClassicalRegister(n // 2),
)
circuit = qiskit.QuantumCircuit(qreg, creg1, creg2)
circuit.x(qreg[0])
circuit.x(qreg[2])
# Some order of measurements.
circuit.measure(qreg[0], creg2[1])
circuit.measure(qreg[1], creg1[0])
circuit.measure(qreg[2], creg1[1])
circuit.measure(qreg[3], creg2[1])
folded = scaling.fold_gates_at_random(circuit, scale_factor=1.0)
assert get_counts(folded) == get_counts(circuit)
@pytest.mark.parametrize("circuit_type", SUPPORTED_PROGRAM_TYPES.keys())
def test_execute_with_zne_with_supported_circuits(circuit_type):
# Define a circuit equivalent to the identity
qreg = cirq.LineQubit.range(2)
cirq_circuit = cirq.Circuit(
cirq.H.on_each(qreg),
cirq.CNOT(*qreg),
cirq.CNOT(*qreg),
cirq.H.on_each(qreg),
)
# Convert to one of the supported program types
circuit = convert_from_mitiq(cirq_circuit, circuit_type)
expected = generic_executor(circuit, noise_level=0.0)
unmitigated = generic_executor(circuit)
# Use odd scale factors for deterministic results
fac = RichardsonFactory([1.0, 3.0, 5.0])
zne_value = execute_with_zne(circuit, generic_executor, factory=fac)
# Test zero noise limit is better than unmitigated expectation value
assert abs(unmitigated - expected) > abs(zne_value - expected)
@pytest.mark.parametrize("circuit_type", SUPPORTED_PROGRAM_TYPES.keys())
def test_layerwise_execute_with_zne_with_supported_circuits(circuit_type):
# Define a circuit equivalent to the identity
qreg = cirq.LineQubit.range(2)
cirq_circuit = cirq.Circuit(
cirq.H.on_each(qreg),
cirq.CNOT(*qreg),
cirq.CNOT(*qreg),
cirq.H.on_each(qreg),
)
# Convert to one of the supported program types
circuit = convert_from_mitiq(cirq_circuit, circuit_type)
expected = generic_executor(circuit, noise_level=0.0)
unmitigated = generic_executor(circuit)
# Use odd scale factors for deterministic results
fac = RichardsonFactory([1, 3, 5])
# Layerwise-fold
layer_to_fold = 0
fold_layer_func = get_layer_folding(layer_to_fold)
zne_value = execute_with_zne(
circuit, generic_executor, factory=fac, scale_noise=fold_layer_func
)
# Test zero noise limit is better than unmitigated expectation value
assert abs(unmitigated - expected) > abs(zne_value - expected)
def test_execute_with_zne_transpiled_qiskit_circuit():
"""Tests ZNE when transpiling to a Qiskit device. Note transpiling can
introduce idle (unused) qubits to the circuit.
"""
from qiskit_ibm_runtime.fake_provider import FakeSantiago
santiago = FakeSantiago()
backend = AerSimulator.from_backend(santiago)
def execute(circuit: qiskit.QuantumCircuit, shots: int = 8192) -> float:
job = backend.run(circuit, shots=shots)
return job.result().get_counts().get("00", 0.0) / shots
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circuit = qiskit.QuantumCircuit(qreg, creg)
for _ in range(10):
circuit.x(qreg)
circuit.measure(qreg, creg)
circuit = qiskit.transpile(circuit, backend, optimization_level=0)
true_value = 1.0
zne_value = execute_with_zne(circuit, execute)
# Note: Unmitigated value is also (usually) within 10% of the true value.
# This is more to test usage than effectiveness.
assert abs(zne_value - true_value) < 0.1
def test_execute_zne_on_qiskit_circuit_with_QFT():
"""Tests ZNE of a Qiskit device with a QFT gate."""
def qs_noisy_simulation(
circuit: qiskit.QuantumCircuit, shots: int = 1
) -> float:
noise_model = initialized_depolarizing_noise(noise_level=0.02)
backend = AerSimulator(noise_model=noise_model)
job = backend.run(circuit.decompose(), shots=shots)
return job.result().get_counts().get("0", 0.0) / shots
circuit = qiskit.QuantumCircuit(1)
circuit &= qiskit.circuit.library.QFT(1)
circuit.measure_all()
mitigated = execute_with_zne(circuit, qs_noisy_simulation)
assert abs(mitigated) < 1000
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
from argparse import ArgumentParser, Namespace, BooleanOptionalAction
from qiskit import QuantumCircuit as qc
from qiskit import QuantumRegister as qr
from qiskit import transpile
from qiskit_aer import AerSimulator
from qiskit.result import Counts
from matplotlib.pyplot import show, subplots, xticks, yticks
from math import pi, sqrt
from heapq import nlargest
class GroversAlgorithm:
def __init__(self,
title: str = "Grover's Algorithm",
n_qubits: int = 5,
search: set[int] = { 11, 9, 0, 3 },
shots: int = 1000,
fontsize: int = 10,
print: bool = False,
combine_states: bool = False) -> None:
"""
_summary_
Args:
title (str, optional): Window title. Defaults to "Grover's Algorithm".
n_qubits (int, optional): Number of qubits. Defaults to 5.
search (set[int], optional): Set of nonnegative integers to search for using Grover's algorithm. Defaults to { 11, 9, 0, 3 }.
shots (int, optional): Amount of times the algorithm is simulated. Defaults to 10000.
fontsize (int, optional): Histogram's font size. Defaults to 10.
print (bool, optional): Whether or not to print quantum circuit(s). Defaults to False.
combine_states (bool, optional): Whether to combine all non-winning states into 1 bar labeled "Others" or not. Defaults to False.
"""
# Parsing command line arguments
self._parser: ArgumentParser = ArgumentParser(description = "Run grover's algorithm via command line", add_help = False)
self._init_parser(title, n_qubits, search, shots, fontsize, print, combine_states)
self._args: Namespace = self._parser.parse_args()
# Set of nonnegative ints to search for
self.search: set[int] = set(self._args.search)
# Set of m N-qubit binary strings representing target state(s) (i.e. self.search in base 2)
self._targets: set[str] = { f"{s:0{self._args.n_qubits}b}" for s in self.search }
# N-qubit quantum register
self._qubits: qr = qr(self._args.n_qubits, "qubit")
def _print_circuit(self, circuit: qc, name: str) -> None:
"""Print quantum circuit.
Args:
circuit (qc): Quantum circuit to print.
name (str): Quantum circuit's name.
"""
print(f"\n{name}:\n{circuit}")
def _oracle(self, targets: set[str]) -> qc:
"""Mark target state(s) with negative phase.
Args:
targets (set[str]): N-qubit binary string(s) representing target state(s).
Returns:
qc: Quantum circuit representation of oracle.
"""
# Create N-qubit quantum circuit for oracle
oracle = qc(self._qubits, name = "Oracle")
for target in targets:
# Reverse target state since Qiskit uses little-endian for qubit ordering
target = target[::-1]
# Flip zero qubits in target
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Simulate (N - 1)-control Z gate
# 1. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# 2. (N - 1)-control Toffoli gate
oracle.mcx(list(range(self._args.n_qubits - 1)), self._args.n_qubits - 1)
# 3. Hadamard gate
oracle.h(self._args.n_qubits - 1)
# Flip back to original state
for i in range(self._args.n_qubits):
if target[i] == "0":
# Pauli-X gate
oracle.x(i)
# Display oracle, if applicable
if self._args.print: self._print_circuit(oracle, "ORACLE")
return oracle
def _diffuser(self) -> qc:
"""Amplify target state(s) amplitude, which decreases the amplitudes of other states
and increases the probability of getting the correct solution (i.e. target state(s)).
Returns:
qc: Quantum circuit representation of diffuser (i.e. Grover's diffusion operator).
"""
# Create N-qubit quantum circuit for diffuser
diffuser = qc(self._qubits, name = "Diffuser")
# Hadamard gate
diffuser.h(self._qubits)
# Oracle with all zero target state
diffuser.append(self._oracle({"0" * self._args.n_qubits}), list(range(self._args.n_qubits)))
# Hadamard gate
diffuser.h(self._qubits)
# Display diffuser, if applicable
if self._args.print: self._print_circuit(diffuser, "DIFFUSER")
return diffuser
def _grover(self) -> qc:
"""Create quantum circuit representation of Grover's algorithm,
which consists of 4 parts: (1) state preparation/initialization,
(2) oracle, (3) diffuser, and (4) measurement of resulting state.
Steps 2-3 are repeated an optimal number of times (i.e. Grover's
iterate) in order to maximize probability of success of Grover's algorithm.
Returns:
qc: Quantum circuit representation of Grover's algorithm.
"""
# Create N-qubit quantum circuit for Grover's algorithm
grover = qc(self._qubits, name = "Grover Circuit")
# Intialize qubits with Hadamard gate (i.e. uniform superposition)
grover.h(self._qubits)
# # Apply barrier to separate steps
grover.barrier()
# Apply oracle and diffuser (i.e. Grover operator) optimal number of times
for _ in range(int((pi / 4) * sqrt((2 ** self._args.n_qubits) / len(self._targets)))):
grover.append(self._oracle(self._targets), list(range(self._args.n_qubits)))
grover.append(self._diffuser(), list(range(self._args.n_qubits)))
# Measure all qubits once finished
grover.measure_all()
# Display grover circuit, if applicable
if self._args.print: self._print_circuit(grover, "GROVER CIRCUIT")
return grover
def _outcome(self, winners: list[str], counts: Counts) -> None:
"""Print top measurement(s) (state(s) with highest frequency)
and target state(s) in binary and decimal form, determine
if top measurement(s) equals target state(s), then print result.
Args:
winners (list[str]): State(s) (N-qubit binary string(s))
with highest probability of being measured.
counts (Counts): Each state and its respective frequency.
"""
print("WINNER(S):")
print(f"Binary = {winners}\nDecimal = {[ int(key, 2) for key in winners ]}\n")
print("TARGET(S):")
print(f"Binary = {self._targets}\nDecimal = {self.search}\n")
if not all(key in self._targets for key in winners): print("Target(s) not found...")
else:
winners_frequency, total = 0, 0
for value, frequency in counts.items():
if value in winners:
winners_frequency += frequency
total += frequency
print(f"Target(s) found with {winners_frequency / total:.2%} accuracy!")
def _show_histogram(self, histogram_data) -> None:
"""Print outcome and display histogram of simulation results.
Args:
data: Each state and its respective frequency.
"""
# State(s) with highest count and their frequencies
winners = { winner : histogram_data.get(winner) for winner in nlargest(len(self._targets), histogram_data, key = histogram_data.get) }
# Print outcome
self._outcome(list(winners.keys()), histogram_data)
# X-axis and y-axis value(s) for winners, respectively
winners_x_axis = [ str(winner) for winner in [*winners] ]
winners_y_axis = [ *winners.values() ]
# All other states (i.e. non-winners) and their frequencies
others = { state : frequency for state, frequency in histogram_data.items() if state not in winners }
# X-axis and y-axis value(s) for all other states, respectively
other_states_x_axis = "Others" if self._args.combine else [*others]
other_states_y_axis = [ sum([*others.values()]) ] if self._args.combine else [ *others.values() ]
# Create histogram for simulation results
figure, axes = subplots(num = "Grover's Algorithm — Results", layout = "constrained")
axes.bar(winners_x_axis, winners_y_axis, color = "green", label = "Target")
axes.bar(other_states_x_axis, other_states_y_axis, color = "red", label = "Non-target")
axes.legend(fontsize = self._args.fontsize)
axes.grid(axis = "y", ls = "dashed")
axes.set_axisbelow(True)
# Set histogram title, x-axis title, and y-axis title respectively
axes.set_title(f"Outcome of {self._args.shots} Simulations", fontsize = int(self._args.fontsize * 1.45))
axes.set_xlabel("States (Qubits)", fontsize = int(self._args.fontsize * 1.3))
axes.set_ylabel("Frequency", fontsize = int(self._args.fontsize * 1.3))
# Set font properties for x-axis and y-axis labels respectively
xticks(fontsize = self._args.fontsize, family = "monospace", rotation = 0 if self._args.combine else 70)
yticks(fontsize = self._args.fontsize, family = "monospace")
# Set properties for annotations displaying frequency above each bar
annotation = axes.annotate("",
xy = (0, 0),
xytext = (5, 5),
xycoords = "data",
textcoords = "offset pixels",
ha = "center",
va = "bottom",
family = "monospace",
weight = "bold",
fontsize = self._args.fontsize,
bbox = dict(facecolor = "white", alpha = 0.4, edgecolor = "None", pad = 0)
)
def _hover(event) -> None:
"""Display frequency above each bar upon hovering over it.
Args:
event: Matplotlib event.
"""
visibility = annotation.get_visible()
if event.inaxes == axes:
for bars in axes.containers:
for bar in bars:
cont, _ = bar.contains(event)
if cont:
x, y = bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height()
annotation.xy = (x, y)
annotation.set_text(y)
annotation.set_visible(True)
figure.canvas.draw_idle()
return
if visibility:
annotation.set_visible(False)
figure.canvas.draw_idle()
# Display histogram
id = figure.canvas.mpl_connect("motion_notify_event", _hover)
show()
figure.canvas.mpl_disconnect(id)
def run(self) -> None:
"""
Run Grover's algorithm simulation.
"""
# Simulate Grover's algorithm locally
backend = AerSimulator(method = "density_matrix")
# Generate optimized grover circuit for simulation
transpiled_circuit = transpile(self._grover(), backend, optimization_level = 2)
# Run Grover's algorithm simulation
job = backend.run(transpiled_circuit, shots = self._args.shots)
# Get simulation results
results = job.result()
# Get each state's histogram data (including frequency) from simulation results
data = results.get_counts()
# Display simulation results
self._show_histogram(data)
def _init_parser(self,
title: str,
n_qubits: int,
search: set[int],
shots: int,
fontsize: int,
print: bool,
combine_states: bool) -> None:
"""
Helper method to initialize command line argument parser.
Args:
title (str): Window title.
n_qubits (int): Number of qubits.
search (set[int]): Set of nonnegative integers to search for using Grover's algorithm.
shots (int): Amount of times the algorithm is simulated.
fontsize (int): Histogram's font size.
print (bool): Whether or not to print quantum circuit(s).
combine_states (bool): Whether to combine all non-winning states into 1 bar labeled "Others" or not.
"""
self._parser.add_argument("-H, --help",
action = "help",
help = "show this help message and exit")
self._parser.add_argument("-T, --title",
type = str,
default = title,
dest = "title",
metavar = "<title>",
help = f"window title (default: \"{title}\")")
self._parser.add_argument("-n, --n-qubits",
type = int,
default = n_qubits,
dest = "n_qubits",
metavar = "<n_qubits>",
help = f"number of qubits (default: {n_qubits})")
self._parser.add_argument("-s, --search",
default = search,
type = int,
nargs = "+",
dest = "search",
metavar = "<search>",
help = f"nonnegative integers to search for with Grover's algorithm (default: {search})")
self._parser.add_argument("-S, --shots",
type = int,
default = shots,
dest = "shots",
metavar = "<shots>",
help = f"amount of times the algorithm is simulated (default: {shots})")
self._parser.add_argument("-f, --font-size",
type = int,
default = fontsize,
dest = "fontsize",
metavar = "<font_size>",
help = f"histogram's font size (default: {fontsize})")
self._parser.add_argument("-p, --print",
action = BooleanOptionalAction,
type = bool,
default = print,
dest = "print",
help = f"whether or not to print quantum circuit(s) (default: {print})")
self._parser.add_argument("-c, --combine",
action = BooleanOptionalAction,
type = bool,
default = combine_states,
dest = "combine",
help = f"whether to combine all non-winning states into 1 bar labeled \"Others\" or not (default: {combine_states})")
if __name__ == "__main__":
GroversAlgorithm().run()
|
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/Qiskit/feedback
|
Qiskit
|
from qiskit import *
q = QuantumRegister(3,'q')
c = ClassicalRegister(2,'c')
q1 = QuantumRegister(4,'q1')
c1 = ClassicalRegister(2,'c1')
res = ClassicalRegister(1,'r')
backend = Aer.get_backend('qasm_simulator')
qc = QuantumCircuit(q,c,res)
qc.x([0,1])
qc.measure([0,1],[0,1])
qc.h(2).c_if([c[0],c[1]],3)
qc.measure(2,res)
qjob = execute(qc,backend)
counts = qjob.result().get_counts()
print(counts)
qc.draw('mpl', cregbundle=False)
qc1 = QuantumCircuit(q,c,c1,res)
qc1.x([0,1])
qc1.measure([0,1],[c[0],c1[0]])
qc1.h(2).c_if([c[0],c1[1]],2)
qc1.measure(2,res)
qjob1 = execute(qc1,backend)
counts = qjob1.result().get_counts()
print(counts)
qc1.draw('mpl',cregbundle=False)
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Purity RB analysis class.
"""
from typing import List, Dict, Union
from qiskit.result import sampled_expectation_value
from qiskit_experiments.curve_analysis import ScatterTable
import qiskit_experiments.curve_analysis as curve
from qiskit_experiments.framework import AnalysisResultData
from qiskit_experiments.library.randomized_benchmarking import RBAnalysis
from qiskit_experiments.library.randomized_benchmarking.rb_analysis import (_calculate_epg,
_exclude_1q_error)
class PurityRBAnalysis(RBAnalysis):
r"""A class to analyze purity randomized benchmarking experiments.
# section: overview
This analysis takes only single series.
This series is fit by the exponential decay function.
From the fit :math:`\alpha` value this analysis estimates the error per Clifford (EPC).
When analysis option ``gate_error_ratio`` is provided, this analysis also estimates
errors of individual gates assembling a Clifford gate.
In computation of two-qubit EPC, this analysis can also decompose
the contribution from the underlying single qubit depolarizing channels when
``epg_1_qubit`` analysis option is provided [1].
# section: fit_model
.. math::
F(x) = a \alpha^x + b
# section: fit_parameters
defpar a:
desc: Height of decay curve.
init_guess: Determined by :math:`1 - b`.
bounds: [0, 1]
defpar b:
desc: Base line.
init_guess: Determined by :math:`(1/2)^n` where :math:`n` is number of qubit.
bounds: [0, 1]
defpar \alpha:
desc: Depolarizing parameter.
init_guess: Determined by :func:`~.guess.rb_decay`.
bounds: [0, 1]
# section: reference
.. ref_arxiv:: 1 1712.06550
"""
def __init__(self):
super().__init__()
def _run_data_processing(
self,
raw_data: List[Dict],
category: str = "raw",
) -> ScatterTable:
"""Perform data processing from the experiment result payload.
For purity this converts the counts into Trace(rho^2) and then runs the
rest of the standard RB fitters
For now this does it by spoofing a new counts dictionary and then
calling the super _run_data_processing
Args:
raw_data: Payload in the experiment data.
category: Category string of the output dataset.
Returns:
Processed data that will be sent to the formatter method.
Raises:
DataProcessorError: When key for x values is not found in the metadata.
ValueError: When data processor is not provided.
"""
#figure out the number of qubits... has to be 1 or 2 for now
if self.options.outcome=='0':
nq=1
elif self.options.outcome=='00':
nq=2
else:
raise ValueError("Only supporting 1 or 2Q purity")
ntrials = int(len(raw_data)/3**nq)
raw_data2 = []
nshots = int(sum(raw_data[0]['counts'].values()))
for i in range(ntrials):
trial_raw = [d for d in raw_data if d["metadata"]["trial"]==i]
raw_data2.append(trial_raw[0])
purity = 1/2**nq
if nq==1:
for ii in range(3):
purity += sampled_expectation_value(trial_raw[ii]['counts'],'Z')**2/2**nq
else:
for ii in range(9):
purity += sampled_expectation_value(trial_raw[ii]['counts'],'ZZ')**2/2**nq
purity += sampled_expectation_value(trial_raw[ii]['counts'],'IZ')**2/2**nq/3**(nq-1)
purity += sampled_expectation_value(trial_raw[ii]['counts'],'ZI')**2/2**nq/3**(nq-1)
raw_data2[-1]['counts'] = {'0'*nq: int(purity*nshots*10),'1'*nq: int((1-purity)*nshots*10)}
return super()._run_data_processing(raw_data2,category)
def _create_analysis_results(
self,
fit_data: curve.CurveFitResult,
quality: str,
**metadata,
) -> List[AnalysisResultData]:
"""Create analysis results for important fit parameters.
Args:
fit_data: Fit outcome.
quality: Quality of fit outcome.
Returns:
List of analysis result data.
"""
outcomes = curve.CurveAnalysis._create_analysis_results(self, fit_data, quality, **metadata)
num_qubits = len(self._physical_qubits)
# Calculate EPC
# For purity we need to correct by
alpha = fit_data.ufloat_params["alpha"]**0.5
scale = (2**num_qubits - 1) / (2**num_qubits)
epc = scale * (1 - alpha)
outcomes.append(
AnalysisResultData(
name="EPC",
value=epc,
chisq=fit_data.reduced_chisq,
quality=quality,
extra=metadata,
)
)
# Correction for 1Q depolarizing channel if EPGs are provided
if self.options.epg_1_qubit and num_qubits == 2:
epc = _exclude_1q_error(
epc=epc,
qubits=self._physical_qubits,
gate_counts_per_clifford=self._gate_counts_per_clifford,
extra_analyses=self.options.epg_1_qubit,
)
outcomes.append(
AnalysisResultData(
name="EPC_corrected",
value=epc,
chisq=fit_data.reduced_chisq,
quality=quality,
extra=metadata,
)
)
# Calculate EPG
if self._gate_counts_per_clifford is not None and self.options.gate_error_ratio:
epg_dict = _calculate_epg(
epc=epc,
qubits=self._physical_qubits,
gate_error_ratio=self.options.gate_error_ratio,
gate_counts_per_clifford=self._gate_counts_per_clifford,
)
if epg_dict:
for gate, epg_val in epg_dict.items():
outcomes.append(
AnalysisResultData(
name=f"EPG_{gate}",
value=epg_val,
chisq=fit_data.reduced_chisq,
quality=quality,
extra=metadata,
)
)
return outcomes
def _generate_fit_guesses(
self,
user_opt: curve.FitOptions,
curve_data: curve.ScatterTable,
) -> Union[curve.FitOptions, List[curve.FitOptions]]:
"""Create algorithmic initial fit guess from analysis options and curve data.
Args:
user_opt: Fit options filled with user provided guess and bounds.
curve_data: Formatted data collection to fit.
Returns:
List of fit options that are passed to the fitter function.
"""
user_opt.bounds.set_if_empty(
a=(0, 1),
alpha=(0, 1),
b=(0, 1),
)
b_guess = 1 / 2 ** len(self._physical_qubits)
if len(curve_data.x)>3:
alpha_guess = curve.guess.rb_decay(curve_data.x[0:3], curve_data.y[0:3], b=b_guess)
else:
alpha_guess = curve.guess.rb_decay(curve_data.x, curve_data.y, b=b_guess)
alpha_guess = alpha_guess**2
if alpha_guess < 0.6:
a_guess = (curve_data.y[0] - b_guess)
else:
a_guess = (curve_data.y[0] - b_guess) / (alpha_guess ** curve_data.x[0])
user_opt.p0.set_if_empty(
b=b_guess,
a=a_guess,
alpha=alpha_guess,
)
return user_opt
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
%load_ext autoreload
%autoreload 2
from qiskit.circuit.library.standard_gates import RXGate, RZGate, RYGate, CXGate, CZGate, SGate, HGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
import numpy as np
def get_linear_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3):
quantum_register = QuantumRegister(num_of_qubits, name="qubit")
quantum_circuit = QuantumCircuit(quantum_register)
quantum_circuit.initialize(input_state)
for iteration in range(circuit_depth):
for qubit_index in range(num_of_qubits):
RY_theta_index = iteration*2*num_of_qubits + qubit_index
RZ_theta_index = RY_theta_index + num_of_qubits
quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]])
quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]])
for qubit_index in range(num_of_qubits - 1):
quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[qubit_index + 1]])
for qubit_index in range(num_of_qubits):
RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index
RZ_theta_index = RY_theta_index + num_of_qubits
quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]])
quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]])
return quantum_circuit
def get_full_entangelment_ansatz(num_of_qubits, thetas, input_state, circuit_depth=3):
quantum_register = QuantumRegister(num_of_qubits, name="qubit")
quantum_circuit = QuantumCircuit(quantum_register)
quantum_circuit.initialize(input_state)
for iteration in range(circuit_depth):
for qubit_index in range(num_of_qubits):
RY_theta_index = iteration*2*num_of_qubits + qubit_index
RZ_theta_index = RY_theta_index + num_of_qubits
quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]])
quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]])
for qubit_index in range(num_of_qubits - 1):
for target_qubit_index in range(qubit_index + 1, num_of_qubits):
quantum_circuit.append(CXGate(), [quantum_register[qubit_index], quantum_register[target_qubit_index]])
for qubit_index in range(num_of_qubits):
RY_theta_index = 2*num_of_qubits*circuit_depth + qubit_index
RZ_theta_index = RY_theta_index + num_of_qubits
quantum_circuit.append(RYGate(thetas[RY_theta_index]), [quantum_register[qubit_index]])
quantum_circuit.append(RZGate(thetas[RZ_theta_index]), [quantum_register[qubit_index]])
return quantum_circuit
initial_thetas = np.random.uniform(low=0, high=360, size=32)
initial_eigenvector = np.identity(16)[0]
print(get_linear_entangelment_ansatz(4, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24)
initial_eigenvector = np.identity(8)[0]
print(get_linear_entangelment_ansatz(3, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16)
initial_eigenvector = np.identity(4)[0]
print(get_linear_entangelment_ansatz(2, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=32)
initial_eigenvector = np.identity(16)[0]
print(get_full_entangelment_ansatz(4, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=24)
initial_eigenvector = np.identity(8)[0]
print(get_full_entangelment_ansatz(3, initial_thetas, 3))
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=16)
initial_eigenvector = np.identity(4)[0]
print(get_full_entangelment_ansatz(2, initial_thetas, 3))
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
# %load imports.py
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
import ipywidgets as widgets
widgets.IntSlider()
widgets.FloatSlider()
widgets.FloatLogSlider()
widgets.IntRangeSlider()
widgets.FloatRangeSlider()
widgets.IntProgress(75)
widgets.FloatProgress(98)
widgets.BoundedIntText(7)
widgets.BoundedFloatText(7, step=0.1)
widgets.IntText(7)
widgets.FileUpload(
accept='', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf'
multiple=False # True to accept multiple files upload else False
)
widgets.Controller(
index=0,
)
out = widgets.Output(layout={'border': '1px solid black'})
from IPython.display import YouTubeVideo
with out:
display(YouTubeVideo('eWzY2nGfkXk'))
out
from ipywidgets import Layout, Button, Box
items_layout = Layout( width='auto') # override the default width of the button to 'auto' to let the button grow
box_layout = Layout(display='flex',
flex_flow='column',
align_items='stretch',
border='solid',
width='50%')
words = ['correct', 'horse', 'battery', 'staple']
items = [Button(description=word, layout=items_layout, button_style='danger') for word in words]
box = Box(children=items, layout=box_layout)
box
from ipywidgets import Layout, Button, Box, VBox
# Items flex proportionally to the weight and the left over space around the text
items_auto = [
Button(description='weight=1; auto', layout=Layout(flex='1 1 auto', width='auto'), button_style='danger'),
Button(description='weight=3; auto', layout=Layout(flex='3 1 auto', width='auto'), button_style='danger'),
Button(description='weight=1; auto', layout=Layout(flex='1 1 auto', width='auto'), button_style='danger'),
]
# Items flex proportionally to the weight
items_0 = [
Button(description='weight=1; 0%', layout=Layout(flex='1 1 0%', width='auto'), button_style='danger'),
Button(description='weight=3; 0%', layout=Layout(flex='3 1 0%', width='auto'), button_style='danger'),
Button(description='weight=1; 0%', layout=Layout(flex='1 1 0%', width='auto'), button_style='danger'),
]
box_layout = Layout(display='flex',
flex_flow='row',
align_items='stretch',
width='70%')
box_auto = Box(children=items_auto, layout=box_layout)
box_0 = Box(children=items_0, layout=box_layout)
VBox([box_auto, box_0])
from ipywidgets import Layout, Button, Box, FloatText, Textarea, Dropdown, Label, IntSlider
form_item_layout = Layout(
display='flex',
flex_flow='row',
justify_content='space-between'
)
form_items = [
Box([Label(value='Age of the captain'), IntSlider(min=40, max=60)], layout=form_item_layout),
Box([Label(value='Egg style'),
Dropdown(options=['Scrambled', 'Sunny side up', 'Over easy'])], layout=form_item_layout),
Box([Label(value='Ship size'),
FloatText()], layout=form_item_layout),
Box([Label(value='Information'),
Textarea()], layout=form_item_layout)
]
form = Box(form_items, layout=Layout(
display='flex',
flex_flow='column',
border='solid 2px',
align_items='stretch',
width='50%'
))
form
from ipywidgets import Layout, Button, VBox, Label, Box
item_layout = Layout(height='100px', min_width='40px')
items = [Button(layout=item_layout, description=str(i), button_style='warning') for i in range(40)]
box_layout = Layout(overflow='scroll hidden',
border='3px solid black',
width='500px',
height='',
flex_flow='row',
display='flex')
carousel = Box(children=items, layout=box_layout)
VBox([Label('Scroll horizontally:'), carousel])
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the decompose pass"""
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler.passes import Decompose
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import HGate, CCXGate, U2Gate
from qiskit.quantum_info.operators import Operator
from qiskit.test import QiskitTestCase
class TestDecompose(QiskitTestCase):
"""Tests the decompose pass."""
def setUp(self):
super().setUp()
# example complex circuit
# ┌────────┐ ┌───┐┌─────────────┐
# q2_0: ┤0 ├────────────■──┤ H ├┤0 ├
# │ │ │ └───┘│ circuit-57 │
# q2_1: ┤1 gate1 ├────────────■───────┤1 ├
# │ │┌────────┐ │ └─────────────┘
# q2_2: ┤2 ├┤0 ├──■──────────────────────
# └────────┘│ │ │
# q2_3: ──────────┤1 gate2 ├──■──────────────────────
# │ │┌─┴─┐
# q2_4: ──────────┤2 ├┤ X ├────────────────────
# └────────┘└───┘
circ1 = QuantumCircuit(3)
circ1.h(0)
circ1.t(1)
circ1.x(2)
my_gate = circ1.to_gate(label="gate1")
circ2 = QuantumCircuit(3)
circ2.h(0)
circ2.cx(0, 1)
circ2.x(2)
my_gate2 = circ2.to_gate(label="gate2")
circ3 = QuantumCircuit(2)
circ3.x(0)
q_bits = QuantumRegister(5)
qc = QuantumCircuit(q_bits)
qc.append(my_gate, q_bits[:3])
qc.append(my_gate2, q_bits[2:])
qc.mct(q_bits[:4], q_bits[4])
qc.h(0)
qc.append(circ3, [0, 1])
self.complex_circuit = qc
def test_basic(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_decompose_none(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_decompose_only_h(self):
"""Test to decompose a single H, without the rest"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 2)
for node in op_nodes:
self.assertIn(node.name, ["cx", "u2"])
def test_decompose_toffoli(self):
"""Test decompose CCX."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(CCXGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_decompose_conditional(self):
"""Test decompose a 1-qubit gates with a conditional."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr).c_if(cr, 1)
circuit.x(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.append(U2Gate(0, pi), [qr[0]]).c_if(cr, 1)
ref_circuit.x(qr).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(after_dag, ref_dag)
def test_decompose_oversized_instruction(self):
"""Test decompose on a single-op gate that doesn't use all qubits."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/3440
qc1 = QuantumCircuit(2)
qc1.x(0)
gate = qc1.to_gate()
qc2 = QuantumCircuit(2)
qc2.append(gate, [0, 1])
output = qc2.decompose()
self.assertEqual(qc1, output)
def test_decomposition_preserves_qregs_order(self):
"""Test decomposing a gate preserves it's definition registers order"""
qr = QuantumRegister(2, "qr1")
qc1 = QuantumCircuit(qr)
qc1.cx(1, 0)
gate = qc1.to_gate()
qr2 = QuantumRegister(2, "qr2")
qc2 = QuantumCircuit(qr2)
qc2.append(gate, qr2)
expected = QuantumCircuit(qr2)
expected.cx(1, 0)
self.assertEqual(qc2.decompose(), expected)
def test_decompose_global_phase_1q(self):
"""Test decomposition of circuit with global phase"""
qc1 = QuantumCircuit(1)
qc1.rz(0.1, 0)
qc1.ry(0.5, 0)
qc1.global_phase += pi / 4
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_global_phase_2q(self):
"""Test decomposition of circuit with global phase"""
qc1 = QuantumCircuit(2, global_phase=pi / 4)
qc1.rz(0.1, 0)
qc1.rxx(0.2, 0, 1)
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_global_phase_1q_composite(self):
"""Test decomposition of circuit with global phase in a composite gate."""
circ = QuantumCircuit(1, global_phase=pi / 2)
circ.x(0)
circ.h(0)
v = circ.to_gate()
qc1 = QuantumCircuit(1)
qc1.append(v, [0])
qcd = qc1.decompose()
self.assertEqual(Operator(qc1), Operator(qcd))
def test_decompose_only_h_gate(self):
"""Test decomposition parameters so that only a certain gate is decomposed."""
circ = QuantumCircuit(2, 1)
circ.h(0)
circ.cz(0, 1)
decom_circ = circ.decompose(["h"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 2)
self.assertEqual(dag.op_nodes()[0].name, "u2")
self.assertEqual(dag.op_nodes()[1].name, "cz")
def test_decompose_only_given_label(self):
"""Test decomposition parameters so that only a given label is decomposed."""
decom_circ = self.complex_circuit.decompose(["gate2"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 7)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].name, "h")
self.assertEqual(dag.op_nodes()[2].name, "cx")
self.assertEqual(dag.op_nodes()[3].name, "x")
self.assertEqual(dag.op_nodes()[4].name, "mcx")
self.assertEqual(dag.op_nodes()[5].name, "h")
self.assertRegex(dag.op_nodes()[6].name, "circuit-")
def test_decompose_only_given_name(self):
"""Test decomposition parameters so that only given name is decomposed."""
decom_circ = self.complex_circuit.decompose(["mcx"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 13)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].op.label, "gate2")
self.assertEqual(dag.op_nodes()[2].name, "h")
self.assertEqual(dag.op_nodes()[3].name, "cu1")
self.assertEqual(dag.op_nodes()[4].name, "rcccx")
self.assertEqual(dag.op_nodes()[5].name, "h")
self.assertEqual(dag.op_nodes()[6].name, "h")
self.assertEqual(dag.op_nodes()[7].name, "cu1")
self.assertEqual(dag.op_nodes()[8].name, "rcccx_dg")
self.assertEqual(dag.op_nodes()[9].name, "h")
self.assertEqual(dag.op_nodes()[10].name, "c3sx")
self.assertEqual(dag.op_nodes()[11].name, "h")
self.assertRegex(dag.op_nodes()[12].name, "circuit-")
def test_decompose_mixture_of_names_and_labels(self):
"""Test decomposition parameters so that mixture of names and labels is decomposed"""
decom_circ = self.complex_circuit.decompose(["mcx", "gate2"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 15)
self.assertEqual(dag.op_nodes()[0].op.label, "gate1")
self.assertEqual(dag.op_nodes()[1].name, "h")
self.assertEqual(dag.op_nodes()[2].name, "cx")
self.assertEqual(dag.op_nodes()[3].name, "x")
self.assertEqual(dag.op_nodes()[4].name, "h")
self.assertEqual(dag.op_nodes()[5].name, "cu1")
self.assertEqual(dag.op_nodes()[6].name, "rcccx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertEqual(dag.op_nodes()[8].name, "h")
self.assertEqual(dag.op_nodes()[9].name, "cu1")
self.assertEqual(dag.op_nodes()[10].name, "rcccx_dg")
self.assertEqual(dag.op_nodes()[11].name, "h")
self.assertEqual(dag.op_nodes()[12].name, "c3sx")
self.assertEqual(dag.op_nodes()[13].name, "h")
self.assertRegex(dag.op_nodes()[14].name, "circuit-")
def test_decompose_name_wildcards(self):
"""Test decomposition parameters so that name wildcards is decomposed"""
decom_circ = self.complex_circuit.decompose(["circuit-*"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 9)
self.assertEqual(dag.op_nodes()[0].name, "h")
self.assertEqual(dag.op_nodes()[1].name, "t")
self.assertEqual(dag.op_nodes()[2].name, "x")
self.assertEqual(dag.op_nodes()[3].name, "h")
self.assertRegex(dag.op_nodes()[4].name, "cx")
self.assertEqual(dag.op_nodes()[5].name, "x")
self.assertEqual(dag.op_nodes()[6].name, "mcx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertEqual(dag.op_nodes()[8].name, "x")
def test_decompose_label_wildcards(self):
"""Test decomposition parameters so that label wildcards is decomposed"""
decom_circ = self.complex_circuit.decompose(["gate*"])
dag = circuit_to_dag(decom_circ)
self.assertEqual(len(dag.op_nodes()), 9)
self.assertEqual(dag.op_nodes()[0].name, "h")
self.assertEqual(dag.op_nodes()[1].name, "t")
self.assertEqual(dag.op_nodes()[2].name, "x")
self.assertEqual(dag.op_nodes()[3].name, "h")
self.assertEqual(dag.op_nodes()[4].name, "cx")
self.assertEqual(dag.op_nodes()[5].name, "x")
self.assertEqual(dag.op_nodes()[6].name, "mcx")
self.assertEqual(dag.op_nodes()[7].name, "h")
self.assertRegex(dag.op_nodes()[8].name, "circuit-")
def test_decompose_empty_gate(self):
"""Test a gate where the definition is an empty circuit is decomposed."""
empty = QuantumCircuit(1)
circuit = QuantumCircuit(1)
circuit.append(empty.to_gate(), [0])
decomposed = circuit.decompose()
self.assertEqual(len(decomposed.data), 0)
def test_decompose_reps(self):
"""Test decompose reps function is decomposed correctly"""
decom_circ = self.complex_circuit.decompose(reps=2)
decomposed = self.complex_circuit.decompose().decompose()
self.assertEqual(decom_circ, decomposed)
def test_decompose_single_qubit_clbit(self):
"""Test the decomposition of a block with a single qubit and clbit works.
Regression test of Qiskit/qiskit-terra#8591.
"""
block = QuantumCircuit(1, 1)
block.h(0)
circuit = QuantumCircuit(1, 1)
circuit.append(block, [0], [0])
decomposed = circuit.decompose()
self.assertEqual(decomposed, block)
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Core module of the timeline drawer.
This module provides the `DrawerCanvas` which is a collection of drawings.
The canvas instance is not just a container of drawing objects, as it also performs
data processing like binding abstract coordinates.
Initialization
~~~~~~~~~~~~~~
The `DataCanvas` is not exposed to users as they are implicitly initialized in the
interface function. It is noteworthy that the data canvas is agnostic to plotters.
This means once the canvas instance is initialized we can reuse this data
among multiple plotters. The canvas is initialized with a stylesheet.
```python
canvas = DrawerCanvas(stylesheet=stylesheet)
canvas.load_program(sched)
canvas.update()
```
Once all properties are set, `.update` method is called to apply changes to drawings.
Update
~~~~~~
To update the image, a user can set new values to canvas and then call the `.update` method.
```python
canvas.set_time_range(2000, 3000)
canvas.update()
```
All stored drawings are updated accordingly. The plotter API can access to
drawings with `.collections` property of the canvas instance. This returns
an iterator of drawings with the unique data key.
If a plotter provides object handler for plotted shapes, the plotter API can manage
the lookup table of the handler and the drawings by using this data key.
"""
from __future__ import annotations
import warnings
from collections.abc import Iterator
from copy import deepcopy
from functools import partial
from enum import Enum
import numpy as np
from qiskit import circuit
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.timeline import drawings, types
from qiskit.visualization.timeline.stylesheet import QiskitTimelineStyle
class DrawerCanvas:
"""Data container for drawings."""
def __init__(self, stylesheet: QiskitTimelineStyle):
"""Create new data container."""
# stylesheet
self.formatter = stylesheet.formatter
self.generator = stylesheet.generator
self.layout = stylesheet.layout
# drawings
self._collections: dict[str, drawings.ElementaryData] = {}
self._output_dataset: dict[str, drawings.ElementaryData] = {}
# vertical offset of bits
self.bits: list[types.Bits] = []
self.assigned_coordinates: dict[types.Bits, float] = {}
# visible controls
self.disable_bits: set[types.Bits] = set()
self.disable_types: set[str] = set()
# time
self._time_range = (0, 0)
# graph height
self.vmax = 0
self.vmin = 0
@property
def time_range(self) -> tuple[int, int]:
"""Return current time range to draw.
Calculate net duration and add side margin to edge location.
Returns:
Time window considering side margin.
"""
t0, t1 = self._time_range
duration = t1 - t0
new_t0 = t0 - duration * self.formatter["margin.left_percent"]
new_t1 = t1 + duration * self.formatter["margin.right_percent"]
return new_t0, new_t1
@time_range.setter
def time_range(self, new_range: tuple[int, int]):
"""Update time range to draw."""
self._time_range = new_range
@property
def collections(self) -> Iterator[tuple[str, drawings.ElementaryData]]:
"""Return currently active entries from drawing data collection.
The object is returned with unique name as a key of an object handler.
When the horizontal coordinate contains `AbstractCoordinate`,
the value is substituted by current time range preference.
"""
yield from self._output_dataset.items()
def add_data(self, data: drawings.ElementaryData):
"""Add drawing to collections.
If the given object already exists in the collections,
this interface replaces the old object instead of adding new entry.
Args:
data: New drawing to add.
"""
if not self.formatter["control.show_clbits"]:
data.bits = [b for b in data.bits if not isinstance(b, circuit.Clbit)]
self._collections[data.data_key] = data
# pylint: disable=cyclic-import
def load_program(self, program: circuit.QuantumCircuit):
"""Load quantum circuit and create drawing..
Args:
program: Scheduled circuit object to draw.
Raises:
VisualizationError: When circuit is not scheduled.
"""
not_gate_like = (circuit.Barrier,)
if getattr(program, "_op_start_times") is None:
# Run scheduling for backward compatibility
from qiskit import transpile
from qiskit.transpiler import InstructionDurations, TranspilerError
warnings.warn(
"Visualizing un-scheduled circuit with timeline drawer has been deprecated. "
"This circuit should be transpiled with scheduler though it consists of "
"instructions with explicit durations.",
DeprecationWarning,
)
try:
program = transpile(
program,
scheduling_method="alap",
instruction_durations=InstructionDurations(),
optimization_level=0,
)
except TranspilerError as ex:
raise VisualizationError(
f"Input circuit {program.name} is not scheduled and it contains "
"operations with unknown delays. This cannot be visualized."
) from ex
for t0, instruction in zip(program.op_start_times, program.data):
bits = list(instruction.qubits) + list(instruction.clbits)
for bit_pos, bit in enumerate(bits):
if not isinstance(instruction.operation, not_gate_like):
# Generate draw object for gates
gate_source = types.ScheduledGate(
t0=t0,
operand=instruction.operation,
duration=instruction.operation.duration,
bits=bits,
bit_position=bit_pos,
)
for gen in self.generator["gates"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(gate_source):
self.add_data(datum)
if len(bits) > 1 and bit_pos == 0:
# Generate draw object for gate-gate link
line_pos = t0 + 0.5 * instruction.operation.duration
link_source = types.GateLink(
t0=line_pos, opname=instruction.operation.name, bits=bits
)
for gen in self.generator["gate_links"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(link_source):
self.add_data(datum)
if isinstance(instruction.operation, circuit.Barrier):
# Generate draw object for barrier
barrier_source = types.Barrier(t0=t0, bits=bits, bit_position=bit_pos)
for gen in self.generator["barriers"]:
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(barrier_source):
self.add_data(datum)
self.bits = list(program.qubits) + list(program.clbits)
for bit in self.bits:
for gen in self.generator["bits"]:
# Generate draw objects for bit
obj_generator = partial(gen, formatter=self.formatter)
for datum in obj_generator(bit):
self.add_data(datum)
# update time range
t_end = max(program.duration, self.formatter["margin.minimum_duration"])
self.set_time_range(t_start=0, t_end=t_end)
def set_time_range(self, t_start: int, t_end: int):
"""Set time range to draw.
Args:
t_start: Left boundary of drawing in units of cycle time.
t_end: Right boundary of drawing in units of cycle time.
"""
self.time_range = (t_start, t_end)
def set_disable_bits(self, bit: types.Bits, remove: bool = True):
"""Interface method to control visibility of bits.
Specified object in the blocked list will not be shown.
Args:
bit: A qubit or classical bit object to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if remove:
self.disable_bits.add(bit)
else:
self.disable_bits.discard(bit)
def set_disable_type(self, data_type: types.DataTypes, remove: bool = True):
"""Interface method to control visibility of data types.
Specified object in the blocked list will not be shown.
Args:
data_type: A drawing data type to disable.
remove: Set `True` to disable, set `False` to enable.
"""
if isinstance(data_type, Enum):
data_type_str = str(data_type.value)
else:
data_type_str = data_type
if remove:
self.disable_types.add(data_type_str)
else:
self.disable_types.discard(data_type_str)
def update(self):
"""Update all collections.
This method should be called before the canvas is passed to the plotter.
"""
self._output_dataset.clear()
self.assigned_coordinates.clear()
# update coordinate
y0 = -self.formatter["margin.top"]
for bit in self.layout["bit_arrange"](self.bits):
# remove classical bit
if isinstance(bit, circuit.Clbit) and not self.formatter["control.show_clbits"]:
continue
# remove idle bit
if not self._check_bit_visible(bit):
continue
offset = y0 - 0.5
self.assigned_coordinates[bit] = offset
y0 = offset - 0.5
self.vmax = 0
self.vmin = y0 - self.formatter["margin.bottom"]
# add data
temp_gate_links = {}
temp_data = {}
for data_key, data in self._collections.items():
# deep copy to keep original data hash
new_data = deepcopy(data)
new_data.xvals = self._bind_coordinate(data.xvals)
new_data.yvals = self._bind_coordinate(data.yvals)
if data.data_type == str(types.LineType.GATE_LINK.value):
temp_gate_links[data_key] = new_data
else:
temp_data[data_key] = new_data
# update horizontal offset of gate links
temp_data.update(self._check_link_overlap(temp_gate_links))
# push valid data
for data_key, data in temp_data.items():
if self._check_data_visible(data):
self._output_dataset[data_key] = data
def _check_data_visible(self, data: drawings.ElementaryData) -> bool:
"""A helper function to check if the data is visible.
Args:
data: Drawing object to test.
Returns:
Return `True` if the data is visible.
"""
_barriers = [str(types.LineType.BARRIER.value)]
_delays = [str(types.BoxType.DELAY.value), str(types.LabelType.DELAY.value)]
def _time_range_check(_data):
"""If data is located outside the current time range."""
t0, t1 = self.time_range
if np.max(_data.xvals) < t0 or np.min(_data.xvals) > t1:
return False
return True
def _associated_bit_check(_data):
"""If any associated bit is not shown."""
if all(bit not in self.assigned_coordinates for bit in _data.bits):
return False
return True
def _data_check(_data):
"""If data is valid."""
if _data.data_type == str(types.LineType.GATE_LINK.value):
active_bits = [bit for bit in _data.bits if bit not in self.disable_bits]
if len(active_bits) < 2:
return False
elif _data.data_type in _barriers and not self.formatter["control.show_barriers"]:
return False
elif _data.data_type in _delays and not self.formatter["control.show_delays"]:
return False
return True
checks = [_time_range_check, _associated_bit_check, _data_check]
if all(check(data) for check in checks):
return True
return False
def _check_bit_visible(self, bit: types.Bits) -> bool:
"""A helper function to check if the bit is visible.
Args:
bit: Bit object to test.
Returns:
Return `True` if the bit is visible.
"""
_gates = [str(types.BoxType.SCHED_GATE.value), str(types.SymbolType.FRAME.value)]
if bit in self.disable_bits:
return False
if self.formatter["control.show_idle"]:
return True
for data in self._collections.values():
if bit in data.bits and data.data_type in _gates:
return True
return False
def _bind_coordinate(self, vals: Iterator[types.Coordinate]) -> np.ndarray:
"""A helper function to bind actual coordinates to an `AbstractCoordinate`.
Args:
vals: Sequence of coordinate objects associated with a drawing.
Returns:
Numpy data array with substituted values.
"""
def substitute(val: types.Coordinate):
if val == types.AbstractCoordinate.LEFT:
return self.time_range[0]
if val == types.AbstractCoordinate.RIGHT:
return self.time_range[1]
if val == types.AbstractCoordinate.TOP:
return self.vmax
if val == types.AbstractCoordinate.BOTTOM:
return self.vmin
raise VisualizationError(f"Coordinate {val} is not supported.")
try:
return np.asarray(vals, dtype=float)
except TypeError:
return np.asarray(list(map(substitute, vals)), dtype=float)
def _check_link_overlap(
self, links: dict[str, drawings.GateLinkData]
) -> dict[str, drawings.GateLinkData]:
"""Helper method to check overlap of bit links.
This method dynamically shifts horizontal position of links if they are overlapped.
"""
duration = self.time_range[1] - self.time_range[0]
allowed_overlap = self.formatter["margin.link_interval_percent"] * duration
# return y coordinates
def y_coords(link: drawings.GateLinkData):
return np.array([self.assigned_coordinates.get(bit, np.nan) for bit in link.bits])
# group overlapped links
overlapped_group: list[list[str]] = []
data_keys = list(links.keys())
while len(data_keys) > 0:
ref_key = data_keys.pop()
overlaps = set()
overlaps.add(ref_key)
for key in data_keys[::-1]:
# check horizontal overlap
if np.abs(links[ref_key].xvals[0] - links[key].xvals[0]) < allowed_overlap:
# check vertical overlap
y0s = y_coords(links[ref_key])
y1s = y_coords(links[key])
v1 = np.nanmin(y0s) - np.nanmin(y1s)
v2 = np.nanmax(y0s) - np.nanmax(y1s)
v3 = np.nanmin(y0s) - np.nanmax(y1s)
v4 = np.nanmax(y0s) - np.nanmin(y1s)
if not (v1 * v2 > 0 and v3 * v4 > 0):
overlaps.add(data_keys.pop(data_keys.index(key)))
overlapped_group.append(list(overlaps))
# renew horizontal offset
new_links = {}
for overlaps in overlapped_group:
if len(overlaps) > 1:
xpos_mean = np.mean([links[key].xvals[0] for key in overlaps])
# sort link key by y position
sorted_keys = sorted(overlaps, key=lambda x: np.nanmax(y_coords(links[x])))
x0 = xpos_mean - 0.5 * allowed_overlap * (len(overlaps) - 1)
for ind, key in enumerate(sorted_keys):
data = links[key]
data.xvals = [x0 + ind * allowed_overlap]
new_links[key] = data
else:
key = overlaps[0]
new_links[key] = links[key]
return {key: new_links[key] for key in links.keys()}
|
https://github.com/helenup/Quantum-Euclidean-Distance
|
helenup
|
# import the necessary libraries
import math as m
from qiskit import *
from qiskit import BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# First step is to encode the data into quantum states.
#There are some techniques to do it, in this case Amplitude embedding was used.
A = [2,9,8,5]
B = [7,5,10,3]
norm_A = 0
norm_B = 0
Dist = 0
for i in range(len(A)):
norm_A += A[i]**2
norm_B += B[i]**2
Dist += (A[i]-B[i])**2
Dist = m.sqrt(Dist)
A_norm = m.sqrt(norm_A)
B_norm = m.sqrt(norm_B)
Z = round( A_norm**2 + B_norm**2 )
# create phi and psi state with the data
phi = [A_norm/m.sqrt(Z),-B_norm/m.sqrt(Z)]
psi = []
for i in range(len(A)):
psi.append(((A[i]/A_norm) /m.sqrt(2)))
psi.append(((B[i]/B_norm) /m.sqrt(2)))
# Quantum Circuit
q1 = QuantumRegister(1,name='q1')
q2 = QuantumRegister(4,name='q2')
c = ClassicalRegister(1,name='c')
qc= QuantumCircuit(q1,q2,c)
# states initialization
qc.initialize( phi, q2[0] )
qc.initialize( psi, q2[1:4] )
# The swap test operator
qc.h( q1[0] )
qc.cswap( q1[0], q2[0], q2[1] )
qc.h( q1[0] )
qc.measure(q1,c)
display(qc.draw(output="mpl"))
## Results
shots = 10000
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=shots)
job_result = job.result()
counts = job_result.get_counts(qc)
x = abs(((counts['0']/shots - 0.5)/0.5)*2*Z)
Q_Dist = round(m.sqrt(x),4)
print('Quantum Distance: ', round(Q_Dist,3))
print('Euclidean Distance: ',round(Dist,3))
|
https://github.com/apozas/qaoa-color
|
apozas
|
from functools import reduce
from itertools import product
from qiskit import BasicAer, QuantumRegister
from qiskit_aqua import QuantumInstance
from qiskit_aqua import Operator, run_algorithm
from qiskit.quantum_info import Pauli
from qiskit_aqua.components.optimizers import COBYLA
from constrainedqaoa import constrainedQAOA
import numpy as np
edges = [(0, 0)]
vertices = 1
colors = 2
n_qubits = vertices * colors
zr = np.zeros(n_qubits)
ws = np.eye(n_qubits)
cost_operator = reduce(
lambda x, y: x + y,
[
Operator([[1, (Pauli(ws[colors*v1 + j, :], zr)
*Pauli(ws[colors*v2 + j, :], zr))]])
for (v1, v2), j in product(edges, range(colors))
]
)
mixer_operator = reduce(
lambda x, y: x + y,
[
Operator([[1, (Pauli(zr, ws[colors*i + j, :])
*Pauli(zr, ws[colors*i + (j+1) % colors, :]))]]) +
Operator([[1, (Pauli(ws[colors*i + j % colors, :], ws[colors*i + j % colors, :])
*Pauli(ws[colors*i + (j+1) % colors, :], ws[colors*i + (j+1) % colors, :]))]])
for i, j in product(range(vertices), range(colors))
]
)
if colors == 2:
mixer_operator.scaling_coeff(1/2)
print(mixer_operator.print_operators())
what = 'circuit'
circ = mixer_operator.evolve(np.eye(4), np.pi*0.35, what, 1, QuantumRegister(2))
if what == 'matrix':
print(np.round(circ, 4))
elif what == 'circuit':
print(circ.draw())
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
constrained = constrainedQAOA(cost_operator, cobyla, mixer_operator, 1)
backend = BasicAer.get_backend('statevector_simulator')
seed = 50
constrained.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed=seed, seed_mapper=seed)
result = constrained.run(quantum_instance)
result['eigvecs']
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from transpile_benchy.metrics.gate_counts import (
DepthMetric,
TotalMetric,
TotalSwaps,
)
from qiskit.circuit.library import iSwapGate
from qiskit.transpiler import CouplingMap
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from mirror_gates.utilities import SubsMetric
from mirror_gates.logging import transpile_benchy_logger
# N = 4
# coupling_map = CouplingMap.from_line(N)
coupling_map = CouplingMap.from_heavy_hex(5)
from transpile_benchy.library import CircuitLibrary
library = CircuitLibrary.from_txt("../../../circuits/medium_circuits.txt")
# library = CircuitLibrary.from_txt("../../circuits/debug.txt")
# XXX set consolidate to False
# this is allowed only because my pass manager will preserve consolidation
# see post_stage, I call fastconsolidate manually
# NOTE: use TotalSwaps to verify baselines have > 0 swaps
# otherwise, there is no room for improvement.
# we can include these if we want to show our methods will still work
# but somewhat trivial since we just append VF2Layout
metrics = [
DepthMetric(consolidate=False),
TotalMetric(consolidate=False),
TotalSwaps(consolidate=False),
SubsMetric(),
]
transpilers = [
QiskitLevel3(coupling_map, cx_basis=True),
Mirage(coupling_map, logger=transpile_benchy_logger, cx_basis=True),
]
from transpile_benchy.benchmark import Benchmark
benchmark = Benchmark(
transpilers=transpilers,
circuit_library=library,
metrics=metrics,
logger=transpile_benchy_logger,
num_runs=5,
)
benchmark.run()
# print(benchmark)
print(benchmark)
benchmark.summary_statistics(transpilers[0], transpilers[1])
from transpile_benchy.render import plot_benchmark
plot_benchmark(
benchmark,
save=1,
legend_show=1,
filename="cnot_hex",
color_override=[6, 9],
)
|
https://github.com/TheClintest/QuantumMedianFilter
|
TheClintest
|
from QMF import *
filename = "lena.png"
#Trasformazione in array
img_array = Converter.to_array(filename)
#Processo...
#Trasformazione in immagine
Converter.to_image(img_array, "nuova_immagine.png")
patcher = ImagePatcher()
patcher.load_image(img_array) # Caricamento/Processing
patches = patcher.get_patches() # Suddivisione
result_patches = patches.copy() # Dizionario per i risultati
for pos, patch in patches.items():
# Simulazione...
result_patches[pos] = Converter.decode_image(answer, patch.copy(), color_size=8)
# Risultati
img_result = patcher.convert_patches(result_patches)
Converter.to_image(img_result, "result.png")
max_bond_dimension = 32
simulator = Simulator(max_bond_dimension)
qmf = QuantumMedianFilter()
lambda_parameter = 100 # Parametro di esecuzione
# Generazione dei circuiti
qmf.generate(simulator, color_size=8, coordinate_size=2, optimization=3)
for pos, patch in patches.items():
#Generazione NEQR
neqr = Circuit.neqr(patch, color_num=color_size, verbose=False)
neqr_transpiled = sim.transpile(neqr, optimization=0, verbose=False)
#Generazione QMF
qmf.prepare_old(np.array(patch), lambda_parameter, color_size, neqr_transpiled)
circuit = qmf.get()
#Simulazione
answer = sim.simulate_old(circuit, shots=128, verbose=False)
#Recupero dei risultati
result_patches[pos] = Converter.decode_image(answer, patch.copy(), color_size=8)
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import dimod
import neal
import numpy as np
from dwave.system import DWaveSampler, EmbeddingComposite, DWaveCliqueSampler
A_int = np.array([[0,1,2,3,4,1],
[2,1,4,1,0,2],
[1,5,2,3,1,1]])
m, n = A_int.shape
vartype = dimod.Vartype.BINARY
c_int = np.array([1,2,1,-3,1,-1])
b = np.array([7,8,5])
print(A_int.dot(np.array([1,0,0,0,1,3])))
def get_binary_form(c,bits):
c_bin = []
for c_j in c:
c_bin += [c_j * 2**i for i in range(0,bits)]
return np.array(c_bin)
# represent each x_i as 3 bits to the power of 2
bits = 3
# Set Penalty for Constraints aprox solution
P = max(abs(c_int))*3
c = get_binary_form(c_int,bits)
print(c)
A = np.array([get_binary_form(A_int[i], bits) for i in range(0,m)])
print(A)
# Set up linear and quadratic coefficients
L = c.T - P * 2 * np.matmul(b.T,A)
Q = P * np.matmul(A.T,A)
offset = P * b.T.dot(b)
bqm = dimod.as_bqm(L, Q, offset, vartype)
exactSolver = dimod.ExactSolver()
sim = neal.SimulatedAnnealingSampler()
num_reads = 2500
exactSet = exactSolver.sample(bqm)
simSet = sim.sample(bqm, num_reads = num_reads)
def construct_x(sample, bits):
x=[]
for k in range(0,len(sample.keys()),bits):
x += [sum(sample[k+j]* 2**j for j in range(0,bits))]
return np.array(x)
def testSamples(sampleset, bits):
print("Minimum Energy Level found in:",sampleset.first)
X = []
for sample, energy, in sampleset.data(fields=['sample', 'energy']):
x = construct_x(sample,bits)
if all(A_int.dot(x)[i] == b[i] for i in range(0,m)) :
X += [(x,energy)]
return X
solutions_exact = testSamples(exactSet, bits)
for x, energy in solutions_exact :
print("Found solution {} with Energy Level {}".format(x,energy))
solutions_neal = testSamples(simSet, bits)
solutions_unique = { str(x) : energy for x, energy in solutions_neal}
solutions_count = {x:0 for x in solutions_unique.keys()}
for x,energy in solutions_neal:
solutions_count[str(x)]+=1
for x in solutions_unique.keys() :
print("Found solution {} {} times with Energy Level {}".format(x,solutions_count[x],solutions_unique[x]))
samplerComposite = EmbeddingComposite(DWaveSampler())
sampleset = samplerComposite.sample(bqm,num_reads = num_reads) # a7cb9757-6989-43d2-9e06-914c9e947727
sampleset.to_pandas_dataframe()
solutions_real = testSamples(sampleset, bits)
solutions_unique = { str(x) : energy for x, energy in solutions_real}
for x in solutions_unique.keys() :
print("Found solution {} with Energy Level {}".format(x,solutions_unique[x]))
samplerClique = DWaveCliqueSampler()
sampleset = samplerClique.sample(bqm,num_reads = num_reads) # ecebd686-0b4e-47c2-9087-b5e234d79d89
sampleset.to_pandas_dataframe()
solutions_real = testSamples(sampleset, bits)
solutions_unique = { str(x) : energy for x, energy in solutions_real}
for x in solutions_unique.keys() :
print("Found solution {} with Energy Level {}".format(x,solutions_unique[x]))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
%run qlatvia.py
draw_qubit()
sqrttwo=2**0.5
draw_quantum_state(1,0,"")
draw_quantum_state(1/sqrttwo,1/sqrttwo,"|+>")
# drawing the angle with |0>-axis
from matplotlib.pyplot import gca, text
from matplotlib.patches import Arc
gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=45) )
text(0.08,0.05,'.',fontsize=30)
text(0.21,0.09,'\u03C0/4')
%run qlatvia.py
draw_qubit()
[x,y]=[1,0]
draw_quantum_state(x,y,"v0")
sqrttwo = 2**0.5
oversqrttwo = 1/sqrttwo
R = [ [oversqrttwo, -1*oversqrttwo], [oversqrttwo,oversqrttwo] ]
#
# your code is here
#
#
import numpy as np
R = np.array(R)
# initial state 0
s0 = np.array([x, y])
for i in range(1, 9):
# rotate the matrix
s0 = np.matmul(R, s0)
# draw the matrix
draw_quantum_state(s0[0], s0[1], "after " + str(i))
%run qlatvia.py
draw_qubit()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
# we define a quantum circuit with one qubit and one bit
qreg1 = QuantumRegister(1) # quantum register with a single qubit
creg1 = ClassicalRegister(1) # classical register with a single bit
mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers
rotation_angle = pi/4
for i in range(1,9):
mycircuit1.ry(2*rotation_angle,qreg1[0])
# the following code is used to get the quantum state of the quantum register
job = execute(mycircuit1,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(mycircuit1)
print("iteration",i,": the quantum state is",current_quantum_state)
x_value = current_quantum_state[0].real # get the amplitude of |0>
y_value = current_quantum_state[1].real # get the amplitude of |1>
draw_quantum_state(x_value,y_value,"|v"+str(i)+">")
#
# your code is here
#
import math
%run qlatvia.py
def rotate_angle_times(angle, times):
draw_qubit()
qreg1 = QuantumRegister(1) # quantum register with a single qubit
creg1 = ClassicalRegister(1) # classical register with a single bit
mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers
rotation_angle = angle
for i in range(1,times):
# defined for block sphere
mycircuit1.ry(2*rotation_angle,qreg1[0])
# simulator gives the states
job = execute(mycircuit1,Aer.get_backend('statevector_simulator'))
current_quantum_state = job.result().get_statevector(mycircuit1)
print("iteration",i,": the quantum state is",current_quantum_state)
x_value = current_quantum_state[0].real # get the amplitude of |0>
y_value = current_quantum_state[1].real # get the amplitude of |1>
draw_quantum_state(x_value,y_value,"|v"+str(i)+">")
rotate_angle_times((math.pi / 6), 12)
rotate_angle_times(((3 * math.pi) / 8), 16)
rotate_angle_times(((2**(0.5)) * math.pi ), 20)
#
# your code is here
#
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# first qubit
qreg1 = QuantumRegister(1)
creg1 = ClassicalRegister(1)
mycircuit1 = QuantumCircuit(qreg1,creg1)
# second qubit
qreg2 = QuantumRegister(1)
creg2 = ClassicalRegister(1)
mycircuit2 = QuantumCircuit(qreg2,creg2)
# third qubit
qreg3 = QuantumRegister(1)
creg3 = ClassicalRegister(1)
mycircuit3 = QuantumCircuit(qreg3,creg3)
# randomly pick the angle of rotation
r = randrange(100)
theta = 2*pi*(r/100) # radians
print("the picked angle is",r*3.6,"degrees and",theta,"radians")
# rotate the first qubit
mycircuit1.ry(2*theta,qreg1[0])
# the different angles orthogonal to theta
theta1 = theta + pi/2
theta2 = theta - pi/2
# rotate the second and third qubits
mycircuit2.ry(2*theta1,qreg2[0])
mycircuit3.ry(2*theta2,qreg3[0])
# read the quantum state of the first qubit
job = execute(mycircuit1,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(mycircuit1)
[x1,y1]=[current_quantum_state[0].real,current_quantum_state[1].real]
print("the first qubit:",x1,y1)
# read the quantum state of the second qubit
job = execute(mycircuit2,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(mycircuit2)
[x2,y2]=[current_quantum_state[0].real,current_quantum_state[1].real]
print("the second qubit:",x2,y2)
# read the quantum state of the third qubit
job = execute(mycircuit3,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(mycircuit3)
[x3,y3]=[current_quantum_state[0].real,current_quantum_state[1].real]
print("the third qubit:",x3,y3)
%run qlatvia.py
draw_qubit()
draw_quantum_state(x1,y1,"v0")
draw_quantum_state(x2,y2,"v1")
draw_quantum_state(x3,y3,"v2")
print("the dot product of |v0> and |v1> is",x1*x2+y1*y2)
print("the dot product of |v0> and |v2> is",x1*x3+y1*y3)
print("the dot product of |v1> and |v2> is",x2*x3+y2*y3)
# make a full rotation by theta + theta_prime
theta_prime = 2*pi - theta
# rotate all qubits with theta_prime
mycircuit1.ry(2*theta_prime,qreg1[0])
mycircuit2.ry(2*theta_prime,qreg2[0])
mycircuit3.ry(2*theta_prime,qreg3[0])
# measure all qubits
mycircuit1.measure(qreg1,creg1)
mycircuit2.measure(qreg2,creg2)
mycircuit3.measure(qreg3,creg3)
# draw the first circuit
mycircuit1.draw()
# draw the first circuit
mycircuit2.draw()
# draw the first circuit
mycircuit3.draw()
# execute the first circuit
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit1)
print(counts)
# execute the second circuit
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit2)
print(counts)
# execute the third circuit
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit3)
print(counts)
#
# your code is here
#
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi, cos, sin
# first qubit
qreg = QuantumRegister(1)
creg = ClassicalRegister(1)
mycircuit = QuantumCircuit(qreg,creg)
theta=pi/4
for i in range(1,9):
total_theta = i*theta
mycircuit.ry(2*theta,qreg[0])
job = execute(mycircuit, Aer.get_backend('unitary_simulator'))
current_unitary = job.result().get_unitary(mycircuit, decimals=3)
print("after",i,"iteration(s):")
print(current_unitary[0][0].real,current_unitary[0][1].real)
print(current_unitary[1][0].real,current_unitary[1][1].real)
print("calculated by python:")
print(round(cos(total_theta),3),round(-sin(total_theta),3))
print(round(sin(total_theta),3),round(cos(total_theta),3))
print()
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
MöttönenStatePreparation
==========================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard.state.sparsevector._MöttönenStatePreparation
.. autosummary::
:nosignatures:
MöttönenStatePreparation
MöttönenStatePreparation
#########################
.. autoclass:: MöttönenStatePreparation
:members:
"""
from dc_qiskit_algorithms.MottonenStatePreparation import state_prep_möttönen
from qiskit import QuantumCircuit
from scipy import sparse
from ._QmlSparseVectorStatePreparation import QmlSparseVectorStatePreparation
class MottonenStatePreparation(QmlSparseVectorStatePreparation):
def prepare_state(self, qc, state_vector):
# type: (QmlSparseVectorStatePreparation, QuantumCircuit, sparse.dok_matrix) -> QuantumCircuit
"""
Apply the Möttönen state preparation routine on a quantum circuit using the given state vector.
The quantum circuit's quantum registers must be able to hold the state vector. Also it is expected
that the registers are initialized to the ground state ´´|0>´´ each.
:param qc: the quantum circuit to be used
:param state_vector: the (complex) state vector of unit length to be prepared
:return: the quantum circuit
"""
qregs = qc.qregs
# State Prep
register = [reg[i] for reg in qregs for i in range(0, reg.size)]
state_prep_möttönen(qc, state_vector, register)
return qc
def is_classifier_branch(self, branch_value):
# type: (QmlSparseVectorStatePreparation, int) -> bool
"""
The classifier will be directly usable if the branch label is 0.
:param branch_value: the branch measurement value
:return: True if the branch measurement was 0
"""
return branch_value == 0
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
import numpy as np
def NOT(input):
q = QuantumRegister(1) # a qubit in which to encode and manipulate the input
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# We encode '0' as the qubit state |0⟩, and '1' as |1⟩
# Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'
# For an input of '1', we do an x to rotate the |0⟩ to |1⟩
if input=='1':
qc.x( q[0] )
# Now we've encoded the input, we can do a NOT on it using x
qc.x( q[0] )
# Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]
qc.measure( q[0], c[0] )
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1)
output = next(iter(job.result().get_counts()))
return output
def XOR(input1,input2):
q = QuantumRegister(2) # two qubits in which to encode and manipulate the input
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[1],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def AND(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def NAND(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
def OR(input1,input2):
q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output
c = ClassicalRegister(1) # a bit to store the output
qc = QuantumCircuit(q, c) # this is where the quantum program goes
# YOUR QUANTUM PROGRAM GOES HERE
qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = execute(qc,backend,shots=1,memory=True)
output = job.result().get_memory()[0]
return output
print('\nResults for the NOT gate')
for input in ['0','1']:
print(' Input',input,'gives output',NOT(input))
print('\nResults for the XOR gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',XOR(input1,input2))
print('\nResults for the AND gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',AND(input1,input2))
print('\nResults for the NAND gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',NAND(input1,input2))
print('\nResults for the OR gate')
for input1 in ['0','1']:
for input2 in ['0','1']:
print(' Inputs',input1,input2,'give output',OR(input1,input2))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
|
vandnaChaturvedi
|
import numpy as np
import qiskit
from qiskit import QuantumCircuit
import matplotlib.pyplot as plt
from qiskit.circuit import QuantumCircuit, Parameter
import warnings
warnings.filterwarnings('ignore')
theta = Parameter("θ")
phi = Parameter("φ")
lamb = Parameter("λ")
def sampleCircuitA(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
circuit.barrier()
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
return circuit
circuitA = sampleCircuitA(qubits=4)
circuitA.draw(output='mpl')
def sampleCircuitB1(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u1(theta, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u1(theta, j)
return circuit
def sampleCircuitB2(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u2(phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u2(phi, lamb, j)
return circuit
def sampleCircuitB3(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u3(theta, phi, lamb, j)
return circuit
circuitB1 = sampleCircuitB1(qubits=4)
circuitB1.draw(output='mpl')
circuitB2 = sampleCircuitB2(qubits=4)
circuitB2.draw(output='mpl')
circuitB3 = sampleCircuitB3(qubits=4)
circuitB3.draw(output='mpl')
def sampleCircuitC(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
circuit.barrier()
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, 3, 2)
circuit.crx(theta, 0, 3)
circuit.crx(theta, 1, 0)
circuit.crx(theta, 2, 1)
return circuit
circuitC = sampleCircuitC(qubits=4)
circuitC.draw(output='mpl')
def sampleCircuitD(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(qubits - 1, -1, -1):
for k in range(qubits - 1, -1, -1):
if j != k:
circuit.crx(theta, j, k)
circuit.barrier()
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
return circuit
circuitD = sampleCircuitD(qubits=4)
circuitD.draw(output='mpl')
def sampleCircuitE(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(1, qubits, 2):
circuit.crx(theta, j, j - 1)
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(2, qubits, 2):
circuit.crx(theta, j, j - 1)
return circuit
circuitE = sampleCircuitE(qubits=4)
circuitE.draw(output='mpl')
def sampleCircuitF(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
return circuit
circuitF = sampleCircuitF(qubits=4)
circuitF.draw(output='mpl')
def sampleEncoding(qubits):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.h(i)
circuit.ry(theta, i)
return circuit
circuit = sampleEncoding(4)
circuit.draw(output='mpl')
# demo:
circuit = sampleEncoding(5).compose(sampleCircuitB3(layer=2, qubits=5))
circuit.draw(output='mpl')
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from qiskit.transpiler import CouplingMap
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from mirror_gates.logging import transpile_benchy_logger
from transpile_benchy.library import CircuitLibrary
library = CircuitLibrary.from_txt("../../circuits/iters_select.txt")
coupling_map = CouplingMap.from_line(64)
# coupling_map = CouplingMap.from_heavy_hex(5)
# XXX we hardcoded layout to not be parallelized to avoid a pipe error
# before collecting data for this result -> change the hardcoded value
# maybe requires downgrading to 3.9 to get this to work....????
transpilers = [
QiskitLevel3(coupling_map, python_sabre=True),
Mirage(
coupling_map,
use_fast_settings=True,
name="Mirage",
parallel=True,
swap_trials=6,
layout_trials=6,
),
]
from transpile_benchy.benchmark import Benchmark
# only interested in TimeMetric, is there by default
benchmark = Benchmark(
transpilers=transpilers,
circuit_library=library,
num_runs=1,
logger=transpile_benchy_logger,
)
benchmark.run()
benchmark.summary_statistics(transpilers[0], transpilers[1])
from transpile_benchy.render import plot_benchmark
plot_benchmark(
benchmark,
save=1,
legend_show=1,
filename="speed",
plot_type="trendline",
color_override=[0, 3],
)
print(benchmark)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The Iterative Quantum Amplitude Estimation Algorithm."""
from __future__ import annotations
from typing import cast
import warnings
import numpy as np
from scipy.stats import beta
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.providers import Backend
from qiskit.primitives import BaseSampler
from qiskit.utils import QuantumInstance
from qiskit.utils.deprecation import deprecate_arg, deprecate_func
from .amplitude_estimator import AmplitudeEstimator, AmplitudeEstimatorResult
from .estimation_problem import EstimationProblem
from ..exceptions import AlgorithmError
class IterativeAmplitudeEstimation(AmplitudeEstimator):
r"""The Iterative Amplitude Estimation algorithm.
This class implements the Iterative Quantum Amplitude Estimation (IQAE) algorithm, proposed
in [1]. The output of the algorithm is an estimate that,
with at least probability :math:`1 - \alpha`, differs by epsilon to the target value, where
both alpha and epsilon can be specified.
It differs from the original QAE algorithm proposed by Brassard [2] in that it does not rely on
Quantum Phase Estimation, but is only based on Grover's algorithm. IQAE iteratively
applies carefully selected Grover iterations to find an estimate for the target amplitude.
References:
[1]: Grinko, D., Gacon, J., Zoufal, C., & Woerner, S. (2019).
Iterative Quantum Amplitude Estimation.
`arXiv:1912.05559 <https://arxiv.org/abs/1912.05559>`_.
[2]: Brassard, G., Hoyer, P., Mosca, M., & Tapp, A. (2000).
Quantum Amplitude Amplification and Estimation.
`arXiv:quant-ph/0005055 <http://arxiv.org/abs/quant-ph/0005055>`_.
"""
@deprecate_arg(
"quantum_instance",
additional_msg=(
"Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a "
"migration guide."
),
since="0.24.0",
)
def __init__(
self,
epsilon_target: float,
alpha: float,
confint_method: str = "beta",
min_ratio: float = 2,
quantum_instance: QuantumInstance | Backend | None = None,
sampler: BaseSampler | None = None,
) -> None:
r"""
The output of the algorithm is an estimate for the amplitude `a`, that with at least
probability 1 - alpha has an error of epsilon. The number of A operator calls scales
linearly in 1/epsilon (up to a logarithmic factor).
Args:
epsilon_target: Target precision for estimation target `a`, has values between 0 and 0.5
alpha: Confidence level, the target probability is 1 - alpha, has values between 0 and 1
confint_method: Statistical method used to estimate the confidence intervals in
each iteration, can be 'chernoff' for the Chernoff intervals or 'beta' for the
Clopper-Pearson intervals (default)
min_ratio: Minimal q-ratio (:math:`K_{i+1} / K_i`) for FindNextK
quantum_instance: Deprecated: Quantum Instance or Backend
sampler: A sampler primitive to evaluate the circuits.
Raises:
AlgorithmError: if the method to compute the confidence intervals is not supported
ValueError: If the target epsilon is not in (0, 0.5]
ValueError: If alpha is not in (0, 1)
ValueError: If confint_method is not supported
"""
# validate ranges of input arguments
if not 0 < epsilon_target <= 0.5:
raise ValueError(f"The target epsilon must be in (0, 0.5], but is {epsilon_target}.")
if not 0 < alpha < 1:
raise ValueError(f"The confidence level alpha must be in (0, 1), but is {alpha}")
if confint_method not in {"chernoff", "beta"}:
raise ValueError(
f"The confidence interval method must be chernoff or beta, but is {confint_method}."
)
super().__init__()
# set quantum instance
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.quantum_instance = quantum_instance
# store parameters
self._epsilon = epsilon_target
self._alpha = alpha
self._min_ratio = min_ratio
self._confint_method = confint_method
self._sampler = sampler
@property
def sampler(self) -> BaseSampler | None:
"""Get the sampler primitive.
Returns:
The sampler primitive to evaluate the circuits.
"""
return self._sampler
@sampler.setter
def sampler(self, sampler: BaseSampler) -> None:
"""Set sampler primitive.
Args:
sampler: A sampler primitive to evaluate the circuits.
"""
self._sampler = sampler
@property
@deprecate_func(
since="0.24.0",
is_property=True,
additional_msg="See https://qisk.it/algo_migration for a migration guide.",
)
def quantum_instance(self) -> QuantumInstance | None:
"""Deprecated. Get the quantum instance.
Returns:
The quantum instance used to run this algorithm.
"""
return self._quantum_instance
@quantum_instance.setter
@deprecate_func(
since="0.24.0",
is_property=True,
additional_msg="See https://qisk.it/algo_migration for a migration guide.",
)
def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None:
"""Deprecated. Set quantum instance.
Args:
quantum_instance: The quantum instance used to run this algorithm.
"""
if isinstance(quantum_instance, Backend):
quantum_instance = QuantumInstance(quantum_instance)
self._quantum_instance = quantum_instance
@property
def epsilon_target(self) -> float:
"""Returns the target precision ``epsilon_target`` of the algorithm.
Returns:
The target precision (which is half the width of the confidence interval).
"""
return self._epsilon
@epsilon_target.setter
def epsilon_target(self, epsilon: float) -> None:
"""Set the target precision of the algorithm.
Args:
epsilon: Target precision for estimation target `a`.
"""
self._epsilon = epsilon
def _find_next_k(
self,
k: int,
upper_half_circle: bool,
theta_interval: tuple[float, float],
min_ratio: float = 2.0,
) -> tuple[int, bool]:
"""Find the largest integer k_next, such that the interval (4 * k_next + 2)*theta_interval
lies completely in [0, pi] or [pi, 2pi], for theta_interval = (theta_lower, theta_upper).
Args:
k: The current power of the Q operator.
upper_half_circle: Boolean flag of whether theta_interval lies in the
upper half-circle [0, pi] or in the lower one [pi, 2pi].
theta_interval: The current confidence interval for the angle theta,
i.e. (theta_lower, theta_upper).
min_ratio: Minimal ratio K/K_next allowed in the algorithm.
Returns:
The next power k, and boolean flag for the extrapolated interval.
Raises:
AlgorithmError: if min_ratio is smaller or equal to 1
"""
if min_ratio <= 1:
raise AlgorithmError("min_ratio must be larger than 1 to ensure convergence")
# initialize variables
theta_l, theta_u = theta_interval
old_scaling = 4 * k + 2 # current scaling factor, called K := (4k + 2)
# the largest feasible scaling factor K cannot be larger than K_max,
# which is bounded by the length of the current confidence interval
max_scaling = int(1 / (2 * (theta_u - theta_l)))
scaling = max_scaling - (max_scaling - 2) % 4 # bring into the form 4 * k_max + 2
# find the largest feasible scaling factor K_next, and thus k_next
while scaling >= min_ratio * old_scaling:
theta_min = scaling * theta_l - int(scaling * theta_l)
theta_max = scaling * theta_u - int(scaling * theta_u)
if theta_min <= theta_max <= 0.5 and theta_min <= 0.5:
# the extrapolated theta interval is in the upper half-circle
upper_half_circle = True
return int((scaling - 2) / 4), upper_half_circle
elif theta_max >= 0.5 and theta_max >= theta_min >= 0.5:
# the extrapolated theta interval is in the upper half-circle
upper_half_circle = False
return int((scaling - 2) / 4), upper_half_circle
scaling -= 4
# if we do not find a feasible k, return the old one
return int(k), upper_half_circle
def construct_circuit(
self, estimation_problem: EstimationProblem, k: int = 0, measurement: bool = False
) -> QuantumCircuit:
r"""Construct the circuit :math:`\mathcal{Q}^k \mathcal{A} |0\rangle`.
The A operator is the unitary specifying the QAE problem and Q the associated Grover
operator.
Args:
estimation_problem: The estimation problem for which to construct the QAE circuit.
k: The power of the Q operator.
measurement: Boolean flag to indicate if measurements should be included in the
circuits.
Returns:
The circuit implementing :math:`\mathcal{Q}^k \mathcal{A} |0\rangle`.
"""
num_qubits = max(
estimation_problem.state_preparation.num_qubits,
estimation_problem.grover_operator.num_qubits,
)
circuit = QuantumCircuit(num_qubits, name="circuit")
# add classical register if needed
if measurement:
c = ClassicalRegister(len(estimation_problem.objective_qubits))
circuit.add_register(c)
# add A operator
circuit.compose(estimation_problem.state_preparation, inplace=True)
# add Q^k
if k != 0:
circuit.compose(estimation_problem.grover_operator.power(k), inplace=True)
# add optional measurement
if measurement:
# real hardware can currently not handle operations after measurements, which might
# happen if the circuit gets transpiled, hence we're adding a safeguard-barrier
circuit.barrier()
circuit.measure(estimation_problem.objective_qubits, c[:])
return circuit
def _good_state_probability(
self,
problem: EstimationProblem,
counts_or_statevector: dict[str, int] | np.ndarray,
num_state_qubits: int,
) -> tuple[int, float] | float:
"""Get the probability to measure '1' in the last qubit.
Args:
problem: The estimation problem, used to obtain the number of objective qubits and
the ``is_good_state`` function.
counts_or_statevector: Either a counts-dictionary (with one measured qubit only!) or
the statevector returned from the statevector_simulator.
num_state_qubits: The number of state qubits.
Returns:
If a dict is given, return (#one-counts, #one-counts/#all-counts),
otherwise Pr(measure '1' in the last qubit).
"""
if isinstance(counts_or_statevector, dict):
one_counts = 0
for state, counts in counts_or_statevector.items():
if problem.is_good_state(state):
one_counts += counts
return int(one_counts), one_counts / sum(counts_or_statevector.values())
else:
statevector = counts_or_statevector
num_qubits = int(np.log2(len(statevector))) # the total number of qubits
# sum over all amplitudes where the objective qubit is 1
prob = 0
for i, amplitude in enumerate(statevector):
# consider only state qubits and revert bit order
bitstr = bin(i)[2:].zfill(num_qubits)[-num_state_qubits:][::-1]
objectives = [bitstr[index] for index in problem.objective_qubits]
if problem.is_good_state(objectives):
prob = prob + np.abs(amplitude) ** 2
return prob
def estimate(
self, estimation_problem: EstimationProblem
) -> "IterativeAmplitudeEstimationResult":
"""Run the amplitude estimation algorithm on provided estimation problem.
Args:
estimation_problem: The estimation problem.
Returns:
An amplitude estimation results object.
Raises:
ValueError: A quantum instance or Sampler must be provided.
AlgorithmError: Sampler job run error.
"""
if self._quantum_instance is None and self._sampler is None:
raise ValueError("A quantum instance or sampler must be provided.")
# initialize memory variables
powers = [0] # list of powers k: Q^k, (called 'k' in paper)
ratios = [] # list of multiplication factors (called 'q' in paper)
theta_intervals = [[0, 1 / 4]] # a priori knowledge of theta / 2 / pi
a_intervals = [[0.0, 1.0]] # a priori knowledge of the confidence interval of the estimate
num_oracle_queries = 0
num_one_shots = []
# maximum number of rounds
max_rounds = (
int(np.log(self._min_ratio * np.pi / 8 / self._epsilon) / np.log(self._min_ratio)) + 1
)
upper_half_circle = True # initially theta is in the upper half-circle
if self._quantum_instance is not None and self._quantum_instance.is_statevector:
# for statevector we can directly return the probability to measure 1
# note, that no iterations here are necessary
# simulate circuit
circuit = self.construct_circuit(estimation_problem, k=0, measurement=False)
ret = self._quantum_instance.execute(circuit)
# get statevector
statevector = ret.get_statevector(circuit)
# calculate the probability of measuring '1'
num_qubits = circuit.num_qubits - circuit.num_ancillas
prob = self._good_state_probability(estimation_problem, statevector, num_qubits)
prob = cast(float, prob) # tell MyPy it's a float and not Tuple[int, float ]
a_confidence_interval = [prob, prob] # type: list[float]
a_intervals.append(a_confidence_interval)
theta_i_interval = [
np.arccos(1 - 2 * a_i) / 2 / np.pi for a_i in a_confidence_interval # type: ignore
]
theta_intervals.append(theta_i_interval)
num_oracle_queries = 0 # no Q-oracle call, only a single one to A
else:
num_iterations = 0 # keep track of the number of iterations
# number of shots per iteration
shots = 0
# do while loop, keep in mind that we scaled theta mod 2pi such that it lies in [0,1]
while theta_intervals[-1][1] - theta_intervals[-1][0] > self._epsilon / np.pi:
num_iterations += 1
# get the next k
k, upper_half_circle = self._find_next_k(
powers[-1],
upper_half_circle,
theta_intervals[-1], # type: ignore
min_ratio=self._min_ratio,
)
# store the variables
powers.append(k)
ratios.append((2 * powers[-1] + 1) / (2 * powers[-2] + 1))
# run measurements for Q^k A|0> circuit
circuit = self.construct_circuit(estimation_problem, k, measurement=True)
counts = {}
if self._quantum_instance is not None:
ret = self._quantum_instance.execute(circuit)
# get the counts and store them
counts = ret.get_counts(circuit)
shots = self._quantum_instance._run_config.shots
else:
try:
job = self._sampler.run([circuit])
ret = job.result()
except Exception as exc:
raise AlgorithmError("The job was not completed successfully. ") from exc
shots = ret.metadata[0].get("shots")
if shots is None:
circuit = self.construct_circuit(estimation_problem, k=0, measurement=True)
try:
job = self._sampler.run([circuit])
ret = job.result()
except Exception as exc:
raise AlgorithmError(
"The job was not completed successfully. "
) from exc
# calculate the probability of measuring '1'
prob = 0.0
for bit, probabilities in ret.quasi_dists[0].binary_probabilities().items():
# check if it is a good state
if estimation_problem.is_good_state(bit):
prob += probabilities
a_confidence_interval = [prob, prob]
a_intervals.append(a_confidence_interval)
theta_i_interval = [
np.arccos(1 - 2 * a_i) / 2 / np.pi for a_i in a_confidence_interval
]
theta_intervals.append(theta_i_interval)
num_oracle_queries = 0 # no Q-oracle call, only a single one to A
break
counts = {
k: round(v * shots)
for k, v in ret.quasi_dists[0].binary_probabilities().items()
}
# calculate the probability of measuring '1', 'prob' is a_i in the paper
num_qubits = circuit.num_qubits - circuit.num_ancillas
# type: ignore
one_counts, prob = self._good_state_probability(
estimation_problem, counts, num_qubits
)
num_one_shots.append(one_counts)
# track number of Q-oracle calls
num_oracle_queries += shots * k
# if on the previous iterations we have K_{i-1} == K_i, we sum these samples up
j = 1 # number of times we stayed fixed at the same K
round_shots = shots
round_one_counts = one_counts
if num_iterations > 1:
while (
powers[num_iterations - j] == powers[num_iterations]
and num_iterations >= j + 1
):
j = j + 1
round_shots += shots
round_one_counts += num_one_shots[-j]
# compute a_min_i, a_max_i
if self._confint_method == "chernoff":
a_i_min, a_i_max = _chernoff_confint(prob, round_shots, max_rounds, self._alpha)
else: # 'beta'
a_i_min, a_i_max = _clopper_pearson_confint(
round_one_counts, round_shots, self._alpha / max_rounds
)
# compute theta_min_i, theta_max_i
if upper_half_circle:
theta_min_i = np.arccos(1 - 2 * a_i_min) / 2 / np.pi
theta_max_i = np.arccos(1 - 2 * a_i_max) / 2 / np.pi
else:
theta_min_i = 1 - np.arccos(1 - 2 * a_i_max) / 2 / np.pi
theta_max_i = 1 - np.arccos(1 - 2 * a_i_min) / 2 / np.pi
# compute theta_u, theta_l of this iteration
scaling = 4 * k + 2 # current K_i factor
theta_u = (int(scaling * theta_intervals[-1][1]) + theta_max_i) / scaling
theta_l = (int(scaling * theta_intervals[-1][0]) + theta_min_i) / scaling
theta_intervals.append([theta_l, theta_u])
# compute a_u_i, a_l_i
a_u = np.sin(2 * np.pi * theta_u) ** 2
a_l = np.sin(2 * np.pi * theta_l) ** 2
a_u = cast(float, a_u)
a_l = cast(float, a_l)
a_intervals.append([a_l, a_u])
# get the latest confidence interval for the estimate of a
confidence_interval = tuple(a_intervals[-1])
# the final estimate is the mean of the confidence interval
estimation = np.mean(confidence_interval)
result = IterativeAmplitudeEstimationResult()
result.alpha = self._alpha
result.post_processing = estimation_problem.post_processing
result.num_oracle_queries = num_oracle_queries
result.estimation = estimation
result.epsilon_estimated = (confidence_interval[1] - confidence_interval[0]) / 2
result.confidence_interval = confidence_interval
result.estimation_processed = estimation_problem.post_processing(estimation)
confidence_interval = tuple(
estimation_problem.post_processing(x) for x in confidence_interval
)
result.confidence_interval_processed = confidence_interval
result.epsilon_estimated_processed = (confidence_interval[1] - confidence_interval[0]) / 2
result.estimate_intervals = a_intervals
result.theta_intervals = theta_intervals
result.powers = powers
result.ratios = ratios
return result
class IterativeAmplitudeEstimationResult(AmplitudeEstimatorResult):
"""The ``IterativeAmplitudeEstimation`` result object."""
def __init__(self) -> None:
super().__init__()
self._alpha: float | None = None
self._epsilon_target: float | None = None
self._epsilon_estimated: float | None = None
self._epsilon_estimated_processed: float | None = None
self._estimate_intervals: list[list[float]] | None = None
self._theta_intervals: list[list[float]] | None = None
self._powers: list[int] | None = None
self._ratios: list[float] | None = None
self._confidence_interval_processed: tuple[float, float] | None = None
@property
def alpha(self) -> float:
r"""Return the confidence level :math:`\alpha`."""
return self._alpha
@alpha.setter
def alpha(self, value: float) -> None:
r"""Set the confidence level :math:`\alpha`."""
self._alpha = value
@property
def epsilon_target(self) -> float:
"""Return the target half-width of the confidence interval."""
return self._epsilon_target
@epsilon_target.setter
def epsilon_target(self, value: float) -> None:
"""Set the target half-width of the confidence interval."""
self._epsilon_target = value
@property
def epsilon_estimated(self) -> float:
"""Return the estimated half-width of the confidence interval."""
return self._epsilon_estimated
@epsilon_estimated.setter
def epsilon_estimated(self, value: float) -> None:
"""Set the estimated half-width of the confidence interval."""
self._epsilon_estimated = value
@property
def epsilon_estimated_processed(self) -> float:
"""Return the post-processed estimated half-width of the confidence interval."""
return self._epsilon_estimated_processed
@epsilon_estimated_processed.setter
def epsilon_estimated_processed(self, value: float) -> None:
"""Set the post-processed estimated half-width of the confidence interval."""
self._epsilon_estimated_processed = value
@property
def estimate_intervals(self) -> list[list[float]]:
"""Return the confidence intervals for the estimate in each iteration."""
return self._estimate_intervals
@estimate_intervals.setter
def estimate_intervals(self, value: list[list[float]]) -> None:
"""Set the confidence intervals for the estimate in each iteration."""
self._estimate_intervals = value
@property
def theta_intervals(self) -> list[list[float]]:
"""Return the confidence intervals for the angles in each iteration."""
return self._theta_intervals
@theta_intervals.setter
def theta_intervals(self, value: list[list[float]]) -> None:
"""Set the confidence intervals for the angles in each iteration."""
self._theta_intervals = value
@property
def powers(self) -> list[int]:
"""Return the powers of the Grover operator in each iteration."""
return self._powers
@powers.setter
def powers(self, value: list[int]) -> None:
"""Set the powers of the Grover operator in each iteration."""
self._powers = value
@property
def ratios(self) -> list[float]:
r"""Return the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`."""
return self._ratios
@ratios.setter
def ratios(self, value: list[float]) -> None:
r"""Set the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`."""
self._ratios = value
@property
def confidence_interval_processed(self) -> tuple[float, float]:
"""Return the post-processed confidence interval."""
return self._confidence_interval_processed
@confidence_interval_processed.setter
def confidence_interval_processed(self, value: tuple[float, float]) -> None:
"""Set the post-processed confidence interval."""
self._confidence_interval_processed = value
def _chernoff_confint(
value: float, shots: int, max_rounds: int, alpha: float
) -> tuple[float, float]:
"""Compute the Chernoff confidence interval for `shots` i.i.d. Bernoulli trials.
The confidence interval is
[value - eps, value + eps], where eps = sqrt(3 * log(2 * max_rounds/ alpha) / shots)
but at most [0, 1].
Args:
value: The current estimate.
shots: The number of shots.
max_rounds: The maximum number of rounds, used to compute epsilon_a.
alpha: The confidence level, used to compute epsilon_a.
Returns:
The Chernoff confidence interval.
"""
eps = np.sqrt(3 * np.log(2 * max_rounds / alpha) / shots)
lower = np.maximum(0, value - eps)
upper = np.minimum(1, value + eps)
return lower, upper
def _clopper_pearson_confint(counts: int, shots: int, alpha: float) -> tuple[float, float]:
"""Compute the Clopper-Pearson confidence interval for `shots` i.i.d. Bernoulli trials.
Args:
counts: The number of positive counts.
shots: The number of shots.
alpha: The confidence level for the confidence interval.
Returns:
The Clopper-Pearson confidence interval.
"""
lower, upper = 0, 1
# if counts == 0, the beta quantile returns nan
if counts != 0:
lower = beta.ppf(alpha / 2, counts, shots - counts + 1)
# if counts == shots, the beta quantile returns nan
if counts != shots:
upper = beta.ppf(1 - alpha / 2, counts + 1, shots - counts)
return lower, upper
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc)
|
https://github.com/arian-code/nptel_quantum_assignments
|
arian-code
|
import numpy as np
#Option A
p1=np.matrix([[0, 1],[-1, 0]])
print (p1)
print (p1.getH())
if (p1==p1.getH()).all():
print ("It is hermitian")
else:
print ("It is not hermitian")
#Option B
p1=np.matrix([[0, 0+1j],[0-1j, 0]])
print (p1)
print (p1.getH())
if (p1==p1.getH()).all():
print ("It is hermitian")
else:
print ("It is not hermitian")
#Option C
p1=np.matrix([[1, 0],[0, 0-1j]])
print (p1)
print (p1.getH())
if (p1==p1.getH()).all():
print ("It is hermitian")
else:
print ("It is not hermitian")
#Option D
p1=np.matrix([[1, 0+1j],[0-1j, -1]])
print (p1)
print (p1.getH())
if (p1==p1.getH()).all():
print ("It is hermitian")
else:
print ("It is not hermitian")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
qc.draw('mpl')
|
https://github.com/PaulaGarciaMolina/QNLP_Qiskit_Hackathon
|
PaulaGarciaMolina
|
import numpy as np
import pickle
import qiskit
qiskit.__qiskit_version__
from discopy import Ty, Word # Import the classes for the type of word and for the word
s, n = Ty('s'), Ty('n') # Define the types s and n
# Define the words (notice that we include both meaning and grammar)
# nouns
man, woman, kid = Word('man', n), Word('woman', n), Word('kid', n)
# adjectives
morose, irascible = Word('morose', n @ n.l), Word('irascible', n @ n.l)
frightened, cheerful = Word('frightened', n @ n.l), Word('cheerful', n @ n.l)
gloomy, furious = Word('gloomy', n @ n.l), Word('furious', n @ n.l)
terrified, joyful = Word('terrified', n @ n.l), Word('joyful', n @ n.l)
downcast, miserable = Word('downcast', n @ n.l), Word('miserable', n @ n.l)
old, young = Word('old', n @ n.l), Word('young', n @ n.l)
# Intransitive verbs
cries, shouts = Word('cries', n.r @ s), Word('shouts', n.r @ s)
laughs, snaps = Word('laughs', n.r @ s), Word('snaps', n.r @ s)
# Transitive verbs
grieves, startles = Word('grieves', n.r @ s @ n.l), Word('startles', n.r @ s @ n.l)
entertains, irritates = Word('entertains', n.r @ s @ n.l), Word('irritates', n.r @ s @ n.l)
nouns = [man, woman, kid]
adjectives = [morose, irascible, frightened, cheerful, gloomy, furious, terrified, joyful, downcast, miserable, old, young]
int_verbs = [cries, shouts, laughs, snaps]
t_verbs = [grieves, startles, entertains, irritates]
vocab = nouns + int_verbs + t_verbs + adjectives
from discopy import Cup, Id, pregroup
grammar = Id(n) @ Cup(n.l, n) @ Id(n.r @ s) >> Cup(n, n.r) @ Id(s) >> Id(s)
sentence = joyful @ woman @ laughs >> grammar
pregroup.draw(sentence)
grammar = Cup(n, n.r) @ Id(s) @ Cup(n.l, n)
sentence = woman @ grieves @ kid >> grammar
pregroup.draw(sentence)
grammar = Id(n) @ Cup(n.l, n) @ Id(n.r @ s) @ Cup(n.l, n) >> Cup(n, n.r) @ Id(s) >> Id(s)
sentence = morose @ woman @ grieves @ kid >> grammar
pregroup.draw(sentence)
grammar = Cup(n, n.r) @ Id(s) @ Cup(n.l, n) @ Cup(n.l, n) >> Id(s)
sentence = man @ grieves @ morose @ man >> grammar
pregroup.draw(sentence)
from discopy import Diagram
from discopy.grammar import draw
# Store the grammatical structures of each sentence type in a dictionary
grammar_dict = {
'ADJ_N_IV' : Id(n) @ Cup(n.l, n) @ Id(n.r @ s) >> Cup(n, n.r) @ Id(s) >> Id(s),
'N_TV_N': Cup(n, n.r) @ Id(s) @ Cup(n.l, n),
'ADJ_N_TV_N': Id(n) @ Cup(n.l, n) @ Id(n.r @ s) @ Cup(n.l, n) >> Cup(n, n.r) @ Id(s) >> Id(s),
'N_TV_ADJ_N': Cup(n, n.r) @ Id(s) @ Cup(n.l, n) @ Cup(n.l, n) >> Id(s)}
# Create parsing (grammatical analysis) dictionary where the grammatical sentences
# are the keys and the associated values are the diagrams (words + grammar)
data_psr = {}
#Creates all possible sentences
# Intransitive sentences
parsing_int = {"{} {} {}.".format(adj, noun, int_verb): adj @ noun @ int_verb >> grammar_dict['ADJ_N_IV']
for adj in adjectives for noun in nouns for int_verb in int_verbs}
sentences_int = list(parsing_int.keys())
for sentence in sentences_int:
diagram = parsing_int[sentence]
data_psr[sentence] = parsing_int[sentence]
# Transitive sentences (without adjective)
parsing_tra = {"{} {} {}.".format(subj, t_verb, obj): subj @ t_verb @ obj >> grammar_dict['N_TV_N']
for subj in nouns for t_verb in t_verbs for obj in nouns}
# Transitive sentences (with adjective)
parsing_tra_ladj = {"{} {} {} {}.".format(adj, subj, t_verb, obj): adj @ subj @ t_verb @ obj >> grammar_dict['ADJ_N_TV_N']
for adj in adjectives for subj in nouns for t_verb in t_verbs for obj in nouns}
parsing_tra_radj = {"{} {} {} {}.".format(subj, t_verb, adj, obj): subj @ t_verb @ adj @ obj >> grammar_dict['N_TV_ADJ_N']
for subj in nouns for t_verb in t_verbs for adj in adjectives for obj in nouns}
parsing_tra.update(parsing_tra_ladj) #merges transitive adjectives into original dict
parsing_tra.update(parsing_tra_radj)
sentences_tra = list(parsing_tra.keys())
for sentence in sentences_tra:
diagram = parsing_tra[sentence]
data_psr[sentence] = parsing_tra[sentence]
with open('../sentiment_analysis_dataset.txt') as f:
data = f.readlines()
labels_dict = {} # Dictionary with the labels for each sentence
data_psr_dict = {} # Dictionary with the parsing for each sentence
sent_type = {} # Dictionary with the sentence type for each sentence
adjective_words = [a.name for a in adjectives]
for sentence in data:
sentstr = sentence[:-7] #seperates the sentence string from the data at the end
if sentence[-6:-3] == 'int':
diagram = parsing_int[sentstr]
data_psr_dict[sentstr] = diagram
labels_dict[sentstr] = sentence[-2]
sent_type[sentstr] = 'int'
elif sentence[-6:-3] == 'tra':
diagram = parsing_tra[sentstr]
data_psr_dict[sentstr] = diagram
labels_dict[sentstr] = sentence[-2]
if len(sentstr.split()) == 4:
if sentstr.split()[0] in adjective_words:
sent_type[sentstr] = 'tra_' + 'l' #adjective on the left
else:
sent_type[sentstr] = 'tra_' + 'r' #adjective on the right
else:
sent_type[sentstr] = 'tra' #the simple transitive verb sentence type
c0 = 0
c1 = 0
c2 = 0
c3 = 0
for value in labels_dict.values():
if value == '0':
c0 +=1
elif value == '1':
c1 += 1
elif value == '2':
c2 += 1
elif value == '3':
c3 += 1
print('Number of elements for each sentiment')
print('Happy: ', c0)
print('Sad: ', c1)
print('Angry: ', c2)
print('Scared: ', c3)
print('Total', len(data_psr_dict))
from discopy import Cap, Box
# Code of this cell addapted from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources
#iterates through all sentences and reshapes them as above according to their type
data_new_psr_dict = {}
for sentstr in data_psr_dict.keys():
num_words = len(sentstr.split(' '))
words = data_psr_dict[sentstr].boxes[:num_words]
if sent_type[sentstr] == 'int':
noun = Box(words[1].name, n.l, Ty())
words_new = (Cap(n, n.l)) >> (words[0] @ Id(n) @ noun @ words[2])
sentence = words_new >> grammar_dict['ADJ_N_IV']
data_new_psr_dict[sentstr] = sentence.normal_form()
elif 'tra' in sent_type[sentstr]:
if sent_type[sentstr] == 'tra':
noun1 = Box(words[0].name, n.r, Ty())
noun2 = Box(words[2].name, n.l, Ty())
words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['N_TV_N']
data_new_psr_dict[sentstr] = sentence.normal_form()
elif sent_type[sentstr] == 'tra_l': #adjective at beginning
noun1 = Box(words[1].name, n.l, Ty())
noun2 = Box(words[3].name, n.l, Ty())
words_new = (Cap(n, n.l) @ Cap(n, n.l)) >> (words[0] @ Id(n) @ noun1 @ words[2] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['ADJ_N_TV_N']
data_new_psr_dict[sentstr] = sentence.normal_form()
elif sent_type[sentstr] == 'tra_r': #adjective on second noun
noun1 = Box(words[0].name, n.r, Ty())
noun2 = Box(words[3].name, n.l, Ty())
words_new = (Cap(n.r, n) @ Cap(n, n.l)) >> (noun1 @ Id(n) @ words[1] @ words[2] @ Id(n) @ noun2)
sentence = words_new >> grammar_dict['N_TV_ADJ_N']
data_new_psr_dict[sentstr] = sentence.normal_form()
vocab_psr = []
for word in vocab:
if word.cod == Ty('n'):
vocab_psr.append(Box(word.name, n.r, Ty())) # n.l case is dealt with in definition of quantum functor
else:
vocab_psr.append(word)
# Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources
from discopy.quantum import Ket, IQPansatz, Bra, qubit
from discopy.quantum.circuit import Functor, Id
from discopy.quantum.circuit import Circuit
from functools import reduce, partial
from discopy.quantum.gates import Rx, Rz
import numpy as np
q_s = 1 # number of qubits for type s (sentence)
q_n = 1 # number of qubits for type n (noun)
depth = 1 # depth of the IQPansatz
p_n = 3 # number of parameters for the single qubit iqp ansatz
# Define the dimensions of the objects of the circuit functor
ob = {s: q_s, n: q_n}
ob_cqmap = {s: qubit ** q_s, n: qubit ** q_n}
# Define the ansätze for states and effects
def single_qubit_iqp_ansatz(params):
if len(params) == 1:
return Rx(params[0])
if len(params) == 2:
return Rx(params[0]) >> Rz(params[1])
if len(params) == 3:
return IQPansatz(1, params)
def ansatz_state(state, params):
arity = sum(ob[Ty(factor.name)] for factor in state.cod)
if arity == 1:
return Ket(0) >> single_qubit_iqp_ansatz(params)
return Ket(*tuple([0 for i in range(arity)])) >> IQPansatz(arity, params)
def ansatz_effect(effect, params):
arity = sum(ob[Ty(factor.name)] for factor in effect.dom)
if arity == 1:
return single_qubit_iqp_ansatz(params) >> Bra(0)
return IQPansatz(arity, params) >> Bra(*tuple([0 for i in range(arity)]))
def ansatz(box,params):
dom_type = box.dom
cod_type = box.cod
if len(dom_type) == 0 and len(cod_type) != 0:
return ansatz_state(box, params)
if len(dom_type) != 0 and len(cod_type) == 0:
return ansatz_effect(box, params)
# Construct the circuit functor
def F(params):
ar = dict()
for i in range(len(vocab_psr)):
pgbox = vocab_psr[i]
qbox = ansatz(vocab_psr[i], params[i])
ar.update({pgbox: qbox})
if pgbox.cod == Ty():
ar.update({Box(pgbox.name, n.l, Ty()): qbox})
return Functor(ob_cqmap, ar)
# Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources
#*****************************************************
# Functions to deal with the parametrisation
#*****************************************************
def paramshapes(vocab_psr):
parshapes = []
for box in vocab_psr:
dom_type = box.dom
cod_type = box.cod
dom_arity = sum(ob[Ty(factor.name)] for factor in box.dom)
cod_arity = sum(ob[Ty(factor.name)] for factor in box.cod)
if dom_arity == 0 or cod_arity == 0: # states and effects
arity = max(dom_arity, cod_arity)
assert arity != 0
parshapes.append((depth, arity-1))
return parshapes
def randparams(par_shapes):
params = np.array([])
for i in range(len(par_shapes)):
params = np.concatenate((params, np.ravel(np.random.rand(*par_shapes[i])))) # np.ravel flattens an array
return params
def reshape_params(unshaped_pars, par_shapes):
pars_reshaped = [[] for ii in range(len(par_shapes))]
shift = 0
for ss, s in enumerate(par_shapes):
idx0 = 0 + shift
if len(s) == 1:
idx1 = s[0] + shift
elif len(s) == 2:
idx1 = s[0] * s[1] + shift
pars_reshaped[ss] = np.reshape(unshaped_pars[idx0:idx1], s)
if len(s) == 1:
shift += s[0]
elif len(s) == 2:
shift += s[0] * s[1]
return pars_reshaped
# Code of this cell from https://github.com/CQCL/qnlp_lorenz_etal_2021_resources
#****************************************
# Parameters of the current model
#****************************************
par_shapes = paramshapes(vocab_psr)
rand_unshaped_pars = randparams(par_shapes)
rand_shaped_pars = reshape_params(rand_unshaped_pars, par_shapes)
print('Number of parameters: ', len(rand_unshaped_pars))
# Print the quantum circuit for each sentence
func = F(rand_shaped_pars)
for sentstr in data_new_psr_dict:
print(sentstr)
print(data_new_psr_dict[sentstr])
#func(data_new_psr_dict[sentstr]).draw(draw_box_labels=True, figsize=(5, 5))
from sklearn.model_selection import train_test_split
psr_diagrams = []
psr_diagrams_dict = {}
psr_labels = []
sentences = []
#create lists of sentences and corresponding diagram and labels
for sentstr in data_new_psr_dict.keys():
sentences.append(sentstr)
diagram = data_new_psr_dict[sentstr]
psr_diagrams.append(diagram)
psr_diagrams_dict[sentstr] = diagram
if labels_dict[sentstr] == '0':
label = np.array([1,0,0,0])
elif labels_dict[sentstr] == '1':
label = np.array([0,1,0,0])
elif labels_dict[sentstr] == '2':
label = np.array([0,0,1,0])
elif labels_dict[sentstr] == '3':
label = np.array([0,0,0,1])
psr_labels.append(label)
#Splits the sentences and corresponding labels into train and test sets
train_sent, test_sent, train_labels, test_labels = \
train_test_split(sentences, psr_labels, test_size=0.25, random_state=42)
#Finds the discopy diagrams for the sentences in train and test
train_data_psr = [psr_diagrams_dict[sent] for sent in train_sent]
test_data_psr = [psr_diagrams_dict[sent] for sent in test_sent]
from qiskit import BasicAer, execute, ClassicalRegister
from pytket.extensions.qiskit import tk_to_qiskit
from qiskit.quantum_info import Statevector
#intransitive sentence
func(psr_diagrams_dict['morose woman cries.']).draw()
#basic transitive sentence
func(psr_diagrams_dict['man grieves woman.']).draw()
#transitive sentence, left adjective
func(psr_diagrams_dict['morose man grieves woman.']).draw()
#transitive sentence, right adjective
func(psr_diagrams_dict['man entertains joyful woman.']).draw()
def get_qiskit_results(circ, sent, retries=10, qasm=False):
"""Function to get the Qiskit's results from a DisCoPy circuit.
Args:
circ: DisCoPy circuit.
sent: English sentence corresponding to circuit
retries: number of retries before assigning a random result
if the postselection leads to zero values (Default is 10).
qasm: if True qasm_simulator is used, if not statevector_simulator
(Default is False).
Returns:
array: results from the postselection measurement.
"""
#Finds the sentence's type to determine the number of qubits and position of the sentence qubits
s_type = sent_type[sent]
if s_type == 'int':
n_qubits = 8
posts = [4,5]
elif s_type == 'tra':
n_qubits = 6
posts = [2,3]
elif s_type == 'tra_l':
n_qubits = 10
posts = [4,5]
else:
assert s_type == 'tra_r'
n_qubits = 10
posts = [2,3]
#the diagrams are initially in discopy, so we first convert them to tket and then to qiskit
qc = tk_to_qiskit(circ.to_tk())
if qasm == True:
backend = Aer.get_backend('qasm_simulator')
#qasm_simulator
out_reg = ClassicalRegister(2)
qc.add_register(out_reg)
qc.measure(posts, out_reg)
if noise_model is not None:
# Include noise model
results = execute(qc, backend, shots=max_shots, noise_model=noise_model,
coupling_map=coupling_map,basis_gates=basis_gates).result().get_counts()
else:
results = execute(qc, backend, shots=max_shots).result().get_counts()
zeros = '0' * (n_qubits - 1)
if '0 ' + zeros not in results and '1 ' + zeros not in results:
if retries == 0:
return np.random.rand(2)
return get_qiskit_results(circ, s_type, transpile, retries=retries-1, qasm = qasm_bool)
return parse_results(results, eff=zeros)
else:
qc.remove_final_measurements()
state_dict = Statevector(qc).to_dict()
#The only values we care about are the ones when the non-sentence qubits are all zero. This leaves 4 possible values
#for the sentence qubits, which we store in a list here
selections = ['0' * posts[0] + val + '0' * (n_qubits - posts[1] - 1) for val in ['00', '01', '10', '11']]
return [np.abs(state_dict[sel])**2 for sel in selections] #returns the amplitude of each of these four states
from qiskit.algorithms.optimizers import SPSA
import time
global_costs = [] #global variable to keep track of cost during training
begin_time = time.time()
def cost_ce(unshaped_params): #finds cross entropy cost
#creates a functor which turns a sentence diagram into a circuit parameterized by unshaped_params
func = F(reshape_params(unshaped_params, par_shapes))
#Applies this functor to every training diagram
circs = [func(diag) for diag in train_data_psr]
#Finds the post-selected qiskit results for each circuit
results = np.array([get_qiskit_results(circs[i], train_sent[i]) for i in range(len(train_sent))])
#Turns each result into a probability distribution
results_tweaked = [np.abs(np.array(res) - 1e-9) for res in results]
pred_labels_distrs = [res.flatten() / np.sum(res) for res in results_tweaked]
#finds the cross entropy
cross_entropies = np.array([np.sum(train_labels[s] * np.log2(pred_labels_distrs[s])) for s in range(len(train_labels))])
cost = -1 / len(train_data_psr) * np.sum(cross_entropies)
#stores the cost in a global list so we can track progress
global_costs.append(cost)
if len(global_costs) % 100 == 0: #since SPSA calls the cost function twice per iteration, this prints every 50 iterations
print("at iteration", len(global_costs)/2, time.time() - begin_time)
return cost
ps = {}
#Chooses random parameters to begin with
rand_unshaped_pars = randparams(par_shapes)
num_vars = len(rand_unshaped_pars)
#create bounds between 0 and 1 for every variable
bounds = [[0.0, 1.0] for _ in range(len(rand_unshaped_pars))]
n_iterations = 1250
a = time.time()
#creates a qiskit SPSA optimizer
opt = SPSA(maxiter=n_iterations)
print("\n\ncalibrating")
opt.calibrate(cost_ce, initial_point=rand_unshaped_pars) #calibrates it with the cost function and starting parameters
print("training")
global_costs = []
begin_time = time.time()
ps = opt.optimize(num_vars, cost_ce, initial_point=rand_unshaped_pars, variable_bounds=bounds)
print("took", time.time() - a)
pickle.dump([ps, global_costs], open("sentiment_analysis_qiskit_ce_1250.p", "wb"))
func = F(reshape_params(ps[0], par_shapes))
circs = [func(diag) for diag in test_data_psr]
results = np.array([get_qiskit_results(circs[i], test_sent[i]) for i in range(len(test_sent))])
results_tweaked = [np.abs(np.array(res) - 1e-9) for res in results]
pred_labels_distrs = [res.flatten() / np.sum(res) for res in results_tweaked]
from sklearn.metrics import confusion_matrix
import pandas as pd
import seaborn as sns
c_matrix = confusion_matrix([np.argmax(t) for t in test_labels], [np.argmax(r) for r in pred_labels_distrs])
df_cm = pd.DataFrame(c_matrix, ['happy','sad','angry','scared'], ['happy','sad','angry','scared'])
df_cm.index.name = 'Actual'
df_cm.columns.name = 'Predicted'
sns.heatmap(df_cm, annot=True, annot_kws={"size": 16},cmap='viridis',
xticklabels=True, yticklabels=True)
print("test accuracy =", sum([np.argmax(test_labels[i]) == np.argmax(pred_labels_distrs[i]) for i in range(len(test_labels))])/len(test_labels))
costs = global_costs[51:]
n = ps[-1]
costs = [(costs[j*2] + costs[j*2 + 1])/2 for j in range(n//2)]
import matplotlib.pyplot as plt
plt.xlabel('Iterations')
plt.ylabel('Cross Entropy')
plt.title("2-Qubit Multi-class Classification")
plt.plot(costs)
|
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.
"""A collection of backend information formatted to generate drawing data.
This instance will be provided to generator functions. The module provides an abstract
class :py:class:``DrawerBackendInfo`` with necessary methods to generate drawing objects.
Because the data structure of backend class may depend on providers, this abstract class
has an abstract factory method `create_from_backend`. Each subclass should provide
the factory method which conforms to the associated provider. By default we provide
:py:class:``OpenPulseBackendInfo`` class that has the factory method taking backends
satisfying OpenPulse specification [1].
This class can be also initialized without the factory method by manually specifying
required information. This may be convenient for visualizing a pulse program for simulator
backend that only has a device Hamiltonian information. This requires two mapping objects
for channel/qubit and channel/frequency along with the system cycle time.
If those information are not provided, this class will be initialized with a set of
empty data and the drawer illustrates a pulse program without any specific information.
Reference:
- [1] Qiskit Backend Specifications for OpenQASM and OpenPulse Experiments,
https://arxiv.org/abs/1809.03452
"""
from abc import ABC, abstractmethod
from collections import defaultdict
from typing import Dict, List, Union, Optional
from qiskit import pulse
from qiskit.providers import BackendConfigurationError
from qiskit.providers.backend import Backend
class DrawerBackendInfo(ABC):
"""Backend information to be used for the drawing data generation."""
def __init__(
self,
name: Optional[str] = None,
dt: Optional[float] = None,
channel_frequency_map: Optional[Dict[pulse.channels.Channel, float]] = None,
qubit_channel_map: Optional[Dict[int, List[pulse.channels.Channel]]] = None,
):
"""Create new backend information.
Args:
name: Name of the backend.
dt: System cycle time.
channel_frequency_map: Mapping of channel and associated frequency.
qubit_channel_map: Mapping of qubit and associated channels.
"""
self.backend_name = name or "no-backend"
self._dt = dt
self._chan_freq_map = channel_frequency_map or {}
self._qubit_channel_map = qubit_channel_map or {}
@classmethod
@abstractmethod
def create_from_backend(cls, backend: Backend):
"""Initialize a class with backend information provided by provider.
Args:
backend: Backend object.
"""
raise NotImplementedError
@property
def dt(self):
"""Return cycle time."""
return self._dt
def get_qubit_index(self, chan: pulse.channels.Channel) -> Union[int, None]:
"""Get associated qubit index of given channel object."""
for qind, chans in self._qubit_channel_map.items():
if chan in chans:
return qind
return chan.index
def get_channel_frequency(self, chan: pulse.channels.Channel) -> Union[float, None]:
"""Get frequency of given channel object."""
return self._chan_freq_map.get(chan, None)
class OpenPulseBackendInfo(DrawerBackendInfo):
"""Drawing information of backend that conforms to OpenPulse specification."""
@classmethod
def create_from_backend(cls, backend: Backend):
"""Initialize a class with backend information provided by provider.
Args:
backend: Backend object.
Returns:
OpenPulseBackendInfo: New configured instance.
"""
configuration = backend.configuration()
defaults = backend.defaults()
# load name
name = backend.name()
# load cycle time
dt = configuration.dt
# load frequencies
chan_freqs = {}
chan_freqs.update(
{pulse.DriveChannel(qind): freq for qind, freq in enumerate(defaults.qubit_freq_est)}
)
chan_freqs.update(
{pulse.MeasureChannel(qind): freq for qind, freq in enumerate(defaults.meas_freq_est)}
)
for qind, u_lo_mappers in enumerate(configuration.u_channel_lo):
temp_val = 0.0 + 0.0j
for u_lo_mapper in u_lo_mappers:
temp_val += defaults.qubit_freq_est[u_lo_mapper.q] * u_lo_mapper.scale
chan_freqs[pulse.ControlChannel(qind)] = temp_val.real
# load qubit channel mapping
qubit_channel_map = defaultdict(list)
for qind in range(configuration.n_qubits):
qubit_channel_map[qind].append(configuration.drive(qubit=qind))
qubit_channel_map[qind].append(configuration.measure(qubit=qind))
for tind in range(configuration.n_qubits):
try:
qubit_channel_map[qind].extend(configuration.control(qubits=(qind, tind)))
except BackendConfigurationError:
pass
return OpenPulseBackendInfo(
name=name, dt=dt, channel_frequency_map=chan_freqs, qubit_channel_map=qubit_channel_map
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.qasm3
program = """
OPENQASM 3.0;
include "stdgates.inc";
input float[64] a;
qubit[3] q;
bit[2] mid;
bit[3] out;
let aliased = q[0:1];
gate my_gate(a) c, t {
gphase(a / 2);
ry(a) c;
cx c, t;
}
gate my_phase(a) c {
ctrl @ inv @ gphase(a) c;
}
my_gate(a * 2) aliased[0], q[{1, 2}][0];
measure q[0] -> mid[0];
measure q[1] -> mid[1];
while (mid == "00") {
reset q[0];
reset q[1];
my_gate(a) q[0], q[1];
my_phase(a - pi/2) q[1];
mid[0] = measure q[0];
mid[1] = measure q[1];
}
if (mid[0]) {
let inner_alias = q[{0, 1}];
reset inner_alias;
}
out = measure q;
"""
circuit = qiskit.qasm3.loads(program)
circuit.draw("mpl")
|
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import numpy as np
from fractions import Fraction as frac
import qiskit.quantum_info as qi
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
qc=QuantumCircuit(4)
#In this particular oracle, the last qubit is storing the value of the function
qc.cx(0,3)
qc.cx(1,3)
qc.cx(2,3)
#The last qubit is 1 if there are odd no. of 1s in the other 3 qubits
#and 0 otherwise
#Hence it is a balanced function
qc.draw('mpl')
qc1=QuantumCircuit(3)
qc1.x(2)
qc1.h(0)
qc1.h(1)
qc1.h(2)
qc1.barrier(range(3))
qc1.cx(0,2)
qc1.cx(1,2)
qc1.barrier(range(3))
qc1.h(0)
qc1.h(1)
meas = QuantumCircuit(3, 2)
meas.measure(range(2),range(2))
# The Qiskit circuit object supports composition using
# the addition operator.
circ = qc1+meas
circ.draw('mpl')
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=1000)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
plot_histogram(counts)
qc2=QuantumCircuit(5)
qc2.x(4)
qc2.h(0)
qc2.h(1)
qc2.h(2)
qc2.h(3)
qc2.h(4)
qc2.barrier(range(5))
#Your code for the oracle here
#YOU ARE PERMITTED TO USE ONLY SINGLE QUBIT GATES AND CNOT(cx) GATES
qc2.cx(0,4)
qc2.cx(1,4)
qc2.cx(2,4)
qc2.cx(3,4)
qc2.x(4)
qc2.barrier(range(5))
qc2.h(0)
qc2.h(1)
qc2.h(2)
qc2.h(3)
meas2 = QuantumCircuit(5, 4)
meas2.measure(range(4),range(4))
circ2 = qc2+meas2
circ2.draw('mpl')
#verification cell, reinitialising the circuit so that it's easier for you to copy-paste the oracle
qc2=QuantumCircuit(5)
#Add X gates HERE as required to change the input state
qc2.x([0,2])
qc2.barrier(range(5))
qc2.cx(0,4)
qc2.cx(1,4)
qc2.cx(2,4)
qc2.cx(3,4)
qc2.x(4)
qc2.barrier(range(5))
measv = QuantumCircuit(5, 1)
measv.measure(4,0)
circv = qc2+measv
circv.draw('mpl')
#DO NOT RUN THIS CELL WITHOUT EDITING THE ABOVE ONE AS DESIRED
#The following code will give you f(x) for the value of x you chose in the above cell
backend_sim2 = Aer.get_backend('qasm_simulator')
job_sim2 = execute(circv, backend_sim2, shots=1000)
result_sim2 = job_sim2.result()
counts2 = result_sim2.get_counts(circv)
print(counts2)
plot_histogram(counts2)
|
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):
# 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)
# Print the results
print("simulation: ", result_sim, result_counts)
if draw_circuit: # draw the circuit
draw(qc)
else: # or show the results
show_results(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):
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 not draw_circuit: # show the results
show_results(result_counts)
except:
print("All devices are currently unavailable.")
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)
# H gate on qubit 0
# measure the specific qubit
# H gate on qubit 1
# measure the specific qubit
# CNOT gate
# measure the specific qubit
# H gate on 2 qubits
# CNOT gate
# measure
# measure
# execute_remotely(circuit)
|
https://github.com/abhishekchak52/quantum-computing-course
|
abhishekchak52
|
import math
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.visualization import plot_bloch_multivector
from qiskit.visualization import plot_bloch_vector
from qiskit.visualization import plot_histogram
qbackend = Aer.get_backend('qasm_simulator')
sbackend = Aer.get_backend('statevector_simulator')
ubackend = Aer.get_backend('unitary_simulator')
qiskit.__version__
import torch
torch.__version__
import strawberryfields as sf
sf.__version__
help(sf)
import cirq
cirq.__version__
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
"""
Utility functions for debugging and testing.
"""
from typing import Tuple
import numpy as np
from scipy.stats import unitary_group
import qiskit.transpiler.synthesis.aqc.fast_gradient.fast_grad_utils as fgu
def relative_error(a_mat: np.ndarray, b_mat: np.ndarray) -> float:
"""
Computes relative residual between two matrices in Frobenius norm.
"""
return float(np.linalg.norm(a_mat - b_mat, "fro")) / float(np.linalg.norm(b_mat, "fro"))
def make_unit_vector(pos: int, nbits: int) -> np.ndarray:
"""
Makes a unit vector ``e = (0 ... 0 1 0 ... 0)`` of size ``2^n`` with
unit at the position ``num``. **Note**: result depends on bit ordering.
Args:
pos: position of unit in vector.
nbits: number of meaningful bit in the number "pos".
Returns:
unit vector of size ``2^n``.
"""
vec = np.zeros((2**nbits,), dtype=np.int64)
vec[fgu.reverse_bits(pos, nbits, enable=True)] = 1
return vec
def eye_int(n: int) -> np.ndarray:
"""
Creates an identity matrix with integer entries.
Args:
n: number of bits.
Returns:
unit matrix of size ``2^n`` with integer entries.
"""
return np.eye(2**n, dtype=np.int64)
def kron3(a_mat: np.ndarray, b_mat: np.ndarray, c_mat: np.ndarray) -> np.ndarray:
"""
Computes Kronecker product of 3 matrices.
"""
return np.kron(a_mat, np.kron(b_mat, c_mat))
def kron5(
a_mat: np.ndarray, b_mat: np.ndarray, c_mat: np.ndarray, d_mat: np.ndarray, e_mat: np.ndarray
) -> np.ndarray:
"""
Computes Kronecker product of 5 matrices.
"""
return np.kron(np.kron(np.kron(np.kron(a_mat, b_mat), c_mat), d_mat), e_mat)
def rand_matrix(dim: int, kind: str = "complex") -> np.ndarray:
"""
Generates a random complex or integer value matrix.
Args:
dim: matrix size dim-x-dim.
kind: "complex" or "randint".
Returns:
a random matrix.
"""
if kind == "complex":
return (
np.random.rand(dim, dim).astype(np.cfloat)
+ np.random.rand(dim, dim).astype(np.cfloat) * 1j
)
else:
return np.random.randint(low=1, high=100, size=(dim, dim), dtype=np.int64)
def make_test_matrices2x2(n: int, k: int, kind: str = "complex") -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a ``2^n x 2^n`` random matrix made as a Kronecker product of identity
ones and a single 1-qubit gate. This models a layer in quantum circuit with
an arbitrary 1-qubit gate somewhere in the middle.
Args:
n: number of qubits.
k: index of qubit a 1-qubit gate is acting on.
kind: entries of the output matrix are defined as:
"complex", "primes" or "randint".
Returns:
A tuple of (1) ``2^n x 2^n`` random matrix; (2) ``2 x 2`` matrix of 1-qubit
gate used for matrix construction.
"""
if kind == "primes":
a_mat = np.asarray([[2, 3], [5, 7]], dtype=np.int64)
else:
a_mat = rand_matrix(dim=2, kind=kind)
m_mat = kron3(eye_int(k), a_mat, eye_int(n - k - 1))
return m_mat, a_mat
def make_test_matrices4x4(
n: int, j: int, k: int, kind: str = "complex"
) -> Tuple[np.ndarray, np.ndarray]:
"""
Creates a ``2^n x 2^n`` random matrix made as a Kronecker product of identity
ones and a single 2-qubit gate. This models a layer in quantum circuit with
an arbitrary 2-qubit gate somewhere in the middle.
Args:
n: number of qubits.
j: index of the first qubit the 2-qubit gate acting on.
k: index of the second qubit the 2-qubit gate acting on.
kind: entries of the output matrix are defined as:
"complex", "primes" or "randint".
Returns:
A tuple of (1) ``2^n x 2^n`` random matrix; (2) ``4 x 4`` matrix of
2-qubit gate used for matrix construction.
"""
if kind == "primes":
a_mat = np.asarray([[2, 3], [5, 7]], dtype=np.int64)
b_mat = np.asarray([[11, 13], [17, 19]], dtype=np.int64)
c_mat = np.asarray([[47, 53], [41, 43]], dtype=np.int64)
d_mat = np.asarray([[31, 37], [23, 29]], dtype=np.int64)
else:
a_mat, b_mat = rand_matrix(dim=2, kind=kind), rand_matrix(dim=2, kind=kind)
c_mat, d_mat = rand_matrix(dim=2, kind=kind), rand_matrix(dim=2, kind=kind)
if j < k:
m_mat = kron5(eye_int(j), a_mat, eye_int(k - j - 1), b_mat, eye_int(n - k - 1)) + kron5(
eye_int(j), c_mat, eye_int(k - j - 1), d_mat, eye_int(n - k - 1)
)
else:
m_mat = kron5(eye_int(k), b_mat, eye_int(j - k - 1), a_mat, eye_int(n - j - 1)) + kron5(
eye_int(k), d_mat, eye_int(j - k - 1), c_mat, eye_int(n - j - 1)
)
g_mat = np.kron(a_mat, b_mat) + np.kron(c_mat, d_mat)
return m_mat, g_mat
def rand_circuit(num_qubits: int, depth: int) -> np.ndarray:
"""
Generates a random circuit of unit blocks for debugging and testing.
"""
blocks = np.tile(np.arange(num_qubits).reshape(num_qubits, 1), depth)
for i in range(depth):
np.random.shuffle(blocks[:, i])
return blocks[0:2, :].copy()
def rand_su_mat(dim: int) -> np.ndarray:
"""
Generates a random SU matrix.
Args:
dim: matrix size ``dim-x-dim``.
Returns:
random SU matrix.
"""
u_mat = unitary_group.rvs(dim)
u_mat /= np.linalg.det(u_mat) ** (1.0 / float(dim))
return u_mat
|
https://github.com/JavaFXpert/quantum-circuit-pygame
|
JavaFXpert
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, execute
from qiskit.tools.visualization import plot_state_qsphere
from utils import load_image
class QSphere(pygame.sprite.Sprite):
"""Displays a qsphere"""
def __init__(self, circuit):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.set_circuit(circuit)
# def update(self):
# # Nothing yet
# a = 1
def set_circuit(self, circuit):
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
job_sim = execute(circuit, backend_sv_sim)
result_sim = job_sim.result()
quantum_state = result_sim.get_statevector(circuit, decimals=3)
qsphere = plot_state_qsphere(quantum_state)
qsphere.savefig("utils/data/bell_qsphere.png")
self.image, self.rect = load_image('bell_qsphere.png', -1)
self.rect.inflate_ip(-100, -100)
self.image.convert()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- 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/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/quantum-kittens/quantum-computing-basics
|
quantum-kittens
|
# run this cell if you're executing this notebook in your browser
!pip install qiskit
from IPython.display import clear_output
clear_output()
from qiskit import *
import numpy as np
qc = QuantumCircuit(2,2)
qc.draw('mpl')
qreg = QuantumRegister(2, name = 'qreg')
creg = ClassicalRegister(2, name = 'creg')
qc = QuantumCircuit(qreg, creg)
qc.draw('mpl')
qc = QuantumCircuit(1)
# set the angles to whatever you want
theta = np.pi/2
phi = np.pi/4
lambdaa = np.pi
# comment/uncomment the gates to play with them
qc.x(0) # x on qubit 0
qc.y(0) # y on qubit 0
qc.z(0) # z on qubit 0
qc.s(0) # s gate on qubit 0, sqrt of z
qc.sdg(0) # s† on qubit 0
qc.t(0) # t gate on qubit 0, sqrt of s
qc.tdg(0) # t† on qubit 0
### rotations
qc.rx(theta,0) # rx rotation on qubit 0
qc.ry(theta,0) # ry rotation on qubit 0
qc.rz(theta,0) # rz rotation on qubit 0
### generic
qc.u(theta, phi, lambdaa, 0) #u3 gate
qc.u2(phi, lambdaa, 0) #u2 = u3(pi/2, phi, lambdaa)
qc.p(lambdaa, 0) #p = u1 = u3(0, 0, lambdaa)
#
display(qc.draw('mpl'))
display(qc.draw())
qc = QuantumCircuit(2)
# set the angles to whatever you want
theta = np.pi/2
phi = np.pi/4
lambdaa = np.pi
# comment/uncomment any of the following to your heart's content
qc.cx(0,1) # CNOT with qubit 0 as control and qubit 1 as target
qc.cy(0,1) # controlled-Y with qubit 0 as control and qubit 1 as target
qc.cz(0,1) # controlled-Z with qubit 0 as control and qubit 1 as target
qc.ch(0, 1) # controlled-H with qubit 0 as control and qubit 1 as target
qc.cu3(theta, phi, lambdaa, 0, 1) # controlled-u3 with qubit 0 as control and qubit 1 as target
qc.swap(0,1) # swap qubits 0 and 1
#
qc.draw('mpl')
from qiskit.circuit.library import CXGate
qc = QuantumCircuit(3)
# Method 1:
qc.ccx(0,1,2)
# Method 2:
qc.mct([0,1],2)
#Method 3
our_ccx = CXGate().control()
qc.append(our_ccx, [0,1,2])
qc.draw('mpl')
qc_bell = QuantumCircuit(2)
qc_bell.h(0)
qc_bell.cx(0,1)
qc_bell.x(1)
qc_bell.z(1)
display(qc_bell.draw('mpl'))
from qiskit.quantum_info import Statevector
state = Statevector(qc_bell)
state.draw('latex', prefix = '\\left|\\psi^-\\right\\rangle = ' )
bell_qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
gate bell a, b {
u(pi/2, 0, pi) a;
cx a, b;
}
qreg q[2];
creg c[2];
bell q[0], q[1];
x q[1];
z q[1];
barrier q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
"""
qc_bell_qasm = QuantumCircuit.from_qasm_str(bell_qasm_string)
qc_bell_qasm.draw('mpl')
qc_bell_string = qc_bell.qasm()
print(qc_bell_string)
qc_bell_init = QuantumCircuit(2)
qc_bell_init.h(0)
qc_bell_init.cx(0,1)
display(qc_bell_init.draw('mpl'))
bell_gate = qc_bell_init.to_gate()
bell_gate.name ='Bell Gate'
qc_bell_gate = QuantumCircuit(2)
qc_bell_gate.append(bell_gate, [0,1])
display(qc_bell_gate.draw('mpl'))
from qiskit.quantum_info import Operator
from qiskit.visualization import array_to_latex
U = Operator(qc_bell)
array_to_latex(U.data, prefix = 'U = ')
from qiskit.providers.aer import UnitarySimulator
backend = UnitarySimulator() # alternative: backend = Aer.get_backend('unitary_simulator')
job = execute(qc_bell, backend)
U = job.result().get_unitary()
display(array_to_latex(U.data, prefix = 'U = '))
from qiskit.providers.aer import QasmSimulator
qc_measure = QuantumCircuit(2,2)
qc_measure.barrier()
qc_measure.measure([0,1], [0,1]) # alternative: qc_measure = QuantumCircuit(2) | qc_measure.measure_all() = .barrier() + measure every qubit + creates a classical register
qc_bell_measure = qc_measure.compose(qc_bell, range(2), front = True) # combines two circuits, placing qc_bell in front of qc_measure
display(qc_bell_measure.draw('mpl'))
backend = QasmSimulator() # alternative: backend = Aer.get_backend('qasm_simulator')
job = execute(qc_bell_measure, backend, shots = 1024) # alternative: qc_transpiled = transpile(qc_bell_measure, backend), job = backend.run(qc_transpiled, shots = 1024)
counts = job.result().get_counts()
print('Counts: ' + str(counts))
from qiskit.visualization import plot_histogram
plot_histogram(counts)
job = execute(qc_bell_measure, backend, shots = 1024)
counts_2 = job.result().get_counts()
print('Counts, second experiment: ' + str(counts_2))
legend = ['First Experiment', 'Second Experiment']
plot_histogram([counts, counts_2], legend = legend, color = ['teal', 'black'], figsize = (10, 7), bar_labels = False)
qc_ghz = QuantumCircuit(3)
qc_ghz.h(0)
qc_ghz.cx(0,1)
qc_ghz.ccx(0,1,2)
qc_ghz.draw('mpl') #original circuit
display(qc_ghz.decompose().draw('mpl')) #decompose one level down
display(qc_ghz.decompose().decompose().draw('mpl')) #decompose two levels down
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
gates_pass = Unroller(['u1', 'u2', 'u3', 'cx']) #play around with this
pm = PassManager(gates_pass)
pm.run(qc_ghz).draw('mpl')
print('The circuit depth of the Bell circuit without measurements is: ' + str(qc_bell.depth()))
#Qiskit counts the measurements in the depth calculation:
print('The circuit depth of the Bell circuit with measurements is: ' + str(qc_bell_measure.depth()))
from qiskit.circuit.random import random_circuit
import random
#play around with these parameters:
num_qubits = 3
max_depth = 10
add_measurements = True #True/False
#random circuit:
rand_circ = random_circuit(num_qubits, depth = random.randint(1,max_depth), measure=add_measurements)
rand_circ.draw('mpl')
# run this cell to see if you are correct
print('The circuit depth is: ' + str(rand_circ.depth()))
|
https://github.com/nahumsa/volta
|
nahumsa
|
import sys
sys.path.append('../../')
# Python imports
import numpy as np
import matplotlib.pyplot as plt
# Qiskit
from qiskit import BasicAer
from qiskit.aqua.components.optimizers import COBYLA, SPSA
from qiskit.circuit.library import TwoLocal
# VOLTA
from volta.vqd import VQD
from volta.utils import classical_solver
from volta.hamiltonians import BCS_hamiltonian
%load_ext autoreload
%autoreload 2
EPSILONS = [3, 3]
V = -2
hamiltonian = BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
eigenvalues, eigenvectors = classical_solver(hamiltonian)
print(f"Eigenvalues: {eigenvalues}")
from itertools import product
# Get the ideal count
ideal_dict = {}
bin_combinations = list(product(['0','1'], repeat=hamiltonian.num_qubits))
for i, eigvect in enumerate(np.abs(eigenvectors)**2):
dic = {}
for ind, val in enumerate(bin_combinations):
val = ''.join(val)
dic[val] = eigvect[ind]
ideal_dict[i] = dic
from qiskit.aqua import QuantumInstance
# Define Optimizer
# optimizer = COBYLA()
optimizer = SPSA(maxiter=1000)
# Define Backend
# backend = BasicAer.get_backend('qasm_simulator')
backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'),
shots=10000)
# Define ansatz
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2)
# Run algorithm
Algo = VQD(hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=3,
beta=10.,
optimizer=optimizer,
backend=backend)
Algo.run()
vqd_energies = Algo.energies
vqd_states = Algo.states
from copy import copy
# Create states and measure them
states = []
for ind, state in enumerate(vqd_states):
states.append(copy(state))
states[ind].measure_all()
from qiskit import execute
from qiskit.visualization import plot_histogram
backend = BasicAer.get_backend('qasm_simulator')
count = execute(states[0], backend=backend, shots=10000).result().get_counts()
plot_histogram([ideal_dict[0], count],legend=['Ideal','Result'])
count = execute(states[1], backend=backend, shots=10000).result().get_counts()
plot_histogram([ideal_dict[1], count],legend=['Ideal','Result'])
count = execute(states[2], backend=backend, shots=10000).result().get_counts()
plot_histogram([ideal_dict[2], count],legend=['Ideal','Result'])
count = execute(states[3], backend=backend, shots=10000).result().get_counts()
plot_histogram([ideal_dict[3], count],legend=['Ideal','Result'])
eigenvalues
vqd_energies
n_1_sim, n_2_sim = 1, 2
n_1_vqd, n_2_vqd = 1, 2
print(f"Gap Exact: {(eigenvalues[n_2_sim] - eigenvalues[n_1_sim])/2}")
print(f"Gap VQD: {(vqd_energies[n_2_vqd] - vqd_energies[n_1_vqd])/2}")
from tqdm import tqdm
def hamiltonian_varying_eps(eps, V):
energies_VQD = []
energies_Classical = []
for epsilons in tqdm(eps):
hamiltonian = BCS_hamiltonian(epsilons, V)
optimizer = COBYLA(maxiter=10000)
backend = BasicAer.get_backend('qasm_simulator')
Algo = VQD(hamiltonian=hamiltonian,
n_excited_states=1,
beta=3.,
optimizer=optimizer,
backend=backend)
Algo.run(0)
uantum = Algo.energies
energies_VQD.append([quantum[1], quantum[2]])
classical = classical_solver(hamiltonian)
energies_Classical.append([classical[1], classical[2]])
return energies_VQD, energies_Classical
eps = [[1, 1.5], [1, 2.], [1, 2.5]]
V = -1.
energy_vqd, energy_classical = hamiltonian_varying_eps(eps, V)
plt.plot([str(v) for v in eps], [value[1] - value[0] for value in energy_vqd], 'ro', label="VQD")
plt.plot([str(v) for v in eps], [value[1] - value[0] for value in energy_classical], 'go', label="Exact")
plt.xlabel('$\epsilon$')
plt.ylabel('Gap')
plt.legend()
plt.show()
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# Install the plugin
# !pip install -e .
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.routing import AIRouting
from qiskit.circuit.library import EfficientSU2
circuit = EfficientSU2(100, entanglement="circular", reps=1).decompose()
print(
f"Original circuit -> Depth: {circuit.depth()}, Gates(2q): {circuit.num_nonlocal_gates()}"
)
circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
qiskit_ai_transpiler = PassManager(
[AIRouting(backend_name="ibm_torino", optimization_level=1, layout_mode="optimize")]
)
ai_transpiled_circuit = qiskit_ai_transpiler.run(circuit)
print(
f"Qiskit AI Transpiler -> Depth: {ai_transpiled_circuit.depth()}, Gates(2q): {ai_transpiled_circuit.num_nonlocal_gates()}"
)
ai_transpiled_circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
coupling_map = QiskitRuntimeService().backend("ibm_torino").coupling_map
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=3, coupling_map=coupling_map
)
lvl3_transpiled_circuit = qiskit_lvl3_transpiler.run(circuit)
print(
f"Qiskit lvl3 Transpiler -> Depth: {lvl3_transpiled_circuit.depth()}, Gates(2q): {lvl3_transpiled_circuit.num_nonlocal_gates()}"
)
lvl3_transpiled_circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
from qiskit_transpiler_service.transpiler_service import TranspilerService
qiskit_lvl3_transpiler_service = TranspilerService(
backend_name="ibm_torino",
ai="false",
optimization_level=3,
)
lvl3_transpiled_circuit_v2 = qiskit_lvl3_transpiler_service.run(circuit)
print(
f"Qiskit lvl3 Transpiler -> Depth: {lvl3_transpiled_circuit_v2.depth()}, Gates(2q): {lvl3_transpiled_circuit_v2.num_nonlocal_gates()}"
)
lvl3_transpiled_circuit_v2.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
qiskit_lvl3_ai_transpiler_service = TranspilerService(
backend_name="ibm_torino",
ai="true",
optimization_level=3,
)
lvl3_transpiled_ai_circuit_v2 = qiskit_lvl3_ai_transpiler_service.run(circuit)
print(
f"Qiskit lvl3 AI Transpiler -> Depth: {lvl3_transpiled_ai_circuit_v2.depth()}, Gates(2q): {lvl3_transpiled_ai_circuit_v2.num_nonlocal_gates()}"
)
lvl3_transpiled_ai_circuit_v2.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
|
https://github.com/maximusron/qgss_2021_labs
|
maximusron
|
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear')
ansatz.draw('mpl', style='iqx')
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
from qiskit import Aer
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718)
from qiskit.circuit import QuantumCircuit
from qiskit.opflow import Z, X
H = X ^ X
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
# YOUR CODE HERE
expectation = StateFn(H, is_measurement=True) @ StateFn(U)
matmult_result = expectation.eval()
from qc_grader import grade_lab4_ex1
# Note that the grading function is expecting a complex number
grade_lab4_ex1(matmult_result)
from qiskit.opflow import CircuitSampler, PauliExpectation
sampler = CircuitSampler(q_instance)
# YOUR CODE HERE
expectation = StateFn(H, is_measurement=True) @ StateFn(U)
in_pauli_basis = PauliExpectation().convert(expectation)
shots_result = sampler.convert(in_pauli_basis).eval()
from qc_grader import grade_lab4_ex2
# Note that the grading function is expecting a complex number
grade_lab4_ex2(shots_result)
from qiskit.opflow import PauliExpectation, CircuitSampler
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
in_pauli_basis = PauliExpectation().convert(expectation)
sampler = CircuitSampler(q_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(in_pauli_basis, params=value_dict).eval()
return np.real(result)
eps = 0.2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('lin_comb') # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341])
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(q_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here!
return np.real(result)
# Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import GradientDescent
from qc_grader.gradient_descent import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate the gradient
initial_point=initial_point) # initial point
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='tab:red', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend();
from qiskit.opflow import NaturalGradient
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
natural_gradient = NaturalGradient(regularization='ridge').convert(expectation)
natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient)
sampler = CircuitSampler(q_instance, caching="all")
def evaluate_natural_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(natural_gradient, params=value_dict).eval()
return np.real(result)
print('Vanilla gradient:', evaluate_gradient(initial_point))
print('Natural gradient:', evaluate_natural_gradient(initial_point))
qng_loss = []
def qng_callback(nfevs, x, fx, stepsize):
qng_loss.append(fx)
qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback)
x_opt, fx_opt, nfevs = qng.optimize(initial_point.size,
evaluate_expectation,
gradient_function=evaluate_natural_gradient,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
from qc_grader.spsa import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback)
x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
# Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import QNSPSA
from qc_grader.qnspsa import QNSPSA
qnspsa_loss = []
def qnspsa_callback(nfev, x, fx, stepsize, accepted):
qnspsa_loss.append(fx)
fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation())
qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback)
x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
autospsa_loss = []
def autospsa_callback(nfev, x, fx, stepsize, accepted):
autospsa_loss.append(fx)
autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback)
x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X)
from qc_grader import grade_lab4_ex3
# Note that the grading function is expecting a Hamiltonian
grade_lab4_ex3(H_tfi)
from qiskit.circuit.library import EfficientSU2
efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2)
tfi_sampler = CircuitSampler(q_instance)
def evaluate_tfi(parameters):
exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2))
value_dict = dict(zip(efficient_su2.parameters, parameters))
result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval()
return np.real(result)
# target energy
tfi_target = -3.4939592074349326
# initial point for reproducibility
tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282,
0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126,
0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325,
0.48311132, 0.43623886, 0.6371297 ])
spsa = SPSA(maxiter = 300, learning_rate = None, perturbation = None, callback = None)
tfi_result = spsa.optimize(tfi_init.size, evaluate_tfi, initial_point = tfi_init)
tfi_minimum = tfi_result[1]
print("Error:", np.abs(tfi_result[1] - tfi_target))
from qc_grader import grade_lab4_ex4
# Note that the grading function is expecting a floating point number
grade_lab4_ex4(tfi_minimum)
from qiskit_machine_learning.datasets import ad_hoc_data
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=20, test_size=10, n=2, one_hot=False, gap=0.5
)
# the training labels are in {0, 1} but we'll use {-1, 1} as class labels!
training_labels = 2 * training_labels - 1
test_labels = 2 * test_labels - 1
def plot_sampled_data():
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label in zip(test_features, test_labels):
marker = 's'
plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k')
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_sampled_data()
from qiskit.circuit.library import ZZFeatureMap
dim = 2
feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple!
feature_map.draw('mpl', style='iqx')
ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here!
ansatz.draw('mpl', style='iqx')
circuit = feature_map.compose(ansatz)
circuit.draw('mpl', style='iqx')
hamiltonian = Z ^ Z # global Z operators
gd_qnn_loss = []
def gd_qnn_callback(*args):
gd_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback)
from qiskit_machine_learning.neural_networks import OpflowQNN
qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
exp_val=PauliExpectation(),
gradient=Gradient(), # <-- Parameter-Shift gradients
quantum_instance=q_instance)
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
#initial_point = np.array([0.2, 0.1, 0.3, 0.4])
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)
classifier.fit(training_features, training_labels);
predicted = classifier.predict(test_features)
def plot_predicted():
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label, pred in zip(test_features, test_labels, predicted):
marker = 's'
color = 'tab:green' if pred == -1 else 'tab:blue'
if label != pred: # mark wrongly classified
plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5,
facecolor='none', edgecolor='tab:red')
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10),
Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10),
Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_predicted()
qng_qnn_loss = []
def qng_qnn_callback(*args):
qng_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients!
quantum_instance=q_instance)
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point)
classifier.fit(training_features, training_labels);
def plot_losses():
plt.figure(figsize=(12, 6))
plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients')
plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients')
plt.xlabel('iterations')
plt.ylabel('loss')
plt.legend(loc='best')
plot_losses()
from qiskit.opflow import I
def sample_gradients(num_qubits, reps, local=False):
"""Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions.
We sample 100 times for random parameters and compute the gradient of the first RY rotation gate.
"""
index = num_qubits - 1
# you can also exchange this for a local operator and observe the same!
if local:
operator = Z ^ Z ^ (I ^ (num_qubits - 2))
else:
operator = Z ^ num_qubits
# real amplitudes ansatz
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
# construct Gradient we want to evaluate for different values
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = Gradient().convert(expectation, params=ansatz.parameters[index])
# evaluate for 100 different, random parameter values
num_points = 100
grads = []
for _ in range(num_points):
# points are uniformly chosen from [0, pi]
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
from qiskit.opflow import NaturalGradient
def sample_natural_gradients(num_qubits, reps):
index = num_qubits - 1
operator = Z ^ num_qubits
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``.
# Hint: Check the ``sample_gradients`` function, this one is almost the same.
grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index])
num_points = 100
grads = []
for _ in range(num_points):
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients')
plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = 6
operator = Z ^ Z ^ (I ^ (num_qubits - 4))
def minimize(circuit, optimizer):
initial_point = np.random.random(circuit.num_parameters)
exp = StateFn(operator, is_measurement=True) @ StateFn(circuit)
grad = Gradient().convert(exp)
# pauli basis
exp = PauliExpectation().convert(exp)
grad = PauliExpectation().convert(grad)
sampler = CircuitSampler(q_instance, caching="all")
def loss(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(exp, values_dict).eval())
def gradient(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(grad, values_dict).eval())
return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point)
circuit = RealAmplitudes(4, reps=1, entanglement='linear')
circuit.draw('mpl', style='iqx')
circuit.reps = 5
circuit.draw('mpl', style='iqx')
def layerwise_training(ansatz, max_num_layers, optimizer):
optimal_parameters = []
fopt = None
for reps in range(1, max_num_layers):
ansatz.reps = reps
# bind already optimized parameters
values_dict = dict(zip(ansatz.parameters, optimal_parameters))
partially_bound = ansatz.bind_parameters(values_dict)
xopt, fopt, _ = minimize(partially_bound, optimizer)
print('Circuit depth:', ansatz.depth(), 'best value:', fopt)
optimal_parameters += list(xopt)
return fopt, optimal_parameters
ansatz = RealAmplitudes(4, entanglement='linear')
optimizer = GradientDescent(maxiter=50)
np.random.seed(12)
fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlHadamardNeighborClassifier
===============================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard._QmlHadamardNeighborClassifier
Implementing the Hadamard distance & majority based classifier (http://stacks.iop.org/0295-5075/119/i=6/a=60002).
.. autosummary::
:nosignatures:
QmlHadamardNeighborClassifier
AsyncPredictJob
More details:
QmlHadamardNeighborClassifier
###############################
.. autoclass:: QmlHadamardNeighborClassifier
:members:
AsyncPredictJob
##################
.. autoclass:: AsyncPredictJob
:members:
"""
import itertools
import logging
from typing import List, Union, Optional, Iterable, Sized
import numpy as np
import qiskit
from qiskit.circuit import QuantumCircuit
from qiskit.providers import BackendV2, JobV1
from qiskit.qobj import QasmQobj
from qiskit.transpiler import CouplingMap
from sklearn.base import ClassifierMixin, TransformerMixin
from dc_qiskit_qml.QiskitOptions import QiskitOptions
from ...encoding_maps import EncodingMap
log = logging.getLogger(__name__)
class CompactHadamardClassifier(ClassifierMixin, TransformerMixin):
"""
The Hadamard distance & majority based classifier implementing sci-kit learn's mechanism of fit/predict
"""
def __init__(self, encoding_map, backend, shots=1024, coupling_map=None,
basis_gates=None, theta=None, options=None):
# type: (EncodingMap, BackendV2, int, CouplingMap, List[str], Optional[float], Optional[QiskitOptions]) -> None
"""
Create the classifier
:param encoding_map: a classical feature map to apply to every training and testing sample before building
the circuit
:param classifier_circuit_factory: the circuit building factory class
:param backend: the qiskit backend to do the compilation & computation on
:param shots: *deprecated* use options. the amount of shots for the experiment
:param coupling_map: *deprecated* use options. if given overrides the backend's coupling map, useful when using the simulator
:param basis_gates: *deprecated* use options. if given overrides the backend's basis gates, useful for the simulator
:param theta: an advanced feature that generalizes the "Hadamard" gate as a rotation with this angle
:param options: the options for transpilation & executions with qiskit.
"""
self.encoding_map = encoding_map # type: EncodingMap
self.basis_gates = basis_gates # type: List[str]
self.shots = shots # type: int
self.backend = backend # type: BackendV2
self.coupling_map = coupling_map # type: CouplingMap
self._X = np.asarray([]) # type: np.ndarray
self._y = np.asarray([]) # type: np.ndarray
self.last_predict_X = None
self.last_predict_label = None
self.last_predict_probability = [] # type: List[float]
self._last_predict_circuits = [] # type: List[QuantumCircuit]
self.last_predict_p_acc = [] # type: List[float]
self.theta = np.pi / 2 if theta is None else theta # type: float
if options is not None:
self.options = options # type: QiskitOptions
else:
self.options = QiskitOptions()
self.options.basis_gates = basis_gates
self.options.coupling_map = coupling_map
self.options.shots = shots
def transform(self, X, y='deprecated', copy=None):
return X
def fit(self, X, y):
# type: (QmlHadamardNeighborClassifier, Iterable) -> QmlHadamardNeighborClassifier
"""
Internal fit method just saves the train sample set
:param X: array_like, training sample
"""
self._X = np.asarray(X)
self._y = y
log.debug("Setting training data:")
for x, y in zip(self._X, self._y):
log.debug("%s: %s", x, y)
return self
def _create_circuits(self, unclassified_input):
# type: (Iterable) -> None
"""
Creates the circuits to be executed on the quantum computer
:param unclassified_input: array like, the input set
"""
self._last_predict_circuits = []
for index, x in enumerate(unclassified_input):
log.info("Creating state for input %d: %s.", index, x)
circuit_name = 'qml_hadamard_index_%d' % index
X_input = self.encoding_map.map(x)
X_train_0 = [self.encoding_map.map(s) for s, l in zip(self._X, self._y) if l == 0]
X_train_1 = [self.encoding_map.map(s) for s, l in zip(self._X, self._y) if l == 1]
full_data = list(itertools.zip_longest([X_train_0, X_train_1], fillvalue=None))
# all_batches = max(len(X_train_0), len(X_train_1))
#
# index_no =
#
# ancilla = QuantumRegister(ancilla_qubits_needed, "a")
# index = QuantumRegister(index_of_samples_qubits_needed, "i")
# data = QuantumRegister(sample_space_dimensions_qubits_needed, "f^S")
# clabel = ClassicalRegister(label_qubits_needed, "l^c")
qc = QuantumCircuit()
self._last_predict_circuits.append(qc)
def predict_qasm_only(self, X):
# type: (Union[Sized, Iterable]) -> QasmQobj
"""
Instead of predicting straight away returns the Qobj, the command object for executing
the experiment
:param X: array like, unclassified input set
:return: the compiled Qobj ready for execution!
"""
self.last_predict_X = X
self.last_predict_label = []
self._last_predict_circuits = []
self.last_predict_probability = []
self.last_predict_p_acc = []
log.info("Creating circuits (#%d inputs)..." % len(X))
self._create_circuits(X)
log.info("Compiling circuits...")
transpiled_qc = qiskit.transpile(
self._last_predict_circuits,
backend=self.backend,
coupling_map=self.options.coupling_map,
basis_gates=self.options.basis_gates,
backend_properties=self.options.backend_properties,
initial_layout=self.options.initial_layout,
seed_transpiler=self.options.seed_transpiler,
optimization_level=self.options.optimization_level
) # type: List[QuantumCircuit]
qobj = qiskit.assemble(transpiled_qc,
backend=self.backend,
shots=self.options.shots,
qobj_id=self.options.qobj_id,
qobj_header=self.options.qobj_header,
memory=self.options.memory,
max_credits=self.options.max_credits,
seed_simulator=self.options.seed_simulator,
default_qubit_los=self.options.default_qubit_los,
default_meas_los=self.options.default_meas_los,
schedule_los=self.options.schedule_los,
meas_level=self.options.meas_level,
meas_return=self.options.meas_return,
memory_slots=self.options.memory_slots,
memory_slot_size=self.options.memory_slot_size,
rep_time=self.options.rep_time,
parameter_binds=self.options.parameter_binds,
**self.options.run_config
)
return qobj
def predict(self, X, do_async=False):
# type: (QmlHadamardNeighborClassifier, Union[Sized, Iterable], bool) -> Union[Optional[List[int]], 'AsyncPredictJob']
"""
Predict the class labels of the unclassified input set!
:param X: array like, the unclassified input set
:param do_async: if True return a wrapped job, it is handy for reading out the prediction results from a real processor
:return: depending on the input either the prediction on class labels or a wrapper object for an async task
"""
qobj = self.predict_qasm_only(X)
log.info("Executing circuits...")
job = self.backend.run(qobj) # type: JobV1
|
https://github.com/biswaroopmukherjee/Quantum-Waddle
|
biswaroopmukherjee
|
import qiskit
from qiskit import IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider(group='open') #check open servers
import numpy as np
import time
import networkx as nx
import matplotlib.pyplot as plt
import random
from qiskit import (QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer)
from matplotlib import cm
%matplotlib inline
def counts_to_prob_2d(counts):
states = list(counts.keys())
state_counts = list(counts.values())
nshots = sum(state_counts)
n = int(len(states[0])/2)
def sep_xy(states):
# Separate x and y coordinates in state vector
states_x = [s[:n] for s in states]
states_y = [s[n:] for s in states]
states_x = np.array([int(s[::-1],2) for s in states_x])
states_y = np.array([int(s[::-1],2) for s in states_y])
return states_x, states_y
x,y = sep_xy(states)
# Create array of probability values
probabilities = np.zeros((2**n,2**n))
probabilities[x,y] = state_counts
probabilities /= nshots
return probabilities
def increment_gate(circuit, qpos, qcoin):
n = len(qpos)
for i in range(n):
circuit.mct(qcoin[:]+qpos[i+1:], qpos[i], None, mode='noancilla')
def decrement_gate(circuit, qpos, qcoin):
n = len(qpos)
for i in range(n):
if i+1 < n: circuit.x(qpos[i+1:])
circuit.mct(qcoin[:]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: circuit.x(qpos[i+1:])
def step(circuit, qpos, qcoin, cpos, simulatorType):
circuit.h(qcoin)
circuit.barrier()
# y operations
increment_gate(circuit, qpos[len(qpos)//2:], qcoin)
circuit.x(qcoin[0])
decrement_gate(circuit, qpos[len(qpos)//2:], qcoin)
# x operations
circuit.x(qcoin)
increment_gate(circuit, qpos[:len(qpos)//2], qcoin)
circuit.x(qcoin[0])
decrement_gate(circuit, qpos[:len(qpos)//2:], qcoin)
circuit.barrier()
if simulatorType == 'classical':
circuit.measure(qpos,cpos)
def initialize_2D(circuit, n, pos):
# convert position to binary
formatLabel = '{0:0'+str(n)+'b}'
x = formatLabel.format(pos[0])
y = formatLabel.format(pos[1])
for i in range(len(x)):
if x[i]=='1':
circuit.x((n-i)-1)
for j in range(len(y)):
if y[j]=='1':
circuit.x((2*n-j)-1)
return circuit
def run(steps,simulatorType):
# steps = number of quantum walks steps
# simulatorType = 'sim', 'quantum' or 'classical'
if simulatorType == 'sim':
simulator = Aer.get_backend('qasm_simulator')
elif simulatorType == 'quantum':
simulator = provider.get_backend('ibmq_16_melbourne')
elif simulatorType == 'classical':
simulator = Aer.get_backend('qasm_simulator')
else:
simulator = Aer.get_backend('qasm_simulator')
qpos = QuantumRegister(2*n,'qc')
qcoin = QuantumRegister(2,'qanc')
cpos = ClassicalRegister(2*n,'cr')
circuit = QuantumCircuit(qpos, qcoin, cpos)
circuit = initialize_2D(circuit, n, [round(n/2),round(n/2)])
for i in range(steps):
step(circuit, qpos, qcoin, cpos, simulatorType)
# # Map the quantum measurement to the classical bits
circuit.measure(qpos,cpos)
# # Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# monitor job
job_monitor(job)
# # Grab results from the job
result = job.result()
# # Returns counts
counts = result.get_counts(circuit)
return counts
n=2
steps = 3
for i in range(steps+1):
#run classical random walk
countsClassical = run(i,'classical')
propClassical = counts_to_prob_2d(countsClassical)
#run quantum simulation
countsSim = run(i,'sim')
propSim = counts_to_prob_2d(countsSim)
#run the real thing
countsQuantum = run(i,'quantum')
propQuantum = counts_to_prob_2d(countsQuantum)
#plotting
names = []
values = []
formatLabel = '{0:0'+str(n)+'b}'
for idx in range(2**n):
names.append('|' + formatLabel.format(idx) +'>')
values.append(idx)
f, axs = plt.subplots(1,3,figsize=(13,8))
margin=0.4
f.subplots_adjust(margin, margin, 1.-margin, 1.-margin)
axs[0].set_title('classical random walk')
plt.sca(axs[0])
plt.imshow(propClassical,cmap=plt.get_cmap('Reds'))
plt.xticks(rotation=45)
axs[0].set_xticks(values)
axs[0].set_xticklabels(names)
plt.xlim(-0.5,values[-1]+0.5)
axs[0].set_yticks(values)
axs[0].set_yticklabels(names)
plt.ylim(-0.5,values[-1]+0.5)
axs[1].set_title('simulated quantum walk')
plt.sca(axs[1])
plt.imshow(propSim,cmap=plt.get_cmap('Greens'))
plt.xticks(rotation=45)
axs[1].set_xticks(values)
axs[1].set_xticklabels(names)
plt.xlim(-0.5,values[-1]+0.5)
axs[1].set_yticks(values)
axs[1].set_yticklabels(names)
plt.ylim(-0.5,values[-1]+0.5)
axs[2].set_title('IBM quantum walk')
plt.sca(axs[2])
plt.imshow(propQuantum,cmap=plt.get_cmap('Blues'))
plt.xticks(rotation=45)
axs[2].set_xticks(values)
axs[2].set_xticklabels(names)
plt.xlim(-0.5,values[-1]+0.5)
axs[2].set_yticks(values)
axs[2].set_yticklabels(names)
plt.ylim(-0.5,values[-1]+0.5)
plt.tight_layout()
plt.show()
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
!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/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.
"""Tests for SuperOp quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError, QuantumCircuit
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.operators.channel import SuperOp
from .channel_test_case import ChannelTestCase
class TestSuperOp(ChannelTestCase):
"""Tests for SuperOp channel representation."""
def test_init(self):
"""Test initialization"""
chan = SuperOp(self.sopI)
assert_allclose(chan.data, self.sopI)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat = np.zeros((4, 16))
chan = SuperOp(mat)
assert_allclose(chan.data, mat)
self.assertEqual(chan.dim, (4, 2))
self.assertIsNone(chan.num_qubits)
chan = SuperOp(mat.T)
assert_allclose(chan.data, mat.T)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, SuperOp, mat, input_dims=[4], output_dims=[4])
def test_circuit_init(self):
"""Test initialization from a circuit."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
op = SuperOp(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = SuperOp(Operator(np.kron(y90, np.kron(self.UX, self.UH))))
self.assertEqual(target, op)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 0, 1)
op = SuperOp(circuit)
target = SuperOp(Operator(np.diag([1, 1, 1, np.exp(1j * lam)])))
self.assertEqual(target, op)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(0, 1)
op = SuperOp(circuit)
target = SuperOp(
Operator(np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])))
)
self.assertEqual(target, op)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, SuperOp, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4)
self.assertEqual(SuperOp(mat), SuperOp(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = SuperOp(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = SuperOp(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = SuperOp(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_evolve(self):
"""Test evolve method."""
input_rho = DensityMatrix([[0, 0], [0, 1]])
# Identity channel
chan = SuperOp(self.sopI)
target_rho = DensityMatrix([[0, 0], [0, 1]])
self.assertEqual(input_rho.evolve(chan), target_rho)
# Hadamard channel
mat = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
chan = SuperOp(np.kron(mat.conj(), mat))
target_rho = DensityMatrix(np.array([[1, -1], [-1, 1]]) / 2)
self.assertEqual(input_rho.evolve(chan), target_rho)
# Completely depolarizing channel
chan = SuperOp(self.depol_sop(1))
target_rho = DensityMatrix(np.eye(2) / 2)
self.assertEqual(input_rho.evolve(chan), target_rho)
def test_evolve_subsystem(self):
"""Test subsystem evolve method."""
# Single-qubit random superoperators
op_a = SuperOp(self.rand_matrix(4, 4))
op_b = SuperOp(self.rand_matrix(4, 4))
op_c = SuperOp(self.rand_matrix(4, 4))
id1 = SuperOp(np.eye(4))
id2 = SuperOp(np.eye(16))
rho = DensityMatrix(self.rand_rho(8))
# Test evolving single-qubit of 3-qubit system
op = op_a
# Evolve on qubit 0
full_op = id2.tensor(op_a)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[0])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubit 1
full_op = id1.tensor(op_a).tensor(id1)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[1])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubit 2
full_op = op_a.tensor(id2)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[2])
self.assertEqual(rho_test, rho_targ)
# Test 2-qubit evolution
op = op_b.tensor(op_a)
# Evolve on qubits [0, 2]
full_op = op_b.tensor(id1).tensor(op_a)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[0, 2])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubits [2, 0]
full_op = op_a.tensor(id1).tensor(op_b)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[2, 0])
self.assertEqual(rho_test, rho_targ)
# Test 3-qubit evolution
op = op_c.tensor(op_b).tensor(op_a)
# Evolve on qubits [0, 1, 2]
full_op = op
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[0, 1, 2])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubits [2, 1, 0]
full_op = op_a.tensor(op_b).tensor(op_c)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[2, 1, 0])
self.assertEqual(rho_test, rho_targ)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(SuperOp(self.depol_sop(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(SuperOp(1.25 * self.sopI - 0.25 * self.depol_sop(1)).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
mat = self.rand_matrix(4, 4)
chan = SuperOp(mat)
targ = SuperOp(np.conjugate(mat))
self.assertEqual(chan.conjugate(), targ)
def test_transpose(self):
"""Test transpose method."""
mat = self.rand_matrix(4, 4)
chan = SuperOp(mat)
targ = SuperOp(np.transpose(mat))
self.assertEqual(chan.transpose(), targ)
def test_adjoint(self):
"""Test adjoint method."""
mat = self.rand_matrix(4, 4)
chan = SuperOp(mat)
targ = SuperOp(np.transpose(np.conj(mat)))
self.assertEqual(chan.adjoint(), targ)
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, SuperOp(np.eye(16)))
self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# UnitaryChannel evolution
chan1 = SuperOp(self.sopX)
chan2 = SuperOp(self.sopY)
chan = chan1.compose(chan2)
targ = SuperOp(self.sopZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = SuperOp(self.depol_sop(0.5))
chan = chan1.compose(chan1)
targ = SuperOp(self.depol_sop(0.75))
self.assertEqual(chan, targ)
# Random superoperator
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(np.dot(mat2, mat1))
self.assertEqual(chan1.compose(chan2), targ)
self.assertEqual(chan1 & chan2, targ)
targ = SuperOp(np.dot(mat1, mat2))
self.assertEqual(chan2.compose(chan1), targ)
self.assertEqual(chan2 & chan1, targ)
# Compose different dimensions
chan1 = SuperOp(self.rand_matrix(16, 4))
chan2 = SuperOp(
self.rand_matrix(4, 16),
)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
chan = chan2.compose(chan1)
self.assertEqual(chan.dim, (4, 4))
def test_dot(self):
"""Test dot method."""
# UnitaryChannel evolution
chan1 = SuperOp(self.sopX)
chan2 = SuperOp(self.sopY)
targ = SuperOp(self.sopZ)
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# 50% depolarizing channel
chan1 = SuperOp(self.depol_sop(0.5))
targ = SuperOp(self.depol_sop(0.75))
self.assertEqual(chan1.dot(chan1), targ)
self.assertEqual(chan1 @ chan1, targ)
# Random superoperator
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(np.dot(mat2, mat1))
self.assertEqual(chan2.dot(chan1), targ)
targ = SuperOp(np.dot(mat1, mat2))
# Compose different dimensions
chan1 = SuperOp(self.rand_matrix(16, 4))
chan2 = SuperOp(self.rand_matrix(4, 16))
chan = chan1.dot(chan2)
self.assertEqual(chan.dim, (4, 4))
chan = chan1 @ chan2
self.assertEqual(chan.dim, (4, 4))
chan = chan2.dot(chan1)
self.assertEqual(chan.dim, (2, 2))
chan = chan2 @ chan1
self.assertEqual(chan.dim, (2, 2))
def test_compose_front(self):
"""Test front compose method."""
# DEPRECATED
# UnitaryChannel evolution
chan1 = SuperOp(self.sopX)
chan2 = SuperOp(self.sopY)
chan = chan1.compose(chan2, front=True)
targ = SuperOp(self.sopZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = SuperOp(self.depol_sop(0.5))
chan = chan1.compose(chan1, front=True)
targ = SuperOp(self.depol_sop(0.75))
self.assertEqual(chan, targ)
# Random superoperator
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(np.dot(mat2, mat1))
self.assertEqual(chan2.compose(chan1, front=True), targ)
targ = SuperOp(np.dot(mat1, mat2))
self.assertEqual(chan1.compose(chan2, front=True), targ)
# Compose different dimensions
chan1 = SuperOp(self.rand_matrix(16, 4))
chan2 = SuperOp(self.rand_matrix(4, 16))
chan = chan1.compose(chan2, front=True)
self.assertEqual(chan.dim, (4, 4))
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
def test_compose_subsystem(self):
"""Test subsystem compose method."""
# 3-qubit superoperator
mat = self.rand_matrix(64, 64)
mat_a = self.rand_matrix(4, 4)
mat_b = self.rand_matrix(4, 4)
mat_c = self.rand_matrix(4, 4)
iden = SuperOp(np.eye(4))
op = SuperOp(mat)
op1 = SuperOp(mat_a)
op2 = SuperOp(mat_b).tensor(SuperOp(mat_a))
op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
# op3 qargs=[0, 1, 2]
full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), SuperOp(targ))
self.assertEqual(op & op3([0, 1, 2]), SuperOp(targ))
# op3 qargs=[2, 1, 0]
full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), SuperOp(targ))
self.assertEqual(op & op3([2, 1, 0]), SuperOp(targ))
# op2 qargs=[0, 1]
full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op2, qargs=[0, 1]), SuperOp(targ))
self.assertEqual(op & op2([0, 1]), SuperOp(targ))
# op2 qargs=[2, 0]
full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op2, qargs=[2, 0]), SuperOp(targ))
self.assertEqual(op & op2([2, 0]), SuperOp(targ))
# op1 qargs=[0]
full_op = iden.tensor(iden).tensor(SuperOp(mat_a))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op1, qargs=[0]), SuperOp(targ))
self.assertEqual(op & op1([0]), SuperOp(targ))
# op1 qargs=[1]
full_op = iden.tensor(SuperOp(mat_a)).tensor(iden)
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op1, qargs=[1]), SuperOp(targ))
self.assertEqual(op & op1([1]), SuperOp(targ))
# op1 qargs=[2]
full_op = SuperOp(mat_a).tensor(iden).tensor(iden)
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op1, qargs=[2]), SuperOp(targ))
self.assertEqual(op & op1([2]), SuperOp(targ))
def test_dot_subsystem(self):
"""Test subsystem dot method."""
# 3-qubit operator
mat = self.rand_matrix(64, 64)
mat_a = self.rand_matrix(4, 4)
mat_b = self.rand_matrix(4, 4)
mat_c = self.rand_matrix(4, 4)
iden = SuperOp(np.eye(4))
op = SuperOp(mat)
op1 = SuperOp(mat_a)
op2 = SuperOp(mat_b).tensor(SuperOp(mat_a))
op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
# op3 qargs=[0, 1, 2]
full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), SuperOp(targ))
# op3 qargs=[2, 1, 0]
full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), SuperOp(targ))
# op2 qargs=[0, 1]
full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op2, qargs=[0, 1]), SuperOp(targ))
# op2 qargs=[2, 0]
full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op2, qargs=[2, 0]), SuperOp(targ))
# op1 qargs=[0]
full_op = iden.tensor(iden).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op1, qargs=[0]), SuperOp(targ))
# op1 qargs=[1]
full_op = iden.tensor(SuperOp(mat_a)).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op1, qargs=[1]), SuperOp(targ))
# op1 qargs=[2]
full_op = SuperOp(mat_a).tensor(iden).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op1, qargs=[2]), SuperOp(targ))
def test_compose_front_subsystem(self):
"""Test subsystem front compose method."""
# 3-qubit operator
mat = self.rand_matrix(64, 64)
mat_a = self.rand_matrix(4, 4)
mat_b = self.rand_matrix(4, 4)
mat_c = self.rand_matrix(4, 4)
iden = SuperOp(np.eye(4))
op = SuperOp(mat)
op1 = SuperOp(mat_a)
op2 = SuperOp(mat_b).tensor(SuperOp(mat_a))
op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
# op3 qargs=[0, 1, 2]
full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), SuperOp(targ))
# op3 qargs=[2, 1, 0]
full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), SuperOp(targ))
# op2 qargs=[0, 1]
full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), SuperOp(targ))
# op2 qargs=[2, 0]
full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), SuperOp(targ))
# op1 qargs=[0]
full_op = iden.tensor(iden).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op1, qargs=[0], front=True), SuperOp(targ))
# op1 qargs=[1]
full_op = iden.tensor(SuperOp(mat_a)).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op1, qargs=[1], front=True), SuperOp(targ))
# op1 qargs=[2]
full_op = SuperOp(mat_a).tensor(iden).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op1, qargs=[2], front=True), SuperOp(targ))
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = SuperOp(self.sopI)
chan2 = SuperOp(self.sopX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = SuperOp(self.sopI)
chan2 = SuperOp(self.sopX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 ^ chan2
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = SuperOp(self.depol_sop(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = SuperOp(self.depol_sop(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.sopI
mat2 = 0.5 * self.depol_sop(1)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = SuperOp(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = SuperOp(mat)
op0 = SuperOp(mat0)
op1 = SuperOp(mat1)
op01 = op1.tensor(op0)
eye = SuperOp(self.sopI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = SuperOp(mat)
op0 = SuperOp(mat0)
op1 = SuperOp(mat1)
op01 = op1.tensor(op0)
eye = SuperOp(self.sopI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = SuperOp(self.sopI)
chan2 = SuperOp(np.eye(16))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = SuperOp(self.sopI)
val = 0.5
targ = SuperOp(val * self.sopI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = SuperOp(self.sopI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = SuperOp(self.sopI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = SuperOp(self.sopI)
targ = SuperOp(-self.sopI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings, note
import matplotlib.pyplot as plt
import numpy as np
import math
from qiskit import QuantumCircuit, Aer, transpile, assemble, execute
from qiskit.visualization import plot_histogram
from qiskit.circuit.library import CCXGate, CXGate, CSwapGate, HGate, SwapGate, CPhaseGate
from numpy.random import randint
import pandas as pd
from fractions import Fraction
from math import gcd # greatest common divisor
"""Function to compute the elements of Z_n."""
def multiplicative_group(n):
"""Returns the multiplicative group modulo n.
Args:
n: Modulus of the multiplicative group.
"""
print("multiplicative group")
assert n > 1
group = [1]
for x in range(2, n):
if math.gcd(x, n) == 1:
group.append(x)
return group
def qft_dagger(n):
"""n-qubit QFTdagger the first n qubits in circ"""
qc = QuantumCircuit(n)
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-np.pi/float(2**(j-m)), m, j)
qc.h(j)
qc.name = "QFT†"
return qc
qft_dagger(8)
def general_modular_exp(a, N, power):
mult_group = multiplicative_group(N)
if a not in mult_group:
raise ValueError("'a' must be in " + str(mult_group))
print(mult_group)
general_modular_exp(7, 15, 2)
def VBE_Adder(qubit_size):
#outputs a + b
#inverse outputs b - a (but in two's complement)
#move to carry
qc = QuantumCircuit(3*qubit_size + 1)
for i in range(qubit_size-1):
qc.ccx(i, i+qubit_size, 2+i+(2*qubit_size))
#toffoli to second register
qc.ccx(qubit_size-1, (2*qubit_size)-1, 2*qubit_size)
#add a to b
for i in range(qubit_size):
qc.cx(i, i+qubit_size)
#second register carry and last b
for i in range(qubit_size-1):
qc.ccx(i+qubit_size, 1+i+(2*qubit_size), 2+i+(2*qubit_size))
qc.ccx((2*qubit_size)-1, 3*qubit_size, 2*qubit_size)
qc.cx(3*qubit_size, (2*qubit_size)-1)
#adder overflow
for i in range(qubit_size-1):
qc.ccx((2*qubit_size) - 2 - i, (3*qubit_size) - i - 1, (3*qubit_size) - i)
qc.cx((qubit_size) - 2 - i, (2*qubit_size) - 2 - i)
qc.ccx((qubit_size) - 2 - i, (2*qubit_size) - 2 - i, (3*qubit_size) - i)
qc.cx((qubit_size) - 2 - i, (2*qubit_size) - 2 - i)
qc.cx((3*qubit_size) - i - 1, (2*qubit_size) - 2 - i)
#print(qc.draw(output='text'))
qc.name = "VBE ADDER"
#qc.to_gate()
return qc
#print(VBE_Adder(4))
def Modular_adder(qubit_size, N):
binN = bin(N)[2:].zfill(qubit_size)[::-1]
#move to carry
qc = QuantumCircuit(4*qubit_size + 2)
qc.append(VBE_Adder(qubit_size), [i for i in range(3*qubit_size+1)])
for i in range(qubit_size):
qc.swap(i, i + 1 + 3*qubit_size)
qc.append(VBE_Adder(qubit_size).inverse(), [i for i in range(3*qubit_size+1)])
qc.x(2*qubit_size)
qc.cx(2*qubit_size, 4*qubit_size+1)
qc.x(2*qubit_size)
for i in range(qubit_size):
if binN[i] == "1":
qc.cx(4*qubit_size + 1, i)
qc.append(VBE_Adder(qubit_size), [i for i in range(3*qubit_size+1)])
for i in range(qubit_size):
if binN[i] == "1":
qc.cx(4*qubit_size + 1, i)
for i in range(qubit_size):
qc.swap(i, i + 1 + 3*qubit_size)
qc.append(VBE_Adder(qubit_size).inverse(), [i for i in range(3*qubit_size+1)])
qc.cx(2*qubit_size, 4*qubit_size+1)
qc.append(VBE_Adder(qubit_size), [i for i in range(3*qubit_size+1)])
qc.name = "MODULAR ADDER"
return qc
Modular_adder(4,11)
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:60% !important; }</style>"))
size = 4
N = 7
qc = QuantumCircuit(4*size + 2)
# a = 3,2,1,0
#qc.x(3)
qc.x(2)
qc.x(1)
qc.x(0)
# b = 8,7,6,5,4
#qc.x(7)
qc.x(6)
qc.x(5)
qc.x(4)
# carry = 12,11,10,9
# modulus N = 16,15,14,13
binN = bin(N)[2:].zfill(size)[::-1]
for i in range(size):
if binN[i] == "1":
qc.x(3*size + 1 + i)
# temporary carry = 17
print(qc)
qc.measure_all()
qc.append(Modular_adder(size,N), [i for i in range(4*size+2)])
qc.measure_all()
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()
second_set = readings[0][0:4*size+2]
first_set = readings[0][(4*size)+3:(8*size)+6]
print(readings)
print(first_set)
print(second_set)
print('a = ' + str(first_set[3*size + 2: 4*size + 2]))
print('b = ' + str(first_set[2*size + 1: 3*size + 2]))
print('b out = ' + str(second_set[2*size + 1: 3*size + 2]))
#print('carry = ' + str(second_set[0:size]))
def Modular_multiplier(qubit_size, N, a):
qc = QuantumCircuit(5*qubit_size + 3)
for i in range(qubit_size):
mod = bin(a*(2**i) % N)[2:].zfill(qubit_size)[::-1]
for j in range(qubit_size):
if mod[j] == "1":
qc.ccx(0, i+1, qubit_size + 1 + j)
#print([qubit_size + i + 1 for i in range(4*qubit_size+2)])
qc.append(Modular_adder(qubit_size, N), [qubit_size + i + 1 for i in range(4*qubit_size+2)])
#can just repeat the above method, but this looks symmetric
#the circuit diagram is more intuitive
for j in range(qubit_size):
if mod[::-1][j] == "1":
qc.ccx(0, i+1, 2*qubit_size - j)
#set x if control is false
qc.x(0)
for i in range(qubit_size):
qc.ccx(0,i+1,2*qubit_size + 1 + i)
qc.x(0)
qc.name = "MODULAR MULTIPLIER " + str(a) + "x mod " + str(N)
#print(qc.draw(output='text'))
return qc
Modular_multiplier(4, 15, 13)
size = 2
N = 2
a = 1
qc = QuantumCircuit(5*size + 3)
#control qubit
qc.x(0)
# x = 4,3,2,1
#qc.x(4)
#qc.x(3)
#qc.x(2)
#qc.x(1)
# N = 21,20,19,18
binN = bin(N)[2:].zfill(size)[::-1]
for i in range(size):
if binN[i] == "1":
qc.x(4*size + 2 + i)
# temporary carry = 17
#print(qc)
qc.measure_all()
qc.append(Modular_multiplier(size, N, a), [i for i in range(5*size+3)])
#print(qc)
qc.measure_all()
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()
second_set = readings[0][0:5*size+3]
first_set = readings[0][(5*size)+4:(10*size)+8]
print(readings)
print(first_set)
print(second_set)
print('x = ' + str(first_set[4*size + 2: 5*size + 2]))
print('b = ' + str(first_set[2*size + 1: 3*size + 2]))
print('b out = ' + str(second_set[2*size + 1: 3*size + 2]))
#print('carry = ' + str(second_set[0:size]))
def Modular_exponentiation(qubit_size, N, a):
qc = QuantumCircuit(6*qubit_size + 3)
#need to set x to 1
qc.x(qubit_size+1)
for i in range(qubit_size):
#for i in range(1):
qc.cx(i,qubit_size)
print([i + qubit_size for i in range(5*qubit_size+3)])
qc.append(Modular_multiplier(qubit_size, N, a**(2**i)%N), [i + qubit_size for i in range(5*qubit_size+3)])
for j in range(qubit_size):
qc.swap(qubit_size+1+j, 3*qubit_size+1+j)
#we dont use A for this multiplier because we need the modular multiplicative inverse
#print(a**(2**i)%N)
#print(pow(a**(2**i)%N, -1, N))
qc.append(Modular_multiplier(qubit_size, N, pow(a**(2**i)%N, -1, N)).inverse(), [i + qubit_size for i in range(5*qubit_size+3)])
qc.cx(i,qubit_size)
qc.name = "MODULAR EXPONENTIATION"
#print(qc.draw(output='text'))
return qc
Modular_exponentiation(3, 7, 3)
qubit_size = 2
N = 3
a = 1
qc = QuantumCircuit(6*qubit_size + 3)
# x = 3,2,1,0
#qc.x(3)
qc.x(2)
#qc.x(1)
#qc.x(0)
# N = 21,20,19,18
binN = bin(N)[2:].zfill(qubit_size)[::-1]
print(binN)
for i in range(qubit_size):
if binN[i] == "1":
qc.x(5*qubit_size + 2 + i)
#print(qc)
qc.measure_all()
qc.append(Modular_exponentiation(qubit_size, N, a), [i for i in range(6*qubit_size+3)])
qc.measure_all()
print(qc)
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()[0].split(' ')
second_set = readings[0]
first_set = readings[1]
print(first_set)
print(second_set)
first_set_exp = first_set[(5 * qubit_size) + 3 : (6 * qubit_size) + 3]
first_set_x = first_set[(4 * qubit_size) + 2 : (5 * qubit_size) + 2]
first_set_a = first_set[(3 * qubit_size) + 2 : (4 * qubit_size) + 2]
first_set_b = first_set[(2 * qubit_size) + 1 : (3 * qubit_size) + 2]
first_set_N = first_set[qubit_size + 1 : (2 * qubit_size) + 1]
second_set_exp = second_set[(5 * qubit_size) + 3 : (6 * qubit_size) + 3]
second_set_x = second_set[(4 * qubit_size) + 2 : (5 * qubit_size) + 2]
second_set_a = second_set[(3 * qubit_size) + 2 : (4 * qubit_size) + 2]
second_set_b = second_set[(2 * qubit_size) + 1 : (3 * qubit_size) + 2]
second_set_N = second_set[qubit_size + 1 : (2 * qubit_size) + 1]
print("A = " + str(a))
print("exps 1 -> 2 = " + str(first_set_exp) + " -> " + str(second_set_exp))
print("xs 1 -> 2 = " + str(first_set_x) + " -> " + str(second_set_x))
print("as 1 -> 2 = " + str(first_set_a) + " -> " + str(second_set_a))
print("bs 1 -> 2 = " + str(first_set_b) + " -> " + str(second_set_b))
print("Ns 1 -> 2 = " + str(first_set_N) + " -> " + str(second_set_N))
#print('carry = ' + str(second_set[0:size]))
def run_shors(qubit_size, N, a, run_amt):
qc = QuantumCircuit(6*qubit_size + 3, qubit_size)
# N = 21,20,19,18
binN = bin(N)[2:].zfill(qubit_size)[::-1]
for i in range(qubit_size):
qc.h(i)
for i in range(qubit_size):
if binN[i] == "1":
qc.x(5*qubit_size + 2 + i)
qc.append(Modular_exponentiation(qubit_size, N, a), [i for i in range(6*qubit_size+3)])
qc.append(qft_dagger(qubit_size), [i for i in range(qubit_size)])
qc.measure([i for i in range(qubit_size)],[i for i in range(qubit_size)])
print(qc)
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=run_amt, memory=True)
return(job.result().get_memory())
print(run_shors(8,14,9,20))
%timeit run_shors(10,26,7,20)
# for loop at the bootom from qiskit textbook for postpro
# https://qiskit.org/textbook/ch-algorithms/shor.html#:~:text=if%20phase%20!%3D%200,guess)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20factor_found%20%3D%20True
def shors_with_postpro(N, a, tries):
factors = []
if not a < N:
raise ValueError("a(%i) must be less than N(%i)"%(a,N))
common_denom = gcd(a,N)
if not common_denom == 1:
raise ValueError("a(%i) and N(%i) must be coprime but they have a gcd of (%i)"%(a, N, common_denom))
length_message = len(bin(N)[2:])*2
if length_message > 8:
print(f"The length of the number you are trying to factor is large ({length_message}), it may fail or take a long time")
res = run_shors(len(bin(N)[2:])*2, N, a, tries)
for result in res:
phase = (int(result,2)/(2**length_message))
frac = Fraction(phase).limit_denominator(N)
r = frac.denominator
if phase != 0:
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
for guess in guesses:
if guess not in [1,N] and (N % guess) == 0:
factors += [guess]
return factors
shors_with_postpro(30, 7, 20)
def twos_comp_to_int(binNum):
binNum = int(binNum,2) ^ ((2**len(binNum))-1)
binNum = bin(binNum + 1)
return -int(binNum,2)
@st.composite
def draw_pair_of_ints(draw):
size = draw(st.integers(min_value=1, max_value=6))
a = draw(st.integers(min_value=0, max_value=(2**size)-1))
b = draw(st.integers(min_value=0, max_value=(2**size)-1))
return(a, b, size)
@st.composite
def draw_shors_variables(draw):
size = draw(st.integers(min_value=2, max_value=5))
mod = draw(st.integers(min_value=3, max_value=(2**size)-1))
a = draw(st.integers(min_value=2, max_value=mod-1))
return(a, mod, size)
@st.composite
def draw_pair_of_ints_and_mod(draw):
size = draw(st.integers(min_value=2, max_value=3))
mod = draw(st.integers(min_value=2, max_value=(2**size)-1))
a = draw(st.integers(min_value=0, max_value=mod-1))
b = draw(st.integers(min_value=0, max_value=mod-1))
return(a, b, size, mod)
@given(draw_shors_variables())
@settings(deadline=None)
def test_shors_with_postpro(vals):
a = vals[0]
N = vals[1]
size = vals[2]
for i in range(size):
try:
pow(a**(2**i)%N, -1, N)
except ValueError:
assert(not(math.gcd(a,N) == 1))
if math.gcd(a,N) == 1:
factors = shors_with_postpro(N, a, 20)
for factor in factors:
print(f"N {N}, factor {factor}")
assert(N % factor == 0)
@given(draw_pair_of_ints_and_mod())
@settings(deadline=None)
def test_modular_exponentiation(vals):
a = vals[0]
x = vals[1]
size = vals[2]
N = vals[3]
for i in range(size):
try:
pow(a**(2**i)%N, -1, N)
except ValueError:
assert(not(math.gcd(a,N) == 1))
if math.gcd(a,N) == 1:
qc = QuantumCircuit(6*size + 3)
binX = bin(x)[2:].zfill(size)[::-1]
binN = bin(N)[2:].zfill(size)[::-1]
print("size " + str(size))
print("a " + str(a))
print("x " + str(x))
print("N " + str(N))
print("\n")
# x = 3,2,1,0
for i in range(size):
if binX[i] == "1":
qc.x(i)
for i in range(size):
if binN[i] == "1":
qc.x(5*size + 2 + i)
#print(qc)
qc.measure_all()
qc.append(Modular_exponentiation(size, N, a), [i for i in range(6*size+3)])
qc.measure_all()
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()[0].split(' ')
second_set = readings[0]
first_set = readings[1]
print(first_set)
print(second_set)
first_set_exp = first_set[(5 * size) + 3 : (6 * size) + 3]
first_set_x = first_set[(4 * size) + 2 : (5 * size) + 2]
first_set_a = first_set[(3 * size) + 2 : (4 * size) + 2]
first_set_b = first_set[(2 * size) + 1 : (3 * size) + 2]
first_set_N = first_set[size + 1 : (2 * size) + 1]
second_set_exp = second_set[(5 * size) + 3 : (6 * size) + 3]
second_set_x = second_set[(4 * size) + 2 : (5 * size) + 2]
second_set_a = second_set[(3 * size) + 2 : (4 * size) + 2]
second_set_b = second_set[(2 * size) + 1 : (3 * size) + 2]
second_set_N = second_set[size + 1 : (2 * size) + 1]
print("A = " + str(a))
print("exps 1 -> 2 = " + str(first_set_exp) + " -> " + str(second_set_exp))
print("xs 1 -> 2 = " + str(first_set_x) + " -> " + str(second_set_x))
print("as 1 -> 2 = " + str(first_set_a) + " -> " + str(second_set_a))
print("bs 1 -> 2 = " + str(first_set_b) + " -> " + str(second_set_b))
print("Ns 1 -> 2 = " + str(first_set_N) + " -> " + str(second_set_N))
print(a)
print(x)
print(N)
print('\n\n')
assert((a ** x) % N == int(second_set_x, 2))
@given(draw_pair_of_ints_and_mod(), st.booleans())
@settings(deadline=None)
def test_modular_multiplier_then_inverse_returns_original_values(vals, control):
a = vals[0]
x = vals[1]
size = vals[2]
N = vals[3]
qc = QuantumCircuit(5*size + 3)
binX = bin(x)[2:].zfill(size)[::-1]
binN = bin(N)[2:].zfill(size)[::-1]
print("size " + str(size))
print("a " + str(a))
print("x " + str(x))
print("N " + str(N))
print("control " + str(control))
print("\n")
#control qubit
if control == True:
qc.x(0)
# x = 3,2,1,0
for i in range(size):
if binX[i] == "1":
qc.x(i+1)
for i in range(size):
if binN[i] == "1":
qc.x(4*size + 2 + i)
print(qc)
qc.measure_all()
qc.append(Modular_multiplier(size, N, a), [i for i in range(5*size+3)])
qc.append(Modular_multiplier(size, N, a).inverse(), [i for i in range(5*size+3)])
qc.measure_all()
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()
second_set = readings[0][0:5*size+3]
first_set = readings[0][(5*size)+4:(10*size)+7]
print("readings " + str(readings))
print("first set " + str(first_set))
print("second set " + str(second_set))
assert(first_set == second_set)
@given(draw_pair_of_ints_and_mod(), st.booleans())
@settings(deadline=None)
def test_modular_multiplier(vals, control):
a = vals[0]
x = vals[1]
size = vals[2]
N = vals[3]
qc = QuantumCircuit(5*size + 3)
binX = bin(x)[2:].zfill(size)[::-1]
binN = bin(N)[2:].zfill(size)[::-1]
#control qubit
if control == True:
qc.x(0)
# x = 3,2,1,0
for i in range(size):
if binX[i] == "1":
qc.x(i+1)
for i in range(size):
if binN[i] == "1":
qc.x(4*size + 2 + i)
qc.measure_all()
qc.append(Modular_multiplier(size, N, a), [i for i in range(5*size+3)])
qc.measure_all()
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()
second_set = readings[0][0:5*size+3]
first_set = readings[0][(5*size)+3:(10*size)+7]
print("readings " + str(readings))
print("first set " + str(first_set))
print("x " + str(first_set[4*size + 3: 5*size + 3]))
x = int(first_set[4*size + 3: 5*size + 3], 2)
print("b " + str(first_set[2*size + 1: 3*size + 2]))
b = int(first_set[2*size + 1: 3*size + 2], 2)
print("bout " + str(second_set[2*size + 1: 3*size + 2]))
bout = int(second_set[2*size + 1: 3*size + 2], 2)
print("control " + str(control))
print("N " + str(N))
print('b = ' + str(b))
print('a = ' + str(a))
print('x = ' + str(x))
print('b out = ' + str(bout))
print('\n\n')
if (control == False):
assert(bout == x)
else:
assert((a * x) % N == bout)
#assert(carry == 0)
@given(draw_pair_of_ints_and_mod())
@settings(deadline=None)
def test_modular_adder(vals):
a = vals[0]
b = vals[1]
size = vals[2]
N = vals[3]
qc = QuantumCircuit(4*size + 2)
binA = bin(a)[2:].zfill(size)[::-1]
binB = bin(b)[2:].zfill(size)[::-1]
binN = bin(N)[2:].zfill(size)[::-1]
print("size " + str(size))
print("a " + str(a))
print("b " + str(b))
print("N " + str(N))
print("\n")
# a = 3,2,1,0
for i in range(size):
if binA[i] == "1":
qc.x(i)
# b = 8,7,6,5,4
for i in range(size):
if binB[i] == "1":
qc.x(i+size)
# carry = 12,11,10,9
# modulus N = 16,15,14,13
for i in range(size):
if binN[i] == "1":
qc.x(3*size + 1 + i)
# temporary carry = 17
#print(qc)
qc.measure_all()
qc.append(Modular_adder(size,N), [i for i in range(4*size+2)])
qc.measure_all()
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()
second_set = readings[0][0:4*size+2]
first_set = readings[0][(4*size)+3:(8*size)+6]
print(readings)
a = int(first_set[3*size + 2: 4*size + 2], 2)
b = int(first_set[2*size + 1: 3*size + 2], 2)
bout = int(second_set[2*size + 1: 3*size + 2], 2)
print('a = ' + str(a))
print('b = ' + str(b))
print('b out = ' + str(bout))
print('\n\n')
assert((a+b)%N == bout)
#assert(carry == 0)
@given(draw_pair_of_ints())
@settings(deadline=None)
def test_add_using_VBE_Adder(vals):
a = vals[0]
b = vals[1]
size = vals[2]
qc = QuantumCircuit(3*size + 1)
binA = bin(a)[2:].zfill(size)[::-1]
binB = bin(b)[2:].zfill(size)[::-1]
print("size " + str(size))
print("a " + str(a))
print(binA)
print("b " + str(b))
print(binB)
# a = 3,2,1,0
for i in range(size):
if binA[i] == "1":
qc.x(i)
# b = 8,7,6,5,4
for i in range(size):
if binB[i] == "1":
qc.x(i+size)
# carry = 12,11,10,9
qc.measure_all()
qc.append(VBE_Adder(size), [i for i in range(3*size+1)])
qc.measure_all()
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()
second_set = readings[0][0:3*size+1]
first_set = readings[0][(3*size)+2:(6*size)+4]
print(readings)
a = int(first_set[2*size + 1: 3*size + 1],2)
b = int(first_set[size: 2*size + 1],2)
bout = int(second_set[size: 2*size + 1],2)
carry = int(second_set[0: size],2)
print('a = ' + str(a))
print('b = ' + str(b))
print('b out = ' + str(bout))
print('\n\n')
assert(a+b == bout)
assert(carry == 0)
@given(draw_pair_of_ints())
@settings(deadline=None)
def test_subtract_using_VBE_Adder_inverse(vals):
a = vals[0]
b = vals[1]
size = vals[2]
qc = QuantumCircuit(3*size + 1)
binA = bin(a)[2:].zfill(size)[::-1]
binB = bin(b)[2:].zfill(size)[::-1]
print("size " + str(size))
print("a " + str(a))
print(binA)
print("b " + str(b))
print(binB)
# a = 3,2,1,0
for i in range(size):
if binA[i] == "1":
qc.x(i)
# b = 8,7,6,5,4
for i in range(size):
if binB[i] == "1":
qc.x(i+size)
# carry = 12,11,10,9
qc.measure_all()
qc.append(VBE_Adder(size).inverse(), [i for i in range(3*size+1)])
qc.measure_all()
backend = Aer.get_backend('aer_simulator')
job = execute(qc, backend, shots=1, memory=True)
readings = job.result().get_memory()
second_set = readings[0][0:3*size+1]
first_set = readings[0][(3*size)+2:(6*size)+4]
print(readings)
a = int(first_set[2*size + 1: 3*size + 1],2)
b = int(first_set[size: 2*size + 1],2)
if (b < a):
bout = twos_comp_to_int(second_set[size: 2*size + 1])
else:
bout = int(second_set[size: 2*size + 1],2)
carry = int(second_set[0: size],2)
print('a = ' + str(a))
print('b = ' + str(b))
print('b out = ' + str(bout))
print('\n\n')
assert(b-a == bout)
assert(carry == 0)
if __name__ == '__main__':
#test_shors_with_postpro()
#test_modular_exponentiation()
#test_modular_multiplier_then_inverse_returns_original_values()
test_modular_multiplier()
#test_modular_adder()
#test_add_using_VBE_Adder()
#test_subtract_using_VBE_Adder_inverse()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs)
print("created zne_qcs (length:", len(zne_qcs), ")")
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
# QREM
shots = 1 << 13
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
jobs.append(job)
dt_now = datetime.datetime.now()
import pickle
with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high))))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 3
strike_price_2 = 4
# set the barrier threshold
barrier = 2.5
# map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price_1 = (
(strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_strike_price_2 = (
(strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1)
# condition and condition result
conditions = []
barrier_thresholds = [2] * dimension
n_aux_conditions = 0
for i in range(dimension):
# target dimension of random distribution and corresponding condition (which is required to be True)
comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False)
n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas)
conditions += [comparator]
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1]
f_min = 0
f_max = mapped_strike_price_2 - mapped_strike_price_1
objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar_cond = AncillaRegister(len(conditions) + 1, "conditions")
ar = AncillaRegister(
max(n_aux, n_aux_conditions, objective.num_ancillas), "work"
) # additional qubits
objective_index = u.num_qubits
# define the circuit
asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar)
# load the probability distribution
asian_barrier_spread.append(u, qr_state)
# apply the conditions
for i, cond in enumerate(conditions):
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas])
# aggregate the conditions on a single qubit
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
# apply the aggregation function controlled on the condition
asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux])
# apply the payoff function
asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas])
# uncompute the aggregation
asian_barrier_spread.append(
agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]
)
# uncompute the conditions
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
for j, cond in enumerate(reversed(conditions)):
i = len(conditions) - j - 1
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(
cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]
)
print(asian_barrier_spread.draw())
print("objective qubit index", objective_index)
# plot exact payoff function
plt.figure(figsize=(7, 5))
x = np.linspace(sum(low), sum(high))
y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function (for $S_1 = S_2$)", size=15)
plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# plot contour of payoff function with respect to both time steps, including barrier
plt.figure(figsize=(7, 5))
z = np.zeros((17, 17))
x = np.linspace(low[0], high[0], 17)
y = np.linspace(low[1], high[1], 17)
for i, x_ in enumerate(x):
for j, y_ in enumerate(y):
z[i, j] = np.minimum(
np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1
)
if x_ > barrier or y_ > barrier:
z[i, j] = 0
plt.title("Payoff Function", size=15)
plt.contourf(x, y, z)
plt.colorbar()
plt.xlabel("Spot Price $S_1$", size=15)
plt.ylabel("Spot Price $S_2$", size=15)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1)
leq_barrier = [np.max(v) <= barrier for v in u.values]
exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier])
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(asian_barrier_spread_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=asian_barrier_spread,
objective_qubits=[objective_index],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}))
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value:\t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
# %% [markdown]
# # 第4章原始程式碼
# %%
#Program 4.1 Apply CX-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.cx(0,1)
qc.draw('mpl')
# %%
#Program 4.2 Show unitary matrix of CX-gate (MSB as target bit)
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
qc = QuantumCircuit(2)
qc.cx(0,1)
display(qc.draw('mpl'))
sim = Aer.get_backend('aer_simulator')
qc.save_unitary()
unitary = sim.run(qc).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CNOT (MSB as target bit) = }"))
# %%
#Program 4.3 Show unitary matrix of CX-gate (LSB as target bit)
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
sim = Aer.get_backend('aer_simulator')
qc = QuantumCircuit(2)
qc.cx(1,0)
display(qc.draw('mpl'))
qc.save_unitary()
unitary = sim.run(qc).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CNOT (LSB as target bit) = }"))
# %%
#Program 4.4a Appliy CX-gate to qubit
from qiskit import QuantumCircuit,execute
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(8,8)
sv = Statevector.from_label('11011000')
qc.initialize(sv,range(8))
qc.cx(0,1)
qc.cx(2,3)
qc.cx(4,5)
qc.cx(6,7)
qc.measure(range(8),range(8))
qc.draw('mpl')
# %%
#Program 4.4b Measure state of qubit w/ CX-gate
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
# %%
#Program 4.5 Build Bell state via H- and CX-gate
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1,0)
print("Below is the Bell state (top: q0 for target; bottom: q1 for control):")
display(qc.draw('mpl'))
print("Below is the Bell state (top: q1 for control; bottom: q0 for traget):")
display(qc.draw('mpl',reverse_bits=True))
# %%
#Program 4.6a Build Bell state via H- and CX-gate
from qiskit import QuantumCircuit
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure(range(2),range(2))
qc.draw('mpl')
# %%
#Program 4.6b Measure state of qubit in Bell state
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
# %%
#Program 4.7a Iinitialize qubit and build Bell state via H- and CX-gate
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(2,2)
sv = Statevector.from_label('10')
qc.initialize(sv,range(2))
qc.h(0)
qc.cx(0,1)
qc.measure(range(2),range(2))
qc.draw('mpl')
# %%
#Program 4.7b Measure state of qubit in Bell state
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
# %%
#Program 4.8 Show quantum circuit for quantum teleportation
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qs = QuantumRegister(1,'qs')
qa = QuantumRegister(1,'qa')
qb = QuantumRegister(1,'qb')
cr = ClassicalRegister(2,'c')
qc = QuantumCircuit(qs,qa,qb,cr)
qc.h(qa)
qc.cx(qa,qb)
qc.barrier()
qc.cx(qs,qa)
qc.h(qs)
qc.measure(qs,0)
qc.measure(qa,1)
qc.barrier()
qc.x(qb)
qc.z(qb)
qc.draw('mpl')
# %%
#Program 4.9 Apply CX-, CY-, CZ-, CH-, and SWAP-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
qc.cx(0,1)
qc.cy(2,3)
qc.cz(4,5)
qc.ch(6,7)
qc.swap(8,9)
qc.cx(10,11)
qc.cx(11,10)
qc.cx(10,11)
qc.draw('mpl')
# %%
#Program 4.10 Apply CCX-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.ccx(0,1,2)
qc.draw('mpl')
# %%
#Program 4.11 Show unitary matrix of CCX-gate
from qiskit import QuantumCircuit, Aer
from qiskit.visualization import array_to_latex
sim = Aer.get_backend('aer_simulator')
qc1 = QuantumCircuit(3)
qc1.ccx(0,1,2)
print("="*70,"\nBelow is quantum circuit of CCNOT gate (MSB as target bit):")
display(qc1.draw('mpl'))
qc1.save_unitary()
unitary = sim.run(qc1).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CCNOT (MSB as target bit) = }\n"))
qc2 = QuantumCircuit(3)
qc2.ccx(2,1,0)
print("="*70,"\nBelow is quantum circuit of CCNOT gate (LSB as target bit):")
display(qc2.draw('mpl'))
qc2.save_unitary()
unitary = sim.run(qc2).result().get_unitary()
display(array_to_latex(unitary, prefix="\\text{CCNOT (LSB as target bit) = }\n"))
# %%
#Program 4.12 Apply CCCCX-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(7)
qc.ccx(0,1,4)
qc.ccx(2,3,5)
qc.ccx(4,5,6)
qc.draw('mpl')
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# 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.
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.aqua import Pluggable, get_pluggable_class, PluggableType
from .multivariate_distribution import MultivariateDistribution
class MultivariateVariationalDistribution(MultivariateDistribution):
"""
The Multivariate Variational Distribution.
"""
CONFIGURATION = {
'name': 'MultivariateVariationalDistribution',
'description': 'Multivariate Variational Distribution',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'MultivariateVariationalDistribution_schema',
'type': 'object',
'properties': {
'num_qubits': {
'type': 'array',
"items": {
"type": "number"
}
},
'params': {
'type': 'array',
"items": {
"type": "number"
}
},
'low': {
'type': ['array', 'null'],
"items": {
"type": "number"
},
'default': None
},
'high': {
'type': ['array', 'null'],
"items": {
"type": "number"
},
'default': None
},
},
'additionalProperties': False
},
'depends': [
{
'pluggable_type': 'variational_form',
'default': {
'name': 'RY'
}
}
],
}
def __init__(self, num_qubits, var_form, params, low=None, high=None):
if low is None:
low = np.zeros(len(num_qubits))
if high is None:
high = np.ones(len(num_qubits))
self._num_qubits = num_qubits
self._var_form = var_form
self.params = params
probabilities = np.zeros(2 ** sum(num_qubits))
super().__init__(num_qubits, probabilities, low, high)
self._var_form = var_form
self.params = params
@classmethod
def init_params(cls, params):
"""
Initialize via parameters dictionary.
Args:
params: parameters dictionary
Returns:
An object instance of this class
"""
multi_var_params_params = params.get(Pluggable.SECTION_KEY_UNIVARIATE_DISTRIBUTION)
num_qubits = multi_var_params_params.get('num_qubits')
params = multi_var_params_params.get('params')
low = multi_var_params_params.get('low')
high = multi_var_params_params.get('high')
var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM)
var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM,
var_form_params['name']).init_params(params)
return cls(num_qubits, var_form, params, low, high)
def build(self, qc, q, q_ancillas=None):
circuit_var_form = self._var_form.construct_circuit(self.params, q)
qc.extend(circuit_var_form)
def set_probabilities(self, quantum_instance):
"""
Set Probabilities
Args:
quantum_instance: QuantumInstance
Returns:
"""
q_ = QuantumRegister(self._num_qubits, name='q')
qc_ = QuantumCircuit(q_)
circuit_var_form = self._var_form.construct_circuit(self.params, q_)
qc_ += circuit_var_form
if quantum_instance.is_statevector:
pass
else:
c_ = ClassicalRegister(self._num_qubits, name='c')
qc_.add_register(c_)
qc_.measure(q_, c_)
result = quantum_instance.execute(qc_)
if quantum_instance.is_statevector:
result = result.get_statevector(qc_)
values = np.multiply(result, np.conj(result))
values = list(values.real)
else:
result = result.get_counts(qc_)
keys = list(result)
values = list(result.values())
values = [float(v) / np.sum(values) for v in values]
values = [x for _, x in sorted(zip(keys, values))]
probabilities = values
self._probabilities = np.array(probabilities)
return
|
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.
# pylint: disable=missing-docstring
import os
import configparser as cp
from uuid import uuid4
from unittest import mock
from qiskit import exceptions
from qiskit.test import QiskitTestCase
from qiskit import user_config
class TestUserConfig(QiskitTestCase):
def setUp(self):
super().setUp()
self.file_path = "test_%s.conf" % uuid4()
def test_empty_file_read(self):
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({}, config.settings)
def test_invalid_optimization_level(self):
test_config = """
[default]
transpile_optimization_level = 76
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file)
def test_invalid_circuit_drawer(self):
test_config = """
[default]
circuit_drawer = MSPaint
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file)
def test_circuit_drawer_valid(self):
test_config = """
[default]
circuit_drawer = latex
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"circuit_drawer": "latex"}, config.settings)
def test_invalid_circuit_reverse_bits(self):
test_config = """
[default]
circuit_reverse_bits = Neither
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file)
def test_circuit_reverse_bits_valid(self):
test_config = """
[default]
circuit_reverse_bits = false
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"circuit_reverse_bits": False}, config.settings)
def test_optimization_level_valid(self):
test_config = """
[default]
transpile_optimization_level = 1
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"transpile_optimization_level": 1}, config.settings)
def test_invalid_num_processes(self):
test_config = """
[default]
num_processes = -256
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
self.assertRaises(exceptions.QiskitUserConfigError, config.read_config_file)
def test_valid_num_processes(self):
test_config = """
[default]
num_processes = 31
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"num_processes": 31}, config.settings)
def test_valid_parallel(self):
test_config = """
[default]
parallel = False
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual({"parallel_enabled": False}, config.settings)
def test_all_options_valid(self):
test_config = """
[default]
circuit_drawer = latex
circuit_mpl_style = default
circuit_mpl_style_path = ~:~/.qiskit
circuit_reverse_bits = false
transpile_optimization_level = 3
suppress_packaging_warnings = true
parallel = false
num_processes = 15
"""
self.addCleanup(os.remove, self.file_path)
with open(self.file_path, "w") as file:
file.write(test_config)
file.flush()
config = user_config.UserConfig(self.file_path)
config.read_config_file()
self.assertEqual(
{
"circuit_drawer": "latex",
"circuit_mpl_style": "default",
"circuit_mpl_style_path": ["~", "~/.qiskit"],
"circuit_reverse_bits": False,
"transpile_optimization_level": 3,
"num_processes": 15,
"parallel_enabled": False,
},
config.settings,
)
def test_set_config_all_options_valid(self):
self.addCleanup(os.remove, self.file_path)
user_config.set_config("circuit_drawer", "latex", file_path=self.file_path)
user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path)
user_config.set_config("circuit_mpl_style_path", "~:~/.qiskit", file_path=self.file_path)
user_config.set_config("circuit_reverse_bits", "false", file_path=self.file_path)
user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path)
user_config.set_config("parallel", "false", file_path=self.file_path)
user_config.set_config("num_processes", "15", file_path=self.file_path)
config_settings = None
with mock.patch.dict(os.environ, {"QISKIT_SETTINGS": self.file_path}, clear=True):
config_settings = user_config.get_config()
self.assertEqual(
{
"circuit_drawer": "latex",
"circuit_mpl_style": "default",
"circuit_mpl_style_path": ["~", "~/.qiskit"],
"circuit_reverse_bits": False,
"transpile_optimization_level": 3,
"num_processes": 15,
"parallel_enabled": False,
},
config_settings,
)
def test_set_config_multiple_sections(self):
self.addCleanup(os.remove, self.file_path)
user_config.set_config("circuit_drawer", "latex", file_path=self.file_path)
user_config.set_config("circuit_mpl_style", "default", file_path=self.file_path)
user_config.set_config("transpile_optimization_level", "3", file_path=self.file_path)
user_config.set_config("circuit_drawer", "latex", section="test", file_path=self.file_path)
user_config.set_config("parallel", "false", section="test", file_path=self.file_path)
user_config.set_config("num_processes", "15", section="test", file_path=self.file_path)
config = cp.ConfigParser()
config.read(self.file_path)
self.assertEqual(config.sections(), ["default", "test"])
self.assertEqual(
{
"circuit_drawer": "latex",
"circuit_mpl_style": "default",
"transpile_optimization_level": "3",
},
dict(config.items("default")),
)
|
https://github.com/danieljaffe/quantum-algorithms-qiskit
|
danieljaffe
|
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>)
out of four possible values."""
#import numpy and plot library
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
# define variables, 1) initialize qubits to zero
n = 2
grover_circuit = QuantumCircuit(n)
#define initialization function
def initialize_s(qc, qubits):
'''Apply a H-gate to 'qubits' in qc'''
for q in qubits:
qc.h(q)
return qc
### begin grovers circuit ###
#2) Put qubits in equal state of superposition
grover_circuit = initialize_s(grover_circuit, [0,1])
# 3) Apply oracle reflection to marked instance x_0 = 3, (|11>)
grover_circuit.cz(0,1)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
# 4) apply additional reflection (diffusion operator)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
# 5) measure the qubits
grover_circuit.measure_all()
# Load IBM Q account and get the least busy backend device
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)
from qiskit.tools.monitor import job_monitor
job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
#highest amplitude should correspond with marked value x_0 (|11>)
|
https://github.com/yaelbh/qiskit-projectq-provider
|
yaelbh
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name,missing-docstring,broad-except,no-member
from test._random_circuit_generator import RandomCircuitGenerator
from test.common import QiskitProjectQTestCase
import random
import unittest
import numpy
from scipy.stats import chi2_contingency
from qiskit import (QuantumCircuit, QuantumRegister,
ClassicalRegister, execute)
from qiskit import BasicAer
from qiskit_addon_projectq import ProjectQProvider
class TestQasmSimulatorProjectQ(QiskitProjectQTestCase):
"""
Test projectq simulator.
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
# Set up random circuits
n_circuits = 5
min_depth = 1
max_depth = 10
min_qubits = 1
max_qubits = 4
random_circuits = RandomCircuitGenerator(min_qubits=min_qubits,
max_qubits=max_qubits,
min_depth=min_depth,
max_depth=max_depth,
seed=None)
for _ in range(n_circuits):
basis = list(random.sample(random_circuits.op_signature.keys(),
random.randint(2, 7)))
if 'reset' in basis:
basis.remove('reset')
if 'u0' in basis:
basis.remove('u0')
random_circuits.add_circuits(1, basis=basis)
cls.rqg = random_circuits
def setUp(self):
ProjectQ = ProjectQProvider()
self.projectq_sim = ProjectQ.get_backend('projectq_qasm_simulator')
self.aer_sim = BasicAer.get_backend('qasm_simulator')
def test_gate_x(self):
shots = 100
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr, name='test_gate_x')
qc.x(qr[0])
qc.measure(qr, cr)
result_pq = execute(qc, backend=self.projectq_sim,
shots=shots).result(timeout=30)
self.assertEqual(result_pq.get_counts(qc), {'1': shots})
def test_entangle(self):
shots = 100
N = 5
qr = QuantumRegister(N)
cr = ClassicalRegister(N)
qc = QuantumCircuit(qr, cr, name='test_entangle')
qc.h(qr[0])
for i in range(1, N):
qc.cx(qr[0], qr[i])
qc.measure(qr, cr)
result = execute(qc, backend=self.projectq_sim, shots=shots).result(timeout=30)
counts = result.get_counts(qc)
self.log.info(counts)
for key, _ in counts.items():
with self.subTest(key=key):
self.assertTrue(key in ['0' * N, '1' * N])
def test_random_circuits(self):
for circuit in self.rqg.get_circuits():
self.log.info(circuit.qasm())
shots = 100
result_pq = execute(circuit, backend=self.projectq_sim,
shots=shots).result(timeout=30)
result_qk = execute(circuit, backend=self.aer_sim,
shots=shots).result(timeout=30)
counts_pq = result_pq.get_counts(circuit)
counts_qk = result_qk.get_counts(circuit)
self.log.info('qasm_simulator_projectq: %s', str(counts_pq))
self.log.info('qasm_simulator: %s', str(counts_qk))
states = counts_qk.keys() | counts_pq.keys()
# contingency table
ctable = numpy.array([[counts_pq.get(key, 0) for key in states],
[counts_qk.get(key, 0) for key in states]])
result = chi2_contingency(ctable)
self.log.info('chi2_contingency: %s', str(result))
with self.subTest(circuit=circuit):
self.assertGreater(result[1], 0.01)
def test_all_bits_measured(self):
shots = 2
qr = QuantumRegister(2)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr, name='all_bits_measured')
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.measure(qr[0], cr[0])
qc.h(qr[0])
execute(qc, backend=self.projectq_sim,
shots=shots).result(timeout=30)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
https://github.com/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.
"""Tests for Statevector quantum state class."""
import unittest
import logging
from itertools import permutations
from ddt import ddt, data
import numpy as np
from numpy.testing import assert_allclose
from qiskit.test import QiskitTestCase
from qiskit import QiskitError
from qiskit import QuantumRegister, QuantumCircuit
from qiskit import transpile
from qiskit.circuit.library import HGate, QFT, GlobalPhaseGate
from qiskit.providers.basicaer import QasmSimulatorPy
from qiskit.utils import optionals
from qiskit.quantum_info.random import random_unitary, random_statevector, random_pauli
from qiskit.quantum_info.states import Statevector
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.symplectic import Pauli, SparsePauliOp
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.visualization.state_visualization import numbers_to_latex_terms, state_to_latex
logger = logging.getLogger(__name__)
@ddt
class TestStatevector(QiskitTestCase):
"""Tests for Statevector class."""
@classmethod
def rand_vec(cls, n, normalize=False):
"""Return complex vector or statevector"""
seed = np.random.randint(0, np.iinfo(np.int32).max)
logger.debug("rand_vec default_rng seeded with seed=%s", seed)
rng = np.random.default_rng(seed)
vec = rng.random(n) + 1j * rng.random(n)
if normalize:
vec /= np.sqrt(np.dot(vec, np.conj(vec)))
return vec
def test_init_array_qubit(self):
"""Test subsystem initialization from N-qubit array."""
# Test automatic inference of qubit subsystems
vec = self.rand_vec(8)
for dims in [None, 8]:
state = Statevector(vec, dims=dims)
assert_allclose(state.data, vec)
self.assertEqual(state.dim, 8)
self.assertEqual(state.dims(), (2, 2, 2))
self.assertEqual(state.num_qubits, 3)
def test_init_array(self):
"""Test initialization from array."""
vec = self.rand_vec(3)
state = Statevector(vec)
assert_allclose(state.data, vec)
self.assertEqual(state.dim, 3)
self.assertEqual(state.dims(), (3,))
self.assertIsNone(state.num_qubits)
vec = self.rand_vec(2 * 3 * 4)
state = Statevector(vec, dims=[2, 3, 4])
assert_allclose(state.data, vec)
self.assertEqual(state.dim, 2 * 3 * 4)
self.assertEqual(state.dims(), (2, 3, 4))
self.assertIsNone(state.num_qubits)
def test_init_circuit(self):
"""Test initialization from circuit."""
circuit = QuantumCircuit(3)
circuit.x(0)
state = Statevector(circuit)
self.assertEqual(state.dim, 8)
self.assertEqual(state.dims(), (2, 2, 2))
self.assertTrue(all(state.data == np.array([0, 1, 0, 0, 0, 0, 0, 0], dtype=complex)))
self.assertEqual(state.num_qubits, 3)
def test_init_array_except(self):
"""Test initialization exception from array."""
vec = self.rand_vec(4)
self.assertRaises(QiskitError, Statevector, vec, dims=[4, 2])
self.assertRaises(QiskitError, Statevector, vec, dims=[2, 4])
self.assertRaises(QiskitError, Statevector, vec, dims=5)
def test_init_statevector(self):
"""Test initialization from Statevector."""
vec1 = Statevector(self.rand_vec(4))
vec2 = Statevector(vec1)
self.assertEqual(vec1, vec2)
def test_from_circuit(self):
"""Test initialization from a circuit."""
# random unitaries
u0 = random_unitary(2).data
u1 = random_unitary(2).data
# add to circuit
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.unitary(u0, [qr[0]])
circ.unitary(u1, [qr[1]])
target = Statevector(np.kron(u1, u0).dot([1, 0, 0, 0]))
vec = Statevector.from_instruction(circ)
self.assertEqual(vec, target)
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
target = Statevector.from_label("000").evolve(Operator(circuit))
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.h(1)
circuit.cp(lam, 0, 1)
target = Statevector.from_label("00").evolve(Operator(circuit))
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circ.x(0)
circuit.ch(0, 1)
target = Statevector.from_label("00").evolve(Operator(circuit))
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test custom controlled gate
qc = QuantumCircuit(2)
qc.x(0)
qc.h(1)
gate = qc.to_gate()
gate_ctrl = gate.control()
circuit = QuantumCircuit(3)
circuit.x(0)
circuit.append(gate_ctrl, range(3))
target = Statevector.from_label("000").evolve(Operator(circuit))
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test initialize instruction
target = Statevector([1, 0, 0, 1j]) / np.sqrt(2)
circuit = QuantumCircuit(2)
circuit.initialize(target.data, [0, 1])
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
target = Statevector([1, 0, 1, 0]) / np.sqrt(2)
circuit = QuantumCircuit(2)
circuit.initialize("+", [1])
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
target = Statevector([1, 0, 0, 0])
circuit = QuantumCircuit(2)
circuit.initialize(0, [0, 1]) # initialize from int
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test reset instruction
target = Statevector([1, 0])
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.reset(0)
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
# Test 0q instruction
target = Statevector([1j, 0])
circuit = QuantumCircuit(1)
circuit.append(GlobalPhaseGate(np.pi / 2), [], [])
psi = Statevector.from_instruction(circuit)
self.assertEqual(psi, target)
def test_from_instruction(self):
"""Test initialization from an instruction."""
target = np.dot(HGate().to_matrix(), [1, 0])
vec = Statevector.from_instruction(HGate()).data
global_phase_equivalent = matrix_equal(vec, target, ignore_phase=True)
self.assertTrue(global_phase_equivalent)
def test_from_label(self):
"""Test initialization from a label"""
x_p = Statevector(np.array([1, 1]) / np.sqrt(2))
x_m = Statevector(np.array([1, -1]) / np.sqrt(2))
y_p = Statevector(np.array([1, 1j]) / np.sqrt(2))
y_m = Statevector(np.array([1, -1j]) / np.sqrt(2))
z_p = Statevector(np.array([1, 0]))
z_m = Statevector(np.array([0, 1]))
label = "01"
target = z_p.tensor(z_m)
self.assertEqual(target, Statevector.from_label(label))
label = "+-"
target = x_p.tensor(x_m)
self.assertEqual(target, Statevector.from_label(label))
label = "rl"
target = y_p.tensor(y_m)
self.assertEqual(target, Statevector.from_label(label))
def test_equal(self):
"""Test __eq__ method"""
for _ in range(10):
vec = self.rand_vec(4)
self.assertEqual(Statevector(vec), Statevector(vec.tolist()))
def test_getitem(self):
"""Test __getitem__ method"""
for _ in range(10):
vec = self.rand_vec(4)
state = Statevector(vec)
for i in range(4):
self.assertEqual(state[i], vec[i])
self.assertEqual(state[format(i, "b")], vec[i])
def test_getitem_except(self):
"""Test __getitem__ method raises exceptions."""
for i in range(1, 4):
state = Statevector(self.rand_vec(2**i))
self.assertRaises(QiskitError, state.__getitem__, 2**i)
self.assertRaises(QiskitError, state.__getitem__, -1)
def test_copy(self):
"""Test Statevector copy method"""
for _ in range(5):
vec = self.rand_vec(4)
orig = Statevector(vec)
cpy = orig.copy()
cpy._data[0] += 1.0
self.assertFalse(cpy == orig)
def test_is_valid(self):
"""Test is_valid method."""
state = Statevector([1, 1])
self.assertFalse(state.is_valid())
for _ in range(10):
state = Statevector(self.rand_vec(4, normalize=True))
self.assertTrue(state.is_valid())
def test_to_operator(self):
"""Test to_operator method for returning projector."""
for _ in range(10):
vec = self.rand_vec(4)
target = Operator(np.outer(vec, np.conj(vec)))
op = Statevector(vec).to_operator()
self.assertEqual(op, target)
def test_evolve(self):
"""Test _evolve method."""
for _ in range(10):
op = random_unitary(4)
vec = self.rand_vec(4)
target = Statevector(np.dot(op.data, vec))
evolved = Statevector(vec).evolve(op)
self.assertEqual(target, evolved)
def test_evolve_subsystem(self):
"""Test subsystem _evolve method."""
# Test evolving single-qubit of 3-qubit system
for _ in range(5):
vec = self.rand_vec(8)
state = Statevector(vec)
op0 = random_unitary(2)
op1 = random_unitary(2)
op2 = random_unitary(2)
# Test evolve on 1-qubit
op = op0
op_full = Operator(np.eye(4)).tensor(op)
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[0]), target)
# Evolve on qubit 1
op_full = Operator(np.eye(2)).tensor(op).tensor(np.eye(2))
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[1]), target)
# Evolve on qubit 2
op_full = op.tensor(np.eye(4))
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[2]), target)
# Test evolve on 2-qubits
op = op1.tensor(op0)
# Evolve on qubits [0, 2]
op_full = op1.tensor(np.eye(2)).tensor(op0)
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[0, 2]), target)
# Evolve on qubits [2, 0]
op_full = op0.tensor(np.eye(2)).tensor(op1)
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[2, 0]), target)
# Test evolve on 3-qubits
op = op2.tensor(op1).tensor(op0)
# Evolve on qubits [0, 1, 2]
op_full = op
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[0, 1, 2]), target)
# Evolve on qubits [2, 1, 0]
op_full = op0.tensor(op1).tensor(op2)
target = Statevector(np.dot(op_full.data, vec))
self.assertEqual(state.evolve(op, qargs=[2, 1, 0]), target)
def test_evolve_qudit_subsystems(self):
"""Test nested evolve calls on qudit subsystems."""
dims = (3, 4, 5)
init = self.rand_vec(np.prod(dims))
ops = [random_unitary((dim,)) for dim in dims]
state = Statevector(init, dims)
for i, op in enumerate(ops):
state = state.evolve(op, [i])
target_op = np.eye(1)
for op in ops:
target_op = np.kron(op.data, target_op)
target = Statevector(np.dot(target_op, init), dims)
self.assertEqual(state, target)
def test_evolve_global_phase(self):
"""Test evolve circuit with global phase."""
state_i = Statevector([1, 0])
qr = QuantumRegister(2)
phase = np.pi / 4
circ = QuantumCircuit(qr, global_phase=phase)
circ.x(0)
state_f = state_i.evolve(circ, qargs=[0])
target = Statevector([0, 1]) * np.exp(1j * phase)
self.assertEqual(state_f, target)
def test_conjugate(self):
"""Test conjugate method."""
for _ in range(10):
vec = self.rand_vec(4)
target = Statevector(np.conj(vec))
state = Statevector(vec).conjugate()
self.assertEqual(state, target)
def test_expand(self):
"""Test expand method."""
for _ in range(10):
vec0 = self.rand_vec(2)
vec1 = self.rand_vec(3)
target = np.kron(vec1, vec0)
state = Statevector(vec0).expand(Statevector(vec1))
self.assertEqual(state.dim, 6)
self.assertEqual(state.dims(), (2, 3))
assert_allclose(state.data, target)
def test_tensor(self):
"""Test tensor method."""
for _ in range(10):
vec0 = self.rand_vec(2)
vec1 = self.rand_vec(3)
target = np.kron(vec0, vec1)
state = Statevector(vec0).tensor(Statevector(vec1))
self.assertEqual(state.dim, 6)
self.assertEqual(state.dims(), (3, 2))
assert_allclose(state.data, target)
def test_inner(self):
"""Test inner method."""
for _ in range(10):
vec0 = Statevector(self.rand_vec(4))
vec1 = Statevector(self.rand_vec(4))
target = np.vdot(vec0.data, vec1.data)
result = vec0.inner(vec1)
self.assertAlmostEqual(result, target)
vec0 = Statevector(self.rand_vec(6), dims=(2, 3))
vec1 = Statevector(self.rand_vec(6), dims=(2, 3))
target = np.vdot(vec0.data, vec1.data)
result = vec0.inner(vec1)
self.assertAlmostEqual(result, target)
def test_inner_except(self):
"""Test inner method raises exceptions."""
vec0 = Statevector(self.rand_vec(4))
vec1 = Statevector(self.rand_vec(3))
self.assertRaises(QiskitError, vec0.inner, vec1)
vec0 = Statevector(self.rand_vec(6), dims=(2, 3))
vec1 = Statevector(self.rand_vec(6), dims=(3, 2))
self.assertRaises(QiskitError, vec0.inner, vec1)
def test_add(self):
"""Test add method."""
for _ in range(10):
vec0 = self.rand_vec(4)
vec1 = self.rand_vec(4)
state0 = Statevector(vec0)
state1 = Statevector(vec1)
self.assertEqual(state0 + state1, Statevector(vec0 + vec1))
def test_add_except(self):
"""Test add method raises exceptions."""
state1 = Statevector(self.rand_vec(2))
state2 = Statevector(self.rand_vec(3))
self.assertRaises(QiskitError, state1.__add__, state2)
def test_subtract(self):
"""Test subtract method."""
for _ in range(10):
vec0 = self.rand_vec(4)
vec1 = self.rand_vec(4)
state0 = Statevector(vec0)
state1 = Statevector(vec1)
self.assertEqual(state0 - state1, Statevector(vec0 - vec1))
def test_multiply(self):
"""Test multiply method."""
for _ in range(10):
vec = self.rand_vec(4)
state = Statevector(vec)
val = np.random.rand() + 1j * np.random.rand()
self.assertEqual(val * state, Statevector(val * state))
def test_negate(self):
"""Test negate method"""
for _ in range(10):
vec = self.rand_vec(4)
state = Statevector(vec)
self.assertEqual(-state, Statevector(-1 * vec))
def test_equiv(self):
"""Test equiv method"""
vec = np.array([1, 0, 0, -1j]) / np.sqrt(2)
phase = np.exp(-1j * np.pi / 4)
statevec = Statevector(vec)
self.assertTrue(statevec.equiv(phase * vec))
self.assertTrue(statevec.equiv(Statevector(phase * vec)))
self.assertFalse(statevec.equiv(2 * vec))
def test_equiv_on_circuit(self):
"""Test the equiv method on different types of input."""
statevec = Statevector([1, 0])
qc = QuantumCircuit(1)
self.assertTrue(statevec.equiv(qc))
qc.x(0)
self.assertFalse(statevec.equiv(qc))
def test_to_dict(self):
"""Test to_dict method"""
with self.subTest(msg="dims = (2, 3)"):
vec = Statevector(np.arange(1, 7), dims=(2, 3))
target = {"00": 1, "01": 2, "10": 3, "11": 4, "20": 5, "21": 6}
self.assertDictAlmostEqual(target, vec.to_dict())
with self.subTest(msg="dims = (11, )"):
vec = Statevector(np.arange(1, 12), dims=(11,))
target = {str(i): i + 1 for i in range(11)}
self.assertDictAlmostEqual(target, vec.to_dict())
with self.subTest(msg="dims = (2, 11)"):
vec = Statevector(np.arange(1, 23), dims=(2, 11))
target = {}
for i in range(11):
for j in range(2):
key = f"{i},{j}"
target[key] = 2 * i + j + 1
self.assertDictAlmostEqual(target, vec.to_dict())
def test_probabilities_product(self):
"""Test probabilities method for product state"""
state = Statevector.from_label("+0")
# 2-qubit qargs
with self.subTest(msg="P(None)"):
probs = state.probabilities()
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([0, 1])"):
probs = state.probabilities([0, 1])
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([1, 0]"):
probs = state.probabilities([1, 0])
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
with self.subTest(msg="P([0])"):
probs = state.probabilities([0])
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
with self.subTest(msg="P([1])"):
probs = state.probabilities([1])
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
def test_probabilities_ghz(self):
"""Test probabilities method for GHZ state"""
state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
# 3-qubit qargs
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
target = np.array([0.5, 0, 0, 0.5])
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
target = np.array([0.5, 0.5])
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
def test_probabilities_w(self):
"""Test probabilities method with W state"""
state = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
# 3-qubit qargs
target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
target = np.array([1 / 3, 1 / 3, 1 / 3, 0])
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
target = np.array([2 / 3, 1 / 3])
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities(qargs)
self.assertTrue(np.allclose(probs, target))
def test_probabilities_dict_product(self):
"""Test probabilities_dict method for product state"""
state = Statevector.from_label("+0")
# 2-qubit qargs
with self.subTest(msg="P(None)"):
probs = state.probabilities_dict()
target = {"00": 0.5, "10": 0.5}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([0, 1])"):
probs = state.probabilities_dict([0, 1])
target = {"00": 0.5, "10": 0.5}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([1, 0]"):
probs = state.probabilities_dict([1, 0])
target = {"00": 0.5, "01": 0.5}
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
with self.subTest(msg="P([0])"):
probs = state.probabilities_dict([0])
target = {"0": 1}
self.assertDictAlmostEqual(probs, target)
with self.subTest(msg="P([1])"):
probs = state.probabilities_dict([1])
target = {"0": 0.5, "1": 0.5}
self.assertDictAlmostEqual(probs, target)
def test_probabilities_dict_ghz(self):
"""Test probabilities_dict method for GHZ state"""
state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
# 3-qubit qargs
target = {"000": 0.5, "111": 0.5}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 2-qubit qargs
target = {"00": 0.5, "11": 0.5}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
target = {"0": 0.5, "1": 0.5}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
def test_probabilities_dict_w(self):
"""Test probabilities_dict method with W state"""
state = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
# 3-qubit qargs
target = np.array([0, 1 / 3, 1 / 3, 0, 1 / 3, 0, 0, 0])
target = {"001": 1 / 3, "010": 1 / 3, "100": 1 / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 2-qubit qargs
target = {"00": 1 / 3, "01": 1 / 3, "10": 1 / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
# 1-qubit qargs
target = {"0": 2 / 3, "1": 1 / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = state.probabilities_dict(qargs)
self.assertDictAlmostEqual(probs, target)
def test_sample_counts_ghz(self):
"""Test sample_counts method for GHZ state"""
shots = 2000
threshold = 0.02 * shots
state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
state.seed(100)
# 3-qubit qargs
target = {"000": shots / 2, "111": shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 2-qubit qargs
target = {"00": shots / 2, "11": shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 1-qubit qargs
target = {"0": shots / 2, "1": shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
def test_sample_counts_w(self):
"""Test sample_counts method for W state"""
shots = 3000
threshold = 0.02 * shots
state = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
state.seed(100)
target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 2-qubit qargs
target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
# 1-qubit qargs
target = {"0": 2 * shots / 3, "1": shots / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
counts = state.sample_counts(shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, threshold)
def test_probabilities_dict_unequal_dims(self):
"""Test probabilities_dict for a state with unequal subsystem dimensions."""
vec = np.zeros(60, dtype=float)
vec[15:20] = np.ones(5)
vec[40:46] = np.ones(6)
state = Statevector(vec / np.sqrt(11.0), dims=[3, 4, 5])
p = 1.0 / 11.0
self.assertDictEqual(
state.probabilities_dict(),
{
s: p
for s in [
"110",
"111",
"112",
"120",
"121",
"311",
"312",
"320",
"321",
"322",
"330",
]
},
)
# differences due to rounding
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0]), {"0": 4 * p, "1": 4 * p, "2": 3 * p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[1]), {"1": 5 * p, "2": 5 * p, "3": p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[2]), {"1": 5 * p, "3": 6 * p}, delta=1e-10
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0, 1]),
{"10": p, "11": 2 * p, "12": 2 * p, "20": 2 * p, "21": 2 * p, "22": p, "30": p},
delta=1e-10,
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[1, 0]),
{"01": p, "11": 2 * p, "21": 2 * p, "02": 2 * p, "12": 2 * p, "22": p, "03": p},
delta=1e-10,
)
self.assertDictAlmostEqual(
state.probabilities_dict(qargs=[0, 2]),
{"10": 2 * p, "11": 2 * p, "12": p, "31": 2 * p, "32": 2 * p, "30": 2 * p},
delta=1e-10,
)
def test_sample_counts_qutrit(self):
"""Test sample_counts method for qutrit state"""
p = 0.3
shots = 1000
threshold = 0.03 * shots
state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)])
state.seed(100)
with self.subTest(msg="counts"):
target = {"0": shots * p, "2": shots * (1 - p)}
counts = state.sample_counts(shots=shots)
self.assertDictAlmostEqual(counts, target, threshold)
def test_sample_memory_ghz(self):
"""Test sample_memory method for GHZ state"""
shots = 2000
state = (Statevector.from_label("000") + Statevector.from_label("111")) / np.sqrt(2)
state.seed(100)
# 3-qubit qargs
target = {"000": shots / 2, "111": shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": shots / 2, "11": shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": shots / 2, "1": shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
def test_sample_memory_w(self):
"""Test sample_memory method for W state"""
shots = 3000
state = (
Statevector.from_label("001")
+ Statevector.from_label("010")
+ Statevector.from_label("100")
) / np.sqrt(3)
state.seed(100)
target = {"001": shots / 3, "010": shots / 3, "100": shots / 3}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": shots / 3, "01": shots / 3, "10": shots / 3}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": 2 * shots / 3, "1": shots / 3}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = state.sample_memory(shots, qargs=qargs)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), set(target))
def test_sample_memory_qutrit(self):
"""Test sample_memory method for qutrit state"""
p = 0.3
shots = 1000
state = Statevector([np.sqrt(p), 0, np.sqrt(1 - p)])
state.seed(100)
with self.subTest(msg="memory"):
memory = state.sample_memory(shots)
self.assertEqual(len(memory), shots)
self.assertEqual(set(memory), {"0", "2"})
def test_reset_2qubit(self):
"""Test reset method for 2-qubit state"""
state = Statevector(np.array([1, 0, 0, 1]) / np.sqrt(2))
state.seed(100)
with self.subTest(msg="reset"):
psi = state.copy()
value = psi.reset()
target = Statevector(np.array([1, 0, 0, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset"):
psi = state.copy()
value = psi.reset([0, 1])
target = Statevector(np.array([1, 0, 0, 0]))
self.assertEqual(value, target)
with self.subTest(msg="reset [0]"):
psi = state.copy()
value = psi.reset([0])
targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 0, 1, 0]))]
self.assertIn(value, targets)
with self.subTest(msg="reset [0]"):
psi = state.copy()
value = psi.reset([1])
targets = [Statevector(np.array([1, 0, 0, 0])), Statevector(np.array([0, 1, 0, 0]))]
self.assertIn(value, targets)
def test_reset_qutrit(self):
"""Test reset method for qutrit"""
state = Statevector(np.array([1, 1, 1]) / np.sqrt(3))
state.seed(200)
value = state.reset()
target = Statevector(np.array([1, 0, 0]))
self.assertEqual(value, target)
def test_measure_2qubit(self):
"""Test measure method for 2-qubit state"""
state = Statevector.from_label("+0")
seed = 200
shots = 100
with self.subTest(msg="measure"):
for i in range(shots):
psi = state.copy()
psi.seed(seed + i)
outcome, value = psi.measure()
self.assertIn(outcome, ["00", "10"])
if outcome == "00":
target = Statevector.from_label("00")
self.assertEqual(value, target)
else:
target = Statevector.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [0, 1]"):
for i in range(shots):
psi = state.copy()
outcome, value = psi.measure([0, 1])
self.assertIn(outcome, ["00", "10"])
if outcome == "00":
target = Statevector.from_label("00")
self.assertEqual(value, target)
else:
target = Statevector.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [1, 0]"):
for i in range(shots):
psi = state.copy()
outcome, value = psi.measure([1, 0])
self.assertIn(outcome, ["00", "01"])
if outcome == "00":
target = Statevector.from_label("00")
self.assertEqual(value, target)
else:
target = Statevector.from_label("10")
self.assertEqual(value, target)
with self.subTest(msg="measure [0]"):
for i in range(shots):
psi = state.copy()
outcome, value = psi.measure([0])
self.assertEqual(outcome, "0")
target = Statevector(np.array([1, 0, 1, 0]) / np.sqrt(2))
self.assertEqual(value, target)
with self.subTest(msg="measure [1]"):
for i in range(shots):
psi = state.copy()
outcome, value = psi.measure([1])
self.assertIn(outcome, ["0", "1"])
if outcome == "0":
target = Statevector.from_label("00")
self.assertEqual(value, target)
else:
target = Statevector.from_label("10")
self.assertEqual(value, target)
def test_measure_qutrit(self):
"""Test measure method for qutrit"""
state = Statevector(np.array([1, 1, 1]) / np.sqrt(3))
seed = 200
shots = 100
for i in range(shots):
psi = state.copy()
psi.seed(seed + i)
outcome, value = psi.measure()
self.assertIn(outcome, ["0", "1", "2"])
if outcome == "0":
target = Statevector([1, 0, 0])
self.assertEqual(value, target)
elif outcome == "1":
target = Statevector([0, 1, 0])
self.assertEqual(value, target)
else:
target = Statevector([0, 0, 1])
self.assertEqual(value, target)
def test_from_int(self):
"""Test from_int method"""
with self.subTest(msg="from_int(0, 4)"):
target = Statevector([1, 0, 0, 0])
value = Statevector.from_int(0, 4)
self.assertEqual(target, value)
with self.subTest(msg="from_int(3, 4)"):
target = Statevector([0, 0, 0, 1])
value = Statevector.from_int(3, 4)
self.assertEqual(target, value)
with self.subTest(msg="from_int(8, (3, 3))"):
target = Statevector([0, 0, 0, 0, 0, 0, 0, 0, 1], dims=(3, 3))
value = Statevector.from_int(8, (3, 3))
self.assertEqual(target, value)
def test_expval(self):
"""Test expectation_value method"""
psi = Statevector([1, 0, 0, 1]) / np.sqrt(2)
for label, target in [
("II", 1),
("XX", 1),
("YY", -1),
("ZZ", 1),
("IX", 0),
("YZ", 0),
("ZX", 0),
("YI", 0),
]:
with self.subTest(msg=f"<{label}>"):
op = Pauli(label)
expval = psi.expectation_value(op)
self.assertAlmostEqual(expval, target)
psi = Statevector([np.sqrt(2), 0, 0, 0, 0, 0, 0, 1 + 1j]) / 2
for label, target in [
("XXX", np.sqrt(2) / 2),
("YYY", -np.sqrt(2) / 2),
("ZZZ", 0),
("XYZ", 0),
("YIY", 0),
]:
with self.subTest(msg=f"<{label}>"):
op = Pauli(label)
expval = psi.expectation_value(op)
self.assertAlmostEqual(expval, target)
labels = ["XXX", "IXI", "YYY", "III"]
coeffs = [3.0, 5.5, -1j, 23]
spp_op = SparsePauliOp.from_list(list(zip(labels, coeffs)))
expval = psi.expectation_value(spp_op)
target = 25.121320343559642 + 0.7071067811865476j
self.assertAlmostEqual(expval, target)
@data(
"II",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZX",
"ZY",
"ZZ",
"-II",
"-IX",
"-IY",
"-IZ",
"-XI",
"-XX",
"-XY",
"-XZ",
"-YI",
"-YX",
"-YY",
"-YZ",
"-ZI",
"-ZX",
"-ZY",
"-ZZ",
"iII",
"iIX",
"iIY",
"iIZ",
"iXI",
"iXX",
"iXY",
"iXZ",
"iYI",
"iYX",
"iYY",
"iYZ",
"iZI",
"iZX",
"iZY",
"iZZ",
"-iII",
"-iIX",
"-iIY",
"-iIZ",
"-iXI",
"-iXX",
"-iXY",
"-iXZ",
"-iYI",
"-iYX",
"-iYY",
"-iYZ",
"-iZI",
"-iZX",
"-iZY",
"-iZZ",
)
def test_expval_pauli(self, pauli):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = Pauli(pauli)
state = random_statevector(2**op.num_qubits, seed=seed)
target = state.expectation_value(op.to_matrix())
expval = state.expectation_value(op)
self.assertAlmostEqual(expval, target)
@data([0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1])
def test_expval_pauli_qargs(self, qubits):
"""Test expectation_value method for Pauli op"""
seed = 1020
op = random_pauli(2, seed=seed)
state = random_statevector(2**3, seed=seed)
target = state.expectation_value(op.to_matrix(), qubits)
expval = state.expectation_value(op, qubits)
self.assertAlmostEqual(expval, target)
@data(*(qargs for i in range(4) for qargs in permutations(range(4), r=i + 1)))
def test_probabilities_qargs(self, qargs):
"""Test probabilities method with qargs"""
# Get initial state
nq = 4
nc = len(qargs)
state_circ = QuantumCircuit(nq, nc)
for i in range(nq):
state_circ.ry((i + 1) * np.pi / (nq + 1), i)
# Get probabilities
state = Statevector(state_circ)
probs = state.probabilities(qargs)
# Estimate target probs from simulator measurement
sim = QasmSimulatorPy()
shots = 5000
seed = 100
circ = transpile(state_circ, sim)
circ.measure(qargs, range(nc))
result = sim.run(circ, shots=shots, seed_simulator=seed).result()
target = np.zeros(2**nc, dtype=float)
for i, p in result.get_counts(0).int_outcomes().items():
target[i] = p / shots
# Compare
delta = np.linalg.norm(probs - target)
self.assertLess(delta, 0.05)
def test_global_phase(self):
"""Test global phase is handled correctly when evolving statevector."""
qc = QuantumCircuit(1)
qc.rz(0.5, 0)
qc2 = transpile(qc, basis_gates=["p"])
sv = Statevector.from_instruction(qc2)
expected = np.array([0.96891242 - 0.24740396j, 0])
self.assertEqual(float(qc2.global_phase), 2 * np.pi - 0.25)
self.assertEqual(sv, Statevector(expected))
def test_reverse_qargs(self):
"""Test reverse_qargs method"""
circ1 = QFT(5)
circ2 = circ1.reverse_bits()
state1 = Statevector.from_instruction(circ1)
state2 = Statevector.from_instruction(circ2)
self.assertEqual(state1.reverse_qargs(), state2)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "requires matplotlib")
@unittest.skipUnless(optionals.HAS_PYLATEX, "requires pylatexenc")
def test_drawings(self):
"""Test draw method"""
qc1 = QFT(5)
sv = Statevector.from_instruction(qc1)
with self.subTest(msg="str(statevector)"):
str(sv)
for drawtype in ["repr", "text", "latex", "latex_source", "qsphere", "hinton", "bloch"]:
with self.subTest(msg=f"draw('{drawtype}')"):
sv.draw(drawtype)
with self.subTest(msg=" draw('latex', convention='vector')"):
sv.draw("latex", convention="vector")
def test_state_to_latex_for_none(self):
"""
Test for `\rangleNone` output in latex representation
See https://github.com/Qiskit/qiskit-terra/issues/8169
"""
sv = Statevector(
[
7.07106781e-01 - 8.65956056e-17j,
-5.55111512e-17 - 8.65956056e-17j,
7.85046229e-17 + 8.65956056e-17j,
-7.07106781e-01 + 8.65956056e-17j,
0.00000000e00 + 0.00000000e00j,
-0.00000000e00 + 0.00000000e00j,
-0.00000000e00 + 0.00000000e00j,
0.00000000e00 - 0.00000000e00j,
],
dims=(2, 2, 2),
)
latex_representation = state_to_latex(sv)
self.assertEqual(
latex_representation,
"\\frac{\\sqrt{2}}{2} |000\\rangle- \\frac{\\sqrt{2}}{2} |011\\rangle",
)
def test_state_to_latex_for_large_statevector(self):
"""Test conversion of large dense state vector"""
sv = Statevector(np.ones((2**15, 1)))
latex_representation = state_to_latex(sv)
self.assertEqual(
latex_representation,
" |000000000000000\\rangle+ |000000000000001\\rangle+ |000000000000010\\rangle+"
" |000000000000011\\rangle+ |000000000000100\\rangle+ |000000000000101\\rangle +"
" \\ldots + |111111111111011\\rangle+ |111111111111100\\rangle+"
" |111111111111101\\rangle+ |111111111111110\\rangle+ |111111111111111\\rangle",
)
def test_state_to_latex_with_prefix(self):
"""Test adding prefix to state vector latex output"""
psi = Statevector(np.array([np.sqrt(1 / 2), 0, 0, np.sqrt(1 / 2)]))
prefix = "|\\psi_{AB}\\rangle = "
latex_sv = state_to_latex(psi)
latex_expected = prefix + latex_sv
latex_representation = state_to_latex(psi, prefix=prefix)
self.assertEqual(latex_representation, latex_expected)
def test_state_to_latex_for_large_sparse_statevector(self):
"""Test conversion of large sparse state vector"""
sv = Statevector(np.eye(2**15, 1))
latex_representation = state_to_latex(sv)
self.assertEqual(latex_representation, " |000000000000000\\rangle")
def test_state_to_latex_with_max_size_limit(self):
"""Test limit the maximum number of non-zero terms in the expression"""
sv = Statevector(
[
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 - 0.35355339j,
0.0 + 0.35355339j,
0.0 + 0.35355339j,
0.0 - 0.35355339j,
],
dims=(2, 2, 2, 2),
)
latex_representation = state_to_latex(sv, max_size=5)
self.assertEqual(
latex_representation,
"\\frac{\\sqrt{2}}{4} |0000\\rangle+"
"\\frac{\\sqrt{2}}{4} |0001\\rangle + "
"\\ldots +"
"\\frac{\\sqrt{2} i}{4} |1110\\rangle- "
"\\frac{\\sqrt{2} i}{4} |1111\\rangle",
)
def test_state_to_latex_with_decimals_round(self):
"""Test rounding of decimal places in the expression"""
sv = Statevector(
[
0.35355339 + 0.0j,
0.35355339 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 + 0.0j,
0.0 - 0.35355339j,
0.0 + 0.35355339j,
],
dims=(2, 2, 2),
)
latex_representation = state_to_latex(sv, decimals=3)
self.assertEqual(
latex_representation,
"0.354 |000\\rangle+0.354 |001\\rangle- 0.354 i |110\\rangle+0.354 i |111\\rangle",
)
def test_number_to_latex_terms(self):
"""Test conversions of complex numbers to latex terms"""
cases = [
([1 - 8e-17, 0], ["", None]),
([0, -1], [None, "-"]),
([0, 1], [None, ""]),
([0, 1j], [None, "i"]),
([-1, 1], ["-", "+"]),
([0, 1j], [None, "i"]),
([-1, 1j], ["-", "+i"]),
([1e-16 + 1j], ["i"]),
([-1 + 1e-16 * 1j], ["-"]),
([-1, -1 - 1j], ["-", "+(-1 - i)"]),
([np.sqrt(2) / 2, np.sqrt(2) / 2], ["\\frac{\\sqrt{2}}{2}", "+\\frac{\\sqrt{2}}{2}"]),
([1 + np.sqrt(2)], ["(1 + \\sqrt{2})"]),
]
with self.assertWarns(DeprecationWarning):
for numbers, latex_terms in cases:
terms = numbers_to_latex_terms(numbers, 15)
self.assertListEqual(terms, latex_terms)
def test_statevector_draw_latex_regression(self):
"""Test numerical rounding errors are not printed"""
sv = Statevector(np.array([1 - 8e-17, 8.32667268e-17j]))
latex_string = sv.draw(output="latex_source")
self.assertTrue(latex_string.startswith(" |0\\rangle"))
self.assertNotIn("|1\\rangle", latex_string)
def test_statevctor_iter(self):
"""Test iteration over a state vector"""
empty_vector = []
dummy_vector = [1, 2, 3]
empty_sv = Statevector([])
sv = Statevector(dummy_vector)
# Assert that successive iterations behave as expected, i.e., the
# iterator is reset upon each exhaustion of the corresponding
# collection of elements.
for _ in range(2):
self.assertEqual(empty_vector, list(empty_sv))
self.assertEqual(dummy_vector, list(sv))
def test_statevector_len(self):
"""Test state vector length"""
empty_vector = []
dummy_vector = [1, 2, 3]
empty_sv = Statevector([])
sv = Statevector(dummy_vector)
self.assertEqual(len(empty_vector), len(empty_sv))
self.assertEqual(len(dummy_vector), len(sv))
def test_clip_probabilities(self):
"""Test probabilities are clipped to [0, 1]."""
sv = Statevector([1.1, 0])
self.assertEqual(list(sv.probabilities()), [1.0, 0.0])
# The "1" key should be zero and therefore omitted.
self.assertEqual(sv.probabilities_dict(), {"0": 1.0})
def test_round_probabilities(self):
"""Test probabilities are correctly rounded.
This is good to test to ensure clipping, renormalizing and rounding work together.
"""
p = np.sqrt(1 / 3)
sv = Statevector([p, p, p, 0])
expected = [0.33, 0.33, 0.33, 0]
self.assertEqual(list(sv.probabilities(decimals=2)), expected)
if __name__ == "__main__":
unittest.main()
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import QuantumCircuit, transpile, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
qc.h(2)
qc.cp(pi/2, 1, 2)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 0, 1)
qc.h(0)
qc.swap(0, 2)
qc.draw()
def qft_rotations(circuit, n):
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qc = QuantumCircuit(4)
qft(qc,4)
qc.draw()
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5 (101 in binary)
qc.x(0)
qc.x(2)
qc.draw()
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy()
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qft(qc, 3)
qc.draw()
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
J = 4.0
B_x = 2.0
B_z = 1.0
import numpy as np
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.aqua.operators import *
from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance
from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.visualization import plot_histogram
Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)
- B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z )
) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ))
ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
print(ansatz)
backend = AerSimulator(method='matrix_product_state')
quantum_instance = QuantumInstance(backend,
shots = 8192,
initial_layout = None,
optimization_level = 3)
optimizer = COBYLA(maxiter=10000, tol=0.000000001)
vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False)
print('We are using:', quantum_instance.backend)
vqe_result = vqe.run(quantum_instance)
print(vqe['result'])
plot_histogram(vqe_result['eigenstate'])
import pickle
filename = "2D_Ising_Model_CountsDIS2.pkl"
a = {'vqe_result': vqe_result}
#This saves the data
with open(filename, 'wb') as handle:
pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)
# This loads the data
with open(filename, 'rb') as handle:
b = pickle.load(handle)
|
https://github.com/Manish-Sudhir/QiskitCheck
|
Manish-Sudhir
|
import warnings
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer, transpile, IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_bloch_multivector, plot_histogram, array_to_latex
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
import pandas as pd
import math
from qiskit.quantum_info import Statevector
from scipy.stats import chi2_contingency, ttest_ind
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
pi = np.pi
# q = QuantumRegister(2)
# c = ClassicalRegister(1)
# qc2 = QuantumCircuit(q,c)
# qc2.x(1)
# qc2.h(0)
# qc2.cnot(0,1)
qc2 = QuantumCircuit(2)
# qc2.x(1)
# qc2.h(0)
# qc2.measure(q[0],c)
# qc2.measure(q[1],c)
# THIS DOESNT WORK
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
# qc2.h(0)
# qc2.x(0)
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
# qc2.h(0)
# 4 BELL STATES
# qc2.x(1)
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
qc2.h(1)
qc2.cp(pi/2,1,0)
qc2.h(0)
print(qc2)
sv = Statevector.from_label('01')
sv.evolve(qc2)
print(sv)
backend = Aer.get_backend('aer_simulator')
qc2.measure_all()
# sv = Statevector.from_label('01')
# sv.evolve(qc2)
# print(sv)
qc2.save_statevector()
# probs = psi.probabilities()
# print(probs)
final_state = backend.run(qc2).result().get_statevector()
print(final_state)
# display(array_to_latex(final_state, prefix="\\text{Statevector} = "))
job = execute(qc2, backend, shots=10000, memory=True)#run the circuit 1000000 times
counts = job.result().get_counts()#return the result counts
print(counts)
qc2 = QuantumCircuit(2)
# qc2.p(0.5*2*math.pi/100, 1)
qc2.h(0)
# qc2.cnot(0,1)
# qc2.x(0)
# qc2.x(1)
# qc2.h(0)
# qc2.cnot(0,1)
# qc2.h(1)
print(qc2)
backend = Aer.get_backend('aer_simulator')
sv1 = Statevector.from_label('00')
print(type(sv1))
wow = sv1.evolve(qc2)
probs = wow.probabilities()
probsD = wow.probabilities_dict()
print(sv1)
for values in probsD.values():
round(values,2)
d = {key: round(values,2) for key,values in probsD.items()}
print("probs dictionary rounded",d)
print("probs for qubit1 (not rounded): ",wow.probabilities_dict([0]))
print("probs for qubit2 (not rounded): ", wow.probabilities_dict([1]))
# print("probs: ", type(probs))
# print("probs Dictionary: ", probsD)
# probs_qubit_0 = wow.probabilities([0])
# probs_qubit_1 = wow.probabilities([1])
# print('Qubit-0 probs: {}'.format(probs_qubit_0))
# print('Qubit-1 probs: {}'.format(probs_qubit_1))
# print(wow.probabilities_dict([0]))
# print(wow.probabilities_dict([1]))
for values in d.values():
# print(values)
if (values==0.5):
print("true")
else:
print("false")
qc2.measure_all()
sv = qc2.save_statevector()
print("sv: " ,sv)
# probs = psi.probabilities()
# print(probs)
final_state = backend.run(qc2).result().get_statevector()
print("final : " ,final_state)
job = execute(qc2, backend, shots=10000, memory=True)#run the circuit 1000000 times
counts = job.result().get_counts()#return the result counts
print(counts)
def assertProbability(qc,qubitChoice: int, qubitState :str, expectedProbability):
sv = Statevector.from_label("00")
evl = sv.evolve(qc)
probs = evl.probabilities_dict([qubitChoice])
probsRound = {key: round(values,2) for key,values in probs.items()}
for key,value in probsRound.items():
if(key==qubitState):
if(value==expectedProbability):
print("Expected Probability present")
else:
raise(AssertionError("Probability not present"))
else:
raise(AssertionError("Probability not present"))
qc = QuantumCircuit(2)
qc.h(0)
assertProbability(qc,1,"0",1)
psi = Statevector.from_label('10')
print(psi)
print("statevector measurement: " ,psi.measure())
# rev = psi.reverse_qargs()
# Probabilities for measuring both qubits
probs = psi.probabilities()
print('probs: {}'.format(probs))
probsD = psi.probabilities_dict()
print("probs dictionary: ", probsD)
# Probabilities for measuring only qubit-0
probs_qubit_0 = psi.probabilities([0])
print('Qubit-0 probs: {}'.format(probs_qubit_0))
print('Qubit-0 probs: {}'.format(psi.probabilities_dict([0])))
# Probabilities for measuring only qubit-1
probs_qubit_1 = psi.probabilities([1])
print('Qubit-1 probs: {}'.format(probs_qubit_1))
print('Qubit-1 probs: {}'.format(psi.probabilities_dict([1])))
def measure_z(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def assertEntangled(backend,qc,qubit1,qubit2,measurements_to_make,alpha = 0.05):
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(2))
elif (qc.num_clbits != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
zQuantumCircuit = measure_z(qc, [qubit1, qubit2])
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
# zDf = pd.DataFrame(columns=['q0', 'q1'])
# for row in zCounts:
# zDf = zDf.append({'q0':row[0], 'q1':row[1]}, ignore_index=True)
# print(zDf.astype(str))
resDf = pd.DataFrame(columns=['0','1'])
classical_qubit_index = 1
for qubit in [qubit1,qubit2]:
zero_amount, one_amount = 0,0
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
df = {'0':zero_amount, '1':one_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
resDf['0'] = resDf['0'].astype(int)
resDf['1'] = resDf['1'].astype(int)
print(resDf.astype(str))
chiVal, pVal, dOfFreedom, exp = chi2_contingency(resDf)
print("chi square value: ",chiVal,"p value: ",pVal,"expected values: ",exp)
if(pVal<alpha):
raise(AssertionError("states are not entangled"))
else:
print("states are entangled")
backend = Aer.get_backend('aer_simulator')
qc3 = QuantumCircuit(2)
qc3.h(0)
# qc3.cnot(0,1)
# qc3.x(0)
# qc3.h(0)
# qc3.cnot(0,1)
# qc3.h(1)
# qc3.h(0)
assertEntangled(backend,qc3,0,1,100000,0.05)
# Completed but more testing required
def assertEntangled(backend,qc,qubits_to_assert,measurements_to_make,alpha = 0.05):
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (qc.num_clbits == 0):
qc.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
zQuantumCircuit = measure_z(qc, qubits_to_assert)
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
print(zMemory)
q1=[]
q2=[]
print("lol ",qubits_to_assert[0])
print(qubits_to_assert[1])
newDict = dict.fromkeys(['qubit1','qubit2'])
newDict = {'qubit1': qubits_to_assert[0],'qubit2':qubits_to_assert[1]}
print("new dict", newDict)
# if(qubits_to_assert[0]==0 and qubits_to_assert[1]==0):
# qubits_to_assert[1]
classicalQubitIndex = 1
for qubit in newDict.keys():
print("this qubit:",qubit)
for measurement in zMemory:
print("this measurement", measurement)
if (measurement[2-classicalQubitIndex] == '0'):
print("measure: ",measurement[2-classicalQubitIndex],"also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
print("Added to q1 for measure0:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
print("Added to q2 for measure0:", measurement[2-classicalQubitIndex])
else:
print("measureOTHER: ",measurement[2-classicalQubitIndex], "also: qubittoassert0",qubits_to_assert[0],"and qubittoassert1: ",qubits_to_assert[1])
if(qubit=='qubit1'):
q1.append(measurement[2-classicalQubitIndex])
print("Added to q1 for measure1:", measurement[2-classicalQubitIndex])
else:
q2.append(measurement[2-classicalQubitIndex])
print("Added to q2 for measure1:", measurement[2-classicalQubitIndex])
classicalQubitIndex+=1
print("Q1: ",q1)
print("Q2: ",q2)
measDict = dict.fromkeys(['qubit1','qubit2'])
measDict = {'qubit1': q1,'qubit2':q2}
measDf1 = pd.DataFrame.from_dict(measDict,orient='index')
# measDf = pd.DataFrame.from_dict(measDict)
# print(measDf)
measDf12=measDf1.transpose()
print(measDf12)
# df = pd.DataFrame.from_dict(a, orient='index')
# df = df.transpose()
ct = pd.crosstab(measDf12.qubit1,measDf12.qubit2)
chiVal, pVal, dOfFreedom, exp = chi2_contingency(ct)
print("chi square value: ",chiVal,"p value: ",pVal,"expected values: ",exp)
if(pVal>alpha):
raise(AssertionError("states are not entangled"))
else:
print("states are entangled")
backend = Aer.get_backend('aer_simulator')
qr = QuantumRegister(2)
cr=ClassicalRegister(2)
qc3 = QuantumCircuit(qr,cr)
qc3.x(1)
# # qc3.x(1)
# # qc3.x(0)
qc3.h(0)
# qc3.cnot(0,1)
# qc3.h(0)
# qc3.cnot(0,1)
# qc3.x(1)
# qc3.rx(np.pi/2,qr[0])
# qc3.p(10*2*math.pi/100, 0)
# qc3.p(0.5*2*math.pi/100, 1)
print(qc3)
assertEntangled(backend,qc3,[0,1],20,0.05)
# circuit = QuantumCircuit(2)
# circuit.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], circuit.qubits)
# assertEntangled(backend,circuit,[0,1],10,0.05)
def measure_x(circuit, qubitIndexes):
cBitIndex = 0
for index in qubitIndexes:
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
def measure_y(circuit, qubit_indexes):
cBitIndex = 0
for index in qubit_indexes:
circuit.sdg(index)
circuit.h(index)
circuit.measure(index, cBitIndex)
cBitIndex+=1
return circuit
## assert that qubits are equal
def assertEqual(backend, quantumCircuit, qubits_to_assert, measurements_to_make, alpha):
## needs to make at least 2 measurements, one for x axis, one for y axis
## realistically we need more for any statistical significance
if (measurements_to_make < 2):
raise ValueError("Must make at least 2 measurements")
# makes sure qubits_to_assert is a list
if (not isinstance(qubits_to_assert, list)):
qubits_to_assert = [qubits_to_assert]
## classical register must be of same length as amount of qubits to assert
## if there is no classical register add them according to length of qubit list
if (quantumCircuit.num_clbits == 0):
quantumCircuit.add_register(ClassicalRegister(len(qubits_to_assert)))
elif (len(qubits_to_assert) != 2):
raise ValueError("QuantumCircuit classical register must be of length 2")
## divide measurements to make by 3 as we need to run measurements twice, one for x and one for y
measurements_to_make = measurements_to_make // 3
## copy the circit and set measurement to y axis
yQuantumCircuit = measure_y(quantumCircuit.copy(), qubits_to_assert)
## measure the x axis
xQuantumCircuit = measure_x(quantumCircuit.copy(), qubits_to_assert)
## measure the z axis
zQuantumCircuit = measure_z(quantumCircuit, qubits_to_assert)
## get y axis results
yJob = execute(yQuantumCircuit, backend, shots=measurements_to_make, memory=True)
yMemory = yJob.result().get_memory()
yCounts = yJob.result().get_counts()
## get x axis results
xJob = execute(xQuantumCircuit, backend, shots=measurements_to_make, memory=True)
xMemory = xJob.result().get_memory()
xCounts = xJob.result().get_counts()
## get z axis results
zJob = execute(zQuantumCircuit, backend, shots=measurements_to_make, memory=True)
zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
resDf = pd.DataFrame(columns=['0','1','+','i','-','-i'])
classical_qubit_index = 1
for qubit in qubits_to_assert:
zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0
for experiment in xCounts:
if (experiment[2-classical_qubit_index] == '0'):
plus_amount += xCounts[experiment]
else:
minus_amount += xCounts[experiment]
for experiment in yCounts:
if (experiment[2-classical_qubit_index] == '0'):
i_amount += yCounts[experiment]
else:
minus_i_amount += yCounts[experiment]
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
df = {'0':zero_amount, '1':one_amount,
'+':plus_amount, 'i':i_amount,
'-':minus_amount,'-i':minus_i_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
## convert the columns to a strict numerical type
resDf['+'] = resDf['+'].astype(int)
resDf['i'] = resDf['i'].astype(int)
resDf['-'] = resDf['-'].astype(int)
resDf['-i'] = resDf['-i'].astype(int)
resDf['0'] = resDf['0'].astype(int)
resDf['1'] = resDf['1'].astype(int)
print(resDf.astype(str))
# print(z1)
arr = resDf.to_numpy()
q1Vals = arr[0, 0:] # Stores measurements across all axes for the 1st qubit
print("Measurements for qubit1: ", q1Vals)
q2Vals = arr[1, 0:] # Stores measurements across all axes for the 2nd qubit
print("Measurements for qubit2: ", q2Vals)
tTest, pValue = ttest_ind(q1Vals, q2Vals, alternative = 'two-sided') # Apply t test
print("stat: ",tTest, "pValue: ", pValue)
if pValue > alpha:
print("The two qubits are equal (fail to reject null hypothesis) ")
else:
print("There is a significant difference between the two qubits (reject null hypothesis)")
qc = QuantumCircuit(2)
# qc.initialize([0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0], qc.qubits)
# qc.h(0)
# qc.x(1)
# qc.p(0.5*2*math.pi/100, 1)
# qc.h(0)
# qc.h(1)
# qc.p(10*2*math.pi/100, 0)
# qc.p(20*2*math.pi/100, 1)
assertEqual(backend, qc, [0,0], 300000, 0.01)
qc = QuantumCircuit(2,2)
qc.h(0)
qc.h(1)
qc.p(0.5*2*math.pi/100, 1)
# qc.cnot(0,1)
zQuantumCircuit = measure_z(qc, [0,1])
zJob = execute(zQuantumCircuit, backend, shots=100000, memory=True)
zMemory = zJob.result().get_memory()
zCounts = zJob.result().get_counts()
xQuantumCircuit = measure_x(qc, [0,1])
xJob = execute(xQuantumCircuit, backend, shots=100000, memory=True)
xMemory = xJob.result().get_memory()
xCounts = xJob.result().get_counts()
yQuantumCircuit = measure_y(qc, [0,1])
yJob = execute(yQuantumCircuit, backend, shots=100000, memory=True)
yMemory = yJob.result().get_memory()
yCounts = yJob.result().get_counts()
print("z axis : ", zCounts)
print("x axis : ", xCounts)
print("y axis : ", yCounts)
resDf = pd.DataFrame(columns=['0','1','+','i','-','-i'])
classical_qubit_index = 1
for qubit in [0,1]:
zero_amount, one_amount, plus_amount, i_amount, minus_amount, minus_i_amount = 0,0,0,0,0,0
for experiment in xCounts:
if (experiment[2-classical_qubit_index] == '0'):
plus_amount += xCounts[experiment]
else:
minus_amount += xCounts[experiment]
for experiment in yCounts:
if (experiment[2-classical_qubit_index] == '0'):
i_amount += yCounts[experiment]
else:
minus_i_amount += yCounts[experiment]
for experiment in zCounts:
if (experiment[2-classical_qubit_index] == '0'):
zero_amount += zCounts[experiment]
else:
one_amount += zCounts[experiment]
df = {'0':zero_amount, '1':one_amount,
'+':plus_amount, 'i':i_amount,
'-':minus_amount,'-i':minus_i_amount}
resDf = resDf.append(df, ignore_index = True)
classical_qubit_index+=1
print(resDf.astype(str))
lst = [["Ajay", 70], ["Manish", 92], ["Arjun", 42]]
df = pd.DataFrame(lst, columns=["Name", "Marks"], index=["Student1","Student2","Student3"])
df
def getList(dict):
return list(dict.keys())
qubitVal = {0: [1,0], 1: [0,1]}
values = getList(counts)
if(len(values) == 1):
print("They are not entangled")
elif(len(values) == 4):
firstStr = values[0]
secondStr = values[1]
thirdStr = values[2]
fourthStr = values[3]
print(firstStr,secondStr,thirdStr,fourthStr)
first1 = int(firstStr[0])
first2 = int(firstStr[1])
second1 = int(secondStr[0])
second2 =int(secondStr[1])
third1 = int(thirdStr[0])
third2 = int(thirdStr[1])
fourth1 = int(fourthStr[0])
fourth2 = int(fourthStr[1])
firstArr = np.array([qubitVal[first1], qubitVal[first2]])
secondArr = np.array([qubitVal[second1], qubitVal[second2]])
thirdArr = np.array([qubitVal[third1], qubitVal[third2]])
fourthArr = np.array([qubitVal[fourth1], qubitVal[fourth2]])
firstTensor = np.tensordot(firstArr[0], firstArr[1], axes=0)
secondTensor = np.tensordot(secondArr[0], secondArr[1], axes=0)
thirdTensor = np.tensordot(thirdArr[0], thirdArr[1], axes=0)
fourthTensor = np.tensordot(fourthArr[0], fourthArr[1], axes=0)
print("Tensors: ",firstTensor, " HI ",secondTensor,thirdTensor,fourthTensor)
column1 = np.add(firstTensor,secondTensor)
column2 = np.add(thirdTensor, fourthTensor)
print("AB: ",column1," CD: ",column2)
column = np.add(column1,column2)
print(column)
else:
firstStr = values[0]
secondStr = values[1]
print(firstStr)
print(secondStr)
first1 = int(firstStr[0])
first2 = int(firstStr[1])
second1 = int(secondStr[0])
second2 = int(secondStr[1])
firstArr = np.array([qubitVal[first1], qubitVal[first2]])
secondArr = np.array([qubitVal[second1], qubitVal[second2]])
firstTensor= np.tensordot(firstArr[0], firstArr[1], axes=0)
secondTensor = np.tensordot(secondArr[0], secondArr[1], axes=0)
print("first: ",firstTensor)
print("second: ",secondTensor)
print("final: ")
column = np.add(firstTensor,secondTensor)
print(column)
abVal = column[0]
cdVal = column[1]
aVal = abVal[0]
bVal = abVal[1]
cVal = cdVal[0]
dVal = cdVal[1]
if(aVal*dVal!=bVal*cVal):
print("They are entangled")
else:
print("Not Entangled")
def getList(dict):
return list(dict.keys())
# NOTE: Checks if a qubit value is 0 then return a matrix with [1,0] similarly for 1 with [0,1]
qubitVal = {0: [1,0], 1: [0,1]}
# NOTE: Upon analysis the measurement returned by the QC are also present in the bell state of the qc
# NOTE: For example if the counts output 00 and 01
values = getList(counts) # NOTE: Returns the measurement counts of the circuit and takes the key values ie 00 and 01 and converts it to a list using a function I created
if(len(values) == 1):
print("They are not entangled")
else:
# NOTE: Stores the first and second values as strings returned by counts for example: 00 and 01
firstStr = values[0]
secondStr = values[1]
# NOTE: Seperates the digits and stores them as integers
first1 = int(firstStr[0])
first2 = int(firstStr[1])
second1 = int(secondStr[0])
second2 = int(secondStr[1])
# NOTE: Creates a 2x2 matrix to store ___
firstArr = np.array([qubitVal[first1], qubitVal[first2]])
secondArr = np.array([qubitVal[second1], qubitVal[second2]])
# if(second1==1):
# subtract = True
# NOTE: Performs the tensor product for the ___ for both the first and second values
firstTensor= np.tensordot(firstArr[0], firstArr[1], axes=0)
print("first: ", firstArr, "first array first position: ", firstArr[0],"first array second position: ", firstArr[1])
print("second: ",secondArr,"second array first position: ", secondArr[0], "second array second position: ",secondArr[1])
secondTensor = np.tensordot(secondArr[0], secondArr[1], axes=0)
# print("first: ",firstTensor)
# print("second: ",secondTensor)
# NOTE: Condition to check if counts returns 4 measurements in which case we repeat the process for the 3rd and 4th measurements
if(len(values) == 4):
thirdStr = values[2]
fourthStr = values[3]
third1 = int(thirdStr[0])
third2 = int(thirdStr[1])
fourth1 = int(fourthStr[0])
fourth2 = int(fourthStr[1])
thirdArr = np.array([qubitVal[third1], qubitVal[third2]])
fourthArr = np.array([qubitVal[fourth1], qubitVal[fourth2]])
thirdTensor = np.tensordot(thirdArr[0], thirdArr[1], axes=0)
fourthTensor = np.tensordot(fourthArr[0], fourthArr[1], axes=0)
print(f"Tensors: {firstTensor}\n ,{secondTensor}\n,{thirdTensor}\n,{fourthTensor}\n")
column1 = np.add(firstTensor,secondTensor)
column2 = np.add(thirdTensor, fourthTensor)
print("AB: ",column1," CD: ",column2)
column = np.add(column1,column2)
print(column)
else:
print("first: ",firstTensor)
print("second: ",secondTensor)
print("final: ")
# NOTE: adds the two tensorproducts to give our column vector
# if(subtract==True):
# column = np.subtract(firstTensor,secondTensor)
# else:
column = np.add(firstTensor,secondTensor)
print(column)
# NOTE: Sets the value for our A,B,C,D values
abVal = column[0]
cdVal = column[1]
aVal = abVal[0]
bVal = abVal[1]
cVal = cdVal[0]
dVal = cdVal[1]
# NOTE: Checks our condition
if(aVal*dVal!=bVal*cVal):
print("They are entangled")
else:
print("Not Entangled")
def getList(dict):
return list(dict.keys())
# NOTE: Checks if a qubit value is 0 then return a matrix with [1,0] similarly for 1 with [0,1]
qubitVal = {0: [1,0], 1: [0,1]}
# NOTE: Upon analysis the measurement returned by the QC are also present in the bell state of the qc
# NOTE: For example if the counts output 00 and 01
values = getList(counts) # NOTE: Returns the measurement counts of the circuit and takes the key values ie 00 and 01 and converts it to a list using a function I created
if(len(values) == 1):
print("They are not entangled")
else:
# NOTE: Stores the first and second values as strings returned by counts for example: 00 and 01
firstStr = values[0]
secondStr = values[1]
# NOTE: Seperates the digits and stores them as an integer based on our previous example first1 woul store 0 and first2 would store 0
first1 = int(firstStr[0])
first2 = int(firstStr[1])
second1 = int(secondStr[0])
second2 = int(secondStr[1])
# NOTE: Creates a 2x2 matrix to store qubit values ex: first Arr would be [[1,0],[1,0]]
firstArr = np.array([qubitVal[first1], qubitVal[first2]])
secondArr = np.array([qubitVal[second1], qubitVal[second2]])
# NOTE: Performs the tensor product for the ___ for both the first and second values ex: firstTensor is the tensor product of [1,0] and [1,0]
firstTensor= np.tensordot(firstArr[0], firstArr[1], axes=0)
secondTensor = np.tensordot(secondArr[0], secondArr[1], axes=0)
# NOTE: Condition to check if counts returns 4 measurements in which case we repeat the process for the 3rd and 4th measurements
if(len(values) == 4):
thirdStr = values[2]
fourthStr = values[3]
third1 = int(thirdStr[0])
third2 = int(thirdStr[1])
fourth1 = int(fourthStr[0])
fourth2 = int(fourthStr[1])
thirdArr = np.array([qubitVal[third1], qubitVal[third2]])
fourthArr = np.array([qubitVal[fourth1], qubitVal[fourth2]])
thirdTensor = np.tensordot(thirdArr[0], thirdArr[1], axes=0)
fourthTensor = np.tensordot(fourthArr[0], fourthArr[1], axes=0)
column1 = np.add(firstTensor,secondTensor)
column2 = np.add(thirdTensor, fourthTensor)
column = np.add(column1,column2)
print(column)
else:
# NOTE: adds the two tensorproducts to give our column vector
column = np.add(firstTensor,secondTensor)
print(column)
# NOTE: Sets the value for our A,B,C,D values
abVal = column[0]
cdVal = column[1]
aVal = abVal[0]
bVal = abVal[1]
cVal = cdVal[0]
dVal = cdVal[1]
# NOTE: Checks our condition
if(aVal*dVal!=bVal*cVal):
print("They are entangled")
else:
print("Not Entangled")
# no constructor
# usee gate
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_st_qcs), ")")
t3_st_qcs[-1].draw("mpl") # only view trotter gates
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(t3_st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout)
print('Job ID', cal_job.job_id())
dt_now = datetime.datetime.now()
print(dt_now)
with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_jakarta_100step_20220412_171248_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
# set the target state
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
# mit_results = meas_fitter.filter.apply(job.result()) # apply QREM
rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq')
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
from qiskit import *
%matplotlib inline
import numpy as np
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure([0,1],[0,1])
qc.draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
result = execute(qc,backend).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(qc))
counts = result.get_counts(qc)
legenda = ['Meu resultado']
plot_histogram(counts,color='red' ,legend=legenda)
IBMQ.load_account()
provedor = IBMQ.get_provider('ibm-q')
backend = provedor.get_backend('ibmq_valencia')
job = execute(qc,backend)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result2 = job.result()
counts2 = result2.get_counts(qc)
legenda = ['Simulador','CQ Real']
plot_histogram([counts,counts2],color=['red','green'] ,legend=legenda)
qc2 = QuantumCircuit(2,2)
qc2.h(0)
qc2.cx(0,1)
backend_st = Aer.get_backend('statevector_simulator')
result3 = execute(qc2, backend_st).result()
statevector = result3.get_statevector()
from qiskit.tools.visualization import plot_state_city
plot_state_city(statevector)
from qiskit.tools.visualization import plot_state_paulivec
plot_state_paulivec(statevector)
from qiskit.tools.visualization import plot_state_hinton
plot_state_hinton(statevector)
from qiskit.tools.visualization import plot_bloch_multivector
plot_bloch_multivector(statevector)
%matplotlib notebook
# Repare que não está escrito inline como geralmente
plot_bloch_multivector(statevector)
# Para voltar ao normal é necessário apenas rodar o comando original
%matplotlib inline
from qiskit.tools.visualization import plot_bloch_vector
plot_bloch_vector([1,0,0])
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
"""Add custom gates to the session EquivalenceLibrary instance.
NOTE: sel is global, so just import this file before calling transpile.
"""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel
from qiskit.circuit.library.standard_gates import CXGate, SwapGate, XXPlusYYGate
# https://arxiv.org/pdf/2110.11537.pdf
cx_decomp = QuantumCircuit(2)
cx_decomp.u(np.pi / 2, -np.pi / 2, 0, 0)
cx_decomp.u(np.pi / 2, np.pi, -np.pi / 2, 1)
cx_decomp.append(XXPlusYYGate(-np.pi / 2), [0, 1])
cx_decomp.u(np.pi, -np.pi / 2, np.pi / 2, 0)
cx_decomp.u(0, 0, np.pi, 1)
cx_decomp.append(XXPlusYYGate(-np.pi / 2), [0, 1])
cx_decomp.u(np.pi / 2, -np.pi / 2, -3 * np.pi / 2, 0)
cx_decomp.u(0, -np.pi / 2, -np.pi, 1)
sel.add_equivalence(CXGate(), cx_decomp)
swap_decomp = QuantumCircuit(2)
swap_decomp.append(XXPlusYYGate(-np.pi / 2, 0), [0, 1])
swap_decomp.rx(-np.pi / 2, 0)
swap_decomp.rx(-np.pi / 2, 1)
swap_decomp.append(XXPlusYYGate(-np.pi / 2), [0, 1])
swap_decomp.rx(np.pi / 2, 0)
swap_decomp.rx(np.pi / 2, 1)
swap_decomp.ry(-np.pi / 2, 0)
swap_decomp.ry(-np.pi / 2, 1)
swap_decomp.append(XXPlusYYGate(-np.pi / 2), [0, 1])
swap_decomp.ry(np.pi / 2, 0)
swap_decomp.ry(np.pi / 2, 1)
sel.add_equivalence(SwapGate(), swap_decomp)
# bb = transpile(
# circ, basis_gates=["u", "xx_plus_yy"], coupling_map=topo, optimization_level=3
# )
# bb.draw(output="mpl")
#######################
# NOTE this is a hack :) #
# https://github.com/Qiskit/qiskit-terra/issues/9485
# add I = U(0, 0, 0) to the equivalence library
# from qiskit.circuit.equivalence_library import SessionEquivalenceLibrary as sel
# from qiskit import QuantumCircuit
# from qiskit.circuit.library import IGate
# qc = QuantumCircuit(1)
# qc.u(0, 0, 0, 0)
# sel.add_equivalence(IGate(), qc)
|
https://github.com/AnikenC/JaxifiedQiskit
|
AnikenC
|
# All Imports
import numpy as np
import jax
import jax.numpy as jnp
from jax.numpy.linalg import norm
import qiskit.pulse as pulse
from qiskit_dynamics.array import Array
from library.utils import PauliToQuditOperator, TwoQuditHamiltonian
from library.new_sims import JaxedSolver
Array.set_default_backend('jax')
jax.config.update('jax_enable_x64', True)
jax.config.update('jax_platform_name', 'cpu')
# Testing out the TwoQuditBackend Functionality
dt = 1/4.5e9
atol = 1e-2
rtol = 1e-4
batchsize = 400
t_linspace = np.linspace(0.0, 400e-9, 11)
t_span = np.array([t_linspace[0], t_linspace[-1]])
qudit_dim = 3
q_end = TwoQuditHamiltonian(
qudit_dim=qudit_dim,
dt=dt
)
solver = q_end.solver
ham_ops = q_end.ham_ops
ham_chans = q_end.ham_chans
chan_freqs = q_end.chan_freqs
# Make the Custom Schedule Construction Function
amp_vals = jnp.linspace(0.5, 0.99, batchsize, dtype=jnp.float64).reshape(-1, 1)
sigma_vals = jnp.linspace(20, 80, batchsize, dtype=jnp.int8).reshape(-1, 1)
freq_vals = jnp.linspace(-0.5, 0.5, batchsize, dtype=jnp.float64).reshape(-1, 1) * 1e6
batch_params = jnp.concatenate((amp_vals, sigma_vals, freq_vals), axis=-1)
init_y0 = jnp.ones(qudit_dim ** 2, dtype=jnp.complex128)
init_y0 /= norm(init_y0)
batch_y0 = jnp.tile(init_y0, (batchsize, 1))
batch_str = ["XX", "IX", "YZ", "ZY"] * 100
print(f"initial statevec: {init_y0}")
print(f"statevector * hc: {init_y0 @ init_y0.conj().T}")
def standard_func(params):
amp, sigma, freq = params
# Here we use a Drag Pulse as defined in qiskit pulse as its already a Scalable Symbolic Pulse
special_pulse = pulse.Drag(
duration=320,
amp=amp,
sigma=sigma,
beta=0.1,
angle=0.1,
limit_amplitude=False
)
with pulse.build(default_alignment='sequential') as sched:
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
pulse.shift_frequency(freq, d0)
pulse.play(special_pulse, d0)
pulse.shift_frequency(freq, d1)
pulse.play(special_pulse, d1)
pulse.shift_frequency(freq, u0)
pulse.play(special_pulse, u0)
pulse.shift_frequency(freq, u1)
pulse.play(special_pulse, u1)
return sched
# Make the JaxedSolver backend
j_solver = JaxedSolver(
schedule_func=standard_func,
solver=solver,
dt=dt,
carrier_freqs=chan_freqs,
ham_chans=ham_chans,
ham_ops=ham_ops,
t_span=t_span,
rtol=rtol,
atol=atol
)
j_solver.estimate2(batch_y0=batch_y0, batch_params=batch_params, batch_obs_str=batch_str)
%timeit j_solver.estimate2(batch_y0=batch_y0, batch_params=batch_params, batch_obs_str=batch_str)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
| |
https://github.com/JohnBurke4/qaoa_testing_framework
|
JohnBurke4
|
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
import numpy as np
import random
class CostHamiltonian:
circuit = {}
def __init__(self, numQubits, layers=1, costType='maxcut', problem=None):
self.numQubits = numQubits
self.costType = costType
self.layers = layers
self.problem = problem
def build(self):
self.circuit = {}
for l in range(0, self.layers):
if (self.costType == 'rz_maxcut'):
circuitDetails = self.__buildMaxcutLayer(self.problem, l)
self.circuit[l] = circuitDetails
elif (self.costType == 'ma_rz_maxcut'):
circuitDetails = self.__buildMAMaxcutLayer(self.problem, l)
self.circuit[l] = circuitDetails
elif (self.costType == 'two_local_real_maxcut'):
circuitDetails = self.__buildTwoLocalRealMaxcutLayer(self.problem, l)
self.circuit[l] = circuitDetails
elif (self.costType == "constant_maxcut"):
circuitDetails = self.__buildMaxcutConstantLayer(self.problem, l)
self.circuit[l] = circuitDetails
elif (self.costType == "ry_maxcut"):
circuitDetails = self.__buildRYMaxcutLayer(self.problem, l)
self.circuit[l] = circuitDetails
elif (self.costType == "ma_ry_maxcut"):
circuitDetails = self.__buildMARYMaxcutLayer(self.problem, l)
self.circuit[l] = circuitDetails
elif (self.costType == "rx_maxcut"):
circuitDetails = self.__buildRXMaxcutLayer(self.problem, l)
self.circuit[l] = circuitDetails
elif (self.costType == "ma_rx_maxcut"):
circuitDetails = self.__buildMARXMaxcutLayer(self.problem, l)
self.circuit[l] = circuitDetails
elif (self.costType == "cx_ry_maxcut"):
circuitDetails = self.__buildCXRYMaxcutLayer(self.problem, l)
self.circuit[l] = circuitDetails
elif (self.costType == "none"):
circuitDetails = self.__buildNoCircuit()
self.circuit[l] = circuitDetails
elif (self.costType == "3SAT"):
circuitDetails = self.__build3SATLayer(None, l)
self.circuit[l] = circuitDetails
elif (self.costType == "test_rz_maxcut"):
circuitDetails = self.__buildTestMaxcutLayer(self.problem, l)
self.circuit[l] = circuitDetails
return True
def getCircuitAtLayer(self, l):
return self.circuit[l]
def getAllCircuits(self):
return self.circuit
def __buildMaxcutConstantLayer(self, graph, l):
# theta = Parameter('cost_maxcut_' + str(l))
qc = QuantumCircuit(self.numQubits)
for edge in graph.edges():
qc.rzz(np.pi/len(graph.edges()), edge[0], edge[1])
return (qc, [])
def __buildMaxcutLayer(self, graph, l):
theta = Parameter('cost_maxcut_' + str(l))
qc = QuantumCircuit(self.numQubits)
for edge in graph.edges():
qc.rzz(theta, edge[0], edge[1])
return (qc, [theta])
def __buildMAMaxcutLayer(self, graph, l):
theta = [Parameter('cost_maxcut_' + str(l) + "_" + str(i)) for i in range(0, len(graph.edges()))]
qc = QuantumCircuit(self.numQubits)
i = 0
for edge in graph.edges():
qc.rzz(theta[i], edge[0], edge[1])
i+=1
return (qc, theta)
def __buildNoCircuit(self):
qc = QuantumCircuit(self.numQubits)
return (qc, [])
def __buildTwoLocalRealMaxcutLayer(self, graph, l):
theta = [Parameter('cost_maxcut_' + str(l) + "_" + str(i)) for i in range(0, 3*len(graph.edges()))]
qc = QuantumCircuit(self.numQubits)
i = 0
for edge in graph.edges():
qc.ry(theta[i], edge[0])
i+=1
qc.cx(edge[0], edge[1])
qc.ry(theta[i], edge[0])
i+=1
qc.ry(theta[i], edge[1])
i+=1
return (qc, theta)
def __buildRYMaxcutLayer(self, graph, l):
theta = Parameter('cost_maxcut_' + str(l))
qc = QuantumCircuit(self.numQubits)
i = 0
edges = list(graph.edges())
v = len(graph.nodes)
orderedEdges = []
rightEdges = []
# j = list(range(1, v))
for e in edges:
e1 = e[0]
e2 = e[1]
if (e1 > e2):
rightEdges.append((e2, e1))
else:
rightEdges.append(e)
for e in rightEdges:
e1 = e[0]
e2 = e[1]
orderedEdges.append((v - 1 - e2, v - 1 - e1))
orderedEdges = rightEdges
orderedEdges.sort(key=lambda x:x[0], reverse=False)
orderedEdges.sort(key=lambda x:x[1], reverse=False)
print(orderedEdges)
counts = [0] * v
for e in orderedEdges:
counts[e[1]] += 1
print(counts)
for edge in orderedEdges:
qc.cx(edge[0], edge[1])
qc.ry(theta,edge[1])
qc.cx(edge[0], edge[1])
return (qc, [theta])
def __buildMARYMaxcutLayer(self, graph, l):
theta = [Parameter('cost_maxcut_' + str(l) + "_" + str(i)) for i in range(0, len(graph.edges()))]
qc = QuantumCircuit(self.numQubits)
i = 0
edges = list(graph.edges())
v = len(graph.nodes)
orderedEdges = []
rightEdges = []
# j = list(range(1, v))
for e in edges:
e1 = e[0]
e2 = e[1]
if (e1 > e2):
rightEdges.append((e2, e1))
else:
rightEdges.append(e)
for e in rightEdges:
e1 = e[0]
e2 = e[1]
orderedEdges.append((v - 1 - e2, v - 1 - e1))
orderedEdges = rightEdges
# for e in rightEdges.copy():
# # print(e)
# e1 = e[0]
# e2 = e[1]
# if (e2 in j):
# rightEdges.remove(e)
# orderedEdges.append(e)
# j.remove(e2)
# # print(len(orderedEdges))
# orderedEdges.sort(key=lambda x:x[1], reverse=False)
# orderedEdges = orderedEdges + rightEdges
# # print(orderedEdges)
# print(orderedEdges)
orderedEdges.sort(key=lambda x:x[0], reverse=False)
orderedEdges.sort(key=lambda x:x[1], reverse=False)
print(orderedEdges)
counts = [0] * v
for e in orderedEdges:
counts[e[1]] += 1
print(counts)
# qc.cx(0, 1)
# qc.ry(np.pi/2,1)
# qc.cx(0, 1)
# qc.cx(0, 2)
# qc.ry(-np.pi/2,2)
# qc.cx(0, 2)
for edge in orderedEdges:
qc.cx(edge[0], edge[1])
qc.ry(theta[i],edge[1])
qc.cx(edge[0], edge[1])
i+=1
return (qc, theta)
def __buildRXMaxcutLayer(self, graph, l):
theta = Parameter('cost_maxcut_' + str(l))
qc = QuantumCircuit(self.numQubits)
for edge in graph.edges():
qc.rxx(theta, edge[0], edge[1])
return (qc, [theta])
def __buildMARXMaxcutLayer(self, graph, l):
theta = [Parameter('cost_maxcut_' + str(l) + "_" + str(i)) for i in range(0, len(graph.edges()))]
qc = QuantumCircuit(self.numQubits)
i = 0
for edge in graph.edges():
qc.rxx(theta[i], edge[0], edge[1])
i+=1
return (qc, theta)
def __buildCXRYMaxcutLayer(self, graph, l):
theta = Parameter('cost_maxcut_' + str(l))
i = 0
qc = QuantumCircuit(self.numQubits)
for edge in graph.edges():
qc.cx(edge[0], edge[1])
qc.ry(theta, edge[1])
qc.cx(edge[0], edge[1])
i+=1
return (qc, [theta])
def __buildMACXRYMaxcutLayer(self, graph, l):
theta = [Parameter('cost_maxcut_' + str(l) + "_" + str(i)) for i in range(0, len(graph.edges()))]
i = 0
qc = QuantumCircuit(self.numQubits)
for edge in graph.edges():
qc.cx(edge[0], edge[1])
qc.ry(theta[i], edge[1])
qc.cx(edge[0], edge[1])
i+=1
return (qc, theta)
def __build3SATLayer(self, clauses, l):
theta = Parameter('cost_maxcut_' + str(l))
qc = QuantumCircuit(self.numQubits)
qc.h([0, 1, 2])
# clause 1
qc.x([0, 1, 2])
qc.mct([0, 1, 2], 3)
qc.rz(theta, 3)
qc.mct([0, 1, 2], 3)
qc.x([0, 1, 2])
# clause 2
qc.x([1])
qc.mct([0, 1, 2], 3)
qc.rz(theta, 3)
qc.mct([0, 1, 2], 3)
qc.x([1])
# clause 3
qc.x([2])
qc.mct([0, 1, 2], 3)
qc.rz(theta, 3)
qc.mct([0, 1, 2], 3)
qc.x([2])
# clause 4
qc.x([2, 3])
qc.mct([0, 1, 2], 3)
qc.rz(theta, 3)
qc.mct([0, 1, 2], 3)
qc.x([2, 3])
# clause 5
qc.x([3])
qc.mct([0, 1, 2], 3)
qc.rz(theta, 3)
qc.mct([0, 1, 2], 3)
qc.x([3])
# # clause 6
# qc.x([1, 2])
# qc.mct([0, 1, 2], 3)
# qc.rz(theta, 3)
# qc.mct([0, 1, 2], 3)
# qc.x([1, 2])
# clause 7
qc.mct([0, 1, 2], 3)
qc.rz(theta, 3)
qc.mct([0, 1, 2], 3)
return (qc, [theta])
def __buildTestMaxcutLayer(self, graph, l):
theta1 = Parameter('cost_maxcut_1_' + str(l))
theta2 = Parameter('cost_maxcut_2_' + str(l))
qc = QuantumCircuit(self.numQubits)
for edge in graph.edges():
qc.rz(theta2, edge[0])
qc.rz(theta2, edge[1])
qc.rzz(theta1, edge[0], edge[1])
return (qc, [theta1, theta2])
|
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
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure(0, 0)
circ.measure(1, 1)
circ.draw('mpl')
from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration('h', [0], h_q0)
from qiskit import transpile
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
circ = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
circ = QuantumCircuit(1, 1)
custom_gate = Gate('my_custom_gate', 1, [3.14, 1])
# 3.14 is an arbitrary parameter for demonstration
circ.append(custom_gate, [0])
circ.measure(0, 0)
circ.draw('mpl')
with pulse.build(backend, name='custom') as my_schedule:
pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0))
circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])
# Alternatively: circ.add_calibration(custom_gate, [0], my_schedule)
circ = transpile(circ, backend)
circ.draw('mpl', idle_wires=False)
circ = QuantumCircuit(2, 2)
circ.append(custom_gate, [1])
from qiskit import QiskitError
try:
circ = transpile(circ, backend)
except QiskitError as e:
print(e)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.qasm3
program = """
OPENQASM 3.0;
include "stdgates.inc";
input float[64] a;
qubit[3] q;
bit[2] mid;
bit[3] out;
let aliased = q[0:1];
gate my_gate(a) c, t {
gphase(a / 2);
ry(a) c;
cx c, t;
}
gate my_phase(a) c {
ctrl @ inv @ gphase(a) c;
}
my_gate(a * 2) aliased[0], q[{1, 2}][0];
measure q[0] -> mid[0];
measure q[1] -> mid[1];
while (mid == "00") {
reset q[0];
reset q[1];
my_gate(a) q[0], q[1];
my_phase(a - pi/2) q[1];
mid[0] = measure q[0];
mid[1] = measure q[1];
}
if (mid[0]) {
let inner_alias = q[{0, 1}];
reset inner_alias;
}
out = measure q;
"""
circuit = qiskit.qasm3.loads(program)
circuit.draw("mpl")
|
https://github.com/krishphys/LiH_Variational_quantum_eigensolver
|
krishphys
|
from qiskit import BasicAer, Aer, IBMQ
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.initial_states import Zero
from qiskit.aqua.components.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA
from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ
from qiskit.aqua.operators import WeightedPauliOperator, Z2Symmetries
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.circuit.library import EfficientSU2
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import QuantumError, ReadoutError
from qiskit.providers.aer.noise.errors import pauli_error
from qiskit.providers.aer.noise.errors import depolarizing_error
from qiskit.providers.aer.noise.errors import thermal_relaxation_error
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
from qiskit.providers.aer import noise
provider = IBMQ.load_account()
import numpy as np
import matplotlib.pyplot as plt
from functools import partial
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Classically solve for the lowest eigenvalue
# This is used just to compare how well you VQE approximation is performing
def exact_solver(qubitOp,shift):
ee = ExactEigensolver(qubitOp)
result = ee.run()
ref = result['energy']+shift
print('Reference value: {}'.format(ref))
return ref
# Define your function for computing the qubit operations of LiH
def compute_LiH_qubitOp(map_type, inter_dist, basis='sto3g'):
# Specify details of our molecule
driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 ' + str(inter_dist), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis=basis)
# Compute relevant 1 and 2 body integrals.
molecule = driver.run()
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
print("HF energy: {}".format(molecule.hf_energy - molecule.nuclear_repulsion_energy))
print("# of electrons: {}".format(num_particles))
print("# of spin orbitals: {}".format(num_spin_orbitals))
# Please be aware that the idx here with respective to original idx
freeze_list = [0]
remove_list = [-3, -2] # negative number denotes the reverse order
# Prepare full idx of freeze_list and remove_list
# Convert all negative idx to positive
remove_list = [x % molecule.num_orbitals for x in remove_list]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
# Update the idx in remove_list of the idx after frozen, since the idx of orbitals are changed after freezing
remove_list = [x - len(freeze_list) for x in remove_list]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
# Prepare fermionic hamiltonian with orbital freezing and eliminating, and then map to qubit hamiltonian
# and if PARITY mapping is selected, reduction qubits
energy_shift = 0.0
qubit_reduction = True if map_type == 'parity' else False
ferOp = FermionicOperator(h1=h1, h2=h2)
if len(freeze_list) > 0:
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)
num_spin_orbitals -= len(freeze_list)
num_particles -= len(freeze_list)
if len(remove_list) > 0:
ferOp = ferOp.fermion_mode_elimination(remove_list)
num_spin_orbitals -= len(remove_list)
qubitOp = ferOp.mapping(map_type=map_type)
qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles) if qubit_reduction else qubitOp
qubitOp.chop(10**-10)
#Overall energy shift:
shift = energy_shift + nuclear_repulsion_energy
return qubitOp, num_spin_orbitals, num_particles, qubit_reduction, shift
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
def get_ground_State(map_type,inter_dist,init_state,ansatz,optimizer_select):
qubitOp, num_spin_orbitals, num_particles, \
qubit_reduction,shift = compute_LiH_qubitOp(map_type,inter_dist=inter_dist)
#Initial State
if init_state == "Zero":
initState = Zero(qubitOp.num_qubits)
elif init_state == "HartreeFock":
initState = HartreeFock(
num_spin_orbitals,
num_particles,
qubit_mapping=map_type,
two_qubit_reduction=qubit_reduction
)
#Ansatz
depth = 10
if ansatz == "RY":
var_form = EfficientSU2(qubitOp.num_qubits,entanglement='full',su2_gates=['ry'],reps = 1,\
initial_state=initState)
elif ansatz == "RYRZ":
var_form = EfficientSU2(qubitOp.num_qubits,entanglement='full',su2_gates=['ry','rz'],reps = 1,\
initial_state=initState)
elif ansatz == "SwapRZ":
var_form = EfficientSU2(qubitOp.num_qubits,entanglement='full',su2_gates=['swap','rz'],reps = 1,\
initial_state=initState)
elif ansatz == "UCCSD":
var_form = UCCSD(
num_orbitals=num_spin_orbitals,
num_particles=num_particles,
initial_state=initState,
qubit_mapping=map_type
)
#Optimizer
if optimizer_select == "COBYLA":
optimizer = COBYLA(maxiter = 1000)
elif optimizer_select == "SPSA":
optimizer = SPSA(max_trials = 1000)
#Noise model
backend_ = "qasm_simulator"
shots = 1000
provider = IBMQ.get_provider(hub='ibm-q')
backend = Aer.get_backend(backend_)
device = provider.get_backend("ibmq_vigo")
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device.properties())
quantum_instance = QuantumInstance(backend=backend,
shots=shots,
noise_model=noise_model,
coupling_map=coupling_map,
measurement_error_mitigation_cls=CompleteMeasFitter,
cals_matrix_refresh_period=30)
#Running VQE
vqe = VQE(qubitOp, var_form, optimizer, callback = store_intermediate_result)
vqe_result = np.real(vqe.run(quantum_instance)['eigenvalue'] + shift)
callbackDict = {"counts":counts,"values":values,"params":params,"deviation":deviation}
return vqe_result,callbackDict,qubitOp,shift
map_type = "parity"
inter_dist = 1.6
initialStateList = ["Zero","HartreeFock"]
ansatzList = ["UCCSD","RY","RYRZ","SwapRZ"]
optimizerList = ["COBYLA","SPSA"]
import itertools
choices = list(itertools.product(initialStateList,ansatzList,optimizerList))
choices[8:]
selected_choices = choices[8:]
len(selected_choices)
selected_choices[0]
map_type = "parity"
inter_dist = 1.6
for i in selected_choices:
counts = []
values =[]
params =[]
deviation = []
init_state = i[0]
ansatz = i[1]
optimizer_select = i[2]
chosen = str({"Optimizer ":optimizer_select,"Ansatz ":ansatz,"Initial State ":init_state})
vqe_result,callbackDict,qubitOp,shift = get_ground_State(map_type,inter_dist,init_state,ansatz,optimizer_select)
ref = exact_solver(qubitOp , shift)
energy_error = np.abs(np.real(ref) - vqe_result)
print("Energy Error :",energy_error)
# Calculating energy error
vqe_energies = np.real(callbackDict["values"]) + shift
energy_errors = np.abs(np.real(ref) - vqe_energies)
plt.plot(callbackDict["counts"] , energy_errors)
plt.xlabel('Counts')
plt.ylabel('Energy Error/ Hartree')
plt.title("Choices : "+chosen)
plt.show()
print("--------------------------------")
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Basic rescheduling functions which take schedule or instructions and return new schedules."""
import warnings
from collections import defaultdict
from typing import List, Optional, Iterable, Union, Type
import numpy as np
from qiskit.pulse import channels as chans, exceptions, instructions
from qiskit.pulse.channels import ClassicalIOChannel
from qiskit.pulse.exceptions import PulseError
from qiskit.pulse.exceptions import UnassignedDurationError
from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap
from qiskit.pulse.instructions import directives
from qiskit.pulse.schedule import Schedule, ScheduleBlock, ScheduleComponent
def block_to_schedule(block: ScheduleBlock) -> Schedule:
"""Convert ``ScheduleBlock`` to ``Schedule``.
Args:
block: A ``ScheduleBlock`` to convert.
Returns:
Scheduled pulse program.
Raises:
UnassignedDurationError: When any instruction duration is not assigned.
PulseError: When the alignment context duration is shorter than the schedule duration.
.. note:: This transform may insert barriers in between contexts.
"""
if not block.is_schedulable():
raise UnassignedDurationError(
"All instruction durations should be assigned before creating `Schedule`."
"Please check `.parameters` to find unassigned parameter objects."
)
schedule = Schedule.initialize_from(block)
for op_data in block.blocks:
if isinstance(op_data, ScheduleBlock):
context_schedule = block_to_schedule(op_data)
if hasattr(op_data.alignment_context, "duration"):
# context may have local scope duration, e.g. EquispacedAlignment for 1000 dt
post_buffer = op_data.alignment_context.duration - context_schedule.duration
if post_buffer < 0:
raise PulseError(
f"ScheduleBlock {op_data.name} has longer duration than "
"the specified context duration "
f"{context_schedule.duration} > {op_data.duration}."
)
else:
post_buffer = 0
schedule.append(context_schedule, inplace=True)
# prevent interruption by following instructions.
# padding with delay instructions is no longer necessary, thanks to alignment context.
if post_buffer > 0:
context_boundary = instructions.RelativeBarrier(*op_data.channels)
schedule.append(context_boundary.shift(post_buffer), inplace=True)
else:
schedule.append(op_data, inplace=True)
# transform with defined policy
return block.alignment_context.align(schedule)
def compress_pulses(schedules: List[Schedule]) -> List[Schedule]:
"""Optimization pass to replace identical pulses.
Args:
schedules: Schedules to compress.
Returns:
Compressed schedules.
"""
existing_pulses = []
new_schedules = []
for schedule in schedules:
new_schedule = Schedule.initialize_from(schedule)
for time, inst in schedule.instructions:
if isinstance(inst, instructions.Play):
if inst.pulse in existing_pulses:
idx = existing_pulses.index(inst.pulse)
identical_pulse = existing_pulses[idx]
new_schedule.insert(
time,
instructions.Play(identical_pulse, inst.channel, inst.name),
inplace=True,
)
else:
existing_pulses.append(inst.pulse)
new_schedule.insert(time, inst, inplace=True)
else:
new_schedule.insert(time, inst, inplace=True)
new_schedules.append(new_schedule)
return new_schedules
def flatten(program: Schedule) -> Schedule:
"""Flatten (inline) any called nodes into a Schedule tree with no nested children.
Args:
program: Pulse program to remove nested structure.
Returns:
Flatten pulse program.
Raises:
PulseError: When invalid data format is given.
"""
if isinstance(program, Schedule):
flat_sched = Schedule.initialize_from(program)
for time, inst in program.instructions:
flat_sched.insert(time, inst, inplace=True)
return flat_sched
else:
raise PulseError(f"Invalid input program {program.__class__.__name__} is specified.")
def inline_subroutines(program: Union[Schedule, ScheduleBlock]) -> Union[Schedule, ScheduleBlock]:
"""Recursively remove call instructions and inline the respective subroutine instructions.
Assigned parameter values, which are stored in the parameter table, are also applied.
The subroutine is copied before the parameter assignment to avoid mutation problem.
Args:
program: A program which may contain the subroutine, i.e. ``Call`` instruction.
Returns:
A schedule without subroutine.
Raises:
PulseError: When input program is not valid data format.
"""
if isinstance(program, Schedule):
return _inline_schedule(program)
elif isinstance(program, ScheduleBlock):
return _inline_block(program)
else:
raise PulseError(f"Invalid program {program.__class__.__name__} is specified.")
def _inline_schedule(schedule: Schedule) -> Schedule:
"""A helper function to inline subroutine of schedule.
.. note:: If subroutine is ``ScheduleBlock`` it is converted into Schedule to get ``t0``.
"""
ret_schedule = Schedule.initialize_from(schedule)
for t0, inst in schedule.children:
# note that schedule.instructions unintentionally flatten the nested schedule.
# this should be performed by another transformer node.
if isinstance(inst, instructions.Call):
# bind parameter
subroutine = inst.assigned_subroutine()
# convert into schedule if block is given
if isinstance(subroutine, ScheduleBlock):
subroutine = block_to_schedule(subroutine)
# recursively inline the program
inline_schedule = _inline_schedule(subroutine)
ret_schedule.insert(t0, inline_schedule, inplace=True)
elif isinstance(inst, Schedule):
# recursively inline the program
inline_schedule = _inline_schedule(inst)
ret_schedule.insert(t0, inline_schedule, inplace=True)
else:
ret_schedule.insert(t0, inst, inplace=True)
return ret_schedule
def _inline_block(block: ScheduleBlock) -> ScheduleBlock:
"""A helper function to inline subroutine of schedule block.
.. note:: If subroutine is ``Schedule`` the function raises an error.
"""
ret_block = ScheduleBlock.initialize_from(block)
for inst in block.blocks:
if isinstance(inst, instructions.Call):
# bind parameter
subroutine = inst.assigned_subroutine()
if isinstance(subroutine, Schedule):
raise PulseError(
f"A subroutine {subroutine.name} is a pulse Schedule. "
"This program cannot be inserted into ScheduleBlock because "
"t0 associated with instruction will be lost."
)
# recursively inline the program
inline_block = _inline_block(subroutine)
ret_block.append(inline_block, inplace=True)
elif isinstance(inst, ScheduleBlock):
# recursively inline the program
inline_block = _inline_block(inst)
ret_block.append(inline_block, inplace=True)
else:
ret_block.append(inst, inplace=True)
return ret_block
def remove_directives(schedule: Schedule) -> Schedule:
"""Remove directives.
Args:
schedule: A schedule to remove compiler directives.
Returns:
A schedule without directives.
"""
return schedule.exclude(instruction_types=[directives.Directive])
def remove_trivial_barriers(schedule: Schedule) -> Schedule:
"""Remove trivial barriers with 0 or 1 channels.
Args:
schedule: A schedule to remove trivial barriers.
Returns:
schedule: A schedule without trivial barriers
"""
def filter_func(inst):
return isinstance(inst[1], directives.RelativeBarrier) and len(inst[1].channels) < 2
return schedule.exclude(filter_func)
def align_measures(
schedules: Iterable[ScheduleComponent],
inst_map: Optional[InstructionScheduleMap] = None,
cal_gate: str = "u3",
max_calibration_duration: Optional[int] = None,
align_time: Optional[int] = None,
align_all: Optional[bool] = True,
) -> List[Schedule]:
"""Return new schedules where measurements occur at the same physical time.
This transformation will align the first :class:`.Acquire` on
every channel to occur at the same time.
Minimum measurement wait time (to allow for calibration pulses) is enforced
and may be set with ``max_calibration_duration``.
By default only instructions containing a :class:`.AcquireChannel` or :class:`.MeasureChannel`
will be shifted. If you wish to keep the relative timing of all instructions in the schedule set
``align_all=True``.
This method assumes that ``MeasureChannel(i)`` and ``AcquireChannel(i)``
correspond to the same qubit and the acquire/play instructions
should be shifted together on these channels.
.. code-block::
from qiskit import pulse
from qiskit.pulse import transforms
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
a0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
sched = pulse.Schedule()
sched.append(pulse.Play(pulse.Constant(10, 0.5), d0), inplace=True)
sched.append(pulse.Play(pulse.Constant(10, 1.), m0).shift(sched.duration), inplace=True)
sched.append(pulse.Acquire(20, a0, mem0).shift(sched.duration), inplace=True)
sched_shifted = sched << 20
aligned_sched, aligned_sched_shifted = transforms.align_measures([sched, sched_shifted])
assert aligned_sched == aligned_sched_shifted
If it is desired to only shift acquisition and measurement stimulus instructions
set the flag ``align_all=False``:
.. code-block::
aligned_sched, aligned_sched_shifted = transforms.align_measures(
[sched, sched_shifted],
align_all=False,
)
assert aligned_sched != aligned_sched_shifted
Args:
schedules: Collection of schedules to be aligned together
inst_map: Mapping of circuit operations to pulse schedules
cal_gate: The name of the gate to inspect for the calibration time
max_calibration_duration: If provided, inst_map and cal_gate will be ignored
align_time: If provided, this will be used as final align time.
align_all: Shift all instructions in the schedule such that they maintain
their relative alignment with the shifted acquisition instruction.
If ``False`` only the acquisition and measurement pulse instructions
will be shifted.
Returns:
The input list of schedules transformed to have their measurements aligned.
Raises:
PulseError: If the provided alignment time is negative.
"""
def get_first_acquire_times(schedules):
"""Return a list of first acquire times for each schedule."""
acquire_times = []
for schedule in schedules:
visited_channels = set()
qubit_first_acquire_times = defaultdict(lambda: None)
for time, inst in schedule.instructions:
if isinstance(inst, instructions.Acquire) and inst.channel not in visited_channels:
visited_channels.add(inst.channel)
qubit_first_acquire_times[inst.channel.index] = time
acquire_times.append(qubit_first_acquire_times)
return acquire_times
def get_max_calibration_duration(inst_map, cal_gate):
"""Return the time needed to allow for readout discrimination calibration pulses."""
# TODO (qiskit-terra #5472): fix behavior of this.
max_calibration_duration = 0
for qubits in inst_map.qubits_with_instruction(cal_gate):
cmd = inst_map.get(cal_gate, qubits, np.pi, 0, np.pi)
max_calibration_duration = max(cmd.duration, max_calibration_duration)
return max_calibration_duration
if align_time is not None and align_time < 0:
raise exceptions.PulseError("Align time cannot be negative.")
first_acquire_times = get_first_acquire_times(schedules)
# Extract the maximum acquire in every schedule across all acquires in the schedule.
# If there are no acquires in the schedule default to 0.
max_acquire_times = [max(0, *times.values()) for times in first_acquire_times]
if align_time is None:
if max_calibration_duration is None:
if inst_map:
max_calibration_duration = get_max_calibration_duration(inst_map, cal_gate)
else:
max_calibration_duration = 0
align_time = max(max_calibration_duration, *max_acquire_times)
# Shift acquires according to the new scheduled time
new_schedules = []
for sched_idx, schedule in enumerate(schedules):
new_schedule = Schedule.initialize_from(schedule)
stop_time = schedule.stop_time
if align_all:
if first_acquire_times[sched_idx]:
shift = align_time - max_acquire_times[sched_idx]
else:
shift = align_time - stop_time
else:
shift = 0
for time, inst in schedule.instructions:
measurement_channels = {
chan.index
for chan in inst.channels
if isinstance(chan, (chans.MeasureChannel, chans.AcquireChannel))
}
if measurement_channels:
sched_first_acquire_times = first_acquire_times[sched_idx]
max_start_time = max(
sched_first_acquire_times[chan]
for chan in measurement_channels
if chan in sched_first_acquire_times
)
shift = align_time - max_start_time
if shift < 0:
warnings.warn(
"The provided alignment time is scheduling an acquire instruction "
"earlier than it was scheduled for in the original Schedule. "
"This may result in an instruction being scheduled before t=0 and "
"an error being raised."
)
new_schedule.insert(time + shift, inst, inplace=True)
new_schedules.append(new_schedule)
return new_schedules
def add_implicit_acquires(schedule: ScheduleComponent, meas_map: List[List[int]]) -> Schedule:
"""Return a new schedule with implicit acquires from the measurement mapping replaced by
explicit ones.
.. warning:: Since new acquires are being added, Memory Slots will be set to match the
qubit index. This may overwrite your specification.
Args:
schedule: Schedule to be aligned.
meas_map: List of lists of qubits that are measured together.
Returns:
A ``Schedule`` with the additional acquisition instructions.
"""
new_schedule = Schedule.initialize_from(schedule)
acquire_map = {}
for time, inst in schedule.instructions:
if isinstance(inst, instructions.Acquire):
if inst.mem_slot and inst.mem_slot.index != inst.channel.index:
warnings.warn(
"One of your acquires was mapped to a memory slot which didn't match"
" the qubit index. I'm relabeling them to match."
)
# Get the label of all qubits that are measured with the qubit(s) in this instruction
all_qubits = []
for sublist in meas_map:
if inst.channel.index in sublist:
all_qubits.extend(sublist)
# Replace the old acquire instruction by a new one explicitly acquiring all qubits in
# the measurement group.
for i in all_qubits:
explicit_inst = instructions.Acquire(
inst.duration,
chans.AcquireChannel(i),
mem_slot=chans.MemorySlot(i),
kernel=inst.kernel,
discriminator=inst.discriminator,
)
if time not in acquire_map:
new_schedule.insert(time, explicit_inst, inplace=True)
acquire_map = {time: {i}}
elif i not in acquire_map[time]:
new_schedule.insert(time, explicit_inst, inplace=True)
acquire_map[time].add(i)
else:
new_schedule.insert(time, inst, inplace=True)
return new_schedule
def pad(
schedule: Schedule,
channels: Optional[Iterable[chans.Channel]] = None,
until: Optional[int] = None,
inplace: bool = False,
pad_with: Optional[Type[instructions.Instruction]] = None,
) -> Schedule:
"""Pad the input Schedule with ``Delay``s on all unoccupied timeslots until
``schedule.duration`` or ``until`` if not ``None``.
Args:
schedule: Schedule to pad.
channels: Channels to pad. Defaults to all channels in
``schedule`` if not provided. If the supplied channel is not a member
of ``schedule`` it will be added.
until: Time to pad until. Defaults to ``schedule.duration`` if not provided.
inplace: Pad this schedule by mutating rather than returning a new schedule.
pad_with: Pulse ``Instruction`` subclass to be used for padding.
Default to :class:`~qiskit.pulse.instructions.Delay` instruction.
Returns:
The padded schedule.
Raises:
PulseError: When non pulse instruction is set to `pad_with`.
"""
until = until or schedule.duration
channels = channels or schedule.channels
if pad_with:
if issubclass(pad_with, instructions.Instruction):
pad_cls = pad_with
else:
raise PulseError(
f"'{pad_with.__class__.__name__}' is not valid pulse instruction to pad with."
)
else:
pad_cls = instructions.Delay
for channel in channels:
if isinstance(channel, ClassicalIOChannel):
continue
if channel not in schedule.channels:
schedule = schedule.insert(0, instructions.Delay(until, channel), inplace=inplace)
continue
prev_time = 0
timeslots = iter(schedule.timeslots[channel])
to_pad = []
while prev_time < until:
try:
t0, t1 = next(timeslots)
except StopIteration:
to_pad.append((prev_time, until - prev_time))
break
if prev_time < t0:
to_pad.append((prev_time, min(t0, until) - prev_time))
prev_time = t1
for t0, duration in to_pad:
schedule = schedule.insert(t0, pad_cls(duration, channel), inplace=inplace)
return schedule
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports for the notebook."""
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import minimize
import qiskit
"""Defining circuits with parameters."""
# Get a circuit and registers
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
# Add gates with particular parameters
circ.h(qreg)
circ.rx(0.2, qreg[0])
circ.cx(qreg[0], qreg[1])
circ.ry(0.1, qreg[1])
# Visualize the circuit
print(circ)
def circuit(alpha1: float, alpha2: float):
"""Returns the circuit above with the input parameters."""
### Your code here!
"""Estimating a one qubit expectation value."""
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
### Your code here!
"""Estimating a one qubit expectation value."""
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.x(qreg)
circ.h(qreg)
### Your code here!
"""Estimating a two qubit expectation value."""
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg[1])
### Your code here!
"""Helper function to evaluate the expectation of any valid Pauli string."""
def expectation_circuit(circuit: qiskit.QuantumCircuit, pauli_string: str) -> qiskit.QuantumCircuit:
"""Returns a circuit to compute expectation of the Pauli string in the
state prepared by the input circuit.
Args:
circuit: Prepares the state |\psi> from |0>.
pauli_string: String (tensor product) of Paulis to evaluate
an expectation of. The length of pauli_string
must be equal to the total number of qubits in
the circuit. (Use identities for no operator!)
"""
if len(circuit.qregs) != 1:
raise ValueError("Circuit should have only one quantum register.")
if len(circuit.cregs) != 1:
print("# cregs =", len(circuit.cregs))
raise ValueError("Circuit should have only one classical register.")
### Your code here!
"""Test your function here."""
circ, qreg, creg = circuit(np.pi / 2, np.pi / 4)
print("Bare circuit:")
print(circ)
### Your code here!
"""Function to execute the circuit and do the postprocessing."""
def run_and_process(circuit: qiskit.QuantumCircuit, shots: int = 10000) -> float:
"""Runs an 'expectation circuit' and returns the expectation value of the
measured Pauli string.
Args:
circuit: Circuit to execute.
shots: Number of circuit executions.
"""
### Your code here!
"""Define your function here!"""
def expectation(circuit: qiskit.QuantumCircuit, pauli_string: str, shots: int = 10000) -> float:
"""Returns the expectation value of the pauli string in the state prepared by the circuit."""
### Your code here!
"""Test your function here."""
### Your code here!
"""Compute the expectation of a Hamiltonian."""
# Provided circuit
qreg = qiskit.QuantumRegister(3)
creg = qiskit.ClassicalRegister(3)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
circ.rx(np.pi / 4, qreg[0])
circ.cz(qreg[0], qreg[1])
circ.cz(qreg[1], qreg[2])
print(circ)
weights = (0.5, -0.3, 1.2)
paulis = ("IZZ", "ZZI", "ZIZ")
### Your code here
"""Function to compute the cost of any Hamiltonian in the state prepared by the circuit."""
def cost(circuit, weights, paulis):
"""Returns <psi|H|psi> where |psi> is prepared by the circuit
and the weights and paulis define a Hamiltonian H.
Args:
circuit: Circuit which prepares a state.
weights: List of floats which are the coeffs/weights of each Pauli string.
paulis: List of strings which specify the Paulis.
"""
if len(weights) != len(paulis):
raise ValueError("Args weights and paulis must have the same length.")
### Your code here!
"""Evaluate your cost here!"""
### Your code here!
"""Plot a cost landscape."""
def oneq_circ(param):
qreg = qiskit.QuantumRegister(1)
creg = qiskit.ClassicalRegister(1)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.rx(param, qreg)
return circ
weights = (1.0,)
paulis = ("Z",)
pvals = np.linspace(-np.pi, np.pi, 100)
cvals = []
### Your code here!
"""Get a parameterized circuit."""
def circuit(params):
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
circ.cx(qreg[0], qreg[1])
circ.rx(params[0], qreg[0])
circ.ry(params[1], qreg[1])
circ.cz(qreg[0], qreg[1])
circ.s(qreg[0])
circ.t(qreg[1])
return circ
"""Visualize the circuit."""
print(circuit([1, 2]))
"""Hamiltonian cost to minimize."""
weights = (1.2, -0.2)
paulis = ("IZ", "ZX")
"""Define a cost/objective function."""
def obj(params):
"""Returns the cost for the given parameters."""
### Your code here
"""Test your function on this set of parameters."""
obj([0, 0])
"""Run an optimization algorithm to return the lowest cost and best parameters."""
result = minimize(obj, x0=[0, 0], method="COBYLA")
"""See the optimization results."""
print("Lowest cost function value found:", result.fun)
print("Best parameters:", result.x)
|
https://github.com/Tim-Li/Qiskit-NTU-hackathon-2022_QGEN
|
Tim-Li
|
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# from ibm_quantum_widgetsets import *
from qiskit.providers.aer import QasmSimulator
from qiskit.algorithms.optimizers import *
from qiskit.utils import algorithm_globals
from qiskit.circuit.library import TwoLocal
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.utils import QuantumInstance
from qiskit_optimization import QuadraticProgram
from qiskit.opflow import Z, I
from ibm_quantum_widgets import *
from qiskit.visualization import plot_histogram
# from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.opflow import PauliExpectation, CVaRExpectation
from qiskit.circuit.library import RealAmplitudes
from qiskit_optimization.converters import LinearEqualityToPenalty
from qiskit_optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
def output(result, prob_path, fval_path):
prob = {}
fval = {}
for i in range(len(result.samples)):
tmp = ""
count = 0
for num in range(8):
tmp += str(int(result.samples[i].x[num]))
count += int(result.samples[i].x[num])
prob[tmp] = result.samples[i].probability
fval[tmp] = result.samples[i].fval
np.save(prob_path, prob)
np.save(fval_path, fval)
def unnormalized_h(adj_mtx):
qubit_num = len(adj_mtx)
iden = I
for i in range(1,qubit_num):
iden = iden^I
op = iden-iden
# print(op)
for i in range(qubit_num):
for j in range(qubit_num):
if i > j:
# 2ZiZj
temp = np.ones(qubit_num)*I
temp[i] = Z
temp[j] = Z
op_0 = temp[0]
for k in range(1, qubit_num):
op_0 = op_0^temp[k]
print(op_0)
op = op + 2*op_0
# 0.5*I - 0.5*ZiZj
if adj_mtx[i][j] == 1:
op = op + (0.5*iden - 0.5 * op_0)
op = op + qubit_num * iden
return op
def normalized_h(adj_mtx,ratio):
qubit_num = len(adj_mtx)
iden = I
for i in range(1,qubit_num):
iden = iden^I
op = iden-iden
#print(op)
# for 1/m * 0.5*sum(I-zizj) term
first_term = iden-iden
m=0
# for zizj term
second_term = iden - iden
for i in range(qubit_num):
for j in range(qubit_num):
if i>j:
# 2ZiZj
temp = np.ones(qubit_num)*I
temp[i] = Z
temp[j] = Z
op_0 = temp[0]
for k in range(1,qubit_num):
op_0 = op_0^temp[k]
#print(op_0)
second_term = second_term + 2*op_0
# 0.5*I - 0.5*ZiZj
if adj_mtx[i][j] == 1:
first_term = first_term + 0.5*iden - 0.5 * op_0
m+=1
#unweighted_h = op + first_term + second_term + qubit_num * iden
k = ((ratio/qubit_num**2))
weighted_h = op + first_term/m + float(k)*(second_term + qubit_num * iden)
return weighted_h
def adjacency_matrix(graph):
matrix = []
for i in range(len(graph)):
matrix.append([0]*(len(graph)))
for j in graph[i]:
matrix[i][j] = 1
return matrix
lst = [[1,4,6],[0,2],[1,5,7],[4],[0,3,5],[2,4],[0],[2]]
adj_mtx = adjacency_matrix(lst)
op = unnormalized_h(adj_mtx)
# op.to_matrix_op() # See the operator with matrix form
qp = QuadraticProgram()
qp.from_ising(op)
print(qp)
# solving Quadratic Program using exact classical eigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
result = exact.solve(qp)
print(result.prettyprint())
lst = [[1,4,6],[0,2],[1,5,7],[4],[0,3,5],[2,4],[0],[2]]
adj_mtx = adjacency_matrix(lst)
op = unnormalized_h(adj_mtx)
# op.to_matrix_op() # See the operator with matrix form
qp = QuadraticProgram()
qp.from_ising(op)
print(qp)
optimizer = SLSQP(maxiter=10000)
algorithm_globals.random_seed = 1234
seed = 11234
num = 8
backend = Aer.get_backend('statevector_simulator')
ry = TwoLocal(num, 'ry', 'cz', reps=4, entanglement='full')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
vqe = VQE(ry, optimizer=optimizer, quantum_instance=quantum_instance)
vqe_meo = MinimumEigenOptimizer(vqe)
result = vqe_meo.solve(qp)
print(result.samples)
for opt in range(4):
for it in range(1, 11):
if opt == 0:
optimizer = SLSQP(maxiter=1000)
elif opt == 1:
optimizer = COBYLA(maxiter=1000)
elif opt == 2:
optimizer = NELDER_MEAD(maxiter=1000)
elif opt == 3:
optimizer = POWELL(maxiter=1000)
algorithm_globals.random_seed = 1234
seed = 12345
backend = Aer.get_backend('statevector_simulator')
qNum = 8
ry = TwoLocal(qNum, 'ry', 'cz', reps=it, entanglement='full')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
vqe = VQE(ry, optimizer=optimizer, quantum_instance=quantum_instance)
vqe_meo = MinimumEigenOptimizer(vqe)
result = vqe_meo.solve(qp)
print(result)
# use dictionary form to output result
output(result, f"data/VQE/prob_all_opt{opt}_layer{it}.npy", f"data/VQE/fval_all_opt{opt}_layer{it}.npy")
classical_exp = 2
probability = np.zeros([4, 10])
cost = np.zeros([4, 10])
pdepth = np.arange(1, 11)
expectation = np.zeros([4, 10])
for opt in range(4):
for it in range(1, 11):
df = np.load(f"data/VQE/prob_all_opt{opt}_layer{it}.npy",allow_pickle='TRUE').item()
df2 = np.load(f"data/VQE/fval_all_opt{opt}_layer{it}.npy",allow_pickle='TRUE').item()
probability[opt, it-1] = df.get('10011010', 0)
probability[opt, it-1] += df.get('01100101', 0)
cost[opt, it-1] = df2.get('10011010', 0)
for key in df:
expectation[opt, it-1] += df[key] * df2[key]
alpha = (expectation - classical_exp) / np.abs(classical_exp)
plt.figure(figsize=(10,8))
for opt in range(4):
plt.plot(pdepth, probability[opt])
plt.legend(["SLSQP", "COBYLA", "NELDER_MEAD", "POWELL"])
plt.xlim(0.5, 10.5)
plt.ylim(0, 1)
plt.xticks(np.arange(1, 11), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], fontsize=18)
plt.title("VQE, Probability of Finding Right Answer\n (10011010 or 01100101)", fontsize=18)
plt.xlabel("p-depth", fontsize=18)
plt.ylabel("Probability", fontsize=18)
plt.grid("--")
plt.savefig(f"graph/VQE/prob.png", bbox_inches='tight',pad_inches = 0,dpi=300)
plt.close()
plt.figure(figsize=(10,8))
for opt in range(4):
plt.plot(pdepth, expectation[opt])
plt.legend(["SLSQP", "COBYLA", "NELDER_MEAD", "POWELL"])
plt.xlim(0.5, 10.5)
plt.ylim(2, 8)
plt.xticks(np.arange(1, 11), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], fontsize=18)
plt.title("VQE, Expectation of Cost Function\n (Right Answer: 2)", fontsize=18)
plt.xlabel("p-depth", fontsize=18)
plt.ylabel("Expectation Value", fontsize=18)
plt.grid("--")
plt.savefig(f"graph/VQE/expect.png", bbox_inches='tight',pad_inches = 0,dpi=300)
plt.close()
plt.figure(figsize=(15,8))
for opt in range(4):
plt.plot(pdepth, alpha[opt])
plt.legend(["SLSQP", "COBYLA", "ADAM", "CG", "Gradient descent"])
plt.xlim(0.5, 10.5)
plt.ylim(0, 5)
plt.xticks(np.arange(1, 11), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], fontsize=18)
plt.title(r"VQE, $\frac{expectation - classical\ expectation}{|classical\ expectation|}$", fontsize=18)
plt.xlabel("p-depth", fontsize=18)
plt.ylabel("Error rate", fontsize=18)
plt.grid("--")
plt.savefig(f"graph/VQE/alpha.png", bbox_inches='tight',pad_inches = 0,dpi=300)
plt.show()
plt.close()
dd = np.load(f"data/QAOA/prob_all_opt0_layer1.npy",allow_pickle='TRUE').item()
new_ans = {}
x = []
for key in dd:
tmp = 0
for i in range(8):
tmp += int(key[i])
if tmp == 4:
x.append(key)
for it in range(1,11):
df = np.load(f"data/VQE/prob_all_opt0_layer{it}.npy",allow_pickle='TRUE').item()
df2 = np.load(f"data/VQE/prob_all_opt1_layer{it}.npy",allow_pickle='TRUE').item()
df3 = np.load(f"data/VQE/prob_all_opt2_layer{it}.npy",allow_pickle='TRUE').item()
df4 = np.load(f"data/VQE/prob_all_opt3_layer{it}.npy",allow_pickle='TRUE').item()
y = np.zeros(len(x))
y2 = np.zeros(len(x))
y3 = np.zeros(len(x))
y4 = np.zeros(len(x))
for i in range(len(x)):
y[i] = float(df.get(x[i], 0.))
y2[i] = float(df2.get(x[i], 0.))
y3[i] = float(df3.get(x[i], 0.))
y4[i] = float(df4.get(x[i], 0.))
wid = 0.5
X = np.linspace(0, 150, len(x))
plt.figure(figsize=(25, 8))
plt.xlim(-2, 155)
# plt.ylim(0, 1)
plt.title(f"VQE, Reps={it}", fontsize=16)
plt.bar(X, y, width=wid, color='r')
plt.bar(X+0.5, y2, width=wid, color='b')
plt.bar(X+1, y3, width=wid, color='k')
plt.bar(X+1.5, y4, width=wid, color='g')
plt.legend(labels=["SLSQP", "COBYLA", "NELDER_MEAD", "POWELL"])
plt.xticks(X, x)
plt.ylabel("Probabilities", fontsize=16)
plt.xticks(rotation=90, fontsize=16)
plt.savefig(f"graph/VQE/few_{it}.png", bbox_inches='tight',pad_inches = 0,dpi=200)
plt.show()
plt.close()
lst = [[1,4,6],[0,2],[1,5,7],[4],[0,3,5],[2,4],[0],[2]]
adj_mtx = adjacency_matrix(lst)
op_w = normalized_h(adj_mtx, 1)
# op.to_matrix_op() # See the operator with matrix form
qp_w = QuadraticProgram()
qp_w.from_ising(op_w)
print(qp_w)
optimizer = SLSQP(maxiter=10000)
algorithm_globals.random_seed = 1234
seed = 11234
num = 8
backend = Aer.get_backend('statevector_simulator')
ry = TwoLocal(num, 'ry', 'cz', reps=4, entanglement='full')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
vqe = VQE(ry, optimizer=optimizer, quantum_instance=quantum_instance)
vqe_meo = MinimumEigenOptimizer(vqe)
result = vqe_meo.solve(qp_w)
print(result.samples)
# VQE data
ratio_arr = np.linspace(0.2,2,5)
for opt in range(2):
for it in range(1, 11):
for ratio_idx in range(len(ratio_arr)):
if opt == 0:
optimizer = SLSQP(maxiter=1000)
elif opt == 1:
optimizer = COBYLA(maxiter=1000)
#elif opt == 2:
#optimizer = NELDER_MEAD(maxiter=1000)
#elif opt == 3:
# optimizer = POWELL(maxiter=1000)
algorithm_globals.random_seed = 1234
seed = 12345
backend = Aer.get_backend('statevector_simulator')
qNum = 8
ry = TwoLocal(qNum, 'ry', 'cz', reps=it, entanglement='full')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
vqe = VQE(ry, optimizer=optimizer, quantum_instance=quantum_instance)
vqe_meo = MinimumEigenOptimizer(vqe)
ratio = ratio_arr[ratio_idx]
op_w = normalized_h(adj_mtx, ratio)
qp = QuadraticProgram()
qp.from_ising(op_w)
result = vqe_meo.solve(qp)
print(result)
output(result, f"data_normalized/VQE/prob_all_opt{opt}_layer{it}_ratio{ratio}.npy", f"data_normalized/VQE/fval_all_opt{opt}_layer{it}_ratio{ratio}.npy")
classical_exp = np.load("data/normalized/classical_exp_arr.npy")
classical_exp_arr = np.zeros([50])
for i in range(5):
classical_exp_arr[10*i:10*(i+1)] = classical_exp[i]
print(classical_exp_arr)
df = np.load(f"data/normalized/VQE/prob_all_opt{0}_layer{1}_ratio{0.2}.npy",allow_pickle='TRUE').item()
classical_exp = np.load("data/normalized/classical_exp_arr.npy")
probability = np.zeros([4, 10])
cost = np.zeros([4, 10])
pdepth = np.arange(1, 11)
expectation = np.zeros([4, 10])
ratMax = [0.2, 0.65, 1.1, 1.55, 2.0]
output_prob = np.zeros([50, 3])
output_expectation = np.zeros([50, 3])
output_error_rate = np.zeros([50, 3])
count = 0
for opt in range(0, 2):
for it in range(1, 11):
for ra in ratMax:
df = np.load(f"data/normalized/VQE/prob_all_opt{opt}_layer{it}_ratio{ra}.npy",allow_pickle='TRUE').item()
df2 = np.load(f"data/normalized/VQE/fval_all_opt{opt}_layer{it}_ratio{ra}.npy",allow_pickle='TRUE').item()
output_prob[count, 0] = output_expectation[count, 0] = output_error_rate[count, 0] = it
output_prob[count, 1] = output_expectation[count, 1] = output_error_rate[count, 1] = ra
output_prob[count, 2] = df.get('10011010', 0) + df.get('01100101', 0)
for key in df:
output_expectation[count, 2] += df[key] * df2[key]
count += 1
for i in range(50):
output_error_rate[i, 2] = (output_expectation[i, 2] - classical_exp_arr[i]) / np.abs(classical_exp_arr[i])
if opt == 0:
np.savetxt("data/normalized/VQE_output/probability.csv", output_prob, delimiter=",")
np.savetxt("data/normalized/VQE_output/expectation.csv", output_expectation, delimiter=",")
np.savetxt("data/normalized/VQE_output/error_rate.csv", output_error_rate, delimiter=",")
np.save("data/normalized/VQE_output_reprocessed/probability.npy", output_prob)
np.save("data/normalized/VQE_output_reprocessed/expectation.npy", output_expectation)
np.save("data/normalized/VQE_output_reprocessed/error_rate.npy", output_error_rate)
if opt == 1:
np.savetxt("data/normalized/VQE_output/probability_2.csv", output_prob, delimiter=",")
np.savetxt("data/normalized/VQE_output/expectation_2.csv", output_expectation, delimiter=",")
np.savetxt("data/normalized/VQE_output/error_rate_2.csv", output_error_rate, delimiter=",")
np.save("data/normalized/VQE_output_reprocessed/probability_2.npy", output_prob)
np.save("data/normalized/VQE_output_reprocessed/expectation_2.npy", output_expectation)
np.save("data/normalized/VQE_output_reprocessed/error_rate_2.npy", output_error_rate)
lst = [[1,4,6],[0,2],[1,5,7],[4],[0,3,5],[2,4],[0],[2]]
adj_mtx = adjacency_matrix(lst)
op = unnormalized_h(adj_mtx)
# op.to_matrix_op() # See the operator with matrix form
qp = QuadraticProgram()
qp.from_ising(op)
print(qp)
optimizer = SLSQP(maxiter=10000)
algorithm_globals.random_seed = 1234
seed = 11234
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
qaoa = QAOA(optimizer=optimizer, reps=3, quantum_instance=quantum_instance)
meo = MinimumEigenOptimizer(qaoa)
qaoa_meo = MinimumEigenOptimizer(qaoa)
result = qaoa_meo.solve(qp)
print(result.samples)
for opt in range(4):
for it in range(1, 11):
if opt == 0:
optimizer = SLSQP(maxiter=1000)
elif opt == 1:
optimizer = COBYLA(maxiter=1000)
elif opt == 2:
optimizer = NELDER_MEAD(maxiter=1000)
elif opt == 3:
optimizer = POWELL(maxiter=1000)
algorithm_globals.random_seed = 1234
seed = 12345
backend = Aer.get_backend('statevector_simulator')
qNum = 8
qaoa = QAOA(optimizer=optimizer, reps=3, quantum_instance=quantum_instance)
meo = MinimumEigenOptimizer(qaoa)
qaoa_meo = MinimumEigenOptimizer(qaoa)
result = qaoa_meo.solve(qp)
print(result)
output(result, f"data/QAOA/prob_all_opt{opt}_layer{it}.npy", f"data/QAOA/fval_all_opt{opt}_layer{it}.npy")
classical_exp = 2
probability = np.zeros([4, 10])
cost = np.zeros([4, 10])
pdepth = np.arange(1, 11)
expectation = np.zeros([4, 10])
for opt in range(4):
for it in range(1, 11):
df = np.load(f"data/QAOA/prob_all_opt{opt}_layer{it}.npy",allow_pickle='TRUE').item()
df2 = np.load(f"data/QAOA/fval_all_opt{opt}_layer{it}.npy",allow_pickle='TRUE').item()
probability[opt, it-1] = df.get('10011010', 0)
probability[opt, it-1] += df.get('01100101', 0)
cost[opt, it-1] = df2.get('10011010', 0)
for key in df:
expectation[opt, it-1] += df[key] * df2[key]
alpha = (expectation - classical_exp) / np.abs(classical_exp)
plt.figure(figsize=(10,8))
for opt in range(4):
plt.plot(pdepth, probability[opt])
plt.legend(["SLSQP", "COBYLA", "NELDER_MEAD", "POWELL"])
plt.xlim(0.5, 10.5)
plt.ylim(0, 1)
plt.xticks(np.arange(1, 11), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], fontsize=18)
plt.title("QAOA, Probability of Finding Right Answer\n (10011010 or 01100101)", fontsize=18)
plt.xlabel("p-depth", fontsize=18)
plt.ylabel("Probability", fontsize=18)
plt.grid("--")
plt.savefig(f"graph/QAOA/prob.png", bbox_inches='tight',pad_inches = 0,dpi=300)
plt.close()
plt.figure(figsize=(10,8))
for opt in range(4):
plt.plot(pdepth, expectation[opt])
plt.legend(["SLSQP", "COBYLA", "NELDER_MEAD", "POWELL"])
plt.xlim(0.5, 10.5)
# plt.ylim(2, 8)
plt.xticks(np.arange(1, 11), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], fontsize=18)
plt.title("QAOA, Expectation of Cost Function\n (Right Answer: 2)", fontsize=18)
plt.xlabel("p-depth", fontsize=18)
plt.ylabel("Expectation Value", fontsize=18)
plt.grid("--")
plt.savefig(f"graph/QAOA/expect.png", bbox_inches='tight',pad_inches = 0,dpi=300)
plt.close()
plt.figure(figsize=(15,8))
for opt in range(4):
plt.plot(pdepth, alpha[opt])
plt.legend(["SLSQP", "COBYLA", "NELDER_MEAD", "POWELL"])
plt.xlim(0.5, 10.5)
plt.ylim(0, 5)
plt.xticks(np.arange(1, 11), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], fontsize=18)
plt.title(r"QAOA, $\frac{expectation - classical\ expectation}{|classical\ expectation|}$", fontsize=18)
plt.xlabel("p-depth", fontsize=18)
plt.ylabel("Error rate", fontsize=18)
plt.grid("--")
plt.savefig(f"graph/QAOA/alpha.png", bbox_inches='tight',pad_inches = 0,dpi=300)
plt.show()
plt.close()
lst = [[1,4,6],[0,2],[1,5,7],[4],[0,3,5],[2,4],[0],[2]]
adj_mtx = adjacency_matrix(lst)
op_w = normalized_h(adj_mtx, 1)
# op.to_matrix_op() # See the operator with matrix form
qp_w = QuadraticProgram()
qp_w.from_ising(op_w)
print(qp_w)
optimizer = SLSQP(maxiter=10000)
algorithm_globals.random_seed = 1234
seed = 11234
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
qaoa = QAOA(optimizer=optimizer, reps=3, quantum_instance=quantum_instance)
meo = MinimumEigenOptimizer(qaoa)
qaoa_meo = MinimumEigenOptimizer(qaoa)
result = qaoa_meo.solve(qp_w)
print(result.samples)
x = []
prob = np.zeros([4, 10])
func = np.zeros([4, 10])
ratio_arr = np.linspace(0.2,2,5)
for opt in range(2):
for it in range(1, 11):
for ratio_idx in range(len(ratio_arr)):
if opt == 0:
optimizer = SLSQP(maxiter=1000)
elif opt == 1:
optimizer = COBYLA(maxiter=1000)
# if opt == 2:
# optimizer = NELDER_MEAD(maxiter=1000)
# elif opt == 3:
# optimizer = POWELL(maxiter=1000)
algorithm_globals.random_seed = 1234
seed = 12345
backend = Aer.get_backend('statevector_simulator')
qNum = 8
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
qaoa = QAOA(optimizer=optimizer, reps=it, quantum_instance=quantum_instance)
meo = MinimumEigenOptimizer(qaoa)
qaoa_meo = MinimumEigenOptimizer(qaoa)
#prepare qp
ratio = ratio_arr[ratio_idx]
op_w = normalized_h(adj_mtx, ratio)
qp = QuadraticProgram()
qp.from_ising(op_w)
result = qaoa_meo.solve(qp)
print(result)
output(result, f"data_normalized/QAOA/prob_all_opt{opt}_layer{it}_ratio{ratio}.npy", f"data_normalized/QAOA/fval_all_opt{opt}_layer{it}_ratio{ratio}.npy")
df = np.load(f"data/normalized/QAOA/prob_all_opt{0}_layer{1}_ratio{0.2}.npy",allow_pickle='TRUE').item()
classical_exp = np.load("data/normalized/classical_exp_arr.npy")
probability = np.zeros([4, 10])
cost = np.zeros([4, 10])
pdepth = np.arange(1, 11)
expectation = np.zeros([4, 10])
ratMax = [0.2, 0.65, 1.1, 1.55, 2.0]
output_prob = np.zeros([50, 3])
output_expectation = np.zeros([50, 3])
output_error_rate = np.zeros([50, 3])
count = 0
for opt in range(0, 1):
for it in range(1, 11):
for ra in ratMax:
df = np.load(f"data/normalized/QAOA/prob_all_opt{opt}_layer{it}_ratio{ra}.npy",allow_pickle='TRUE').item()
df2 = np.load(f"data/normalized/QAOA/fval_all_opt{opt}_layer{it}_ratio{ra}.npy",allow_pickle='TRUE').item()
output_prob[count, 0] = output_expectation[count, 0] = output_error_rate[count, 0] = it
output_prob[count, 1] = output_expectation[count, 1] = output_error_rate[count, 1] = ra
output_prob[count, 2] = df.get('10011010', 0) + df.get('01100101', 0)
for key in df:
output_expectation[count, 2] += df[key] * df2[key]
count += 1
for i in range(50):
output_error_rate[i, 2] = (output_expectation[i, 2] - classical_exp_arr[i]) / np.abs(classical_exp_arr[i])
if opt == 0:
np.savetxt("data/normalized/QAOA_output/probability.csv", output_prob, delimiter=",")
np.savetxt("data/normalized/QAOA_output/expectation.csv", output_expectation, delimiter=",")
np.savetxt("data/normalized/QAOA_output/error_rate.csv", output_error_rate, delimiter=",")
np.save("data/normalized/QAOA_output_reprocessed/probability.npy", output_prob)
np.save("data/normalized/QAOA_output_reprocessed/expectation.npy", output_expectation)
np.save("data/normalized/QAOA_output_reprocessed/error_rate.npy", output_error_rate)
if opt == 1:
np.savetxt("data/normalized/QAOA_output/probability_2.csv", output_prob, delimiter=",")
np.savetxt("data/normalized/QAOA_output/expectation_2.csv", output_expectation, delimiter=",")
np.savetxt("data/normalized/QAOA_output/error_rate_2.csv", output_error_rate, delimiter=",")
np.save("data/normalized/QAOA_output_reprocessed/probability_2.npy", output_prob)
np.save("data/normalized/QAOA_output_reprocessed/expectation_2.npy", output_expectation)
np.save("data/normalized/QAOA_output_reprocessed/error_rate_2.npy", output_error_rate)
iter_arr = np.linspace(1,8,8)
ratio_arr = np.linspace(0.2,2,5)
op = operator_from_adjacency_matrix(adj_mtx)
for iter_idx in range(len(iter_arr)):
iter_num = iter_arr[iter_idx]
qp = QuadraticProgram()
qp.from_ising(op)
backend = Aer.get_backend('statevector_simulator')
grover_optimizer = GroverOptimizer(8, num_iterations=iter_num, quantum_instance=backend)
result = grover_optimizer.solve(qp)
print(result.prettyprint())
output(result, f"data/GROVER/prob_iter{iter_num}.npy", f"data/GROVER/fval_iter{iter_num}.npy")
plt.figure(figsize=(15,8))
legend_arr = []
for i in range(len(ratio_arr)):
legend_arr.append("ratio = "+str(ratio_arr[i]))
plt.plot(iter_arr, alpha[i])
legend_arr.append("Unnormalized")
plt.plot(iter_arr,unnormalized_alpha)
xticks_arr = []
for i in range(len(iter_arr)):
xticks_arr.append(str(iter_arr[i]))
plt.legend(legend_arr)
plt.xlim(0.5, 8.5)
plt.xticks(iter_arr, xticks_arr, fontsize=18)
plt.title(r"GROVER, $\frac{expectation - classical\ expectation}{|classical\ expectation|}$", fontsize=18)
plt.xlabel("Number of iteration", fontsize=18)
plt.ylabel("Error rate", fontsize=18)
plt.grid("--")
plt.savefig(f"graph/GROVER/NORMALIZED/error_rate.png", bbox_inches='tight',pad_inches = 0,dpi=300)
plt.show()
normalized_error_rate = np.load("data/normalized/VQE_output_reprocessed/error_rate.npy")
# df = pd.read_csv('data/normalized/VQE_output/probability.csv', sep=',',header=None)
x = np.arange(1, 11)
y = np.zeros([5, 10])
ratio_arr = np.linspace(0.2,2,5)
# print(normalized_error_rate)
normalized_error_rate = normalized_error_rate[:, 2:]
for i in range(5):
y[i] = normalized_error_rate[i::5].T
classical_exp = 2
probability = np.zeros([4, 10])
cost = np.zeros([4, 10])
pdepth = np.arange(1, 11)
expectation = np.zeros([4, 10])
for opt in range(4):
for it in range(1, 11):
df = np.load(f"data/VQE/prob_all_opt{opt}_layer{it}.npy",allow_pickle='TRUE').item()
df2 = np.load(f"data/VQE/fval_all_opt{opt}_layer{it}.npy",allow_pickle='TRUE').item()
probability[opt, it-1] = df.get('10011010', 0)
probability[opt, it-1] += df.get('01100101', 0)
cost[opt, it-1] = df2.get('10011010', 0)
for key in df:
expectation[opt, it-1] += df[key] * df2[key]
alpha = (expectation - classical_exp) / np.abs(classical_exp)
plt.figure(figsize=(15,8))
for i in range(5):
plt.plot(x, y[i])
plt.plot(x, alpha[0])
plt.legend(["ratio = 0.2", "ratio = 0.65", "ratio = 1.1", "ratio = 1.55", "ratio = 2", "Unnormalized"])
plt.xlim(0.5, 10.5)
# plt.ylim(0, 5)
plt.xticks(np.arange(1, 11), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], fontsize=18)
plt.title(r"VQE with SLSQP, $\frac{expectation - classical\ expectation}{|classical\ expectation|}$", fontsize=18)
plt.xlabel("p-depth", fontsize=18)
plt.ylabel("Error rate", fontsize=18)
plt.grid("--")
plt.savefig(f"graph/VQE_compare.png", bbox_inches='tight',pad_inches = 0,dpi=300)
plt.show()
plt.close()
normalized_error_rate = np.load("data/normalized/QAOA_output_reprocessed/error_rate.npy")
# df = pd.read_csv('data/normalized/VQE_output/probability.csv', sep=',',header=None)
x = np.arange(1, 11)
y = np.zeros([5, 10])
ratio_arr = np.linspace(0.2,2,5)
# print(normalized_error_rate)
normalized_error_rate = normalized_error_rate[:, 2:]
for i in range(5):
y[i] = normalized_error_rate[i::5].T
classical_exp = 2
probability = np.zeros([4, 10])
cost = np.zeros([4, 10])
pdepth = np.arange(1, 11)
expectation = np.zeros([4, 10])
for opt in range(4):
for it in range(1, 11):
df = np.load(f"data/QAOA/prob_all_opt{opt}_layer{it}.npy",allow_pickle='TRUE').item()
df2 = np.load(f"data/QAOA/fval_all_opt{opt}_layer{it}.npy",allow_pickle='TRUE').item()
probability[opt, it-1] = df.get('10011010', 0)
probability[opt, it-1] += df.get('01100101', 0)
cost[opt, it-1] = df2.get('10011010', 0)
for key in df:
expectation[opt, it-1] += df[key] * df2[key]
alpha = (expectation - classical_exp) / np.abs(classical_exp)
plt.figure(figsize=(15,8))
for i in range(5):
plt.plot(x, y[i])
plt.plot(x, alpha[0])
plt.legend(["ratio = 0.2", "ratio = 0.65", "ratio = 1.1", "ratio = 1.55", "ratio = 2", "Unnormalized"])
plt.xlim(0.5, 10.5)
# plt.ylim(0, 5)
plt.xticks(np.arange(1, 11), ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], fontsize=18)
plt.title(r"QAOA with SLSQP, $\frac{expectation - classical\ expectation}{|classical\ expectation|}$", fontsize=18)
plt.xlabel("p-depth", fontsize=18)
plt.ylabel("Error rate", fontsize=18)
plt.grid("--")
plt.savefig(f"graph/QAOA_compare.png", bbox_inches='tight',pad_inches = 0,dpi=300)
plt.show()
plt.close()
n = 8
penalty = 2 * n
linear2penalty = LinearEqualityToPenalty(penalty=penalty)
qp = linear2penalty.convert(qp)
_, offset = qp.to_ising()
# set classical optimizer
maxiter = 1000
optimizer = COBYLA(maxiter=maxiter)
# set variational ansatz
ansatz = RealAmplitudes(n, reps=1)
m = ansatz.num_parameters
# set backend
backend_name = "qasm_simulator" # use this for QASM simulator
# backend_name = 'aer_simulator_statevector' # use this for statevector simlator
backend = Aer.get_backend(backend_name)
# 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] += [-(obj + offset)]
for alpha in alphas:
# initialize CVaR_alpha objective
cvar_exp = CVaRExpectation(alpha, PauliExpectation())
cvar_exp.compute_variance = lambda x: [0] # to be fixed in PR #1373
# initialize VQE using CVaR
vqe = VQE(
expectation=cvar_exp,
optimizer=optimizer,
ansatz=ansatz,
quantum_instance=backend,
callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha),
)
# initialize optimization algorithm based on CVaR-VQE
opt_alg = MinimumEigenOptimizer(vqe)
# solve problem
results[alpha] = opt_alg.solve(qp)
# print results
print("alpha = {}:".format(alpha))
print(results[alpha].prettyprint())
print()
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit import QuantumCircuit, transpile, schedule, IBMQ
from qiskit.transpiler import PassManager
import numpy as np
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-internal', group='deployed', project='default')
backend = provider.get_backend('ibm_lagos')
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
from IPython.display import display
from qiskit.circuit.library.standard_gates.equivalence_library import StandardEquivalenceLibrary as std_eqlib
# Transpiler passes
from qiskit.transpiler.passes import Collect2qBlocks
from qiskit.transpiler.passes import ConsolidateBlocks
from qiskit.transpiler.passes import Optimize1qGatesDecomposition
from qiskit.transpiler.passes.basis import BasisTranslator, UnrollCustomDefinitions
from qiskit.transpiler.passes.calibration.builders import RZXCalibrationBuilderNoEcho
# New transpiler pass
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import EchoRZXWeylDecomposition
from qiskit.circuit.library.standard_gates import (RZZGate, RXXGate, RYYGate, RZXGate,
CPhaseGate, CRZGate, HGate, SwapGate, CXGate, iSwapGate)
import qiskit.quantum_info as qi
from qiskit.quantum_info.synthesis.two_qubit_decompose import (TwoQubitControlledUDecomposer,
TwoQubitWeylDecomposition)
theta = 0.8
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.rz(theta, 1)
qc.cx(0, 1)
qc.draw('mpl')
qct = transpile(qc, backend)
schedule(qct, backend).draw()
theta = 0.8
# equivalent decomposition in terms of echoed Cross-Resonance gates.
qc = QuantumCircuit(2)
qc.rz(np.pi / 2, 1)
qc.sx(1)
qc.rz(np.pi / 2, 1)
qc.rzx(theta / 2, 0, 1)
qc.x(0)
qc.rzx(-theta / 2, 0, 1)
qc.x(0)
qc.rz(np.pi / 2, 1)
qc.sx(1)
qc.rz(np.pi / 2, 1)
qc.draw('mpl')
# Add the calibrations.
pm = PassManager([RZXCalibrationBuilderNoEcho(backend)])
qc_pulse_efficient = pm.run(qc)
# qc_pulse_efficient.calibrations
schedule(qc_pulse_efficient, backend).draw()
# Compare the schedule durations
print('Duration of standard CNOT-based circuit:')
print(schedule(qct, backend).duration)
print('Duration of pulse-efficient circuit:')
print(schedule(qc_pulse_efficient, backend).duration)
# random two-qubit circuit
qc = QuantumCircuit(2)
qc.rzx(0.2, 1, 0)
qc.cp(1, 0, 1)
qc.s(0)
qc.rzz(-0.6, 0, 1)
qc.swap(0, 1)
qc.h(0)
qc.ryy(2.3, 0, 1)
qc.iswap(0, 1)
qc.draw('mpl')
unitary = qi.Operator(qc)
decomposer_weyl = TwoQubitWeylDecomposition(unitary)
decomposer_weyl.circuit().draw('mpl')
gate = RZXGate
two_qubit_decompose = TwoQubitControlledUDecomposer(gate)
new_circuit = two_qubit_decompose(unitary)
new_circuit.draw('mpl')
# Random circuit
delta = 8 * np.pi / 5
epsilon = np.pi / 2
eta = -5.1
theta = 0.02
qc = QuantumCircuit(3)
qc.ryy(theta, 0, 1)
qc.s(0)
qc.rz(eta, 1)
qc.rzz(epsilon, 0, 1)
qc.swap(0, 1)
qc.cx(1, 0)
qc.rzz(delta, 1, 2)
qc.swap(1, 2)
qc.h(2)
print('Original circuit:')
display(qc.draw('mpl', idle_wires=False))
qct = transpile(qc, backend)
print('Standard Qiskit transpilation:')
display(qct.draw('mpl', idle_wires=False))
pm = PassManager(
[
# Consolidate consecutive two-qubit operations.
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=['rz', 'sx', 'x', 'rxx']),
]
)
qct_consolidated = pm.run(qct)
qct_consolidated.draw('mpl', idle_wires=None)
pm = PassManager(
[
# Rewrite circuit in terms of Weyl-decomposed echoed RZX gates.
EchoRZXWeylDecomposition(backend),
]
)
qct_rzx_weyl = pm.run(qct_consolidated )
qct_rzx_weyl.draw('mpl', idle_wires=None)
# Random circuit
delta = 8 * np.pi / 5
epsilon = np.pi / 2
eta = -5.1
theta = 0.02
qc = QuantumCircuit(3)
qc.ryy(theta, 0, 1)
qc.s(0)
qc.rz(eta, 1)
qc.rzz(epsilon, 0, 1)
qc.swap(0, 1)
qc.cx(1, 0)
qc.rzz(delta, 1, 2)
qc.swap(1, 2)
qc.h(2)
print('Original circuit:')
display(qc.draw('mpl', idle_wires=False))
qct = transpile(qc, backend)
print('Standard Qiskit transpilation:')
display(qct.draw('mpl', idle_wires=False))
rzx_basis = ['rzx', 'rz', 'x', 'sx']
# Build a pass manager that contains all needed transpiler passes
pm = 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),
# Attach scaled CR pulse schedules to the RZX gates.
RZXCalibrationBuilderNoEcho(backend),
# Simplify single-qubit gates.
UnrollCustomDefinitions(std_eqlib, rzx_basis),
BasisTranslator(std_eqlib, rzx_basis),
Optimize1qGatesDecomposition(rzx_basis)
]
)
# Run the pass manager
qc_pulse_efficient = pm.run(qct)
print('Pulse-efficient, RZX-based circuit:')
display(qc_pulse_efficient.draw('mpl', idle_wires=False))
# Compare the schedule durations
print('Duration of standard CNOT-based circuit:')
print(schedule(qct, backend).duration)
print('Duration of pulse-efficient circuit:')
print(schedule(qc_pulse_efficient, backend).duration)
|
https://github.com/arnaucasau/Quantum-Computing-3SAT
|
arnaucasau
|
# imports
import math
# importing Qiskit
from qiskit import QuantumCircuit, Aer, assemble, transpile
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram
f = open("cnf_test2.txt")
info = f.readline().split(' ')
n_var = int(info[0])
n_clause = int(info[1])
lines = [line.rstrip('\n') for line in f]
formula = []
for i in lines:
l = i.split(' ')
formula.append([int(l[0]),int(l[1]),int(l[2])])
n_qubits = n_var + 3*n_var*(2 + n_clause) + n_clause + 1
n_measures = 7*n_var
iters = 3*n_var
qc = QuantumCircuit(n_qubits)
for i in range(n_var):
qc.h(i)
ini = n_var+n_clause
theta = 2*math.acos(math.sqrt(2/3))
for i in range(iters):
qc.u(theta,0,0,ini)
qc.x(ini)
qc.ch(ini, ini+1)
qc.x(ini)
ini += 2+n_clause
qc.x(n_qubits-1)
qc.h(n_qubits-1)
initial = qc.to_gate()
initial.name = "Initialization"
qc.draw()
qc = QuantumCircuit(n_qubits)
for it in range(iters):
first_bit = n_var+(2+n_clause)*it+n_clause
first_clause = n_var+(2+n_clause)*it
nc = 0
for clause in formula:
control = list()
for lit in clause:
lit_aux = abs(lit)-1
if lit < 0:
qc.x(lit_aux)
control.append(lit_aux)
qc.mct(control,first_clause+nc)
for lit in clause:
if lit < 0:
lit_aux = abs(lit)-1
qc.x(lit_aux)
nc += 1
nc = 0
for clause in formula:
lit1 = abs(clause[0])-1
lit2 = abs(clause[1])-1
lit3 = abs(clause[2])-1
control = list()
control.append(first_bit)
control.append(first_bit+1)
control.append(first_clause+nc)
for n in range(nc):
control.append(first_clause+n)
qc.x(first_clause+n)
qc.x(first_bit)
qc.x(first_bit+1)
qc.mct(control,lit1)
qc.x(first_bit+1)
qc.x(first_bit)
qc.x(first_bit+1)
qc.mct(control,lit2)
qc.x(first_bit+1)
qc.x(first_bit)
qc.mct(control,lit3)
qc.x(first_bit)
for n in range(nc):
qc.x(first_clause+n)
nc += 1
nc = 0
for clause in formula:
control = list()
for lit in clause:
lit_aux = abs(lit)-1
if lit < 0:
qc.x(lit_aux)
control.append(lit_aux)
qc.mct(control,n_qubits-1-n_clause+nc)
for lit in clause:
if lit < 0:
lit_aux = abs(lit)-1
qc.x(lit_aux)
nc += 1
schoning_step = qc.to_gate()
schoning_step.name = "Schoning"
qc.draw(fold=10000)
qc = QuantumCircuit(n_qubits)
qc.append(schoning_step, list(range(n_qubits)))
control = list()
for nc in range(n_clause):
qc.x(n_qubits-1-n_clause+nc)
control.append(n_qubits-1-n_clause+nc)
qc.mct(control,n_qubits-1)
for nc in range(n_clause):
qc.x(n_qubits-1-n_clause+nc)
qc.append(schoning_step.inverse(), list(range(n_qubits)))
oracle = qc.to_gate()
oracle.name = "Oracle"
qc.draw()
qc = QuantumCircuit(n_qubits)
l = list()
aux = list()
ini = n_var
for i in range(iters):
for j in range(n_clause):
aux.append(ini+j)
ini += n_clause+2
for j in range(n_clause):
aux.append(ini+j)
for i in range(n_var):
qc.h(i)
qc.x(i)
l.append(i)
ini = n_var+n_clause
theta = 2*math.acos(math.sqrt(2/3))
for i in range(iters):
qc.x(ini)
qc.ch(ini, ini+1)
qc.x(ini)
qc.u(-theta,0,0,ini)
qc.x(ini)
qc.x(ini+1)
l.append(ini)
l.append(ini+1)
ini += 2+n_clause
#qc.mct(l,n_qubits-1)
original = l
total = len(l)
l2 = list()
i = 0
while total != 1:
for j in range(math.ceil(total/4)):
qc.mct(l[4*j:4*j+4],aux[i])
l2.append(aux[i])
i+=1
l = l2
total = len(l)
l2 = list()
diff_part1 = qc.to_gate()
diff_part1.name = "diff_part1"
qc.draw()
qc = QuantumCircuit(n_qubits)
qc.append(diff_part1, list(range(n_qubits)))
qc.mct(l,n_qubits-1)
qc.append(diff_part1.inverse(), list(range(n_qubits)))
diffuser = qc.to_gate()
diffuser.name = "Diffuser"
qc.draw()
rounds = math.pi/4.0*math.sqrt((4/3)**n_var)
print("Result:",rounds)
print("Iterations R ≤",math.ceil(rounds))
if math.floor(rounds) == 0:
rounds = round(rounds)
else:
rounds = math.floor(rounds)
print("Iterations chosen:", rounds)
qc = QuantumCircuit(n_qubits,n_measures)
qc.append(initial, list(range(n_qubits)))
for i in range(rounds):
qc.append(oracle, list(range(n_qubits)))
qc.append(diffuser, list(range(n_qubits)))
actual = 0
for i in range(n_var):
qc.measure([i],[i])
actual += 1
ini = n_var+n_clause
for i in range(iters):
qc.measure([ini],[actual])
qc.measure([ini+1],[actual+1])
ini += 2+n_clause
actual += 2
qc.draw()
# Select the AerSimulator from the Aer provider
simulator = AerSimulator(method='matrix_product_state')
#simulator = AerSimulator(method='statevector')
#simulator = AerSimulator(method='extended_stabilizer')
# Run and get counts, using the matrix_product_state method
tcirc = transpile(qc, simulator)
result = simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(result.success))
counts = result.get_counts(0)
print(counts)
assig = list(next(iter(counts))[::-1][0:n_var])
steps = next(iter(counts))[::-1][n_var:]
print(assig)
print(steps)
def check_formula(formula, assig):
c = 0
for clause in formula:
lit1_pos = abs(clause[0])-1
lit2_pos = abs(clause[1])-1
lit3_pos = abs(clause[2])-1
total = 0
if (clause[0] < 0 and assig[lit1_pos] == '0') or (clause[0] > 0 and assig[lit1_pos] == '1'):
total += 1
if (clause[1] < 0 and assig[lit2_pos] == '0') or (clause[1] > 0 and assig[lit2_pos] == '1'):
total += 1
if (clause[2] < 0 and assig[lit3_pos] == '0') or (clause[2] > 0 and assig[lit3_pos] == '1'):
total += 1
if total == 0:
return (False,c)
c += 1
return (True,-1)
def schoning(formula,assig,steps,verbose=True):
n = len(assig)
if verbose:
print("initial guess","->",assig)
print("")
for i in range(3*n):
checking = check_formula(formula, assig)
if checking[0]:
return True
lit = int(steps[2*i])+2*int(steps[2*i+1])
var = abs(formula[checking[1]][lit])-1
if assig[var] == '0':
assig[var] = '1'
else:
assig[var] = '0'
if verbose:
print("iter",i+1,"->",assig)
return check_formula(formula, assig)[0]
schoning(formula,assig,steps)
simulator = AerSimulator(method='matrix_product_state')
tcirc = transpile(qc, simulator)
result = simulator.run(tcirc, shots=1024).result()
print('This succeeded?: {}'.format(result.success))
counts = result.get_counts(0)
total = 0
true = 0
for key in counts:
assig = list(key[::-1][0:n_var])
steps = key[::-1][n_var:]
r = schoning(formula,assig,steps,verbose=False)
if r:
true += counts[key]
total += counts[key]
print(true/total*100,"% of success")
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.visualization import plot_bloch_multivector,plot_state_qsphere
import matplotlib.pyplot as plt
q = np.array([1.+0.j, 0.+0.j])
plot_bloch_multivector(q)
plot_state_qsphere(q)
q = np.array([0.+0.j, 1.+0.j])
plot_bloch_multivector(q)
plot_state_qsphere(q)
qc = QuantumCircuit(1)
qc.barrier()
qc1 = qc.copy()
qc.x(0)
qc.barrier()
qc2 =qc.copy()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
q1 = execute(qc1,backend).result().get_statevector()
q2 = execute(qc2,backend).result().get_statevector()
print(q1,q2)
q = np.array([1/np.sqrt(2)+0.j, 1/np.sqrt(2)+0.j])
plot_bloch_multivector(q)
plot_state_qsphere(q)
q = np.array([1/np.sqrt(2)+0.j, -(1/np.sqrt(2))+0.j])
plot_bloch_multivector(q)
plot_state_qsphere(q)
qc = QuantumCircuit(1)
qc.barrier()
qc1 = qc.copy()
qc.h(0)
qc.barrier()
qc2 =qc.copy()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
q1 = execute(qc1,backend).result().get_statevector()
q2 = execute(qc2,backend).result().get_statevector()
print(q1,q2)
qc = QuantumCircuit(1)
qc.barrier()
qc1 = qc.copy()
qc.x(0)
qc.h(0)
qc.barrier()
qc2 =qc.copy()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
q1 = execute(qc1,backend).result().get_statevector()
q2 = execute(qc2,backend).result().get_statevector()
print(q1,q2)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
%matplotlib inline
from qiskit_finance import QiskitFinanceError
from qiskit_finance.data_providers import *
import datetime
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
data = RandomDataProvider(
tickers=["TICKER1", "TICKER2"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
means = data.get_mean_vector()
print("Means:")
print(means)
rho = data.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = data.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(data._tickers):
print(s)
print(data._data[cnt])
data = RandomDataProvider(
tickers=["CompanyA", "CompanyB", "CompanyC"],
start=datetime.datetime(2015, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=1,
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
stocks = ["GOOG", "AAPL"]
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
wiki = WikipediaDataProvider(
token=token,
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
)
wiki.run()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
if token != "REPLACE-ME":
if wiki._data:
if wiki._n <= 1:
print(
"Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers."
)
else:
rho = wiki.get_similarity_matrix()
print("A time-series similarity measure:")
print(rho)
plt.imshow(rho)
plt.show()
cov = wiki.get_covariance_matrix()
print("A covariance matrix:")
print(cov)
plt.imshow(cov)
plt.show()
else:
print("No wiki data loaded.")
if token != "REPLACE-ME":
if wiki._data:
print("The underlying evolution of stock prices:")
for (cnt, s) in enumerate(stocks):
plt.plot(wiki._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
for (cnt, s) in enumerate(stocks):
print(s)
print(wiki._data[cnt])
else:
print("No wiki data loaded.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
nasdaq = DataOnDemandProvider(
token=token,
tickers=["GOOG", "AAPL"],
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 2),
)
nasdaq.run()
for (cnt, s) in enumerate(nasdaq._tickers):
plt.plot(nasdaq._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
token = "REPLACE-ME"
if token != "REPLACE-ME":
try:
lse = ExchangeDataProvider(
token=token,
tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"],
stockmarket=StockMarket.LONDON,
start=datetime.datetime(2018, 1, 1),
end=datetime.datetime(2018, 12, 31),
)
lse.run()
for (cnt, s) in enumerate(lse._tickers):
plt.plot(lse._data[cnt], label=s)
plt.legend()
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
print(ex)
print("Error retrieving data.")
try:
data = YahooDataProvider(
tickers=["MSFT", "AAPL", "GOOG"],
start=datetime.datetime(2021, 1, 1),
end=datetime.datetime(2021, 12, 31),
)
data.run()
for (cnt, s) in enumerate(data._tickers):
plt.plot(data._data[cnt], label=s)
plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3)
plt.xticks(rotation=90)
plt.show()
except QiskitFinanceError as ex:
data = None
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#Assign these values as per your requirements.
global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion
min_qubits=1
max_qubits=3
skip_qubits=1
max_circuits=3
num_shots=1000
use_XX_YY_ZZ_gates = True
Noise_Inclusion = False
saveplots = False
Memory_utilization_plot = True
Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2"
backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends
gate_counts_plots = True
#Change your Specification of Simulator in Declaring Backend Section
#By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2()
import numpy as np
import os,json
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute
import time
import matplotlib.pyplot as plt
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error)
# Benchmark Name
benchmark_name = "Hamiltonian Simulation"
# Selection of basis gate set for transpilation
# Note: selector 1 is a hardware agnostic gate set
basis_selector = 1
basis_gates_array = [
[],
['rx', 'ry', 'rz', 'cx'], # a common basis set, default
['cx', 'rz', 'sx', 'x'], # IBM default basis set
['rx', 'ry', 'rxx'], # IonQ default basis set
['h', 'p', 'cx'], # another common basis set
['u', 'cx'] # general unitaries basis gates
]
np.random.seed(0)
num_gates = 0
depth = 0
def get_QV(backend):
import json
# Assuming backend.conf_filename is the filename and backend.dirname is the directory path
conf_filename = backend.dirname + "/" + backend.conf_filename
# Open the JSON file
with open(conf_filename, 'r') as file:
# Load the JSON data
data = json.load(file)
# Extract the quantum_volume parameter
QV = data.get('quantum_volume', None)
return QV
def checkbackend(backend_name,Type_of_Simulator):
if Type_of_Simulator == "built_in":
available_backends = []
for i in Aer.backends():
available_backends.append(i.name)
if backend_name in available_backends:
platform = backend_name
return platform
else:
print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!")
print(f"available backends are : {available_backends}")
platform = "qasm_simulator"
return platform
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2":
import qiskit.providers.fake_provider as fake_backends
if hasattr(fake_backends,backend_name) is True:
print(f"Backend {backend_name} is available for type {Type_of_Simulator}.")
backend_class = getattr(fake_backends,backend_name)
backend_instance = backend_class()
return backend_instance
else:
print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!")
if Type_of_Simulator == "FAKEV2":
backend_class = getattr(fake_backends,"FakeSantiagoV2")
else:
backend_class = getattr(fake_backends,"FakeSantiago")
backend_instance = backend_class()
return backend_instance
if Type_of_Simulator == "built_in":
platform = checkbackend(backend_name,Type_of_Simulator)
#By default using "Qasm Simulator"
backend = Aer.get_backend(platform)
QV_=None
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"backend version is {backend.backend_version}")
elif Type_of_Simulator == "FAKE":
basis_selector = 0
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting.
max_qubits=backend.configuration().n_qubits
print(f"{platform} device is capable of running {backend.configuration().n_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
elif Type_of_Simulator == "FAKEV2":
basis_selector = 0
if "V2" not in backend_name:
backend_name = backend_name+"V2"
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.name +"-" +backend.backend_version
max_qubits=backend.num_qubits
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
else:
print("Enter valid Simulator.....")
# saved circuits and subcircuits for display
QC_ = None
XX_ = None
YY_ = None
ZZ_ = None
XXYYZZ_ = None
# import precalculated data to compare against
filename = os.path.join("precalculated_data.json")
with open(filename, 'r') as file:
data = file.read()
precalculated_data = json.loads(data)
############### Circuit Definition
def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z):
'''
Construct a Qiskit circuit for Hamiltonian Simulation
:param n_spins:The number of spins to simulate
:param K: The Trotterization order
:param t: duration of simulation
:return: return a Qiskit circuit for this Hamiltonian
'''
num_qubits = n_spins
secret_int = f"{K}-{t}"
# allocate qubits
qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins);
qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}")
tau = t / K
# start with initial state of 1010101...
for k in range(0, n_spins, 2):
qc.x(qr[k])
qc.barrier()
# loop over each trotter step, adding gates to the circuit defining the hamiltonian
for k in range(K):
# the Pauli spin vector product
[qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)]
[qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)]
qc.barrier()
# Basic implementation of exp(i * t * (XX + YY + ZZ))
if _use_XX_YY_ZZ_gates:
# XX operator on each pair of qubits in linear chain
for j in range(2):
for i in range(j%2, n_spins - 1, 2):
qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
# YY operator on each pair of qubits in linear chain
for j in range(2):
for i in range(j%2, n_spins - 1, 2):
qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
# ZZ operation on each pair of qubits in linear chain
for j in range(2):
for i in range(j%2, n_spins - 1, 2):
qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
# Use an optimal XXYYZZ combined operator
# See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf
else:
# optimized XX + YY + ZZ operator on each pair of qubits in linear chain
for j in range(2):
for i in range(j % 2, n_spins - 1, 2):
qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]])
qc.barrier()
# measure all the qubits used in the circuit
for i_qubit in range(n_spins):
qc.measure(qr[i_qubit], cr[i_qubit])
# save smaller circuit example for display
global QC_
if QC_ == None or n_spins <= 6:
if n_spins < 9: QC_ = qc
return qc
############### XX, YY, ZZ Gate Implementations
# Simple XX gate on q0 and q1 with angle 'tau'
def xx_gate(tau):
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate")
qc.h(qr[0])
qc.h(qr[1])
qc.cx(qr[0], qr[1])
qc.rz(3.1416*tau, qr[1])
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.h(qr[1])
# save circuit example for display
global XX_
XX_ = qc
return qc
# Simple YY gate on q0 and q1 with angle 'tau'
def yy_gate(tau):
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate")
qc.s(qr[0])
qc.s(qr[1])
qc.h(qr[0])
qc.h(qr[1])
qc.cx(qr[0], qr[1])
qc.rz(3.1416*tau, qr[1])
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.h(qr[1])
qc.sdg(qr[0])
qc.sdg(qr[1])
# save circuit example for display
global YY_
YY_ = qc
return qc
# Simple ZZ gate on q0 and q1 with angle 'tau'
def zz_gate(tau):
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate")
qc.cx(qr[0], qr[1])
qc.rz(3.1416*tau, qr[1])
qc.cx(qr[0], qr[1])
# save circuit example for display
global ZZ_
ZZ_ = qc
return qc
# Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau'
def xxyyzz_opt_gate(tau):
alpha = tau; beta = tau; gamma = tau
qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt")
qc.rz(3.1416/2, qr[1])
qc.cx(qr[1], qr[0])
qc.rz(3.1416*gamma - 3.1416/2, qr[0])
qc.ry(3.1416/2 - 3.1416*alpha, qr[1])
qc.cx(qr[0], qr[1])
qc.ry(3.1416*beta - 3.1416/2, qr[1])
qc.cx(qr[1], qr[0])
qc.rz(-3.1416/2, qr[0])
# save circuit example for display
global XXYYZZ_
XXYYZZ_ = qc
return qc
# Create an empty noise model
noise_parameters = NoiseModel()
if Type_of_Simulator == "built_in":
# Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5%
depol_one_qb_error = 0.05
depol_two_qb_error = 0.005
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx'])
# Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0%
amp_damp_one_qb_error = 0.0
amp_damp_two_qb_error = 0.0
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx'])
# Add reset noise to all single qubit resets
reset_to_zero_error = 0.005
reset_to_one_error = 0.005
noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"])
# Add readout error
p0given1_error = 0.000
p1given0_error = 0.000
error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]])
noise_parameters.add_all_qubit_readout_error(error_meas)
#print(noise_parameters)
elif Type_of_Simulator == "FAKE"or"FAKEV2":
noise_parameters = NoiseModel.from_backend(backend)
#print(noise_parameters)
### Analysis methods to be expanded and eventually compiled into a separate analysis.py file
import math, functools
def hellinger_fidelity_with_expected(p, q):
""" p: result distribution, may be passed as a counts distribution
q: the expected distribution to be compared against
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
Qiskit Hellinger Fidelity Function
"""
p_sum = sum(p.values())
q_sum = sum(q.values())
if q_sum == 0:
print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0")
return 0
p_normed = {}
for key, val in p.items():
p_normed[key] = val/p_sum
# if p_sum != 0:
# p_normed[key] = val/p_sum
# else:
# p_normed[key] = 0
q_normed = {}
for key, val in q.items():
q_normed[key] = val/q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed.keys():
total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
# in some situations (error mitigation) this can go negative, use abs value
if total < 0:
print(f"WARNING: using absolute value in fidelity calculation")
total = abs(total)
dist = np.sqrt(total)/np.sqrt(2)
fidelity = (1-dist**2)**2
return fidelity
def polarization_fidelity(counts, correct_dist, thermal_dist=None):
"""
Combines Hellinger fidelity and polarization rescaling into fidelity calculation
used in every benchmark
counts: the measurement outcomes after `num_shots` algorithm runs
correct_dist: the distribution we expect to get for the algorithm running perfectly
thermal_dist: optional distribution to pass in distribution from a uniform
superposition over all states. If `None`: generated as
`uniform_dist` with the same qubits as in `counts`
returns both polarization fidelity and the hellinger fidelity
Polarization from: `https://arxiv.org/abs/2008.11294v1`
"""
num_measured_qubits = len(list(correct_dist.keys())[0])
#print(num_measured_qubits)
counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()}
# calculate hellinger fidelity between measured expectation values and correct distribution
hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist)
# to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits
if num_measured_qubits > 16:
return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity }
# if not provided, generate thermal dist based on number of qubits
if thermal_dist == None:
thermal_dist = uniform_dist(num_measured_qubits)
# set our fidelity rescaling value as the hellinger fidelity for a depolarized state
floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist)
# rescale fidelity result so uniform superposition (random guessing) returns fidelity
# rescaled to 0 to provide a better measure of success of the algorithm (polarization)
new_floor_fidelity = 0
fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity)
return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity }
## Uniform distribution function commonly used
def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity):
"""
Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks
fidelity: raw fidelity to rescale
floor_fidelity: threshold fidelity which is equivalent to random guessing
new_floor_fidelity: what we rescale the floor_fidelity to
Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0:
1 -> 1;
0.25 -> 0;
0.5 -> 0.3333;
"""
rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1
# ensure fidelity is within bounds (0, 1)
if rescaled_fidelity < 0:
rescaled_fidelity = 0.0
if rescaled_fidelity > 1:
rescaled_fidelity = 1.0
return rescaled_fidelity
def uniform_dist(num_state_qubits):
dist = {}
for i in range(2**num_state_qubits):
key = bin(i)[2:].zfill(num_state_qubits)
dist[key] = 1/(2**num_state_qubits)
return dist
from matplotlib.patches import Rectangle
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize
from matplotlib.patches import Circle
############### Color Map functions
# Create a selection of colormaps from which to choose; default to custom_spectral
cmap_spectral = plt.get_cmap('Spectral')
cmap_greys = plt.get_cmap('Greys')
cmap_blues = plt.get_cmap('Blues')
cmap_custom_spectral = None
# the default colormap is the spectral map
cmap = cmap_spectral
cmap_orig = cmap_spectral
# current cmap normalization function (default None)
cmap_norm = None
default_fade_low_fidelity_level = 0.16
default_fade_rate = 0.7
# Specify a normalization function here (default None)
def set_custom_cmap_norm(vmin, vmax):
global cmap_norm
if vmin == vmax or (vmin == 0.0 and vmax == 1.0):
print("... setting cmap norm to None")
cmap_norm = None
else:
print(f"... setting cmap norm to [{vmin}, {vmax}]")
cmap_norm = Normalize(vmin=vmin, vmax=vmax)
# Remake the custom spectral colormap with user settings
def set_custom_cmap_style(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
#print("... set custom map style")
global cmap, cmap_custom_spectral, cmap_orig
cmap_custom_spectral = create_custom_spectral_cmap(
fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate)
cmap = cmap_custom_spectral
cmap_orig = cmap_custom_spectral
# Create the custom spectral colormap from the base spectral
def create_custom_spectral_cmap(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
# determine the breakpoint from the fade level
num_colors = 100
breakpoint = round(fade_low_fidelity_level * num_colors)
# get color list for spectral map
spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)]
#print(fade_rate)
# create a list of colors to replace those below the breakpoint
# and fill with "faded" color entries (in reverse)
low_colors = [0] * breakpoint
#for i in reversed(range(breakpoint)):
for i in range(breakpoint):
# x is index of low colors, normalized 0 -> 1
x = i / breakpoint
# get color at this index
bc = spectral_colors[i]
r0 = bc[0]
g0 = bc[1]
b0 = bc[2]
z0 = bc[3]
r_delta = 0.92 - r0
#print(f"{x} {bc} {r_delta}")
# compute saturation and greyness ratio
sat_ratio = 1 - x
#grey_ratio = 1 - x
''' attempt at a reflective gradient
if i >= breakpoint/2:
xf = 2*(x - 0.5)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (yf + 0.5)
else:
xf = 2*(0.5 - x)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (0.5 - yf)
'''
grey_ratio = 1 - math.pow(x, 1/fade_rate)
#print(f" {xf} {yf} ")
#print(f" {sat_ratio} {grey_ratio}")
r = r0 + r_delta * sat_ratio
g_delta = r - g0
b_delta = r - b0
g = g0 + g_delta * grey_ratio
b = b0 + b_delta * grey_ratio
#print(f"{r} {g} {b}\n")
low_colors[i] = (r,g,b,z0)
#print(low_colors)
# combine the faded low colors with the regular spectral cmap to make a custom version
cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:])
#spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)]
#for i in range(10): print(spectral_colors[i])
#print("")
return cmap_custom_spectral
# Make the custom spectral color map the default on module init
set_custom_cmap_style()
# Arrange the stored annotations optimally and add to plot
def anno_volumetric_data(ax, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True):
# sort all arrays by the x point of the text (anno_offs)
global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos
all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos))
x_anno_offs = [a for a,b,c,d,e in all_annos]
y_anno_offs = [b for a,b,c,d,e in all_annos]
anno_labels = [c for a,b,c,d,e in all_annos]
x_annos = [d for a,b,c,d,e in all_annos]
y_annos = [e for a,b,c,d,e in all_annos]
#print(f"{x_anno_offs}")
#print(f"{y_anno_offs}")
#print(f"{anno_labels}")
for i in range(len(anno_labels)):
x_anno = x_annos[i]
y_anno = y_annos[i]
x_anno_off = x_anno_offs[i]
y_anno_off = y_anno_offs[i]
label = anno_labels[i]
if i > 0:
x_delta = abs(x_anno_off - x_anno_offs[i - 1])
y_delta = abs(y_anno_off - y_anno_offs[i - 1])
if y_delta < 0.7 and x_delta < 2:
y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6
#x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1
ax.annotate(label,
xy=(x_anno+0.0, y_anno+0.1),
arrowprops=dict(facecolor='black', shrink=0.0,
width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)),
xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]),
rotation=labelrot,
horizontalalignment='left', verticalalignment='baseline',
color=(0.2,0.2,0.2),
clip_on=True)
if saveplots == True:
plt.savefig("VolumetricPlotSample.jpg")
# Plot one group of data for volumetric presentation
def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True,
x_size=1.0, y_size=1.0, zorder=1, offset_flag=False,
max_depth=0, suppress_low_fidelity=False):
# since data may come back out of order, save point at max y for annotation
i_anno = 0
x_anno = 0
y_anno = 0
# plot data rectangles
low_fidelity_count = True
last_y = -1
k = 0
# determine y-axis dimension for one pixel to use for offset of bars that start at 0
(_, dy) = get_pixel_dims(ax)
# do this loop in reverse to handle the case where earlier cells are overlapped by later cells
for i in reversed(range(len(d_data))):
x = depth_index(d_data[i], depth_base)
y = float(w_data[i])
f = f_data[i]
# each time we star a new row, reset the offset counter
# DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars
# that represent time starting from 0 secs. We offset by one pixel each and center the group
if y != last_y:
last_y = y;
k = 3 # hardcoded for 8 cells, offset by 3
#print(f"{i = } {x = } {y = }")
if max_depth > 0 and d_data[i] > max_depth:
#print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}")
break;
# reject cells with low fidelity
if suppress_low_fidelity and f < suppress_low_fidelity_level:
if low_fidelity_count: break
else: low_fidelity_count = True
# the only time this is False is when doing merged gradation plots
if do_border == True:
# this case is for an array of x_sizes, i.e. each box has different width
if isinstance(x_size, list):
# draw each of the cells, with no offset
if not offset_flag:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder))
# use an offset for y value, AND account for x and width to draw starting at 0
else:
ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder))
# this case is for only a single cell
else:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size))
# save the annotation point with the largest y value
if y >= y_anno:
x_anno = x
y_anno = y
i_anno = i
# move the next bar down (if using offset)
k -= 1
# if no data rectangles plotted, no need for a label
if x_anno == 0 or y_anno == 0:
return
x_annos.append(x_anno)
y_annos.append(y_anno)
anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 )
# adjust radius of annotation circle based on maximum width of apps
anno_max = 10
if w_max > 10:
anno_max = 14
if w_max > 14:
anno_max = 18
scale = anno_max / anno_dist
# offset of text from end of arrow
if scale > 1:
x_anno_off = scale * x_anno - x_anno - 0.5
y_anno_off = scale * y_anno - y_anno
else:
x_anno_off = 0.7
y_anno_off = 0.5
x_anno_off += x_anno
y_anno_off += y_anno
# print(f"... {xx} {yy} {anno_dist}")
x_anno_offs.append(x_anno_off)
y_anno_offs.append(y_anno_off)
anno_labels.append(label)
if do_label:
ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot,
horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2))
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# init arrays to hold annotation points for label spreading
def vplot_anno_init ():
global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# Number of ticks on volumetric depth axis
max_depth_log = 22
# average transpile factor between base QV depth and our depth based on results from QV notebook
QV_transpile_factor = 12.7
# format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1
# (sign handling may be incorrect)
def format_number(num, digits=0):
if isinstance(num, str): num = float(num)
num = float('{:.3g}'.format(abs(num)))
sign = ''
metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1}
for index in metric:
num_check = num / metric[index]
if num_check >= 1:
num = round(num_check, digits)
sign = index
break
numstr = f"{str(num)}"
if '.' in numstr:
numstr = numstr.rstrip('0').rstrip('.')
return f"{numstr}{sign}"
# Return the color associated with the spcific value, using color map norm
def get_color(value):
# if there is a normalize function installed, scale the data
if cmap_norm:
value = float(cmap_norm(value))
if cmap == cmap_spectral:
value = 0.05 + value*0.9
elif cmap == cmap_blues:
value = 0.00 + value*1.0
else:
value = 0.0 + value*0.95
return cmap(value)
# Return the x and y equivalent to a single pixel for the given plot axis
def get_pixel_dims(ax):
# transform 0 -> 1 to pixel dimensions
pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0))
xpix = pixdims[1][0]
ypix = pixdims[0][1]
#determine x- and y-axis dimension for one pixel
dx = (1 / xpix)
dy = (1 / ypix)
return (dx, dy)
############### Helper functions
# return the base index for a circuit depth value
# take the log in the depth base, and add 1
def depth_index(d, depth_base):
if depth_base <= 1:
return d
if d == 0:
return 0
return math.log(d, depth_base) + 1
# draw a box at x,y with various attributes
def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1):
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5*y_size,
zorder=zorder)
# draw a circle at x,y with various attributes
def circle_at(x, y, value, type=1, fill=True):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Circle((x, y), size/2,
alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5)
def box4_at(x, y, value, type=1, fill=True, alpha=1.0):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.3,0.3,0.3)
ec = fc
return Rectangle((x - size/8, y - size/2), size/4, size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.1)
# Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value
def qv_box_at(x, y, qv_width, qv_depth, value, depth_base):
#print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}")
return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width,
edgecolor = (value,value,value),
facecolor = (value,value,value),
fill=True,
lw=1)
def bkg_box_at(x, y, value=0.9):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (value,value,value),
fill=True,
lw=0.5)
def bkg_empty_box_at(x, y):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (1.0,1.0,1.0),
fill=True,
lw=0.5)
# Plot the background for the volumetric analysis
def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"):
if suptitle == None:
suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}"
QV0 = QV
qv_estimate = False
est_str = ""
if QV == 0: # QV = 0 indicates "do not draw QV background or label"
QV = 2048
elif QV < 0: # QV < 0 indicates "add est. to label"
QV = -QV
qv_estimate = True
est_str = " (est.)"
if avail_qubits > 0 and max_qubits > avail_qubits:
max_qubits = avail_qubits
max_width = 13
if max_qubits > 11: max_width = 18
if max_qubits > 14: max_width = 20
if max_qubits > 16: max_width = 24
if max_qubits > 24: max_width = 33
#print(f"... {avail_qubits} {max_qubits} {max_width}")
plot_width = 6.8
plot_height = 0.5 + plot_width * (max_width / max_depth_log)
#print(f"... {plot_width} {plot_height}")
# define matplotlib figure and axis; use constrained layout to fit colorbar to right
fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True)
plt.suptitle(suptitle)
plt.xlim(0, max_depth_log)
plt.ylim(0, max_width)
# circuit depth axis (x axis)
xbasis = [x for x in range(1,max_depth_log)]
xround = [depth_base**(x-1) for x in xbasis]
xlabels = [format_number(x) for x in xround]
ax.set_xlabel('Circuit Depth')
ax.set_xticks(xbasis)
plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor")
# other label options
#plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left')
#plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor")
# circuit width axis (y axis)
ybasis = [y for y in range(1,max_width)]
yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now
ylabels = [str(y) for y in yround] # not used now
#ax.set_ylabel('Circuit Width (Number of Qubits)')
ax.set_ylabel('Circuit Width')
ax.set_yticks(ybasis)
#create simple line plot (not used right now)
#ax.plot([0, 10],[0, 10])
log2QV = math.log2(QV)
QV_width = log2QV
QV_depth = log2QV * QV_transpile_factor
# show a quantum volume rectangle of QV = 64 e.g. (6 x 6)
if QV0 != 0:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base))
else:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base))
# the untranspiled version is commented out - we do not show this by default
# also show a quantum volume rectangle un-transpiled
# ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base))
# show 2D array of volumetric cells based on this QV_transpiled
# DEVNOTE: we use +1 only to make the visuals work; s/b without
# Also, the second arg of the min( below seems incorrect, needs correction
maxprod = (QV_width + 1) * (QV_depth + 1)
for w in range(1, min(max_width, round(QV) + 1)):
# don't show VB squares if width greater than known available qubits
if avail_qubits != 0 and w > avail_qubits:
continue
i_success = 0
for d in xround:
# polarization factor for low circuit widths
maxtest = maxprod / ( 1 - 1 / (2**w) )
# if circuit would fail here, don't draw box
if d > maxtest: continue
if w * d > maxtest: continue
# guess for how to capture how hardware decays with width, not entirely correct
# # reduce maxtext by a factor of number of qubits > QV_width
# # just an approximation to account for qubit distances
# if w > QV_width:
# over = w - QV_width
# maxtest = maxtest / (1 + (over/QV_width))
# draw a box at this width and depth
id = depth_index(d, depth_base)
# show vb rectangles; if not showing QV, make all hollow (or less dark)
if QV0 == 0:
#ax.add_patch(bkg_empty_box_at(id, w))
ax.add_patch(bkg_box_at(id, w, 0.95))
else:
ax.add_patch(bkg_box_at(id, w, 0.9))
# save index of last successful depth
i_success += 1
# plot empty rectangle after others
d = xround[i_success]
id = depth_index(d, depth_base)
ax.add_patch(bkg_empty_box_at(id, w))
# Add annotation showing quantum volume
if QV0 != 0:
t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12,
horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2),
bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1))
# add colorbar to right of plot
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax,
shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7))
return ax
# Function to calculate circuit depth
def calculate_circuit_depth(qc):
# Calculate the depth of the circuit
depth = qc.depth()
return depth
def calculate_transpiled_depth(qc,basis_selector):
# use either the backend or one of the basis gate sets
if basis_selector == 0:
qc = transpile(qc, backend)
else:
basis_gates = basis_gates_array[basis_selector]
qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0)
transpiled_depth = qc.depth()
return transpiled_depth,qc
def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title):
avg_fidelity_means = []
avg_Hf_fidelity_means = []
avg_num_qubits_values = list(fidelity_data.keys())
# Calculate the average fidelity and Hamming fidelity for each unique number of qubits
for num_qubits in avg_num_qubits_values:
avg_fidelity = np.average(fidelity_data[num_qubits])
avg_fidelity_means.append(avg_fidelity)
avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits])
avg_Hf_fidelity_means.append(avg_Hf_fidelity)
return avg_fidelity_means,avg_Hf_fidelity_means
list_of_gates = []
def list_of_standardgates():
import qiskit.circuit.library as lib
from qiskit.circuit import Gate
import inspect
# List all the attributes of the library module
gate_list = dir(lib)
# Filter out non-gate classes (like functions, variables, etc.)
gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)]
# Get method names from QuantumCircuit
circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction)
method_names = [name for name, _ in circuit_methods]
# Map gate class names to method names
gate_to_method = {}
for gate in gates:
gate_class = getattr(lib, gate)
class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name
for method in method_names:
if method == class_name or method == class_name.replace('cr', 'c-r'):
gate_to_method[gate] = method
break
# Add common operations that are not strictly gates
additional_operations = {
'Measure': 'measure',
'Barrier': 'barrier',
}
gate_to_method.update(additional_operations)
for k,v in gate_to_method.items():
list_of_gates.append(v)
def update_counts(gates,custom_gates):
operations = {}
for key, value in gates.items():
operations[key] = value
for key, value in custom_gates.items():
if key in operations:
operations[key] += value
else:
operations[key] = value
return operations
def get_gate_counts(gates,custom_gate_defs):
result = gates.copy()
# Iterate over the gate counts in the quantum circuit
for gate, count in gates.items():
if gate in custom_gate_defs:
custom_gate_ops = custom_gate_defs[gate]
# Multiply custom gate operations by the count of the custom gate in the circuit
for _ in range(count):
result = update_counts(result, custom_gate_ops)
# Remove the custom gate entry as we have expanded it
del result[gate]
return result
dict_of_qc = dict()
custom_gates_defs = dict()
# Function to count operations recursively
def count_operations(qc):
dict_of_qc.clear()
circuit_traverser(qc)
operations = dict()
operations = dict_of_qc[qc.name]
del dict_of_qc[qc.name]
# print("operations :",operations)
# print("dict_of_qc :",dict_of_qc)
for keys in operations.keys():
if keys not in list_of_gates:
for k,v in dict_of_qc.items():
if k in operations.keys():
custom_gates_defs[k] = v
operations=get_gate_counts(operations,custom_gates_defs)
custom_gates_defs.clear()
return operations
def circuit_traverser(qc):
dict_of_qc[qc.name]=dict(qc.count_ops())
for i in qc.data:
if str(i.operation.name) not in list_of_gates:
qc_1 = i.operation.definition
circuit_traverser(qc_1)
def get_memory():
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
max_mem = usage.ru_maxrss/1024 #in MB
return max_mem
def analyzer(num_qubits):
# we have precalculated the correct distribution that a perfect quantum computer will return
# it is stored in the json file we import at the top of the code
correct_dist = precalculated_data[f"Qubits - {num_qubits}"]
return correct_dist
num_state_qubits=1 #(default) not exposed to users
def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits,
max_circuits=max_circuits, num_shots=num_shots, use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates):
creation_times = []
elapsed_times = []
quantum_times = []
circuit_depths = []
transpiled_depths = []
fidelity_data = {}
Hf_fidelity_data = {}
numckts = []
mem_usage = []
algorithmic_1Q_gate_counts = []
algorithmic_2Q_gate_counts = []
transpiled_1Q_gate_counts = []
transpiled_2Q_gate_counts = []
print(f"{benchmark_name} Benchmark Program - {platform}")
#defining all the standard gates supported by qiskit in a list
if gate_counts_plots == True:
list_of_standardgates()
# validate parameters (smallest circuit is 2 qubits)
max_qubits = max(2, max_qubits)
min_qubits = min(max(2, min_qubits), max_qubits)
if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even
skip_qubits = max(1, skip_qubits)
#print(f"min, max qubits = {min_qubits} {max_qubits}")
global _use_XX_YY_ZZ_gates
_use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates
if _use_XX_YY_ZZ_gates:
print("... using unoptimized XX YY ZZ gates")
global max_ckts
max_ckts = max_circuits
global min_qbits,max_qbits,skp_qubits
min_qbits = min_qubits
max_qbits = max_qubits
skp_qubits = skip_qubits
print(f"min, max qubits = {min_qubits} {max_qubits}")
# Execute Benchmark Program N times for multiple circuit sizes
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
fidelity_data[num_qubits] = []
Hf_fidelity_data[num_qubits] = []
# reset random seed
np.random.seed(0)
# determine number of circuits to execute for this group
num_circuits = max(1, max_circuits)
print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}")
numckts.append(num_circuits)
# parameters of simulation
#### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA #########
w = precalculated_data['w'] # strength of disorder
k = precalculated_data['k'] # Trotter error.
# A large Trotter order approximates the Hamiltonian evolution better.
# But a large Trotter order also means the circuit is deeper.
# For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation.
t = precalculated_data['t'] # time of simulation
#######################################################################
for circuit_id in range(num_circuits):
print("*********************************************")
print(f"qc of {num_qubits} qubits for circuit_id: {circuit_id}")
#creation of Quantum Circuit.
ts = time.time()
h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1]
h_z = precalculated_data['h_z'][:num_qubits]
qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z)
#creation time
creation_time = time.time() - ts
creation_times.append(creation_time)
print(f"creation time = {creation_time*1000} ms")
# Calculate gate count for the algorithmic circuit (excluding barriers and measurements)
if gate_counts_plots == True:
operations = count_operations(qc)
n1q = 0; n2q = 0
if operations != None:
for key, value in operations.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c") or key.startswith("mc"):
n2q += value
else:
n1q += value
algorithmic_1Q_gate_counts.append(n1q)
algorithmic_2Q_gate_counts.append(n2q)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc=qc.decompose()
#print(qc)
# Calculate circuit depth
depth = calculate_circuit_depth(qc)
circuit_depths.append(depth)
# Calculate transpiled circuit depth
transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector)
transpiled_depths.append(transpiled_depth)
#print(qc)
print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}")
if gate_counts_plots == True:
# Calculate gate count for the transpiled circuit (excluding barriers and measurements)
tr_ops = qc.count_ops()
#print("tr_ops = ",tr_ops)
tr_n1q = 0; tr_n2q = 0
if tr_ops != None:
for key, value in tr_ops.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c"): tr_n2q += value
else: tr_n1q += value
transpiled_1Q_gate_counts.append(tr_n1q)
transpiled_2Q_gate_counts.append(tr_n2q)
print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}")
print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}")
#execution
if Type_of_Simulator == "built_in":
#To check if Noise is required
if Noise_Inclusion == True:
noise_model = noise_parameters
else:
noise_model = None
ts = time.time()
job = execute(qc, backend, shots=num_shots, noise_model=noise_model)
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" :
ts = time.time()
job = backend.run(qc,shots=num_shots, noise_model=noise_parameters)
#retrieving the result
result = job.result()
#print(result)
#calculating elapsed time
elapsed_time = time.time() - ts
elapsed_times.append(elapsed_time)
# Calculate quantum processing time
quantum_time = result.time_taken
quantum_times.append(quantum_time)
print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms")
#counts in result object
counts = result.get_counts()
#Correct distribution to compare with counts
correct_dist = analyzer(num_qubits)
#fidelity calculation comparision of counts and correct_dist
fidelity_dict = polarization_fidelity(counts, correct_dist)
fidelity_data[num_qubits].append(fidelity_dict['fidelity'])
Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity'])
#maximum memory utilization (if required)
if Memory_utilization_plot == True:
max_mem = get_memory()
print(f"Maximum Memory Utilized: {max_mem} MB")
mem_usage.append(max_mem)
print("*********************************************")
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
if _use_XX_YY_ZZ_gates:
print("\nXX, YY, ZZ =")
print(XX_); print(YY_); print(ZZ_)
else:
print("\nXXYYZZ_opt =")
print(XXYYZZ_)
return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths,
fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts,
transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage)
# Execute the benchmark program, accumulate metrics, and calculate circuit depths
(creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts,
algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run()
# Define the range of qubits for the x-axis
num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits)
print("num_qubits_range =",num_qubits_range)
# Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits
avg_creation_times = []
avg_elapsed_times = []
avg_quantum_times = []
avg_circuit_depths = []
avg_transpiled_depths = []
avg_1Q_algorithmic_gate_counts = []
avg_2Q_algorithmic_gate_counts = []
avg_1Q_Transpiled_gate_counts = []
avg_2Q_Transpiled_gate_counts = []
max_memory = []
start = 0
for num in numckts:
avg_creation_times.append(np.mean(creation_times[start:start+num]))
avg_elapsed_times.append(np.mean(elapsed_times[start:start+num]))
avg_quantum_times.append(np.mean(quantum_times[start:start+num]))
avg_circuit_depths.append(np.mean(circuit_depths[start:start+num]))
avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num]))
if gate_counts_plots == True:
avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num])))
avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num])))
avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num])))
avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num])))
if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num]))
start += num
# Calculate the fidelity data
avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison")
# Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits
# Add labels to the bars
def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"):
for rect in rects:
height = rect.get_height()
ax.annotate(str.format(height), # Formatting to two decimal places
xy=(rect.get_x() + rect.get_width() / 2, height / 2),
xytext=(0, 0),
textcoords="offset points",
ha='center', va=va,color=text_color,rotation=90)
bar_width = 0.3
# Determine the number of subplots and their arrangement
if Memory_utilization_plot and gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30))
# Plotting for both memory utilization and gate counts
# ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available
elif Memory_utilization_plot:
fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30))
# Plotting for memory utilization only
# ax1, ax2, ax3, ax6, ax7 are available
elif gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30))
# Plotting for gate counts only
# ax1, ax2, ax3, ax4, ax5, ax6 are available
else:
fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30))
# Default plotting
# ax1, ax2, ax3, ax6 are available
fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16)
for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000
avg_creation_times[i] *= 1000
ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue')
autolabel(ax1.patches, ax1)
ax1.set_xlabel('Number of Qubits')
ax1.set_ylabel('Average Creation Time (ms)')
ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14)
ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000
avg_elapsed_times[i] *= 1000
for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000
avg_quantum_times[i] *= 1000
Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time')
Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time')
autolabel(Elapsed,ax2,str='{:.1f}')
autolabel(Quantum,ax2,str='{:.1f}')
ax2.set_xlabel('Number of Qubits')
ax2.set_ylabel('Average Time (ms)')
ax2.set_title('Average Time vs Number of Qubits')
ax2.legend()
ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here
Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here
autolabel(Normalized,ax3,str='{:.2f}')
autolabel(Algorithmic,ax3,str='{:.2f}')
ax3.set_xlabel('Number of Qubits')
ax3.set_ylabel('Average Circuit Depth')
ax3.set_title('Average Circuit Depth vs Number of Qubits')
ax3.legend()
if gate_counts_plots == True:
ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_1Q_counts,ax4,str='{}')
autolabel(Algorithmic_1Q_counts,ax4,str='{}')
ax4.set_xlabel('Number of Qubits')
ax4.set_ylabel('Average 1-Qubit Gate Counts')
ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits')
ax4.legend()
ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_2Q_counts,ax5,str='{}')
autolabel(Algorithmic_2Q_counts,ax5,str='{}')
ax5.set_xlabel('Number of Qubits')
ax5.set_ylabel('Average 2-Qubit Gate Counts')
ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits')
ax5.legend()
ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here
Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here
autolabel(Hellinger,ax6,str='{:.2f}')
autolabel(Normalized,ax6,str='{:.2f}')
ax6.set_xlabel('Number of Qubits')
ax6.set_ylabel('Average Value')
ax6.set_title("Fidelity Comparison")
ax6.legend()
if Memory_utilization_plot == True:
ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations")
autolabel(ax7.patches, ax7)
ax7.set_xlabel('Number of Qubits')
ax7.set_ylabel('Maximum Memory Utilized (MB)')
ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14)
plt.tight_layout(rect=[0, 0, 1, 0.96])
if saveplots == True:
plt.savefig("ParameterPlotsSample.jpg")
plt.show()
# Quantum Volume Plot
Suptitle = f"Volumetric Positioning - {platform}"
appname=benchmark_name
if QV_ == None:
QV=2048
else:
QV=QV_
depth_base =2
ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity")
w_data = num_qubits_range
# determine width for circuit
w_max = 0
for i in range(len(w_data)):
y = float(w_data[i])
w_max = max(w_max, y)
d_tr_data = avg_transpiled_depths
f_data = avg_f
plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max)
anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
|
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
|
Alice-Bob-SW
|
##############################################################################
# Copyright 2023 Alice & Bob
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
import pytest
from qiskit import QuantumCircuit, execute
from qiskit_alice_bob_provider import AliceBobRemoteProvider
realserver = pytest.mark.skipif(
"not config.getoption('api_key') and not config.getoption('base_url')"
)
@realserver
def test_happy_path(base_url: str, api_key: str) -> None:
c = QuantumCircuit(1, 2)
c.initialize('+', 0)
c.measure_x(0, 0)
c.measure(0, 1)
provider = AliceBobRemoteProvider(
api_key=api_key,
url=base_url,
)
backend = provider.get_backend(
'EMU:1Q:LESCANNE_2020', average_nb_photons=6.0
)
job = execute(c, backend, shots=100)
res = job.result()
res.get_counts()
|
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/alexyev/Grover-s_Algorithm
|
alexyev
|
import matplotlib.pyplot as plt
import numpy as np
!pip install qiskit
from qiskit import IBMQ, Aer, assemble, transpile, execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
!pip install qiskit.visualization
from qiskit.visualization import *
from qiskit.tools.jupyter import *
!pip install ibm_quantum_widgets
from ibm_quantum_widgets import *
from qiskit.tools.monitor import job_monitor
provider = IBMQ.load_account()
num_qubits = 2
grover_circuit = QuantumCircuit(num_qubits, num_qubits)
def initialize_circ(qc, qubits):
for q in qubits:
qc.h(q)
return qc
grover_circuit = initialize_circ(grover_circuit, [0,1])
grover_circuit.barrier()
grover_circuit.draw()
grover_circuit.cz(0, 1)
grover_circuit.barrier()
grover_circuit.draw()
grover_circuit.h([0, 1])
grover_circuit.z([0, 1])
grover_circuit.cz(0, 1)
grover_circuit.h([0, 1])
grover_circuit.barrier()
grover_circuit.measure([0,1], [0, 1])
grover_circuit.draw()
backend = Aer.get_backend('qasm_simulator')
job = execute(grover_circuit, backend, shots = 1)
result = job.result()
counts = result.get_counts()
print(counts)
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print(device)
transpiled_grover_circuit = transpile(grover_circuit, device, optimization_level=3)
job = device.run(transpiled_grover_circuit)
job_monitor(job, interval=2)
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
|
https://github.com/duartefrazao/Quantum-Finance-Algorithms
|
duartefrazao
|
from qiskit import Aer
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
from aux_functions import IncompatibleArguments
import numpy as np
import matplotlib.pyplot as plt
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, assemble, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
#Quadratic
from qiskit.optimization import QuadraticProgram
from docplex.mp.advmodel import AdvModel
def portfolio_optimization3(assets,assets_to_include,mu,sigma,num_assets_portfolio,risk_aversion,penalty):
if len(mu) != sigma.shape[0] or len(mu) != sigma.shape[1] or len(mu) != len(assets):
raise IncompatibleArguments("Sigma, mu and assets need to be equal in size")
if not 0 <= risk_aversion <= 1:
raise IncompatibleArguments("Risk aversion needs to be in [0,1]")
if not 0 < num_assets_portfolio <= len(assets):
raise IncompatibleArguments("Number of assets to include in the portfolio needs to be smaller or equal to the number of assets passed")
if len(assets_to_include) > num_assets_portfolio:
raise IncompatibleArguments("Can't include stocks mentioned, they are more than the number of assets to include")
for asset in assets_to_include:
if not asset in assets:
raise IncompatibleArguments("Asset " + asset + " not contained in asset list")
#Initialize binary variable array
mdl = AdvModel('docplex model')
mdl.init_numpy()
decision_vars = np.array([])
to_choose_assets = np.zeros(len(assets))
for i in range(len(assets)):
curr_asset = assets[i]
if curr_asset in assets_to_include:
to_choose_assets[i]=1
decision_vars = np.append(decision_vars,[mdl.binary_var(str(curr_asset))])
#Terms
vec_ones = np.ones(len(decision_vars)) #helper vector
num_assets_chosen = np.matmul(vec_ones.T,decision_vars)
num_necessary_assets_chosen = np.matmul(to_choose_assets.T,decision_vars)
expected_num_assets_chosen = len(assets_to_include)
expected_returns_portfolio = np.matmul(mu.T,decision_vars)
variance_portfolio = np.matmul(decision_vars.T,np.dot(sigma,decision_vars)) / 2
#Objective function
mdl.minimize(
- expected_returns_portfolio
+ (risk_aversion * variance_portfolio)
+ penalty * ((expected_num_assets_chosen - num_necessary_assets_chosen)**2)
+ penalty*(num_assets_chosen - num_assets_portfolio)**2)
qubo = QuadraticProgram()
qubo.from_docplex(mdl)
if DEBUG:
print(mdl.export_as_lp_string())
return qubo
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
es_problem = driver.run()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
from qiskit.algorithms.eigensolvers import NumPyEigensolver
numpy_solver = NumPyEigensolver(filter_criterion=es_problem.get_default_filter_criterion())
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.algorithms import GroundStateEigensolver, QEOM
from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD
ansatz = UCCSD(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
initial_state=HartreeFock(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
),
)
estimator = Estimator()
# This first part sets the ground state solver
# see more about this part in the ground state calculation tutorial
solver = VQE(estimator, ansatz, SLSQP())
solver.initial_point = [0.0] * ansatz.num_parameters
gse = GroundStateEigensolver(mapper, solver)
# The qEOM algorithm is simply instantiated with the chosen ground state solver and Estimator primitive
qeom_excited_states_solver = QEOM(gse, estimator, "sd")
from qiskit_nature.second_q.algorithms import ExcitedStatesEigensolver
numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, numpy_solver)
numpy_results = numpy_excited_states_solver.solve(es_problem)
qeom_results = qeom_excited_states_solver.solve(es_problem)
print(numpy_results)
print("\n\n")
print(qeom_results)
import numpy as np
def filter_criterion(eigenstate, eigenvalue, aux_values):
return np.isclose(aux_values["ParticleNumber"][0], 2.0)
new_numpy_solver = NumPyEigensolver(filter_criterion=filter_criterion)
new_numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, new_numpy_solver)
new_numpy_results = new_numpy_excited_states_solver.solve(es_problem)
print(new_numpy_results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.visualization import plot_error_map
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
plot_error_map(backend)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""These tests are the examples given in the arXiv paper describing OpenQASM 2. Specifically, there
is a test for each subsection (except the description of 'qelib1.inc') in section 3 of
https://arxiv.org/abs/1707.03429v2. The examples are copy/pasted from the source files there."""
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import math
import os
import tempfile
import ddt
from qiskit import qasm2
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister, Qubit
from qiskit.circuit.library import U1Gate, U3Gate, CU1Gate
from qiskit.test import QiskitTestCase
from . import gate_builder
def load(string, *args, **kwargs):
# We're deliberately not using the context-manager form here because we need to use it in a
# slightly odd pattern.
# pylint: disable=consider-using-with
temp = tempfile.NamedTemporaryFile(mode="w", delete=False)
try:
temp.write(string)
# NamedTemporaryFile claims not to be openable a second time on Windows, so close it
# (without deletion) so Rust can open it again.
temp.close()
return qasm2.load(temp.name, *args, **kwargs)
finally:
# Now actually clean up after ourselves.
os.unlink(temp.name)
@ddt.ddt
class TestArxivExamples(QiskitTestCase):
@ddt.data(qasm2.loads, load)
def test_teleportation(self, parser):
example = """\
// quantum teleportation example
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
creg c0[1];
creg c1[1];
creg c2[1];
// optional post-rotation for state tomography
gate post q { }
u3(0.3,0.2,0.1) q[0];
h q[1];
cx q[1],q[2];
barrier q;
cx q[0],q[1];
h q[0];
measure q[0] -> c0[0];
measure q[1] -> c1[0];
if(c0==1) z q[2];
if(c1==1) x q[2];
post q[2];
measure q[2] -> c2[0];"""
parsed = parser(example)
post = gate_builder("post", [], QuantumCircuit([Qubit()]))
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2)
qc.append(U3Gate(0.3, 0.2, 0.1), [q[0]], [])
qc.h(q[1])
qc.cx(q[1], q[2])
qc.barrier(q)
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.measure(q[1], c1[0])
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.append(post(), [q[2]], [])
qc.measure(q[2], c2[0])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_qft(self, parser):
example = """\
// quantum Fourier transform
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c[4];
x q[0];
x q[2];
barrier q;
h q[0];
cu1(pi/2) q[1],q[0];
h q[1];
cu1(pi/4) q[2],q[0];
cu1(pi/2) q[2],q[1];
h q[2];
cu1(pi/8) q[3],q[0];
cu1(pi/4) q[3],q[1];
cu1(pi/2) q[3],q[2];
h q[3];
measure q -> c;"""
parsed = parser(example)
qc = QuantumCircuit(QuantumRegister(4, "q"), ClassicalRegister(4, "c"))
qc.x(0)
qc.x(2)
qc.barrier(range(4))
qc.h(0)
qc.append(CU1Gate(math.pi / 2), [1, 0])
qc.h(1)
qc.append(CU1Gate(math.pi / 4), [2, 0])
qc.append(CU1Gate(math.pi / 2), [2, 1])
qc.h(2)
qc.append(CU1Gate(math.pi / 8), [3, 0])
qc.append(CU1Gate(math.pi / 4), [3, 1])
qc.append(CU1Gate(math.pi / 2), [3, 2])
qc.h(3)
qc.measure(range(4), range(4))
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_inverse_qft_1(self, parser):
example = """\
// QFT and measure, version 1
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c[4];
h q;
barrier q;
h q[0];
measure q[0] -> c[0];
if(c==1) u1(pi/2) q[1];
h q[1];
measure q[1] -> c[1];
if(c==1) u1(pi/4) q[2];
if(c==2) u1(pi/2) q[2];
if(c==3) u1(pi/2+pi/4) q[2];
h q[2];
measure q[2] -> c[2];
if(c==1) u1(pi/8) q[3];
if(c==2) u1(pi/4) q[3];
if(c==3) u1(pi/4+pi/8) q[3];
if(c==4) u1(pi/2) q[3];
if(c==5) u1(pi/2+pi/8) q[3];
if(c==6) u1(pi/2+pi/4) q[3];
if(c==7) u1(pi/2+pi/4+pi/8) q[3];
h q[3];
measure q[3] -> c[3];"""
parsed = parser(example)
q = QuantumRegister(4, "q")
c = ClassicalRegister(4, "c")
qc = QuantumCircuit(q, c)
qc.h(q)
qc.barrier(q)
qc.h(q[0])
qc.measure(q[0], c[0])
qc.append(U1Gate(math.pi / 2).c_if(c, 1), [q[1]])
qc.h(q[1])
qc.measure(q[1], c[1])
qc.append(U1Gate(math.pi / 4).c_if(c, 1), [q[2]])
qc.append(U1Gate(math.pi / 2).c_if(c, 2), [q[2]])
qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 3), [q[2]])
qc.h(q[2])
qc.measure(q[2], c[2])
qc.append(U1Gate(math.pi / 8).c_if(c, 1), [q[3]])
qc.append(U1Gate(math.pi / 4).c_if(c, 2), [q[3]])
qc.append(U1Gate(math.pi / 8 + math.pi / 4).c_if(c, 3), [q[3]])
qc.append(U1Gate(math.pi / 2).c_if(c, 4), [q[3]])
qc.append(U1Gate(math.pi / 8 + math.pi / 2).c_if(c, 5), [q[3]])
qc.append(U1Gate(math.pi / 4 + math.pi / 2).c_if(c, 6), [q[3]])
qc.append(U1Gate(math.pi / 8 + math.pi / 4 + math.pi / 2).c_if(c, 7), [q[3]])
qc.h(q[3])
qc.measure(q[3], c[3])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_inverse_qft_2(self, parser):
example = """\
// QFT and measure, version 2
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
creg c0[1];
creg c1[1];
creg c2[1];
creg c3[1];
h q;
barrier q;
h q[0];
measure q[0] -> c0[0];
if(c0==1) u1(pi/2) q[1];
h q[1];
measure q[1] -> c1[0];
if(c0==1) u1(pi/4) q[2];
if(c1==1) u1(pi/2) q[2];
h q[2];
measure q[2] -> c2[0];
if(c0==1) u1(pi/8) q[3];
if(c1==1) u1(pi/4) q[3];
if(c2==1) u1(pi/2) q[3];
h q[3];
measure q[3] -> c3[0];"""
parsed = parser(example)
q = QuantumRegister(4, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
c3 = ClassicalRegister(1, "c3")
qc = QuantumCircuit(q, c0, c1, c2, c3)
qc.h(q)
qc.barrier(q)
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.append(U1Gate(math.pi / 2).c_if(c0, 1), [q[1]])
qc.h(q[1])
qc.measure(q[1], c1[0])
qc.append(U1Gate(math.pi / 4).c_if(c0, 1), [q[2]])
qc.append(U1Gate(math.pi / 2).c_if(c1, 1), [q[2]])
qc.h(q[2])
qc.measure(q[2], c2[0])
qc.append(U1Gate(math.pi / 8).c_if(c0, 1), [q[3]])
qc.append(U1Gate(math.pi / 4).c_if(c1, 1), [q[3]])
qc.append(U1Gate(math.pi / 2).c_if(c2, 1), [q[3]])
qc.h(q[3])
qc.measure(q[3], c3[0])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_ripple_carry_adder(self, parser):
example = """\
// quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184
OPENQASM 2.0;
include "qelib1.inc";
gate majority a,b,c
{
cx c,b;
cx c,a;
ccx a,b,c;
}
gate unmaj a,b,c
{
ccx a,b,c;
cx c,a;
cx a,b;
}
qreg cin[1];
qreg a[4];
qreg b[4];
qreg cout[1];
creg ans[5];
// set input states
x a[0]; // a = 0001
x b; // b = 1111
// add a to b, storing result in b
majority cin[0],b[0],a[0];
majority a[0],b[1],a[1];
majority a[1],b[2],a[2];
majority a[2],b[3],a[3];
cx a[3],cout[0];
unmaj a[2],b[3],a[3];
unmaj a[1],b[2],a[2];
unmaj a[0],b[1],a[1];
unmaj cin[0],b[0],a[0];
measure b[0] -> ans[0];
measure b[1] -> ans[1];
measure b[2] -> ans[2];
measure b[3] -> ans[3];
measure cout[0] -> ans[4];"""
parsed = parser(example)
majority_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()])
majority_definition.cx(2, 1)
majority_definition.cx(2, 0)
majority_definition.ccx(0, 1, 2)
majority = gate_builder("majority", [], majority_definition)
unmaj_definition = QuantumCircuit([Qubit(), Qubit(), Qubit()])
unmaj_definition.ccx(0, 1, 2)
unmaj_definition.cx(2, 0)
unmaj_definition.cx(0, 1)
unmaj = gate_builder("unmaj", [], unmaj_definition)
cin = QuantumRegister(1, "cin")
a = QuantumRegister(4, "a")
b = QuantumRegister(4, "b")
cout = QuantumRegister(1, "cout")
ans = ClassicalRegister(5, "ans")
qc = QuantumCircuit(cin, a, b, cout, ans)
qc.x(a[0])
qc.x(b)
qc.append(majority(), [cin[0], b[0], a[0]])
qc.append(majority(), [a[0], b[1], a[1]])
qc.append(majority(), [a[1], b[2], a[2]])
qc.append(majority(), [a[2], b[3], a[3]])
qc.cx(a[3], cout[0])
qc.append(unmaj(), [a[2], b[3], a[3]])
qc.append(unmaj(), [a[1], b[2], a[2]])
qc.append(unmaj(), [a[0], b[1], a[1]])
qc.append(unmaj(), [cin[0], b[0], a[0]])
qc.measure(b, ans[:4])
qc.measure(cout[0], ans[4])
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_randomised_benchmarking(self, parser):
example = """\
// One randomized benchmarking sequence
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
barrier q;
cz q[0],q[1];
barrier q;
s q[0];
cz q[0],q[1];
barrier q;
s q[0];
z q[0];
h q[0];
barrier q;
measure q -> c;
"""
parsed = parser(example)
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.barrier(q)
qc.cz(q[0], q[1])
qc.barrier(q)
qc.s(q[0])
qc.cz(q[0], q[1])
qc.barrier(q)
qc.s(q[0])
qc.z(q[0])
qc.h(q[0])
qc.barrier(q)
qc.measure(q, c)
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_process_tomography(self, parser):
example = """\
OPENQASM 2.0;
include "qelib1.inc";
gate pre q { } // pre-rotation
gate post q { } // post-rotation
qreg q[1];
creg c[1];
pre q[0];
barrier q;
h q[0];
barrier q;
post q[0];
measure q[0] -> c[0];"""
parsed = parser(example)
pre = gate_builder("pre", [], QuantumCircuit([Qubit()]))
post = gate_builder("post", [], QuantumCircuit([Qubit()]))
qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c"))
qc.append(pre(), [0])
qc.barrier(qc.qubits)
qc.h(0)
qc.barrier(qc.qubits)
qc.append(post(), [0])
qc.measure(0, 0)
self.assertEqual(parsed, qc)
@ddt.data(qasm2.loads, load)
def test_error_correction(self, parser):
example = """\
// Repetition code syndrome measurement
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
qreg a[2];
creg c[3];
creg syn[2];
gate syndrome d1,d2,d3,a1,a2
{
cx d1,a1; cx d2,a1;
cx d2,a2; cx d3,a2;
}
x q[0]; // error
barrier q;
syndrome q[0],q[1],q[2],a[0],a[1];
measure a -> syn;
if(syn==1) x q[0];
if(syn==2) x q[2];
if(syn==3) x q[1];
measure q -> c;"""
parsed = parser(example)
syndrome_definition = QuantumCircuit([Qubit() for _ in [None] * 5])
syndrome_definition.cx(0, 3)
syndrome_definition.cx(1, 3)
syndrome_definition.cx(1, 4)
syndrome_definition.cx(2, 4)
syndrome = gate_builder("syndrome", [], syndrome_definition)
q = QuantumRegister(3, "q")
a = QuantumRegister(2, "a")
c = ClassicalRegister(3, "c")
syn = ClassicalRegister(2, "syn")
qc = QuantumCircuit(q, a, c, syn)
qc.x(q[0])
qc.barrier(q)
qc.append(syndrome(), [q[0], q[1], q[2], a[0], a[1]])
qc.measure(a, syn)
qc.x(q[0]).c_if(syn, 1)
qc.x(q[2]).c_if(syn, 2)
qc.x(q[1]).c_if(syn, 3)
qc.measure(q, c)
self.assertEqual(parsed, qc)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
import numpy as np
N = 10**7; d = np.arange(2,N+1,1); dl = np.zeros(len(d)); nv = np.zeros(len(d))
n = 1
for j in range(2,len(d)):
nv[j] = n
dl[j] = 2**n
if d[j] >= dl[j]:
n += 1
from matplotlib import pyplot as plt
plt.plot(d,d, label=r'$d$')
plt.plot(d,dl, label=r'$dl$')
plt.xlabel(r'$d$'); plt.ylabel(r'$dl$'); plt.show()
plt.plot(d,nv, label=r'$n$')
plt.xlabel(r'$d$'); plt.ylabel(r'$n$'); plt.show()
|
https://github.com/osamarais/qiskit_iterative_solver
|
osamarais
|
import qiskit
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.extensions import UnitaryGate
import numpy as np
from scipy.linalg import fractional_matrix_power
from scipy.io import loadmat
from copy import deepcopy
# problem = 'lower triangular'
# problem = 'lower triangular identities'
# problem = 'diagonal'
problem = 'laplacian'
if 'lower triangular'==problem:
N = 16
A = np.eye(N)
for i in range(N-1):
A[i+1,i] = -1
A_orig = deepcopy(A)
A = A/2
RHS_provided = False
if 'lower triangular identities'==problem:
N = 4
I = 4
A = np.eye(N*I)
for i in range(N-1):
A[(i+1)*I:(i+2)*I,(i)*I:(i+1)*I] = -np.eye(I)
A_orig = deepcopy(A)
A = A/2
RHS_provided = False
if 'diagonal'==problem:
# # A = np.array([[1, 0, 0],[-1, 1, 0],[0, -1, 1]])/2
# step = 0.025
step = 0.05
x = np.diag(np.concatenate( (np.arange(-1,0,step),np.arange(step,1+step,step)) ) )
# x = np.diag(np.concatenate( (np.arange(1,0,-step),-np.arange(-step,-1-step,-step)) ) )
# # x = np.diag(np.arange(step,1+step,step))
# # x = np.diag([1,0.5])
# # x = np.diag(np.arange(1,0,-step))
A = x
A = np.array(A)
A_orig = deepcopy(A)
RHS_provided = False
# A = np.eye(8)
# # DON'T FORGET TO NORMALIZE A!!!!
if 'laplacian'==problem:
problem_number = 2
size = 4
iterations = int(np.floor(128/size -1))
# iterations = 7
K = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['A']
R = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['R']
B = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['B']
f = np.array( loadmat('N_{}_problem_{}.mat'.format(size,problem_number)) ).item()['f']
f = f/np.linalg.norm(f)
print('|R|_2 = {}'.format(np.linalg.norm(R,2)))
A = np.eye((iterations+1)*size,(iterations+1)*size)
for block in range(iterations):
A[(block+1)*size:(block+2)*size,(block)*size:(block+1)*size] = -R
# A[(block+1)*size:(block+2)*size,(block)*size:(block+1)*size] = -np.eye(size)
A_orig = deepcopy(A)
# Normalize the matrix using the upper bound
A = A/2
np.linalg.norm(A,2)
RHS_provided = True
# A_identities = deepcopy(A)
# spy(A_identities)
A_shape = np.shape(A_orig)
# Hermitian Dilation
# Only if A is not Hermitian
if np.any(A != A.conj().T):
A = np.block([
[np.zeros(np.shape(A)),A],
[A.conj().T,np.zeros(np.shape(A))]
])
HD = True
else:
HD = False
print(HD)
from matplotlib.pyplot import spy
spy(A)
if RHS_provided:
b = np.zeros(((iterations+1)*size,1))
for block in range(iterations):
b[(block+1)*size:(block+2)*size,:] = f
b = b / np.linalg.norm(b,2)
b = b.flatten()
b_orig = deepcopy(b)
if HD:
b = np.concatenate([b,np.zeros(b.shape)])
print(b)
# Check the norm and condition number of the matrix
if np.size(A)>1:
print( '||A||_2 = {} \n cond(A) = {} \n ||A^-1||_2 = {}'.format( np.linalg.norm(A,2), np.linalg.cond(A), np.linalg.norm(np.linalg.inv(A),2) ) )
else:
print('||A||_2 = {} \n cond(A) = {}'.format(np.linalg.norm(A),1) )
if np.size(A)>1:
A_num_qubits = int(np.ceil(np.log2(np.shape(A)[0])))
padding_size = 2**A_num_qubits - np.shape(A)[0]
if padding_size > 0:
A = np.block([
[A, np.zeros([np.shape(A)[0],padding_size])],
[np.zeros([padding_size,np.shape(A)[0]]), np.zeros([padding_size,padding_size])]
])
else:
A_num_qubits = 1
padding_size = 1
A = np.array([[A,0],[0,0]])
print(A_num_qubits)
print(padding_size)
print(A)
# If RHS is given, it also needs to be padded
if RHS_provided:
b = np.pad(b,(0,padding_size))
# Create block encoding of A by creating a Unitary matrix
# Question: does A need to be Hermitian to define this sort of block encoding?
# Answer: Yes, A is defined as Hermitian for QET and QSP
# But the block encoding U_A does not have to be Hermitian
# This block encoding needs to be the REFLECTION operator in order to
# stay consistent with the conventions of the QET or QSP
# QET uses U_A
# QSP uses O_A
O = np.block([
[A , -fractional_matrix_power(np.eye(np.shape(A)[0]) - np.linalg.matrix_power(A,2),0.5)],
[fractional_matrix_power(np.eye(np.shape(A)[0]) - np.linalg.matrix_power(A,2),0.5) , A]
])
print(O)
# We also need to get the block-encoding size, i.e. m, used to encode A in U_A
m = int(np.log2(np.shape(O)[0]) - A_num_qubits)
O_A_num_qubits = int(np.log2(np.shape(O)[0]))
print('m = {} \nNumber of Qubits for O_A is {}'.format(m,O_A_num_qubits))
# Check is still Unitary
np.linalg.norm(np.matmul(O,O.T)-np.eye(np.shape(O)[0]),2)
blockA = UnitaryGate(O,label='O_A')
register_1 = QuantumRegister(size = 1, name = '|0>')
register_2 = QuantumRegister(size = m, name = '|0^m>')
register_3 = QuantumRegister(size = O_A_num_qubits-m, name = '|\phi>')
# Create a rotation circuit in the block-encoding basis
def CR_phi_d(phi, d, register_1, register_2):
circuit = QuantumCircuit(register_1,register_2,name = 'CR_( \phi \tilde {})'.format(d))
circuit.cnot(register_2,register_1,ctrl_state=0)
circuit.rz(phi*2, register_1)
circuit.cnot(register_2,register_1,ctrl_state=0)
return circuit
from scipy.io import loadmat
phi_angles = np.array( loadmat('phi_k_50_14.mat') ).item()['phi']
phi_tilde_angles = np.zeros(np.shape(phi_angles))
temp = np.zeros(np.shape(phi_angles))
# plot QSP angles
for d,phi in enumerate(phi_angles):
if d==0 or d==np.size(phi_angles)-1:
temp[d] = phi_angles[d] - np.pi/4
else:
temp[d] = phi_angles[d]
phase_angles = phi_angles.reshape(phi_angles.shape[0])
from matplotlib import pyplot as plt
%matplotlib inline
plt.plot(phase_angles)
# It seems like using the QSP angles might be more stable numerically....
circuit = QuantumCircuit(register_1, register_2, register_3, name = 'QSP')
if RHS_provided:
circuit.initialize(b,list(reversed(register_3)))
# First thing is to Hadamard the ancilla qubit since we want Re(P(A))
circuit.h(register_1)
# Note: QSPPACK produces symmetric phase angles, so reversing phase angles is unnecessary
# for d, phi in enumerate(reversed(phase_angles)):
for d, phi in reversed(list(enumerate(phase_angles))):
circuit = circuit.compose(CR_phi_d(phi,d,register_1,register_2))
if d>0:
# The endianness of the bits matters. Need to change the order of the bits
circuit.append(blockA,list(reversed(register_3[:])) + register_2[:])
# Apply the final Hadamard gate
circuit.h(register_1)
circuit = circuit.reverse_bits()
circuit.size()
# print(circuit)
# from qiskit import transpile
# circuit = transpile(circuit)
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute
from qiskit import Aer
Aer.backends()
# solver = 'unitary'
solver = 'statevector'
machine = "CPU"
# machine = "GPU"
# precision = "single"
precision = "double"
if solver=='unitary':
# backend = Aer.get_backend('unitary_simulator',precision = 'double',device="GPU")
backend = Aer.get_backend('unitary_simulator',precision = precision,device=machine)
job = execute(circuit, backend, shots=0)
result = job.result()
QSP_unitary = result.get_unitary(circuit,100)
QSP_matrix = np.array(QSP_unitary.to_matrix())
print(QSP_matrix)
elif solver=='statevector':
backend = Aer.get_backend('statevector_simulator',precision = precision,device=machine)
# backend = Aer.get_backend('statevector_simulator',precision = 'double',device="GPU")
job = execute(circuit, backend, shots=0)
result = job.result()
QSP_statevector = result.get_statevector()
print(QSP_statevector)
if solver=='statevector':
# We can ignore the padding size and directly use the size of b (considering Hermitian dilation)
if HD:
P_A_b = np.real(QSP_statevector.data[int(b_orig.shape[0]):(2*b_orig.shape[0])])
else:
P_A_b = np.real(QSP_statevector.data[0:b.shape[0]])
P_A_b = P_A_b/np.linalg.norm(P_A_b)
b_orig.shape[0]
if solver=='statevector':
print(P_A_b)
if solver=='statevector':
expected_P_A_b = np.linalg.solve(A_orig,b_orig)
expected_P_A_b = expected_P_A_b/np.linalg.norm(expected_P_A_b)
if solver=='statevector':
print(expected_P_A_b)
if solver=='statevector':
for iteration_number in range(iterations):
plt.plot(expected_P_A_b[iteration_number*size:(iteration_number+1)*size])
if solver=='statevector':
for iteration_number in range(iterations):
plt.plot(P_A_b[iteration_number*size:(iteration_number+1)*size])
exact_solution = np.linalg.solve(K,f)
plt.plot(exact_solution/np.linalg.norm(exact_solution))
x_exact_normalized = exact_solution
x_exact_normalized = x_exact_normalized/np.linalg.norm(x_exact_normalized)
error_actual = []
if solver=='statevector':
for iteration_number in range(1,iterations):
e = x_exact_normalized - (P_A_b[iteration_number*size:(iteration_number+1)*size]/np.linalg.norm(P_A_b[iteration_number*size:(iteration_number+1)*size])).reshape(np.shape(x_exact_normalized))
error_actual.append(np.linalg.norm(e))
plt.plot(np.log10(error_actual))
error_expected = []
if solver=='statevector':
for iteration_number in range(1,iterations):
e = x_exact_normalized - (expected_P_A_b[iteration_number*size:(iteration_number+1)*size]/np.linalg.norm(expected_P_A_b[iteration_number*size:(iteration_number+1)*size])).reshape(np.shape(x_exact_normalized))
error_expected.append(np.linalg.norm(e))
plt.plot(np.log10(error_expected),'--')
plt.legend(['actual','expected'])
plt.xlabel('iterations')
plt.ylabel('log10 e')
plt.title('N = {}, {} iterations'.format(size,iterations))
error_actual
error_expected
np.linalg.cond(A_orig)
plt.plot(np.log10(np.abs(np.array(error_actual)-error_expected)))
if solver=='unitary':
A_inv = np.linalg.inv(A_orig)
if HD:
# Extract the appropriate block
N1 = 2**int(O_A_num_qubits-2)
# Remove the padding
N2 = np.shape(A_orig)[0]
P_A = np.real(QSP_matrix[N1:(N1+N2),0:N2])
else:
# Extract the appropriate block
# Remove the padding
N2 = np.shape(A_orig)[0]
P_A = np.real(QSP_matrix[0:N2,0:N2])
print(P_A/P_A[0,0])
print("Error: {}".format(np.linalg.norm(P_A/abs(P_A[0,0])-A_inv,2)))
if 'unitary'==solver and 'diagonal'==problem:
plt.plot(np.arange(-1,0,0.05),np.diag(P_A)[0:20]/abs(P_A[0,0]),'r',linewidth=3)
plt.plot(np.arange(0.05,1.05,0.05),np.diag(P_A)[20:40]/abs(P_A[0,0]),'r',linewidth=3)
plt.plot(np.arange(-1.25,0,0.01),1/np.arange(-1.25,0,0.01),'k--',)
plt.plot(np.arange(0.01,1.25,0.01),1/np.arange(0.01,1.25,0.01),'k--')
plt.ylim([-25,25])
if 'unitary'==solver and 'diagonal'==problem:
error = np.abs(np.diag(A_inv)-np.diag(P_A / abs(P_A[0,0])))
plt.plot(np.diag(A)[0:int(len(error)/2)],error[0:int(len(error)/2)],np.diag(A)[int(len(error)/2):len(error)],error[int(len(error)/2):len(error)])
plt.xlabel('normalized eigenvalues')
plt.ylabel('error')
# # np.set_printoptions(threshold=np.inf)
# for i in range(P_A.shape[0]):
# # print(QSP_matrix[i,i]/0.0062)
# print(P_A[i,i]/abs(P_A[0,0]))
# # print(QSP_matrix/QSP_matrix[0,0])
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import ddt
import qiskit.qasm2
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestLexer(QiskitTestCase):
# Most of the lexer is fully exercised in the parser tests. These tests here are really mopping
# up some error messages and whatnot that might otherwise be missed.
def test_pathological_formatting(self):
# This is deliberately _terribly_ formatted, included multiple blanks lines in quick
# succession and comments in places you really wouldn't expect to see comments.
program = """
OPENQASM
// do we really need a comment here?
2.0//and another comment very squished up
;
include // this line introduces a file import
"qelib1.inc" // this is the file imported
; // this is a semicolon
gate // we're making a gate
bell( // void, with loose parenthesis in comment )
) a,//
b{h a;cx a //,,,,
,b;}
qreg // a quantum register
q
[ // a square bracket
2];bell q[0],//
q[1];creg c[2];measure q->c;"""
parsed = qiskit.qasm2.loads(program)
expected_unrolled = qiskit.QuantumCircuit(
qiskit.QuantumRegister(2, "q"), qiskit.ClassicalRegister(2, "c")
)
expected_unrolled.h(0)
expected_unrolled.cx(0, 1)
expected_unrolled.measure([0, 1], [0, 1])
self.assertEqual(parsed.decompose(), expected_unrolled)
@ddt.data("0.25", "00.25", "2.5e-1", "2.5e-01", "0.025E+1", ".25", ".025e1", "25e-2")
def test_float_lexes(self, number):
program = f"qreg q[1]; U({number}, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [0.25, 0, 0])
def test_no_decimal_float_rejected_in_strict_mode(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError,
r"\[strict\] all floats must include a decimal point",
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(25e-2, 0, 0) q[0];", strict=True)
@ddt.data("", "qre", "cre", ".")
def test_non_ascii_bytes_error(self, prefix):
token = f"{prefix}\xff"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "encountered a non-ASCII byte"):
qiskit.qasm2.loads(token)
def test_integers_cannot_start_with_zero(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "integers cannot have leading zeroes"
):
qiskit.qasm2.loads("0123")
@ddt.data("", "+", "-")
def test_float_exponents_must_have_a_digit(self, sign):
token = f"12.34e{sign}"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "needed to see an integer exponent"
):
qiskit.qasm2.loads(token)
def test_non_builtins_cannot_be_capitalised(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "identifiers cannot start with capital"
):
qiskit.qasm2.loads("Qubit")
def test_unterminated_filename_is_invalid(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "unexpected end-of-file while lexing string literal"
):
qiskit.qasm2.loads('include "qelib1.inc')
def test_filename_with_linebreak_is_invalid(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "unexpected line break while lexing string literal"
):
qiskit.qasm2.loads('include "qe\nlib1.inc";')
def test_strict_single_quoted_path_rejected(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] paths must be in double quotes"
):
qiskit.qasm2.loads("OPENQASM 2.0; include 'qelib1.inc';", strict=True)
def test_version_must_have_word_boundary_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version"
):
qiskit.qasm2.loads("OPENQASM 2a;")
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version"
):
qiskit.qasm2.loads("OPENQASM 2.0a;")
def test_no_boundary_float_in_version_position(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM .5a;")
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM 0.2e1a;")
def test_integers_must_have_word_boundaries_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after an integer"
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[2a];")
def test_floats_must_have_word_boundaries_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(2.0a, 0, 0) q[0];")
def test_single_equals_is_rejected(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"single equals '=' is never valid"
):
qiskit.qasm2.loads("if (a = 2) U(0, 0, 0) q[0];")
def test_bare_dot_is_not_valid_float(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a numeric fractional part"
):
qiskit.qasm2.loads("qreg q[0]; U(2 + ., 0, 0) q[0];")
def test_invalid_token(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"encountered '!', which doesn't match"
):
qiskit.qasm2.loads("!")
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
'''
helloworld.py
This file is intended as a simple template for qiskit files.
The code can be found at: https://qiskit.org/documentation/intro_tutorial1.html
'''
### 1. Import Packages
import numpy as np
from matplotlib import pyplot
from qiskit import QuantumCircuit, transpile # instructions of quantum system
from qiskit.providers.aer import QasmSimulator # Aer high performance circuit simulator
from qiskit.visualization import plot_histogram # creates histograms of circuit output
### 2. Initialize Variables
circuit = QuantumCircuit(2,2) # initialize the 2 qubits in zero state, and 2 classical bits set to 0
### 3. Add gates
circuit.h(0) # add Hadamard gate on qubit 0
circuit.cx(0, 1) # add CNOT gate with control qubit 0 and target qubit 1
circuit.measure([0,1], [0,1]) # Measure the two qubits and saves the result to the two classical bits
# Note: this circuit implements a simple Bell state, where there is equal chance of measuring |00> and |11>
### 4. Visualize the Circuit
circuit.draw(output='mpl') # draw the circuit as matplotlib figure
pyplot.show() # show the figure
### 5. Simulate the Experiment
simulator = QasmSimulator() # Create instance of Aer's qasm_simulator
compiled_circuit = transpile(circuit, simulator) # Compile the circuit down to low-level QASM instructions.
# Supported by the backend (not needed for simple circuits)
job = simulator.run(compiled_circuit, shots=1000) # Execute circuit on qasm simulator
result = job.result() # Fetch results
counts = result.get_counts(circuit) # Get the counts of outcomes from results
print("\nTotal count for 00 and 11 are:", counts) # Print total count for each outcome
### 6. Visualize the Results
plot_histogram(counts) # plots the results as a histogram
pyplot.show() # show the figure
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.