repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/kardashin/E91_protocol
|
kardashin
|
# Checking the version of PYTHON; we only support > 3.5
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
# useful additional packages
import numpy as np
import random
import math
import re # regular expressions module
# importing the QISKit
from qiskit import QuantumCircuit, QuantumProgram
import Qconfig
# Quantum program setup
Q_program = QuantumProgram()
Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url
# Creating registers
qr = Q_program.create_quantum_register("qr", 2)
cr = Q_program.create_classical_register("cr", 4)
singlet = Q_program.create_circuit('singlet', [qr], [cr])
singlet.x(qr[0])
singlet.x(qr[1])
singlet.h(qr[0])
singlet.cx(qr[0],qr[1])
## Alice's measurement circuits
# measure the spin projection of Alice's qubit onto the a_1 direction (X basis)
measureA1 = Q_program.create_circuit('measureA1', [qr], [cr])
measureA1.h(qr[0])
measureA1.measure(qr[0],cr[0])
# measure the spin projection of Alice's qubit onto the a_2 direction (W basis)
measureA2 = Q_program.create_circuit('measureA2', [qr], [cr])
measureA2.s(qr[0])
measureA2.h(qr[0])
measureA2.t(qr[0])
measureA2.h(qr[0])
measureA2.measure(qr[0],cr[0])
# measure the spin projection of Alice's qubit onto the a_3 direction (standard Z basis)
measureA3 = Q_program.create_circuit('measureA3', [qr], [cr])
measureA3.measure(qr[0],cr[0])
## Bob's measurement circuits
# measure the spin projection of Bob's qubit onto the b_1 direction (W basis)
measureB1 = Q_program.create_circuit('measureB1', [qr], [cr])
measureB1.s(qr[1])
measureB1.h(qr[1])
measureB1.t(qr[1])
measureB1.h(qr[1])
measureB1.measure(qr[1],cr[1])
# measure the spin projection of Bob's qubit onto the b_2 direction (standard Z basis)
measureB2 = Q_program.create_circuit('measureB2', [qr], [cr])
measureB2.measure(qr[1],cr[1])
# measure the spin projection of Bob's qubit onto the b_3 direction (V basis)
measureB3 = Q_program.create_circuit('measureB3', [qr], [cr])
measureB3.s(qr[1])
measureB3.h(qr[1])
measureB3.tdg(qr[1])
measureB3.h(qr[1])
measureB3.measure(qr[1],cr[1])
## Lists of measurement circuits
aliceMeasurements = [measureA1, measureA2, measureA3]
bobMeasurements = [measureB1, measureB2, measureB3]
# Define the number of singlets N
numberOfSinglets = 500
aliceMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b of Alice
bobMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b' of Bob
circuits = [] # the list in which the created circuits will be stored
for i in range(numberOfSinglets):
# create the name of the i-th circuit depending on Alice's and Bob's measurement choices
circuitName = str(i) + ':A' + str(aliceMeasurementChoices[i]) + '_B' + str(bobMeasurementChoices[i])
# create the joint measurement circuit
# add Alice's and Bob's measurement circuits to the singlet state curcuit
Q_program.add_circuit(circuitName,
singlet + # singlet state circuit
aliceMeasurements[aliceMeasurementChoices[i]-1] + # measurement circuit of Alice
bobMeasurements[bobMeasurementChoices[i]-1] # measurement circuit of Bob
)
# add the created circuit to the circuits list
circuits.append(circuitName)
print(circuits[0])
result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240)
print(result)
result.get_counts(circuits[0])
abPatterns = [
re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1)
re.compile('..01$'), # search for the '..01' output
re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1)
re.compile('..11$') # search for the '..11' output
]
aliceResults = [] # Alice's results (string a)
bobResults = [] # Bob's results (string a')
for i in range(numberOfSinglets):
res = list(result.get_counts(circuits[i]).keys())[0] # extract the key from the dict and transform it to str; execution result of the i-th circuit
if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(-1) # Bob got the result -1
if abPatterns[1].search(res):
aliceResults.append(1)
bobResults.append(-1)
if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(1) # Bob got the result 1
if abPatterns[3].search(res):
aliceResults.append(1)
bobResults.append(1)
aliceKey = [] # Alice's key string k
bobKey = [] # Bob's key string k'
# comparing the stings with measurement choices
for i in range(numberOfSinglets):
# if Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions
if (aliceMeasurementChoices[i] == 2 and bobMeasurementChoices[i] == 1) or (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 2):
aliceKey.append(aliceResults[i]) # record the i-th result obtained by Alice as the bit of the secret key k
bobKey.append(- bobResults[i]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k'
keyLength = len(aliceKey) # length of the secret key
abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's keys
for j in range(keyLength):
if aliceKey[j] != bobKey[j]:
abKeyMismatches += 1
# function that calculates CHSH correlation value
def chsh_corr(result):
# lists with the counts of measurement results
# each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively
countA1B1 = [0, 0, 0, 0] # XW observable
countA1B3 = [0, 0, 0, 0] # XV observable
countA3B1 = [0, 0, 0, 0] # ZW observable
countA3B3 = [0, 0, 0, 0] # ZV observable
for i in range(numberOfSinglets):
res = list(result.get_counts(circuits[i]).keys())[0]
# if the spins of the qubits of the i-th singlet were projected onto the a_1/b_1 directions
if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 1):
for j in range(4):
if abPatterns[j].search(res):
countA1B1[j] += 1
if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 3):
for j in range(4):
if abPatterns[j].search(res):
countA1B3[j] += 1
if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 1):
for j in range(4):
if abPatterns[j].search(res):
countA3B1[j] += 1
# if the spins of the qubits of the i-th singlet were projected onto the a_3/b_3 directions
if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 3):
for j in range(4):
if abPatterns[j].search(res):
countA3B3[j] += 1
# number of the results obtained from the measurements in a particular basis
total11 = sum(countA1B1)
total13 = sum(countA1B3)
total31 = sum(countA3B1)
total33 = sum(countA3B3)
# expectation values of XW, XV, ZW and ZV observables (2)
expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # -1/sqrt(2)
expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total13 # 1/sqrt(2)
expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total31 # -1/sqrt(2)
expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # -1/sqrt(2)
corr = expect11 - expect13 + expect31 + expect33 # calculate the CHSC correlation value (3)
return corr
corr = chsh_corr(result) # CHSH correlation value
# CHSH inequality test
print('CHSH correlation value: ' + str(round(corr, 3)))
# Keys
print('Length of the key: ' + str(keyLength))
print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n')
# measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis)
measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr])
measureEA2.s(qr[0])
measureEA2.h(qr[0])
measureEA2.t(qr[0])
measureEA2.h(qr[0])
measureEA2.measure(qr[0],cr[2])
# measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis)
measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr])
measureEA3.measure(qr[0],cr[2])
# measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis)
measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr])
measureEB1.s(qr[1])
measureEB1.h(qr[1])
measureEB1.t(qr[1])
measureEB1.h(qr[1])
measureEB1.measure(qr[1],cr[3])
# measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement)
measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr])
measureEB2.measure(qr[1],cr[3])
# lists of measurement circuits
eveMeasurements = [measureEA2, measureEA3, measureEB1, measureEB2]
# list of Eve's measurement choices
# the first and the second elements of each row represent the measurement of Alice's and Bob's qubits by Eve respectively
eveMeasurementChoices = []
for j in range(numberOfSinglets):
if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement
eveMeasurementChoices.append([0, 2])
else: # in 50% of cases perform the ZZ measurement
eveMeasurementChoices.append([1, 3])
circuits = [] # the list in which the created circuits will be stored
for j in range(numberOfSinglets):
# create the name of the j-th circuit depending on Alice's, Bob's and Eve's choices of measurement
circuitName = str(j) + ':A' + str(aliceMeasurementChoices[j]) + '_B' + str(bobMeasurementChoices[j] + 2) + '_E' + str(eveMeasurementChoices[j][0]) + str(eveMeasurementChoices[j][1] - 1)
# create the joint measurement circuit
# add Alice's and Bob's measurement circuits to the singlet state curcuit
Q_program.add_circuit(circuitName,
singlet + # singlet state circuit
eveMeasurements[eveMeasurementChoices[j][0]-1] + # Eve's measurement circuit of Alice's qubit
eveMeasurements[eveMeasurementChoices[j][1]-1] + # Eve's measurement circuit of Bob's qubit
aliceMeasurements[aliceMeasurementChoices[j]-1] + # measurement circuit of Alice
bobMeasurements[bobMeasurementChoices[j]-1] # measurement circuit of Bob
)
# add the created circuit to the circuits list
circuits.append(circuitName)
result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240)
print(result)
print(str(circuits[0]) + '\t' + str(result.get_counts(circuits[0])))
ePatterns = [
re.compile('00..$'), # search for the '00..' result (Eve obtained the results -1 and -1 for Alice's and Bob's qubits)
re.compile('01..$'), # search for the '01..' result (Eve obtained the results 1 and -1 for Alice's and Bob's qubits)
re.compile('10..$'),
re.compile('11..$')
]
aliceResults = [] # Alice's results (string a)
bobResults = [] # Bob's results (string a')
# list of Eve's measurement results
# the elements in the 1-st column are the results obtaned from the measurements of Alice's qubits
# the elements in the 2-nd column are the results obtaned from the measurements of Bob's qubits
eveResults = []
# recording the measurement results
for j in range(numberOfSinglets):
res = list(result.get_counts(circuits[j]).keys())[0] # extract a key from the dict and transform it to str
# Alice and Bob
if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(-1) # Bob got the result -1
if abPatterns[1].search(res):
aliceResults.append(1)
bobResults.append(-1)
if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(1) # Bob got the result 1
if abPatterns[3].search(res):
aliceResults.append(1)
bobResults.append(1)
# Eve
if ePatterns[0].search(res): # check if the key is '00..'
eveResults.append([-1, -1]) # results of the measurement of Alice's and Bob's qubits are -1,-1
if ePatterns[1].search(res):
eveResults.append([1, -1])
if ePatterns[2].search(res):
eveResults.append([-1, 1])
if ePatterns[3].search(res):
eveResults.append([1, 1])
aliceKey = [] # Alice's key string a
bobKey = [] # Bob's key string a'
eveKeys = [] # Eve's keys; the 1-st column is the key of Alice, and the 2-nd is the key of Bob
# comparing the strings with measurement choices (b and b')
for j in range(numberOfSinglets):
# if Alice and Bob measured the spin projections onto the a_2/b_1 or a_3/b_2 directions
if (aliceMeasurementChoices[j] == 2 and bobMeasurementChoices[j] == 1) or (aliceMeasurementChoices[j] == 3 and bobMeasurementChoices[j] == 2):
aliceKey.append(aliceResults[j]) # record the i-th result obtained by Alice as the bit of the secret key k
bobKey.append(-bobResults[j]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k'
eveKeys.append([eveResults[j][0], -eveResults[j][1]]) # record the i-th bits of the keys of Eve
keyLength = len(aliceKey) # length of the secret skey
abKeyMismatches = 0 # number of mismatching bits in the keys of Alice and Bob
eaKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Alice
ebKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Bob
for j in range(keyLength):
if aliceKey[j] != bobKey[j]:
abKeyMismatches += 1
if eveKeys[j][0] != aliceKey[j]:
eaKeyMismatches += 1
if eveKeys[j][1] != bobKey[j]:
ebKeyMismatches += 1
eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Bob's key
ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Alice's key
corr = chsh_corr(result)
# CHSH inequality test
print('CHSH correlation value: ' + str(round(corr, 3)) + '\n')
# Keys
print('Length of the key: ' + str(keyLength))
print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n')
print('Eve\'s knowledge of Alice\'s key: ' + str(round(eaKnowledge * 100, 2)) + ' %')
print('Eve\'s knowledge of Bob\'s key: ' + str(round(ebKnowledge * 100, 2)) + ' %')
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
MaxCut Benchmark Program - QSim
"""
import datetime
import json
import logging
import math
import os
import re
import sys
import time
from collections import namedtuple
import numpy as np
from scipy.optimize import minimize
from qiskit import (BasicAer, ClassicalRegister, # for computing expectation tables
QuantumCircuit, QuantumRegister, execute, transpile)
from qiskit.circuit import ParameterVector
sys.path[1:1] = [ "_common", "_common/qsim", "maxcut/_common" ]
sys.path[1:1] = [ "../../_common", "../../_common/qsim", "../../maxcut/_common/" ]
import common
import execute as ex
import metrics as metrics
from execute import BenchmarkResult
# DEVNOTE: this logging feature should be moved to common level
logger = logging.getLogger(__name__)
fname, _, ext = os.path.basename(__file__).partition(".")
log_to_file = False
try:
if log_to_file:
logging.basicConfig(
# filename=f"{fname}_{datetime.datetime.now().strftime('%Y_%m_%d_%S')}.log",
filename=f"{fname}.log",
filemode='w',
encoding='utf-8',
level=logging.INFO,
format='%(asctime)s %(name)s - %(levelname)s:%(message)s'
)
else:
logging.basicConfig(
level=logging.WARNING,
format='%(asctime)s %(name)s - %(levelname)s:%(message)s')
except Exception as e:
print(f'Exception {e} occured while configuring logger: bypassing logger config to prevent data loss')
pass
# Benchmark Name
benchmark_name = "MaxCut"
np.random.seed(0)
maxcut_inputs = dict() #inputs to the run method
verbose = False
print_sample_circuit = True
# Indicates whether to perform the (expensive) pre compute of expectations
do_compute_expectation = True
# saved circuits for display
QC_ = None
Uf_ = None
# based on examples from https://qiskit.org/textbook/ch-applications/qaoa.html
QAOA_Parameter = namedtuple('QAOA_Parameter', ['beta', 'gamma'])
# Qiskit uses the little-Endian convention. Hence, measured bit-strings need to be reversed while evaluating cut sizes
reverseStep = -1
#%% MaxCut circuit creation and fidelity analaysis functions
def create_qaoa_circ(nqubits, edges, parameters):
qc = QuantumCircuit(nqubits)
# initial_state
for i in range(0, nqubits):
qc.h(i)
for par in parameters:
#print(f"... gamma, beta = {par.gamma} {par.beta}")
# problem unitary
for i,j in edges:
qc.rzz(- par.gamma, i, j)
qc.barrier()
# mixer unitary
for i in range(0, nqubits):
qc.rx(2 * par.beta, i)
return qc
def MaxCut (num_qubits, secret_int, edges, rounds, thetas_array, parameterized, measured = True):
if parameterized:
return MaxCut_param(num_qubits, secret_int, edges, rounds, thetas_array)
# if no thetas_array passed in, create defaults
if thetas_array is None:
thetas_array = 2*rounds*[1.0]
#print(f"... incoming thetas_array={thetas_array} rounds={rounds}")
# get number of qaoa rounds (p) from length of incoming array
p = len(thetas_array)//2
# if rounds passed in is less than p, truncate array
if rounds < p:
p = rounds
thetas_array = thetas_array[:2*rounds]
# if more rounds requested than in thetas_array, give warning (can fill array later)
elif rounds > p:
rounds = p
print(f"WARNING: rounds is greater than length of thetas_array/2; using rounds={rounds}")
logger.info(f'*** Constructing NON-parameterized circuit for num_qubits = {num_qubits} secret_int = {secret_int}')
# create parameters in the form expected by the ansatz generator
# this is an array of betas followed by array of gammas, each of length = rounds
betas = thetas_array[:p]
gammas = thetas_array[p:]
parameters = [QAOA_Parameter(*t) for t in zip(betas,gammas)]
# and create the circuit, without measurements
qc = create_qaoa_circ(num_qubits, edges, parameters)
# pre-compute and save an array of expected measurements
if do_compute_expectation:
logger.info('Computing expectation')
compute_expectation(qc, num_qubits, secret_int)
# add the measure here
if measured: qc.measure_all()
# save small circuit example for display
global QC_
if QC_ == None or num_qubits <= 6:
if num_qubits < 9: QC_ = qc
# return a handle on the circuit
return qc, None
############### Circuit Definition - Parameterized version
# Create ansatz specific to this problem, defined by G = nodes, edges, and the given parameters
# Do not include the measure operation, so we can pre-compute statevector
def create_qaoa_circ_param(nqubits, edges, betas, gammas):
qc = QuantumCircuit(nqubits)
# initial_state
for i in range(0, nqubits):
qc.h(i)
for beta, gamma in zip(betas, gammas):
#print(f"... gamma, beta = {gammas}, {betas}")
# problem unitary
for i,j in edges:
qc.rzz(- gamma, i, j)
qc.barrier()
# mixer unitary
for i in range(0, nqubits):
qc.rx(2 * beta, i)
return qc
_qc = None
beta_params = []
gamma_params = []
# Create the benchmark program circuit
# Accepts optional rounds and array of thetas (betas and gammas)
def MaxCut_param (num_qubits, secret_int, edges, rounds, thetas_array):
# if no thetas_array passed in, create defaults
if thetas_array is None:
thetas_array = 2*rounds*[1.0]
#print(f"... incoming thetas_array={thetas_array} rounds={rounds}")
# get number of qaoa rounds (p) from length of incoming array
p = len(thetas_array)//2
# if rounds passed in is less than p, truncate array
if rounds < p:
p = rounds
thetas_array = thetas_array[:2*rounds]
# if more rounds requested than in thetas_array, give warning (can fill array later)
elif rounds > p:
rounds = p
print(f"WARNING: rounds is greater than length of thetas_array/2; using rounds={rounds}")
#print(f"... actual thetas_array={thetas_array}")
# create parameters in the form expected by the ansatz generator
# this is an array of betas followed by array of gammas, each of length = rounds
global _qc
global betas
global gammas
# create the circuit the first time, add measurements
if ex.do_transpile_for_execute:
logger.info(f'*** Constructing parameterized circuit for num_qubits = {num_qubits} secret_int = {secret_int}')
betas = ParameterVector("𝞫", p)
gammas = ParameterVector("𝞬", p)
_qc = create_qaoa_circ_param(num_qubits, edges, betas, gammas)
# add the measure here, only after circuit is created
_qc.measure_all()
params = {betas: thetas_array[:p], gammas: thetas_array[p:]}
#logger.info(f"Binding parameters {params = }")
logger.info(f"Create binding parameters for {thetas_array}")
qc = _qc
#print(qc)
# pre-compute and save an array of expected measurements
if do_compute_expectation:
logger.info('Computing expectation')
compute_expectation(qc, num_qubits, secret_int, params=params)
# save small circuit example for display
global QC_
if QC_ == None or num_qubits <= 6:
if num_qubits < 9: QC_ = qc
# return a handle on the circuit
return qc, params
############### Expectation Tables
# DEVNOTE: We are building these tables on-demand for now, but for larger circuits
# this will need to be pre-computed ahead of time and stored in a data file to avoid run-time delays.
# dictionary used to store pre-computed expectations, keyed by num_qubits and secret_string
# these are created at the time the circuit is created, then deleted when results are processed
expectations = {}
# Compute array of expectation values in range 0.0 to 1.0
# Use statevector_simulator to obtain exact expectation
def compute_expectation(qc, num_qubits, secret_int, backend_id='statevector_simulator', params=None):
#ts = time.time()
if params != None:
qc = qc.bind_parameters(params)
#execute statevector simulation
sv_backend = BasicAer.get_backend(backend_id)
sv_result = execute(qc, sv_backend).result()
# get the probability distribution
counts = sv_result.get_counts()
#print(f"... statevector expectation = {counts}")
# store in table until circuit execution is complete
id = f"_{num_qubits}_{secret_int}"
expectations[id] = counts
#print(f" ... time to execute statevector simulator: {time.time() - ts}")
# Return expected measurement array scaled to number of shots executed
def get_expectation(num_qubits, degree, num_shots):
# find expectation counts for the given circuit
id = f"_{num_qubits}_{degree}"
if id in expectations:
counts = expectations[id]
# scale to number of shots
for k, v in counts.items():
# counts[k] = round(v * num_shots)
counts[k] = v * num_shots
# delete from the dictionary
del expectations[id]
return counts
else:
return None
############### Result Data Analysis
expected_dist = {}
# Compare the measurement results obtained with the expected measurements to determine fidelity
def analyze_and_print_result (qc, result, num_qubits, secret_int, num_shots):
global expected_dist
# print(result)
if result.backend_name == 'dm_simulator':
try:
probs = result.results[0].data.partial_probability # get results as measured probability
except AttributeError:
try:
probs = result.results[0].data.ensemble_probability
except AttributeError:
probs = None
else:
probs = result.get_counts(qc) # get results as measured counts
# retrieve pre-computed expectation values for the circuit that just completed
expected_dist = get_expectation(num_qubits, secret_int, num_shots)
# if the expectation is not being calculated (only need if we want to compute fidelity)
# assume that the expectation is the same as measured probability, yielding fidelity = 1
if expected_dist == None:
expected_dist = probs
# print("\nexpected_dist ====== ", expected_dist)
if verbose: print(f"For width {num_qubits} problem {secret_int}\n measured: {probs}\n expected: {expected_dist}")
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(probs, expected_dist)
if verbose: print(f"For secret int {secret_int} fidelity: {fidelity}")
return probs, fidelity
#%% Computation of various metrics, such as approximation ratio, etc.
def compute_cutsizes(results, nodes, edges):
"""
Given a result object, extract the values of meaasured cuts and the corresponding
counts into ndarrays. Also compute and return the corresponding cut sizes.
Returns
-------
cuts : list of strings
each element is a bitstring denoting a cut
counts : ndarray of ints
measured counts corresponding to cuts
sizes : ndarray of ints
cut sizes (i.e. number of edges crossing the cut)
"""
cuts = list(results.results[0].data.partial_probability.keys())
counts = list(results.results[0].data.partial_probability.values())
sizes = [common.eval_cut(nodes, edges, cut, reverseStep) for cut in cuts]
return cuts, counts, sizes
def get_size_dist(counts, sizes):
""" For given measurement outcomes, i.e. combinations of cuts, counts and sizes, return counts corresponding to each cut size.
"""
unique_sizes = list(set(sizes))
unique_counts = [0] * len(unique_sizes)
for i, size in enumerate(unique_sizes):
corresp_counts = [counts[ind] for ind,s in enumerate(sizes) if s == size]
unique_counts[i] = sum(corresp_counts)
# Make sure that the scores are in ascending order
s_and_c_list = [[a,b] for (a,b) in zip(unique_sizes, unique_counts)]
s_and_c_list = sorted(s_and_c_list, key = lambda x : x[0])
unique_sizes = [x[0] for x in s_and_c_list]
unique_counts = [x[1] for x in s_and_c_list]
cumul_counts = np.cumsum(unique_counts)
return unique_counts, unique_sizes, cumul_counts.tolist()
# Compute the objective function on a given sample
def compute_sample_mean(counts, sizes, **kwargs):
"""
Compute the mean of cut sizes (i.e. the weighted average of sizes weighted by counts)
This approximates the expectation value of the state at the end of the circuit
Parameters
----------
counts : ndarray of ints
measured counts corresponding to cuts
sizes : ndarray of ints
cut sizes (i.e. number of edges crossing the cut)
**kwargs : optional arguments
will be ignored
Returns
-------
float
"""
# Convert counts and sizes to ndarrays, if they are lists
counts, sizes = np.array(counts), np.array(sizes)
return - np.sum(counts * sizes) / np.sum(counts)
def compute_cvar(counts, sizes, alpha = 0.1, **kwargs):
"""
Obtains the Conditional Value at Risk or CVaR for samples measured at the end of the variational circuit.
Reference: Barkoutsos, P. K., Nannicini, G., Robert, A., Tavernelli, I. & Woerner, S. Improving Variational Quantum Optimization using CVaR. Quantum 4, 256 (2020).
Parameters
----------
counts : ndarray of ints
measured counts corresponding to cuts
sizes : ndarray of ints
cut sizes (i.e. number of edges crossing the cut)
alpha : float, optional
Confidence interval value for CVaR. The default is 0.1.
Returns
-------
float
CVaR value
"""
# Convert counts and sizes to ndarrays, if they are lists
counts, sizes = np.array(counts), np.array(sizes)
# Sort the negative of the cut sizes in a non-decreasing order.
# Sort counts in the same order as sizes, so that i^th element of each correspond to each other
sort_inds = np.argsort(-sizes)
sizes = sizes[sort_inds]
counts = counts[sort_inds]
# Choose only the top num_avgd = ceil(alpha * num_shots) cuts. These will be averaged over.
num_avgd = math.ceil(alpha * np.sum(counts))
# Compute cvar
cvar_sum = 0
counts_so_far = 0
for c, s in zip(counts, sizes):
if counts_so_far + c >= num_avgd:
cts_to_consider = num_avgd - counts_so_far
cvar_sum += cts_to_consider * s
break
else:
counts_so_far += c
cvar_sum += c * s
return - cvar_sum / num_avgd
def compute_gibbs(counts, sizes, eta = 0.5, **kwargs):
"""
Compute the Gibbs objective function for given measurements
Parameters
----------
counts : ndarray of ints
measured counts corresponding to cuts
sizes : ndarray of ints
cut sizes (i.e. number of edges crossing the cut)
eta : float, optional
Inverse Temperature
Returns
-------
float
- Gibbs objective function value / optimal value
"""
# Convert counts and sizes to ndarrays, if they are lists
counts, sizes = np.array(counts), np.array(sizes)
ls = max(sizes)#largest size
shifted_sizes = sizes - ls
# gibbs = - np.log( np.sum(counts * np.exp(eta * sizes)) / np.sum(counts))
gibbs = - eta * ls - np.log(np.sum (counts / np.sum(counts) * np.exp(eta * shifted_sizes)))
return gibbs
def compute_best_cut_from_measured(counts, sizes, **kwargs):
"""From the measured cuts, return the size of the largest cut
"""
return - np.max(sizes)
def compute_quartiles(counts, sizes):
"""
Compute and return the sizes of the cuts at the three quartile values (i.e. 0.25, 0.5 and 0.75)
Parameters
----------
counts : ndarray of ints
measured counts corresponding to cuts
sizes : ndarray of ints
cut sizes (i.e. number of edges crossing the cut)
Returns
-------
quantile_sizes : ndarray of of 3 floats
sizes of cuts corresponding to the three quartile values.
"""
# Convert counts and sizes to ndarrays, if they are lists
counts, sizes = np.array(counts), np.array(sizes)
# Sort sizes and counts in the sequence of non-decreasing values of sizes
sort_inds = np.argsort(sizes)
sizes = sizes[sort_inds]
counts = counts[sort_inds]
num_shots = np.sum(counts)
q_vals = [0.25, 0.5, 0.75]
ct_vals = [math.floor(q * num_shots) for q in q_vals]
cumsum_counts = np.cumsum(counts)
locs = np.searchsorted(cumsum_counts, ct_vals)
quantile_sizes = sizes[locs]
return quantile_sizes
def uniform_cut_sampling(num_qubits, degree, num_shots, _instances=None):
"""
For a given problem, i.e. num_qubits and degree values, sample cuts uniformly
at random from all possible cuts, num_shots number of times. Return the corresponding
cuts, counts and cut sizes.
"""
# First, load the nodes and edges corresponding to the problem
instance_filename = os.path.join(os.path.dirname(__file__),
"..", "_common", common.INSTANCE_DIR,
f"mc_{num_qubits:03d}_{degree:03d}_000.txt")
nodes, edges = common.read_maxcut_instance(instance_filename, _instances)
# Obtain num_shots number of uniform random samples between 0 and 2 ** num_qubits
unif_cuts = np.random.randint(2 ** num_qubits, size=num_shots).tolist()
unif_cuts_uniq = list(set(unif_cuts))
# Get counts corresponding to each sampled int/cut
unif_counts = [unif_cuts.count(cut) for cut in unif_cuts_uniq]
unif_cuts = list(set(unif_cuts))
def int_to_bs(numb):
# Function for converting from an integer to (bit)strings of length num_qubits
strr = format(numb, "b") #convert to binary
strr = '0' * (num_qubits - len(strr)) + strr
return strr
unif_cuts = [int_to_bs(i) for i in unif_cuts]
unif_sizes = [common.eval_cut(nodes, edges, cut, reverseStep) for cut in unif_cuts]
# Also get the corresponding distribution of cut sizes
unique_counts_unif, unique_sizes_unif, cumul_counts_unif = get_size_dist(unif_counts, unif_sizes)
return unif_cuts, unif_counts, unif_sizes, unique_counts_unif, unique_sizes_unif, cumul_counts_unif
def get_random_angles(rounds, restarts):
"""Create max_circuit number of random initial conditions
Args:
rounds (int): number of rounds in QAOA
restarts (int): number of random initial conditions
Returns:
restarts (list of lists of floats): list of length restarts. Each list element is a list of angles
"""
# restarts = min(10, restarts)
# Create random angles
theta_min = [0] * 2 * rounds
# Upper limit for betas=pi; upper limit for gammas=2pi
theta_max = [np.pi] * rounds + [2 * np.pi] * rounds
thetas = np.random.uniform(
low=theta_min, high=theta_max, size=(restarts, 2 * rounds)
)
thetas = thetas.tolist()
return thetas
def get_restart_angles(thetas_array, rounds, restarts):
"""
Create random initial conditions for the restart loop.
thetas_array takes precedence over restarts.
If the user inputs valid thetas_array, restarts will be inferred accordingly.
If thetas_array is None and restarts is 1, return all 1's as initial angles.
If thetas_array is None and restarts >1, generate restarts number of random initial conditions
If only one set of random angles are desired, then the user needs to create them and send as thetas_array
Args:
thetas_array (list of lists of floats): list of initial angles.
restarts (int): number of random initial conditions
rounds (int): of QAOA
Returns:
thetas (list of lists. Shape = (max_circuits, 2 * rounds))
restarts : int
"""
assert type(restarts) == int and restarts > 0, "max_circuits must be an integer greater than 0"
default_angles = [[1] * 2 * rounds]
default_restarts = 1
if thetas_array is None:
if restarts == 1:
# if the angles are none, but restarts equals 1, use default of all 1's
return default_angles, default_restarts
else:
# restarts can only be greater than 1.
return get_random_angles(rounds, restarts), restarts
if type(thetas_array) != list:
# thetas_array is not None, but is also not a list.
print("thetas_array is not a list. Using random angles.")
return get_random_angles(rounds, restarts), restarts
# At this point, thetas_array is a list. check if thetas_array is a list of lists
if not all([type(item) == list for item in thetas_array]):
# if every list element is not a list, return random angles
print("thetas_array is not a list of lists. Using random angles.")
return get_random_angles(rounds, restarts), restarts
if not all([len(item) == 2 * rounds for item in thetas_array]):
# If not all list elements are lists of the correct length...
print("Each element of thetas_array must be a list of length 2 * rounds. Using random angles.")
return get_random_angles(rounds, restarts), restarts
# At this point, thetas_array is a list of lists of length 2*rounds. All conditions are satisfied. Return inputted angles.
return thetas_array, len(thetas_array)
#%% Storing final iteration data to json file, and to metrics.circuit_metrics_final_iter
def save_runtime_data(result_dict): # This function will need changes, since circuit metrics dictionaries are now different
cm = result_dict.get('circuit_metrics')
detail = result_dict.get('circuit_metrics_detail', None)
detail_2 = result_dict.get('circuit_metrics_detail_2', None)
benchmark_inputs = result_dict.get('benchmark_inputs', None)
final_iter_metrics = result_dict.get('circuit_metrics_final_iter')
backend_id = result_dict.get('benchmark_inputs').get('backend_id')
metrics.circuit_metrics_detail_2 = detail_2
for width in detail_2:
# unique_id = restart_ind * 1000 + minimizer_iter_ind
restart_ind_list = list(detail_2.get(width).keys())
for restart_ind in restart_ind_list:
degree = cm[width]['1']['degree']
opt = final_iter_metrics[width]['1']['optimal_value']
instance_filename = os.path.join(os.path.dirname(__file__),
"..", "_common", common.INSTANCE_DIR, f"mc_{int(width):03d}_{int(degree):03d}_000.txt")
metrics.circuit_metrics[width] = detail.get(width)
metrics.circuit_metrics['subtitle'] = cm.get('subtitle')
finIterDict = final_iter_metrics[width][restart_ind]
if benchmark_inputs['save_final_counts']:
# if the final iteration cut counts were stored, retrieve them
iter_dist = {'cuts' : finIterDict['cuts'], 'counts' : finIterDict['counts'], 'sizes' : finIterDict['sizes']}
else:
# The value of iter_dist does not matter otherwise
iter_dist = None
# Retrieve the distribution of cut sizes for the final iteration for this width and degree
iter_size_dist = {'unique_sizes' : finIterDict['unique_sizes'], 'unique_counts' : finIterDict['unique_counts'], 'cumul_counts' : finIterDict['cumul_counts']}
converged_thetas_list = finIterDict.get('converged_thetas_list')
parent_folder_save = os.path.join('__data', f'{metrics.get_backend_label(backend_id)}')
store_final_iter_to_metrics_json(
num_qubits=int(width),
degree = int(degree),
restart_ind=int(restart_ind),
num_shots=int(benchmark_inputs['num_shots']),
converged_thetas_list=converged_thetas_list,
opt=opt,
iter_size_dist=iter_size_dist,
iter_dist = iter_dist,
dict_of_inputs=benchmark_inputs,
parent_folder_save=parent_folder_save,
save_final_counts=False,
save_res_to_file=True,
_instances=None
)
def store_final_iter_to_metrics_json(num_qubits,
degree,
restart_ind,
num_shots,
converged_thetas_list,
opt,
iter_size_dist,
iter_dist,
parent_folder_save,
dict_of_inputs,
save_final_counts,
save_res_to_file,
_instances=None):
"""
For a given graph (specified by num_qubits and degree),
1. For a given restart, store properties of the final minimizer iteration to metrics.circuit_metrics_final_iter, and
2. Store various properties for all minimizer iterations for each restart to a json file.
Parameters
----------
num_qubits, degree, restarts, num_shots : ints
parent_folder_save : string (location where json file will be stored)
dict_of_inputs : dictionary of inputs that were given to run()
save_final_counts: bool. If true, save counts, cuts and sizes for last iteration to json file.
save_res_to_file: bool. If False, do not save data to json file.
iter_size_dist : dictionary containing distribution of cut sizes. Keys are 'unique_sizes', 'unique_counts' and 'cumul_counts'
opt (int) : Max Cut value
"""
# In order to compare with uniform random sampling, get some samples
unif_cuts, unif_counts, unif_sizes, unique_counts_unif, unique_sizes_unif, cumul_counts_unif = uniform_cut_sampling(
num_qubits, degree, num_shots, _instances)
unif_dict = {'unique_counts_unif': unique_counts_unif,
'unique_sizes_unif': unique_sizes_unif,
'cumul_counts_unif': cumul_counts_unif} # store only the distribution of cut sizes, and not the cuts themselves
# Store properties such as (cuts, counts, sizes) of the final iteration, the converged theta values, as well as the known optimal value for the current problem, in metrics.circuit_metrics_final_iter. Also store uniform cut sampling results
metrics.store_props_final_iter(num_qubits, restart_ind, 'optimal_value', opt)
metrics.store_props_final_iter(num_qubits, restart_ind, None, iter_size_dist)
metrics.store_props_final_iter(num_qubits, restart_ind, 'converged_thetas_list', converged_thetas_list)
metrics.store_props_final_iter(num_qubits, restart_ind, None, unif_dict)
# metrics.store_props_final_iter(num_qubits, restart_ind, None, iter_dist) # do not store iter_dist, since it takes a lot of memory for larger widths, instead, store just iter_size_dist
if save_res_to_file:
# Save data to a json file
dump_to_json(parent_folder_save, num_qubits,
degree, restart_ind, iter_size_dist, iter_dist, dict_of_inputs, converged_thetas_list, opt, unif_dict,
save_final_counts=save_final_counts)
def dump_to_json(parent_folder_save, num_qubits, degree, restart_ind, iter_size_dist, iter_dist,
dict_of_inputs, converged_thetas_list, opt, unif_dict, save_final_counts=False):
"""
For a given problem (specified by number of qubits and graph degree) and restart_index,
save the evolution of various properties in a json file.
Items stored in the json file: Data from all iterations (iterations), inputs to run program ('general properties'), converged theta values ('converged_thetas_list'), max cut size for the graph (optimal_value), distribution of cut sizes for random uniform sampling (unif_dict), and distribution of cut sizes for the final iteration (final_size_dist)
if save_final_counts is True, then also store the distribution of cuts
"""
if not os.path.exists(parent_folder_save): os.makedirs(parent_folder_save)
store_loc = os.path.join(parent_folder_save,'width_{}_restartInd_{}.json'.format(num_qubits, restart_ind))
# Obtain dictionary with iterations data corresponding to given restart_ind
all_restart_ids = list(metrics.circuit_metrics[str(num_qubits)].keys())
ids_this_restart = [r_id for r_id in all_restart_ids if int(r_id) // 1000 == restart_ind]
iterations_dict_this_restart = {r_id : metrics.circuit_metrics[str(num_qubits)][r_id] for r_id in ids_this_restart}
# Values to be stored in json file
dict_to_store = {'iterations' : iterations_dict_this_restart}
dict_to_store['general_properties'] = dict_of_inputs
dict_to_store['converged_thetas_list'] = converged_thetas_list
dict_to_store['optimal_value'] = opt
dict_to_store['unif_dict'] = unif_dict
dict_to_store['final_size_dist'] = iter_size_dist
# Also store the value of counts obtained for the final counts
if save_final_counts:
dict_to_store['final_counts'] = iter_dist
#iter_dist.get_counts()
# Now save the output
with open(store_loc, 'w') as outfile:
json.dump(dict_to_store, outfile)
#%% Loading saved data (from json files)
def load_data_and_plot(folder=None, backend_id=None, **kwargs):
"""
The highest level function for loading stored data from a previous run
and plotting optgaps and area metrics
Parameters
----------
folder : string
Directory where json files are saved.
"""
_gen_prop = load_all_metrics(folder, backend_id=backend_id)
if _gen_prop != None:
gen_prop = {**_gen_prop, **kwargs}
plot_results_from_data(**gen_prop)
def load_all_metrics(folder=None, backend_id=None):
"""
Load all data that was saved in a folder.
The saved data will be in json files in this folder
Parameters
----------
folder : string
Directory where json files are saved.
Returns
-------
gen_prop : dict
of inputs that were used in maxcut_benchmark.run method
"""
# if folder not passed in, create its name using standard format
if folder is None:
folder = f"__data/{metrics.get_backend_label(backend_id)}"
# Note: folder here should be the folder where only the width=... files are stored, and not a folder higher up in the directory
assert os.path.isdir(folder), f"Specified folder ({folder}) does not exist."
metrics.init_metrics()
list_of_files = os.listdir(folder)
width_restart_file_tuples = [(*get_width_restart_tuple_from_filename(fileName), fileName)
for (ind, fileName) in enumerate(list_of_files) if fileName.startswith("width")] # list with elements that are tuples->(width,restartInd,filename)
width_restart_file_tuples = sorted(width_restart_file_tuples, key=lambda x:(x[0], x[1])) #sort first by width, and then by restartInd
distinct_widths = list(set(it[0] for it in width_restart_file_tuples))
list_of_files = [
[tup[2] for tup in width_restart_file_tuples if tup[0] == width] for width in distinct_widths
]
# connot continue without at least one dataset
if len(list_of_files) < 1:
print("ERROR: No result files found")
return None
for width_files in list_of_files:
# For each width, first load all the restart files
for fileName in width_files:
gen_prop = load_from_width_restart_file(folder, fileName)
# next, do processing for the width
method = gen_prop['method']
if method == 2:
num_qubits, _ = get_width_restart_tuple_from_filename(width_files[0])
metrics.process_circuit_metrics_2_level(num_qubits)
metrics.finalize_group(str(num_qubits))
# override device name with the backend_id if supplied by caller
if backend_id != None:
metrics.set_plot_subtitle(f"Device = {backend_id}")
return gen_prop
def load_from_width_restart_file(folder, fileName):
"""
Given a folder name and a file in it, load all the stored data and store the values in metrics.circuit_metrics.
Also return the converged values of thetas, the final counts and general properties.
Parameters
----------
folder : string
folder where the json file is located
fileName : string
name of the json file
Returns
-------
gen_prop : dict
of inputs that were used in maxcut_benchmark.run method
"""
# Extract num_qubits and s from file name
num_qubits, restart_ind = get_width_restart_tuple_from_filename(fileName)
print(f"Loading from {fileName}, corresponding to {num_qubits} qubits and restart index {restart_ind}")
with open(os.path.join(folder, fileName), 'r') as json_file:
data = json.load(json_file)
gen_prop = data['general_properties']
converged_thetas_list = data['converged_thetas_list']
unif_dict = data['unif_dict']
opt = data['optimal_value']
if gen_prop['save_final_counts']:
# Distribution of measured cuts
final_counts = data['final_counts']
final_size_dist = data['final_size_dist']
backend_id = gen_prop.get('backend_id')
metrics.set_plot_subtitle(f"Device = {backend_id}")
# Update circuit metrics
for circuit_id in data['iterations']:
# circuit_id = restart_ind * 1000 + minimizer_loop_ind
for metric, value in data['iterations'][circuit_id].items():
metrics.store_metric(num_qubits, circuit_id, metric, value)
method = gen_prop['method']
if method == 2:
metrics.store_props_final_iter(num_qubits, restart_ind, 'optimal_value', opt)
metrics.store_props_final_iter(num_qubits, restart_ind, None, final_size_dist)
metrics.store_props_final_iter(num_qubits, restart_ind, 'converged_thetas_list', converged_thetas_list)
metrics.store_props_final_iter(num_qubits, restart_ind, None, unif_dict)
if gen_prop['save_final_counts']:
metrics.store_props_final_iter(num_qubits, restart_ind, None, final_counts)
return gen_prop
def get_width_restart_tuple_from_filename(fileName):
"""
Given a filename, extract the corresponding width and degree it corresponds to
For example the file "width=4_degree=3.json" corresponds to 4 qubits and degree 3
Parameters
----------
fileName : TYPE
DESCRIPTION.
Returns
-------
num_qubits : int
circuit width
degree : int
graph degree.
"""
pattern = 'width_([0-9]+)_restartInd_([0-9]+).json'
match = re.search(pattern, fileName)
# assert match is not None, f"File {fileName} found inside folder. All files inside specified folder must be named in the format 'width_int_restartInd_int.json"
num_qubits = int(match.groups()[0])
degree = int(match.groups()[1])
return (num_qubits,degree)
#%% Run method: Benchmarking loop
MAX_QUBITS = 24
iter_dist = {'cuts' : [], 'counts' : [], 'sizes' : []} # (list of measured bitstrings, list of corresponding counts, list of corresponding cut sizes)
iter_size_dist = {'unique_sizes' : [], 'unique_counts' : [], 'cumul_counts' : []} # for the iteration being executed, stores the distribution for cut sizes
saved_result = { }
instance_filename = None
def run (min_qubits=3, max_qubits=8, skip_qubits=2,
max_circuits=1, num_shots=1, # for dm-simulator num_shots=1
method=1, rounds=1, degree=3, alpha=0.1, thetas_array=None, parameterized= False, do_fidelities=True,
max_iter=30, score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits',
fixed_metrics={}, num_x_bins=15, y_size=None, x_size=None, use_fixed_angles=False,
objective_func_type = 'approx_ratio', plot_results = True,
save_res_to_file = False, save_final_counts = False, detailed_save_names = False, comfort=False,
backend_id='dm_simulator', provider_backend=None, eta=0.5,
#hub="ibm-q", group="open", project="main",
exec_options=None, context=None,
_instances=None):
"""
Parameters
----------
min_qubits : int, optional
The smallest circuit width for which benchmarking will be done The default is 3.
max_qubits : int, optional
The largest circuit width for which benchmarking will be done. The default is 6.
skip_qubits : int, optional
Skip at least this many qubits during run loop. The default is 2.
max_circuits : int, optional
Number of restarts. The default is None.
num_shots : int, optional
Number of times the circut will be measured, for each iteration. The default is 100.
method : int, optional
If 1, then do standard metrics, if 2, implement iterative algo metrics. The default is 1.
rounds : int, optional
number of QAOA rounds. The default is 1.
degree : int, optional
degree of graph. The default is 3.
thetas_array : list, optional
list or ndarray of beta and gamma values. The default is None.
use_fixed_angles : bool, optional
use betas and gammas obtained from a 'fixed angles' table, specific to degree and rounds
N : int, optional
For the max % counts metric, choose the highest N% counts. The default is 10.
alpha : float, optional
Value between 0 and 1. The default is 0.1.
parameterized : bool, optional
Whether to use parametrized circuits or not. The default is False.
do_fidelities : bool, optional
Compute circuit fidelity. The default is True.
max_iter : int, optional
Number of iterations for the minimizer routine. The default is 30.
score_metric : list or string, optional
Which metrics are to be plotted in area metrics plots. The default is 'fidelity'.
x_metric : list or string, optional
Horizontal axis for area plots. The default is 'cumulative_exec_time'.
y_metric : list or string, optional
Vertical axis for area plots. The default is 'num_qubits'.
fixed_metrics : TYPE, optional
DESCRIPTION. The default is {}.
num_x_bins : int, optional
DESCRIPTION. The default is 15.
y_size : TYPint, optional
DESCRIPTION. The default is None.
x_size : string, optional
DESCRIPTION. The default is None.
backend_id : string, optional
DESCRIPTION. The default is 'qasm_simulator'.
provider_backend : string, optional
DESCRIPTION. The default is None.
hub : string, optional
DESCRIPTION. The default is "ibm-q".
group : string, optional
DESCRIPTION. The default is "open".
project : string, optional
DESCRIPTION. The default is "main".
exec_options : string, optional
DESCRIPTION. The default is None.
objective_func_type : string, optional
Objective function to be used by the classical minimizer algorithm. The default is 'approx_ratio'.
plot_results : bool, optional
Plot results only if True. The default is True.
save_res_to_file : bool, optional
Save results to json files. The default is True.
save_final_counts : bool, optional
If True, also save the counts from the final iteration for each problem in the json files. The default is True.
detailed_save_names : bool, optional
If true, the data and plots will be saved with more detailed names. Default is False
confort : bool, optional
If true, print comfort dots during execution
"""
# Store all the input parameters into a dictionary.
# This dictionary will later be stored in a json file
# It will also be used for sending parameters to the plotting function
dict_of_inputs = locals()
# Get angles for restarts. Thetas = list of lists. Lengths are max_circuits and 2*rounds
thetas, max_circuits = get_restart_angles(thetas_array, rounds, max_circuits)
# Update the dictionary of inputs
dict_of_inputs = {**dict_of_inputs, **{'thetas_array': thetas, 'max_circuits' : max_circuits}}
# Delete some entries from the dictionary
# for key in ["hub", "group", "project", "provider_backend", "exec_options"]:
# dict_of_inputs.pop(key)
global maxcut_inputs
maxcut_inputs = dict_of_inputs
global QC_
global circuits_done
global minimizer_loop_index
global opt_ts
print(f"{benchmark_name} ({method}) Benchmark Program - QSim")
QC_ = None
# Create a folder where the results will be saved. Folder name=time of start of computation
# In particular, for every circuit width, the metrics will be stored the moment the results are obtained
# In addition to the metrics, the (beta,gamma) values obtained by the optimizer, as well as the counts
# measured for the final circuit will be stored.
# Use the following parent folder, for a more detailed
if detailed_save_names:
start_time_str = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
parent_folder_save = os.path.join('__results', f'{backend_id}', objective_func_type, f'run_start_{start_time_str}')
else:
parent_folder_save = os.path.join('__results', f'{backend_id}', objective_func_type)
if save_res_to_file and not os.path.exists(parent_folder_save): os.makedirs(os.path.join(parent_folder_save))
# validate parameters
max_qubits = max(4, max_qubits)
max_qubits = min(MAX_QUBITS, max_qubits)
min_qubits = min(max(4, min_qubits), max_qubits)
skip_qubits = max(2, skip_qubits)
# create context identifier
if context is None: context = f"{benchmark_name} ({method}) Benchmark"
degree = max(3, degree)
rounds = max(1, rounds)
# don't compute exectation unless fidelity is is needed
global do_compute_expectation
do_compute_expectation = do_fidelities
# given that this benchmark does every other width, set y_size default to 1.5
if y_size == None:
y_size = 1.5
# Choose the objective function to minimize, based on values of the parameters
possible_approx_ratios = {'cvar_ratio', 'approx_ratio', 'gibbs_ratio', 'bestcut_ratio'}
non_objFunc_ratios = possible_approx_ratios - { objective_func_type }
function_mapper = {'cvar_ratio' : compute_cvar,
'approx_ratio' : compute_sample_mean,
'gibbs_ratio' : compute_gibbs,
'bestcut_ratio' : compute_best_cut_from_measured}
# if using fixed angles, get thetas array from table
if use_fixed_angles:
# Load the fixed angle tables from data file
fixed_angles = common.read_fixed_angles(
os.path.join(os.path.dirname(__file__), '..', '_common', 'angles_regular_graphs.json'),
_instances)
thetas_array = common.get_fixed_angles_for(fixed_angles, degree, rounds)
if thetas_array == None:
print(f"ERROR: no fixed angles for rounds = {rounds}")
return
##########
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler
def execution_handler (qc, result, num_qubits, s_int, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots)
metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity)
def execution_handler2 (qc, result, num_qubits, s_int, num_shots):
# Stores the results to the global saved_result variable
global saved_result
saved_result = result
# Initialize execution module using the execution result handler above and specified backend_id
# for method=2 we need to set max_jobs_active to 1, so each circuit completes before continuing
if method == 2:
ex.max_jobs_active = 1
ex.init_execution(execution_handler2)
else:
ex.init_execution(execution_handler)
# initialize the execution module with target information
ex.set_execution_target(backend_id, provider_backend=provider_backend,
# hub=hub, group=group, project=project,
exec_options=exec_options,
context=context
)
# for noiseless simulation, set noise model to be None
# ex.set_noise_model(None)
##########
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
# DEVNOTE: increment by 2 to match the collection of problems in 'instance' folder
for num_qubits in range(min_qubits, max_qubits + 1, 2):
if method == 1:
print(f"************\nExecuting [{max_circuits}] circuits for num_qubits = {num_qubits}")
else:
print(f"************\nExecuting [{max_circuits}] restarts for num_qubits = {num_qubits}")
# If degree is negative,
if degree < 0 :
degree = max(3, (num_qubits + degree))
# Load the problem and its solution
global instance_filename
instance_filename = os.path.join(
os.path.dirname(__file__),
"..",
"_common",
common.INSTANCE_DIR,
f"mc_{num_qubits:03d}_{degree:03d}_000.txt",
)
nodes, edges = common.read_maxcut_instance(instance_filename, _instances)
opt, _ = common.read_maxcut_solution(
instance_filename[:-4] + ".sol", _instances
)
# if the file does not exist, we are done with this number of qubits
if nodes == None:
print(f" ... problem not found.")
break
for restart_ind in range(1, max_circuits + 1):
# restart index should start from 1
# Loop over restarts for a given graph
# if not using fixed angles, get initial or random thetas from array saved earlier
# otherwise use random angles (if restarts > 1) or [1] * 2 * rounds
if not use_fixed_angles:
thetas_array = thetas[restart_ind - 1]
if method == 1:
# create the circuit for given qubit size and secret string, store time metric
ts = time.time()
# if using fixed angles in method 1, need to access first element
# DEVNOTE: eliminate differences between method 1 and 2 and handling of thetas_array
thetas_array_0 = thetas_array
if use_fixed_angles:
thetas_array_0 = thetas_array[0]
qc, params = MaxCut(num_qubits, restart_ind, edges, rounds, thetas_array_0, parameterized)
qc = qc.reverse_bits() # to reverse the endianness
metrics.store_metric(num_qubits, restart_ind, 'create_time', time.time()-ts)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc2 = qc.decompose()
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc2, num_qubits, restart_ind, shots=num_shots, params=params)
if method == 2:
# a unique circuit index used inside the inner minimizer loop as identifier
minimizer_loop_index = 0 # Value of 0 corresponds to the 0th iteration of the minimizer
start_iters_t = time.time()
# Always start by enabling transpile ...
ex.set_tranpilation_flags(do_transpile_metrics=True, do_transpile_for_execute=True)
logger.info(f'=============== Begin method 2 loop, enabling transpile')
def expectation(thetas_array):
# Every circuit needs a unique id; add unique_circuit_index instead of s_int
global minimizer_loop_index
unique_id = restart_ind * 1000 + minimizer_loop_index
# store thetas_array
metrics.store_metric(num_qubits, unique_id, 'thetas_array', thetas_array.tolist())
#************************************************
#*** Circuit Creation and Decomposition start ***
# create the circuit for given qubit size, secret string and params, store time metric
ts = time.time()
qc, params = MaxCut(num_qubits, unique_id, edges, rounds, thetas_array, parameterized)
# qc = qc.reverse_bits() # to reverse the endianness
metrics.store_metric(num_qubits, unique_id, 'create_time', time.time()-ts)
# also store the 'rounds' and 'degree' for each execution
# DEVNOTE: Currently, this is stored for each iteration. Reduce this redundancy
metrics.store_metric(num_qubits, unique_id, 'rounds', rounds)
metrics.store_metric(num_qubits, unique_id, 'degree', degree)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc2 = qc.decompose()
# Circuit Creation and Decomposition end
#************************************************
#************************************************
#*** Quantum Part: Execution of Circuits ***
# submit circuit for execution on target with the current parameters
ex.submit_circuit(qc2, num_qubits, unique_id, shots=num_shots, params=params)
# Must wait for circuit to complete
#ex.throttle_execution(metrics.finalize_group)
ex.finalize_execution(None, report_end=False) # don't finalize group until all circuits done
# after first execution and thereafter, no need for transpilation if parameterized
if parameterized:
ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False)
logger.info(f'**** First execution complete, disabling transpile')
#************************************************
global saved_result
# Fidelity Calculation and Storage
_, fidelity = analyze_and_print_result(qc, saved_result, num_qubits, unique_id, num_shots)
metrics.store_metric(num_qubits, unique_id, 'fidelity', fidelity)
#************************************************
#*** Classical Processing of Results - essential to optimizer ***
global opt_ts
dict_of_vals = dict()
# Start counting classical optimizer time here again
tc1 = time.time()
cuts, counts, sizes = compute_cutsizes(saved_result, nodes, edges)
# Compute the value corresponding to the objective function first
dict_of_vals[objective_func_type] = function_mapper[objective_func_type](counts, sizes, alpha = alpha)
# Store the optimizer time as current time- tc1 + ts - opt_ts, since the time between tc1 and ts is not time used by the classical optimizer.
metrics.store_metric(num_qubits, unique_id, 'opt_exec_time', time.time() - tc1 + ts - opt_ts)
# Note: the first time it is stored it is just the initialization time for optimizer
#************************************************
#************************************************
#*** Classical Processing of Results - not essential for optimizer. Used for tracking metrics ***
# Compute the distribution of cut sizes; store them under metrics
unique_counts, unique_sizes, cumul_counts = get_size_dist(counts, sizes)
global iter_size_dist
iter_size_dist = {'unique_sizes' : unique_sizes, 'unique_counts' : unique_counts, 'cumul_counts' : cumul_counts}
metrics.store_metric(num_qubits, unique_id, None, iter_size_dist)
# Compute and the other metrics (eg. cvar, gibbs and max N % if the obj function was set to approx ratio)
for s in non_objFunc_ratios:
dict_of_vals[s] = function_mapper[s](counts, sizes, alpha = alpha)
# Store the ratios
dict_of_ratios = { key : -1 * val / opt for (key, val) in dict_of_vals.items()}
dict_of_ratios['gibbs_ratio'] = dict_of_ratios['gibbs_ratio'] / eta
metrics.store_metric(num_qubits, unique_id, None, dict_of_ratios)
# Get the best measurement and store it
best = - compute_best_cut_from_measured(counts, sizes)
metrics.store_metric(num_qubits, unique_id, 'bestcut_ratio', best / opt)
# Also compute and store the weights of cuts at three quantile values
quantile_sizes = compute_quartiles(counts, sizes)
# Store quantile_optgaps as a list (allows storing in json files)
metrics.store_metric(num_qubits, unique_id, 'quantile_optgaps', (1 - quantile_sizes / opt).tolist())
# Also store the cuts, counts and sizes in a global variable, to allow access elsewhere
global iter_dist
iter_dist = {'cuts' : cuts, 'counts' : counts, 'sizes' : sizes}
minimizer_loop_index += 1
#************************************************
if comfort:
if minimizer_loop_index == 1: print("")
print(".", end ="")
# reset timer for optimizer execution after each iteration of quantum program completes
opt_ts = time.time()
return dict_of_vals[objective_func_type]
# after first execution and thereafter, no need for transpilation if parameterized
# DEVNOTE: this appears to NOT be needed, as we can turn these off after
def callback(xk):
if parameterized:
ex.set_tranpilation_flags(do_transpile_metrics=False, do_transpile_for_execute=False)
opt_ts = time.time()
# perform the complete algorithm; minimizer invokes 'expectation' function iteratively
##res = minimize(expectation, thetas_array, method='COBYLA', options = { 'maxiter': max_iter}, callback=callback)
res = minimize(expectation, thetas_array, method='COBYLA', options = { 'maxiter': max_iter})
# To-do: Set bounds for the minimizer
unique_id = restart_ind * 1000 + 0
metrics.store_metric(num_qubits, unique_id, 'opt_exec_time', time.time()-opt_ts)
if comfort:
print("")
# Save final iteration data to metrics.circuit_metrics_final_iter
# This data includes final counts, cuts, etc.
store_final_iter_to_metrics_json(num_qubits=num_qubits,
degree=degree,
restart_ind=restart_ind,
num_shots=num_shots,
converged_thetas_list=res.x.tolist(),
opt=opt,
iter_size_dist=iter_size_dist, iter_dist=iter_dist, parent_folder_save=parent_folder_save,
dict_of_inputs=dict_of_inputs, save_final_counts=save_final_counts,
save_res_to_file=save_res_to_file, _instances=_instances)
# for method 2, need to aggregate the detail metrics appropriately for each group
# Note that this assumes that all iterations of the circuit have completed by this point
if method == 2:
metrics.process_circuit_metrics_2_level(num_qubits)
metrics.finalize_group(str(num_qubits))
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
global print_sample_circuit
if print_sample_circuit:
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
#if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!")
# Plot metrics for all circuit sizes
if method == 1:
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} ({method}) - QSim",
options=dict(shots=num_shots,rounds=rounds))
elif method == 2:
#metrics.print_all_circuit_metrics()
if plot_results:
plot_results_from_data(**dict_of_inputs)
# ******************************
def plot_results_from_data(num_shots=100, rounds=1, degree=3, max_iter=30, max_circuits = 1,
objective_func_type='approx_ratio', method=2, use_fixed_angles=False,
score_metric='fidelity', x_metric='cumulative_exec_time', y_metric='num_qubits', fixed_metrics={},
num_x_bins=15, y_size=None, x_size=None, x_min=None, x_max=None,
offset_flag=False, # default is False for QAOA
detailed_save_names=False, **kwargs):
"""
Plot results
"""
if detailed_save_names:
# If detailed names are desired for saving plots, put date of creation, etc.
cur_time=datetime.datetime.now()
dt = cur_time.strftime("%Y-%m-%d_%H-%M-%S")
short_obj_func_str = metrics.score_label_save_str[objective_func_type]
suffix = f'-s{num_shots}_r{rounds}_d{degree}_mi{max_iter}_of-{short_obj_func_str}_{dt}' #of=objective function
else:
short_obj_func_str = metrics.score_label_save_str[objective_func_type]
suffix = f'of-{short_obj_func_str}' #of=objective function
obj_str = metrics.known_score_labels[objective_func_type]
options = {'shots' : num_shots, 'rounds' : rounds, 'degree' : degree, 'restarts' : max_circuits, 'fixed_angles' : use_fixed_angles, '\nObjective Function' : obj_str}
suptitle = f"Benchmark Results - MaxCut ({method}) - QSim"
metrics.plot_all_area_metrics(f"Benchmark Results - MaxCut ({method}) - QSim",
score_metric=score_metric, x_metric=x_metric, y_metric=y_metric,
fixed_metrics=fixed_metrics, num_x_bins=num_x_bins,
x_size=x_size, y_size=y_size, x_min=x_min, x_max=x_max,
offset_flag=offset_flag,
options=options, suffix=suffix)
metrics.plot_metrics_optgaps(suptitle, options=options, suffix=suffix, objective_func_type = objective_func_type)
# this plot is deemed less useful
#metrics.plot_ECDF(suptitle=suptitle, options=options, suffix=suffix)
all_widths = list(metrics.circuit_metrics_final_iter.keys())
all_widths = [int(ii) for ii in all_widths]
list_of_widths = [all_widths[-1]]
metrics.plot_cutsize_distribution(suptitle=suptitle,options=options, suffix=suffix, list_of_widths = list_of_widths)
metrics.plot_angles_polar(suptitle = suptitle, options = options, suffix = suffix)
# if main, execute method
if __name__ == '__main__':
ex.local_args() # calling local_args() needed while taking noise parameters through command line arguments (for individual benchmarks)
run()
# %%
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# consider the following list with 4 elements
L = [1,-2,0,5]
print(L)
# 3 * v
v = [1,-2,0,5]
print("v is",v)
# we use the same list for the result
for i in range(len(v)):
v[i] = 3 * v[i]
print("3v is",v)
# -0.6 * u
# reinitialize the list v
v = [1,-2,0,5]
for i in range(len(v)):
v[i] = -0.6 * v[i]
print("0.6v is",v)
u = [-3,-2,0,-1,4]
v = [-1,-1,2,-3,5]
result=[]
for i in range(len(u)):
result.append(u[i]+v[i])
print("u+v is",result)
# print the result vector similarly to a column vector
print() # print an empty line
print("the elements of u+v are")
for j in range(len(result)):
print(result[j])
from random import randrange
#
# your solution is here
#
from random import randrange
dimension = 7
# create u and v as empty lists
u = []
v = []
for i in range(dimension):
u.append(randrange(-10,11)) # add a randomly picked number to the list u
v.append(randrange(-10,11)) # add a randomly picked number to the list v
# print both lists
print("u is",u)
print("v is",v)
#r=randrange(-10,11) # randomly pick a number from the list {-10,-9,...,-1,0,1,...,9,10}
#
# your solution is here
#
# please execute the cell for Task 1 to define u and v
# create a result list
# the first method
result=[]
# fill it with zeros
for i in range(dimension):
result.append(0)
print("by using the first method, the result vector is initialized to",result)
# the second method
# alternative and shorter solution for creating a list with zeros
result = [0] * 7
print("by using the second method, the result vector is initialized to",result)
# calculate 3u-2v
for i in range(dimension):
result[i] = 3 * u[i] - 2 * v[i]
# print all lists
print("u is",u)
print("v is",v)
print("3u-2v is",result)
v = [-1,-3,5,3,1,2]
length_square=0
for i in range(len(v)):
print(v[i],":square ->",v[i]**2) # print each entry and its square value
length_square = length_square + v[i]**2 # sum up the square of each entry
length = length_square ** 0.5 # take the square root of the summation of the squares of all entries
print("the summation is",length_square)
print("then the length is",length)
# for square root, we can also use built-in function math.sqrt
print() # print an empty line
from math import sqrt
print("the square root of",length_square,"is",sqrt(length_square))
#
# your solution is here
#
u = [1,-2,-4,2]
fouru=[4,-8,-16,8]
len_u = 0
len_fouru = 0
for i in range(len(u)):
len_u = len_u + u[i]**2 # adding square of each value
len_fouru = len_fouru + fouru[i]**2 # adding square of each value
len_u = len_u ** 0.5 # taking square root of the summation
len_fouru = len_fouru ** 0.5 # taking square root of the summation
# print the lengths
print("length of u is",len_u)
print("4 * length of u is",4 * len_u)
print("length of 4u is",len_fouru)
#
# your solution is here
#
from random import randrange
u = [1,-2,-4,2]
print("u is",u)
r = randrange(9) # r is a number in {0,...,8}
r = r + 1 # r is a number in {1,...,9}
r = r/10 # r is a number in {1/10,...,9/10}
print()
print("r is",r)
newu=[]
for i in range(len(u)):
newu.append(-1*r*u[i])
print()
print("-ru is",newu)
print()
length = 0
for i in range(len(newu)):
length = length + newu[i]**2 # adding square of each number
print(newu[i],"->[square]->",newu[i]**2)
print()
print("the summation of squares is",length)
length = length**0.5 # taking square root
print("the length of",newu,"is",length)
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test phase estimation"""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import ddt, data, unpack
import numpy as np
from qiskit.circuit.library import ZGate, XGate, HGate, IGate
from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector, Operator
from qiskit.synthesis import MatrixExponential, SuzukiTrotter
from qiskit.primitives import Sampler
from qiskit_algorithms import PhaseEstimationScale
from qiskit_algorithms.phase_estimators import (
PhaseEstimation,
HamiltonianPhaseEstimation,
IterativePhaseEstimation,
)
import qiskit
from qiskit import QuantumCircuit
from qiskit.opflow import (
H,
X,
Y,
Z,
I,
StateFn,
PauliTrotterEvolution,
MatrixEvolution,
PauliSumOp,
)
from qiskit.test import slow_test
@ddt
class TestHamiltonianPhaseEstimation(QiskitAlgorithmsTestCase):
"""Tests for obtaining eigenvalues from phase estimation"""
def hamiltonian_pe(
self,
hamiltonian,
state_preparation=None,
num_evaluation_qubits=6,
backend=None,
evolution=None,
bound=None,
):
"""Run HamiltonianPhaseEstimation and return result with all phases."""
if backend is None:
backend = qiskit.BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
quantum_instance = qiskit.utils.QuantumInstance(backend=backend, shots=10000)
with self.assertWarns(DeprecationWarning):
phase_est = HamiltonianPhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits, quantum_instance=quantum_instance
)
result = phase_est.estimate(
hamiltonian=hamiltonian,
state_preparation=state_preparation,
evolution=evolution,
bound=bound,
)
return result
@data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 4))
def test_pauli_sum_1(self, evolution):
"""Two eigenvalues from Pauli sum with X, Z"""
with self.assertWarns(DeprecationWarning):
hamiltonian = 0.5 * X + Z
state_preparation = StateFn(H.to_circuit())
result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution)
phase_dict = result.filter_phases(0.162, as_float=True)
phases = list(phase_dict.keys())
phases.sort()
self.assertAlmostEqual(phases[0], -1.125, delta=0.001)
self.assertAlmostEqual(phases[1], 1.125, delta=0.001)
@data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 3))
def test_pauli_sum_2(self, evolution):
"""Two eigenvalues from Pauli sum with X, Y, Z"""
with self.assertWarns(DeprecationWarning):
hamiltonian = 0.5 * X + Y + Z
state_preparation = None
result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution)
phase_dict = result.filter_phases(0.1, as_float=True)
phases = list(phase_dict.keys())
phases.sort()
self.assertAlmostEqual(phases[0], -1.484, delta=0.001)
self.assertAlmostEqual(phases[1], 1.484, delta=0.001)
def test_single_pauli_op(self):
"""Two eigenvalues from Pauli sum with X, Y, Z"""
hamiltonian = Z
state_preparation = None
with self.assertWarns(DeprecationWarning):
result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=None)
eigv = result.most_likely_eigenvalue
with self.subTest("First eigenvalue"):
self.assertAlmostEqual(eigv, 1.0, delta=0.001)
with self.assertWarns(DeprecationWarning):
state_preparation = StateFn(X.to_circuit())
result = self.hamiltonian_pe(hamiltonian, state_preparation, bound=1.05)
eigv = result.most_likely_eigenvalue
with self.subTest("Second eigenvalue"):
self.assertAlmostEqual(eigv, -0.98, delta=0.01)
@slow_test
def test_H2_hamiltonian(self):
"""Test H2 hamiltonian"""
with self.assertWarns(DeprecationWarning):
hamiltonian = (
(-1.0523732457728587 * (I ^ I))
+ (0.3979374248431802 * (I ^ Z))
+ (-0.3979374248431802 * (Z ^ I))
+ (-0.011280104256235324 * (Z ^ Z))
+ (0.18093119978423147 * (X ^ X))
)
state_preparation = StateFn((I ^ H).to_circuit())
evo = PauliTrotterEvolution(trotter_mode="suzuki", reps=4)
with self.assertWarns(DeprecationWarning):
result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evo)
with self.subTest("Most likely eigenvalues"):
self.assertAlmostEqual(result.most_likely_eigenvalue, -1.855, delta=0.001)
with self.subTest("Most likely phase"):
self.assertAlmostEqual(result.phase, 0.5937, delta=0.001)
with self.subTest("All eigenvalues"):
phase_dict = result.filter_phases(0.1)
phases = list(phase_dict.keys())
self.assertAlmostEqual(phases[0], -0.8979, delta=0.001)
self.assertAlmostEqual(phases[1], -1.8551, delta=0.001)
self.assertAlmostEqual(phases[2], -1.2376, delta=0.001)
def test_matrix_evolution(self):
"""1Q Hamiltonian with MatrixEvolution"""
with self.assertWarns(DeprecationWarning):
hamiltonian = (0.5 * X) + (0.6 * Y) + (0.7 * I)
state_preparation = None
result = self.hamiltonian_pe(
hamiltonian, state_preparation, evolution=MatrixEvolution()
)
phase_dict = result.filter_phases(0.2, as_float=True)
phases = list(phase_dict.keys())
self.assertAlmostEqual(phases[0], 1.490, delta=0.001)
self.assertAlmostEqual(phases[1], -0.090, delta=0.001)
def _setup_from_bound(self, evolution, op_class):
with self.assertWarns(DeprecationWarning):
hamiltonian = 0.5 * X + Y + Z
state_preparation = None
bound = 1.2 * sum(abs(hamiltonian.coeff * coeff) for coeff in hamiltonian.coeffs)
if op_class == "MatrixOp":
hamiltonian = hamiltonian.to_matrix_op()
backend = qiskit.BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000)
with self.assertWarns(DeprecationWarning):
phase_est = HamiltonianPhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi)
result = phase_est.estimate(
hamiltonian=hamiltonian,
bound=bound,
evolution=evolution,
state_preparation=state_preparation,
)
return result
def test_from_bound(self):
"""HamiltonianPhaseEstimation with bound"""
with self.assertWarns(DeprecationWarning):
for op_class in ("SummedOp", "MatrixOp"):
result = self._setup_from_bound(MatrixEvolution(), op_class)
cutoff = 0.01
phases = result.filter_phases(cutoff)
with self.subTest(f"test phases has the correct length: {op_class}"):
self.assertEqual(len(phases), 2)
with self.subTest(f"test scaled phases are correct: {op_class}"):
self.assertEqual(list(phases.keys()), [1.5, -1.5])
phases = result.filter_phases(cutoff, scaled=False)
with self.subTest(f"test unscaled phases are correct: {op_class}"):
self.assertEqual(list(phases.keys()), [0.25, 0.75])
def test_trotter_from_bound(self):
"""HamiltonianPhaseEstimation with bound and Trotterization"""
with self.assertWarns(DeprecationWarning):
result = self._setup_from_bound(
PauliTrotterEvolution(trotter_mode="suzuki", reps=3), op_class="SummedOp"
)
phase_dict = result.filter_phases(0.1)
phases = list(phase_dict.keys())
with self.subTest("test phases has the correct length"):
self.assertEqual(len(phases), 2)
with self.subTest("test phases has correct values"):
self.assertAlmostEqual(phases[0], 1.5, delta=0.001)
self.assertAlmostEqual(phases[1], -1.5, delta=0.001)
# sampler tests
def hamiltonian_pe_sampler(
self,
hamiltonian,
state_preparation=None,
num_evaluation_qubits=6,
evolution=None,
bound=None,
uses_opflow=True,
):
"""Run HamiltonianPhaseEstimation and return result with all phases."""
sampler = Sampler()
phase_est = HamiltonianPhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits, sampler=sampler
)
if uses_opflow:
with self.assertWarns(DeprecationWarning):
result = phase_est.estimate(
hamiltonian=hamiltonian,
state_preparation=state_preparation,
evolution=evolution,
bound=bound,
)
else:
result = phase_est.estimate(
hamiltonian=hamiltonian,
state_preparation=state_preparation,
evolution=evolution,
bound=bound,
)
return result
@data(MatrixExponential(), SuzukiTrotter(reps=4))
def test_pauli_sum_1_sampler(self, evolution):
"""Two eigenvalues from Pauli sum with X, Z"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1)]))
state_preparation = QuantumCircuit(1).compose(HGate())
result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution)
phase_dict = result.filter_phases(0.162, as_float=True)
phases = list(phase_dict.keys())
phases.sort()
self.assertAlmostEqual(phases[0], -1.125, delta=0.001)
self.assertAlmostEqual(phases[1], 1.125, delta=0.001)
@data(MatrixExponential(), SuzukiTrotter(reps=3))
def test_pauli_sum_2_sampler(self, evolution):
"""Two eigenvalues from Pauli sum with X, Y, Z"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1), ("Y", 1)]))
state_preparation = None
result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution)
phase_dict = result.filter_phases(0.1, as_float=True)
phases = list(phase_dict.keys())
phases.sort()
self.assertAlmostEqual(phases[0], -1.484, delta=0.001)
self.assertAlmostEqual(phases[1], 1.484, delta=0.001)
def test_single_pauli_op_sampler(self):
"""Two eigenvalues from Pauli sum with X, Y, Z"""
hamiltonian = SparsePauliOp(Pauli("Z"))
state_preparation = None
result = self.hamiltonian_pe_sampler(
hamiltonian, state_preparation, evolution=None, uses_opflow=False
)
eigv = result.most_likely_eigenvalue
with self.subTest("First eigenvalue"):
self.assertAlmostEqual(eigv, 1.0, delta=0.001)
state_preparation = QuantumCircuit(1).compose(XGate())
result = self.hamiltonian_pe_sampler(
hamiltonian, state_preparation, bound=1.05, uses_opflow=False
)
eigv = result.most_likely_eigenvalue
with self.subTest("Second eigenvalue"):
self.assertAlmostEqual(eigv, -0.98, delta=0.01)
@data(
Statevector(QuantumCircuit(2).compose(IGate()).compose(HGate())),
QuantumCircuit(2).compose(IGate()).compose(HGate()),
)
def test_H2_hamiltonian_sampler(self, state_preparation):
"""Test H2 hamiltonian"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp(
SparsePauliOp.from_list(
[
("II", -1.0523732457728587),
("IZ", 0.3979374248431802),
("ZI", -0.3979374248431802),
("ZZ", -0.011280104256235324),
("XX", 0.18093119978423147),
]
)
)
evo = SuzukiTrotter(reps=4)
result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evo)
with self.subTest("Most likely eigenvalues"):
self.assertAlmostEqual(result.most_likely_eigenvalue, -1.855, delta=0.001)
with self.subTest("Most likely phase"):
self.assertAlmostEqual(result.phase, 0.5937, delta=0.001)
with self.subTest("All eigenvalues"):
phase_dict = result.filter_phases(0.1)
phases = sorted(phase_dict.keys())
self.assertAlmostEqual(phases[0], -1.8551, delta=0.001)
self.assertAlmostEqual(phases[1], -1.2376, delta=0.001)
self.assertAlmostEqual(phases[2], -0.8979, delta=0.001)
def test_matrix_evolution_sampler(self):
"""1Q Hamiltonian with MatrixEvolution"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Y", 0.6), ("I", 0.7)]))
state_preparation = None
result = self.hamiltonian_pe_sampler(
hamiltonian, state_preparation, evolution=MatrixExponential()
)
phase_dict = result.filter_phases(0.2, as_float=True)
phases = sorted(phase_dict.keys())
self.assertAlmostEqual(phases[0], -0.090, delta=0.001)
self.assertAlmostEqual(phases[1], 1.490, delta=0.001)
@ddt
class TestPhaseEstimation(QiskitAlgorithmsTestCase):
"""Evolution tests."""
def one_phase(
self,
unitary_circuit,
state_preparation=None,
backend_type=None,
phase_estimator=None,
num_iterations=6,
):
"""Run phase estimation with operator, eigenvalue pair `unitary_circuit`,
`state_preparation`. Return the estimated phase as a value in :math:`[0,1)`.
"""
if backend_type is None:
backend_type = "qasm_simulator"
backend = qiskit.BasicAer.get_backend(backend_type)
if phase_estimator is None:
phase_estimator = IterativePhaseEstimation
with self.assertWarns(DeprecationWarning):
qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000)
with self.assertWarns(DeprecationWarning):
if phase_estimator == IterativePhaseEstimation:
p_est = IterativePhaseEstimation(num_iterations=num_iterations, quantum_instance=qi)
elif phase_estimator == PhaseEstimation:
p_est = PhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi)
else:
raise ValueError("Unrecognized phase_estimator")
result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation)
phase = result.phase
return phase
@data(
(X.to_circuit(), 0.5, "statevector_simulator", IterativePhaseEstimation),
(X.to_circuit(), 0.5, "qasm_simulator", IterativePhaseEstimation),
(None, 0.0, "qasm_simulator", IterativePhaseEstimation),
(X.to_circuit(), 0.5, "qasm_simulator", PhaseEstimation),
(None, 0.0, "qasm_simulator", PhaseEstimation),
(X.to_circuit(), 0.5, "statevector_simulator", PhaseEstimation),
)
@unpack
def test_qpe_Z(self, state_preparation, expected_phase, backend_type, phase_estimator):
"""eigenproblem Z, |0> and |1>"""
unitary_circuit = Z.to_circuit()
with self.assertWarns(DeprecationWarning):
phase = self.one_phase(
unitary_circuit,
state_preparation,
backend_type=backend_type,
phase_estimator=phase_estimator,
)
self.assertEqual(phase, expected_phase)
@data(
(H.to_circuit(), 0.0, IterativePhaseEstimation),
((H @ X).to_circuit(), 0.5, IterativePhaseEstimation),
(H.to_circuit(), 0.0, PhaseEstimation),
((H @ X).to_circuit(), 0.5, PhaseEstimation),
)
@unpack
def test_qpe_X_plus_minus(self, state_preparation, expected_phase, phase_estimator):
"""eigenproblem X, (|+>, |->)"""
unitary_circuit = X.to_circuit()
with self.assertWarns(DeprecationWarning):
phase = self.one_phase(
unitary_circuit, state_preparation, phase_estimator=phase_estimator
)
self.assertEqual(phase, expected_phase)
@data(
(X.to_circuit(), 0.125, IterativePhaseEstimation),
(I.to_circuit(), 0.875, IterativePhaseEstimation),
(X.to_circuit(), 0.125, PhaseEstimation),
(I.to_circuit(), 0.875, PhaseEstimation),
)
@unpack
def test_qpe_RZ(self, state_preparation, expected_phase, phase_estimator):
"""eigenproblem RZ, (|0>, |1>)"""
alpha = np.pi / 2
unitary_circuit = QuantumCircuit(1)
unitary_circuit.rz(alpha, 0)
with self.assertWarns(DeprecationWarning):
phase = self.one_phase(
unitary_circuit, state_preparation, phase_estimator=phase_estimator
)
self.assertEqual(phase, expected_phase)
def test_check_num_iterations(self):
"""test check for num_iterations greater than zero"""
unitary_circuit = X.to_circuit()
state_preparation = None
with self.assertRaises(ValueError):
self.one_phase(unitary_circuit, state_preparation, num_iterations=-1)
def phase_estimation(
self,
unitary_circuit,
state_preparation=None,
num_evaluation_qubits=6,
backend=None,
construct_circuit=False,
):
"""Run phase estimation with operator, eigenvalue pair `unitary_circuit`,
`state_preparation`. Return all results
"""
if backend is None:
backend = qiskit.BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000)
with self.assertWarns(DeprecationWarning):
phase_est = PhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits, quantum_instance=qi
)
if construct_circuit:
pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation)
result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits)
else:
result = phase_est.estimate(
unitary=unitary_circuit, state_preparation=state_preparation
)
return result
@data(True, False)
def test_qpe_Zplus(self, construct_circuit):
"""superposition eigenproblem Z, |+>"""
unitary_circuit = Z.to_circuit()
state_preparation = H.to_circuit() # prepare |+>
with self.assertWarns(DeprecationWarning):
result = self.phase_estimation(
unitary_circuit,
state_preparation,
backend=qiskit.BasicAer.get_backend("statevector_simulator"),
construct_circuit=construct_circuit,
)
phases = result.filter_phases(1e-15, as_float=True)
with self.subTest("test phases has correct values"):
self.assertEqual(list(phases.keys()), [0.0, 0.5])
with self.subTest("test phases has correct probabilities"):
np.testing.assert_allclose(list(phases.values()), [0.5, 0.5])
with self.subTest("test bitstring representation"):
phases = result.filter_phases(1e-15, as_float=False)
self.assertEqual(list(phases.keys()), ["000000", "100000"])
# sampler tests
def one_phase_sampler(
self,
unitary_circuit,
state_preparation=None,
phase_estimator=None,
num_iterations=6,
shots=None,
):
"""Run phase estimation with operator, eigenvalue pair `unitary_circuit`,
`state_preparation`. Return the estimated phase as a value in :math:`[0,1)`.
"""
if shots is not None:
options = {"shots": shots}
else:
options = {}
sampler = Sampler(options=options)
if phase_estimator is None:
phase_estimator = IterativePhaseEstimation
if phase_estimator == IterativePhaseEstimation:
p_est = IterativePhaseEstimation(num_iterations=num_iterations, sampler=sampler)
elif phase_estimator == PhaseEstimation:
p_est = PhaseEstimation(num_evaluation_qubits=6, sampler=sampler)
else:
raise ValueError("Unrecognized phase_estimator")
result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation)
phase = result.phase
return phase
@data(
(QuantumCircuit(1).compose(XGate()), 0.5, None, IterativePhaseEstimation),
(QuantumCircuit(1).compose(XGate()), 0.5, 1000, IterativePhaseEstimation),
(None, 0.0, 1000, IterativePhaseEstimation),
(QuantumCircuit(1).compose(XGate()), 0.5, 1000, PhaseEstimation),
(None, 0.0, 1000, PhaseEstimation),
(QuantumCircuit(1).compose(XGate()), 0.5, None, PhaseEstimation),
)
@unpack
def test_qpe_Z_sampler(self, state_preparation, expected_phase, shots, phase_estimator):
"""eigenproblem Z, |0> and |1>"""
unitary_circuit = QuantumCircuit(1).compose(ZGate())
phase = self.one_phase_sampler(
unitary_circuit,
state_preparation=state_preparation,
phase_estimator=phase_estimator,
shots=shots,
)
self.assertEqual(phase, expected_phase)
@data(
(QuantumCircuit(1).compose(HGate()), 0.0, IterativePhaseEstimation),
(QuantumCircuit(1).compose(HGate()).compose(ZGate()), 0.5, IterativePhaseEstimation),
(QuantumCircuit(1).compose(HGate()), 0.0, PhaseEstimation),
(QuantumCircuit(1).compose(HGate()).compose(ZGate()), 0.5, PhaseEstimation),
)
@unpack
def test_qpe_X_plus_minus_sampler(self, state_preparation, expected_phase, phase_estimator):
"""eigenproblem X, (|+>, |->)"""
unitary_circuit = QuantumCircuit(1).compose(XGate())
phase = self.one_phase_sampler(
unitary_circuit,
state_preparation,
phase_estimator,
)
self.assertEqual(phase, expected_phase)
@data(
(QuantumCircuit(1).compose(XGate()), 0.125, IterativePhaseEstimation),
(QuantumCircuit(1).compose(IGate()), 0.875, IterativePhaseEstimation),
(QuantumCircuit(1).compose(XGate()), 0.125, PhaseEstimation),
(QuantumCircuit(1).compose(IGate()), 0.875, PhaseEstimation),
)
@unpack
def test_qpe_RZ_sampler(self, state_preparation, expected_phase, phase_estimator):
"""eigenproblem RZ, (|0>, |1>)"""
alpha = np.pi / 2
unitary_circuit = QuantumCircuit(1)
unitary_circuit.rz(alpha, 0)
phase = self.one_phase_sampler(
unitary_circuit,
state_preparation,
phase_estimator,
)
self.assertEqual(phase, expected_phase)
@data(
((X ^ X).to_circuit(), 0.25, IterativePhaseEstimation),
((I ^ X).to_circuit(), 0.125, IterativePhaseEstimation),
((X ^ X).to_circuit(), 0.25, PhaseEstimation),
((I ^ X).to_circuit(), 0.125, PhaseEstimation),
)
@unpack
def test_qpe_two_qubit_unitary(self, state_preparation, expected_phase, phase_estimator):
"""two qubit unitary T ^ T"""
unitary_circuit = QuantumCircuit(2)
unitary_circuit.t(0)
unitary_circuit.t(1)
phase = self.one_phase_sampler(
unitary_circuit,
state_preparation,
phase_estimator,
)
self.assertEqual(phase, expected_phase)
def test_check_num_iterations_sampler(self):
"""test check for num_iterations greater than zero"""
unitary_circuit = QuantumCircuit(1).compose(XGate())
state_preparation = None
with self.assertRaises(ValueError):
self.one_phase_sampler(unitary_circuit, state_preparation, num_iterations=-1)
def test_phase_estimation_scale_from_operator(self):
"""test that PhaseEstimationScale from_pauli_sum works with Operator"""
circ = QuantumCircuit(2)
op = Operator(circ)
scale = PhaseEstimationScale.from_pauli_sum(op)
self.assertEqual(scale._bound, 4.0)
def phase_estimation_sampler(
self,
unitary_circuit,
sampler: Sampler,
state_preparation=None,
num_evaluation_qubits=6,
construct_circuit=False,
):
"""Run phase estimation with operator, eigenvalue pair `unitary_circuit`,
`state_preparation`. Return all results
"""
phase_est = PhaseEstimation(num_evaluation_qubits=num_evaluation_qubits, sampler=sampler)
if construct_circuit:
pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation)
result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits)
else:
result = phase_est.estimate(
unitary=unitary_circuit, state_preparation=state_preparation
)
return result
@data(True, False)
def test_qpe_Zplus_sampler(self, construct_circuit):
"""superposition eigenproblem Z, |+>"""
unitary_circuit = QuantumCircuit(1).compose(ZGate())
state_preparation = QuantumCircuit(1).compose(HGate()) # prepare |+>
sampler = Sampler()
result = self.phase_estimation_sampler(
unitary_circuit,
sampler,
state_preparation,
construct_circuit=construct_circuit,
)
phases = result.filter_phases(1e-15, as_float=True)
with self.subTest("test phases has correct values"):
self.assertEqual(list(phases.keys()), [0.0, 0.5])
with self.subTest("test phases has correct probabilities"):
np.testing.assert_allclose(list(phases.values()), [0.5, 0.5])
with self.subTest("test bitstring representation"):
phases = result.filter_phases(1e-15, as_float=False)
self.assertEqual(list(phases.keys()), ["000000", "100000"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
|
https://github.com/fysmoe1121/entanglementQKDprotocol-qiskit
|
fysmoe1121
|
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/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests AQC plugin.
"""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import SLSQP
from qiskit.converters import dag_to_circuit, circuit_to_dag
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import UnitarySynthesis
from qiskit.transpiler.synthesis.aqc.aqc_plugin import AQCSynthesisPlugin
class TestAQCSynthesisPlugin(QiskitTestCase):
"""Basic tests of the AQC synthesis plugin."""
def setUp(self):
super().setUp()
self._qc = QuantumCircuit(3)
self._qc.mcx(
[
0,
1,
],
2,
)
self._target_unitary = Operator(self._qc).data
self._seed_config = {"seed": 12345}
def test_aqc_plugin(self):
"""Basic test of the plugin."""
plugin = AQCSynthesisPlugin()
dag = plugin.run(self._target_unitary, config=self._seed_config)
approx_circuit = dag_to_circuit(dag)
approx_unitary = Operator(approx_circuit).data
np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3)
def test_plugin_setup(self):
"""Tests the plugin via unitary synthesis pass"""
transpiler_pass = UnitarySynthesis(
basis_gates=["rx", "ry", "rz", "cx"], method="aqc", plugin_config=self._seed_config
)
dag = circuit_to_dag(self._qc)
dag = transpiler_pass.run(dag)
approx_circuit = dag_to_circuit(dag)
approx_unitary = Operator(approx_circuit).data
np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3)
def test_plugin_configuration(self):
"""Tests plugin with a custom configuration."""
config = {
"network_layout": "sequ",
"connectivity_type": "full",
"depth": 0,
"seed": 12345,
"optimizer": SLSQP(),
}
transpiler_pass = UnitarySynthesis(
basis_gates=["rx", "ry", "rz", "cx"], method="aqc", plugin_config=config
)
dag = circuit_to_dag(self._qc)
dag = transpiler_pass.run(dag)
approx_circuit = dag_to_circuit(dag)
approx_unitary = Operator(approx_circuit).data
np.testing.assert_array_almost_equal(self._target_unitary, approx_unitary, 3)
def test_with_pass_manager(self):
"""Tests the plugin via pass manager"""
qc = QuantumCircuit(3)
qc.unitary(np.eye(8), [0, 1, 2])
aqc = PassManager(
[
UnitarySynthesis(
basis_gates=["u", "cx"], method="aqc", plugin_config=self._seed_config
)
]
).run(qc)
approx_unitary = Operator(aqc).data
np.testing.assert_array_almost_equal(np.eye(8), approx_unitary, 3)
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
# makes weyl plot of candidate gates with basic metrics
from slam.utils.gates.bare_candidates import build_gates
import numpy as np
from slam.utils.gates.duraton_scaling import atomic_cost_scaling
from matplotlib import colors
from slam.utils.visualize import coordinate_2dlist_weyl
unitary_list, coordinate_list = build_gates()
color_list = []
speed_method = "linear"
for u in unitary_list[1:]:
h, _ = atomic_cost_scaling(
params=u.params, scores=np.array([0]), speed_method=speed_method, duration_1q=0
)
color_list.append(h.duration)
fig = coordinate_2dlist_weyl(
np.array(coordinate_list[1:]).reshape(-1, 3),
c=color_list,
elev=90,
azim=-90,
cmap="viridis",
);
fig = coordinate_2dlist_weyl(
np.array(coordinate_list[1:]).reshape(-1, 3),
c=color_list,
elev=90,
azim=-90,
cmap="viridis",
);
# fig.tight_layout()
# save matplotlib fig as pdf
# fig.savefig(f'/home/evm9/decomposition_EM/images/weyl_plot_{speed_method}_haar.pdf', format='pdf')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Create circuit to test transpiler on
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, Diagonal
oracle = Diagonal([1]*7 + [-1])
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc = qc.compose(GroverOperator(oracle))
# Use Statevector object to calculate the ideal output
from qiskit.quantum_info import Statevector
ideal_distribution = Statevector.from_instruction(qc).probabilities_dict()
from qiskit.visualization import plot_histogram
plot_histogram(ideal_distribution)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend('ibm_algiers')
# Need to add measurements to the circuit
qc.measure_all()
from qiskit import transpile
circuits = []
for optimization_level in [0, 3]:
t_qc = transpile(qc,
backend,
optimization_level=optimization_level,
seed_transpiler=0)
print(f'CNOTs (optimization_level={optimization_level}): ',
t_qc.count_ops()['cx'])
circuits.append(t_qc)
from qiskit.transpiler import PassManager, InstructionDurations
from qiskit.transpiler.passes import ASAPSchedule, DynamicalDecoupling
from qiskit.circuit.library import XGate
# Get gate durations so the transpiler knows how long each operation takes
durations = InstructionDurations.from_backend(backend)
# This is the sequence we'll apply to idling qubits
dd_sequence = [XGate(), XGate()]
# Run scheduling and dynamic decoupling passes on circuit
pm = PassManager([ASAPSchedule(durations),
DynamicalDecoupling(durations, dd_sequence)]
)
circ_dd = pm.run(circuits[1])
# Add this new circuit to our list
circuits.append(circ_dd)
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=circuits, # sample all three circuits
skip_transpilation=True,
shots=8000)
result = job.result()
from qiskit.visualization import plot_histogram
binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists]
plot_histogram(binary_prob+[ideal_distribution],
bar_labels=False,
legend=['optimization_level=0',
'optimization_level=3',
'optimization_level=3 + dd',
'ideal distribution'])
from qiskit.quantum_info import hellinger_fidelity
for counts in result.quasi_dists:
print(
f"{hellinger_fidelity(counts.binary_probabilities(), ideal_distribution):.3f}"
)
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 6 12:00:14 2022
@author: pejmanjouzdani
"""
import numpy as np
from qiskit import QuantumCircuit
from BasicFunctions.functions import getBinary
def getRealPart_base_circ(nspins, circ_U , Q, j_ref, gamma = np.pi/10):
circ_adj = QuantumCircuit(nspins+1)
circ_adj.ry(gamma, qubit=-1) ### R_gamma
circ_adj.x(qubit=-1) ### X
### U
### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) )
### control-Q ; Ancillary - n target
for (q,o) in enumerate(Q):
if o==1:
circ_adj.cx(-1, q)
if o==2:
circ_adj.cy(-1, q)
if o==3:
circ_adj.cz(-1, q)
### U^
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse())
### control-P_{0 j_ref}
circ_adj.x(qubit=nspins)
J1 = list(getBinary(j_ref, nspins)) + [0]
for (q,o) in enumerate(J1):
if o==1:
circ_adj.cx(nspins, q)
circ_adj.x(nspins)
### S and H on ancillary
circ_adj.s(-1)
circ_adj.h(nspins)
return circ_adj
|
https://github.com/qiskit-community/qiskit-toqm
|
qiskit-community
|
# 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.
import qiskit_toqm.native as toqm
class ToqmHeuristicStrategy:
def __init__(self, latency_descriptions, top_k, queue_target, queue_max, retain_popped=1):
"""
Constructs a TOQM strategy that aims to minimize overall circuit duration.
The priority queue used in the A* is configured to drop the worst nodes
whenever it reaches the queue size limit. Node expansion is also limited
to exploring the best ``K`` children.
Args:
latency_descriptions (List[toqm.LatencyDescription]): The latency descriptions
for all gates that will appear in the circuit, including swaps.
top_k (int): The maximum number of best child nodes that can be pushed to the
queue during expansion of any given node.
queue_target (int): When the priority queue reaches capacity, nodes are dropped
until the size reaches this value.
queue_max (int): The priority queue capacity.
retain_popped (int): Final nodes to retain.
Raises:
RuntimeError: No routing was found.
"""
# The following defaults are based on:
# https://github.com/time-optimal-qmapper/TOQM/blob/main/code/README.txt
self.mapper = toqm.ToqmMapper(
toqm.TrimSlowNodes(queue_max, queue_target),
toqm.GreedyTopK(top_k),
toqm.CXFrontier(),
toqm.Table(list(latency_descriptions)),
[toqm.GreedyMapper()],
[],
0
)
self.mapper.setRetainPopped(retain_popped)
def __call__(self, gates, num_qubits, coupling_map):
"""
Run native ToqmMapper and return the native result.
Args:
gates (List[toqm.GateOp]): The topologically ordered list of gate operations.
num_qubits (int): The number of virtual qubits used in the circuit.
coupling_map (toqm.CouplingMap): The coupling map of the target.
Returns:
toqm.ToqmResult: The native result.
"""
return self.mapper.run(gates, num_qubits, coupling_map)
class ToqmOptimalStrategy:
def __init__(self, latency_descriptions, perform_layout=True, no_swaps=False):
"""
Constructs a TOQM strategy that finds an optimal (minimal) routing
in terms of overall circuit duration.
Args:
latency_descriptions (List[toqm.LatencyDescription]): The latency descriptions
for all gates that will appear in the circuit, including swaps.
perform_layout (Boolean): If true, permutes the initial layout rather than
inserting swap gates at the start of the circuit.
no_swaps (Boolean): If true, attempts to find a routing without inserting swaps.
Raises:
RuntimeError: No routing was found.
"""
# The following defaults are based on:
# https://github.com/time-optimal-qmapper/TOQM/blob/main/code/README.txt
self.mapper = toqm.ToqmMapper(
toqm.DefaultQueue(),
toqm.NoSwaps() if no_swaps else toqm.DefaultExpander(),
toqm.CXFrontier(),
toqm.Table(latency_descriptions),
[],
[toqm.HashFilter(), toqm.HashFilter2()],
-1 if perform_layout else 0
)
def __call__(self, gates, num_qubits, coupling_map):
"""
Run native ToqmMapper and return the native result.
Args:
gates (List[toqm.GateOp]): The topologically ordered list of gate operations.
num_qubits (int): The number of virtual qubits used in the circuit.
coupling_map (toqm.CouplingMap): The coupling map of the target.
Returns:
toqm.ToqmResult: The native result.
"""
return self.mapper.run(gates, num_qubits, coupling_map)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import torch
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
_ = torch.manual_seed(123456) # suppress output
import numpy as np
num_dim = 2
num_discrete_values = 8
num_qubits = num_dim * int(np.log2(num_discrete_values))
from scipy.stats import multivariate_normal
coords = np.linspace(-2, 2, num_discrete_values)
rv = multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0], [0, 1]], seed=algorithm_globals.random_seed)
grid_elements = np.transpose([np.tile(coords, len(coords)), np.repeat(coords, len(coords))])
prob_data = rv.pdf(grid_elements)
prob_data = prob_data / np.sum(prob_data)
import matplotlib.pyplot as plt
from matplotlib import cm
mesh_x, mesh_y = np.meshgrid(coords, coords)
grid_shape = (num_discrete_values, num_discrete_values)
fig, ax = plt.subplots(figsize=(9, 9), subplot_kw={"projection": "3d"})
prob_grid = np.reshape(prob_data, grid_shape)
surf = ax.plot_surface(mesh_x, mesh_y, prob_grid, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
from qiskit import QuantumCircuit
from qiskit.circuit.library import EfficientSU2
qc = QuantumCircuit(num_qubits)
qc.h(qc.qubits)
ansatz = EfficientSU2(num_qubits, reps=6)
qc.compose(ansatz, inplace=True)
qc.decompose().draw("mpl")
qc.num_parameters
from qiskit.primitives import Sampler
shots = 10000
sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed})
from qiskit_machine_learning.connectors import TorchConnector
from qiskit_machine_learning.neural_networks import SamplerQNN
def create_generator() -> TorchConnector:
qnn = SamplerQNN(
circuit=qc,
sampler=sampler,
input_params=[],
weight_params=qc.parameters,
sparse=False,
)
initial_weights = algorithm_globals.random.random(qc.num_parameters)
return TorchConnector(qnn, initial_weights)
from torch import nn
class Discriminator(nn.Module):
def __init__(self, input_size):
super(Discriminator, self).__init__()
self.linear_input = nn.Linear(input_size, 20)
self.leaky_relu = nn.LeakyReLU(0.2)
self.linear20 = nn.Linear(20, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input: torch.Tensor) -> torch.Tensor:
x = self.linear_input(input)
x = self.leaky_relu(x)
x = self.linear20(x)
x = self.sigmoid(x)
return x
generator = create_generator()
discriminator = Discriminator(num_dim)
def adversarial_loss(input, target, w):
bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input)
weighted_loss = w * bce_loss
total_loss = -torch.sum(weighted_loss)
return total_loss
from torch.optim import Adam
lr = 0.01 # learning rate
b1 = 0.7 # first momentum parameter
b2 = 0.999 # second momentum parameter
generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005)
discriminator_optimizer = Adam(
discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005
)
from IPython.display import clear_output
def plot_training_progress():
# we don't plot if we don't have enough data
if len(generator_loss_values) < 2:
return
clear_output(wait=True)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9))
# Generator Loss
ax1.set_title("Loss")
ax1.plot(generator_loss_values, label="generator loss", color="royalblue")
ax1.plot(discriminator_loss_values, label="discriminator loss", color="magenta")
ax1.legend(loc="best")
ax1.set_xlabel("Iteration")
ax1.set_ylabel("Loss")
ax1.grid()
# Relative Entropy
ax2.set_title("Relative entropy")
ax2.plot(entropy_values)
ax2.set_xlabel("Iteration")
ax2.set_ylabel("Relative entropy")
ax2.grid()
plt.show()
import time
from scipy.stats import multivariate_normal, entropy
n_epochs = 50
num_qnn_outputs = num_discrete_values**num_dim
generator_loss_values = []
discriminator_loss_values = []
entropy_values = []
start = time.time()
for epoch in range(n_epochs):
valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float)
fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float)
# Configure input
real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1)
# Configure samples
samples = torch.tensor(grid_elements, dtype=torch.float)
disc_value = discriminator(samples)
# Generate data
gen_dist = generator(torch.tensor([])).reshape(-1, 1)
# Train generator
generator_optimizer.zero_grad()
generator_loss = adversarial_loss(disc_value, valid, gen_dist)
# store for plotting
generator_loss_values.append(generator_loss.detach().item())
generator_loss.backward(retain_graph=True)
generator_optimizer.step()
# Train Discriminator
discriminator_optimizer.zero_grad()
real_loss = adversarial_loss(disc_value, valid, real_dist)
fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach())
discriminator_loss = (real_loss + fake_loss) / 2
# Store for plotting
discriminator_loss_values.append(discriminator_loss.detach().item())
discriminator_loss.backward()
discriminator_optimizer.step()
entropy_value = entropy(gen_dist.detach().squeeze().numpy(), prob_data)
entropy_values.append(entropy_value)
plot_training_progress()
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} sec")
with torch.no_grad():
generated_probabilities = generator().numpy()
fig = plt.figure(figsize=(18, 9))
# Generated CDF
gen_prob_grid = np.reshape(np.cumsum(generated_probabilities), grid_shape)
ax1 = fig.add_subplot(1, 3, 1, projection="3d")
ax1.set_title("Generated CDF")
ax1.plot_surface(mesh_x, mesh_y, gen_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax1.set_zlim(-0.05, 1.05)
# Real CDF
real_prob_grid = np.reshape(np.cumsum(prob_data), grid_shape)
ax2 = fig.add_subplot(1, 3, 2, projection="3d")
ax2.set_title("True CDF")
ax2.plot_surface(mesh_x, mesh_y, real_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax2.set_zlim(-0.05, 1.05)
# Difference
ax3 = fig.add_subplot(1, 3, 3, projection="3d")
ax3.set_title("Difference between CDFs")
ax3.plot_surface(
mesh_x, mesh_y, real_prob_grid - gen_prob_grid, linewidth=2, antialiased=False, cmap=cm.coolwarm
)
ax3.set_zlim(-0.05, 0.1)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/UST-QuAntiL/nisq-analyzer-content
|
UST-QuAntiL
|
import os
import qiskit.ignis.verification.randomized_benchmarking as rb
#Number of seeds (random sequences)
nseeds = 2
#Number of Cliffords in the sequence
nCliffs = [1, 10, 20, 50]
#2Q RB on Q0,Q2 and 1Q RB on Q1 etc., also defines the width of the circuit
# rb_pattern = [[0,2],[1],[3,4]]
rb_pattern = [[0,1],[2],[3,4]]
rb_pattern_string = '_'.join(['-'.join([str(r) for r in rb]) for rb in rb_pattern])
#Do three times as many 1Q Cliffords
#length_multiplier = [1,3,1,2]
rb_opts = {}
rb_opts['length_vector'] = nCliffs
rb_opts['nseeds'] = nseeds
rb_opts['rb_pattern'] = rb_pattern
#rb_opts['length_multiplier'] = length_multiplier
rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts)
# store generated circuits in desired directory
count = 0
indexListElem = 0
for listElem in rb_circs:
indexListElem += 1
listElem_string = str(indexListElem)
count += len(listElem)
for indexElem, elem in enumerate(listElem):
print("----------------------------------------")
print(f"depth: {elem.depth()}")
print(f"number of multi-qubit gates: {elem.num_nonlocal_gates()}")
nCliffs_string = str(nCliffs[indexElem])
file_name = 'pattern' + rb_pattern_string + 'nCliffs' + nCliffs_string + 'seed' + listElem_string + '.qasm'
save_dir = '/Users/mariesalm/Downloads/temp/' # enter your directory here
with open(os.path.join(save_dir, file_name), 'w') as file:
file.write(elem.qasm())
print("****************************************")
print (f"Generated {count} circuits")
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_jakarta')
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
def bernstein_vazirani(s):
ls = len(s)
qc = QuantumCircuit(ls+1,ls)
qc.h(range(ls))
qc.x(ls)
qc.h(ls)
qc.barrier();
for ii, yesno in enumerate(reversed(s)): # the black box
if yesno == '1':
qc.cx(ii, ls);
qc.barrier();
qc.h(range(ls));
qc.barrier();
qc.measure(range(ls),range(ls))
return qc
s = '011' # secretnumber
qc = bernstein_vazirani(s)
qc.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/yatharth0610/Quantum-Algorithms-qiskit-
|
yatharth0610
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.compiler import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import numpy as np
import qiskit.quantum_info as qi
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
#This cell is just for seeing what the U tilde matrix looks like
a, b, c, d = np.cos(np.pi/8), np.sin(np.pi/8), -np.sin(np.pi/8), np.cos(np.pi/8)
u_tilde = np.array([[a,c],[b,d]]).reshape(2,2)
print(u_tilde)
#This cell defines the controlled variant of the U tilde matrix
qc_for_u = QuantumCircuit(1)
qc_for_u.ry(np.pi/4, 0)
qc_for_u.name = "U"
controlled_u_tilde = qc_for_u.to_gate().control(2)
qc1 = QuantumCircuit(3)
qc1.x(0)
qc1.x(1)
qc1.toffoli(0,1,2)#Flipping the third bit if the first two are zero
qc1.x(0) #Essentially 000 -> 001
qc1.x(1)
qc1.x(0)
qc1.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one
qc1.x(0) #Essentially 001 -> 011
qc1.append(controlled_u_tilde, [1, 2, 0])
qc1.x(0)
qc1.toffoli(0,2,1)#Undoing the flip from before
qc1.x(0)
qc1.x(0)
qc1.x(1)
qc1.toffoli(0,1,2)#Undoing the flip from before
qc1.x(0)
qc1.x(1)
qc1.draw('mpl')
U_circ = qi.Operator(qc1).data
print(U_circ)
qc2 = QuantumCircuit(3)
# Code for U
qc2.x(0)
qc2.x(1)
qc2.toffoli(0,1,2)#Flipping the third bit if the first two are zero
qc2.x(0) #Essentially 000 -> 001
qc2.x(1)
qc2.x(0)
qc2.toffoli(0,2,1)#Flipping the second bit if the first bit is zero and the third is one
qc2.x(0) #Essentially 001 -> 011
qc2.append(controlled_u_tilde, [1, 2, 0])
qc2.x(0)
qc2.toffoli(0,2,1)#Undoing the flip from before
qc2.x(0)
qc2.x(0)
qc2.x(1)
qc2.toffoli(0,1,2)#Undoing the flip from before
qc2.x(0)
qc2.x(1)
# Code for V
qc2.x(0)
qc2.toffoli(0,1,2) # |010> -> |011>
qc2.x(0)
qc2.toffoli(1,2,0) # V-tilde is the same as Toffoli
qc2.x(0)
qc2.toffoli(0,1,2) # Reversing the flip
qc2.x(0)
qc2.draw('mpl')
def without_global_phase(matrix: np.ndarray, atol: float = 1e-8) :
phases1 = np.angle(matrix[abs(matrix) > atol].ravel(order='F'))
if len(phases1) > 0:
matrix = np.exp(-1j * phases1[0]) * matrix
return matrix
V_circ = without_global_phase(qi.Operator(qc2).data)
print(V_circ)
#Function just returns norm ignoring global phase between unitaries
def norm(unitary_a: np.ndarray, unitary_b: np.ndarray) :
return np.linalg.norm(without_global_phase(unitary_b)-without_global_phase(unitary_a), ord=2)
#Make the Pauli Y gate
qcy = QuantumCircuit(1)
for i in range(6):
qcy.t(0)
qcy.h(0)
for i in range(4):
qcy.t(0)
qcy.h(0)
for i in range(2):
qcy.t(0)
Y_circ = qi.Operator(qcy).data
Y = np.array([[0,-1j],[1j,0]])
print(norm(Y_circ,Y))
print("Final Circuit:")
qcy.draw('mpl')
uni_q = np.array([[-0.25+0.60355339j, 0.60355339+0.45710678j],
[0.60355339-0.45710678j, 0.25+0.60355339j]]).reshape(2,2)
while True:
qc3 = QuantumCircuit(1)
for i in range(5):
for j in range(np.random.randint(8)):
qc3.t(0)
qc3.h(0)
for j in range(np.random.randint(8)):
qc3.t(0)
uni_q_circ = qi.Operator(qc3).data
if norm(uni_q_circ,uni_q) < 1e-8:
break
print("Final Error: ", norm(uni_q_circ,uni_q))
print("Final Circuit:")
qc3.draw('mpl')
#Defining the gate as controlled_irx
from qiskit.extensions import *
pi_alpha = np.arccos(0.6)
qc_for_irx = QuantumCircuit(1)
irx = np.array([[1j*np.cos(pi_alpha/2),np.sin(pi_alpha/2)],[np.sin(pi_alpha/2),1j*np.cos(pi_alpha/2)]]).reshape(2,2)
g_irx = UnitaryGate(data=irx,label=None)
controlled_irx = g_irx.control(2)
def final_vector(qc):
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=3)
return outputstate
n = 4
qcb = QuantumCircuit(n,n)
qcb.x(0)#Ancilla
qcb.x(1)#Ancilla You can use these two as control to use the controlled_irx gate
count1 = 0
while abs(0.5 - (count1*pi_alpha/np.pi)%2) >= 1e-2 or count1 % 4 != 0:
count1 += 1
count2 = 0
while abs(1.5 - (count2*pi_alpha/np.pi)%2) >= 1e-2 or count2 % 4 != 0:
count2 += 1
count3 = 0
while abs(4.0 - (count3*pi_alpha/np.pi)%4) >= 1e-2 or count3 % 4 != 2:
count3 += 1
for i in range(count1): # Rotation about x by pi/2 (count1 % 4 == 0)
qcb.append(controlled_irx, [0, 1, 2])
qcb.cx(2, 3)
for i in range(count2): # Rotation about x by -pi/2 (count2 % 4 == 0)
qcb.append(controlled_irx, [0, 1, 2])
qcb.x(0)
qcb.cx(3, 0)
for i in range(count3): # Rotation about x by 0 (count3 % 4 == 2)
qcb.append(controlled_irx, [0, 2, 3])
qcb.cx(3, 0)
qcb.x(0)
print("Executing circuit...")
#Get state of qubit which should have the |+> state using the backend simulator
i = 3 #Index for the qubit at |+> state
qcb.h(i)#Puts the |+> state to |0>
for i in range(4):
qcb.measure(i, i)
def run_circuit(qcb):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qcb, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qcb)
print(counts)
plot_histogram(counts)
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
from qiskit import *
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from matplotlib import pyplot
# Quanum ciruit to make a Bell state
bell = QuantumCircuit(2,2)
bell.h(0)
bell.cx(0,1)
meas = QuantumCircuit(2,2)
meas.measure([0,1],[0,1])
# execute quantum circuit
backend = BasicAer.get_backend('qasm_simulator')
circ = bell + meas
result = execute(circ,backend,shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts).show() # don't need pyplot.show() anymore
# could also call .savefig('output.png') to save to file
second_result = execute(circ,backend, shots=1000).result()
second_counts = second_result.get_counts(circ)
legend = ['first execution', 'second execution']
plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12),
color=['orange', 'black'], bar_labels=False).savefig('histogram1.png')
### Advanced Visualizations
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_state_paulivec, plot_state_hinton
from qiskit.visualization import plot_state_qsphere
# execute quantum circuit
backend = BasicAer.get_backend('statevector_simulator')
result = execute(bell,backend).result()
psi = result.get_statevector(bell)
plot_state_city(psi,
title = "My City",
color = ['black', 'orange']).show()
plot_state_hinton(psi,
title = "My Hinton").show()
plot_state_qsphere(psi).show()
plot_state_paulivec(psi,
title = "My Paulivec",
color = ['purple', 'orange', 'green']).show()
plot_bloch_multivector(psi,
title = "My Bloch Spheres").show()
# note: there is no vector in block multivector since system is in an entangled state
### Plotting Bloch Vectors
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0],
title = "My Bloch Sphere").show()
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from qiskit import *
from qiskit.circuit.library import *
from qiskit.providers.aer import *
sim = AerSimulator(method='statevector', device='GPU')
qubits = 15
depth=10
shots = 10
circuit = QuantumVolume(qubits, depth, seed=0)
circuit.measure_all()
result = execute(circuit,sim,shots=shots,seed_simulator=12345).result()
print("{0} qubits Quantum Volume, Simulation Time = {1} sec".format(qubits,result.to_dict()['results'][0]['time_taken']))
counts = result.get_counts()
print(counts)
from qiskit import *
from qiskit.circuit.library import *
from qiskit.providers.aer import *
sim = AerSimulator(method='statevector', device='GPU', cuStateVec_enable=True)
qubits = 15
depth=10
shots = 10
circuit = QuantumVolume(qubits, depth, seed=0)
circuit.measure_all()
result = execute(circuit,sim,shots=shots,seed_simulator=12345).result()
if result.to_dict()['results'][0]['metadata']['cuStateVec_enable'] == True:
print("cuStateVector is used for the simulation")
print("{0} qubits, Time = {1} sec".format(qubits,result.to_dict()['results'][0]['time_taken']))
counts = result.get_counts()
print(counts)
from qiskit import *
from qiskit.circuit.library import *
from qiskit.providers.aer import *
import matplotlib.pyplot as plt
sim = AerSimulator(method='statevector', device='GPU')
shots = 100
depth=10
time_thrust= []
time_cuStateVec= []
qubits_list = []
for qubits in range (15, 26):
qubits_list.append(qubits)
circuit = QuantumVolume(qubits, depth, seed=0)
circuit.measure_all()
result = execute(circuit,sim,shots=shots,seed_simulator=12345,fusion_threshold=20,cuStateVec_enable=False).result()
time_thrust.append(float(result.to_dict()['results'][0]['time_taken']))
result_cuStateVec = execute(circuit,sim,shots=shots,seed_simulator=12345,fusion_threshold=20,cuStateVec_enable=True).result()
time_cuStateVec.append(float(result_cuStateVec.to_dict()['results'][0]['time_taken']))
plt.yscale("log")
plt.plot(qubits_list, time_thrust, marker="o", label='ThrustGPU')
plt.plot(qubits_list, time_cuStateVec, 'g', marker="x", label='cuStateVec')
plt.legend()
|
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/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, 1], [0, 1])
circ.draw("mpl")
from qiskit import transpile, schedule as build_schedule
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1
schedule = build_schedule(transpiled_circ, backend)
schedule.draw()
from qiskit import pulse
with pulse.build() as h_q0:
pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'),
pulse.DriveChannel(0))
circ.add_calibration('h', [0], h_q0)
schedule = build_schedule(circ, backend)
schedule.draw()
circ = QuantumCircuit(2, 2)
circ.x(0)
circ.x(0)
circ.x(1)
circ.measure([0, 1], [0, 1])
circ.draw("mpl")
schedule = build_schedule(circ, backend, method="as_late_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
schedule = build_schedule(circ, backend, method="as_soon_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
ghz.draw(output='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.
import os
import numpy as np
import pytest
import qiskit
from cirq import (
Circuit,
CXPowGate,
DepolarizingChannel,
I,
LineQubit,
MixedUnitaryChannel,
Rx,
Rz,
X,
Y,
Z,
ops,
unitary,
)
from mitiq import Executor, Observable, PauliString
from mitiq.cdr import generate_training_circuits
from mitiq.cdr._testing import random_x_z_cnot_circuit
from mitiq.interface.mitiq_cirq import compute_density_matrix
from mitiq.interface.mitiq_qiskit import qiskit_utils
from mitiq.interface.mitiq_qiskit.conversions import to_qiskit
from mitiq.pec.representations.learning import (
_parse_learning_kwargs,
biased_noise_loss_function,
depolarizing_noise_loss_function,
learn_biased_noise_parameters,
learn_depolarizing_noise_parameter,
)
rng = np.random.RandomState(1)
circuit = random_x_z_cnot_circuit(
LineQubit.range(2), n_moments=5, random_state=rng
)
# Set number of samples used to calculate mitigated value in loss function
pec_kwargs = {"num_samples": 20, "random_state": 1}
observable = Observable(PauliString("XZ"), PauliString("YY"))
training_circuits = generate_training_circuits(
circuit=circuit,
num_training_circuits=3,
fraction_non_clifford=0,
method_select="uniform",
method_replace="closest",
)
CNOT_ops = list(circuit.findall_operations_with_gate_type(CXPowGate))
Rx_ops = list(circuit.findall_operations_with_gate_type(Rx))
Rz_ops = list(circuit.findall_operations_with_gate_type(Rz))
def ideal_execute(circ: Circuit) -> np.ndarray:
return compute_density_matrix(circ, noise_level=(0.0,))
ideal_executor = Executor(ideal_execute)
ideal_values = np.array(ideal_executor.evaluate(training_circuits, observable))
def biased_noise_channel(epsilon: float, eta: float) -> MixedUnitaryChannel:
a = 1 - epsilon
b = epsilon * (3 * eta + 1) / (3 * (eta + 1))
c = epsilon / (3 * (eta + 1))
mix = [
(a, unitary(I)),
(b, unitary(Z)),
(c, unitary(X)),
(c, unitary(Y)),
]
return ops.MixedUnitaryChannel(mix)
@pytest.mark.parametrize("epsilon", [0.05, 0.1])
@pytest.mark.parametrize(
"operations", [[Circuit(CNOT_ops[0][1])], [Circuit(Rx_ops[0][1])]]
)
def test_depolarizing_noise_loss_function(epsilon, operations):
"""Test that the biased noise loss function value (calculated with error
mitigation) is less than (or equal to) the loss calculated with the noisy
(unmitigated) executor"""
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.with_noise(DepolarizingChannel(epsilon))
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
noisy_values = np.array(
noisy_executor.evaluate(training_circuits, observable)
)
loss = depolarizing_noise_loss_function(
epsilon=np.array([epsilon]),
operations_to_mitigate=operations,
training_circuits=training_circuits,
ideal_values=ideal_values,
noisy_executor=noisy_executor,
pec_kwargs=pec_kwargs,
observable=observable,
)
assert loss <= np.mean((noisy_values - ideal_values) ** 2)
@pytest.mark.parametrize("epsilon", [0, 0.7, 1])
@pytest.mark.parametrize("eta", [0, 1])
@pytest.mark.parametrize(
"operations", [[Circuit(CNOT_ops[0][1])], [Circuit(Rx_ops[0][1])]]
)
def test_biased_noise_loss_function(epsilon, eta, operations):
"""Test that the biased noise loss function value (calculated with error
mitigation) is less than (or equal to) the loss calculated with the noisy
(unmitigated) executor"""
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.with_noise(biased_noise_channel(epsilon, eta))
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
noisy_values = np.array(
noisy_executor.evaluate(training_circuits, observable)
)
loss = biased_noise_loss_function(
params=[epsilon, eta],
operations_to_mitigate=operations,
training_circuits=training_circuits,
ideal_values=ideal_values,
noisy_executor=noisy_executor,
pec_kwargs=pec_kwargs,
observable=observable,
)
assert loss <= np.mean((noisy_values - ideal_values) ** 2)
@pytest.mark.parametrize(
"operations", [[Circuit(CNOT_ops[0][1])], [Circuit(Rz_ops[0][1])]]
)
def test_biased_noise_loss_compare_ideal(operations):
"""Test that the loss function is zero when the noise strength is zero"""
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.with_noise(biased_noise_channel(0, 0))
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
loss = biased_noise_loss_function(
params=[0, 0],
operations_to_mitigate=operations,
training_circuits=training_circuits,
ideal_values=ideal_values,
noisy_executor=noisy_executor,
pec_kwargs=pec_kwargs,
observable=observable,
)
assert np.isclose(loss, 0)
@pytest.mark.parametrize(
"operations",
[
[to_qiskit(Circuit(CNOT_ops[0][1]))],
[to_qiskit(Circuit(Rx_ops[0][1]))],
[to_qiskit(Circuit(Rz_ops[0][1]))],
],
)
def test_biased_noise_loss_function_qiskit(operations):
"""Test the learning function with initial noise strength and noise bias
with a small offset from the simulated noise model values"""
qiskit_circuit = to_qiskit(circuit)
qiskit_training_circuits = generate_training_circuits(
circuit=qiskit_circuit,
num_training_circuits=3,
fraction_non_clifford=0.2,
method_select="uniform",
method_replace="closest",
random_state=rng,
)
obs = Observable(PauliString("XY"), PauliString("ZZ"))
def ideal_execute_qiskit(circ: qiskit.QuantumCircuit) -> float:
return qiskit_utils.execute(circ, obs.matrix())
ideal_executor_qiskit = Executor(ideal_execute_qiskit)
ideal_values = np.array(
ideal_executor_qiskit.evaluate(qiskit_training_circuits)
)
epsilon = 0.1
def noisy_execute_qiskit(circ: qiskit.QuantumCircuit) -> float:
noise_model = qiskit_utils.initialized_depolarizing_noise(epsilon)
return qiskit_utils.execute_with_noise(circ, obs.matrix(), noise_model)
noisy_executor_qiskit = Executor(noisy_execute_qiskit)
noisy_values = np.array(
noisy_executor_qiskit.evaluate(qiskit_training_circuits)
)
loss = biased_noise_loss_function(
params=[epsilon, 0],
operations_to_mitigate=operations,
training_circuits=qiskit_training_circuits,
ideal_values=ideal_values,
noisy_executor=noisy_executor_qiskit,
pec_kwargs=pec_kwargs,
)
assert loss <= np.mean((noisy_values - ideal_values) ** 2)
@pytest.mark.parametrize("epsilon", [0.05, 0.1])
def test_learn_depolarizing_noise_parameter(epsilon):
"""Test the learning function with initial noise strength with a small
offset from the simulated noise model values"""
operations_to_learn = [Circuit(op[1]) for op in CNOT_ops]
offset = 0.1
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.copy()
insertions = []
for op in CNOT_ops:
index = op[0] + 1
qubits = op[1].qubits
for q in qubits:
insertions.append((index, DepolarizingChannel(epsilon)(q)))
noisy_circ.batch_insert(insertions)
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
epsilon0 = (1 - offset) * epsilon
eps_string = str(epsilon).replace(".", "_")
pec_data = np.loadtxt(
os.path.join(
"./mitiq/pec/representations/tests/learning_pec_data",
f"learning_pec_data_eps_{eps_string}.txt",
)
)
[success, epsilon_opt] = learn_depolarizing_noise_parameter(
operations_to_learn=operations_to_learn,
circuit=circuit,
ideal_executor=ideal_executor,
noisy_executor=noisy_executor,
num_training_circuits=5,
fraction_non_clifford=0.2,
training_random_state=np.random.RandomState(1),
epsilon0=epsilon0,
observable=observable,
learning_kwargs={"pec_data": pec_data},
)
assert success
assert abs(epsilon_opt - epsilon) < offset * epsilon
@pytest.mark.parametrize("epsilon", [0.05, 0.1])
@pytest.mark.parametrize("eta", [1, 2])
def test_learn_biased_noise_parameters(epsilon, eta):
"""Test the learning function can run without pre-executed data"""
operations_to_learn = [Circuit(op[1]) for op in CNOT_ops]
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.copy()
insertions = []
for op in CNOT_ops:
index = op[0] + 1
qubits = op[1].qubits
for q in qubits:
insertions.append(
(index, biased_noise_channel(epsilon, eta)(q))
)
noisy_circ.batch_insert(insertions)
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
eps_offset = 0.1
eta_offset = 0.2
epsilon0 = (1 - eps_offset) * epsilon
eta0 = (1 - eta_offset) * eta
num_training_circuits = 5
pec_data = np.zeros([122, 122, num_training_circuits])
eps_string = str(epsilon).replace(".", "_")
for tc in range(0, num_training_circuits):
pec_data[:, :, tc] = np.loadtxt(
os.path.join(
"./mitiq/pec/representations/tests/learning_pec_data",
f"learning_pec_data_eps_{eps_string}eta_{eta}tc_{tc}.txt",
)
)
[success, epsilon_opt, eta_opt] = learn_biased_noise_parameters(
operations_to_learn=operations_to_learn,
circuit=circuit,
ideal_executor=ideal_executor,
noisy_executor=noisy_executor,
num_training_circuits=num_training_circuits,
fraction_non_clifford=0.2,
training_random_state=np.random.RandomState(1),
epsilon0=epsilon0,
eta0=eta0,
observable=observable,
learning_kwargs={"pec_data": pec_data},
)
assert success
assert abs(epsilon_opt - epsilon) < eps_offset * epsilon
assert abs(eta_opt - eta) < eta_offset * eta
def test_empty_learning_kwargs():
learning_kwargs = {}
pec_data, method, minimize_kwargs = _parse_learning_kwargs(
learning_kwargs=learning_kwargs
)
assert pec_data is None
assert method == "Nelder-Mead"
assert minimize_kwargs == {}
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/sebastianvromero/qecc_shor9q
|
sebastianvromero
|
%run QECC_Shor9Q_functions.ipynb
# Qubits for our entangled state
q0 = QuantumRegister(3, name = 'q0')
q1 = QuantumRegister(3, name = 'q1')
q2 = QuantumRegister(3, name = 'q2')
# Ancillas for bit-flip errors
bf0 = AncillaRegister(2, name = 'bf0')
bf1 = AncillaRegister(2, name = 'bf1')
bf2 = AncillaRegister(2, name = 'bf2')
# Ancillas for phase-flip errors
pf = AncillaRegister(2, name = 'pf')
circuit = QuantumCircuit(q0, bf0, q1, bf1, q2, bf2, pf)
# Define our initial normalized state
initial_state = normalize_state(1.0 + 1.0j, 2.0 + 0.0j)
circuit.initialize(initial_state, 0)
# Draws the circuit
# circuit.draw(output = 'mpl', plot_barriers = False)
# Add controlled-NOTNOT to qubits 0, 3 and 6
circuit.append(cnotnot(), [q0[0], q1[0], q2[0]])
# Add Hadamard gates to qubits 0, 3 and 6
circuit.h(q0[0])
circuit.h(q1[0])
circuit.h(q2[0])
# Add controlled-NOTNOT in our three packs of three qubits
circuit.append(cnotnot(), [q0[0], q0[1], q0[2]])
circuit.append(cnotnot(), [q1[0], q1[1], q1[2]])
circuit.append(cnotnot(), [q2[0], q2[1], q2[2]])
circuit.barrier(q0, bf0, q1, bf1, q2, bf2, pf)
circuit.draw(output = 'mpl', plot_barriers = False)
_ = get_state(circuit, fancy_print = True)
# Add a source of random noise in our channels
circuit.append(random_noise(reveal_error = True),
[q0[0], q0[1], q0[2],
q1[0], q1[1], q1[2],
q2[0], q2[1], q2[2]])
circuit.barrier(q0, bf0, q1, bf1, q2, bf2, pf)
circuit.draw(output = 'mpl', plot_barriers = False)
_ = get_state(circuit, fancy_print = True)
# Add Hadamard gates for the bit-flip ancillas
for index in range(2):
circuit.h(bf0[index])
circuit.h(bf1[index])
circuit.h(bf2[index])
# Add controlled-ZZ gates in our ancillas
# First pack of three qubits
circuit.append(czz(), [bf0[0], q0[0], q0[1]])
circuit.append(czz(), [bf0[1], q0[1], q0[2]])
# Second pack of three qubits
circuit.append(czz(), [bf1[0], q1[0], q1[1]])
circuit.append(czz(), [bf1[1], q1[1], q1[2]])
# Third pack of three qubits
circuit.append(czz(), [bf2[0], q2[0], q2[1]])
circuit.append(czz(), [bf2[1], q2[1], q2[2]])
circuit.barrier(q0, bf0, q1, bf1, q2, bf2, pf)
# Add Hadamard gates for the bit-flip ancillas
for index in range(2):
circuit.h(bf0[index])
circuit.h(bf1[index])
circuit.h(bf2[index])
# Add double controlled gates to correct bit-flip errors
# First pack of three qubits
circuit.append(invccnot(), [bf0[1], bf0[0], q0[0]])
circuit.ccx(bf0[0], bf0[1], q0[1])
circuit.append(invccnot(), [bf0[0], bf0[1], q0[2]])
# Second pack of three qubits
circuit.append(invccnot(), [bf1[1], bf1[0], q1[0]])
circuit.ccx(bf1[0], bf1[1], q1[1])
circuit.append(invccnot(), [bf1[0], bf1[1], q1[2]])
# Third pack of three qubits
circuit.append(invccnot(), [bf2[1], bf2[0], q2[0]])
circuit.ccx(bf2[0], bf2[1], q2[1])
circuit.append(invccnot(), [bf2[0], bf2[1], q2[2]])
circuit.barrier(q0, bf0, q1, bf1, q2, bf2, pf)
# BIT-FLIP ERRORS SOLVED! Let's go with the phase-flip errors
circuit.draw(output = 'mpl', plot_barriers = False)
_ = get_state(circuit, fancy_print = True)
# Add Hadamard gates for the phase-flip ancillas
for index in range(2):
circuit.h(pf[index])
# Add controlled-6X gates in our ancillas
circuit.append(c6x(), [pf[0], q0[0], q0[1], q0[2], q1[0], q1[1], q1[2]])
circuit.append(c6x(), [pf[1], q1[0], q1[1], q1[2], q2[0], q2[1], q2[2]])
# Add Hadamard gates for the phase-flip ancillas
for index in range(2):
circuit.h(pf[index])
# Add double controlled gates to correct phase-flip errors
circuit.append(invccz(), [pf[1], pf[0], q0[0]])
circuit.append(ccz(), [pf[1], pf[0], q1[0]])
circuit.append(invccz(), [pf[0], pf[1], q2[0]])
circuit.barrier(q0, bf0, q1, bf1, q2, bf2, pf)
# PHASE-FLIP ERRORS SOLVED! Let's go for the final manipulations in our state
circuit.draw(output = 'mpl', plot_barriers = False, fold = 40)
_ = get_state(circuit, fancy_print = True)
# Add controlled-NOTNOT in our three packs of three qubits
circuit.append(cnotnot(), [q0[0], q0[1], q0[2]])
circuit.append(cnotnot(), [q1[0], q1[1], q1[2]])
circuit.append(cnotnot(), [q2[0], q2[1], q2[2]])
# Add Hadamard gates to qubits 0, 3 and 6
circuit.h(q0[0])
circuit.h(q1[0])
circuit.h(q2[0])
# Add controlled-NOTNOT to qubits 0, 3 and 6
circuit.append(cnotnot(), [q0[0], q1[0], q2[0]])
circuit.draw(output = 'mpl', plot_barriers = False, fold = 40)
# Get the state vector
final_state = get_state(circuit, fancy_print = True)
check_error_to_ancilla(final_state)
# print(circuit.draw(output = 'latex_source', filename = '/tmp/circuit.tex'))
import qiskit.tools.jupyter
%qiskit_version_table
|
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.
"""Non-string identifiers for circuit and record identifiers test"""
import unittest
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit.exceptions import CircuitError
from qiskit.test import QiskitTestCase
class TestAnonymousIds(QiskitTestCase):
"""Test the anonymous use of registers."""
def test_create_anonymous_classical_register(self):
"""ClassicalRegister with no name."""
cr = ClassicalRegister(size=3)
self.assertIsInstance(cr, ClassicalRegister)
def test_create_anonymous_quantum_register(self):
"""QuantumRegister with no name."""
qr = QuantumRegister(size=3)
self.assertIsInstance(qr, QuantumRegister)
def test_create_anonymous_classical_registers(self):
"""Several ClassicalRegister with no name."""
cr1 = ClassicalRegister(size=3)
cr2 = ClassicalRegister(size=3)
self.assertNotEqual(cr1.name, cr2.name)
def test_create_anonymous_quantum_registers(self):
"""Several QuantumRegister with no name."""
qr1 = QuantumRegister(size=3)
qr2 = QuantumRegister(size=3)
self.assertNotEqual(qr1.name, qr2.name)
def test_create_anonymous_mixed_registers(self):
"""Several Registers with no name."""
cr0 = ClassicalRegister(size=3)
qr0 = QuantumRegister(size=3)
# Get the current index count of the registers
cr_index = int(cr0.name[1:])
qr_index = int(qr0.name[1:])
cr1 = ClassicalRegister(size=3)
_ = QuantumRegister(size=3)
qr2 = QuantumRegister(size=3)
# Check that the counters for each kind are incremented separately.
cr_current = int(cr1.name[1:])
qr_current = int(qr2.name[1:])
self.assertEqual(cr_current, cr_index + 1)
self.assertEqual(qr_current, qr_index + 2)
def test_create_circuit_noname(self):
"""Create_circuit with no name."""
qr = QuantumRegister(size=3)
cr = ClassicalRegister(size=3)
qc = QuantumCircuit(qr, cr)
self.assertIsInstance(qc, QuantumCircuit)
class TestInvalidIds(QiskitTestCase):
"""Circuits and records with invalid IDs"""
def test_invalid_type_circuit_name(self):
"""QuantumCircuit() with invalid type name."""
qr = QuantumRegister(size=3)
cr = ClassicalRegister(size=3)
self.assertRaises(CircuitError, QuantumCircuit, qr, cr, name=1)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
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/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import matplotlib.pyplot as plotter
import numpy as np
from IPython.display import display, Math, Latex
%matplotlib inline
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(2) # we will need seperates registers for using 'c_if' later.
qc = QuantumCircuit(qr,crz,crx)
qc.x(0)
qc.h(0) # 'psi' can't be unknown to us as we are creating it here. Let us take '-' state as our 'psi'
# We will verify later if the '-' is been teleported.
qc.h(1)
qc.cx(1,2) # creating a bell state
qc.barrier() # Use barrier to separate steps, everything till this barrier is just intialisation.
qc.cx(0,1) # '0' and '1' are with Alice and '2' is with Bob.
# psi_1 prepared.
qc.h(0)
# psi_2 prepared.
qc.barrier()
qc.measure(0,0)
qc.measure(1,1)
qc.draw (output = 'mpl')
qc.x(2).c_if(crx,1) # 'c_if' compares a classical register with a value (either 0 or 1) and performs the
qc.z(2).c_if(crz,1) # operation if they are equal.
qc.draw('mpl')
# be careful of the order of applying X and Z!
qc.h(2)
qc.measure(2,crx[1])
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 10000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc)
print(counts)
plot_histogram(counts)
# the output should be '1xx' if the teleportation is successful.
# Refer to above cell for a detailed explanation of the strategy.
qc1 = QuantumCircuit(2, 2)
# Preparing Alice's Bell state: \beta_{00}
qc1.h(0)
qc1.cx(0, 1)
# Skyler's mischief:
# Suppose for this example that she applied Pauli-Y.
# You can change 'y' to 'x' or 'z' in the following line for other cases.
qc1.y(0)
# Alice's strategy:
qc1.cx(0, 1)
qc1.h(0)
qc1.measure(0, 0)
qc1.measure(1, 1)
qc1.draw('mpl')
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 10000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc1)
print(counts)
if '10' in counts:
print('Skyler used Pauli-X!')
if '11' in counts:
print('Skyler used Pauli-Y!')
if '01' in counts:
print('Skyler used Pauli-Z!')
plot_histogram(counts)
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
HHL Benchmark Program - QSim
"""
import sys
import time
import numpy as np
pi = np.pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute
import sparse_Ham_sim as shs
import uniform_controlled_rotation as ucr
from qiskit.circuit.library import QFT
# include QFT in this list, so we can refer to the QFT sub-circuit definition
#sys.path[1:1] = ["_common", "_common/qiskit", "quantum-fourier-transform/qiskit"]
#sys.path[1:1] = ["../../_common", "../../_common/qiskit", "../../quantum-fourier-transform/qiskit"]
# cannot use the QFT common yet, as HHL seems to use reverse bit order
sys.path[1:1] = ["_common", "_common/qsim", "quantum-fourier-transform/qsim"]
sys.path[1:1] = ["../../_common", "../../_common/qsim", "../../quantum-fourier-transform/qsim"]
#from qft_benchmark import qft_gate, inv_qft_gate
import execute as ex
import metrics as metrics
# Benchmark Name
benchmark_name = "HHL"
np.random.seed(0)
verbose = False
# Variable for number of resets to perform after mid circuit measurements
num_resets = 1
# saved circuits for display
QC_ = None
U_ = None
UI_ = None
QFT_ = None
QFTI_ = None
HP_ = None
INVROT_ = None
############### Circuit Definitions
''' replaced with code below ...
def qft_dagger(qc, clock, n):
qc.h(clock[1]);
for j in reversed(range(n)):
for k in reversed(range(j+1,n)):
qc.cu1(-np.pi/float(2**(k-j)), clock[k], clock[j]);
qc.h(clock[0]);
def qft(qc, clock, n):
qc.h(clock[0]);
for j in reversed(range(n)):
for k in reversed(range(j+1,n)):
qc.cu1(np.pi/float(2**(k-j)), clock[k], clock[j]);
qc.h(clock[1]);
'''
'''
DEVNOTE: the QFT and IQFT are defined here as they are in the QFT benchmark - almost;
Here, the sign of the angles is reversed and the QFT is actually used as the inverse QFT.
This is an inconsistency that needs to be resolved later.
The QPE part of the algorithm should be using the inverse QFT, but the qubit order is not correct.
The QFT as defined in the QFT benchmark operates on qubits in the opposite order from the HHL pattern.
'''
def initialize_state(qc, qreg, b):
""" b (int): initial basis state |b> """
n = qreg.size
b_bin = np.binary_repr(b, width=n)
if verbose:
print(f"... initializing |b> to {b}, binary repr = {b_bin}")
for q in range(n):
if b_bin[n-1-q] == '1':
qc.x(qreg[q])
return qc
def IQFT(qc, qreg):
""" inverse QFT
qc : QuantumCircuit
qreg : QuantumRegister belonging to qc
does not include SWAP at end of the circuit
"""
n = int(qreg.size)
for i in reversed(range(n)):
for j in range(i+1,n):
phase = -pi/2**(j-i)
qc.cp(phase, qreg[i], qreg[j])
qc.h(qreg[i])
return qc
def QFT(qc, qreg):
""" QFT
qc : QuantumCircuit
qreg : QuantumRegister belonging to qc
does not include SWAP at end of circuit
"""
n = int(qreg.size)
for i in range(n):
qc.h(qreg[i])
for j in reversed(range(i+1,n)):
phase = pi/2**(j-i)
qc.cp(phase, qreg[i], qreg[j])
return qc
def inv_qft_gate(input_size, method=1):
#def qft_gate(input_size):
#global QFT_
qr = QuantumRegister(input_size);
#qc = QuantumCircuit(qr, name="qft")
qc = QuantumCircuit(qr, name="IQFT")
if method == 1:
# Generate multiple groups of diminishing angle CRZs and H gate
for i_qubit in range(0, input_size):
# start laying out gates from highest order qubit (the hidx)
hidx = input_size - i_qubit - 1
# if not the highest order qubit, add multiple controlled RZs of decreasing angle
if hidx < input_size - 1:
num_crzs = i_qubit
for j in range(0, num_crzs):
divisor = 2 ** (num_crzs - j)
#qc.crz( math.pi / divisor , qr[hidx], qr[input_size - j - 1])
##qc.crz( -np.pi / divisor , qr[hidx], qr[input_size - j - 1])
qc.cp(-np.pi / divisor, qr[hidx], qr[input_size - j - 1]);
# followed by an H gate (applied to all qubits)
qc.h(qr[hidx])
elif method == 2:
# apply IQFT to register
for i in range(input_size)[::-1]:
for j in range(i+1,input_size):
phase = -np.pi/2**(j-i)
qc.cp(phase, qr[i], qr[j])
qc.h(qr[i])
qc.barrier()
return qc
############### Inverse QFT Circuit
def qft_gate(input_size, method=1):
#def inv_qft_gate(input_size):
#global QFTI_
qr = QuantumRegister(input_size);
#qc = QuantumCircuit(qr, name="inv_qft")
qc = QuantumCircuit(qr, name="QFT")
if method == 1:
# Generate multiple groups of diminishing angle CRZs and H gate
for i_qubit in reversed(range(0, input_size)):
# start laying out gates from highest order qubit (the hidx)
hidx = input_size - i_qubit - 1
# precede with an H gate (applied to all qubits)
qc.h(qr[hidx])
# if not the highest order qubit, add multiple controlled RZs of decreasing angle
if hidx < input_size - 1:
num_crzs = i_qubit
for j in reversed(range(0, num_crzs)):
divisor = 2 ** (num_crzs - j)
#qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1])
##qc.crz( np.pi / divisor , qr[hidx], qr[input_size - j - 1])
qc.cp( np.pi / divisor , qr[hidx], qr[input_size - j - 1])
elif method == 2:
# apply QFT to register
for i in range(input_size):
qc.h(qr[i])
for j in range(i+1, input_size):
phase = np.pi/2**(j-i)
qc.cp(phase, qr[i], qr[j])
qc.barrier()
return qc
############# Controlled U Gate
#Construct the U gates for A
def ctrl_u(exponent):
qc = QuantumCircuit(1, name=f"U^{exponent}")
for i in range(exponent):
#qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target);
#qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target);
qc.u(np.pi/2, -np.pi/2, np.pi/2, 0);
cu_gate = qc.to_gate().control(1)
return cu_gate, qc
#Construct the U^-1 gates for reversing A
def ctrl_ui(exponent):
qc = QuantumCircuit(1, name=f"U^-{exponent}")
for i in range(exponent):
#qc.u(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, target);
#qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, control, target);
qc.u(np.pi/2, np.pi/2, -np.pi/2, 0);
cu_gate = qc.to_gate().control(1)
return cu_gate, qc
####### DEVNOTE: The following functions (up until the make_circuit) are from the first inccarnation
# of this benchmark and are not used here. Should be removed, but kept here for reference for now
############# Quantum Phase Estimation
# DEVNOTE: The QPE and IQPE methods below mirror the mechanism in Hector_Wong
# Need to investigate whether the clock qubits are in the correct, as this implementation
# seems to require the QFT be implemented in reverse also. TODO
# Append a series of Quantum Phase Estimation gates to the circuit
def qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1):
qc.barrier()
''' original code from Hector_Wong
# e^{i*A*t}
#qc.cu(np.pi/2, -np.pi/2, np.pi/2, 3*np.pi/4, clock[0], target, label='U');
# The CU gate is equivalent to a CU1 on the control bit followed by a CU3
qc.u1(3*np.pi/4, clock[0]);
qc.cu3(np.pi/2, -np.pi/2, np.pi/2, clock[0], target);
# e^{i*A*t*2}
#qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2');
qc.cu3(np.pi, np.pi, 0, clock[1], target);
qc.barrier();
'''
# apply series of controlled U operations to the state |1>
# does nothing to state |0>
# DEVNOTE: have not found a way to create a controlled operation that contains a U gate
# with the global phase; instead do it piecemeal for now
if method == 1:
repeat = 1
#for j in reversed(range(len(clock))):
for j in (range(len(clock))):
# create U with exponent of 1, but in a loop repeating N times
for k in range(repeat):
# this global phase is applied to clock qubit
qc.u1(3*np.pi/4, clock[j]);
# apply the rest of U controlled by clock qubit
#cp, _ = ctrl_u(repeat)
cp, _ = ctrl_u(1)
qc.append(cp, [clock[j], target])
repeat *= 2
qc.barrier();
#Define global U operator as the phase operator (for printing later)
_, U_ = ctrl_u(1)
if method == 2:
for j in range(len(clock)):
control = clock[j]
phase = -(2*np.pi)*2**j
con_H_sim = shs.control_Ham_sim(A, phase)
qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]]
qc.append(con_H_sim, qubits)
# Perform an inverse QFT on the register holding the eigenvalues
qc.append(inv_qft_gate(len(clock), method), clock)
# Append a series of Inverse Quantum Phase Estimation gates to the circuit
def inv_qpe(qc, clock, target, extra_qubits=None, ancilla=None, A=None, method=1):
# Perform a QFT on the register holding the eigenvalues
qc.append(qft_gate(len(clock), method), clock)
qc.barrier()
if method == 1:
''' original code from Hector_Wong
# e^{i*A*t*2}
#qc.cu(np.pi, np.pi, 0, 0, clock[1], target, label='U2');
qc.cu3(np.pi, np.pi, 0, clock[1], target);
# e^{i*A*t}
#qc.cu(np.pi/2, np.pi/2, -np.pi/2, -3*np.pi/4, clock[0], target, label='U');
# The CU gate is equivalent to a CU1 on the control bit followed by a CU3
qc.u1(-3*np.pi/4, clock[0]);
qc.cu3(np.pi/2, np.pi/2, -np.pi/2, clock[0], target);
qc.barrier()
'''
# apply inverse series of controlled U operations to the state |1>
# does nothing to state |0>
# DEVNOTE: have not found a way to create a controlled operation that contains a U gate
# with the global phase; instead do it piecemeal for now
repeat = 2 ** (len(clock) - 1)
for j in reversed(range(len(clock))):
#for j in (range(len(clock))):
# create U with exponent of 1, but in a loop repeating N times
for k in range(repeat):
# this global phase is applied to clock qubit
qc.u1(-3*np.pi/4, clock[j]);
# apply the rest of U controlled by clock qubit
#cp, _ = ctrl_u(repeat)
cp, _ = ctrl_ui(1)
qc.append(cp, [clock[j], target])
repeat = int(repeat / 2)
qc.barrier();
#Define global U operator as the phase operator (for printing later)
_, UI_ = ctrl_ui(1)
if method == 2:
for j in reversed(range(len(clock))):
control = clock[j]
phase = (2*np.pi)*2**j
con_H_sim = shs.control_Ham_sim(A, phase)
qubits = [control] + [q for q in target] + [q for q in extra_qubits] + [ancilla[0]]
qc.append(con_H_sim, qubits)
############### Make HHL Circuit
# Make the HHL circuit
def make_circuit(A, b, num_clock_qubits):
""" Generate top-level circuit for HHL algo A|x>=|b>
A : sparse Hermitian matrix
b (int): between 0,...,2^n-1. Initial basis state |b>
"""
# save smaller circuit example for display
global QC_, U_, UI_, QFT_, QFTI_, HP_, INVROT_
# read in number of qubits
N = len(A)
n = int(np.log2(N))
n_t = num_clock_qubits # number of qubits in clock register
num_qubits = 2*n + n_t + 1
# lower bound on eigenvalues of A. Fixed for now
C = 1/4
''' Define sets of qubits for this algorithm '''
# create 'input' quantum and classical measurement register
qr = QuantumRegister(n, name='input')
qr_b = QuantumRegister(n, name='in_anc') # ancillas for Hamiltonian simulation (?)
cr = ClassicalRegister(n)
# create 'clock' quantum register
qr_t = QuantumRegister(n_t, name='clock') # for phase estimation
# create 'ancilla' quantum and classical measurement register
qr_a = QuantumRegister(1, name='ancilla') # ancilla qubit
cr_a = ClassicalRegister(1)
# create the top-level HHL circuit, with all the registers
qc = QuantumCircuit(qr, qr_b, qr_t, qr_a, cr, cr_a, name=f"hhl-{num_qubits}-{b}")
''' Initialize the input and clock qubits '''
# initialize the |b> state - the 'input'
qc = initialize_state(qc, qr, b)
#qc.barrier()
# Hadamard the phase estimation register - the 'clock'
for q in range(n_t):
qc.h(qr_t[q])
qc.barrier()
''' Perform Quantum Phase Estimation on input (b), clock, and ancilla '''
# perform controlled e^(i*A*t)
for q in range(n_t):
control = qr_t[q]
anc = qr_a[0]
phase = -(2*pi)*2**q
qc_u = shs.control_Ham_sim(n, A, phase)
if phase <= 0:
qc_u.name = "e^{" + str(q) + "iAt}"
else:
qc_u.name = "e^{-" + str(q) + "iAt}"
if U_ == None:
U_ = qc_u
qc.append(qc_u, qr[0:len(qr)] + qr_b[0:len(qr_b)] + [control] + [anc])
qc.barrier()
''' Perform Inverse Quantum Fourier Transform on clock qubits '''
#qc = IQFT(qc, qr_t)
qc_qfti = inv_qft_gate(n_t, method=2)
qc.append(qc_qfti, qr_t)
if QFTI_ == None:
QFTI_ = qc_qfti
qc.barrier()
''' Perform inverse rotation with ancilla '''
# reset ancilla
qc.reset(qr_a[0])
# compute angles for inversion rotations
alpha = [2*np.arcsin(C)]
for x in range(1,2**n_t):
x_bin_rev = np.binary_repr(x, width=n_t)[::-1]
lam = int(x_bin_rev,2)/(2**n_t)
if lam < C:
alpha.append(0)
elif lam >= C:
alpha.append(2*np.arcsin(C/lam))
theta = ucr.alpha2theta(alpha)
# do inversion step
qc_invrot = ucr.uniformly_controlled_rot(n_t, theta)
qc.append(qc_invrot, qr_t[0:len(qr_t)] + [qr_a[0]])
if INVROT_ == None:
INVROT_ = qc_invrot
# and measure ancilla
qc.measure(qr_a[0], cr_a[0], basis = "Ensemble", add_param = "Z")
qc.reset(qr_a[0])
qc.barrier()
''' Perform Quantum Fourier Transform on clock qubits '''
#qc = QFT(qc, qr_t)
qc_qft = qft_gate(n_t, method=2)
qc.append(qc_qft, qr_t)
if QFT_ == None:
QFT_ = qc_qft
qc.barrier()
''' Perform Inverse Quantum Phase Estimation on input (b), clock, and ancilla '''
# uncompute phase estimation
# perform controlled e^(-i*A*t)
for q in reversed(range(n_t)):
control = qr_t[q]
phase = (2*pi)*2**q
qc_ui = shs.control_Ham_sim(n, A, phase)
if phase <= 0:
qc_ui.name = "e^{" + str(q) + "iAt}"
else:
qc_ui.name = "e^{-" + str(q) + "iAt}"
if UI_ == None:
UI_ = qc_ui
qc.append(qc_ui, qr[0:len(qr)] + qr_b[0:len(qr_b)] + [control] + [anc])
qc.barrier()
# Hadamard (again) the phase estimation register - the 'clock'
for q in range(n_t):
qc.h(qr_t[q])
qc.barrier()
''' Perform final measurements '''
# measure ancilla and main register
qc.measure(qr[0:], cr[0:], basis = "Ensemble", add_param = "Z")
if QC_ == None:
QC_ = qc
#print(f"... made circuit = \n{QC_}")
return qc
############### Result Data Analysis
saved_result = None
# Compute the expected distribution, given the matrix A and input value b
def true_distr(A, b=0):
N = len(A)
n = int(np.log2(N))
b_vec = np.zeros(N); b_vec[b] = 1.0
#b = np.array([1,1])/np.sqrt(2)
x = np.linalg.inv(A) @ b_vec
# normalize x
x_n = x/np.linalg.norm(x)
probs = np.array([np.abs(xj)**2 for xj in x_n])
distr = {}
for j, prob in enumerate(probs):
if prob > 1e-8:
j_bin = np.binary_repr(j, width=n)
distr[j_bin] = prob
distr = {out:distr[out]/sum(distr.values()) for out in distr}
return distr
# post-select counts where ancilla was measured as |1>
def postselect(outcomes, return_probs=True):
mar_out = {}
for b_str in outcomes:
if b_str[0] == '1':
counts = outcomes[b_str]
mar_out[b_str[2:]] = counts
# print(f"mar_out[b_str[2:]] ===== {mar_out[b_str[2:]]}")
# compute postselection rate
ps_shots = sum(mar_out.values())
# print(f"ps_shots ===== {ps_shots}")
shots = sum(outcomes.values())
rate = ps_shots/shots
# convert to probability distribution
if return_probs == True:
mar_out = {b_str:round(mar_out[b_str]/ps_shots, 4) for b_str in mar_out}
return mar_out, rate
# Analyze the quality of the result obtained from executing circuit qc
def analyze_and_print_result (qc, result, num_qubits, s_int, num_shots):
global saved_result
saved_result = result
# obtain counts from the result object
counts = result.get_counts(qc)
# print(f"counts ===== {counts}")
if verbose:
print(f"... for circuit = {num_qubits} {s_int}, counts = {counts}")
# post-select counts where ancilla was measured as |1>
post_counts, rate = postselect(counts)
# print(f"post_counts ===== {post_counts}")
num_input_qubits = len(list(post_counts.keys())[0])
if verbose:
print(f'... ratio of counts with ancilla measured |1> : {round(rate, 4)}')
# compute true distribution from secret int
off_diag_index = 0
b = 0
# remove instance index from s_int
s_int = s_int - 1000 * int(s_int/1000)
# get off_diag_index and b
s_int_o = int(s_int)
s_int_b = int(s_int)
while (s_int_o % 2) == 0:
s_int_o = int(s_int_o/2)
off_diag_index += 1
while (s_int_b % 3) == 0:
s_int_b = int(s_int_b/3)
b += 1
if verbose:
print(f"... rem(s_int) = {s_int}, b = {b}, odi = {off_diag_index}")
# temporarily fix diag and off-diag matrix elements
diag_el = 0.5
off_diag_el = -0.25
A = shs.generate_sparse_H(num_input_qubits, off_diag_index,
diag_el=diag_el, off_diag_el=off_diag_el)
ideal_distr = true_distr(A, b)
# # compute total variation distance
# tvd = TVD(ideal_distr, post_counts)
# # use TVD as infidelity
# fidelity = 1 - tvd
# #fidelity = metrics.polarization_fidelity(post_counts, ideal_distr)
fidelity = metrics.polarization_fidelity(post_counts, ideal_distr)
# print(f"fidelity ===== {fidelity}")
return post_counts, fidelity
################ Benchmark Loop
# Execute program with default parameters (based on min and max_qubits)
# This routine computes a reasonable min and max input and clock qubit range to sweep
# from the given min and max qubit sizes using the formula below and making the
# assumption that num_input_qubits ~= num_clock_qubits and num_input_qubits < num_clock_qubits:
# num_qubits = 2 * num_input_qubits + num_clock_qubits + 1 (the ancilla)
def run (min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=100,
method = 1, use_best_widths=True,
backend_id='dm_simulator', provider_backend=None,
#hub="ibm-q", group="open", project="main",
exec_options=None,
context=None):
# we must have at least 4 qubits and min must be less than max
max_qubits = max(4, max_qubits)
min_qubits = min(max(4, min_qubits), max_qubits)
skip_qubits = max(1, skip_qubits)
#print(f"... using min_qubits = {min_qubits} and max_qubits = {max_qubits}")
# create context identifier
if context is None: context = f"{benchmark_name} Benchmark"
''' first attempt ..
min_input_qubits = min_qubits//2
if min_qubits%2 == 1:
min_clock_qubits = min_qubits//2 + 1
else:
min_clock_qubits = min_qubits//2
max_input_qubits = max_qubits//2
if max_qubits%2 == 1:
max_clock_qubits = max_qubits//2 + 1
else:
max_clock_qubits = max_qubits//2
'''
# the calculation below is based on the formula described above, where I = input, C = clock:
# I = int((N - 1) / 3)
min_input_qubits = int((min_qubits - 1) / 3)
max_input_qubits = int((max_qubits - 1) / 3)
# C = N - 1 - 2 * I
min_clock_qubits = min_qubits - 1 - 2 * min_input_qubits
max_clock_qubits = max_qubits - 1 - 2 * max_input_qubits
#print(f"... input, clock qubit width range: {min_input_qubits} : {max_input_qubits}, {min_clock_qubits} : {max_clock_qubits}")
return run2(min_input_qubits=min_input_qubits,max_input_qubits= max_input_qubits,
min_clock_qubits=min_clock_qubits, max_clock_qubits=max_clock_qubits,
skip_qubits=skip_qubits,
max_circuits=max_circuits, num_shots=num_shots,
method=method, use_best_widths=use_best_widths,
backend_id=backend_id, provider_backend=provider_backend,
# hub=hub, group=group, project=project,
exec_options=exec_options,
context=context)
# Execute program with default parameters and permitting the user to specify an
# arbitrary range of input and clock qubit widths
# The benchmark sweeps over all input widths and clock widths in the range specified
def run2 (min_input_qubits=1, max_input_qubits=5, skip_qubits=1,
min_clock_qubits=1, max_clock_qubits=5,
max_circuits=3, num_shots=100,
method=2, use_best_widths=False,
backend_id='dm_simulator', provider_backend=None,
# hub="ibm-q", group="open", project="main",
exec_options=None,
context=None):
print(f"{benchmark_name} Benchmark Program - Qiskit")
# ensure valid input an clock qubit widths
min_input_qubits = min(max(1, min_input_qubits), max_input_qubits)
max_input_qubits = max(min_input_qubits, max_input_qubits)
min_clock_qubits = min(max(1, min_clock_qubits), max_clock_qubits)
max_clock_qubits = max(min_clock_qubits, max_clock_qubits)
#print(f"... in, clock: {min_input_qubits}, {max_input_qubits}, {min_clock_qubits}, {max_clock_qubits}")
# initialize saved circuits for display
global QC_, U_, UI_, QFT_, QFTI_, HP_, INVROT_
QC_ = None
U_ = None
UI_ = None
QFT_ = None
QFTI_ = None
HP_ = None
INVROT_ = None
##########
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler
def execution_handler(qc, result, num_qubits, s_int, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
#counts, fidelity = analyze_and_print_result(qc, result, num_qubits, ideal_distr)
counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(s_int), num_shots)
metrics.store_metric(num_qubits, s_int, 'fidelity', fidelity)
# Variable for new qubit group ordering if using mid_circuit measurements
mid_circuit_qubit_group = []
# If using mid_circuit measurements, set transform qubit group to true
transform_qubit_group = False
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
# hub=hub, group=group, project=project,
exec_options=exec_options,
context=context)
# for noiseless simulation, set noise model to be None
#ex.set_noise_model(None)
# temporarily fix diag and off-diag matrix elements
diag_el = 0.5
off_diag_el = -0.25
##########
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
#for num_input_qubits in range(min_input_qubits, max_input_qubits+1):
for num_input_qubits in range(min_input_qubits, max_input_qubits + 1, skip_qubits):
N = 2**num_input_qubits # matrix size
for num_clock_qubits in range(min_clock_qubits, max_clock_qubits+1, skip_qubits):
num_qubits = 2*num_input_qubits + num_clock_qubits + 1
# determine number of circuits to execute for this group
num_circuits = max_circuits
# if flagged to use best input and clock for specific num_qubits, check against formula
if use_best_widths:
if num_input_qubits != int((num_qubits - 1) / 3) or num_clock_qubits != (num_qubits - 1 - 2 * num_input_qubits):
if verbose:
print(f"... SKIPPING {num_circuits} circuits with {num_qubits} qubits, using {num_input_qubits} input qubits and {num_clock_qubits} clock qubits")
continue
print(f"************\nExecuting {num_circuits} circuits with {num_qubits} qubits, using {num_input_qubits} input qubits and {num_clock_qubits} clock qubits")
# loop over randomly generated problem instances
for i in range(num_circuits):
# generate a non-zero value < N
#b = np.random.choice(range(N)) # orig code, gens 0 sometimes
b = np.random.choice(range(1, N))
# and a non-zero index
off_diag_index = np.random.choice(range(1, N))
# define secret_int (include 'i' since b and off_diag_index don't need to be unique)
s_int = 1000 * (i+1) + (2**off_diag_index)*(3**b)
#s_int = (2**off_diag_index)*(3**b)
if verbose:
print(f"... create A for b = {b}, off_diag_index = {off_diag_index}, s_int = {s_int}")
A = shs.generate_sparse_H(num_input_qubits, off_diag_index,
diag_el=diag_el, off_diag_el=off_diag_el)
# create the circuit for given qubit size and secret string, store time metric
ts = time.time()
qc = make_circuit(A, b, num_clock_qubits)
metrics.store_metric(num_qubits, s_int, 'create_time', time.time()-ts)
#print(qc)
# submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc, num_qubits, s_int, shots=num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
#if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!")
print("\nU Circuit ="); print(U_ if U_ != None else " ... too large!")
print("\nU^-1 Circuit ="); print(UI_ if UI_ != None else " ... too large!")
print("\nQFT Circuit ="); print(QFT_ if QFT_ != None else " ... too large!")
print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!")
print("\nHamiltonian Phase Estimation Circuit ="); print(HP_ if HP_ != None else " ... too large!")
print("\nControlled Rotation Circuit ="); print(INVROT_ if INVROT_ != None else " ... too large!")
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim",
transform_qubit_group = transform_qubit_group, new_qubit_group = mid_circuit_qubit_group)
# if main, execute method
if __name__ == '__main__': run()
|
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.
"""Test CZ circuits synthesis functions."""
import unittest
from test import combine
import numpy as np
from ddt import ddt
from qiskit import QuantumCircuit
from qiskit.circuit.library import Permutation
from qiskit.synthesis.linear_phase import synth_cz_depth_line_mr
from qiskit.synthesis.linear.linear_circuits_utils import check_lnn_connectivity
from qiskit.quantum_info import Clifford
from qiskit.test import QiskitTestCase
@ddt
class TestCZSynth(QiskitTestCase):
"""Test the linear reversible circuit synthesis functions."""
@combine(num_qubits=[3, 4, 5, 6, 7])
def test_cz_synth_lnn(self, num_qubits):
"""Test the CZ synthesis code for linear nearest neighbour connectivity."""
seed = 1234
rng = np.random.default_rng(seed)
num_gates = 10
num_trials = 5
for _ in range(num_trials):
mat = np.zeros((num_qubits, num_qubits))
qctest = QuantumCircuit(num_qubits)
# Generate a random CZ circuit
for _ in range(num_gates):
i = rng.integers(num_qubits)
j = rng.integers(num_qubits)
if i != j:
qctest.cz(i, j)
if j > i:
mat[i][j] = (mat[i][j] + 1) % 2
else:
mat[j][i] = (mat[j][i] + 1) % 2
qc = synth_cz_depth_line_mr(mat)
# Check that the output circuit 2-qubit depth equals to 2*n+2
depth2q = qc.depth(filter_function=lambda x: x.operation.num_qubits == 2)
self.assertTrue(depth2q == 2 * num_qubits + 2)
# Check that the output circuit has LNN connectivity
self.assertTrue(check_lnn_connectivity(qc))
# Assert that we get the same element, up to reverse order of qubits
perm = Permutation(num_qubits=num_qubits, pattern=range(num_qubits)[::-1])
qctest = qctest.compose(perm)
self.assertEqual(Clifford(qc), Clifford(qctest))
if __name__ == "__main__":
unittest.main()
|
https://github.com/OJB-Quantum/Qiskit-Metal-to-Litho
|
OJB-Quantum
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from qiskit_metal import draw, Dict
from qiskit_metal.toolbox_metal import math_and_overrides
from qiskit_metal.qlibrary.core import QComponent
dir(QComponent)
class MyQComponent(QComponent):
"""
Use this class as a template for your components - have fun
Description:
Options:
"""
# Edit these to define your own tempate options for creation
# Default drawing options
default_options = Dict(width='500um',
height='300um',
pos_x='0um',
pos_y='0um',
orientation='0',
layer='1')
"""Default drawing options"""
# Name prefix of component, if user doesn't provide name
component_metadata = Dict(short_name='component',
_qgeometry_table_poly='True')
"""Component metadata"""
def make(self):
"""Convert self.options into QGeometry."""
p = self.parse_options() # Parse the string options into numbers
# EDIT HERE - Replace the following with your code
# Create some raw geometry
# Use autocompletion for the `draw.` module (use tab key)
rect = draw.rectangle(p.width, p.height, p.pos_x, p.pos_y)
rect = draw.rotate(rect, p.orientation)
rect = draw.translate(rect,p.pos_x,p.pos_y)
geom = {'my_polygon': rect}
self.add_qgeometry('poly', geom, layer=p.layer, subtract=False)
draw.rectangle(1,2,0,0)
draw.rotate(draw.rectangle(1,2,0,0), 45)
face = draw.shapely.geometry.Point(0, 0).buffer(1)
eye = draw.shapely.geometry.Point(0, 0).buffer(0.2)
eye_l = draw.translate(eye, -0.4, 0.4)
eye_r = draw.translate(eye, 0.4, 0.4)
smile = draw.shapely.geometry.Point(0, 0).buffer(0.8)
cut_sq = draw.shapely.geometry.box(-1, -0.3, 1, 1)
smile = draw.subtract(smile, cut_sq)
face = draw.subtract(face, smile)
face = draw.subtract(face, eye_r)
face = draw.subtract(face, eye_l)
face
import qiskit_metal as metal
?metal.qlibrary.core.QComponent.add_qgeometry
?metal.qlibrary.core.QComponent.add_pin
from qiskit_metal import draw, Dict
from qiskit_metal.toolbox_metal import math_and_overrides
from qiskit_metal.qlibrary.core import QComponent
class MySimpleGapCapacitor(QComponent):
"""
Inherits 'QComponent' class.
Description:
A simple CPW style gap capacitor, with endcap islands each coupled to their own
cpw transmission line that ends in a pin.
Options:
* cpw_width: width of the cpw trace of the transmission line
* cpw_gap: dielectric gap of the cpw transmission line
* cap_width: width of the gap capacitor (size of the charge islands)
* cap_gap: dielectric space between the two islands
* pos_x/_y: position of the capacitor on chip
* orientation: 0-> is parallel to x-axis, with orientation (in degrees) counterclockwise.
* layer: the layer number for the layout
"""
# Edit these to define your own tempate options for creation
# Default drawing options
default_options = Dict(cpw_width='15um',
cpw_gap='9um',
cap_width='35um',
cap_gap='3um',
pos_x='0um',
pos_y='0um',
orientation='0',
layer='1')
"""Default drawing options"""
# Name prefix of component, if user doesn't provide name
component_metadata = Dict(short_name='component',
_qgeometry_table_poly='True',
_qgeometry_table_path='True')
"""Component metadata"""
def make(self):
"""Convert self.options into QGeometry."""
p = self.parse_options() # Parse the string options into numbers
pad = draw.rectangle(p.cpw_width, p.cap_width, 0, 0)
pad_left = draw.translate(pad,-(p.cpw_width+p.cap_gap)/2,0)
pad_right = draw.translate(pad,(p.cpw_width+p.cap_gap)/2,0)
pad_etch = draw.rectangle(2*p.cpw_gap+2*p.cpw_width+p.cap_gap,2*p.cpw_gap+p.cap_width)
cpw_left = draw.shapely.geometry.LineString([[-(p.cpw_width+p.cap_gap/2),0],[-(p.cpw_width*3 +p.cap_gap/2),0]])
cpw_right = draw.shapely.geometry.LineString([[(p.cpw_width+p.cap_gap/2),0],[(p.cpw_width*3 +p.cap_gap/2),0]])
geom_list = [pad_left,pad_right,cpw_left,cpw_right,pad_etch]
geom_list = draw.rotate(geom_list,p.orientation)
geom_list = draw.translate(geom_list,p.pos_x,p.pos_y)
[pad_left,pad_right,cpw_left,cpw_right,pad_etch] = geom_list
self.add_qgeometry('path', {'cpw_left':cpw_left, 'cpw_right':cpw_right}, layer=p.layer, width = p.cpw_width)
self.add_qgeometry('path', {'cpw_left_etch':cpw_left, 'cpw_right_etch':cpw_right}, layer=p.layer, width = p.cpw_width+2*p.cpw_gap, subtract=True)
self.add_qgeometry('poly', {'pad_left':pad_left, 'pad_right':pad_right}, layer=p.layer)
self.add_qgeometry('poly', {'pad_etch':pad_etch}, layer=p.layer, subtract=True)
self.add_pin('cap_left', cpw_left.coords, width = p.cpw_width, gap = p.cpw_gap, input_as_norm=True)
self.add_pin('cap_right', cpw_right.coords, width = p.cpw_width, gap = p.cpw_gap, input_as_norm=True)
design = metal.designs.DesignPlanar()
gui = metal.MetalGUI(design)
my_cap = MySimpleGapCapacitor(design,'my_cap')
gui.rebuild()
design.overwrite_enabled = True
gui.main_window.close()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Test cases for parameter manager."""
from copy import deepcopy
import numpy as np
from qiskit import pulse
from qiskit.circuit import Parameter
from qiskit.pulse.exceptions import PulseError, UnassignedDurationError
from qiskit.pulse.parameter_manager import ParameterGetter, ParameterSetter
from qiskit.pulse.transforms import AlignEquispaced, AlignLeft, inline_subroutines
from qiskit.test import QiskitTestCase
class ParameterTestBase(QiskitTestCase):
"""A base class for parameter manager unittest, providing test schedule."""
def setUp(self):
"""Just some useful, reusable Parameters, constants, schedules."""
super().setUp()
self.amp1_1 = Parameter("amp1_1")
self.amp1_2 = Parameter("amp1_2")
self.amp2 = Parameter("amp2")
self.amp3 = Parameter("amp3")
self.dur1 = Parameter("dur1")
self.dur2 = Parameter("dur2")
self.dur3 = Parameter("dur3")
self.parametric_waveform1 = pulse.Gaussian(
duration=self.dur1, amp=self.amp1_1 + self.amp1_2, sigma=self.dur1 / 4
)
self.parametric_waveform2 = pulse.Gaussian(
duration=self.dur2, amp=self.amp2, sigma=self.dur2 / 5
)
self.parametric_waveform3 = pulse.Gaussian(
duration=self.dur3, amp=self.amp3, sigma=self.dur3 / 6
)
self.ch1 = Parameter("ch1")
self.ch2 = Parameter("ch2")
self.ch3 = Parameter("ch3")
self.d1 = pulse.DriveChannel(self.ch1)
self.d2 = pulse.DriveChannel(self.ch2)
self.d3 = pulse.DriveChannel(self.ch3)
self.phi1 = Parameter("phi1")
self.phi2 = Parameter("phi2")
self.phi3 = Parameter("phi3")
self.meas_dur = Parameter("meas_dur")
self.mem1 = Parameter("s1")
self.reg1 = Parameter("m1")
self.context_dur = Parameter("context_dur")
# schedule under test
subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft())
subroutine += pulse.ShiftPhase(self.phi1, self.d1)
subroutine += pulse.Play(self.parametric_waveform1, self.d1)
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi3, self.d3)
long_schedule = pulse.ScheduleBlock(
alignment_context=AlignEquispaced(self.context_dur), name="long_schedule"
)
long_schedule += subroutine
long_schedule += pulse.ShiftPhase(self.phi2, self.d2)
long_schedule += pulse.Play(self.parametric_waveform2, self.d2)
with self.assertWarns(DeprecationWarning):
long_schedule += pulse.Call(sched)
long_schedule += pulse.Play(self.parametric_waveform3, self.d3)
long_schedule += pulse.Acquire(
self.meas_dur,
pulse.AcquireChannel(self.ch1),
mem_slot=pulse.MemorySlot(self.mem1),
reg_slot=pulse.RegisterSlot(self.reg1),
)
self.test_sched = long_schedule
class TestParameterGetter(ParameterTestBase):
"""Test getting parameters."""
def test_get_parameter_from_channel(self):
"""Test get parameters from channel."""
test_obj = pulse.DriveChannel(self.ch1 + self.ch2)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.ch1, self.ch2}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_pulse(self):
"""Test get parameters from pulse instruction."""
test_obj = self.parametric_waveform1
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.amp1_1, self.amp1_2, self.dur1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_acquire(self):
"""Test get parameters from acquire instruction."""
test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1))
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_inst(self):
"""Test get parameters from instruction."""
test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0))
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.phi2}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_call(self):
"""Test get parameters from instruction."""
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi1, self.d1)
with self.assertWarns(DeprecationWarning):
test_obj = pulse.Call(subroutine=sched)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_with_function(self):
"""Test ParameterExpressions formed trivially in a function."""
def get_shift(variable):
return variable - 1
test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_alignment_context(self):
"""Test get parameters from alignment context."""
test_obj = AlignEquispaced(duration=self.context_dur + self.dur1)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.context_dur, self.dur1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_complex_schedule(self):
"""Test get parameters from complicated schedule."""
test_block = deepcopy(self.test_sched)
visitor = ParameterGetter()
visitor.visit(test_block)
self.assertEqual(len(visitor.parameters), 17)
class TestParameterSetter(ParameterTestBase):
"""Test setting parameters."""
def test_set_parameter_to_channel(self):
"""Test set parameters from channel."""
test_obj = pulse.DriveChannel(self.ch1 + self.ch2)
value_dict = {self.ch1: 1, self.ch2: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.DriveChannel(3)
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_pulse(self):
"""Test set parameters from pulse instruction."""
test_obj = self.parametric_waveform1
value_dict = {self.amp1_1: 0.1, self.amp1_2: 0.2, self.dur1: 160}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.Gaussian(duration=160, amp=0.3, sigma=40)
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_acquire(self):
"""Test set parameters to acquire instruction."""
test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1))
value_dict = {self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.Acquire(16000, pulse.AcquireChannel(2), pulse.MemorySlot(2))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_inst(self):
"""Test get parameters from instruction."""
test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0))
value_dict = {self.phi1: 0.123, self.phi2: 0.456}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.ShiftPhase(0.579, pulse.DriveChannel(0))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_call(self):
"""Test get parameters from instruction."""
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi1, self.d1)
with self.assertWarns(DeprecationWarning):
test_obj = pulse.Call(subroutine=sched)
value_dict = {self.phi1: 1.57, self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_sched = pulse.Schedule()
ref_sched += pulse.ShiftPhase(1.57, pulse.DriveChannel(2))
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Call(subroutine=ref_sched)
self.assertEqual(assigned, ref_obj)
def test_with_function(self):
"""Test ParameterExpressions formed trivially in a function."""
def get_shift(variable):
return variable - 1
test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1)
value_dict = {self.phi1: 2.0, self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.ShiftPhase(1.0, pulse.DriveChannel(2))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_alignment_context(self):
"""Test get parameters from alignment context."""
test_obj = AlignEquispaced(duration=self.context_dur + self.dur1)
value_dict = {self.context_dur: 1000, self.dur1: 100}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = AlignEquispaced(duration=1100)
self.assertEqual(assigned, ref_obj)
def test_nested_assignment_partial_bind(self):
"""Test nested schedule with call instruction.
Inline the schedule and partially bind parameters."""
context = AlignEquispaced(duration=self.context_dur)
subroutine = pulse.ScheduleBlock(alignment_context=context)
subroutine += pulse.Play(self.parametric_waveform1, self.d1)
nested_block = pulse.ScheduleBlock()
with self.assertWarns(DeprecationWarning):
nested_block += pulse.Call(subroutine=subroutine)
test_obj = pulse.ScheduleBlock()
test_obj += nested_block
test_obj = inline_subroutines(test_obj)
value_dict = {self.context_dur: 1000, self.dur1: 200, self.ch1: 1}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_context = AlignEquispaced(duration=1000)
ref_subroutine = pulse.ScheduleBlock(alignment_context=ref_context)
ref_subroutine += pulse.Play(
pulse.Gaussian(200, self.amp1_1 + self.amp1_2, 50), pulse.DriveChannel(1)
)
ref_nested_block = pulse.ScheduleBlock()
ref_nested_block += ref_subroutine
ref_obj = pulse.ScheduleBlock()
ref_obj += ref_nested_block
self.assertEqual(assigned, ref_obj)
def test_complex_valued_parameter(self):
"""Test complex valued parameter can be casted to a complex value,
but raises PendingDeprecationWarning.."""
amp = Parameter("amp")
test_obj = pulse.Constant(duration=160, amp=1j * amp)
value_dict = {amp: 0.1}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(test_obj)
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Constant(duration=160, amp=1j * 0.1)
self.assertEqual(assigned, ref_obj)
def test_complex_value_to_parameter(self):
"""Test complex value can be assigned to parameter object,
but raises PendingDeprecationWarning."""
amp = Parameter("amp")
test_obj = pulse.Constant(duration=160, amp=amp)
value_dict = {amp: 0.1j}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(test_obj)
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Constant(duration=160, amp=1j * 0.1)
self.assertEqual(assigned, ref_obj)
def test_complex_parameter_expression(self):
"""Test assignment of complex-valued parameter expression to parameter,
but raises PendingDeprecationWarning."""
amp = Parameter("amp")
mag = Parameter("A")
phi = Parameter("phi")
test_obj = pulse.Constant(duration=160, amp=amp)
test_obj_copy = deepcopy(test_obj)
# generate parameter expression
value_dict = {amp: mag * np.exp(1j * phi)}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
# generate complex value
value_dict = {mag: 0.1, phi: 0.5}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(assigned)
# evaluated parameter expression: 0.0877582561890373 + 0.0479425538604203*I
value_dict = {amp: 0.1 * np.exp(0.5j)}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
ref_obj = visitor.visit(test_obj_copy)
self.assertEqual(assigned, ref_obj)
def test_invalid_pulse_amplitude(self):
"""Test that invalid parameters are still checked upon assignment."""
amp = Parameter("amp")
test_sched = pulse.ScheduleBlock()
test_sched.append(
pulse.Play(
pulse.Constant(160, amp=2 * amp),
pulse.DriveChannel(0),
),
inplace=True,
)
with self.assertRaises(PulseError):
test_sched.assign_parameters({amp: 0.6}, inplace=False)
def test_set_parameter_to_complex_schedule(self):
"""Test get parameters from complicated schedule."""
test_block = deepcopy(self.test_sched)
value_dict = {
self.amp1_1: 0.1,
self.amp1_2: 0.2,
self.amp2: 0.3,
self.amp3: 0.4,
self.dur1: 100,
self.dur2: 125,
self.dur3: 150,
self.ch1: 0,
self.ch2: 2,
self.ch3: 4,
self.phi1: 1.0,
self.phi2: 2.0,
self.phi3: 3.0,
self.meas_dur: 300,
self.mem1: 3,
self.reg1: 0,
self.context_dur: 1000,
}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_block)
# create ref schedule
subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft())
subroutine += pulse.ShiftPhase(1.0, pulse.DriveChannel(0))
subroutine += pulse.Play(pulse.Gaussian(100, 0.3, 25), pulse.DriveChannel(0))
sched = pulse.Schedule()
sched += pulse.ShiftPhase(3.0, pulse.DriveChannel(4))
ref_obj = pulse.ScheduleBlock(alignment_context=AlignEquispaced(1000), name="long_schedule")
ref_obj += subroutine
ref_obj += pulse.ShiftPhase(2.0, pulse.DriveChannel(2))
ref_obj += pulse.Play(pulse.Gaussian(125, 0.3, 25), pulse.DriveChannel(2))
with self.assertWarns(DeprecationWarning):
ref_obj += pulse.Call(sched)
ref_obj += pulse.Play(pulse.Gaussian(150, 0.4, 25), pulse.DriveChannel(4))
ref_obj += pulse.Acquire(
300, pulse.AcquireChannel(0), pulse.MemorySlot(3), pulse.RegisterSlot(0)
)
self.assertEqual(assigned, ref_obj)
class TestAssignFromProgram(QiskitTestCase):
"""Test managing parameters from programs. Parameter manager is implicitly called."""
def test_attribute_parameters(self):
"""Test the ``parameter`` attributes."""
sigma = Parameter("sigma")
amp = Parameter("amp")
waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp)
block = pulse.ScheduleBlock()
block += pulse.Play(waveform, pulse.DriveChannel(10))
ref_set = {amp, sigma}
self.assertSetEqual(set(block.parameters), ref_set)
def test_parametric_pulses(self):
"""Test Parametric Pulses with parameters determined by ParameterExpressions
in the Play instruction."""
sigma = Parameter("sigma")
amp = Parameter("amp")
waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp)
block = pulse.ScheduleBlock()
block += pulse.Play(waveform, pulse.DriveChannel(10))
block.assign_parameters({amp: 0.2, sigma: 4}, inplace=True)
self.assertEqual(block.blocks[0].pulse.amp, 0.2)
self.assertEqual(block.blocks[0].pulse.sigma, 4.0)
def test_parameters_from_subroutine(self):
"""Test that get parameter objects from subroutines."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
program_layer0 = pulse.Schedule()
program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0))
# from call instruction
program_layer1 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer1 += pulse.instructions.Call(program_layer0)
self.assertEqual(program_layer1.get_parameters("amp")[0], param1)
# from nested call instruction
program_layer2 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer2 += pulse.instructions.Call(program_layer1)
self.assertEqual(program_layer2.get_parameters("amp")[0], param1)
def test_assign_parameter_to_subroutine(self):
"""Test that assign parameter objects to subroutines."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
program_layer0 = pulse.Schedule()
program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0))
reference = program_layer0.assign_parameters({param1: 0.1}, inplace=False)
# to call instruction
program_layer1 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer1 += pulse.instructions.Call(program_layer0)
target = program_layer1.assign_parameters({param1: 0.1}, inplace=False)
self.assertEqual(inline_subroutines(target), reference)
# to nested call instruction
program_layer2 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer2 += pulse.instructions.Call(program_layer1)
target = program_layer2.assign_parameters({param1: 0.1}, inplace=False)
self.assertEqual(inline_subroutines(target), reference)
def test_assign_parameter_to_subroutine_parameter(self):
"""Test that assign parameter objects to parameter of subroutine."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
param_sub1 = Parameter("p1")
param_sub2 = Parameter("p2")
subroutine = pulse.Schedule()
subroutine += pulse.Play(waveform, pulse.DriveChannel(0))
reference = subroutine.assign_parameters({param1: 0.6}, inplace=False)
main_prog = pulse.Schedule()
pdict = {param1: param_sub1 + param_sub2}
with self.assertWarns(DeprecationWarning):
main_prog += pulse.instructions.Call(subroutine, value_dict=pdict)
# parameter is overwritten by parameters
self.assertEqual(len(main_prog.parameters), 2)
target = main_prog.assign_parameters({param_sub1: 0.1, param_sub2: 0.5}, inplace=False)
result = inline_subroutines(target)
self.assertEqual(result, reference)
class TestScheduleTimeslots(QiskitTestCase):
"""Test for edge cases of timing overlap on parametrized channels.
Note that this test is dedicated to `Schedule` since `ScheduleBlock` implicitly
assigns instruction time t0 that doesn't overlap with existing instructions.
"""
def test_overlapping_pulses(self):
"""Test that an error is still raised when overlapping instructions are assigned."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
with self.assertRaises(PulseError):
schedule |= pulse.Play(
pulse.Waveform([0.5, 0.5, 0.5, 0.5]), pulse.DriveChannel(param_idx)
)
def test_overlapping_on_assignment(self):
"""Test that assignment will catch against existing instructions."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx: 1})
def test_overlapping_on_expression_assigment_to_zero(self):
"""Test constant*zero expression conflict."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(2 * param_idx))
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx: 0})
def test_merging_upon_assignment(self):
"""Test that schedule can match instructions on a channel."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1))
schedule = schedule.insert(
4, pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
)
schedule.assign_parameters({param_idx: 1})
self.assertEqual(schedule.ch_duration(pulse.DriveChannel(1)), 8)
self.assertEqual(schedule.channels, (pulse.DriveChannel(1),))
def test_overlapping_on_multiple_assignment(self):
"""Test that assigning one qubit then another raises error when overlapping."""
param_idx1 = Parameter("q1")
param_idx2 = Parameter("q2")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx1))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx2))
schedule.assign_parameters({param_idx1: 2})
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx2: 2})
def test_cannot_build_schedule_with_unassigned_duration(self):
"""Test we cannot build schedule with parameterized instructions"""
dur = Parameter("dur")
ch = pulse.DriveChannel(0)
test_play = pulse.Play(pulse.Gaussian(dur, 0.1, dur / 4), ch)
sched = pulse.Schedule()
with self.assertRaises(UnassignedDurationError):
sched.insert(0, test_play)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, backend=FakeBoeblingen())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.visualization.timeline import draw as timeline_draw
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
timeline_draw(circ)
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
from dell_runtime import DellRuntimeProvider
from qiskit import QuantumCircuit
RUNTIME_PROGRAM = """
# This code is part of qiskit-runtime.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
from qiskit.compiler import transpile, schedule
def main(
backend,
user_messenger,
circuits,
**kwargs,
):
circuits = transpile(
circuits,
)
if not isinstance(circuits, list):
circuits = [circuits]
# Compute raw results
result = backend.run(circuits, **kwargs).result()
user_messenger.publish(result.to_dict(), final=True)
"""
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
# PROGRAM_PREFIX = 'qiskit-test'
def main():
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
runtime_program = provider.runtime.program(program_id)
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
job.result(timeout=120)
if __name__ == "__main__":
main()
|
https://github.com/Dpbm/scientific-research-1-quantum-oracles
|
Dpbm
|
%matplotlib inline
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_histogram, array_to_latex
from qiskit.circuit.library import QFT, GroverOperator
from qiskit.primitives import Sampler
from qiskit_aer import AerSimulator
from math import pi, sqrt, sin
import matplotlib.pyplot as plt
from itertools import product
import pandas as pd
import functools
from utils import get_image_path
from utils import fibonacci as recursive_fibonacci
from tqdm.notebook import tqdm_notebook
def simulate(qc, shots=1000, backend=AerSimulator()):
transpiled_circuit = transpile(qc, backend) if not isinstance(backend, Sampler) else qc
return backend.run(transpiled_circuit, shots=shots)
def get_counts(job):
return job.result().get_counts()
def fibonacci(n):
qc = QuantumCircuit(n)
qc.ry(pi/2, range(n))
if(n > 1):
for i in range(0, n-1):
qc.cry(-pi/2, i, i+1)
return qc
qc = fibonacci(4)
qc.measure_all()
qc.draw('mpl', filename=get_image_path("fibonacci-circuit.png"))
job = simulate(qc)
counts = get_counts(job)
def complete_results(counts):
results = {}
for bit_string in product('01', repeat=len(qc.qubits)):
bit_string = ''.join(bit_string)
results[bit_string] = 0 if counts.get(bit_string) is None else counts[bit_string]
return results
fig= plot_histogram(complete_results(counts))
fig.savefig(get_image_path('fibonacci-4.png'))
display(fig)
def get_fibonacci_number(counts):
return len(counts)
# F(4)
get_fibonacci_number(counts)
def evaluate_fibonacci_quantum(n, shots=1000):
qc = fibonacci(n)
qc.measure_all()
job = simulate(qc, shots=shots)
counts = get_counts(job)
return get_fibonacci_number(counts)
x_values = list(range(1,15))
y_values = {"classical":[recursive_fibonacci(n+1) for n in x_values], "quantum":[]}
def comparation(shots=1000):
y_values["quantum"] = []
for n in x_values:
y_values["quantum"].append(evaluate_fibonacci_quantum(n, shots))
return y_values
y_values_1000 = comparation(shots=1000)
y_values_4000 = comparation(shots=4000)
y_values_6000 = comparation(shots=6000)
x = pd.Series(x_values)
y_1000 = pd.DataFrame(y_values_1000)
y_4000 = pd.DataFrame(y_values_4000)
y_6000 = pd.DataFrame(y_values_6000)
f, (ax1, ax2, ax3) = plt.subplots(1, 3, sharey=True, figsize=(30, 10))
#plt.title("Comparation between quantum and classical Fibonacci algorithm")
ax1.plot(x, y_1000)
ax1.legend(labels=["classical", "quantum"])
ax1.set_title("shots=1000")
ax2.plot(x, y_4000)
ax2.legend(labels=["classical", "quantum"])
ax2.set_title("shots=4000")
ax3.plot(x, y_6000)
ax3.legend(labels=["classical", "quantum"])
ax3.set_title("shots=6000")
plt.show()
f.savefig(get_image_path('comparation.png'))
def fibonacci_oracle(n):
qc = QuantumCircuit(n, name="oracle")
#from https://arxiv.org/pdf/2006.10656.pdf
predicate = lambda k: k & k >> 1 == 0
max_value = int('1'*n, 2)
for k in range(max_value):
if(predicate(k)):
bit_string = format(k, 'b').zfill(n)[::-1]
zeros = [index for index, bit in enumerate(bit_string) if bit == '0' ]
qc.x(zeros)
qc.mcp(pi, list(range(1, n)), 0)
qc.x(zeros)
return qc
def show_unitary(qc):
sim = AerSimulator()
qc_unitary = qc.copy()
qc_unitary.save_unitary()
unitary = sim.run(transpile(qc_unitary, sim), shots=1000).result().get_unitary()
display(array_to_latex(unitary, max_size=100000))
n = 4
oracle = fibonacci_oracle(n)
show_unitary(oracle)
oracle.draw('mpl')
def create_grover_operator(n_iterations, oracle):
grover = GroverOperator(oracle, name="grover").repeat(n_iterations).to_gate().control()
return grover
def create_qft_dagger(n):
return QFT(n, inverse=True).to_gate(label="QFT†")
def create_quantum_couting_algorithm(n, oracle):
total_qubits = n*2
qc = QuantumCircuit(total_qubits, n)
qc.h(range(total_qubits))
iterations = 1
for qubit in range(n):
qc.append(create_grover_operator(iterations, oracle), [qubit] + list(range(n, total_qubits)))
iterations *= 2
qc.append(create_qft_dagger(n), list(range(n)))
qc.measure(range(n), range(n))
return qc
qc = create_quantum_couting_algorithm(n, oracle)
qc.draw('mpl', filename=get_image_path("quantum_counting.png"))
def get_dist(job):
dists = job.result().quasi_dists
print(dists)
return dists[0]
def get_total_results(dist):
measured_str = max(dist, key=dist.get)
theta = (measured_str/(2**n))*pi*2
N = 2 ** n
M = N * (sin(theta/2)**2)
return M
def evaluate_fibonacci_quantum_2(n, shots):
progress = tqdm_notebook(total=3)
oracle = fibonacci_oracle(n)
progress.update(1)
qc = create_quantum_couting_algorithm(n, oracle)
progress.update(1)
dist = get_dist(simulate(qc, backend=Sampler()))
progress.update(1)
return get_total_results(dist)
x_values = list(range(2,7))
y_values = {"classical":[recursive_fibonacci(n+1) for n in x_values], "quantum":[]}
def comparation_2(shots=1000):
y_values["quantum"] = []
for n in x_values:
y_values["quantum"].append(evaluate_fibonacci_quantum_2(n, shots))
return y_values
y_values_1000 = comparation_2(shots=1000)
y_values_4000 = comparation_2(shots=4000)
y_values_6000 = comparation_2(shots=6000)
y_values_10000 = comparation_2(shots=10000)
x = pd.Series(x_values)
y_1000 = pd.DataFrame(y_values_1000)
y_4000 = pd.DataFrame(y_values_4000)
y_6000 = pd.DataFrame(y_values_6000)
y_10000 = pd.DataFrame(y_values_10000)
f, ax = plt.subplots(2, 2, sharey=True, figsize=(30, 10))
ax1 = ax[0][0]
ax2 = ax[0][1]
ax3 = ax[1][0]
ax4 = ax[1][1]
#plt.title("Comparation between quantum and classical Fibonacci algorithm")
ax1.plot(x, y_1000)
ax1.legend(labels=["classical", "quantum"])
ax1.set_title("shots=1000")
ax2.plot(x, y_4000)
ax2.legend(labels=["classical", "quantum"])
ax2.set_title("shots=4000")
ax3.plot(x, y_6000)
ax3.legend(labels=["classical", "quantum"])
ax3.set_title("shots=6000")
ax4.plot(x, y_10000)
ax4.legend(labels=["classical", "quantum"])
ax4.set_title("shots=10000")
plt.show()
f.savefig(get_image_path('comparation2.png'))
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
import itertools
import json
import numpy as np
from numpy.random import RandomState
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.compiler import transpile
from cvxopt import matrix, solvers # pylint: disable=import-error
class QKA:
def __init__(self, feature_map, backend, initial_layout=None, user_messenger=None):
self.feature_map = feature_map
self.feature_map_circuit = self.feature_map.construct_circuit
self.backend = backend
self.initial_layout = initial_layout
self.num_parameters = self.feature_map._num_parameters
self._user_messenger = user_messenger
self.result = {}
self.kernel_matrix = KernelMatrix(
feature_map=self.feature_map, backend=self.backend, initial_layout=self.initial_layout
)
def spsa_parameters(self):
spsa_params = np.zeros((5))
spsa_params[0] = 0.05 # a
spsa_params[1] = 0.1 # c
spsa_params[2] = 0.602 # alpha
spsa_params[3] = 0.101 # gamma
spsa_params[4] = 0 # A
return spsa_params
def cvxopt_solver(self, K, y, C, max_iters=10000, show_progress=False):
if y.ndim == 1:
y = y[:, np.newaxis]
H = np.outer(y, y) * K
f = -np.ones(y.shape)
n = K.shape[1] # number of training points
y = y.astype("float")
P = matrix(H)
q = matrix(f)
G = matrix(np.vstack((-np.eye((n)), np.eye((n)))))
h = matrix(np.vstack((np.zeros((n, 1)), np.ones((n, 1)) * C)))
A = matrix(y, y.T.shape)
b = matrix(np.zeros(1), (1, 1))
solvers.options["maxiters"] = max_iters
solvers.options["show_progress"] = show_progress
ret = solvers.qp(P, q, G, h, A, b, kktsolver="ldl")
return ret
def spsa_step_one(self, lambdas, spsa_params, count):
prng = RandomState(count)
c_spsa = float(spsa_params[1]) / np.power(count + 1, spsa_params[3])
delta = 2 * prng.randint(0, 2, size=np.shape(lambdas)[0]) - 1
lambda_plus = lambdas + c_spsa * delta
lambda_minus = lambdas - c_spsa * delta
return lambda_plus, lambda_minus, delta
def spsa_step_two(self, cost_plus, cost_minus, lambdas, spsa_params, delta, count):
a_spsa = float(spsa_params[0]) / np.power(count + 1 + spsa_params[4], spsa_params[2])
c_spsa = float(spsa_params[1]) / np.power(count + 1, spsa_params[3])
g_spsa = (cost_plus - cost_minus) * delta / (2.0 * c_spsa)
lambdas_new = lambdas - a_spsa * g_spsa
lambdas_new = lambdas_new.flatten()
cost_final = (cost_plus + cost_minus) / 2
return cost_final, lambdas_new
def align_kernel(self, data, labels, initial_kernel_parameters=None, maxiters=1, C=1):
if initial_kernel_parameters is not None:
lambdas = initial_kernel_parameters
else:
lambdas = np.random.uniform(-1.0, 1.0, size=(self.num_parameters))
spsa_params = self.spsa_parameters()
lambda_save = []
cost_final_save = []
for count in range(maxiters):
lambda_plus, lambda_minus, delta = self.spsa_step_one(
lambdas=lambdas, spsa_params=spsa_params, count=count
)
kernel_plus = self.kernel_matrix.construct_kernel_matrix(
x1_vec=data, x2_vec=data, parameters=lambda_plus
)
kernel_minus = self.kernel_matrix.construct_kernel_matrix(
x1_vec=data, x2_vec=data, parameters=lambda_minus
)
ret_plus = self.cvxopt_solver(K=kernel_plus, y=labels, C=C)
cost_plus = -1 * ret_plus["primal objective"]
ret_minus = self.cvxopt_solver(K=kernel_minus, y=labels, C=C)
cost_minus = -1 * ret_minus["primal objective"]
cost_final, lambda_best = self.spsa_step_two(
cost_plus=cost_plus,
cost_minus=cost_minus,
lambdas=lambdas,
spsa_params=spsa_params,
delta=delta,
count=count,
)
lambdas = lambda_best
interim_result = {"cost": cost_final, "kernel_parameters": lambdas}
print(interim_result)
self._user_messenger.publish(interim_result)
lambda_save.append(lambdas)
cost_final_save.append(cost_final)
# Evaluate aligned kernel matrix with optimized set of
# parameters averaged over last 10% of SPSA steps:
num_last_lambdas = int(len(lambda_save) * 0.10)
if num_last_lambdas > 0:
last_lambdas = np.array(lambda_save)[-num_last_lambdas:, :]
lambdas = np.sum(last_lambdas, axis=0) / num_last_lambdas
else:
lambdas = np.array(lambda_save)[-1, :]
kernel_best = self.kernel_matrix.construct_kernel_matrix(
x1_vec=data, x2_vec=data, parameters=lambdas
)
self.result["aligned_kernel_parameters"] = lambdas
self.result["aligned_kernel_matrix"] = kernel_best
return self.result
class KernelMatrix:
def __init__(self, feature_map, backend, initial_layout=None):
self._feature_map = feature_map
self._feature_map_circuit = self._feature_map.construct_circuit
self._backend = backend
self._initial_layout = initial_layout
self.results = {}
def construct_kernel_matrix(self, x1_vec, x2_vec, parameters=None):
is_identical = False
if np.array_equal(x1_vec, x2_vec):
is_identical = True
experiments = []
measurement_basis = "0" * self._feature_map._num_qubits
if is_identical:
my_product_list = list(
itertools.combinations(range(len(x1_vec)), 2)
) # all pairwise combos of datapoint indices
for index_1, index_2 in my_product_list:
circuit_1 = self._feature_map_circuit(
x=x1_vec[index_1], parameters=parameters, name="{}_{}".format(index_1, index_2)
)
circuit_2 = self._feature_map_circuit(
x=x1_vec[index_2], parameters=parameters, inverse=True
)
circuit = circuit_1.compose(circuit_2)
circuit.measure_all()
experiments.append(circuit)
experiments = transpile(
experiments, backend=self._backend, initial_layout=self._initial_layout
)
program_data = self._backend.run(experiments, shots=8192).result()
self.results["program_data"] = program_data
mat = np.eye(
len(x1_vec), len(x1_vec)
) # kernel matrix element on the diagonal is always 1
for experiment, [index_1, index_2] in enumerate(my_product_list):
counts = program_data.get_counts(experiment=experiment)
shots = sum(counts.values())
mat[index_1][index_2] = (
counts.get(measurement_basis, 0) / shots
) # kernel matrix element is the probability of measuring all 0s
mat[index_2][index_1] = mat[index_1][index_2] # kernel matrix is symmetric
return mat
else:
for index_1, point_1 in enumerate(x1_vec):
for index_2, point_2 in enumerate(x2_vec):
circuit_1 = self._feature_map_circuit(
x=point_1, parameters=parameters, name="{}_{}".format(index_1, index_2)
)
circuit_2 = self._feature_map_circuit(
x=point_2, parameters=parameters, inverse=True
)
circuit = circuit_1.compose(circuit_2)
circuit.measure_all()
experiments.append(circuit)
experiments = transpile(
experiments, backend=self._backend, initial_layout=self._initial_layout
)
program_data = self._backend.run(experiments, shots=8192).result()
self.results["program_data"] = program_data
mat = np.zeros((len(x1_vec), len(x2_vec)))
i = 0
for index_1, _ in enumerate(x1_vec):
for index_2, _ in enumerate(x2_vec):
counts = program_data.get_counts(experiment=i)
shots = sum(counts.values())
mat[index_1][index_2] = counts.get(measurement_basis, 0) / shots
i += 1
return mat
|
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/HuangJunye/Qiskit-for-GameDev
|
HuangJunye
|
from qiskit import QuantumCircuit
from circuit_grid import CircuitGridModel, CircuitGridNode
import circuit_node_types as node_types
from sympy import pi
import logging
id_gate = CircuitGridNode(node_types.ID)
x_gate = CircuitGridNode(node_types.X, 1)
y_gate = CircuitGridNode(node_types.Y, 1)
z_gate = CircuitGridNode(node_types.Z, 1)
h_gate = CircuitGridNode(node_types.H, 1)
s_gate = CircuitGridNode(node_types.S, 1)
sdg_gate = CircuitGridNode(node_types.SDG, 1)
t_gate = CircuitGridNode(node_types.T, 1)
tdg_gate = CircuitGridNode(node_types.TDG, 1)
u1_gate = CircuitGridNode(node_types.U1, 1, theta=pi)
u2_gate = CircuitGridNode(node_types.U2, 1, theta=pi, phi=pi)
u3_gate = CircuitGridNode(node_types.U3, 1, theta=pi, phi=pi, lam=pi)
rx_gate = CircuitGridNode(node_types.RX, 1, theta=pi)
ry_gate = CircuitGridNode(node_types.RY, 1, theta=pi)
rz_gate = CircuitGridNode(node_types.RZ, 1, theta=pi)
cx_gate = CircuitGridNode(node_types.CX, 1, ctrl_a=0)
cy_gate = CircuitGridNode(node_types.CY, 2, ctrl_a=1)
cz_gate = CircuitGridNode(node_types.CZ, 3, ctrl_a=2)
ch_gate = CircuitGridNode(node_types.CH, 4, ctrl_a=3)
crz_gate = CircuitGridNode(node_types.CRZ, 1, theta=pi, ctrl_a=0)
cu1_gate = CircuitGridNode(node_types.CU1, 1, theta=pi, ctrl_a=0)
cu3_gate = CircuitGridNode(node_types.CU3, 1, theta=pi, phi=pi, lam=pi, ctrl_a=0)
ccx_gate = CircuitGridNode(node_types.CCX, 2, ctrl_a=0, ctrl_b=1)
swap_gate = CircuitGridNode(node_types.SWAP, 1, swap=2)
cswap_gate = CircuitGridNode(node_types.CSWAP, 1, ctrl_a=0, swap=2)
barrier = CircuitGridNode(node_types.BARRIER, 1)
measure_z = CircuitGridNode(node_types.MEASURE_Z, 1)
reset = CircuitGridNode(node_types.RESET, 1)
_if = CircuitGridNode(node_types.IF, 1)
gates = [
id_gate,
x_gate,
y_gate,
z_gate,
h_gate,
s_gate,
sdg_gate,
t_gate,
tdg_gate,
u1_gate,
u2_gate,
u3_gate,
rx_gate,
ry_gate,
rz_gate,
cx_gate,
cy_gate,
cz_gate,
ch_gate,
crz_gate,
cu1_gate,
cu3_gate,
ccx_gate,
swap_gate,
cswap_gate,
barrier,
measure_z,
reset,
_if
]
for gate in gates:
print(gate)
for gate in gates:
print(gate.qasm())
circuit_grid = CircuitGridModel(4,5)
print(circuit_grid)
print(gates[0])
for j in range(circuit_grid.circuit_depth):
for i in range(circuit_grid.qubit_count):
circuit_grid.set_node(i,j,gates[i*circuit_grid.circuit_depth + j])
qasm_str = circuit_grid.create_qasm_for_circuit()
print(qasm_str)
qc = QuantumCircuit.from_qasm_str(qasm_str)
qc.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/epelaaez/QuantumLibrary
|
epelaaez
|
import config
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, IBMQ, Aer, execute
from qiskit.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
def bell_state():
qreg = QuantumRegister(2, 'q')
creg = ClassicalRegister(2, 'c')
qc = QuantumCircuit(qreg, creg)
# Create bell state itself by putting first qubit into superposition and then applying a CNOT gate between the two qubits
qc.h(qreg[0])
qc.cx(qreg[0], qreg[1])
# Measure both qubits
qc.measure(qreg[0], creg[0])
qc.measure(qreg[1], creg[1])
# Return circuit
return qc
circ = bell_state()
circ.draw()
IBMQ.save_account(f"{config.IBM_KEY}", overwrite = True)
IBMQ.load_account()
backend = Aer.get_backend('qasm_simulator')
# Uncomment below to run on hardware
# provider = IBMQ.get_provider(hub='ibm-q')
# backend = least_busy(provider.backends())
result = execute(circ, backend, shots=1024).result()
counts = result.get_counts(circ)
plot_histogram(counts)
|
https://github.com/sarthag/Quantum-Algos-using-Qiskit
|
sarthag
|
# Importing Packages
from qiskit import QuantumCircuit
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
def encode(qc, qubit, msg):
if len(msg) != 2 or not set(msg).issubset({"0","1"}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
# Circuit for Superdense coding
qc = QuantumCircuit(2)
# Generating entangled state
qc.h(1)
qc.cx(1, 0)
qc.barrier()
# Encoding message
message = '11'
qc = encode(qc, 1, message)
qc.barrier()
# Decoding Message
qc.cx(1, 0)
qc.h(1)
# Measuring qubits
qc.measure_all()
qc.draw(output="mpl", style=style)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(qc)
result = aer_sim.run(qobj).result()
counts = result.get_counts(qc)
print(counts)
plot_histogram(counts)
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_bloch_multivector, plot_state_qsphere
# Import image and file processing tools
from PIL import Image
import os
print("Ch 6: Animating the U gates")
print("--------------------------")
# This program requires an /images directory at the same location as the script.
dirName = 'images'
print("Checking if /images directory exists...")
if not os.path.exists(dirName):
os.mkdir(dirName)
print("Directory" , dirName , "created ")
else:
print("Directory" , dirName , "exists")
def get_psi(circuit):
global psi
backend = Aer.get_backend('statevector_simulator')
result = execute(circuit, backend).result()
psi = result.get_statevector(circuit)
return(psi)
def create_images(gate,theta=0.0,phi=0.0,lam=0.0):
# Set the loop parameters
steps=20.0
theta_steps=theta/steps
phi_steps=phi/steps
lam_steps=lam/steps
n, theta,phi,lam=0,0.0,0.0,0.0
# Create image and animation tools
global q_images, b_images, q_filename, b_filename
b_images=[]
q_images=[]
b_filename="animated_qubit"
q_filename="animated_qsphere"
# The image creation loop
while n < steps+1:
qc=QuantumCircuit(1)
if gate=="u3":
qc.u3(theta,phi,lam,0)
title="U3: \u03B8 = "+str(round(theta,2))+" \u03D5 = "+str(round(phi,2))+" \u03BB = "+str(round(lam,2))
elif gate=="u2":
qc.u2(phi,lam,0)
title="U2: \u03D5 = "+str(round(phi,2))+" \u03BB = "+str(round(lam,2))
else:
qc.h(0)
qc.u1(phi,0)
title="U1: \u03D5 = "+str(round(phi,2))
# Get the statevector of the qubit
# Create Bloch sphere images
plot_bloch_multivector(get_psi(qc),title).savefig('images/bloch'+str(n)+'.png')
imb = Image.open('images/bloch'+str(n)+'.png')
b_images.append(imb)
# Create Q sphere images
plot_state_qsphere(psi).savefig('images/qsphere'+str(n)+'.png')
imq = Image.open('images/qsphere'+str(n)+'.png')
q_images.append(imq)
# Rev our loop
n+=1
theta+=theta_steps
phi+=phi_steps
lam+=lam_steps
# Create and save the animated GIFs
def save_gif(gate):
duration=100
b_images[0].save(gate+'_'+b_filename+'.gif',
save_all=True,
append_images=b_images[1:],
duration=duration,
loop=0)
q_images[0].save(gate+'_'+q_filename+'.gif',
save_all=True,
append_images=q_images[1:],
duration=duration,
loop=0)
print("Bloch sphere animation saved as: \n"+os.getcwd()+"/"+gate+"_"+b_filename+".gif"+"\nQsphere animation saved as: \n"+os.getcwd()+"/"+gate+"_"+q_filename+".gif")
# Main loop
def main():
global gate
gate=""
theta=0.0
phi=0.0
lam=0.0
while gate !="exit":
gate=input("Enter u1, u2, or u3:\n")
if gate =="u3":
theta=float(input("Enter \u03B8:\n"))
if gate in ["u3","u2","u1"]:
phi=float(input("Enter \u03D5:\n"))
if gate in ["u3","u2"]:
lam=float(input("Enter \u03BB:\n"))
if gate in ["u3","u2","u1"]:
print("Building animation...")
create_images(gate,theta,phi,lam)
save_gif(gate)
else:
print("Not a valid gate, try again...")
if __name__ == '__main__':
main()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""
Stabilizer state class.
"""
from __future__ import annotations
import numpy as np
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.operators.op_shape import OpShape
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.symplectic import Clifford, Pauli, PauliList
from qiskit.quantum_info.operators.symplectic.clifford_circuits import _append_x
from qiskit.quantum_info.states.quantum_state import QuantumState
from qiskit.circuit import QuantumCircuit, Instruction
class StabilizerState(QuantumState):
"""StabilizerState class.
Stabilizer simulator using the convention from reference [1].
Based on the internal class :class:`~qiskit.quantum_info.Clifford`.
.. code-block::
from qiskit import QuantumCircuit
from qiskit.quantum_info import StabilizerState, Pauli
# Bell state generation circuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
stab = StabilizerState(qc)
# Print the StabilizerState
print(stab)
# Calculate the StabilizerState measurement probabilities dictionary
print (stab.probabilities_dict())
# Calculate expectation value of the StabilizerState
print (stab.expectation_value(Pauli('ZZ')))
.. parsed-literal::
StabilizerState(StabilizerTable: ['+XX', '+ZZ'])
{'00': 0.5, '11': 0.5}
1
References:
1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*,
Phys. Rev. A 70, 052328 (2004).
`arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_
"""
def __init__(
self,
data: StabilizerState | Clifford | Pauli | QuantumCircuit | Instruction,
validate: bool = True,
):
"""Initialize a StabilizerState object.
Args:
data (StabilizerState or Clifford or Pauli or QuantumCircuit or
qiskit.circuit.Instruction):
Data from which the stabilizer state can be constructed.
validate (boolean): validate that the stabilizer state data is
a valid Clifford.
"""
# Initialize from another StabilizerState
if isinstance(data, StabilizerState):
self._data = data._data
# Initialize from a Pauli
elif isinstance(data, Pauli):
self._data = Clifford(data.to_instruction())
# Initialize from a Clifford, QuantumCircuit or Instruction
else:
self._data = Clifford(data, validate)
# Initialize
super().__init__(op_shape=OpShape.auto(num_qubits_r=self._data.num_qubits, num_qubits_l=0))
def __eq__(self, other):
return (self._data.stab == other._data.stab).all()
def __repr__(self):
return f"StabilizerState({self._data.stabilizer})"
@property
def clifford(self):
"""Return StabilizerState Clifford data"""
return self._data
def is_valid(self, atol=None, rtol=None):
"""Return True if a valid StabilizerState."""
return self._data.is_unitary()
def _add(self, other):
raise NotImplementedError(f"{type(self)} does not support addition")
def _multiply(self, other):
raise NotImplementedError(f"{type(self)} does not support scalar multiplication")
def trace(self) -> float:
"""Return the trace of the stabilizer state as a density matrix,
which equals to 1, since it is always a pure state.
Returns:
float: the trace (should equal 1).
Raises:
QiskitError: if input is not a StabilizerState.
"""
if not self.is_valid():
raise QiskitError("StabilizerState is not a valid quantum state.")
return 1.0
def purity(self) -> float:
"""Return the purity of the quantum state,
which equals to 1, since it is always a pure state.
Returns:
float: the purity (should equal 1).
Raises:
QiskitError: if input is not a StabilizerState.
"""
if not self.is_valid():
raise QiskitError("StabilizerState is not a valid quantum state.")
return 1.0
def to_operator(self) -> Operator:
"""Convert state to matrix operator class"""
return Clifford(self.clifford).to_operator()
def conjugate(self):
"""Return the conjugate of the operator."""
ret = self.copy()
ret._data = ret._data.conjugate()
return ret
def tensor(self, other: StabilizerState) -> StabilizerState:
"""Return the tensor product stabilizer state self ⊗ other.
Args:
other (StabilizerState): a stabilizer state object.
Returns:
StabilizerState: the tensor product operator self ⊗ other.
Raises:
QiskitError: if other is not a StabilizerState.
"""
if not isinstance(other, StabilizerState):
other = StabilizerState(other)
ret = self.copy()
ret._data = self.clifford.tensor(other.clifford)
return ret
def expand(self, other: StabilizerState) -> StabilizerState:
"""Return the tensor product stabilizer state other ⊗ self.
Args:
other (StabilizerState): a stabilizer state object.
Returns:
StabilizerState: the tensor product operator other ⊗ self.
Raises:
QiskitError: if other is not a StabilizerState.
"""
if not isinstance(other, StabilizerState):
other = StabilizerState(other)
ret = self.copy()
ret._data = self.clifford.expand(other.clifford)
return ret
def evolve(
self, other: Clifford | QuantumCircuit | Instruction, qargs: list | None = None
) -> StabilizerState:
"""Evolve a stabilizer state by a Clifford operator.
Args:
other (Clifford or QuantumCircuit or qiskit.circuit.Instruction):
The Clifford operator to evolve by.
qargs (list): a list of stabilizer subsystem positions to apply the operator on.
Returns:
StabilizerState: the output stabilizer state.
Raises:
QiskitError: if other is not a StabilizerState.
QiskitError: if the operator dimension does not match the
specified StabilizerState subsystem dimensions.
"""
if not isinstance(other, StabilizerState):
other = StabilizerState(other)
ret = self.copy()
ret._data = self.clifford.compose(other.clifford, qargs=qargs)
return ret
def expectation_value(self, oper: Pauli, qargs: None | list = None) -> complex:
"""Compute the expectation value of a Pauli operator.
Args:
oper (Pauli): a Pauli operator to evaluate expval.
qargs (None or list): subsystems to apply the operator on.
Returns:
complex: the expectation value (only 0 or 1 or -1 or i or -i).
Raises:
QiskitError: if oper is not a Pauli operator.
"""
if not isinstance(oper, Pauli):
raise QiskitError("Operator for expectation value is not a Pauli operator.")
num_qubits = self.clifford.num_qubits
if qargs is None:
qubits = range(num_qubits)
else:
qubits = qargs
# Construct Pauli on num_qubits
pauli = Pauli(num_qubits * "I")
phase = 0
pauli_phase = (-1j) ** oper.phase if oper.phase else 1
for pos, qubit in enumerate(qubits):
pauli.x[qubit] = oper.x[pos]
pauli.z[qubit] = oper.z[pos]
phase += pauli.x[qubit] & pauli.z[qubit]
# Check if there is a stabilizer that anti-commutes with an odd number of qubits
# If so the expectation value is 0
for p in range(num_qubits):
num_anti = 0
num_anti += np.count_nonzero(pauli.z & self.clifford.stab_x[p])
num_anti += np.count_nonzero(pauli.x & self.clifford.stab_z[p])
if num_anti % 2 == 1:
return 0
# Otherwise pauli is (-1)^a prod_j S_j^b_j for Clifford stabilizers
# If pauli anti-commutes with D_j then b_j = 1.
# Multiply pauli by stabilizers with anti-commuting destabilizers
pauli_z = (pauli.z).copy() # Make a copy of pauli.z
for p in range(num_qubits):
# Check if destabilizer anti-commutes
num_anti = 0
num_anti += np.count_nonzero(pauli.z & self.clifford.destab_x[p])
num_anti += np.count_nonzero(pauli.x & self.clifford.destab_z[p])
if num_anti % 2 == 0:
continue
# If anti-commutes multiply Pauli by stabilizer
phase += 2 * self.clifford.stab_phase[p]
phase += np.count_nonzero(self.clifford.stab_z[p] & self.clifford.stab_x[p])
phase += 2 * np.count_nonzero(pauli_z & self.clifford.stab_x[p])
pauli_z = pauli_z ^ self.clifford.stab_z[p]
# For valid stabilizers, `phase` can only be 0 (= 1) or 2 (= -1) at this point.
if phase % 4 != 0:
return -pauli_phase
return pauli_phase
def equiv(self, other: StabilizerState) -> bool:
"""Return True if the two generating sets generate the same stabilizer group.
Args:
other (StabilizerState): another StabilizerState.
Returns:
bool: True if other has a generating set that generates the same StabilizerState.
"""
if not isinstance(other, StabilizerState):
try:
other = StabilizerState(other)
except QiskitError:
return False
num_qubits = self.num_qubits
if other.num_qubits != num_qubits:
return False
pauli_orig = PauliList.from_symplectic(
self._data.stab_z, self._data.stab_x, 2 * self._data.stab_phase
)
pauli_other = PauliList.from_symplectic(
other._data.stab_z, other._data.stab_x, 2 * other._data.stab_phase
)
# Check that each stabilizer from the original set commutes with each stabilizer
# from the other set
if not np.all([pauli.commutes(pauli_other) for pauli in pauli_orig]):
return False
# Compute the expected value of each stabilizer from the original set on the stabilizer state
# determined by the other set. The two stabilizer states coincide if and only if the
# expected value is +1 for each stabilizer
for i in range(num_qubits):
exp_val = self.expectation_value(pauli_other[i])
if exp_val != 1:
return False
return True
def probabilities(self, qargs: None | list = None, decimals: None | int = None) -> np.ndarray:
"""Return the subsystem measurement probability vector.
Measurement probabilities are with respect to measurement in the
computation (diagonal) basis.
Args:
qargs (None or list): subsystems to return probabilities for,
if None return for all subsystems (Default: None).
decimals (None or int): the number of decimal places to round
values. If None no rounding is done (Default: None).
Returns:
np.array: The Numpy vector array of probabilities.
"""
probs_dict = self.probabilities_dict(qargs, decimals)
if qargs is None:
qargs = range(self.clifford.num_qubits)
probs = np.zeros(2 ** len(qargs))
for key, value in probs_dict.items():
place = int(key, 2)
probs[place] = value
return probs
def probabilities_dict(self, qargs: None | list = None, decimals: None | int = None) -> dict:
"""Return the subsystem measurement probability dictionary.
Measurement probabilities are with respect to measurement in the
computation (diagonal) basis.
This dictionary representation uses a Ket-like notation where the
dictionary keys are qudit strings for the subsystem basis vectors.
If any subsystem has a dimension greater than 10 comma delimiters are
inserted between integers so that subsystems can be distinguished.
Args:
qargs (None or list): subsystems to return probabilities for,
if None return for all subsystems (Default: None).
decimals (None or int): the number of decimal places to round
values. If None no rounding is done (Default: None).
Returns:
dict: The measurement probabilities in dict (ket) form.
"""
if qargs is None:
qubits = range(self.clifford.num_qubits)
else:
qubits = qargs
outcome = ["X"] * len(qubits)
outcome_prob = 1.0
probs = {} # probabilities dictionary
self._get_probablities(qubits, outcome, outcome_prob, probs)
if decimals is not None:
for key, value in probs.items():
probs[key] = round(value, decimals)
return probs
def reset(self, qargs: list | None = None) -> StabilizerState:
"""Reset state or subsystems to the 0-state.
Args:
qargs (list or None): subsystems to reset, if None all
subsystems will be reset to their 0-state
(Default: None).
Returns:
StabilizerState: the reset state.
Additional Information:
If all subsystems are reset this will return the ground state
on all subsystems. If only some subsystems are reset this
function will perform a measurement on those subsystems and
evolve the subsystems so that the collapsed post-measurement
states are rotated to the 0-state. The RNG seed for this
sampling can be set using the :meth:`seed` method.
"""
# Resetting all qubits does not require sampling or RNG
if qargs is None:
return StabilizerState(Clifford(np.eye(2 * self.clifford.num_qubits)))
randbits = self._rng.integers(2, size=len(qargs))
ret = self.copy()
for bit, qubit in enumerate(qargs):
# Apply measurement and get classical outcome
outcome = ret._measure_and_update(qubit, randbits[bit])
# Use the outcome to apply X gate to any qubits left in the
# |1> state after measure, then discard outcome.
if outcome == 1:
_append_x(ret.clifford, qubit)
return ret
def measure(self, qargs: list | None = None) -> tuple:
"""Measure subsystems and return outcome and post-measure state.
Note that this function uses the QuantumStates internal random
number generator for sampling the measurement outcome. The RNG
seed can be set using the :meth:`seed` method.
Args:
qargs (list or None): subsystems to sample measurements for,
if None sample measurement of all
subsystems (Default: None).
Returns:
tuple: the pair ``(outcome, state)`` where ``outcome`` is the
measurement outcome string label, and ``state`` is the
collapsed post-measurement stabilizer state for the
corresponding outcome.
"""
if qargs is None:
qargs = range(self.clifford.num_qubits)
randbits = self._rng.integers(2, size=len(qargs))
ret = self.copy()
outcome = ""
for bit, qubit in enumerate(qargs):
outcome = str(ret._measure_and_update(qubit, randbits[bit])) + outcome
return outcome, ret
def sample_memory(self, shots: int, qargs: None | list = None) -> np.ndarray:
"""Sample a list of qubit measurement outcomes in the computational basis.
Args:
shots (int): number of samples to generate.
qargs (None or list): subsystems to sample measurements for,
if None sample measurement of all
subsystems (Default: None).
Returns:
np.array: list of sampled counts if the order sampled.
Additional Information:
This function implements the measurement :meth:`measure` method.
The seed for random number generator used for sampling can be
set to a fixed value by using the stats :meth:`seed` method.
"""
memory = []
for _ in range(shots):
# copy the StabilizerState since measure updates it
stab = self.copy()
memory.append(stab.measure(qargs)[0])
return memory
# -----------------------------------------------------------------------
# Helper functions for calculating the measurement
# -----------------------------------------------------------------------
def _measure_and_update(self, qubit, randbit):
"""Measure a single qubit and return outcome and post-measure state.
Note that this function uses the QuantumStates internal random
number generator for sampling the measurement outcome. The RNG
seed can be set using the :meth:`seed` method.
Note that stabilizer state measurements only have three probabilities:
(p0, p1) = (0.5, 0.5), (1, 0), or (0, 1)
The random case happens if there is a row anti-commuting with Z[qubit]
"""
num_qubits = self.clifford.num_qubits
clifford = self.clifford
stab_x = self.clifford.stab_x
# Check if there exists stabilizer anticommuting with Z[qubit]
# in this case the measurement outcome is random
z_anticommuting = np.any(stab_x[:, qubit])
if z_anticommuting == 0:
# Deterministic outcome - measuring it will not change the StabilizerState
aux_pauli = Pauli(num_qubits * "I")
for i in range(num_qubits):
if clifford.x[i][qubit]:
aux_pauli = self._rowsum_deterministic(clifford, aux_pauli, i + num_qubits)
outcome = aux_pauli.phase
return outcome
else:
# Non-deterministic outcome
outcome = randbit
p_qubit = np.min(np.nonzero(stab_x[:, qubit]))
p_qubit += num_qubits
# Updating the StabilizerState
for i in range(2 * num_qubits):
# the last condition is not in the AG paper but we seem to need it
if (clifford.x[i][qubit]) and (i != p_qubit) and (i != (p_qubit - num_qubits)):
self._rowsum_nondeterministic(clifford, i, p_qubit)
clifford.destab[p_qubit - num_qubits] = clifford.stab[p_qubit - num_qubits].copy()
clifford.x[p_qubit] = np.zeros(num_qubits)
clifford.z[p_qubit] = np.zeros(num_qubits)
clifford.z[p_qubit][qubit] = True
clifford.phase[p_qubit] = outcome
return outcome
@staticmethod
def _phase_exponent(x1, z1, x2, z2):
"""Exponent g of i such that Pauli(x1,z1) * Pauli(x2,z2) = i^g Pauli(x1+x2,z1+z2)"""
# pylint: disable=invalid-name
phase = (x2 * z1 * (1 + 2 * z2 + 2 * x1) - x1 * z2 * (1 + 2 * z1 + 2 * x2)) % 4
if phase < 0:
phase += 4 # now phase in {0, 1, 3}
if phase == 2:
raise QiskitError("Invalid rowsum phase exponent in measurement calculation.")
return phase
@staticmethod
def _rowsum(accum_pauli, accum_phase, row_pauli, row_phase):
"""Aaronson-Gottesman rowsum helper function"""
newr = 2 * row_phase + 2 * accum_phase
for qubit in range(row_pauli.num_qubits):
newr += StabilizerState._phase_exponent(
row_pauli.x[qubit], row_pauli.z[qubit], accum_pauli.x[qubit], accum_pauli.z[qubit]
)
newr %= 4
if (newr != 0) & (newr != 2):
raise QiskitError("Invalid rowsum in measurement calculation.")
accum_phase = int(newr == 2)
accum_pauli.x ^= row_pauli.x
accum_pauli.z ^= row_pauli.z
return accum_pauli, accum_phase
@staticmethod
def _rowsum_nondeterministic(clifford, accum, row):
"""Updating StabilizerState Clifford in the
non-deterministic rowsum calculation.
row and accum are rows in the StabilizerState Clifford."""
row_phase = clifford.phase[row]
accum_phase = clifford.phase[accum]
z = clifford.z
x = clifford.x
row_pauli = Pauli((z[row], x[row]))
accum_pauli = Pauli((z[accum], x[accum]))
accum_pauli, accum_phase = StabilizerState._rowsum(
accum_pauli, accum_phase, row_pauli, row_phase
)
clifford.phase[accum] = accum_phase
x[accum] = accum_pauli.x
z[accum] = accum_pauli.z
@staticmethod
def _rowsum_deterministic(clifford, aux_pauli, row):
"""Updating an auxilary Pauli aux_pauli in the
deterministic rowsum calculation.
The StabilizerState itself is not updated."""
row_phase = clifford.phase[row]
accum_phase = aux_pauli.phase
accum_pauli = aux_pauli
row_pauli = Pauli((clifford.z[row], clifford.x[row]))
accum_pauli, accum_phase = StabilizerState._rowsum(
accum_pauli, accum_phase, row_pauli, row_phase
)
aux_pauli = accum_pauli
aux_pauli.phase = accum_phase
return aux_pauli
# -----------------------------------------------------------------------
# Helper functions for calculating the probabilities
# -----------------------------------------------------------------------
def _get_probablities(self, qubits, outcome, outcome_prob, probs):
"""Recursive helper function for calculating the probabilities"""
qubit_for_branching = -1
ret = self.copy()
for i in range(len(qubits)):
qubit = qubits[len(qubits) - i - 1]
if outcome[i] == "X":
is_deterministic = not any(ret.clifford.stab_x[:, qubit])
if is_deterministic:
single_qubit_outcome = ret._measure_and_update(qubit, 0)
if single_qubit_outcome:
outcome[i] = "1"
else:
outcome[i] = "0"
else:
qubit_for_branching = i
if qubit_for_branching == -1:
str_outcome = "".join(outcome)
probs[str_outcome] = outcome_prob
return
for single_qubit_outcome in range(0, 2):
new_outcome = outcome.copy()
if single_qubit_outcome:
new_outcome[qubit_for_branching] = "1"
else:
new_outcome[qubit_for_branching] = "0"
stab_cpy = ret.copy()
stab_cpy._measure_and_update(
qubits[len(qubits) - qubit_for_branching - 1], single_qubit_outcome
)
stab_cpy._get_probablities(qubits, new_outcome, 0.5 * outcome_prob, probs)
|
https://github.com/AlbertoVari/QC-Grover
|
AlbertoVari
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
import math
# importing Qiskit
from qiskit import Aer, transpile, execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.providers.ibmq import least_busy
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler
from qiskit.primitives import Estimator
from qiskit.circuit import ParameterVector
from qiskit_ibm_provider import IBMProvider
from qiskit_ibm_provider import least_busy
import qiskit_ibm_provider
provider = qiskit_ibm_provider.IBMProvider()
# --> simulator backend = provider.get_backend('ibmq_qasm_simulator')
n = 2
grover_circuit = QuantumCircuit(n)
def initialize_s(qc, qubits):
"""Apply a H-gate to 'qubits' in qc"""
for q in qubits:
qc.h(q)
return qc
grover_circuit = initialize_s(grover_circuit, [0,1])
print(grover_circuit)
grover_circuit.cz(0,1) # Oracle
print("Oracle :",end='\n')
print(grover_circuit)
# Diffusion operator (U_s)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
print("Oracle + Diffusion :",end='\n')
print(grover_circuit)
sv_sim = Aer.get_backend('statevector_simulator')
result = sv_sim.run(grover_circuit).result()
statevec = result.get_statevector()
grover_circuit.measure_all()
# display current supported backends
print("IBMQ Q system ready with almost 5 qubits",end='\n')
print(provider.backends(min_num_qubits=5, simulator=False, operational=True))
small_devices = provider.backends(min_num_qubits=5, simulator=False, operational=True)
backend = least_busy(small_devices)
print("BACKEND : ",backend)
#running the job
job_exp = execute(grover_circuit, backend, shots=2048)
result_exp = job_exp.result()
# Show the results
print('Counts: ', result_exp.get_counts(grover_circuit))
|
https://github.com/qiskit-community/prototype-zne
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("XZ")
print(f" > Observable: {observable.paulis}")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
print(f">>> {job.job_id()}")
print(f">>> {job.status()}")
result = job.result()
print(f">>> {result}")
expval = result.values[0]
metadatum = result.metadata[0]
print(f" > Expectation value: {expval}")
print(f" > Metadata: {metadatum}")
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job = estimator.run(circuits, observables)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f" > Observables: {[obs.paulis for obs in observables]}")
print(f" > Expectation values: {result.values.tolist()}")
print(f" > Metadata: {result.metadata}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job_0 = estimator.run(circuits[0], observables[0])
job_1 = estimator.run(circuits[1], observables[1])
result_0 = job_0.result()
result_1 = job_1.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f" > Observables: {[obs.paulis for obs in observables]}")
print(f" > Expectation values [0]: {result_0.values.tolist()[0]}")
print(f" > Metadata [0]: {result_0.metadata[0]}")
print(f" > Expectation values [1]: {result_1.values.tolist()[0]}")
print(f" > Metadata [1]: {result_1.metadata[0]}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
observable = SparsePauliOp("ZI")
parameter_values = [0, 1, 2, 3, 4, 5]
job = estimator.run(circuit, observable, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Parameter values: {parameter_values}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
estimator = Estimator(options={"shots": 2048}) # Defaults !!!
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
observable = SparsePauliOp("XZ")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
observable = SparsePauliOp("XZ")
job = estimator.run(circuit, observable, shots=1024) # Job-only !!!
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.primitives import BackendEstimator
from qiskit.providers.fake_provider import FakeNairobi # Bring the noise!
backend = FakeNairobi()
estimator = BackendEstimator(backend)
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
observable = SparsePauliOp("XZ")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f" > Observable: {observable.paulis}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Standard Qiskit könyvtárak importálása
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# IBM Quantum fiók betöltése
service = QiskitRuntimeService(channel="ibm_quantum")
from qiskit import QuantumCircuit, execute, Aer
# quantumáramkör létrehozása
circuit = QuantumCircuit(1)
# Get the simulator backend
simulator = Aer.get_backend('qasm_simulator')
def apply_hadamard_and_measure(circuit, simulator,hanyszor):
#Hadamard kapuk alkalmazása a qbitekre
for i in range(hanyszor):
circuit.h(0)
# qubit megmérése
circuit.measure_all()
# szimulálás
job = execute(circuit, simulator, shots=1024)
result = job.result()
counts = result.get_counts(circuit)
return counts
#Más eredményt kapunk ha két kapuk között mérünk. Szuperpozíciót megzavarja a mérés.
# Függvény hívása a Hadamard kapu alkalmazásához és méréshez, majd az eredmények kiírása
counts1 = apply_hadamard_and_measure(circuit, simulator, 2)
print("Eredmények a két H kapu után:")
print(counts1)
# Függvény újra hívása a Hadamard kapu alkalmazásához és méréshez, majd az eredmények kiírása
counts2 = apply_hadamard_and_measure(circuit, simulator, 1)
print("Eredmények az első H kapu után:")
print(counts2)
# Függvény újra hívása a Hadamard kapu alkalmazásához és méréshez, majd az eredmények kiírása
counts3 = apply_hadamard_and_measure(circuit, simulator, 1)
print("Eredmények a második H kapu után:")
print(counts3)
import numpy as np
from qiskit.visualization import plot_state_city
# Kvantumáramkör létrehozása 2 qubittel
circuit = QuantumCircuit(2)
# Pauli-X, Y, Z kapuk alkalmazása a qubitekre
circuit.x(0)
circuit.y(0)
circuit.z(1)
# Qubit mérése
circuit.measure_all()
stateVsim = Aer.get_backend('statevector_simulator')
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, stateVsim, shots=1024)
eredmeny = feladat.result()
stateVector = eredmeny.get_statevector()
print(stateVector)
plot_state_city(stateVector)
from qiskit import QuantumCircuit, Aer, transpile
def set_quantum_state(qc, state):
# Validate input state
valid_states = [0, 1, 2, 3]
if state not in valid_states:
raise ValueError("Invalid state code. Choose from 0, 1, 2, or 3.")
# Quantum circuit creation
# Set the state according to the given state code
if state == 0:
qc.initialize([1, 0, 0, 0], [0, 1]) # |00>
elif state == 1:
qc.initialize([0, 1, 0, 0], [0, 1]) # |01>
elif state == 2:
qc.initialize([0, 0, 1, 0], [0, 1]) # |10>
elif state == 3:
qc.initialize([0, 0, 0, 1], [0, 1]) # |11>
# Transpile the circuit
transpiled_circuit = transpile(qc, Aer.get_backend('statevector_simulator'))
# Run the transpiled circuit
result = Aer.get_backend('statevector_simulator').run(transpiled_circuit).result()
statevector = result.get_statevector()
return statevector
# Example usage:
qc = QuantumCircuit(2)
state = 3 # Set to the |10> state, for example
result_statevector = set_quantum_state(qc, state)
print("Result state vector:", result_statevector)
from qiskit import Aer, transpile
def printStateVector(circuit):
simulator = Aer.get_backend('statevector_simulator')
# Transpile the circuit
transpiled_circuit = transpile(circuit, simulator)
# Run the transpiled circuit
result = simulator.run(transpiled_circuit).result()
statevector = result.get_statevector()
rounded_statevector = np.round(statevector, decimals=3)
print("Rounded State Vector:", rounded_statevector)
# Exercise 2.2 QCCEA
from qiskit import QuantumCircuit, Aer, execute
from qiskit import QuantumCircuit, Aer, transpile, assemble
for i in range (0,4):
print(f"\nKezdő állapot: {i}")
# Szimulátor definiálása
szimulator = Aer.get_backend('qasm_simulator')
# HXH=Z----------------------------------------------------------------------
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
# Hadamard és Pauli-X kapu alkalmazása a qubitre
circuit.h(0)
circuit.x(0)
circuit.h(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"HXH:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
#--------------------------------------------
circuit = QuantumCircuit(2)
# Pauli-Z kapu alkalmazása a qubitre
set_quantum_state(circuit,i)
circuit.z(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"Z:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
# HYH=-Y---------------------------------------------------------------------
# Hadamard kapu alkalmazása a qubitre
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
circuit.h(0)
circuit.y(0)
circuit.h(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"HYH:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
#--------------------------------------------
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
# Kapuk alkalmazása
circuit.y(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"-Y:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
# HZH=X---------------------------------------------------------------------
# Kapuk alkalmazása
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
circuit.h(0)
circuit.z(0)
circuit.h(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"HZH:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
#--------------------------------------------
circuit = QuantumCircuit(2)
set_quantum_state(circuit,i)
# HZH=X
circuit.x(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, szimulator, shots=1)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(f"X:{counts}")
#eredmény kiiratása állapotvectorokkal
printStateVector(circuit)
print(circuit)
# Exercise 2.1 QCCEA - HH=I
# Kvantumáramkör létrehozása egyetlen qubittel
circuit = QuantumCircuit(2)
set_quantum_state(circuit,2)
circuit.h(0)
circuit.h(0)
# Qubit mérése
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, simulator, shots=1024)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(counts)
circuit.i(0)
# Qubit mérése
circuit.measure_all()
feladat = execute(circuit, szimulátor, shots=1024)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(counts)
# Exercise 2.1 QCCEA HH=I
# Kvantumáramkör létrehozása egyetlen qubittel
circuit = QuantumCircuit(2)
circuit.x(0)
# Qubit mérése
circuit.measure_all()
circuit.swap(1,0)
circuit.measure_all()
# Áramkör futtatása a szimulátoron
feladat = execute(circuit, simulator, shots=1024)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(counts)
#3 CNOT = SWAP (in this configuration)
circuit.cx(0,1)
circuit.cx(1,0)
circuit.cx(0,1)
# Qubit mérése
circuit.measure_all()
feladat = execute(circuit, szimulátor, shots=1024)
eredmény = feladat.result()
counts = eredmény.get_counts(circuit)
print(counts)
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import time
import itertools
import numpy as np
from scipy.optimize import minimize, basinhopping
from qiskit import *
from qiskit.quantum_info import Statevector
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA
from qiskit.opflow.state_fns import StateFn, CircuitStateFn
from qiskit.providers.aer import StatevectorSimulator, AerSimulator
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from matplotlib.colors import BoundaryNorm
from modules.utils import *
%matplotlib inline
cmap = plt.get_cmap("plasma") #'viridis'
import qiskit
#%matplotlib inline
print(qiskit.__version__)
### Preliminaries
L = 5
num_trash = 2
logspace_size=50
name = f'VQE_Ising_L5_anti_-1_50x50_1e-3' # _1e-3 # name of the data produced by this notebook
filename = "data/params_" + name # name of the data file that is used
L = 5
anti = -1.
VQE_params = np.load(filename + ".npz", allow_pickle=True)
gx_list = VQE_params['gx_list']
gz_list = VQE_params['gz_list']
opt_params = VQE_params['opt_params']
gx_vals = np.unique(gx_list)
gz_vals = np.unique(gz_list)
mag = QMag(L,anti) #magnetization operator (Qiskit)
Smag = Mag(L,anti) #magnetization operator (numpy)
# the ~ is the adjoint, but also it turns the is_measurement attribute to True
~StateFn(mag)
# state is technically a circuit, that prepares the ground state via VQE circuit
#state.draw() # uncomment to see, but is very long
Qen=np.zeros(len(opt_params)); Sen=np.zeros(len(opt_params)) #energies
Qmags=np.zeros(len(opt_params)); Smags=np.zeros(len(opt_params)) #magnetizations
load = True
if load:
temp = np.load(filename + "_mags-Es.npz",allow_pickle=True)
Qmags = temp["Qmags"]
Qen = temp["Qen"]
Sen = temp["Sen"]
Smags = temp["Smags"]
if not load:
for j in range(len(opt_params)):
gx = gx_list[j]
gz = gz_list[j]
H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op
state = init_vqe(opt_params[j], L=L)
StateFn(state)
meas_outcome = ~StateFn(mag) @ StateFn(state)
Qmags[j] = meas_outcome.eval()
e_outcome = ~StateFn(H) @ StateFn(state)
Qen[j] = e_outcome.eval()
init_state, E, ham = ising_groundstate(L, anti, np.float(gx), np.float(gz))
Sen[j] = E
Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results
np.savez(filename + "_mags-Es",Qmags=Qmags, Qen=Qen, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization
fig,ax = plt.subplots(figsize=(8,5))
cmap = plt.get_cmap("plasma") #'viridis'
im = ax.pcolormesh(gz_vals, gx_vals, abs(Smags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Magnetization ED L %.0f anti %.0f" %(L, anti),fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
fig,ax = plt.subplots(figsize=(8,5))
cmap = plt.get_cmap("plasma") #'viridis'
im = ax.pcolormesh(gz_vals, gx_vals, abs(Qmags).reshape(len(gz_vals),len(gx_vals)), cmap=cmap)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
fig,ax = plt.subplots(figsize=(8,5))
cmap = plt.get_cmap("plasma") #'viridis'
im = ax.pcolormesh(gz_vals, gx_vals, Sen.reshape(len(gz_vals),len(gx_vals)) - Qen.reshape(len(gz_vals),len(gx_vals)), cmap=cmap)
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
plt.xscale("log")
plt.yscale("log")
ax.set_title("Difference in energy L %.0f anti %.0f" %(L, anti),fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
##############################################################################
### II - Training ###########################################################
##############################################################################
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
thetas = np.random.uniform(0, 2*np.pi, 2*L+2) # initial parameters without feature encoding
# thetas = np.random.uniform(0, 2*np.pi, (2*L+2, 2)) # initial parameters with feature encoding
# linear entangler (as in scales linearly with trash qubits)
def get_entangler_map(L, num_trash, i_permut=1):
result = []
nums = list(range(L)) # here was the problem, it doesnt like when list elements are taken from numpy
nums_compressed = nums.copy()[:L-num_trash]
nums_trash = nums.copy()[-num_trash:]
#print(nums, nums_compressed, nums_trash)
# combine all trash qubits with themselves
for trash_q in nums_trash[:-1]:
result.append((trash_q+1,trash_q))
# combine each of the trash qubits with every n-th
repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly
for i in range(L-num_trash):
result.append((repeated[i_permut + i], nums_compressed[i]))
return result
def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz"):
entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)]
circ = qiskit.circuit.library.TwoLocal(L,
parametrized_gate,
entangling_gate,
entanglement,
reps=num_trash,
insert_barriers=insert_barriers,
skip_final_rotation_layer=True
).assign_parameters(thetas[:-num_trash])
if insert_barriers: circ.barrier()
for i in range(num_trash):
circ.ry(thetas[L-i-1], L-i-1)
#circ.ry(circuit.Parameter(f'θ{i}'), L-i-1)
return circ
def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True):
qreg = QuantumRegister(L, 'q')
creg = ClassicalRegister(num_trash, 'c')
circ = QuantumCircuit(qreg, creg)
circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=True)#.assign_parameters(thetas) # difference to bind?
if measurement:
for i in range(num_trash):
circ.measure(qreg[L-i-1], creg[i])
if init_state is not None:
if vqe:
circ = init_vqe(init_state,L=L) + circ
else:
circ.initialize(init_state, qreg)
return circ
def feature_encoding(thetas, x):
""" thetas: parameters to be optimized, x: Ising model parameter (eg. field) """
new_thetas = []
thetas = thetas.reshape((-1,2))
for theta in thetas:
new_thetas.append(theta[0] * x + theta[1])
return new_thetas
idx = 30
num_trash = 2
J, gx, gz = -1., gx_list[idx], gz_list[idx] # Ising parameters for which ground state should be compressed
phi = opt_params[idx] # train on smallest lambda ;; this may grammatically be confusing, init_state = dictionary with unsorted parameters
def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100):
circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe)
# Execute the circuit on the qasm simulator.
job_sim = execute(circ, backend_sim, shots=shots, seed_simulator=123, seed_transpiler=234) # fix seed to make it reproducible
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
# print(counts)
# mems = result_sim.get_memory(circ)
# print(mems)
return counts
run_circuit(thetas, L, num_trash, phi)['11']
# translate to Rikes naming
phis = opt_params
gxs = gx_list
gzs = gz_list
def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0):
""" Optimizes circuit """
if vqe:
init_state = phis[p]
else:
J, gx, gz = p
init_state, _ = ising_groundstate(L, J, gx, gz)
if param_encoding: thetas = feature_encoding(thetas, x)
out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots)
cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0)
return cost/shots
def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0):
""" Optimizes circuit """
cost = 0.
n_samples = len(ising_params)
for i, p in enumerate(ising_params):
if param_encoding:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i])
else:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding)
return cost/n_samples
def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None):
if thetas is None:
n_params = (2*L+2)*2 if param_encoding else (2*L+2)
thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding
print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)))
counts, values, accepted = [], [], []
def store_intermediate_result(eval_count, parameters, mean, std, ac):
# counts.append(eval_count)
values.append(mean)
accepted.append(ac)
# Initialize optimizer
if pick_optimizer == "cobyla":
optimizer = COBYLA(maxiter=max_iter, tol=0.0001)
if pick_optimizer == "adam" or pick_optimizer == "ADAM":
optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter)
# optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08)
if pick_optimizer == "spsa" or pick_optimizer == None:
optimizer = SPSA(maxiter=max_iter,
#blocking=True,
callback=store_intermediate_result,
#learning_rate=1e-1,
#perturbation=0.4
) # recommended from qiskit (first iteraction takes quite long)
# to reduce time figure out optimal learning rate and perturbation in advance
start_time = time.time()
ret = optimizer.optimize(
num_vars=len(thetas),
objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)),
initial_point=thetas
)
print("Time: {:.5f} sec".format(time.time()-start_time))
print(ret)
return ret[0], values, accepted
x,y = np.meshgrid(gx_vals, gz_vals)
def run_inference(thetas, shots=1000, L=5):
points = 50
J = -1.0
x,y = np.meshgrid(gx_vals, gz_vals)
cost = np.zeros((len(gx_vals) * len(gz_vals)))
Smags = np.zeros((len(gx_vals) * len(gz_vals)))
shots = 1000
for i,p in enumerate(list(zip(gxs, gzs))):
cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots)
cost = cost.reshape((len(gx_vals), len(gz_vals)))
return cost
cmap = plt.get_cmap("plasma")
def plot_result(cost):
fig,axs = plt.subplots(ncols=2,figsize=(15,5))
nbins=100
ax = axs[0]
im = ax.pcolormesh(x, y, cost, cmap=cmap, shading="auto")
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_title(f"Loss",fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
for p in params:
gz = gz_list[p]
gx = gx_list[p]
ax.plot(gz,gx,"o",label="training",color="cyan")
ax = axs[1]
im = ax.pcolormesh(gz_vals, gx_vals, Qmags.reshape(len(gz_vals),len(gx_vals)), cmap=cmap, shading="auto")
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=20)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_title("Magnetization VQE L %.0f anti %.0f" %(L, anti),fontsize=20)
ax.set_xlabel(r"$g_z$",fontsize=24)
ax.set_ylabel(r"$g_x$",fontsize=24)
ax.tick_params(labelsize=20)
#reset random seed
#np.random.seed(123)
#from qiskit.utils import algorithm_globals
#algorithm_globals.random_seed = 123
np.intersect1d(
np.intersect1d(np.where(gx_list > 5e-2),np.where(1e-1 > gx_list)),
np.intersect1d(np.where(gz_list > 5e-2),np.where(1e-1 > gz_list))
)
paramss =[
[0], # train on bottom left point
]
for i,params in enumerate(paramss):
print(f"{i} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}")
thetass = [None] * len(paramss)
losss = [None] * len(paramss)
costs = [None] * len(paramss)
for i,params in enumerate(paramss):
print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}")
thetas, loss, accepted = optimize(params, max_iter=50, L=5) #, pick_optimizer="adam")
thetass[i], losss[i] = thetas, loss
plt.plot(loss)
cost = run_inference(thetas)
costs[i] = cost
filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states-01"
np.savez(filename2, losss = losss, costs = costs, thetass = thetass)
for i,params in enumerate(paramss):
print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}")
plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i])
plt.show()
for i,params in enumerate(paramss):
print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}")
thetas, loss, accepted = optimize(params, max_iter=50, L=5) #, pick_optimizer="adam")
thetass[i], losss[i] = thetas, loss
plt.plot(loss)
cost = run_inference(thetas)
costs[i] = cost
filename2 = "data/" + name + "_thetas-loss-cost_vary-training-states-02"
np.savez(filename2, losss = losss, costs = costs, thetass = thetass)
for i,params in enumerate(paramss):
print(f"{i+1} / {len(paramss)} - params (gz, gx) in {[(gzs[p], gxs[p]) for p in params]}")
plot_result(np.load(filename2 + ".npz",allow_pickle=True)["costs"][i])
plt.show()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Test qclib.gate.mc_gate """
from unittest import TestCase
import numpy as np
import qiskit
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.quantum_info import Operator
import qclib.util
from qclib.gates.ldmcu import Ldmcu
from qclib.gates.mcu import MCU
class TestLinearU2(TestCase):
def _get_result_unitary(self, unitary, n_ctrl_base):
exponent = n_ctrl_base - 1
param = (2**exponent - 1) / 2**exponent
values, vectors = np.linalg.eig(unitary)
gate = (
np.power(values[0] + 0j, param) * vectors[:, [0]] @ vectors[:, [0]].conj().T
)
gate = (
gate
+ np.power(values[1] + 0j, param)
* vectors[:, [1]]
@ vectors[:, [1]].conj().T
)
return gate
def test_get_num_qubits(self):
error = 0.1
u1 = np.array([[0, 1], [1, 0]])
ldmcu_approx = MCU(u1, num_controls=10, error=error)
self.assertTrue(ldmcu_approx._get_num_base_ctrl_qubits(u1, error), 4)
def test_mcz(self):
error = 0.1
u = np.array([[1, 0], [0, -1]])
ldmcu_approx_test = MCU(u, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(u, error)
controls = QuantumRegister(base_ctrl_qubits)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
N = len(controls)
for i in range(N):
circuit.x(i)
MCU.mcu(circuit, u, controls, target, error)
state = qclib.util.get_state(circuit)
res_u = self._get_result_unitary(u, base_ctrl_qubits)
self.assertTrue(np.isclose(state[2**N - 1], res_u[0, 0]))
self.assertTrue(np.isclose(state[2 ** (N + 1) - 1], res_u[1, 0]))
controls = QuantumRegister(base_ctrl_qubits + 2)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
N = len(controls)
for i in range(N):
circuit.x(i)
MCU.mcu(circuit, u, controls, target, error)
state = qclib.util.get_state(circuit)
res_u = self._get_result_unitary(u, base_ctrl_qubits)
self.assertTrue(np.isclose(state[2**N - 1], res_u[0, 0]))
self.assertTrue(np.isclose(state[2 ** (N + 1) - 1], res_u[1, 0]))
def test_mcx(self):
error = 0.1
u = np.array([[0, 1], [1, 0]])
ldmcu_approx_test = MCU(u, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(u, error)
controls = QuantumRegister(base_ctrl_qubits)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
N = len(controls)
for i in range(N):
circuit.x(i)
MCU.mcu(circuit, u, controls, target, error)
state = qclib.util.get_state(circuit)
res_u = self._get_result_unitary(u, base_ctrl_qubits)
self.assertTrue(np.isclose(state[2**N - 1], res_u[0, 0]))
self.assertTrue(np.isclose(state[2 ** (N + 1) - 1], res_u[1, 0]))
controls = QuantumRegister(base_ctrl_qubits + 2)
target = QuantumRegister(1)
circuit = qiskit.QuantumCircuit(controls, target)
N = len(controls)
for i in range(N):
circuit.x(i)
MCU.mcu(circuit, u, controls, target, error)
state = qclib.util.get_state(circuit)
res_u = self._get_result_unitary(u, base_ctrl_qubits)
self.assertTrue(np.isclose(state[2**N - 1], res_u[0, 0]))
self.assertTrue(np.isclose(state[2 ** (N + 1) - 1], res_u[1, 0]))
def test_mcz_cnot_count(self):
error = 0.01
u = np.array([[1, 0], [0, -1]])
ldmcu_approx_test = MCU(u, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(u, error)
for n_controls in range(base_ctrl_qubits + 60, base_ctrl_qubits + 62):
controls = QuantumRegister(n_controls)
target = QuantumRegister(1)
circuit_approx = qiskit.QuantumCircuit(controls, target)
MCU.mcu(circuit_approx, u, controls, target, error)
cnot_approx = qclib.util.get_cnot_count(circ=circuit_approx)
controls = QuantumRegister(n_controls)
target = QuantumRegister(1)
circuit_og = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(circuit_og, u, controls, target)
cnot_og = qclib.util.get_cnot_count(circ=circuit_og)
self.assertLessEqual(cnot_approx, cnot_og)
def test_mcx_cnot_count(self):
error = 0.01
u = np.array([[0, 1], [1, 0]])
ldmcu_approx_test = MCU(u, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(u, error)
for n_controls in range(base_ctrl_qubits + 60, base_ctrl_qubits + 62):
controls = QuantumRegister(n_controls)
target = QuantumRegister(1)
circuit_approx = qiskit.QuantumCircuit(controls, target)
MCU.mcu(circuit_approx, u, controls, target, error)
cnot_approx = qclib.util.get_cnot_count(circ=circuit_approx)
controls = QuantumRegister(n_controls)
target = QuantumRegister(1)
circuit_og = qiskit.QuantumCircuit(controls, target)
Ldmcu.ldmcu(circuit_og, u, controls, target)
cnot_og = qclib.util.get_cnot_count(circ=circuit_og)
self.assertLessEqual(cnot_approx, cnot_og)
def test_to_compare_ldmcu_and_ldmcu_approx(self):
unitary = np.array([[0, 1], [1, 0]])
error = 1e-2
ldmcu_approx_test = MCU(unitary, num_controls=100, error=error)
base_ctrl_qubits = ldmcu_approx_test._get_num_base_ctrl_qubits(unitary, error)
controls = QuantumRegister(base_ctrl_qubits)
target = QuantumRegister(1)
ldmcu_circ = QuantumCircuit(controls, target)
Ldmcu.ldmcu(ldmcu_circ, unitary, controls, target)
ldmcu_approx_circ = QuantumCircuit(controls, target)
MCU.mcu(ldmcu_approx_circ, unitary, controls, target, error)
ldmcu_op = Operator(ldmcu_circ).data
ldmcu_approx_op = Operator(ldmcu_approx_circ).data
# absolute(a - b) <= (atol + r_tol * absolute(b)
self.assertTrue(np.allclose(ldmcu_op, ldmcu_approx_op, atol=error))
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
# transpile_parallel.py
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_transpiler_service.transpiler_service import TranspilerService
from qiskit_serverless import get_arguments, save_result, distribute_task, get
from qiskit_ibm_runtime import QiskitRuntimeService
from timeit import default_timer as timer
@distribute_task(target={"cpu": 2})
def transpile_parallel(circuit: QuantumCircuit, config):
"""Distributed transpilation for an abstract circuit into an ISA circuit for a given backend."""
transpiled_circuit = config.run(circuit)
return transpiled_circuit
# Get program arguments
arguments = get_arguments()
circuits = arguments.get("circuits")
backend_name = arguments.get("backend_name")
# Get backend
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.get_backend(backend_name)
# Define Configs
optimization_levels = [1,2,3]
pass_managers = [generate_preset_pass_manager(optimization_level=level, backend=backend) 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="false", optimization_level=3,), 'ai': True, 'optimization_level': 3}
]
configs = pass_managers + transpiler_services
# Start process
print("Starting timer")
start = timer()
# run distributed tasks as async function
# we get task references as a return type
sample_task_references = []
for circuit in circuits:
sample_task_references.append([transpile_parallel(circuit, config) for config in configs])
# now we need to collect results from task references
results = get([task for subtasks in sample_task_references for task in subtasks])
end = timer()
# Record execution time
execution_time_serverless = end-start
print("Execution time: ", execution_time_serverless)
save_result({
"transpiled_circuits": results,
"execution_time" : execution_time_serverless
})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from qiskit.utils import algorithm_globals
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, MinMaxScaler
from qiskit_machine_learning.algorithms.classifiers import VQC
from IPython.display import clear_output
algorithm_globals.random_seed = 42
sampler1 = Sampler()
sampler2 = Sampler()
num_samples = 40
num_features = 2
features = 2 * algorithm_globals.random.random([num_samples, num_features]) - 1
labels = 1 * (np.sum(features, axis=1) >= 0) # in { 0, 1}
features = MinMaxScaler().fit_transform(features)
features.shape
features[0:5, :]
labels = OneHotEncoder(sparse=False).fit_transform(labels.reshape(-1, 1))
labels.shape
labels[0:5, :]
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=30, random_state=algorithm_globals.random_seed
)
train_features.shape
def plot_dataset():
plt.scatter(
train_features[np.where(train_labels[:, 0] == 0), 0],
train_features[np.where(train_labels[:, 0] == 0), 1],
marker="o",
color="b",
label="Label 0 train",
)
plt.scatter(
train_features[np.where(train_labels[:, 0] == 1), 0],
train_features[np.where(train_labels[:, 0] == 1), 1],
marker="o",
color="g",
label="Label 1 train",
)
plt.scatter(
test_features[np.where(test_labels[:, 0] == 0), 0],
test_features[np.where(test_labels[:, 0] == 0), 1],
marker="o",
facecolors="w",
edgecolors="b",
label="Label 0 test",
)
plt.scatter(
test_features[np.where(test_labels[:, 0] == 1), 0],
test_features[np.where(test_labels[:, 0] == 1), 1],
marker="o",
facecolors="w",
edgecolors="g",
label="Label 1 test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.plot([1, 0], [0, 1], "--", color="black")
plot_dataset()
plt.show()
maxiter = 20
objective_values = []
# callback function that draws a live plot when the .fit() method is called
def callback_graph(_, objective_value):
clear_output(wait=True)
objective_values.append(objective_value)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
stage1_len = np.min((len(objective_values), maxiter))
stage1_x = np.linspace(1, stage1_len, stage1_len)
stage1_y = objective_values[:stage1_len]
stage2_len = np.max((0, len(objective_values) - maxiter))
stage2_x = np.linspace(maxiter, maxiter + stage2_len - 1, stage2_len)
stage2_y = objective_values[maxiter : maxiter + stage2_len]
plt.plot(stage1_x, stage1_y, color="orange")
plt.plot(stage2_x, stage2_y, color="purple")
plt.show()
plt.rcParams["figure.figsize"] = (12, 6)
original_optimizer = COBYLA(maxiter=maxiter)
ansatz = RealAmplitudes(num_features)
initial_point = np.asarray([0.5] * ansatz.num_parameters)
original_classifier = VQC(
ansatz=ansatz, optimizer=original_optimizer, callback=callback_graph, sampler=sampler1
)
original_classifier.fit(train_features, train_labels)
print("Train score", original_classifier.score(train_features, train_labels))
print("Test score ", original_classifier.score(test_features, test_labels))
original_classifier.save("vqc_classifier.model")
loaded_classifier = VQC.load("vqc_classifier.model")
loaded_classifier.warm_start = True
loaded_classifier.neural_network.sampler = sampler2
loaded_classifier.optimizer = COBYLA(maxiter=80)
loaded_classifier.fit(train_features, train_labels)
print("Train score", loaded_classifier.score(train_features, train_labels))
print("Test score", loaded_classifier.score(test_features, test_labels))
train_predicts = loaded_classifier.predict(train_features)
test_predicts = loaded_classifier.predict(test_features)
# return plot to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
plot_dataset()
# plot misclassified data points
plt.scatter(
train_features[np.all(train_labels != train_predicts, axis=1), 0],
train_features[np.all(train_labels != train_predicts, axis=1), 1],
s=200,
facecolors="none",
edgecolors="r",
linewidths=2,
)
plt.scatter(
test_features[np.all(test_labels != test_predicts, axis=1), 0],
test_features[np.all(test_labels != test_predicts, axis=1), 1],
s=200,
facecolors="none",
edgecolors="r",
linewidths=2,
)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../../solutions/utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('2t/n')
# 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 = 4
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
qc = QuantumCircuit(3)
subspace_decoder(qc, targets=[0, 1, 2])
qc.draw("mpl")
# Initialize quantum circuit for 3 qubits
# qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(3)
# 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>)
qc.barrier()
general_subspace_encoder(qc, targets=[0, 1, 2]) # encode
qc.barrier()
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
qc.barrier()
general_subspace_decoder(qc, targets=[0, 1, 2]) # decode
qc = qc.bind_parameters({dt: target_time / num_steps})
qc.draw("mpl")
# Initialize quantum circuit for 3 qubits
# qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(3)
# 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>)
qc.barrier()
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
qc.barrier()
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
qc.barrier()
subspace_decoder(qc, targets=[0, 1, 2]) # decode
qc = qc.bind_parameters({dt: target_time / num_steps})
qc.draw("mpl")
dt = Parameter('2t/n')
mdt = Parameter('-2t/n')
qc = QuantumCircuit(2)
qc.rx(dt, 0)
qc.rz(dt, 1)
qc.h(1)
qc.cx(1, 0)
qc.rz(mdt, 0)
qc.rx(mdt, 1)
qc.rz(dt, 1)
qc.cx(1, 0)
qc.h(1)
qc.rz(dt, 0)
qc.draw("mpl")
dt = Parameter('2t/n')
mdt = Parameter('-2t/n')
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
qc.rz(mdt, 0)
qc.rx(mdt, 1)
qc.rz(dt, 1)
qc.cx(1, 0)
qc.h(1)
qc.rx(dt, 1)
qc.draw("mpl")
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
from qiskit.visualization import plot_error_map
device = provider.backend.ibmq_jakarta
plot_error_map(device)
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.ignis.mitigation import complete_meas_cal
# QREM
num_qubits = 3
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
meas_calibs[0].draw("mpl")
meas_calibs[1].draw("mpl")
meas_calibs[2].draw("mpl")
meas_calibs[3].draw("mpl")
meas_calibs[4].draw("mpl")
meas_calibs[5].draw("mpl")
meas_calibs[6].draw("mpl")
meas_calibs[7].draw("mpl")
|
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 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="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
t1 = time.perf_counter()
qc = qc.bind_parameters({dt: target_time / num_steps})
t2 = time.perf_counter()
print("created qc,", t2 - t1, "s")
# Generate state tomography circuits to evaluate fidelity of simulation
t1 = time.perf_counter()
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
t2 = time.perf_counter()
print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s")
# remove barriers
t1 = time.perf_counter()
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
t2 = time.perf_counter()
print("removed barriers from st_qcs,", t2 - t1, "s")
# optimize circuit
t1 = time.perf_counter()
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s")
t3_st_qcs[0].draw("mpl")
# zne wrapping
t1 = time.perf_counter()
zne_qcs = zne_wrapper(t3_st_qcs)
t2 = time.perf_counter()
print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
t2 = time.perf_counter()
print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 1 << 13
reps = 1 # unused
# Number of trotter steps
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from qiskit import IBMQ, assemble, transpile
from qiskit import QuantumCircuit
N_QUBITS = 20 # Number of qubits used in Google paper
# Load IBMQ cloud-based QASM simulator
provider = IBMQ.load_account()
backend = provider.backend.ibmq_qasm_simulator
def random_bitstring_circuit(n_qubits: int) -> QuantumCircuit:
"""
Args:
n_qubits: desired number of qubits in the bitstring
Returns:
QuantumCircuit: creates a random bitstring from the ground state
"""
qc = QuantumCircuit(n_qubits)
# Generate random bitstring
random_bitstring = np.random.randint(2, size=n_qubits)
# Apply X gate to nonzero qubits in bitstring
for i in range(n_qubits):
if random_bitstring[i]:
qc.x(i)
return qc
def floquet_circuit(n_qubits: int, g: float) -> QuantumCircuit:
"""
Args:
n_qubits: number of qubits
g: parameter controlling amount of x-rotation
Returns:
QuantumCircuit: circuit implementation of the unitary operator U_f as
detailed in https://arxiv.org/pdf/2107.13571.pdf
"""
qc = QuantumCircuit(n_qubits)
# X rotation by g*pi on all qubits (simulates the periodic driving pulse)
for i in range(n_qubits):
qc.rx(g*np.pi, i)
qc.barrier()
# Ising interaction (only couples adjacent spins with random coupling strengths)
for i in range(0, n_qubits-1, 2):
phi = np.random.uniform(low=0.5, high=1.5)
theta = -phi * np.pi / 2
qc.rzz(theta, i, i+1)
for i in range(1, n_qubits-1, 2):
phi = np.random.uniform(low=0.5, high=1.5)
theta = -phi * np.pi / 2
qc.rzz(theta, i, i+1)
qc.barrier()
# Longitudinal fields for disorder
for i in range(n_qubits):
h = np.random.uniform(low=-1, high=1)
qc.rz(h * np.pi, i)
return qc
def calculate_mean_polarization(n_qubits: int, counts: dict, q_index: int) -> float:
"""
Args:
n_qubits: total number of qubits
counts: dictionary of bitstring measurement outcomes and their respective total counts
q_index: index of qubit whose expected polarization we want to calculate
Returns:
float: the mean Z-polarization <Z>, in [-1, 1], of the qubit at q_index
"""
run, num_shots = 0, 0
for bitstring in counts.keys():
val = 1 if (int(bitstring[n_qubits-q_index-1]) == 0) else -1
run += val * counts[bitstring]
num_shots += counts[bitstring]
return run / num_shots
def calculate_two_point_correlations(series: list) -> list:
"""
Args:
series: time-ordered list of expectation values for some random variable
Returns:
list: two point correlations <f(0)f(t)> of the random variable evaluated at all t>0
"""
n = len(series)
data = np.asarray(series)
mean = np.mean(data)
c0 = np.sum((data - mean) ** 2) / float(n)
def r(h):
acf_lag = ((data[:n - h] - mean) * (data[h:] - mean)).sum() / float(n) / c0
return round(acf_lag, 3)
x = np.arange(n) # Avoiding lag 0 calculation
acf_coeffs = list(map(r, x))
return acf_coeffs
def simulate(n_qubits: int, initial_state: QuantumCircuit, max_time_steps: int, g: float) -> None:
mean_polarizations = np.zeros((n_qubits, max_time_steps+1))
floq_qc = floquet_circuit(n_qubits, g)
for t in range(0, max_time_steps+1):
if ((t % 5) == 0):
print('Time t=%d' % t)
qc = QuantumCircuit(n_qubits)
qc = qc.compose(initial_state)
for i in range(t):
qc = qc.compose(floq_qc)
qc.measure_all()
transpiled = transpile(qc, backend)
job = backend.run(transpiled)
retrieved_job = backend.retrieve_job(job.job_id())
counts = retrieved_job.result().get_counts()
for qubit in range(n_qubits):
mean_polarizations[qubit,t] = calculate_mean_polarization(n_qubits, counts, q_index=qubit)
return mean_polarizations
polarized_state = QuantumCircuit(N_QUBITS) # All qubits in |0> state
thermal_z = simulate(n_qubits=N_QUBITS,
initial_state=polarized_state,
max_time_steps=50,
g=0.6)
fig, ax = plt.subplots(figsize=(10,10))
im = ax.matshow(thermal_z, cmap='viridis')
plt.rcParams.update({'font.size': 15})
plt.rcParams['text.usetex'] = True
ax.set_xlabel('Floquet cycles (t)')
ax.xaxis.labelpad = 10
ax.set_ylabel('Qubit')
ax.set_xticks(np.arange(0, 51, 10))
ax.set_yticks(np.arange(0, N_QUBITS, 5))
ax.xaxis.set_label_position('top')
im.set_clim(-1, 1)
cbar = plt.colorbar(im, fraction=0.018, pad=0.04)
cbar.set_label(r'$\langle Z(t) \rangle$')
plt.show()
plt.plot(thermal_z[10,:], 'bs-')
plt.xlabel('Floquet cycles (t)')
plt.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False)
plt.ylabel(r'$\langle Z(t) \rangle$')
dtc_z = simulate(n_qubits=N_QUBITS,
initial_state=polarized_state,
max_time_steps=50,
g=0.97)
fig, ax = plt.subplots(figsize=(10,10))
im = ax.matshow(dtc_z, cmap='viridis')
plt.rcParams.update({'font.size': 15})
plt.rcParams['text.usetex'] = True
ax.set_xlabel('Floquet cycles (t)')
ax.xaxis.labelpad = 10
ax.set_ylabel('Qubit')
ax.set_xticks(np.arange(0, 51, 10))
ax.set_yticks(np.arange(0, N_QUBITS, 5))
ax.xaxis.set_label_position('top')
im.set_clim(-1, 1)
cbar = plt.colorbar(im, fraction=0.018, pad=0.04)
cbar.set_label(r'$\langle Z(t) \rangle$')
plt.show()
plt.plot(dtc_z[10,:], 'bs-')
plt.xlabel('Floquet cycles (t)')
plt.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False)
plt.ylabel(r'$\langle Z(t) \rangle$')
|
https://github.com/PKXH/quantum-algorithms
|
PKXH
|
from qiskit import (QuantumCircuit, execute, Aer)
from functools import partial
default_backend = Aer.get_backend('qasm_simulator')
def run_qc_using_backend(backend, qc):
job = execute(qc, backend)
return job.result()
def get_quantum_random_bitstring(sz=1, dump_circuit=False, runner = partial(run_qc_using_backend, default_backend)):
qc = QuantumCircuit(sz,sz)
for ch in range(sz):
qc.h(ch)
qc.measure([ch],[ch])
if dump_circuit:
return qc
else:
return runner(qc)
t = get_quantum_random_bitstring(8,dump_circuit=True)
t.draw('mpl')
from random import randint,sample
def get_random_bitstring(sz):
return [randint(0,1) for i in range(sz)]
t = get_random_bitstring(16)
print(t)
|
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 io
import math
import os
import pathlib
import pickle
import shutil
import tempfile
import unittest
import ddt
import qiskit.qasm2
from qiskit import qpy
from qiskit.circuit import (
ClassicalRegister,
Gate,
Parameter,
QuantumCircuit,
QuantumRegister,
Qubit,
library as lib,
)
from qiskit.test import QiskitTestCase
from . import gate_builder
class TestEmpty(QiskitTestCase):
def test_allows_empty(self):
self.assertEqual(qiskit.qasm2.loads(""), QuantumCircuit())
class TestVersion(QiskitTestCase):
def test_complete_version(self):
program = "OPENQASM 2.0;"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed, QuantumCircuit())
def test_incomplete_version(self):
program = "OPENQASM 2;"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed, QuantumCircuit())
def test_after_comment(self):
program = """
// hello, world
OPENQASM 2.0;
qreg q[2];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
class TestRegisters(QiskitTestCase):
def test_qreg(self):
program = "qreg q1[2]; qreg q2[1]; qreg q3[4];"
parsed = qiskit.qasm2.loads(program)
regs = [QuantumRegister(2, "q1"), QuantumRegister(1, "q2"), QuantumRegister(4, "q3")]
self.assertEqual(list(parsed.qregs), regs)
self.assertEqual(list(parsed.cregs), [])
def test_creg(self):
program = "creg c1[2]; creg c2[1]; creg c3[4];"
parsed = qiskit.qasm2.loads(program)
regs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2"), ClassicalRegister(4, "c3")]
self.assertEqual(list(parsed.cregs), regs)
self.assertEqual(list(parsed.qregs), [])
def test_interleaved_registers(self):
program = "qreg q1[3]; creg c1[2]; qreg q2[1]; creg c2[1];"
parsed = qiskit.qasm2.loads(program)
qregs = [QuantumRegister(3, "q1"), QuantumRegister(1, "q2")]
cregs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2")]
self.assertEqual(list(parsed.qregs), qregs)
self.assertEqual(list(parsed.cregs), cregs)
def test_registers_after_gate(self):
program = "qreg before[2]; CX before[0], before[1]; qreg after[2]; CX after[0], after[1];"
parsed = qiskit.qasm2.loads(program)
before = QuantumRegister(2, "before")
after = QuantumRegister(2, "after")
qc = QuantumCircuit(before, after)
qc.cx(before[0], before[1])
qc.cx(after[0], after[1])
self.assertEqual(parsed, qc)
def test_empty_registers(self):
program = "qreg q[0]; creg c[0];"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "q"), ClassicalRegister(0, "c"))
self.assertEqual(parsed, qc)
@ddt.ddt
class TestGateApplication(QiskitTestCase):
def test_builtin_single(self):
program = """
qreg q[2];
U(0, 0, 0) q[0];
CX q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.u(0, 0, 0, 0)
qc.cx(0, 1)
self.assertEqual(parsed, qc)
def test_builtin_1q_broadcast(self):
program = "qreg q[2]; U(0, 0, 0) q;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.u(0, 0, 0, 0)
qc.u(0, 0, 0, 1)
self.assertEqual(parsed, qc)
def test_builtin_2q_broadcast(self):
program = """
qreg q1[2];
qreg q2[2];
CX q1[0], q2;
barrier;
CX q1, q2[1];
barrier;
CX q1, q2;
"""
parsed = qiskit.qasm2.loads(program)
q1 = QuantumRegister(2, "q1")
q2 = QuantumRegister(2, "q2")
qc = QuantumCircuit(q1, q2)
qc.cx(q1[0], q2[0])
qc.cx(q1[0], q2[1])
qc.barrier()
qc.cx(q1[0], q2[1])
qc.cx(q1[1], q2[1])
qc.barrier()
qc.cx(q1[0], q2[0])
qc.cx(q1[1], q2[1])
self.assertEqual(parsed, qc)
def test_3q_broadcast(self):
program = """
include "qelib1.inc";
qreg q1[2];
qreg q2[2];
qreg q3[2];
ccx q1, q2[0], q3[1];
ccx q1[1], q2, q3[0];
ccx q1[0], q2[1], q3;
barrier;
ccx q1, q2, q3[1];
ccx q1[1], q2, q3;
ccx q1, q2[1], q3;
barrier;
ccx q1, q2, q3;
"""
parsed = qiskit.qasm2.loads(program)
q1 = QuantumRegister(2, "q1")
q2 = QuantumRegister(2, "q2")
q3 = QuantumRegister(2, "q3")
qc = QuantumCircuit(q1, q2, q3)
qc.ccx(q1[0], q2[0], q3[1])
qc.ccx(q1[1], q2[0], q3[1])
qc.ccx(q1[1], q2[0], q3[0])
qc.ccx(q1[1], q2[1], q3[0])
qc.ccx(q1[0], q2[1], q3[0])
qc.ccx(q1[0], q2[1], q3[1])
qc.barrier()
qc.ccx(q1[0], q2[0], q3[1])
qc.ccx(q1[1], q2[1], q3[1])
qc.ccx(q1[1], q2[0], q3[0])
qc.ccx(q1[1], q2[1], q3[1])
qc.ccx(q1[0], q2[1], q3[0])
qc.ccx(q1[1], q2[1], q3[1])
qc.barrier()
qc.ccx(q1[0], q2[0], q3[0])
qc.ccx(q1[1], q2[1], q3[1])
self.assertEqual(parsed, qc)
@ddt.data(True, False)
def test_broadcast_against_empty_register(self, conditioned):
cond = "if (cond == 0) " if conditioned else ""
program = f"""
OPENQASM 2;
include "qelib1.inc";
qreg q1[1];
qreg q2[1];
qreg empty1[0];
qreg empty2[0];
qreg empty3[0];
creg cond[1];
// None of the following statements should produce any gate applications.
{cond}h empty1;
{cond}cx q1[0], empty1;
{cond}cx empty1, q2[0];
{cond}cx empty1, empty2;
{cond}ccx empty1, q1[0], q2[0];
{cond}ccx q1[0], empty2, q2[0];
{cond}ccx q1[0], q2[0], empty3;
{cond}ccx empty1, empty2, q1[0];
{cond}ccx empty1, q1[0], empty2;
{cond}ccx q1[0], empty1, empty2;
{cond}ccx empty1, empty2, empty3;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(
QuantumRegister(1, "q1"),
QuantumRegister(1, "q2"),
QuantumRegister(0, "empty1"),
QuantumRegister(0, "empty2"),
QuantumRegister(0, "empty3"),
ClassicalRegister(1, "cond"),
)
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
qreg q[2];
creg cond[1];
if (cond == 0) U(0, 0, 0) q[0];
if (cond == 1) CX q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), cond)
qc.u(0, 0, 0, 0).c_if(cond, 0)
qc.cx(1, 0).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_conditioned_broadcast(self):
program = """
qreg q1[2];
qreg q2[2];
creg cond[1];
if (cond == 0) U(0, 0, 0) q1;
if (cond == 1) CX q1[0], q2;
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
q1 = QuantumRegister(2, "q1")
q2 = QuantumRegister(2, "q2")
qc = QuantumCircuit(q1, q2, cond)
qc.u(0, 0, 0, q1[0]).c_if(cond, 0)
qc.u(0, 0, 0, q1[1]).c_if(cond, 0)
qc.cx(q1[0], q2[0]).c_if(cond, 1)
qc.cx(q1[0], q2[1]).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_constant_folding(self):
# Most expression-related things are tested in `test_expression.py` instead.
program = """
qreg q[1];
U(4 + 3 * 2 ^ 2, cos(pi) * (1 - ln(1)), 2 ^ 3 ^ 2) q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.u(16.0, -1.0, 512.0, 0)
self.assertEqual(parsed, qc)
def test_call_defined_gate(self):
program = """
gate my_gate a {
U(0, 0, 0) a;
}
qreg q[2];
my_gate q[0];
my_gate q;
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit()])
my_gate_def.u(0, 0, 0, 0)
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0])
qc.append(my_gate(), [0])
qc.append(my_gate(), [1])
self.assertEqual(parsed, qc)
def test_parameterless_gates_accept_parentheses(self):
program = """
qreg q[2];
CX q[0], q[1];
CX() q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.cx(0, 1)
qc.cx(1, 0)
self.assertEqual(parsed, qc)
class TestGateDefinition(QiskitTestCase):
def test_simple_definition(self):
program = """
gate not_bell a, b {
U(0, 0, 0) a;
CX a, b;
}
qreg q[2];
not_bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
not_bell_def = QuantumCircuit([Qubit(), Qubit()])
not_bell_def.u(0, 0, 0, 0)
not_bell_def.cx(0, 1)
not_bell = gate_builder("not_bell", [], not_bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(not_bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
gate not_bell a, b {
U(0, 0, 0) a;
CX a, b;
}
qreg q[2];
creg cond[1];
if (cond == 0) not_bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
not_bell_def = QuantumCircuit([Qubit(), Qubit()])
not_bell_def.u(0, 0, 0, 0)
not_bell_def.cx(0, 1)
not_bell = gate_builder("not_bell", [], not_bell_def)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), cond)
qc.append(not_bell().c_if(cond, 0), [0, 1])
self.assertEqual(parsed, qc)
def test_constant_folding_in_definition(self):
program = """
gate bell a, b {
U(pi/2, 0, pi) a;
CX a, b;
}
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.u(math.pi / 2, 0, math.pi, 0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_parameterised_gate(self):
# Most of the tests of deep parameter expressions are in `test_expression.py`.
program = """
gate my_gate(a, b) c {
U(a, b, a + 2 * b) c;
}
qreg q[1];
my_gate(0.25, 0.5) q[0];
my_gate(0.5, 0.25) q[0];
"""
parsed = qiskit.qasm2.loads(program)
a, b = Parameter("a"), Parameter("b")
my_gate_def = QuantumCircuit([Qubit()])
my_gate_def.u(a, b, a + 2 * b, 0)
my_gate = gate_builder("my_gate", [a, b], my_gate_def)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(my_gate(0.25, 0.5), [0])
qc.append(my_gate(0.5, 0.25), [0])
self.assertEqual(parsed, qc)
# Also check the decomposition has come out exactly as expected. The floating-point
# assertions are safe as exact equality checks because there are no lossy operations with
# these parameters, and the answer should be exact.
decomposed = qc.decompose()
self.assertEqual(decomposed.data[0].operation.name, "u")
self.assertEqual(list(decomposed.data[0].operation.params), [0.25, 0.5, 1.25])
self.assertEqual(decomposed.data[1].operation.name, "u")
self.assertEqual(list(decomposed.data[1].operation.params), [0.5, 0.25, 1.0])
def test_parameterless_gate_with_parentheses(self):
program = """
gate my_gate() a {
U(0, 0, 0) a;
}
qreg q[1];
my_gate q[0];
my_gate() q[0];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit()])
my_gate_def.u(0, 0, 0, 0)
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(my_gate(), [0])
qc.append(my_gate(), [0])
self.assertEqual(parsed, qc)
def test_access_includes_in_definition(self):
program = """
include "qelib1.inc";
gate bell a, b {
h a;
cx a, b;
}
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_access_previous_defined_gate(self):
program = """
include "qelib1.inc";
gate bell a, b {
h a;
cx a, b;
}
gate second_bell a, b {
bell b, a;
}
qreg q[2];
second_bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
second_bell_def = QuantumCircuit([Qubit(), Qubit()])
second_bell_def.append(bell(), [1, 0])
second_bell = gate_builder("second_bell", [], second_bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(second_bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_qubits_lookup_differently_to_gates(self):
# The spec is somewhat unclear on this, and this leads to super weird text, but it's
# technically unambiguously resolvable and this is more permissive.
program = """
include "qelib1.inc";
gate bell h, cx {
h h;
cx h, cx;
}
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_parameters_lookup_differently_to_gates(self):
# The spec is somewhat unclear on this, and this leads to super weird text, but it's
# technically unambiguously resolvable and this is more permissive.
program = """
include "qelib1.inc";
gate shadow(rx, rz) a {
rz(rz) a;
rx(rx) a;
}
qreg q[1];
shadow(0.5, 2.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
rx, rz = Parameter("rx"), Parameter("rz")
shadow_def = QuantumCircuit([Qubit()])
shadow_def.rz(rz, 0)
shadow_def.rx(rx, 0)
shadow = gate_builder("shadow", [rx, rz], shadow_def)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(shadow(0.5, 2.0), [0])
self.assertEqual(parsed, qc)
def test_unused_parameters_convert_correctly(self):
# The main risk here is that there might be lazy application in the gate definition
# bindings, and we might accidentally try and bind parameters that aren't actually in the
# definition.
program = """
gate my_gate(p) q {
U(0, 0, 0) q;
}
qreg q[1];
my_gate(0.5) q[0];
"""
parsed = qiskit.qasm2.loads(program)
# No top-level circuit equality test here, because all the internals of gate application are
# an implementation detail, and we don't want to tie the tests and implementation together
# too closely.
self.assertEqual(list(parsed.qregs), [QuantumRegister(1, "q")])
self.assertEqual(list(parsed.cregs), [])
self.assertEqual(len(parsed.data), 1)
self.assertEqual(parsed.data[0].qubits, (parsed.qubits[0],))
self.assertEqual(parsed.data[0].clbits, ())
self.assertEqual(parsed.data[0].operation.name, "my_gate")
self.assertEqual(list(parsed.data[0].operation.params), [0.5])
decomposed = QuantumCircuit(QuantumRegister(1, "q"))
decomposed.u(0, 0, 0, 0)
self.assertEqual(parsed.decompose(), decomposed)
def test_qubit_barrier_in_definition(self):
program = """
gate my_gate a, b {
barrier a;
barrier b;
barrier a, b;
}
qreg q[2];
my_gate q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.barrier(0)
my_gate_def.barrier(1)
my_gate_def.barrier([0, 1])
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0, 1])
self.assertEqual(parsed, qc)
def test_bare_barrier_in_definition(self):
program = """
gate my_gate a, b {
barrier;
}
qreg q[2];
my_gate q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.barrier(my_gate_def.qubits)
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0, 1])
self.assertEqual(parsed, qc)
def test_duplicate_barrier_in_definition(self):
program = """
gate my_gate a, b {
barrier a, a;
barrier b, a, b;
}
qreg q[2];
my_gate q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.barrier(0)
my_gate_def.barrier([1, 0])
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0, 1])
self.assertEqual(parsed, qc)
def test_pickleable(self):
program = """
include "qelib1.inc";
gate my_gate(a) b, c {
rz(2 * a) b;
h b;
cx b, c;
}
qreg q[2];
my_gate(0.5) q[0], q[1];
my_gate(0.25) q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
a = Parameter("a")
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.rz(2 * a, 0)
my_gate_def.h(0)
my_gate_def.cx(0, 1)
my_gate = gate_builder("my_gate", [a], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(0.5), [0, 1])
qc.append(my_gate(0.25), [1, 0])
self.assertEqual(parsed, qc)
with io.BytesIO() as fptr:
pickle.dump(parsed, fptr)
fptr.seek(0)
loaded = pickle.load(fptr)
self.assertEqual(parsed, loaded)
def test_qpy_single_call_roundtrip(self):
program = """
include "qelib1.inc";
gate my_gate(a) b, c {
rz(2 * a) b;
h b;
cx b, c;
}
qreg q[2];
my_gate(0.5) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
# QPY won't persist custom gates by design choice, so instead let us check against the
# explicit form it uses.
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.rz(1.0, 0)
my_gate_def.h(0)
my_gate_def.cx(0, 1)
my_gate = Gate("my_gate", 2, [0.5])
my_gate.definition = my_gate_def
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate, [0, 1])
with io.BytesIO() as fptr:
qpy.dump(parsed, fptr)
fptr.seek(0)
loaded = qpy.load(fptr)[0]
self.assertEqual(loaded, qc)
# See https://github.com/Qiskit/qiskit-terra/issues/8941
@unittest.expectedFailure
def test_qpy_double_call_roundtrip(self):
program = """
include "qelib1.inc";
gate my_gate(a) b, c {
rz(2 * a) b;
h b;
cx b, c;
}
qreg q[2];
my_gate(0.5) q[0], q[1];
my_gate(0.25) q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
my_gate1_def = QuantumCircuit([Qubit(), Qubit()])
my_gate1_def.rz(1.0, 0)
my_gate1_def.h(0)
my_gate1_def.cx(0, 1)
my_gate1 = Gate("my_gate", 2, [0.5])
my_gate1.definition = my_gate1_def
my_gate2_def = QuantumCircuit([Qubit(), Qubit()])
my_gate2_def.rz(0.5, 0)
my_gate2_def.h(0)
my_gate2_def.cx(0, 1)
my_gate2 = Gate("my_gate", 2, [0.25])
my_gate2.definition = my_gate2_def
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate1, [0, 1])
qc.append(my_gate2, [1, 0])
with io.BytesIO() as fptr:
qpy.dump(parsed, fptr)
fptr.seek(0)
loaded = qpy.load(fptr)[0]
self.assertEqual(loaded, qc)
class TestOpaque(QiskitTestCase):
def test_simple(self):
program = """
opaque my_gate a;
opaque my_gate2() a;
qreg q[2];
my_gate q[0];
my_gate() q[1];
my_gate2 q[0];
my_gate2() q[1];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(Gate("my_gate", 1, []), [0])
qc.append(Gate("my_gate", 1, []), [1])
qc.append(Gate("my_gate2", 1, []), [0])
qc.append(Gate("my_gate2", 1, []), [1])
self.assertEqual(parsed, qc)
def test_parameterised(self):
program = """
opaque my_gate(a, b) c, d;
qreg q[2];
my_gate(0.5, 0.25) q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(Gate("my_gate", 2, [0.5, 0.25]), [1, 0])
self.assertEqual(parsed, qc)
class TestBarrier(QiskitTestCase):
def test_single_register_argument(self):
program = """
qreg first[3];
qreg second[3];
barrier first;
barrier second;
"""
parsed = qiskit.qasm2.loads(program)
first = QuantumRegister(3, "first")
second = QuantumRegister(3, "second")
qc = QuantumCircuit(first, second)
qc.barrier(first)
qc.barrier(second)
self.assertEqual(parsed, qc)
def test_single_qubit_argument(self):
program = """
qreg first[3];
qreg second[3];
barrier first[1];
barrier second[0];
"""
parsed = qiskit.qasm2.loads(program)
first = QuantumRegister(3, "first")
second = QuantumRegister(3, "second")
qc = QuantumCircuit(first, second)
qc.barrier(first[1])
qc.barrier(second[0])
self.assertEqual(parsed, qc)
def test_empty_circuit_empty_arguments(self):
program = "barrier;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit()
self.assertEqual(parsed, qc)
def test_one_register_circuit_empty_arguments(self):
program = "qreg q1[2]; barrier;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q1"))
qc.barrier(qc.qubits)
self.assertEqual(parsed, qc)
def test_multi_register_circuit_empty_arguments(self):
program = "qreg q1[2]; qreg q2[3]; qreg q3[1]; barrier;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(
QuantumRegister(2, "q1"), QuantumRegister(3, "q2"), QuantumRegister(1, "q3")
)
qc.barrier(qc.qubits)
self.assertEqual(parsed, qc)
def test_include_empty_register(self):
program = """
qreg q[2];
qreg empty[0];
barrier empty;
barrier q, empty;
barrier;
"""
parsed = qiskit.qasm2.loads(program)
q = QuantumRegister(2, "q")
qc = QuantumCircuit(q, QuantumRegister(0, "empty"))
qc.barrier(q)
qc.barrier(qc.qubits)
self.assertEqual(parsed, qc)
def test_allows_duplicate_arguments(self):
# There's nothing in the paper that implies this should be forbidden.
program = """
qreg q1[3];
qreg q2[2];
barrier q1, q1;
barrier q1[0], q1;
barrier q1, q1[0];
barrier q1, q2, q1;
"""
parsed = qiskit.qasm2.loads(program)
q1 = QuantumRegister(3, "q1")
q2 = QuantumRegister(2, "q2")
qc = QuantumCircuit(q1, q2)
qc.barrier(q1)
qc.barrier(q1)
qc.barrier(q1)
qc.barrier(q1, q2)
self.assertEqual(parsed, qc)
class TestMeasure(QiskitTestCase):
def test_single(self):
program = """
qreg q[1];
creg c[1];
measure q[0] -> c[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c"))
qc.measure(0, 0)
self.assertEqual(parsed, qc)
def test_broadcast(self):
program = """
qreg q[2];
creg c[2];
measure q -> c;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"))
qc.measure(0, 0)
qc.measure(1, 1)
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
qreg q[2];
creg c[2];
creg cond[1];
if (cond == 0) measure q[0] -> c[0];
if (cond == 1) measure q -> c;
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"), cond)
qc.measure(0, 0).c_if(cond, 0)
qc.measure(0, 0).c_if(cond, 1)
qc.measure(1, 1).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_broadcast_against_empty_register(self):
program = """
qreg q_empty[0];
creg c_empty[0];
measure q_empty -> c_empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty"))
self.assertEqual(parsed, qc)
def test_conditioned_broadcast_against_empty_register(self):
program = """
qreg q_empty[0];
creg c_empty[0];
creg cond[1];
if (cond == 0) measure q_empty -> c_empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(
QuantumRegister(0, "q_empty"),
ClassicalRegister(0, "c_empty"),
ClassicalRegister(1, "cond"),
)
self.assertEqual(parsed, qc)
class TestReset(QiskitTestCase):
def test_single(self):
program = """
qreg q[1];
reset q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.reset(0)
self.assertEqual(parsed, qc)
def test_broadcast(self):
program = """
qreg q[2];
reset q;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.reset(0)
qc.reset(1)
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
qreg q[2];
creg cond[1];
if (cond == 0) reset q[0];
if (cond == 1) reset q;
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), cond)
qc.reset(0).c_if(cond, 0)
qc.reset(0).c_if(cond, 1)
qc.reset(1).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_broadcast_against_empty_register(self):
program = """
qreg empty[0];
reset empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "empty"))
self.assertEqual(parsed, qc)
def test_conditioned_broadcast_against_empty_register(self):
program = """
qreg empty[0];
creg cond[1];
if (cond == 0) reset empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "empty"), ClassicalRegister(1, "cond"))
self.assertEqual(parsed, qc)
class TestInclude(QiskitTestCase):
def setUp(self):
super().setUp()
self.tmp_dir = pathlib.Path(tempfile.mkdtemp())
def tearDown(self):
# Doesn't really matter if the removal fails, since this was a tempdir anyway; it'll get
# cleaned up by the OS at some point.
shutil.rmtree(self.tmp_dir, ignore_errors=True)
super().tearDown()
def test_qelib1_include(self):
program = """
include "qelib1.inc";
qreg q[3];
u3(0.5, 0.25, 0.125) q[0];
u2(0.5, 0.25) q[0];
u1(0.5) q[0];
cx q[0], q[1];
id q[0];
x q[0];
y q[0];
z q[0];
h q[0];
s q[0];
sdg q[0];
t q[0];
tdg q[0];
rx(0.5) q[0];
ry(0.5) q[0];
rz(0.5) q[0];
cz q[0], q[1];
cy q[0], q[1];
ch q[0], q[1];
ccx q[0], q[1], q[2];
crz(0.5) q[0], q[1];
cu1(0.5) q[0], q[1];
cu3(0.5, 0.25, 0.125) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(3, "q"))
qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0])
qc.append(lib.U2Gate(0.5, 0.25), [0])
qc.append(lib.U1Gate(0.5), [0])
qc.append(lib.CXGate(), [0, 1])
qc.append(lib.UGate(0, 0, 0), [0]) # Stand-in for id.
qc.append(lib.XGate(), [0])
qc.append(lib.YGate(), [0])
qc.append(lib.ZGate(), [0])
qc.append(lib.HGate(), [0])
qc.append(lib.SGate(), [0])
qc.append(lib.SdgGate(), [0])
qc.append(lib.TGate(), [0])
qc.append(lib.TdgGate(), [0])
qc.append(lib.RXGate(0.5), [0])
qc.append(lib.RYGate(0.5), [0])
qc.append(lib.RZGate(0.5), [0])
qc.append(lib.CZGate(), [0, 1])
qc.append(lib.CYGate(), [0, 1])
qc.append(lib.CHGate(), [0, 1])
qc.append(lib.CCXGate(), [0, 1, 2])
qc.append(lib.CRZGate(0.5), [0, 1])
qc.append(lib.CU1Gate(0.5), [0, 1])
qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1])
self.assertEqual(parsed, qc)
def test_qelib1_after_gate_definition(self):
program = """
gate bell a, b {
U(pi/2, 0, pi) a;
CX a, b;
}
include "qelib1.inc";
qreg q[2];
bell q[0], q[1];
rx(0.5) q[0];
bell q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.u(math.pi / 2, 0, math.pi, 0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
qc.rx(0.5, 0)
qc.append(bell(), [1, 0])
self.assertEqual(parsed, qc)
def test_include_can_define_version(self):
include = """
OPENQASM 2.0;
qreg inner_q[2];
"""
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write(include)
program = """
OPENQASM 2.0;
include "include.qasm";
"""
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
qc = QuantumCircuit(QuantumRegister(2, "inner_q"))
self.assertEqual(parsed, qc)
def test_can_define_gates(self):
include = """
gate bell a, b {
h a;
cx a, b;
}
"""
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write(include)
program = """
OPENQASM 2.0;
include "qelib1.inc";
include "include.qasm";
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_nested_include(self):
inner = "creg c[2];"
with open(self.tmp_dir / "inner.qasm", "w") as fp:
fp.write(inner)
outer = """
qreg q[2];
include "inner.qasm";
"""
with open(self.tmp_dir / "outer.qasm", "w") as fp:
fp.write(outer)
program = """
OPENQASM 2.0;
include "outer.qasm";
"""
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"))
self.assertEqual(parsed, qc)
def test_first_hit_is_used(self):
empty = self.tmp_dir / "empty"
empty.mkdir()
first = self.tmp_dir / "first"
first.mkdir()
with open(first / "include.qasm", "w") as fp:
fp.write("qreg q[1];")
second = self.tmp_dir / "second"
second.mkdir()
with open(second / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
parsed = qiskit.qasm2.loads(program, include_path=(empty, first, second))
qc = QuantumCircuit(QuantumRegister(1, "q"))
self.assertEqual(parsed, qc)
def test_qelib1_ignores_search_path(self):
with open(self.tmp_dir / "qelib1.inc", "w") as fp:
fp.write("qreg not_used[2];")
program = 'include "qelib1.inc";'
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
qc = QuantumCircuit()
self.assertEqual(parsed, qc)
def test_include_from_current_directory(self):
include = """
qreg q[2];
"""
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write(include)
program = """
OPENQASM 2.0;
include "include.qasm";
"""
prevdir = os.getcwd()
os.chdir(self.tmp_dir)
try:
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
finally:
os.chdir(prevdir)
def test_load_searches_source_directory(self):
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm")
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
def test_load_searches_source_directory_last(self):
first = self.tmp_dir / "first"
first.mkdir()
with open(first / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg not_used[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_path=(first,))
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
def test_load_searches_source_directory_prepend(self):
first = self.tmp_dir / "first"
first.mkdir()
with open(first / "include.qasm", "w") as fp:
fp.write("qreg not_used[2];")
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
parsed = qiskit.qasm2.load(
self.tmp_dir / "program.qasm", include_path=(first,), include_input_directory="prepend"
)
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
def test_load_can_ignore_source_directory(self):
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unable to find 'include.qasm'"):
qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_input_directory=None)
@ddt.ddt
class TestCustomInstructions(QiskitTestCase):
def test_qelib1_include_overridden(self):
program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
u3(0.5, 0.25, 0.125) q[0];
u2(0.5, 0.25) q[0];
u1(0.5) q[0];
cx q[0], q[1];
id q[0];
x q[0];
y q[0];
z q[0];
h q[0];
s q[0];
sdg q[0];
t q[0];
tdg q[0];
rx(0.5) q[0];
ry(0.5) q[0];
rz(0.5) q[0];
cz q[0], q[1];
cy q[0], q[1];
ch q[0], q[1];
ccx q[0], q[1], q[2];
crz(0.5) q[0], q[1];
cu1(0.5) q[0], q[1];
cu3(0.5, 0.25, 0.125) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(3, "q"))
qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0])
qc.append(lib.U2Gate(0.5, 0.25), [0])
qc.append(lib.U1Gate(0.5), [0])
qc.append(lib.CXGate(), [0, 1])
qc.append(lib.IGate(), [0])
qc.append(lib.XGate(), [0])
qc.append(lib.YGate(), [0])
qc.append(lib.ZGate(), [0])
qc.append(lib.HGate(), [0])
qc.append(lib.SGate(), [0])
qc.append(lib.SdgGate(), [0])
qc.append(lib.TGate(), [0])
qc.append(lib.TdgGate(), [0])
qc.append(lib.RXGate(0.5), [0])
qc.append(lib.RYGate(0.5), [0])
qc.append(lib.RZGate(0.5), [0])
qc.append(lib.CZGate(), [0, 1])
qc.append(lib.CYGate(), [0, 1])
qc.append(lib.CHGate(), [0, 1])
qc.append(lib.CCXGate(), [0, 1, 2])
qc.append(lib.CRZGate(0.5), [0, 1])
qc.append(lib.CU1Gate(0.5), [0, 1])
qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1])
self.assertEqual(parsed, qc)
# Also test that the output matches what Qiskit puts out.
from_qiskit = QuantumCircuit.from_qasm_str(program)
self.assertEqual(parsed, from_qiskit)
def test_qelib1_sparse_overrides(self):
"""Test that the qelib1 special import still works as expected when a couple of gates in the
middle of it are custom. As long as qelib1 is handled specially, there is a risk that this
handling will break in weird ways when custom instructions overlap it."""
program = """
include "qelib1.inc";
qreg q[3];
u3(0.5, 0.25, 0.125) q[0];
u2(0.5, 0.25) q[0];
u1(0.5) q[0];
cx q[0], q[1];
id q[0];
x q[0];
y q[0];
z q[0];
h q[0];
s q[0];
sdg q[0];
t q[0];
tdg q[0];
rx(0.5) q[0];
ry(0.5) q[0];
rz(0.5) q[0];
cz q[0], q[1];
cy q[0], q[1];
ch q[0], q[1];
ccx q[0], q[1], q[2];
crz(0.5) q[0], q[1];
cu1(0.5) q[0], q[1];
cu3(0.5, 0.25, 0.125) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("id", 0, 1, lib.IGate),
qiskit.qasm2.CustomInstruction("h", 0, 1, lib.HGate),
qiskit.qasm2.CustomInstruction("crz", 1, 2, lib.CRZGate),
],
)
qc = QuantumCircuit(QuantumRegister(3, "q"))
qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0])
qc.append(lib.U2Gate(0.5, 0.25), [0])
qc.append(lib.U1Gate(0.5), [0])
qc.append(lib.CXGate(), [0, 1])
qc.append(lib.IGate(), [0])
qc.append(lib.XGate(), [0])
qc.append(lib.YGate(), [0])
qc.append(lib.ZGate(), [0])
qc.append(lib.HGate(), [0])
qc.append(lib.SGate(), [0])
qc.append(lib.SdgGate(), [0])
qc.append(lib.TGate(), [0])
qc.append(lib.TdgGate(), [0])
qc.append(lib.RXGate(0.5), [0])
qc.append(lib.RYGate(0.5), [0])
qc.append(lib.RZGate(0.5), [0])
qc.append(lib.CZGate(), [0, 1])
qc.append(lib.CYGate(), [0, 1])
qc.append(lib.CHGate(), [0, 1])
qc.append(lib.CCXGate(), [0, 1, 2])
qc.append(lib.CRZGate(0.5), [0, 1])
qc.append(lib.CU1Gate(0.5), [0, 1])
qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1])
self.assertEqual(parsed, qc)
def test_user_gate_after_overidden_qelib1(self):
program = """
include "qelib1.inc";
qreg q[1];
opaque my_gate q;
my_gate q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(Gate("my_gate", 1, []), [0])
self.assertEqual(parsed, qc)
def test_qiskit_extra_builtins(self):
program = """
qreg q[5];
u(0.5 ,0.25, 0.125) q[0];
p(0.5) q[0];
sx q[0];
sxdg q[0];
swap q[0], q[1];
cswap q[0], q[1], q[2];
crx(0.5) q[0], q[1];
cry(0.5) q[0], q[1];
cp(0.5) q[0], q[1];
csx q[0], q[1];
cu(0.5, 0.25, 0.125, 0.0625) q[0], q[1];
rxx(0.5) q[0], q[1];
rzz(0.5) q[0], q[1];
rccx q[0], q[1], q[2];
rc3x q[0], q[1], q[2], q[3];
c3x q[0], q[1], q[2], q[3];
c3sqrtx q[0], q[1], q[2], q[3];
c4x q[0], q[1], q[2], q[3], q[4];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(5, "q"))
qc.append(lib.UGate(0.5, 0.25, 0.125), [0])
qc.append(lib.PhaseGate(0.5), [0])
qc.append(lib.SXGate(), [0])
qc.append(lib.SXdgGate(), [0])
qc.append(lib.SwapGate(), [0, 1])
qc.append(lib.CSwapGate(), [0, 1, 2])
qc.append(lib.CRXGate(0.5), [0, 1])
qc.append(lib.CRYGate(0.5), [0, 1])
qc.append(lib.CPhaseGate(0.5), [0, 1])
qc.append(lib.CSXGate(), [0, 1])
qc.append(lib.CUGate(0.5, 0.25, 0.125, 0.0625), [0, 1])
qc.append(lib.RXXGate(0.5), [0, 1])
qc.append(lib.RZZGate(0.5), [0, 1])
qc.append(lib.RCCXGate(), [0, 1, 2])
qc.append(lib.RC3XGate(), [0, 1, 2, 3])
qc.append(lib.C3XGate(), [0, 1, 2, 3])
qc.append(lib.C3SXGate(), [0, 1, 2, 3])
qc.append(lib.C4XGate(), [0, 1, 2, 3, 4])
self.assertEqual(parsed, qc)
# There's also the 'u0' gate, but this is weird so we don't wildly care what its definition
# is and it has no Qiskit equivalent, so we'll just test that it using it doesn't produce an
# error.
parsed = qiskit.qasm2.loads(
"qreg q[1]; u0(1) q[0];", custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
self.assertEqual(parsed.data[0].operation.name, "u0")
def test_qiskit_override_delay_opaque(self):
program = """
opaque delay(t) q;
qreg q[1];
delay(1) q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.delay(1, 0, unit="dt")
self.assertEqual(parsed, qc)
def test_qiskit_override_u0_opaque(self):
program = """
opaque u0(n) q;
qreg q[1];
u0(2) q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.id(0)
qc.id(0)
self.assertEqual(parsed.decompose(), qc)
def test_can_override_u(self):
program = """
qreg q[1];
U(0.5, 0.25, 0.125) q[0];
"""
class MyGate(Gate):
def __init__(self, a, b, c):
super().__init__("u", 1, [a, b, c])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("U", 3, 1, MyGate, builtin=True)],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5, 0.25, 0.125), [0])
self.assertEqual(parsed, qc)
def test_can_override_cx(self):
program = """
qreg q[2];
CX q[0], q[1];
"""
class MyGate(Gate):
def __init__(self):
super().__init__("cx", 2, [])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 2, MyGate, builtin=True)],
)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(MyGate(), [0, 1])
self.assertEqual(parsed, qc)
@ddt.data(lambda x: x, reversed)
def test_can_override_both_builtins_with_other_gates(self, order):
program = """
gate unimportant q {}
qreg q[2];
U(0.5, 0.25, 0.125) q[0];
CX q[0], q[1];
"""
class MyUGate(Gate):
def __init__(self, a, b, c):
super().__init__("u", 1, [a, b, c])
class MyCXGate(Gate):
def __init__(self):
super().__init__("cx", 2, [])
custom = [
qiskit.qasm2.CustomInstruction("unused", 0, 1, lambda: Gate("unused", 1, [])),
qiskit.qasm2.CustomInstruction("U", 3, 1, MyUGate, builtin=True),
qiskit.qasm2.CustomInstruction("CX", 0, 2, MyCXGate, builtin=True),
]
custom = order(custom)
parsed = qiskit.qasm2.loads(program, custom_instructions=custom)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(MyUGate(0.5, 0.25, 0.125), [0])
qc.append(MyCXGate(), [0, 1])
self.assertEqual(parsed, qc)
def test_custom_builtin_gate(self):
program = """
qreg q[1];
builtin(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("builtin", 1, [a])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True)
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_builtin_as_gate(self):
program = """
qreg q[1];
gate builtin(t) q {}
builtin(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("builtin", 1, [a])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True)
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_builtin_as_opaque(self):
program = """
qreg q[1];
opaque builtin(t) q;
builtin(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("builtin", 1, [a])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True)
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_custom_as_gate(self):
program = """
qreg q[1];
gate my_gate(t) q {}
my_gate(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("my_gate", 1, [a])
parsed = qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)]
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_custom_as_opaque(self):
program = """
qreg q[1];
opaque my_gate(t) q;
my_gate(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("my_gate", 1, [a])
parsed = qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)]
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
class TestCustomClassical(QiskitTestCase):
def test_qiskit_extensions(self):
program = """
include "qelib1.inc";
qreg q[1];
rx(asin(0.3)) q[0];
ry(acos(0.3)) q[0];
rz(atan(0.3)) q[0];
"""
parsed = qiskit.qasm2.loads(program, custom_classical=qiskit.qasm2.LEGACY_CUSTOM_CLASSICAL)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.rx(math.asin(0.3), 0)
qc.ry(math.acos(0.3), 0)
qc.rz(math.atan(0.3), 0)
self.assertEqual(parsed, qc)
def test_zero_parameter_custom(self):
program = """
qreg q[1];
U(f(), 0, 0) q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: 0.2)]
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.u(0.2, 0, 0, 0)
self.assertEqual(parsed, qc)
def test_multi_parameter_custom(self):
program = """
qreg q[1];
U(f(0.2), g(0.4, 0.1), h(1, 2, 3)) q[0];
"""
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 1, lambda x: 1 + x),
qiskit.qasm2.CustomClassical("g", 2, math.atan2),
qiskit.qasm2.CustomClassical("h", 3, lambda x, y, z: z - y + x),
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.u(1.2, math.atan2(0.4, 0.1), 2, 0)
self.assertEqual(parsed, qc)
def test_use_in_gate_definition(self):
# pylint: disable=invalid-name
program = """
gate my_gate(a, b) q {
U(f(a, b), g(f(b, f(b, a))), b) q;
}
qreg q[1];
my_gate(0.5, 0.25) q[0];
my_gate(0.25, 0.5) q[0];
"""
f = lambda x, y: x - y
g = lambda x: 2 * x
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 2, f),
qiskit.qasm2.CustomClassical("g", 1, g),
],
)
first_gate = parsed.data[0].operation
second_gate = parsed.data[1].operation
self.assertEqual(list(first_gate.params), [0.5, 0.25])
self.assertEqual(list(second_gate.params), [0.25, 0.5])
self.assertEqual(
list(first_gate.definition.data[0].operation.params),
[
f(0.5, 0.25),
g(f(0.25, f(0.25, 0.5))),
0.25,
],
)
self.assertEqual(
list(second_gate.definition.data[0].operation.params),
[
f(0.25, 0.5),
g(f(0.5, f(0.5, 0.25))),
0.5,
],
)
@ddt.ddt
class TestStrict(QiskitTestCase):
@ddt.data(
"gate my_gate(p0, p1$) q0, q1 {}",
"gate my_gate(p0, p1) q0, q1$ {}",
"opaque my_gate(p0, p1$) q0, q1;",
"opaque my_gate(p0, p1) q0, q1$;",
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125$) q[0], q[1];',
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1]$;',
"qreg q[2]; barrier q[0], q[1]$;",
'include "qelib1.inc"; qreg q[1]; rx(sin(pi$)) q[0];',
)
def test_trailing_comma(self, program):
without = qiskit.qasm2.loads("OPENQASM 2.0;\n" + program.replace("$", ""), strict=True)
with_ = qiskit.qasm2.loads(program.replace("$", ","), strict=False)
self.assertEqual(with_, without)
def test_trailing_semicolon_after_gate(self):
program = """
include "qelib1.inc";
gate bell a, b {
h a;
cx a, b;
}; // <- the important bit of the test
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_empty_statement(self):
# This is allowed more as a side-effect of allowing the trailing semicolon after gate
# definitions.
program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
h q[0];
;
cx q[0], q[1];
;;;;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.h(0)
qc.cx(0, 1)
self.assertEqual(parsed, qc)
def test_single_quoted_path(self):
program = """
include 'qelib1.inc';
qreg q[1];
h q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.h(0)
self.assertEqual(parsed, qc)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Pauli Change of Basis Converter"""
import itertools
import unittest
from functools import reduce
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import (
ComposedOp,
I,
OperatorStateFn,
PauliSumOp,
SummedOp,
X,
Y,
Z,
)
from qiskit.opflow.converters import PauliBasisChange
from qiskit.quantum_info import Pauli, SparsePauliOp
class TestPauliCoB(QiskitOpflowTestCase):
"""Pauli Change of Basis Converter tests."""
def test_pauli_cob_singles(self):
"""from to file test"""
singles = [X, Y, Z]
dests = [None, Y]
for pauli, dest in itertools.product(singles, dests):
# print(pauli)
converter = PauliBasisChange(destination_basis=dest)
inst, dest = converter.get_cob_circuit(pauli.primitive)
cob = converter.convert(pauli)
np.testing.assert_array_almost_equal(
pauli.to_matrix(), inst.adjoint().to_matrix() @ dest.to_matrix() @ inst.to_matrix()
)
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob.to_matrix())
np.testing.assert_array_almost_equal(
inst.compose(pauli).compose(inst.adjoint()).to_matrix(), dest.to_matrix()
)
def test_pauli_cob_two_qubit(self):
"""pauli cob two qubit test"""
multis = [Y ^ X, Z ^ Y, I ^ Z, Z ^ I, X ^ X, I ^ X]
for pauli, dest in itertools.product(multis, reversed(multis)):
converter = PauliBasisChange(destination_basis=dest)
inst, dest = converter.get_cob_circuit(pauli.primitive)
cob = converter.convert(pauli)
np.testing.assert_array_almost_equal(
pauli.to_matrix(), inst.adjoint().to_matrix() @ dest.to_matrix() @ inst.to_matrix()
)
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob.to_matrix())
np.testing.assert_array_almost_equal(
inst.compose(pauli).compose(inst.adjoint()).to_matrix(), dest.to_matrix()
)
def test_pauli_cob_multiqubit(self):
"""pauli cob multi qubit test"""
# Helpful prints for debugging commented out below.
multis = [Y ^ X ^ I ^ I, I ^ Z ^ Y ^ X, X ^ Y ^ I ^ Z, I ^ I ^ I ^ X, X ^ X ^ X ^ X]
for pauli, dest in itertools.product(multis, reversed(multis)):
# print(pauli)
# print(dest)
converter = PauliBasisChange(destination_basis=dest)
inst, dest = converter.get_cob_circuit(pauli.primitive)
cob = converter.convert(pauli)
# print(inst)
# print(pauli.to_matrix())
# print(np.round(inst.adjoint().to_matrix() @ cob.to_matrix()))
np.testing.assert_array_almost_equal(
pauli.to_matrix(), inst.adjoint().to_matrix() @ dest.to_matrix() @ inst.to_matrix()
)
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob.to_matrix())
np.testing.assert_array_almost_equal(
inst.compose(pauli).compose(inst.adjoint()).to_matrix(), dest.to_matrix()
)
def test_pauli_cob_traverse(self):
"""pauli cob traverse test"""
# Helpful prints for debugging commented out below.
multis = [(X ^ Y) + (I ^ Z) + (Z ^ Z), (Y ^ X ^ I ^ I) + (I ^ Z ^ Y ^ X)]
dests = [Y ^ Y, I ^ I ^ I ^ Z]
for paulis, dest in zip(multis, dests):
converter = PauliBasisChange(destination_basis=dest, traverse=True)
cob = converter.convert(paulis)
self.assertIsInstance(cob, SummedOp)
inst = [None] * len(paulis)
ret_dest = [None] * len(paulis)
cob_mat = [None] * len(paulis)
for i, pauli in enumerate(paulis):
inst[i], ret_dest[i] = converter.get_cob_circuit(pauli.to_pauli_op().primitive)
self.assertEqual(dest, ret_dest[i])
self.assertIsInstance(cob.oplist[i], ComposedOp)
cob_mat[i] = cob.oplist[i].to_matrix()
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob_mat[i])
np.testing.assert_array_almost_equal(paulis.to_matrix(), sum(cob_mat))
def test_grouped_pauli(self):
"""grouped pauli test"""
pauli = 2 * (I ^ I) + (X ^ I) + 3 * (X ^ Y)
grouped_pauli = PauliSumOp(pauli.primitive, grouping_type="TPB")
converter = PauliBasisChange()
cob = converter.convert(grouped_pauli)
np.testing.assert_array_almost_equal(pauli.to_matrix(), cob.to_matrix())
origin_x = reduce(np.logical_or, pauli.primitive.paulis.x)
origin_z = reduce(np.logical_or, pauli.primitive.paulis.z)
origin_pauli = Pauli((origin_z, origin_x))
inst, dest = converter.get_cob_circuit(origin_pauli)
self.assertEqual(str(dest), "ZZ")
expected_inst = np.array(
[
[0.5, -0.5j, 0.5, -0.5j],
[0.5, 0.5j, 0.5, 0.5j],
[0.5, -0.5j, -0.5, 0.5j],
[0.5, 0.5j, -0.5, -0.5j],
]
)
np.testing.assert_array_almost_equal(inst.to_matrix(), expected_inst)
def test_grouped_pauli_statefn(self):
"""grouped pauli test with statefn"""
grouped_pauli = PauliSumOp(SparsePauliOp(["Y"]), grouping_type="TPB")
observable = OperatorStateFn(grouped_pauli, is_measurement=True)
converter = PauliBasisChange(replacement_fn=PauliBasisChange.measurement_replacement_fn)
cob = converter.convert(observable)
expected = PauliSumOp(SparsePauliOp(["Z"]), grouping_type="TPB")
self.assertEqual(cob[0].primitive, expected)
circuit = QuantumCircuit(1)
circuit.sdg(0)
circuit.h(0)
self.assertEqual(cob[1].primitive, circuit)
if __name__ == "__main__":
unittest.main()
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import *
from qiskit.quantum_info import Statevector
from math import pi
qc=QuantumCircuit(2)
qc.crx(pi/2,0,1)
qc.draw(output="mpl")
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
#Obtain the unitary matrix for CRx gate
print(result.get_unitary(qc, decimals=3))
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qc=QuantumCircuit(2)
qc.x(0)
qc.crx(pi/2,0,1)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qc=QuantumCircuit(2)
qc.cry(pi/2,0,1)
qc.draw(output="mpl")
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
#Obtain the unitary matrix for CRy gate
print(result.get_unitary(qc, decimals=3))
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qc=QuantumCircuit(2)
qc.x(0)
qc.cry(pi/2,0,1)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qc=QuantumCircuit(2)
qc.crz(pi/2,0,1)
qc.draw(output="mpl")
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
#Obtain the unitary matrix for CRz gate
print(result.get_unitary(qc, decimals=3))
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qc=QuantumCircuit(2)
qc.x(0)
qc.crz(pi/2,0,1)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw(output='latex')
|
https://github.com/mlvqc/Byskit
|
mlvqc
|
from qiskit import IBMQ
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
#provider = IBMQ.get_provider(hub='ibm-q-oxford', group='on-boarding', project='on-boarding-proj')
from qiskit import BasicAer
backend = BasicAer.get_backend('qasm_simulator')
# Include matplot lib inline plotting for graphical output and plotting
%matplotlib inline
from byskit import byskit,gen_random_weights
n_parent = 2
n_child = 3
parents,children = gen_random_weights(n_parent,n_child)
b = byskit(backend,parents,children)
b.circ.draw(output='mpl')
# Trying to get results out
results = b.execute_circ().result()
# Import histogram visualisation tool and plot results
from qiskit.tools.visualization import plot_histogram
plot_histogram(results.get_counts(b.circ))
n_parent = 2
n_child = 4
parents,children = gen_random_weights(n_parent,n_child)
b = byskit(backend,parents,children)
b.circ.draw(output='mpl')
results = b.execute_circ().result()
plot_histogram(results.get_counts(b.circ))
|
https://github.com/Slope86/QiskitExtension
|
Slope86
|
from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2
from qiskit_extension.state_vector2 import StateVector2 as sv2
circuit_EPR = qc2(2)
# 1. 在qubit 0 的位置放入一個Hadamard gate
circuit_EPR.h(0)
# 2. 放入一個CNOT gate, 控制qubit為0, 目標qubit為1
circuit_EPR.cx(0, 1)
# 3. 繪製電路圖
circuit_EPR.show_circ()
circuit_EPR.to_matrix()
circuit_EPR.show_matrix()
# 建立一個|00>的state vector
state00 = sv2.from_label('00')
# 顯示出此sv2物件的狀態
state00.show_state()
# 建立state vector: 2( √2|0> + |+> - |-> )
state_x0 = sv2.from_label((2**0.5,"0"),"+",(-1,"-"))
# 顯示出此sv2物件的狀態
state_x0.show_state()
state00.to_matrix()
state_x0.to_matrix()
state00.show_matrix()
state_x0.show_matrix()
# 將|00>經過EPR電路後的狀態
state_EPR = state00.evolve(circuit_EPR)
# 顯示出此sv2物件的狀態
state_EPR.show_state()
# 建立一個GHZ state
state_GHZ = sv2.from_label("000","111")
# 量測GHZ state的第一個qubit, 並顯示出結果
state_GHZ.show_measure(0)
# 量測EPR pair的第一,二顆qubit後,將各種量測結果對應到的state vector存入一個list中
list_after_measure_bit01 = state_GHZ.measure([0,1])
# 顯示出量測到00的後state vector
list_after_measure_bit01[0b00].show_state()
# 此為None, 因為GHZ量測第0,1顆qubit,不可能出現01的結果
list_after_measure_bit01[0b01] is None
# show_state() 預設以Z基底顯示狀態
state_x0.show_state() # 1/√2(|0>+|1>)
# 以X基底顯示狀態
state_x0.show_state(basis='x') # |+>
# 自動判斷基底(以最小entropy的基底顯示)
state_x0.show_state(basis="") # |+>
# measure() / show_measure() 預設以Z基底量測
state_GHZ.show_measure(0) # |0>: |00>, |1>: |11>
# 以X基底量測
state_GHZ.show_measure(0, basis='x') # |+>: 1/√2(|00>+|11>), |->: 1/√2(|00>-|11>)
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
from qiskit import QuantumRegister, ClassicalRegister, BasicAer
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.aqua.components.uncertainty_models import NormalDistribution,UniformDistribution,LogNormalDistribution
IBMQ.enable_account('Enter API key') #Key can be obtained from IBM Quantum
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_qasm_simulator')
q = QuantumRegister(5,'q')
c = ClassicalRegister(5,'c')
print("\n Normal Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
normal = NormalDistribution(num_target_qubits = 5, mu=0, sigma=1, low=- 1, high=1)
normal.build(circuit,q)
circuit.measure(q,c)
circuit.draw(output='mpl',filename='normal.png')
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Normal Distribution')
plt.plot(sortedcounts)
plt.show()
print("\n Uniform Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
uniform = UniformDistribution(num_target_qubits = 5,low=- 0, high=1)
uniform.build(circuit,q)
circuit.measure(q,c)
circuit.draw(output='mpl',filename='uniform.png')
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Uniform Distribution')
plt.plot(sortedcounts)
plt.show()
print("\n Log-Normal Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
lognorm = LogNormalDistribution(num_target_qubits = 5, mu=0, sigma=1, low= 0, high=1)
lognorm.build(circuit,q)
circuit.measure(q,c)
circuit.draw(output='mpl',filename='log.png')
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Log-Normal Distribution')
plt.plot(sortedcounts)
plt.show()
input()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram
import numpy as np
#prepares the initial quantum states for the BB84 protocol by generating a list of quantum states and their associated bases.
def prepare_bb84_states(num_qubits):
states = []
bases = []
for _ in range(num_qubits):
state, basis = generate_bb84_state()
states.append(state)
bases.append(basis)
return states, bases
#generates a single BB84 quantum state and its associated measurement basis.
def generate_bb84_state():
basis = np.random.randint(2) # 0 for rectilinear basis, 1 for diagonal basis
if np.random.rand() < 0.5:
state = QuantumCircuit(1, 1)
if basis == 0:
state.h(0)
else:
state.s(0)
state.h(0)
else:
state = QuantumCircuit(1, 1)
if basis == 0:
state.x(0)
state.h(0)
else:
state.x(0)
state.s(0)
state.h(0)
return state, basis
#measures the quantum states with the appropriate basis and returns the measurement results
def measure_bb84_states(states, bases):
measurements = []
for state, basis in zip(states, bases):
if basis == 0:
state.measure(0, 0)
else:
state.h(0)
state.measure(0, 0)
measurements.append(state)
return measurements
#sifts the keys by comparing Alice and Bob's measurement bases and bits. It checks if the measurement bases match (the same basis) and appends the corresponding bits to the sifted keys
def sift_keys(alice_bases, bob_bases, alice_bits, bob_bits):
sifted_alice_bits = []
sifted_bob_bits = []
for a_basis, b_basis, a_bit, b_bit in zip(alice_bases, bob_bases, alice_bits, bob_bits):
if a_basis == b_basis:
sifted_alice_bits.append(a_bit)
sifted_bob_bits.append(b_bit)
return sifted_alice_bits, sifted_bob_bits
#calculates the error rate between Alice's and Bob's sifted bits
def error_rate(alice_bits, bob_bits):
errors = sum([1 for a, b in zip(alice_bits, bob_bits) if a != b])
return errors / len(alice_bits)
# simulates the BB84 protocol
num_qubits = 100
num_qubits = 100
alice_states, alice_bases = prepare_bb84_states(num_qubits)
bob_bases = np.random.randint(2, size=num_qubits)
bob_measurements = measure_bb84_states(alice_states, bob_bases)
alice_bits = []
for state in alice_states:
result = execute(state, Aer.get_backend('qasm_simulator')).result()
counts = result.get_counts(state)
max_count = max(counts, key=counts.get)
alice_bits.append(int(max_count))
bob_bits = []
for state in bob_measurements:
result = execute(state, Aer.get_backend('qasm_simulator')).result()
counts = result.get_counts(state)
max_count = max(counts, key=counts.get)
bob_bits.append(int(max_count))
sifted_alice_bits, sifted_bob_bits = sift_keys(alice_bases, bob_bases, alice_bits, bob_bits)
error = error_rate(sifted_alice_bits, sifted_bob_bits)
final_key = privacy_amplification(sifted_alice_bits)
print("Sifted key length:", len(sifted_alice_bits))
print("Error rate:", error)
print("Final secret key:", final_key)
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
%matplotlib inline
qc = QuantumRegister(size=2)
circuit = QuantumCircuit(qc)
circuit.draw(output='mpl')
circuit.cx(control_qubit=qc[0],target_qubit=qc[1])
circuit.cx(control_qubit=qc[1],target_qubit=qc[0])
circuit.cx(control_qubit=qc[0],target_qubit=qc[1])
circuit.draw(output='mpl')
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from IPython.display import IFrame
IFrame(src="http://www.youtube.com/embed/sqJIpHYl7oo", width=1920/2, height=1080/2)
s = '110101'
from qiskit import *
n = len(s)
circuit = QuantumCircuit(n+1,n)
# Step 0
circuit.x(n) # the n+1 qubits are indexed 0...n, so the last qubit is index n
circuit.barrier() # just a visual aid for now
# Step 1
circuit.h(range(n+1)) # range(n+1) returns [0,1,2,...,n] in Python. This covers all the qubits
circuit.barrier() # just a visual aid for now
# Step 2
for ii, yesno in enumerate(reversed(s)):
if yesno == '1':
circuit.cx(ii, n)
circuit.barrier() # just a visual aid for now
# Step 3
circuit.h(range(n+1)) # range(n+1) returns [0,1,2,...,n] in Python. This covers all the qubits
circuit.barrier() # just a visual aid for now
circuit.measure(range(n), range(n)) # measure the qubits indexed from 0 to n-1 and store them into the classical bits indexed 0 to n-1
%matplotlib inline
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots=1).result()
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots=1000).result()
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
qiskit.__qiskit_version__
import qiskit.tools.jupyter
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for layouts of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import layouts
class TestBitArrange(QiskitTestCase):
"""Tests for layout.bit_arrange."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
qregs = qiskit.QuantumRegister(3)
cregs = qiskit.ClassicalRegister(3)
self.regs = list(qregs) + list(cregs)
def test_qreg_creg_ascending(self):
"""Test qreg_creg_ascending layout function."""
sorted_regs = layouts.qreg_creg_ascending(self.regs)
ref_regs = [
self.regs[0],
self.regs[1],
self.regs[2],
self.regs[3],
self.regs[4],
self.regs[5],
]
self.assertListEqual(sorted_regs, ref_regs)
def test_qreg_creg_descending(self):
"""Test qreg_creg_descending layout function."""
sorted_regs = layouts.qreg_creg_descending(self.regs)
ref_regs = [
self.regs[2],
self.regs[1],
self.regs[0],
self.regs[5],
self.regs[4],
self.regs[3],
]
self.assertListEqual(sorted_regs, ref_regs)
class TestAxisMap(QiskitTestCase):
"""Tests for layout.time_axis_map."""
def test_time_map_in_dt(self):
"""Test time_map_in_dt layout function."""
axis_config = layouts.time_map_in_dt(time_window=(-100, 500))
self.assertEqual(axis_config.window, (-100, 500))
self.assertEqual(axis_config.label, "System cycle time (dt)")
ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"}
self.assertDictEqual(axis_config.axis_map, ref_map)
|
https://github.com/biswaroopmukherjee/Quantum-Waddle
|
biswaroopmukherjee
|
# Library for implementing XOR
import qiskit
import numpy as np
from qiskit import(
IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister, execute,
QuantumCircuit,
execute,
Aer)
from qiskit.visualization import plot_histogram, plot_state_city
if __name__ == "__main__":
pass
def binary_it(alpha):
''' binary_it:
returns a list that is indexed according to power,
binaried[0] = is LSB.
'''
binaried = [int(x) for x in bin(alpha)[2:]]
binaried.reverse()
return binaried
def invert(alpha):
return [ 1 - x for x in alpha]
def xor_gate_v_each(circuit, a,b,r, v,c,a0):
''' xor_gate_v_each:
See paper 'An Example of the Difference Between Quantum and Classical Random Walks'
args:
circuit -- the py object that holds the quantum circuit.
a -- q. reg. for the vertex.
b -- q. reg. for holding neighbor vertex.
r -- q. reg. for checking valid edge.
f(c, a0) -- function that returns the neighboring
-- vertex of a0 using label c for the vertex label.
c -- label of the edge
a0 -- label of the vertex
'''
#vc = v(c,a0);
vc = 1
#build in the not's for the a0 check.
binaried = binary_it(a0)
#match binaried
if len(binaried) > len(a):
binaried = binaried[:len(a)]
elif len(a) > len(binaried):
for i in range(len(a)-len(binaried)):
binaried.append(0)
notMask = invert(binaried)
for i in range(len(notMask)):
if notMask[i]:
circuit.x(a[i]);
#build in the cnots for xoring b
binaried = binary_it(vc)
#match binaried
if len(binaried) > len(a):
binaried = binaried[:len(a)]
elif len(a) > len(binaried):
for i in range(len(a)-len(binaried)):
binaried.append(0)
for i in range(len(binaried)):
if binaried[i]:
circuit.mct(a,b[i], None, mode='noancilla')
#build in the not's for the a0 return.
for i in range(len(notMask)):
if notMask[i]:
circuit.x(a[i]);
def xor_gate_f_each(circuit, a,b,r, v,c,a0):
''' xor_gate_v_each:
See paper 'An Example of the Difference Between Quantum and Classical Random Walks'
args:
circuit -- the py object that holds the quantum circuit.
a -- q. reg. for the vertex.
b -- q. reg. for holding neighbor vertex.
r -- q. reg. for checking valid edge.
f(c, a0) -- function that returns the neighboring
-- vertex of a0 using label c for the vertex label.
c -- label of the edge
a0 -- label of the vertex
'''
#fc = f(c,a0);
fc = 1
#build in the not's for the a0 check.
binaried = binary_it(a0)
#match binaried
if len(binaried) > len(a):
binaried = binaried[:len(a)]
elif len(a) > len(binaried):
for i in range(len(a)-len(binaried)):
binaried.append(0)
notMask = invert(binaried)
for i in range(len(notMask)):
if notMask[i]:
circuit.x(a[i]);
#build in the cnots for xoring b
binaried = binary_it(fc)
#match binaried
if len(binaried) > len(r):
binaried = binaried[:len(r)]
elif len(r) > len(binaried):
for i in range(len(r)-len(binaried)):
binaried.append(0)
for i in range(len(binaried)):
if binaried[i]:
circuit.mct(a,r[i], None, mode='noancilla')
#build in the not's for the a0 return.
for i in range(len(notMask)):
if notMask[i]:
circuit.x(a[i]);
n = 2
simulator = Aer.get_backend('qasm_simulator')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n, 'b')
r = QuantumRegister(1, 'r')
circuit = QuantumCircuit(a, b, r)
a0 = 1
xor_gate_v_each(circuit, a,b,r, 0,0,a0)
circuit.barrier()
a0 = 2
xor_gate_f_each(circuit, a,b,r, 0,0,a0)
circuit.draw()
|
https://github.com/abbarreto/qiskit2
|
abbarreto
| |
https://github.com/Alice-Bob-SW/emulation-examples
|
Alice-Bob-SW
|
from qiskit import QuantumCircuit, execute, transpile
from typing import Optional
from matplotlib import pyplot as plt
import numpy as np
import scipy as sp
from tqdm.notebook import tqdm
import warnings
# set default plot parameters
plt.rcParams.update({
'figure.facecolor': 'white',
'axes.facecolor': 'white',
'font.family': 'serif',
'font.size': 16,
'figure.dpi': 72.0,
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.major.size': 5.0,
'xtick.minor.size': 2.5,
'ytick.major.size': 5.0,
'ytick.minor.size': 2.5,
'xtick.minor.visible': True,
'ytick.minor.visible': True,
'axes.grid': True,
'axes.titlesize': 'larger',
'axes.labelsize': 'larger',
'legend.fontsize': 'larger',
'grid.color': 'gray',
'grid.linestyle': '--',
'grid.alpha': 0.3,
'lines.linewidth': 1.0,
'figure.figsize': (16, 8)
})
def _measurement_cycle(distance: int) -> QuantumCircuit:
cycle = QuantumCircuit(2 * distance - 1, distance - 1, name='cycle')
for i in range(distance - 1):
ancilla_idx = 2 * i + 1
cycle.initialize('+', ancilla_idx)
for i in range(distance - 1):
ancilla_idx = 2 * i + 1
cycle.cx(ancilla_idx, ancilla_idx + 1)
for i in range(distance - 1):
ancilla_idx = 2 * i + 1
cycle.cx(ancilla_idx, ancilla_idx - 1)
for i in range(distance - 1):
ancilla_idx = 2 * i + 1
cycle.measure_x(ancilla_idx, i)
return cycle
def error_correction_cycle(distance: int, repetitions: int, initial_state: Optional[str] = None) -> QuantumCircuit:
if initial_state is None:
initial_state = distance * '+'
circuit = QuantumCircuit(2 * distance - 1, distance + repetitions * (distance - 1))
circuit.initialize(initial_state, range(0, distance * 2, 2))
circuit.barrier()
for cycle_idx in range(repetitions):
first_bit = distance + cycle_idx * (distance - 1)
circuit.append(_measurement_cycle(distance).to_instruction(), range(2 * distance - 1), range(first_bit, first_bit + distance - 1))
circuit.barrier()
for i in range(distance):
circuit.measure_x(2 * i, i)
return circuit
from pymatching import Matching
def build_check_matrix(distance: int) -> np.ndarray:
return (np.identity(distance) + np.diag([1] * (distance - 1), 1))[:-1]
def build_detection_events(syndrome: np.ndarray) -> np.ndarray:
detection_events = np.copy(syndrome)
detection_events[:, 1:] = (
detection_events[:, 1:] - detection_events[:, 0:-1]
) % 2
return detection_events
class Decoder:
def __init__(self, distance: int, repetitions: int):
self._check_matrix = build_check_matrix(distance)
self._matching = Matching(
self._check_matrix, repetitions=repetitions + 1,
weights=None,
timelike_weights=None,
)
def decode(self, syndrome: np.ndarray) -> np.ndarray:
detection_events = build_detection_events(syndrome)
return self._matching.decode(detection_events)
def extract_results(distance: int, counts: dict[str, int]) -> list[dict]:
H = build_check_matrix(distance)
out = []
for k, v in counts.items():
d = {}
d['output'] = np.array([int(c) for c in reversed(k[-distance:])])
d['raw_syndrome'] = np.array([int(c) for c in reversed(k[:-distance])])
rounds = d['raw_syndrome'].shape[0] // (distance - 1)
syndrome = d['raw_syndrome'].reshape((rounds, distance - 1)).T
d['syndrome'] = np.zeros((syndrome.shape[0], syndrome.shape[1] + 1))
d['syndrome'][:, :-1] = syndrome
d['syndrome'][:, -1] = d['output'] @ H.T
d['count'] = v
out.append(d)
return out
def compare_results(output: np.ndarray, correction: np.ndarray) -> bool:
return np.all(output == correction)
def decode_results(decoder: Decoder, results: list[dict]) -> float:
n_logical_errors = 0
shots = 0
for d in results:
correction = decoder.decode(d['syndrome'])
if not compare_results(d['output'], correction):
n_logical_errors += d['count']
shots += d['count']
return n_logical_errors / shots
from qiskit_alice_bob_provider.local.provider import AliceBobLocalProvider
from qiskit_alice_bob_provider.local.backend import ProcessorSimulator
from qiskit_alice_bob_provider.processor.physical_cat import PhysicalCatProcessor
from qiskit_aer import AerSimulator
provider = AliceBobLocalProvider()
provider.backends()
backend = provider.get_backend('EMU:40Q:PHYSICAL_CATS')
backend.coupling_map.draw()
circ = error_correction_cycle(distance=3, repetitions=1)
circ.draw('mpl')
backend = provider.get_backend('EMU:6Q:PHYSICAL_CATS')
backend.coupling_map.draw()
transpile(circ, backend).draw('mpl')
decoder = Decoder(distance=3, repetitions=1)
raw_results = execute(circ, backend, shots=100_000).result().get_counts()
results = extract_results(distance=3, counts=raw_results)
print('Logical phase flip error rate:', decode_results(decoder, results))
k1 = 100
k2s = np.logspace(4, 7, 10)
nbar = 16
distances = [3, 5, 7, 9]
shots = int(1e5)
logical_error_rates = {}
for distance in tqdm(distances):
repetitions = distance
circ = error_correction_cycle(distance=distance, repetitions=repetitions)
decoder = Decoder(distance=distance, repetitions=repetitions)
this_rates = []
for k2 in tqdm(k2s):
backend = provider.get_backend(
'EMU:40Q:PHYSICAL_CATS',
average_nb_photons=nbar, kappa_1=k1, kappa_2=k2
)
raw_results = execute(circ, backend, shots=shots).result().get_counts()
results = extract_results(distance=distance, counts=raw_results)
this_rates.append(decode_results(decoder, results))
logical_error_rates[distance] = np.array(this_rates)
threshold = 10.0 / shots
plt.figure()
plt.title(f'Logical error rate as a function of $\\kappa_1/\\kappa_2$ and code distance ($\\bar n$={nbar})')
plt.xlabel('$\\kappa_1/\\kappa_2$')
plt.ylabel('Logical error rate')
for distance, error_rates in logical_error_rates.items():
precise_enough = np.nonzero(error_rates >= threshold)[0]
plt.plot(k1/k2s[precise_enough], error_rates[precise_enough], label=f'd={distance}', marker='o', lw=2, ms=8)
plt.legend()
plt.semilogx()
plt.semilogy()
plt.show()
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from qiskit import *
from qiskit.providers.ibmq import least_busy
import numpy as np
from error_matrix import Minv, diags
from circuits import get_bin
def fix_to_full_hist(hist, ORACLE_SIZE=5):
for i in range(2**(ORACLE_SIZE-1)):
b_str = get_bin(i,ORACLE_SIZE-1)
# print(b_str)
if b_str not in hist:
hist[b_str] = 0
return hist
def correct_results(res, ORACLE_SIZE=5):
fixed_hist = fix_to_full_hist(res.get_counts())
# print(fixed_hist)
hist_vert = np.vstack(list(fixed_hist.values()))
# print(hist_vert)
error_corrected = np.matmul(Minv,hist_vert)
corrected_hist = {}
for i in range(len(error_corrected)):
cur_val = error_corrected[i]
cur_bin = get_bin(i,ORACLE_SIZE-1)
corrected_hist[cur_bin] = cur_val[0]
return fixed_hist, corrected_hist
def get_avg(accs):
return sum(accs) / len(accs)
def get_job_by_tag(TARGET_TAG, ibm_computer = ""):
if not account_loaded:
load_account()
provider = IBMQ.get_provider(hub = 'ibm-q')
# print(provider.backends())
small_devices = provider.backends(filters=lambda x: not x.configuration().simulator)
device = least_busy(small_devices)
if ibm_computer != "":
device = provider.get_backend(ibm_computer)
jobs = device.jobs(limit=100)
print(jobs)
for job in jobs:
# print(job.tags())
if len(job.tags()) > 0 and job.tags()[0] == TARGET_TAG:
return job
return None
|
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.
# pylint: disable=invalid-name
"""Test cases for parameter manager."""
from copy import deepcopy
import numpy as np
from qiskit import pulse
from qiskit.circuit import Parameter
from qiskit.pulse.exceptions import PulseError, UnassignedDurationError
from qiskit.pulse.parameter_manager import ParameterGetter, ParameterSetter
from qiskit.pulse.transforms import AlignEquispaced, AlignLeft, inline_subroutines
from qiskit.test import QiskitTestCase
class ParameterTestBase(QiskitTestCase):
"""A base class for parameter manager unittest, providing test schedule."""
def setUp(self):
"""Just some useful, reusable Parameters, constants, schedules."""
super().setUp()
self.amp1_1 = Parameter("amp1_1")
self.amp1_2 = Parameter("amp1_2")
self.amp2 = Parameter("amp2")
self.amp3 = Parameter("amp3")
self.dur1 = Parameter("dur1")
self.dur2 = Parameter("dur2")
self.dur3 = Parameter("dur3")
self.parametric_waveform1 = pulse.Gaussian(
duration=self.dur1, amp=self.amp1_1 + self.amp1_2, sigma=self.dur1 / 4
)
self.parametric_waveform2 = pulse.Gaussian(
duration=self.dur2, amp=self.amp2, sigma=self.dur2 / 5
)
self.parametric_waveform3 = pulse.Gaussian(
duration=self.dur3, amp=self.amp3, sigma=self.dur3 / 6
)
self.ch1 = Parameter("ch1")
self.ch2 = Parameter("ch2")
self.ch3 = Parameter("ch3")
self.d1 = pulse.DriveChannel(self.ch1)
self.d2 = pulse.DriveChannel(self.ch2)
self.d3 = pulse.DriveChannel(self.ch3)
self.phi1 = Parameter("phi1")
self.phi2 = Parameter("phi2")
self.phi3 = Parameter("phi3")
self.meas_dur = Parameter("meas_dur")
self.mem1 = Parameter("s1")
self.reg1 = Parameter("m1")
self.context_dur = Parameter("context_dur")
# schedule under test
subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft())
subroutine += pulse.ShiftPhase(self.phi1, self.d1)
subroutine += pulse.Play(self.parametric_waveform1, self.d1)
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi3, self.d3)
long_schedule = pulse.ScheduleBlock(
alignment_context=AlignEquispaced(self.context_dur), name="long_schedule"
)
long_schedule += subroutine
long_schedule += pulse.ShiftPhase(self.phi2, self.d2)
long_schedule += pulse.Play(self.parametric_waveform2, self.d2)
with self.assertWarns(DeprecationWarning):
long_schedule += pulse.Call(sched)
long_schedule += pulse.Play(self.parametric_waveform3, self.d3)
long_schedule += pulse.Acquire(
self.meas_dur,
pulse.AcquireChannel(self.ch1),
mem_slot=pulse.MemorySlot(self.mem1),
reg_slot=pulse.RegisterSlot(self.reg1),
)
self.test_sched = long_schedule
class TestParameterGetter(ParameterTestBase):
"""Test getting parameters."""
def test_get_parameter_from_channel(self):
"""Test get parameters from channel."""
test_obj = pulse.DriveChannel(self.ch1 + self.ch2)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.ch1, self.ch2}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_pulse(self):
"""Test get parameters from pulse instruction."""
test_obj = self.parametric_waveform1
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.amp1_1, self.amp1_2, self.dur1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_acquire(self):
"""Test get parameters from acquire instruction."""
test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1))
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_inst(self):
"""Test get parameters from instruction."""
test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0))
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.phi2}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_call(self):
"""Test get parameters from instruction."""
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi1, self.d1)
with self.assertWarns(DeprecationWarning):
test_obj = pulse.Call(subroutine=sched)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_with_function(self):
"""Test ParameterExpressions formed trivially in a function."""
def get_shift(variable):
return variable - 1
test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_alignment_context(self):
"""Test get parameters from alignment context."""
test_obj = AlignEquispaced(duration=self.context_dur + self.dur1)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.context_dur, self.dur1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_complex_schedule(self):
"""Test get parameters from complicated schedule."""
test_block = deepcopy(self.test_sched)
visitor = ParameterGetter()
visitor.visit(test_block)
self.assertEqual(len(visitor.parameters), 17)
class TestParameterSetter(ParameterTestBase):
"""Test setting parameters."""
def test_set_parameter_to_channel(self):
"""Test set parameters from channel."""
test_obj = pulse.DriveChannel(self.ch1 + self.ch2)
value_dict = {self.ch1: 1, self.ch2: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.DriveChannel(3)
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_pulse(self):
"""Test set parameters from pulse instruction."""
test_obj = self.parametric_waveform1
value_dict = {self.amp1_1: 0.1, self.amp1_2: 0.2, self.dur1: 160}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.Gaussian(duration=160, amp=0.3, sigma=40)
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_acquire(self):
"""Test set parameters to acquire instruction."""
test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1))
value_dict = {self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.Acquire(16000, pulse.AcquireChannel(2), pulse.MemorySlot(2))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_inst(self):
"""Test get parameters from instruction."""
test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0))
value_dict = {self.phi1: 0.123, self.phi2: 0.456}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.ShiftPhase(0.579, pulse.DriveChannel(0))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_call(self):
"""Test get parameters from instruction."""
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi1, self.d1)
with self.assertWarns(DeprecationWarning):
test_obj = pulse.Call(subroutine=sched)
value_dict = {self.phi1: 1.57, self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_sched = pulse.Schedule()
ref_sched += pulse.ShiftPhase(1.57, pulse.DriveChannel(2))
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Call(subroutine=ref_sched)
self.assertEqual(assigned, ref_obj)
def test_with_function(self):
"""Test ParameterExpressions formed trivially in a function."""
def get_shift(variable):
return variable - 1
test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1)
value_dict = {self.phi1: 2.0, self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.ShiftPhase(1.0, pulse.DriveChannel(2))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_alignment_context(self):
"""Test get parameters from alignment context."""
test_obj = AlignEquispaced(duration=self.context_dur + self.dur1)
value_dict = {self.context_dur: 1000, self.dur1: 100}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = AlignEquispaced(duration=1100)
self.assertEqual(assigned, ref_obj)
def test_nested_assignment_partial_bind(self):
"""Test nested schedule with call instruction.
Inline the schedule and partially bind parameters."""
context = AlignEquispaced(duration=self.context_dur)
subroutine = pulse.ScheduleBlock(alignment_context=context)
subroutine += pulse.Play(self.parametric_waveform1, self.d1)
nested_block = pulse.ScheduleBlock()
with self.assertWarns(DeprecationWarning):
nested_block += pulse.Call(subroutine=subroutine)
test_obj = pulse.ScheduleBlock()
test_obj += nested_block
test_obj = inline_subroutines(test_obj)
value_dict = {self.context_dur: 1000, self.dur1: 200, self.ch1: 1}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_context = AlignEquispaced(duration=1000)
ref_subroutine = pulse.ScheduleBlock(alignment_context=ref_context)
ref_subroutine += pulse.Play(
pulse.Gaussian(200, self.amp1_1 + self.amp1_2, 50), pulse.DriveChannel(1)
)
ref_nested_block = pulse.ScheduleBlock()
ref_nested_block += ref_subroutine
ref_obj = pulse.ScheduleBlock()
ref_obj += ref_nested_block
self.assertEqual(assigned, ref_obj)
def test_complex_valued_parameter(self):
"""Test complex valued parameter can be casted to a complex value,
but raises PendingDeprecationWarning.."""
amp = Parameter("amp")
test_obj = pulse.Constant(duration=160, amp=1j * amp)
value_dict = {amp: 0.1}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(test_obj)
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Constant(duration=160, amp=1j * 0.1)
self.assertEqual(assigned, ref_obj)
def test_complex_value_to_parameter(self):
"""Test complex value can be assigned to parameter object,
but raises PendingDeprecationWarning."""
amp = Parameter("amp")
test_obj = pulse.Constant(duration=160, amp=amp)
value_dict = {amp: 0.1j}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(test_obj)
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Constant(duration=160, amp=1j * 0.1)
self.assertEqual(assigned, ref_obj)
def test_complex_parameter_expression(self):
"""Test assignment of complex-valued parameter expression to parameter,
but raises PendingDeprecationWarning."""
amp = Parameter("amp")
mag = Parameter("A")
phi = Parameter("phi")
test_obj = pulse.Constant(duration=160, amp=amp)
test_obj_copy = deepcopy(test_obj)
# generate parameter expression
value_dict = {amp: mag * np.exp(1j * phi)}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
# generate complex value
value_dict = {mag: 0.1, phi: 0.5}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(assigned)
# evaluated parameter expression: 0.0877582561890373 + 0.0479425538604203*I
value_dict = {amp: 0.1 * np.exp(0.5j)}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
ref_obj = visitor.visit(test_obj_copy)
self.assertEqual(assigned, ref_obj)
def test_invalid_pulse_amplitude(self):
"""Test that invalid parameters are still checked upon assignment."""
amp = Parameter("amp")
test_sched = pulse.ScheduleBlock()
test_sched.append(
pulse.Play(
pulse.Constant(160, amp=2 * amp),
pulse.DriveChannel(0),
),
inplace=True,
)
with self.assertRaises(PulseError):
test_sched.assign_parameters({amp: 0.6}, inplace=False)
def test_set_parameter_to_complex_schedule(self):
"""Test get parameters from complicated schedule."""
test_block = deepcopy(self.test_sched)
value_dict = {
self.amp1_1: 0.1,
self.amp1_2: 0.2,
self.amp2: 0.3,
self.amp3: 0.4,
self.dur1: 100,
self.dur2: 125,
self.dur3: 150,
self.ch1: 0,
self.ch2: 2,
self.ch3: 4,
self.phi1: 1.0,
self.phi2: 2.0,
self.phi3: 3.0,
self.meas_dur: 300,
self.mem1: 3,
self.reg1: 0,
self.context_dur: 1000,
}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_block)
# create ref schedule
subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft())
subroutine += pulse.ShiftPhase(1.0, pulse.DriveChannel(0))
subroutine += pulse.Play(pulse.Gaussian(100, 0.3, 25), pulse.DriveChannel(0))
sched = pulse.Schedule()
sched += pulse.ShiftPhase(3.0, pulse.DriveChannel(4))
ref_obj = pulse.ScheduleBlock(alignment_context=AlignEquispaced(1000), name="long_schedule")
ref_obj += subroutine
ref_obj += pulse.ShiftPhase(2.0, pulse.DriveChannel(2))
ref_obj += pulse.Play(pulse.Gaussian(125, 0.3, 25), pulse.DriveChannel(2))
with self.assertWarns(DeprecationWarning):
ref_obj += pulse.Call(sched)
ref_obj += pulse.Play(pulse.Gaussian(150, 0.4, 25), pulse.DriveChannel(4))
ref_obj += pulse.Acquire(
300, pulse.AcquireChannel(0), pulse.MemorySlot(3), pulse.RegisterSlot(0)
)
self.assertEqual(assigned, ref_obj)
class TestAssignFromProgram(QiskitTestCase):
"""Test managing parameters from programs. Parameter manager is implicitly called."""
def test_attribute_parameters(self):
"""Test the ``parameter`` attributes."""
sigma = Parameter("sigma")
amp = Parameter("amp")
waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp)
block = pulse.ScheduleBlock()
block += pulse.Play(waveform, pulse.DriveChannel(10))
ref_set = {amp, sigma}
self.assertSetEqual(set(block.parameters), ref_set)
def test_parametric_pulses(self):
"""Test Parametric Pulses with parameters determined by ParameterExpressions
in the Play instruction."""
sigma = Parameter("sigma")
amp = Parameter("amp")
waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp)
block = pulse.ScheduleBlock()
block += pulse.Play(waveform, pulse.DriveChannel(10))
block.assign_parameters({amp: 0.2, sigma: 4}, inplace=True)
self.assertEqual(block.blocks[0].pulse.amp, 0.2)
self.assertEqual(block.blocks[0].pulse.sigma, 4.0)
def test_parameters_from_subroutine(self):
"""Test that get parameter objects from subroutines."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
program_layer0 = pulse.Schedule()
program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0))
# from call instruction
program_layer1 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer1 += pulse.instructions.Call(program_layer0)
self.assertEqual(program_layer1.get_parameters("amp")[0], param1)
# from nested call instruction
program_layer2 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer2 += pulse.instructions.Call(program_layer1)
self.assertEqual(program_layer2.get_parameters("amp")[0], param1)
def test_assign_parameter_to_subroutine(self):
"""Test that assign parameter objects to subroutines."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
program_layer0 = pulse.Schedule()
program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0))
reference = program_layer0.assign_parameters({param1: 0.1}, inplace=False)
# to call instruction
program_layer1 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer1 += pulse.instructions.Call(program_layer0)
target = program_layer1.assign_parameters({param1: 0.1}, inplace=False)
self.assertEqual(inline_subroutines(target), reference)
# to nested call instruction
program_layer2 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer2 += pulse.instructions.Call(program_layer1)
target = program_layer2.assign_parameters({param1: 0.1}, inplace=False)
self.assertEqual(inline_subroutines(target), reference)
def test_assign_parameter_to_subroutine_parameter(self):
"""Test that assign parameter objects to parameter of subroutine."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
param_sub1 = Parameter("p1")
param_sub2 = Parameter("p2")
subroutine = pulse.Schedule()
subroutine += pulse.Play(waveform, pulse.DriveChannel(0))
reference = subroutine.assign_parameters({param1: 0.6}, inplace=False)
main_prog = pulse.Schedule()
pdict = {param1: param_sub1 + param_sub2}
with self.assertWarns(DeprecationWarning):
main_prog += pulse.instructions.Call(subroutine, value_dict=pdict)
# parameter is overwritten by parameters
self.assertEqual(len(main_prog.parameters), 2)
target = main_prog.assign_parameters({param_sub1: 0.1, param_sub2: 0.5}, inplace=False)
result = inline_subroutines(target)
self.assertEqual(result, reference)
class TestScheduleTimeslots(QiskitTestCase):
"""Test for edge cases of timing overlap on parametrized channels.
Note that this test is dedicated to `Schedule` since `ScheduleBlock` implicitly
assigns instruction time t0 that doesn't overlap with existing instructions.
"""
def test_overlapping_pulses(self):
"""Test that an error is still raised when overlapping instructions are assigned."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
with self.assertRaises(PulseError):
schedule |= pulse.Play(
pulse.Waveform([0.5, 0.5, 0.5, 0.5]), pulse.DriveChannel(param_idx)
)
def test_overlapping_on_assignment(self):
"""Test that assignment will catch against existing instructions."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx: 1})
def test_overlapping_on_expression_assigment_to_zero(self):
"""Test constant*zero expression conflict."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(2 * param_idx))
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx: 0})
def test_merging_upon_assignment(self):
"""Test that schedule can match instructions on a channel."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1))
schedule = schedule.insert(
4, pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
)
schedule.assign_parameters({param_idx: 1})
self.assertEqual(schedule.ch_duration(pulse.DriveChannel(1)), 8)
self.assertEqual(schedule.channels, (pulse.DriveChannel(1),))
def test_overlapping_on_multiple_assignment(self):
"""Test that assigning one qubit then another raises error when overlapping."""
param_idx1 = Parameter("q1")
param_idx2 = Parameter("q2")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx1))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx2))
schedule.assign_parameters({param_idx1: 2})
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx2: 2})
def test_cannot_build_schedule_with_unassigned_duration(self):
"""Test we cannot build schedule with parameterized instructions"""
dur = Parameter("dur")
ch = pulse.DriveChannel(0)
test_play = pulse.Play(pulse.Gaussian(dur, 0.1, dur / 4), ch)
sched = pulse.Schedule()
with self.assertRaises(UnassignedDurationError):
sched.insert(0, test_play)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.result import QuasiDistribution
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
import numpy as np
import matplotlib.pyplot as plt
import datetime
# set number of assets (= number of qubits)
num_assets = 4
seed = 123
# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
# plot sigma
plt.imshow(sigma, interpolation="nearest")
plt.show()
q = 0.5 # set risk factor
budget = num_assets // 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
portfolio = PortfolioOptimization(
expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget
)
qp = portfolio.to_quadratic_program()
qp
def print_result(result):
selection = result.x
value = result.fval
print("Optimal: selection {}, value {:.4f}".format(selection, value))
eigenstate = result.min_eigen_solver_result.eigenstate
probabilities = (
eigenstate.binary_probabilities()
if isinstance(eigenstate, QuasiDistribution)
else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()}
)
print("\n----------------- Full result ---------------------")
print("selection\tvalue\t\tprobability")
print("---------------------------------------------------")
probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)
for k, v in probabilities:
x = np.array([int(i) for i in list(reversed(k))])
value = portfolio.to_quadratic_program().objective.evaluate(x)
print("%10s\t%.4f\t\t%.4f" % (x, value, v))
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print_result(result)
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/googlercolin/Qiskit-Course
|
googlercolin
|
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from qiskit.aqua.utils import split_dataset_to_data_and_labels
from sklearn import svm
from utility import breast_cancer_pca
from matplotlib import pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
n = 2 # number of principal components kept
training_dataset_size = 20
testing_dataset_size = 10
sample_Total, training_input, test_input, class_labels = breast_cancer_pca(training_dataset_size, testing_dataset_size, n)
data_train, _ = split_dataset_to_data_and_labels(training_input)
data_test, _ = split_dataset_to_data_and_labels(test_input)
print (f"data_train[0].shape: {data_train[0].shape}" )
print (f"data_train[1].shape: {data_train[1].shape}" )
# We use the function of scikit learn to generate linearly separable blobs
centers = [(2.5,0),(0,2.5)]
x, y = make_blobs(n_samples=100, centers=centers, n_features=2,random_state=0,cluster_std=0.5)
fig,ax=plt.subplots(1,2,figsize=(12,4))
ax[0].scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1])
ax[0].set_title('Breast Cancer dataset');
ax[1].scatter(x[:,0],x[:,1],c=y)
ax[1].set_title('Blobs linearly separable');
plt.scatter(data_train[0][:,0],data_train[0][:,1],c=data_train[1])
plt.title('Breast Cancer dataset');
model= svm.LinearSVC()
model.fit(data_train[0], data_train[1])
#small utility function
# some utility functions
def make_meshgrid(x, y, h=.02):
x_min, x_max = x.min() - 1, x.max() + 1
y_min, y_max = y.min() - 1, y.max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
return xx, yy
def plot_contours(ax, clf, xx, yy, **params):
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
out = ax.contourf(xx, yy, Z, **params)
return out
accuracy_train = model.score(data_train[0], data_train[1])
accuracy_test = model.score(data_test[0], data_test[1])
X0, X1 = data_train[0][:, 0], data_train[0][:, 1]
xx, yy = make_meshgrid(X0, X1)
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
fig,ax=plt.subplots(1,2,figsize=(15,5))
ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1])
ax[0].set_title('Accuracy on the training set: '+str(accuracy_train));
ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1])
ax[1].set_title('Accuracy on the test set: '+str(accuracy_test));
clf = svm.SVC(gamma = 'scale')
clf.fit(data_train[0], data_train[1]);
accuracy_train = clf.score(data_train[0], data_train[1])
accuracy_test = clf.score(data_test[0], data_test[1])
X0, X1 = data_train[0][:, 0], data_train[0][:, 1]
xx, yy = make_meshgrid(X0, X1)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
fig,ax=plt.subplots(1,2,figsize=(15,5))
ax[0].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[0].scatter(data_train[0][:,0], data_train[0][:,1], c=data_train[1])
ax[0].set_title('Accuracy on the training set: '+str(accuracy_train));
ax[1].contourf(xx, yy, Z, cmap=plt.cm.coolwarm)
ax[1].scatter(data_test[0][:,0], data_test[0][:,1], c=data_test[1])
ax[1].set_title('Accuracy on the test set: '+str(accuracy_test));
import qiskit as qk
# Creating Qubits
q = qk.QuantumRegister(2)
# Creating Classical Bits
c = qk.ClassicalRegister(2)
circuit = qk.QuantumCircuit(q, c)
circuit.draw('mpl')
# Initialize empty circuit
circuit = qk.QuantumCircuit(q, c)
# Hadamard Gate on the first Qubit
circuit.h(q[0])
# CNOT Gate on the first and second Qubits
circuit.cx(q[0], q[1])
# Measuring the Qubits
circuit.measure(q, c)
circuit.draw('mpl')
# Using Qiskit Aer's Qasm Simulator: Define where do you want to run the simulation.
simulator = qk.BasicAer.get_backend('qasm_simulator')
# Simulating the circuit using the simulator to get the result
job = qk.execute(circuit, simulator, shots=100)
result = job.result()
# Getting the aggregated binary outcomes of the circuit.
counts = result.get_counts(circuit)
print (counts)
from qiskit.aqua.components.feature_maps import SecondOrderExpansion
feature_map = SecondOrderExpansion(feature_dimension=2, depth=1)
x = np.array([0.6, 0.3])
#feature_map.construct_circuit(x)
print(feature_map.construct_circuit(x))
from qiskit.aqua.algorithms import QSVM
qsvm = QSVM(feature_map, training_input, test_input)
#from qiskit.aqua import run_algorithm, QuantumInstance
from qiskit.aqua import algorithm, QuantumInstance
from qiskit import BasicAer
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=10598, seed_transpiler=10598)
result = qsvm.run(quantum_instance)
plt.scatter(training_input['Benign'][:,0], training_input['Benign'][:,1])
plt.scatter(training_input['Malignant'][:,0], training_input['Malignant'][:,1])
length_data = len(training_input['Benign']) + len(training_input['Malignant'])
print("size training set: {}".format(length_data))
#print("Matrix dimension: {}".format(result['kernel_matrix_training'].shape))
print("testing success ratio: ", result['testing_accuracy'])
test_set = np.concatenate((test_input['Benign'], test_input['Malignant']))
y_test = qsvm.predict(test_set, quantum_instance)
plt.scatter(test_set[:, 0], test_set[:,1], c=y_test)
plt.show()
plt.scatter(test_input['Benign'][:,0], test_input['Benign'][:,1])
plt.scatter(test_input['Malignant'][:,0], test_input['Malignant'][:,1])
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.problems import ElectronicBasis
driver = PySCFDriver()
driver.run_pyscf()
ao_problem = driver.to_problem(basis=ElectronicBasis.AO)
print(ao_problem.basis)
ao_hamil = ao_problem.hamiltonian
print(ao_hamil.electronic_integrals.alpha)
from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema
qcschema = driver.to_qcschema()
basis_transformer = get_ao_to_mo_from_qcschema(qcschema)
print(basis_transformer.initial_basis)
print(basis_transformer.final_basis)
mo_problem = basis_transformer.transform(ao_problem)
print(mo_problem.basis)
mo_hamil = mo_problem.hamiltonian
print(mo_hamil.electronic_integrals.alpha)
import numpy as np
from qiskit_nature.second_q.operators import ElectronicIntegrals
from qiskit_nature.second_q.problems import ElectronicBasis
from qiskit_nature.second_q.transformers import BasisTransformer
ao2mo_alpha = np.random.random((2, 2))
ao2mo_beta = np.random.random((2, 2))
basis_transformer = BasisTransformer(
ElectronicBasis.AO,
ElectronicBasis.MO,
ElectronicIntegrals.from_raw_integrals(ao2mo_alpha, h1_b=ao2mo_beta),
)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.molecule)
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
fc_transformer = FreezeCoreTransformer()
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
print(fc_problem.hamiltonian.constants)
fc_transformer = FreezeCoreTransformer(remove_orbitals=[4, 5])
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import ActiveSpaceTransformer
as_transformer = ActiveSpaceTransformer(2, 2)
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
as_transformer = ActiveSpaceTransformer(2, 2, active_orbitals=[0, 4])
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
b = '110'
n = len(b)
simon_circuit = QuantumCircuit(n*2, n)
# Apply Hadamard gates before querying the oracle
simon_circuit.h(range(n))
# Apply barrier for visual separation
simon_circuit.barrier()
simon_circuit = simon_circuit.compose(simon_oracle(b))
# Apply barrier for visual separation
simon_circuit.barrier()
# Apply Hadamard gates to the input register
simon_circuit.h(range(n))
# Measure qubits
simon_circuit.measure(range(n), range(n))
simon_circuit.draw("mpl")
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(simon_circuit).result()
counts = results.get_counts()
print(f"Measured output: {counts}")
plot_histogram(counts)
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
# Function to create Simon's oracle for a given hidden string 's'
def simon_oracle(s):
n = len(s)
oracle_circuit = QuantumCircuit(n*2, n)
# Apply CNOT gates according to the hidden string 's'
for qubit in range(n):
if s[qubit] == '1':
oracle_circuit.cx(qubit, n + qubit)
return oracle_circuit
# Hidden string 'b'
b = '1101'
# Number of qubits
n = len(b)
# Create a quantum circuit
simon_circuit = QuantumCircuit(n*2, n)
# Apply Hadamard gates to the first n qubits
simon_circuit.h(range(n))
# Apply a barrier for visual separation
simon_circuit.barrier()
# Compose the circuit with the Simon oracle for the given hidden string 'b'
simon_circuit = simon_circuit.compose(simon_oracle(b))
# Apply a barrier for visual separation
simon_circuit.barrier()
# Apply Hadamard gates to the first n qubits
simon_circuit.h(range(n))
# Measure the qubits
simon_circuit.measure(range(n), range(n))
# Visualize the circuit
simon_circuit.draw("mpl")
# Transpile the circuit for the simulator
simon_circuit = transpile(simon_circuit, Aer.get_backend('qasm_simulator'))
# Run the simulation
simulator = Aer.get_backend('qasm_simulator')
result = simulator.run(simon_circuit).result()
# Display the measured output
counts = result.get_counts(simon_circuit)
print(f"Measured output: {counts}")
# Plot the results
plot_histogram(counts)
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
# create class that all property based tests inherit from, and add the required methods that specify input
# generation, preconditions, operations, and post conditions
from abc import ABC, abstractmethod
from qiskit import QuantumCircuit
from QiskitPBT.input_generators.input_generator import InputGenerator
class Property(ABC):
# constructor to initialise the class with the statistical analysis object
def __init__(self):
self.statistical_analysis = None
self.classical_assertion_outcome = True
# generate inputs for the test
# outputs a list of the generated inputs
@abstractmethod
def get_input_generators(self) -> list[InputGenerator]:
# specify return type as list of input generators
pass
# specify the preconditions for the test
@abstractmethod
def preconditions(self, *inputs) -> bool:
pass
# the coordinator will pass all inputs in list order to the operations method
# specify the operations to be performed on the input, assumed to be idempotent
@abstractmethod
def operations(self, *inputs) -> tuple[QuantumCircuit]:
pass
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a DensityMatrix
state = DensityMatrix(qc)
plot_state_city(state)
|
https://github.com/ernchern/qiskit-vaqsd
|
ernchern
|
import qiskit
import numpy as np
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit.visualization import plot_histogram
import numpy as np
np.random.seed(99999)
params = np.random.rand(3)
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(1)
# # Add a CX (CNOT) gate on control qubit 0 and target qubit 1
# circuit.cx(0, 1)
circuit.u3(params[0],params[1],params[2],0)
circuit.u3(params[0],params[1],params[2],1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
# Draw the circuit
circuit.draw()
plot_histogram(counts)
counts['00']
np.array([counts['00'],counts['01'],counts['10'],counts['11']])/1000
|
https://github.com/ALI3Nass/X-Circuit-with-Statevector-and-Unitary-Gate
|
ALI3Nass
|
# Qiskit Example: Basic Quantum Circuit Simulation
## Importing Required Libraries
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_bloch_multivector, plot_histogram
from qiskit.quantum_info import Operator
# Create a quantum circuit with 1 qubit and 1 classical bit
circuit = QuantumCircuit(1, 1)
# Apply X gate to the qubit
circuit.x(0)
# Draw the circuit
circuit.draw('mpl')
# Simulate the circuit and obtain the statevector
simulator = Aer.get_backend('statevector_simulator')
result = execute(circuit, backend=simulator).result()
statevector = result.get_statevector()
# Print the statevector
print(statevector)
# Plot the Bloch vector
plot_bloch_multivector(statevector)
# Measure the qubit and obtain the counts
circuit.measure([0], [0])
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=backend, shots=1024).result()
counts = result.get_counts()
# Plot the histogram of counts
plot_histogram(counts)
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('unitary_simulator')
result = execute(circuit, backend = simulator).result()
unitary = result.get_unitary()
print(unitary)
circuit.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
for _ in range(100):
depths.append(
transpile(
ghz,
backend,
layout_method='trivial' # Fixed layout mapped in circuit order
).depth()
)
plt.figure(figsize=(8, 6))
plt.hist(depths, align='left', color='#AC557C')
plt.xlabel('Depth', fontsize=14)
plt.ylabel('Counts', fontsize=14);
|
https://github.com/qiskit-community/Qiskit-Hackathon-at-World-of-QUANTUM
|
qiskit-community
|
import numpy as np
import cmath
# Importing standard Qiskit libraries
from qiskit.quantum_info import Statevector, random_statevector
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.extensions import Initialize
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
qc = QuantumCircuit(1)
#
#
#
# FILL YOUR CODE IN HERE
#
#
#
#
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
#
#
#
# FILL YOUR CODE IN HERE
#
#
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
qc=QuantumCircuit(1,1)
qc.u3(np.pi/4,np.pi/4,np.pi/4,0)
#
# FILL YOUR CODE IN HERE
#
#
#
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
Counts = execute(qc, backend, shots = 1024, seed_simulator=312).result().get_counts() # we run the simulation and get the counts
plot_histogram(Counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
psi = random_statevector(2, seed=11)
init_gate = Initialize(psi)
init_gate.label = "Random State"
## Measure the state in the x,y,z basis and make a guess for the state_vector psi
#Measure in all three different bases
#Put your answer here
#Try to remove any global phase in your answer
phi=
theta=
angles : [phi,theta]
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
| |
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.quantum_info import Operator
from qiskit.tools.monitor import job_monitor
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import random as rand
import scipy.linalg as la
provider = IBMQ.load_account()
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from matplotlib import rcParams
rcParams['text.usetex'] = True
def reverse_list(s):
temp_list = list(s)
temp_list.reverse()
return ''.join(temp_list)
#Useful tool for converting an integer to a binary bit string
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
binry = format(x, 'b').zfill(n)
sup = list( reversed( binry[0:int(len(binry)/2)] ) )
sdn = list( reversed( binry[int(len(binry)/2):len(binry)] ) )
return format(x, 'b').zfill(n)
#return ''.join(sup)+''.join(sdn)
'''The task here is now to define a function which will either update a given circuit with a time-step
or return a single gate which contains all the necessary components of a time-step'''
#==========Needed Functions=============#
#Function to apply a full set of time evolution gates to a given circuit
def qc_evolve(qc, numsite, time, hop, U, trotter_steps):
#Compute angles for the onsite and hopping gates
# based on the model parameters t, U, and dt
theta = hop*time/(2*trotter_slices)
phi = U*time/(trotter_slices)
numq = 2*numsite
y_hop = Operator([[np.cos(theta), 0, 0, -1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[-1j*np.sin(theta), 0, 0, np.cos(theta)]])
x_hop = Operator([[np.cos(theta), 0, 0, 1j*np.sin(theta)],
[0, np.cos(theta), 1j*np.sin(theta), 0],
[0, 1j*np.sin(theta), np.cos(theta), 0],
[1j*np.sin(theta), 0, 0, np.cos(theta)]])
z_onsite = Operator([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, np.exp(1j*phi)]])
#Loop over each time step needed and apply onsite and hopping gates
for trot in range(trotter_steps):
#Onsite Terms
for i in range(0, numsite):
qc.unitary(z_onsite, [i,i+numsite], label="Z_Onsite")
#Add barrier to separate onsite from hopping terms
qc.barrier()
#Hopping terms
for i in range(0,numsite-1):
#Spin-up chain
qc.unitary(y_hop, [i,i+1], label="YHop")
qc.unitary(x_hop, [i,i+1], label="Xhop")
#Spin-down chain
qc.unitary(y_hop, [i+numsite, i+1+numsite], label="Xhop")
qc.unitary(x_hop, [i+numsite, i+1+numsite], label="Xhop")
#Add barrier after finishing the time step
qc.barrier()
#Measure the circuit
for i in range(numq):
qc.measure(i, i)
#Function to run the circuit and store the counts for an evolution with
# num_steps number of time steps.
def sys_evolve(nsites, excitations, total_time, dt, hop, U, trotter_steps):
#Check for correct data types
if not isinstance(nsites, int):
raise TypeError("Number of sites should be int")
if np.isscalar(excitations):
raise TypeError("Initial state should be list or numpy array")
if not np.isscalar(total_time):
raise TypeError("Evolution time should be scalar")
if not np.isscalar(dt):
raise TypeError("Time step should be scalar")
if not np.isscalar(hop):
raise TypeError("Hopping term should be scalar")
if not np.isscalar(U):
raise TypeError("Repulsion term should be scalar")
if not isinstance(trotter_steps, int):
raise TypeError("Number of trotter slices should be int")
numq = 2*nsites
num_steps = int(total_time/dt)
print('Num Steps: ',num_steps)
print('Total Time: ', total_time)
data = np.zeros((2**numq, num_steps))
for t_step in range(0, num_steps):
#Create circuit with t_step number of steps
q = QuantumRegister(numq)
c = ClassicalRegister(numq)
qcirc = QuantumCircuit(q,c)
#=========USE THIS REGION TO SET YOUR INITIAL STATE==============
#Initialize circuit by setting the occupation to
# a spin up and down electron in the middle site
#qcirc.x(int(nsites/2))
#qcirc.x(nsites+int(nsites/2))
for flip in excitations:
qcirc.x(flip)
#if nsites==3:
#Half-filling
#qcirc.x(1)
# qcirc.x(4)
# qcirc.x(0)
# qcirc.x(2)
#1 electron
# qcirc.x(1)
#===============================================================
qcirc.barrier()
#Append circuit with Trotter steps needed
qc_evolve(qcirc, nsites, t_step*dt, hop, U, trotter_steps)
#Choose provider and backend
provider = IBMQ.get_provider()
#backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 8192
max_credits = 10 #Max number of credits to spend on execution
job_exp = execute(qcirc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
result = job_exp.result()
counts = result.get_counts(qcirc)
print(result.get_counts(qcirc))
print("Job: ",t_step+1, " of ", num_steps," complete.")
#Store results in data array and normalize them
for i in range(2**numq):
if counts.get(get_bin(i,numq)) is None:
dat = 0
else:
dat = counts.get(get_bin(i,numq))
data[i,t_step] = dat/shots
return data
#==========Set Parameters of the System=============#
dt = 0.25 #Delta t
T = 4.5
time_steps = int(T/dt)
t = 1.0 #Hopping parameter
U = 2. #On-Site repulsion
#time_steps = 10
nsites = 3
trotter_slices = 5
initial_state = np.array([1,4])
#Run simulation
run_results = sys_evolve(nsites, initial_state, T, dt, t, U, trotter_slices)
#print(True if np.isscalar(initial_state) else False)
#Process and plot data
'''The procedure here is, for each fermionic mode, add the probability of every state containing
that mode (at a given time step), and renormalize the data based on the total occupation of each mode.
Afterwards, plot the data as a function of time step for each mode.'''
proc_data = np.zeros((2*nsites, time_steps))
timesq = np.arange(0.,time_steps*dt, dt)
#Sum over time steps
for t in range(time_steps):
#Sum over all possible states of computer
for i in range(2**(2*nsites)):
#num = get_bin(i, 2*nsite)
num = ''.join( list( reversed(get_bin(i,2*nsites)) ) )
#For each state, check which mode(s) it contains and add them
for mode in range(len(num)):
if num[mode]=='1':
proc_data[mode,t] += run_results[i,t]
#Renormalize these sums so that the total occupation of the modes is 1
norm = 0.0
for mode in range(len(num)):
norm += proc_data[mode,t]
proc_data[:,t] = proc_data[:,t] / norm
'''
At this point, proc_data is a 2d array containing the occupation
of each mode, for every time step
'''
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
for i in range(nsites):
#Create string label
strup = "Site "+str(i+1)+r'$\uparrow$'
strdwn = "Site "+str(i+1)+r'$\downarrow$'
ax2.plot(timesq, proc_data[i,:], marker="^", color=str(colors[i]), label=strup)
ax2.plot(timesq, proc_data[i+nsites,:], marker="v", color=str(colors[i]), label=strdwn)
#ax2.set_ylim(0, 0.55)
ax2.set_xlim(0, time_steps*dt+dt/2.)
#ax2.set_xticks(np.arange(0,time_steps*dt+dt, 0.2))
#ax2.set_yticks(np.arange(0,0.55, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
ax2.legend(fontsize=20)
#Plot the raw data as a colormap
xticks = np.arange(2**(nsite*2))
xlabels=[]
print("Time Steps: ",time_steps, " Step Size: ",dt)
for i in range(2**(nsite*2)):
xlabels.append(get_bin(i,6))
fig, ax = plt.subplots(figsize=(10,20))
c = ax.pcolor(run_results, cmap='binary')
ax.set_title('Time Evolution of 3 Site One Dimensional Chain', fontsize=22)
plt.yticks(xticks, xlabels, size=18)
ax.set_xlabel('Time Step', fontsize=22)
ax.set_ylabel('State', fontsize=26)
plt.show()
#Try by constructing the matrix and finding the eigenvalues
N = 3
Nup = 2
Ndwn = N - Nup
t = 1.0
U = 2.
#Check if two states are different by a single hop
def hop(psii, psij):
#Check spin down
hopp = 0
if psii[0]==psij[0]:
#Create array of indices with nonzero values
indi = np.nonzero(psii[1])[0]
indj = np.nonzero(psij[1])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
#Check spin up
if psii[1]==psij[1]:
indi = np.nonzero(psii[0])[0]
indj = np.nonzero(psij[0])[0]
for i in range(len(indi)):
if abs(indi[i]-indj[i])==1:
hopp = -t
return hopp
return hopp
#On-site terms
def repel(l,state):
if state[0][l]==1 and state[1][l]==1:
return state
else:
return []
#States for 3 electrons with net spin up
'''
states = [ [[1,1,0],[1,0,0]], [[1,1,0],[0,1,0]], [[1,1,0], [0,0,1]],
[[1,0,1],[1,0,0]], [[1,0,1],[0,1,0]], [[1,0,1], [0,0,1]],
[[0,1,1],[1,0,0]], [[0,1,1],[0,1,0]], [[0,1,1], [0,0,1]] ]
#States for 2 electrons in singlet state
'''
states = [ [[1,0,0],[1,0,0]], [[1,0,0],[0,1,0]], [[1,0,0],[0,0,1]],
[[0,1,0],[1,0,0]], [[0,1,0],[0,1,0]], [[0,1,0],[0,0,1]],
[[0,0,1],[1,0,0]], [[0,0,1],[0,1,0]], [[0,0,1],[0,0,1]] ]
#'''
#States for a single electron
#states = [ [[1,0,0],[0,0,0]], [[0,1,0],[0,0,0]], [[0,0,1],[0,0,0]] ]
#'''
H = np.zeros((len(states),len(states)) )
#Construct Hamiltonian matrix
for i in range(len(states)):
psi_i = states[i]
for j in range(len(states)):
psi_j = states[j]
if j==i:
for l in range(0,N):
if psi_i == repel(l,psi_j):
H[i,j] = U
break
else:
H[i,j] = hop(psi_i, psi_j)
print(H)
results = la.eig(H)
print()
for i in range(len(results[0])):
print('Eigenvalue: ',results[0][i])
print('Eigenvector: \n',results[1][i])
print()
dens_ops = []
eigs = []
for vec in results[1]:
dens_ops.append(np.outer(results[1][i],results[1][i]))
eigs.append(results[0][i])
print(dens_ops)
dt = 0.1
tsteps = 50
times = np.arange(0., tsteps*dt, dt)
t_op = la.expm(-1j*H*dt)
#print(np.subtract(np.identity(len(H)), dt*H*1j))
#print(t_op)
#wfk = [0., 0., 0., 0., 1., 0., 0., 0., 0.] #Half-filling initial state
wfk = [0., 0., 0., 0., 1.0, 0., 0., 0., 0.] #2 electron initial state
#wfk = [0., 1., 0.] #1 electron initial state
evolve = np.zeros([tsteps, len(wfk)])
mode_evolve = np.zeros([tsteps, 6])
evolve[0] = wfk
#Figure out how to generalize this later
#'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]) /2.
mode_evolve[0][1] = (evolve[0][3]+evolve[0][4]+evolve[0][5]) /2.
mode_evolve[0][2] = (evolve[0][6]+evolve[0][7]+evolve[0][8]) /2.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /2.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /2.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /2.
'''
mode_evolve[0][0] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][3]+evolve[0][4]+evolve[0][5]) /3.
mode_evolve[0][1] = (evolve[0][0]+evolve[0][1]+evolve[0][2]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][2] = (evolve[0][3]+evolve[0][4]+evolve[0][5]+evolve[0][6]+evolve[0][7]+evolve[0][8]) /3.
mode_evolve[0][3] = (evolve[0][0]+evolve[0][3]+evolve[0][6]) /3.
mode_evolve[0][4] = (evolve[0][1]+evolve[0][4]+evolve[0][7]) /3.
mode_evolve[0][5] = (evolve[0][2]+evolve[0][5]+evolve[0][8]) /3.
#'''
print(mode_evolve[0])
#Define density matrices
for t in range(1, tsteps):
#t_op = la.expm(-1j*H*t)
wfk = np.dot(t_op, wfk)
evolve[t] = np.multiply(np.conj(wfk), wfk)
norm = np.sum(evolve[t])
#print(evolve[t])
#Store data in modes rather than basis defined in 'states' variable
#Procedure for two electrons
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]) / (2)
mode_evolve[t][1] = (evolve[t][3]+evolve[t][4]+evolve[t][5]) / (2)
mode_evolve[t][2] = (evolve[t][6]+evolve[t][7]+evolve[t][8]) / (2)
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) / (2)
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) / (2)
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) / (2)
''' #Procedure for half-filling
mode_evolve[t][0] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][3]+evolve[t][4]+evolve[t][5]) /3.
mode_evolve[t][1] = (evolve[t][0]+evolve[t][1]+evolve[t][2]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][2] = (evolve[t][3]+evolve[t][4]+evolve[t][5]+evolve[t][6]+evolve[t][7]+evolve[t][8]) /3.
mode_evolve[t][3] = (evolve[t][0]+evolve[t][3]+evolve[t][6]) /3.
mode_evolve[t][4] = (evolve[t][1]+evolve[t][4]+evolve[t][7]) /3.
mode_evolve[t][5] = (evolve[t][2]+evolve[t][5]+evolve[t][8]) /3.
#'''
print(mode_evolve[t])
#print(np.linalg.norm(evolve[t]))
#print(len(evolve[:,0]) )
#print(len(times))
#print(evolve[:,0])
#print(min(evolve[:,0]))
#Create plots of the processed data
fig2, ax2 = plt.subplots(figsize=(20,10))
colors = list(mcolors.TABLEAU_COLORS.keys())
sit1 = "Exact Site "+str(1)+r'$\uparrow$'
sit2 = "Exact Site "+str(2)+r'$\uparrow$'
sit3 = "Exact Site "+str(3)+r'$\uparrow$'
#ax2.plot(times, evolve[:,0], linestyle='--', color=colors[0], linewidth=2.5, label=sit1)
#ax2.plot(times, evolve[:,1], linestyle='--', color=str(colors[1]), linewidth=2.5, label=sit2)
#ax2.plot(times, evolve[:,2], linestyle='--', color=str(colors[2]), linewidth=2., label=sit3)
#ax2.plot(times, np.zeros(len(times)))
for i in range(nsites):
#Create string label
strupq = "Quantum Site "+str(i+1)+r'$\uparrow$'
strdwnq = "Quantum Site "+str(i+1)+r'$\downarrow$'
strup = "Numerical Site "+str(i+1)+r'$\uparrow$'
strdwn = "Numerical Site "+str(i+1)+r'$\downarrow$'
ax2.scatter(timesq, proc_data[i,:], marker="*", color=str(colors[i]), label=strupq)
#ax2.scatter(timesq, proc_data[i+nsite,:], marker="v", color=str(colors[i]), label=strdwnq)
ax2.plot(times, mode_evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
ax2.plot(times, mode_evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
#ax2.plot(times, evolve[:,i], linestyle='-', color=str(colors[i]), linewidth=2, label=strup)
#ax2.plot(times, evolve[:,i+3], linestyle='--', color=str(colors[i]), linewidth=2, label=strdwn)
ax2.set_ylim(0, .51)
ax2.set_xlim(0, tsteps*dt+dt/2.)
#ax2.set_xticks(np.arange(0,tsteps*dt+dt, 2*dt))
#ax2.set_yticks(np.arange(0,0.5, 0.05))
ax2.tick_params(labelsize=16)
ax2.set_title('Time Evolution of 2 Electrons in 3 Site Chain', fontsize=22)
ax2.set_xlabel('Time', fontsize=24)
ax2.set_ylabel('Probability', fontsize=24)
#ax2.legend(fontsize=20)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
def compose_1q(lhs: Integral, rhs: Integral) -> Integral:
"""Return the composition of 1-qubit clifford integers."""
return _CLIFFORD_COMPOSE_1Q[lhs, rhs]
def compose_2q(lhs: Integral, rhs: Integral) -> Integral:
"""Return the composition of 2-qubit clifford integers."""
num = lhs
for layer, idx in enumerate(_layer_indices_from_num(rhs)):
circ = _CLIFFORD_LAYER[layer][idx]
num = _compose_num_with_circuit_2q(num, circ)
return num
def _compose_num_with_circuit_2q(num: Integral, qc: QuantumCircuit) -> Integral:
"""Compose a number that represents a Clifford, with a Clifford circuit, and return the
number that represents the resulting Clifford."""
lhs = num
for inst in qc:
qubits = tuple(qc.find_bit(q).index for q in inst.qubits)
rhs = _num_from_2q_gate(op=inst.operation, qubits=qubits)
try:
lhs = _CLIFFORD_COMPOSE_2Q_GATE[lhs, rhs]
except KeyError as err:
raise Exception(f"_CLIFFORD_COMPOSE_2Q_GATE[{lhs}][{rhs}]") from err
return lhs
from qiskit.providers.fake_provider import FakeManila
from qiskit_experiments.library.randomized_benchmarking import StandardRB
backend=FakeManila()
%%time
# create experiment
exp = StandardRB(
qubits=[3],
lengths=list(range(1, 1000, 100)),
num_samples=3,
seed=1234,
backend=backend,
)
# run experiment
expdata = exp.run().block_for_results()
display(expdata.figure(0))
num_lengths = 10
# run several experiments with changing max clifford length (max_length)
for max_length in [1000, 2000, 3000, 4000, 5000]: # [100, 200, 300, 400, 500] for 2Q RBs
exp = StandardRB(
qubits=[2], # for 1Q RBs ([2, 1] for 2Q RBs)
lengths=np.arange(1, max_length, max_length // num_lengths), # see below for examples
backend=FakeManilaV2(),
num_samples=3,
full_sampling=False,
)
# measure the time to generate transpiled RB circuits
exp._transpiled_circuits()
import numpy as np
max_length, num_lengths = 1000, 10
print(np.arange(1, max_length, max_length // num_lengths)) # = range(1, 1000, 100)
max_clifford_length, num_lengths = 2000, 10
print(np.arange(1, max_length, max_length // num_lengths)) # = range(1, 2000, 100)
import copy
from qiskit.circuit.library.standard_gates import SXGate
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit.pulse import Schedule, InstructionScheduleMap
from qiskit_experiments.library.randomized_benchmarking import StandardRB
qubits=(2,)
lengths=list(range(1, 1000, 100))
num_samples=3
seed=777
backend = FakeManilaV2()
%%time
qubits = (2,)
my_sched = Schedule(name="custom_sx_gate")
my_backend = copy.deepcopy(backend)
my_backend.target["sx"][qubits].calibration = my_sched
exp = StandardRB(qubits=qubits, lengths=lengths, num_samples=num_samples, backend=my_backend)
transpiled = exp._transpiled_circuits()
%%time
qubits = (2,)
my_sched = Schedule(name="custom_sx_gate")
my_inst_map = InstructionScheduleMap()
my_inst_map.add(SXGate(), qubits, my_sched)
exp = StandardRB(qubits=qubits, lengths=lengths, num_samples=num_samples, backend=backend)
exp.set_transpile_options(inst_map=my_inst_map)
transpiled = exp._transpiled_circuits()
from qiskit_experiments.library.randomized_benchmarking import StandardRB, InterleavedRB
from qiskit.providers.fake_provider import FakeManila
qubits=[2]
lengths=list(range(1, 1000, 100))
num_samples=3
seed=777
backend = FakeManila()
print("Cliford lengths:", lengths)
print("Number of circuits =", len(lengths)*num_samples)
%%time
# rb_speedup
exp = StandardRB(
qubits=qubits,
lengths=lengths,
num_samples=num_samples,
seed=seed,
backend=backend,
)
transpiled = exp._transpiled_circuits()
# %%time
# # Main
# exp = StandardRB(
# qubits=qubits,
# lengths=lengths,
# num_samples=num_samples,
# seed=seed,
# backend=backend,
# )
# transpiled = exp._transpiled_circuits()
qubits=[3, 2]
lengths=list(range(1, 200, 20))
num_samples=3
seed=777
backend = FakeManila()
print("Cliford lengths:", lengths)
print("Number of circuits =", len(lengths)*num_samples)
%%time
# rb_speedup
exp = StandardRB(
qubits=qubits,
lengths=lengths,
num_samples=num_samples,
seed=seed,
backend=backend,
)
transpiled = exp._transpiled_circuits()
# %%time
# # Main
# exp = StandardRB(
# qubits=qubits,
# lengths=lengths,
# num_samples=num_samples,
# seed=seed,
# backend=backend,
# )
# transpiled = exp._transpiled_circuits()
from qiskit.circuit import Delay
qubits=[2]
lengths=list(range(1, 1000, 100))
num_samples=3
seed=777
backend = FakeManila()
print("Cliford lengths:", lengths)
print("Number of circuits =", len(lengths)*num_samples*2)
from qiskit_experiments.framework.backend_timing import BackendTiming
timing = BackendTiming(backend)
duration_in_dt = timing.round_delay(time=backend.properties().gate_length("sx", qubits)) # 160[dt]
%%time
# rb_speedup
exp = InterleavedRB(
interleaved_element=Delay(duration=duration_in_dt),
qubits=qubits,
lengths=lengths,
num_samples=num_samples,
seed=seed,
backend=backend,
)
transpiled = exp._transpiled_circuits()
# %%time
# # Main
# exp = InterleavedRB(
# interleaved_element=Delay(duration=duration_in_dt),
# qubits=qubits,
# lengths=lengths,
# num_samples=num_samples,
# seed=seed,
# backend=backend,
# )
# transpiled = exp._transpiled_circuits()
qubits=[3, 2]
lengths=list(range(1, 200, 20))
num_samples=3
seed=777
backend = FakeManila()
print("Cliford lengths:", lengths)
print("Number of circuits =", len(lengths)*num_samples*2)
from qiskit.circuit import Delay, QuantumCircuit
delay_qc = QuantumCircuit(2)
delay_qc.delay(1600, 0)
delay_qc.delay(1600, 1)
delay_qc.draw()
%%time
# rb_speedup
exp = InterleavedRB(
interleaved_element=delay_qc,
qubits=qubits,
lengths=lengths,
num_samples=num_samples,
seed=seed,
backend=backend,
)
transpiled = exp._transpiled_circuits()
# %%time
# # Main
# exp = InterleavedRB(
# interleaved_element=delay_qc,
# qubits=qubits,
# lengths=lengths,
# num_samples=num_samples,
# seed=seed,
# backend=backend,
# )
# transpiled = exp._transpiled_circuits()
from qiskit.compiler import transpile
from qiskit.providers.fake_provider import FakeManila
# common RB configuration
qubits=[2]
lengths=list(range(1, 1000, 100))
num_samples=3
seed=777
backend = FakeManila()
print("Cliford lengths:", lengths)
print("Number of circuits =", len(lengths)*num_samples)
from qiskit.ignis.verification import randomized_benchmarking as rb
%%time
# Ignis
# create the RB circuits
circs, _ = rb.randomized_benchmarking_seq(
rb_pattern=[qubits],
length_vector=lengths,
nseeds=num_samples,
seed_offset=seed,
)
# transpile (for basis translation)
transpiled = []
for qcs in circs:
for qc in qcs:
transpiled.append(transpile(qc, backend=backend, optimization_level=0))
# transpiled[0].draw(idle_wires=False)
from qiskit_experiments.library.randomized_benchmarking import StandardRB, InterleavedRB
%%time
# Experiments
# create experiment object
exp = StandardRB(
qubits=qubits,
lengths=lengths,
num_samples=num_samples,
seed=seed,
backend=backend,
)
# compute transpiled circuits
transpiled_qe = exp._transpiled_circuits()
# transpiled_qe[0].draw(idle_wires=False)
# common RB configuration
qubits=[3, 2]
lengths=list(range(1, 200, 20))
num_samples=3
seed=777
backend = FakeManila()
print("Cliford lengths:", lengths)
print("Number of circuits =", len(lengths)*num_samples)
from qiskit.ignis.verification import randomized_benchmarking as rb
%%time
# Ignis
# create the RB circuits
circs, _ = rb.randomized_benchmarking_seq(
rb_pattern=[qubits],
length_vector=lengths,
nseeds=num_samples,
seed_offset=seed,
)
# transpile (for basis translation)
transpiled = []
for qcs in circs:
for qc in qcs:
transpiled.append(transpile(qc, backend=backend, optimization_level=0))
# transpiled[0].draw(idle_wires=False)
from qiskit_experiments.library.randomized_benchmarking import StandardRB, InterleavedRB
%%time
# Experiments
# create experiment object
exp = StandardRB(
qubits=qubits,
lengths=lengths,
num_samples=num_samples,
seed=seed,
backend=backend,
)
# compute transpiled circuits
transpiled_qe = exp._transpiled_circuits()
# transpiled_qe[0].draw(idle_wires=False)
# common RB configuration
from qiskit.circuit import Delay
qubits=[2]
lengths=list(range(1, 1000, 100))
num_samples=3
seed=777
backend = FakeManila()
print("Cliford lengths:", lengths)
print("Number of circuits =", len(lengths)*num_samples*2)
%%time
# Ignis
# create the RB circuits
circuits, xdata, circuits_interleaved = rb.randomized_benchmarking_seq(
rb_pattern=[qubits],
length_vector=lengths,
nseeds=num_samples,
seed_offset=seed,
interleaved_elem=[Delay(duration=160)]
)
# transpile (for basis translation)
transpiled = []
for qcs in circuits:
for qc in qcs:
transpiled.append(transpile(qc, backend=backend, optimization_level=0))
for qcs in circuits_interleaved:
for qc in qcs:
transpiled.append(transpile(qc, backend=backend, optimization_level=0))
# transpiled[30].draw(idle_wires=False)
%%time
# Experiments
from qiskit_experiments.framework.backend_timing import BackendTiming
timing = BackendTiming(backend)
duration_in_dt = timing.round_delay(time=backend.properties().gate_length("sx", qubits)) # 160[dt]
# create experiment object
exp = InterleavedRB(
interleaved_element=Delay(duration=duration_in_dt),
qubits=qubits,
lengths=lengths,
num_samples=num_samples,
seed=seed,
backend=backend,
)
# compute transpiled circuits
transpiled_qe = exp._transpiled_circuits()
# transpiled_qe[30].draw(idle_wires=False)
duration_in_dt
timing.round_delay(time=100e-9) # 100[ns] == 450[dt]
# common RB configuration
from qiskit.circuit import Delay, QuantumCircuit
qubits=[3, 2]
lengths=list(range(1, 200, 20))
num_samples=3
seed=777
backend = FakeManila()
print("Cliford lengths:", lengths)
print("Number of circuits =", len(lengths)*num_samples*2)
delay_qc = QuantumCircuit(2)
delay_qc.delay(1600, 0)
delay_qc.delay(1600, 1)
delay_qc.draw()
%%time
# Ignis
# create the RB circuits
circuits, xdata, circuits_interleaved = rb.randomized_benchmarking_seq(
rb_pattern=[qubits],
length_vector=lengths,
nseeds=num_samples,
seed_offset=seed,
interleaved_elem=[delay_qc]
)
# transpile (for basis translation)
transpiled = []
for qcs in circuits:
for qc in qcs:
transpiled.append(transpile(qc, backend=backend, optimization_level=0))
for qcs in circuits_interleaved:
for qc in qcs:
transpiled.append(transpile(qc, backend=backend, optimization_level=0))
# transpiled[30].draw(idle_wires=False)
%%time
# Experiments
# create experiment object
exp = InterleavedRB(
interleaved_element=delay_qc,
qubits=qubits,
lengths=lengths,
num_samples=num_samples,
seed=seed,
backend=backend,
)
# compute transpiled circuits
transpiled_qe = exp._transpiled_circuits()
# transpiled_qe[30].draw(idle_wires=False)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, BasicAer
from qiskit.visualization import plot_bloch_multivector, plot_histogram
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
qc = QuantumCircuit(3)
# apply Hadamard
for q in range(3):
qc.h(q)
qc.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
res = execute(qc, backend=backend).result()
final_state = res.get_statevector()
print (final_state)
print (1./np.sqrt(8))
𝑋=[[0, 1] ,[1, 0]]
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.draw('mpl')
backend = Aer.get_backend('unitary_simulator')
res = execute(qc, backend=backend).result()
unitary = res.get_unitary()
print (unitary.round(2).real)
qc = QuantumCircuit(3)
qc.z(0)
qc.h(1)
qc.x(2)
qc.draw('mpl')
backend = Aer.get_backend('unitary_simulator')
res = execute(qc, backend=backend).result()
unitary = res.get_unitary()
print (unitary.round(2).real)
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
print (final_state.round(2))
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.draw()
backend_sv =Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend_sv).result().get_statevector()
print (final_state.round(2))
plot_bloch_multivector(final_state)
import qiskit
qiskit.__version__
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.z(1)
qc.draw()
final_state = execute(qc,backend_sv).result().get_statevector()
plot_bloch_multivector(final_state)
qc.cx(0,1)
qc.draw()
final_state = execute(qc,backend_sv).result().get_statevector()
print (final_state)
plot_bloch_multivector(final_state)
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.h(0)
qc.h(1)
display(qc.draw())
backend_uni = Aer.get_backend('unitary_simulator')
unitary = execute(qc,backend_uni).result().get_unitary()
print (unitary.round(2).real)
#array_to_latex(unitary, pretext="\\text{Circuit = }\n")
qc.cx(1,0)
display(qc.draw())
backend_uni = Aer.get_backend('unitary_simulator')
unitary = execute(qc,backend_uni).result().get_unitary()
print (unitary.round(2).real)
|
https://github.com/Axect/QuantumAlgorithms
|
Axect
|
import qiskit
qiskit.__qiskit_version__
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Load our saved IBMQ accounts.
IBMQ.load_account()
nQubits = 14 # number of physical qubits
a = 101 # the hidden integer whose bitstring is 1100101
# make sure that a can be represented with nQubits
a = a % 2**(nQubits)
# Creating registers
# qubits for querying the oracle and finding the hidden integer
qr = QuantumRegister(nQubits)
# for recording the measurement on qr
cr = ClassicalRegister(nQubits)
circuitName = "BernsteinVazirani"
bvCircuit = QuantumCircuit(qr, cr)
# Apply Hadamard gates before querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier so that it is not optimized by the compiler
bvCircuit.barrier()
# Apply the inner-product oracle
for i in range(nQubits):
if (a & (1 << i)):
bvCircuit.z(qr[i])
else:
bvCircuit.iden(qr[i])
# Apply barrier
bvCircuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Measurement
bvCircuit.barrier(qr)
bvCircuit.measure(qr, cr)
bvCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
results = execute(bvCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
backend = IBMQ.get_backend('ibmq_16_melbourne')
shots = 1000
bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1)
job_exp = execute(bvCircuit, backend=backend, shots=shots)
job_monitor(job_exp)
results = job_exp.result()
answer = results.get_counts(bvCircuit)
threshold = int(0.01 * shots) #the threshold of plotting significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed
filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index
plot_histogram(filteredAnswer)
print(filteredAnswer)
|
https://github.com/mlvqc/Byskit
|
mlvqc
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import *
from qiskit.aqua.algorithms import Grover
# First princinple for two parent nodes and one child
class byskit():
def __init__(self, backend, parents, child, evd = None):
self.backend = backend
self.parents = parents
self.child = child
self.n = int(np.shape(parents)[0]/2)
self.n_child = np.shape(child)[1]
self.ctrl = QuantumRegister(self.n, 'ctrl')
self.anc = QuantumRegister(self.n - 1, 'anc')
self.tgt = QuantumRegister(self.n_child, 'tgt')
if evd != None:
self.oracle = QuantumRegister(evd,'oracle')
self.circ = QuantumCircuit(self.ctrl, self.anc, self.tgt, self.oracle)
else:
self.circ = QuantumCircuit(self.ctrl, self.anc, self.tgt)
#self.c_ctrl = ClassicalRegister(self.n, 'c_ctrl')
#self.c_tgt = ClassicalRegister(self.n_child, 'c_tgt')
self.parent_init()
self.child_init()
def parent_init(self):
for i in range(self.n):
theta = self.calc_theta(self.parents[2*i], self.parents[2*i+1])
self.circ.ry(theta, i)
self.circ.barrier()
def child_init(self):
self.a = np.arange(0, 2 ** self.n)
self.gates = []
for i in self.a:
s = str(np.binary_repr(i, width=self.n))
self.gates.append(s)
for i in range(2**self.n):
self.xgate(self.gates[i])
for j in range(self.n_child):
theta = self.calc_theta(self.child[2 * i + 1,j], self.child[2 * i,j])
self.cn_ry(theta,j)
self.xgate(self.gates[i])
self.circ.barrier()
def xgate(self,gate):
for index, item in enumerate(gate):
if int(item) == 0:
self.circ.x(index)
#RY gates
def cn_ry(self,theta,target):
# compute
self.circ.ccx(self.ctrl[0], self.ctrl[1], self.anc[0])
for i in range(2, self.n):
self.circ.ccx(self.ctrl[i], self.anc[i - 2], self.anc[i - 1])
# copy
self.circ.cry(theta,self.anc[self.n - 2], self.tgt[target])
# uncompute
for i in range(self.n - 1, 1, -1):
self.circ.ccx(self.ctrl[i], self.anc[i - 2], self.anc[i - 1])
self.circ.ccx(self.ctrl[0], self.ctrl[1], self.anc[0])
def calc_theta(self,p1,p0):
return 2 * np.arctan(np.sqrt((p1)/(p0)))
def plot(self):
self.circ.draw(output='mpl')
plt.show()
def execute_circ(self):
self.circ.measure_all()
results = execute(self.circ, self.backend, shots=4321)
return results
def rejection_sampling(self, evidence, shots=1000, amplitude_amplification=False):
# Run job many times to get multiple samples
samples_list = []
self.n_samples = shots
if amplitude_amplification==True:
self.amplitude_amplification(evidence)
self.circ.measure_all()
#self.circ.measure((self.ctrl, self.tgt),(self.c_ctrl, self.c_tgt))
for i in range(self.n_samples):
job = execute(self.circ, backend=self.backend, shots=1)
result = list(job.result().get_counts(self.circ).keys())[0]
accept = True
for e in evidence:
if result[evidence[e]['n']]==evidence[e]['state']:
pass
else:
accept=False
if accept == True:
#print('Accepted result ', result)
samples_list.append(result)
print()
print(self.n_samples, 'samples drawn:', len(samples_list), 'samples accepted,', self.n_samples - len(samples_list),
'samples rejected.')
print('Percentage of samples rejected: ', 100 * (1 - (len(samples_list) / self.n_samples)), '%')
return samples_list
def evaluate(self, samples_list, observations):
p_o = 0
for sample in samples_list:
accept = True
for o in observations:
if sample[observations[o]['n']] == observations[o]['state']:
pass
else:
accept = False
if accept == True:
#print('Observation true given evidence')
p_o += 1
p_o /= len(samples_list)
print('Probabilty of observations given evidence = ', p_o)
return p_o
def amplitude_amplification(self,evidence):
self.state_preparation = self.circ
self.oracle = QuantumCircuit(self.ctrl, self.anc, self.tgt)
for index, e in enumerate(evidence):
if evidence[e]['state'] == '1':
self.oracle.z([evidence[e]['n']])
self.grover_op = Grover(self.oracle, state_preparation=self.state_preparation)
self.grover_op.draw()
def oracle(self):
pass
def u_gate(self):
pass
def gen_random_weights(n_parent,n_child):
np.random.seed(0)
p = np.random.rand(n_parent)
parents = []
for i in p:
parents.append(i)
parents.append(1 - i)
parents = np.array(parents)
child = np.random.rand(2 ** (n_parent + 1), n_child)
for i in range(n_child):
for j in range(2 ** (n_parent)):
child[2 * j + 1, i] = 1 - child[2 * j, i]
return parents, child
if __name__=='__main__':
from qiskit import IBMQ
IBMQ.load_account()
#provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = IBMQ.get_provider(hub='ibm-q-oxford', group='on-boarding', project='on-boarding-proj')
from qiskit import Aer #BasicAer
#backend = BasicAer.get_backend('unitary_simulator')
backend = Aer.get_backend('qasm_simulator')
n_parent = 3
n_child = 3
parents, children = gen_random_weights(n_parent, n_child)
b = byskit(backend, parents, children)
b.plot()
evidence = {
'one':{
'n':1,
'state':'1'
}
}
#b.rejection_sampling(evidence,amplitude_amplification=True)
sample_list = b.rejection_sampling(evidence)
observations = {
'three':{
'n':2,
'state':'0'
}
}
prob = b.evaluate(sample_list, observations)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Test cases for parameter manager."""
from copy import deepcopy
import numpy as np
from qiskit import pulse
from qiskit.circuit import Parameter
from qiskit.pulse.exceptions import PulseError, UnassignedDurationError
from qiskit.pulse.parameter_manager import ParameterGetter, ParameterSetter
from qiskit.pulse.transforms import AlignEquispaced, AlignLeft, inline_subroutines
from qiskit.test import QiskitTestCase
class ParameterTestBase(QiskitTestCase):
"""A base class for parameter manager unittest, providing test schedule."""
def setUp(self):
"""Just some useful, reusable Parameters, constants, schedules."""
super().setUp()
self.amp1_1 = Parameter("amp1_1")
self.amp1_2 = Parameter("amp1_2")
self.amp2 = Parameter("amp2")
self.amp3 = Parameter("amp3")
self.dur1 = Parameter("dur1")
self.dur2 = Parameter("dur2")
self.dur3 = Parameter("dur3")
self.parametric_waveform1 = pulse.Gaussian(
duration=self.dur1, amp=self.amp1_1 + self.amp1_2, sigma=self.dur1 / 4
)
self.parametric_waveform2 = pulse.Gaussian(
duration=self.dur2, amp=self.amp2, sigma=self.dur2 / 5
)
self.parametric_waveform3 = pulse.Gaussian(
duration=self.dur3, amp=self.amp3, sigma=self.dur3 / 6
)
self.ch1 = Parameter("ch1")
self.ch2 = Parameter("ch2")
self.ch3 = Parameter("ch3")
self.d1 = pulse.DriveChannel(self.ch1)
self.d2 = pulse.DriveChannel(self.ch2)
self.d3 = pulse.DriveChannel(self.ch3)
self.phi1 = Parameter("phi1")
self.phi2 = Parameter("phi2")
self.phi3 = Parameter("phi3")
self.meas_dur = Parameter("meas_dur")
self.mem1 = Parameter("s1")
self.reg1 = Parameter("m1")
self.context_dur = Parameter("context_dur")
# schedule under test
subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft())
subroutine += pulse.ShiftPhase(self.phi1, self.d1)
subroutine += pulse.Play(self.parametric_waveform1, self.d1)
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi3, self.d3)
long_schedule = pulse.ScheduleBlock(
alignment_context=AlignEquispaced(self.context_dur), name="long_schedule"
)
long_schedule += subroutine
long_schedule += pulse.ShiftPhase(self.phi2, self.d2)
long_schedule += pulse.Play(self.parametric_waveform2, self.d2)
with self.assertWarns(DeprecationWarning):
long_schedule += pulse.Call(sched)
long_schedule += pulse.Play(self.parametric_waveform3, self.d3)
long_schedule += pulse.Acquire(
self.meas_dur,
pulse.AcquireChannel(self.ch1),
mem_slot=pulse.MemorySlot(self.mem1),
reg_slot=pulse.RegisterSlot(self.reg1),
)
self.test_sched = long_schedule
class TestParameterGetter(ParameterTestBase):
"""Test getting parameters."""
def test_get_parameter_from_channel(self):
"""Test get parameters from channel."""
test_obj = pulse.DriveChannel(self.ch1 + self.ch2)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.ch1, self.ch2}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_pulse(self):
"""Test get parameters from pulse instruction."""
test_obj = self.parametric_waveform1
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.amp1_1, self.amp1_2, self.dur1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_acquire(self):
"""Test get parameters from acquire instruction."""
test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1))
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_inst(self):
"""Test get parameters from instruction."""
test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0))
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.phi2}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_call(self):
"""Test get parameters from instruction."""
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi1, self.d1)
with self.assertWarns(DeprecationWarning):
test_obj = pulse.Call(subroutine=sched)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_with_function(self):
"""Test ParameterExpressions formed trivially in a function."""
def get_shift(variable):
return variable - 1
test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.phi1, self.ch1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_alignment_context(self):
"""Test get parameters from alignment context."""
test_obj = AlignEquispaced(duration=self.context_dur + self.dur1)
visitor = ParameterGetter()
visitor.visit(test_obj)
ref_params = {self.context_dur, self.dur1}
self.assertSetEqual(visitor.parameters, ref_params)
def test_get_parameter_from_complex_schedule(self):
"""Test get parameters from complicated schedule."""
test_block = deepcopy(self.test_sched)
visitor = ParameterGetter()
visitor.visit(test_block)
self.assertEqual(len(visitor.parameters), 17)
class TestParameterSetter(ParameterTestBase):
"""Test setting parameters."""
def test_set_parameter_to_channel(self):
"""Test set parameters from channel."""
test_obj = pulse.DriveChannel(self.ch1 + self.ch2)
value_dict = {self.ch1: 1, self.ch2: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.DriveChannel(3)
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_pulse(self):
"""Test set parameters from pulse instruction."""
test_obj = self.parametric_waveform1
value_dict = {self.amp1_1: 0.1, self.amp1_2: 0.2, self.dur1: 160}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.Gaussian(duration=160, amp=0.3, sigma=40)
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_acquire(self):
"""Test set parameters to acquire instruction."""
test_obj = pulse.Acquire(16000, pulse.AcquireChannel(self.ch1), pulse.MemorySlot(self.ch1))
value_dict = {self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.Acquire(16000, pulse.AcquireChannel(2), pulse.MemorySlot(2))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_inst(self):
"""Test get parameters from instruction."""
test_obj = pulse.ShiftPhase(self.phi1 + self.phi2, pulse.DriveChannel(0))
value_dict = {self.phi1: 0.123, self.phi2: 0.456}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.ShiftPhase(0.579, pulse.DriveChannel(0))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_call(self):
"""Test get parameters from instruction."""
sched = pulse.Schedule()
sched += pulse.ShiftPhase(self.phi1, self.d1)
with self.assertWarns(DeprecationWarning):
test_obj = pulse.Call(subroutine=sched)
value_dict = {self.phi1: 1.57, self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_sched = pulse.Schedule()
ref_sched += pulse.ShiftPhase(1.57, pulse.DriveChannel(2))
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Call(subroutine=ref_sched)
self.assertEqual(assigned, ref_obj)
def test_with_function(self):
"""Test ParameterExpressions formed trivially in a function."""
def get_shift(variable):
return variable - 1
test_obj = pulse.ShiftPhase(get_shift(self.phi1), self.d1)
value_dict = {self.phi1: 2.0, self.ch1: 2}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = pulse.ShiftPhase(1.0, pulse.DriveChannel(2))
self.assertEqual(assigned, ref_obj)
def test_set_parameter_to_alignment_context(self):
"""Test get parameters from alignment context."""
test_obj = AlignEquispaced(duration=self.context_dur + self.dur1)
value_dict = {self.context_dur: 1000, self.dur1: 100}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_obj = AlignEquispaced(duration=1100)
self.assertEqual(assigned, ref_obj)
def test_nested_assignment_partial_bind(self):
"""Test nested schedule with call instruction.
Inline the schedule and partially bind parameters."""
context = AlignEquispaced(duration=self.context_dur)
subroutine = pulse.ScheduleBlock(alignment_context=context)
subroutine += pulse.Play(self.parametric_waveform1, self.d1)
nested_block = pulse.ScheduleBlock()
with self.assertWarns(DeprecationWarning):
nested_block += pulse.Call(subroutine=subroutine)
test_obj = pulse.ScheduleBlock()
test_obj += nested_block
test_obj = inline_subroutines(test_obj)
value_dict = {self.context_dur: 1000, self.dur1: 200, self.ch1: 1}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
ref_context = AlignEquispaced(duration=1000)
ref_subroutine = pulse.ScheduleBlock(alignment_context=ref_context)
ref_subroutine += pulse.Play(
pulse.Gaussian(200, self.amp1_1 + self.amp1_2, 50), pulse.DriveChannel(1)
)
ref_nested_block = pulse.ScheduleBlock()
ref_nested_block += ref_subroutine
ref_obj = pulse.ScheduleBlock()
ref_obj += ref_nested_block
self.assertEqual(assigned, ref_obj)
def test_complex_valued_parameter(self):
"""Test complex valued parameter can be casted to a complex value,
but raises PendingDeprecationWarning.."""
amp = Parameter("amp")
test_obj = pulse.Constant(duration=160, amp=1j * amp)
value_dict = {amp: 0.1}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(test_obj)
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Constant(duration=160, amp=1j * 0.1)
self.assertEqual(assigned, ref_obj)
def test_complex_value_to_parameter(self):
"""Test complex value can be assigned to parameter object,
but raises PendingDeprecationWarning."""
amp = Parameter("amp")
test_obj = pulse.Constant(duration=160, amp=amp)
value_dict = {amp: 0.1j}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(test_obj)
with self.assertWarns(DeprecationWarning):
ref_obj = pulse.Constant(duration=160, amp=1j * 0.1)
self.assertEqual(assigned, ref_obj)
def test_complex_parameter_expression(self):
"""Test assignment of complex-valued parameter expression to parameter,
but raises PendingDeprecationWarning."""
amp = Parameter("amp")
mag = Parameter("A")
phi = Parameter("phi")
test_obj = pulse.Constant(duration=160, amp=amp)
test_obj_copy = deepcopy(test_obj)
# generate parameter expression
value_dict = {amp: mag * np.exp(1j * phi)}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_obj)
# generate complex value
value_dict = {mag: 0.1, phi: 0.5}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
assigned = visitor.visit(assigned)
# evaluated parameter expression: 0.0877582561890373 + 0.0479425538604203*I
value_dict = {amp: 0.1 * np.exp(0.5j)}
visitor = ParameterSetter(param_map=value_dict)
with self.assertWarns(PendingDeprecationWarning):
ref_obj = visitor.visit(test_obj_copy)
self.assertEqual(assigned, ref_obj)
def test_invalid_pulse_amplitude(self):
"""Test that invalid parameters are still checked upon assignment."""
amp = Parameter("amp")
test_sched = pulse.ScheduleBlock()
test_sched.append(
pulse.Play(
pulse.Constant(160, amp=2 * amp),
pulse.DriveChannel(0),
),
inplace=True,
)
with self.assertRaises(PulseError):
test_sched.assign_parameters({amp: 0.6}, inplace=False)
def test_set_parameter_to_complex_schedule(self):
"""Test get parameters from complicated schedule."""
test_block = deepcopy(self.test_sched)
value_dict = {
self.amp1_1: 0.1,
self.amp1_2: 0.2,
self.amp2: 0.3,
self.amp3: 0.4,
self.dur1: 100,
self.dur2: 125,
self.dur3: 150,
self.ch1: 0,
self.ch2: 2,
self.ch3: 4,
self.phi1: 1.0,
self.phi2: 2.0,
self.phi3: 3.0,
self.meas_dur: 300,
self.mem1: 3,
self.reg1: 0,
self.context_dur: 1000,
}
visitor = ParameterSetter(param_map=value_dict)
assigned = visitor.visit(test_block)
# create ref schedule
subroutine = pulse.ScheduleBlock(alignment_context=AlignLeft())
subroutine += pulse.ShiftPhase(1.0, pulse.DriveChannel(0))
subroutine += pulse.Play(pulse.Gaussian(100, 0.3, 25), pulse.DriveChannel(0))
sched = pulse.Schedule()
sched += pulse.ShiftPhase(3.0, pulse.DriveChannel(4))
ref_obj = pulse.ScheduleBlock(alignment_context=AlignEquispaced(1000), name="long_schedule")
ref_obj += subroutine
ref_obj += pulse.ShiftPhase(2.0, pulse.DriveChannel(2))
ref_obj += pulse.Play(pulse.Gaussian(125, 0.3, 25), pulse.DriveChannel(2))
with self.assertWarns(DeprecationWarning):
ref_obj += pulse.Call(sched)
ref_obj += pulse.Play(pulse.Gaussian(150, 0.4, 25), pulse.DriveChannel(4))
ref_obj += pulse.Acquire(
300, pulse.AcquireChannel(0), pulse.MemorySlot(3), pulse.RegisterSlot(0)
)
self.assertEqual(assigned, ref_obj)
class TestAssignFromProgram(QiskitTestCase):
"""Test managing parameters from programs. Parameter manager is implicitly called."""
def test_attribute_parameters(self):
"""Test the ``parameter`` attributes."""
sigma = Parameter("sigma")
amp = Parameter("amp")
waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp)
block = pulse.ScheduleBlock()
block += pulse.Play(waveform, pulse.DriveChannel(10))
ref_set = {amp, sigma}
self.assertSetEqual(set(block.parameters), ref_set)
def test_parametric_pulses(self):
"""Test Parametric Pulses with parameters determined by ParameterExpressions
in the Play instruction."""
sigma = Parameter("sigma")
amp = Parameter("amp")
waveform = pulse.library.Gaussian(duration=128, sigma=sigma, amp=amp)
block = pulse.ScheduleBlock()
block += pulse.Play(waveform, pulse.DriveChannel(10))
block.assign_parameters({amp: 0.2, sigma: 4}, inplace=True)
self.assertEqual(block.blocks[0].pulse.amp, 0.2)
self.assertEqual(block.blocks[0].pulse.sigma, 4.0)
def test_parameters_from_subroutine(self):
"""Test that get parameter objects from subroutines."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
program_layer0 = pulse.Schedule()
program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0))
# from call instruction
program_layer1 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer1 += pulse.instructions.Call(program_layer0)
self.assertEqual(program_layer1.get_parameters("amp")[0], param1)
# from nested call instruction
program_layer2 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer2 += pulse.instructions.Call(program_layer1)
self.assertEqual(program_layer2.get_parameters("amp")[0], param1)
def test_assign_parameter_to_subroutine(self):
"""Test that assign parameter objects to subroutines."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
program_layer0 = pulse.Schedule()
program_layer0 += pulse.Play(waveform, pulse.DriveChannel(0))
reference = program_layer0.assign_parameters({param1: 0.1}, inplace=False)
# to call instruction
program_layer1 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer1 += pulse.instructions.Call(program_layer0)
target = program_layer1.assign_parameters({param1: 0.1}, inplace=False)
self.assertEqual(inline_subroutines(target), reference)
# to nested call instruction
program_layer2 = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
program_layer2 += pulse.instructions.Call(program_layer1)
target = program_layer2.assign_parameters({param1: 0.1}, inplace=False)
self.assertEqual(inline_subroutines(target), reference)
def test_assign_parameter_to_subroutine_parameter(self):
"""Test that assign parameter objects to parameter of subroutine."""
param1 = Parameter("amp")
waveform = pulse.library.Constant(duration=100, amp=param1)
param_sub1 = Parameter("p1")
param_sub2 = Parameter("p2")
subroutine = pulse.Schedule()
subroutine += pulse.Play(waveform, pulse.DriveChannel(0))
reference = subroutine.assign_parameters({param1: 0.6}, inplace=False)
main_prog = pulse.Schedule()
pdict = {param1: param_sub1 + param_sub2}
with self.assertWarns(DeprecationWarning):
main_prog += pulse.instructions.Call(subroutine, value_dict=pdict)
# parameter is overwritten by parameters
self.assertEqual(len(main_prog.parameters), 2)
target = main_prog.assign_parameters({param_sub1: 0.1, param_sub2: 0.5}, inplace=False)
result = inline_subroutines(target)
self.assertEqual(result, reference)
class TestScheduleTimeslots(QiskitTestCase):
"""Test for edge cases of timing overlap on parametrized channels.
Note that this test is dedicated to `Schedule` since `ScheduleBlock` implicitly
assigns instruction time t0 that doesn't overlap with existing instructions.
"""
def test_overlapping_pulses(self):
"""Test that an error is still raised when overlapping instructions are assigned."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
with self.assertRaises(PulseError):
schedule |= pulse.Play(
pulse.Waveform([0.5, 0.5, 0.5, 0.5]), pulse.DriveChannel(param_idx)
)
def test_overlapping_on_assignment(self):
"""Test that assignment will catch against existing instructions."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx: 1})
def test_overlapping_on_expression_assigment_to_zero(self):
"""Test constant*zero expression conflict."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(2 * param_idx))
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx: 0})
def test_merging_upon_assignment(self):
"""Test that schedule can match instructions on a channel."""
param_idx = Parameter("q")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(1))
schedule = schedule.insert(
4, pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx))
)
schedule.assign_parameters({param_idx: 1})
self.assertEqual(schedule.ch_duration(pulse.DriveChannel(1)), 8)
self.assertEqual(schedule.channels, (pulse.DriveChannel(1),))
def test_overlapping_on_multiple_assignment(self):
"""Test that assigning one qubit then another raises error when overlapping."""
param_idx1 = Parameter("q1")
param_idx2 = Parameter("q2")
schedule = pulse.Schedule()
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx1))
schedule |= pulse.Play(pulse.Waveform([1, 1, 1, 1]), pulse.DriveChannel(param_idx2))
schedule.assign_parameters({param_idx1: 2})
with self.assertRaises(PulseError):
schedule.assign_parameters({param_idx2: 2})
def test_cannot_build_schedule_with_unassigned_duration(self):
"""Test we cannot build schedule with parameterized instructions"""
dur = Parameter("dur")
ch = pulse.DriveChannel(0)
test_play = pulse.Play(pulse.Gaussian(dur, 0.1, dur / 4), ch)
sched = pulse.Schedule()
with self.assertRaises(UnassignedDurationError):
sched.insert(0, test_play)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Chi quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.channel import Chi
from .channel_test_case import ChannelTestCase
class TestChi(ChannelTestCase):
"""Tests for Chi channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = Chi(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat16 = np.eye(16) / 4
chan = Chi(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Chi, mat16, input_dims=2, output_dims=4)
# Non multi-qubit dimensions should raise exception
self.assertRaises(QiskitError, Chi, np.eye(6) / 2, input_dims=3, output_dims=2)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Chi(circuit)
target = Chi(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Chi, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4, real=True)
self.assertEqual(Chi(mat), Chi(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = Chi(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Chi(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Chi(self.depol_chi(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(Chi(1.25 * self.chiI - 0.25 * self.depol_chi(1)).is_cptp())
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Chi(np.eye(4)).compose, Chi(np.eye(16)))
self.assertRaises(QiskitError, Chi(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Chi(self.chiX)
chan2 = Chi(self.chiY)
chan = chan1.compose(chan2)
target = rho.evolve(Chi(self.chiZ))
output = rho.evolve(chan)
self.assertEqual(output, target)
# 50% depolarizing channel
chan1 = Chi(self.depol_chi(0.5))
chan = chan1.compose(chan1)
target = rho.evolve(Chi(self.depol_chi(0.75)))
output = rho.evolve(chan)
self.assertEqual(output, target)
# Compose random
chi1 = self.rand_matrix(4, 4, real=True)
chi2 = self.rand_matrix(4, 4, real=True)
chan1 = Chi(chi1, input_dims=2, output_dims=2)
chan2 = Chi(chi2, input_dims=2, output_dims=2)
target = rho.evolve(chan1).evolve(chan2)
chan = chan1.compose(chan2)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(output, target)
chan = chan1 & chan2
output = rho.evolve(chan)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(output, target)
def test_dot(self):
"""Test dot method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Chi(self.chiX)
chan2 = Chi(self.chiY)
target = rho.evolve(Chi(self.chiZ))
output = rho.evolve(chan2.dot(chan1))
self.assertEqual(output, target)
# Compose random
chi1 = self.rand_matrix(4, 4, real=True)
chi2 = self.rand_matrix(4, 4, real=True)
chan1 = Chi(chi1, input_dims=2, output_dims=2)
chan2 = Chi(chi2, input_dims=2, output_dims=2)
target = rho.evolve(chan1).evolve(chan2)
chan = chan2.dot(chan1)
output = rho.evolve(chan)
self.assertEqual(output, target)
chan = chan2 @ chan1
output = rho.evolve(chan)
self.assertEqual(output, target)
def test_compose_front(self):
"""Test front compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Chi(self.chiX)
chan2 = Chi(self.chiY)
chan = chan2.compose(chan1, front=True)
target = rho.evolve(Chi(self.chiZ))
output = rho.evolve(chan)
self.assertEqual(output, target)
# Compose random
chi1 = self.rand_matrix(4, 4, real=True)
chi2 = self.rand_matrix(4, 4, real=True)
chan1 = Chi(chi1, input_dims=2, output_dims=2)
chan2 = Chi(chi2, input_dims=2, output_dims=2)
target = rho.evolve(chan1).evolve(chan2)
chan = chan2.compose(chan1, front=True)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(output, target)
def test_expand(self):
"""Test expand method."""
# Pauli channels
paulis = [self.chiI, self.chiX, self.chiY, self.chiZ]
targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats
for i, chi1 in enumerate(paulis):
for j, chi2 in enumerate(paulis):
chan1 = Chi(chi1)
chan2 = Chi(chi2)
chan = chan1.expand(chan2)
# Target for diagonal Pauli channel
targ = Chi(np.diag(targs[i + 4 * j]))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan, targ)
# Completely depolarizing
rho = DensityMatrix(np.diag([1, 0, 0, 0]))
chan_dep = Chi(self.depol_chi(1))
chan = chan_dep.expand(chan_dep)
target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(output, target)
def test_tensor(self):
"""Test tensor method."""
# Pauli channels
paulis = [self.chiI, self.chiX, self.chiY, self.chiZ]
targs = 4 * np.eye(16) # diagonals of Pauli channel Chi mats
for i, chi1 in enumerate(paulis):
for j, chi2 in enumerate(paulis):
chan1 = Chi(chi1)
chan2 = Chi(chi2)
chan = chan2.tensor(chan1)
# Target for diagonal Pauli channel
targ = Chi(np.diag(targs[i + 4 * j]))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan, targ)
# Test overload
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan, targ)
# Completely depolarizing
rho = DensityMatrix(np.diag([1, 0, 0, 0]))
chan_dep = Chi(self.depol_chi(1))
chan = chan_dep.tensor(chan_dep)
target = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
output = rho.evolve(chan)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(output, target)
# Test operator overload
chan = chan_dep ^ chan_dep
output = rho.evolve(chan)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(output, target)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = Chi(self.depol_chi(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = Chi(self.depol_chi(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.chiI
mat2 = 0.5 * self.depol_chi(1)
chan1 = Chi(mat1)
chan2 = Chi(mat2)
targ = Chi(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = Chi(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 = Chi(mat)
op0 = Chi(mat0)
op1 = Chi(mat1)
op01 = op1.tensor(op0)
eye = Chi(self.chiI)
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 = Chi(mat)
op0 = Chi(mat0)
op1 = Chi(mat1)
op01 = op1.tensor(op0)
eye = Chi(self.chiI)
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 = Chi(self.chiI)
chan2 = Chi(np.eye(16))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = Chi(self.chiI)
val = 0.5
targ = Chi(val * self.chiI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = Chi(self.chiI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Chi(self.chiI)
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 = Chi(self.chiI)
targ = Chi(-self.chiI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import os, shutil, time
from random_qubo.random_qubo import RandomQubo
DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y")
def getPath(filename = "", directory = ""):
return DIR + "/" + directory + "/" + filename
bounds = {"matrix_q_lb": -5, "matrix_q_ub": 5, "c_lb": -5, "c_ub": 5}
DIR
shutil.rmtree(DIR, ignore_errors=True)
os.makedirs(getPath(directory = "SPARSE"))
os.makedirs(getPath(directory = "DENSE"))
os.makedirs(getPath(directory = "MULTIPLE"))
os.makedirs(getPath(directory = "CPLEX"))
# create sparse random qubos
# 3 variables connected
# start with 3x1 qubits
qaoa_max_qubits = 27 # number of qubits in Falcon r5.1 processors
var = 3
multiple = 1
while True:
qp = RandomQubo.create_random_qubo("test_" + str(multiple), var, multiple=multiple, **bounds)
qp.write_to_lp_file(getPath(qp.name, directory = "SPARSE"))
if qp.get_num_vars() > qaoa_max_qubits :
print(multiple)
break
multiple = multiple + 1
# create dense random qubos
# start with 3 variables
while True:
qp = RandomQubo.create_random_qubo("test_" + str(var), var, **bounds)
qp.write_to_lp_file(getPath(qp.name, directory = "DENSE"))
if qp.get_num_vars() > qaoa_max_qubits :
print(var)
break
var = var + 3
# create more test data for pegasus
# instances with several times the last instance which Mumbai is able to solve
# 27 variables each
# start with 27x2 qubits
var = qaoa_max_qubits
multiples = [2, 5, 10, 20]
for multiple in multiples:
qp = RandomQubo.create_random_qubo("test_" + str(multiple), var, multiple=multiple, **bounds)
qp.write_to_lp_file(getPath(qp.name, directory = "MULTIPLE"))
qp = RandomQubo.create_random_qubo("test_cplex", 100, **bounds) # used 10 for test data
qp.write_to_lp_file(getPath(qp.name, directory = "CPLEX"))
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import sys, math, time
from qiskit import BasicAer, execute
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
def get_circuit(Nbits):
q = QuantumRegister(Nbits)
c = ClassicalRegister(Nbits)
ckt = QuantumCircuit(q, c)
ckt.h(q)
ckt.barrier()
ckt.measure(q,c)
return ckt
Nbits = 5;
ckt = get_circuit(Nbits)
ckt.draw(output = 'mpl')
ckt=get_circuit(Nbits)
n_qubits = ckt.n_qubits
backend=BasicAer.get_backend("qasm_simulator")
job = execute(ckt, backend=backend, shots=1000, memory=True)
res = job.result()
bit_str = ''.join(job.result().get_memory())
#print (res)
def get_random_Float(ckt, vmin=0., vmax =10.0, size=20 ):
nbits = 100
n_qubits = ckt.n_qubits
#print (n_qubits)
Nshots = (nbits * size + n_qubits -1) // n_qubits;
#print ('Nshots=',Nshots)
backend=BasicAer.get_backend("qasm_simulator");
job = execute(ckt, backend=backend, shots=Nshots, memory=True);
#print (job.result())
bit_str = ''.join(job.result().get_memory())
#print (bit_str, len(bit_str))
scale = float(vmax-vmin)/float(2**nbits-1)
random_vec = np.array([ vmin + scale*float(int(bit_str[i:i+nbits], 2))
for i in range(0, nbits*size, nbits)], dtype=float)
return random_vec
ckt=get_circuit(Nbits)
Rvec=get_random_Float(ckt)
print (Rvec, len(Rvec))
# Draw a sample from uniform distribution.
t1 = time.time()
sample = get_random_Float(ckt, vmin=-7.67, vmax=19.52, size=100)
#sample = uniform_rand_float64(circuit, glo_num_qubits, size=4321, vmin=-7.67, vmax=19.52)
t2 = time.time() - t1
print (t2)
# Print out some details.
print("Uniform distribution over floating point numbers:")
print(" sample type:", type(sample), ", element type:", sample.dtype,", shape:", sample.shape)
print(" sample min: {:.4f}, max: {:.4f}".format(np.amin(sample), np.amax(sample)))
print(" sampling time: {:.2f} secs".format(t2))
# Plotting the distribution.
plt.hist(sample.ravel(),
bins=min(int(np.ceil(np.sqrt(sample.size))), 100),
density=True, facecolor='b', alpha=0.75)
plt.xlabel("value", size=12)
plt.ylabel("probability", size=12)
plt.title("Uniform distribution over float64 numbers in\
[{:.2f} ... {:.2f}]".format(
np.amin(sample), np.amax(sample)), size=12)
plt.grid(True)
# plt.savefig("uniform_distrib_float.png", bbox_inches="tight")
plt.show()
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
import numpy as np
from qiskit.quantum_info import state_fidelity, Statevector
def getStatevector(circuit):
return Statevector(circuit).data
import warnings
warnings.filterwarnings('ignore')
def P_haar(N, F):
if F == 1:
return 0
else:
return (N - 1) * ((1 - F) ** (N - 2))
def KL(P, Q):
epsilon = 1e-8
kl_divergence = 0.0
for p, q in zip(P, Q):
kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) )
return abs(kl_divergence)
def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False):
unit = 1 / bins
limits = []
probabilities = np.array([0] * bins)
for i in range(1, bins + 1):
limits.append(unit * i)
for i in range(epoch):
circuit_1 = sampler(layer=layer, qubits=qubits)
circuit_2 = sampler(layer=layer, qubits=qubits)
f = state_fidelity(
getStatevector(circuit_1),
getStatevector(circuit_2)
)
for j in range(bins):
if f <= limits[j]:
probabilities[j] += 1
break
pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits]
probabilities = [ p / epoch for p in probabilities ]
if return_detail:
return pHaar_vqc, probabilities
else:
return KL(probabilities, pHaar_vqc)
|
https://github.com/nielsaNTNU/qiskit_utilities
|
nielsaNTNU
|
import pylab as pl
import qiskit.tools.jupyter
from GenerateRandomCircuit import *
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info import Kraus, SuperOp
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.visualization import plot_histogram
# Import from Qiskit Aer noise module
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise import QuantumError, ReadoutError
from qiskit.providers.aer.noise import depolarizing_error
from qiskit.providers.aer.noise import thermal_relaxation_error
backendname_sim = Aer.get_backend('qasm_simulator')
G_qasm_simulator=createGraph(backendname_sim,5)
nx.draw_networkx(G_qasm_simulator)
circ = randomCircuit(G_qasm_simulator, depth=20)
circ.draw(output='mpl')
circs=[]
for i in range(1024):
circs.append(circ)
job_clean = execute(circs, backendname_sim, shots=1024)
results_clean=job_clean.result().results
# counts_clean=job.result().get_counts()
# plot_histogram(counts_clean)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 5) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 5) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(5)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(5):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(5):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
job_thermal = execute(circs, backendname_sim,
basis_gates=noise_thermal.basis_gates,
noise_model=noise_thermal,shots=1024)
results_thermal=job_thermal.result().results
# result_thermal = job.result()
counts_clean = job_clean.result().get_counts(0)
counts_thermal = job_thermal.result().get_counts(0)
# Plot noisy output
plot_histogram([counts_thermal,counts_clean],legend=['thermal','clean'])
numones=np.zeros((2**5,1))
for i in range(2**5):
numones[i]=bin(i).count("1")
def expectationValue(results):
#num_qubits = results[0].header.n_qubits
E=np.zeros((len(results),1))
for item in range(0,len(results)):
shots = results[item].shots
counts = results[item].data.counts
for key in list(counts.__dict__.keys()):
c=getattr(counts, key)#number of counts
E[item] += numones[int(key,0)]*c/shots
E_conv = np.zeros_like(E)
for j in range(1,len(results)+1):
E_conv[j-1] = sum(E[0:j])/j
return E, E_conv
E_clean, E_conv_clean = expectationValue(job_clean.result().results)
E_thermal, E_conv_thermal = expectationValue(job_thermal.result().results)
pl.plot(E_conv_clean)
pl.plot(E_conv_thermal)
|
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/TheGupta2012/QickStart-Challenges
|
TheGupta2012
|
## Enter Team ID
import os
os.environ["TEAMID"] = "Excalibur"
from qiskit import QuantumCircuit
def dj_circuit_2q(oracle):
dj_circuit = QuantumCircuit(3,2)
### Your code here
dj_circuit.x(2)
dj_circuit.barrier()
dj_circuit.h(range(3))
dj_circuit.barrier()
dj_circuit.compose(oracle, inplace = True)
dj_circuit.barrier()
dj_circuit.h(range(2))
dj_circuit.measure(range(2), range(2))
### Your code here
return dj_circuit
def test_function_1():
# a constant oracle with f(x)=0 for all inputs
oracle = QuantumCircuit(3)
oracle.id(2)
dj_circuit = dj_circuit_2q(oracle)
return dj_circuit
test_function_1().draw()
from grader.graders.problem_4.grader import grader1
grader1.evaluate(dj_circuit_2q)
def dj_circuit_4q(oracle):
circuit = QuantumCircuit(5, 4)
### Your code here
circuit.x(4)
circuit.barrier()
circuit.h(range(5))
circuit.barrier()
circuit.compose(oracle, inplace = True)
circuit.barrier()
circuit.h(range(4))
circuit.measure(range(4), range(4))
### Your code here
return circuit
def test_function_2():
oracle = QuantumCircuit(5)
oracle.id(4)
dj_circuit = dj_circuit_4q(oracle)
return dj_circuit
test_function_2().draw()
from grader.graders.problem_4.grader import grader2
grader2.evaluate(dj_circuit_4q)
from qiskit import QuantumCircuit
def dj_circuit_general(n, oracle):
dj_circuit = QuantumCircuit(n+1, n)
### Your code here
dj_circuit.x(n)
dj_circuit.barrier()
dj_circuit.h(range(n+1))
dj_circuit.barrier()
dj_circuit.compose(oracle, inplace = True)
dj_circuit.barrier()
dj_circuit.h(range(n))
dj_circuit.measure(range(n), range(n))
### Your code here
return dj_circuit
def test_function_3():
N = 6
# constant oracle with f(x) = 0
oracle = QuantumCircuit(7)
oracle.id(6)
circuit = dj_circuit_general(N, oracle)
return circuit
test_function_3().draw()
from grader.graders.problem_4.grader import grader3
grader3.evaluate(dj_circuit_general)
|
https://github.com/rochisha0/stock-picking
|
rochisha0
|
from qiskit.finance.data_providers import RandomDataProvider
import numpy as np
import matplotlib.pyplot as plt
import datetime
import pandas as pd
from nsepy import get_history
from docplex.mp.model import Model
from qiskit.optimization import QuadraticProgram
from qiskit.optimization.converters import LinearEqualityToPenalty
from qiskit.aqua.algorithms import NumPyMinimumEigensolver
import pennylane as qml
num_assets = 3
# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(tickers=stocks,
start=datetime.datetime(2016,1,1),
end=datetime.datetime(2016,1,30))
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
q = 0.5 # set risk factor
budget = 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
mdl = Model('docplex model')
x = mdl.binary_var_list(num_assets)
# set objective function:
#
# maximize { mu^T * x - q * x^T * sigma * x }
#
objective = mdl.sum([mu[i] * x[i] for i in range(num_assets)]) # mu^T * x
objective -= q * mdl.sum([sigma[i][j]*x[i]*x[j] for i in range(num_assets) for j in range(num_assets)])
mdl.maximize(objective)
# add budget constraint:
#
# 1^T * x == budget
#
cost = mdl.sum([x[i] for i in range(num_assets)])
mdl.add_constraint(cost == budget, ctname='budget')
# converting to Quadratic Program
mod = QuadraticProgram()
mod.from_docplex(mdl)
#removing the constraint to create the QUBO
lineq2penalty = LinearEqualityToPenalty(penalty)
qubo = lineq2penalty.convert(mod)
#converting QUBO to an Ising Hamiltonian
H, offset = qubo.to_ising()
H.num_qubits
H = H.to_legacy_op()
H.print_details()
def ansatz(theta):
qml.RX(theta[0], wires=0)
qml.RX(theta[1], wires=1)
qml.RX(theta[2], wires=2)
qml.CNOT(wires=[0,1])
qml.CNOT(wires=[0,2])
qml.CNOT(wires=[1,2])
qml.RX(theta[3], wires=0)
qml.RX(theta[4], wires=1)
qml.RX(theta[5], wires=2)
qml.CNOT(wires=[0,1])
qml.CNOT(wires=[0,2])
qml.CNOT(wires=[1,2])
qml.RX(theta[6], wires=0)
qml.RX(theta[7], wires=1)
qml.RX(theta[8], wires=2)
return ansatz
dev1 = qml.device("default.qubit", wires=3)
@qml.qnode(dev1)
def circuit_IIZ(params):
ansatz(params)
return qml.expval(qml.Identity(0)@qml.Identity(1)@qml.PauliZ(2))
@qml.qnode(dev1)
def circuit_IZI(params):
ansatz(params)
return qml.expval(qml.Identity(0)@qml.PauliZ(1)@qml.Identity(2))
@qml.qnode(dev1)
def circuit_ZII(params):
ansatz(params)
return qml.expval(qml.PauliZ(0)@qml.Identity(1)@qml.Identity(2))
@qml.qnode(dev1)
def circuit_IZZ(params):
ansatz(params)
return qml.expval(qml.Identity(0)@qml.PauliZ(1)@qml.PauliZ(2))
@qml.qnode(dev1)
def circuit_ZIZ(params):
ansatz(params)
return qml.expval(qml.PauliZ(0)@qml.Identity(1)@qml.PauliZ(2))
@qml.qnode(dev1)
def circuit_ZZI(params):
ansatz(params)
return qml.expval(qml.PauliZ(0)@qml.PauliZ(1)@qml.Identity(2))
def pauli_operator_to_dict(pauli_operator):
d = pauli_operator.to_dict()
paulis = d['paulis']
paulis_dict = {}
for x in paulis:
label = x['label']
coeff = x['coeff']['real']
paulis_dict[label] = coeff
return paulis_dict
pauli_dict = pauli_operator_to_dict(H)
def vqe(parameters):
expval_ZII = pauli_dict['ZII'] * circuit_ZII(parameters)
expval_IIZ = pauli_dict['IIZ'] * circuit_IIZ(parameters)
expval_IZI = pauli_dict['IZI'] * circuit_IZI(parameters)
expval_ZZI = pauli_dict['ZZI'] * circuit_ZZI(parameters)
expval_ZIZ = pauli_dict['ZIZ'] * circuit_ZIZ(parameters)
expval_IZZ = pauli_dict['IZZ'] * circuit_IZZ(parameters)
# summing the measurement results
classical_adder = expval_ZII + expval_IIZ + expval_ZIZ + expval_ZZI + expval_ZIZ + expval_IZZ
return classical_adder
opt = qml.GradientDescentOptimizer(stepsize=0.5)
value = []
# optimize parameters in objective
params = np.random.rand(9)
steps = 200
for i in range(steps):
params = opt.step(vqe, params)
value.append(vqe(params))
plt.plot(value)
@qml.qnode(dev1)
def final_circ(params):
ansatz(params)
return qml.probs(wires=[0,1,2])
params
plt.bar(['000', '001', '010', '011', '100', '101', '110', '111'], final_circ(params))
from qiskit.optimization.applications.ising.common import sample_most_likely
exact_eigensolver = NumPyMinimumEigensolver(H)
result = exact_eigensolver.run()
sample_most_likely(result.eigenstate)
pauli_dict
H.print_details()
|
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/MAI-cyber/QIT
|
MAI-cyber
|
# ! pip install numpy
# ! pip install qiskit
# ! pip install matplotlib
from qiskit import QuantumCircuit, Aer ,BasicAer, execute
from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_qsphere
from qiskit.quantum_info import Statevector
import matplotlib.pyplot as plt
import numpy as np
def phase_oracle(name = 'Of'):
qc = QuantumCircuit(3, name=name)
qc.x(1)
qc.cx(1,2)
qc.x(1)
return qc
def diffuser( name='V'):
qc = QuantumCircuit(3, name=name)
for qb in range(2): #first layer of Hadamards in diffuser
qc.h(qb)
for i in range(2):
qc.x(i)
qc.ccx(0,1,2)
for i in range(2):
qc.x(i)
for qb in range(2): #second layer of Hadamards in diffuser
qc.h(qb)
return qc
n = 2
gr = QuantumCircuit(n+1, 2)
m = 2 # Number of solutions
r = int(np.floor(np.pi/4*np.sqrt(2**(n)/m))) # Determine r
gr.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr.x(n)
gr.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr.append(phase_oracle(), range(n+1))
gr.append(diffuser(), range(n+1))
gr.measure(0, 0)
gr.measure(1, 1) # step 3: measure all qubits
gr.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr, backend=simulator, shots=1000)
counts = job.result().get_counts()
plot_histogram(counts)
# Probability og finding the state p(|m>) = p(00)+ p(10)
n = 2
prob_marked = []
# Returns probability of success
def probability(counts):
key_sol1 = '00'
key_sol2 = '10'
val_sol = counts[key_sol1] + counts[key_sol2]
val_total = sum(counts.values())
prob_of_success = val_sol/val_total
return prob_of_success
gr0 = QuantumCircuit(n+1, n)
r = 0
gr0.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr0.x(n)
gr0.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr1.append(phase_oracle(n+1), range(n+1))
gr1.append(diffuser(n+1), range(n+1))
gr0.measure(range(n), range(n)) # step 3: measure all qubits
gr0.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr0, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
gr1 = QuantumCircuit(n+1, n)
r = 1
gr1.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr1.x(n)
gr1.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr1.append(phase_oracle(), range(n+1))
gr1.append(diffuser(), range(n+1))
gr1.measure(range(n), range(n)) # step 3: measure all qubits
gr1.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr1, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
gr2 = QuantumCircuit(n+1, n)
r = 2
gr2.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr2.x(n)
gr2.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr2.append(phase_oracle(), range(n+1))
gr2.append(diffuser(), range(n+1))
gr2.measure(range(n), range(n)) # step 3: measure all qubits
gr2.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr2, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
gr3 = QuantumCircuit(n+1, n)
r = 3
gr3.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr3.x(n)
gr3.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr3.append(phase_oracle(), range(n+1))
gr3.append(diffuser(), range(n+1))
gr3.measure(range(n), range(n)) # step 3: measure all qubits
gr3.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr3, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
gr4 = QuantumCircuit(n+1, n)
r = 4
gr4.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr4.x(n)
gr4.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr4.append(phase_oracle(), range(n+1))
gr4.append(diffuser(), range(n+1))
gr4.measure(range(n), range(n)) # step 3: measure all qubits
gr4.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr4, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
r = [0,1,2,3,4]
plt.plot(r, prob_marked, 'o-')
plt.xlabel("Grover Iterations (r)")
plt.ylabel("Probability of Marked State")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.