repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### added h gate ###
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/snow0369/qiskit_tutorial_2021_summerschool
|
snow0369
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, transpile
from qiskit.providers.aer import AerProvider
from qiskit.tools.visualization import plot_histogram
import random
import numpy as np
def ghz(n):
# 객체의 선언
qr_ghz = QuantumRegister(n)
cr_ghz = ClassicalRegister(n)
qc_ghz = QuantumCircuit(qr_ghz, cr_ghz)
# 회로 구성
qc_ghz.h(qr_ghz[0])
for i in range(1, n):
qc_ghz.cx(0, i)
qc_ghz.barrier()
qc_ghz.measure(qr_ghz, cr_ghz)
return qc_ghz
# 5-ghz 회로 출력
qc = ghz(5)
qc.draw('mpl');
# qasm 시뮬레이션
qasm_simulator = AerProvider().get_backend("qasm_simulator")
job_qasm = execute(qc, backend=qasm_simulator, shots=1024)
counts = job_qasm.result().get_counts()
# 시각화
plot_histogram(counts);
bell_qr = QuantumRegister(2, 'bell')
message_qr = QuantumRegister(1, 'message')
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
qtel_qc = QuantumCircuit(message_qr, bell_qr, cr1, cr2)
a1, a2, a3 = ( random.random() * np.pi for _ in range(3) )
# complete the circuit
qtel_qc.h(bell_qr[0])
qtel_qc.cx(bell_qr[0], bell_qr[1])
qtel_qc.barrier()
qtel_qc.u3(a1, a2, a3, message_qr)
qtel_qc.cx(message_qr, bell_qr[0])
qtel_qc.h(message_qr)
qtel_qc.barrier()
qtel_qc.measure(message_qr, cr1)
qtel_qc.measure(bell_qr[0], cr2)
qtel_qc.barrier()
qtel_qc.x(bell_qr[1]).c_if(cr2, 1)
qtel_qc.z(bell_qr[1]).c_if(cr1, 1)
qtel_qc.draw('mpl');
sv_simulator = AerProvider().get_backend('statevector_simulator')
job_sv = sv_simulator.run(qtel_qc)
sv = job_sv.result().get_statevector()
print(sv)
print([sum(sv[:4]), sum(sv[4:])])
verif_ckt = QuantumCircuit(1)
verif_ckt.u3(a1, a2, a3, 0)
sv_verif = sv_simulator.run(verif_ckt).result().get_statevector()
print(sv_verif)
from qiskit.circuit.library.basis_change.qft import QFT
qft_ckt = QFT(5)
qft_ckt.draw("mpl");
qft_ckt_tr = transpile(qft_ckt, basis_gates=['u1', 'u2', 'cx'])
qft_ckt_tr.draw('mpl');
coupling_map = list()
for i in range(5 - 1):
coupling_map.append([i, i+1])
coupling_map.append([i+1, i])
qft_ckt_tr_lin = transpile(qft_ckt, basis_gates=['u1', 'u2', 'cx'],
coupling_map=coupling_map)
print(coupling_map)
qft_ckt_tr_lin.draw('mpl');
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
import time
import numpy as np
from matplotlib import pyplot as plt
from IPython.display import clear_output
%matplotlib inline
class potts:
def __init__(self, L,q): #Create Potts model
self.L=L #lattice length/width
self.size=L**2 #model size
self.q=q #number of states
self.h=np.zeros(self.q) #bias
self.J=1 #couplings
self.randomize_state()
self.set_temp()
def set_temp(self,T=1):
self.T=1.0
self.beta=1.0/self.T
def set_beta(self,B):
self.beta=B
if B==0:
self.B=None
else:
self.T=1/B
def randomize_state(self):
self.s = np.random.randint(0,self.q,(self.L,self.L))
def MetropolisStep(self): #Execute step of Metropolis algorithm
i = np.random.randint(self.L) #row
j = np.random.randint(self.L) #column
snew = np.random.randint(self.q) #target state
eDiff = self.h[self.s[i,j]]-self.h[snew]
eDiff+= self.J*(int(self.s[i,j]==self.s[(i+1)%self.L,j])-int(snew==self.s[(i+1)%self.L,j])) #up
eDiff+= self.J*(int(self.s[i,j]==self.s[(i-1)%self.L,j])-int(snew==self.s[(i-1)%self.L,j])) #down
eDiff+= self.J*(int(self.s[i,j]==self.s[i,(j+1)%self.L])-int(snew==self.s[i,(j+1)%self.L])) #right
eDiff+= self.J*(int(self.s[i,j]==self.s[i,(j-1)%self.L])-int(snew==self.s[i,(j-1)%self.L])) #left
if eDiff <= 0 or np.random.rand() < np.exp(-self.beta*eDiff): # Metropolis!
self.s[i,j] = snew
def Energy(self):
E=0
for i in range(self.L):
for j in range(self.L):
E-= self.h[self.s[i,j]]
E-= self.J*int(self.s[i,j]==self.s[(i+1)%self.L,j]) #up
E-= self.J*int(self.s[i,j]==self.s[(i-1)%self.L,j]) #down
E-= self.J*int(self.s[i,j]==self.s[i,(j+1)%self.L]) #right
E-= self.J*int(self.s[i,j]==self.s[i,(j-1)%self.L]) #left
return(E)
L=5
q=3
size=L**2
P=potts(L,q)
print(P.s)
fig = plt.figure()
im = plt.imshow(P.s)
viz = [np.array(P.s)]
Nbetas=5#21
betas=10**np.linspace(-0.25,0.25,Nbetas)
C=np.zeros(Nbetas)
for bind in range(Nbetas):
P.set_beta(betas[bind])
T=10000
E=np.zeros(T)
for t in range(T):
for rep in range(L**2):
P.MetropolisStep()
E[t]=P.Energy()
viz += [np.array(P.s)]
C[bind]=betas[bind]*np.var(E)/size
Bc=np.log(1+np.sqrt(q))
plt.figure()
plt.semilogx(betas,C)
plt.semilogx([Bc,Bc],[0,np.max(C)*1.05],'--k')
plt.show()
print(len(viz), viz[0].shape)
fig = plt.figure()
im = plt.imshow(viz[0])
# plt.show()
def show(im, fig, array):
for s in array:
im.set_data(s)
fig.canvas.flush_events()
# time.sleep(0.03)
# clear_output(wait=True)
show(im, fig, viz)
import numpy as np
from skimage import measure
class CPM:
def __init__(self, L,cells=[1],V0=None,th=1): #Create Potts model
self.L=L #lattice length/width
self.size=L**2 #model size
self.cells=cells
self.c=1+np.sum(self.cells)
self.q=1+len(self.cells) #number of states
self.J=np.zeros((self.q,self.q)) #couplings
self.th = th # volume constraint
self.type = [0]
i=0
for c in self.cells:
i+=1
for rep in range(c):
self.type+=[i]
if V0 is None:
self.V0=int(np.round(L*L/(self.c-1)*0.5))
else:
self.V0=V0
self.randomize_couplings()
self.initialize_state()
self.set_temp()
def set_temp(self,T=1):
self.T=1.0
self.beta=1.0/self.T
def set_beta(self,B):
self.beta=B
if B==0:
self.B=None
else:
self.T=1/B
def randomize_couplings(self):
for i in range(self.q):
for j in range(i,self.q):
self.J[i,j]=np.random.rand()
if not i==j:
self.J[j,i]=self.J[i,j]
self.J[0,0]=0
def initialize_state(self):
# self.s = np.random.randint(0,self.c,(self.L,self.L))
self.s=np.zeros((self.L,self.L),int) #add starting cells in random positions
for ind in range(1,self.c):
i,j = np.random.randint(1,self.L-1,2) # row,column of cell, borders are forbidden
self.s[i,j]=ind
self.VE = self.volume_energy(self.s)
def volume_energy(self,s):
unique, counts = np.unique(s, return_counts=True)
V=counts[1:]
return self.th/(2*self.V0)*np.sum((V-self.V0)**2)
#old code computing areas of connected blobs
# cells= measure.label(s,connectivity=1)
# props=measure.regionprops(cells)
# print('areas',[prop.filled_area for prop in props])
# return np.sum([(prop.filled_area-self.V0)**2 for prop in props])
def get_neighbors(self,i,j): # Get the array of Von Newmann neighbors of a cell
nn = []
nn+=[self.s[(i+1)%self.L,j]] #up
nn+=[self.s[(i-1)%self.L,j]] #down
nn+=[self.s[i,(j-1)%self.L]] #left
nn+=[self.s[i,(j+1)%self.L]] #right
return np.array(nn)
def get_moore_neighbors(self,i,j): # Get the array of Moore neighbors of a cell
nn = []
nn+=[self.s[(i+1)%self.L,(j-1)%self.L]] #up-left
nn+=[self.s[(i+1)%self.L,j]] #up
nn+=[self.s[(i+1)%self.L,(j+1)%self.L]] #up-right
nn+=[self.s[i,(j+1)%self.L]] #right
nn+=[self.s[(i-1)%self.L,(j+1)%self.L]] #down-right
nn+=[self.s[(i-1)%self.L,j]] #down
nn+=[self.s[(i-1)%self.L,(j-1)%self.L]] #down-left
nn+=[self.s[i,(j-1)%self.L]] #left
return np.array(nn)
def is_locally_connected(self,cell_domain): # Detect local connectivity
# cell_domain should be 1 if cell is present and 0 otherwise
transitions=0
is_connected=False
if np.sum(cell_domain)>0:
for i in range(8):
if cell_domain[i]<cell_domain[(i+1)%8]: # +1 if transition from 0 to 1
transitions+=1
if transitions<=1:
is_connected=True
return is_connected
def MetropolisStep(self,mode='CA'): # Execute step of Metropolis algorithm
#Select candidate and target nodes
if mode=='MMA':
i,j = np.random.randint(1,self.L-1,2) # row,column of cell, borders are forbidden
nn=self.get_neighbors(i,j) # array of cell neighbors
sijnew = nn[np.random.randint(len(nn))] # target state
cond = sijnew!=self.s[i,j]
if mode=='CA':
i,j = np.random.randint(1,self.L-1,2) # row,column of cell
nn=self.get_neighbors(i,j) # array of cell neighbors
nn_unique=np.unique(nn)
sijnew = nn_unique[np.random.randint(len(nn_unique))] # target state
domain=self.get_moore_neighbors(i,j)
lc_candidate=self.is_locally_connected(domain==self.s[i,j])
lc_target=self.is_locally_connected(domain==sijnew)
cond = lc_candidate and lc_target and sijnew!=self.s[i,j]
#Evaluate acceptance of change
if cond:
eDiff = 0
coupling_neighbors=self.get_neighbors(i,j)
#Compute adhesion energy difference
for sn in coupling_neighbors:
eDiff+= self.J[self.type[sijnew],self.type[sn]]*int(sijnew!=sn) - self.J[self.type[self.s[i,j]],self.type[sn]]*int(self.s[i,j]!=sn)
#Compute volume energy difference
snew=self.s.copy()
snew[i,j] = sijnew
VEnew = self.volume_energy(snew)
eDiff += VEnew - self.VE
if eDiff <= 0 or np.log(np.random.rand()) < -self.beta*eDiff: # Metropolis
self.s[i,j] = sijnew
self.VE = VEnew
def Energy(self):
E=self.volume_energy(self.s)
for i in range(self.L):
for j in range(self.L):
if self.s[i,j]>0:
coupling_neighbors=self.get_neighbors(i,j)
#Compute adhesion energy difference
for sn in coupling_neighbors:
if sn<self.s[i,j]: #we compute each link just once
E+= self.J[self.type[self.s[i,j]],self.type[sn]]*int(self.s[i,j]!=sn)
return(E)
#Transform bool array into positive integer
def bool2int(x):
y = 0
for i,j in enumerate(np.array(x)[::-1]):
y += j*2**i
return int(y)
#Transform positive integer into bit array
def bitfield(n,size):
x = [int(x) for x in bin(int(n))[2:]]
x = [0]*(size-len(x)) + x
return np.array(x)
L=4
size=L**2
V0=3
cells=[1]
C=CPM(L,cells=cells,V0=V0)
C.J=np.array([[0,1],[1,0]])*1
C.th=3
T=10000
T0=int(T/10)
import timeit
start_time = timeit.default_timer()
P=np.zeros(2**((L-2)**2))
K=np.zeros(1+(L-2)**2)
allowed=set()
C.initialize_state()
plt.figure()
plt.imshow(C.s)
for t in range(T0):
for rep in range(1+(L-2)**2):
C.MetropolisStep(mode='CA')
for t in range(T):
for rep in range(1+(L-2)**2):
C.MetropolisStep(mode='CA')
ind=bool2int(C.s[1:-1,1:-1].flatten())
allowed.add(ind)
# print()
# print(C.s[1:-1,1:-1])
# print(bitfield(ind,(L-2)**2).reshape((L-2,L-2)))
P[ind]+=1
K[np.sum(C.s[1:-1,1:-1])]+=1
P/=np.sum(P)
# code you want to evaluate
elapsed = timeit.default_timer() - start_time
K/=np.sum(K)
plt.figure()
plt.imshow(C.s)
a=np.array([[0,1],[1,0]])
# print(a.flatten())
# print(bool2int(a.flatten()))
# print(C.J)
P1=np.zeros(2**((L-2)**2))
K1=np.zeros(1+(L-2)**2)
#forbidden=[0,6,9]
for n in range(2**((L-2)**2)):
# if not n in forbidden:
if n in allowed:
C.s[1:-1,1:-1]=bitfield(n,(L-2)**2).reshape((L-2,L-2))
# print(n)
# print(bitfield(n,(L-2)**2).reshape((L-2,L-2)))
E=C.Energy()
P1[n]=np.exp(-E)
K1[np.sum(C.s[1:-1,1:-1])]+=np.exp(-E)
P1/=np.sum(P1)
K1/=np.sum(K1)
plt.figure()
plt.plot(P)
plt.plot(P1)
plt.figure()
plt.plot(K)
plt.plot(K1)
plt.show()
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
#
# your code is here
#
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi, cos, sin
from random import randrange
# quantum circuit with three qubits and three bits
q = QuantumRegister(3,"q")
c = ClassicalRegister(3,"c")
qc = QuantumCircuit(q,c)
# rotate the first qubit by random angle
r = randrange(100)
theta = 2*pi*(r/100) # radians
print("the picked angle is",r*3.6,"degrees and",theta,"radians")
a = cos(theta)
b = sin(theta)
print("a=",round(a,3),"b=",round(b,3))
print("a*a=",round(a**2,3),"b*b=",round(b**2,3))
qc.ry(2*theta,q[2])
# creating an entanglement between q[1] and q[0]
qc.h(q[1])
qc.cx(q[1],q[0])
# CNOT operator by Asja on her qubits where q[2] is the control qubit
qc.cx(q[2],q[1])
# Hadamard operator by Asja on q[2]
qc.h(q[2])
# the measurement done by Asja
qc.measure(q[2],c[2])
qc.measure(q[1],c[1])
# draw thw circuit
display(qc.draw(output='mpl',reverse_bits=True))
# read the state vector
job = execute(qc,Aer.get_backend('statevector_simulator'),optimization_level=0,shots=1)
current_quantum_state=job.result().get_statevector(qc)
print("the state vector is")
for i in range(len(current_quantum_state)):
print(current_quantum_state[i].real)
print()
classical_outcomes = ['00','01','10','11']
for i in range(4):
if (current_quantum_state[2*i].real != 0) or (current_quantum_state[2*i+1].real != 0):
print("the classical outcome is",classical_outcomes[i])
classical_outcome = classical_outcomes[i]
balvis_state = [ current_quantum_state[2*i].real,current_quantum_state[2*i+1].real ]
print()
readable_quantum_state = "|"+classical_outcome+">"
readable_quantum_state += "("+str(round(balvis_state[0],3))+"|0>+"+str(round(balvis_state[1],3))+"|1>)"
print("the new quantum state is",readable_quantum_state)
all_states = ['000','001','010','011','100','101','110','111']
balvis_state_str = "|"+classical_outcome+">("
for i in range(len(current_quantum_state)):
if abs(current_quantum_state[i].real-a)<0.000001:
balvis_state_str += "+a|"+ all_states[i][2]+">"
elif abs(current_quantum_state[i].real+a)<0.000001:
balvis_state_str += "-a|"+ all_states[i][2]+">"
elif abs(current_quantum_state[i].real-b)<0.000001:
balvis_state_str += "+b|"+ all_states[i][2]+">"
elif abs(current_quantum_state[i].real+b)<0.000001:
balvis_state_str += "-b|"+ all_states[i][2]+">"
balvis_state_str += ")"
print("the new quantum state is",balvis_state_str)
#
# your code is here
#
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi, cos, sin
from random import randrange
# quantum circuit with three qubits and two bits
q = QuantumRegister(3,"q")
c1 = ClassicalRegister(1,"c1")
c2 = ClassicalRegister(1,"c2")
qc = QuantumCircuit(q,c1,c2)
# rotate the first qubit by random angle
r = randrange(100)
theta = 2*pi*(r/100) # radians
print("the picked angle is",r*3.6,"degrees and",theta,"radians")
a = cos(theta)
b = sin(theta)
print("a=",round(a,4),"b=",round(b,4))
qc.ry(2*theta,q[2])
# creating an entanglement between q[1] and q[0]
qc.h(q[1])
qc.cx(q[1],q[0])
# CNOT operator by Asja on her qubits where q[2] is the control qubit
qc.cx(q[2],q[1])
# Hadamard operator by Asja on q[2]
qc.h(q[2])
qc.barrier()
# the measurement done by Asja
qc.measure(q[2],c2)
qc.measure(q[1],c1)
qc.barrier()
# post-processing done by Balvis
qc.x(q[0]).c_if(c1,1)
qc.z(q[0]).c_if(c2,1)
# draw the circuit
display(qc.draw(output='mpl',reverse_bits=True))
# read the state vector
job = execute(qc,Aer.get_backend('statevector_simulator'),optimization_level=0,shots=1)
current_quantum_state=job.result().get_statevector(qc)
print("the state vector is")
for i in range(len(current_quantum_state)):
print(round(current_quantum_state[i].real,4))
print()
classical_outcomes = ['00','01','10','11']
for i in range(4):
if (current_quantum_state[2*i].real != 0) or (current_quantum_state[2*i+1].real != 0):
print("the classical outcome is",classical_outcomes[i])
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Generic BackendV2 class that with a simulated ``run``."""
from __future__ import annotations
import warnings
from collections.abc import Iterable
import numpy as np
from qiskit import pulse
from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap
from qiskit.circuit import QuantumCircuit, Instruction
from qiskit.circuit.controlflow import (
IfElseOp,
WhileLoopOp,
ForLoopOp,
SwitchCaseOp,
BreakLoopOp,
ContinueLoopOp,
)
from qiskit.circuit.library.standard_gates import get_standard_gate_name_mapping
from qiskit.exceptions import QiskitError
from qiskit.transpiler import CouplingMap, Target, InstructionProperties, QubitProperties
from qiskit.providers import Options
from qiskit.providers.basic_provider import BasicSimulator
from qiskit.providers.backend import BackendV2
from qiskit.providers.models import (
PulseDefaults,
Command,
)
from qiskit.qobj import PulseQobjInstruction, PulseLibraryItem
from qiskit.utils import optionals as _optionals
# Noise default values/ranges for duration and error of supported
# instructions. There are two possible formats:
# - (min_duration, max_duration, min_error, max_error),
# if the defaults are ranges.
# - (duration, error), if the defaults are fixed values.
_NOISE_DEFAULTS = {
"cx": (7.992e-08, 8.99988e-07, 1e-5, 5e-3),
"ecr": (7.992e-08, 8.99988e-07, 1e-5, 5e-3),
"cz": (7.992e-08, 8.99988e-07, 1e-5, 5e-3),
"id": (2.997e-08, 5.994e-08, 9e-5, 1e-4),
"rz": (0.0, 0.0),
"sx": (2.997e-08, 5.994e-08, 9e-5, 1e-4),
"x": (2.997e-08, 5.994e-08, 9e-5, 1e-4),
"measure": (6.99966e-07, 1.500054e-06, 1e-5, 5e-3),
"delay": (None, None),
"reset": (None, None),
}
# Fallback values for gates with unknown noise default ranges.
_NOISE_DEFAULTS_FALLBACK = {
"1-q": (2.997e-08, 5.994e-08, 9e-5, 1e-4),
"multi-q": (7.992e-08, 8.99988e-07, 5e-3),
}
# Ranges to sample qubit properties from.
_QUBIT_PROPERTIES = {
"dt": 0.222e-9,
"t1": (100e-6, 200e-6),
"t2": (100e-6, 200e-6),
"frequency": (5e9, 5.5e9),
}
# The number of samples determines the pulse durations of the corresponding
# instructions. This default defines pulses with durations in multiples of
# 16 dt for consistency with the pulse granularity of real IBM devices, but
# keeps the number smaller than what would be realistic for
# manageability. If needed, more realistic durations could be added in the
# future (order of 160dt for 1q gates, 1760dt for 2q gates and measure).
_PULSE_LIBRARY = [
PulseLibraryItem(name="pulse_1", samples=np.linspace(0, 1.0, 16, dtype=np.complex128)), # 16dt
PulseLibraryItem(name="pulse_2", samples=np.linspace(0, 1.0, 32, dtype=np.complex128)), # 32dt
PulseLibraryItem(name="pulse_3", samples=np.linspace(0, 1.0, 64, dtype=np.complex128)), # 64dt
]
class GenericBackendV2(BackendV2):
"""Generic :class:`~.BackendV2` implementation with a configurable constructor. This class will
return a :class:`~.BackendV2` instance that runs on a local simulator (in the spirit of fake
backends) and contains all the necessary information to test backend-interfacing components, such
as the transpiler. A :class:`.GenericBackendV2` instance can be constructed from as little as a
specified ``num_qubits``, but users can additionally configure the basis gates, coupling map,
ability to run dynamic circuits (control flow instructions), instruction calibrations and dtm.
The remainder of the backend properties are generated by randomly sampling
from default ranges extracted from historical IBM backend data. The seed for this random
generation can be fixed to ensure the reproducibility of the backend output.
This backend only supports gates in the standard library, if you need a more flexible backend,
there is always the option to directly instantiate a :class:`.Target` object to use for
transpilation.
"""
def __init__(
self,
num_qubits: int,
basis_gates: list[str] | None = None,
*,
coupling_map: list[list[int]] | CouplingMap | None = None,
control_flow: bool = False,
calibrate_instructions: bool | InstructionScheduleMap | None = None,
dtm: float | None = None,
seed: int | None = None,
):
"""
Args:
num_qubits: Number of qubits that will be used to construct the backend's target.
Note that, while there is no limit in the size of the target that can be
constructed, this backend runs on local noisy simulators, and these might
present limitations in the number of qubits that can be simulated.
basis_gates: List of basis gate names to be supported by
the target. These must be part of the standard qiskit circuit library.
The default set of basis gates is ``["id", "rz", "sx", "x", "cx"]``
The ``"reset"``, ``"delay"``, and ``"measure"`` instructions are
always supported by default, even if not specified via ``basis_gates``.
coupling_map: Optional coupling map
for the backend. Multiple formats are supported:
#. :class:`~.CouplingMap` instance
#. List, must be given as an edge list representing the two qubit interactions
supported by the backend, for example:
``[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]``
If ``coupling_map`` is specified, it must match the number of qubits
specified in ``num_qubits``. If ``coupling_map`` is not specified,
a fully connected coupling map will be generated with ``num_qubits``
qubits.
control_flow: Flag to enable control flow directives on the target
(defaults to False).
calibrate_instructions: Instruction calibration settings, this argument
supports both boolean and :class:`.InstructionScheduleMap` as
input types, and is ``None`` by default:
#. If ``calibrate_instructions==None``, no calibrations will be added to the target.
#. If ``calibrate_instructions==True``, all gates will be calibrated for all
qubits using the default pulse schedules generated internally.
#. If ``calibrate_instructions==False``, all gates will be "calibrated" for
all qubits with an empty pulse schedule.
#. If an :class:`.InstructionScheduleMap` instance is given, the calibrations
in this instruction schedule map will be appended to the target
instead of the default pulse schedules (this allows for custom calibrations).
dtm: System time resolution of output signals in nanoseconds.
None by default.
seed: Optional seed for generation of default values.
"""
super().__init__(
provider=None,
name=f"generic_backend_{num_qubits}q",
description=f"This is a device with {num_qubits} qubits and generic settings.",
backend_version="",
)
self._sim = None
self._rng = np.random.default_rng(seed=seed)
self._dtm = dtm
self._num_qubits = num_qubits
self._control_flow = control_flow
self._calibrate_instructions = calibrate_instructions
self._supported_gates = get_standard_gate_name_mapping()
if coupling_map is None:
self._coupling_map = CouplingMap().from_full(num_qubits)
else:
if isinstance(coupling_map, CouplingMap):
self._coupling_map = coupling_map
else:
self._coupling_map = CouplingMap(coupling_map)
if num_qubits != self._coupling_map.size():
raise QiskitError(
f"The number of qubits (got {num_qubits}) must match "
f"the size of the provided coupling map (got {self._coupling_map.size()})."
)
self._basis_gates = (
basis_gates if basis_gates is not None else ["cx", "id", "rz", "sx", "x"]
)
for name in ["reset", "delay", "measure"]:
if name not in self._basis_gates:
self._basis_gates.append(name)
self._build_generic_target()
self._build_default_channels()
@property
def target(self):
return self._target
@property
def max_circuits(self):
return None
@property
def dtm(self) -> float:
"""Return the system time resolution of output signals"""
# converting `dtm` from nanoseconds to seconds
return self._dtm * 1e-9 if self._dtm is not None else None
@property
def meas_map(self) -> list[list[int]]:
return self._target.concurrent_measurements
def _build_default_channels(self) -> None:
channels_map = {
"acquire": {(i,): [pulse.AcquireChannel(i)] for i in range(self.num_qubits)},
"drive": {(i,): [pulse.DriveChannel(i)] for i in range(self.num_qubits)},
"measure": {(i,): [pulse.MeasureChannel(i)] for i in range(self.num_qubits)},
"control": {
(edge): [pulse.ControlChannel(i)] for i, edge in enumerate(self._coupling_map)
},
}
setattr(self, "channels_map", channels_map)
def _get_noise_defaults(self, name: str, num_qubits: int) -> tuple:
"""Return noise default values/ranges for duration and error of supported
instructions. There are two possible formats:
- (min_duration, max_duration, min_error, max_error),
if the defaults are ranges.
- (duration, error), if the defaults are fixed values.
"""
if name in _NOISE_DEFAULTS:
return _NOISE_DEFAULTS[name]
if num_qubits == 1:
return _NOISE_DEFAULTS_FALLBACK["1-q"]
return _NOISE_DEFAULTS_FALLBACK["multi-q"]
def _get_calibration_sequence(
self, inst: str, num_qubits: int, qargs: tuple[int]
) -> list[PulseQobjInstruction]:
"""Return calibration pulse sequence for given instruction (defined by name and num_qubits)
acting on qargs.
"""
pulse_library = _PULSE_LIBRARY
# Note that the calibration pulses are different for
# 1q gates vs 2q gates vs measurement instructions.
if inst == "measure":
sequence = [
PulseQobjInstruction(
name="acquire",
duration=1792,
t0=0,
qubits=qargs,
memory_slot=qargs,
)
] + [PulseQobjInstruction(name=pulse_library[1].name, ch=f"m{i}", t0=0) for i in qargs]
return sequence
if num_qubits == 1:
return [
PulseQobjInstruction(name="fc", ch=f"u{qargs[0]}", t0=0, phase="-P0"),
PulseQobjInstruction(name=pulse_library[0].name, ch=f"d{qargs[0]}", t0=0),
]
return [
PulseQobjInstruction(name=pulse_library[1].name, ch=f"d{qargs[0]}", t0=0),
PulseQobjInstruction(name=pulse_library[2].name, ch=f"u{qargs[0]}", t0=0),
PulseQobjInstruction(name=pulse_library[1].name, ch=f"d{qargs[1]}", t0=0),
PulseQobjInstruction(name="fc", ch=f"d{qargs[1]}", t0=0, phase=2.1),
]
def _generate_calibration_defaults(self) -> PulseDefaults:
"""Generate pulse calibration defaults as specified with `self._calibrate_instructions`.
If `self._calibrate_instructions` is True, the pulse schedules will be generated from
a series of default calibration sequences. If `self._calibrate_instructions` is False,
the pulse schedules will contain empty calibration sequences, but still be generated and
added to the target.
"""
# If self._calibrate_instructions==True, this method
# will generate default pulse schedules for all gates in self._basis_gates,
# except for `delay` and `reset`.
calibration_buffer = self._basis_gates.copy()
for inst in ["delay", "reset"]:
calibration_buffer.remove(inst)
# List of calibration commands (generated from sequences of PulseQobjInstructions)
# corresponding to each calibrated instruction. Note that the calibration pulses
# are different for 1q gates vs 2q gates vs measurement instructions.
cmd_def = []
for inst in calibration_buffer:
num_qubits = self._supported_gates[inst].num_qubits
qarg_set = self._coupling_map if num_qubits > 1 else list(range(self.num_qubits))
if inst == "measure":
cmd_def.append(
Command(
name=inst,
qubits=qarg_set,
sequence=(
self._get_calibration_sequence(inst, num_qubits, qarg_set)
if self._calibrate_instructions
else []
),
)
)
else:
for qarg in qarg_set:
qubits = [qarg] if num_qubits == 1 else qarg
cmd_def.append(
Command(
name=inst,
qubits=qubits,
sequence=(
self._get_calibration_sequence(inst, num_qubits, qubits)
if self._calibrate_instructions
else []
),
)
)
qubit_freq_est = np.random.normal(4.8, scale=0.01, size=self.num_qubits).tolist()
meas_freq_est = np.linspace(6.4, 6.6, self.num_qubits).tolist()
return PulseDefaults(
qubit_freq_est=qubit_freq_est,
meas_freq_est=meas_freq_est,
buffer=0,
pulse_library=_PULSE_LIBRARY,
cmd_def=cmd_def,
)
def _build_generic_target(self):
"""This method generates a :class:`~.Target` instance with
default qubit, instruction and calibration properties.
"""
# the qubit properties are sampled from default ranges
properties = _QUBIT_PROPERTIES
self._target = Target(
description=f"Generic Target with {self._num_qubits} qubits",
num_qubits=self._num_qubits,
dt=properties["dt"],
qubit_properties=[
QubitProperties(
t1=self._rng.uniform(properties["t1"][0], properties["t1"][1]),
t2=self._rng.uniform(properties["t2"][0], properties["t2"][1]),
frequency=self._rng.uniform(
properties["frequency"][0], properties["frequency"][1]
),
)
for _ in range(self._num_qubits)
],
concurrent_measurements=[list(range(self._num_qubits))],
)
# Generate instruction schedule map with calibrations to add to target.
calibration_inst_map = None
if self._calibrate_instructions is not None:
if isinstance(self._calibrate_instructions, InstructionScheduleMap):
calibration_inst_map = self._calibrate_instructions
else:
defaults = self._generate_calibration_defaults()
calibration_inst_map = defaults.instruction_schedule_map
# Iterate over gates, generate noise params from defaults,
# and add instructions, noise and calibrations to target.
for name in self._basis_gates:
if name not in self._supported_gates:
raise QiskitError(
f"Provided basis gate {name} is not an instruction "
f"in the standard qiskit circuit library."
)
gate = self._supported_gates[name]
noise_params = self._get_noise_defaults(name, gate.num_qubits)
self._add_noisy_instruction_to_target(gate, noise_params, calibration_inst_map)
if self._control_flow:
self._target.add_instruction(IfElseOp, name="if_else")
self._target.add_instruction(WhileLoopOp, name="while_loop")
self._target.add_instruction(ForLoopOp, name="for_loop")
self._target.add_instruction(SwitchCaseOp, name="switch_case")
self._target.add_instruction(BreakLoopOp, name="break")
self._target.add_instruction(ContinueLoopOp, name="continue")
def _add_noisy_instruction_to_target(
self,
instruction: Instruction,
noise_params: tuple[float, ...] | None,
calibration_inst_map: InstructionScheduleMap | None,
) -> None:
"""Add instruction properties to target for specified instruction.
Args:
instruction: Instance of instruction to be added to the target
noise_params: Error and duration noise values/ranges to
include in instruction properties.
calibration_inst_map: Instruction schedule map with calibration defaults
"""
qarg_set = self._coupling_map if instruction.num_qubits > 1 else range(self.num_qubits)
props = {}
for qarg in qarg_set:
try:
qargs = tuple(qarg)
except TypeError:
qargs = (qarg,)
duration, error = (
noise_params
if len(noise_params) == 2
else (self._rng.uniform(*noise_params[:2]), self._rng.uniform(*noise_params[2:]))
)
if (
calibration_inst_map is not None
and instruction.name not in ["reset", "delay"]
and qarg in calibration_inst_map.qubits_with_instruction(instruction.name)
):
# Do NOT call .get method. This parses Qobj immediately.
# This operation is computationally expensive and should be bypassed.
calibration_entry = calibration_inst_map._get_calibration_entry(
instruction.name, qargs
)
else:
calibration_entry = None
if duration is not None and len(noise_params) > 2:
# Ensure exact conversion of duration from seconds to dt
dt = _QUBIT_PROPERTIES["dt"]
rounded_duration = round(duration / dt) * dt
# Clamp rounded duration to be between min and max values
duration = max(noise_params[0], min(rounded_duration, noise_params[1]))
props.update({qargs: InstructionProperties(duration, error, calibration_entry)})
self._target.add_instruction(instruction, props)
# The "measure" instruction calibrations need to be added qubit by qubit, once the
# instruction has been added to the target.
if calibration_inst_map is not None and instruction.name == "measure":
for qarg in calibration_inst_map.qubits_with_instruction(instruction.name):
try:
qargs = tuple(qarg)
except TypeError:
qargs = (qarg,)
# Do NOT call .get method. This parses Qobj immediately.
# This operation is computationally expensive and should be bypassed.
calibration_entry = calibration_inst_map._get_calibration_entry(
instruction.name, qargs
)
for qubit in qargs:
if qubit < self.num_qubits:
self._target[instruction.name][(qubit,)].calibration = calibration_entry
def run(self, run_input, **options):
"""Run on the backend using a simulator.
This method runs circuit jobs (an individual or a list of :class:`~.QuantumCircuit`
) and pulse jobs (an individual or a list of :class:`~.Schedule` or
:class:`~.ScheduleBlock`) using :class:`~.BasicSimulator` or Aer simulator and returns a
:class:`~qiskit.providers.Job` object.
If qiskit-aer is installed, jobs will be run using the ``AerSimulator`` with
noise model of the backend. Otherwise, jobs will be run using the
``BasicSimulator`` simulator without noise.
Noisy simulations of pulse jobs are not yet supported in :class:`~.GenericBackendV2`.
Args:
run_input (QuantumCircuit or Schedule or ScheduleBlock or list): An
individual or a list of
:class:`~qiskit.circuit.QuantumCircuit`,
:class:`~qiskit.pulse.ScheduleBlock`, or
:class:`~qiskit.pulse.Schedule` objects to run on the backend.
options: Any kwarg options to pass to the backend for running the
config. If a key is also present in the options
attribute/object, then the expectation is that the value
specified will be used instead of what's set in the options
object.
Returns:
Job: The job object for the run
Raises:
QiskitError: If a pulse job is supplied and qiskit_aer is not installed.
"""
circuits = run_input
pulse_job = None
if isinstance(circuits, (pulse.Schedule, pulse.ScheduleBlock)):
pulse_job = True
elif isinstance(circuits, QuantumCircuit):
pulse_job = False
elif isinstance(circuits, list):
if circuits:
if all(isinstance(x, (pulse.Schedule, pulse.ScheduleBlock)) for x in circuits):
pulse_job = True
elif all(isinstance(x, QuantumCircuit) for x in circuits):
pulse_job = False
if pulse_job is None: # submitted job is invalid
raise QiskitError(
"Invalid input object %s, must be either a "
"QuantumCircuit, Schedule, or a list of either" % circuits
)
if pulse_job: # pulse job
raise QiskitError("Pulse simulation is currently not supported for V2 backends.")
# circuit job
if not _optionals.HAS_AER:
warnings.warn("Aer not found using BasicSimulator and no noise", RuntimeWarning)
if self._sim is None:
self._setup_sim()
self._sim._options = self._options
job = self._sim.run(circuits, **options)
return job
def _setup_sim(self) -> None:
if _optionals.HAS_AER:
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel
self._sim = AerSimulator()
noise_model = NoiseModel.from_backend(self)
self._sim.set_options(noise_model=noise_model)
# Update backend default too to avoid overwriting
# it when run() is called
self.set_options(noise_model=noise_model)
else:
self._sim = BasicSimulator()
@classmethod
def _default_options(cls) -> Options:
with warnings.catch_warnings(): # TODO remove catch once aer release without Provider ABC
warnings.filterwarnings(
"ignore",
category=DeprecationWarning,
message=".+abstract Provider and ProviderV1.+",
)
if _optionals.HAS_AER:
from qiskit_aer import AerSimulator
return AerSimulator._default_options()
else:
return BasicSimulator._default_options()
def drive_channel(self, qubit: int):
drive_channels_map = getattr(self, "channels_map", {}).get("drive", {})
qubits = (qubit,)
if qubits in drive_channels_map:
return drive_channels_map[qubits][0]
return None
def measure_channel(self, qubit: int):
measure_channels_map = getattr(self, "channels_map", {}).get("measure", {})
qubits = (qubit,)
if qubits in measure_channels_map:
return measure_channels_map[qubits][0]
return None
def acquire_channel(self, qubit: int):
acquire_channels_map = getattr(self, "channels_map", {}).get("acquire", {})
qubits = (qubit,)
if qubits in acquire_channels_map:
return acquire_channels_map[qubits][0]
return None
def control_channel(self, qubits: Iterable[int]):
control_channels_map = getattr(self, "channels_map", {}).get("control", {})
qubits = tuple(qubits)
if qubits in control_channels_map:
return control_channels_map[qubits]
return []
|
https://github.com/quantumofme/pavia-qiskit-tutorials
|
quantumofme
|
import qiskit as qk
import numpy as np
from scipy.linalg import expm
import matplotlib.pyplot as plt
import math
# Single qubit operators
sx = np.array([[0.0, 1.0],[1.0, 0.0]])
sy = np.array([[0.0, -1.0*1j],[1.0*1j, 0.0]])
sz = np.array([[1.0, 0.0],[0.0, -1.0]])
idt = np.array([[1.0, 0.0],[0.0, 1.0]])
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
psi0 = np.array([1.0, 0.0])
thetas = np.linspace(0,4*math.pi,200)
avg_sx_tot = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta = expm(-1j*0.5*thetas[i]*(sx+sz)/math.sqrt(2)).dot(psi0)
avg_sx_tot[i] = np.real(psi_theta.conjugate().transpose().dot(sx.dot(psi_theta)))
plt.plot(thetas,avg_sx_tot)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.show()
avg_sx_zx = np.zeros(len(thetas))
avg_sx_xz = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta_zx = expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(psi0))
psi_theta_xz = expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(psi0))
avg_sx_zx[i] = np.real(psi_theta_zx.conjugate().transpose().dot(sx.dot(psi_theta_zx)))
avg_sx_xz[i] = np.real(psi_theta_xz.conjugate().transpose().dot(sx.dot(psi_theta_xz)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_zx)
plt.plot(thetas,avg_sx_xz)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Around x = z', 'x first', 'z first'],loc=1)
plt.show()
# Try this with e.g. ntrot = 1, 5, 10, 50.
# You can also try to do sx and sz slices in the reverse order: both choices will become good approximations
# for large n
ntrot = 10
avg_sx_n = np.zeros(len(thetas))
for i in range(len(thetas)):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2))))
for j in range(ntrot-1):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2)))).dot(rot)
psi_theta_n = rot.dot(psi0)
avg_sx_n[i] = np.real(psi_theta_n.conjugate().transpose().dot(sx.dot(psi_theta_n)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_n,'--')
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Exact', 'ntrot = ' + str(ntrot)],loc=1)
plt.show()
delta = 0.1
qr = qk.QuantumRegister(2,name='qr')
zz_example = qk.QuantumCircuit(qr)
zz_example.cx(qr[0],qr[1])
zz_example.u1(2*delta,qr[1])
zz_example.cx(qr[0],qr[1])
zz_example.draw(output='mpl')
J = 1
c_times = np.linspace(0,0.5*math.pi/abs(J),1000)
q_times = np.linspace(0,0.5*math.pi/abs(J),10)
### Classical simulation of the Heisenberg dimer model
psi0 = np.kron( np.array([0,1]), np.array([1,0]) )
H = J * ( np.kron(sx,sx) + np.kron(sy,sy) + np.kron(sz,sz) )
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz1 = np.kron(sz,idt)
sz2 = np.kron(idt,sz)
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
### Digital quantum simulation of the Heisenberg dimer model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
for k in range(len(q_times)):
delta = J*q_times[k]
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
# Run the quantum algorithm
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(Heis2, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
for key,value in counts.items():
if key == '00':
sz1q += value
sz2q += value
elif key == '01':
sz1q -= value
sz2q += value
elif key == '10':
sz1q += value
sz2q -= value
elif key == '11':
sz1q -= value
sz2q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
plt.plot(abs(J)*c_times,0.5*sz1_t,'b--')
plt.plot(abs(J)*c_times,0.5*sz2_t,'c')
plt.plot(abs(J)*q_times,0.5*sz1q_t,'rd')
plt.plot(abs(J)*q_times,0.5*sz2q_t,'ko')
plt.legend(['sz1','sz2','sz1q','sz2q'])
plt.xlabel(r'$\delta = |J|t$')
plt.show()
# WARNING: this cell can take a few minutes to run!
ntrotter = 5
J12 = 1
J23 = 1
c_times = np.linspace(0,math.pi/abs(J12),1000)
q_times = np.linspace(0,math.pi/abs(J12),20)
### Classical simulation of the Heisenberg trimer model
psi0 = np.kron( np.kron( np.array([0,1]), np.array([1,0]) ) , np.array([1,0]) )
sxsx12 = np.kron(sx, np.kron(sx,idt))
sysy12 = np.kron(sy, np.kron(sy,idt))
szsz12 = np.kron(sz, np.kron(sz,idt))
sxsx23 = np.kron(idt, np.kron(sx,sx))
sysy23 = np.kron(idt, np.kron(sy,sy))
szsz23 = np.kron(idt, np.kron(sz,sz))
H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
H23 = J23 * ( sxsx23 + sysy23 + szsz23 )
H = H12 + H23
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz3_t = np.zeros(len(c_times))
sz1 = np.kron(sz, np.kron(idt,idt))
sz2 = np.kron(idt, np.kron(sz,idt))
sz3 = np.kron(idt, np.kron(idt,sz))
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Classical simulation of the Heisenberg trimer model WITH SUZUKI TROTTER DIGITALIZATION
sz1st_t = np.zeros(len(c_times))
sz2st_t = np.zeros(len(c_times))
sz3st_t = np.zeros(len(c_times))
for i in range(len(c_times)):
t = c_times[i]
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter))
for j in range(ntrotter-1):
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter)).dot(Ust)
psi_t = Ust.dot(psi0)
sz1st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Digital quantum simulation of the Heisenberg model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
sz3q_t = np.zeros(len(q_times))
for k in range(len(q_times)):
delta12n = J12*q_times[k]/ntrotter
delta23n = J23*q_times[k]/ntrotter
qr = qk.QuantumRegister(3,name='qr')
cr = qk.ClassicalRegister(3,name='cr')
Heis3 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis3.x(qr[0])
for n in range(ntrotter):
# 1-2 bond mapped on qubits 0 and 1 in the quantum register
# ZZ
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
# 2-3 bond mapped on qubits 1 and 2 in the quantum register
# ZZ
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[2])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[2])
# measure
Heis3.measure(qr,cr)
# Run the quantum algorithm
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(Heis3, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
sz3q = 0
for key,value in counts.items():
if key == '000':
sz1q += value
sz2q += value
sz3q += value
elif key == '001':
sz1q -= value
sz2q += value
sz3q += value
elif key == '010':
sz1q += value
sz2q -= value
sz3q += value
elif key == '011':
sz1q -= value
sz2q -= value
sz3q += value
elif key == '100':
sz1q += value
sz2q += value
sz3q -= value
elif key == '101':
sz1q -= value
sz2q += value
sz3q -= value
elif key == '110':
sz1q += value
sz2q -= value
sz3q -= value
elif key == '111':
sz1q -= value
sz2q -= value
sz3q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
sz3q_t[k] = sz3q/nshots
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(abs(J12)*c_times,0.5*sz1_t,'b', label='sz1 full')
ax.plot(abs(J12)*c_times,0.5*sz2_t,'r', label='sz2 full')
ax.plot(abs(J12)*c_times,0.5*sz3_t,'g', label='sz3 full')
ax.plot(abs(J12)*c_times,0.5*sz1st_t,'b--',label='sz1 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz2st_t,'r--', label='sz2 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz3st_t,'g--', label='sz3 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*q_times,0.5*sz1q_t,'b*',label='sz1 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz2q_t,'ro', label='sz2 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz3q_t,'gd', label='sz3 n = ' + str(ntrotter) + ' (quantum)')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1)
plt.xlabel(r'$\delta_{12} = |J_{12}|t$')
plt.show()
qr = qk.QuantumRegister(1,name='qr')
cr = qk.ClassicalRegister(1,name='cr')
x_meas = qk.QuantumCircuit(qr,cr)
# Here you can add any quantum circuit generating the quantum state
# that you with to measure at the end e.g.
#
# x_meas.u3(a,b,c,qr[0])
#
# Measurement in x direction
x_meas.h(qr[0])
x_meas.measure(qr,cr)
x_meas.draw(output='mpl')
nshots = 8192
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(x_meas, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
print(counts)
average_sigma_x = 0
for key,value in counts.items():
if key == '0':
average_sigma_x += value
elif key == '1':
average_sigma_x -= value
average_sigma_x = average_sigma_x/nshots
print('Average of sx = ', average_sigma_x)
theta_a = np.linspace(0.0, 2*math.pi, 21) # Some angles for the a vector, with respect to the z axis
theta_b = 0.0 # If the b vector is the z axis -> angle = 0
theta_c = math.pi/2 # If the vector c is the x axis -> angle = pi/2 with respect to z
# Quantum version
nshots = 1024
Pab = np.zeros(len(theta_a))
Pac = np.zeros(len(theta_a))
# Quantum circuit to measure Pbc
qr = qk.QuantumRegister(2, name='qr')
cr = qk.ClassicalRegister(2, name='cr')
qc = qk.QuantumCircuit(qr, cr)
## Initialize Bell state
qc.x(qr[0])
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
## Pre measurement unitaries to select the basis along a (for the first qubit) and b (for the second qubit)
qc.u3(theta_b,0,0,qr[0])
qc.u3(theta_c,0,0,qr[1])
## Measures
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
## Running and saving result
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(qc, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
out = 0
for key,value in counts.items():
if (key == '00') or (key == '11'):
out += value
elif (key == '01') or (key == '10'):
out -= value
Pbc = out/nshots
# Now we compute Pab and Pac for different a vectors
for i in range(len(theta_a)):
ta = theta_a[i]
# Quantum circuit to measure Pab with the given a
qr = qk.QuantumRegister(2, name='qr')
cr = qk.ClassicalRegister(2, name='cr')
qc = qk.QuantumCircuit(qr, cr)
## Initialize Bell state
qc.x(qr[0])
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
## Pre measurement unitaries to select the basis along a (for the first qubit) and b (for the second qubit)
qc.u3(ta,0,0,qr[0])
qc.u3(theta_b,0,0,qr[1])
## Measures
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
## Running and saving result
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(qc, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
out = 0
for key,value in counts.items():
if (key == '00') or (key == '11'):
out += value
elif (key == '01') or (key == '10'):
out -= value
Pab[i] = out/nshots
# Quantum circuit to measure Pac with the given a
qr = qk.QuantumRegister(2, name='qr')
cr = qk.ClassicalRegister(2, name='cr')
qc = qk.QuantumCircuit(qr, cr)
## Initialize Bell state
qc.x(qr[0])
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
## Pre measurement unitaries to select the basis along a (for the first qubit) and c (for the second qubit)
qc.u3(ta,0,0,qr[0])
qc.u3(theta_c,0,0,qr[1])
## Measures
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
## Running and saving result
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(qc, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
out = 0
for key,value in counts.items():
if (key == '00') or (key == '11'):
out += value
elif (key == '01') or (key == '10'):
out -= value
Pac[i] = out/nshots
quantum_outs = Pab-Pac
# Classical calculations
thetas = np.linspace(0,2*math.pi,100)
classical_outs = np.zeros(len(thetas))
b_vec = np.array([math.sin(theta_b),0.0,math.cos(theta_b)])
c_vec = np.array([math.sin(theta_c),0.0,math.cos(theta_c)])
Bell_limit = (1 - b_vec.dot(c_vec))*np.ones(len(thetas))
for k in range(len(thetas)):
a_vec = np.array([math.sin(thetas[k]),0.0,math.cos(thetas[k])])
classical_outs[k] = -a_vec.dot(b_vec) + a_vec.dot(c_vec)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(thetas,classical_outs,'b', label='classical computation')
ax.plot(theta_a,quantum_outs,'r*', label='quantum algorithm')
ax.plot(thetas,Bell_limit,'--k', label='Bell bound') # If the data go beyond these boundaries,
ax.plot(thetas,-Bell_limit,'--k', label='Bell bound') # the inequality is violated
ax.plot(thetas,(1+Pbc)*np.ones(len(thetas)),'--c', label='Bell bound (quantum)')
ax.plot(thetas,-(1+Pbc)*np.ones(len(thetas)),'--c', label='Bell bound (quantum)')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1)
plt.xlabel(r'$\theta_a$')
plt.show()
from qiskit.tools.monitor import job_monitor
my_token = ''
ibmq_provider = qk.IBMQ.enable_account(my_token)
delta = 0.5*math.pi
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
my_backend = ibmq_provider.get_backend('ibmqx2')
job = qk.execute(Heis2, backend=my_backend, shots=1024)
job_monitor(job, interval=5)
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
my_backend.configuration().coupling_map # In the output, the first entry in a pair [a,b] is a control, second is the
# corresponding target for a CNOT
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from __future__ import annotations
import numpy as np
import networkx as nx
num_nodes = 4
w = np.array([[0., 1., 1., 0.],
[1., 0., 1., 1.],
[1., 1., 0., 1.],
[0., 1., 1., 0.]])
G = nx.from_numpy_array(w)
layout = nx.random_layout(G, seed=10)
colors = ['r', 'g', 'b', 'y']
nx.draw(G, layout, node_color=colors)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels);
def objective_value(x: np.ndarray, w: np.ndarray) -> float:
"""Compute the value of a cut.
Args:
x: Binary string as numpy array.
w: Adjacency matrix.
Returns:
Value of the cut.
"""
X = np.outer(x, (1 - x))
w_01 = np.where(w != 0, 1, 0)
return np.sum(w_01 * X)
def bitfield(n: int, L: int) -> list[int]:
result = np.binary_repr(n, L)
return [int(digit) for digit in result] # [2:] to chop off the "0b" part
# use the brute-force way to generate the oracle
L = num_nodes
max = 2**L
sol = np.inf
for i in range(max):
cur = bitfield(i, L)
how_many_nonzero = np.count_nonzero(cur)
if how_many_nonzero * 2 != L: # not balanced
continue
cur_v = objective_value(np.array(cur), w)
if cur_v < sol:
sol = cur_v
print(f'Objective value computed by the brute-force method is {sol}')
from qiskit.quantum_info import Pauli, SparsePauliOp
def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]:
r"""Generate Hamiltonian for the graph partitioning
Notes:
Goals:
1 Separate the vertices into two set of the same size.
2 Make sure the number of edges between the two set is minimized.
Hamiltonian:
H = H_A + H_B
H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2}
H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj}
H_A is for achieving goal 2 and H_B is for achieving goal 1.
Args:
weight_matrix: Adjacency matrix.
Returns:
Operator for the Hamiltonian
A constant shift for the obj function.
"""
num_nodes = len(weight_matrix)
pauli_list = []
coeffs = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(-0.5)
shift += 0.5
for i in range(num_nodes):
for j in range(num_nodes):
if i != j:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(1.0)
else:
shift += 1
return SparsePauliOp(pauli_list, coeffs=coeffs), shift
qubit_op, offset = get_operator(w)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, Statevector
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
sampler = Sampler()
def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: State vector or quasi-distribution.
Returns:
Binary string as an array of ints.
"""
if isinstance(state_vector, QuasiDistribution):
values = list(state_vector.values())
else:
values = state_vector
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = bitfield(k, n)
x.reverse()
return np.asarray(x)
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
qaoa = QAOA(sampler, optimizer, reps=2)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by QAOA is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.quantum_info import Operator
npme = NumPyMinimumEigensolver()
result = npme.compute_minimum_eigenvalue(Operator(qubit_op))
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear")
sampling_vqe = SamplingVQE(sampler, ansatz, optimizer)
result = sampling_vqe.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f"Objective value computed by VQE is {objective_value(x, w)}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/magn5452/QiskitQaoa
|
magn5452
|
from operator import xor
import numpy as np
from qiskit import QuantumCircuit
from qiskit.extensions import HamiltonianGate
from qiskit_nature.operators.second_quantization import SpinOp
from VehicleRouting.framework.qaoa.CircuitStrategy import InitialStrategy, MixerStrategy
from VehicleRouting.standard.qaoa.MixerStrategy import PartialSwapMixerStrategy, AdjacentSwapMixerStrategy
class NullInitialStrategy(InitialStrategy):
def __init__(self):
pass
def set_up_initial_state_circuit(self, quantum_circuit: QuantumCircuit):
pass
class HGateInitialStrategy(InitialStrategy):
def __init__(self):
pass
def set_up_initial_state_circuit(self, quantum_circuit: QuantumCircuit):
quantum_circuit.barrier()
for index_qubit in range(0, quantum_circuit.num_qubits):
quantum_circuit.h(index_qubit)
class OneHotSingleInitialStrategy(InitialStrategy):
def __init__(self):
pass
def set_up_initial_state_circuit(self, quantum_circuit: QuantumCircuit):
quantum_circuit.barrier()
initial_array = self.get_initial_array(quantum_circuit.num_qubits)
for index_qubit, value_qubit in enumerate(initial_array):
if value_qubit == 1:
quantum_circuit.x(index_qubit)
def get_initial_array(self, num_qubits):
initial_array = np.zeros(num_qubits)
num_vertices = int(np.round(np.sqrt(num_qubits)))
for index_qubit in range(0, num_qubits):
if np.mod(index_qubit, num_vertices + 1) == 0:
initial_array[index_qubit] = 1
return initial_array
class XGateInitialStrategy(InitialStrategy):
def __init__(self, initial_array):
self.initial_array = initial_array
def set_up_initial_state_circuit(self, quantum_circuit: QuantumCircuit):
quantum_circuit.barrier()
for index_qubit, value_qubit in enumerate(self.initial_array):
if value_qubit == 1:
quantum_circuit.x(index_qubit)
class PartialSwapInitialStrategy(InitialStrategy):
def __init__(self):
pass
def set_up_initial_state_circuit(self, quantum_circuit):
XGateInitialStrategy(initial_array=np.array([1, 0, 0, 0, 1, 0, 0, 0, 1])).set_up_initial_state_circuit(
quantum_circuit)
quantum_circuit.barrier()
n = 0
beta_3 = n * np.pi - np.arcsin(np.sqrt(1 / 3))
beta_2 = n * np.pi - np.arcsin(np.sqrt(1 / 2))
self.set_up_partial_swap_gate(beta_2, 1, 2, 1, 2, quantum_circuit)
self.set_up_partial_swap_gate(beta_3, 0, 1, 0, 1, quantum_circuit)
self.set_up_partial_swap_gate(beta_3, 0, 2, 0, 1, quantum_circuit)
self.set_up_partial_swap_gate(beta_2, 0, 2, 0, 2, quantum_circuit)
self.set_up_partial_swap_gate(beta_2, 0, 1, 0, 2, quantum_circuit)
def set_up_partial_swap_gate(self, beta, city_u, city_v, position_i, position_j, quantum_circuit):
num_vertices = int(np.round(np.sqrt(quantum_circuit.num_qubits)))
hamiltonian = SpinOp([("++--", 1), ("--++", 1)])
unitary_gate = HamiltonianGate(hamiltonian.to_matrix(), beta, label="(" + str(round(beta, 1)) + ")")
quantum_circuit.append(unitary_gate, [self.map(city_u, position_i, num_vertices),
self.map(city_v, position_j,
num_vertices),
self.map(city_u, position_j,
num_vertices),
self.map(city_v, position_i, num_vertices)])
def map(self, city: int, position: int, num_vertices: int):
mapping = num_vertices * np.mod(city, num_vertices) + np.mod(position, num_vertices)
return mapping
class CustomInitialStrategy(InitialStrategy):
def __init__(self):
pass
def set_up_initial_state_circuit(self, quantum_circuit: QuantumCircuit):
initializer = OneHotSingleInitialStrategy()
initializer.set_up_initial_state_circuit(quantum_circuit)
mixer = AdjacentSwapMixerStrategy()
mixer.set_up_mixer_circuit(np.pi / 2, quantum_circuit)
class AdjacentSwapInitialStrategy(InitialStrategy):
def __init__(self):
pass
def set_up_initial_state_circuit(self, quantum_circuit):
initializer = OneHotSingleInitialStrategy()
initializer.set_up_initial_state_circuit(quantum_circuit)
initial_array = initializer.get_initial_array(quantum_circuit.num_qubits)
quantum_circuit.barrier()
num_vertices = int(np.round(np.sqrt(quantum_circuit.num_qubits)))
hamiltonian = self.make_adjacent_swap_mixer_hamiltonian(num_vertices, initial_array)
beta = np.sqrt(3) / (3 ** 2) * np.pi # for n = 3 sqrt(3)/3^2
unitary_gate = HamiltonianGate(hamiltonian.to_matrix(), beta, label="(" + str(round(beta, 1)) + ")")
quantum_circuit.append(unitary_gate, range(quantum_circuit.num_qubits))
def make_adjacent_swap_mixer_hamiltonian(self, num_vertices, initial_array) -> SpinOp:
opr_list = []
for city_u in range(num_vertices):
for city_v in range(num_vertices):
for position_i in range(num_vertices):
for position_j in range(num_vertices):
if city_u < city_v and position_i < position_j:
if initial_array[self.map(city_u, position_i, num_vertices)] == 1 and initial_array[
self.map(city_v, position_j, num_vertices)] == 1:
string, string_hermitian = self.make_string_partial_mixer(city_u, city_v, position_i,
position_j, num_vertices)
print(string)
opr_list.append((string, 1))
opr_list.append((string_hermitian, 1))
return SpinOp(opr_list)
def make_string_partial_mixer(self, city_u, city_v, position_i, position_j, num_vertices):
string_list = []
string_hermitian_list = []
for i in range(num_vertices ** 2):
string_list.append("I")
string_hermitian_list.append("I")
string_list[self.map(city_u, position_i, num_vertices)] = "+"
string_list[self.map(city_v, position_j, num_vertices)] = "+"
string_list[self.map(city_u, position_j, num_vertices)] = "-"
string_list[self.map(city_v, position_i, num_vertices)] = "-"
string_hermitian_list[self.map(city_u, position_i, num_vertices)] = "-"
string_hermitian_list[self.map(city_v, position_j, num_vertices)] = "-"
string_hermitian_list[self.map(city_u, position_j, num_vertices)] = "+"
string_hermitian_list[self.map(city_v, position_i, num_vertices)] = "+"
new_string = "".join(string_list)
new_string_hermitian = "".join(string_hermitian_list)
return new_string, new_string_hermitian
def map(self, city: int, position: int, num_vertices: int):
mapping = num_vertices * np.mod(city, num_vertices) + np.mod(position, num_vertices)
return mapping
class Adjacent2SwapInitialStrategy(InitialStrategy):
def __init__(self):
pass
def set_up_initial_state_circuit(self, quantum_circuit):
initializer = OneHotSingleInitialStrategy()
initializer.set_up_initial_state_circuit(quantum_circuit)
initial_array = initializer.get_initial_array(quantum_circuit.num_qubits)
quantum_circuit.barrier()
num_vertices = int(np.round(np.sqrt(quantum_circuit.num_qubits)))
hamiltonian = self.make_adjacent_swap_mixer_hamiltonian(num_vertices, initial_array)
beta = np.sqrt(3) / (3 ** 2) * np.pi # for n = 3 sqrt(3)/3^2
unitary_gate = HamiltonianGate(hamiltonian.to_matrix(), beta, label="(" + str(round(beta, 1)) + ")")
quantum_circuit.append(unitary_gate, range(quantum_circuit.num_qubits))
def make_adjacent_swap_mixer_hamiltonian(self, num_vertices, initial_array) -> SpinOp:
opr_list = []
for city_u in range(num_vertices):
for city_v in range(num_vertices):
for position_i in range(num_vertices):
for position_j in range(num_vertices):
if city_u != city_v and position_i != position_j:
if initial_array[self.map(city_u, position_i, num_vertices)] == 1 and initial_array[
self.map(city_v, position_j, num_vertices)] == 1:
string, string_hermitian = self.make_string_partial_mixer(city_u, city_v, position_i,
position_j, num_vertices)
print(string)
opr_list.append((string, 1))
opr_list.append((string_hermitian, 1))
return SpinOp(opr_list)
def make_string_partial_mixer(self, city_u, city_v, position_i, position_j, num_vertices):
string_list = []
string_hermitian_list = []
for i in range(num_vertices ** 2):
string_list.append("I")
string_hermitian_list.append("I")
string_list[self.map(city_u, position_i, num_vertices)] = "+"
string_list[self.map(city_v, position_j, num_vertices)] = "+"
string_list[self.map(city_u, position_j, num_vertices)] = "-"
string_list[self.map(city_v, position_i, num_vertices)] = "-"
string_hermitian_list[self.map(city_u, position_i, num_vertices)] = "-"
string_hermitian_list[self.map(city_v, position_j, num_vertices)] = "-"
string_hermitian_list[self.map(city_u, position_j, num_vertices)] = "+"
string_hermitian_list[self.map(city_v, position_i, num_vertices)] = "+"
new_string = "".join(string_list)
new_string_hermitian = "".join(string_hermitian_list)
return new_string, new_string_hermitian
def map(self, city: int, position: int, num_vertices: int):
mapping = num_vertices * np.mod(city, num_vertices) + np.mod(position, num_vertices)
return mapping
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
with pulse.build(name='my_example') as my_program:
# Add instructions here
pass
my_program
from qiskit.pulse import DriveChannel
channel = DriveChannel(0)
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend=backend, name='backend_aware') as backend_aware_program:
channel = pulse.drive_channel(0)
print(pulse.num_qubits())
# Raises an error as backend only has 5 qubits
#pulse.drive_channel(100)
with pulse.build(backend) as delay_5dt:
pulse.delay(5, channel)
from qiskit.pulse import library
amp = 1
sigma = 10
num_samples = 128
gaus = pulse.library.Gaussian(num_samples, amp, sigma,
name="Parametric Gaus")
gaus.draw()
import numpy as np
times = np.arange(num_samples)
gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2))
gaus = library.Waveform(gaussian_samples, name="WF Gaus")
gaus.draw()
gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus")
gaus.draw()
with pulse.build() as schedule:
pulse.play(gaus, channel)
schedule.draw()
with pulse.build() as schedule:
pulse.play([0.001*i for i in range(160)], channel)
schedule.draw()
with pulse.build(backend) as schedule:
pulse.set_frequency(4.5e9, channel)
with pulse.build(backend) as schedule:
pulse.shift_phase(np.pi, channel)
from qiskit.pulse import Acquire, AcquireChannel, MemorySlot
with pulse.build(backend) as schedule:
pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0))
with pulse.build(backend, name='Left align example') as program:
with pulse.align_left():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Right align example') as program:
with pulse.align_right():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
gaussian_pulse = library.gaussian(100, 0.5, 20)
with pulse.align_equispaced(2*gaussian_pulse.duration):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
with pulse.align_sequential():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Offset example') as program:
with pulse.phase_offset(3.14, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
with pulse.frequency_offset(10e6, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
program.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Useful additional packages
import matplotlib.pyplot as plt
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u(pi/2,pi/4,pi/8,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.p(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.id(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.x(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.y(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.z(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.h(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.s(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.sdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.t(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.tdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rx(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ry(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rz(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cy(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cz(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ch(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.crz(pi/2,q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cp(pi/2,q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.swap(q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cswap(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.measure(q, c)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q,c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
# Initializing a three-qubit quantum state
import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.initialize(desired_vector, [q[0],q[1],q[2]])
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
job = backend.run(transpile(qc, backend))
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Boolean Logical DNF, CNF, and ESOP Circuits.
"""
import logging
from abc import abstractmethod, ABC
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.qasm import pi
from qiskit.aqua import AquaError
from .gates import mct
logger = logging.getLogger(__name__)
class BooleanLogicNormalForm(ABC):
@staticmethod
def _get_ast_depth(ast):
if ast[0] == 'const' or ast[0] == 'lit':
return 0
else:
return 1 + max([BooleanLogicNormalForm._get_ast_depth(c) for c in ast[1:]])
@staticmethod
def _get_ast_num_vars(ast):
if ast[0] == 'const':
return 0
all_vars = set()
def get_ast_vars(cur_ast):
if cur_ast[0] == 'lit':
all_vars.add(abs(cur_ast[1]))
else:
for c in cur_ast[1:]:
get_ast_vars(c)
get_ast_vars(ast)
return max(all_vars)
@staticmethod
def _lits_to_flags(vs):
_vs = []
for v in vs:
if v in _vs:
continue
elif -v in _vs:
return None
else:
_vs.append(v)
flags = abs(max(_vs, key=abs)) * [0]
for v in _vs:
flags[abs(v) - 1] = 1 if v > 0 else -1
return flags
"""
The base abstract class for:
- CNF (Conjunctive Normal Forms),
- DNF (Disjunctive Normal Forms), and
- ESOP (Exclusive Sum of Products)
"""
def __init__(self, ast, num_vars=None):
"""
Constructor.
Args:
ast (tuple): The logic expression as an Abstract Syntax Tree (AST) tuple
num_vars (int): Number of boolean variables
"""
ast_depth = BooleanLogicNormalForm._get_ast_depth(ast)
if ast_depth > 2:
raise AquaError('Expressions of depth greater than 2 are not supported.')
self._depth = ast_depth
inferred_num_vars = BooleanLogicNormalForm._get_ast_num_vars(ast)
if num_vars is None:
self._num_variables = inferred_num_vars
else:
if inferred_num_vars > num_vars:
raise AquaError('{} variables present, but only {} specified.'.format(inferred_num_vars, num_vars))
self._num_variables = num_vars
if ast_depth == 0:
self._ast = ast
self._num_clauses = 0
self._max_clause_size = 0
else:
if ast_depth == 1:
if self._depth == 1:
self._num_clauses = 1
self._max_clause_size = len(ast) - 1
self._ast = ast
else: # depth == 2:
if ast[0] == 'and':
op = 'or'
elif ast[0] == 'or':
op = 'and'
else:
raise AquaError('Unexpected expression root operator {}.'.format(ast[0]))
self._num_clauses = len(ast) - 1
self._max_clause_size = 1
self._ast = (ast[0], *[(op, l) for l in ast[1:]])
else: # self._depth == 2
self._num_clauses = len(ast) - 1
self._max_clause_size = max([len(l) - 1 for l in ast[1:]])
self._ast = ast
self._variable_register = None
self._clause_register = None
self._output_register = None
self._ancillary_register = None
@property
def num_variables(self):
return self._num_variables
@property
def num_clauses(self):
return self._num_clauses
@property
def variable_register(self):
return self._variable_register
@property
def clause_register(self):
return self._clause_register
@property
def output_register(self):
return self._output_register
@property
def ancillary_register(self):
return self._ancillary_register
@staticmethod
def _set_up_register(num_qubits_needed, provided_register, description):
if provided_register == 'skip':
return None
else:
if provided_register is None:
if num_qubits_needed > 0:
return QuantumRegister(num_qubits_needed, name=description[0])
else:
num_qubits_provided = len(provided_register)
if num_qubits_needed > num_qubits_provided:
raise ValueError(
'The {} QuantumRegister needs {} qubits, but the provided register contains only {}.'.format(
description, num_qubits_needed, num_qubits_provided
))
else:
return provided_register
def _set_up_circuit(
self,
circuit=None,
variable_register=None,
clause_register=None,
output_register=None,
output_idx=None,
ancillary_register=None,
mct_mode='basic'
):
self._variable_register = BooleanLogicNormalForm._set_up_register(
self.num_variables, variable_register, 'variable'
)
if self._depth > 1:
self._clause_register = BooleanLogicNormalForm._set_up_register(
self.num_clauses, clause_register, 'clause'
)
self._output_register = BooleanLogicNormalForm._set_up_register(
1, output_register, 'output'
)
self._output_idx = output_idx if output_idx else 0
max_num_ancillae = max(
max(
self._num_clauses if self._clause_register else 0,
self._max_clause_size
) - 2,
0
)
num_ancillae = 0
if mct_mode == 'basic' or mct_mode == 'basic-dirty-ancilla':
num_ancillae = max_num_ancillae
elif mct_mode == 'advanced':
if max_num_ancillae >= 3:
num_ancillae = 1
elif mct_mode == 'noancilla':
pass
else:
raise ValueError('Unsupported MCT mode {}.'.format(mct_mode))
self._ancillary_register = BooleanLogicNormalForm._set_up_register(
num_ancillae, ancillary_register, 'ancilla'
)
if circuit is None:
circuit = QuantumCircuit()
if self._variable_register:
circuit.add_register(self._variable_register)
if self._clause_register:
circuit.add_register(self._clause_register)
if self._output_register:
circuit.add_register(self._output_register)
if self._ancillary_register:
circuit.add_register(self._ancillary_register)
return circuit
def _construct_circuit_for_tiny_expr(self, circuit, output_idx=0):
if self._ast == ('const', 1):
circuit.u3(pi, 0, pi, self._output_register[output_idx])
elif self._ast[0] == 'lit':
idx = abs(self._ast[1]) - 1
if self._ast[1] < 0:
circuit.u3(pi, 0, pi, self._variable_register[idx])
circuit.cx(self._variable_register[idx], self._output_register[output_idx])
@abstractmethod
def construct_circuit(self, *args, **kwargs):
raise NotImplementedError
class CNF(BooleanLogicNormalForm):
"""
Class for constructing circuits for Conjunctive Normal Forms
"""
def construct_circuit(
self,
circuit=None,
variable_register=None,
clause_register=None,
output_register=None,
ancillary_register=None,
mct_mode='basic'
):
"""
Construct circuit.
Args:
circuit (QuantumCircuit): The optional circuit to extend from
variable_register (QuantumRegister): The optional quantum register to use for problem variables
clause_register (QuantumRegister): The optional quantum register to use for problem clauses
output_register (QuantumRegister): The optional quantum register to use for holding the output
ancillary_register (QuantumRegister): The optional quantum register to use as ancilla
mct_mode (str): The mode to use for building Multiple-Control Toffoli
Returns:
QuantumCircuit: quantum circuit.
"""
circuit = self._set_up_circuit(
circuit=circuit,
variable_register=variable_register,
clause_register=clause_register,
output_register=output_register,
ancillary_register=ancillary_register,
mct_mode=mct_mode
)
if self._depth == 0:
self._construct_circuit_for_tiny_expr(circuit)
elif self._depth == 1:
lits = [l[1] for l in self._ast[1:]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.AND(
self._variable_register,
self._output_register[0],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
else: # self._depth == 2:
# compute all clauses
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'or':
lits = [l[1] for l in clause_expr[1:]]
elif clause_expr[0] == 'lit':
lits = [clause_expr[1]]
else:
raise AquaError(
'Operator "{}" of clause {} in logic expression {} is unexpected.'.format(
clause_expr[0], clause_index, self._ast)
)
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.OR(
self._variable_register,
self._clause_register[clause_index],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
# collect results from all clauses
circuit.mct(
self._clause_register,
self._output_register[self._output_idx],
self._ancillary_register,
mode=mct_mode
)
# uncompute all clauses
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'or':
lits = [l[1] for l in clause_expr[1:]]
else: # clause_expr[0] == 'lit':
lits = [clause_expr[1]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.OR(
self._variable_register,
self._clause_register[clause_index],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
return circuit
class DNF(BooleanLogicNormalForm):
"""
Class for constructing circuits for Disjunctive Normal Forms
"""
def construct_circuit(
self,
circuit=None,
variable_register=None,
clause_register=None,
output_register=None,
ancillary_register=None,
mct_mode='basic'
):
"""
Construct circuit.
Args:
circuit (QuantumCircuit): The optional circuit to extend from
variable_register (QuantumRegister): The optional quantum register to use for problem variables
clause_register (QuantumRegister): The optional quantum register to use for problem clauses
output_register (QuantumRegister): The optional quantum register to use for holding the output
ancillary_register (QuantumRegister): The optional quantum register to use as ancilla
mct_mode (str): The mode to use for building Multiple-Control Toffoli
Returns:
QuantumCircuit: quantum circuit.
"""
circuit = self._set_up_circuit(
circuit=circuit,
variable_register=variable_register,
clause_register=clause_register,
output_register=output_register,
ancillary_register=ancillary_register,
mct_mode=mct_mode
)
if self._depth == 0:
self._construct_circuit_for_tiny_expr(circuit)
elif self._depth == 1:
lits = [l[1] for l in self._ast[1:]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.OR(
self._variable_register,
self._output_register[0],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
else: # self._depth == 2
# compute all clauses
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'and':
lits = [l[1] for l in clause_expr[1:]]
elif clause_expr[0] == 'lit':
lits = [clause_expr[1]]
else:
raise AquaError(
'Operator "{}" of clause {} in logic expression {} is unexpected.'.format(
clause_expr[0], clause_index, self._ast)
)
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.AND(
self._variable_register,
self._clause_register[clause_index],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
# init the output qubit to 1
circuit.u3(pi, 0, pi, self._output_register[self._output_idx])
# collect results from all clauses
circuit.u3(pi, 0, pi, self._clause_register)
circuit.mct(
self._clause_register,
self._output_register[self._output_idx],
self._ancillary_register,
mode=mct_mode
)
circuit.u3(pi, 0, pi, self._clause_register)
# uncompute all clauses
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'and':
lits = [l[1] for l in clause_expr[1:]]
else: # clause_expr[0] == 'lit':
lits = [clause_expr[1]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.AND(
self._variable_register,
self._clause_register[clause_index],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
return circuit
class ESOP(BooleanLogicNormalForm):
"""
Class for constructing circuits for Exclusive Sum of Products
"""
def construct_circuit(
self,
circuit=None,
variable_register=None,
output_register=None,
output_idx=None,
ancillary_register=None,
mct_mode='basic'
):
"""
Construct circuit.
Args:
circuit (QuantumCircuit): The optional circuit to extend from
variable_register (QuantumRegister): The optional quantum register to use for problem variables
output_register (QuantumRegister): The optional quantum register to use for holding the output
output_idx (int): The index of the output register to write to
ancillary_register (QuantumRegister): The optional quantum register to use as ancilla
mct_mode (str): The mode to use for building Multiple-Control Toffoli
Returns:
QuantumCircuit: quantum circuit.
"""
circuit = self._set_up_circuit(
circuit=circuit,
variable_register=variable_register,
clause_register='skip',
output_register=output_register,
output_idx=output_idx,
ancillary_register=ancillary_register,
mct_mode=mct_mode
)
# compute all clauses
if self._depth == 0:
self._construct_circuit_for_tiny_expr(circuit, output_idx=output_idx)
else:
for clause_index, clause_expr in enumerate(self._ast[1:]):
if clause_expr[0] == 'and':
lits = [l[1] for l in clause_expr[1:]]
else: # clause_expr[0] == 'lit':
lits = [clause_expr[1]]
flags = BooleanLogicNormalForm._lits_to_flags(lits)
circuit.AND(
self._variable_register,
self._output_register[self._output_idx],
self._ancillary_register,
flags=flags,
mct_mode=mct_mode
)
return circuit
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test hardcoded decomposition rules and matrix definitions for standard gates."""
import inspect
import numpy as np
from ddt import ddt, data, idata, unpack
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.circuit import ParameterVector, Gate, ControlledGate
from qiskit.circuit.library import standard_gates
from qiskit.circuit.library import (
HGate,
CHGate,
IGate,
RGate,
RXGate,
CRXGate,
RYGate,
CRYGate,
RZGate,
CRZGate,
SGate,
SdgGate,
CSwapGate,
TGate,
TdgGate,
U1Gate,
CU1Gate,
U2Gate,
U3Gate,
CU3Gate,
XGate,
CXGate,
ECRGate,
CCXGate,
YGate,
CYGate,
ZGate,
CZGate,
RYYGate,
PhaseGate,
CPhaseGate,
UGate,
CUGate,
SXGate,
SXdgGate,
CSXGate,
RVGate,
XXMinusYYGate,
)
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from .gate_utils import _get_free_params
class TestGateDefinitions(QiskitTestCase):
"""Test the decomposition of a gate in terms of other gates
yields the equivalent matrix as the hardcoded matrix definition
up to a global phase."""
def test_ch_definition(self): # TODO: expand this to all gates
"""Test ch gate matrix and definition."""
circ = QuantumCircuit(2)
circ.ch(0, 1)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_ccx_definition(self):
"""Test ccx gate matrix and definition."""
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_crz_definition(self):
"""Test crz gate matrix and definition."""
circ = QuantumCircuit(2)
circ.crz(1, 0, 1)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_cry_definition(self):
"""Test cry gate matrix and definition."""
circ = QuantumCircuit(2)
circ.cry(1, 0, 1)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_crx_definition(self):
"""Test crx gate matrix and definition."""
circ = QuantumCircuit(2)
circ.crx(1, 0, 1)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_cswap_definition(self):
"""Test cswap gate matrix and definition."""
circ = QuantumCircuit(3)
circ.cswap(0, 1, 2)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_cu1_definition(self):
"""Test cu1 gate matrix and definition."""
circ = QuantumCircuit(2)
circ.append(CU1Gate(1), [0, 1])
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_cu3_definition(self):
"""Test cu3 gate matrix and definition."""
circ = QuantumCircuit(2)
circ.append(CU3Gate(1, 1, 1), [0, 1])
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_cx_definition(self):
"""Test cx gate matrix and definition."""
circ = QuantumCircuit(2)
circ.cx(0, 1)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_ecr_definition(self):
"""Test ecr gate matrix and definition."""
circ = QuantumCircuit(2)
circ.ecr(0, 1)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_rv_definition(self):
"""Test R(v) gate to_matrix and definition."""
qreg = QuantumRegister(1)
circ = QuantumCircuit(qreg)
vec = np.array([0.1, 0.2, 0.3], dtype=float)
circ.rv(*vec, 0)
decomposed_circ = circ.decompose()
self.assertTrue(Operator(circ).equiv(Operator(decomposed_circ)))
def test_rv_r_equiv(self):
"""Test R(v) gate is equivalent to R gate."""
theta = np.pi / 5
phi = np.pi / 3
rgate = RGate(theta, phi)
axis = np.array([np.cos(phi), np.sin(phi), 0]) # RGate axis
rotvec = theta * axis
rv = RVGate(*rotvec)
rg_matrix = rgate.to_matrix()
rv_matrix = rv.to_matrix()
np.testing.assert_array_max_ulp(rg_matrix.real, rv_matrix.real, 4)
np.testing.assert_array_max_ulp(rg_matrix.imag, rv_matrix.imag, 4)
def test_rv_zero(self):
"""Test R(v) gate with zero vector returns identity"""
rv = RVGate(0, 0, 0)
self.assertTrue(np.array_equal(rv.to_matrix(), np.array([[1, 0], [0, 1]])))
def test_xx_minus_yy_definition(self):
"""Test XX-YY gate decomposition."""
theta, beta = np.random.uniform(-10, 10, size=2)
gate = XXMinusYYGate(theta, beta)
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1])
decomposed_circuit = circuit.decompose()
self.assertTrue(len(decomposed_circuit) > len(circuit))
self.assertTrue(Operator(circuit).equiv(Operator(decomposed_circuit), atol=1e-7))
@ddt
class TestStandardGates(QiskitTestCase):
"""Standard Extension Test."""
@unpack
@data(
*inspect.getmembers(
standard_gates,
predicate=lambda value: (inspect.isclass(value) and issubclass(value, Gate)),
)
)
def test_definition_parameters(self, class_name, gate_class):
"""Verify definitions from standard library include correct parameters."""
free_params = _get_free_params(gate_class)
n_params = len(free_params)
param_vector = ParameterVector("th", n_params)
if class_name in ("MCPhaseGate", "MCU1Gate"):
param_vector = param_vector[:-1]
gate = gate_class(*param_vector, num_ctrl_qubits=2)
elif class_name in ("MCXGate", "MCXGrayCode", "MCXRecursive", "MCXVChain"):
num_ctrl_qubits = 2
param_vector = param_vector[:-1]
gate = gate_class(num_ctrl_qubits, *param_vector)
elif class_name == "MSGate":
num_qubits = 2
param_vector = param_vector[:-1]
gate = gate_class(num_qubits, *param_vector)
else:
gate = gate_class(*param_vector)
if gate.definition is not None:
self.assertEqual(gate.definition.parameters, set(param_vector))
@unpack
@data(
*inspect.getmembers(
standard_gates,
predicate=lambda value: (inspect.isclass(value) and issubclass(value, Gate)),
)
)
def test_inverse(self, class_name, gate_class):
"""Verify self-inverse pair yield identity for all standard gates."""
free_params = _get_free_params(gate_class)
n_params = len(free_params)
float_vector = [0.1 + 0.1 * i for i in range(n_params)]
if class_name in ("MCPhaseGate", "MCU1Gate"):
float_vector = float_vector[:-1]
gate = gate_class(*float_vector, num_ctrl_qubits=2)
elif class_name in ("MCXGate", "MCXGrayCode", "MCXRecursive", "MCXVChain"):
num_ctrl_qubits = 3
float_vector = float_vector[:-1]
gate = gate_class(num_ctrl_qubits, *float_vector)
elif class_name == "PauliGate":
pauli_string = "IXYZ"
gate = gate_class(pauli_string)
else:
gate = gate_class(*float_vector)
from qiskit.quantum_info.operators.predicates import is_identity_matrix
self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.inverse()).data))
if gate.definition is not None:
self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.definition.inverse()).data))
self.assertTrue(is_identity_matrix(Operator(gate).dot(gate.inverse().definition).data))
@ddt
class TestGateEquivalenceEqual(QiskitTestCase):
"""Test the decomposition of a gate in terms of other gates
yields the same matrix as the hardcoded matrix definition."""
class_list = Gate.__subclasses__() + ControlledGate.__subclasses__()
exclude = {
"ControlledGate",
"DiagonalGate",
"UCGate",
"MCGupDiag",
"MCU1Gate",
"UnitaryGate",
"HamiltonianGate",
"MCPhaseGate",
"UCPauliRotGate",
"SingleQubitUnitary",
"MCXGate",
"VariadicZeroParamGate",
"ClassicalFunction",
"ClassicalElement",
"StatePreparation",
"LinearFunction",
"PermutationGate",
"Commuting2qBlock",
"PauliEvolutionGate",
"_U0Gate",
"_DefinedGate",
}
# Amazingly, Python's scoping rules for class bodies means that this is the closest we can get
# to a "natural" comprehension or functional iterable definition:
# https://docs.python.org/3/reference/executionmodel.html#resolution-of-names
@idata(filter(lambda x, exclude=exclude: x.__name__ not in exclude, class_list))
def test_equivalence_phase(self, gate_class):
"""Test that the equivalent circuits from the equivalency_library
have equal matrix representations"""
n_params = len(_get_free_params(gate_class))
params = [0.1 * i for i in range(1, n_params + 1)]
if gate_class.__name__ == "RXXGate":
params = [np.pi / 2]
if gate_class.__name__ in ["MSGate"]:
params[0] = 2
if gate_class.__name__ in ["PauliGate"]:
params = ["IXYZ"]
if gate_class.__name__ in ["BooleanExpression"]:
params = ["x | y"]
gate = gate_class(*params)
equiv_lib_list = std_eqlib.get_entry(gate)
for ieq, equivalency in enumerate(equiv_lib_list):
with self.subTest(msg=gate.name + "_" + str(ieq)):
op1 = Operator(gate)
op2 = Operator(equivalency)
self.assertEqual(op1, op2)
@ddt
class TestStandardEquivalenceLibrary(QiskitTestCase):
"""Standard Extension Test."""
@data(
HGate,
CHGate,
IGate,
RGate,
RXGate,
CRXGate,
RYGate,
CRYGate,
RZGate,
CRZGate,
SGate,
SdgGate,
CSwapGate,
TGate,
TdgGate,
U1Gate,
CU1Gate,
U2Gate,
U3Gate,
CU3Gate,
XGate,
CXGate,
ECRGate,
CCXGate,
YGate,
CYGate,
ZGate,
CZGate,
RYYGate,
PhaseGate,
CPhaseGate,
UGate,
CUGate,
SXGate,
SXdgGate,
CSXGate,
)
def test_definition_parameters(self, gate_class):
"""Verify decompositions from standard equivalence library match definitions."""
n_params = len(_get_free_params(gate_class))
param_vector = ParameterVector("th", n_params)
float_vector = [0.1 * i for i in range(n_params)]
param_gate = gate_class(*param_vector)
float_gate = gate_class(*float_vector)
param_entry = std_eqlib.get_entry(param_gate)
float_entry = std_eqlib.get_entry(float_gate)
if not param_gate.definition or not param_gate.definition.data:
return
self.assertGreaterEqual(len(param_entry), 1)
self.assertGreaterEqual(len(float_entry), 1)
param_qc = QuantumCircuit(param_gate.num_qubits)
float_qc = QuantumCircuit(float_gate.num_qubits)
param_qc.append(param_gate, param_qc.qregs[0])
float_qc.append(float_gate, float_qc.qregs[0])
self.assertTrue(any(equiv == param_qc.decompose() for equiv in param_entry))
self.assertTrue(any(equiv == float_qc.decompose() for equiv in float_entry))
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022-2023 Qiskit on IQM developers
#
# 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.
"""Testing IQM provider.
"""
from collections.abc import Sequence
from importlib.metadata import version
import re
import uuid
from mockito import ANY, matchers, mock, patch, when
import numpy as np
import pytest
from qiskit import QuantumCircuit, execute
from qiskit.circuit import Parameter
from qiskit.circuit.library import RGate, RXGate, RYGate, XGate, YGate
from qiskit.compiler import transpile
import requests
from iqm.iqm_client import HeraldingMode, IQMClient, QuantumArchitecture, RunResult, RunStatus
from iqm.qiskit_iqm.iqm_provider import IQMBackend, IQMFacadeBackend, IQMJob, IQMProvider
from tests.utils import get_mock_ok_response
@pytest.fixture
def backend(linear_architecture_3q):
client = mock(IQMClient)
when(client).get_quantum_architecture().thenReturn(linear_architecture_3q)
return IQMBackend(client)
@pytest.fixture
def circuit():
return QuantumCircuit(3, 3)
@pytest.fixture
def circuit_2() -> QuantumCircuit:
circuit = QuantumCircuit(5)
circuit.cz(0, 1)
return circuit
@pytest.fixture
def submit_circuits_default_kwargs() -> dict:
return {
'qubit_mapping': None,
'calibration_set_id': None,
'shots': 1024,
'max_circuit_duration_over_t2': None,
'heralding_mode': HeraldingMode.NONE,
}
@pytest.fixture
def job_id():
return uuid.uuid4()
def test_default_options(backend):
assert backend.options.shots == 1024
assert backend.options.calibration_set_id is None
assert backend.options.max_circuit_duration_over_t2 is None
assert backend.options.heralding_mode == HeraldingMode.NONE
assert backend.options.circuit_callback is None
def test_backend_name(backend):
assert re.match(r'IQM(.*)Backend', backend.name)
def test_retrieve_job(backend):
job = backend.retrieve_job('a job id')
assert job.backend() == backend
assert job.job_id() == 'a job id'
def test_default_max_circuits(backend):
assert backend.max_circuits is None
def test_set_max_circuits(backend):
assert backend.max_circuits is None
backend.max_circuits = 17
assert backend.max_circuits == 17
backend.max_circuits = 168
assert backend.max_circuits == 168
def test_qubit_name_to_index_to_qubit_name(adonis_architecture_shuffled_names):
client = mock(IQMClient)
when(client).get_quantum_architecture().thenReturn(adonis_architecture_shuffled_names)
backend = IQMBackend(client)
correct_idx_name_associations = set(enumerate(['QB1', 'QB2', 'QB3', 'QB4', 'QB5']))
assert all(backend.index_to_qubit_name(idx) == name for idx, name in correct_idx_name_associations)
assert all(backend.qubit_name_to_index(name) == idx for idx, name in correct_idx_name_associations)
assert backend.index_to_qubit_name(7) is None
assert backend.qubit_name_to_index('Alice') is None
def test_serialize_circuit_raises_error_for_non_transpiled_circuit(backend, circuit):
circuit = QuantumCircuit(2, 2)
with pytest.raises(ValueError, match='has not been transpiled against the current backend'):
backend.serialize_circuit(circuit)
def test_serialize_circuit_raises_error_for_unsupported_instruction(backend, circuit):
circuit.sx(0)
with pytest.raises(ValueError, match=f"Instruction 'sx' in the circuit '{circuit.name}' is not natively supported"):
backend.serialize_circuit(circuit)
def test_serialize_circuit_does_not_raise_for_x_rx_y_ry(backend, circuit):
circuit.x(0)
circuit.rx(0.123, 0)
circuit.y(0)
circuit.ry(0.321, 0)
backend.serialize_circuit(circuit)
def test_serialize_circuit_raises_error_for_unsupported_metadata(backend, circuit):
circuit.append(RGate(theta=np.pi, phi=0), [0])
circuit.metadata = {'some-key': complex(1.0, 2.0)}
with pytest.warns(UserWarning):
serialized_circuit = backend.serialize_circuit(circuit)
assert serialized_circuit.metadata is None
@pytest.mark.parametrize(
'gate, expected_angle, expected_phase',
[
(RGate(theta=np.pi, phi=0), 1 / 2, 0),
(RGate(theta=0, phi=np.pi), 0, 1 / 2),
(RGate(theta=0, phi=2 * np.pi), 0, 1),
(RGate(theta=2 * np.pi, phi=np.pi), 1, 1 / 2),
],
)
def test_serialize_circuit_maps_r_gate(circuit, gate, expected_angle, expected_phase, backend):
circuit.append(gate, [0])
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 1
instr = circuit_ser.instructions[0]
assert instr.name == 'prx'
assert instr.qubits == ('0',)
# Serialized angles should be in full turns
assert instr.args['angle_t'] == expected_angle
assert instr.args['phase_t'] == expected_phase
@pytest.mark.parametrize(
'gate, expected_angle, expected_phase',
[
(XGate(), 1 / 2, 0),
(RXGate(theta=np.pi / 2), 1 / 4, 0),
(RXGate(theta=2 * np.pi / 3), 1 / 3, 0),
(YGate(), 1 / 2, 1 / 4),
(RYGate(theta=np.pi / 2), 1 / 4, 1 / 4),
(RYGate(theta=2 * np.pi / 3), 1 / 3, 1 / 4),
],
)
def test_serialize_circuit_maps_x_rx_y_ry_gates(backend, circuit, gate, expected_angle, expected_phase):
circuit.append(gate, [0])
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 1
instr = circuit_ser.instructions[0]
assert instr.name == 'prx'
assert instr.qubits == ('0',)
assert instr.args['angle_t'] == expected_angle
assert instr.args['phase_t'] == expected_phase
def test_serialize_circuit_maps_cz_gate(circuit, backend):
circuit.cz(0, 2)
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 1
assert circuit_ser.instructions[0].name == 'cz'
assert circuit_ser.instructions[0].qubits == ('0', '2')
assert circuit_ser.instructions[0].args == {}
def test_serialize_circuit_maps_individual_measurements(circuit, backend):
circuit.measure(0, 0)
circuit.measure(1, 1)
circuit.measure(2, 2)
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 3
for i, instruction in enumerate(circuit_ser.instructions):
assert instruction.name == 'measure'
assert instruction.qubits == (f'{i}',)
assert instruction.args == {'key': f'c_3_0_{i}'}
def test_serialize_circuit_batch_measurement(circuit, backend):
circuit.measure([0, 1, 2], [0, 1, 2])
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 3
for i, instruction in enumerate(circuit_ser.instructions):
assert instruction.name == 'measure'
assert instruction.qubits == (f'{i}',)
assert instruction.args == {'key': f'c_3_0_{i}'}
def test_serialize_circuit_barrier(circuit, backend):
circuit.r(theta=np.pi, phi=0, qubit=0)
circuit.barrier([0, 1])
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 2
assert circuit_ser.instructions[1].name == 'barrier'
assert circuit_ser.instructions[1].qubits == ('0', '1')
assert circuit_ser.instructions[1].args == {}
def test_serialize_circuit_id(circuit, backend):
circuit.r(theta=np.pi, phi=0, qubit=0)
circuit.id(0)
circuit_ser = backend.serialize_circuit(circuit)
assert len(circuit_ser.instructions) == 1
assert circuit_ser.instructions[0].name == 'prx'
def test_transpile(backend, circuit):
circuit.h(0)
circuit.id(1)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.cx(2, 0)
circuit_transpiled = transpile(circuit, backend=backend)
cmap = backend.coupling_map.get_edges()
for instruction, qubits, _ in circuit_transpiled.data:
assert instruction.name in ('r', 'cz')
if instruction.name == 'cz':
idx1 = circuit_transpiled.find_bit(qubits[0]).index
idx2 = circuit_transpiled.find_bit(qubits[1]).index
assert ((idx1, idx2) in cmap) or ((idx2, idx1) in cmap)
def test_run_non_native_circuit_with_the_execute_function(backend, circuit):
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(0, 2)
some_id = uuid.uuid4()
backend.client.submit_circuits = lambda *args, **kwargs: some_id
job = execute(circuit, backend=backend, optimization_level=0)
assert isinstance(job, IQMJob)
assert job.job_id() == str(some_id)
def test_run_gets_options_from_execute_function(backend, circuit):
"""Test that any additional keyword arguments to the `execute` function are passed to `IQMBackend.run`. This is more
of a test for Qiskit's `execute` function itself, but still good to have it here to know that the use case works.
"""
def run_mock(qc, **kwargs):
assert isinstance(qc, QuantumCircuit)
assert 'calibration_set_id' in kwargs
assert kwargs['calibration_set_id'] == '92d8dd9a-2678-467e-a20b-ef9c1a594d1f'
assert 'something_else' in kwargs
assert kwargs['something_else'] == [1, 2, 3]
patch(backend.run, run_mock)
execute(
circuit, backend, shots=10, calibration_set_id='92d8dd9a-2678-467e-a20b-ef9c1a594d1f', something_else=[1, 2, 3]
)
def test_run_single_circuit(backend, circuit, submit_circuits_default_kwargs, job_id):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {'qubit_mapping': {'0': 'QB1'}}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
job = backend.run(circuit)
assert isinstance(job, IQMJob)
assert job.job_id() == str(job_id)
# Should also work if the circuit is passed inside a list
job = backend.run([circuit])
assert isinstance(job, IQMJob)
assert job.job_id() == str(job_id)
def test_run_sets_circuit_metadata_to_the_job(backend):
circuit_1 = QuantumCircuit(3)
circuit_1.cz(0, 1)
circuit_1.metadata = {'key1': 'value1', 'key2': 'value2'}
circuit_2 = QuantumCircuit(3)
circuit_2.cz(0, 1)
circuit_2.metadata = {'key1': 'value2', 'key2': 'value1'}
some_id = uuid.uuid4()
backend.client.submit_circuits = lambda *args, **kwargs: some_id
job = backend.run([circuit_1, circuit_2], shots=10)
assert isinstance(job, IQMJob)
assert job.job_id() == str(some_id)
assert job.circuit_metadata == [circuit_1.metadata, circuit_2.metadata]
@pytest.mark.parametrize('shots', [13, 978, 1137])
def test_run_with_custom_number_of_shots(backend, circuit, submit_circuits_default_kwargs, job_id, shots):
circuit.measure(0, 0)
kwargs = submit_circuits_default_kwargs | {'shots': shots, 'qubit_mapping': {'0': 'QB1'}}
when(backend.client).submit_circuits(ANY, **kwargs).thenReturn(job_id)
backend.run(circuit, shots=shots)
@pytest.mark.parametrize(
'calibration_set_id', ['67e77465-d90e-4839-986e-9270f952b743', uuid.UUID('67e77465-d90e-4839-986e-9270f952b743')]
)
def test_run_with_custom_calibration_set_id(
backend, circuit, submit_circuits_default_kwargs, job_id, calibration_set_id
):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {
'calibration_set_id': uuid.UUID('67e77465-d90e-4839-986e-9270f952b743'),
'qubit_mapping': {'0': 'QB1'},
}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
backend.run([circuit], calibration_set_id=calibration_set_id)
def test_run_with_duration_check_disabled(backend, circuit, submit_circuits_default_kwargs, job_id):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {'qubit_mapping': {'0': 'QB1'}, 'max_circuit_duration_over_t2': 0.0}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
backend.run([circuit], max_circuit_duration_over_t2=0.0)
def test_run_uses_heralding_mode_none_by_default(backend, circuit, submit_circuits_default_kwargs, job_id):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {'heralding_mode': HeraldingMode.NONE, 'qubit_mapping': {'0': 'QB1'}}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
backend.run([circuit])
def test_run_with_heralding_mode_zeros(backend, circuit, submit_circuits_default_kwargs, job_id):
circuit.measure(0, 0)
circuit_ser = backend.serialize_circuit(circuit)
kwargs = submit_circuits_default_kwargs | {'heralding_mode': HeraldingMode.ZEROS, 'qubit_mapping': {'0': 'QB1'}}
when(backend.client).submit_circuits([circuit_ser], **kwargs).thenReturn(job_id)
backend.run([circuit], heralding_mode='zeros')
# mypy: disable-error-code="attr-defined"
def test_run_with_circuit_callback(backend, job_id, submit_circuits_default_kwargs):
qc1 = QuantumCircuit(3)
qc1.measure_all()
qc2 = QuantumCircuit(3)
qc2.r(np.pi, 0.3, 0)
qc2.measure_all()
def sample_callback(circuits) -> None:
assert isinstance(circuits, Sequence)
assert all(isinstance(c, QuantumCircuit) for c in circuits)
assert len(circuits) == 2
assert circuits[0].name == qc1.name
assert circuits[1].name == qc2.name
sample_callback.called = True
sample_callback.called = False
kwargs = submit_circuits_default_kwargs | {'qubit_mapping': {'0': 'QB1', '1': 'QB2', '2': 'QB3'}}
when(backend.client).submit_circuits(ANY, **kwargs).thenReturn(job_id)
backend.run([qc1, qc2], circuit_callback=sample_callback)
assert sample_callback.called is True
def test_run_with_unknown_option(backend, circuit, job_id):
circuit.measure_all()
when(backend.client).submit_circuits(...).thenReturn(job_id)
with pytest.warns(Warning, match=r'Unknown backend option\(s\)'):
backend.run(circuit, to_option_or_not_to_option=17)
def test_run_batch_of_circuits(backend, circuit, submit_circuits_default_kwargs, job_id):
theta = Parameter('theta')
theta_range = np.linspace(0, 2 * np.pi, 3)
circuit.cz(0, 1)
circuit.r(theta, 0, 0)
circuit.cz(0, 1)
circuits = [circuit.assign_parameters({theta: t}) for t in theta_range]
circuits_serialized = [backend.serialize_circuit(circuit) for circuit in circuits]
kwargs = submit_circuits_default_kwargs | {'qubit_mapping': {'0': 'QB1', '1': 'QB2'}}
when(backend.client).submit_circuits(circuits_serialized, **kwargs).thenReturn(job_id)
job = backend.run(circuits)
assert isinstance(job, IQMJob)
assert job.job_id() == str(job_id)
def test_error_on_empty_circuit_list(backend):
with pytest.raises(ValueError, match='Empty list of circuits submitted for execution.'):
backend.run([], shots=42)
def test_close_client(backend):
when(backend.client).close_auth_session().thenReturn(True)
try:
backend.close_client()
except Exception as exc: # pylint: disable=broad-except
assert False, f'backend raised an exception {exc} on .close_client()'
def test_get_backend(linear_architecture_3q):
url = 'http://some_url'
when(IQMClient).get_quantum_architecture().thenReturn(linear_architecture_3q)
provider = IQMProvider(url)
backend = provider.get_backend()
assert isinstance(backend, IQMBackend)
assert backend.client._base_url == url
assert backend.num_qubits == 3
assert set(backend.coupling_map.get_edges()) == {(0, 1), (1, 0), (1, 2), (2, 1)}
def test_client_signature(adonis_architecture):
url = 'http://some_url'
provider = IQMProvider(url)
when(requests).get('http://some_url/quantum-architecture', headers=matchers.ANY, timeout=matchers.ANY).thenReturn(
get_mock_ok_response(QuantumArchitecture(quantum_architecture=adonis_architecture).model_dump())
)
backend = provider.get_backend()
assert f'qiskit-iqm {version("qiskit-iqm")}' in backend.client._signature
def test_get_facade_backend(adonis_architecture, adonis_coupling_map):
url = 'http://some_url'
when(IQMClient).get_quantum_architecture().thenReturn(adonis_architecture)
provider = IQMProvider(url)
backend = provider.get_backend('facade_adonis')
assert isinstance(backend, IQMFacadeBackend)
assert backend.client._base_url == url
assert backend.num_qubits == 5
assert set(backend.coupling_map.get_edges()) == adonis_coupling_map
def test_get_facade_backend_raises_error_non_matching_architecture(linear_architecture_3q):
url = 'http://some_url'
when(IQMClient).get_quantum_architecture().thenReturn(linear_architecture_3q)
provider = IQMProvider(url)
with pytest.raises(ValueError, match='Quantum architecture of the remote quantum computer does not match Adonis.'):
provider.get_backend('facade_adonis')
def test_facade_backend_raises_error_on_remote_execution_fail(adonis_architecture, circuit_2):
url = 'http://some_url'
result = {
'status': 'failed',
'measurements': [],
'metadata': {
'request': {
'shots': 1024,
'circuits': [
{
'name': 'circuit_2',
'instructions': [{'name': 'measure', 'qubits': ['0'], 'args': {'key': 'm1'}}],
}
],
}
},
}
result_status = {'status': 'failed'}
when(IQMClient).get_quantum_architecture().thenReturn(adonis_architecture)
when(IQMClient).submit_circuits(...).thenReturn(uuid.uuid4())
when(IQMClient).get_run(ANY(uuid.UUID)).thenReturn(RunResult.from_dict(result))
when(IQMClient).get_run_status(ANY(uuid.UUID)).thenReturn(RunStatus.from_dict(result_status))
provider = IQMProvider(url)
backend = provider.get_backend('facade_adonis')
with pytest.raises(RuntimeError, match='Remote execution did not succeed'):
backend.run(circuit_2)
|
https://github.com/biswaroopmukherjee/Quantum-Waddle
|
biswaroopmukherjee
|
import numpy as np
import time
import networkx as nx
import matplotlib.pyplot as plt
import random
from qiskit import (QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer)
%matplotlib inline
from qiskit import IBMQ
from qiskit.tools.monitor import job_monitor
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider(group='open')
def counts_to_prob_1d(counts):
# Convert histogram counts to probability vector of size 1 x 2^n
states = list(counts.keys())
state_counts = list(counts.values())
nshots = sum(state_counts)
# Convert binary to integer index, reversing order as consistent w qiskit convention
states_x = [int(s[::-1],2) for s in states]
# Create array of probability values
probabilities = np.zeros(2**n)
probabilities[states_x] = state_counts
probabilities /= nshots
return probabilities
def increment_gate(circuit, qpos, qcoin):
n = len(qpos)
for i in range(n):
circuit.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
def decrement_gate(circuit, qpos, qcoin):
n = len(qpos)
circuit.x(qcoin[0])
for i in range(n):
if i+1 < n: circuit.x(qpos[i+1:])
circuit.mct([qcoin[0]]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: circuit.x(qpos[i+1:])
def step(circuit, qpos, qcoin,cpos,simulatorType):
circuit.h(qcoin)
circuit.barrier()
increment_gate(circuit, qpos, qcoin)
circuit.barrier()
decrement_gate(circuit, qpos, qcoin)
circuit.barrier()
if simulatorType == 'classical':
circuit.measure(qpos,cpos)
def run(steps,simulatorType):
# steps = number of quantum walks steps
# simulatorType = 'sim', 'quantum' or 'classical'
if simulatorType == 'sim':
simulator = Aer.get_backend('qasm_simulator')
elif simulatorType == 'quantum':
simulator = provider.get_backend('ibmq_5_yorktown')
elif simulatorType == 'classical':
simulator = Aer.get_backend('qasm_simulator')
else:
simulator = Aer.get_backend('qasm_simulator')
qpos = QuantumRegister(n,'qc')
qcoin = QuantumRegister(1,'qanc')
cpos = ClassicalRegister(n,'cr')
circuit = QuantumCircuit(qpos, qcoin, cpos)
for i in range(steps):
step(circuit, qpos, qcoin,cpos, simulatorType)
# # Map the quantum measurement to the classical bits
circuit.measure(qpos,cpos)
# # Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# # monitor job
job_monitor(job)
# # Grab results from the job
result = job.result()
# # Returns counts
counts = result.get_counts(circuit)
return counts
seed = 12
random.seed(seed)
np.random.seed(seed)
def plotCircleGraph(names,propabilities,color=[0,0,1]):
G = nx.Graph()
colorarray = []
# generate array of colors
numProp = len(propabilities)
for idx in range(numProp):
colorarray.append(color+[0.5*propabilities[idx]])
# generate graph
for idx in range(numProp-1):
G.add_edge(idx, idx+1)
# add last edge
G.add_edge(0,numProp-1)
# label nodes
labels = {}
for idx in range(numProp):
labels[idx] = names[idx]
nx.draw(G,
pos=nx.circular_layout(G),
node_color=colorarray,
cmap=plt.cm.Blues,
node_size=3000,
edge_color='k',
)
pos=nx.circular_layout(G)
labels = nx.draw_networkx_labels(G,pos,labels,font_size=16,
bbox=dict(facecolor='w', alpha=1, edgecolor='w')
)
# run and plot 1D walk
steps = 3
n=2
for i in range(steps+1):
#run classical random walk
countsClassical = run(i,'classical')
propClassical = counts_to_prob_1d(countsClassical)
#run quantum simulation
countsSim = run(i,'sim')
propSim = counts_to_prob_1d(countsSim)
#run the real thing
countsQuantum = run(i,'quantum')
propQuantum = counts_to_prob_1d(countsQuantum)
names = []
formatLabel = '{0:0'+str(n)+'b}'
for idx in range(2**n):
names.append('|' + formatLabel.format(idx) +'>')
#plotting
f, axs = plt.subplots(2,3,figsize=(13,8))
margin=0.4
f.subplots_adjust(margin, margin, 1.-margin, 1.-margin)
axs[0,0].set_title('classical random walk', fontsize=14)
plt.sca(axs[0,0])
plotCircleGraph(names,propClassical,color=[1,0,0])
plt.sca(axs[1,0])
plt.bar(names,propClassical,edgecolor='black', color=[1,0,0,.4], lw=2)
plt.ylim(0,1)
plt.xticks(rotation=45)
axs[0,1].set_title('simulated quantum walk', fontsize=14)
plt.sca(axs[0,1])
plotCircleGraph(names,propSim,color=[0.3,1,0])
plt.sca(axs[1,1])
plt.bar(names,propSim,edgecolor='black', color=[0.3,1,0,.4], lw=2)
plt.ylim(0,1)
plt.xticks(rotation=45)
axs[0,2].set_title('IBM quantum walk', fontsize=14)
plt.sca(axs[0,2])
plotCircleGraph(names,propQuantum,color=[0.1,0.3,1])
plt.sca(axs[1,2])
plt.bar(names,propQuantum,edgecolor='black', color=[0.1,0.3,1,.4], lw=2)
plt.ylim(0,1)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
|
https://github.com/theRealNoah/qiskit-grovers-3by3
|
theRealNoah
|
# Quantum Computing and Communications Term Project
# Spring 2021 by Noah Hamilton
# Inspired by https://qiskit.org/textbook/ch-algorithms/grover.html#sudoku
# This is the code for the implementation of the Grover's Algorithm solving a
# 3x3 Binary Sudoku.
# Problem Environment + Rules
# Each Column must contain exactly one 1.
# Each Row must contain exactly one 1.
# ----------------
# | v0 | v1 | v2 |
# ----------------
# | v3 | v4 | v5 |
# ----------------
# | v6 | v7 | v8 |
# ----------------
# For this simulation, we will use the Qiskit library and the IBMQ Simulator.
import qiskit as q
import matplotlib.pyplot as plt
from qiskit import IBMQ
import numpy as np
from qiskit.quantum_info.operators import Operator
plt.close()
IBMQ.save_account(
'ab770cdeb560aa1f1dfff99b0076fa95172a84dfaabe83d593e234549f5601d05f921e4c76a38cb4e02951c0a7b137aa30730e739c527cdffbf32495adb77896', overwrite=True)
# After defining the problem, the first step is to create an oracle.
# Need to create a classical function that checks whether the state of our
# variables is a valid solution.
# To do this we first need to define the conditions to check:
# for each row/column the solutions can boil down to
# ((NOT A) AND (B XOR C) OR ((NOT C) AND (A XOR B ))
# So, check each row and column for this condition.
# List of all rows and Columns
# 1st Row - [v0, v1, v2]
# 2nd Row - [v3, v4, v5]
# 3rd Row - [v6, v7, v8]
# 1st Col - [v0, v3, v6]
# 2nd Col - [v1, v4, v7]
# 3rd Col - [v2, v5, v8]
# To make things simpler, I'm creating a compiled list of clauses
clause_list = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8]]
# Assigning the value of each variable to a bit in our circuit.
# We need to define a function that will check if exactly one of these is true.
# The final output should be the Quantum Equivalent of Classical:
# ((NOT A) AND (B XOR C) OR ((NOT C) AND (A XOR B ))
# The NOT Gate in classical can be represented by an X Gate (NOT)
# The XOR Gate can be represented by the combination of 2 CX (CNOT)
# The AND Gate can be implemented using a Toffoli Gate ccx (CCNOT)
# No current quantum gates are explicit creations of an OR Gate because all
# operations must be reversible.
# To create the OR Logic, we need to use a unitary matrix using the Operator
# class and use an Ancilla Bit (extra bit)
# Ancilla Bit - https://en.wikipedia.org/wiki/Ancilla_bit
# Credit: https://quantumcomputing.stackexchange.com/a/5834
OR_Unitary_Matrix = [[0, 1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1]
]
OR_Operator = Operator(OR_Unitary_Matrix)
print('The OR Operator Created is a Unitary operator:', OR_Operator.is_unitary())
# Parameters:
# qc: Quantum Circuit Element
# a: First bit
# b: Second bit
# c: Third bit
# ancilla_1 - ancilla_3 --- extra qubits needed for processing.
# out_qubit: Output
# def OnlyOneTrue(qc, a, b, c, ancilla_1, ancilla_2, ancilla_3, out_qubit):
# # NOT A
# qc.x(a)
# # B XOR C
# # ancilla_1 will be flipped only if b and c are different.
# qc.cx(b, ancilla_1)
# qc.cx(c, ancilla_1)
# # NOT A AND (B XOR C) - stored in ancilla_2
# qc.ccx(a, ancilla_1, ancilla_2)
# # RESET ancilla_1 will be flipped back only if b and c are different.
# qc.cx(b, ancilla_1)
# qc.cx(c, ancilla_1)
# # Need to undo NOT A for second half.
# qc.x(a)
# # NOT C
# qc.x(c)
# # A XOR B
# # ancilla_1 will be flipped only if b and a are different.
# qc.cx(a, ancilla_1)
# qc.cx(b, ancilla_1)
# # NOT C AND (B XOR A) - stored in ancilla_3
# qc.ccx(c, ancilla_1, ancilla_3)
# # RESET ancilla_1 will be flipped only if b and a are different.
# qc.cx(a, ancilla_1)
# qc.cx(b, ancilla_1)
# # OR Operation
# qc.append(OR_Operator, [ancilla_2, ancilla_3, out_qubit])
# qc.x(c) # Reset Value of C
def OnlyOneTrue(qc, a, b, c, ancilla_2, ancilla_3, out_qubit):
# NOT A
qc.x(a)
# B XOR C
# ancilla_1 will be flipped only if b and c are different.
qc.cx(b, out_qubit)
qc.cx(c, out_qubit)
# NOT A AND (B XOR C) - stored in ancilla_2
qc.ccx(a, out_qubit, ancilla_2)
# RESET ancilla_1 will be flipped back only if b and c are different.
qc.cx(b, out_qubit)
qc.cx(c, out_qubit)
# Need to undo NOT A for second half.
qc.x(a)
# NOT C
qc.x(c)
# A XOR B
# ancilla_1 will be flipped only if b and a are different.
qc.cx(a, out_qubit)
qc.cx(b, out_qubit)
# NOT C AND (B XOR A) - stored in ancilla_3
qc.ccx(c, out_qubit, ancilla_3)
# RESET ancilla_1 will be flipped only if b and a are different.
qc.cx(a, out_qubit)
qc.cx(b, out_qubit)
# OR Operation
qc.append(OR_Operator, [ancilla_2, ancilla_3, out_qubit])
qc.x(c) # Reset Value of C
# Define a Diffuser to be used with N Qubits
def diffuser(nqubits):
qc = q.QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "U$_s$"
return U_s
# # Testing that the OnlyOneTrue function works
# # Displays Quantum Equivalent Circuit
# in_qubits = q.QuantumRegister(3, name='input')
# ancilla_qubits = q.QuantumRegister(4, name='ancilla')
# out_qubit = q.QuantumRegister(1, name='output')
# qc = q.QuantumCircuit(in_qubits, ancilla_qubits, out_qubit)
# OnlyOneTrue(qc, in_qubits[0], in_qubits[1], in_qubits[2], ancilla_qubits[0],
# ancilla_qubits[1], ancilla_qubits[2], ancilla_qubits[3], out_qubit)
# qc.draw(output='mpl')
# plt.title(
# 'Quantum Equivalent of Classical: ((NOT A) AND (B XOR C) OR ((NOT C) AND (A XOR B ))')
# Create separate registers to name bits
var_qubits = q.QuantumRegister(9, name='v')
ancilla_qubits = q.QuantumRegister(12, name='ancilla')
clause_qubits = q.QuantumRegister(6, name='c')
output_qubit = q.QuantumRegister(1, name='out')
cbits = q.ClassicalRegister(9, name='cbits')
# Create Quantum Circuit
qc = q.QuantumCircuit(var_qubits, ancilla_qubits,
clause_qubits, output_qubit, cbits)
# Initialize 'out0' in state |->
qc.initialize([1, -1]/np.sqrt(2), output_qubit)
# Initialize qubits in state |s>
qc.h(var_qubits)
qc.barrier() # For Visual Separation (may remove later)
# Next, create a checking circuit using the Oracle using phase kickback
def sudoku_oracle(qc, clause_list, clause_qubits):
# Use OnlyOneTrue gate to check each clause
i = 0
for clause in clause_list:
OnlyOneTrue(qc, clause[0], clause[1], clause[2], ancilla_qubits[2*i],
ancilla_qubits[2*i + 1],
clause_qubits[i])
i += 1
# Flip 'output' bit if all classes are satisfied
qc.mct(clause_qubits, output_qubit)
# Uncompute clauses to reset clause-checking bits to 0
i = 0
for clause in clause_list:
OnlyOneTrue(qc, clause[0], clause[1], clause[2], ancilla_qubits[2*i],
ancilla_qubits[2*i + 1],
clause_qubits[i])
i += 1
# First Iteration
# Apply our oracle
sudoku_oracle(qc, clause_list, clause_qubits)
qc.barrier() # For Visual Separation (may remove later)
# Apply our diffuser
qc.append(diffuser(9), [0, 1, 2, 3, 4, 5, 6, 7, 8])
# Second Iteration
sudoku_oracle(qc, clause_list, clause_qubits)
qc.barrier() # for visual separation
# Apply our diffuser
qc.append(diffuser(9), [0, 1, 2, 3, 4, 5, 6, 7, 8])
# Measure the variable qubits
qc.measure(var_qubits, cbits)
# qc.draw(output='mpl', fold=-1)
############################################################
# # Select the AerSimulator from the Aer provider
# backend = q.Aer.get_backend('statevector_simulator')
# backend.MAX_QUBIT_MEMORY = 32
# shots = 1024
# job = q.execute(qc, backend)
# # try:
# # job_status = job.status() # Query the backend server for job status.
# # if job_status is q.JobStatus.RUNNING:
# # print("The job is still running")
# # except IBMQJobApiError as ex:
# # print("Something wrong happened!: {}".format(ex))
# result = job.result()
# q.visualization.plot_histogram(result.get_counts())
# # Run and get counts, using the matrix_product_state method
##############################################################
#tcirc = q.transpile(qc, simulator)
# result = simulator.run(qc).result()
# Simulate and Plot Results
# The QASM_Simulator only supports up to 32 qubits. I currently use 34.
qasm_simulator = q.Aer.get_backend('qasm_simulator')
transpiled_qc = q.transpile(qc, qasm_simulator)
qobj = q.assemble(transpiled_qc)
result = qasm_simulator.run(qobj).result()
# Simulate the Circuit using the open-source QASM Simulator provided by IBM Q.
# simulator = q.Aer.get_backend('qasm_simulator')
# results = q.execute(circuit, backend=simulator).result()
# q.visualization.plot_histogram(results.get_counts(circuit))
# Used for showing Circuits and Histograms.
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.qasm3
program = """
OPENQASM 3.0;
include "stdgates.inc";
input float[64] a;
qubit[3] q;
bit[2] mid;
bit[3] out;
let aliased = q[0:1];
gate my_gate(a) c, t {
gphase(a / 2);
ry(a) c;
cx c, t;
}
gate my_phase(a) c {
ctrl @ inv @ gphase(a) c;
}
my_gate(a * 2) aliased[0], q[{1, 2}][0];
measure q[0] -> mid[0];
measure q[1] -> mid[1];
while (mid == "00") {
reset q[0];
reset q[1];
my_gate(a) q[0], q[1];
my_phase(a - pi/2) q[1];
mid[0] = measure q[0];
mid[1] = measure q[1];
}
if (mid[0]) {
let inner_alias = q[{0, 1}];
reset inner_alias;
}
out = measure q;
"""
circuit = qiskit.qasm3.loads(program)
circuit.draw("mpl")
|
https://github.com/SultanMS/Quantum-Neural-Network
|
SultanMS
|
# Quantum NNN: Ver 0.1, By Sultan Almuhammadi and Sarah Alghamdi
# Date: Dec 1, 2021
from sklearn import model_selection, datasets, svm
from qiskit import QuantumCircuit, Aer, IBMQ, QuantumRegister, ClassicalRegister
import qiskit
import numpy as np
import copy
import matplotlib.pyplot as plt1
import matplotlib.pyplot as plt2
iris = datasets.load_iris()
X = iris.data[0:100] # We only take the first two features.
Y = iris.target[0:100]
X_train, X_test, Y_train, Y_test, = model_selection.train_test_split(X, Y, test_size=0.33, random_state=42)
print(Y_train)
print(X_train[0])
print (len(Y_train), len(X_train), len(X_test), len(Y_test))
print (X_test)
N = 4
myX_train = [[0 for i in range(N)] for j in range(len(X_train))]
myX_test = [[0 for i in range(N)] for j in range(len(X_test))]
# Correct the size of the features basaed on N
for i in range(len(X_train)):
for j in range(N):
if (j<len(X_train[i])):
myX_train[i][j]=X_train[i][j]
else:
myX_train[i][j] = 1.0
for i in range(len(X_test)):
for j in range(N):
if (j<len(X_test[i])):
myX_test[i][j]=X_test[i][j]
else:
myX_test[i][j] = 1.0
print(myX_test)
def feature_map(X):
q = QuantumRegister(N)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
for i, x in enumerate(X):
qc.rx(x, i)
return qc, c
def variational_circuit(qc, theta):
for i in range(N-1):
qc.cnot(i, i+1)
qc.cnot(N-1, 0)
for i in range(N):
qc.ry(theta[i], i)
return qc
# SSultan Test
X = [5.2, 3.4, 1.4,0.2]
theta = [0.785]*N
myqc, myc = feature_map(X)
myqc = variational_circuit(myqc, theta)
myqc.measure(0, myc)
myqc.draw()
def quantum_nn(X, theta, simulator=True):
qc, c = feature_map(X)
qc = variational_circuit(qc, theta)
qc.measure(0, c)
shots= 10000
backend = Aer.get_backend('qasm_simulator')
if simulator == False:
shots = 1000
provider= IBMQ.load_account()
backend= provider.get_backend('ibmq_bogota')
job = qiskit.execute(qc, backend, shots=shots)
result = job.result()
counts = result.get_counts(qc)
return counts['1']/shots
def loss(prediction, target):
return (prediction - target)**2
def gradient (X,Y,theta):
delta = 0.01
grad = []
for i in range(len(theta)):
dtheta = copy.copy(theta)
dtheta[i] += delta
pred1 =quantum_nn(X,dtheta)
pred2 =quantum_nn(X,theta)
grad.append((loss(pred1, Y) - loss(pred2, Y)) / delta)
return np.array(grad)
def accuracy(X, Y, theta):
counter = 0
for i in range(len(X)):
X_i = X[i]
Y_i = Y[i]
prediction = quantum_nn(X_i, theta)
#pint(X_i, Y_i, prediction)
if prediction < 0.5 and Y_i == 0:
counter +=1
elif prediction >= 0.5 and Y_i == 1 :
counter +=1
return 100.0*counter/len(Y)
# main program
eta = 0.05
loss_list = []
acc_list = []
theta = np.ones(N)
print(' Epoch\t Loss\t Accuracy')
for k in range(10):
loss_tmp = []
for i in range(len(myX_train)):
X_i = myX_train[i]
Y_i = Y_train[i]
prediction = quantum_nn(X_i, theta)
loss_tmp.append(loss(prediction,Y_i))
theta =theta - eta * gradient(X_i, Y_i, theta)
loss_list.append(np.mean(loss_tmp))
acc = accuracy(myX_train, Y_train, theta)
acc_list.append(acc)
print(f'\t{k}\t {loss_list[-1]:.3f}\t {acc:.1f}')
plt1.plot(loss_list)
plt1.xlabel('Epoch')
plt1.ylabel('Loss')
plt1.show()
plt2.plot(acc_list)
plt2.xlabel('Epoch')
plt2.ylabel('Accuracy (%)')
plt2.show()
accuracy(myX_test, Y_test, theta)
X_sample = myX_test[6]
print('The predection of the test sample on a simulator:')
quantum_nn(X_sample, theta)
print('The predection of the test sample (for N = 4) on IBM-Q quantum computer (ibm_bogota):')
quantum_nn(X_sample, theta, simulator = False)
|
https://github.com/Rodri-rf/playing_with_quantum_computing
|
Rodri-rf
|
"""Example usage of the Quantum Inspire backend with the Qiskit SDK.
A simple example that demonstrates how to use the SDK to create
a circuit to demonstrate conditional gate execution.
For documentation on how to use Qiskit we refer to
[https://qiskit.org/](https://qiskit.org/).
Specific to Quantum Inspire is the creation of the QI instance, which is used to set the authentication
of the user and provides a Quantum Inspire backend that is used to execute the circuit.
Copyright 2018-19 QuTech Delft. Licensed under the Apache License, Version 2.0.
"""
import os
from qiskit import BasicAer, execute
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from quantuminspire.credentials import get_authentication
from quantuminspire.qiskit import QI
QI_URL = os.getenv('API_URL', 'https://api.quantum-inspire.com/')
authentication = get_authentication()
QI.set_authentication(authentication, QI_URL)
qi_backend = QI.get_backend('QX single-node simulator')
q = QuantumRegister(2, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(3, name="conditional")
qc.h([0, 2])
qc.cnot(q[0], q[1])
qc.measure_all()
qi_job = execute(qc, backend=qi_backend, shots=1024)
qi_result = qi_job.result()
histogram = qi_result.get_counts(qc)
print("\nResult from the remote Quantum Inspire backend:\n")
print('State\tCounts')
[print('{0}\t{1}'.format(state, counts)) for state, counts in histogram.items()]
print("\nResult from the local Qiskit simulator backend:\n")
backend = BasicAer.get_backend("qasm_simulator")
job = execute(qc, backend=backend, shots=1024)
result = job.result()
print(result.get_counts(qc))
qc.draw(output="latex")
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Evaluator of auxiliary operators for algorithms."""
from __future__ import annotations
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import (
CircuitSampler,
ListOp,
StateFn,
OperatorBase,
ExpectationBase,
)
from qiskit.providers import Backend
from qiskit.quantum_info import Statevector
from qiskit.utils import QuantumInstance
from qiskit.utils.deprecation import deprecate_func
from .list_or_dict import ListOrDict
@deprecate_func(
additional_msg=(
"Instead, use the function "
"``qiskit_algorithms.observables_evaluator.estimate_observables``. See "
"https://qisk.it/algo_migration for a migration guide."
),
since="0.24.0",
)
def eval_observables(
quantum_instance: QuantumInstance | Backend,
quantum_state: Statevector | QuantumCircuit | OperatorBase,
observables: ListOrDict[OperatorBase],
expectation: ExpectationBase,
threshold: float = 1e-12,
) -> ListOrDict[tuple[complex, complex]]:
"""
Deprecated: Accepts a list or a dictionary of operators and calculates
their expectation values - means
and standard deviations. They are calculated with respect to a quantum state provided. A user
can optionally provide a threshold value which filters mean values falling below the threshold.
This function has been superseded by the
:func:`qiskit_algorithms.observables_evaluator.eval_observables` function.
It will be deprecated in a future release and subsequently
removed after that.
Args:
quantum_instance: A quantum instance used for calculations.
quantum_state: An unparametrized quantum circuit representing a quantum state that
expectation values are computed against.
observables: A list or a dictionary of operators whose expectation values are to be
calculated.
expectation: An instance of ExpectationBase which defines a method for calculating
expectation values.
threshold: A threshold value that defines which mean values should be neglected (helpful for
ignoring numerical instabilities close to 0).
Returns:
A list or a dictionary of tuples (mean, standard deviation).
Raises:
ValueError: If a ``quantum_state`` with free parameters is provided.
"""
if (
isinstance(
quantum_state, (QuantumCircuit, OperatorBase)
) # Statevector cannot be parametrized
and len(quantum_state.parameters) > 0
):
raise ValueError(
"A parametrized representation of a quantum_state was provided. It is not "
"allowed - it cannot have free parameters."
)
# Create new CircuitSampler to avoid breaking existing one's caches.
sampler = CircuitSampler(quantum_instance)
list_op = _prepare_list_op(quantum_state, observables)
observables_expect = expectation.convert(list_op)
observables_expect_sampled = sampler.convert(observables_expect)
# compute means
values = np.real(observables_expect_sampled.eval())
# compute standard deviations
# We use sampler.quantum_instance to take care of case in which quantum_instance is Backend
std_devs = _compute_std_devs(
observables_expect_sampled, observables, expectation, sampler.quantum_instance
)
# Discard values below threshold
observables_means = values * (np.abs(values) > threshold)
# zip means and standard deviations into tuples
observables_results = list(zip(observables_means, std_devs))
# Return None eigenvalues for None operators if observables is a list.
# None operators are already dropped in compute_minimum_eigenvalue if observables is a dict.
return _prepare_result(observables_results, observables)
def _prepare_list_op(
quantum_state: Statevector | QuantumCircuit | OperatorBase,
observables: ListOrDict[OperatorBase],
) -> ListOp:
"""
Accepts a list or a dictionary of operators and converts them to a ``ListOp``.
Args:
quantum_state: An unparametrized quantum circuit representing a quantum state that
expectation values are computed against.
observables: A list or a dictionary of operators.
Returns:
A ``ListOp`` that includes all provided observables.
"""
if isinstance(observables, dict):
observables = list(observables.values())
if not isinstance(quantum_state, StateFn):
quantum_state = StateFn(quantum_state)
return ListOp([StateFn(obs, is_measurement=True).compose(quantum_state) for obs in observables])
def _prepare_result(
observables_results: list[tuple[complex, complex]],
observables: ListOrDict[OperatorBase],
) -> ListOrDict[tuple[complex, complex]]:
"""
Prepares a list or a dictionary of eigenvalues from ``observables_results`` and
``observables``.
Args:
observables_results: A list of of tuples (mean, standard deviation).
observables: A list or a dictionary of operators whose expectation values are to be
calculated.
Returns:
A list or a dictionary of tuples (mean, standard deviation).
"""
if isinstance(observables, list):
observables_eigenvalues: ListOrDict[tuple[complex, complex]] = [None] * len(observables)
key_value_iterator = enumerate(observables_results)
else:
observables_eigenvalues = {}
key_value_iterator = zip(observables.keys(), observables_results)
for key, value in key_value_iterator:
if observables[key] is not None:
observables_eigenvalues[key] = value
return observables_eigenvalues
def _compute_std_devs(
observables_expect_sampled: OperatorBase,
observables: ListOrDict[OperatorBase],
expectation: ExpectationBase,
quantum_instance: QuantumInstance | Backend,
) -> list[complex]:
"""
Calculates a list of standard deviations from expectation values of observables provided.
Args:
observables_expect_sampled: Expected values of observables.
observables: A list or a dictionary of operators whose expectation values are to be
calculated.
expectation: An instance of ExpectationBase which defines a method for calculating
expectation values.
quantum_instance: A quantum instance used for calculations.
Returns:
A list of standard deviations.
"""
variances = np.real(expectation.compute_variance(observables_expect_sampled))
if not isinstance(variances, np.ndarray) and variances == 0.0:
# when `variances` is a single value equal to 0., our expectation value is exact and we
# manually ensure the variances to be a list of the correct length
variances = np.zeros(len(observables), dtype=float)
# TODO: this will crash if quantum_instance is a backend
std_devs = np.sqrt(variances / quantum_instance.run_config.shots)
return std_devs
|
https://github.com/ionq-samples/qiskit-getting-started
|
ionq-samples
|
# import Aer here, before calling qiskit_ionq_provider
from qiskit import Aer
from qiskit_ionq import IonQProvider
# Call provider and set token value
provider = IonQProvider(token='My token')
provider.backends()
from qiskit import QuantumCircuit
# Create a bell state circuit.
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
# Show the circuit:
qc.draw()
from qiskit.providers.jobstatus import JobStatus
# Get an IonQ simulator backend to run circuits on:
backend = provider.get_backend("ionq_simulator")
# Then run the circuit:
job = backend.run(qc, shots=1000)
# Save job_id
job_id_bell = job.job_id()
# Fetch the result:
result = job.result()
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts())
# Next get an IonQ hardware backend to run circuits on:
qpu_backend = provider.get_backend("ionq_qpu")
# Then run the circuit:
qpu_job_bell = qpu_backend.run(qc)
# Store job id
job_id_bell = qpu_job_bell.job_id()
# Check if job is done
if qpu_job_bell.status() is JobStatus.DONE:
print("Job status is DONE")
# Fetch the result:
qpu_result_bell = qpu_job_bell.result()
else:
print("Job status is ", qpu_job_bell.status() )
# If job is finished, plot and validate results:
plot_histogram(qpu_result_bell.get_counts())
# Retrieve a previously executed job:
old_job = backend.retrieve_job(job_id_bell)
# Then render the old job results:
old_result = old_job.result()
plot_histogram(old_result.get_counts())
n=4
qc_cat = QuantumCircuit(n, n)
qc_cat.h(0)
for i in range(1,n):
qc_cat.cx(0, i)
qc_cat.measure(range(n), range(n))
# Show the circuit:
qc_cat.draw()
# Run the circuit on the simulator and plot the results
job_cat = backend.run(qc_cat)
# Save job id
job_id_cat = job_cat.job_id()
# Fetch the result:
result_cat = job_cat.result()
plot_histogram(result_cat.get_counts())
# Then run the circuit on the hardware:
qpu_job_cat = qpu_backend.run(qc_cat)
# Save job id
qpu_job_id_cat = qpu_job_cat.job_id()
# Check if job is done
if qpu_job_cat.status() is JobStatus.DONE:
print("Job status is DONE")
# Fetch the result:
qpu_result_cat = qpu_job_cat.result()
else:
print("Job status is ", qpu_job_cat.status() )
# If job is finished, plot and validate results:
plot_histogram(qpu_result_cat.get_counts())
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# useful math functions
from math import pi, cos, acos, sqrt
import sys
# importing the QISKit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import available_backends, execute, register, get_backend
# importing API token to access remote backends
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
except:
qx_config = {
"APItoken":"YOUR_TOKEN_HERE",
"url":"https://quantumexperience.ng.bluemix.net/api"}
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def ch(qProg, a, b):
""" Controlled-Hadamard gate """
qProg.h(b)
qProg.sdg(b)
qProg.cx(a, b)
qProg.h(b)
qProg.t(b)
qProg.cx(a, b)
qProg.t(b)
qProg.h(b)
qProg.s(b)
qProg.x(b)
qProg.s(a)
return qProg
def cu3(qProg, theta, phi, lambd, c, t):
""" Controlled-u3 gate """
qProg.u1((lambd-phi)/2, t)
qProg.cx(c, t)
qProg.u3(-theta/2, 0, -(phi+lambd)/2, t)
qProg.cx(c, t)
qProg.u3(theta/2, phi, 0, t)
return qProg
#CHANGE THIS 7BIT 0-1 STRING TO PERFORM EXPERIMENT ON ENCODING 0000000, ..., 1111111
x1234567 = "0101010"
if len(x1234567) != 7 or not("1" in x1234567 or "0" in x1234567):
raise Exception("x1234567 is a 7-bit 0-1 pattern. Please set it to the correct pattern")
#compute the value of rotation angle theta of (3,1)-QRAC
theta = acos(sqrt(0.5 + sqrt(3.0)/6.0))
#to record the u3 parameters for encoding 000, 010, 100, 110, 001, 011, 101, 111
rotationParams = {"000":(2*theta, pi/4, -pi/4), "010":(2*theta, 3*pi/4, -3*pi/4),
"100":(pi-2*theta, pi/4, -pi/4), "110":(pi-2*theta, 3*pi/4, -3*pi/4),
"001":(2*theta, -pi/4, pi/4), "011":(2*theta, -3*pi/4, 3*pi/4),
"101":(pi-2*theta, -pi/4, pi/4), "111":(pi-2*theta, -3*pi/4, 3*pi/4)}
# Creating registers
# qubits for encoding 7 bits of information with qr[0] kept by the sender
qr = QuantumRegister(3)
# bits for recording the measurement of the qubits qr[1] and qr[2]
cr = ClassicalRegister(2)
encodingName = "Encode"+x1234567
encodingCircuit = QuantumCircuit(qr, cr, name=encodingName)
#Prepare superposition of mixing QRACs of x1...x6 and x7
encodingCircuit.u3(1.187, 0, 0, qr[0])
#Encoding the seventh bit
seventhBit = x1234567[6]
if seventhBit == "1": #copy qr[0] into qr[1] and qr[2]
encodingCircuit.cx(qr[0], qr[1])
encodingCircuit.cx(qr[0], qr[2])
#perform controlled-Hadamard qr[0], qr[1], and toffoli qr[0], qr[1] , qr[2]
encodingCircuit = ch(encodingCircuit, qr[0], qr[1])
encodingCircuit.ccx(qr[0], qr[1], qr[2])
#End of encoding the seventh bit
#encode x1...x6 with two (3,1)-QRACS. To do that, we must flip q[0] so that the controlled encoding is executed
encodingCircuit.x(qr[0])
#Encoding the first 3 bits 000, ..., 111 into the second qubit, i.e., (3,1)-QRAC on the second qubit
firstThreeBits = x1234567[0:3]
#encodingCircuit.cu3(*rotationParams[firstThreeBits], qr[0], qr[1])
encodingCircuit = cu3(encodingCircuit, *rotationParams[firstThreeBits], qr[0], qr[1])
#Encoding the second 3 bits 000, ..., 111 into the third qubit, i.e., (3,1)-QRAC on the third qubit
secondThreeBits = x1234567[3:6]
#encodingCircuit.cu3(*rotationParams[secondTreeBits], qr[0], qr[2])
encodingCircuit = cu3(encodingCircuit, *rotationParams[secondThreeBits], qr[0], qr[2])
#end of encoding
encodingCircuit.barrier()
# dictionary for decoding circuits
decodingCircuits = {}
# Quantum circuits for decoding the 1st to 6th bits
for i, pos in enumerate(["First", "Second", "Third", "Fourth", "Fifth", "Sixth"]):
circuitName = "Decode"+pos
decodingCircuits[circuitName] = QuantumCircuit(qr, cr, name=circuitName)
if i < 3: #measure 1st, 2nd, 3rd bit
if pos == "Second": #if pos == "First" we can directly measure
decodingCircuits[circuitName].h(qr[1])
elif pos == "Third":
decodingCircuits[circuitName].u3(pi/2, -pi/2, pi/2, qr[1])
decodingCircuits[circuitName].measure(qr[1], cr[1])
else: #measure 4th, 5th, 6th bit
if pos == "Fifth": #if pos == "Fourth" we can directly measure
decodingCircuits[circuitName].h(qr[2])
elif pos == "Sixth":
decodingCircuits[circuitName].u3(pi/2, -pi/2, pi/2, qr[2])
decodingCircuits[circuitName].measure(qr[2], cr[1])
#Quantum circuits for decoding the 7th bit
decodingCircuits["DecodeSeventh"] = QuantumCircuit(qr, cr, name="DecodeSeventh")
decodingCircuits["DecodeSeventh"].measure(qr[1], cr[0])
decodingCircuits["DecodeSeventh"].measure(qr[2], cr[1])
#combine encoding and decoding of (7,2)-QRACs to get a list of complete circuits
circuitNames = []
circuits = []
k1 = encodingName
for k2 in decodingCircuits.keys():
circuitNames.append(k1+k2)
circuits.append(encodingCircuit+decodingCircuits[k2])
print("List of circuit names:", circuitNames) #list of circuit names
#Q_program.get_qasms(circuitNames) #list qasms codes
backend = "local_qasm_simulator"
#backend = "ibmqx2"
shots = 1000
job = execute(circuits, backend=backend, shots=shots)
results = job.result()
for k in ["DecodeFirst", "DecodeSecond", "DecodeThird", "DecodeFourth", "DecodeFifth", "DecodeSixth"]:
print("Experimental Result of ", encodingName+k)
plot_histogram(results.get_counts(circuits[circuitNames.index(encodingName+k)]))
print("Experimental result of ", encodingName+"DecodeSeventh")
plot_histogram(results.get_counts(circuits[circuitNames.index(encodingName+"DecodeSeventh")]))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
|
https://github.com/qiskit-community/qiskit-jku-provider
|
qiskit-community
|
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=missing-docstring,redefined-builtin
import unittest
import os
from qiskit import QuantumCircuit
from .common import QiskitTestCase
from qiskit_jku_provider import QasmSimulator
from qiskit import execute
class TestQasmSimulatorJKUBasic(QiskitTestCase):
"""Runs the Basic qasm_simulator tests from Terra on JKU."""
def setUp(self):
self.seed = 88
self.backend = QasmSimulator(silent=True)
qasm_filename = os.path.join(os.path.dirname(__file__), 'qasms', 'example.qasm')
compiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename)
compiled_circuit.name = 'test'
self.circuit = compiled_circuit
def test_qasm_simulator_single_shot(self):
"""Test single shot run."""
result = execute(self.circuit, self.backend, seed_transpiler=34342, shots=1).result()
self.assertEqual(result.success, True)
def test_qasm_simulator(self):
"""Test data counts output for single circuit run against reference."""
shots = 1024
result = execute(self.circuit, self.backend, seed_transpiler=34342, shots=shots).result()
threshold = 0.04 * shots
counts = result.get_counts('test')
target = {'100 100': shots / 8, '011 011': shots / 8,
'101 101': shots / 8, '111 111': shots / 8,
'000 000': shots / 8, '010 010': shots / 8,
'110 110': shots / 8, '001 001': shots / 8}
self.assertDictAlmostEqual(counts, target, threshold)
if __name__ == '__main__':
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can choose different colors for the real and imaginary parts of the density matrix.
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)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
print(problem)
hamiltonian = problem.hamiltonian
coefficients = hamiltonian.electronic_integrals
print(coefficients.alpha)
second_q_op = hamiltonian.second_q_op()
print(second_q_op)
hamiltonian.nuclear_repulsion_energy # NOT included in the second_q_op above
problem.molecule
problem.reference_energy
problem.num_particles
problem.num_spatial_orbitals
problem.basis
problem.properties
problem.properties.particle_number
problem.properties.angular_momentum
problem.properties.magnetization
problem.properties.electronic_dipole_moment
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import JordanWignerMapper
solver = GroundStateEigensolver(
JordanWignerMapper(),
NumPyMinimumEigensolver(),
)
result = solver.solve(problem)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 42
from qiskit.circuit import Parameter
from qiskit import QuantumCircuit
params1 = [Parameter("input1"), Parameter("weight1")]
qc1 = QuantumCircuit(1)
qc1.h(0)
qc1.ry(params1[0], 0)
qc1.rx(params1[1], 0)
qc1.draw("mpl")
from qiskit.quantum_info import SparsePauliOp
observable1 = SparsePauliOp.from_list([("Y" * qc1.num_qubits, 1)])
from qiskit_machine_learning.neural_networks import EstimatorQNN
estimator_qnn = EstimatorQNN(
circuit=qc1, observables=observable1, input_params=[params1[0]], weight_params=[params1[1]]
)
estimator_qnn
from qiskit.circuit import ParameterVector
inputs2 = ParameterVector("input", 2)
weights2 = ParameterVector("weight", 4)
print(f"input parameters: {[str(item) for item in inputs2.params]}")
print(f"weight parameters: {[str(item) for item in weights2.params]}")
qc2 = QuantumCircuit(2)
qc2.ry(inputs2[0], 0)
qc2.ry(inputs2[1], 1)
qc2.cx(0, 1)
qc2.ry(weights2[0], 0)
qc2.ry(weights2[1], 1)
qc2.cx(0, 1)
qc2.ry(weights2[2], 0)
qc2.ry(weights2[3], 1)
qc2.draw(output="mpl")
from qiskit_machine_learning.neural_networks import SamplerQNN
sampler_qnn = SamplerQNN(circuit=qc2, input_params=inputs2, weight_params=weights2)
sampler_qnn
estimator_qnn_input = algorithm_globals.random.random(estimator_qnn.num_inputs)
estimator_qnn_weights = algorithm_globals.random.random(estimator_qnn.num_weights)
print(
f"Number of input features for EstimatorQNN: {estimator_qnn.num_inputs} \nInput: {estimator_qnn_input}"
)
print(
f"Number of trainable weights for EstimatorQNN: {estimator_qnn.num_weights} \nWeights: {estimator_qnn_weights}"
)
sampler_qnn_input = algorithm_globals.random.random(sampler_qnn.num_inputs)
sampler_qnn_weights = algorithm_globals.random.random(sampler_qnn.num_weights)
print(
f"Number of input features for SamplerQNN: {sampler_qnn.num_inputs} \nInput: {sampler_qnn_input}"
)
print(
f"Number of trainable weights for SamplerQNN: {sampler_qnn.num_weights} \nWeights: {sampler_qnn_weights}"
)
estimator_qnn_forward = estimator_qnn.forward(estimator_qnn_input, estimator_qnn_weights)
print(
f"Forward pass result for EstimatorQNN: {estimator_qnn_forward}. \nShape: {estimator_qnn_forward.shape}"
)
sampler_qnn_forward = sampler_qnn.forward(sampler_qnn_input, sampler_qnn_weights)
print(
f"Forward pass result for SamplerQNN: {sampler_qnn_forward}. \nShape: {sampler_qnn_forward.shape}"
)
estimator_qnn_forward_batched = estimator_qnn.forward(
[estimator_qnn_input, estimator_qnn_input], estimator_qnn_weights
)
print(
f"Forward pass result for EstimatorQNN: {estimator_qnn_forward_batched}. \nShape: {estimator_qnn_forward_batched.shape}"
)
sampler_qnn_forward_batched = sampler_qnn.forward(
[sampler_qnn_input, sampler_qnn_input], sampler_qnn_weights
)
print(
f"Forward pass result for SamplerQNN: {sampler_qnn_forward_batched}. \nShape: {sampler_qnn_forward_batched.shape}"
)
estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward(
estimator_qnn_input, estimator_qnn_weights
)
print(
f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad}"
)
print(
f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}"
)
sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward(
sampler_qnn_input, sampler_qnn_weights
)
print(
f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad}"
)
print(
f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}"
)
estimator_qnn.input_gradients = True
sampler_qnn.input_gradients = True
estimator_qnn_input_grad, estimator_qnn_weight_grad = estimator_qnn.backward(
estimator_qnn_input, estimator_qnn_weights
)
print(
f"Input gradients for EstimatorQNN: {estimator_qnn_input_grad}. \nShape: {estimator_qnn_input_grad.shape}"
)
print(
f"Weight gradients for EstimatorQNN: {estimator_qnn_weight_grad}. \nShape: {estimator_qnn_weight_grad.shape}"
)
sampler_qnn_input_grad, sampler_qnn_weight_grad = sampler_qnn.backward(
sampler_qnn_input, sampler_qnn_weights
)
print(
f"Input gradients for SamplerQNN: {sampler_qnn_input_grad}. \nShape: {sampler_qnn_input_grad.shape}"
)
print(
f"Weight gradients for SamplerQNN: {sampler_qnn_weight_grad}. \nShape: {sampler_qnn_weight_grad.shape}"
)
observable2 = SparsePauliOp.from_list([("Z" * qc1.num_qubits, 1)])
estimator_qnn2 = EstimatorQNN(
circuit=qc1,
observables=[observable1, observable2],
input_params=[params1[0]],
weight_params=[params1[1]],
)
estimator_qnn_forward2 = estimator_qnn2.forward(estimator_qnn_input, estimator_qnn_weights)
estimator_qnn_input_grad2, estimator_qnn_weight_grad2 = estimator_qnn2.backward(
estimator_qnn_input, estimator_qnn_weights
)
print(f"Forward output for EstimatorQNN1: {estimator_qnn_forward.shape}")
print(f"Forward output for EstimatorQNN2: {estimator_qnn_forward2.shape}")
print(f"Backward output for EstimatorQNN1: {estimator_qnn_weight_grad.shape}")
print(f"Backward output for EstimatorQNN2: {estimator_qnn_weight_grad2.shape}")
parity = lambda x: "{:b}".format(x).count("1") % 2
output_shape = 2 # parity = 0, 1
sampler_qnn2 = SamplerQNN(
circuit=qc2,
input_params=inputs2,
weight_params=weights2,
interpret=parity,
output_shape=output_shape,
)
sampler_qnn_forward2 = sampler_qnn2.forward(sampler_qnn_input, sampler_qnn_weights)
sampler_qnn_input_grad2, sampler_qnn_weight_grad2 = sampler_qnn2.backward(
sampler_qnn_input, sampler_qnn_weights
)
print(f"Forward output for SamplerQNN1: {sampler_qnn_forward.shape}")
print(f"Forward output for SamplerQNN2: {sampler_qnn_forward2.shape}")
print(f"Backward output for SamplerQNN1: {sampler_qnn_weight_grad.shape}")
print(f"Backward output for SamplerQNN2: {sampler_qnn_weight_grad2.shape}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A module for visualizing device coupling maps."""
import math
from typing import List
import numpy as np
from qiskit.exceptions import MissingOptionalLibraryError, QiskitError
from qiskit.providers.backend import BackendV2
from qiskit.tools.visualization import HAS_MATPLOTLIB, VisualizationError
from qiskit.visualization.utils import matplotlib_close_if_inline
def plot_gate_map(
backend,
figsize=None,
plot_directed=False,
label_qubits=True,
qubit_size=None,
line_width=4,
font_size=None,
qubit_color=None,
qubit_labels=None,
line_color=None,
font_color="w",
ax=None,
filename=None,
qubit_coordinates=None,
):
"""Plots the gate map of a device.
Args:
backend (BaseBackend): The backend instance that will be used to plot the device
gate map.
figsize (tuple): Output figure size (wxh) in inches.
plot_directed (bool): Plot directed coupling map.
label_qubits (bool): Label the qubits.
qubit_size (float): Size of qubit marker.
line_width (float): Width of lines.
font_size (int): Font size of qubit labels.
qubit_color (list): A list of colors for the qubits
qubit_labels (list): A list of qubit labels
line_color (list): A list of colors for each line from coupling_map.
font_color (str): The font color for the qubit labels.
ax (Axes): A Matplotlib axes instance.
filename (str): file path to save image to.
Returns:
Figure: A Matplotlib figure instance.
Raises:
QiskitError: if tried to pass a simulator, or if the backend is None,
but one of num_qubits, mpl_data, or cmap is None.
MissingOptionalLibraryError: if matplotlib not installed.
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.visualization import plot_gate_map
%matplotlib inline
provider = IBMQ.load_account()
accountProvider = IBMQ.get_provider(hub='ibm-q')
backend = accountProvider.get_backend('ibmq_vigo')
plot_gate_map(backend)
"""
if not HAS_MATPLOTLIB:
raise MissingOptionalLibraryError(
libname="Matplotlib",
name="plot_gate_map",
pip_install="pip install matplotlib",
)
if isinstance(backend, BackendV2):
pass
elif backend.configuration().simulator:
raise QiskitError("Requires a device backend, not simulator.")
qubit_coordinates_map = {}
qubit_coordinates_map[1] = [[0, 0]]
qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]
qubit_coordinates_map[7] = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 0], [2, 1], [2, 2]]
qubit_coordinates_map[20] = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[3, 0],
[3, 1],
[3, 2],
[3, 3],
[3, 4],
]
qubit_coordinates_map[15] = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 7],
[1, 6],
[1, 5],
[1, 4],
[1, 3],
[1, 2],
[1, 1],
[1, 0],
]
qubit_coordinates_map[16] = [
[1, 0],
[1, 1],
[2, 1],
[3, 1],
[1, 2],
[3, 2],
[0, 3],
[1, 3],
[3, 3],
[4, 3],
[1, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5],
[1, 6],
]
qubit_coordinates_map[27] = [
[1, 0],
[1, 1],
[2, 1],
[3, 1],
[1, 2],
[3, 2],
[0, 3],
[1, 3],
[3, 3],
[4, 3],
[1, 4],
[3, 4],
[1, 5],
[2, 5],
[3, 5],
[1, 6],
[3, 6],
[0, 7],
[1, 7],
[3, 7],
[4, 7],
[1, 8],
[3, 8],
[1, 9],
[2, 9],
[3, 9],
[3, 10],
]
qubit_coordinates_map[28] = [
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 2],
[1, 6],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[2, 5],
[2, 6],
[2, 7],
[2, 8],
[3, 0],
[3, 4],
[3, 8],
[4, 0],
[4, 1],
[4, 2],
[4, 3],
[4, 4],
[4, 5],
[4, 6],
[4, 7],
[4, 8],
]
qubit_coordinates_map[53] = [
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[1, 2],
[1, 6],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[2, 5],
[2, 6],
[2, 7],
[2, 8],
[3, 0],
[3, 4],
[3, 8],
[4, 0],
[4, 1],
[4, 2],
[4, 3],
[4, 4],
[4, 5],
[4, 6],
[4, 7],
[4, 8],
[5, 2],
[5, 6],
[6, 0],
[6, 1],
[6, 2],
[6, 3],
[6, 4],
[6, 5],
[6, 6],
[6, 7],
[6, 8],
[7, 0],
[7, 4],
[7, 8],
[8, 0],
[8, 1],
[8, 2],
[8, 3],
[8, 4],
[8, 5],
[8, 6],
[8, 7],
[8, 8],
[9, 2],
[9, 6],
]
qubit_coordinates_map[65] = [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[0, 5],
[0, 6],
[0, 7],
[0, 8],
[0, 9],
[1, 0],
[1, 4],
[1, 8],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[2, 5],
[2, 6],
[2, 7],
[2, 8],
[2, 9],
[2, 10],
[3, 2],
[3, 6],
[3, 10],
[4, 0],
[4, 1],
[4, 2],
[4, 3],
[4, 4],
[4, 5],
[4, 6],
[4, 7],
[4, 8],
[4, 9],
[4, 10],
[5, 0],
[5, 4],
[5, 8],
[6, 0],
[6, 1],
[6, 2],
[6, 3],
[6, 4],
[6, 5],
[6, 6],
[6, 7],
[6, 8],
[6, 9],
[6, 10],
[7, 2],
[7, 6],
[7, 10],
[8, 1],
[8, 2],
[8, 3],
[8, 4],
[8, 5],
[8, 6],
[8, 7],
[8, 8],
[8, 9],
[8, 10],
]
if isinstance(backend, BackendV2):
num_qubits = backend.num_qubits
coupling_map = backend.plot_coupling_map
else:
config = backend.configuration()
num_qubits = config.n_qubits
coupling_map = config.coupling_map
# don't reference dictionary if provided as a parameter
if qubit_coordinates is None:
qubit_coordinates = qubit_coordinates_map.get(num_qubits)
# try to adjust num_qubits to match the next highest hardcoded grid size
if qubit_coordinates is None:
if any([num_qubits < key for key in qubit_coordinates_map.keys()]):
num_qubits_roundup = max(qubit_coordinates_map.keys())
for key in qubit_coordinates_map.keys():
if key < num_qubits_roundup and key > num_qubits:
num_qubits_roundup = key
qubit_coordinates = qubit_coordinates_map.get(num_qubits_roundup)
return plot_coupling_map(
num_qubits,
qubit_coordinates,
coupling_map,
figsize,
plot_directed,
label_qubits,
qubit_size,
line_width,
font_size,
qubit_color,
qubit_labels,
line_color,
font_color,
ax,
filename,
)
def plot_coupling_map(
num_qubits: int,
qubit_coordinates: List[List[int]],
coupling_map: List[List[int]],
figsize=None,
plot_directed=False,
label_qubits=True,
qubit_size=None,
line_width=4,
font_size=None,
qubit_color=None,
qubit_labels=None,
line_color=None,
font_color="w",
ax=None,
filename=None,
):
"""Plots an arbitrary coupling map of qubits (embedded in a plane).
Args:
num_qubits (int): The number of qubits defined and plotted.
qubit_coordinates (List[List[int]]): A list of two-element lists, with entries of each nested
list being the planar coordinates in a 0-based square grid where each qubit is located.
coupling_map (List[List[int]]): A list of two-element lists, with entries of each nested
list being the qubit numbers of the bonds to be plotted.
figsize (tuple): Output figure size (wxh) in inches.
plot_directed (bool): Plot directed coupling map.
label_qubits (bool): Label the qubits.
qubit_size (float): Size of qubit marker.
line_width (float): Width of lines.
font_size (int): Font size of qubit labels.
qubit_color (list): A list of colors for the qubits
qubit_labels (list): A list of qubit labels
line_color (list): A list of colors for each line from coupling_map.
font_color (str): The font color for the qubit labels.
ax (Axes): A Matplotlib axes instance.
filename (str): file path to save image to.
Returns:
Figure: A Matplotlib figure instance.
Raises:
MissingOptionalLibraryError: if matplotlib not installed.
QiskitError: If length of qubit labels does not match number of qubits.
Example:
.. jupyter-execute::
from qiskit.visualization import plot_coupling_map
%matplotlib inline
num_qubits = 8
coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]]
qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]]
plot_coupling_map(num_qubits, coupling_map, qubit_coordinates)
"""
if not HAS_MATPLOTLIB:
raise MissingOptionalLibraryError(
libname="Matplotlib",
name="plot_coupling_map",
pip_install="pip install matplotlib",
)
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
input_axes = False
if ax:
input_axes = True
if font_size is None:
font_size = 12
if qubit_size is None:
qubit_size = 24
if num_qubits > 20:
qubit_size = 28
font_size = 10
if qubit_labels is None:
qubit_labels = list(range(num_qubits))
else:
if len(qubit_labels) != num_qubits:
raise QiskitError("Length of qubit labels does not equal number of qubits.")
if qubit_coordinates is not None:
grid_data = qubit_coordinates
else:
if not input_axes:
fig, ax = plt.subplots(figsize=(5, 5))
ax.axis("off")
if filename:
fig.savefig(filename)
return fig
x_max = max(d[1] for d in grid_data)
y_max = max(d[0] for d in grid_data)
max_dim = max(x_max, y_max)
if figsize is None:
if num_qubits == 1 or (x_max / max_dim > 0.33 and y_max / max_dim > 0.33):
figsize = (5, 5)
else:
figsize = (9, 3)
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
ax.axis("off")
# set coloring
if qubit_color is None:
qubit_color = ["#648fff"] * num_qubits
if line_color is None:
line_color = ["#648fff"] * len(coupling_map) if coupling_map else []
# Add lines for couplings
if num_qubits != 1:
for ind, edge in enumerate(coupling_map):
is_symmetric = False
if edge[::-1] in coupling_map:
is_symmetric = True
y_start = grid_data[edge[0]][0]
x_start = grid_data[edge[0]][1]
y_end = grid_data[edge[1]][0]
x_end = grid_data[edge[1]][1]
if is_symmetric:
if y_start == y_end:
x_end = (x_end - x_start) / 2 + x_start
elif x_start == x_end:
y_end = (y_end - y_start) / 2 + y_start
else:
x_end = (x_end - x_start) / 2 + x_start
y_end = (y_end - y_start) / 2 + y_start
ax.add_artist(
plt.Line2D(
[x_start, x_end],
[-y_start, -y_end],
color=line_color[ind],
linewidth=line_width,
zorder=0,
)
)
if plot_directed:
dx = x_end - x_start
dy = y_end - y_start
if is_symmetric:
x_arrow = x_start + dx * 0.95
y_arrow = -y_start - dy * 0.95
dx_arrow = dx * 0.01
dy_arrow = -dy * 0.01
head_width = 0.15
else:
x_arrow = x_start + dx * 0.5
y_arrow = -y_start - dy * 0.5
dx_arrow = dx * 0.2
dy_arrow = -dy * 0.2
head_width = 0.2
ax.add_patch(
mpatches.FancyArrow(
x_arrow,
y_arrow,
dx_arrow,
dy_arrow,
head_width=head_width,
length_includes_head=True,
edgecolor=None,
linewidth=0,
facecolor=line_color[ind],
zorder=1,
)
)
# Add circles for qubits
for var, idx in enumerate(grid_data):
# add check if num_qubits had been rounded up
if var >= num_qubits:
break
_idx = [idx[1], -idx[0]]
ax.add_artist(
mpatches.Ellipse(
_idx,
qubit_size / 48,
qubit_size / 48, # This is here so that the changes
color=qubit_color[var],
zorder=1,
)
) # to how qubits are plotted does
if label_qubits: # not affect qubit size kwarg.
ax.text(
*_idx,
s=qubit_labels[var],
horizontalalignment="center",
verticalalignment="center",
color=font_color,
size=font_size,
weight="bold",
)
ax.set_xlim([-1, x_max + 1])
ax.set_ylim([-(y_max + 1), 1])
ax.set_aspect("equal")
if not input_axes:
matplotlib_close_if_inline(fig)
if filename:
fig.savefig(filename)
return fig
return None
def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None):
"""Plot the layout of a circuit transpiled for a given target backend.
Args:
circuit (QuantumCircuit): Input quantum circuit.
backend (BaseBackend): Target backend.
view (str): Layout view: either 'virtual' or 'physical'.
Returns:
Figure: A matplotlib figure showing layout.
Raises:
QiskitError: Invalid view type given.
VisualizationError: Circuit has no layout attribute.
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
import numpy as np
from qiskit import QuantumCircuit, IBMQ, transpile
from qiskit.visualization import plot_histogram, plot_gate_map, plot_circuit_layout
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
%matplotlib inline
IBMQ.load_account()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_vigo')
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
"""
if circuit._layout is None:
raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.")
if isinstance(backend, BackendV2):
num_qubits = backend.num_qubits
else:
num_qubits = backend.configuration().n_qubits
qubits = []
qubit_labels = [None] * num_qubits
bit_locations = {
bit: {"register": register, "index": index}
for register in circuit._layout.get_registers()
for index, bit in enumerate(register)
}
for index, qubit in enumerate(circuit._layout.get_virtual_bits()):
if qubit not in bit_locations:
bit_locations[qubit] = {"register": None, "index": index}
if view == "virtual":
for key, val in circuit._layout.get_virtual_bits().items():
bit_register = bit_locations[key]["register"]
if bit_register is None or bit_register.name != "ancilla":
qubits.append(val)
qubit_labels[val] = bit_locations[key]["index"]
elif view == "physical":
for key, val in circuit._layout.get_physical_bits().items():
bit_register = bit_locations[val]["register"]
if bit_register is None or bit_register.name != "ancilla":
qubits.append(key)
qubit_labels[key] = key
else:
raise VisualizationError("Layout view must be 'virtual' or 'physical'.")
qcolors = ["#648fff"] * num_qubits
for k in qubits:
qcolors[k] = "k"
if isinstance(backend, BackendV2):
cmap = backend.plot_coupling_map
else:
cmap = backend.configuration().coupling_map
lcolors = ["#648fff"] * len(cmap)
for idx, edge in enumerate(cmap):
if edge[0] in qubits and edge[1] in qubits:
lcolors[idx] = "k"
fig = plot_gate_map(
backend,
qubit_color=qcolors,
qubit_labels=qubit_labels,
line_color=lcolors,
qubit_coordinates=qubit_coordinates,
)
return fig
def plot_error_map(backend, figsize=(12, 9), show_title=True):
"""Plots the error map of a given backend.
Args:
backend (IBMQBackend): Given backend.
figsize (tuple): Figure size in inches.
show_title (bool): Show the title or not.
Returns:
Figure: A matplotlib figure showing error map.
Raises:
VisualizationError: Input is not IBMQ backend.
VisualizationError: The backend does not provide gate errors for the 'sx' gate.
MissingOptionalLibraryError: If seaborn is not installed
Example:
.. jupyter-execute::
:hide-code:
:hide-output:
from qiskit.test.ibmq_mock import mock_get_backend
mock_get_backend('FakeVigo')
.. jupyter-execute::
from qiskit import QuantumCircuit, execute, IBMQ
from qiskit.visualization import plot_error_map
%matplotlib inline
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_vigo')
plot_error_map(backend)
"""
try:
import seaborn as sns
except ImportError as ex:
raise MissingOptionalLibraryError(
libname="seaborn",
name="plot_error_map",
pip_install="pip install seaborn",
) from ex
if not HAS_MATPLOTLIB:
raise MissingOptionalLibraryError(
libname="Matplotlib",
name="plot_error_map",
pip_install="pip install matplotlib",
)
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import gridspec, ticker
color_map = sns.cubehelix_palette(reverse=True, as_cmap=True)
props = backend.properties().to_dict()
config = backend.configuration().to_dict()
num_qubits = config["n_qubits"]
# sx error rates
single_gate_errors = [0] * num_qubits
for gate in props["gates"]:
if gate["gate"] == "sx":
_qubit = gate["qubits"][0]
for param in gate["parameters"]:
if param["name"] == "gate_error":
single_gate_errors[_qubit] = param["value"]
break
else:
raise VisualizationError(
f"Backend '{backend}' did not supply an error for the 'sx' gate."
)
# Convert to percent
single_gate_errors = 100 * np.asarray(single_gate_errors)
avg_1q_err = np.mean(single_gate_errors)
single_norm = matplotlib.colors.Normalize(
vmin=min(single_gate_errors), vmax=max(single_gate_errors)
)
q_colors = [color_map(single_norm(err)) for err in single_gate_errors]
cmap = config["coupling_map"]
directed = False
line_colors = []
if cmap:
directed = False
if num_qubits < 20:
for edge in cmap:
if [edge[1], edge[0]] not in cmap:
directed = True
break
cx_errors = []
for line in cmap:
for item in props["gates"]:
if item["qubits"] == line:
cx_errors.append(item["parameters"][0]["value"])
break
else:
continue
# Convert to percent
cx_errors = 100 * np.asarray(cx_errors)
avg_cx_err = np.mean(cx_errors)
cx_norm = matplotlib.colors.Normalize(vmin=min(cx_errors), vmax=max(cx_errors))
line_colors = [color_map(cx_norm(err)) for err in cx_errors]
# Measurement errors
read_err = []
for qubit in range(num_qubits):
for item in props["qubits"][qubit]:
if item["name"] == "readout_error":
read_err.append(item["value"])
read_err = 100 * np.asarray(read_err)
avg_read_err = np.mean(read_err)
max_read_err = np.max(read_err)
fig = plt.figure(figsize=figsize)
gridspec.GridSpec(nrows=2, ncols=3)
grid_spec = gridspec.GridSpec(
12,
12,
height_ratios=[1] * 11 + [0.5],
width_ratios=[2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2],
)
left_ax = plt.subplot(grid_spec[2:10, :1])
main_ax = plt.subplot(grid_spec[:11, 1:11])
right_ax = plt.subplot(grid_spec[2:10, 11:])
bleft_ax = plt.subplot(grid_spec[-1, :5])
if cmap:
bright_ax = plt.subplot(grid_spec[-1, 7:])
qubit_size = 28
if num_qubits <= 5:
qubit_size = 20
plot_gate_map(
backend,
qubit_color=q_colors,
line_color=line_colors,
qubit_size=qubit_size,
line_width=5,
plot_directed=directed,
ax=main_ax,
)
main_ax.axis("off")
main_ax.set_aspect(1)
if cmap:
single_cb = matplotlib.colorbar.ColorbarBase(
bleft_ax, cmap=color_map, norm=single_norm, orientation="horizontal"
)
tick_locator = ticker.MaxNLocator(nbins=5)
single_cb.locator = tick_locator
single_cb.update_ticks()
single_cb.update_ticks()
bleft_ax.set_title(f"H error rate (%) [Avg. = {round(avg_1q_err, 3)}]")
if cmap is None:
bleft_ax.axis("off")
bleft_ax.set_title(f"H error rate (%) = {round(avg_1q_err, 3)}")
if cmap:
cx_cb = matplotlib.colorbar.ColorbarBase(
bright_ax, cmap=color_map, norm=cx_norm, orientation="horizontal"
)
tick_locator = ticker.MaxNLocator(nbins=5)
cx_cb.locator = tick_locator
cx_cb.update_ticks()
bright_ax.set_title(f"CNOT error rate (%) [Avg. = {round(avg_cx_err, 3)}]")
if num_qubits < 10:
num_left = num_qubits
num_right = 0
else:
num_left = math.ceil(num_qubits / 2)
num_right = num_qubits - num_left
left_ax.barh(range(num_left), read_err[:num_left], align="center", color="#DDBBBA")
left_ax.axvline(avg_read_err, linestyle="--", color="#212121")
left_ax.set_yticks(range(num_left))
left_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)])
left_ax.set_yticklabels([str(kk) for kk in range(num_left)], fontsize=12)
left_ax.invert_yaxis()
left_ax.set_title("Readout Error (%)", fontsize=12)
for spine in left_ax.spines.values():
spine.set_visible(False)
if num_right:
right_ax.barh(
range(num_left, num_qubits),
read_err[num_left:],
align="center",
color="#DDBBBA",
)
right_ax.axvline(avg_read_err, linestyle="--", color="#212121")
right_ax.set_yticks(range(num_left, num_qubits))
right_ax.set_xticks([0, round(avg_read_err, 2), round(max_read_err, 2)])
right_ax.set_yticklabels(
[str(kk) for kk in range(num_left, num_qubits)], fontsize=12
)
right_ax.invert_yaxis()
right_ax.invert_xaxis()
right_ax.yaxis.set_label_position("right")
right_ax.yaxis.tick_right()
right_ax.set_title("Readout Error (%)", fontsize=12)
else:
right_ax.axis("off")
for spine in right_ax.spines.values():
spine.set_visible(False)
if show_title:
fig.suptitle(f"{backend.name()} Error Map", fontsize=24, y=0.9)
matplotlib_close_if_inline(fig)
return fig
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
### Install Qiskit and relevant packages, if needed
### IMPORTANT: Make sure you are on 3.10 > python < 3.12
%pip install qiskit[visualization]==1.0.2
%pip install qiskit-ibm-runtime
%pip install qiskit-aer
%pip install graphviz
%pip install qiskit-serverless -U
%pip install qiskit-transpiler-service -U
%pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U
# Import all in one cell
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.circuit.library import RealAmplitudes
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.transpiler import InstructionProperties
from qiskit.visualization import plot_distribution
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.primitives import StatevectorEstimator
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import (
QiskitRuntimeService,
EstimatorV2 as Estimator,
SamplerV2 as Sampler,
EstimatorOptions
)
### Save API Token, if needed
%set_env QXToken=deleteThisAndPasteYourTokenHere
# Set Grade only mode
%set_env QC_GRADE_ONLY=true
# Make sure there is no space between the equal sign
# and the beginning of your token
# qc-grader should be 0.18.12 (or higher)
import qc_grader
qc_grader.__version__
from qc_grader.challenges.iqc_2024 import (
grade_lab4_ex1,
grade_lab4_ex2,
grade_lab4_ex3,
grade_lab4_ex4,
grade_lab4_ex5,
grade_lab4_ex6,
grade_lab4_ex7
)
# Define num_qubits, the number of qubits, for the rest of the Lab
num_qubits = 5
# Load the dictionary
birds_dataset = pd.read_csv('birds_dataset.csv')
# Check if the dataset is loaded correctly - coefficients should be complex numbers
for i in range(2**num_qubits):
key = 'c%.0f' %i
birds_dataset[key] = birds_dataset[key].astype(np.complex128)
# Print the dataset
birds_dataset
### Write your code below here ###
list_coefficients = []
list_labels = []
for i in range(10):
amplitude_state = []
if i < 5:
list_labels.append(1)
else:
list_labels.append(0)
for j in range(2**num_qubits):
key = 'c%.0f' %j
amplitude_state.append(birds_dataset[key][i])
list_coefficients.append(amplitude_state)
### Don't change any code past this line ###
# Submit your answer using following code
grade_lab4_ex1(list_coefficients, list_labels)
index_bird = 2 # You can check different birds by changing the index
amplitudes = list_coefficients[index_bird]
# Build the amplitude embedding
qc = QuantumCircuit(5)
qc.initialize(amplitudes, range(num_qubits))
qc.measure_all()
# Draw the amplitude embedding circuit
qc.draw(output="mpl")
# Draw the decomposition of the amplitude embedding circuit
qc.decompose(reps=8).draw(output="mpl", fold=40)
### Write your code below here ###
num_qubits = 5
reps = 1
entanglement = 'full'
ansatz = RealAmplitudes(num_qubits, reps=reps, entanglement=entanglement, insert_barriers=True)
ansatz.decompose(reps=1).draw(output="mpl")
### Don't change any code past this line ###
# Submit your answer using following code
grade_lab4_ex2(num_qubits, reps, entanglement)
# Define the observable
obs = SparsePauliOp("ZZZZZ")
# Define the estimator and pass manager
estimator = StatevectorEstimator() #To train we use StatevectorEstimator to get the exact simulation
pm = generate_preset_pass_manager(backend=AerSimulator(), optimization_level=3, seed_transpiler=0)
# Define the cost function
def cost_func(params, list_coefficients, list_labels, ansatz, obs, estimator, pm, callback_dict):
"""Return cost function for optimization
Parameters:
params (ndarray): Array of ansatz parameters
list_coefficients (list): List of arrays of complex coefficients
list_labels (list): List of labels
ansatz (QuantumCircuit): Parameterized ansatz circuit
obs (SparsePauliOp): Observable
estimator (EstimatorV2): Statevector estimator primitive instance
pm (PassManager): Pass manager
callback_dict (dict): Dictionary to store callback information
Returns:
float: Cost function estimate
"""
cost = 0
for amplitudes,label in zip(list_coefficients, list_labels):
qc = QuantumCircuit(num_qubits)
# Amplitude embedding
qc.initialize(amplitudes)
# Compose initial state + ansatz
classifier = qc.compose(ansatz)
# Transpile classifier
transpiled_classifier = pm.run(classifier)
# Transpile observable
transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout)
# Run estimator
pub = (transpiled_classifier, transpiled_obs, params)
job = estimator.run([pub])
# Get result
result = job.result()[0].data.evs
# Compute cost function (cumulative)
cost += np.abs(result - label)
callback_dict["iters"] += 1
callback_dict["prev_vector"] = params
callback_dict["cost_history"].append(cost)
# Print the iterations to screen on a single line
print(
"Iters. done: {} [Current cost: {}]".format(callback_dict["iters"], cost),
end="\r",
flush=True,
)
return cost
# Intialize the lists to store the results from different runs
cost_history_list = []
res_list = []
# Retrieve the initial parameters
params_0_list = np.load("params_0_list.npy")
for it, params_0 in enumerate(params_0_list):
print('Iteration number: ', it)
# Initialize a callback dictionary
callback_dict = {
"prev_vector": None,
"iters": 0,
"cost_history": [],
}
# Minimize the cost function using scipy
res = minimize(
cost_func,
params_0,
args=(list_coefficients, list_labels, ansatz, obs, estimator, pm, callback_dict),
method="cobyla", # Classical optimizer
options={'maxiter': 200}) # Maximum number of iterations
# Print the results after convergence
print(res)
# Save the results from different runs
res_list.append(res)
cost_history_list.append(callback_dict["cost_history"])
fig, ax = plt.subplots(1, 1, figsize=(7,5))
ax.set_title('Cost history')
ax.set_ylabel('Cost')
ax.set_xlabel('Iterations')
### Write your code below here ###
#np.save('res_list.npy', res_list)
for it, cost_history in enumerate(cost_history_list):
ax.plot(cost_history, label='Trial '+str(it))
ax.legend()
### Don't change any code past this line ###
def test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm):
"""Return the performance of the classifier
Parameters:
list_coefficients (list): List of arrays of complex coefficients
list_labels (list): List of labels
ansatz (QuantumCircuit): Parameterized ansatz circuit
obs (SparsePauliOp): Observable
opt_params (ndarray): Array of optimized parameters
estimator (EstimatorV2): Statevector estimator
pm (PassManager): Pass manager for transpilation
Returns:
list: List of test results
"""
### Write your code below here ###
results_test = []
for amplitudes,label in zip(list_coefficients, list_labels):
qc = QuantumCircuit(num_qubits)
qc.initialize(amplitudes)
classifier = qc.compose(ansatz)
transpiled_classifier = pm.run(classifier)
pub = (transpiled_classifier, obs, opt_params)
job = estimator.run([pub])
result = job.result()[0].data.evs
results_test.append(abs(result))
### Don't change any code past this line ###
return results_test
def compute_performance(result_list, list_labels):
"""Return the performance of the classifier
Parameters:
result_list (list): List of results
list_labels (list): List of labels
Returns:
float: Performance of the classifier
"""
### Write your code below here ###
performance = 100
for result, label in zip(result_list, list_labels):
performance -= np.abs(abs(result) - label)/len(list_coefficients)*100
### Don't change any code past this line ###
return performance
fig, ax = plt.subplots(1, 1, figsize=(7,5))
ax.set_title('Cost on test data')
ax.set_ylabel('Cost')
ax.set_xlabel('State index')
ax.plot(list_labels, 'k-', linewidth=3, alpha=0.6, label='Labels')
for index in range(len(res_list)):
opt_params = res_list[index].x
results_test = test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm)
print(f"Performance for trial {index}: {compute_performance(results_test, list_labels)}")
ax.plot(results_test, 'o--', label='Predictions trial '+str(index))
ax.legend()
# Submit your answer using following code
best_result_index = 4 # Choose the index with the best result
grade_lab4_ex3(res_list[best_result_index]) # Expected result type: OptimizeResult
fake_backend = GenericBackendV2(
num_qubits=5,
basis_gates=["id", "rz", "sx", "x", "cx"]
)
def update_error_rate(backend, error_rates):
"""Updates the error rates of the backend
Parameters:
backend (BackendV2): Backend to update
error_rates (dict): Dictionary of error rates
Returns:
None
"""
default_duration=1e-8
if "default_duration" in error_rates:
default_duration = error_rates["default_duration"]
# Update the 1-qubit gate properties
for i in range(backend.num_qubits):
qarg = (i,)
if "rz_error" in error_rates:
backend.target.update_instruction_properties('rz', qarg, InstructionProperties(error=error_rates["rz_error"], duration=default_duration))
if "x_error" in error_rates:
backend.target.update_instruction_properties('x', qarg, InstructionProperties(error=error_rates["x_error"], duration=default_duration))
if "sx_error" in error_rates:
backend.target.update_instruction_properties('sx', qarg, InstructionProperties(error=error_rates["sx_error"], duration=default_duration))
if "measure_error" in error_rates:
backend.target.update_instruction_properties('measure', qarg, InstructionProperties(error=error_rates["measure_error"], duration=default_duration))
# Update the 2-qubit gate properties (CX gate) for all edges in the chosen coupling map
if "cx_error" in error_rates:
for edge in backend.coupling_map:
backend.target.update_instruction_properties('cx', tuple(edge), InstructionProperties(error=error_rates["cx_error"], duration=default_duration))
error_rates = {
"default_duration": 1e-8,
"rz_error": 1e-8,
"x_error": 1e-8,
"sx_error": 1e-8,
"measure_error": 1e-8,
"cx_error": 1e-8
}
update_error_rate(fake_backend, error_rates)
fig, ax = plt.subplots(1, 1, figsize=(7,5))
ax.set_title('Cost on test data')
ax.set_ylabel('Cost')
ax.set_xlabel('State index')
ax.plot(list_labels, 'k-', linewidth=3, alpha=0.6, label='Labels')
error_rate_list = [1e-1, 1e-2, 1e-3, 1e-4]
fake_backend = GenericBackendV2(
num_qubits=5,
basis_gates=["id", "rz", "sx", "x", "cx"]
)
for error_rate_value in error_rate_list:
### Write your code below here ###
error_rates = {
"default_duration": 1e-8,
"rz_error": error_rate_value,
"x_error": 1e-8,
"sx_error": 1e-8,
"measure_error": 1e-8,
"cx_error": error_rate_value
}
update_error_rate(fake_backend, error_rates)
estimator = Estimator(backend=fake_backend)
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
opt_params = res_list[best_result_index].x
### Don't change any code past this line ###
results_test = test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm)
print(f"Performance for run {index}: {compute_performance(results_test, list_labels)}")
ax.plot(results_test, 'o--', label='Predictions error rate '+str(error_rate_value))
ax.legend()
# Submit your answer using following code
grade_lab4_ex4(fake_backend) # Expected answer type: BackendV2
# Choose a real backend
service = QiskitRuntimeService()
backend = service.backend("ibm_osaka")
# Define a fake backend with the same properties as the real backend
fake_backend = AerSimulator.from_backend(backend)
index_bird = 0 #you can check different birds by changing the index
qc = QuantumCircuit(num_qubits)
qc.initialize(list_coefficients[index_bird])
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
transpiled_qc = pm.run(qc)
print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
transpiled_qc.draw(output="mpl", idle_wires=False, fold=40)
def amplitude_embedding(num_qubits, bird_index):
"""Create amplitude embedding circuit
Parameters:
num_qubits (int): Number of qubits for the ansatz
bird_index (int): Data index of the bird
Returns:
qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird
"""
def generate_GHZ(qc):
qc.h(0)
for i, j in zip(range(num_qubits-1), range(1,num_qubits)):
qc.cx(i, j)
### Write your code below here ###
def generate_binary(qc, number):
position=0
bit=1
while number >= bit:
if number & bit:
qc.x(position)
bit <<= 1
position=position+1
qc = QuantumCircuit(num_qubits)
if bird_index < 5:
generate_GHZ(qc)
generate_binary(qc, bird_index)
### Don't change any code past this line ###
return qc
index_bird = 0 # You can check different birds by changing the index
# Build the amplitude embedding
qc = amplitude_embedding(num_qubits, index_bird)
qc.measure_all()
# Define the backend and the pass manager
aer_sim = AerSimulator()
pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3)
isa_circuit = pm.run(qc)
# Define the sampler with the number of shots
sampler = Sampler(backend=aer_sim)
result = sampler.run([isa_circuit]).result()
samp_dist = result[0].data.meas.get_counts()
plot_distribution(samp_dist, figsize=(15, 5))
index_bird = 0 #You can check different birds by changing the index
qc = amplitude_embedding(num_qubits, index_bird)
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
transpiled_qc = pm.run(qc)
print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
transpiled_qc.draw(output="mpl", fold=False, idle_wires=False)
# Submit your answer using following code
grade_lab4_ex5(amplitude_embedding) # Expected answer type Callable
old_ansatz = RealAmplitudes(num_qubits, reps=1, entanglement='full', insert_barriers=True)
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
transpiled_ansatz = pm.run(old_ansatz)
print('Depth of two-qubit gates: ', transpiled_ansatz.depth(lambda x: len(x.qubits) == 2))
transpiled_ansatz.draw(output="mpl", idle_wires=False, fold=40)
### Write your code below here ###
ansatz = RealAmplitudes(num_qubits, reps=1, entanglement='pairwise', insert_barriers=True)
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
transpiled_ansatz = pm.run(ansatz)
### Don't change any code past this line ###
print('Depth of two-qubit gates: ', transpiled_ansatz.depth(lambda x: len(x.qubits) == 2))
transpiled_ansatz.draw(output="mpl", fold=False, idle_wires=False)
old_mapping = QuantumCircuit(num_qubits)
old_mapping.initialize(list_coefficients[index_bird])
old_classifier = old_mapping.compose(old_ansatz)
new_mapping = amplitude_embedding(num_qubits, index_bird)
new_classifier = new_mapping.compose(ansatz)
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
old_transpiled_classifier = pm.run(old_classifier)
new_transpiled_classifier = pm.run(new_classifier)
print('Old depth of two-qubit gates: ', old_transpiled_classifier.depth(lambda x: len(x.qubits) == 2))
print('Current depth of two-qubit gates: ', new_transpiled_classifier.depth(lambda x: len(x.qubits) == 2))
def test_shallow_VQC(list_labels, ansatz, obs, opt_params, estimator, pm):
"""Return the performance of the classifier
Parameters:
list_labels (list): List of labels
ansatz (QuantumCircuit): Parameterized ansatz circuit
obs (SparsePauliOp): Observable
opt_params (ndarray): Array of optimized parameters
estimator (EstimatorV2): Statevector estimator
pm (PassManager): Pass manager for transpilation
Returns:
results_test (list): List of test results
"""
### Write your code below here ###
results_test = []
for bird, label in enumerate(list_labels):
qc = amplitude_embedding(num_qubits, bird)
classifier = qc.compose(ansatz)
transpiled_classifier = pm.run(classifier)
transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout)
pub = (transpiled_classifier, transpiled_obs, opt_params)
job = estimator.run([pub])
result = job.result()[0].data.evs
results_test.append(abs(result))
### Don't change any code past this line ###
return results_test
estimator = Estimator(backend=fake_backend)
estimator.options.default_shots = 5000
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
opt_params = np.load('opt_params_shallow_VQC.npy') # Load optimal parameters
results_test = test_shallow_VQC(list_labels, ansatz, obs, opt_params, estimator, pm)
print(f"Performance: {compute_performance(results_test, list_labels)}")
fig, ax = plt.subplots(1, 1, figsize=(7,5))
ax.set_title('Cost on test data')
ax.set_ylabel('Cost')
ax.set_xlabel('State index')
ax.plot(list_labels, 'k-', linewidth=3, alpha=0.6, label='Labels')
ax.plot(results_test, 'o--', label='Fake Backend')
ax.legend()
# Submit your answer using following code
grade_lab4_ex6(results_test) # Expected answer type: list[float]
service = QiskitRuntimeService()
backend = service.backend("ibm_osaka")
def test_shallow_VQC_QPU(list_labels, anstaz, obs, opt_params, options, backend):
"""Return the performance of the classifier
Parameters:
list_labels (list): List of labels
ansatz (QuantumCircuit): Parameterized ansatz circuit
obs (SparsePauliOp): Observable
opt_params (ndarray): Array of optimized parameters
options (EstimatorOptions): Estimator options
backend (service.backend): Backend to run the job
Returns:
job_id (str): Job ID
"""
estimator = Estimator(backend=backend, options=options)
pm = generate_preset_pass_manager(optimization_level=3, backend=backend)
pubs = []
for bird, label in enumerate(list_labels):
### Write your code below here ###
qc = QuantumCircuit(num_qubits)
amplitude_embedding(qc, bird)
classifier = qc.compose(ansatz)
transpiled_classifier = pm.run(classifier)
transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout)
### Don't change any code past this line ###
pub = (transpiled_classifier, transpiled_obs, opt_params)
pubs.append(pub)
job = estimator.run(pubs)
job_id = job.job_id()
print(f"Job ID: {job_id}")
print(f"Status: {job.status()}")
return job_id
## SOLUTIONS
## No DD, no TREX (no ZNE)
resilience = 0
DD = False
options_0 = EstimatorOptions(default_shots = 5000,
optimization_level=0,
resilience_level=resilience)
options_0.dynamical_decoupling.enable = DD
options_0.dynamical_decoupling.sequence_type = 'XpXm'
## DD + TREX (no ZNE)
resilience = 1
DD = True
options_1 = EstimatorOptions(default_shots = 5000,
optimization_level=0,
resilience_level=resilience)
options_1.dynamical_decoupling.enable = DD
options_1.dynamical_decoupling.sequence_type = 'XpXm'
# Submit your answer using following code
grade_lab4_ex7(options_0, options_1) # Expected answer type: EstimatorOptions, EstimatorOptions
def retrieve_job(job_id):
''' Retrieve results from job_id '''
job = service.job(job_id)
results_test = []
errors_test = []
for result in job.result():
results_test.append(abs(result.data.evs))
errors_test.append(abs(result.data.stds))
return results_test, errors_test
## No DD, no TREX (no ZNE)
job_id_0 = test_shallow_VQC_QPU(list_labels, ansatz, obs, opt_params, options_0, backend)
## DD + TREX (no ZNE)
job_id_1 = test_shallow_VQC_QPU(list_labels, ansatz, obs, opt_params, options_1, backend)
results_test_0_DD, errors_test_0_DD = retrieve_job() #(Add job_id 0 here)
results_test_1_DD, errors_test_1_DD = retrieve_job() #(Add job_id 1 here)
fig, ax = plt.subplots(1, 1, figsize=(7,5))
ax.set_title('Cost on test data')
ax.set_ylabel('Cost')
ax.set_xlabel('State index')
print(f"Performance for no DD + no TREX: {compute_performance(results_test_0_DD, list_labels):.3f}")
print(f"Performance for DD + TREX: {compute_performance(results_test_1_DD, list_labels):.3f}")
ax.errorbar(range(10), results_test_0_DD, fmt='-o', yerr=errors_test_0_DD, color='tab:orange', label='Osaka no EM')
ax.errorbar(range(10), results_test_1_DD, fmt='-o', yerr=errors_test_1_DD, color='tab:blue', label='Osaka TREX + DD')
ax.plot(list_labels, 'k-', label='Labels')
ax.legend()
|
https://github.com/joemoorhouse/quantum-mc
|
joemoorhouse
|
from math import pi
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister
from .qft import qft, iqft, cqft, ciqft, ccu1
from qiskit.circuit.library import SXdgGate
# Modified version of qarithmetic https://github.com/hkhetawat/QArithmetic
################################################################################
# Bitwise Operators
################################################################################
# bit-wise operations
def bitwise_and(qc, a, b, c, N):
for i in range(0, N):
qc.ccx(a[i], b[i], c[i])
def bitwise_or(qc, a, b, c, N):
for i in range(0, N):
qc.ccx(a[i], b[i], c[i])
qc.cx(a[i], c[i])
qc.cx(b[i], c[i])
def bitwise_xor(qc, a, b, c, N):
for i in range(0, N):
qc.cx(a[i], c[i])
qc.cx(b[i], c[i])
def bitwise_not(qc, a, c, N):
for i in range(0, N):
qc.cx(a[i], c[i])
qc.x(c[i])
# Cyclically left-shifts a binary string "a" of length n.
# If "a" is zero-padded, equivalent to multiplying "a" by 2.
def lshift(circ, a, n=-1):
# Init n if it was not
if n == -1:
n = len(a)
# Iterate through pairs and do swaps.
for i in range(n,1,-1):
circ.swap(a[i-1],a[i-2])
# Cyclically left-shifts a binary string "a" of length n, controlled by c.
# If "a" is zero-padded, equivalent to multiplying "a" by 2, if and only if c.
def c_lshift(circ, c, a, n=-1):
# Init n if it was not
if n == -1:
n = len(a)
# Iterate through pairs and do swaps.
for i in range(n,1,-1):
circ.cswap(c, a[i-1],a[i-2])
# Cyclically right-shifts a binary string "a" of length n.
# If "a" is zero-padded, equivalent to dividing "a" by 2.
def rshift(circ, a, n=-1):
# Init n if it was not
if n == -1:
n = len(a)
# Iterate through pairs and do swaps.
for i in range(n-1):
circ.swap(a[i],a[i+1])
# Cyclically right-shifts a binary string "a" of length n, controlled by c.
# If "a" is zero-padded, equivalent to dividing "a" by 2, if and only if c.
def c_rshift(circ, c, a, n=-1):
# Init n if it was not
if n == -1:
n = len(a)
# Iterate through pairs and do swaps.
for i in range(n,1,-1):
circ.cswap(c, a[i-1],a[i-2])
################################################################################
# Addition Circuits
################################################################################
# Define some functions for the ripple adder.
def sum(circ, cin, a, b):
circ.cx(a,b)
circ.cx(cin,b)
def sum_cq(circ, cin, a, b):
if a == 1:
circ.x(b)
circ.cx(cin,b)
def carry(circ, cin, a, b, cout):
circ.ccx(a, b, cout)
circ.cx(a, b)
circ.ccx(cin, b, cout)
# in this version a is classical and b quatum
def carry_cq(circ, cin, a, b, cout):
if a == 1:
circ.cx(b, cout)
circ.x(b)
circ.ccx(cin, b, cout)
def carry_dg_cq(circ, cin, a, b, cout):
circ.ccx(cin, b, cout)
if a == 1:
circ.x(b)
circ.cx(b, cout)
def carry_dg(circ, cin, a, b, cout):
circ.ccx(cin, b, cout)
circ.cx(a, b)
circ.ccx(a, b, cout)
# Draper adder that takes |a>|b> to |a>|a+b>.
# |a> has length x and is less than or equal to n
# |b> has length n+1 (left padded with a zero).
# https://arxiv.org/pdf/quant-ph/0008033.pdf
def add(circ, a, b, n):
# move n forward by one to account for overflow
n += 1
# Take the QFT.
qft(circ, b, n)
# Compute controlled-phases.
# Iterate through the targets.
for i in range(n,0,-1):
# Iterate through the controls.
for j in range(i,0,-1):
# If the qubit a[j-1] exists run cu1, if not assume the qubit is 0 and never existed
if len(a) - 1 >= j - 1:
circ.cu1(2*pi/2**(i-j+1), a[j-1], b[i-1])
# Take the inverse QFT.
iqft(circ, b, n)
# Draper adder that takes |a>|b> to |a>|a+b>, controlled on |c>.
# |a> has length x and is less than or equal to n
# |b> has length n+1 (left padded with a zero).
# |c> is a single qubit that's the control.
def cadd(circ, c, a, b, n):
# move n forward by one to account for overflow
n += 1
# Take the QFT.
cqft(circ, c, b, n)
# Compute controlled-phases.
# Iterate through the targets.
for i in range(n,0,-1):
# Iterate through the controls.
for j in range(i,0,-1):
# If the qubit a[j-1] exists run ccu, if not assume the qubit is 0 and never existed
if len(a) - 1 >= j - 1:
ccu1(circ, 2*pi/2**(i-j+1), c, a[j-1], b[i-1])
# Take the inverse QFT.
ciqft(circ, c, b, n)
# Adder that takes |a>|b> to |a>|a+b>.
# |a> has length n.
# |b> has length n+1.
# Based on Vedral, Barenco, and Ekert (1996).
def add_ripple(circ, a, b, n):
# Create a carry register of length n.
c = QuantumRegister(n)
circ.add_register(c)
# Calculate all the carries except the last one.
for i in range(0, n-1):
carry(circ, c[i], a[i], b[i], c[i+1])
# The last carry bit is the leftmost bit of the sum.
carry(circ, c[n-1], a[n-1], b[n-1], b[n])
# Calculate the second-to-leftmost bit of the sum.
circ.cx(c[n-1],b[n-1])
# Invert the carries and calculate the remaining sums.
for i in range(n-2,-1,-1):
carry_dg(circ, c[i], a[i], b[i], c[i+1])
sum(circ, c[i], a[i], b[i])
# Adder that takes |a>|b> to |a>|a+b>.
# |a> has length n.
# |b> has length n+1.
# Based on Vedral, Barenco, and Ekert (1996).
def add_ripple_in_place(circ, a, b, anc, n):
# Calculate all the carries except the last one.
for i in range(0, n-1):
carry(circ, anc[i], a[i], b[i], anc[i+1])
# The last carry bit is the leftmost bit of the sum.
carry(circ, anc[n-1], a[n-1], b[n-1], b[n])
# Calculate the second-to-leftmost bit of the sum.
circ.cx(anc[n-1],b[n-1])
# Invert the carries and calculate the remaining sums.
for i in range(n-2,-1,-1):
carry_dg(circ, anc[i], a[i], b[i], anc[i+1])
sum(circ, anc[i], a[i], b[i])
# Adder that takes |a>|b> to |a>|a+b>.
# |a> has length <= n. |a> will be padded with zeros to length n
# |b> has length n+1.
# Based on Vedral, Barenco, and Ekert (1996).
def add_ripple_in_place_padding(circ, a, b, anc, n):
# Calculate all the carries except the last one.
for i in range(0, n - 1):
if i < len(a):
carry(circ, anc[i], a[i], b[i], anc[i+1])
else: # pad with zeros
carry_cq(circ, anc[i], 0, b[i], anc[i+1])
# The last carry bit is the leftmost bit of the sum.
if (n-1) < len(a):
carry(circ, anc[n-1], a[n-1], b[n-1], b[n])
else:
carry_cq(circ, anc[n-1], 0, b[n-1], b[n])
# Calculate the second-to-leftmost bit of the sum.
circ.cx(anc[n-1],b[n-1])
# Invert the carries and calculate the remaining sums.
for i in range(n-2,-1,-1):
if i < len(a):
carry_dg(circ, anc[i], a[i], b[i], anc[i+1])
sum(circ, anc[i], a[i], b[i])
else:
carry_dg_cq(circ, anc[i], 0, b[i], anc[i+1])
sum_cq(circ, anc[i], 0, b[i])
# Adder that takes |a>|b> to |a>|a+b>.
# |a> has length n *and is classical*.
# |b> has length n+1.
# Based on Vedral, Barenco, and Ekert (1996).
def add_ripple_in_place_cq(circ, a, qr_b, qr_anc, n):
# Calculate all the carries except the last one.
for i in range(0, n-1):
carry_cq(circ, qr_anc[i], a[i], qr_b[i], qr_anc[i+1])
# The last carry bit is the leftmost bit of the sum.
carry_cq(circ, qr_anc[n-1], a[n-1], qr_b[n-1], qr_b[n])
# Calculate the second-to-leftmost bit of the sum.
circ.cx(qr_anc[n-1],qr_b[n-1])
# Invert the carries and calculate the remaining sums.
for i in range(n-2,-1,-1):
carry_dg_cq(circ, qr_anc[i], a[i], qr_b[i], qr_anc[i+1])
sum_cq(circ, qr_anc[i], a[i], qr_b[i])
# Adder that takes |a>|b>|0> to |a>|b>|a+b>.
# |a> has length n.
# |b> has length n.
# |s> = |0> has length n+1.
def add_ripple_ex(circ, a, b, s, n):
# Copy b to s.
for i in range(0, n):
circ.cx(b[i],s[i])
# Add a and s.
add_ripple(circ, a, s, n)
################################################################################
# Subtraction Circuits
################################################################################
# Subtractor that takes |a>|b> to |a>|a-b>.
# |a> has length n+1 (left padded with a zero).
# |b> has length n+1 (left padded with a zero).
def sub(circ, a, b, n):
# Flip the bits of a.
circ.x(a)
# Add it to b.
add(circ, a, b, n - 1)
# Flip the bits of the result. This yields the sum.
circ.x(b)
# Flip back the bits of a.
circ.x(a)
# Subtractor that takes |a>|b> to |a-b>|b>.
# |a> has length n+1 (left padded with a zero).
# |b> has length n+1 (left padded with a zero).
def sub_swap(circ, a, b, n):
# Flip the bits of a.
circ.x(a)
# Add it to b.
add(circ, b, a, n - 1)
# Flip the bits of the result. This yields the sum.
circ.x(a)
# Subtractor that takes |a>|b> to |a>|a-b>.
# |a> has length n.
# |b> has length n+1.
def sub_ripple(circ, a, b, n):
# We add "a" to the 2's complement of "b."
# First flip the bits of "b."
circ.x(b)
# Create a carry register of length n.
c = QuantumRegister(n)
circ.add_register(c)
# Add 1 to the carry register, which adds 1 to b, negating it.
circ.x(c[0])
# Calculate all the carries except the last one.
for i in range(0, n-1):
carry(circ, c[i], a[i], b[i], c[i+1])
# The last carry bit is the leftmost bit of the sum.
carry(circ, c[n-1], a[n-1], b[n-1], b[n])
# Calculate the second-to-leftmost bit of the sum.
circ.cx(c[n-1],b[n-1])
# Invert the carries and calculate the remaining sums.
for i in range(n-2,-1,-1):
carry_dg(circ, c[i], a[i], b[i], c[i+1])
sum(circ, c[i], a[i], b[i])
# Flip the carry to restore it to zero.
circ.x(c[0])
# Subtractor that takes |a>|b>|0> to |a>|b>|a-b>.
# |a> has length n.
# |b> has length n.
# |s> = |0> has length n+1.
def sub_ripple_ex(circ, a, b, s, n):
# Copy b to s.
for i in range(0, n):
circ.cx(b[i],s[i])
# Subtract a and s.
sub_ripple(circ, a, s, n)
################################################################################
# Multiplication Circuit
################################################################################
# Controlled operations
# Take a subset of a quantum register from index x to y, inclusive.
def sub_qr(qr, x, y): # may also be able to use qbit_argument_conversion
sub = []
for i in range (x, y+1):
sub = sub + [(qr[i])]
return sub
def full_qr(qr):
return sub_qr(qr, 0, len(qr) - 1)
# Computes the product c=a*b.
# a has length n.
# b has length n.
# c has length 2n.
def mult(circ, a, b, c, n):
for i in range (0, n):
cadd(circ, a[i], b, sub_qr(c, i, n+i), n)
# Computes the product c=a*b if and only if control.
# a has length n.
# b has length n.
# control has length 1.
# c has length 2n.
def cmult(circ, control, a, b, c, n):
qa = QuantumRegister(len(a))
qb = QuantumRegister(len(b))
qc = QuantumRegister(len(c))
tempCircuit = QuantumCircuit(qa, qb, qc)
mult(tempCircuit, qa, qb, qc, n)
tempCircuit = tempCircuit.control(1) #Add Decomposition after pull request inclusion #5446 on terra
print("Remember To Decompose after release >0.16.1")
circ.compose(tempCircuit, qubits=full_qr(control) + full_qr(a) + full_qr(b) + full_qr(c), inplace=True)
################################################################################
# Division Circuit
################################################################################
# Divider that takes |p>|d>|q>.
# |p> is length 2n and has n zeros on the left: 0 ... 0 p_n ... p_1.
# |d> has length 2n and has n zeros on the right: d_2n ... d_{n+1) 0 ... 0.
# |q> has length n and is initially all zeros.
# At the end of the algorithm, |q> will contain the quotient of p/d, and the
# left n qubits of |p> will contain the remainder of p/d.
def div(circ, p, d, q, n):
# Calculate each bit of the quotient and remainder.
for i in range(n,0,-1):
# Left shift |p>, which multiplies it by 2.
lshift(circ, p, 2*n)
# Subtract |d> from |p>.
sub_swap(circ, p, d, 2*n)
# If |p> is positive, indicated by its most significant bit being 0,
# the (i-1)th bit of the quotient is 1.
circ.x(p[2*n-1])
circ.cx(p[2*n-1], q[i-1])
circ.x(p[2*n-1])
# If |p> is negative, indicated by the (i-1)th bit of |q> being 0, add D back
# to P.
circ.x(q[i-1])
cadd(circ, q[i-1], d, p, 2*n - 1)
circ.x(q[i-1])
################################################################################
# Expontential Circuit
################################################################################
# square that takes |a> |b>
# |a> is length n and is a unsigned integer
# |b> is length 2n and has 2n zeros, after execution b = a^2
def square(circ, a, b, n=-1):
if n == -1:
n = len(a)
# First Addition
circ.cx(a[0], b[0])
for i in range(1, n):
circ.ccx(a[0], a[i], b[i])
# Custom Addition Circuit For Each Qubit of A
for k in range(1, n):
# modifying qubits
d = b[k:n+k+1]
qft(circ, d, n+1) #Technically the first few QFT could be refactored to use less gates due to guaranteed controls
# Compute controlled-phases.
# Iterate through the targets.
for i in range(n+1,0,-1):
# Iterate through the controls.
for j in range(i,0,-1):
if len(a) - 1 < j - 1:
pass # skip over non existent qubits
elif k == j - 1: # Cannot control twice
circ.cu1(2*pi/2**(i-j+1), a[j-1], d[i-1])
else:
ccu1(circ, 2*pi/2**(i-j+1), a[k], a[j-1], d[i-1])
iqft(circ, d, n+1)
# a has length n
# b has length v
# finalOut has length n*((2^v)-1), for safety
def power(circ, a, b, finalOut): #Because this is reversible/gate friendly memory blooms to say the least
# Track Number of Qubits
n = len(a)
v = len(b)
# Left 0 pad a, to satisfy multiplication function arguments
aPad = AncillaRegister(n * (pow(2, v) - 3)) # Unsure of where to Anciallas these
circ.add_register(aPad)
padAList = full_qr(aPad)
aList = full_qr(a)
a = aList + padAList
# Create a register d for mults and init with state 1
d = AncillaRegister(n) # Unsure of where to Anciallas these
circ.add_register(d)
# Create a register for tracking the output of cmult to the end
ancOut = AncillaRegister(n*2) # Unsure of where to Anciallas these
circ.add_register(ancOut)
# Left 0 pad finalOut to provide safety to the final multiplication
if (len(a) * 2) - len(finalOut) > 0:
foPad = AncillaRegister((len(a) * 2) - len(finalOut))
circ.add_register(foPad)
padFoList = full_qr(foPad)
foList = full_qr(finalOut)
finalOut = foList + padFoList
# Create zero bits
num_recycle = (2 * n * (pow(2, v) - 2)) - (n * pow(2, v)) # 24
permaZeros = []
if num_recycle > 0:
permaZeros = AncillaRegister(num_recycle) #8
circ.add_register(permaZeros)
permaZeros = full_qr(permaZeros)
# Instead of MULT copy bits over
if v >= 1:
for i in range(n):
circ.ccx(b[0], a[i], d[i])
circ.x(b[0])
circ.cx(b[0], d[0])
circ.x(b[0])
# iterate through every qubit of b
for i in range(1,v): # for every bit of b
for j in range(pow(2, i)):
# run multiplication operation if and only if b is 1
bonus = permaZeros[:2*len(d) - len(ancOut)]
cmult(circ, [b[i]], a[:len(d)], d, full_qr(ancOut) + bonus, len(d))
# if the multiplication was not run copy the qubits so they are not destroyed when creating new register
circ.x(b[i])
for qub in range(0,len(d)):
circ.ccx(b[i], d[qub], ancOut[qub])
circ.x(b[i])
# Move the output to the input for next function and double the qubit length
d = ancOut
if i == v - 1 and j == pow(2, i) - 2:
# this is the second to last step send qubiits to output
ancOut = finalOut
elif not (i == v - 1 and j == pow(2, i) - 1):
# if this is not the very last step
# create a new output register of twice the length and register it
ancOut = AncillaRegister(len(d) + n) # Should label permazero bits
circ.add_register(ancOut)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.qasm3
program = """
OPENQASM 3.0;
include "stdgates.inc";
input float[64] a;
qubit[3] q;
bit[2] mid;
bit[3] out;
let aliased = q[0:1];
gate my_gate(a) c, t {
gphase(a / 2);
ry(a) c;
cx c, t;
}
gate my_phase(a) c {
ctrl @ inv @ gphase(a) c;
}
my_gate(a * 2) aliased[0], q[{1, 2}][0];
measure q[0] -> mid[0];
measure q[1] -> mid[1];
while (mid == "00") {
reset q[0];
reset q[1];
my_gate(a) q[0], q[1];
my_phase(a - pi/2) q[1];
mid[0] = measure q[0];
mid[1] = measure q[1];
}
if (mid[0]) {
let inner_alias = q[{0, 1}];
reset inner_alias;
}
out = measure q;
"""
circuit = qiskit.qasm3.loads(program)
circuit.draw("mpl")
|
https://github.com/nmoran/qiskit-qdrift-quid19
|
nmoran
|
import numpy as np
import matplotlib.pyplot as plt
import math
from qiskit import Aer, IBMQ, QuantumRegister, QuantumCircuit
from qiskit.providers.ibmq import least_busy
from qiskit.providers.aer import noise
# lib from Qiskit Aqua
from qiskit.aqua.operators.common import evolution_instruction
from qiskit.aqua import Operator, QuantumInstance
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B
from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ
# lib from Qiskit Aqua Chemistry
from qiskit.chemistry import QiskitChemistry
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock
driver = PySCFDriver(atom='H .0 .0 .0; Li .0 .0 1.6', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
ferOp = FermionicOperator(h1=h1, h2=h2)
qubitOp = ferOp.mapping(map_type='jordan_wigner', threshold=10**-10)
qubitOp.chop(10**-10)
num_terms = len(qubitOp.paulis)
max_term = max([np.abs(qubitOp.paulis[i][0]) for i in range(num_terms)])
error=.01
norm = 0
probs = []
for i in range(len(qubitOp.paulis)):
norm += np.abs(qubitOp.paulis[i][0])
for i in range(len(qubitOp.paulis)):
probs.append(np.abs(qubitOp.paulis[i][0])/norm)
runs = 10
times = np.linspace(.1,1,10)
qdrift_av_counts=[]
trotter_counts=[]
#iterate through the list of durations
for time_idx in range(len(times)):
qdrift_gate_counts = []
num_time_slices = math.ceil((num_terms*max_term*times[time_idx])**2 / 2*error)
#Iterate (runs) numbers of time to get average data
for run in range(runs):
random_pauli_list=[]
#the number of steps from the norm, time, and error
num_steps = math.ceil((2*norm*times[time_idx])**2 /error)
standard_timestep = times[time_idx]*norm/num_steps
for i in range(num_steps):
idx = np.random.choice(num_terms,p=probs)
#form the list keeping track of the sign of the coefficients
random_pauli_list.append([np.sign(qubitOp.paulis[idx][0])*standard_timestep,qubitOp.paulis[idx][1]])
instruction_qdrift=evolution_instruction(random_pauli_list, evo_time=1, num_time_slices=1,
controlled=False, power=1,
use_basis_gates=True, shallow_slicing=False)
quantum_registers_qdrift = QuantumRegister(qubitOp.num_qubits)
qc_qdrift = QuantumCircuit(quantum_registers_qdrift)
qc_qdrift.append(instruction_qdrift, quantum_registers_qdrift)
qc_qdrift = qc_qdrift.decompose()
total_qdrift = qc_qdrift.count_ops()['cx']+qc_qdrift.count_ops()['u1']+qc_qdrift.count_ops()['u2']+qc_qdrift.count_ops()['u3']
qdrift_gate_counts.append(total_qdrift)
instruction_trotter=evolution_instruction(qubitOp.paulis, evo_time=times[time_idx], num_time_slices=num_time_slices,
controlled=False, power=1,
use_basis_gates=True, shallow_slicing=False)
quantum_registers_trotter = QuantumRegister(qubitOp.num_qubits)
qc_trotter = QuantumCircuit(quantum_registers_trotter)
qc_trotter.append(instruction_trotter, quantum_registers_trotter)
qc_trotter = qc_trotter.decompose()
total_trotter = qc_trotter.count_ops()['cx']+qc_trotter.count_ops()['u1']+qc_trotter.count_ops()['u2']+qc_trotter.count_ops()['u3']
trotter_counts.append(total_trotter)
qdrift_av_counts.append(sum(qdrift_gate_counts)/len(qdrift_gate_counts))
plt.plot(times,qdrift_av_counts,label='qdrift_avg_counts')
plt.plot(times,trotter_counts,label = 'trotter_counts')
plt.title('Gates vs Error for Time Evolution')
plt.xlabel("Duration of evolution")
plt.ylabel("Number of Gates")
plt.legend(loc=0)
plt.savefig("LiH_gates_v_time.png", dpi=600)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
from qiskit import Aer
from qiskit.transpiler import PassManager
from qiskit_aqua import Operator, QuantumInstance
from qiskit_aqua.algorithms.adaptive import VQE
from qiskit_aqua.algorithms.classical import ExactEigensolver
from qiskit_aqua.components.optimizers import L_BFGS_B
from qiskit_aqua.components.variational_forms import RY
from qiskit_chemistry import FermionicOperator
from qiskit_chemistry.drivers import PySCFDriver, UnitsType
driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
qubitOp_jw = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001)
qubitOp_jw.chop(10**-10)
# Using exact eigensolver to get the smallest eigenvalue
exact_eigensolver = ExactEigensolver(qubitOp_jw, k=1)
ret = exact_eigensolver.run()
# print(qubitOp_jw.print_operators())
print('The exact ground state energy is: {}'.format(ret['energy']))
print('The Hartree Fock Electron Energy is: {}'.format(molecule.hf_energy - molecule.nuclear_repulsion_energy))
# particle hole transformation
newferOp, energy_shift = ferOp.particle_hole_transformation(num_particles=2)
print('Energy shift is: {}'.format(energy_shift))
newqubitOp_jw = newferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001)
newqubitOp_jw.chop(10**-10)
exact_eigensolver = ExactEigensolver(newqubitOp_jw, k=1)
ret = exact_eigensolver.run()
# print(newqubitOp_jw.print_operators())
print('The exact ground state energy in PH basis is {}'.format(ret['energy']))
print('The exact ground state energy in PH basis is {} (with energy_shift)'.format(ret['energy'] - energy_shift))
# setup VQE
# setup optimizer, use L_BFGS_B optimizer for example
lbfgs = L_BFGS_B(maxfun=1000, factr=10, iprint=10)
# setup variational form generator (generate trial circuits for VQE)
var_form = RY(newqubitOp_jw.num_qubits, 5, entangler_map = {0: [1], 1:[2], 2:[3]})
# setup VQE with operator, variational form, and optimizer
vqe_algorithm = VQE(newqubitOp_jw, var_form, lbfgs, 'matrix')
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, pass_manager=PassManager())
results = vqe_algorithm.run(quantum_instance)
print("Minimum value: {}".format(results['eigvals'][0].real))
print("Minimum value: {}".format(results['eigvals'][0].real - energy_shift))
print("Parameters: {}".format(results['opt_params']))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for local invariance routines."""
import unittest
from numpy.testing import assert_allclose
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.synthesis.two_qubit.local_invariance import two_qubit_local_invariants
from qiskit.quantum_info import Operator
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestLocalInvariance(QiskitTestCase):
"""Test local invariance routines"""
def test_2q_local_invariance_simple(self):
"""Check the local invariance parameters
for known simple cases.
"""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
U = Operator(qc)
vec = two_qubit_local_invariants(U)
assert_allclose(vec, [1, 0, 3])
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.cx(qr[1], qr[0])
U = Operator(qc)
vec = two_qubit_local_invariants(U)
assert_allclose(vec, [0, 0, 1])
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.cx(qr[1], qr[0])
qc.cx(qr[0], qr[1])
U = Operator(qc)
vec = two_qubit_local_invariants(U)
assert_allclose(vec, [0, 0, -1])
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.swap(qr[1], qr[0])
U = Operator(qc)
vec = two_qubit_local_invariants(U)
assert_allclose(vec, [-1, 0, -3])
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import datetime
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.rcParams.update({"text.usetex": True})
plt.rcParams["figure.figsize"] = (6,4)
mpl.rcParams["figure.dpi"] = 200
from qiskit_ibm_runtime import Estimator, Session, QiskitRuntimeService, Options
from qiskit.quantum_info import SparsePauliOp
from qiskit import QuantumCircuit
service = QiskitRuntimeService()
backend_simulator = "backend_simulator"
backend = "ibmq_montreal"
qubits = 4
trotter_layer = QuantumCircuit(qubits)
trotter_layer.rx(0.1, range(qubits))
trotter_layer.cx(0, 1)
trotter_layer.cx(2, 3)
trotter_layer.rz(-0.2, [1, 3])
trotter_layer.cx(0, 1)
trotter_layer.cx(2, 3)
trotter_layer.cx(1, 2)
trotter_layer.rz(-0.2, 2)
trotter_layer.cx(1, 2)
num_steps = 6
trotter_circuit_list = []
for i in range(1, num_steps):
trotter_circuit = QuantumCircuit(qubits)
for _ in range(i):
trotter_circuit = trotter_circuit.compose(trotter_layer)
trotter_circuit_list.append(trotter_circuit)
print(f'Trotter circuit with {i} Trotter steps`)
display(trotter_circuit.draw(fold=-1))
obs = SparsePauliOp("Z"*qubits)
obs_list = [obs]*len(trotter_circuit_list)
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 0 # No mitigation
with Session(service=service, backend=backend_simulator) as session:
estimator_sim = Estimator(session=session, options=options)
job_sim = estimator_sim.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_sim.job_id)
print(job_sim.result())
expvals_ideal = job_sim.result().values
expvals_ideal_variance = [metadata['variance']/metadata['shots'] for metadata in job_sim.result().metadata]
std_error_ideal = np.sqrt(expvals_ideal_variance)
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 0 # No error mitigation
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job.job_id)
print(job.result())
expvals_unmit = job.result().values
expvals_unmit_variance = [metadata['variance']/metadata['shots'] for metadata in job.result().metadata]
std_error_unmit = np.sqrt(expvals_unmit_variance)
options = Options()
options.execution.shots = 1000
options.optimization_level = 3 # Dynamical decoupling
options.resilience_level = 0 # No error mitigation
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_dd = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_dd.job_id)
print(job_dd.result())
expvals_unmit_dd = job_dd.result().values
expvals_unmit_dd_variance = [metadata['variance']/metadata['shots'] for metadata in job_dd.result().metadata]
std_error_dd = np.sqrt(expvals_unmit_dd_variance)
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_dd, std_error_dd, fmt = 'o', linestyle = '-', capsize=4, c='blue', label='Dynamical decoupling')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.resilience_level = 1 # T-REx
options.optimization_level = 0 # No optimization
options.execution.shots = 1000
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_trex = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_trex.job_id)
print(job_trex.result())
expvals_unmit_trex = job_trex.result().values
expvals_unmit_trex_variance = [metadata['variance']/metadata['shots'] for metadata in job_trex.result().metadata]
std_error_trex = np.sqrt(expvals_unmit_trex_variance)
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 2 # ZNE
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_zne = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_zne.job_id)
print(job_zne.result())
expvals_unmit_zne = job_zne.result().values
# Standard error: coming soon!
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE')
plt.xlabel('No. Trotter Steps')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
def interim_results_callback(job_id, result):
now = datetime.datetime.now()
print(now, "*** Callback ***", result, "\n")
options = Options()
options.optimization_level = 0 # No optimization
options.execution.shots = 100
options.resilience_level = 3 # PEC
options.environment.callback = interim_results_callback
with Session(service=service, backend=backend) as session:
estimator_pec = Estimator(session=session, options=options)
job_pec = estimator_pec.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_pec.job_id)
expvals_pec = job_pec.result().values
std_error_pec = [metadata['standard_error'] for metadata in job_pec.result().metadata]
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
print(job_pec.result())
pec_metadata = job_pec.result().metadata
fig, ax = plt.subplots()
fig.subplots_adjust(right=0.75)
twin1 = ax.twinx()
twin2 = ax.twinx()
twin3 = ax.twinx()
twin2.spines.right.set_position(("axes", 1.2))
twin3.spines.right.set_position(("axes", 1.4))
p1, = ax.plot(range(1, num_steps), [m["total_mitigated_layers"] for m in pec_metadata] , "b-", label="Total mitigated layers")
p2, = twin1.plot(range(1, num_steps), [m["sampling_overhead"] for m in pec_metadata], "r-", label="Sampling overhead")
p3, = twin2.plot(range(1, num_steps), [m["samples"] for m in pec_metadata], "g-", label="Samples")
p4, = twin3.plot(range(1, num_steps), [m["shots"] for m in pec_metadata], "c-", label="Shots")
ax.set_ylim(0, 20)
twin1.set_ylim(0, 2.8)
twin2.set_ylim(0, 300)
twin3.set_ylim(0, 35000)
ax.set_xlabel("No. Trotter Steps")
ax.set_ylabel("Total mitigated layers")
twin1.set_ylabel("Sampling overhead")
twin2.set_ylabel("Samples")
twin3.set_ylabel("Shots")
ax.yaxis.label.set_color(p1.get_color())
twin1.yaxis.label.set_color(p2.get_color())
twin2.yaxis.label.set_color(p3.get_color())
twin3.yaxis.label.set_color(p4.get_color())
tkw = dict(size=4, width=1.5)
ax.tick_params(axis='y', colors=p1.get_color(), **tkw)
twin1.tick_params(axis='y', colors=p2.get_color(), **tkw)
twin2.tick_params(axis='y', colors=p3.get_color(), **tkw)
twin3.tick_params(axis='y', colors=p4.get_color(), **tkw)
plt.xticks([1, 2, 3, 4, 5])
ax.legend(handles=[p1, p2, p3, p4])
plt.title('PEC metadata')
plt.show()
from matplotlib.pyplot import figure
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx')
plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE')
plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC')
plt.title('Trotter circuits expectation value')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # no optimization
options.resilience_level = 2 # ZNE
options.resilience.noise_factors = [1, 2, 3, 4]
options.resilience.noise_amplifier = "LocalFoldingAmplifier"
options.resilience.extrapolator = "QuadraticExtrapolator"
with Session(service=service, backend='ibmq_montreal') as session:
estimator = Estimator(session=session, options=options)
job_zne_options = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_zne_options.job_id)
print(job_zne_options.result())
from qiskit.tools import jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
my_list = [1,2,3 ,4,5, 6,8,8,3,23,7,75,54,3]
def my_oracle(my_input):
winner=7
if my_input is winner:
response = True
else:
response = False
return response
for index, trial_number in enumerate(my_list):
if my_oracle(trial_number) is True:
print('Winner found at index :%i'%index)
print('%i calls to the Oracle used'%(index+1))
break
from qiskit import *
from qiskit.qiskit_aer import Aer
from qiskit import QuantumCircuit
import matplotlib.pyplot as plt
import numpy as np
oracle = QuantumCircuit(2, name='oracle')
oracle.cz(0,1)
oracle.to_gate()
oracle.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
grover_circ = QuantumCircuit(2,2)
grover_circ.h(0)
grover_circ.append(oracle,[0,1])
grover_circ.draw(output='mpl')
job = execute(grover_circ, backend)
result = job.result()
sv = result.get_statevector()
np.arount(sv, 2)
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
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/CQCL/pytket-qiskit
|
CQCL
|
# Copyright 2019 Cambridge Quantum Computing
#
# 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
#
# https://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.
from qiskit import Aer
from qiskit.compiler import assemble
from qiskit.providers.aer.noise import NoiseModel
from pytket.backends import Backend
from pytket.qiskit import tk_to_qiskit
from pytket.backends.ibm.ibm import _convert_bin_str
from pytket._circuit import Circuit
from pytket._transform import Transform
from pytket._simulation import pauli_tensor_matrix, operator_matrix
import numpy as np
class AerBackend(Backend) :
def __init__(self, noise_model:NoiseModel=None) :
"""Backend for running simulations on Qiskit Aer Qasm simulator.
:param noise_model: Noise model to use in simulation, defaults to None.
:type noise_model: NoiseModel, optional
"""
self._backend = Aer.get_backend('qasm_simulator')
self.noise_model = noise_model
def run(self, circuit:Circuit, shots:int, fit_to_constraints=True, seed:int=None) -> np.ndarray:
"""Run a circuit on Qiskit Aer Qasm simulator.
:param circuit: The circuit to run
:type circuit: Circuit
:param shots: Number of shots (repeats) to run
:type shots: int
:param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True
:type fit_to_constraints: bool, optional
:param seed: random seed to for simulator
:type seed: int
:return: Table of shot results, each row is a shot, columns are ordered by qubit ordering. Values are 0 or 1, corresponding to qubit basis states.
:rtype: numpy.ndarray
"""
c = circuit.copy()
if fit_to_constraints :
Transform.RebaseToQiskit().apply(c)
qc = tk_to_qiskit(c)
qobj = assemble(qc, shots=shots, seed_simulator=seed, memory=True)
job = self._backend.run(qobj, noise_model=self.noise_model)
shot_list = job.result().get_memory(qc)
return np.asarray([_convert_bin_str(shot) for shot in shot_list])
def get_counts(self, circuit, shots, fit_to_constraints=True, seed=None) :
"""
Run the circuit on the backend and accumulate the results into a summary of counts
:param circuit: The circuit to run
:param shots: Number of shots (repeats) to run
:param fit_to_constraints: Compile the circuit to meet the constraints of the backend, defaults to True
:param seed: Random seed to for simulator
:return: Dictionary mapping bitvectors of results to number of times that result was observed (zero counts are omitted)
"""
c = circuit.copy()
if fit_to_constraints :
Transform.RebaseToQiskit().apply(c)
qc = tk_to_qiskit(c)
qobj = assemble(qc, shots=shots, seed_simulator=seed)
job = self._backend.run(qobj, noise_model=self.noise_model)
counts = job.result().get_counts(qc)
return {tuple(_convert_bin_str(b)) : c for b, c in counts.items()}
class AerStateBackend(Backend) :
def __init__(self) :
self._backend = Aer.get_backend('statevector_simulator')
def get_state(self, circuit, fit_to_constraints=True) :
"""
Calculate the statevector for a circuit.
:param circuit: circuit to calculate
:return: complex numpy array of statevector
"""
c = circuit.copy()
if fit_to_constraints :
Transform.RebaseToQiskit().apply(c)
qc = tk_to_qiskit(c)
qobj = assemble(qc)
job = self._backend.run(qobj)
return np.asarray(job.result().get_statevector(qc, decimals=16))
def run(self, circuit, shots, fit_to_constraints=True) :
raise Exception("Aer State Backend cannot currently generate shots. Use `get_state` instead.")
def get_pauli_expectation_value(self, state_circuit, pauli, shots=1000) :
state = self.get_state(state_circuit)
pauli_op = pauli_tensor_matrix(pauli, state_circuit.n_qubits)
return np.vdot(state, pauli_op.dot(state))
def get_operator_expectation_value(self, state_circuit, operator, shots=1000) :
"""
Calculates expectation value for an OpenFermion QubitOperator by summing over pauli expectations
Note: This method is significantly faster using the ProjectQBackend than the AerStateBackend.
"""
state = self.get_state(state_circuit)
n_qubits = state_circuit.n_qubits
op_as_lists = [(list(p),c) for p,c in operator.terms.items()]
op = operator_matrix(op_as_lists, n_qubits)
return np.vdot(state, op.dot(state))
class AerUnitaryBackend(Backend) :
def __init__(self) :
self._backend = Aer.get_backend('unitary_simulator')
def run(self, circuit, shots, fit_to_constraints=True) :
raise Exception("Aer Unitary Backend cannot currently generate shots. Use `get_unitary` instead.")
def get_unitary(self, circuit, fit_to_constraints=True) :
"""
Obtains the unitary for a given quantum circuit
:param circuit: The circuit to inspect
:type circuit: Circuit
:param fit_to_constraints: Forces the circuit to be decomposed into the correct gate set, defaults to True
:type fit_to_constraints: bool, optional
:return: The unitary of the circuit. Qubits are ordered with qubit 0 as the least significant qubit
"""
c = circuit.copy()
if fit_to_constraints :
Transform.RebaseToQiskit().apply(c)
qc = tk_to_qiskit(c)
qobj = assemble(qc)
job = self._backend.run(qobj)
return job.result().get_unitary(qc)
|
https://github.com/zhangx1923/QISKit_Deve_Challenge
|
zhangx1923
|
# Import your solution function
from challenge_submission import compiler_function
# Import submission evaluation and scoring functions
from challenge_evaluation import evaluate, score
# Possibly useful other helper function
from challenge_evaluation import qasm_to_dag_circuit, load_coupling, get_layout
# Select the simulation backend to calculate the quantum states resulting from the circuits
# On Windows platform the C++ Simulator is not yet available with pip install
backend = 'local_qiskit_simulator'
#backend = 'local_qasm_simulator' # uncomment this line if you are a Windows user
# Load example circuits and coupling maps
ex_nr = 1 # examples to add per qubit number. maximum is 10 with the provided circuits
test_circuit_filenames = {}
for i in range(ex_nr):
test_circuit_filenames['circuits/random%d_n5_d5.qasm' % i] = get_layout(5)
for i in range(ex_nr):
test_circuit_filenames['circuits/random%d_n16_d16.qasm' % i] = get_layout(16)
for i in range(ex_nr):
test_circuit_filenames['circuits/random%d_n20_d20.qasm' % i] = get_layout(20)
# store circuit, coupling map pairs in test_circuits. Circuits are in qasm form.
test_circuits = {}
for filename, cmap in test_circuit_filenames.items():
with open(filename, 'r') as infile:
qasm = infile.read()
test_circuits[filename] = {"qasm": qasm, "coupling_map": cmap}
result = evaluate(compiler_function, test_circuits, verbose=True, backend = backend)
result
test_circuits['circuits/random0_n5_d5.qasm'].keys()
myres = score(compiler_function, backend = backend)
print("Your compiler scored %6.5f x better \
and was %6.5f x faster than the QISKit reference compiler." % myres)
# import some coupling map generation functions
from gencoupling import *
# generate a square coupling map with 18 qubits and nearest neighbour connectivity
# then remove 4 random links
# also try linear, circle, rect, torus, ibmqx etc.
lr = rect(6,3,order = 0.5, defects = -4)
plot_layout(lr)
# save the coupling map in the layouts folder
lr["name"] = "random_rectangular_lattice_4_defects_q18"
save_coupling(lr)
# load the saved coupling by name
rr = load_coupling("random_rectangular_lattice_4_defects_q18")
rr["coupling_map"]
plot_layout(lr)
# if your working directory is the folder with this notebook you can also use
import os
mydir = os.curdir
os.chdir('circuits')
!python generator.py -n 17 -d 17
os.chdir(mydir)
with open('random0_n17_d17.qasm', 'r') as infile:
qasm = infile.read()
print(qasm)
|
https://github.com/GroenteLepel/qiskit-quantum-knn
|
GroenteLepel
|
import numpy as np
import qiskit as qk
from qiskit.utils import QuantumInstance
import pytest
from qiskit_quantum_knn.qknn import QKNeighborsClassifier
def test_get_all_contrasts():
assert True
def test_calculate_fidelities():
ex_counts = {
'00 0': 10,
'00 1': 1,
'01 0': 20,
'01 1': 1,
'10 0': 15,
'10 1': 3,
'11 0': 2,
'11 1': 4,
}
fidelities = QKNeighborsClassifier.calculate_fidelities(ex_counts)
print(fidelities)
# no physically correct fidelities but
np.testing.assert_allclose(
fidelities,
[0.78826531, 1.01785714, 0.66326531, 0.24489796]
)
def test_calculate_contrasts():
assert True
def test_setup_control_counts():
assert True
def test_majority_vote_voting():
qknn = QKNeighborsClassifier(n_neighbors=3)
example_fidelities = np.array([
[0.1, 0.9, 0.1, 0.9],
[0.9, 0.1, 0.9, 0.1],
])
example_labels = np.array([-1, 1, -1, 1])
votes = qknn.majority_vote(
labels=example_labels,
fidelities=example_fidelities
)
np.testing.assert_array_equal(votes, [1, -1])
@pytest.mark.parametrize(
"n_train_states,n_test_states,n_qubit_states",
[(8, 1, 8), (8, 8, 8), (5, 8, 8)]
)
def test_majority_vote_result_shape(n_train_states: int,
n_test_states: int,
n_qubit_states: int):
qknn = QKNeighborsClassifier(n_neighbors=3)
example_fidelities = np.random.rand(n_test_states, n_qubit_states)
example_labels = np.random.choice(
[-1, 1],
n_train_states
)
votes = qknn.majority_vote(
labels=example_labels,
fidelities=example_fidelities
)
assert votes.shape == (n_test_states,)
def test_qknn():
backend = qk.BasicAer.get_backend('qasm_simulator')
instance = QuantumInstance(backend, shots=10000)
# initialising the qknn model
qknn = QKNeighborsClassifier(
n_neighbors=3,
quantum_instance=instance
)
train_data = [
[1/np.sqrt(2), 1/np.sqrt(2), 0, 0],
[1/np.sqrt(2), 1/np.sqrt(2), 0, 0],
[0, 0, 1/np.sqrt(2), 1/np.sqrt(2)],
[0, 0, 1/np.sqrt(2), 1/np.sqrt(2)]
]
train_labels = [
1,
1,
-1,
-1
]
test_data = [
[1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0],
[0, 0, 1 / np.sqrt(2), 1 / np.sqrt(2)]
]
qknn.fit(train_data, train_labels)
qknn_prediction = qknn.predict(test_data)
np.testing.assert_array_equal(qknn_prediction, [1, -1])
|
https://github.com/brhn-4/CMSC457
|
brhn-4
|
from qutip import *
# 5-qubit system
N = 5
identity = qeye(2)
X = sigmax()
Y = sigmay()
Z = sigmaz()
def pauli_i(N, i, pauli):
# pauli: X Y Z
tmp = [identity for m in range(N)]
tmp[i]=pauli
return tensor(tmp)
n=3
paulix_n = pauli_i(N, n, X)
H0 = 0
for n in range(N):
H0 += pauli_i(N, n, X)
H0 = -0.5*H0
H1 = 0
for n in range(N-1):
H1 += 0.1 * pauli_i(N, n, Z) * pauli_i(N, n+1, Y)
import numpy as np
def H1_coeff(t, args):
return 9 * np.exp(-(t / 5.) ** 2)
H = [H0, [H1, H1_coeff]]
t = [0.5, 0.6]
psi0 = tensor([basis(2, 1)] + [basis(2,0) for i in range(N-1)]) # Define initial state
output = mesolve(H, psi0, t)
print(output)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Kraus, SuperOp
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,
pauli_error, depolarizing_error, thermal_relaxation_error)
# Construct a 1-qubit bit-flip and phase-flip errors
p_error = 0.05
bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])
phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])
print(bit_flip)
print(phase_flip)
# Compose two bit-flip and phase-flip errors
bitphase_flip = bit_flip.compose(phase_flip)
print(bitphase_flip)
# Tensor product two bit-flip and phase-flip errors with
# bit-flip on qubit-0, phase-flip on qubit-1
error2 = phase_flip.tensor(bit_flip)
print(error2)
# Convert to Kraus operator
bit_flip_kraus = Kraus(bit_flip)
print(bit_flip_kraus)
# Convert to Superoperator
phase_flip_sop = SuperOp(phase_flip)
print(phase_flip_sop)
# Convert back to a quantum error
print(QuantumError(bit_flip_kraus))
# Check conversion is equivalent to original error
QuantumError(bit_flip_kraus) == bit_flip
# Measurement miss-assignement probabilities
p0given1 = 0.1
p1given0 = 0.05
ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]])
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates
error = depolarizing_error(0.05, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
# Print noise model info
print(noise_model)
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only
error = depolarizing_error(0.05, 1)
noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0])
# Print noise model info
print(noise_model)
# System Specification
n_qubits = 4
circ = QuantumCircuit(n_qubits)
# Test Circuit
circ.h(0)
for qubit in range(n_qubits - 1):
circ.cx(qubit, qubit + 1)
circ.measure_all()
print(circ)
# Ideal simulator and execution
sim_ideal = AerSimulator()
result_ideal = sim_ideal.run(circ).result()
plot_histogram(result_ideal.get_counts(0))
# Example error probabilities
p_reset = 0.03
p_meas = 0.1
p_gate1 = 0.05
# QuantumError objects
error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)])
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)])
error_gate2 = error_gate1.tensor(error_gate1)
# Add errors to noise model
noise_bit_flip = NoiseModel()
noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset")
noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure")
noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"])
print(noise_bit_flip)
# Create noisy simulator backend
sim_noise = AerSimulator(noise_model=noise_bit_flip)
# Transpile circuit for noisy basis gates
circ_tnoise = transpile(circ, sim_noise)
# Run and get counts
result_bit_flip = sim_noise.run(circ_tnoise).result()
counts_bit_flip = result_bit_flip.get_counts(0)
# Plot noisy output
plot_histogram(counts_bit_flip)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
# Run the noisy simulation
sim_thermal = AerSimulator(noise_model=noise_thermal)
# Transpile circuit for noisy basis gates
circ_tthermal = transpile(circ, sim_thermal)
# Run and get counts
result_thermal = sim_thermal.run(circ_tthermal).result()
counts_thermal = result_thermal.get_counts(0)
# Plot noisy output
plot_histogram(counts_thermal)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can choose different colors for the real and imaginary parts of the density matrix.
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)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
|
https://github.com/maryrbarros2/QuantumAlgorithms_Qiskit
|
maryrbarros2
|
from qiskit import QuantumCircuit, assemble, Aer
from qiskit.visualization import plot_histogram
from qiskit_textbook.widgets import binary_widget
binary_widget(nbits=6)
n = 8
n_q = n #number of qubits in the circuit.
n_b = n #number of output bits we will extract from the circuit at the end.
qc_output = QuantumCircuit(n_q,n_b)
#adding a measure operation to each of our eight qubits
#.measure(j,j): adds a measurement to our circuit that tells qubit j to write an output to bit j
for j in range(n):
qc_output.measure(j,j)
#Visualing the circuit
qc_output.draw()
sim = Aer.get_backend('aer_simulator') # this is the simulator we'll use
qobj = assemble(qc_output) # this turns the circuit into an object our backend can run
result = sim.run(qobj).result() # we run the experiment and get the result from that experiment
# from the results, we get a dictionary containing the number of times (counts)
# each result appeared
counts = result.get_counts()
# and display it on a histogram
plot_histogram(counts)
#NOT gate - i.e., X quantum gate
qc_encode = QuantumCircuit(n) #creating a quantum circuit of n qbits
qc_encode.x(7) #applying x gate into the 7th qubit
qc_encode.draw() #drawing the circuit
#obs: remember here that we already setted n = 8.
#creating a new circuit that contains the n qbits + the measuremnt part
qc = qc_encode + qc_output
qc.draw()
#running and ploting the results
qobj = assemble(qc)
counts = sim.run(qobj).result().get_counts()
plot_histogram(counts)
#### Exercice: trying a new number: 36 = 100100
qc_encode2 = QuantumCircuit(6)
qc_encode2.x(2)
qc_encode2.x(5)
qc_encode2.draw()
n_q = 6 #number of qubits in the circuit.
n_b = 6 #number of output bits we will extract from the circuit at the end.
qc_output2 = QuantumCircuit(n_q,n_b)
for j in range(6):
qc_output2.measure(j,j)
qc_output2.draw()
qc2 = qc_encode2 + qc_output2
qc2.draw()
qobj2 = assemble(qc_output2) # this turns the circuit into an object our backend can run
result2 = sim.run(qobj2).result() # we run the experiment and get the result from that experiment
# from the results, we get a dictionary containing the number of times (counts)
# each result appeared
counts2 = result2.get_counts()
# and display it on a histogram
plot_histogram(counts2)
qobj2 = assemble(qc2)
counts2 = sim.run(qobj2).result().get_counts()
plot_histogram(counts2)
qc_cnot = QuantumCircuit(2) #quantum circuit of 2 qubits
qc_cnot.cx(0,1) #cnot between qubits 0 and 1
qc_cnot.draw() #draw the circuit
qc = QuantumCircuit(2,2)
qc.x(0) #apply x on qubit 0; It becomes 1
qc.cx(0,1) #apply cnot between qbit 0 and 1
qc.measure(0,0)
qc.measure(1,1)
qc.draw()
qobja = assemble(qc) # this turns the circuit into an object our backend can run
resulta = sim.run(qobja).result() # we run the experiment and get the result from that experiment
# from the results, we get a dictionary containing the number of times (counts)
# each result appeared
countsa = resulta.get_counts()
# and display it on a histogram
plot_histogram(countsa)
qc_ha = QuantumCircuit(4,2)
# encode inputs in qubits 0 and 1
qc_ha.x(0) # For a=0, remove the this line. For a=1, leave it.
qc_ha.x(1) # For b=0, remove the this line. For b=1, leave it.
qc_ha.barrier()
# use cnots to write the XOR of the inputs on qubit 2
qc_ha.cx(0,2)
qc_ha.cx(1,2)
# use ccx to write the AND of the inputs on qubit 3
qc_ha.ccx(0,1,3)
qc_ha.barrier()
# extract outputs
qc_ha.measure(2,0) # extract XOR value
qc_ha.measure(3,1) # extract AND value
qc_ha.draw()
qobj = assemble(qc_ha)
counts = sim.run(qobj).result().get_counts()
plot_histogram(counts)
|
https://github.com/yatharth0610/Quantum-Algorithms-qiskit-
|
yatharth0610
|
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()
# The '0' state
plot_bloch_vector([0,0,1])
# The '1' state
plot_bloch_vector([0,0,-1])
qc1 = QuantumCircuit(2,2) # Initializing a quantum ciruit (2 qubits, 2 classical bits)
# All initialized to '0' by default.
qc1.draw(output='mpl') # Draws the circuit diagram
qc1.x(0) # Applying X gate to the first qubit
qc1.draw(output='mpl')
qc1.x(1) # Applying X gate to the second qubit
qc1.draw(output='mpl')
# The '+' state
plot_bloch_vector([1,0,0])
# The '-' state
plot_bloch_vector([-1,0,0])
qc2 = QuantumCircuit(2,2) # A new quantum circuit with 2 qubits and 2 classical bits
qc2.h(0) # Applying the Hadamard gate on first qubit
qc2.draw(output='mpl')
qc2.cx(0,1) # Applying CX gate ('control','target')
qc2.draw(output='mpl')
qc2.measure(0,0) # Measure first qubit and store it in first classical bit
qc2.measure(1,1) # Measure second qubit and store it in second classical bit
# The code below plots a histogram of the measurement result. You can copy it for further use.
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc2)
print(counts)
plot_histogram(counts)
qc1.h(0)
qc1.cx(0, 1)
qc1.draw(output='mpl')
qc1.measure(0,0)
qc1.measure(1,1)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc1)
print(counts)
plot_histogram(counts)
qc3 = QuantumCircuit(3,3)
qc3.x(range(3)) # Setting the all qubits to '1'
qc3.toffoli(0,1,2) # (control,control,target)
qc3.measure(0,0)
qc3.measure(1,1)
qc3.measure(2,2)
def run_circuit(qc3):
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
result = execute(qc3, backend, shots = 2000).result() # we run the simulation
counts = result.get_counts() # we get the counts
return counts
counts = run_circuit(qc3)
print(counts)
plot_histogram(counts)
# The output should be '011' as the highest (q2) is flipped because the other two qubits were set to '1'
qc4 = QuantumCircuit(2,2)
#Applying the Pauli-X gate to quantum bit 0, we turn it into 1 so that the swap outcome is observable.
qc4.x(0)
qc4.cx(0, 1)
qc4.cx(1, 0)
qc4.cx(0, 1)
qc4.draw(output='mpl')
qc4.measure(0,0)
qc4.measure(1,1)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc4)
print(counts)
plot_histogram(counts)
qc5 = QuantumCircuit(2,2)
#We turn quantum bit 1 into 1 so that we can observe the results of HZH on both 0 (from q0) and 1 (from q1).
qc5.x(1)
qc5.h((0, 1))
qc5.z((0, 1))
qc5.h((0, 1))
qc5.draw(output='mpl')
qc5.measure(0,0)
qc5.measure(1,1)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc5)
print(counts)
plot_histogram(counts)
qc6 = QuantumCircuit(3,3)
#Initializing quantum bits using gates:
#q0 is initialized to 0.
#q1 is initialized to 1.
qc6.x(1)
#q2 is initialized to the state given above.
qc6.x(2)
qc6.h(2)
qc6.t(2)
#We change q2 for the controlled swap now; we'll bring it back to the same state afterwards.
qc6.tdg(2)
qc6.h(2)
#Controlled swap.
qc6.toffoli(0, 2, 1)
qc6.toffoli(1, 2, 0)
qc6.toffoli(0, 2, 1)
#We convert q2 back to whatever it was.
qc6.h(2)
qc6.t(2)
qc6.draw(output='mpl')
qc6.measure(0, 0)
qc6.measure(1, 1)
qc6.measure(2, 2)
def run_circuit(qc):
backend = Aer.get_backend('qasm_simulator')
result = execute(qc, backend, shots = 2000).result()
counts = result.get_counts()
return counts
counts = run_circuit(qc6)
print(counts)
plot_histogram(counts)
|
https://github.com/QuSTaR/kaleidoscope
|
QuSTaR
|
# -*- coding: utf-8 -*-
# This file is part of Kaleidoscope.
#
# (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.
# pylint: disable=invalid-unary-operand-type, consider-using-generator
"""CNOT error density plot"""
import numpy as np
from scipy.stats import gaussian_kde
import matplotlib as mpl
import matplotlib.pyplot as plt
from qiskit.providers.models.backendproperties import BackendProperties
from kaleidoscope.colors import COLORS1, COLORS2, COLORS3, COLORS4, COLORS5, COLORS14
from kaleidoscope.errors import KaleidoscopeError
from kaleidoscope.qiskit.backends.pseudobackend import properties_to_pseudobackend
def cnot_error_density(backends,
figsize=None,
colors=None,
offset=None,
scale='log',
covariance_factor=0.1,
xlim=None,
text_xval=None,
xticks=None):
"""Plot CNOT error distribution for one or more IBMQ backends.
Parameters:
backends (list or IBMQBackend or BackendProperties): A single or ist of IBMQBackend
instances or properties.
figsize (tuple): Optional figure size in inches.
colors (list): A list of Matplotlib compatible colors to plot with.
offset (float): Positive offset for spacing out the backends.
scale (str): 'linear' or 'log' scaling of x-axis.
covariance_factor (float): Sets the width of the gaussian for each point.
xlim (list or tuple): Optional lower and upper limits of cnot error values.
text_xval (float): Optional xaxis value at which to start the backend text.
xticks (list): Optional list of xaxis ticks to plot.
Returns:
Figure: A matplotlib Figure instance.
Raises:
KaleidoscopeError: A backend with < 2 qubits was passed.
KaleidoscopeError: Number of colors did not match number of backends.
Example:
.. jupyter-execute::
from qiskit import *
from kaleidoscope.qiskit.backends import cnot_error_density
provider = IBMQ.load_account()
backends = []
backends.append(provider.backends.ibmq_vigo)
backends.append(provider.backends.ibmq_ourense)
backends.append(provider.backends.ibmq_valencia)
backends.append(provider.backends.ibmq_santiago)
cnot_error_density(backends)
"""
if not isinstance(backends, list):
backends = [backends]
for idx, back in enumerate(backends):
if isinstance(back, BackendProperties):
backends[idx] = properties_to_pseudobackend(back)
for back in backends:
if back.configuration().n_qubits < 2:
raise KaleidoscopeError('Number of backend qubits must be > 1')
if scale not in ['linear', 'log']:
raise KaleidoscopeError("scale must be 'linear' or 'log'.")
# Attempt to autosize if figsize=None
if figsize is None:
if len(backends) > 1:
fig = plt.figure(figsize=(12, len(backends)*1.5))
else:
fig = plt.figure(figsize=(12, 2))
else:
fig = plt.figure(figsize=figsize)
text_color = 'k'
if offset is None:
offset = 100 if len(backends) > 3 else 200
offset = -offset
if colors is None:
if len(backends) == 1:
colors = COLORS1
elif len(backends) == 2:
colors = COLORS2
elif len(backends) == 3:
colors = COLORS3
elif len(backends) == 4:
colors = COLORS4
elif len(backends) == 5:
colors = COLORS5
else:
colors = [COLORS14[kk % 14] for kk in range(len(backends))]
else:
if len(colors) != len(backends):
raise KaleidoscopeError('Number of colors does not match number of backends.')
cx_errors = []
for idx, back in enumerate(backends):
back_props = back.properties().to_dict()
cx_errs = []
meas_errs = []
for gate in back_props['gates']:
if len(gate['qubits']) == 2:
# Ignore cx gates with values of 1.0
if gate['parameters'][0]['value'] != 1.0:
cx_errs.append(gate['parameters'][0]['value'])
for qubit in back_props['qubits']:
for item in qubit:
if item['name'] == 'readout_error':
meas_errs.append(item['value'])
cx_errors.append(100*np.asarray(cx_errs))
max_cx_err = max([cerr.max() for cerr in cx_errors])
min_cx_err = min([cerr.min() for cerr in cx_errors])
if xlim is None:
if scale == 'linear':
xlim = [0, 1.5*max_cx_err]
else:
xlim = [10**np.floor(np.log10(min_cx_err)),
10**np.ceil(np.log10(max_cx_err))]
if text_xval is None:
if scale == 'linear':
text_xval = 0.8*xlim[1]
else:
text_xval = 0.6*xlim[1]
for idx, back in enumerate(backends):
cx_density = gaussian_kde(cx_errors[idx])
xs = np.linspace(xlim[0], xlim[1], 2500)
cx_density.covariance_factor = lambda: covariance_factor
cx_density._compute_covariance()
if scale == 'linear':
plt.plot(xs, 100*cx_density(xs)+offset*idx, zorder=idx, color=colors[idx])
else:
plt.semilogx(xs, 100*cx_density(xs)+offset*idx, zorder=idx, color=colors[idx])
plt.fill_between(xs, offset*idx,
100*cx_density(xs)+offset*idx, zorder=idx, color=colors[idx])
qv_val = back.configuration().quantum_volume
if qv_val:
qv = "(QV"+str(qv_val)+")"
else:
qv = ''
bname = back.name().split('_')[-1].title()+" {}".format(qv)
plt.text(text_xval, offset*idx+0.2*(-offset), bname, fontsize=20, color=colors[idx])
fig.axes[0].get_yaxis().set_visible(False)
# get rid of the frame
for spine in plt.gca().spines.values():
spine.set_visible(False)
if xticks is None:
if scale == 'linear':
xticks = np.round(np.linspace(xlim[0], xlim[1], 4), 2)
else:
xticks = np.asarray(xticks)
if xticks is not None:
plt.xticks(np.floor(xticks), labels=np.floor(xticks), color=text_color)
plt.xticks(fontsize=18)
plt.xlim(xlim)
plt.tick_params(axis='x', colors=text_color)
plt.xlabel('Gate Error', fontsize=18, color=text_color)
plt.title('CNOT Error Distributions', fontsize=18, color=text_color)
fig.tight_layout()
if mpl.get_backend() in ["module://ipykernel.pylab.backend_inline",
"module://matplotlib_inline.backend_inline",
"nbAgg"]:
plt.close(fig)
return fig
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import datetime
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.rcParams.update({"text.usetex": True})
plt.rcParams["figure.figsize"] = (6,4)
mpl.rcParams["figure.dpi"] = 200
from qiskit_ibm_runtime import Estimator, Session, QiskitRuntimeService, Options
from qiskit.quantum_info import SparsePauliOp
from qiskit import QuantumCircuit
service = QiskitRuntimeService()
backend_simulator = "backend_simulator"
backend = "ibmq_montreal"
qubits = 4
trotter_layer = QuantumCircuit(qubits)
trotter_layer.rx(0.1, range(qubits))
trotter_layer.cx(0, 1)
trotter_layer.cx(2, 3)
trotter_layer.rz(-0.2, [1, 3])
trotter_layer.cx(0, 1)
trotter_layer.cx(2, 3)
trotter_layer.cx(1, 2)
trotter_layer.rz(-0.2, 2)
trotter_layer.cx(1, 2)
num_steps = 6
trotter_circuit_list = []
for i in range(1, num_steps):
trotter_circuit = QuantumCircuit(qubits)
for _ in range(i):
trotter_circuit = trotter_circuit.compose(trotter_layer)
trotter_circuit_list.append(trotter_circuit)
print(f'Trotter circuit with {i} Trotter steps`)
display(trotter_circuit.draw(fold=-1))
obs = SparsePauliOp("Z"*qubits)
obs_list = [obs]*len(trotter_circuit_list)
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 0 # No mitigation
with Session(service=service, backend=backend_simulator) as session:
estimator_sim = Estimator(session=session, options=options)
job_sim = estimator_sim.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_sim.job_id)
print(job_sim.result())
expvals_ideal = job_sim.result().values
expvals_ideal_variance = [metadata['variance']/metadata['shots'] for metadata in job_sim.result().metadata]
std_error_ideal = np.sqrt(expvals_ideal_variance)
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 0 # No error mitigation
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job.job_id)
print(job.result())
expvals_unmit = job.result().values
expvals_unmit_variance = [metadata['variance']/metadata['shots'] for metadata in job.result().metadata]
std_error_unmit = np.sqrt(expvals_unmit_variance)
options = Options()
options.execution.shots = 1000
options.optimization_level = 3 # Dynamical decoupling
options.resilience_level = 0 # No error mitigation
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_dd = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_dd.job_id)
print(job_dd.result())
expvals_unmit_dd = job_dd.result().values
expvals_unmit_dd_variance = [metadata['variance']/metadata['shots'] for metadata in job_dd.result().metadata]
std_error_dd = np.sqrt(expvals_unmit_dd_variance)
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_dd, std_error_dd, fmt = 'o', linestyle = '-', capsize=4, c='blue', label='Dynamical decoupling')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.resilience_level = 1 # T-REx
options.optimization_level = 0 # No optimization
options.execution.shots = 1000
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_trex = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_trex.job_id)
print(job_trex.result())
expvals_unmit_trex = job_trex.result().values
expvals_unmit_trex_variance = [metadata['variance']/metadata['shots'] for metadata in job_trex.result().metadata]
std_error_trex = np.sqrt(expvals_unmit_trex_variance)
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # No optimization
options.resilience_level = 2 # ZNE
with Session(service=service, backend=backend) as session:
estimator = Estimator(session=session, options=options)
job_zne = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_zne.job_id)
print(job_zne.result())
expvals_unmit_zne = job_zne.result().values
# Standard error: coming soon!
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE')
plt.xlabel('No. Trotter Steps')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
def interim_results_callback(job_id, result):
now = datetime.datetime.now()
print(now, "*** Callback ***", result, "\n")
options = Options()
options.optimization_level = 0 # No optimization
options.execution.shots = 100
options.resilience_level = 3 # PEC
options.environment.callback = interim_results_callback
with Session(service=service, backend=backend) as session:
estimator_pec = Estimator(session=session, options=options)
job_pec = estimator_pec.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_pec.job_id)
expvals_pec = job_pec.result().values
std_error_pec = [metadata['standard_error'] for metadata in job_pec.result().metadata]
plt.title('Trotter circuits expectation value')
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
print(job_pec.result())
pec_metadata = job_pec.result().metadata
fig, ax = plt.subplots()
fig.subplots_adjust(right=0.75)
twin1 = ax.twinx()
twin2 = ax.twinx()
twin3 = ax.twinx()
twin2.spines.right.set_position(("axes", 1.2))
twin3.spines.right.set_position(("axes", 1.4))
p1, = ax.plot(range(1, num_steps), [m["total_mitigated_layers"] for m in pec_metadata] , "b-", label="Total mitigated layers")
p2, = twin1.plot(range(1, num_steps), [m["sampling_overhead"] for m in pec_metadata], "r-", label="Sampling overhead")
p3, = twin2.plot(range(1, num_steps), [m["samples"] for m in pec_metadata], "g-", label="Samples")
p4, = twin3.plot(range(1, num_steps), [m["shots"] for m in pec_metadata], "c-", label="Shots")
ax.set_ylim(0, 20)
twin1.set_ylim(0, 2.8)
twin2.set_ylim(0, 300)
twin3.set_ylim(0, 35000)
ax.set_xlabel("No. Trotter Steps")
ax.set_ylabel("Total mitigated layers")
twin1.set_ylabel("Sampling overhead")
twin2.set_ylabel("Samples")
twin3.set_ylabel("Shots")
ax.yaxis.label.set_color(p1.get_color())
twin1.yaxis.label.set_color(p2.get_color())
twin2.yaxis.label.set_color(p3.get_color())
twin3.yaxis.label.set_color(p4.get_color())
tkw = dict(size=4, width=1.5)
ax.tick_params(axis='y', colors=p1.get_color(), **tkw)
twin1.tick_params(axis='y', colors=p2.get_color(), **tkw)
twin2.tick_params(axis='y', colors=p3.get_color(), **tkw)
twin3.tick_params(axis='y', colors=p4.get_color(), **tkw)
plt.xticks([1, 2, 3, 4, 5])
ax.legend(handles=[p1, p2, p3, p4])
plt.title('PEC metadata')
plt.show()
from matplotlib.pyplot import figure
plt.errorbar(range(1, num_steps), expvals_ideal, std_error_ideal, fmt = 'o', linestyle = '--', capsize=4, c='red', label='Ideal')
plt.errorbar(range(1, num_steps), expvals_unmit, std_error_unmit, fmt = 'o', linestyle = '-', capsize=4, c='green', label='No mitigation')
plt.errorbar(range(1, num_steps), expvals_unmit_trex, std_error_trex, fmt = 'o', linestyle = '-', capsize=4, c='violet', label='T-REx')
plt.errorbar(range(1, num_steps), expvals_unmit_zne, [0]*(num_steps-1), fmt = 'o', linestyle = '-', capsize=4, c='cyan', label='ZNE')
plt.errorbar(range(1, num_steps), expvals_pec, std_error_pec, fmt = 'd', linestyle = '-', capsize=4, c='orange', label='PEC')
plt.title('Trotter circuits expectation value')
plt.ylabel(f"$\langle ZZZZ \\rangle$")
plt.xlabel('No. Trotter Steps')
plt.xticks([1, 2, 3, 4, 5])
plt.legend()
plt.show()
options = Options()
options.execution.shots = 1000
options.optimization_level = 0 # no optimization
options.resilience_level = 2 # ZNE
options.resilience.noise_factors = [1, 2, 3, 4]
options.resilience.noise_amplifier = "LocalFoldingAmplifier"
options.resilience.extrapolator = "QuadraticExtrapolator"
with Session(service=service, backend='ibmq_montreal') as session:
estimator = Estimator(session=session, options=options)
job_zne_options = estimator.run(circuits=trotter_circuit_list, observables=obs_list)
print('job id:', job_zne_options.job_id)
print(job_zne_options.result())
from qiskit.tools import jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import json
from typing import Any, Callable, Optional, Tuple, Union
from urllib.parse import urljoin
from qiskit import QuantumCircuit, execute
from qiskit.providers import JobStatus
from qiskit.providers.ibmq.job import IBMQJob
from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint
from .exercises import get_question_id
from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate
def _circuit_criteria(
circuit: QuantumCircuit,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[int], Optional[int]]:
if max_qubits is not None and circuit.num_qubits > max_qubits:
print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.')
print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.')
return None, None
try:
if check_gates and not uses_multiqubit_gate(circuit):
print('Your circuit appears to not use any multi-quibit gates.')
print('Please review your circuit and try again.')
return None, None
cost = compute_cost(circuit)
if min_cost is not None and cost < min_cost:
print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n'
'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.')
return None, None
return circuit.num_qubits, cost
except Exception as err:
print(f'Unable to compute cost: {err}')
return None, None
def _circuit_grading(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
payload = None
server = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or '
'the grading servers are down right now.')
return None, None
else:
server = None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
payload = {
'answer': circuit_to_json(circuit)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _job_grading(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str):
print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}')
print(f'Please submit a job as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading '
'servers are down right now.')
return None, None
else:
server = None
job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id
if not job:
print('An invalid or non-existent job was specified.')
return None, None
job_status = job.status()
if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]:
print(f'Job did not successfully complete: {job_status.value}.')
return None, None
elif job_status is not JobStatus.DONE:
print(f'Job has not yet completed: {job_status.value}.')
print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.')
return None, None
header = job.result().header.to_dict()
if 'qc_cost' not in header:
if is_submit:
print('An unprepared answer was specified. '
'Please prepare() and grade() answer before submitting.')
else:
print('An unprepared answer was specified. Please prepare() answer before grading.')
return None, None
download_url, result_url = get_job_urls(job)
if not download_url or not result_url:
print('Unable to obtain job URLs')
return None, None
payload = {
'answer': json.dumps({
'download_url': download_url,
'result_url': result_url
})
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _number_grading(
answer: int,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(answer, int):
print(f'Expected a integer, but was given {type(answer)}')
print(f'Please provide a number as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server '
'or the grading servers are down right now.')
return None, None
else:
server = None
payload = {
'answer': str(answer)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def prepare_circuit(
circuit: QuantumCircuit,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit.')
return None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiment. Please wait...')
job = execute(
circuit,
qobj_header={
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def prepare_solver(
solver_func: Callable,
lab_id: str,
ex_id: str,
problem_set: Optional[Any] = None,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not callable(solver_func):
print(f'Expected a function, but was given {type(solver_func)}')
print(f'Please provide a function that returns a QuantumCircuit.')
return None
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading servers are down right now.')
return
endpoint = server + 'problem-set'
index, value = get_problem_set(lab_id, ex_id, endpoint)
print(f'Running {solver_func.__name__}...')
qc_1 = solver_func(problem_set)
_, cost = _circuit_criteria(
qc_1,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if value and index is not None and index >= 0 and cost is not None:
qc_2 = solver_func(value)
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiments. Please wait...')
job = execute(
[qc_1, qc_2],
qobj_header={
'qc_index': [None, index],
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def grade_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, server = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=False,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_job(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str
) -> bool:
payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def submit_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, _ = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=True,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_job(
job_or_id: IBMQJob,
lab_id: str,
ex_id: str,
) -> bool:
payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def get_problem_set(
lab_id: str, ex_id: str, endpoint: str
) -> Tuple[Optional[int], Optional[Any]]:
problem_set_response = None
try:
payload = {'question_id': get_question_id(lab_id, ex_id)}
problem_set_response = send_request(endpoint, query=payload, method='GET')
except Exception as err:
print('Unable to obtain the problem set')
if problem_set_response:
status = problem_set_response.get('status')
if status == 'valid':
try:
index = problem_set_response.get('index')
value = json.loads(problem_set_response.get('value'))
return index, value
except Exception as err:
print(f'Problem set could not be processed: {err}')
else:
cause = problem_set_response.get('cause')
print(f'Problem set failed: {cause}')
return None, None
def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool:
try:
answer_response = send_request(endpoint, body=payload)
status = answer_response.get('status', None)
cause = answer_response.get('cause', None)
score = cost if cost else answer_response.get('score', None)
handle_grade_response(status, score=score, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def submit_answer(payload: dict) -> bool:
try:
access_token = get_access_token()
baseurl = get_submission_endpoint()
endpoint = urljoin(baseurl, './challenges/answers')
submit_response = send_request(
endpoint,
body=payload,
query={'access_token': access_token}
)
status = submit_response.get('status', None)
if status is None:
status = submit_response.get('valid', None)
cause = submit_response.get('cause', None)
handle_submit_response(status, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def handle_grade_response(
status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None
) -> None:
if status == 'valid':
print('\nCongratulations 🎉! Your answer is correct.')
if score is not None:
print(f'Your score is {score}.')
elif status == 'invalid':
print(f'\nOops 😕! {cause}')
print('Please review your answer and try again.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete then try again.')
else:
print(f'Failed: {cause}')
print('Unable to grade your answer.')
def handle_submit_response(
status: Union[str, bool], cause: Optional[str] = None
) -> None:
if status == 'valid' or status is True:
print('\nSuccess 🎉! Your answer has been submitted.')
elif status == 'invalid' or status is False:
print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}')
print('Make sure your answer is correct and successfully graded before submitting.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete, grade it, and then try to submit again.')
else:
print(f'Failed: {cause}')
print('Unable to submit your answer at this time.')
|
https://github.com/hephaex/Quantum-Computing-Awesome-List
|
hephaex
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
### Creating 3 qubit and 2 classical bits in each separate register
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
### A third party eve helps to create an entangled state
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, a, b):
qc.cx(a, b)
qc.h(a)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
teleportation_circuit.barrier()
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit.extensions import Initialize
import math
qc = QuantumCircuit(1)
initial_state = [0,1]
init_gate = Initialize(initial_state)
# qc.append(initialize_qubit, [0])
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
from qiskit import IBMQ
IBMQ.save_account('### IMB TOKEN ')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
https://github.com/IlliaOvcharenko/quantum-search
|
IlliaOvcharenko
|
import sys, os
sys.path.append(os.getcwd())
import matplotlib
matplotlib.use('Agg')
import math
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import (QiskitRuntimeService,
SamplerV2 as Sampler)
from fire import Fire
def main()
ibm_token = open("credentials/ibm-token.txt").read().replace("\n", "")
ibm_quantum_service = QiskitRuntimeService(channel="ibm_quantum", token=ibm_token)
array = [4, 7, 2, 1, 3]
# item = 5 # answer should be 6
# item = 4 # answer should be 0
item = 2 # answer should be 5
# array = [4, 7, 2, 1, 3, 0, 5, 6]
# # item = 5 # answer should be 6
# # item = 4 # answer should be 0
# item = 0 # answer should be 5
# array = np.arange(50)
# np.random.seed(42)
# np.random.shuffle(array)
# array = array.tolist()
# item = 10
print(f"Input array: {array}")
print(f"Item to search: {item}")
print(f"Answer: {array.index(item)}")
# evalue)
n_index_qbits = math.ceil(math.log(len(array), 2))
n_value_qbits = math.ceil(math.log(max(array), 2))
to_bits = lambda i: bin(i)[2:][::-1]
to_int = lambda b: int(b[::-1], 2)
# print(array)
# print([to_bits(v) for v in array])
# print([to_int(to_bits(v)) for v in array])
# exit(0)
index_qbits = [i for i in range(n_index_qbits)]
value_qbits = [i + n_index_qbits for i in range(n_value_qbits)]
phase_qbit = n_index_qbits + n_value_qbits
print(f"N qubits for index: {n_index_qbits}")
print(f"N qubits for value: {n_value_qbits}")
# n_grover_iterations = math.floor(math.sqrt(len(array)))
n_grover_iterations = 1
print(f"Num of grover iterations: {n_grover_iterations}")
# print(index_qbits)
# print(value_qbits)
# print(phase_qbit)
# exit(0)
qc = QuantumCircuit(
QuantumRegister(n_index_qbits, "index"),
QuantumRegister(n_value_qbits, "value"),
QuantumRegister(1, "phase"),
icr := ClassicalRegister(n_index_qbits, "meas-index"),
# ClassicalRegister(3, "meas-value"),
# pcr := ClassicalRegister(1, "meas-phase"),
)
# TODO hadamar for index
# TODO ket minus for phase
qc.h(index_qbits)
# qc.x(index_qbits[0])
# qc.x(index_qbits[1])
qc.x(phase_qbit)
qc.h(phase_qbit)
def add_oracle(global_qc):
qc = QuantumCircuit(
QuantumRegister(n_index_qbits, "index"),
QuantumRegister(n_value_qbits, "value"),
QuantumRegister(1, "phase"),
# vcr := ClassicalRegister(3, "meas-index"),
# ClassicalRegister(3, "meas-value"),
# pcr := ClassicalRegister(3, "meas-phase"),
)
for array_idx in range(len(array)):
# qc.barrier()
array_idx_bit = to_bits(array_idx)[:n_index_qbits]
array_idx_bit += "0" * (n_index_qbits - len(array_idx_bit))
array_item = array[array_idx]
array_item_bit = to_bits(array_item)[:n_value_qbits]
array_item_bit += "0" * (n_value_qbits - len(array_item_bit))
zeros = [index_qbits[i] for i, b in enumerate(array_idx_bit) if b == "0"]
ones = [value_qbits[i] for i, b in enumerate(array_item_bit) if b == "1"]
# print(array_idx)
# print(array_idx_bit)
# print(array_item)
# print(array_item_bit)
# print(zeros)
# print(ones)
# print()
for value_idx in ones:
if zeros:
qc.x(zeros)
qc.mcx(index_qbits, value_idx)
if zeros:
qc.x(zeros)
global_qc = global_qc.compose(qc)
item_bit = to_bits(item)
item_bit += "0" * (n_value_qbits - len(item_bit))
zeros = [value_qbits[i] for i, b in enumerate(item_bit) if b == "0"]
if zeros:
global_qc.x(zeros)
global_qc.mcx(value_qbits, phase_qbit)
if zeros:
global_qc.x(zeros)
global_qc = global_qc.compose(qc.inverse())
return global_qc
def add_diffuser(global_qc):
qc = QuantumCircuit(
QuantumRegister(n_index_qbits, "index"),
QuantumRegister(n_value_qbits, "value"),
QuantumRegister(1, "phase"),
)
qc.h(index_qbits)
qc.x(index_qbits)
qc.mcx(index_qbits, phase_qbit)
qc.x(index_qbits)
qc.h(index_qbits)
global_qc = global_qc.compose(qc)
return global_qc
for _ in range(n_grover_iterations):
qc = add_oracle(qc)
qc = add_diffuser(qc)
# qc.draw("mpl")
# plt.savefig("figs/oracle-qc.png", bbox_inches="tight")
# qc.h(phase_qbit)
qc.measure(index_qbits, icr)
qc.draw("mpl")
plt.savefig("figs/oracle-qc-array-8.png", bbox_inches="tight")
# qc = qc.measure_all(inplace=False)
# sampler = Sampler()
# job = sampler.run(qc, shots=64)
# result = job.result()
# print(max(result.quasi_dists[0].items(), key=lambda x: x[1]))
# print(result.quasi_dists[0][array.index(item)])
backend = ibm_quantum_service.get_backend("ibm_sherbrooke")
# backend = ibm_quantum_service.least_busy(operational=True, simulator=False)
print(f"Selected quantum computer: {backend}")
pm = generate_preset_pass_manager(backend=backend, optimization_level=1)
qc_opt = pm.run(qc)
# qc_opt.draw("mpl")
# plt.savefig("figs/oracle-qc-opt-array-8.png", bbox_inches="tight")
sampler = Sampler(backend=backend)
job = sampler.run([qc_opt], shots=5)
print(f"Job ID is {job.job_id()}")
# pub_result = job.result()[0]
# print(pub_result)
if __name__ == "__main__":
Fire(main)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
# 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.
# Copyright 2021 Dell (www.dell.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from dell_runtime import DellRuntimeProvider
from qiskit.providers.ibmq.runtime import RuntimeProgram, RuntimeJob, ResultDecoder
from qiskit import QuantumCircuit
import os
RUNTIME_PROGRAM = """
import random
from qiskit import transpile
from qiskit.circuit.random import random_circuit
def prepare_circuits(backend):
circuit = random_circuit(num_qubits=5, depth=4, measure=True,
seed=random.randint(0, 1000))
return transpile(circuit, backend)
def main(backend, user_messenger, **kwargs):
iterations = kwargs['iterations']
interim_results = kwargs.pop('interim_results', {})
final_result = kwargs.pop("final_result", {})
for it in range(iterations):
qc = prepare_circuits(backend)
# user_messenger.publish({"iteration": it, "interim_results": interim_results})
backend.run(qc).result()
user_messenger.publish(final_result, final=True)
"""
RUNTIME_PROGRAM_METADATA = {
"description": "Test program",
"max_execution_time": 300,
"backend_requirements": {"min_num_qubits": 5},
"parameters": [
{"name": "param1", "description": "Some parameter.",
"type": "integer", "required": True}
],
"return_values": [
{"name": "ret_val", "description": "Some return value.", "type": "string"}
],
"interim_results": [
{"name": "int_res", "description": "Some interim result", "type": "string"},
],
"name": "qiskit-test",
}
# PROGRAM_PREFIX = 'qiskit-test'
class EmulatorRuntimeServiceTest(unittest.TestCase):
def test_upload(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
proglist = provider.runtime.programs()
self.assertIsNotNone(proglist[program_id])
findProgId = False
if program_id in proglist:
findProgId = True
self.assertTrue(findProgId)
def test_runtime_backends(self):
provider = DellRuntimeProvider()
backends = provider.runtime.backends()
self.assertGreater(len(backends), 1)
def test_view_program(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
runtime_program = provider.runtime.program(program_id)
self.assertEqual(runtime_program.description, "Test program")
self.assertEqual(runtime_program.program_id, program_id)
def test_run_program(self):
provider = DellRuntimeProvider()
self.assertIsNotNone(provider)
self.assertIsNotNone(provider.runtime)
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
self.assertEqual(1, len(provider.runtime.programs()))
runtime_program = provider.runtime.program(program_id)
self.assertIsNotNone(runtime_program)
try:
job = provider.runtime.run(program_id, options=None, inputs={"iterations": 2})
result = job.result(timeout=120)
self.assertIsNotNone(result)
except Exception:
self.fail("should pass")
def test_programs(self):
provider = DellRuntimeProvider()
self.assertIsNotNone(provider)
self.assertIsNotNone(provider.runtime)
provider.runtime.upload_program("fake-program1", metadata=RUNTIME_PROGRAM_METADATA)
provider.runtime.upload_program("fake-program2", metadata=RUNTIME_PROGRAM_METADATA)
programs = provider.runtime.programs()
self.assertEqual(len(programs), 2)
def test_update_program(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
new_meta = {'description': 'Qiskit Test Update', 'max_execution_time': RUNTIME_PROGRAM_METADATA['max_execution_time']}
updated = provider.runtime.update_program(program_id, name='Test Update', metadata=new_meta)
self.assertTrue(updated)
program2 = provider.runtime.program(program_id, refresh=True)
self.assertEqual('Qiskit Test Update', program2.description)
self.assertEqual('Test Update', program2.name)
def test_pprint_programs(self):
provider = DellRuntimeProvider()
self.assertIsNotNone(provider)
self.assertIsNotNone(provider.runtime)
pr_id_1 = provider.runtime.upload_program("fake-program1", metadata=RUNTIME_PROGRAM_METADATA)
import sys
import io
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
provider.runtime.pprint_programs()
output = new_stdout.getvalue()
sys.stdout = old_stdout
self.assertTrue(output.startswith(
'''==================================================
{}:
Name: {}'''.format(pr_id_1,'qiskit-test')
))
def test_has_service(self):
provider = DellRuntimeProvider()
self.assertTrue(provider.has_service('runtime'))
self.assertFalse(provider.has_service('fake-service'))
def test_metadata(self):
provider = DellRuntimeProvider()
pr_id = provider.runtime.upload_program("fake-program1", metadata=RUNTIME_PROGRAM_METADATA)
program = provider.runtime.program(pr_id)
self.assertEqual('qiskit-test', program.name)
self.assertEqual(RUNTIME_PROGRAM_METADATA['description'], program.description)
self.assertEqual(RUNTIME_PROGRAM_METADATA['max_execution_time'],
program.max_execution_time)
self.assertEqual(RUNTIME_PROGRAM_METADATA['backend_requirements'],
program.backend_requirements)
def test_circuit_runner(self):
from . import circuit_runner as cr
try:
cr.main()
except Exception as e:
self.fail("should pass")
def test_dir_circuit_runner(self):
from . import dir_circuit_runner as dcr
try:
dcr.main()
except Exception as e:
self.fail("should pass")
def test_upload_file(self):
provider = DellRuntimeProvider()
self.assertIsNotNone(provider)
self.assertIsNotNone(provider.runtime)
here = os.path.dirname(os.path.realpath(__file__))
program_id = provider.runtime.upload_program(here + "/dirtest/", metadata=RUNTIME_PROGRAM_METADATA)
self.assertEqual(1, len(provider.runtime.programs()))
runtime_program = provider.runtime.program(program_id)
self.assertIsNotNone(runtime_program)
try:
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
result = job.result(timeout=120)
self.assertIsNotNone(result)
except Exception:
self.fail("should pass")
def test_reserved_names(self):
provider = DellRuntimeProvider()
self.assertIsNotNone(provider)
self.assertIsNotNone(provider.runtime)
try:
here = os.path.dirname(os.path.realpath(__file__))
program_id = provider.runtime.upload_program(here + "/dirfail/", metadata=RUNTIME_PROGRAM_METADATA)
self.fail("Should not allow upload")
except Exception:
self.assertTrue(True)
def test_delete_program(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
prog_list = provider.runtime.programs(refresh=False)
self.assertTrue(len(prog_list) >= 1)
deleted = provider.runtime.delete_program(program_id)
self.assertTrue(deleted)
new_prog_list = provider.runtime.programs(refresh=True)
self.assertGreater(len(prog_list), len(new_prog_list))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.problems import BaseProblem
dummy_hamiltonian = None
base_problem = BaseProblem(dummy_hamiltonian)
print(base_problem.properties)
from qiskit_nature.second_q.properties import AngularMomentum
print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties)
print("Adding AngularMomentum to problem.properties...")
base_problem.properties.add(AngularMomentum(2))
print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties)
print("Discarding AngularMomentum from problem.properties...")
base_problem.properties.discard(AngularMomentum)
print("AngularMomentum is in problem.properties:", AngularMomentum in base_problem.properties)
from qiskit_nature.second_q.drivers import PySCFDriver
es_problem = PySCFDriver().run()
print(es_problem.properties.particle_number)
print(es_problem.properties.angular_momentum)
print(es_problem.properties.magnetization)
print(es_problem.properties.electronic_dipole_moment)
print(es_problem.properties.electronic_density)
from qiskit_nature.second_q.properties import ElectronicDensity
density = ElectronicDensity.from_orbital_occupation(
es_problem.orbital_occupations,
es_problem.orbital_occupations_b,
)
es_problem.properties.electronic_density = density
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
r"""
.. _pulse_builder:
=============
Pulse Builder
=============
..
We actually want people to think of these functions as being defined within the ``qiskit.pulse``
namespace, not the submodule ``qiskit.pulse.builder``.
.. currentmodule: qiskit.pulse
Use the pulse builder DSL to write pulse programs with an imperative syntax.
.. warning::
The pulse builder interface is still in active development. It may have
breaking API changes without deprecation warnings in future releases until
otherwise indicated.
The pulse builder provides an imperative API for writing pulse programs
with less difficulty than the :class:`~qiskit.pulse.Schedule` API.
It contextually constructs a pulse schedule and then emits the schedule for
execution. For example, to play a series of pulses on channels is as simple as:
.. plot::
:include-source:
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()
To begin pulse programming we must first initialize our program builder
context with :func:`build`, after which we can begin adding program
statements. For example, below we write a simple program that :func:`play`\s
a pulse:
.. plot::
:include-source:
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog``
and then begins to construct the program within the context. The output pulse
schedule will survive after the context is exited and can be executed like a
normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``.
Pulse programming has a simple imperative style. This leaves the programmer
to worry about the raw experimental physics of pulse programming and not
constructing cumbersome data structures.
We can optionally pass a :class:`~qiskit.providers.Backend` to
:func:`build` to enable enhanced functionality. Below, we prepare a Bell state
by automatically compiling the required pulses from their gate-level
representations, while simultaneously applying a long decoupling pulse to a
neighboring qubit. We terminate the experiment with a measurement to observe the
state we prepared. This program which mixes circuits and pulses will be
automatically lowered to be run as a pulse program:
.. plot::
:include-source:
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
With the pulse builder we are able to blend programming on qubits and channels.
While the pulse schedule is based on instructions that operate on
channels, the pulse builder automatically handles the mapping from qubits to
channels for you.
In the example below we demonstrate some more features of the pulse builder:
.. code-block::
import math
from qiskit import pulse, QuantumCircuit
from qiskit.pulse import library
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
# Create a pulse.
gaussian_pulse = library.gaussian(10, 1.0, 2)
# Get the qubit's corresponding drive channel from the backend.
d0 = pulse.drive_channel(0)
d1 = pulse.drive_channel(1)
# Play a pulse at t=0.
pulse.play(gaussian_pulse, d0)
# Play another pulse directly after the previous pulse at t=10.
pulse.play(gaussian_pulse, d0)
# The default scheduling behavior is to schedule pulses in parallel
# across channels. For example, the statement below
# plays the same pulse on a different channel at t=0.
pulse.play(gaussian_pulse, d1)
# We also provide pulse scheduling alignment contexts.
# The default alignment context is align_left.
# The sequential context schedules pulse instructions sequentially in time.
# This context starts at t=10 due to earlier pulses above.
with pulse.align_sequential():
pulse.play(gaussian_pulse, d0)
# Play another pulse after at t=20.
pulse.play(gaussian_pulse, d1)
# We can also nest contexts as each instruction is
# contained in its local scheduling context.
# The output of a child context is a context-schedule
# with the internal instructions timing fixed relative to
# one another. This is schedule is then called in the parent context.
# Context starts at t=30.
with pulse.align_left():
# Start at t=30.
pulse.play(gaussian_pulse, d0)
# Start at t=30.
pulse.play(gaussian_pulse, d1)
# Context ends at t=40.
# Alignment context where all pulse instructions are
# aligned to the right, ie., as late as possible.
with pulse.align_right():
# Shift the phase of a pulse channel.
pulse.shift_phase(math.pi, d1)
# Starts at t=40.
pulse.delay(100, d0)
# Ends at t=140.
# Starts at t=130.
pulse.play(gaussian_pulse, d1)
# Ends at t=140.
# Acquire data for a qubit and store in a memory slot.
pulse.acquire(100, 0, pulse.MemorySlot(0))
# We also support a variety of macros for common operations.
# Measure all qubits.
pulse.measure_all()
# Delay on some qubits.
# This requires knowledge of which channels belong to which qubits.
# delay for 100 cycles on qubits 0 and 1.
pulse.delay_qubits(100, 0, 1)
# Call a quantum circuit. The pulse builder lazily constructs a quantum
# circuit which is then transpiled and scheduled before inserting into
# a pulse schedule.
# NOTE: Quantum register indices correspond to physical qubit indices.
qc = QuantumCircuit(2, 2)
qc.cx(0, 1)
pulse.call(qc)
# Calling a small set of standard gates and decomposing to pulses is
# also supported with more natural syntax.
pulse.u3(0, math.pi, 0, 0)
pulse.cx(0, 1)
# It is also be possible to call a preexisting schedule
tmp_sched = pulse.Schedule()
tmp_sched += pulse.Play(gaussian_pulse, d0)
pulse.call(tmp_sched)
# We also support:
# frequency instructions
pulse.set_frequency(5.0e9, d0)
# phase instructions
pulse.shift_phase(0.1, d0)
# offset contexts
with pulse.phase_offset(math.pi, d0):
pulse.play(gaussian_pulse, d0)
The above is just a small taste of what is possible with the builder. See the rest of the module
documentation for more information on its capabilities.
.. autofunction:: build
Channels
========
Methods to return the correct channels for the respective qubit indices.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
print(d0)
.. parsed-literal::
DriveChannel(0)
.. autofunction:: acquire_channel
.. autofunction:: control_channels
.. autofunction:: drive_channel
.. autofunction:: measure_channel
Instructions
============
Pulse instructions are available within the builder interface. Here's an example:
.. plot::
:include-source:
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
.. autofunction:: acquire
.. autofunction:: barrier
.. autofunction:: call
.. autofunction:: delay
.. autofunction:: play
.. autofunction:: reference
.. autofunction:: set_frequency
.. autofunction:: set_phase
.. autofunction:: shift_frequency
.. autofunction:: shift_phase
.. autofunction:: snapshot
Contexts
========
Builder aware contexts that modify the construction of a pulse program. For
example an alignment context like :func:`align_right` may
be used to align all pulses as late as possible in a pulse program.
.. plot::
:include-source:
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
.. autofunction:: align_equispaced
.. autofunction:: align_func
.. autofunction:: align_left
.. autofunction:: align_right
.. autofunction:: align_sequential
.. autofunction:: circuit_scheduler_settings
.. autofunction:: frequency_offset
.. autofunction:: phase_offset
.. autofunction:: transpiler_settings
Macros
======
Macros help you add more complex functionality to your pulse program.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as measure_sched:
mem_slot = pulse.measure(0)
print(mem_slot)
.. parsed-literal::
MemorySlot(0)
.. autofunction:: measure
.. autofunction:: measure_all
.. autofunction:: delay_qubits
Circuit Gates
=============
To use circuit level gates within your pulse program call a circuit
with :func:`call`.
.. warning::
These will be removed in future versions with the release of a circuit
builder interface in which it will be possible to calibrate a gate in
terms of pulses and use that gate in a circuit.
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as u3_sched:
pulse.u3(math.pi, 0, math.pi, 0)
.. autofunction:: cx
.. autofunction:: u1
.. autofunction:: u2
.. autofunction:: u3
.. autofunction:: x
Utilities
=========
The utility functions can be used to gather attributes about the backend and modify
how the program is built.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as u3_sched:
print('Number of qubits in backend: {}'.format(pulse.num_qubits()))
samples = 160
print('There are {} samples in {} seconds'.format(
samples, pulse.samples_to_seconds(160)))
seconds = 1e-6
print('There are {} seconds in {} samples.'.format(
seconds, pulse.seconds_to_samples(1e-6)))
.. parsed-literal::
Number of qubits in backend: 1
There are 160 samples in 3.5555555555555554e-08 seconds
There are 1e-06 seconds in 4500 samples.
.. autofunction:: active_backend
.. autofunction:: active_transpiler_settings
.. autofunction:: active_circuit_scheduler_settings
.. autofunction:: num_qubits
.. autofunction:: qubit_channels
.. autofunction:: samples_to_seconds
.. autofunction:: seconds_to_samples
"""
import collections
import contextvars
import functools
import itertools
import uuid
import warnings
from contextlib import contextmanager
from functools import singledispatchmethod
from typing import (
Any,
Callable,
ContextManager,
Dict,
Iterable,
List,
Mapping,
Optional,
Set,
Tuple,
TypeVar,
Union,
NewType,
)
import numpy as np
from qiskit import circuit
from qiskit.circuit.library import standard_gates as gates
from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType
from qiskit.pulse import (
channels as chans,
configuration,
exceptions,
instructions,
macros,
library,
transforms,
)
from qiskit.providers.backend import BackendV2
from qiskit.pulse.instructions import directives
from qiskit.pulse.schedule import Schedule, ScheduleBlock
from qiskit.pulse.transforms.alignments import AlignmentKind
#: contextvars.ContextVar[BuilderContext]: active builder
BUILDER_CONTEXTVAR = contextvars.ContextVar("backend")
T = TypeVar("T")
StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot])
def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]:
"""Decorator thats schedules and calls the lazily compiled circuit before
executing the decorated builder method."""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
self._compile_lazy_circuit()
return function(self, *args, **kwargs)
return wrapper
def _requires_backend(function: Callable[..., T]) -> Callable[..., T]:
"""Decorator a function to raise if it is called without a builder with a
set backend.
"""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
if self.backend is None:
raise exceptions.BackendNotSet(
'This function requires the builder to have a "backend" set.'
)
return function(self, *args, **kwargs)
return wrapper
class _PulseBuilder:
"""Builder context class."""
__alignment_kinds__ = {
"left": transforms.AlignLeft(),
"right": transforms.AlignRight(),
"sequential": transforms.AlignSequential(),
}
def __init__(
self,
backend=None,
block: Optional[ScheduleBlock] = None,
name: Optional[str] = None,
default_alignment: Union[str, AlignmentKind] = "left",
default_transpiler_settings: Mapping = None,
default_circuit_scheduler_settings: Mapping = None,
):
"""Initialize the builder context.
.. note::
At some point we may consider incorporating the builder into
the :class:`~qiskit.pulse.Schedule` class. However, the risk of
this is tying the user interface to the intermediate
representation. For now we avoid this at the cost of some code
duplication.
Args:
backend (Backend): Input backend to use in
builder. If not set certain functionality will be unavailable.
block: Initital ``ScheduleBlock`` to build on.
name: Name of pulse program to be built.
default_alignment: Default scheduling alignment for builder.
One of ``left``, ``right``, ``sequential`` or an instance of
:class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass.
default_transpiler_settings: Default settings for the transpiler.
default_circuit_scheduler_settings: Default settings for the
circuit to pulse scheduler.
Raises:
PulseError: When invalid ``default_alignment`` or `block` is specified.
"""
#: Backend: Backend instance for context builder.
self._backend = backend
#: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``.
self._backend_ctx_token = None
#: QuantumCircuit: Lazily constructed quantum circuit
self._lazy_circuit = None
#: Dict[str, Any]: Transpiler setting dictionary.
self._transpiler_settings = default_transpiler_settings or {}
#: Dict[str, Any]: Scheduler setting dictionary.
self._circuit_scheduler_settings = default_circuit_scheduler_settings or {}
#: List[ScheduleBlock]: Stack of context.
self._context_stack = []
#: str: Name of the output program
self._name = name
# Add root block if provided. Schedule will be built on top of this.
if block is not None:
if isinstance(block, ScheduleBlock):
root_block = block
elif isinstance(block, Schedule):
root_block = self._naive_typecast_schedule(block)
else:
raise exceptions.PulseError(
f"Input `block` type {block.__class__.__name__} is "
"not a valid format. Specify a pulse program."
)
self._context_stack.append(root_block)
# Set default alignment context
alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment)
if not isinstance(alignment, AlignmentKind):
raise exceptions.PulseError(
f"Given `default_alignment` {repr(default_alignment)} is "
"not a valid transformation. Set one of "
f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, '
"or set an instance of `AlignmentKind` subclass."
)
self.push_context(alignment)
def __enter__(self) -> ScheduleBlock:
"""Enter this builder context and yield either the supplied schedule
or the schedule created for the user.
Returns:
The schedule that the builder will build on.
"""
self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self)
output = self._context_stack[0]
output._name = self._name or output.name
return output
@_compile_lazy_circuit_before
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit the builder context and compile the built pulse program."""
self.compile()
BUILDER_CONTEXTVAR.reset(self._backend_ctx_token)
@property
def backend(self):
"""Returns the builder backend if set.
Returns:
Optional[Backend]: The builder's backend.
"""
return self._backend
@_compile_lazy_circuit_before
def push_context(self, alignment: AlignmentKind):
"""Push new context to the stack."""
self._context_stack.append(ScheduleBlock(alignment_context=alignment))
@_compile_lazy_circuit_before
def pop_context(self) -> ScheduleBlock:
"""Pop the last context from the stack."""
if len(self._context_stack) == 1:
raise exceptions.PulseError("The root context cannot be popped out.")
return self._context_stack.pop()
def get_context(self) -> ScheduleBlock:
"""Get current context.
Notes:
New instruction can be added by `.append_subroutine` or `.append_instruction` method.
Use above methods rather than directly accessing to the current context.
"""
return self._context_stack[-1]
@property
@_requires_backend
def num_qubits(self):
"""Get the number of qubits in the backend."""
# backendV2
if isinstance(self.backend, BackendV2):
return self.backend.num_qubits
return self.backend.configuration().n_qubits
@property
def transpiler_settings(self) -> Mapping:
"""The builder's transpiler settings."""
return self._transpiler_settings
@transpiler_settings.setter
@_compile_lazy_circuit_before
def transpiler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
self._transpiler_settings = settings
@property
def circuit_scheduler_settings(self) -> Mapping:
"""The builder's circuit to pulse scheduler settings."""
return self._circuit_scheduler_settings
@circuit_scheduler_settings.setter
@_compile_lazy_circuit_before
def circuit_scheduler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
self._circuit_scheduler_settings = settings
@_compile_lazy_circuit_before
def compile(self) -> ScheduleBlock:
"""Compile and output the built pulse program."""
# Not much happens because we currently compile as we build.
# This should be offloaded to a true compilation module
# once we define a more sophisticated IR.
while len(self._context_stack) > 1:
current = self.pop_context()
self.append_subroutine(current)
return self._context_stack[0]
def _compile_lazy_circuit(self):
"""Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule
to the builder's context schedule.
Note that the lazy circuit is not stored as a call instruction.
"""
if self._lazy_circuit:
lazy_circuit = self._lazy_circuit
# reset lazy circuit
self._lazy_circuit = self._new_circuit()
self.call_subroutine(self._compile_circuit(lazy_circuit))
def _compile_circuit(self, circ) -> Schedule:
"""Take a QuantumCircuit and output the pulse schedule associated with the circuit."""
from qiskit import compiler # pylint: disable=cyclic-import
transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings)
sched = compiler.schedule(
transpiled_circuit, self.backend, **self.circuit_scheduler_settings
)
return sched
def _new_circuit(self):
"""Create a new circuit for lazy circuit scheduling."""
return circuit.QuantumCircuit(self.num_qubits)
@_compile_lazy_circuit_before
def append_instruction(self, instruction: instructions.Instruction):
"""Add an instruction to the builder's context schedule.
Args:
instruction: Instruction to append.
"""
self._context_stack[-1].append(instruction)
def append_reference(self, name: str, *extra_keys: str):
"""Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction.
Args:
name: Name of subroutine.
extra_keys: Assistance keys to uniquely specify the subroutine.
"""
inst = instructions.Reference(name, *extra_keys)
self.append_instruction(inst)
@_compile_lazy_circuit_before
def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]):
"""Append a :class:`ScheduleBlock` to the builder's context schedule.
This operation doesn't create a reference. Subroutine is directly
appended to current context schedule.
Args:
subroutine: ScheduleBlock to append to the current context block.
Raises:
PulseError: When subroutine is not Schedule nor ScheduleBlock.
"""
if not isinstance(subroutine, (ScheduleBlock, Schedule)):
raise exceptions.PulseError(
f"'{subroutine.__class__.__name__}' is not valid data format in the builder. "
"'Schedule' and 'ScheduleBlock' can be appended to the builder context."
)
if len(subroutine) == 0:
return
if isinstance(subroutine, Schedule):
subroutine = self._naive_typecast_schedule(subroutine)
self._context_stack[-1].append(subroutine)
@singledispatchmethod
def call_subroutine(
self,
subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock],
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
"""Call a schedule or circuit defined outside of the current scope.
The ``subroutine`` is appended to the context schedule as a call instruction.
This logic just generates a convenient program representation in the compiler.
Thus, this doesn't affect execution of inline subroutines.
See :class:`~pulse.instructions.Call` for more details.
Args:
subroutine: Target schedule or circuit to append to the current context.
name: Name of subroutine if defined.
value_dict: Parameter object and assigned value mapping. This is more precise way to
identify a parameter since mapping is managed with unique object id rather than
name. Especially there is any name collision in a parameter table.
kw_params: Parameter values to bind to the target subroutine
with string parameter names. If there are parameter name overlapping,
these parameters are updated with the same assigned value.
Raises:
PulseError:
- When input subroutine is not valid data format.
"""
raise exceptions.PulseError(
f"Subroutine type {subroutine.__class__.__name__} is "
"not valid data format. Call QuantumCircuit, "
"Schedule, or ScheduleBlock."
)
@call_subroutine.register
def _(
self,
target_block: ScheduleBlock,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_block) == 0:
return
# Create local parameter assignment
local_assignment = {}
for param_name, value in kw_params.items():
params = target_block.get_parameters(param_name)
if not params:
raise exceptions.PulseError(
f"Parameter {param_name} is not defined in the target subroutine. "
f'{", ".join(map(str, target_block.parameters))} can be specified.'
)
for param in params:
local_assignment[param] = value
if value_dict:
if local_assignment.keys() & value_dict.keys():
warnings.warn(
"Some parameters provided by 'value_dict' conflict with one through "
"keyword arguments. Parameter values in the keyword arguments "
"are overridden by the dictionary values.",
UserWarning,
)
local_assignment.update(value_dict)
if local_assignment:
target_block = target_block.assign_parameters(local_assignment, inplace=False)
if name is None:
# Add unique string, not to accidentally override existing reference entry.
keys = (target_block.name, uuid.uuid4().hex)
else:
keys = (name,)
self.append_reference(*keys)
self.get_context().assign_references({keys: target_block}, inplace=True)
@call_subroutine.register
def _(
self,
target_schedule: Schedule,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_schedule) == 0:
return
self.call_subroutine(
self._naive_typecast_schedule(target_schedule),
name=name,
value_dict=value_dict,
**kw_params,
)
@call_subroutine.register
def _(
self,
target_circuit: circuit.QuantumCircuit,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_circuit) == 0:
return
self._compile_lazy_circuit()
self.call_subroutine(
self._compile_circuit(target_circuit),
name=name,
value_dict=value_dict,
**kw_params,
)
@_requires_backend
def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
"""Call the circuit ``gate`` in the pulse program.
The qubits are assumed to be defined on physical qubits.
If ``lazy == True`` this circuit will extend a lazily constructed
quantum circuit. When an operation occurs that breaks the underlying
circuit scheduling assumptions such as adding a pulse instruction or
changing the alignment context the circuit will be
transpiled and scheduled into pulses with the current active settings.
Args:
gate: Gate to call.
qubits: Qubits to call gate on.
lazy: If false the circuit will be transpiled and pulse scheduled
immediately. Otherwise, it will extend the active lazy circuit
as defined above.
"""
try:
iter(qubits)
except TypeError:
qubits = (qubits,)
if lazy:
self._call_gate(gate, qubits)
else:
self._compile_lazy_circuit()
self._call_gate(gate, qubits)
self._compile_lazy_circuit()
def _call_gate(self, gate, qargs):
if self._lazy_circuit is None:
self._lazy_circuit = self._new_circuit()
self._lazy_circuit.append(gate, qargs=qargs)
@staticmethod
def _naive_typecast_schedule(schedule: Schedule):
# Naively convert into ScheduleBlock
from qiskit.pulse.transforms import inline_subroutines, flatten, pad
preprocessed_schedule = inline_subroutines(flatten(schedule))
pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade)
# default to left alignment, namely ASAP scheduling
target_block = ScheduleBlock(name=schedule.name)
for _, inst in preprocessed_schedule.instructions:
target_block.append(inst, inplace=True)
return target_block
def get_dt(self):
"""Retrieve dt differently based on the type of Backend"""
if isinstance(self.backend, BackendV2):
return self.backend.dt
return self.backend.configuration().dt
def build(
backend=None,
schedule: Optional[ScheduleBlock] = None,
name: Optional[str] = None,
default_alignment: Optional[Union[str, AlignmentKind]] = "left",
default_transpiler_settings: Optional[Dict[str, Any]] = None,
default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None,
) -> ContextManager[ScheduleBlock]:
"""Create a context manager for launching the imperative pulse builder DSL.
To enter a building context and starting building a pulse program:
.. code-block::
from qiskit import execute, pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 0.5), d0)
While the output program ``pulse_prog`` cannot be executed as we are using
a mock backend. If a real backend is being used, executing the program is
done with:
.. code-block:: python
qiskit.execute(pulse_prog, backend)
Args:
backend (Backend): A Qiskit backend. If not supplied certain
builder functionality will be unavailable.
schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built.
name: Name of pulse program to be built.
default_alignment: Default scheduling alignment for builder.
One of ``left``, ``right``, ``sequential`` or an alignment context.
default_transpiler_settings: Default settings for the transpiler.
default_circuit_scheduler_settings: Default settings for the
circuit to pulse scheduler.
Returns:
A new builder context which has the active builder initialized.
"""
return _PulseBuilder(
backend=backend,
block=schedule,
name=name,
default_alignment=default_alignment,
default_transpiler_settings=default_transpiler_settings,
default_circuit_scheduler_settings=default_circuit_scheduler_settings,
)
# Builder Utilities
def _active_builder() -> _PulseBuilder:
"""Get the active builder in the active context.
Returns:
The active active builder in this context.
Raises:
exceptions.NoActiveBuilder: If a pulse builder function is called
outside of a builder context.
"""
try:
return BUILDER_CONTEXTVAR.get()
except LookupError as ex:
raise exceptions.NoActiveBuilder(
"A Pulse builder function was called outside of "
"a builder context. Try calling within a builder "
'context, eg., "with pulse.build() as schedule: ...".'
) from ex
def active_backend():
"""Get the backend of the currently active builder context.
Returns:
Backend: The active backend in the currently active
builder context.
Raises:
exceptions.BackendNotSet: If the builder does not have a backend set.
"""
builder = _active_builder().backend
if builder is None:
raise exceptions.BackendNotSet(
'This function requires the active builder to have a "backend" set.'
)
return builder
def append_schedule(schedule: Union[Schedule, ScheduleBlock]):
"""Call a schedule by appending to the active builder's context block.
Args:
schedule: Schedule or ScheduleBlock to append.
"""
_active_builder().append_subroutine(schedule)
def append_instruction(instruction: instructions.Instruction):
"""Append an instruction to the active builder's context schedule.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.builder.append_instruction(pulse.Delay(10, d0))
print(pulse_prog.instructions)
.. parsed-literal::
((0, Delay(10, DriveChannel(0))),)
"""
_active_builder().append_instruction(instruction)
def num_qubits() -> int:
"""Return number of qubits in the currently active backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.num_qubits())
.. parsed-literal::
2
.. note:: Requires the active builder context to have a backend set.
"""
if isinstance(active_backend(), BackendV2):
return active_backend().num_qubits
return active_backend().configuration().n_qubits
def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]:
"""Obtain the number of samples that will elapse in ``seconds`` on the
active backend.
Rounds down.
Args:
seconds: Time in seconds to convert to samples.
Returns:
The number of samples for the time to elapse
"""
dt = _active_builder().get_dt()
if isinstance(seconds, np.ndarray):
return (seconds / dt).astype(int)
return int(seconds / dt)
def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]:
"""Obtain the time in seconds that will elapse for the input number of
samples on the active backend.
Args:
samples: Number of samples to convert to time in seconds.
Returns:
The time that elapses in ``samples``.
"""
return samples * _active_builder().get_dt()
def qubit_channels(qubit: int) -> Set[chans.Channel]:
"""Returns the set of channels associated with a qubit.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.qubit_channels(0))
.. parsed-literal::
{MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)}
.. note:: Requires the active builder context to have a backend set.
.. note:: A channel may still be associated with another qubit in this list
such as in the case where significant crosstalk exists.
"""
# implement as the inner function to avoid API change for a patch release in 0.24.2.
def get_qubit_channels_v2(backend: BackendV2, qubit: int):
r"""Return a list of channels which operate on the given ``qubit``.
Returns:
List of ``Channel``\s operated on my the given ``qubit``.
"""
channels = []
# add multi-qubit channels
for node_qubits in backend.coupling_map:
if qubit in node_qubits:
control_channel = backend.control_channel(node_qubits)
if control_channel:
channels.extend(control_channel)
# add single qubit channels
channels.append(backend.drive_channel(qubit))
channels.append(backend.measure_channel(qubit))
channels.append(backend.acquire_channel(qubit))
return channels
# backendV2
if isinstance(active_backend(), BackendV2):
return set(get_qubit_channels_v2(active_backend(), qubit))
return set(active_backend().configuration().get_qubit_channels(qubit))
def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]:
"""Returns the unique channels of the input qubits."""
channels = set()
for channel_or_qubit in channels_or_qubits:
if isinstance(channel_or_qubit, int):
channels |= qubit_channels(channel_or_qubit)
elif isinstance(channel_or_qubit, chans.Channel):
channels.add(channel_or_qubit)
else:
raise exceptions.PulseError(
f'{channel_or_qubit} is not a "Channel" or qubit (integer).'
)
return channels
def active_transpiler_settings() -> Dict[str, Any]:
"""Return the current active builder context's transpiler settings.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
transpiler_settings = {'optimization_level': 3}
with pulse.build(backend,
default_transpiler_settings=transpiler_settings):
print(pulse.active_transpiler_settings())
.. parsed-literal::
{'optimization_level': 3}
"""
return dict(_active_builder().transpiler_settings)
def active_circuit_scheduler_settings() -> Dict[str, Any]:
"""Return the current active builder context's circuit scheduler settings.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
circuit_scheduler_settings = {'method': 'alap'}
with pulse.build(
backend,
default_circuit_scheduler_settings=circuit_scheduler_settings):
print(pulse.active_circuit_scheduler_settings())
.. parsed-literal::
{'method': 'alap'}
"""
return dict(_active_builder().circuit_scheduler_settings)
# Contexts
@contextmanager
def align_left() -> ContextManager[None]:
"""Left alignment pulse scheduling context.
Pulse instructions within this context are scheduled as early as possible
by shifting them left to the earliest available time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_left():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=0
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignLeft())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_right() -> AlignmentKind:
"""Right alignment pulse scheduling context.
Pulse instructions within this context are scheduled as late as possible
by shifting them right to the latest available time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignRight())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_sequential() -> AlignmentKind:
"""Sequential alignment pulse scheduling context.
Pulse instructions within this context are scheduled sequentially in time
such that no two instructions will be played at the same time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_sequential():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will also start at t=100
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignSequential())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind:
"""Equispaced alignment pulse scheduling context.
Pulse instructions within this context are scheduled with the same interval spacing such that
the total length of the context block is ``duration``.
If the total free ``duration`` cannot be evenly divided by the number of instructions
within the context, the modulo is split and then prepended and appended to
the returned schedule. Delay instructions are automatically inserted in between pulses.
This context is convenient to write a schedule for periodical dynamic decoupling or
the Hahn echo sequence.
Examples:
.. plot::
:include-source:
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
Args:
duration: Duration of this context. This should be larger than the schedule duration.
Yields:
None
Notes:
The scheduling is performed for sub-schedules within the context rather than
channel-wise. If you want to apply the equispaced context for each channel,
you should use the context independently for channels.
"""
builder = _active_builder()
builder.push_context(transforms.AlignEquispaced(duration=duration))
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_func(
duration: Union[int, ParameterExpression], func: Callable[[int], float]
) -> AlignmentKind:
"""Callback defined alignment pulse scheduling context.
Pulse instructions within this context are scheduled at the location specified by
arbitrary callback function `position` that takes integer index and returns
the associated fractional location within [0, 1].
Delay instruction is automatically inserted in between pulses.
This context may be convenient to write a schedule of arbitrary dynamical decoupling
sequences such as Uhrig dynamical decoupling.
Examples:
.. plot::
:include-source:
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
Args:
duration: Duration of context. This should be larger than the schedule duration.
func: A function that takes an index of sub-schedule and returns the
fractional coordinate of of that sub-schedule.
The returned value should be defined within [0, 1].
The pulse index starts from 1.
Yields:
None
Notes:
The scheduling is performed for sub-schedules within the context rather than
channel-wise. If you want to apply the numerical context for each channel,
you need to apply the context independently to channels.
"""
builder = _active_builder()
builder.push_context(transforms.AlignFunc(duration=duration, func=func))
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]:
"""Arbitrary alignment transformation defined by a subclass instance of
:class:`~qiskit.pulse.transforms.alignments.AlignmentKind`.
Args:
alignment_context: Alignment context instance that defines schedule transformation.
Yields:
None
Raises:
PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses.
"""
if not isinstance(alignment_context, AlignmentKind):
raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.")
builder = _active_builder()
builder.push_context(alignment_context)
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def transpiler_settings(**settings) -> ContextManager[None]:
"""Set the currently active transpiler settings for this context.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.active_transpiler_settings())
with pulse.transpiler_settings(optimization_level=3):
print(pulse.active_transpiler_settings())
.. parsed-literal::
{}
{'optimization_level': 3}
"""
builder = _active_builder()
curr_transpiler_settings = builder.transpiler_settings
builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings)
try:
yield
finally:
builder.transpiler_settings = curr_transpiler_settings
@contextmanager
def circuit_scheduler_settings(**settings) -> ContextManager[None]:
"""Set the currently active circuit scheduler settings for this context.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(method='alap'):
print(pulse.active_circuit_scheduler_settings())
.. parsed-literal::
{}
{'method': 'alap'}
"""
builder = _active_builder()
curr_circuit_scheduler_settings = builder.circuit_scheduler_settings
builder.circuit_scheduler_settings = collections.ChainMap(
settings, curr_circuit_scheduler_settings
)
try:
yield
finally:
builder.circuit_scheduler_settings = curr_circuit_scheduler_settings
@contextmanager
def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]:
"""Shift the phase of input channels on entry into context and undo on exit.
Examples:
.. code-block::
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
with pulse.phase_offset(math.pi, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
Args:
phase: Amount of phase offset in radians.
channels: Channels to offset phase of.
Yields:
None
"""
for channel in channels:
shift_phase(phase, channel)
try:
yield
finally:
for channel in channels:
shift_phase(-phase, channel)
@contextmanager
def frequency_offset(
frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False
) -> ContextManager[None]:
"""Shift the frequency of inputs channels on entry into context and undo on exit.
Examples:
.. code-block:: python
:emphasize-lines: 7, 16
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
# shift frequency by 1GHz
with pulse.frequency_offset(1e9, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
with pulse.build(backend) as pulse_prog:
# Shift frequency by 1GHz.
# Undo accumulated phase in the shifted frequency frame
# when exiting the context.
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 4
Args:
frequency: Amount of frequency offset in Hz.
channels: Channels to offset frequency of.
compensate_phase: Compensate for accumulated phase accumulated with
respect to the channels' frame at its initial frequency.
Yields:
None
"""
builder = _active_builder()
# TODO: Need proper implementation of compensation. t0 may depend on the parent context.
# For example, the instruction position within the equispaced context depends on
# the current total number of instructions, thus adding more instruction after
# offset context may change the t0 when the parent context is transformed.
t0 = builder.get_context().duration
for channel in channels:
shift_frequency(frequency, channel)
try:
yield
finally:
if compensate_phase:
duration = builder.get_context().duration - t0
accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1)
for channel in channels:
shift_phase(-accumulated_phase, channel)
for channel in channels:
shift_frequency(-frequency, channel)
# Channels
def drive_channel(qubit: int) -> chans.DriveChannel:
"""Return ``DriveChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.drive_channel(0) == pulse.DriveChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().drive_channel(qubit)
return active_backend().configuration().drive(qubit)
def measure_channel(qubit: int) -> chans.MeasureChannel:
"""Return ``MeasureChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.measure_channel(0) == pulse.MeasureChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().measure_channel(qubit)
return active_backend().configuration().measure(qubit)
def acquire_channel(qubit: int) -> chans.AcquireChannel:
"""Return ``AcquireChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.acquire_channel(0) == pulse.AcquireChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().acquire_channel(qubit)
return active_backend().configuration().acquire(qubit)
def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]:
"""Return ``ControlChannel`` for ``qubit`` on the active builder backend.
Return the secondary drive channel for the given qubit -- typically
utilized for controlling multi-qubit interactions.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)]
.. note:: Requires the active builder context to have a backend set.
Args:
qubits: Tuple or list of ordered qubits of the form
`(control_qubit, target_qubit)`.
Returns:
List of control channels associated with the supplied ordered list
of qubits.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().control_channel(qubits)
return active_backend().configuration().control(qubits=qubits)
# Base Instructions
def delay(duration: int, channel: chans.Channel, name: Optional[str] = None):
"""Delay on a ``channel`` for a ``duration``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.delay(10, d0)
Args:
duration: Number of cycles to delay for on ``channel``.
channel: Channel to delay on.
name: Name of the instruction.
"""
append_instruction(instructions.Delay(duration, channel, name=name))
def play(
pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None
):
"""Play a ``pulse`` on a ``channel``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
Args:
pulse: Pulse to play.
channel: Channel to play pulse on.
name: Name of the pulse.
"""
if not isinstance(pulse, library.Pulse):
pulse = library.Waveform(pulse)
append_instruction(instructions.Play(pulse, channel, name=name))
def acquire(
duration: int,
qubit_or_channel: Union[int, chans.AcquireChannel],
register: StorageLocation,
**metadata: Union[configuration.Kernel, configuration.Discriminator],
):
"""Acquire for a ``duration`` on a ``channel`` and store the result
in a ``register``.
Examples:
.. code-block::
from qiskit import pulse
acq0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as pulse_prog:
pulse.acquire(100, acq0, mem0)
# measurement metadata
kernel = pulse.configuration.Kernel('linear_discriminator')
pulse.acquire(100, acq0, mem0, kernel=kernel)
.. note:: The type of data acquire will depend on the execution ``meas_level``.
Args:
duration: Duration to acquire data for
qubit_or_channel: Either the qubit to acquire data for or the specific
:class:`~qiskit.pulse.channels.AcquireChannel` to acquire on.
register: Location to store measured result.
metadata: Additional metadata for measurement. See
:class:`~qiskit.pulse.instructions.Acquire` for more information.
Raises:
exceptions.PulseError: If the register type is not supported.
"""
if isinstance(qubit_or_channel, int):
qubit_or_channel = chans.AcquireChannel(qubit_or_channel)
if isinstance(register, chans.MemorySlot):
append_instruction(
instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata)
)
elif isinstance(register, chans.RegisterSlot):
append_instruction(
instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata)
)
else:
raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported')
def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Set the ``frequency`` of a pulse ``channel``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_frequency(1e9, d0)
Args:
frequency: Frequency in Hz to set channel to.
channel: Channel to set frequency of.
name: Name of the instruction.
"""
append_instruction(instructions.SetFrequency(frequency, channel, name=name))
def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Shift the ``frequency`` of a pulse ``channel``.
Examples:
.. code-block:: python
:emphasize-lines: 6
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_frequency(1e9, d0)
Args:
frequency: Frequency in Hz to shift channel frequency by.
channel: Channel to shift frequency of.
name: Name of the instruction.
"""
append_instruction(instructions.ShiftFrequency(frequency, channel, name=name))
def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Set the ``phase`` of a pulse ``channel``.
Examples:
.. code-block:: python
:emphasize-lines: 8
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_phase(math.pi, d0)
Args:
phase: Phase in radians to set channel carrier signal to.
channel: Channel to set phase of.
name: Name of the instruction.
"""
append_instruction(instructions.SetPhase(phase, channel, name=name))
def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Shift the ``phase`` of a pulse ``channel``.
Examples:
.. code-block::
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_phase(math.pi, d0)
Args:
phase: Phase in radians to shift channel carrier signal by.
channel: Channel to shift phase of.
name: Name of the instruction.
"""
append_instruction(instructions.ShiftPhase(phase, channel, name))
def snapshot(label: str, snapshot_type: str = "statevector"):
"""Simulator snapshot.
Examples:
.. code-block::
from qiskit import pulse
with pulse.build() as pulse_prog:
pulse.snapshot('first', 'statevector')
Args:
label: Label for snapshot.
snapshot_type: Type of snapshot.
"""
append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type))
def call(
target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]],
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
"""Call the subroutine within the currently active builder context with arbitrary
parameters which will be assigned to the target program.
.. note::
If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference`
instruction will be created and appended to the current context.
The ``target`` program will be immediately assigned to the current scope as a subroutine.
If the ``target`` program is :class:`.Schedule`, it will be wrapped by the
:class:`.Call` instruction and appended to the current context to avoid
a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`.
If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled
and the new :class:`.Schedule` will be added as a :class:`.Call` instruction.
Examples:
1. Calling a schedule block (recommended)
.. code-block::
from qiskit import circuit, pulse
from qiskit.providers.fake_provider import FakeBogotaV2
backend = FakeBogotaV2()
with pulse.build() as x_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block0",
transform=AlignLeft()
),
name="block1",
transform=AlignLeft()
)
The actual program is stored in the reference table attached to the schedule.
.. code-block::
print(pulse_prog.references)
.. parsed-literal::
ReferenceManager:
- ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(...
In addition, you can call a parameterized target program with parameter assignment.
.. code-block::
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine, amp=0.3)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.3+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
name="block3",
transform=AlignLeft()
)
If there is a name collision between parameters, you can distinguish them by specifying
each parameter object in a python dictionary. For example,
.. code-block::
amp1 = circuit.Parameter('amp')
amp2 = circuit.Parameter('amp')
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1))
with pulse.build() as pulse_prog:
pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3})
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)),
Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)),
name="block4",
transform=AlignLeft()
),
name="block5",
transform=AlignLeft()
)
2. Calling a schedule
.. code-block::
x_sched = backend.instruction_schedule_map.get("x", (0,))
with pulse.build(backend) as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
Call(
Schedule(
(
0,
Play(
Drag(
duration=160,
amp=(0.18989731546729305+0j),
sigma=40,
beta=-1.201258305015517,
name='drag_86a8'
),
DriveChannel(0),
name='drag_86a8'
)
),
name="x"
),
name='x'
),
name="block6",
transform=AlignLeft()
)
Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`.
The parameter assignment mechanism is available also for schedules.
However, the called schedule is not treated as a reference.
3. Calling a quantum circuit
.. code-block::
backend = FakeBogotaV2()
qc = circuit.QuantumCircuit(1)
qc.x(0)
with pulse.build(backend) as pulse_prog:
pulse.call(qc)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
Call(
Schedule(
(
0,
Play(
Drag(
duration=160,
amp=(0.18989731546729305+0j),
sigma=40,
beta=-1.201258305015517,
name='drag_86a8'
),
DriveChannel(0),
name='drag_86a8'
)
),
name="circuit-87"
),
name='circuit-87'
),
name="block7",
transform=AlignLeft()
)
.. warning::
Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model
is migrating toward the pulse gate model, where schedules are attached to
circuits through the :meth:`.QuantumCircuit.add_calibration` method.
Args:
target: Target circuit or pulse schedule to call.
name: Optional. A unique name of subroutine if defined. When the name is explicitly
provided, one cannot call different schedule blocks with the same name.
value_dict: Optional. Parameters assigned to the ``target`` program.
If this dictionary is provided, the ``target`` program is copied and
then stored in the main built schedule and its parameters are assigned to the given values.
This dictionary is keyed on :class:`~.Parameter` objects,
allowing parameter name collision to be avoided.
kw_params: Alternative way to provide parameters.
Since this is keyed on the string parameter name,
the parameters having the same name are all updated together.
If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter`
objects instead.
"""
_active_builder().call_subroutine(target, name, value_dict, **kw_params)
def reference(name: str, *extra_keys: str):
"""Refer to undefined subroutine by string keys.
A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created
and a schedule can be separately registered to the reference at a later stage.
.. code-block:: python
from qiskit import pulse
with pulse.build() as main_prog:
pulse.reference("x_gate", "q0")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine})
Args:
name: Name of subroutine.
extra_keys: Helper keys to uniquely specify the subroutine.
"""
_active_builder().append_reference(name, *extra_keys)
# Directives
def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None):
"""Barrier directive for a set of channels and qubits.
This directive prevents the compiler from moving instructions across
the barrier. Consider the case where we want to enforce that one pulse
happens after another on separate channels, this can be done with:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(backend) as barrier_pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.barrier(d0, d1)
pulse.play(pulse.Constant(10, 1.0), d1)
Of course this could have been accomplished with:
.. code-block::
from qiskit.pulse import transforms
with pulse.build(backend) as aligned_pulse_prog:
with pulse.align_sequential():
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.play(pulse.Constant(10, 1.0), d1)
barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog)
aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog)
assert barrier_pulse_prog == aligned_pulse_prog
The barrier allows the pulse compiler to take care of more advanced
scheduling alignment operations across channels. For example
in the case where we are calling an outside circuit or schedule and
want to align a pulse at the end of one call:
.. code-block::
import math
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
with pulse.align_right():
pulse.x(1)
# Barrier qubit 1 and d0.
pulse.barrier(1, d0)
# Due to barrier this will play before the gate on qubit 1.
pulse.play(pulse.Constant(10, 1.0), d0)
# This will end at the same time as the pulse above due to
# the barrier.
pulse.x(1)
.. note:: Requires the active builder context to have a backend set if
qubits are barriered on.
Args:
channels_or_qubits: Channels or qubits to barrier.
name: Name for the barrier
"""
channels = _qubits_to_channels(*channels_or_qubits)
if len(channels) > 1:
append_instruction(directives.RelativeBarrier(*channels, name=name))
# Macros
def macro(func: Callable):
"""Wrap a Python function and activate the parent builder context at calling time.
This enables embedding Python functions as builder macros. This generates a new
:class:`pulse.Schedule` that is embedded in the parent builder context with
every call of the decorated macro function. The decorated macro function will
behave as if the function code was embedded inline in the parent builder context
after parameter substitution.
Examples:
.. plot::
:include-source:
from qiskit import pulse
@pulse.macro
def measure(qubit: int):
pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit))
mem_slot = pulse.MemorySlot(qubit)
pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot)
return mem_slot
with pulse.build(backend=backend) as sched:
mem_slot = measure(0)
print(f"Qubit measured into {mem_slot}")
sched.draw()
Args:
func: The Python function to enable as a builder macro. There are no
requirements on the signature of the function, any calls to pulse
builder methods will be added to builder context the wrapped function
is called from.
Returns:
Callable: The wrapped ``func``.
"""
func_name = getattr(func, "__name__", repr(func))
@functools.wraps(func)
def wrapper(*args, **kwargs):
_builder = _active_builder()
# activate the pulse builder before calling the function
with build(backend=_builder.backend, name=func_name) as built:
output = func(*args, **kwargs)
_builder.call_subroutine(built)
return output
return wrapper
def measure(
qubits: Union[List[int], int],
registers: Union[List[StorageLocation], StorageLocation] = None,
) -> Union[List[StorageLocation], StorageLocation]:
"""Measure a qubit within the currently active builder context.
At the pulse level a measurement is composed of both a stimulus pulse and
an acquisition instruction which tells the systems measurement unit to
acquire data and process it. We provide this measurement macro to automate
the process for you, but if desired full control is still available with
:func:`acquire` and :func:`play`.
To use the measurement it is as simple as specifying the qubit you wish to
measure:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
qubit = 0
with pulse.build(backend) as pulse_prog:
# Do something to the qubit.
qubit_drive_chan = pulse.drive_channel(0)
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
reg = pulse.measure(qubit)
For now it is not possible to do much with the handle to ``reg`` but in the
future we will support using this handle to a result register to build
up ones program. It is also possible to supply this register:
.. code-block::
with pulse.build(backend) as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
mem0 = pulse.MemorySlot(0)
reg = pulse.measure(qubit, mem0)
assert reg == mem0
.. note:: Requires the active builder context to have a backend set.
Args:
qubits: Physical qubit to measure.
registers: Register to store result in. If not selected the current
behavior is to return the :class:`MemorySlot` with the same
index as ``qubit``. This register will be returned.
Returns:
The ``register`` the qubit measurement result will be stored in.
"""
backend = active_backend()
try:
qubits = list(qubits)
except TypeError:
qubits = [qubits]
if registers is None:
registers = [chans.MemorySlot(qubit) for qubit in qubits]
else:
try:
registers = list(registers)
except TypeError:
registers = [registers]
measure_sched = macros.measure(
qubits=qubits,
backend=backend,
qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)},
)
# note this is not a subroutine.
# just a macro to automate combination of stimulus and acquisition.
# prepare unique reference name based on qubit and memory slot index.
qubits_repr = "&".join(map(str, qubits))
mslots_repr = "&".join((str(r.index) for r in registers))
_active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}")
if len(qubits) == 1:
return registers[0]
else:
return registers
def measure_all() -> List[chans.MemorySlot]:
r"""Measure all qubits within the currently active builder context.
A simple macro function to measure all of the qubits in the device at the
same time. This is useful for handling device ``meas_map`` and single
measurement constraints.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
# Measure all qubits and return associated registers.
regs = pulse.measure_all()
.. note::
Requires the active builder context to have a backend set.
Returns:
The ``register``\s the qubit measurement results will be stored in.
"""
backend = active_backend()
qubits = range(num_qubits())
registers = [chans.MemorySlot(qubit) for qubit in qubits]
measure_sched = macros.measure(
qubits=qubits,
backend=backend,
qubit_mem_slots={qubit: qubit for qubit in qubits},
)
# note this is not a subroutine.
# just a macro to automate combination of stimulus and acquisition.
_active_builder().call_subroutine(measure_sched, name="measure_all")
return registers
def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]):
r"""Insert delays on all of the :class:`channels.Channel`\s that correspond
to the input ``qubits`` at the same time.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
with pulse.build(backend) as pulse_prog:
# Delay for 100 cycles on qubits 0, 1 and 2.
regs = pulse.delay_qubits(100, 0, 1, 2)
.. note:: Requires the active builder context to have a backend set.
Args:
duration: Duration to delay for.
qubits: Physical qubits to delay on. Delays will be inserted based on
the channels returned by :func:`pulse.qubit_channels`.
"""
qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits))
with align_left():
for chan in qubit_chans:
delay(duration, chan)
# Gate instructions
def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
"""Call a gate and lazily schedule it to its corresponding
pulse instruction.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.pulse import builder
from qiskit.circuit.library import standard_gates as gates
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
builder.call_gate(gates.CXGate(), (0, 1))
We can see the role of the transpiler in scheduling gates by optimizing
away two consecutive CNOT gates:
.. code-block::
with pulse.build(backend) as pulse_prog:
with pulse.transpiler_settings(optimization_level=3):
builder.call_gate(gates.CXGate(), (0, 1))
builder.call_gate(gates.CXGate(), (0, 1))
assert pulse_prog == pulse.Schedule()
.. note:: If multiple gates are called in a row they may be optimized by
the transpiler, depending on the
:func:`pulse.active_transpiler_settings``.
.. note:: Requires the active builder context to have a backend set.
Args:
gate: Circuit gate instance to call.
qubits: Qubits to call gate on.
lazy: If ``false`` the gate will be compiled immediately, otherwise
it will be added onto a lazily evaluated quantum circuit to be
compiled when the builder is forced to by a circuit assumption
being broken, such as the inclusion of a pulse instruction or
new alignment context.
"""
_active_builder().call_gate(gate, qubits, lazy=lazy)
def cx(control: int, target: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the
input physical qubits.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.cx(0, 1)
"""
call_gate(gates.CXGate(), (control, target))
def u1(theta: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u1(math.pi, 1)
"""
call_gate(gates.U1Gate(theta), qubit)
def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u2(0, math.pi, 1)
"""
call_gate(gates.U2Gate(phi, lam), qubit)
def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u3(math.pi, 0, math.pi, 1)
"""
call_gate(gates.U3Gate(theta, phi, lam), qubit)
def x(qubit: int):
"""Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.x(0)
"""
call_gate(gates.XGate(), qubit)
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
"""
This file contains functions that are written utils/gates/snail_death_gate.py
Refactoring note, should call functions from there instead of writing them here
"""
import matplotlib.pyplot as plt
import numpy as np
c_ampArray = np.linspace(0, 0.8, 81)
g_ampArray = np.linspace(0, 0.8, 81)
from slam.utils.data_utils import h5py_load
glist = h5py_load("snail_death", "snail_death")["snail_death"]
def check_snail(gc, gg):
"""returns true if snail still alive"""
c_ampArray = np.linspace(0, 0.8, 81)
g_ampArray = np.linspace(0, 0.8, 81)
x = np.where(c_ampArray == gc)[0]
y = np.where(g_ampArray == gg)[0]
return glist.T[x,y] > 0.5
def get_speedlimit(gc, gg):
"""Find highest amps (preserving gate ratio) where snail still alive
TODO Make this way smarter by using parametric functions and finding intercepts!
Failing now because not all values are contained in glist linspace array"""
upper_bound_scale = np.min([0.8/gc, 0.8/gg])
scale = upper_bound_scale
y= lambda x: gg/gc
while (gc > 1e-6 and gg > 1e-6) and scale > 0:
sc, sg = gc*scale, gg*scale
scale -= .01 #shrink ratio until valid
if check_snail(sc, sg):
break
return sc, sg
plt.figure()
plt.pcolormesh(g_ampArray, c_ampArray, glist.T, cmap='RdBu', vmax=1, vmin=0)
plt.xlabel("gain amp(DAC)")
plt.ylabel('conv amp(DAC)')
cbar = plt.colorbar()
plt.ylim(0,.8)
plt.xlim(-0.01,.8)
cbar.set_label("g pct", rotation=90)
import json
from matplotlib import pyplot as plt
import numpy as np
from config import srcpath
datapath = f"{srcpath}/data/Q1_11.07mA_snailPump_length0.5_prepareE_False_freqG_9070_freqC_695-11_processed.json"
dd = json.load(open(datapath))
g2_conv = dd["g2_conv"]
g2_gain = dd["g2_gain"]
g_pct = np.array(dd["g_pct"])
plt.figure()
plt.pcolormesh(g2_conv, g2_gain, g_pct.T, shading='auto', cmap='RdBu', vmin=0, vmax=1)
plt.xlabel(f"g2eff_conv (MHz)")
plt.ylabel(f"g2eff_gain (MHz)")
# plt.xticks(np.linspace(0, 50, 6), map(str, np.linspace(0, 50, 6, dtype=int)))
# plt.yticks(np.linspace(0, 15, 4), map(str, np.linspace(0, 15, 4, dtype=int)))
cbar = plt.colorbar()
cbar.set_label("g pct", rotation=90)
cbar.set_ticks([0.0, 0.5, 1.0])
# namign variables to match old version
glist = g_pct
c_ampArray = g2_conv
g_ampArray = g2_gain
# step 1 data cleaning
glist_temp = glist.copy().T
# iterate through each column
for i in range(glist_temp.shape[1]):
# find the last value close to 0.5
idx = np.where(np.isclose(glist_temp[:,i], 0.5, atol=.05))[0]
if len(idx) > 0:
idx = idx[-1]
else:
# set all values to 0
glist_temp[:,i] = 0
continue
# set all values before that to 0
glist_temp[:idx,i] = 0
# set that value to 1
glist_temp[idx,i] = 1
# set every value after that to 0
glist_temp[idx+1:,i] = 0
# remove the obvious outlier
glist_temp[0, 68] = 0
plt.figure()
plt.pcolormesh(c_ampArray, g_ampArray, glist_temp, vmax=1, vmin=0)
plt.ylabel("gain amp(DAC)")
plt.xlabel('conv amp(DAC)')
cbar = plt.colorbar()
cbar.set_label("g pct", rotation=90)
#step 2 reduce dimensionality
coords = []
for i in range(glist_temp.shape[0]):
for j in range(glist_temp.shape[1]):
if glist_temp[i,j] == 1:
coords.append([c_ampArray[j], g_ampArray[i]])
coords.sort(key=lambda x: x[0])
# add in point (1,0) to make sure bounded
coords.append([coords[-1][0],0])
plt.figure()
plt.plot([x[0] for x in coords], [x[1] for x in coords], '-o')
plt.ylabel("gain amp(DAC)")
plt.xlabel('conv amp(DAC)')
cbar.set_label("g pct", rotation=90)
# # don't have to do because already scaled in new data
# # use conv_data and gain_data to see how voltage is related to the gc/gg terms in order to scale the axes properly
# # load from data conv_data and gain_data using h5py
# import h5py
# with h5py.File('data/conv_data.h5', 'r') as hf:
# plt.plot(hf['DAC_list'][:], hf['g2_fit'][:], '-o', label='conv')
# # save slope
# conv_slope = np.average(hf['g2_fit'][:]/hf['DAC_list'][:])
# with h5py.File('data/gain_data.h5', 'r') as hf:
# plt.plot(hf['DAC_list'][:], hf['g2_fit'][:], '-o', label='gain')
# # save slope
# gain_slope = np.average(hf['g2_fit'][:]/hf['DAC_list'][:])
# plt.legend()
# plt.xlabel('DAC')
# plt.ylabel('g2')
# #print slopes
# print(conv_slope, gain_slope)
#step 2.5 arbitrary scaling to convert DAC to Hamiltonian (rad/s) ?
real_scaling = 1
conv_slope =1
gain_slope = 1
# slopes are 1 because already scaled in new data
if real_scaling:
#decide to scale so x and y intercept are near pi/2
#scale x axis
x = [x[0]*conv_slope for x in coords] #0.64*np.pi
# scale y axis
y = [x[1]*gain_slope for x in coords] #1.7*np.pi
# step 2.6 normalization so the maximum intercept is pi/2
# find max between x- and y-axis intercept
max_intercept = np.max([np.abs(x[-1]), np.abs(y[0])])
# scale x and y
x = [x[i]/max_intercept*np.pi/2 for i in range(len(x))]
y = [y[i]/max_intercept*np.pi/2 for i in range(len(y))]
else:
#scale x axis
x = [x[0]*0.64*np.pi for x in coords] #
# scale y axis
y = [x[1]*1.7*np.pi for x in coords] #
# step 3 univariate spline
from scipy.interpolate import UnivariateSpline
N=800
s = UnivariateSpline(x, y, s=0.001)
xs = np.linspace(0, max(x), N)
plt.figure()
# plt.plot(x, y, 'o', xs, s(xs), '-', label="Characterized Speed Limit")
plt.plot(xs, s(xs), '-', label="Characterized Speed Limit")
plt.ylabel("Gain")
plt.xlabel('Conv')
plt.xlim(0,max(xs))
plt.ylim(0,max(s(xs)))
#also put linear fit on plot
s2 = lambda x: -x + np.pi/2
xs = np.linspace(0, np.pi/2, N)
plt.plot(xs, s2(xs), 'g-', label='Linear Speed Limit')
slf = lambda x: np.sqrt((np.pi/2)**2 - x**2)
plt.plot(xs, slf(xs), 'r-', label='Squared Speed Limit')
c = np.pi/4
slf = lambda x: 0.5 * (-2*c + np.sqrt(4*c**2 - 8*c*x + 4*c*np.pi - 4*x**2 + np.pi**2))
plt.plot(xs, slf(xs), 'b-', label='Mid Speed Limit')
#plot cnot gate
gate_c = 0.25*np.pi
gate_g = 0.25*np.pi
if gate_c == 0:
plt.plot([0, 0], [0, max(s(xs))], 'r--', label='CX gate')
else:
ratio = gate_g/gate_c * xs
plt.plot(xs, ratio, 'r--', label='CX gate', alpha=0.5)
# plot B gate
gate_c = 3*np.pi/8
gate_g = 1*np.pi/8
ratio = gate_g/gate_c * xs
plt.plot(xs, ratio, 'b--', label='B gate', alpha=0.5)
gate_c = 1*np.pi/8
gate_g = 3*np.pi/8
ratio = gate_g/gate_c * xs
plt.plot(xs, ratio, 'b--', alpha=0.5)
#plot intersections
if gate_c == 0:
idx = 0
print(xs[idx], s(xs[idx]))
else:
idx = max(np.argwhere(np.abs(ratio - s(xs)) < 0.01))
print(xs[idx], ratio[idx])
plt.plot(xs[idx], s(xs[idx]), 'b*', markersize=8)
idx = max(np.argwhere(np.abs(ratio - s2(xs)) < 0.01))
plt.plot(xs[idx], s2(xs[idx]), 'gP', markersize=8)
plt.title("Speed Limit Characterization")
#show legend underneath plot
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), fancybox=True, shadow=True, ncol=2)
plt.show()
from slam.utils.gates.bare_candidates import build_gates, get_group_name
from slam.utils.gates.duraton_scaling import cost_scaling, atomic_cost_scaling
unitary_list, coordinate_list = build_gates()
#coordinate_2dlist_weyl(*coordinate_list);
# collect_data(unitary_list)
# step 3 univariate spline
from scipy.interpolate import UnivariateSpline
from weylchamber import WeylChamber, c1c2c3
from tqdm import tqdm
N=800
slf_hardware = UnivariateSpline(x, y, s=0.001)
xs = np.linspace(0, max(x), N)
# make a subfigure for each 1Q duration
durations_1q = [0, 0.1, 0.25]#, 0.5]
with plt.style.context(['science','ieee']):
fig = plt.figure(figsize=(12, 10))
fig.suptitle("Speed Limit Characterization")
for index, duration_1q in enumerate(durations_1q):
ax = fig.add_subplot(2, len(durations_1q), index+1)
# add second row of subfigures, set to be same size as first row
# ax2 = fig.add_subplot(2, len(durations_1q), 1+len(durations_1q)+index, projection="3d", figsize=(16,4))
ax2 = fig.add_subplot(2, len(durations_1q), 1+len(durations_1q)+index, projection="3d")
#set ax2 camera view to be top down
w = WeylChamber()
w.weyl_edge_bg_properties = {'color': 'k', 'linewidth': 0}
w.fig_height = 8
w.fig_width = 8
w.top_margin =0
w.bottom_margin = 0
w.left_margin = 0
w.right_margin = 0
w.elev = 90
w.azim = -90
#remove labels
w.labels = {}
w.render(ax2)
# scale subplots to be same height and width
ax.set_aspect('equal')
# ax2.set_aspect('auto')
# set the z axis to be invisible
ax2.w_zaxis.line.set_lw(0.)
ax2.set_zticks([])
ax2.set_zlabel('')
#ax2.get_zaxis().set_visible(False)
# REFERENCE GATES
#plot cnot gate
gate_c = 0.25*np.pi
gate_g = 0.25*np.pi
if gate_c == 0:
ax.plot([0, 0], [0, max(s(xs))], 'r--', label='CX gate')
else:
ratio = gate_g/gate_c * xs
ax.plot(xs, ratio, 'r--', label='CX gate', alpha=0.25)
# plot B gate
gate_c = 3*np.pi/8
gate_g = 1*np.pi/8
ratio = gate_g/gate_c * xs
ax.plot(xs, ratio, 'b--', label='B gate', alpha=0.25)
gate_c = 1*np.pi/8
gate_g = 3*np.pi/8
ratio = gate_g/gate_c * xs
ax.plot(xs, ratio, 'b--', alpha=0.25)
##############
method_list = ['linear', 'squared', 'hardware'] #'mid'
#color for each method
colors = ['g', 'r', 'b', 'k']
for method_i, method in tqdm(enumerate(method_list)):
if method == 'hardware':
# plt.plot(x, y, 'o', xs, s(xs), '-', label="Characterized Speed Limit")
ax.plot(xs, slf_hardware(xs), label="Characterized Speed Limit", color=colors[method_i], linestyle='-')
s_method = slf_hardware
elif method == 'linear':
#also put linear fit on plot
slf_linear = lambda x: -x + np.pi/2
xs = np.linspace(0, np.pi/2, N)
ax.plot(xs, slf_linear(xs), label='Linear Speed Limit',color=colors[method_i], linestyle='-')
s_method = slf_linear
elif method == 'squared':
slf_squared = lambda x: np.sqrt((np.pi/2)**2 - x**2)
ax.plot(xs, slf_squared(xs), label='Squared Speed Limit',color=colors[method_i], linestyle='-')
s_method = slf_squared
elif method == 'mid':
c = np.pi/4
slf_mid = lambda x: 0.5 * (-2*c + np.sqrt(4*c**2 - 8*c*x + 4*c*np.pi - 4*x**2 + np.pi**2))
ax.plot(xs, slf_mid(xs), label='Mid Speed Limit', color=colors[method_i], linestyle='-')
s_method = slf_mid
for m_i, metric in enumerate([0,1,2, (-1, .47)]):
# matplotlib marker and color unique to each metric
marker = ['o', 'P', '*', 's'][m_i]
label = ['Haar', 'CX', 'SWAP', 'W(.47)'][m_i]
color = colors[method_i]
# add a legend entry for each metric
# group_name = get_group_name(method, duration_1q)
# cost_scaling(speed_method=method, duration_1q=duration_1q)
# gate = pick_winner(group_name, metric=metric, plot=False, tqdm_bool=False)[0]
# gate_c ,gate_g = gate.params[2], gate.params[3]
# XXX rewrite using atomic cost function
raise NotImplementedError("This code is not updated to use the new atomic cost function")
for candidate_gate in unitary_list:
scaled_gate, _ = atomic_cost_scaling(candidate_gate.params, scores=
# plot intersections
if gate_c == 0:
idx = 0
#print(xs[idx], s_method(xs[idx]))
else:
ratio = gate_g/gate_c * xs
idx = max(np.argwhere(np.abs(ratio - s_method(xs)) < 0.02))
#print(xs[idx], ratio[idx])
# only label the last metric
if duration_1q == durations_1q[-1] and method == method_list[-1]:
ax.plot(xs[idx], s_method(xs[idx]), color+marker, markersize=10, label=label)
else:
ax.plot(xs[idx], s_method(xs[idx]), color+marker, markersize=10)
# plot weyl coordinates
ax2.scatter3D(*c1c2c3(gate.to_matrix()), color=color, marker=marker)
# idx = max(np.argwhere(np.abs(ratio - s2(xs)) < 0.01))
# plt.plot(xs[idx], s2(xs[idx]), 'gP', markersize=8)
#plot config
ax.set_ylabel(r"Gain ($\theta_g$)")
ax.set_xlabel(r'Conversion ($\theta_c$)')
ax.set_xlim(0,max(xs))
ax.set_ylim(0,max(slf_linear(xs)))
ax.set_title(f"D[1Q] = {duration_1q}")
# make axis in units of pi
ax.set_xticks(np.linspace(0, np.pi/2, 5))
ax.set_yticks(np.linspace(0, np.pi/2, 5))
ax.set_xticklabels([r'$0$', r'$\pi/8$', r'$\pi/4$', r'$3\pi/8$', r'$\pi/2$'])
ax.set_yticklabels([r'$0$', r'$\pi/8$', r'$\pi/4$', r'$3\pi/8$', r'$\pi/2$'])
#ax.show()
# only show legend once for all subplots
if duration_1q == durations_1q[-1]:
# # set legend to be outside of plot
# handles, labels = ax.get_legend_handles_labels()
# set marker color to black
# handles = [h[0] for h in handles]
# for i in handles:
# i.set_markerfacecolor('k')
# by_label = dict(zip(labels, handles))
# ax.legend(by_label.values(), by_label.keys(), loc='upper center', bbox_to_anchor=(0.5, -0.1), ncol=4, fancybox=True, shadow=True)
# ax.legend(bbox_to_anchor=(.5, .5), loc='upper left', ncols = 9, borderaxespad=0.)
# create legend off to the right
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
# force x and y axis to be the same scale
#fig.tight_layout()
plt.show()
from itertools import combinations
coordinate_list = list(w.weyl_points.keys())
print (coordinate_list)
weyl_edges = []
for c1, c2 in combinations(coordinate_list, 2):
if set([c1, c2]) in [set(["A1", "O"]), set(["A1", "A1"]), set(["A1", "A2"])]:
weyl_edges.append([c1, c2, True])
else:
weyl_edges.append([c1, c2, False])
w.weyl_edges = weyl_edges
w.plot()
# save fig as pdf
from slam.utils.visualize import fpath_images
fig.savefig(f'{fpath_images}/speed_limit.pdf', bbox_inches='tight')
#save as svg
fig.savefig(f'{fpath_images}/speed_limit.svg', bbox_inches='tight')
#rewrite ConversionGainGate to have a cost function that is dynamic in the parameters
from slam.utils.gates.custom_gates import ConversionGainGate
class SpeedLimitedGate(ConversionGainGate):
def __init__(self, p1, p2, g1, g2, t_el, speed_limit_function):
self.g1 = g1 #conversion
self.g2 = g2 #gain
self.t_el = t_el
self.slf = speed_limit_function
super().__init__(p1, p2, g1, g2, t_el)
def cost(self):
assert not (self.g1 == 0 and self.g2 ==0)
#norm = np.pi/2 # TODO move norm from preprocessing into here
# get upper bound of g terms from speed limit data
xs = np.linspace(0, np.pi/2, N) #XXX, danger! assumes the max intercept was on the x-axis (assumes y-axis intercept is np.pi/2)
if self.g1 == 0: #avoid case when ratio is undefined by only scaling
idx = 0
scaled_g1, scaled_g2 = float(xs[idx]), float(s(xs[idx]))
else:
ratio = self.g2/self.g1 * xs
idx = max(np.argwhere(np.abs(ratio - self.slf(xs)) < 0.02))[0]
scaled_g1, scaled_g2 = float(xs[idx]), float(ratio[idx]) #conversion, gain
#inversely scale time for new g terms
# should be the same unless either g1 or g2 is 0
if self.g1 == 0:
scale = scaled_g2/self.g2
else:
scale = scaled_g1/self.g1
# if scale < 1 means we are decreasing strength, so increase time
scaled_t = self.t_el / scale
#cost is duration of gate
return scaled_t
c = ConversionGainGate(0, 0, .25*np.pi, .25*np.pi, 1) #using vanilla class same as linear speed limit
c.cost()
c = SpeedLimitedGate(0, 0, .25*np.pi, .25*np.pi, 1, speed_limit_function=s)
c.cost()
s2 = lambda x: -x + np.pi/2
d = SpeedLimitedGate(0, 0, .25*np.pi, .25*np.pi, 1, speed_limit_function=s2)
d.cost()
#rounding error when finding intersection?
e = SpeedLimitedGate(*[0, 0, 0.009817477042468103, 0.18653206380689397, 1], speed_limit_function=s)
e.cost()
# step 3 univariate spline
from scipy.interpolate import UnivariateSpline
N=400
plt.figure()
s2 = lambda x: -x + np.pi/2
xs = np.linspace(0, np.pi/2, N)
plt.plot(xs, s2(xs), 'o-', xs, s2(xs))
plt.ylabel("gain amp(DAC)")
plt.xlabel('conv amp(DAC)')
plt.xlim(0,max(xs))
plt.ylim(0,max(s(xs)))
#plot cnot gate
gate_c = 0.25*np.pi
gate_g = 0.25*np.pi
if gate_c == 0:
plt.plot([0, 0], [0, max(s(xs))], 'ro')
else:
ratio = gate_g/gate_c * xs
plt.plot(xs, ratio, 'r--')
if gate_c == 0:
idx = 0
print(xs[idx], s2(xs[idx]))
else:
idx = max(np.argwhere(np.abs(ratio - s2(xs)) < 0.01))
print(xs[idx], ratio[idx])
plt.plot(xs[idx], s2(xs[idx]), 'ro')
plt.show()
np.pi/2
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
dag_drawer(dag)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/Bikramaditya0154/Quantum-Simulation-of-the-ground-state-of-Hydrogen-molecule-using-Variational-Quantum-Eigensolver-
|
Bikramaditya0154
|
from qiskit.algorithms import VQE
from qiskit_nature.algorithms import (GroundStateEigensolver,
NumPyMinimumEigensolverFactory)
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureMoleculeDriver, ElectronicStructureDriverType)
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import ParityMapper
import matplotlib.pyplot as plt
import numpy as np
from qiskit_nature.circuit.library import UCCSD, HartreeFock
from qiskit.circuit.library import EfficientSU2
from qiskit.algorithms.optimizers import COBYLA, SPSA, SLSQP
from qiskit.opflow import TwoQubitReduction
from qiskit import BasicAer, Aer
from qiskit.utils import QuantumInstance
from qiskit.utils.mitigation import CompleteMeasFitter
from qiskit.providers.aer.noise import NoiseModel
def get_qubit_op(dist):
# Define Molecule
molecule = Molecule(
# Coordinates in Angstrom
geometry=[
["H", [0.0, 0.0, 0.0] ],
["H", [dist, 0.0, 0.0] ]
],
multiplicity=1, # = 2*spin + 1
charge=0,
)
driver = ElectronicStructureMoleculeDriver(
molecule=molecule,
basis="sto3g",
driver_type=ElectronicStructureDriverType.PYSCF)
# Get properties
properties = driver.run()
num_particles = (properties
.get_property("ParticleNumber")
.num_particles)
num_spin_orbitals = int(properties
.get_property("ParticleNumber")
.num_spin_orbitals)
# Define Problem, Use freeze core approximation, remove orbitals.
problem = ElectronicStructureProblem(
driver
)
second_q_ops = problem.second_q_ops() # Get 2nd Quant OP
num_spin_orbitals = problem.num_spin_orbitals
num_particles = problem.num_particles
mapper = ParityMapper() # Set Mapper
hamiltonian = second_q_ops[0] # Set Hamiltonian
# Do two qubit reduction
converter = QubitConverter(mapper,two_qubit_reduction=True)
reducer = TwoQubitReduction(num_particles)
qubit_op = converter.convert(hamiltonian)
qubit_op = reducer.convert(qubit_op)
return qubit_op, num_particles, num_spin_orbitals, problem, converter
def exact_solver(problem, converter):
solver = NumPyMinimumEigensolverFactory()
calc = GroundStateEigensolver(converter, solver)
result = calc.solve(problem)
return result
backend = BasicAer.get_backend("statevector_simulator")
distances = np.arange(0.5, 5.0, 0.1)
exact_energies = []
vqe_energies = []
optimizer = SLSQP(maxiter=5)
for dist in distances:
(qubit_op, num_particles, num_spin_orbitals,
problem, converter) = get_qubit_op(dist)
result = exact_solver(problem,converter)
exact_energies.append(result.total_energies[0].real)
init_state = HartreeFock(num_spin_orbitals, num_particles, converter)
var_form = UCCSD(converter,
num_particles,
num_spin_orbitals,
initial_state=init_state)
vqe = VQE(var_form, optimizer, quantum_instance=backend)
vqe_calc = vqe.compute_minimum_eigenvalue(qubit_op)
vqe_result = problem.interpret(vqe_calc).total_energies[0].real
vqe_energies.append(vqe_result)
print(f"Interatomic Distance: {np.round(dist, 2)}",
f"VQE Result: {vqe_result:.5f}",
f"Exact Energy: {exact_energies[-1]:.5f}")
print("All energies have been calculated.")
plt.plot(distances, exact_energies, label="Exact Energy")
plt.plot(distances, vqe_energies, label="VQE Energy")
plt.xlabel('Interatomic distance (Angstrom)')
plt.ylabel('Energy(Hartree)')
plt.legend()
plt.show()
|
https://github.com/qismib/TraNQI
|
qismib
|
#importing packages
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit import transpile, assemble
from qiskit.visualization import *
#######################
#IMPLEMENTING QUANTUM CLASS: 1 trainable parameter
#Hadamard gate (superposition) + Rotation_Y (trainable parameter) + Measure_Z. Returning the expectation value over n_shots
class QuantumCircuit:
"""
This class provides an interface to interact with our Quantum Circuit
"""
def __init__(self, n_qubits, backend, shots):
#-----Circuit definition
self._circuit = qiskit.QuantumCircuit(n_qubits)
self.theta = qiskit.circuit.Parameter('theta')
all_qubits = [i for i in range (n_qubits)]#qubits vector
self._circuit.h(all_qubits)#over all the qubits
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
#-----
self.backend = backend
self.shots = shots
def run(self, thetas):
#acting on a simulator
t_qc = transpile(self._circuit,
self.backend)#matching the features of a quantum device
qobj = assemble(t_qc,
shots = self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])#assembling features (circuit, sampling, parameter list)
job = self.backend.run(qobj)#running on the simulator
result = job.result().get_counts() #counts for each values: |0> or |1>. DIVERSO DA LINK
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probability for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
#testing the implementation
simulator = qiskit.Aer.get_backend('qasm_simulator')
n_qubits = 1
circuit = QuantumCircuit(n_qubits, simulator, 100)
print(circuit._circuit)
#circuit._circuit.draw(output='mpl')#to print as a pyplot figure (new library needed)
exp = circuit.run([np.pi])
print('Expected value for rotation pi: {}'.format(exp[0]))
#######################
#CREATING A QUANTUM CLASSICAL CLASS
#extending autograd functions for a quantum layer(forward and backward)
class HybridFunction(Function):
"""Hybrid quantum-classical function definition"""
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
"""Forward pass computation"""
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
# context variable (it may take multiple values and return them related to the context). Used to keep track for backpropagation
expectation_z = ctx.quantum_circuit.run(input[0].tolist()) #evaluating model with trainable parameter
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result) #saves a given tensor for a future call to backward (trainable parameter and the result obtained)
return result
@staticmethod
def backward(ctx, grad_output): #grad_output os previous gradient
"""Backward computation"""
input, expectation =ctx.saved_tensors #evaluated in forward
input_list = np.array(input.tolist())
#shifting parameters
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients=[]
for i in range(len(input_list)):
#evaluating model after shift
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
#evaluating gradient with finite difference formula
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
#returns the chain of previous gradient and evaluated gradient
class Hybrid(nn.Module):
"""Hybrid quantum-cassical layer definition"""
def __init__(self, n_qubits ,backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(n_qubits, backend, shots)
self.shift = shift #parameter shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift) #calling forward and backward
##################3
#DATA LOADING
#training data
n_samples=100
X_train=datasets.MNIST(root='./data', train=True, download=True, transform=transforms.Compose([transforms.ToTensor()]))
#keeping only labels 0 and 1
idx=np.append(np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples])
X_train.data = X_train.data[idx] #tensor values
X_train.targets = X_train.targets[idx]#tensor labels
#making batches (dim = 1). Ir returns an iterable(pytorch tensor)
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
data_iter = iter(train_loader)#making the iterable an iterator, an object with the next method that can be used in a for cycle
#showing samples
n_samples_show = 6
fig, axes = plt.subplots(nrows=1, ncols=int(n_samples_show), figsize=(10, 3))
#subolot returns the figure and axis that are indipendent as default
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[int(n_samples_show) - 1].imshow(images[0].numpy().squeeze(), cmap='gray')#squeeze removes unuseful dim(1). Converting into a numpy vector
axes[int(n_samples_show) - 1].set_xticks([])
axes[int(n_samples_show) - 1].set_yticks([])
axes[int(n_samples_show) - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
#validation data
n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
#########################
#CREATING THE NN
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, kernel_size=5) #input = gray scale
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.dropout = nn.Dropout2d() #deactivating randomly some neurons to avoid overfitting
self.fc1 = nn.Linear(256, 64) #input dimension: CH(16) x Matrix_dim (4x4)
self.fc2 = nn.Linear(64,1)
self.hybrid = Hybrid(n_qubits, qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi/2 )
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)),2)
x = F.max_pool2d(F.relu(self.conv2(x)),2)
x = self.dropout(x)
x = x.view(1,-1) #reshaping tensor
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x) #calling the forward method
return torch.cat((x, 1-x),-1)#returning probabilities
#######################
#TRAINING AND TESTING
#function to train the nn
def training_loop (n_epochs, optimizer, model, loss_fn, train_loader):
loss_values = []
for epoch in range(0, n_epochs, +1):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()#getting rid of previous gradients
output = model(data)#forward pass
loss = loss_fn(output, target)
loss.backward()
optimizer.step()#updating parameters
total_loss.append(loss.item())#item transforms into a number
loss_values.append(sum(total_loss)/len(total_loss))#obtainign the average loss
print('Training [{:.0f}%] Loss: {:.4f}'.format(100*(epoch+1)/n_epochs, loss_values[-1]))
return loss_values
#defining a function to test our net
def validate(model, test_loader, loss_function, n_test, axes):
correct = 0
total_loss = []
count = 0
with torch.no_grad(): # disabling the gradient as we don't want to update parameters
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data) #evaluating the model on test data
# evaluating the accuracy of our model
pred = output.argmax(dim=1,
keepdim=True) # we are interested in the max value of probability
correct += pred.eq(target.view_as(pred)).sum().item() # checking if it matches with label
#evluating loss function
loss = loss_function(output, target)
total_loss.append(loss.item())
#printing the resut as images
if count >= n_test:
continue
else:
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('Predicted {}'.format(pred.item()))
count += 1
print('Performance on test data: \n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'
.format(sum(total_loss)/len(total_loss),(correct / len(test_loader))*100))
#Training the NN
#we can use any optimiser, learning rate and cost/loss function to train over multiple epochs
model = Net()
params = list(model.parameters())
learning_rate = 0.001
optimizer = optim.Adam(params, learning_rate)
loss_func = nn.NLLLoss()
epochs = 20
loss_list = []
model.train() #training the module in training mode(specifying the intention to the layers). Used for dropout or batchnorm
loss_list = (training_loop(epochs, optimizer, model, loss_func, train_loader))
#plotting the training graph
plt.figure(num=2)
plt.plot(loss_list)
plt.title('Hybrid NN Training convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
###########################
#TESTING THE NN
n_test_show = 6
fig, axes = plt.subplots(nrows=1, ncols=n_test_show, figsize=(10, 3))
model.eval()
validate(model, test_loader, loss_func, n_test_show, axes)
plt.show()
|
https://github.com/qclib/qclib
|
qclib
|
# 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.
"""UnitaryGate tests"""
import json
import numpy
from numpy.testing import assert_allclose
import qiskit
from qiskit.extensions.unitary import UnitaryGate
from qiskit.test import QiskitTestCase
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.operators import Operator
from qiskit.transpiler.passes import CXCancellation
class TestUnitaryGate(QiskitTestCase):
"""Tests for the Unitary class."""
def test_set_matrix(self):
"""Test instantiation"""
try:
UnitaryGate([[0, 1], [1, 0]])
# pylint: disable=broad-except
except Exception as err:
self.fail(f"unexpected exception in init of Unitary: {err}")
def test_set_matrix_raises(self):
"""test non-unitary"""
try:
UnitaryGate([[1, 1], [1, 0]])
# pylint: disable=broad-except
except Exception:
pass
else:
self.fail("setting Unitary with non-unitary did not raise")
def test_set_init_with_unitary(self):
"""test instantiation of new unitary with another one (copy)"""
uni1 = UnitaryGate([[0, 1], [1, 0]])
uni2 = UnitaryGate(uni1)
self.assertEqual(uni1, uni2)
self.assertFalse(uni1 is uni2)
def test_conjugate(self):
"""test conjugate"""
ymat = numpy.array([[0, -1j], [1j, 0]])
uni = UnitaryGate([[0, 1j], [-1j, 0]])
self.assertTrue(numpy.array_equal(uni.conjugate().to_matrix(), ymat))
def test_adjoint(self):
"""test adjoint operation"""
uni = UnitaryGate([[0, 1j], [-1j, 0]])
self.assertTrue(numpy.array_equal(uni.adjoint().to_matrix(), uni.to_matrix()))
class TestUnitaryCircuit(QiskitTestCase):
"""Matrix gate circuit tests."""
def test_1q_unitary(self):
"""test 1 qubit unitary matrix"""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
qc.x(qr[0])
qc.append(UnitaryGate(matrix), [qr[0]])
# test of qasm output
self.log.info(qc.qasm())
# test of text drawer
self.log.info(qc)
dag = circuit_to_dag(qc)
dag_nodes = dag.named_nodes("unitary")
self.assertTrue(len(dag_nodes) == 1)
dnode = dag_nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0],))
assert_allclose(dnode.op.to_matrix(), matrix)
def test_2q_unitary(self):
"""test 2 qubit unitary matrix"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmax, sigmay)
qc.x(qr[0])
uni2q = UnitaryGate(matrix)
qc.append(uni2q, [qr[0], qr[1]])
passman = PassManager()
passman.append(CXCancellation())
qc2 = passman.run(qc)
# test of qasm output
self.log.info(qc2.qasm())
# test of text drawer
self.log.info(qc2)
dag = circuit_to_dag(qc)
nodes = dag.two_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1]))
assert_allclose(dnode.op.to_matrix(), matrix)
qc3 = dag_to_circuit(dag)
self.assertEqual(qc2, qc3)
def test_3q_unitary(self):
"""test 3 qubit unitary matrix on non-consecutive bits"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay))
qc.x(qr[0])
uni3q = UnitaryGate(matrix)
qc.append(uni3q, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
# test of text drawer
self.log.info(qc)
dag = circuit_to_dag(qc)
nodes = dag.multi_qubit_ops()
self.assertEqual(len(nodes), 1)
dnode = nodes[0]
self.assertIsInstance(dnode.op, UnitaryGate)
self.assertEqual(dnode.qargs, (qr[0], qr[1], qr[3]))
assert_allclose(dnode.op.to_matrix(), matrix)
def test_1q_unitary_int_qargs(self):
"""test single qubit unitary matrix with 'int' and 'list of ints' qubits argument"""
sigmax = numpy.array([[0, 1], [1, 0]])
sigmaz = numpy.array([[1, 0], [0, -1]])
# new syntax
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.unitary(sigmax, 0)
qc.unitary(sigmax, qr[1])
qc.unitary(sigmaz, [0, 1])
# expected circuit
qc_target = QuantumCircuit(qr)
qc_target.append(UnitaryGate(sigmax), [0])
qc_target.append(UnitaryGate(sigmax), [qr[1]])
qc_target.append(UnitaryGate(sigmaz), [[0, 1]])
self.assertEqual(qc, qc_target)
def test_qobj_with_unitary_matrix(self):
"""test qobj output with unitary matrix"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmay, numpy.kron(sigmax, sigmay))
qc.rx(numpy.pi / 4, qr[0])
uni = UnitaryGate(matrix)
qc.append(uni, [qr[0], qr[1], qr[3]])
qc.cx(qr[3], qr[2])
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[1]
self.assertEqual(instr.name, "unitary")
assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix)
# check conversion to dict
qobj_dict = qobj.to_dict()
class NumpyEncoder(json.JSONEncoder):
"""Class for encoding json str with complex and numpy arrays."""
def default(self, obj):
if isinstance(obj, numpy.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
# check json serialization
self.assertTrue(isinstance(json.dumps(qobj_dict, cls=NumpyEncoder), str))
def test_labeled_unitary(self):
"""test qobj output with unitary matrix"""
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
sigmax = numpy.array([[0, 1], [1, 0]])
sigmay = numpy.array([[0, -1j], [1j, 0]])
matrix = numpy.kron(sigmax, sigmay)
uni = UnitaryGate(matrix, label="xy")
qc.append(uni, [qr[0], qr[1]])
qobj = qiskit.compiler.assemble(qc)
instr = qobj.experiments[0].instructions[0]
self.assertEqual(instr.name, "unitary")
self.assertEqual(instr.label, "xy")
def test_qasm_unitary_only_one_def(self):
"""test that a custom unitary can be converted to qasm and the
definition is only written once"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0]])
qc.append(unitary_gate, [qr[1]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0 { u(0,0,0) q0; }\n"
"qreg q0[2];\ncreg c0[1];\n"
"x q0[0];\n"
"unitary q0[0];\n"
"unitary q0[1];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_unitary_twice(self):
"""test that a custom unitary can be converted to qasm and that if
the qasm is called twice it is the same every time"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.array([[1, 0], [0, 1]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0]])
qc.append(unitary_gate, [qr[1]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0 { u(0,0,0) q0; }\n"
"qreg q0[2];\ncreg c0[1];\n"
"x q0[0];\n"
"unitary q0[0];\n"
"unitary q0[1];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_2q_unitary(self):
"""test that a 2 qubit custom unitary can be converted to qasm"""
qr = QuantumRegister(2, "q0")
cr = ClassicalRegister(1, "c0")
qc = QuantumCircuit(qr, cr)
matrix = numpy.asarray([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
unitary_gate = UnitaryGate(matrix)
qc.x(qr[0])
qc.append(unitary_gate, [qr[0], qr[1]])
qc.append(unitary_gate, [qr[1], qr[0]])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0,q1 { u(pi,-pi/2,pi/2) q0; u(pi,pi/2,-pi/2) q1; }\n"
"qreg q0[2];\n"
"creg c0[1];\n"
"x q0[0];\n"
"unitary q0[0],q0[1];\n"
"unitary q0[1],q0[0];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_qasm_unitary_noop(self):
"""Test that an identity unitary can be converted to OpenQASM 2"""
qc = QuantumCircuit(QuantumRegister(3, "q0"))
qc.unitary(numpy.eye(8), qc.qubits)
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate unitary q0,q1,q2 { }\n"
"qreg q0[3];\n"
"unitary q0[0],q0[1],q0[2];\n"
)
self.assertEqual(expected_qasm, qc.qasm())
def test_unitary_decomposition(self):
"""Test decomposition for unitary gates over 2 qubits."""
qc = QuantumCircuit(3)
qc.unitary(random_unitary(8, seed=42), [0, 1, 2])
self.assertTrue(Operator(qc).equiv(Operator(qc.decompose())))
def test_unitary_decomposition_via_definition(self):
"""Test decomposition for 1Q unitary via definition."""
mat = numpy.array([[0, 1], [1, 0]])
self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat))
def test_unitary_decomposition_via_definition_2q(self):
"""Test decomposition for 2Q unitary via definition."""
mat = numpy.array([[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, -1, 0, 0]])
self.assertTrue(numpy.allclose(Operator(UnitaryGate(mat).definition).data, mat))
def test_unitary_control(self):
"""Test parameters of controlled - unitary."""
mat = numpy.array([[0, 1], [1, 0]])
gate = UnitaryGate(mat).control()
self.assertTrue(numpy.allclose(gate.params, mat))
self.assertTrue(numpy.allclose(gate.base_gate.params, mat))
|
https://github.com/AlluSu/Grover-Search
|
AlluSu
|
'''
Demonstrating Grover's search algorithm.
Scenario: We have a phone book containing names and numbers. Because the phone book is sorted alphabetically by names,
it is easy to find a persons phone number by persons name. However, a more difficult task would be if we want to find a person by a phone number.
Number-wise, if we have a million (1 000 000) entries in a phone book, we would on average have to look up half of it to find the correct entry (500 000 lookups).
Worst case complexity is 1 000 000 queries.
Grover's algorithm provides a quadratical speed-up to unstructured search probelms. Applying Grover's algorithm to this problem would reduce the needed amount
of lookups to only 1000, in the worst case.
This program simulates the above scenario on a smaller scale.
'''
import json
import random
from os import getenv
from dotenv import load_dotenv
import matplotlib.pyplot as plt
from qiskit import transpile, assemble, IBMQ
from qiskit.quantum_info import Statevector
from qiskit.algorithms import AmplificationProblem, Grover
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
# Loads the API key used to connect to the cloud
load_dotenv()
# Global variables for easier maintenace of code
TOKEN = getenv('IBM_QUANTUM_TOKEN')
USED_BACKEND = 'ibm_oslo'
FILE_TO_WRITE_NAME ='History.txt'
# Function used for printing quantum circuits as matplotlib images
def print_quantum_circuits(circuits):
#Matplotlib output, freezes the program execution until windows are closed
for circuit in circuits:
circuit.draw(output = 'mpl')
plt.show()
# Function used for connecting to the IBM quantum computer
# TODO: Remove deprecated components
def connect_to_cloud(token, backend):
IBMQ.save_account(token, overwrite=True)
provider = IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
used_backend = provider.get_backend(backend) # for lower latency choosing the geographically closest one
print(f"The used backend is: {used_backend}")
return used_backend
# Writing the randomized entry to see if the results are correct by the quantum computer.
# Results can be obtained from the IBM cloud with the job_id.
# TODO: Use a real (cloud) database instead of a .txt-file.
def write_to_history(randomized_entry, job_id):
results_history = open(FILE_TO_WRITE_NAME, "a")
results_history.write("\n" + str(randomized_entry) + " " + str(job_id) + "\n")
results_history.close()
# Run the Grover search on a simulator backend.
# TODO: Refactor logging/printing to separate component.
def run_grover_in_simulator(grover_circuits):
service = QiskitRuntimeService()
backend_simulator = "ibmq_qasm_simulator"
with Session(service=service, backend=backend_simulator):
sampler = Sampler()
job = sampler.run(circuits=grover_circuits, shots=1000)
job_monitor(job)
result = job.result()
print('===================================== RESULTS =====================================')
print(f"{result.quasi_dists}")
print(f"{result.metadata}")
qubits = 3
optimal_amount = Grover.optimal_num_iterations(1, qubits)
print(f"The optimal amount of Grover iterations is: {optimal_amount} with {qubits} qubits")
return result, job
# Run the Grover search on a real quantum computer backend.
def run_grover_in_quantum_computer(random_name_formatted, backend, grover_circuits):
print(f"The value, which we are looking for is: {random_name_formatted}")
mapped_circuit = transpile(grover_circuits, backend=backend)
quantum_object = assemble(mapped_circuit, backend=backend, shots=1000)
job = backend.run(quantum_object)
job_monitor(job)
job_id = job.job_id()
result = job.result()
print(result)
return result, job
# Visualize the results gotten from the simulator run.
# TODO: Refactor logging/printing to separate component.
def visualize_simulator_results(result, random_name_formatted):
for distribution in range(0, len(result.quasi_dists)):
results_dictionary = result.quasi_dists[distribution].binary_probabilities()
answer = max(results_dictionary, key=results_dictionary.get)
print(f"With {distribution + 1} iterations the following probabilities were returned: \n {result.quasi_dists[distribution]}")
print(f"Maximum probability was for the value {answer}")
print(f"Correct answer: {random_name_formatted}")
print('Correct!' if answer == random_name_formatted else 'Failure!')
print('\n')
histogram = plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations', '3 iterations', '4 iterations', '5 iterations', '6 iterations', '7 iterations', '8 iterations'])
plt.xlabel("Which entry in the data [0,..,7]")
plt.show()
def visualize_existing_simulator_results():
with open('test-results/simulator/cfuq0n7b5be8coe26so0-result.json') as f:
measurements = json.load(f)
plot_histogram(measurements['quasi_dists'], legend=['1 iteration', '2 iterations', '3 iterations', '4 iterations', '5 iterations', '6 iterations', '7 iterations', '8 iterations'])
plt.show()
def visualize_existing_qc_results():
with open('test-results/real/63fda07b6d831406fd4b6847-output.json') as f:
measurements = json.load(f)
measurements_results = measurements.get('results')
counts_list = []
for value in measurements_results:
counts_list.append(value.get('data').get("counts"))
plot_histogram(data=counts_list, legend=['1 iteration', '2 iterations', '3 iterations', '4 iterations', '5 iterations', '6 iterations', '7 iterations', '8 iterations'])
plt.show()
# The real program execution starts here.
def run_grover():
# Commented out, used during the writing of the seminar report to visualize results to use in the report
# TODO: Refactor to get results straight from the cloud with job id, or give path as parameter
# visualize_existing_simulator_results()
# visualize_existing_qc_results()
# STEP 1: Construct and define the unstructured search problem.
random_name = random.randint(0,7) # This simulates a random person from a phone book containing 8 entries [0,..,7]. As 8 = 2³, we need 3 qubits.
random_name_formatted = format(random_name, '03b') # This formats the random person's name to a 3-bit string
oracle = Statevector.from_label(random_name_formatted) # Oracle, which is a black-box quantum circuit telling if your guess is right or wrong. We will let the oracle know the owner.
unstructured_search = AmplificationProblem(oracle, is_good_state=random_name_formatted) # Grover's algorithm uses a technique for modifying quantum states to raise the probability amplitude of the wanted value
# STEP 2: Constructing the adequate quantum circuit for the problem
grover_circuits = []
# Grover's algorithm's accuracy to find the right solution increases with the amount of iterations ip to a certain point (in theory).
values = [0, 1, 2, 3, 4, 5, 6, 7]
for value in range(0, len(values)):
grover = Grover(iterations=values[value]) # using Grover's algorithm straight from the Qiskit library
quantum_circuit = grover.construct_circuit(unstructured_search)
quantum_circuit.measure_all()
grover_circuits.append(quantum_circuit)
# Commented for now so the program does not freeze
# Used for printing the quantum circuits if interested to see them
# print_quantum_circuits(grover_circuits)
# STEP 3: Submit the circuits to IBM Quantum Computer or run with a simulator
# NOTE: Occasionally the simulator is significantly faster than the real computer due to queue
try:
user_option = int(input(
"Press \n 1 for simulator \n 2 for real hardware \n 3 for retrieving an existing job by job_id \n 4 for both simulator and real hardware \n"
))
except ValueError:
raise ValueError('Please give an integer')
# Simulator
if user_option == 1:
# Result from Grover's algorithm
result, job = run_grover_in_simulator(grover_circuits)
# Write the randomized entry and job id of the run to a file
write_to_history(random_name_formatted, job)
# Counting probabilities and doing plotting & visualization with matplotlib
visualize_simulator_results(result, random_name_formatted)
# Real quantum computer
elif user_option == 2:
# Connect to IBM cloud and get the backend provider.
backend = connect_to_cloud(TOKEN, USED_BACKEND)
result = run_grover_in_quantum_computer(random_name_formatted, backend, grover_circuits)
# Write the randomized entry and job id of the run to a file
write_to_history(random_name_formatted, result.job_id())
# Due to occasional queues (45 minutes to 4 hours) in the free-tier quantum computer, it is easier to investigate and experiment by using previous runs, which can be obtained with the job id.
elif user_option == 3:
job_id = input("Give job id: ")
backend = connect_to_cloud(TOKEN, USED_BACKEND)
result = backend.retrieve_job(job_id)
print(f"as a dict: {result.result().to_dict()}")
all_results_as_dict = result.result().to_dict()
print(all_results_as_dict)
# This runs the job on a simulator and on the real hardware for the same randomized value.
# Decided to create this due to better and transparent comparison for the different systems.
elif user_option == 4:
result = run_grover_in_simulator(grover_circuits)
write_to_history(random_name_formatted, result[1].job_id())
visualize_simulator_results(result[0], random_name_formatted)
backend = connect_to_cloud(TOKEN, USED_BACKEND)
quantum_job_result_and_id = run_grover_in_quantum_computer(random_name_formatted, backend, grover_circuits)
write_to_history(random_name_formatted, quantum_job_result_and_id[1].job_id())
# Undefined input closes the program.
else:
print("Closing program!")
exit()
def main():
run_grover()
if __name__ == "__main__":
main()
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Unit tests for QASM preprocessing functions
"""
import pytest
from qiskit import QuantumCircuit
from qbraid.interface import circuits_allclose
from qbraid.passes.qasm2 import flatten_qasm_program
from qbraid.programs import load_program
from qbraid.transpiler.conversions.qasm2 import qasm2_to_cirq
qasm_0 = """OPENQASM 2.0;
include "qelib1.inc";
gate rzx(param0) q0,q1 { h q1; cx q0,q1; rz(-pi/4) q1; cx q0,q1; h q1; }
gate ecr q0,q1 { rzx(pi/4) q0,q1; x q0; rzx(-pi/4) q0,q1; }
gate rzx_6320157840(param0) q0,q1 { h q1; cx q0,q1; rz(2.3200048200765524) q1; cx q0,q1; h q1; }
qreg q[4];
cry(5.518945082555831) q[0],q[1];
u(5.75740842861076,5.870881397684582,1.8535618384181967) q[2];
ecr q[3],q[0];
rzx_6320157840(2.3200048200765524) q[2],q[1];
rccx q[1],q[2],q[3];
csx q[0],q[1];
rxx(5.603791034636421) q[2],q[0];
"""
qasm_1 = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
rccx q[1],q[2],q[0];
cu(5.64,3.60,3.73, 5.68) q[1],q[0];
c3x q[1],q[3],q[0],q[2];
c3sqrtx q[3],q[1],q[2],q[0];
c4x q[2],q[0],q[1],q[4],q[3];
rc3x q[1],q[2],q[0],q[3];
"""
qasm_lst = [qasm_0, qasm_1]
def strings_equal(s1, s2):
"""Check if two strings are equal, ignoring spaces and newlines."""
s1_clean = s1.replace(" ", "").replace("\n", "")
s2_clean = s2.replace(" ", "").replace("\n", "")
return s1_clean == s2_clean
@pytest.mark.parametrize("qasm_str", qasm_lst)
def test_preprocess_qasm(qasm_str):
"""Test converting qasm string to format supported by Cirq parser"""
qiskit_circuit = QuantumCircuit().from_qasm_str(qasm_str)
supported_qasm = flatten_qasm_program(qasm_str)
cirq_circuit = qasm2_to_cirq(supported_qasm)
qprogram = load_program(cirq_circuit)
qprogram._convert_to_line_qubits()
cirq_circuit_compat = qprogram.program
assert circuits_allclose(cirq_circuit_compat, qiskit_circuit)
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
from qiskit.circuit.library.standard_gates import RXGate, RZGate, CXGate, CZGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
def anzats_circ1(thetas, D2, in_state):
qr = QuantumRegister(4, name="q")
qc = QuantumCircuit(qr)
qc.initialize(in_state)
for d in range(D2):
qc.append(RXGate(thetas[0]), [qr[0]])
qc.append(RXGate(thetas[1]), [qr[1]])
qc.append(RXGate(thetas[2]), [qr[2]])
qc.append(RXGate(thetas[3]), [qr[3]])
qc.append(RZGate(thetas[4]), [qr[0]])
qc.append(RZGate(thetas[5]), [qr[1]])
qc.append(RZGate(thetas[6]), [qr[2]])
qc.append(RZGate(thetas[7]), [qr[3]])
qc.append(CZGate(), [qr[0], qr[1]])
qc.append(CZGate(), [qr[1], qr[2]])
qc.append(CZGate(), [qr[2], qr[3]])
qc.barrier(qr)
qc.append(RXGate(thetas[0]), [qr[0]])
qc.append(RXGate(thetas[1]), [qr[1]])
qc.append(RXGate(thetas[2]), [qr[2]])
qc.append(RXGate(thetas[3]), [qr[3]])
qc.append(RZGate(thetas[4]), [qr[0]])
qc.append(RZGate(thetas[5]), [qr[1]])
qc.append(RZGate(thetas[6]), [qr[2]])
qc.append(RZGate(thetas[7]), [qr[3]])
qc.measure_all()
return qc
def anzats_circ1_uninitialized(thetas, D2):
qr = QuantumRegister(4, name="q")
qc = QuantumCircuit(qr)
for d in range(D2):
qc.append(RXGate(thetas[0]), [qr[0]])
qc.append(RXGate(thetas[1]), [qr[1]])
qc.append(RXGate(thetas[2]), [qr[2]])
qc.append(RXGate(thetas[3]), [qr[3]])
qc.append(RZGate(thetas[4]), [qr[0]])
qc.append(RZGate(thetas[5]), [qr[1]])
qc.append(RZGate(thetas[6]), [qr[2]])
qc.append(RZGate(thetas[7]), [qr[3]])
qc.append(CZGate(), [qr[0], qr[1]])
qc.append(CZGate(), [qr[1], qr[2]])
qc.append(CZGate(), [qr[2], qr[3]])
qc.barrier(qr)
qc.append(RXGate(thetas[0]), [qr[0]])
qc.append(RXGate(thetas[1]), [qr[1]])
qc.append(RXGate(thetas[2]), [qr[2]])
qc.append(RXGate(thetas[3]), [qr[3]])
qc.append(RZGate(thetas[4]), [qr[0]])
qc.append(RZGate(thetas[5]), [qr[1]])
qc.append(RZGate(thetas[6]), [qr[2]])
qc.append(RZGate(thetas[7]), [qr[3]])
qc.measure_all()
return qc
import numpy as np
def get_k_basis(k, n):
full_basis = np.identity(n)
return full_basis[:k]
from qiskit.opflow import X, Z, I, H, Y
# for convinience let all coefficients ai and Jij be 0.5
H_transverse_ising = 0.5*((I^I^I^X) + (I^I^X^I) + (I^X^I^I) + (X^I^I^I) + \
(Z^Z^I^I) + (Z^I^Z^I) + (Z^I^I^Z) + (I^Z^Z^I) + \
(I^Z^I^Z) + (I^I^Z^Z))
# TODO: change this to a 4 qubits Hamiltonian
H2_molecule_Hamiltonian = -0.5053051899926562*(I^I) + \
-0.3277380754984016*(Z^I) + \
0.15567463610622564*(Z^Z) + \
-0.3277380754984016*(I^Z)
import matplotlib
from qiskit import assemble, Aer
from qiskit import *
from qiskit.visualization import plot_histogram
import math
sim = Aer.get_backend('aer_simulator')
def convert_string_to_index(string):
return int(string, 2)
# TODO: this isn't the right way to calculate the result state, should be changed
def convert_result_to_state(result):
total_meas = 0
for k in result.keys():
total_meas += result[k]
amount_of_qubits = len(k)
state = np.zeros(2**amount_of_qubits)
for k in result.keys():
index = convert_string_to_index(k)
state[index] = result[k]/total_meas
return state
# TODO: finish these functions
def calc_ising_avg(qc):
avg = 0
for i in range(4):
qc_tmp = qc.copy()
qc_tmp.append(H, [i])
def calc_molecular_avg(qc):
pass
def calc_target_func1(thetas, basis, D2, Ham):
target_func = 0
for j in basis:
qc = anzats_circ1(thetas, D2, j)
print(qc.draw())
qobj = assemble(qc)
result = sim.run(qobj).result().get_counts()
state = convert_result_to_state(result)
dagger_state = np.matrix(state)
state = dagger_state.getH()
state = np.array(state)
dagger_state = np.array(dagger_state)
# TODO: calculate this with estimation with the Ham pauli strings
# if Ham == "Ising Model":
# product = calc_ising_avg(qc)
# else product = calc_molecular_avg(qc)
product = np.matmul(Ham, state)
product = np.matmul(dagger_state, product)
target_func += product
return target_func
# JUST TO RUN AND CHECK
k = 4
basis = get_k_basis(k,16)
D2 = 1
Ham = H_transverse_ising.to_matrix()
thetas = np.zeros(8)
calc_target_func1(thetas, basis, D2, Ham)
def objective_func1(thetas):
k = 4
basis = get_k_basis(k,16)
D2 = 1
Ham = H_transverse_ising.to_matrix()
# Ham = H_transverse_ising
target_func = calc_target_func1(thetas, basis,D2, Ham)
return target_func[0][0]
from qiskit.algorithms.optimizers import L_BFGS_B
bfgs_optimizer = L_BFGS_B(maxiter=60)
point, value, nfev = bfgs_optimizer.optimize(8,objective_func1,initial_point=np.zeros(8))
print(point)
print("---point---")
print(value)
print("---value---")
thetas_opt = point
def anzats_circ2(phis, D1, in_state):
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
qc.initialize(in_state)
for d in range(D1):
qc.append(RXGate(phis[0]), [qr[2]])
qc.append(RXGate(phis[1]), [qr[3]])
qc.append(RZGate(phis[2]), [qr[2]])
qc.append(RZGate(phis[3]), [qr[3]])
qc.append(CZGate(), [qr[2], qr[3]])
qc.barrier(qr)
return qc
def calc_target_func2(thetas_opt, phis, in_state, D1, D2, Ham):
target_func = 0
qc2 = anzats_circ2(phis, D1, in_state)
qc1 = anzats_circ1_uninitialized(thetas_opt, D2)
qc = qc2.compose(qc1)
print(qc.draw())
qobj = assemble(qc)
result = sim.run(qobj).result().get_counts()
state = convert_result_to_state(result)
dagger_state = np.matrix(state)
state = dagger_state.getH()
state = np.array(state)
dagger_state = np.array(dagger_state)
# TODO: calculate this with estimation with the Ham pauli strings
# if Ham == "Ising Model":
# product = calc_ising_avg(qc)
# else product = calc_molecular_avg(qc)
product = np.matmul(Ham, state)
product = np.matmul(dagger_state, product)
target_func += product
return target_func
i = np.random.randint(0,k)
def objective_func2(phis):
in_state = basis[i]
print("in state")
print(in_state)
D1 = 1
D2 = 1
Ham = H_transverse_ising.to_matrix()
# Ham = H_transverse_ising
target_func2 = calc_target_func2(thetas_opt, phis, in_state, D1, D2, Ham)
print("target func:")
print(target_func2[0][0])
return target_func2[0][0]
def objective_func2_neg(phis):
return -1*objective_func2(phis)
#to see wraping function is working well
phis = np.array([np.pi, np.pi, np.pi, np.pi])
exp =objective_func2(phis)
print("exp:")
print(exp)
exp_neg =objective_func2_neg(phis)
print("exp_neg:")
print(exp_neg)
point, value, nfev = bfgs_optimizer.optimize(4,objective_func2_neg,initial_point=np.array([2, 2, 2, 2]))
print(point)
print("---point---")
print(value)
print("---value---")
value = -value
print(value)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can choose different colors for the real and imaginary parts of the density matrix.
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)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import numpy as np
from qiskit import *
qc = QuantumCircuit(3)
# Apply H-gate to each qubit:
for qubit in range(3):
qc.h(qubit)
# See the circuit:
qc.draw('mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
print(out)
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.draw('mpl')
#create circuit with two qubit
qc = QuantumCircuit(2)
# Apply CNOT
qc.cx(0,1)
# See the circuit:
qc.draw('mpl')
#create two qubit circuit
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.h(0)
qc.draw('mpl')
# Let's see the result:
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
print(final_state)
# Apply a CNOT:
qc.cx(0,1)
qc.draw('mpl')
# Let's see the result:
final_state = execute(qc,backend).result().get_statevector()
print(final_state)
|
https://github.com/ranaarp/Qiskit-Meetup-content
|
ranaarp
|
import numpy as np
from qiskit import BasicAer
from qiskit.visualization import plot_histogram
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
input_3sat = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
oracle = LogicalExpressionOracle(input_3sat)
grover = Grover(oracle)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_instance)
print(result['result'])
plot_histogram(result['measurement'])
# Load our saved IBMQ accounts and get the ibmq_16_melbourne backend
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_16_melbourne')
from qiskit.compiler import transpile
# transpile the circuit for ibmq_16_melbourne
grover_compiled = transpile(result['circuit'], backend=backend, optimization_level=3)
print('gates = ', grover_compiled.count_ops())
print('depth = ', grover_compiled.depth())
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
try:
import cplex
from cplex.exceptions import CplexError
except:
print("Warning: Cplex not found.")
import math
from qiskit.utils import algorithm_globals
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.algorithms.optimizers import SPSA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
# Initialize the problem by defining the parameters
n = 3 # number of nodes + depot (n+1)
K = 2 # number of vehicles
# Get the data
class Initializer:
def __init__(self, n):
self.n = n
def generate_instance(self):
n = self.n
# np.random.seed(33)
np.random.seed(1543)
xc = (np.random.rand(n) - 0.5) * 10
yc = (np.random.rand(n) - 0.5) * 10
instance = np.zeros([n, n])
for ii in range(0, n):
for jj in range(ii + 1, n):
instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2
instance[jj, ii] = instance[ii, jj]
return xc, yc, instance
# Initialize the problem by randomly generating the instance
initializer = Initializer(n)
xc, yc, instance = initializer.generate_instance()
class ClassicalOptimizer:
def __init__(self, instance, n, K):
self.instance = instance
self.n = n # number of nodes
self.K = K # number of vehicles
def compute_allowed_combinations(self):
f = math.factorial
return f(self.n) / f(self.K) / f(self.n - self.K)
def cplex_solution(self):
# refactoring
instance = self.instance
n = self.n
K = self.K
my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)]
my_ub = [1 for x in range(0, n**2 + n - 1)]
my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)]
my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join(
["C" for x in range(0, n - 1)]
)
my_rhs = (
2 * ([K] + [1 for x in range(0, n - 1)])
+ [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))]
+ [0 for x in range(0, n)]
)
my_sense = (
"".join(["E" for x in range(0, 2 * n)])
+ "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))])
+ "".join(["E" for x in range(0, n)])
)
try:
my_prob = cplex.Cplex()
self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except CplexError as exc:
print(exc)
return
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs):
n = self.n
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype)
prob.set_log_stream(None)
prob.set_error_stream(None)
prob.set_warning_stream(None)
prob.set_results_stream(None)
rows = []
for ii in range(0, n):
col = [x for x in range(0 + n * ii, n + n * ii)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [x for x in range(0 + ii, n**2, n)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
# Sub-tour elimination constraints:
for ii in range(0, n):
for jj in range(0, n):
if (ii != jj) and (ii * jj > 0):
col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1]
coef = [1, 1, -1]
rows.append([col, coef])
for ii in range(0, n):
col = [(ii) * (n + 1)]
coef = [1]
rows.append([col, coef])
prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs)
# Instantiate the classical optimizer class
classical_optimizer = ClassicalOptimizer(instance, n, K)
# Print number of feasible solutions
print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations()))
# Solve the problem in a classical fashion via CPLEX
x = None
z = None
try:
x, classical_cost = classical_optimizer.cplex_solution()
# Put the solution in the z variable
z = [x[ii] for ii in range(n**2) if ii // n != ii % n]
# Print the solution
print(z)
except:
print("CPLEX may be missing.")
# Visualize the solution
def visualize_solution(xc, yc, x, C, n, K, title_str):
plt.figure()
plt.scatter(xc, yc, s=200)
for i in range(len(xc)):
plt.annotate(i, (xc[i] + 0.15, yc[i]), size=16, color="r")
plt.plot(xc[0], yc[0], "r*", ms=20)
plt.grid()
for ii in range(0, n**2):
if x[ii] > 0:
ix = ii // n
iy = ii % n
plt.arrow(
xc[ix],
yc[ix],
xc[iy] - xc[ix],
yc[iy] - yc[ix],
length_includes_head=True,
head_width=0.25,
)
plt.title(title_str + " cost = " + str(int(C * 100) / 100.0))
plt.show()
if x is not None:
visualize_solution(xc, yc, x, classical_cost, n, K, "Classical")
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
class QuantumOptimizer:
def __init__(self, instance, n, K):
self.instance = instance
self.n = n
self.K = K
def binary_representation(self, x_sol=0):
instance = self.instance
n = self.n
K = self.K
A = np.max(instance) * 100 # A parameter of cost function
# Determine the weights w
instance_vec = instance.reshape(n**2)
w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0]
w = np.zeros(n * (n - 1))
for ii in range(len(w_list)):
w[ii] = w_list[ii]
# Some variables I will use
Id_n = np.eye(n)
Im_n_1 = np.ones([n - 1, n - 1])
Iv_n_1 = np.ones(n)
Iv_n_1[0] = 0
Iv_n = np.ones(n - 1)
neg_Iv_n_1 = np.ones(n) - Iv_n_1
v = np.zeros([n, n * (n - 1)])
for ii in range(n):
count = ii - 1
for jj in range(n * (n - 1)):
if jj // (n - 1) == ii:
count = ii
if jj // (n - 1) != ii and jj % (n - 1) == count:
v[ii][jj] = 1.0
vn = np.sum(v[1:], axis=0)
# Q defines the interactions between variables
Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v))
# g defines the contribution from the individual variables
g = (
w
- 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T)
- 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T)
)
# c is the constant offset
c = 2 * A * (n - 1) + 2 * A * (K**2)
try:
max(x_sol)
# Evaluates the cost distance from a binary representation of a path
fun = (
lambda x: np.dot(np.around(x), np.dot(Q, np.around(x)))
+ np.dot(g, np.around(x))
+ c
)
cost = fun(x_sol)
except:
cost = 0
return Q, g, c, cost
def construct_problem(self, Q, g, c) -> QuadraticProgram:
qp = QuadraticProgram()
for i in range(n * (n - 1)):
qp.binary_var(str(i))
qp.objective.quadratic = Q
qp.objective.linear = g
qp.objective.constant = c
return qp
def solve_problem(self, qp):
algorithm_globals.random_seed = 10598
vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes())
optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe)
result = optimizer.solve(qp)
# compute cost of the obtained result
_, _, _, level = self.binary_representation(x_sol=result.x)
return result.x, level
# Instantiate the quantum optimizer class with parameters:
quantum_optimizer = QuantumOptimizer(instance, n, K)
# Check if the binary representation is correct
try:
if z is not None:
Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z)
print("Binary cost:", binary_cost, "classical cost:", classical_cost)
if np.abs(binary_cost - classical_cost) < 0.01:
print("Binary formulation is correct")
else:
print("Error in the binary formulation")
else:
print("Could not verify the correctness, due to CPLEX solution being unavailable.")
Q, g, c, binary_cost = quantum_optimizer.binary_representation()
print("Binary cost:", binary_cost)
except NameError as e:
print("Warning: Please run the cells above first.")
print(e)
qp = quantum_optimizer.construct_problem(Q, g, c)
quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp)
print(quantum_solution, quantum_cost)
# Put the solution in a way that is compatible with the classical variables
x_quantum = np.zeros(n**2)
kk = 0
for ii in range(n**2):
if ii // n != ii % n:
x_quantum[ii] = quantum_solution[kk]
kk += 1
# visualize the solution
visualize_solution(xc, yc, x_quantum, quantum_cost, n, K, "Quantum")
# and visualize the classical for comparison
if x is not None:
visualize_solution(xc, yc, x, classical_cost, n, K, "Classical")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/lancecarter03/QiskitLearning
|
lancecarter03
|
from qiskit import *
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
secretNumber = '111000'
circuit = QuantumCircuit(len(secretNumber)+1, len(secretNumber))
circuit.h(range(len(secretNumber)))
circuit.x(len(secretNumber))
circuit.h(len(secretNumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretNumber)):
if yesno == '1':
circuit.cx(ii, len(secretNumber))
circuit.barrier()
circuit.h(range(len(secretNumber)))
circuit.barrier()
circuit.measure(range(len(secretNumber)),range(len(secretNumber)))
circuit.draw(output="mpl")
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend = simulator, shots=1).result()
counts = result.get_counts()
print(counts)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Unit tests for converting Braket circuits to/from OpenQASM
"""
import numpy as np
import qiskit
from braket.circuits import Circuit
from qbraid.interface import circuits_allclose
from qbraid.transpiler.conversions.braket import braket_to_qasm3
from qbraid.transpiler.conversions.qasm3 import qasm3_to_braket
from qbraid.transpiler.conversions.qiskit import qiskit_to_qasm3
def test_braket_to_qasm3_bell_circuit():
"""Test converting braket bell circuit to OpenQASM 3.0 string"""
qasm_expected = """
OPENQASM 3.0;
bit[2] b;
qubit[2] q;
h q[0];
cnot q[0], q[1];
b[0] = measure q[0];
b[1] = measure q[1];
"""
qasm_expected_2 = """
OPENQASM 3.0;
bit[2] __bits__;
qubit[2] __qubits__;
h __qubits__[0];
cnot __qubits__[0], __qubits__[1];
__bits__[0] = measure __qubits__[0];
__bits__[1] = measure __qubits__[1];
"""
bell = Circuit().h(0).cnot(0, 1)
qbraid_qasm = braket_to_qasm3(bell)
assert qasm_expected.strip("\n") == qbraid_qasm or qasm_expected_2.strip("\n") == qbraid_qasm
def test_braket_from_qasm3():
"""Test converting OpenQASM 3 string to braket circuit"""
qasm_str = """
OPENQASM 3.0;
bit[2] b;
qubit[2] q;
rx(0.15) q[0];
rx(0.3) q[1];
"""
circuit_expected = Circuit().rx(0, 0.15).rx(1, 0.3)
assert circuit_expected == qasm3_to_braket(qasm_str)
def test_qiskit_to_qasm3_to_braket():
"""Test converting Qiskit circuit to Braket via OpenQASM 3.0 for mapped gate defs"""
qc = qiskit.QuantumCircuit(4)
qc.cx(0, 1)
qc.s(0)
qc.sdg(1)
qc.t(2)
qc.tdg(3)
qc.sx(0)
qc.sxdg(1)
qc.p(np.pi / 8, 3)
qc.cp(np.pi / 4, 2, 3)
qasm3_str = qiskit_to_qasm3(qc)
circuit = qasm3_to_braket(qasm3_str)
assert circuits_allclose(qc, circuit)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Benchmarking tests for Qiskit conversions
"""
import pytest
import qiskit
from qbraid.interface import circuits_allclose
from qbraid.transpiler import ConversionGraph, transpile
from ...fixtures.qiskit.gates import get_qiskit_gates
TARGETS = [("braket", 0.98), ("cirq", 0.98), ("pyquil", 0.98), ("pytket", 0.98)]
qiskit_gates = get_qiskit_gates(seed=0)
graph = ConversionGraph(require_native=True)
def convert_from_qiskit_to_x(target, gate_name):
"""Construct a Qiskit circuit with the given gate, transpile it to
target program type, and check equivalence.
"""
gate = qiskit_gates[gate_name]
source_circuit = qiskit.QuantumCircuit(gate.num_qubits)
source_circuit.compose(gate, inplace=True)
target_circuit = transpile(source_circuit, target, conversion_graph=graph)
assert circuits_allclose(source_circuit, target_circuit, strict_gphase=False)
@pytest.mark.parametrize(("target", "baseline"), TARGETS)
def test_qiskit_coverage(target, baseline):
"""Test converting Qiskit circuits to supported target program type over
all Qiskit standard gates and check against baseline expected accuracy.
"""
ACCURACY_BASELINE = baseline
ALLOWANCE = 0.01
failures = {}
for gate_name in qiskit_gates:
try:
convert_from_qiskit_to_x(target, gate_name)
except Exception as e: # pylint: disable=broad-exception-caught
failures[f"{target}-{gate_name}"] = e
total_tests = len(qiskit_gates)
nb_fails = len(failures)
nb_passes = total_tests - nb_fails
accuracy = float(nb_passes) / float(total_tests)
assert accuracy >= ACCURACY_BASELINE - ALLOWANCE, (
f"The coverage threshold was not met. {nb_fails}/{total_tests} tests failed "
f"({nb_fails / (total_tests):.2%}) and {nb_passes}/{total_tests} passed "
f"(expected >= {ACCURACY_BASELINE}).\nFailures: {failures.keys()}\n\n"
)
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit.visualization import *
# Concentrating on the first 100 samples
n_samples = 100
X_train = datasets.MNIST(root='./data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# Leaving only labels 0 and 1
idx = np.append(np.where(X_train.targets == 0)[0][:n_samples],
np.where(X_train.targets == 1)[0][:n_samples]
)
idx = np.append(idx,
np.where(X_train.targets == 2)[0][:n_samples]
)
# idx = np.append(idx,
# np.where(X_train.targets == 3)[0][:n_samples]
# )
print(idx)
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 0)[0][:n_samples],
np.where(X_test.targets == 1)[0][:n_samples])
idx = np.append(idx,
np.where(X_test.targets == 2)[0][:n_samples]
)
# idx = np.append(idx,
# np.where(X_test.targets == 3)[0][:n_samples]
# )
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
# print(dict_of_counts)
# print(len(list(dict_of_counts.keys())[0]))
num_qubits = len(list(dict_of_counts.keys())[0])
result = np.zeros(len(qubit_range))
result = np.zeros(num_qubits)
# print(result)
for el in dict_of_counts:
for i in range(num_qubits):
# print("i", i)
# print("el[i]", el[i])
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
# print(result)
# print(result[qubit_range])
return result[qubit_range]
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
self.n_qubits = n_qubits
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
job = qiskit.execute(self._circuit,
self.backend,
shots = self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
result = job.result().get_counts(self._circuit)
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
# print("states: ", states)
# print("probabilities: ", probabilities)
new_probabilities = exctract_single_qubit_measurment(result, list(range(self.n_qubits)))/self.shots
# print("new_probabilities: ", new_probabilities)
# new_expectation = np.sum(states * new_probabilities)
# print("old expectation", np.array([expectation]))
return new_probabilities
# return np.array([expectation])
simulator = qiskit.Aer.get_backend('qasm_simulator')
circuit = QuantumCircuit(2, simulator, 100)
print('Expected value for rotation pi {}'.format(circuit.run([np.pi])[0]))
circuit._circuit.draw()
class HybridFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
# print("FORWARD BEGIN")
# print("input: ", input)
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
# print("expectation_z: ", expectation_z)
result = torch.tensor([expectation_z])
# print("result", result)
ctx.save_for_backward(input, result)
# print("FORWARD END")
return result
@staticmethod
def backward(ctx, grad_output):
# print("BACKWARD BEGIN")
# print("Grad_output: ", grad_output)
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
# print("input_list: ", input.tolist())
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = expectation_right - expectation_left
gradients.append(gradient)
# print("HALO")
gradients = np.array([gradients]).T
# print("gradients: ", gradients)
# print("BACKWARD END")
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(2, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(6400, 64)
self.fc2 = nn.Linear(64, 2)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
self.fc3 = nn.Linear(2, 3)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(-1, 6400)
x = F.relu(self.fc1(x))
# print(x)
x = self.fc2(x)
# print("x before hybrid layer", x)
# print(x.size())
x = self.hybrid(x)
# print("x after hybrid layer", x)
# x = F.relu(self.fc3(x.float()))
# print("return: ", torch.cat((x, 1 - x), -1))
x = self.fc3(x.float())
# print(torch.cat((x, 1 - x), -1))
# return torch.cat((x, 1 - x), -1)
# print("softmax: ", F.softmax(x))
# print("argmax: ", torch.argmax(x))
return F.softmax(x)
# return torch.argmax(x)
#
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.01)
loss_func = nn.CrossEntropyLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
# print(target)
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
plt.plot(loss_list)
plt.title('Hybrid NN Training Convergence')
plt.xlabel('Training Iterations')
plt.ylabel('Neg Log Likelihood Loss')
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model.eval()
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('Predicted {}'.format(pred.item()))
count += 1
import qiskit
qiskit.__qiskit_version__
|
https://github.com/wyqian1027/Qiskit-Fall-Fest-USC-2022
|
wyqian1027
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.opflow import One, Zero, Plus, Minus
from qiskit.opflow import I, X, Y, Z, S, H
from qiskit.visualization import plot_bloch_multivector, plot_bloch_vector, plot_histogram
from math import pi, sqrt, acos, asin, e, log, sin, cos
from numpy import angle
Zero
One
Plus
Minus
1.5 * Zero
-3 * Plus
Zero^Zero^One
Plus^Minus^Zero^Zero
Zero + One
Plus + Minus
(Zero^Zero^One) + (Zero^One^Zero) + (One^Zero^Zero)
(Zero^Zero^One) - 1.5*(Zero^One^Zero) + 3*(One^Zero^Zero)
def arbitrary_state(beta):
##### ==================================
# Write your solution in here.
##### ==================================
Zero.eval('0')
Zero.eval('1')
Minus.eval('0')
Minus.eval('1')
~Zero
~One
~Plus
print("< 0 | 0 > =",(~Zero @ Zero).eval())
print("< 1 | 0 > =",(~One @ Zero).eval())
beta = 0.232 + 0.341j
arbitrary_state(beta)
beta = 0.232 + 0.341j
print("< 1 | Ψ > =",(~One @ arbitrary_state(beta)).eval())
print("< 0 | Ψ > =",(~Zero @ arbitrary_state(beta)).eval())
print("< Ψ | Ψ > =", (~arbitrary_state(beta) @ arbitrary_state(beta)).eval())
def normality_check(beta):
##### ==================================
# Write your solution in here.
##### ==================================
# Play with your beta parameter to see if this value changes.
beta = 0.232 + 0.341j
print("|< 1 | Ψ >|^2 + |< 0 | Ψ >|^2 =", normality_check(beta))
def convert_braket_to_Bloch(beta):
if beta == 0: # special case
return [1.0, 0, 0]
##### ==================================
# Write your solution in here.
##### ==================================
return [1.0, theta, phi]
# Check
beta = -1/sqrt(2)*1j
plot_bloch_vector(convert_braket_to_Bloch(beta), coord_type='spherical',
title=r"$|\psi\rangle = \frac{1}{\sqrt{2}}|0\rangle-\frac{1}{\sqrt{2}}i|0\rangle$")
# Play with more values of beta to see if it matches with your expectation
beta = -1/sqrt(10)*1j
plot_bloch_vector(convert_braket_to_Bloch(beta), coord_type='spherical',
title=r"$|\psi\rangle = \sqrt{1-|\beta|^2}|0\rangle+\beta|0\rangle$ in Spherical")
X
Y
Z
def expectation_Z(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
##### ==================================
print("<Z> =", expectation_Z(beta))
def expectation_X(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
##### ==================================
def expectation_Y(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
##### ==================================
def get_cartesian_coordinate(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
##### ==================================
return [x, y, z]
# Play with more values of beta to see if it matches with your previous Bloch sphere
beta = -1/sqrt(10)*1j
plot_bloch_vector(get_cartesian_coordinate(beta), coord_type='cartesian',
title=r"$|\psi\rangle = \sqrt{1-|\beta|^2}|0\rangle+\beta|0\rangle$ in Cartesian")
# Let's define the quantum simulator
sv_simulator = Aer.get_backend("statevector_simulator")
qasm_simulator = Aer.get_backend("qasm_simulator")
this_circ = QuantumCircuit(1)
this_circ.initialize([1/sqrt(2), -1/sqrt(2)])
this_circ.measure_all()
this_circ.draw('mpl')
shots = 1024
counts = execute(this_circ, backend=qasm_simulator, shots=shots).result().get_counts()
print(counts)
plot_histogram(counts, title=r"Measuring the $|+\rangle$ state")
def contruct_arbitrary_state_on_circuit(beta):
##### ==================================
# Write your solution in here. Here you do not need to append the measurement part in this function
##### ==================================
return circuit
shots = 81920
beta = 0.213
this_circuit = contruct_arbitrary_state_on_circuit(beta)
this_circuit.measure_all()
counts = execute(this_circuit, backend=qasm_simulator, shots=shots).result().get_counts()
print("Probability in |1> basis =", beta**2)
plot_histogram(counts, title=r"Measuring the arbitrary $|\psi(\beta)\rangle$ state")
def expectation_Z_with_QASM(beta, shots):
##### ==================================
# Write your solution in here. Here
##### ==================================
return expectation
beta = -1/sqrt(2)*1j
shots = 81920
print("Expectation <Z> with QASM =", expectation_Z_with_QASM(beta, shots=shots))
print("Expectation <Z> with opflow =", expectation_Z(beta))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import pew_circuit as pew
from qiskit import QuantumCircuit, execute, Aer
#from aether import QuantumCircuit, simulate
import pygame
import numpy as np
simulator = Aer.get_backend('qasm_simulator')
shot=1
def Qand(First_bool,Second_bool):
First_bool=bool(First_bool)
Second_bool=bool(Second_bool)
a = int(First_bool)
b = int(Second_bool)
qc = QuantumCircuit(3,1)
if a == 1:
qc.x(0)
if b == 1:
qc.x(1)
qc.ccx(0, 1, 2) #toffoli
qc.measure(2,0)
job = execute(qc, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value ==1]
return bool(int(state[0]))
def Qnand(First_bool,Second_bool):
First_bool=bool(First_bool)
Second_bool=bool(Second_bool)
a = int(First_bool)
b = int(Second_bool)
qc = QuantumCircuit(3,1)
if a == 1:
qc.x(0)
if b == 1:
qc.x(1)
qc.ccx(0, 1, 2) #toffoli
qc.x(2)
qc.measure(2,0)
job = execute(qc, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value ==1]
return bool(int(state[0]))
def Qor(First_bool,Second_bool):
return Qnand(Qnand(First_bool,First_bool),Qnand(Second_bool,Second_bool))
def qrand(nbits):
"""generates nbits real random numbers using quantum state measurements in qiskit."""
circ = QuantumCircuit(1, 1)
circ.h(0)
circ.measure(0, 0)
b=''#string holder
for i in range(nbits):
job=execute(circ, simulator,shots=shot)
counts = job.result().get_counts()
state = [key for (key, value) in counts.items() if value == 1] #find the measured state, this is a list
b=b+state[0] #state[0] is a string
return int(b, 2)
dis = pew.init()
screen = pew.Pix()
#Selecting game speed
init_speed =3
game_speed = init_speed
#circuit graphics
pygame.font.init()
#add backgorund
pygame.draw.rect(dis,(255,255,255),(0,320,320,100))
#gate backkgorund
#add gate, change from H to Z to Meas by key stroke
font1 = pygame.font.Font(None, 70)
text = font1.render('H', True, (255, 0, 0))
dis.blit(text, (10, 330))
g=0
#add gate, change from H to Z to Meas by key stroke
gates = np.zeros(3, dtype=str)
gates[0] = 'H'
gates[1] = 'Z'
gates[2] = 'M'
corr = [0, 1, 0, 2] #correct sequence of gates
images = {}
for i in range(4):
imag_ = pygame.image.load(str(i+1) + 'c.png')
x_size = int((i+1)*65)
images[i] = imag_#pygame.transform.scale(imag_,(x_size,85))
g=0 #tracks selected gate
currg=0 #tracks current position in circuit
success=False #tracks whether or not circuit is successfully constructed
ima3 = pygame.image.load('1c.png')
#ima3 = pygame.transform.scale(ima3,(65,50))
dis.blit(ima3, (45, 325))
#Selecting initial position of the snake
snake = [(3,3)]
#Selecting initial velocity of the snake
dx, dy = 1, 0
#Selecting initial position of the apple
apple_x, apple_y = 6, 4
screen.pixel(apple_x, apple_y, 1)
#Selecting the initial position of the first noise
nx=3
ny=4
noise=[(nx, ny)]
while True:
screen.pixel(noise[0][0], noise[0][1],2)
#Here we print the head of the snake
if len(snake) > 1:
x, y = snake[-2]
screen.pixel(x, y, 1)
x, y = snake[-1]
screen.pixel(x, y, 3)
pew.show(screen)
pew.tick(1 / game_speed)
#Here we change the velocity of the snake depending on the key input
keys = pew.keys()
if keys & pew.K_UP and dy == 0:
dx, dy = 0, -1
elif keys & pew.K_LEFT and dx == 0:
dx, dy = -1, 0
elif keys & pew.K_RIGHT and dx == 0:
dx, dy = 1, 0
elif keys & pew.K_DOWN and dy == 0:
dx, dy = 0, 1
#Gate switch
if keys & pew.K_O:
pygame.draw.rect(dis,(255,255,255),(0,320,50,50))
g = (g+1) % 3 #cycle between gates
font1 = pygame.font.Font(None, 70)
text = font1.render(gates[g], True, (255, 0, 0))
dis.blit(text, (10, 330))
#Now are going to update the position of the head of the snake
#We define the next position of the head depending on the velocity
x = (x + dx) %8
y = (y + dy) %8
#Now we define a loop to end the loop (and the game) if the next position
# of the head is in the snake or it goes out of the grid
if Qor((x, y) in snake, (x,y) in noise):
#Here we turn of all the pixles from the snake and the apple
for (i,j) in snake:
screen.pixel(i,j,0)
screen.pixel(apple_x,apple_y,0)
for (i,j) in noise:
screen.pixel(i,j,0)
break
#If none of those thing happens the head of the snake gets updated to the new position
snake.append((x, y))
#Now we create a conditional loop for changing the size and spawning new apples depending
# on if the snake eats the apple or not
if Qand(x == apple_x, y == apple_y):
if g != corr[currg]:
break
else:
if currg == len(corr)-1: #if the required sequence is accomplished
success=True
break
dis.blit(images[currg+1], (45, 325))
currg+=1
#If the snake eats the apple we turn of the pixel of the apple
screen.pixel(apple_x, apple_y, 0)
#Now we define the coordinates of the apple to lie inside the snake for the loop
apple_x, apple_y = snake[0]
#We create a loop to generate an apple ouside the snake
while (apple_x, apple_y) in snake or (apple_x, apple_y) in noise:
apple_x=qrand(3)
apple_y=qrand(3)
#We light the pixels of the new apple
screen.pixel(apple_x, apple_y, 1)
# k=k+1
nx=snake[0][0]
ny=snake[0][1]
while Qor(Qor(Qor((nx,ny) in snake, (Qand(nx==apple_x, ny==apple_y))) ,(nx,ny) in noise) , (nx,ny)==(x,y)):
nx=qrand(3) #as opposed to random.getrandbits(3)
ny=qrand(3)
noise.append((nx,ny))
screen.pixel(nx, ny,2)
#We increase the speed of the game
game_speed += 0.2
#If the snake eats the apple we don't delete the last pixel of the snake. Otherwise we remove
# the last pixel to not increase the size of the snake
else:
x, y = snake.pop(0)
screen.pixel(x, y, 0)
def blit_screen(screen,text):
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
#When the loop is finished we print the game over screen
#turn off all pixels
if success == True:
text = pew.Pix.from_text("You win!")
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
else:
text = pew.Pix.from_text("Game over!")
blit_screen(screen,text)
for dx in range(-8, text.width):
screen.blit(text, -dx, 1)
pew.show(screen)
pew.tick(1 / 12)
pygame.quit()
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
from numpy.random import rand
from qiskit import transpile
## The Receiver entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Receiver(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Decode the message measuring the circuit (density-dependent)
def decode_quantum_message(self, message, density, backend):
## The values of the participant
self.values = []
for i, qc in enumerate(message):
qc.barrier()
if rand() < density:
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
qc.measure(0, 0)
transpiled_qc = transpile(qc, backend=backend)
result = backend.run(transpiled_qc, shots=1, memory=True).result()
measured_bit = int(result.get_memory()[0])
self.values.append(measured_bit)
else:
self.values.append(-1)
return message
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
# Practical Implementation of a Quantum String Matching Algorithm
# S. Faro, F.P. Marino, and A. Scardace
# QUASAR 2024
%%capture
!pip install ibm-cloud-sdk-core==3.18.2
!pip install qiskit==0.45.1
!pip install qiskit-aer==0.13.1
!pip install pylatexenc==2.10
from numpy import log2, sqrt
from numpy import pi
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.gate import Gate
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer
from qiskit import transpile
def run(circuit: QuantumCircuit, shots: int) -> dict:
simulator = Aer.get_backend('aer_simulator')
compiled_circuit = transpile(circuit, simulator)
job = simulator.run(compiled_circuit, shots=shots)
result = job.result()
return result.get_counts(compiled_circuit)
def init_register(bin_str: str) -> QuantumCircuit:
data_qr = QuantumRegister(len(bin_str), 'data')
qc = QuantumCircuit(data_qr)
for i, bit in enumerate(bin_str):
if bit == '1':
qc.x(data_qr[i])
return qc
classical_value = '1001'
init_register(classical_value).draw(fold=255)
def rot(n: int, s: int) -> QuantumCircuit:
y_qr = QuantumRegister(n, 'y')
qc = QuantumCircuit(y_qr, name='ROT_' + str(s))
for i in range(1, (int(log2(n)) - int(log2(s)) + 2)):
for j in range(int(n / (s * (2**i)))):
for q in range(j * s * (2**i), s * (j*2 ** i+1)):
qc.swap(n - 1 - (q+s), n - 1 - (q+2 ** (i-1) * s + s))
return qc
num_qubits = 8
shift_value = 2
rot(num_qubits, shift_value).draw(fold=255)
def rot_gate(n: int, s: int) -> Gate:
rot_circuit = rot(n, s)
return rot_circuit.to_gate(label='ROT_' + str(s))
def parameterized_rot(n: int) -> QuantumCircuit:
j_qr = QuantumRegister(int(log2(n)), 'j')
y_qr = QuantumRegister(n, 'y')
qc = QuantumCircuit(j_qr, y_qr)
for i in range(int(log2(n))):
crot = rot_gate(n, 2**i).control(1)
qc = qc.compose(crot, [j_qr[i]] + y_qr[:])
return qc
num_qubits = 8
parameterized_rot(num_qubits).draw(fold=255)
text = '10110001'
text_length = len(text)
shift_qr = QuantumRegister(int(log2(text_length)), 'shift')
text_qr = QuantumRegister(text_length, 'text')
output_cr = ClassicalRegister(text_length, 'output_classic')
circ = QuantumCircuit(shift_qr, text_qr, output_cr)
circ.h(shift_qr)
circ.append(init_register(text), text_qr[:])
circ.append(parameterized_rot(text_length), shift_qr[:] + text_qr[:])
circ.measure(text_qr, output_cr)
counts = run(circ, 100)
plot_histogram(counts, title='Rotate ' + text + ' Leftward in Superposition')
def match(m: int) -> QuantumCircuit:
x_qr = QuantumRegister(m, 'x')
y_qr = QuantumRegister(m, 'y')
out_qr = QuantumRegister(1, 'out')
qc = QuantumCircuit(x_qr, y_qr, out_qr)
for i in range(m):
qc.cx(x_qr[i], y_qr[i])
qc.x(y_qr[i])
qc.mcx(y_qr[:], out_qr)
for i in reversed(range(m)):
qc.x(y_qr[i])
qc.cx(x_qr[i], y_qr[i])
return qc
pattern_length = 4
match(pattern_length).draw(fold=255)
text = '1011'
text_length = len(text)
pattern_qr = QuantumRegister(text_length, 'pattern')
text_qr = QuantumRegister(text_length, 'text')
output_qr = QuantumRegister(1, 'output')
output_cr = ClassicalRegister(text_length + 1, 'output_classic')
circ = QuantumCircuit(pattern_qr, text_qr, output_qr, output_cr)
circ.h(pattern_qr)
circ.append(init_register(text), text_qr[:])
circ.append(match(text_length), pattern_qr[:] + text_qr[:] + output_qr[:])
circ.measure(pattern_qr, output_cr[:-1])
circ.measure(output_qr, output_cr[-1])
counts = run(circ, 100)
plot_histogram(counts, title='Matching ' + text)
def match_gate(m: int) -> Gate:
match_circuit = match(m)
return match_circuit.to_gate(label='MATCH')
def esm(m: int, n: int) -> QuantumCircuit:
j_qr = QuantumRegister(int(log2(n)), 'j')
x_qr = QuantumRegister(m, 'x')
y_qr = QuantumRegister(n, 'y')
out = QuantumRegister(1, 'out')
qc = QuantumCircuit(
j_qr,
x_qr,
y_qr,
out
)
qc = qc.compose(parameterized_rot(n), j_qr[:] + y_qr[:])
qc = qc.compose(match_gate(m), x_qr[:] + y_qr[:m] + out[:])
qc = qc.compose(parameterized_rot(n).inverse(), j_qr[:] + y_qr[:])
return qc
pattern_length = 2
text_length = 4
esm(pattern_length, text_length).draw(fold=255)
def esm_oracle(m: int, n: int):
esm_circuit = esm(m, n)
return esm_circuit.to_gate(label='ESMO')
def diffuser(n: int) -> Gate:
qc = QuantumCircuit(n)
qc.h(range(n))
qc.x(range(n))
qc.h(n-1)
qc.mcx(list(range(n-1)), n-1)
qc.h(n-1)
qc.x(range(n))
qc.h(range(n))
return qc.to_gate(label='DIFF')
def grover(esmo: Gate, t: int, x: str, y: str) -> QuantumCircuit:
n = len(y)
m = len(x)
logn = int(log2(n))
num_iterations = int(pi/4 * sqrt(n/t))
j_qr = QuantumRegister(logn, 'j')
x_qr = QuantumRegister(m, 'x')
y_qr = QuantumRegister(n, 'y')
out_qr = QuantumRegister(2, 'out')
out_cr = ClassicalRegister(logn+1, 'c')
qc = QuantumCircuit(j_qr, x_qr, y_qr, out_qr, out_cr)
qc.h(j_qr)
qc.x(out_qr[0])
qc.h(out_qr[0])
qc = qc.compose(init_register(x), x_qr[:])
qc = qc.compose(init_register(y), y_qr[:])
for _ in range(num_iterations):
qc = qc.compose(esmo)
qc = qc.compose(diffuser(logn))
qc.measure(j_qr, out_cr[:-1])
qc = qc.compose(esmo, j_qr[:] + x_qr[:] + y_qr[:] + [out_qr[1]])
qc.measure(out_qr[1], out_cr[-1])
return qc
x = '11'
y = '10101100'
esmo = esm_oracle(len(x), len(y))
grover(esmo, 1, x, y).draw(fold=255)
x = '00'
y = '01010101'
esmo = esm_oracle(len(x), len(y))
counts = run(grover(esmo, 1, x, y), 100)
plot_histogram(counts, title=f'Search for {x} in {y} - 0 occurrence(s)')
x = '00'
y = '11010011'
esmo = esm_oracle(len(x), len(y))
counts = run(grover(esmo, 1, x, y), 100)
plot_histogram(counts, title=f'Search for {x} in {y} - 1 occurrence(s)')
x = '00'
y = '00111001'
esmo = esm_oracle(len(x), len(y))
counts = run(grover(esmo, 2, x, y), 100)
plot_histogram(counts, title=f'Search for {x} in {y} - 2 occurrence(s)')
def search(x: str, y: str) -> int:
m = len(x)
n = len(y)
esmo = esm_oracle(m, n)
for t in range(1, int(n/2) + 1):
print('Trying with t =', t)
results = run(grover(esmo, t, x, y), 1)
results = list(results.keys())[0]
outcome = int(results[0])
position = int(results[1:], 2)
if outcome: return position
else: print('Pattern not found in position', position)
return -1
x = input('Enter the value of x: ')
y = input('Enter the value of y: ')
if len(x) > len(y):
raise Exception('The length of x must be shorter than the length of y.')
if x.count('0') + x.count('1') < len(x):
raise Exception('The pattern must be a binary string.')
if y.count('0') + y.count('1') < len(y):
raise Exception('The text must be a binary string.')
print('')
position = search(x, y)
if position >= 0: print('Pattern occurrence found in position', str(position))
else: print('Pattern occurrence not found.')
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
from qiskit.quantum_info import DensityMatrix
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
from qCircuit import createInputCircuit, createModelCircuit, createNoisyModelCircuit
from qLipschitz import QLipschitz
from qDistance import d, D
import warnings
warnings.filterwarnings('ignore')
X_train, Y_train = datasets.make_circles(n_samples=500, noise=0.09, factor=0.4)
X_test, Y_test = datasets.make_circles(n_samples=200, noise=0.09, factor=0.4)
print('Training Data:')
print(X_train[:10])
print('\nTraining Label:')
print(Y_train[:10])
plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train)
plt.show()
print(f'Total datas: {len(X_train)}')
print(f'labels: {list(set(Y_train))}')
print(f' - label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f' - label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5
temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1))
temp[:, :-1] = X_train
temp[:, -1] = Z_train
X_train2 = temp
Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5
temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1))
temp[:, :-1] = X_test
temp[:, -1] = Z_test
X_test2 = temp
print('Solved Training Data:')
print(X_train2[:10])
def plot3D(X, Y):
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(
X[:, 0], X[:, 1], X[:, 2],
zdir='z', s=30, c=Y, depthshade=True
)
plt.show()
plot3D(X_train2, Y_train)
X, Y = datasets.load_iris(return_X_y=True)
X_train_0 = X[0:30]
X_train_1 = X[50:80]
X_train_iris = np.vstack((X_train_0, X_train_1))
Y_train_0 = Y[0:30]
Y_train_1 = Y[50:80]
Y_train_iris = np.vstack((Y_train_0, Y_train_1)).flatten()
X, Y = datasets.load_iris(return_X_y=True)
X_test_0 = X[30:50]
X_test_1 = X[80:100]
X_test_iris = np.vstack((X_test_0, X_test_1))
Y_test_0 = Y[30:50]
Y_test_1 = Y[80:100]
Y_test_iris = np.vstack((Y_test_0, Y_test_1)).flatten()
X_train_iris = (X_train_iris - X_train_iris.min(axis=0)) / (X_train_iris.max(axis=0) - X_train_iris.min(axis=0))
X_test_iris = (X_test_iris - X_test_iris.min(axis=0)) / (X_test_iris.max(axis=0) - X_test_iris.min(axis=0))
import qiskit
from qiskit import Aer, execute
qasm_backend = Aer.get_backend('qasm_simulator')
params = [
[[-1.18991246e-01, -8.69694713e-01, 1.43722811e-03],
[ 3.47641545e+00, -4.73632073e-02, 1.97135609e+00],
[ 1.95775707e+00, -1.12139160e-02, -6.21796144e-03]],
[[ 2.02460380e-02, -2.25797547e+00, 5.14234265e-03],
[-1.71552299e-02, 2.46283604e-03, -1.03805722e-02],
[-2.37244982e-03, -3.35799404e-03, 6.10191152e-03]]
]
params_iris = [
[[-3.42142600e-02, -5.45047534e-03, 8.11905347e-01],
[-1.52484152e+00, 1.49884676e+00, -1.25408626e-02],
[-1.89515860e-03, 1.35760410e-02, 8.22999582e-03],
[ 1.39102114e+00, 4.19729865e-01, 1.60000380e-04]],
[[ 7.88431068e-01, -8.86177264e-01, 1.33830291e-02],
[-3.71228143e-03, -1.12994101e-02, -1.27897783e-02],
[ 9.45954683e-03, -3.34659883e-03, 1.17217829e-02],
[ 1.98256181e-02, -1.07358054e-02, 7.53621360e-03]]
]
# Test 1: createModelCircuit
createModelCircuit(params).draw(output='mpl')
def predict(model, data):
qubits_num = len(data)
input_circuit = createInputCircuit(data)
qcircuit = input_circuit.compose(model)
# the measurement
qcircuit.measure(list(range(qubits_num)), list(range(qubits_num)))
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
p1 = 0
for i in range(2 ** (qubits_num - 1)):
comb = str(bin(i + 2 ** (qubits_num - 1))[2:])
p1 += counts.get(comb, 0)
p1 /= shots
if p1 > 0.5:
return 1
else:
return 0
def accuracy(model, datas, labels):
predictions = [ predict(model, data) for data in datas ]
acc = 0
for i, p in enumerate(predictions):
if p == labels[i]:
acc += 1
return acc / len(predictions)
def evaluate(model, X_test, Y_test):
acc = accuracy(model, X_test, Y_test)
print("FINAL ACCURACY: {:0.2f}%".format(acc * 100))
# Test 2: evaluate noiseless model
test2_circuit = createModelCircuit(params_iris)
evaluate(test2_circuit, X_train_iris, Y_train_iris)
evaluate(test2_circuit, X_test_iris, Y_test_iris)
# Test 3: create noisy model circuit - circle
test3_p = 0.001
test3_circuit = createNoisyModelCircuit(params, test3_p, 'phase_flip')
test3_circuit.draw(output='mpl')
# Test 4: evaluate noisy model - circle
test4_p = 0.001
models_type = [
'noiseless', 'bit_flip', 'phase_flip', 'depolarizing'
]
test4_circuits = [
createModelCircuit(params),
createNoisyModelCircuit(params, test4_p, 'bit_flip'),
createNoisyModelCircuit(params, test4_p, 'phase_flip'),
createNoisyModelCircuit(params, test4_p, 'depolarizing')
]
for i, model_type in enumerate(models_type):
print(f'Evaluate <{model_type}>: ')
evaluate(test4_circuits[i], X_test2, Y_test)
print()
# Test 5: calculate lipschitz constant
print('Classifier for centric circle: ')
test5_1_circuit = createModelCircuit(params)
test5_1_qlipschitz = QLipschitz(test5_1_circuit, [0, 1])
print(test5_1_qlipschitz.constant)
print('\nClassifier for Iris: ')
test5_2_circuit = createModelCircuit(params_iris)
test5_2_qlipschitz = QLipschitz(test5_2_circuit, [0, 1])
print(test5_2_qlipschitz.constant)
# Test 6-1: calculate lipschitz constant in noisy model
test6_p = [0.0001, 0.001, 0.05, 0.1]
models_type = [
'noiseless', 'bit_flip', 'phase_flip', 'depolarizing'
]
print('Classifier for centric circle: ')
for p in test6_p:
test6_1_circuits = [
createModelCircuit(params),
createNoisyModelCircuit(params, p, 'bit_flip'),
createNoisyModelCircuit(params, p, 'phase_flip'),
createNoisyModelCircuit(params, p, 'depolarizing')
]
print(f'p: {p}')
for i, model_type in enumerate(models_type):
test6_1_qlipschitz = QLipschitz(test6_1_circuits[i], [0, 1])
print(f'{model_type} model: {test6_1_qlipschitz.constant[0]}')
print()
# Test 6-2: calculate lipschitz constant in noisy model
test6_p = [0.0001, 0.001, 0.05, 0.1]
models_type = [
'noiseless', 'bit_flip', 'phase_flip', 'depolarizing'
]
print('Classifier for Iris: ')
for p in test6_p:
test6_2_circuits = [
createModelCircuit(params_iris),
createNoisyModelCircuit(params_iris, p, 'bit_flip'),
createNoisyModelCircuit(params_iris, p, 'phase_flip'),
createNoisyModelCircuit(params_iris, p, 'depolarizing')
]
print(f'p: {p}')
for i, model_type in enumerate(models_type):
test6_2_qlipschitz = QLipschitz(test6_2_circuits[i], [0, 1])
print(f'{model_type} model: {test6_2_qlipschitz.constant[0]}')
print()
# Test 7-1: find proper epsilon - circle
import random
# D(rou, sigma) <= epsilon
indices = []
while len(indices) < 50:
a = random.randint(0, len(X_train2) - 1)
b = random.randint(0, len(X_train2) - 1)
if a != b:
indices.append([a, b])
distances = []
for pair in indices:
rou = getDensityMatrix(createInputCircuit(X_train2[pair[0]]))
sigma = getDensityMatrix(createInputCircuit(X_train2[pair[1]]))
distances.append(D(rou, sigma))
print('find proper epsilon - centric circle')
print(f'Mean distance: {sum(distances) / len(distances)}')
print(f'Max distance: {max(distances)}')
print(f'Min distance: {min(distances)}')
# Test 7-2: find proper epsilon - iris
# D(rou, sigma) <= epsilon
indices = []
while len(indices) < 50:
a = random.randint(0, len(X_train_iris) - 1)
b = random.randint(0, len(X_train_iris) - 1)
if a != b:
indices.append([a, b])
distances = []
for pair in indices:
rou = getDensityMatrix(createInputCircuit(X_train_iris[pair[0]]))
sigma = getDensityMatrix(createInputCircuit(X_train_iris[pair[1]]))
distances.append(D(rou, sigma))
print('find proper epsilon - centric iris')
print(f'Mean distance: {sum(distances) / len(distances)}')
print(f'Max distance: {max(distances)}')
print(f'Min distance: {min(distances)}')
# Test 8-1: find proper delta - circle
test8_1_circuit = createModelCircuit(params)
test8_1_qlipschitz = QLipschitz(test8_1_circuit, [0, 1])
test8_1_A = test8_1_qlipschitz.A
# d(A(rou), A(sigma)) <= delta
indices = []
while len(indices) < 50:
a = random.randint(0, len(X_train2) - 1)
b = random.randint(0, len(X_train2) - 1)
if a != b:
indices.append([a, b])
distances = []
for pair in indices:
rou = getDensityMatrix(createInputCircuit(X_train2[pair[0]]))
sigma = getDensityMatrix(createInputCircuit(X_train2[pair[1]]))
distances.append(d(test8_1_A, rou, sigma))
print('find proper delta - circle')
print(f'Mean distance: {sum(distances) / len(distances)}')
print(f'Max distance: {max(distances)}')
print(f'Min distance: {min(distances)}')
# Test 8-2: find proper delta - circle
test8_2_circuit = createModelCircuit(params_iris)
test8_2_qlipschitz = QLipschitz(test8_2_circuit, [0, 1])
test8_2_A = test8_2_qlipschitz.A
# d(A(rou), A(sigma)) <= delta
indices = []
while len(indices) < 50:
a = random.randint(0, len(X_train_iris) - 1)
b = random.randint(0, len(X_train_iris) - 1)
if a != b:
indices.append([a, b])
distances = []
for pair in indices:
rou = getDensityMatrix(createInputCircuit(X_train_iris[pair[0]]))
sigma = getDensityMatrix(createInputCircuit(X_train_iris[pair[1]]))
distances.append(d(test8_2_A, rou, sigma))
print('find proper delta - iris')
print(f'Mean distance: {sum(distances) / len(distances)}')
print(f'Max distance: {max(distances)}')
print(f'Min distance: {min(distances)}')
# Test 9-1: fairness verifying - circle
test9_1_circuit = createNoisyModelCircuit(params, p=0.001, errorType='bit_flip')
test9_1_qlipschitz = QLipschitz(test9_1_circuit, [0, 1])
print(f'Lipschitz constant: {test9_1_qlipschitz.constant[0]}\n')
test9_1_fairness_params = [
# epsilon, delta
[1, 1], [0.9, 0.89], [0.6, 0.58], [0.6, 0.59]
]
for epsilon, delta in test9_1_fairness_params:
flag, kernel = test9_1_qlipschitz.fairVeriQ(epsilon, delta)
print(f'A is ({epsilon},{delta})-fair: <{flag}>')
if not flag:
print(f' - bias kernel pair is: {kernel}')
print()
# Test 9-2: fairness verifying - iris
test9_2_circuit = createNoisyModelCircuit(params_iris, p=0.001, errorType='phase_flip')
test9_2_qlipschitz = QLipschitz(test9_2_circuit, [0, 1])
print(f'Lipschitz constant: {test9_2_qlipschitz.constant[0]}\n')
test9_2_fairness_params = [
# epsilon, delta
[1, 0.99], [0.8, 0.79], [0.5, 0.3]
]
for epsilon, delta in test9_2_fairness_params:
flag, kernel = test9_1_qlipschitz.fairVeriQ(epsilon, delta)
print(f'A is ({epsilon},{delta})-fair: <{flag}>')
if not flag:
print(f' - bias kernel pair is: {kernel}')
print()
# Test 10: generate bias pair
test10_circuit = createNoisyModelCircuit(params_iris, p=0.01, errorType='depolarizing')
test10_qlipschitz = QLipschitz(test10_circuit, [0, 1])
print(f'Lipschitz constant: {test10_qlipschitz.constant[0]}\n')
flag, kernel = test10_qlipschitz.fairVeriQ(epsilon=0.9, delta=0.3)
print(f'fairness: {flag}')
assert (not flag)
test10_sigma = getDensityMatrix(createInputCircuit(X_train_iris[11]))
test10_bias_pair = test10_qlipschitz.generateBiasPair(test10_sigma, kernel, epsilon=0.9)
test10_rou_psi, test10_rou_phi = test10_bias_pair
# print(test10_bias_pair)
print(f'epsilon=0.9, delta=0.3')
print('D: ', D(test10_rou_psi, test10_rou_phi))
print('d: ', d(test10_qlipschitz.A, test10_rou_psi, test10_rou_phi))
|
https://github.com/ace314/Quantum-Multi-collision-Problem
|
ace314
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
def n_controlled_Z(circuit, controls, target):
"""Implement a Z gate with multiple controls"""
if (len(controls) > 2):
raise ValueError('The controlled Z with more than 2 controls is not implemented')
elif (len(controls) == 1):
circuit.h(target)
circuit.cx(controls[0], target)
circuit.h(target)
elif (len(controls) == 2):
circuit.h(target)
circuit.ccx(controls[0], controls[1], target)
circuit.h(target)
def inversion_about_average(circuit, register, n, barriers):
"""Apply inversion about the average step of Grover's algorithm."""
circuit.h(register)
circuit.x(register)
if barriers:
circuit.barrier()
n_controlled_Z(circuit, [register[j] for j in range(n-1)], register[n-1])
if barriers:
circuit.barrier()
circuit.x(register)
circuit.h(register)
def phase_oracle(circuit, qindex, qr):
circuit.cx(qindex[1],qr[0])
circuit.cx(qindex[2],qr[1])
def phase_flipping2(circuit, qindex, qr, qanx, T):
phase_oracle(groverCircuit, qindex, qr)
for i in range(T[1] // 2):
circuit.x(qanx[1])
for i in range(T[1] % 2):
circuit.x(qanx[2])
groverCircuit.barrier()
circuit.cx(qr[0], qanx[1])
circuit.cx(qr[1], qanx[2])
circuit.barrier()
circuit.cx(qanx[1], qanx[0])
circuit.cx(qanx[2], qanx[0])
circuit.ccx(qanx[1],qanx[2],qanx[0])
circuit.barrier()
circuit.cx(qr[0], qanx[1])
circuit.cx(qr[1], qanx[2])
circuit.x(qanx[0])
groverCircuit.barrier()
#print(T[1])
for i in range(T[1] // 2):
circuit.x(qanx[1])
for i in range(T[1] % 2):
circuit.x(qanx[2])
phase_oracle(groverCircuit, qindex, qr)
def phase_flipping3(circuit, qindex, qanx, T):
phase_oracle(groverCircuit, qindex, qr)
for i in range((T[0] // 4) % 2):
circuit.x(qanx[1])
for i in range((T[0] // 2) % 2):
circuit.x(qanx[2])
for i in range((T[0] // 1) % 2):
circuit.x(qanx[3])
groverCircuit.barrier()
circuit.cx(qindex[0], qanx[1])
circuit.cx(qindex[1], qanx[2])
circuit.cx(qindex[2], qanx[3])
circuit.barrier()
circuit.cx(qanx[1], qanx[0])
circuit.cx(qanx[2], qanx[0])
circuit.cx(qanx[3], qanx[0])
circuit.ccx(qanx[1], qanx[2], qanx[0])
circuit.ccx(qanx[2], qanx[3], qanx[0])
circuit.ccx(qanx[3], qanx[1], qanx[0])
circuit.ccx(qanx[1], qanx[2], qanx[4])
circuit.ccx(qanx[3], qanx[4], qanx[0])
circuit.ccx(qanx[1], qanx[2], qanx[4])
circuit.barrier()
circuit.cx(qindex[0], qanx[1])
circuit.cx(qindex[1], qanx[2])
circuit.cx(qindex[2], qanx[3])
circuit.x(qanx[0])
groverCircuit.barrier()
for i in range((T[0] // 4) % 2):
circuit.x(qanx[1])
for i in range((T[0] // 2) % 2):
circuit.x(qanx[2])
for i in range((T[0] // 1) % 2):
circuit.x(qanx[3])
phase_oracle(groverCircuit, qindex, qr)
L = np.array([[2,2],[7,3]])
print(L)
K = L[:,0]
print(K)
barriers = True
m = 3
n = 2
qindex = QuantumRegister(m)
qr = QuantumRegister(n)
qanx = QuantumRegister(5)
cindex = ClassicalRegister(m)
cr = ClassicalRegister(n)
groverCircuit = QuantumCircuit(qindex, qr, qanx, cindex, cr)
groverCircuit.h(qindex)
groverCircuit.x(qanx[0])
groverCircuit.h(qanx[0])
groverCircuit.barrier()
#num_loop = int(np.ceil(np.cbrt(2 ** m)))
num_loop = int(np.cbrt(2 ** m))
num_loop = 6
print("num_loop = ", num_loop)
#phase_oracle(groverCircuit, qindex, qr)
for i in range(num_loop):
if barriers:
groverCircuit.barrier()
# the first stage of grover
phase_flipping2(groverCircuit, qindex, qr, qanx, L[0,:])
if barriers:
groverCircuit.barrier()
# the third stage of grover
phase_flipping3(groverCircuit, qindex, qanx, L[0,:])
if barriers:
groverCircuit.barrier()
#the second stage of grover
# phase_flipping2(groverCircuit, qindex, qr, qanx, L[1,:])
if barriers:
groverCircuit.barrier()
# phase_flipping3(groverCircuit, qindex, qanx, L[1,:])
if barriers:
groverCircuit.barrier()
groverCircuit.barrier()
inversion_about_average(groverCircuit, qindex, m, barriers)
if barriers:
groverCircuit.barrier()
groverCircuit.measure(qindex,cindex)
%matplotlib inline
groverCircuit.draw(output='mpl')
# groverCircuit.draw(output="mpl")
backend = BasicAer.get_backend('qasm_simulator')
shots = 8192
results = execute(groverCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
print(answer)
index = np.argmax(answer)
index = 2
print(index)
ans = np.zeros(2)
flag = False
for [i, j] in L:
#print([i,j])
#print(index % 4)
if j == index % 4:
flag = True
ans[0] = i
ans[1] = index
break
if flag:
print("ans = ", ans)
else :
print("failed")
|
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
|
Sanjay-995
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
import numpy as np
from numpy import pi
import math
from math import sqrt
import matplotlib as mpl
%matplotlib inline
qc = QuantumCircuit(1,1)
qc.h(0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
qc = QuantumCircuit(1,1)
# Insert code fragment here
qc.ry(math.pi / 2, 0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
qc = QuantumCircuit(1,1)
# Insert code fragment here
qc.rx(math.pi / 2, 0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
qc = QuantumCircuit(1,1)
# Insert code fragment here
qc.rx(math.pi / 2, 0)
qc.rz(-math.pi / 2, 0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
qc = QuantumCircuit(1,1)
# Insert code fragment here
qc.ry(math.pi, 0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
|
https://github.com/EdoardoZappia/Qiskit-Primitive
|
EdoardoZappia
|
#!pip install qiskit
#import qiskit.tools.jupyter
#%qiskit_version_table
#%qiskit_copyright
#pip install qcircuit
#pip install pdflatex
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
import numpy as np
import qiskit.quantum_info as qi
import qiskit
from qiskit import Aer
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.visualization.circuit import *
from qiskit import transpile, assemble
import matplotlib.pyplot as plt
from qiskit.circuit import Parameter
# Supress warnings
import warnings
warnings.filterwarnings("ignore")
# Create a quantum circuit instance with one qubit
circuit = QuantumCircuit(2,0)
# Apply Hadamard Gate
circuit.h(0)
# Draw quantum circuit
circuit.draw(output = "mpl")
# Print all the available quantum simulators
Aer.backends()
# Load statevector simulator
simulator = Aer.get_backend("statevector_simulator")
# Create quatum job to execute
job = simulator.run(circuit)
# Execute the job
result = job.result()
state_ex=result.get_statevector(circuit) #if possible mantains phases as fractions
state = result.get_statevector(circuit, decimals = 4) #using parameter decimals, approximates the fractions
state_ex.draw(output='latex')
state.draw(output='latex')
state.draw(output = "bloch")
#to do statevector simulation more easily
def statevect_sim(circuit: QuantumCircuit):
simulator=Aer.get_backend("statevector_simulator")
state=simulator.run(circuit).result().get_statevector(circuit)
print(state)
return state.draw('latex')
# Apply RX / RY / S /T gates
circuit2=QuantumCircuit(1,0)
circuit2.rx(np.pi/2,0) #rx(theta, n) gate is a single-qubit gate rotation of angle theta around the x-axis of the qubit n
circuit2.draw(output='mpl')
statevect_sim(circuit2)
simulator.run(circuit2).result().get_statevector(circuit2).draw(output = "bloch")
circuit3=QuantumCircuit(1,0)
circuit3.ry(np.pi*3/2,0) #ry(theta, n) gate is a single-qubit gate rotation of angle theta around the y-axis of the qubit n
circuit3.draw(output='mpl')
#create the job
job3=simulator.run(circuit3)
#execute the job
result3=job3.result()
#create the state
state3_ex=result3.get_statevector(circuit3)
state3=result3.get_statevector(circuit3,decimals=4)
state3_ex.draw(output='latex')
state3.draw(output='latex')
#or we can just use
statevect_sim(circuit3)
state3.draw(output='bloch')
circuit4=QuantumCircuit(1,0)
circuit4.rx(np.pi/4,0)
circuit4.s(0) #s(n) gate is a single-qubit gate rotation of angle pi/2 around the z-axis of the qubit n
circuit4.draw(output='mpl')
statevect_sim(circuit4)
simulator.run(circuit4).result().get_statevector(circuit4).draw(output = "bloch")
circuit5=QuantumCircuit(1,0)
circuit5.h(0) #the state is in |+>
circuit5.t(0) #t(n) gate is a single-qubit gate rotation of angle pi/4 around the z-axis of the qubit n
circuit5.draw(output='mpl')
statevect_sim(circuit5)
simulator.run(circuit5).result().get_statevector(circuit5).draw(output = "bloch")
# Create quantum circuit with two quantum registers and two classical registers
circuit_bell = QuantumCircuit(2, 2)
# Create Bell state following the expression above
circuit_bell.h(0)
circuit_bell.cx(0,1)
statevect_sim(circuit_bell)
# Visualize the circuit
circuit_bell.draw(output = 'mpl')
circuit=QuantumCircuit(3)
circuit.x(0)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(1,2)
statevect_sim(circuit)
circuit.draw('mpl')
circuit=QuantumCircuit(2)
circuit.x(0)
circuit.h(0)
circuit.x(1)
circuit.cx(0,1)
circuit.draw('mpl')
circuit.swap(0,1) #qiskit visualization of qubits is reversed
statevect_sim(circuit)
#from qiskit.visualization import plot_state_city, plot_state_hinton, plot_state_qsphere, plot_histogram
state2=simulator.run(circuit2).result().get_statevector(circuit2)
state2.draw(output='latex')
plot_state_city(state2) #Plot two 3d bar graphs (two dimensional) of the real and imaginary part of the density matrix rho
plot_state_hinton(state2)
#seaborn package required
plot_state_qsphere(state2)
state=simulator.run(circuit).result().get_statevector(circuit)
state.draw('latex')
plot_state_city(state)
plot_state_hinton(state)
plot_state_qsphere(state)
state_bell=simulator.run(circuit_bell).result().get_statevector(circuit_bell)
state_bell.draw('latex')
plot_state_city(state_bell)
plot_state_hinton(state_bell)
plot_state_qsphere(state_bell)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator') #Unitary Simulator is a simulator provided by Qiskit that calculates and returns the unitary matrix that represents the Quantum Circuit
# Create job and execute
job = backend.run(circuit_bell)
result = job.result()
# Show the results
print(result.get_unitary(circuit_bell, decimals=3))
# Initialize quantum and classical registers
qr = QuantumRegister(2)
cr = ClassicalRegister(2) #classical registers are needed to store the results of measurements (if we use the command measure(qr,cr))
# Build quantum circuit
circuit_qasm = QuantumCircuit(qr, cr)
#Create Bell state
circuit_qasm.h(0)
circuit_qasm.cx(0,1)
# Measure qubits
circuit_qasm.measure(qr, cr) #circuit_qasm.measure_all() memeasures all qubits, creates a new register to store the measurements and adds a barrier before the measurements
circuit_qasm.draw(output = 'mpl')
backend = Aer.get_backend("qasm_simulator")
shots = 1024 #1024 is the standard number of shots
job = execute(circuit_qasm, backend, shots = shots)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
qr=QuantumRegister(2)
cr=ClassicalRegister(2)
circ_bell=QuantumCircuit(qr,cr)
circ_bell.x(0)
circ_bell.h(0)
circ_bell.cx(0,1)
circ_bell.measure(qr,cr)
circ_bell.draw('mpl')
job_bell=execute(circ_bell,backend,shots=1024)
result_bell=job_bell.result()
counts_bell=result_bell.get_counts()
plot_histogram(counts_bell)
#Import the random circuit class
from qiskit.circuit.random import random_circuit
#Create two random circuits
qc1 = random_circuit(2,2) #2 qubits, 2 layers of gates (in this case one layer: two one-qubit gate or one two-qubits gate)
qc2 = random_circuit(2,4)
#Concatenate the two random circuits
qc = qc1.compose(qc2)
#Draw the circuit
qc.draw('mpl')
#Define function to print circuit properties:
def print_circuit_props(qc):
width = qc.width() #number of gates in the layer with the most gates ("control" operation is counted as a gate (Ex. cx(0,1) width=2, one gate on qubit 0 and one on qubit 1),
#also the idenity (do nothing) in the layer with the most gates is counted as one gate, see the next example)
depth = qc.depth() #number of layers in witch we can partition the circuit
num_operators = qc.count_ops() #gives the list of operations with their number of applications
circuit_size = qc.size() #number of gates of the circuit
print('Width = ',width)
print('Depth = ', depth)
print('Circuit size = ',circuit_size)
print('Number of operators = ', num_operators)
#Pass our quantum circuit to print out the circuit properties
print_circuit_props(qc)
qc = QuantumCircuit(3)
qc.cx(0,1)
print_circuit_props(qc)
qc.draw('mpl')
qc = QuantumCircuit(3)
qc.ccx(0,1,2)
#Print out the circuit properties
print_circuit_props(qc)
qc.draw('mpl')
qc.decompose().draw('mpl')
#Print out the circuit properties
print_circuit_props(qc.decompose())
#Create a custom two-qubit composite gate
#Create the quantum register
qr = QuantumRegister(2, name='qr_c') #name parameter gives a name to qubits
#Generate quantum circuit which will make up the composite gate
comp_qc = QuantumCircuit(qr, name='my-composite') #my-composite is the name of the circuit
#Add any gates you wish to your composite gate
comp_qc.h(0)
comp_qc.cx(0, 1)
#Create the composite instructions by converting the QuantumCircuit to a list of Instructions
composite_inst = comp_qc.to_instruction()
#Draw the circuit which will represent the composite gate
comp_qc.draw('mpl')
#Create another 3-qubit circuit
qr2 = QuantumRegister(3, 'qr')
#Create a quantum circuit using the quantum register
qc = QuantumCircuit(qr2)
#Add any arbitrary gates that would represent the function of the composite gate
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
#Draw the composite circuit
qc.draw('mpl')
#Append your composite gate to the specified qubits.
qc.append(composite_inst, [qr2[0], qr2[1]])
#Draw the complete circuit
qc.draw('mpl')
qr=QuantumRegister(2,'qr')
circ=QuantumCircuit(qr,name='bell_minus')
circ.x(0)
circ.h(0)
circ.cx(0,1)
bell_minus = circ.to_instruction()
circ.draw('mpl')
qr_new=QuantumRegister(2,'qr_new')
circ1=QuantumCircuit(qr_new)
circ1.append(bell_minus, [qr_new[0], qr_new[1]])
circ1.draw('mpl')
theta = Parameter('θ')
n = 5
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(n-1):
qc.cx(i, i+1)
qc.barrier()
qc.rz(theta, range(5)) #theta is the angle of rotation range(5) is a way to apply rz to qubits from 0 to 4
qc.barrier()
for i in reversed(range(n-1)):
qc.cx(i, i+1)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
theta_range = np.linspace(0, 2 * np.pi, 128) #returns a list of 128 values equispaced in[0, 2pi]
circuits = [qc.bind_parameters({theta: theta_val}) for theta_val in theta_range]
#circuits is a list in whitch each element is the qc circuit with the parameter substituted by a value of theta_range
#Ex. circuit[0] = qc with theta=0 circuit[-1] = qc with theta=2pi
circuits[-1].draw('mpl')
from qiskit import BasicAer, transpile
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(circuits, backend)) #we are running all the circuits contained in circuits list
#transpile(circ,syst) optimizes the circuit for the system
#Transpilation is the process of rewriting a given input circuit to match the topology of a specific quantum device,
# and/or to optimize the circuit for execution on present day noisy quantum systems.
#Most circuits must undergo a series of transformations that make them compatible with a given target device,
# and optimize them to reduce the effects of noise on the resulting outcomes.
# Rewriting quantum circuits to match hardware constraints and optimizing for performance can be far from trivial.
# The flow of logic in the rewriting tool chain need not be linear, and can often have iterative sub-loops, conditional branches, and other complex behaviors.
#https://docs.quantum.ibm.com/api/qiskit/transpiler
counts = job.result().get_counts()
plot_histogram(counts) #this are the counts of measurement of the first qubit of all the elements of circuits list
job_zero = backend.run(transpile(circuits[0], backend)) #theta = 0
counts_zero = job_zero.result().get_counts()
plot_histogram(counts_zero)
job_20 = backend.run(transpile(circuits[20], backend)) #theta = 0.9894780011306435
counts_20 = job_20.result().get_counts()
plot_histogram(counts_20)
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111) #to create subplot of the figure fig
#The argument (111) is a shorthand for a subplot grid specification. In this case:
#The first digit represents the number of rows in the grid.
#The second digit represents the number of columns in the grid.
#The third digit represents the index of the subplot.
ax.plot(theta_range, list(map(lambda c: c.get('0', 0), counts)), '.-', label='0')
ax.plot(theta_range, list(map(lambda c: c.get('1', 0), counts)), '.-', label='1')
#lambda c:c.get('0',0), c is the input of the function, c.get('0',0) returns the value associated to the key '0', the other 0 is the default value
#The use of map() and lambda functions is one way to apply a function to each element of an iterable
#so map(lambda c: c.get('0', 0), counts) returns the number of '0' in each element of counts
ax.set_xticks([i * np.pi / 2 for i in range(5)])
ax.set_xticklabels(['0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'], fontsize=14)
ax.set_xlabel('θ', fontsize=14)
ax.set_ylabel('Counts', fontsize=14)
ax.legend(fontsize=14)
p = Parameter('p')
qc = QuantumCircuit(3, name='oracle')
qc.rz(p, 0)
qc.cx(0, 1)
qc.rz(p, 1)
qc.cx(1, 2)
qc.rz(p, 2)
theta = Parameter('theta')
phi = Parameter('phi')
gamma = Parameter('gamma')
qr = QuantumRegister(9)
larger_qc = QuantumCircuit(qr)
larger_qc.append(qc.to_instruction({p: theta}), qr[0:3])
larger_qc.append(qc.to_instruction({p: phi}), qr[3:6])
larger_qc.append(qc.to_instruction({p: gamma}), qr[6:9])
print(larger_qc.draw())
print(larger_qc.decompose().draw())
# Will execute the circuit on the state vector (sv) simulator
# Returns state vector results, circuit diagram, and Bloch sphere
from qiskit import Aer, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
def execute_circuit_sv(quantum_circuit):
#Create a state vector simulator
statevector_simulator = Aer.get_backend('statevector_simulator')
#Execute the circuit on the simulator
result = execute(quantum_circuit, statevector_simulator).result()
#Assign state vector results
statevector_results = result.get_statevector(quantum_circuit)
#Draw the circuit diagram
circuit_diagram = quantum_circuit.draw('mpl')
#Draw the Bloch sphere result
q_sphere = plot_state_qsphere(statevector_results)
#Return the results, circuit diagram, and Bloch sphere
return statevector_results, circuit_diagram, q_sphere
#H-gate
#Create the single qubit circuit
qc = QuantumCircuit(1)
#Add an H gate to the qubit
qc.h(0)
#Execute the circuit and capture all the results
result, img, qsphere = execute_circuit_sv(qc)
qsphere
#U3-gate
from math import pi
#Create a single qubit circuit
qc = QuantumCircuit(1)
#Add a U3 gate and rotate all parameters by pi/2, and apply it to the qubit
qc.u(pi/2, pi/2, pi/2, 0) #U3(theta, phi, lambda) executes a rotation of theta around x-axis, of phi around z-axis and pf lambda around y-axis
#Execute the circuit and capture all the results
result, img, qsphere = execute_circuit_sv(qc)
qsphere
import qiskit_ibm_provider
# Save you credential on disc
#IBMProvider.save_account("Your token", overwrite= True)
from qiskit_ibm_provider import IBMProvider
provider = IBMProvider()
from qiskit_ibm_provider import IBMProvider
provider = IBMProvider(token=<INSERT_IBM_QUANTUM_TOKEN>)
print(provider.backends())
# We use IBMQ ibm_brisbane
device_backend = provider.get_backend('ibm_brisbane')
# Display device configuration.
config = device_backend.configuration()
print("This backend is called {} (version {}) with {} qubit{}. "
"\nThe basis gates supported on this device are {}."
"".format(config.backend_name,
config.backend_version,
config.n_qubits,
'' if config.n_qubits == 1 else 's',
config.basis_gates))
#from qiskit.visualization import plot_coupling_map
#qubit_coordinates = [[0, 0], [0, 1], [0, 2], [1, 1], [2, 1]]
#plot_coupling_map(config.n_qubits, qubit_coordinates, config.coupling_map)
props = device_backend.properties()
def display_qubit_info(qubit, properties):
"""Print a string describing some of reported properties of the given qubit."""
# Conversion factors from standard SI units
us = 1e6
ns = 1e9
print("Qubit {0} has a \n"
" - T1 time of {1:.2f} microseconds\n"
" - T2 time of {2:.2f} microseconds\n"
" - U2 gate error of {3:.2e}\n"
" - Readout error of {4:.2e} ".format(
qubit,
properties.t1(qubit) * us,
properties.t2(qubit) * us,
properties.gate_error('sx', qubit),
properties.readout_error(qubit)))
display_qubit_info(0, props)
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
circuit = QuantumCircuit(7)
circuit.h(3)
circuit.cx(0, 6)
circuit.cx(6, 0)
circuit.cx(0, 1)
circuit.cx(3, 1)
circuit.cx(3, 0)
coupling_map = CouplingMap(couplinglist=coupling)
bs = BasicSwap(coupling_map=coupling_map)
pass_manager = PassManager(bs)
basic_circ = pass_manager.run(circuit)
ls = LookaheadSwap(coupling_map=coupling_map)
pass_manager = PassManager(ls)
lookahead_circ = pass_manager.run(circuit)
ss = StochasticSwap(coupling_map=coupling_map)
pass_manager = PassManager(ss)
stochastic_circ = pass_manager.run(circuit)
circuit.draw(output='mpl')
lookahead_circ.draw(output='mpl')
import math
from qiskit.providers.fake_provider import FakeTokyo
backend = FakeTokyo()
optimized_0 = transpile(circuit, backend=backend, seed_transpiler=11, optimization_level=0)
optimized_0.draw('mpl')
qc = random_circuit(3,2)
qc.measure_all()
# Select a backend to run the circuit
backend = provider.get_backend('ibmq_qasm_simulator')
result = backend.run(transpile(qc, backend), shots=1000).result()
counts = result.get_counts(qc)
print(counts)
# Plot the result
plot_histogram(counts, color='green', title="New Histogram")
## Insert your code here
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
#INSERT CODE HERE
## CHECK THE RESULT
from qiskit.visualization import plot_bloch_multivector, plot_histogram, array_to_latex
display(array_to_latex(Statevector.from_instruction(qc), prefix="\\text{Statevector} = "))
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#INSERT CODE HERE
## WRITE YOUR CODE HERE:
#
#
#
#
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
counts
## WRITE YOUR CODE/calculation HERE:
#
#
#
#
# inverse circuit
#BONUS VISUALIZATION
gate_colours = {
"displaycolor": {
"x": [ # gate name
"#da1e28", # box color (red)
"#FFFFFF" # box text color (white)
],
"h": [ # gate name
"#da1e28", # box color (red)
"#FFFFFF" # box text color (white)
],
"cx": [ # gate name
"#da1e28", # box color (red)
"#FFFFFF" # box text color (white)
],
"ry": [ # gate name
"#da1e28", # box color (red)
"#FFFFFF" # box text color (white)
],
},
}
display(qci.draw('mpl',style=gate_colours))
from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
qc_AB = QuantumCircuit(2)
qc_AB.h(0)
qc_AB.cx(0,1)
qc_AB.draw('mpl')
psi_AB = qi.Statevector.from_instruction(qc_AB)
psi_AB.draw('latex', prefix='|\\psi_{AB}\\rangle = ')
rho_AB = qi.DensityMatrix.from_instruction(qc_AB)
rho_AB.draw('latex', prefix='\\rho_{AB} = ')
from qiskit.visualization import plot_state_city
plot_state_city(rho_AB.data, title='Density Matrix')
import numpy as np
rho_p = qi.DensityMatrix.from_label('+')
display(rho_p.draw('latex', prefix='\\rho_p = '))
gamma_p = rho_p.purity()
print("State purity: ", np.round(np.real(gamma_p),3))
rho_m = 1/2*(qi.DensityMatrix.from_label('0') + qi.DensityMatrix.from_label('1'))
display(rho_m.draw('latex', prefix='\\rho_m = '))
gamma_m = rho_m.purity()
print("State purity: ", np.round(np.real(gamma_m),3))
rho_B = qi.partial_trace(rho_AB,[0])
rho_A = qi.partial_trace(rho_AB,[1])
display(rho_B.draw('latex', prefix=" \\rho_{B} = "),
rho_A.draw('latex', prefix=" \\rho_{A} = "))
qc_CD = QuantumCircuit(2)
qc_CD.ry(np.pi/3,0)
qc_CD.h(1)
qc_CD.cx(0,1)
qc_CD.cx(1,0)
qc_CD.draw("mpl", style="iqx")
from qiskit import *
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info import partial_trace, entropy
import numpy as np
import math
nQubits = # <--- insert your code here
nClassicBits = 4
circuit.draw(output='mpl')
# Run the quantum circuit on a statevector simulator backend
backend = # <--- insert your code here
outputstate = # <--- insert your code here
print(outputstate)
list_check = [5,7,8,10]
for ind in list_check:
print(outputstate[ind])
def check_vn_entropy(vn_entropy):
if vn_entropy != 0.:
print("The state is a mixed state")
## insert your code here -->
check_vn_entropy(my_entropy)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions import RXGate, XGate, CXGate
XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
XX
XX.data
input_dim, output_dim = XX.dim
input_dim, output_dim
op = Operator(np.random.rand(2 ** 1, 2 ** 2))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
op = Operator(np.random.rand(6, 6))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# Force input dimension to be (4,) rather than (2, 2)
op = Operator(np.random.rand(2 ** 1, 2 ** 2), input_dims=[4])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# Specify system is a qubit and qutrit
op = Operator(np.random.rand(6, 6),
input_dims=[2, 3], output_dims=[2, 3])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
print('Dimension of input system 0:', op.input_dims([0]))
print('Dimension of input system 1:', op.input_dims([1]))
# Create an Operator from a Pauli object
pauliXX = Pauli('XX')
Operator(pauliXX)
# Create an Operator for a Gate object
Operator(CXGate())
# Create an operator from a parameterized Gate object
Operator(RXGate(np.pi / 2))
# Create an operator from a QuantumCircuit object
circ = QuantumCircuit(10)
circ.h(0)
for j in range(1, 10):
circ.cx(j-1, j)
# Convert circuit to an operator by implicit unitary simulation
Operator(circ)
# Create an operator
XX = Operator(Pauli('XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
circ = transpile(circ, backend, basis_gates=['u1','u2','u3','cx'])
job = backend.run(circ)
job.result().get_counts(0)
# Add to a circuit
circ2 = QuantumCircuit(2, 2)
circ2.append(Pauli('XX'), [0, 1])
circ2.measure([0,1], [0,1])
circ2.draw()
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.tensor(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.expand(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.compose(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.compose(B, front=True)
# Compose XZ with an 3-qubit identity operator
op = Operator(np.eye(2 ** 3))
XZ = Operator(Pauli('XZ'))
op.compose(XZ, qargs=[0, 2])
# Compose YX in front of the previous operator
op = Operator(np.eye(2 ** 3))
YX = Operator(Pauli('YX'))
op.compose(XZ, qargs=[0, 2], front=True)
XX = Operator(Pauli('XX'))
YY = Operator(Pauli('YY'))
ZZ = Operator(Pauli('ZZ'))
op = 0.5 * (XX + YY - 3 * ZZ)
op
op.is_unitary()
# Compose with a matrix passed as a list
Operator(np.eye(2)).compose([[0, 1], [1, 0]])
Operator(Pauli('X')) == Operator(XGate())
Operator(XGate()) == np.exp(1j * 0.5) * Operator(XGate())
# Two operators which differ only by phase
op_a = Operator(XGate())
op_b = np.exp(1j * 0.5) * Operator(XGate())
# Compute process fidelity
F = process_fidelity(op_a, op_b)
print('Process fidelity =', F)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""
Choi-matrix representation of a Quantum Channel.
"""
from __future__ import annotations
import copy as _copy
import math
import numpy as np
from qiskit import _numpy_compat
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.instruction import Instruction
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel
from qiskit.quantum_info.operators.op_shape import OpShape
from qiskit.quantum_info.operators.channel.superop import SuperOp
from qiskit.quantum_info.operators.channel.transformations import _to_choi
from qiskit.quantum_info.operators.channel.transformations import _bipartite_tensor
from qiskit.quantum_info.operators.mixins import generate_apidocs
from qiskit.quantum_info.operators.base_operator import BaseOperator
class Choi(QuantumChannel):
r"""Choi-matrix representation of a Quantum Channel.
The Choi-matrix representation of a quantum channel :math:`\mathcal{E}`
is a matrix
.. math::
\Lambda = \sum_{i,j} |i\rangle\!\langle j|\otimes
\mathcal{E}\left(|i\rangle\!\langle j|\right)
Evolution of a :class:`~qiskit.quantum_info.DensityMatrix`
:math:`\rho` with respect to the Choi-matrix is given by
.. math::
\mathcal{E}(\rho) = \mbox{Tr}_{1}\left[\Lambda
(\rho^T \otimes \mathbb{I})\right]
where :math:`\mbox{Tr}_1` is the :func:`partial_trace` over subsystem 1.
See reference [1] for further details.
References:
1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus
for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015).
`arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_
"""
def __init__(
self,
data: QuantumCircuit | Instruction | BaseOperator | np.ndarray,
input_dims: int | tuple | None = None,
output_dims: int | tuple | None = None,
):
"""Initialize a quantum channel Choi matrix operator.
Args:
data (QuantumCircuit or
Instruction or
BaseOperator or
matrix): data to initialize superoperator.
input_dims (tuple): the input subsystem dimensions.
[Default: None]
output_dims (tuple): the output subsystem dimensions.
[Default: None]
Raises:
QiskitError: if input data cannot be initialized as a
Choi matrix.
Additional Information:
If the input or output dimensions are None, they will be
automatically determined from the input data. If the input data is
a Numpy array of shape (4**N, 4**N) qubit systems will be used. If
the input operator is not an N-qubit operator, it will assign a
single subsystem with dimension specified by the shape of the input.
"""
# If the input is a raw list or matrix we assume that it is
# already a Choi matrix.
if isinstance(data, (list, np.ndarray)):
# Initialize from raw numpy or list matrix.
choi_mat = np.asarray(data, dtype=complex)
# Determine input and output dimensions
dim_l, dim_r = choi_mat.shape
if dim_l != dim_r:
raise QiskitError("Invalid Choi-matrix input.")
if input_dims:
input_dim = np.prod(input_dims)
if output_dims:
output_dim = np.prod(output_dims)
if output_dims is None and input_dims is None:
output_dim = int(math.sqrt(dim_l))
input_dim = dim_l // output_dim
elif input_dims is None:
input_dim = dim_l // output_dim
elif output_dims is None:
output_dim = dim_l // input_dim
# Check dimensions
if input_dim * output_dim != dim_l:
raise QiskitError("Invalid shape for input Choi-matrix.")
op_shape = OpShape.auto(
dims_l=output_dims, dims_r=input_dims, shape=(output_dim, input_dim)
)
else:
# Otherwise we initialize by conversion from another Qiskit
# object into the QuantumChannel.
if isinstance(data, (QuantumCircuit, Instruction)):
# If the input is a Terra QuantumCircuit or Instruction we
# convert it to a SuperOp
data = SuperOp._init_instruction(data)
else:
# We use the QuantumChannel init transform to initialize
# other objects into a QuantumChannel or Operator object.
data = self._init_transformer(data)
op_shape = data._op_shape
output_dim, input_dim = op_shape.shape
# Now that the input is an operator we convert it to a Choi object
rep = getattr(data, "_channel_rep", "Operator")
choi_mat = _to_choi(rep, data._data, input_dim, output_dim)
super().__init__(choi_mat, op_shape=op_shape)
def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED):
dtype = self.data.dtype if dtype is None else dtype
return np.array(self.data, dtype=dtype, copy=copy)
@property
def _bipartite_shape(self):
"""Return the shape for bipartite matrix"""
return (self._input_dim, self._output_dim, self._input_dim, self._output_dim)
def _evolve(self, state, qargs=None):
return SuperOp(self)._evolve(state, qargs)
# ---------------------------------------------------------------------
# BaseOperator methods
# ---------------------------------------------------------------------
def conjugate(self):
ret = _copy.copy(self)
ret._data = np.conj(self._data)
return ret
def transpose(self):
ret = _copy.copy(self)
ret._op_shape = self._op_shape.transpose()
# Make bipartite matrix
d_in, d_out = self.dim
data = np.reshape(self._data, (d_in, d_out, d_in, d_out))
# Swap input and output indices on bipartite matrix
data = np.transpose(data, (1, 0, 3, 2))
ret._data = np.reshape(data, (d_in * d_out, d_in * d_out))
return ret
def compose(self, other: Choi, qargs: list | None = None, front: bool = False) -> Choi:
if qargs is None:
qargs = getattr(other, "qargs", None)
if qargs is not None:
return Choi(SuperOp(self).compose(other, qargs=qargs, front=front))
if not isinstance(other, Choi):
other = Choi(other)
new_shape = self._op_shape.compose(other._op_shape, qargs, front)
output_dim, input_dim = new_shape.shape
if front:
first = np.reshape(other._data, other._bipartite_shape)
second = np.reshape(self._data, self._bipartite_shape)
else:
first = np.reshape(self._data, self._bipartite_shape)
second = np.reshape(other._data, other._bipartite_shape)
# Contract Choi matrices for composition
data = np.reshape(
np.einsum("iAjB,AkBl->ikjl", first, second),
(input_dim * output_dim, input_dim * output_dim),
)
ret = Choi(data)
ret._op_shape = new_shape
return ret
def tensor(self, other: Choi) -> Choi:
if not isinstance(other, Choi):
other = Choi(other)
return self._tensor(self, other)
def expand(self, other: Choi) -> Choi:
if not isinstance(other, Choi):
other = Choi(other)
return self._tensor(other, self)
@classmethod
def _tensor(cls, a, b):
ret = _copy.copy(a)
ret._op_shape = a._op_shape.tensor(b._op_shape)
ret._data = _bipartite_tensor(
a._data, b.data, shape1=a._bipartite_shape, shape2=b._bipartite_shape
)
return ret
# Update docstrings for API docs
generate_apidocs(Choi)
|
https://github.com/ColibrITD-SAS/mpqp
|
ColibrITD-SAS
|
from math import sqrt, pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import oracle_simple
import composed_gates
def get_circuit(n, oracles):
"""
Build the circuit composed by the oracle black box and the other quantum gates.
:param n: The number of qubits (not including the ancillas)
:param oracles: A list of black box (quantum) oracles; each of them selects a specific state
:returns: The proper quantum circuit
:rtype: qiskit.QuantumCircuit
"""
cr = ClassicalRegister(n)
## Testing
if n > 3:
#anc = QuantumRegister(n - 1, 'anc')
# n qubits for the real number
# n - 1 qubits for the ancillas
qr = QuantumRegister(n + n - 1)
qc = QuantumCircuit(qr, cr)
else:
# We don't need ancillas
qr = QuantumRegister(n)
qc = QuantumCircuit(qr, cr)
## /Testing
print("Number of qubits is {0}".format(len(qr)))
print(qr)
# Initial superposition
for j in range(n):
qc.h(qr[j])
# The length of the oracles list, or, in other words, how many roots of the function do we have
m = len(oracles)
# Grover's algorithm is a repetition of an oracle box and a diffusion box.
# The number of repetitions is given by the following formula.
print("n is ", n)
r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2))
print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r))
oracle_t1 = oracle_simple.OracleSimple(n, 5)
oracle_t2 = oracle_simple.OracleSimple(n, 0)
for j in range(r):
for i in range(len(oracles)):
oracles[i].get_circuit(qr, qc)
diffusion(n, qr, qc)
for j in range(n):
qc.measure(qr[j], cr[j])
return qc, len(qr)
def diffusion(n, qr, qc):
"""
The Grover diffusion operator.
Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit.
"""
for j in range(n):
qc.h(qr[j])
# D matrix, flips state |000> only (instead of flipping all the others)
for j in range(n):
qc.x(qr[j])
# 0..n-2 control bits, n-1 target, n..
if n > 3:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1],
[qr[j] for j in range(n, n + n - 1)])
else:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1], None)
for j in range(n):
qc.x(qr[j])
for j in range(n):
qc.h(qr[j])
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
# Importing Packages
import matplotlib.pyplot as plt
import numpy as np
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile, assemble
from qiskit.visualization import plot_histogram
# Input Secret Number
s = input("Input the secret number:\n")
n=len(s)
qc = QuantumCircuit(n+1, n)
# Putting states in superposition
qc.x(n)
for i in range(n+1):
qc.h(i)
qc.barrier()
# Apply the inner-product oracle
s=s[::-1] # reverse s to fit qiskit's qubit ordering
print(s)
for k in range(n):
if s[k] == '1':
qc.cx(k, n)
qc.barrier()
# Measuring
for m in range(n):
qc.h(m)
qc.barrier()
for b in range(n):
qc.measure(b,b)
qc.draw(output="mpl")
# Simulating on local simulator
aer_sim = Aer.get_backend('aer_simulator')
shots = 1024
qobj = assemble(qc)
results = aer_sim.run(qobj).result()
count = results.get_counts()
plot_histogram(count)
|
https://github.com/kuehnste/QiskitTutorial
|
kuehnste
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import *
from qiskit.quantum_info import state_fidelity
# Magic function to render plots in the notebook after the cell executing the plot command
%matplotlib inline
def run_on_qasm_simulator(quantum_circuit, num_shots):
"""Takes a circuit, the number of shots and a backend and returns the counts for running the circuit
on the qasm_simulator backend."""
qasm_simulator = Aer.get_backend('qasm_simulator')
job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots)
result = job.result()
counts = result.get_counts(quantum_circuit)
return counts
def oracle_f1():
"Oracle implementing function f1"
qc = QuantumCircuit(3)
qc.cnot(0,2)
qc.cnot(1,2)
qc.x(2)
qc.cnot(1,2)
qc.cnot(0,2)
return qc
def oracle_f2():
"Oracle implementing function f2"
qc = QuantumCircuit(3)
qc.cnot(0,2)
qc.x(2)
qc.cnot(1,2)
return qc
# We visualize the oracle
qc_oracle_f1 = oracle_f1()
qc_oracle_f1.draw('mpl')
# Create a quantum circuit for 3 qubits and 2 classical registers
qc_deutch_josza_oracle1 = QuantumCircuit(3,2)
# Add the Hadamard gate
qc_deutch_josza_oracle1.h(0)
qc_deutch_josza_oracle1.h(1)
# Apply the oracle
qc_deutch_josza_oracle1.compose(qc_oracle_f1, inplace=True)
# Add the z-gate acting on the ancilla
qc_deutch_josza_oracle1.z(2)
# Apply the oracle again
qc_deutch_josza_oracle1.compose(qc_oracle_f1, inplace=True)
# Add the Hadamard gate
qc_deutch_josza_oracle1.h(0)
qc_deutch_josza_oracle1.h(1)
# Add measurement to the first two qubits
qc_deutch_josza_oracle1.barrier()
qc_deutch_josza_oracle1.measure(range(2),range(2))
# Visualize the circuit
qc_deutch_josza_oracle1.draw('mpl')
# The number of shots we use
num_shots = 100
# Now we run the circuit
res_qc_deutch_josza_oracle1 = run_on_qasm_simulator(qc_deutch_josza_oracle1, num_shots)
# Visualize the results in form of a histogram
plot_histogram(res_qc_deutch_josza_oracle1, title='Deutsch-Josza algorithm, oracle 1')
# We visualize the oracle
qc_oracle_f2 = oracle_f2()
qc_oracle_f2.draw('mpl')
# Create a quantum circuit for 3 qubits and 2 classical registers
qc_deutch_josza_oracle2 = QuantumCircuit(3,2)
# Add the Hadamard gate
qc_deutch_josza_oracle2.h(0)
qc_deutch_josza_oracle2.h(1)
# Apply the oracle
qc_deutch_josza_oracle2.compose(qc_oracle_f2, inplace=True)
# Add the z-gate acting on the ancilla
qc_deutch_josza_oracle2.z(2)
# Apply the oracle again
qc_deutch_josza_oracle2.compose(qc_oracle_f2, inplace=True)
# Add the Hadamard gate
qc_deutch_josza_oracle2.h(0)
qc_deutch_josza_oracle2.h(1)
# Add measurement to the first two qubits
qc_deutch_josza_oracle2.barrier()
qc_deutch_josza_oracle2.measure(range(2),range(2))
# Visualize the circuit
qc_deutch_josza_oracle2.draw('mpl')
# The number of shots we use
num_shots = 100
# Now we run the circuit
res_qc_deutch_josza_oracle2 = run_on_qasm_simulator(qc_deutch_josza_oracle2, num_shots)
# Visualize the results in form of a histogram
plot_histogram(res_qc_deutch_josza_oracle2, title='Deutsch-Josza algorithm, oracle 2')
# Generate the circuits that are preparing the basis states
qc_00 = QuantumCircuit(3)
# 00
qc_01 = QuantumCircuit(3)
qc_01.x(1)
# 10
qc_10 = QuantumCircuit(3)
qc_10.x(0)
# 11
qc_11 = QuantumCircuit(3)
qc_11.x(0)
qc_11.x(1)
qcs_basis_states = [qc_00, qc_01, qc_10, qc_11]
# The number of shots we are going to use
num_shots = 100
# Prepare empty lists for the results of the two oracles
res_oracle1 = list()
res_oracle2 = list()
# We run the oracles on the basis states and record the outcomes
for qc_basis_state in qcs_basis_states:
# The quantum circuit sending a basis state through oracle 1 and measuring the output
qc_oracle1 = QuantumCircuit(3,1)
qc_oracle1.compose(qc_basis_state, inplace=True)
qc_oracle1.compose(oracle_f1(), inplace=True)
qc_oracle1.measure(2,0)
# The quantum circuit sending a basis state through oracle 2 and measuring the output
qc_oracle2 = QuantumCircuit(3,1)
qc_oracle2.compose(qc_basis_state, inplace=True)
qc_oracle2.compose(oracle_f2(), inplace=True)
qc_oracle2.measure(2,0)
# We run the circuits on the qasm simulator
res_oracle1.append(run_on_qasm_simulator(qc_oracle1, num_shots))
res_oracle2.append(run_on_qasm_simulator(qc_oracle2, num_shots))
# Visualize the results for oracle 1
plot_histogram(res_oracle1, title='Results oracle 1', legend=['input |00>', 'input |01>', 'input |10>', 'input |11>'])
# Visualize the results for oracle 2
plot_histogram(res_oracle2, title='Results oracle 2', legend=['input |00>', 'input |01>', 'input |10>', 'input |11>'])
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test PauliSumOp."""
import unittest
from itertools import product
from test.python.opflow import QiskitOpflowTestCase
from ddt import ddt, data, unpack
import numpy as np
from scipy.sparse import csr_matrix
from sympy import Symbol
from qiskit import QuantumCircuit, transpile
from qiskit.circuit import Parameter, ParameterExpression, ParameterVector
from qiskit.opflow import (
CX,
CircuitStateFn,
DictStateFn,
H,
I,
One,
OperatorStateFn,
PauliSumOp,
SummedOp,
X,
Y,
Z,
Zero,
OpflowError,
)
from qiskit.quantum_info import Pauli, PauliTable, SparsePauliOp
@ddt
class TestPauliSumOp(QiskitOpflowTestCase):
"""PauliSumOp tests."""
def test_construct(self):
"""constructor test"""
sparse_pauli = SparsePauliOp(Pauli("XYZX"), coeffs=[2.0])
coeff = 3.0
pauli_sum = PauliSumOp(sparse_pauli, coeff=coeff)
self.assertIsInstance(pauli_sum, PauliSumOp)
self.assertEqual(pauli_sum.primitive, sparse_pauli)
self.assertEqual(pauli_sum.coeff, coeff)
self.assertEqual(pauli_sum.num_qubits, 4)
def test_coeffs(self):
"""ListOp.coeffs test"""
sum1 = SummedOp(
[(0 + 1j) * X, (1 / np.sqrt(2) + 1j / np.sqrt(2)) * Z], 0.5
).collapse_summands()
self.assertAlmostEqual(sum1.coeffs[0], 0.5j)
self.assertAlmostEqual(sum1.coeffs[1], (1 + 1j) / (2 * np.sqrt(2)))
a_param = Parameter("a")
b_param = Parameter("b")
param_exp = ParameterExpression({a_param: 1, b_param: 0}, Symbol("a") ** 2 + Symbol("b"))
sum2 = SummedOp([X, (1 / np.sqrt(2) - 1j / np.sqrt(2)) * Y], param_exp).collapse_summands()
self.assertIsInstance(sum2.coeffs[0], ParameterExpression)
self.assertIsInstance(sum2.coeffs[1], ParameterExpression)
# Nested ListOp
sum_nested = SummedOp([X, sum1])
self.assertRaises(TypeError, lambda: sum_nested.coeffs)
def test_add(self):
"""add test"""
pauli_sum = 3 * X + Y
self.assertIsInstance(pauli_sum, PauliSumOp)
expected = PauliSumOp(3.0 * SparsePauliOp(Pauli("X")) + SparsePauliOp(Pauli("Y")))
self.assertEqual(pauli_sum, expected)
pauli_sum = X + Y
summed_op = SummedOp([X, Y])
self.assertEqual(pauli_sum, summed_op)
a = Parameter("a")
b = Parameter("b")
actual = a * PauliSumOp.from_list([("X", 2)]) + b * PauliSumOp.from_list([("Y", 1)])
expected = SummedOp(
[PauliSumOp.from_list([("X", 2)], a), PauliSumOp.from_list([("Y", 1)], b)]
)
self.assertEqual(actual, expected)
def test_mul(self):
"""multiplication test"""
target = 2 * (X + Z)
self.assertEqual(target.coeff, 1)
self.assertListEqual(target.primitive.to_list(), [("X", (2 + 0j)), ("Z", (2 + 0j))])
target = 0 * (X + Z)
self.assertEqual(target.coeff, 0)
self.assertListEqual(target.primitive.to_list(), [("X", (1 + 0j)), ("Z", (1 + 0j))])
beta = Parameter("β")
target = beta * (X + Z)
self.assertEqual(target.coeff, 1.0 * beta)
self.assertListEqual(target.primitive.to_list(), [("X", (1 + 0j)), ("Z", (1 + 0j))])
def test_adjoint(self):
"""adjoint test"""
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("XYZX"), coeffs=[2]), coeff=3)
expected = PauliSumOp(SparsePauliOp(Pauli("XYZX")), coeff=6)
self.assertEqual(pauli_sum.adjoint(), expected)
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("XYZY"), coeffs=[2]), coeff=3j)
expected = PauliSumOp(SparsePauliOp(Pauli("XYZY")), coeff=-6j)
self.assertEqual(pauli_sum.adjoint(), expected)
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("X"), coeffs=[1]))
self.assertEqual(pauli_sum.adjoint(), pauli_sum)
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("Y"), coeffs=[1]))
self.assertEqual(pauli_sum.adjoint(), pauli_sum)
pauli_sum = PauliSumOp(SparsePauliOp(Pauli("Z"), coeffs=[1]))
self.assertEqual(pauli_sum.adjoint(), pauli_sum)
pauli_sum = (Z ^ Z) + (Y ^ I)
self.assertEqual(pauli_sum.adjoint(), pauli_sum)
def test_equals(self):
"""equality test"""
self.assertNotEqual((X ^ X) + (Y ^ Y), X + Y)
self.assertEqual((X ^ X) + (Y ^ Y), (Y ^ Y) + (X ^ X))
self.assertEqual(0 * X + I, I)
self.assertEqual(I, 0 * X + I)
theta = ParameterVector("theta", 2)
pauli_sum0 = theta[0] * (X + Z)
pauli_sum1 = theta[1] * (X + Z)
expected = PauliSumOp(
SparsePauliOp(Pauli("X")) + SparsePauliOp(Pauli("Z")),
coeff=1.0 * theta[0],
)
self.assertEqual(pauli_sum0, expected)
self.assertNotEqual(pauli_sum1, expected)
def test_tensor(self):
"""Test for tensor operation"""
with self.subTest("Test 1"):
pauli_sum = ((I - Z) ^ (I - Z)) + ((X - Y) ^ (X + Y))
expected = (I ^ I) - (I ^ Z) - (Z ^ I) + (Z ^ Z) + (X ^ X) + (X ^ Y) - (Y ^ X) - (Y ^ Y)
self.assertEqual(pauli_sum, expected)
with self.subTest("Test 2"):
pauli_sum = (Z + I) ^ Z
expected = (Z ^ Z) + (I ^ Z)
self.assertEqual(pauli_sum, expected)
with self.subTest("Test 3"):
pauli_sum = Z ^ (Z + I)
expected = (Z ^ Z) + (Z ^ I)
self.assertEqual(pauli_sum, expected)
@data(([1, 2, 4], "XIYZI"), ([2, 1, 0], "ZYX"))
@unpack
def test_permute(self, permutation, expected_pauli):
"""Test the permute method."""
pauli_sum = PauliSumOp(SparsePauliOp.from_list([("XYZ", 1)]))
expected = PauliSumOp(SparsePauliOp.from_list([(expected_pauli, 1)]))
permuted = pauli_sum.permute(permutation)
with self.subTest(msg="test permutated object"):
self.assertEqual(permuted, expected)
with self.subTest(msg="test original object is unchanged"):
original = PauliSumOp(SparsePauliOp.from_list([("XYZ", 1)]))
self.assertEqual(pauli_sum, original)
@data([1, 2, 1], [1, 2, -1])
def test_permute_invalid(self, permutation):
"""Test the permute method raises an error on invalid permutations."""
pauli_sum = PauliSumOp(SparsePauliOp((X ^ Y ^ Z).primitive))
with self.assertRaises(OpflowError):
pauli_sum.permute(permutation)
def test_compose(self):
"""compose test"""
target = (X + Z) @ (Y + Z)
expected = 1j * Z - 1j * Y - 1j * X + I
self.assertEqual(target, expected)
observable = (X ^ X) + (Y ^ Y) + (Z ^ Z)
state = CircuitStateFn((CX @ (X ^ H @ X)).to_circuit())
self.assertAlmostEqual((~OperatorStateFn(observable) @ state).eval(), -3)
def test_to_matrix(self):
"""test for to_matrix method"""
target = (Z + Y).to_matrix()
expected = np.array([[1.0, -1j], [1j, -1]])
np.testing.assert_array_equal(target, expected)
def test_str(self):
"""str test"""
target = 3.0 * (X + 2.0 * Y - 4.0 * Z)
expected = "3.0 * X\n+ 6.0 * Y\n- 12.0 * Z"
self.assertEqual(str(target), expected)
alpha = Parameter("α")
target = alpha * (X + 2.0 * Y - 4.0 * Z)
expected = "1.0*α * (\n 1.0 * X\n + 2.0 * Y\n - 4.0 * Z\n)"
self.assertEqual(str(target), expected)
def test_eval(self):
"""eval test"""
target0 = (2 * (X ^ Y ^ Z) + 3 * (X ^ X ^ Z)).eval("000")
target1 = (2 * (X ^ Y ^ Z) + 3 * (X ^ X ^ Z)).eval(Zero ^ 3)
expected = DictStateFn({"110": (3 + 2j)})
self.assertEqual(target0, expected)
self.assertEqual(target1, expected)
phi = 0.5 * ((One + Zero) ^ 2)
zero_op = (Z + I) / 2
one_op = (I - Z) / 2
h1 = one_op ^ I
h2 = one_op ^ (one_op + zero_op)
h2a = one_op ^ one_op
h2b = one_op ^ zero_op
self.assertEqual((~OperatorStateFn(h1) @ phi).eval(), 0.5)
self.assertEqual((~OperatorStateFn(h2) @ phi).eval(), 0.5)
self.assertEqual((~OperatorStateFn(h2a) @ phi).eval(), 0.25)
self.assertEqual((~OperatorStateFn(h2b) @ phi).eval(), 0.25)
pauli_op = (Z ^ I ^ X) + (I ^ I ^ Y)
mat_op = pauli_op.to_matrix_op()
full_basis = ["".join(b) for b in product("01", repeat=pauli_op.num_qubits)]
for bstr1, bstr2 in product(full_basis, full_basis):
self.assertEqual(pauli_op.eval(bstr1).eval(bstr2), mat_op.eval(bstr1).eval(bstr2))
def test_exp_i(self):
"""exp_i test"""
# TODO: add tests when special methods are added
pass
def test_to_instruction(self):
"""test for to_instruction"""
target = ((X + Z) / np.sqrt(2)).to_instruction()
qc = QuantumCircuit(1)
qc.u(np.pi / 2, 0, np.pi, 0)
qc_out = transpile(target.definition, basis_gates=["u"])
self.assertEqual(qc_out, qc)
def test_to_pauli_op(self):
"""test to_pauli_op method"""
target = X + Y
self.assertIsInstance(target, PauliSumOp)
expected = SummedOp([X, Y])
self.assertEqual(target.to_pauli_op(), expected)
def test_getitem(self):
"""test get item method"""
target = X + Z
self.assertEqual(target[0], PauliSumOp(SparsePauliOp(X.primitive)))
self.assertEqual(target[1], PauliSumOp(SparsePauliOp(Z.primitive)))
def test_len(self):
"""test len"""
target = X + Y + Z
self.assertEqual(len(target), 3)
def test_reduce(self):
"""test reduce"""
target = X + X + Z
self.assertEqual(len(target.reduce()), 2)
def test_to_spmatrix(self):
"""test to_spmatrix"""
target = X + Y
expected = csr_matrix([[0, 1 - 1j], [1 + 1j, 0]])
self.assertEqual((target.to_spmatrix() - expected).nnz, 0)
def test_from_list(self):
"""test from_list"""
target = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
expected = (
-1.052373245772859 * (I ^ I)
+ 0.39793742484318045 * (I ^ Z)
- 0.39793742484318045 * (Z ^ I)
- 0.01128010425623538 * (Z ^ Z)
+ 0.18093119978423156 * (X ^ X)
)
self.assertEqual(target, expected)
a = Parameter("a")
target = PauliSumOp.from_list([("X", 0.5 * a), ("Y", -0.5j * a)], dtype=object)
expected = PauliSumOp(
SparsePauliOp.from_list([("X", 0.5 * a), ("Y", -0.5j * a)], dtype=object)
)
self.assertEqual(target.primitive, expected.primitive)
def test_matrix_iter(self):
"""Test PauliSumOp dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
table = PauliTable.from_labels(labels)
coeff = 10
op = PauliSumOp(SparsePauliOp(table, coeffs), coeff)
for idx, i in enumerate(op.matrix_iter()):
self.assertTrue(np.array_equal(i, coeff * coeffs[idx] * Pauli(labels[idx]).to_matrix()))
def test_matrix_iter_sparse(self):
"""Test PauliSumOp sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
coeffs = np.array([1, 2, 3, 4, 5, 6])
coeff = 10
table = PauliTable.from_labels(labels)
op = PauliSumOp(SparsePauliOp(table, coeffs), coeff)
for idx, i in enumerate(op.matrix_iter(sparse=True)):
self.assertTrue(
np.array_equal(i.toarray(), coeff * coeffs[idx] * Pauli(labels[idx]).to_matrix())
)
def test_is_hermitian(self):
"""Test is_hermitian method"""
with self.subTest("True test"):
target = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
self.assertTrue(target.is_hermitian())
with self.subTest("False test"):
target = PauliSumOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045j),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
self.assertFalse(target.is_hermitian())
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.qasm3
program = """
OPENQASM 3.0;
include "stdgates.inc";
input float[64] a;
qubit[3] q;
bit[2] mid;
bit[3] out;
let aliased = q[0:1];
gate my_gate(a) c, t {
gphase(a / 2);
ry(a) c;
cx c, t;
}
gate my_phase(a) c {
ctrl @ inv @ gphase(a) c;
}
my_gate(a * 2) aliased[0], q[{1, 2}][0];
measure q[0] -> mid[0];
measure q[1] -> mid[1];
while (mid == "00") {
reset q[0];
reset q[1];
my_gate(a) q[0], q[1];
my_phase(a - pi/2) q[1];
mid[0] = measure q[0];
mid[1] = measure q[1];
}
if (mid[0]) {
let inner_alias = q[{0, 1}];
reset inner_alias;
}
out = measure q;
"""
circuit = qiskit.qasm3.loads(program)
circuit.draw("mpl")
|
https://github.com/jcylim/QiskitProject
|
jcylim
|
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Demo basic optimization: Remove Zero Rotations and Remove Double CNOTs.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import CompositeGate
from qiskit.extensions.standard.cx import CnotGate
from qiskit.extensions.standard.rx import RXGate
quantum_r = QuantumRegister(4, "qr")
classical_r = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(quantum_r, classical_r)
circuit.h(quantum_r[0])
circuit.rx(0, quantum_r[0])
circuit.cx(quantum_r[0], quantum_r[1])
circuit.cx(quantum_r[0], quantum_r[1])
circuit.h(quantum_r[0])
circuit.cx(quantum_r[0], quantum_r[1])
composite_gate_1 = CompositeGate("composite1", [],
[quantum_r[x] for x in range(4)])
composite_gate_1._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_1)
circuit.h(quantum_r[0])
composite_gate_2 = CompositeGate("composite2", [],
[quantum_r[x] for x in range(4)])
composite_gate_2._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_2)
circuit.cx(quantum_r[0], quantum_r[1])
circuit.h(quantum_r[0])
composite_gate_3 = CompositeGate("composite3", [],
[quantum_r[x] for x in range(4)])
composite_gate_3._attach(CnotGate(quantum_r[0], quantum_r[1]))
composite_gate_3._attach(CnotGate(quantum_r[0], quantum_r[2]))
circuit._attach(composite_gate_3)
circuit.h(quantum_r[0])
composite_gate_4 = CompositeGate("composite4", [],
[quantum_r[x] for x in range(4)])
composite_gate_4._attach(CnotGate(quantum_r[0], quantum_r[1]))
composite_gate_4._attach(RXGate(0, quantum_r[0]))
composite_gate_4._attach(CnotGate(quantum_r[0], quantum_r[1]))
circuit._attach(composite_gate_4)
print("Removed Zero Rotations: " + str(circuit.remove_zero_rotations()))
print("Removed Double CNOTs: " + str(circuit.remove_double_cnots_once()))
QASM_source = circuit.qasm()
print(QASM_source)
|
https://github.com/thyung/qiskit_factorization
|
thyung
|
import numpy as np
from numpy import pi
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.circuit import QuantumRegister, ClassicalRegister
from qiskit.circuit.library import QFT
sim = Aer.get_backend('statevector_simulator')
init_state = '101'
qc1 = QuantumCircuit(3)
qc1.initialize(init_state)
qc1.append(QFT(num_qubits=3), [0, 1, 2])
display(qc1.draw())
sv1 = sim.run(transpile(qc1, sim)).result().get_statevector()
plot_bloch_multivector(sv1)
sim = Aer.get_backend('statevector_simulator')
init_state = '101'
qc2 = QuantumCircuit(3)
qc2.initialize(init_state)
qc2.barrier()
qc2.h(2)
qc2.cp(pi/2, 1, 2)
qc2.cp(pi/4, 0, 2)
qc2.h(1)
qc2.cp(pi/2, 0, 1)
qc2.h(0)
qc2.swap(0, 2)
display(qc2.draw())
sv2 = sim.run(qc2).result().get_statevector()
plot_bloch_multivector(sv2)
# implement general QFT
def create_qft(n, draw=False):
qc = QuantumCircuit(n)
for i in reversed(range(n)):
qc.h(i)
for e, j in enumerate(reversed(range(i))):
qc.cp(pi/2**(e+1), j, i)
for i in range(n//2):
qc.swap(i, n-i-1)
if draw:
display(qc.draw())
return qc.to_gate(label='myqft{}'.format(n))
sim = Aer.get_backend('statevector_simulator')
init_state = '101'
qc3 = QuantumCircuit(3)
qc3.initialize(init_state)
qc3.append(create_qft(3, True), [0, 1, 2])
display(qc3.draw())
sv3 = sim.run(transpile(qc3, sim)).result().get_statevector()
plot_bloch_multivector(sv3)
def create_carrier_orig(name=None, draw=False):
c0 = QuantumRegister(1, 'c0')
a0 = QuantumRegister(1, 'a0')
b0 = QuantumRegister(1, 'b0')
c1 = QuantumRegister(1, 'c1')
qc = QuantumCircuit(c0, a0, b0, c1)
qc.toffoli(1, 2, 3)
qc.cx(1, 2)
qc.toffoli(0, 2, 3)
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'carrier_orig')
def create_carrier_orig_inv(name=None):
qc = QuantumCircuit(4)
qc.append(create_carrier_orig().inverse(), range(4))
return qc.to_gate(label=name or 'carrier_orig_inv')
create_carrier_orig('carrier', True)
def create_carrier(name=None, draw=False):
c0 = QuantumRegister(1, 'c0')
a0 = QuantumRegister(1, 'a0')
b0 = QuantumRegister(1, 'b0')
c1 = QuantumRegister(1, 'c1')
qc = QuantumCircuit(c0, a0, b0, c1)
qc.toffoli(1, 2, 3)
qc.cx(1, 2)
qc.toffoli(0, 2, 3)
qc.cx(1, 2)
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'carrier')
def create_carrier_inv(name=None):
qc = QuantumCircuit(4)
qc.append(create_carrier().inverse(), range(4))
return qc.to_gate(label=name or 'carrier_inv')
create_carrier('carrier', True)
def create_sum(name=None, draw=False):
c0 = QuantumRegister(1, 'c0')
a0 = QuantumRegister(1, 'a0')
b0 = QuantumRegister(1, 'b0')
qc = QuantumCircuit(c0, a0, b0)
qc.cx(a0, b0)
qc.cx(c0, b0)
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'sum')
def create_sum_inv(name=None):
qc = QuantumCircuit(3)
qc.append(create_sum().inverse(), range(3))
return qc.to_gate(label=name or 'sum_inv')
create_sum('sum', True)
a = QuantumRegister(3, 'a')
b = QuantumRegister(4, 'b')
c = QuantumRegister(3, 'c')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, creg)
qc.x(a[0]) # a = 101(2)
qc.x(a[2])
qc.x(b[1]) # b = 110(2)
qc.x(b[2])
qc.append(create_carrier_orig(), [c[0], a[0], b[0], c[1]])
qc.append(create_carrier_orig(), [c[1], a[1], b[1], c[2]])
qc.append(create_carrier_orig(), [c[2], a[2], b[2], b[3]])
qc.cx(a[2], b[2])
qc.append(create_sum(), [c[2], a[2], b[2]])
qc.append(create_carrier_orig_inv(), [c[1], a[1], b[1], c[2]])
qc.append(create_sum(), [c[1], a[1], b[1]])
qc.append(create_carrier_orig_inv(), [c[0], a[0], b[0], c[1]])
qc.append(create_sum(), [c[0], a[0], b[0]])
qc.barrier()
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
a = QuantumRegister(3, 'a')
b = QuantumRegister(4, 'b')
c = QuantumRegister(3, 'c')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, creg)
qc.x(a[0]) # a = 101(2)
qc.x(a[2])
qc.x(b[1]) # b = 110(2)
qc.x(b[2])
qc.append(create_carrier(), [c[0], a[0], b[0], c[1]])
qc.append(create_carrier(), [c[1], a[1], b[1], c[2]])
qc.append(create_carrier(), [c[2], a[2], b[2], b[3]])
# qc.cx(a[2], b[2]) # this was put into create_carrier()
qc.append(create_sum(), [c[2], a[2], b[2]])
qc.append(create_carrier_inv(), [c[1], a[1], b[1], c[2]])
qc.append(create_sum(), [c[1], a[1], b[1]])
qc.append(create_carrier_inv(), [c[0], a[0], b[0], c[1]])
qc.append(create_sum(), [c[0], a[0], b[0]])
qc.barrier()
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_adder(n, name=None, draw=False):
"""create adder with n bits a, n+1 bits b and n bits carrier"""
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
qc = QuantumCircuit(a, b, c)
for i in range(n-1):
qc.append(create_carrier(), [c[i], a[i], b[i], c[i+1]])
qc.append(create_carrier(), [c[n-1], a[n-1], b[n-1], b[n]])
qc.append(create_sum(), [c[n-1], a[n-1], b[n-1]])
for i in reversed(range(n-1)):
qc.append(create_carrier_inv(), [c[i], a[i], b[i], c[i+1]])
qc.append(create_sum(), [c[i], a[i], b[i]])
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'adder')
def create_adder_inv(n, name=None):
qc = QuantumCircuit(3*n+1)
qc.append(create_adder(n).inverse(), range(3*n+1))
return qc.to_gate(label=name or 'adder_inv')
create_adder(3, 'adder', True)
a = QuantumRegister(3, 'a')
b = QuantumRegister(4, 'b')
c = QuantumRegister(3, 'c')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, creg)
qc.x(a[0]) # a = 5
qc.x(a[2])
qc.x(b[1]) # b = 6
qc.x(b[2])
qc.append(create_adder(3), range(10))
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_adder_mod(n, bigN, name=None, draw=False):
"""
:param n: number of bits for a, c and bigN; b has n+1 bits
:param bigN: mod number
:return: Gate of 4n+2 qubits
0 to n-1 (n qubits) for a
n to 2n (n+1 qubits) for b
2n+1 to 3n (n qubits) for c (init to 0)
3n+1 to 4n (n qubits) for bigN (init to bigN when use)
4n+1 (1 qubit) for temp (init to 0)
"""
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bigN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(a, b, c, bN, t)
# block 1
qc.append(create_adder(n), list(a)+list(b)+list(c))
for i in range(n):
qc.swap(a[i], bN[i])
qc.append(create_adder_inv(n), list(a)+list(b)+list(c))
qc.x(b[n])
qc.cx(b[n], t[0])
qc.x(b[n])
tempN = bigN
i = 0
while tempN != 0:
if tempN % 2 != 0:
qc.cx(t[0], a[i])
i = i + 1
tempN = tempN // 2
qc.append(create_adder(n), list(a)+list(b)+list(c))
tempN = bigN
i = 0
while tempN != 0:
if tempN % 2 != 0:
qc.cx(t[0], a[i])
i = i + 1
tempN = tempN // 2
for i in range(n):
qc.swap(a[i], bN[i])
# block 2
qc.append(create_adder_inv(n), list(a)+list(b)+list(c))
qc.cx(b[n], t[0])
qc.append(create_adder(n), list(a)+list(b)+list(c))
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'adder_mod')
create_adder_mod(3, 5, 'adder_mod', True)
n = 3
bigN = 5
#qc = QuantumCircuit(4*n+2)
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bigN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, bN, t, creg)
qc.x(a[2]) # a = 4
qc.x(b[2]) # b = 4
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_adder_mod(n, bigN), list(a) + list(b) + list(c) + list(bN) + list(t))
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_ctrl_mult_mod(n, bigN, m, name=None, draw=False):
"""
Calculate zm mod N and output to b
:param n: number of bits for a, c and bigN; b has n+1 bits
:param bigN: mod number
:param m: multiplier
:return: Gate of 4n+2 qubits
0 (1 qubit) for x
1 to n (n qubits) for z
n+1 to 2n (n qubits) for a
2n+1 to 3n+1 (n+1 qubits) for b
3n+2 to 4n+1 (n qubits) for c (init to 0)
4n+2 to 5n+1 (n qubits) for bigN (init to bigN when use)
5n+2 (1 qubit) for temp (init to 0)
"""
x = QuantumRegister(1, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(x, z, a, b, c, bN, t)
next_mod = m # m 2^0 mod N
for j in range(n):
temp_mod = next_mod
i = 0
while temp_mod != 0:
if temp_mod % 2 != 0:
qc.ccx(x[0], z[j], a[i])
i = i + 1
temp_mod = temp_mod // 2
qc.append(create_adder_mod(n, bigN), list(a) + list(b) + list(c) + list(bN) + list(t))
temp_mod = next_mod
i = 0
while temp_mod != 0:
if temp_mod % 2 != 0:
qc.ccx(x[0], z[j], a[i])
i = i + 1
temp_mod = temp_mod // 2
next_mod = (next_mod * 2) % bigN # update for m 2^i+1 mod N
# seems no need to copy z to b if x=0. may try to remove this block and test
# qc.x(x[0])
# for j in range(n):
# qc.ccx(x[0], z[j], b[j])
# qc.x(x[0])
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'ctrl_mult_mod')
def create_ctrl_mult_mod_inv(n, bigN, m):
qc = QuantumCircuit(5*n+3)
qc.append(create_ctrl_mult_mod(n, bigN, m).inverse(), range(5*n+3))
return qc.to_gate(label='ctrl_mult_mod_inv')
create_ctrl_mult_mod(3, 5, 3, 'ctrl_mult_mod', True)
n = 3
bigN = 5
m = 3
x = QuantumRegister(1, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(n, 'creg')
qc = QuantumCircuit(x, z, a, b, c, bN, t, creg)
qc.x(x[0]) # x = 1
qc.x(z[0]) # z = 3
qc.x(z[1])
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_ctrl_mult_mod(n, bigN, m), list(x) + z[:] + list(a) + list(b) + list(c) + list(bN) + list(t))
# for i in range(n):
# qc.measure(b[i], creg[i])
qc.measure(b[0:n], creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from sympy import mod_inverse
def create_mod_exp(n, bigN, y, nx, name=None, draw=False):
"""
Calculate y^x mod N and output to z
:param n: number of bits for z, a, c and bigN; b has n+1 bits
:param bigN: mod number
:param y: multiplier
:param nx: number of bits for x
:return: Gate of 4n+2 qubits
0 to nx-1 (n qubit) for x
nx to nx+n-1 (n qubits) for z (init to 1 when use)
nx+n to nx+2n-1 (n qubits) for a (init to 0)
nx+2n to nx+3n (n+1 qubits) for b (init to 0)
nx+3n+1 to nx+4n (n qubits) for c (init to 0)
nx+4n+1 to nx+5n (n qubits) for bigN (init to bigN when use)
nx+5n+1 (1 qubit) for temp (init to 0)
"""
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(x, z, a, b, c, bN, t)
m = y
for i in range(nx):
qc.append(create_ctrl_mult_mod(n, bigN, m),
[x[i]] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
for j in range(n):
qc.cswap(x[i], z[j], b[j])
m_inv = mod_inverse(m, bigN)
qc.append(create_ctrl_mult_mod_inv(n, bigN, m_inv),
[x[i]] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
m = (m * m) % bigN # update for next cycle
if draw:
display(qc.draw())
return qc.to_gate(label=name or 'mod_exp')
create_mod_exp(3, 5, 3, 3, 'mod_exp', True)
n = 3
bigN = 5
y = 3
nx = 3
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(n, 'creg')
qc = QuantumCircuit(x, z, a, b, c, bN, t, creg)
qc.x(x[0]) # x = 3
qc.x(x[1])
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.measure(z, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts) # 3^3 mod 5 = 2 or 010(2)
n = 5
bigN = 15
y = 7
nx = 8
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 15 = 1111(2)
qc.x(bN[1])
qc.x(bN[2])
qc.x(bN[3])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(192/2**8).limit_denominator(221)
import math
print(math.gcd(7**2+1, 15))
print(math.gcd(7**2-1, 15))
n = 6
bigN = 55
y = 7
nx = 12
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 55 = 110111(2)
qc.x(bN[1])
qc.x(bN[2])
qc.x(bN[4])
qc.x(bN[5])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
import matplotlib.pyplot as plt
import math
from fractions import Fraction
def is_solution(k, nx, a, N, p, q):
r = Fraction(k/2**nx).limit_denominator(N).denominator
if r % 2 == 1:
return False
if math.gcd(a**(r//2)+1, N) == p and math.gcd(a**(r//2)-1, N) == q:
return True
if math.gcd(a**(r//2)+1, N) == q and math.gcd(a**(r//2)-1, N) == p:
return True
return False
def analyze_result(counts, nx, a, N, p, q):
xycorrect = {}
xywrong = {}
for k,v in counts.items():
if is_solution(int(k, 2), nx, a, N, p, q):
xycorrect[int(k, 2)] = v
else:
xywrong[int(k, 2)] = v
plt.title('Factor {}'.format(N))
plt.xlabel('measured values on {} qubits'.format(nx))
plt.ylabel('counts')
plt.scatter(xycorrect.keys(), xycorrect.values(), s=1, c='g')
plt.scatter(xywrong.keys(), xywrong.values(), s=1, c='r')
plt.legend(['correct', 'wrong'])
print('correct count {}, wrong count {}, total {}, correct rate {}'.format(
sum(xycorrect.values()),
sum(xywrong.values()),
sum(xycorrect.values()) + sum(xywrong.values()),
float(sum(xycorrect.values())) / float(sum(xycorrect.values()) + sum(xywrong.values()),)))
analyze_result(counts, 12, 7, 55, 5, 11)
from fractions import Fraction
Fraction(3891/2**12).limit_denominator(55)
import math
print(math.gcd(7**10+1, 55))
print(math.gcd(7**10-1, 55))
n = 8
bigN = 221
y = 7
nx = 16
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 221 = 11011101(2)
qc.x(bN[2])
qc.x(bN[3])
qc.x(bN[4])
qc.x(bN[6])
qc.x(bN[7])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
analyze_result(counts, 16, 7, 221, 13, 17)
from fractions import Fraction
Fraction(1365/2**16).limit_denominator(221)
import math
print(math.gcd(3**24+1, 221))
print(math.gcd(3**24-1, 221))
17*13
n = 9
bigN = 437
y = 7
nx = 18
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 437 = 110110101(2)
qc.x(bN[2])
qc.x(bN[4])
qc.x(bN[5])
qc.x(bN[7])
qc.x(bN[8])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
analyze_result(counts, 18, 7, 437, 19, 23)
from fractions import Fraction
Fraction(123128/2**18).limit_denominator(437)
import math
print(math.gcd(7**33+1, 437))
print(math.gcd(7**33-1, 437))
23*19
qc_t = transpile(qc, backend)
print('circuit depth {}, operator count {}'.format(qc_t.depth(), qc_t.count_ops()))
n = 10
bigN = 851
y = 7
nx = 20
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 851 = 1101010011(2)
qc.x(bN[1])
qc.x(bN[4])
qc.x(bN[6])
qc.x(bN[8])
qc.x(bN[9])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
analyze_result(counts, 20, 7, 851, 23, 37)
from fractions import Fraction
Fraction(0/2**20).limit_denominator(851)
def gen_qc(n, bigN, y, nx):
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
cregx = ClassicalRegister(nx, 'cregx')
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
tmp_bigN = bigN
i = 0
while tmp_bigN != 0:
if tmp_bigN % 2 == 1:
qc.x(bN[i])
tmp_bigN = tmp_bigN // 2
i = i + 1
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(create_qft(nx), x)
qc.measure(x, cregx)
backend = Aer.get_backend('qasm_simulator')
qc_t = transpile(qc, backend)
return qc_t
qc_15 = gen_qc(4, 15, 7, 8)
qc_55 = gen_qc(6, 55, 7, 12)
qc_221 = gen_qc(8, 221, 7, 16)
qc_437 = gen_qc(9, 437, 7, 18)
qc_851 = gen_qc(10, 851, 7, 20)
print(qc_15.depth(), qc_15.count_ops())
print(qc_851.depth(), qc_851.count_ops())
n_array = [4, 6, 8, 9, 10]
qc_array = [qc_15, qc_55, qc_221, qc_437, qc_851]
depth_array = []
ops_array = []
for qc_i in qc_array:
depth_array.append(qc_i.depth())
ops_array.append(sum(qc_i.count_ops().values()))
print(depth_array)
print(ops_array)
import matplotlib.pyplot as plt
import numpy
opsfit = numpy.polyfit(n_array, ops_array, 3)
print(opsfit)
opsmodel = numpy.poly1d(opsfit)
opsline = numpy.linspace(1, 10, 10)
plt.xlabel('n qubits for N')
plt.ylabel('depth and count_ops')
plt.scatter(n_array, depth_array, marker='o', c='blue')
plt.scatter(n_array, ops_array, marker='x', c='orange')
plt.plot(opsline, opsmodel(opsline), c='orange')
plt.legend(['depth', 'count_ops', 'cout_ops poly deg 3 fit'])
plt.show()
opsline2 = numpy.linspace(1, 100, 100)
plt.xlabel('n qubits for N')
plt.ylabel('count_ops')
plt.scatter(n_array, ops_array, marker='x', c='orange')
plt.plot(opsline2, opsmodel(opsline2), c='orange')
plt.legend(['count_ops', 'cout_ops poly deg 3 fit'])
plt.show()
qc_7663 = gen_qc(13, 7663, 7, 26)
qc_35263 = gen_qc(16, 35263, 7, 32)
opsline3 = numpy.linspace(1, 20, 20)
plt.xlabel('n qubits for N')
plt.ylabel('count_ops')
plt.scatter(n_array, ops_array, marker='x', c='orange')
plt.scatter([13, 16], [sum(qc_7663.count_ops().values()), sum(qc_35263.count_ops().values())])
plt.plot(opsline3, opsmodel(opsline3), c='orange')
plt.legend(['count_ops', 'count_ops for 7663 and 35263', 'cout_ops poly deg 3 fit'])
plt.xticks(range(0, 22, 2))
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/ionq-samples/qiskit-getting-started
|
ionq-samples
|
#import Aer here, before calling qiskit_ionq_provider
from qiskit import Aer
from qiskit_ionq import IonQProvider
#Call provider and set token value
ionq_provider = IonQProvider(token='my token')
ionq_provider.backends()
import numpy as np
from qiskit import execute
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.utils import QuantumInstance
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA, ADAM, L_BFGS_B, SLSQP, SPSA
from qiskit import Aer
from qiskit.circuit import Parameter
from qiskit.circuit.parametervector import ParameterVectorElement
from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule
from qiskit_nature.circuit.library import HartreeFock
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
from qiskit_nature.runtime import VQEProgram
from matplotlib import pyplot as plt
%matplotlib inline
class UCCAnsatz():
def __init__(self, params, num_particles, num_spin_orbitals):
# number of qubits
self.num_of_qubits = num_spin_orbitals
# number of parameters
self.num_params = len(params)
# parameters
self.params = []
for index in range(self.num_params):
p = Parameter("t"+str(index))
self.params.append(ParameterVectorElement(p, index))
def UCC1(self):
qc = QuantumCircuit(4)
# basis rotation
qc.rx(np.pi / 2, 0)
qc.h(1)
qc.h(2)
qc.h(3)
# parameter theta_0
qc.cx(0, 1)
qc.cx(1, 2)
qc.cx(2, 3)
qc.rz(self.params[0], 3)
qc.cx(2, 3)
qc.cx(1, 2)
qc.cx(0, 1)
# basis rotation
qc.rx(-np.pi / 2, 0)
qc.h(1)
qc.h(2)
qc.h(3)
return qc
################## Hamiltonian Definition #######################################
def GetHamiltonians(mol):
# construct the driver
driver = PySCFDriver(molecule=mol, unit=UnitsType.ANGSTROM, basis='sto6g')
# the electronic structure problem
problem = ElectronicStructureProblem(driver)
# get quantum molecule
q_molecule = driver.run()
# classical eigenstate
np_solver = NumPyMinimumEigensolver()
np_groundstate_solver = GroundStateEigensolver(QubitConverter(JordanWignerMapper()), np_solver)
np_result = np_groundstate_solver.solve(problem)
print(f"Classical results is {np_result.eigenenergies}")
# generate the second-quantized operators
second_q_ops = problem.second_q_ops()
# construct a qubit converter
qubit_converter = QubitConverter(JordanWignerMapper())
# qubit Operations
qubit_op = qubit_converter.convert(second_q_ops[0])
# return the qubit operations
return qubit_op
def constructAnsatz(params):
# initialize the HF state
hf_state = HartreeFock(4, [1, 1], QubitConverter(JordanWignerMapper()))
# VQE circuit
ansatz = UCCAnsatz(params, 2, 4).UCC1()
# add initial state
ansatz.compose(hf_state, front=True, inplace=True)
# return the circuit
return ansatz
def runVQE(params, backend_id="qasm_simulator", optimizer_id="COBYLA", noise=None):
molecule = Molecule(geometry=[['H', [0., 0., 0.]],
['H', [0., 0., 0.75]]],
charge=0, multiplicity=1)
# Get Hamiltonian
qubit_op = GetHamiltonians(molecule)
# Get classical optimizer
if (optimizer_id == "COBYLA"):
optimizer = COBYLA()
elif (optimizer_id == "SPSA"):
optimizer = SPSA()
elif (optimizer_id == "ADAM"):
optimizer = ADAM()
# Construct and display ansatz
ansatz = constructAnsatz(params)
print('Ansatz :', '\n', ansatz)
# initial parameters
init_params = {}
for index in range(len(params)):
p = Parameter("t"+str(index))
init_params[ParameterVectorElement(p, index)] = 0.0
# backend
if (backend_id == "qasm_simulator"):
backend = Aer.get_backend("qasm_simulator")
elif (backend_id == "ionq_qpu"):
backend = ionq_provider.get_backend("ionq_qpu")
def job_callback(job_id, job_status, queue_position, job) -> None:
'''
Printing logs for debugging.
The function is the parameter job_callback of QuantumInstance
:param job_id:
:param job_status:
:param queue_position:
:param job:
:return:
'''
print(f"[API JOB-CALLBACK] Job Id: {job_id}")
print(f"[API JOB-CALLBACK] Job status: {job_status}")
print(f"[API JOB-CALLBACK] Queue position: {queue_position}")
print(f"[API JOB-CALLBACK] Job: {job}")
ionq_quantum_instance = QuantumInstance(backend=backend, job_callback=job_callback, noise_model=noise)
counts = []
values = []
stds = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
stds.append(std)
# VQE algorithm
algorithm = VQE(ansatz,
optimizer=optimizer,
initial_point = np.array([0.0]),
callback=store_intermediate_result,
quantum_instance=ionq_quantum_instance)
result = algorithm.compute_minimum_eigenvalue(qubit_op)
print("Optimized VQE Energy ", result.eigenvalue.real)
return values, stds
# Execute program with default parameters
eng_hist, error_hist = runVQE([0.0])
plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o")
#plt.plot([*range(len(eng_hist))], eng_hist)
plt.show()
eng_hist_SPSA, error_hist_SPSA = runVQE([0.0],optimizer_id="SPSA")
plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o", label="COBYLA")
plt.plot([*range(len(eng_hist_SPSA))], eng_hist_SPSA, linestyle="", marker="*", label="SPSA")
plt.legend()
plt.show()
eng_hist_ADAM, error_hist_ADAM = runVQE([0.0],optimizer_id="ADAM")
plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o", label="COBYLA")
plt.plot([*range(len(eng_hist_SPSA))], eng_hist_SPSA, linestyle="", marker="*", label="SPSA")
plt.plot([*range(len(eng_hist_ADAM))], eng_hist_ADAM, linestyle="", marker="x", label="ADAM")
plt.legend()
plt.show()
# Noise
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise import depolarizing_error
# default noise model, can be overridden using set_noise_model
noise = NoiseModel()
# Add depolarizing error to all single qubit gates with error rate 0.5%
one_qb_error = 0.005
noise.add_all_qubit_quantum_error(depolarizing_error(one_qb_error, 1), ['u1', 'u2', 'u3'])
# Add depolarizing error to all two qubit gates with error rate 5.0%
two_qb_error = 0.05
noise.add_all_qubit_quantum_error(depolarizing_error(two_qb_error, 2), ['cx'])
eng_hist, error_hist = runVQE([0.0],optimizer_id="COBYLA", noise=noise)
eng_hist_SPSA, error_hist_SPSA = runVQE([0.0],optimizer_id="SPSA", noise=noise)
eng_hist_ADAM, error_hist_ADAM = runVQE([0.0],optimizer_id="ADAM", noise=noise)
plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o", label="COBYLA")
plt.plot([*range(len(eng_hist_SPSA))], eng_hist_SPSA, linestyle="", marker="*", label="SPSA")
plt.plot([*range(len(eng_hist_ADAM))], eng_hist_ADAM, linestyle="", marker="x", label="ADAM")
plt.legend()
plt.show()
# run("ionq_qpu")
# opt_process_exp = [-1.8112359199652812, -1.4416498480789817, -1.2335035452225904, -1.4989706208229303, -1.6937521890989031, -1.6557546667316045, -1.6898027909394815, -1.740016937435431, -1.7592133266130963, -1.755505060521276, -1.7199835843097526, -1.7476529655074913, -1.7142357090197362, -1.7366022956905651, -1.7307574124517149, -1.7437590702130892, -1.721561556686939]
# plt.plot(opt_process, linestyle="", marker="o", color="b", label="simulator")
# plt.plot(opt_process_exp, linestyle="", marker="o", color="r", label="ionq_qpu")
# plt.legend()
# plt.show()
eng_hist, error_hist = runVQE([0.0],optimizer_id="COBYLA", backend_id = "ionq_qpu")
eng_hist_SPSA, error_hist_SPSA = runVQE([0.0],optimizer_id="SPSA", backend_id = "ionq_qpu")
eng_hist_ADAM, error_hist_ADAM = runVQE([0.0],optimizer_id="ADAM", backend_id = "ionq_qpu")
plt.plot([*range(len(eng_hist))], eng_hist, linestyle="", marker="o", label="COBYLA")
plt.plot([*range(len(eng_hist_SPSA))], eng_hist_SPSA, linestyle="", marker="*", label="SPSA")
plt.plot([*range(len(eng_hist_ADAM))], eng_hist_ADAM, linestyle="", marker="x", label="ADAM")
plt.legend()
plt.show()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for graph MPL drawer"""
import unittest
import os
from test.visual import VisualTestUtilities
from contextlib import contextmanager
from pathlib import Path
from qiskit import BasicAer, execute
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit
from qiskit.utils import optionals
from qiskit.visualization.state_visualization import state_drawer
from qiskit.visualization.counts_visualization import plot_histogram
from qiskit.visualization.gate_map import plot_gate_map, plot_coupling_map
from qiskit.providers.fake_provider import (
FakeArmonk,
FakeBelem,
FakeCasablanca,
FakeRueschlikon,
FakeMumbai,
FakeManhattan,
)
if optionals.HAS_MATPLOTLIB:
from matplotlib.pyplot import close as mpl_close
else:
raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".')
BASE_DIR = Path(__file__).parent
RESULT_DIR = Path(BASE_DIR) / "graph_results"
TEST_REFERENCE_DIR = Path(BASE_DIR) / "references"
FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures"
FAILURE_PREFIX = "graph_failure_"
@contextmanager
def cwd(path):
"""A context manager to run in a particular path"""
oldpwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(oldpwd)
class TestGraphMatplotlibDrawer(QiskitTestCase):
"""Graph MPL visualization"""
def setUp(self):
super().setUp()
self.graph_state_drawer = VisualTestUtilities.save_data_wrap(
state_drawer, str(self), RESULT_DIR
)
self.graph_count_drawer = VisualTestUtilities.save_data_wrap(
plot_histogram, str(self), RESULT_DIR
)
self.graph_plot_gate_map = VisualTestUtilities.save_data_wrap(
plot_gate_map, str(self), RESULT_DIR
)
self.graph_plot_coupling_map = VisualTestUtilities.save_data_wrap(
plot_coupling_map, str(self), RESULT_DIR
)
if not os.path.exists(FAILURE_DIFF_DIR):
os.makedirs(FAILURE_DIFF_DIR)
if not os.path.exists(RESULT_DIR):
os.makedirs(RESULT_DIR)
def tearDown(self):
super().tearDown()
mpl_close("all")
@staticmethod
def _image_path(image_name):
return os.path.join(RESULT_DIR, image_name)
@staticmethod
def _reference_path(image_name):
return os.path.join(TEST_REFERENCE_DIR, image_name)
def test_plot_bloch_multivector(self):
"""test bloch sphere
See https://github.com/Qiskit/qiskit-terra/issues/6397.
"""
circuit = QuantumCircuit(1)
circuit.h(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "bloch_multivector.png"
self.graph_state_drawer(state=state, output="bloch", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_hinton(self):
"""test plot_state_hinton"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "hinton.png"
self.graph_state_drawer(state=state, output="hinton", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_qsphere(self):
"""test for plot_state_qsphere"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "qsphere.png"
self.graph_state_drawer(state=state, output="qsphere", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_city(self):
"""test for plot_state_city"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "state_city.png"
self.graph_state_drawer(state=state, output="city", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_state_paulivec(self):
"""test for plot_state_paulivec"""
circuit = QuantumCircuit(1)
circuit.x(0)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "paulivec.png"
self.graph_state_drawer(state=state, output="paulivec", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram(self):
"""for testing the plot_histogram"""
# specifing counts because we do not want oscillation of
# result until a changes is made to plot_histogram
counts = {"11": 500, "00": 500}
fname = "histogram.png"
self.graph_count_drawer(counts, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_with_rest(self):
"""test plot_histogram with 2 datasets and number_to_keep"""
data = [{"00": 3, "01": 5, "10": 6, "11": 12}]
fname = "histogram_with_rest.png"
self.graph_count_drawer(data, number_to_keep=2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_2_sets_with_rest(self):
"""test plot_histogram with 2 datasets and number_to_keep"""
data = [
{"00": 3, "01": 5, "10": 6, "11": 12},
{"00": 5, "01": 7, "10": 6, "11": 12},
]
fname = "histogram_2_sets_with_rest.png"
self.graph_count_drawer(data, number_to_keep=2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_color(self):
"""Test histogram with single color"""
counts = {"00": 500, "11": 500}
fname = "histogram_color.png"
self.graph_count_drawer(data=counts, color="#204940", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_multiple_colors(self):
"""Test histogram with multiple custom colors"""
counts = [
{"00": 10, "01": 15, "10": 20, "11": 25},
{"00": 25, "01": 20, "10": 15, "11": 10},
]
fname = "histogram_multiple_colors.png"
self.graph_count_drawer(
data=counts,
color=["#204940", "#c26219"],
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_hamming(self):
"""Test histogram with hamming distance"""
counts = {"101": 500, "010": 500, "001": 500, "100": 500}
fname = "histogram_hamming.png"
self.graph_count_drawer(data=counts, sort="hamming", target_string="101", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_value_sort(self):
"""Test histogram with sorting by value"""
counts = {"101": 300, "010": 240, "001": 80, "100": 150, "110": 160, "000": 280, "111": 60}
fname = "histogram_value_sort.png"
self.graph_count_drawer(data=counts, sort="value", target_string="000", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_desc_value_sort(self):
"""Test histogram with sorting by descending value"""
counts = {"101": 150, "010": 50, "001": 180, "100": 10, "110": 190, "000": 80, "111": 260}
fname = "histogram_desc_value_sort.png"
self.graph_count_drawer(
data=counts,
sort="value_desc",
target_string="000",
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_legend(self):
"""Test histogram with legend"""
counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}]
fname = "histogram_legend.png"
self.graph_count_drawer(
data=counts,
legend=["first", "second"],
filename=fname,
figsize=(15, 5),
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_histogram_title(self):
"""Test histogram with title"""
counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}]
fname = "histogram_title.png"
self.graph_count_drawer(data=counts, title="My Histogram", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_1_qubit_gate_map(self):
"""Test plot_gate_map using 1 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeArmonk()
fname = "1_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_5_qubit_gate_map(self):
"""Test plot_gate_map using 5 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeBelem()
fname = "5_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_7_qubit_gate_map(self):
"""Test plot_gate_map using 7 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeCasablanca()
fname = "7_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_16_qubit_gate_map(self):
"""Test plot_gate_map using 16 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeRueschlikon()
fname = "16_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_27_qubit_gate_map(self):
"""Test plot_gate_map using 27 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeMumbai()
fname = "27_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_65_qubit_gate_map(self):
"""test for plot_gate_map using 65 qubit backend"""
# getting the mock backend from FakeProvider
backend = FakeManhattan()
fname = "65_qubit_gate_map.png"
self.graph_plot_gate_map(backend=backend, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_figsize(self):
"""Test figsize parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeBelem()
fname = "figsize.png"
self.graph_plot_gate_map(backend=backend, figsize=(10, 10), filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_qubit_size(self):
"""Test qubit_size parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeBelem()
fname = "qubit_size.png"
self.graph_plot_gate_map(backend=backend, qubit_size=38, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_qubit_color(self):
"""Test qubit_color parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeCasablanca()
fname = "qubit_color.png"
self.graph_plot_gate_map(backend=backend, qubit_color=["#ff0000"] * 7, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_qubit_labels(self):
"""Test qubit_labels parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeCasablanca()
fname = "qubit_labels.png"
self.graph_plot_gate_map(
backend=backend, qubit_labels=list(range(10, 17, 1)), filename=fname
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_line_color(self):
"""Test line_color parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeManhattan()
fname = "line_color.png"
self.graph_plot_gate_map(backend=backend, line_color=["#00ff00"] * 144, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_font_color(self):
"""Test font_color parameter of plot_gate_map"""
# getting the mock backend from FakeProvider
backend = FakeManhattan()
fname = "font_color.png"
self.graph_plot_gate_map(backend=backend, font_color="#ff00ff", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_coupling_map(self):
"""Test plot_coupling_map"""
num_qubits = 5
qubit_coordinates = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]
coupling_map = [[1, 0], [1, 2], [1, 3], [3, 4]]
fname = "coupling_map.png"
self.graph_plot_coupling_map(
num_qubits=num_qubits,
qubit_coordinates=qubit_coordinates,
coupling_map=coupling_map,
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
def test_plot_bloch_multivector_figsize_improvements(self):
"""test bloch sphere figsize, font_size, title_font_size and title_pad
See https://github.com/Qiskit/qiskit-terra/issues/7263
and https://github.com/Qiskit/qiskit-terra/pull/7264.
"""
circuit = QuantumCircuit(3)
circuit.h(1)
circuit.sxdg(2)
# getting the state using backend
backend = BasicAer.get_backend("statevector_simulator")
result = execute(circuit, backend).result()
state = result.get_statevector(circuit)
fname = "bloch_multivector_figsize_improvements.png"
self.graph_state_drawer(
state=state,
output="bloch",
figsize=(3, 2),
font_size=10,
title="|0+R> state",
title_font_size=14,
title_pad=8,
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.99)
if __name__ == "__main__":
unittest.main(verbosity=1)
|
https://github.com/Chibikuri/qwopt
|
Chibikuri
|
import numpy as np
import copy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, Aer, execute
from .op_creater import OperationCreator
from qiskit import transpile
np.set_printoptions(linewidth=1000, precision=3)
class CircuitComposer:
'''
If you use google matrix as a probability distribution matrix,
please use E as a graph
'''
def __init__(self, graph, prob_tran, step, optimize=True):
self.operator = OperationCreator(graph, prob_tran, optimize=optimize)
self.n_qubit = self.operator.q_size
self.graph = self.operator.graph
self.ptran = self.operator.ptran
self.step = step
if self.step < 0:
raise ValueError('The number of steps must be 0 and over')
def qw_circuit(self, anc=True, name='quantumwalk', measurement=True,
initialize=True, validation=True, optimization=True):
cont = QuantumRegister(self.n_qubit//2, 'control')
targ = QuantumRegister(self.n_qubit//2, 'target')
anc = QuantumRegister(self.n_qubit//2, 'ancilla')
qw = QuantumCircuit(cont, targ, anc, name=name)
lp = len(self.ptran)**2
# HACK
if isinstance(initialize, bool) and initialize:
self._initialize(qw, [*cont, *targ])
# FIXME
init_state = [1/np.sqrt(lp) for i in range(lp)]
elif isinstance(initialize, (list, np.ndarray)):
self._initialize(qw, [*cont, *targ], state=initialize)
init_state = initialize
else:
# FIXME should be able to put arbitraly input initial
init_state = [1] + [0 for i in range(lp-1)]
qw = self._circuit_composer(qw, cont, targ, anc,
optimization=optimization)
# FIXME more efficient order
if validation:
qw, correct = self._circuit_validator(qw, [*cont, *targ],
init_state)
if measurement:
c = ClassicalRegister(self.n_qubit//2, 'classical')
qw.add_register(c)
# TODO is this correct order?
qw.measure(targ, c)
if correct:
print('Circuit is validated!')
return qw
else:
raise Exception('Circuit validation failed')
else:
if measurement:
c = ClassicalRegister(self.n_qubit//2, 'classical')
qw.add_register(c)
# TODO is this correct order?
qw.measure(targ, c)
return qw
def _circuit_composer(self, circuit, cont, targ, anc,
measurement=True, optimization=False):
qubits = [*cont, *targ, *anc]
if optimization:
# HACK
# ancillary qubits for optimizations
opt_anc = QuantumRegister(self.n_qubit//2)
circuit.add_register(opt_anc)
opt_qubits = [*cont, *targ, *anc, *opt_anc]
else:
opt_qubits = [*cont, *targ, *anc]
Ts = self.operator.T_operation()
Kdg = self.operator.K_operation(dagger=True, optimization=optimization)
K = self.operator.K_operation(dagger=False, optimization=optimization)
D = self.operator.D_operation()
# TODO remove commented out
for step in range(self.step):
for t in Ts:
circuit.append(t, qargs=qubits)
circuit.append(Kdg, qargs=opt_qubits)
circuit.append(D, qargs=targ)
circuit.append(K, qargs=opt_qubits)
for tdg in Ts:
circuit.append(tdg, qargs=qubits)
for i, j in zip(cont, targ):
circuit.swap(i, j)
circuit.barrier()
return circuit
def _circuit_validator(self, circuit, qregs, init_state,
remote=False, test_shots=100000, threshold=1e-4):
# TODO check with unitary simulator(currently, ansilla is bothering...)
nc = ClassicalRegister(self.n_qubit)
circuit.add_register(nc)
for q, c in zip(qregs, nc):
circuit.measure(q, c)
if remote:
backend = IBMQ.get_backend('ibmq_qasm_simulator')
else:
backend = Aer.get_backend('qasm_simulator')
theoretical_prob = self._theoretical_prob(init_state)
print(theoretical_prob)
vjob = execute(circuit, backend=backend, shots=test_shots)
result = vjob.result().get_counts(circuit)
rb = self.n_qubit
bins = [format(i, '0%sb' % rb) for i in range(2**rb)]
probs = np.array([result.get(bi, 0)/test_shots for bi in bins])
print(probs)
# TODO check L2 norm is good enough to validate in larger case
# and check threshold
l2dist = self._L2_dist(theoretical_prob, probs)
if l2dist < threshold:
flag = True
else:
flag = False
circuit.remove_final_measurements()
return circuit, flag
def _initialize(self, circuit, qregs, state='super'):
if isinstance(state, (list, np.ndarray)):
circuit.initialize(state, qregs)
elif state == 'super':
for qr in qregs:
circuit.h(qr)
else:
pass
return circuit
@staticmethod
def _L2_dist(pa, pb):
# FIXME using array
ps = [(p1 - p2)**2 for p1, p2 in zip(pa, pb)]
return sum(ps)
def _theoretical_prob(self, initial):
Pi_op = self._Pi_operator()
swap = self._swap_operator()
operator = (2*Pi_op) - np.identity(len(Pi_op))
Szegedy = np.dot(operator, swap)
Szegedy_n = copy.deepcopy(Szegedy)
if self.step == 0:
init_prob = np.array([abs(i)**2 for i in initial], dtype=np.float)
return init_prob
elif self.step == 1:
prob = np.array([abs(i)**2 for i in np.dot(Szegedy, initial)],
dtype=np.float)
return prob
else:
for n in range(self.step-1):
Szegedy_n = np.dot(Szegedy_n, Szegedy)
probs = np.array([abs(i)**2 for i in np.dot(Szegedy_n, initial)],
dtype=np.float)
return probs
def _swap_operator(self):
q1 = QuantumRegister(self.n_qubit//2)
q2 = QuantumRegister(self.n_qubit//2)
qc = QuantumCircuit(q1, q2)
for c, t in zip(q1, q2):
qc.swap(c, t)
# FIXME
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend=backend)
swap = job.result().get_unitary(qc)
return swap
def _Pi_operator(self):
'''
This is not a quantum operation,
just returning matrix
'''
lg = len(self.ptran)
psi_op = []
count = 0
for i in range(lg):
psi_vec = [0 for _ in range(lg**2)]
for j in range(lg):
psi_vec[count] = np.sqrt(self.ptran[j][i])
count += 1
psi_op.append(np.kron(np.array(psi_vec).T,
np.conjugate(psi_vec)).reshape((lg**2, lg**2)))
Pi = psi_op[0]
for i in psi_op[1:]:
Pi = np.add(Pi, i)
return Pi
def prob_transition(graph, gtype='normal', alpha=0.85):
if gtype == 'google':
return google_matrix(alpha, graph)
else:
pmatrix = np.zeros(graph.shape)
indegrees = np.sum(graph, axis=0)
for ix, indeg in enumerate(indegrees):
if indeg == 0:
pmatrix[:, ix] = graph[:, ix]
else:
pmatrix[:, ix] = graph[:, ix]/indeg
return pmatrix
# def is_unitary(operator, tolerance=0.0001):
# h, w = operator.shape
# if not h == w:
# return False
# adjoint = np.conjugate(operator.transpose())
# product1 = np.dot(operator, adjoint)
# product2 = np.dot(adjoint, operator)
# ida = np.eye(h)
# return np.allclose(product1, ida) & np.allclose(product2, ida)
# def google_matrix(alpha, C):
# E = connect_to_E(C)
# N = len(C)
# G = alpha*E + (1-alpha)/N * np.ones((N, N), dtype=float)
# return G
# def connect_to_E(C):
# '''
# C is conectivity matrix
# C: np.array
# output
# E: np.array
# '''
# N = len(C)
# C = np.array(C)
# E = np.zeros(C.shape)
# rowsum = np.sum(C, axis=0)
# for ind, val in enumerate(rowsum):
# if val == 0:
# for j in range(N):
# E[j][ind] = 1/N
# else:
# for j in range(N):
# E[j][ind] = C[j][ind]/val
# assert(np.sum(np.sum(E, axis=0)) == N)
# return E
# if __name__ == '__main__':
# # graph = np.array([[0, 1, 0, 0, 1, 0, 0, 1],
# # [0, 0, 0, 1, 1, 0, 1, 0],
# # [0, 0, 0, 1, 0, 1, 0, 1],
# # [0, 1, 0, 0, 0, 0, 1, 0],
# # [0, 1, 0, 0, 0, 1, 0, 1],
# # [0, 1, 0, 0, 1, 0, 1, 1],
# # [0, 1, 0, 0, 1, 0, 0, 1],
# # [0, 1, 0, 0, 1, 0, 1, 0]])
# graph = np.array([[0, 1, 1, 0],
# [0, 0, 0, 1],
# [0, 0, 0, 1],
# [0, 1, 1, 0]])
# # e = np.array([[1, 1, 1, 0],
# # [1, 0, 0, 1],
# # [1, 0, 0, 1],
# # [1, 1, 1, 0]])
# pb = prob_transition(graph)
# comp = CircuitComposer(graph, pb, 1)
# comp.qw_circuit()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 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.
"""Phase estimation for the spectrum of a Hamiltonian"""
from __future__ import annotations
import warnings
from qiskit import QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.utils.deprecation import deprecate_arg
from qiskit.opflow import (
SummedOp,
PauliOp,
MatrixOp,
PauliSumOp,
StateFn,
EvolutionBase,
PauliTrotterEvolution,
I,
)
from qiskit.providers import Backend
from .phase_estimation import PhaseEstimation
from .hamiltonian_phase_estimation_result import HamiltonianPhaseEstimationResult
from .phase_estimation_scale import PhaseEstimationScale
from ...circuit.library import PauliEvolutionGate
from ...primitives import BaseSampler
from ...quantum_info import SparsePauliOp, Statevector, Pauli
from ...synthesis import EvolutionSynthesis
class HamiltonianPhaseEstimation:
r"""Run the Quantum Phase Estimation algorithm to find the eigenvalues of a Hermitian operator.
This class is nearly the same as :class:`~qiskit_algorithms.PhaseEstimation`, differing only
in that the input in that class is a unitary operator, whereas here the input is a Hermitian
operator from which a unitary will be obtained by scaling and exponentiating. The scaling is
performed in order to prevent the phases from wrapping around :math:`2\pi`.
The problem of estimating eigenvalues :math:`\lambda_j` of the Hermitian operator
:math:`H` is solved by running a circuit representing
.. math::
\exp(i b H) |\psi\rangle = \sum_j \exp(i b \lambda_j) c_j |\lambda_j\rangle,
where the input state is
.. math::
|\psi\rangle = \sum_j c_j |\lambda_j\rangle,
and :math:`\lambda_j` are the eigenvalues of :math:`H`.
Here, :math:`b` is a scaling factor sufficiently large to map positive :math:`\lambda` to
:math:`[0,\pi)` and negative :math:`\lambda` to :math:`[\pi,2\pi)`. Each time the circuit is
run, one measures a phase corresponding to :math:`lambda_j` with probability :math:`|c_j|^2`.
If :math:`H` is a Pauli sum, the bound :math:`b` is computed from the sum of the absolute
values of the coefficients of the terms. There is no way to reliably recover eigenvalues
from phases very near the endpoints of these intervals. Because of this you should be aware
that for degenerate cases, such as :math:`H=Z`, the eigenvalues :math:`\pm 1` will be
mapped to the same phase, :math:`\pi`, and so cannot be distinguished. In this case, you need
to specify a larger bound as an argument to the method ``estimate``.
This class uses and works together with :class:`~qiskit_algorithms.PhaseEstimationScale` to
manage scaling the Hamiltonian and the phases that are obtained by the QPE algorithm. This
includes setting, or computing, a bound on the eigenvalues of the operator, using this
bound to obtain a scale factor, scaling the operator, and shifting and scaling the measured
phases to recover the eigenvalues.
Note that, although we speak of "evolving" the state according the Hamiltonian, in the
present algorithm, we are not actually considering time evolution. Rather, the role of time is
played by the scaling factor, which is chosen to best extract the eigenvalues of the
Hamiltonian.
A few of the ideas in the algorithm may be found in Ref. [1].
**Reference:**
[1]: Quantum phase estimation of multiple eigenvalues for small-scale (noisy) experiments
T.E. O'Brien, B. Tarasinski, B.M. Terhal
`arXiv:1809.09697 <https://arxiv.org/abs/1809.09697>`_
"""
@deprecate_arg(
"quantum_instance",
additional_msg=(
"Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a "
"migration guide."
),
since="0.24.0",
)
def __init__(
self,
num_evaluation_qubits: int,
quantum_instance: QuantumInstance | Backend | None = None,
sampler: BaseSampler | None = None,
) -> None:
r"""
Args:
num_evaluation_qubits: The number of qubits used in estimating the phase. The phase will
be estimated as a binary string with this many bits.
quantum_instance: Deprecated: The quantum instance on which
the circuit will be run.
sampler: The sampler primitive on which the circuit will be sampled.
"""
# Avoid double warning on deprecated used of `quantum_instance`.
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
self._phase_estimation = PhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits,
quantum_instance=quantum_instance,
sampler=sampler,
)
def _get_scale(self, hamiltonian, bound=None) -> PhaseEstimationScale:
if bound is None:
return PhaseEstimationScale.from_pauli_sum(hamiltonian)
return PhaseEstimationScale(bound)
def _get_unitary(
self, hamiltonian, pe_scale, evolution: EvolutionSynthesis | EvolutionBase
) -> QuantumCircuit:
"""Evolve the Hamiltonian to obtain a unitary.
Apply the scaling to the Hamiltonian that has been computed from an eigenvalue bound
and compute the unitary by applying the evolution object.
"""
if self._phase_estimation._sampler is not None:
evo = PauliEvolutionGate(hamiltonian, -pe_scale.scale, synthesis=evolution)
unitary = QuantumCircuit(evo.num_qubits)
unitary.append(evo, unitary.qubits)
return unitary.decompose().decompose()
else:
# scale so that phase does not wrap.
scaled_hamiltonian = -pe_scale.scale * hamiltonian
unitary = evolution.convert(scaled_hamiltonian.exp_i())
if not isinstance(unitary, QuantumCircuit):
unitary = unitary.to_circuit()
return unitary.decompose().decompose()
# Decomposing twice allows some 1Q Hamiltonians to give correct results
# when using MatrixEvolution(), that otherwise would give incorrect results.
# It does not break any others that we tested.
def estimate(
self,
hamiltonian: PauliOp | MatrixOp | SummedOp | Pauli | SparsePauliOp | PauliSumOp,
state_preparation: StateFn | QuantumCircuit | Statevector | None = None,
evolution: EvolutionSynthesis | EvolutionBase | None = None,
bound: float | None = None,
) -> HamiltonianPhaseEstimationResult:
"""Run the Hamiltonian phase estimation algorithm.
Args:
hamiltonian: A Hermitian operator. If the algorithm is used with a ``Sampler``
primitive, the allowed types are ``Pauli``, ``SparsePauliOp``, and ``PauliSumOp``.
If the algorithm is used with a ``QuantumInstance``, ``PauliOp, ``MatrixOp``,
``PauliSumOp``, and ``SummedOp`` types are allowed.
state_preparation: The ``StateFn`` to be prepared, whose eigenphase will be
measured. If this parameter is omitted, no preparation circuit will be run and
input state will be the all-zero state in the computational basis.
evolution: An evolution converter that generates a unitary from ``hamiltonian``. If
``None``, then the default ``PauliTrotterEvolution`` is used.
bound: An upper bound on the absolute value of the eigenvalues of
``hamiltonian``. If omitted, then ``hamiltonian`` must be a Pauli sum, or a
``PauliOp``, in which case a bound will be computed. If ``hamiltonian``
is a ``MatrixOp``, then ``bound`` may not be ``None``. The tighter the bound,
the higher the resolution of computed phases.
Returns:
``HamiltonianPhaseEstimationResult`` instance containing the result of the estimation
and diagnostic information.
Raises:
TypeError: If ``evolution`` is not of type ``EvolutionSynthesis`` when a ``Sampler`` is
provided.
TypeError: If ``hamiltonian`` type is not ``Pauli`` or ``SparsePauliOp`` or
``PauliSumOp`` when a ``Sampler`` is provided.
ValueError: If ``bound`` is ``None`` and ``hamiltonian`` is not a Pauli sum, i.e. a
``PauliSumOp`` or a ``SummedOp`` whose terms are of type ``PauliOp``.
TypeError: If ``evolution`` is not of type ``EvolutionBase`` when no ``Sampler`` is
provided.
"""
if self._phase_estimation._sampler is not None:
if evolution is not None and not isinstance(evolution, EvolutionSynthesis):
raise TypeError(f"Expecting type EvolutionSynthesis, got {type(evolution)}")
if not isinstance(hamiltonian, (Pauli, SparsePauliOp, PauliSumOp)):
raise TypeError(
f"Expecting Hamiltonian type Pauli, SparsePauliOp or PauliSumOp, "
f"got {type(hamiltonian)}."
)
if isinstance(state_preparation, Statevector):
circuit = QuantumCircuit(state_preparation.num_qubits)
circuit.prepare_state(state_preparation.data)
state_preparation = circuit
if isinstance(hamiltonian, PauliSumOp):
id_coefficient, hamiltonian_no_id = _remove_identity_pauli_sum_op(hamiltonian)
else:
id_coefficient = 0.0
hamiltonian_no_id = hamiltonian
pe_scale = self._get_scale(hamiltonian_no_id, bound)
unitary = self._get_unitary(hamiltonian_no_id, pe_scale, evolution)
else:
if evolution is None:
evolution = PauliTrotterEvolution()
elif not isinstance(evolution, EvolutionBase):
raise TypeError(f"Expecting type EvolutionBase, got {type(evolution)}")
if isinstance(hamiltonian, PauliSumOp):
hamiltonian = hamiltonian.to_pauli_op()
elif isinstance(hamiltonian, PauliOp):
hamiltonian = SummedOp([hamiltonian])
if isinstance(hamiltonian, SummedOp):
# remove identitiy terms
# The term prop to the identity is removed from hamiltonian.
# This is done for three reasons:
# 1. Work around an unknown bug that otherwise causes the energies to be wrong in some
# cases.
# 2. Allow working with a simpler Hamiltonian, one with fewer terms.
# 3. Tighten the bound on the eigenvalues so that the spectrum is better resolved, i.e.
# occupies more of the range of values representable by the qubit register.
# The coefficient of this term will be added to the eigenvalues.
id_coefficient, hamiltonian_no_id = _remove_identity(hamiltonian)
# get the rescaling object
pe_scale = self._get_scale(hamiltonian_no_id, bound)
# get the unitary
unitary = self._get_unitary(hamiltonian_no_id, pe_scale, evolution)
elif isinstance(hamiltonian, MatrixOp):
if bound is None:
raise ValueError("bound must be specified if Hermitian operator is MatrixOp")
# Do not subtract an identity term from the matrix, so do not compensate.
id_coefficient = 0.0
pe_scale = self._get_scale(hamiltonian, bound)
unitary = self._get_unitary(hamiltonian, pe_scale, evolution)
else:
raise TypeError(f"Hermitian operator of type {type(hamiltonian)} not supported.")
if state_preparation is not None and isinstance(state_preparation, StateFn):
state_preparation = state_preparation.to_circuit_op().to_circuit()
# run phase estimation
phase_estimation_result = self._phase_estimation.estimate(
unitary=unitary, state_preparation=state_preparation
)
return HamiltonianPhaseEstimationResult(
phase_estimation_result=phase_estimation_result,
id_coefficient=id_coefficient,
phase_estimation_scale=pe_scale,
)
def _remove_identity(pauli_sum: SummedOp):
"""Remove any identity operators from `pauli_sum`. Return
the sum of the coefficients of the identities and the new operator.
"""
idcoeff = 0.0
ops = []
for op in pauli_sum:
p = op.primitive
if p.x.any() or p.z.any():
ops.append(op)
else:
idcoeff += op.coeff
return idcoeff, SummedOp(ops)
def _remove_identity_pauli_sum_op(pauli_sum: PauliSumOp | SparsePauliOp):
"""Remove any identity operators from ``pauli_sum``. Return
the sum of the coefficients of the identities and the new operator.
"""
def _get_identity(size):
identity = I
for _ in range(size - 1):
identity = identity ^ I
return identity
idcoeff = 0.0
if isinstance(pauli_sum, PauliSumOp):
for operator in pauli_sum:
if operator.primitive.paulis == ["I" * pauli_sum.num_qubits]:
idcoeff += operator.primitive.coeffs[0]
pauli_sum = pauli_sum - operator.primitive.coeffs[0] * _get_identity(
pauli_sum.num_qubits
)
return idcoeff, pauli_sum.reduce()
|
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/Slope86/QiskitExtension
|
Slope86
|
import math
from qiskit_extension.quantum_circuit2 import QuantumCircuit2 as qc2
from qiskit_extension.state_vector2 import StateVector2 as sv2
# Create a 4bits quantum circuit
circ_init = qc2(4)
# Make ground state qubit(0,1) and qubit(2,3) entangled into two EPR pairs
circ_init.h([0,2])
circ_init.cx([0,2],[1,3])
# Display the circuit
circ_init.show_circ()
# Put the ground state into the circuit we build in previous step, and get two EPR pairs
state_EPR = sv2(circ_init)
# Show state
state_EPR.show_state()
circ_Bell_measure = qc2(4)
circ_Bell_measure.cx(1,2)
circ_Bell_measure.h(1)
# Bell measurement on qubits(1,2), and store the four possible states as a list after measurement
# list[0b00]=state after measurement result is 00,
# list[0b01]=state after measurement result is 01,
# ...
list_state_EPR_after_Bell_measure = state_EPR.evolve(circ_Bell_measure).measure([1,2])
# Show the four possible states after the Bell measurement
# Display format: (|00> indicates the measured state, followed by a colon indicating [the remaining state after measurement result is 00])
# |00>: 1/2|0> + 1/2|1> ...
state_EPR.evolve(circ_Bell_measure).show_measure([1,2])
# Get the state after measuring, and the measurement result is 01
state_before_correction = list_state_EPR_after_Bell_measure[0b01]
# Show the state before correction
state_before_correction.show_state(hide=[1,2])
# Correction circuit (measurement result is 01, so perform Pauli-X on qubit 3)
circ_correction = qc2(4)
circ_correction.x(3)
# Put state_before_correction into the correction circuit, get the state after correction
state_after_correction = state_before_correction.evolve(circ_correction)
# Show corrected state, make sure that entangled swap successful
state_after_correction.show_state(hide=[1,2])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import *
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit $q_{0}$, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{1}$, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{2}$, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = backend.run(circ)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = backend.run(circ)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition using
# the compose method.
circ.add_register(meas.cregs[0])
qc = circ.compose(meas)
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend_sim.run(transpile(qc, backend_sim), shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
| |
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
|
AbdulahAmer
|
# Do not forget to Import Qiskit
from qiskit.visualization import *
from qiskit import *
S_simulator=Aer.backends(name='statevector_simulator')[0]
M_simulator=Aer.backends(name='qasm_simulator')[0]
from math import pi
# lets make a fucntions called rotate we do this in python by using def and
# then the function name along with the variables we want our function to take and a colon
def rotations(circuit, n):
# if we went through the whole circuit, we do not have to do anymore work
# just return the circuit we made
if n == 0:
return circuit
# circuit is the QuantumCircuit we want to use the qft on,
# n is the number of qubits in the circuit
n-=1 # 4th qubit is in the n=3 spot on the circuit
# mth qubit is on the n=m-1 spot on the circuit
# also allows us to reduce down to n = 0 and to stop doing the rotations
circuit.h(n) # Apply Hadamard gate to the qubit we are currently working on
for qubit in range(n):
# now use controlled phase gate to rotate
# also divide the rotation angle by 2 each time
circuit.cp(pi/2**(n-qubit), qubit, n) # circuit.cp() takes three arguments
# (theta, target qubit, control qubit)
#so the first time through in this loop the dummy variable
# "qubit" is 0 , so we will do rotation of of pi/2**(n-0) on the 0th qubit using the
# nth qubit as a control qubit. And so on and so forth.
rotations(circuit, n) # do the same thing to the next qubit
qc = QuantumCircuit(5,5)
rotations(qc,5)
qc.draw(output='mpl')
def swap_qubits(circuit,n):
# only need to loop through half of the circuit, since we swap two qubits at a time
for qubit in range(n//2): # // floor function helps us round down when we have odd qubits
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
rotations(circuit, n)
swap_qubits(circuit,n)
return circuit
qc=QuantumCircuit(5,5)
qft(qc,5)
qc.draw(output='mpl')
# Note see how the 3rd qubit does not get swapped since it would swap with itself
# Lets take some state x and put it in the QFT and see what we get out
x=10
from math import log
def find_number_of_qubits(x):
powers_of_two=0
exponent=0
while powers_of_two<x:
powers_of_two=2**exponent
exponent+=1
number_of_qubits = int(log(powers_of_two,2))
return number_of_qubits
n = find_number_of_qubits(x)
encoding = bin(x)
# encoding has an extra '0b' that just says hey i am a binary number we can chop it off
# by replacing it with nothing
print('State we need to encode to try out qft: ', encoding.replace('0b', ''))
qc = QuantumCircuit(n,n) # number of qubits calculated before
qc.x(0)
qc.x(2)
qc.barrier() # seperate steps with a barrier.
print('state before QFT: ', execute(qc, S_simulator).result().get_statevector())
qft(qc, n)
print('state after QFT: ', execute(qc, S_simulator).result().get_statevector())
# Our output is a little messy lets grab the state and clean it up
state = execute(qc, S_simulator).result().get_statevector()
# we use formatting %f to print trimmed version of the real and complex parts of each amplitude
# this is cool to pick up but do not worry too much about this
real=[]
imag=[]
for i in state:
print('%f' % i.real, '%f' % i.imag , 'j')
# We see that we get a weird repeating signal or wave of values for a constant state
real.append(i.real)
imag.append(i.imag)
from matplotlib import pyplot as plt
plt.plot(range(len(state)), real)
plt.plot(range(len(state)), imag)
plt.show()
# What would we get if we take an input where we have an even superposition of all states.
from math import sqrt
n=3
a= sqrt(1/(2**n)) # amplitude
state=[a,a,a,a,a,a,a,a]
qc=QuantumCircuit(3)
qc.initialize(state, [0,1,2])
qc.barrier() # seperate steps with a barrier.
print('state before QFT: ', execute(qc, S_simulator).result().get_statevector())
qft(qc, n)
print('state after QFT: ', execute(qc, S_simulator).result().get_statevector())
# Our output is a little messy lets grab the state and clean it up
state = execute(qc, S_simulator).result().get_statevector()
# we use formatting %f to print trimmed version of the real and complex parts of each amplitude
# this is cool to pick up but do not worry too much about this
real=[]
imag=[]
for i in state:
print('%f' % i.real, '%f' % i.imag , 'j')
# We see that we get a weird repeating signal or wave of values for a constant state
real.append(i.real)
imag.append(i.imag)
from matplotlib import pyplot as plt
plt.plot(range(len(state)), real)
plt.plot(range(len(state)), imag)
plt.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.