repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
#Applying the CZ gate
qc.cz(0,1)
#Draw the circuit
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
#Applying the hadarmad gate to target
qc.h(1)
#apply the cx gate to both qubits
qc.cx(0,1)
#Applying the hadarmad gate to target
qc.h(1)
#Draw the circuit
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
#Apply pauli x-gate on the qubit
qc.x(0)
#Apply the hadamard gate on the qubit
qc.h(0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
# visualize the output as an animation
visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with a single qubit
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
qc.z(0)
qc.h(0)
# qc.draw()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
plot_bloch_multivector(out)
visualize_transition(qc)
out = execute(qc,backend).result()
counts = out.get_counts()
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1,1)
#Apply the Pauli X-gate on the qubit to make the input as |1>
#qc.x(0)
#Apply the hadamard gate on the qubit
qc.h(0)
#try to measure the qbit
qc.measure(0,0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
# visualize the output as an animation
#visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 3 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(3)
#Applying hadamard gate to all the qubits
qc.h(0)
qc.h(1)
qc.h(2)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
#Applying the x gate to second qubit
qc.x(1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#Get the backend for the circuit (simulator or realtime system)
#backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#execute the circuit using the backend
#out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
#array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
#Applying hadamard gate to first qubit, then x gate to second
qc.h(0)
qc.x(1)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#Get the backend for the circuit (simulator or realtime system)
#backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#execute the circuit using the backend
#out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
#array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
# declare the intial sate as [0,1] or |1>
#initial_state = [0,1]
#qc.initialize(initial_state,0)
#Apply the Pauli X-gate on the qubit
qc.x(0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
# visualize the output as an animation
visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
#Apply the Pauli X-gate on the qubit
qc.x(0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
#Apply the Pauli X-gate on the qubit to make the input to y gate as |1>
qc.x(0)
#Apply the Pauli y-gate on the |1> qubit
qc.y(0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
# visualize the output as an animation
visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
#Apply the Pauli X-gate on the qubit to make the input to y gate as |1>
qc.x(0)
#Apply the Pauli z-gate on the |1> qubit
qc.z(0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
# visualize the output as an animation
visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
from numpy import pi
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
#Apply the Pauli X-gate on the qubit to make the input to y gate as |1>
#qc.h(0)
#qc.h(0)
#Apply the Pauli z-gate on the |1> qubit
qc.rz(pi/4,0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
# visualize the output as an animation
visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
from numpy import pi
# Create a quantum circuit with a single qubit
# The default initial state of qubit will be |0> or [1,0]
qc = QuantumCircuit(1)
#Apply the s gate and sdg gate to obtain identity
qc.s(0)
qc.sdg(0)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
# visualize the output as an animation
visualize_transition(qc)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_histogram
import numpy as np
# creating a constant oracle, input has no effect on the ouput
# Create a quantum circuit with 2 qubits. One as input and other as output
constant_oracle = QuantumCircuit(2)
# get a random number from 0 or 1
output = np.random.randint(2)
# what ever get in input, its having no effect.
# the output will be the random value 0 or 1
if output == 1:
constant_oracle.x(1)
# draw the circuit
constant_oracle.draw('mpl')
# creating a balanced oracle,
# perform CNOTs with first qubit input as a control and the second qubit output as the target.
balanced_oracle = QuantumCircuit(2)
# Place X-gate for input qubit
balanced_oracle.x(0)
# Use barrier as divider
balanced_oracle.barrier()
# Place Controlled-NOT gates
balanced_oracle.cx(0, 1)
# using barrier as a divider and avoid cancelling gates by the transpiler
balanced_oracle.barrier()
# Place X-gates
balanced_oracle.x(0)
# Show oracle
balanced_oracle.draw('mpl')
#initialise the input qubits in the state |+⟩
# and the output qubit in the state |−⟩
dj_circuit = QuantumCircuit(2, 1)
# Apply H-gates
dj_circuit.h(0)
# Put qubit in state |->
dj_circuit.x(1)
dj_circuit.h(1)
dj_circuit.draw('mpl')
# define the oracle function to use
#oracle_fn = constant_oracle
oracle_fn = balanced_oracle
# Add oracle function
dj_circuit += oracle_fn
dj_circuit.draw('mpl')
# perform H-gates on qubit and measure input register
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
dj_circuit.measure(0, 0)
# Display circuit
dj_circuit.draw('mpl')
# check the output
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(dj_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/KPRoche/quantum-raspberry-tie
|
KPRoche
|
#----------------------------------------------------------------------
# QuantumRaspberryTie.qk1_local
# by KPRoche (Kevin P. Roche) (c) 2017,2018,2019,2020,2021,2022.2024
#
# NEW RELEASE
# April 2024 to accomodate the official release of Qiskit 1.0
# using new QiskitRuntime libraries and call techniques;
# runs OPENQASM code on an IBM Quantum backend or simulator
# Display the results using the 8x8 LED array on a SenseHat (or SenseHat emulator)
# Will Default to local simulator because the cloud simulator is being retired.
#
# Will Connect and authenticate to the IBM Quantum platform via the QiskitRuntime module (if necessary)
#
# NEW default behavior:
# Spins up a 5-qubit test backend (local simulator) based on FakeManilaV2
# in a "bowtie" arrangement based on older processors
# New Qiskit-logo inspired "thinking" graphic
# NEW backend options:
# -b:aer | spins up a local Aer simulator
# -b:aer_noise or -b:aer_model | spins up a local Aer simulator with a noise model
# based on the least busy real processor for your account (this does require access to
# the IBM Quantum processors and account credentials properly saved via QiskitRuntime
# -b:least | will run code once on the least busy *real* backend for your account
# NOTE: this may take hours before the result returns
# -b:[backend_name] | will use the specified backend if it is available (see note above)
# NEW display options
# NOTE: if multiple options are specified the last one in the parameters will be applied
# hex or -hex | displays on a 12 qubit pattern
# (topologically identical to the heavy hex in IBM processors)
# d16 or -d16 | displays on a 16 qubit pattern
# NOTE: overrides default or tee option for 5 qubit code!
# NOTE: if your quantum circuit has fewer qubits than available in the display mode,
# unmeasured qubits will be displayed in purple
#
# NEW interactive options
# -input | prompts you to add more parameters to what was on the command line
# -select | prompts you for the backend option before initializing
# OTHER options:
# -tee | switches to a tee-shaped 5-qubit arrangement
# -16 or 16 | loads a 16-qubit QASM file and switches to a 16-bit display arrangement
# NOTE: hex display mode will override the 16 qubit display and show only the first 12
# -noq | does not show a logo during the rainbow "thinking" moment; instead rainbows the qubit display
# -e | will attempt to spin up a SenseHat emulator display on your desktop.
# -d | will attempt to display on BOTH the SenseHat and a emulator display
# These require that both the libraries and a working version of the emulator executable be present
# -f:filename load an alternate QASM file
# ----------------------------- pre Qiskit 1.0 History -----------------------
#
# April 2023 -- added dual display option. If sensehat is available, will spin up a second emulator to show
# on the desktop
# Nov 2022 -- Cleaned up -local option to run a local qasm simulator if supported
#
# Feb 2020 -- Added fix to IBM Quantum Experience URL (Thanks Jan Lahman)
#
# October 2019 -- added extra command line parameters. Can force use of Sensehat emulator, or specify backend
# (specifying use of a non-simulator backend will disable loop)
# October 2019 -- will attempt to load SenseHat and connect to hardware.
# If that fails, then loads and launches SenseHat emulator for display instead
#
# September 2019 -- adaptive version can use either new (0.3) ibmq-provider with provider object
# or older (0.2) IBMQ object
# July 2019 -- convert to using QISKIT full library authentication and quantum circuit
# techniques
# March 2018 -- Detect a held center switch on the SenseHat joystick to trigger shutdown
#
# Original (2017) version
# Spin off the display functions in a separate thread so they can exhibit
# smooth color changes while "thinking"
# Use a ping function to try to make sure the website is available before
# sending requests and thus avoid more hangs that way
# Move the QASM code into an outside file
#
#----------------------------------------------------------------------
# import the necessary modules
print("importing libraries...")
print(" ....sys")
import sys # used to check for passed filename
print(" ....os")
import os # used to find script directory
print(" ....requests")
import requests # used for ping
print(" ....threading")
from threading import Thread # used to spin off the display functions
print(" ....colorsys")
from colorsys import hsv_to_rgb # used to build the color array
print(" ....time")
from time import process_time # used for loop timer
print(" ....sleep")
from time import sleep #used for delays
print(" ....qiskit QiskitRuntimeService")
from qiskit_ibm_runtime import QiskitRuntimeService # classes for accessing IBM Quantum online services
print(" ....QuantumCircuit and transpile")
from qiskit import QuantumCircuit, transpile, qiskit
from qiskit.providers import JobStatus
print(" .....simple local emulator (fakeManila)")
from qiskit_ibm_runtime.fake_provider import FakeManilaV2
print (" .....Aer for building local simulators")#importing Aer to use local simulator")
from qiskit_aer import Aer
print(" ....warnings")
import warnings
IBMQVersion = qiskit.__version__
print(IBMQVersion)
#Initialize then check command arguments
UseEmulator = False
DualDisplay = False
QWhileThinking = True
UseTee = False
UseHex = False
UseQ16 = False
UseLocal = True
backendparm = '[localsim]'
SelectBackend = False #for interactive selection of backend
fake_name = "FakeManilaV2"
qubits_needed = 5 #default size for the five-qubit simulation
AddNoise = False
debug = False
qasmfileinput='expt.qasm'
#----------------------------------------------------------------------------
# Create a SVG rendition of the pixel array
#----------------------------------------------------------------------------
def svg_pixels(pixel_list, brighten=1):
# Create canvas
svg_inline = '<svg width="128" height="128" version="1.1" xmlns="http://www.w3.org/2000/svg">\n'
# fill canvas with black background
#svg_inline = svg_inline + '<rect x="0" y="0" width="128" height="128" stroke="black" fill="black" stroke-width="0"/>\n'
# iterate through the list
for i in range(64):
# get the coordinates
x = 4 * 4 * (i % 8)
y = 4 * 4 * (i//8)
pixel=pixel_list[i]
red=pixel[0]
green=pixel[1]
blue=pixel[2]
if brighten > 0:
red = min(int(red * brighten),255)
green = min(int(green * brighten),255)
blue = min(int(blue * brighten),255)
# build the "pixel" rectangle and append it
pixel_str=f'<rect x="{x}" y="{y}" fill="rgb({red},{green},{blue})" width="16" height="16" stroke="white" stroke-width="1"/>\n'
svg_inline = svg_inline + pixel_str
#close the svg
svg_inline = svg_inline + "</svg>"
return svg_inline
def write_svg_file(pixels, label='0000', brighten=1, init=False):
# This uses multiple files to create the webpage qubit display:
# qubits.html is only written if init is True
# It contains the refresh command and the html structure, and pulls in the other two
# pixels.svg holds the display pattern
# pixels.lbl holds the caption
if init:
print("initializing html wrapper for svg display")
try: #create the svg directory if it doesn't exist yet
os.mkdir(r'./svg')
except OSError as error:
print(error)
html_file = open (r'./svg/qubits.html',"w")
browser_str='''<!DOCTYPE html>\r<html>\r<head>\r
<title>SenseHat Display</title>\r
<meta http-equiv="refresh" content="2.5">\r
</head>\r<body>\r
<h3>Latest Display on RPi SenseHat</h3>\r
<object data="pixels.html"/ height='425' width='400'>\r
</body></html>'''
#browser_str = browser_str + '<br> Qubit Pattern: ' + label + '</body></html>'
html_file.write(browser_str)
html_file.close()
svg_file = open (r'./svg/pixels.html',"w")
#lbl_file = open (r'./svg/pixels.lbl',"w")
#browser_str='''<!DOCTYPE html>\r<html>\r<head>\r
# <title>SenseHat Display</title>\r
# <meta http-equiv="refresh" content="1">\r
# </head>\r<body>\r
# <h3>Latest Display on RPi SenseHat</h3>'''
browser_str= svg_pixels(pixels, brighten) + '\r <br/>Qubit Pattern: ' + label + '<br/><br/>\r'
svg_file.write(browser_str)
svg_file.close()
#browser_str = 'Qubit Pattern: ' + label + '\r'
#lbl_file.write(browser_str)
#lbl_file.close()
# -- prompt for any extra arguments if specified
print(sys.argv)
print ("Number of arguments: ",len(sys.argv))
# first check for interactive input request
if (len(sys.argv)>1):
parmlist = sys.argv
if "-input" in sys.argv:
bparmstr = input("add any additional parameters to the initial program call:\n")
if len(bparmstr) > 0:
bparms = bparmstr.split()
print("Command parms:",parmlist,"extra parms:",bparms)
parms = parmlist + bparms
else: parms = parmlist
print("all parms:",parms)
if debug: input("Press Enter to continue")
# now process the option parameters
#for p in range (1, len(sys.argv)):
for p in range (1, len(parms)):
parameter = parms[p]
if type(parameter) is str:
print("Parameter ",p," ",parameter)
if 'debug' in parameter: debug = True
if ('16' == parameter or "-16" == parameter): qasmfileinput='16'
if '-local' in parameter: UseLocal = True # use the aer local simulator instead of the web API
if '-nois' in parameter: # add noise model to local simulator
UseLocal = True
AddNoise = True
if '-noq' in parameter: QWhileThinking = False # do the rainbow wash across the qubit pattern while "thinking"
if '-tee' in parameter:
UseTee = True # use the new tee-shaped 5 qubit layout for the display
if 'hex' in parameter:
UseHex = True # use the heavy hex 12 qubit layout for the display
UseTee = False # (and give it precedence over the tee display
if 'q16' in parameter:
UseQ16 = True # use the 12 qubit layout for the display
UseTee = False # (and give it precedence over the tee display
UseHex = False
if '-e' in parameter: UseEmulator = True # force use of the SenseHat emulator even if hardware is installed
if '-dual' in parameter: DualDisplay = True
if '-select' in parameter:
SelectBackend = True
UseLocal = False
elif ':' in parameter: # parse two-component parameters
print("processing two part parameter ", parameter)
token = parameter.split(':')[0] # before the colon is the key
value = parameter.split(':')[1] # after the colon is the value
if '-b' in token:
backendparm = value # if the key is -b, specify the backend
UseLocal = False
print("requested backend: ", backendparm, ", UseLocal set ",UseLocal)
elif '-f' in token:
qasmfileinput = value # if the key is -f, specify the qasm file
print("-f option: filename",qasmfileinput)
elif '-nois' in token: fake_name = value
if debug: input("press Enter to continue")
print ("QASM File input",qasmfileinput)
# Now we are going to try to instantiate the SenseHat, unless we have asked for the emulator.
# if it fails, we'll try loading the emulator
SenseHatEMU = False
if not UseEmulator:
print ("... importing SenseHat and looking for hardware")
try:
from sense_hat import SenseHat
hat = SenseHat() # instantiating hat right away so we can use it in functions
except:
print ("... problem finding SenseHat")
UseEmulator = True
print(" ....trying SenseHat Emulator instead")
if UseEmulator:
print ("....importing SenseHat Emulator")
from sense_emu import SenseHat # class for controlling the SenseHat
hat = SenseHat() # instantiating hat emulator so we can use it in functions
while not SenseHatEMU:
try:
hat.set_imu_config(True,True,True) #initialize the accelerometer simulation
except:
sleep(1)
else:
SenseHatEMU = True
else:
if DualDisplay:
from sense_emu import SenseHat # class for controlling the SenseHat
hat2 = SenseHat() # instantiating hat emulator so we can use it in functions
while not SenseHatEMU:
try:
hat2.set_imu_config(True,True,True) #initialize the accelerometer simulation
except:
sleep(1)
else:
SenseHatEMU = True
# some variables and settings we are going to need as we start up
print("Setting up...")
# This (hiding deprecation warnings) is temporary because the libraries are changing again
warnings.filterwarnings("ignore", category=DeprecationWarning)
Looping = True # this will be set false after the first go-round if a real backend is called
angle = 180
result = None
runcounter=0
maxpattern='00000'
interval=5
stalled_time = 60 # how many seconds we're willing to wait once a job status is "Running"
thinking=False # used to tell the display thread when to show the result
shutdown=False # used to tell the display thread to trigger a shutdown
qdone=False
showlogo=False
###########################################################################################
#-------------------------------------------------------------------------------
# These variables and functions are for lighting up the qubit display on the SenseHat
# ibm_qx5 builds a "bowtie"
# They were moved up here so we can flash a "Q" as soon as the libraries load
#
# the color shift effect is based on the rainbow example included with the SenseHat library
#-------------------------------------------------------------------------------
# pixel coordinates to draw the bowtie qubits or the 16 qubit array
ibm_qx5 = [[40,41,48,49],[8,9,16,17],[28,29,36,37],[6,7,14,15],[54,55,62,63]]
ibm_qx5t = [[0,1,8,9],[3,4,11,12],[6,7,14,15],[27,28,35,36],[51,52,59,60]]
ibm_qhex = [ [3],
[10], [12],
[17], [21],
[24], [30],
[33], [37],
[42], [44],
[51] ]
ibm_qx16 = [[63],[54],[61],[52],[59],[50],[57],[48],
[7],[14],[5],[12],[3],[10],[1],[8]]
#[[0],[9],[2],[11],[4],[13],[6],[15],
#[56],[49],[58],[51],[60],[53],[62],[55]]
# global to spell OFF in a single operation
X = [255, 255, 255] # white
O = [ 0, 0, 0] # black
off = [
O, O, O, O, O, O, O, O,
O, X, O, X, X, O, X, X,
X, O, X, X, O, O, X, O,
X, O, X, X, X, O, X, X,
X, O, X, X, O, O, X, O,
O, X, O, X, O, O, X, O,
O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O,
]
Qlogo = [
O, O, O, X, X, O, O, O,
O, O, X, O, O, X, O, O,
O, O, X, O, O, X, O, O,
O, O, X, O, O, X, O, O,
O, O, X, O, O, X, O, O,
O, O, O, X, X, O, O, O,
O, O, O, O, X, O, O, O,
O, O, O, X, X, O, O, O,
]
QLarray = [
[3],[4],
[10], [13],
[18], [21],
[26], [29],
[34], [37],
[43],[44],
[52],
[59],[60]
]
QArcs = [
O, O, O, O, O, O, X, O,
O, O, O, O, X, X, X, X,
O, O, X, X, O, O, X, O,
O, O, X, O, O, O, X, O,
O, X, O, O, O, X, X, O,
O, X, O, O, X, X, O, O,
X, X, X, X, O, O, O, O,
O, X, O, O, O, O, O, O,
]
QArcsArray = [
[6] ,
[12],[13],[14],[15],
[18],[19], [22],
[26], [30],
[33], [37],
[41], [44],[45],
[48],[49],[50],[51],
[57]
]
QKLogo = [
O, O, X, X, X, X, O, O,
O, X, X, O, O, X, X, O,
X, X, X, O, O, X, X, X,
X, X, O, X, X, O, X, X,
X, X, O, O, O, O, X, X,
X, O, X, X, X, X, O, X,
O, X, O, O, O, O, X, O,
O, O, X, X, X, X, O, O,
]
QKLogo_mask = [
[2], [3], [4], [5],
[9],[10], [13],[14],
[16],[17],[18], [21],[22],[23],
[24],[25], [27],[28], [31],
[32],[33], [38],[39],
[40], [42],[43], [44],[45], [47],
[49], [54],
[58],[59],[60],[61]
]
QHex = [
O, O, O, X, O, O, O, O,
O, O, X, O, X, O, O, O,
O, X, O, O, O, X, O, O,
X, O, O, O, O, O, X, O,
O, X, O, O, O, X, O, O,
O, O, X, O, X, O, O, O,
O, O, O, X, O, O, O, O,
O, O, O, O, O, O, O, O,
]
Arrow = [
O, O, O, X, O, O, O, O,
O, O, X, X, X, O, O, O,
O, X, O, X, O, X, O, O,
X, O, O, X, O, O, X, O,
O, O, O, X, O, O, O, O,
O, O, O, X, O, O, O, O,
O, O, O, X, O, O, O, O,
O, O, O, X, O, O, O, O,
]
# setting up the 8x8=64 pixel variables for color shifts
hues = [
0.00, 0.00, 0.06, 0.13, 0.20, 0.27, 0.34, 0.41,
0.00, 0.06, 0.13, 0.21, 0.28, 0.35, 0.42, 0.49,
0.07, 0.14, 0.21, 0.28, 0.35, 0.42, 0.50, 0.57,
0.15, 0.22, 0.29, 0.36, 0.43, 0.50, 0.57, 0.64,
0.22, 0.29, 0.36, 0.44, 0.51, 0.58, 0.65, 0.72,
0.30, 0.37, 0.44, 0.51, 0.58, 0.66, 0.73, 0.80,
0.38, 0.45, 0.52, 0.59, 0.66, 0.73, 0.80, 0.87,
0.45, 0.52, 0.60, 0.67, 0.74, 0.81, 0.88, 0.95,
]
pixels = [hsv_to_rgb(h, 1.0, 1.0) for h in hues]
qubits = pixels
# scale lets us do a simple color rotation of hues and convert it to RGB in pixels
def scale(v):
return int(v * 255)
def resetrainbow(show=False):
global pixels,hues
pixels = [hsv_to_rgb(h, 1.0, 1.0) for h in hues]
pixels = [(scale(r), scale(g), scale(b)) for r, g, b in pixels]
if (show):
hat.set_pixels(pixels)
if DualDisplay: hat2.set_pixels(pixels)
def showqubits(pattern='0000000000000000'):
global hat, qubits
padding=''
svgpattern=pattern
if len(pattern)<len(display):
for x in range(len(display)-len(pattern)):
padding = padding + '0'
pattern = pattern + padding
for p in range(64): #first set all pixels off
pixels[p]=[0,0,0]
for q in range(len(display)):
if pattern[q]=='1': # if the digit is "1" assign blue
for p in display[q]:
pixels[p]=[0,0,255]
elif q >= qubits_needed:
for p in display[q]: # if outside the number of measured qubits in the circuit, dim purple
pixels[p]=[75,0,75]
else: # otherwise assign it red
for p in display[q]:
pixels[p]=[255,0,0]
qubits=pixels
qubitpattern=pattern
hat.set_pixels(pixels) # turn them all on
write_svg_file(pixels, svgpattern, 2.5, False)
if DualDisplay: hat2.set_pixels(pixels)
#write_svg_file(qubits,2.5)
#--------------------------------------------------
# blinky lets us use the rainbow rotation code to fill the bowtie pattern
# it can be interrupted by tapping the joystick or if
# an experiment ID is provided and the
# status returns "DONE"
#
#------------------------------------------------------
def blinky(time=20,experimentID=''):
global pixels,hues,experiment, Qlogo, showlogo, QArcs, QKLogo, QHex, qubits, qubitpattern
if QWhileThinking:
mask = QKLogo_mask
else:
mask = display
#resetrainbow()
count=0
GoNow=False
while ((count*.02<time) and (not GoNow)):
# Rotate the hues
hues = [(h + 0.01) % 1.0 for h in hues]
# Convert the hues to RGB values
pixels = [hsv_to_rgb(h, 1.0, 1.0) for h in hues]
# hsv_to_rgb returns 0..1 floats; convert to ints in the range 0..255
pixels = [(scale(r), scale(g), scale(b)) for r, g, b in pixels]
for p in range(64):
#if QWhileThinking:
# if p in sum(Qlogo,[]):
# pass
# else:
# pixels[p]=[0,0,0]
# else:
if p in sum(mask,[]):
#if p in sum(display,[]):
pass
else:
pixels[p]=[0,0,0]
if (result is not None):
if (result.status=='COMPLETED'):
GoNow=True
# Update the display
if not showlogo:
hat.set_pixels(pixels)
if DualDisplay: hat2.set_pixels(pixels)
else:
hat.set_pixels(QKLogo)
if DualDisplay: hat2.set_pixels(QArcs)
sleep(0.002)
count+=1
for event in hat.stick.get_events():
if event.action == 'pressed':
goNow=True
if event.action == 'held' and event.direction =='middle':
shutdown=True
#------------------------------------------------
# now that the light pattern functions are defined,
# build a class glow so we can launch display control as a thread
#------------------------------------------------
class glow():
global thinking,hat, maxpattern, shutdown,off,Qlogo, QArcs, Qhex
def __init__(self):
self._running = True
def stop(self):
self._running = False
self._stop = True
def run(self):
#thinking=False
while self._running:
if shutdown:
hat.set_rotation(angle)
hat.set_pixels(off)
sleep(1)
hat.clear()
if DualDisplay: hat2.clear()
path = 'sudo shutdown -P now '
os.system (path)
else:
if thinking:
blinky(.1)
else:
showqubits(maxpattern)
#----------------------------------------------------------------
# Set the display size and rotation Turn on the display with an IBM "Q" logo
#----------------------------------------------------------------
def orient():
global hat,angle
acceleration = hat.get_accelerometer_raw()
x = acceleration['x']
y = acceleration['y']
z = acceleration['z']
x=round(x, 0)
y=round(y, 0)
z=round(z, 0)
print("current acceleration: ",x,y,z)
if y == -1:
angle = 180
elif y == 1 or (SenseHatEMU and not DualDisplay):
angle = 0
elif x == -1:
angle = 90
elif x == 1:
angle = 270
#else:
#angle = 180
print("angle selected:",angle)
hat.set_rotation(angle)
if DualDisplay: hat2.set_rotation(0)
# Now call the orient function and show an arrow
orient()
display=ibm_qx16
hat.set_pixels(Arrow)
if DualDisplay: hat2.set_pixels(Arrow)
##################################################################
# Input file functions
##################################################################
#----------------------------------------------------------
# find our experiment file... alternate can be specified on command line
# use a couple tricks to make sure it is there
# if not fall back on our default file
#def loadQASMfile():
scriptfolder = os.path.dirname(os.path.realpath("__file__"))
#print(sys.argv)
#print ("Number of arguments: ",len(sys.argv))
# look for a filename option
#if (len(sys.argv) > 1) and type(sys.argv[1]) is str:
#print (type(sys.argv[1]))
# qasmfilename=sys.argv[1]
# print ("input arg:",qasmfilename)
if (qasmfileinput == '16'): qasmfilename='expt16.qasm'
else: qasmfilename = qasmfileinput
#qasmfilename='expt.qasm'
print("QASM File:",qasmfilename)
#complete the path if necessary
if ('/' not in qasmfilename):
qasmfilename=scriptfolder+"/"+qasmfilename
if (not os.path.isfile(qasmfilename)):
qasmfilename=scriptfolder+"/"+'expt.qasm'
print("OPENQASM file: ",qasmfilename)
if (not os.path.isfile(qasmfilename)):
print("QASM file not found... exiting.")
exit()
# Parse any other parameters:
# end DEF ----------------------
###############################################################
# Connection functions
# ping and authentication
###############################################################
#----------------------------------------------------------------------------
# set up a ping function so we can confirm the service can connect before we attempt it
# ping uses the requests library
# based on pi-ping by Wesley Archer (raspberrycoulis) (c) 2017
# https://github.com/raspberrycoulis/Pi-Ping
#----------------------------------------------------------------------------
def ping(website='https://quantum-computing.ibm.com/',repeats=1,wait=0.5,verbose=False):
msg = 'ping response'
for n in range(repeats):
response = requests.get(website)
if int(response.status_code) == 200: # OK
pass
elif int(response.status_code) == 500: # Internal server error
msg ='Internal server error'
elif int(response.status_code) == 503: # Service unavailable
msg = 'Service unavailable'
elif int(response.status_code) == 502: # Bad gateway
msg = 'Bad gateway'
elif int(response.status_code) == 520: # Cloudflare: Unknown error
msg = 'Cloudflare: Unknown error'
elif int(response.status_code) == 522: # Cloudflare: Connection timed out
msg = 'Cloudflare: Connection timed out'
elif int(response.status_code) == 523: # Cloudflare: Origin is unreachable
msg = 'Cloudflare: Origin is unreachable'
elif int(response.status_code) == 524: # Cloudflare: A Timeout occurred
msg = 'Cloudflare: A Timeout occurred'
if verbose: print(response.status_code,msg)
if repeats>1: sleep(wait)
return int(response.status_code)
# end DEF ----------------------------------------------------------------
# ------------------------------------------------------------------------
# try to start our IBM Quantum backend (simulator or real) and connection to IBM Quantum APIs
# Here we attempt to ping the IBM Quantum Computing API servers. If no response, we exit
# If we get a 200 response, the site is live and we initialize our connection to it
#-------------------------------------------------------------------------------
def startIBMQ():
global Q, backend, UseLocal, backendparm
# This version written to work only with the new QiskitRuntimeService module from Qiskit > v1.0
sQPV = IBMQVersion
pd = '.'
dot1 = [pos for pos, char in enumerate(sQPV) if char==pd][0]
dot2 = [pos for pos, char in enumerate(sQPV) if char==pd][1]
IBMQP_Vers=float(sQPV[0:dot2])
if SelectBackend:
backendparm = input("type the backend you wish to use:\n"
"'least' will find a least-busy real backend.\n"
" 'aer' will generate a basic Aer Simulator\n"
" 'aernois' or 'airmodel' will create a real-system noise modeled Aer simulator.\n")
elif UseLocal: backendparm = "FakeManilaV2"
print('IBMQ Provider v',IBMQP_Vers, "backendparm ",backendparm,", UseLocal",UseLocal)
if debug: input("Press Enter Key")
if qubits_needed > 5 and UseLocal:
UseLocal = False
backendparm = 'aer'
if not UseLocal:
print ('Pinging IBM Quantum API server before start')
p=ping('https://api.quantum-computing.ibm.com',1,0.5,True)
#p=ping('https://auth.quantum-computing.ibm.com/api',1,0.5,True)
#p=ping('https://quantum-computing.ibm.com/',1,0.5,True)
try:
print("requested backend: ",backendparm)
except:
sleep(0)
# specify the simulator as the backup backend (this must change after May 15 2024)
backend='ibmq_qasm_simulator'
if p==200:
if (IBMQP_Vers >= 1): # The new authentication technique with provider as the object
print("trying to create backend connection")
Qservice=QiskitRuntimeService()
if "aer" in backendparm:
from qiskit_aer import AerSimulator
if "model" in backendparm or "nois" in backendparm or AddNoise:
print("getting a real backend connection for aer model")
real_backend = Qservice.least_busy(simulator=False)#operational=True, backend("ibm_brisbane")
print("creating AerSimulator modeled from ",real_backend.name)
Q = AerSimulator.from_backend(real_backend)
else:
print("creating basic Aer Simulator")
Q = AerSimulator()
UseLocal=True #now that it's built, mark the backend as local
else:
try:
if "least" in backendparm:
Q = Qservice.least_busy(operational=True, simulator=False)
else:
Q = Qservice.backend(backendparm)
except:
print("first backend attempt failed...")
Q=Qservice.backend(backend)
else:
interval = 300
else: # The older IBMQ authentication technique
exit() #this code only works with the new Qiskit>v1.0
else:
exit()
else: # THIS IS THE CASE FOR USING LOCAL SIMULATOR
backend='local aer qasm_simulator'
print ("Building ",backend, "with requested attributes...")
if not AddNoise:
from qiskit_aer import AerSimulator
Q = AerSimulator() #Aer.get_backend('qasm_simulator')
else:
Q = FakeManilaV2()
#-------------------------------------------------------------------------------
#################################################################################
#
# Main program loop (note: we turned on a logo earlier at line 202)
#
#################################################################################
# Instantiate an instance of our glow class
print("Instantiating glow...")
glowing = glow()
# create the html shell file
write_svg_file(pixels, maxpattern, 2.5, True)
#-------------------------------------------------
# OK, let's get this shindig started
#-------------------------------------------------
#First, let's read our input file and see how many qubits we need?
exptfile = open(qasmfilename,'r') # open the file with the OPENQASM code in it
qasm= exptfile.read() # read the contents into our experiment string
if (len(qasm)<5): # if that is too short to be real, exit
exit
else: # otherwise print it to the console for reference
print("OPENQASM code to send:\n",qasm)
#to determin the number of qubits, we have to make the circuit
qcirc=QuantumCircuit.from_qasm_str(qasm)
qubits_needed = qcirc.num_qubits
rainbowTie = Thread(target=glowing.run) # create the display thread
startIBMQ() # try to connect and instantiate the IBMQ
qcirc=QuantumCircuit.from_qasm_str(qasm)
try:
print("generating circuit from QASM")# (qcirc)
except UnicodeEncodeError:
print ('Unable to render quantum circuit drawing; incompatible Unicode environment')
except:
print ('Unable to render quantum circuit drawing for some reason')
if (qubits_needed > 5 and not UseHex) or UseQ16:
display = ibm_qx16
maxpattern='0000000000000000'
print ("circuit width: ",qubits_needed," using 16 qubit display")
else:
if (UseTee and qubits_needed <= 5 ):
display = ibm_qx5t
maxpattern='00000'
elif (UseHex):
display = ibm_qhex
maxpattern='000000000000'
else:
display = ibm_qx5
maxpattern='00000'
print ("circuit width: ",qubits_needed," using 5 qubit display")
qubitpattern=maxpattern
#backend='simulator'
rainbowTie.start() # start the display thread
while Looping:
runcounter += 1
if "aer" in backendparm: UseLocal=True
try:
if not UseLocal:
p=ping()
else:
p=200
except:
print("connection problem with IBMQ")
else:
if p==200:
orient()
showlogo = True
thinking = True
Qname=Q.name
print("Name:",Q.name,"Version:",Q.version,"No. of qubits:",Q.num_qubits)
if not UseLocal and not "aer" in backendparm:
Qstatus=Q.status()
print(Qstatus.backend_name, "is simulator? ", Q.simulator, "| operational: ", Qstatus.operational ,"| jobs in queue:",Qstatus.pending_jobs)
try:
if not UseLocal:
Qstatus = Q.status() # check the availability
except:
print('Problem getting backend status... waiting to try again')
else:
if not UseLocal:
Qstatus=Q.status()
print('Backend Status: ',Qstatus.status_msg, 'operational:',Qstatus.operational)
if debug: input('press enter')
qstatmsg=Qstatus.status_msg
q_operational=Qstatus.operational
else:
qstatmsg='active'
q_operational=False
if (qstatmsg == 'active' and q_operational) or UseLocal:
print(' executing quantum circuit... on ',Q.name)
#print(Q.name,' options:',Q.options)
try:
print (qcirc)
except UnicodeEncodeError:
print ('Unable to render quantum circuit drawing; incompatible Unicode environment')
except:
print ('Unable to render quantum circuit drawing for some reason')
try:
qk1_circ=transpile(qcirc, Q) # transpile for the new primitive
except:
print("problem transpiling circuit")
else:
print("transpilation complete")
#try:
if not UseLocal:
print("backend: ",Q.name," operational? ",Q.status().operational," Pending:",Q.status().pending_jobs)
else:
print("backend: ",Q.name," operational? ALWAYS")
if debug: input('Press the Enter Key')
print("running job")
qjob=Q.run(qk1_circ) # run
print("JobID: ",qjob.job_id())
print("Job Done?",qjob.done())
#if qjob.errored():
# print("error message:",qjob.error_message())
#qjob=execute(qcirc, Q, shots=500, memory=False)
Looping = UseLocal or Q.simulator
if runcounter < 3: print("Using ", Qname, " ... Looping is set ", Looping)
running_start = 0
running_timeout = False
running_cancelled = False
showlogo = False
qdone = False
while not (qdone or running_timeout or running_cancelled):
qdone = qjob.in_final_state() or qjob.cancelled()
if not UseLocal:
print(running_start,qjob.job_id(),"Job Done? ", qjob.in_final_state(),"| Cancelled? ",qjob.cancelled(),"| queued jobs:",qjob.backend().status().pending_jobs)
else:
print(running_start,qjob.job_id(),"Job Done? ", qjob.in_final_state(),"| Cancelled? ",qjob.cancelled())
if not qdone: running_start+=1;
#if qjob.errored():
# print("error message:",qjob.error_message())
# running_cancelled = True
if qjob.done() :
# only get here once we get DONE status
result=qjob.result() # get the result
counts=result.get_counts(qcirc)
#print("counts:",counts)
maxpattern=max(counts,key=counts.get)
qubitpattern=maxpattern
maxvalue=counts[maxpattern]
print("Maximum value:",maxvalue, "Maximum pattern:",maxpattern)
if UseLocal:
sleep(3)
thinking = False # this cues the display thread to show the qubits in maxpattern
if running_timeout :
print(backend,' Queue appears to have stalled. Restarting Job.')
if running_cancelled :
print(backend,' Job cancelled at backend. Restarting.')
#except:
# print(Q.name, qjob.job_id(), 'problem; waiting to try again')
#else:
# print(p,'response to ping; waiting to try again')
#print("qubit list",qubits)
#write_svg_file(qubits,maxpattern, 2.5)
goAgain=False # wait to do it again
if Looping: print('Waiting ',interval,'s before next run...')
myTimer=process_time()
while not goAgain:
for event in hat.stick.get_events():
if event.action == 'pressed': #somebody tapped the joystick -- go now
goAgain=True
blinky(.001)
hat.set_pixels(pixels)
if DualDisplay: hat2.set_pixels(pixels)
if event.action == 'held' and event.direction =='middle':
shutdown=True
if event.action == 'held' and event.direction !='middle':
Looping = False
break
if (process_time()-myTimer>interval): # 10 seconds elapsed -- go now
goAgain=True
print("Program Execution ended normally")
|
https://github.com/kvillegas33/Heisenberg_model-Qiskit
|
kvillegas33
|
# Here we are importing all packages from qiskit
from qiskit import *
from qiskit.circuit import Parameter
from math import pi
# define the number of qubits
num_q = 3
theta = Parameter('θ')
# Here create the quantum circuit
qc = QuantumCircuit(num_q)
# Here we apply the Rz gate to the ith-qubit
for i in range(num_q):
qc.rz(theta,i)
# Here we draw the quantum circuit
qc.draw(output='mpl')
# define the number of qubits
num_q = 3
# Here create the quantum circuit with one qubit
qc = QuantumCircuit(num_q)
# Here we apply the Rz, Rx, and Ry gates to the ith-qubit
for i in range(num_q):
qc.rz(theta,i)
qc.ry(theta,i)
qc.rx(theta,i)
qc.barrier()
# Here we draw the quantum circuit
qc.draw(output='mpl')
# define the number of qubits
num_q = 5
# Here create the quantum circuit with one qubit
qc = QuantumCircuit(num_q)
phi = Parameter('φ')
# Here is the loop that applies the Rz, Rx, and Ry gates to the ith-qubit
for i in range(num_q):
qc.rz(theta,i)
qc.ry(theta,i)
qc.rx(theta,i)
# Here is the loop that applies the CNOTxRzxCNOT gates
for i in range(num_q-1):
qc.cx(i,i+1)
qc.rz(phi,i+1)
qc.cx(i,i+1)
qc.barrier()
# Here we draw the quantum circuit
qc.draw(output='mpl')
# define the number of qubits
num_q = 5
# Here create the quantum circuit with one qubit
qc = QuantumCircuit(num_q)
# Here is the loop that applies the Rz, Rx, and Ry gates to the ith-qubit
for i in range(num_q):
qc.rz(theta,i)
qc.ry(theta,i)
qc.rx(theta,i)
# Implementation of even interactions
for i in range(num_q-1):
if ((i%2)==0 and (i <= (num_q)-2)):
qc.cx(i,i+1)
qc.rz(phi,i+1)
qc.cx(i,i+1)
# Implementation of the odd interactions
for i in range(num_q-1):
if ((i%2)==1 and (i <= (num_q)-2)):
qc.cx(i,i+1)
qc.rz(phi,i+1)
qc.cx(i,i+1)
qc.barrier()
# Here we draw the quantum circuit
qc.draw(output='mpl')
# define the number of qubits
num_q = 5
# Here create the quantum circuit with one qubit
qc = QuantumCircuit(num_q)
# Here is the loop that applies the Rz, Rx, and Ry gates to the ith-qubit
for i in range(num_q):
qc.rz(theta,i)
qc.ry(theta,i)
qc.rx(theta,i)
qc.barrier()
# Implementation of even interactions
for i in range(num_q-1):
if ((i%2)==0 and (i <= (num_q)-2)):
qc.cx(i,i+1)
qc.rz(phi,i+1)
qc.cx(i,i+1)
qc.cx(i,i+1)
qc.ry(phi,i+1)
qc.cx(i,i+1)
qc.cx(i,i+1)
qc.rx(phi,i+1)
qc.cx(i,i+1)
qc.barrier()
# Implementation of the odd interactions
for i in range(num_q-1):
if ((i%2)==1 and (i <= (num_q)-2)):
qc.cx(i,i+1)
qc.rz(phi,i+1)
qc.cx(i,i+1)
qc.cx(i,i+1)
qc.ry(phi,i+1)
qc.cx(i,i+1)
qc.cx(i,i+1)
qc.rx(phi,i+1)
qc.cx(i,i+1)
qc.barrier()
# Here we draw the quantum circuit
qc.draw(output='mpl')
# define the number of qubits
num_q = 5
# Here create the quantum circuit with one qubit
qc = QuantumCircuit(num_q)
# Here is the loop that applies the Rz, Rx, and Ry gates to the ith-qubit
for i in range(num_q):
qc.rz(theta,i)
qc.ry(theta,i)
qc.rx(theta,i)
qc.barrier()
# Implementation of even interactions
for i in range(num_q-1):
if ((i%2)==0 and (i <= (num_q)-2)):
qc.rz(-pi/2,i+1)
qc.cx(i+1,i)
qc.rz(pi/2-phi,i)
qc.ry(phi-pi/2,i+1)
qc.cx(i,i+1)
qc.ry(pi/2-phi,i+1)
qc.cx(i+1,i)
qc.rz(pi/2,i)
qc.barrier()
# Implementation of the odd interactions
for i in range(num_q-1):
if ((i%2)==1 and (i <= (num_q)-2)):
qc.rz(-pi/2,i+1)
qc.cx(i+1,i)
qc.rz(pi/2-phi,i)
qc.ry(phi-pi/2,i+1)
qc.cx(i,i+1)
qc.ry(pi/2-phi,i+1)
qc.cx(i+1,i)
qc.rz(pi/2,i)
qc.barrier()
# Here we draw the quantum circuit
qc.draw(output='mpl')
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
import math
from typing import List, Union, Tuple
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit import Gate
from qiskit.circuit.library import RYGate, RZGate
from scipy import sparse
from scipy.sparse.linalg import norm
from dc_qiskit_algorithms import UniformRotationGate
from dc_qiskit_algorithms.MottonenStatePreparation import get_alpha_y, get_alpha_z, MottonenStatePreparationGate
def _chi(l):
return 1 + sum([2 ** (i - 1) for i in range(1, l)])
class ControlledStatePreparationGate(Gate):
_debug_flag: bool = False
def __init__(self, matrix: sparse.dok_matrix) -> None:
"""
The matrix has the following structure:
A = (a_ij)
with i being the control and j being the target. Also, each row must be normalized, i.e.,
\sum_j |a_ij|^2 = 1
The matrix is the quantum equivalent of a stochastic matrix therefore.
:param: matrix that has the columns as subspaces and rows as the states to create in them
"""
if isinstance(matrix, list) or isinstance(matrix, np.ndarray):
matrix = sparse.dok_matrix(matrix)
# The columns define the target states, i.e. the space for the controlled state preparation
num_targets_qb = int(math.ceil(math.log2(matrix.shape[1])))
self.num_targets_qb = num_targets_qb
# The rows define the number of control states. If there is one row, this is normal state preparation.
num_controls_qb = int(math.ceil(math.log2(matrix.shape[0])))
self.num_controls_qb = num_controls_qb
super().__init__("iso_matrix", num_qubits=num_controls_qb + num_targets_qb, params=[])
# Of course we save the matrix but we need to calculate the absolute value and the angle/phase
# matrix for the core logic
self.matrix: Union[sparse.dok_matrix] = matrix
matrix_abs = sparse.dok_matrix(matrix.shape)
matrix_angle = sparse.dok_matrix(matrix.shape)
for (i, j), v in self.matrix.items():
matrix_abs[i, j] = np.absolute(v)
matrix_angle[i, j] = np.angle(v)
self.matrix_abs = matrix_abs
self.matrix_angle = matrix_angle
def set_debug_flag(self, flag: bool = False) -> 'ControlledStatePreparationGate':
"""
If this is used, not the standard routine is used (Möttönen state preparation using uniform rotations)
but a manual form of several controlled rotations. This makes the plotting and therefore the debugging a lot
easier, at the expense of a lot of computational time and a strong increase of cx gates when later executed.
Therefore it is really only for debugging!
:param flag: false is the default, for true you get the multiple controlled rotations.
:return: None
"""
self._debug_flag = flag
return self
def _to_angle_matrix_y(self) -> Union[sparse.dok_matrix]:
# First, for each column, the angles that lead to this state need to be computed.
matrix_A = sparse.dok_matrix((self.matrix_abs.shape[0], self.matrix_abs.shape[1] - 1))
for row_no in range(self.matrix_abs.shape[0]):
amplitudes_row: sparse.csc_matrix = self.matrix_abs.getrow(row_no).T
# The reversed is necessary as the "highest" qubit is the one with the least controls
# imagine a circuit the where the highest qubits control the lower one. Yes this is all but numbering
# so that this is why I need to add this comment.
angle_row_list_y: List[sparse.dok_matrix] = [
get_alpha_y(amplitudes_row.todok(), self.num_targets_qb, k)
for k in reversed(range(1, self.num_targets_qb + 1))
]
angles_row = sparse.vstack(angle_row_list_y)
matrix_A[row_no, :] = angles_row.T
return matrix_A
def _to_angle_matrix_z(self) -> Tuple[sparse.spmatrix, sparse.spmatrix]:
# First, for each column, the angles that lead to this state need to be computed.
matrix_A = sparse.dok_matrix((self.matrix_angle.shape[0], self.matrix_angle.shape[1] - 1))
for row_no in range(self.matrix_angle.shape[0]):
amplitudes_row: sparse.csc_matrix = self.matrix_angle.getrow(row_no).T
# The reversed is necessary as the "highest" qubit is the one with the least controls
# imagine a circuit the where the highest qubits control the lower one. Yes this is all but numbering
# so that this is why I need to add this comment.
angle_row_list_z: List[sparse.dok_matrix] = [
get_alpha_z(amplitudes_row.todok(), self.num_targets_qb, k)
for k in reversed(range(1, self.num_targets_qb + 1))
]
angles_row = sparse.vstack(angle_row_list_z)
matrix_A[row_no, :] = angles_row.T
# A global phase is to be expected on each subspace and must be corrected jointly later.
total_depth = max(1, int(np.ceil(np.log2(matrix_A.shape[1]))))
recovered_angles = sparse.dok_matrix((matrix_A.shape[0], 1), dtype=float)
# Each row is a separate sub-space, and by the algorithm of Möttönen et al
# a global phase is to be expected. So we calculate it by...
for row in range(matrix_A.shape[0]):
# ... going through each row and applying rz rotations essentially, but not on all
# involved qubits, just for one branch as the global phase must exist, well, globally.
col = 0
evaluation = 1
for depth in range(total_depth):
evaluation *= np.exp(-0.5j * matrix_A[row, col])
col += 2**depth
# After calculating the amplitude of one branch, I take the angle/phase
# This is still not the global phase, we will get that later...
recovered_angles[row, 0] = np.angle(evaluation)
# ... exactly here we take the difference of the phase of each subspace and the angle
# matrix. That is the global phase of that subspace!
global_phases: sparse.spmatrix = self.matrix_angle[:, 0] - recovered_angles
return matrix_A, global_phases
def _define(self):
# The y angle matrix stands for the absolute value, while the z angles stand for phases
# The difficulty lies in the "global" phases that must be later accounted for in each subspace
y_angle_matrix = self._to_angle_matrix_y()
z_angle_matrix, global_phases = self._to_angle_matrix_z()
if self._debug_flag:
qc_y, qc_z = self._create_debug_circuit(y_angle_matrix, z_angle_matrix, global_phases)
else:
qc_y, qc_z = self._create_production_circuit(y_angle_matrix, z_angle_matrix, global_phases)
qc = qc_y & qc_z
self._definition = qc
def _create_production_circuit(self, y_angle_matrix, z_angle_matrix, global_phases):
# As the subspace phase correction is a very expensive module, we only want to do it if the
# z rotation matrix is non-zero!
no_z_rotations = abs(sparse.linalg.norm(z_angle_matrix)) < 1e-6
control = QuantumRegister(self.num_controls_qb, "q^c")
target = QuantumRegister(self.num_targets_qb, "q^t")
qc_y = QuantumCircuit(control, target, name=self.name)
qc_z = QuantumCircuit(control, target, name=self.name)
# We do a set of uniformly controlled operations from the control register on each target qubit.
# iterating through the target means that a target qubit that has been handled (i.e. was a target of a
# uniform rotation) becomes a controlling qubit.
# Thus, when creating the qargs for the operation, there are going to be all qubits of the control register
# plus those target register qubits that have been used plus the current target qubit as the target
# of the uniform rotation
for l in range(1, self.num_targets_qb + 1):
# Using slicing to get the correct target register qubits, start at the last, go to the (l+1) last.
# The ordering of the qubits in the register is a bit weird... explanation:
# ctr = [ctr0, ctr1, ctr2, ctr3], tgt = tgt0, tgt1, tgt2, tgt3
# l = 2: qargs = [ctr0, ctr1, ctr2, ctr,3, tgt3, tgt2]
# ^==> target of operation
# the Möttönen et al. scheme uses the idea to move a ket |a> to |0> via U. The inverse of this operation
# thus will take |0> to the desired state |a>. The first step of constructing U is to cancel the first qubit
# (tgt0) to be only having the ground state contributing in a product state, this is controlled
# by [tgt1, tgt2, tgt3]. Then (tgt1) is targeted (controls [tgt2, tgt3]) until (tgt3) is reached
# (no control). This is inverted, thus first (tgt3) until (tgt0) with corresponding controls.
qargs = list(control) + target[-1:-1-l:-1]
# If there are no z-rotations we save a lot of gates, so we want to rule that out
if not no_z_rotations:
# The corresponding rotational angles are given in the Z-angle matrix by the function chi selecting
# on the columns according to the operational parameter l.
angles_z: sparse.spmatrix = z_angle_matrix[:, range(_chi(l) - 1, _chi(l + 1) - 1)]
# The column-first Fortran-style reshaping to create one angle vector
angles_z = angles_z.reshape(-1, 1, order='F')
# The negative of the angles is needed to implement the inverse (as described above)
gate_z = UniformRotationGate(gate=lambda a: RZGate(a), alpha=angles_z.todok()) # FIXME: removing the -
qc_z.append(gate_z, qargs)
# The uniform rotation for the y rotation will take care of the absolute value
# The corresponding rotational angles are given in the Z-angle matrix by the function chi selecting
# on the columns according to the operational parameter l.
angles_y: sparse.spmatrix = y_angle_matrix[:, range(_chi(l) - 1, _chi(l + 1) - 1)]
# The column-first Fortran-style reshaping to create one angle vector
angles_y = angles_y.reshape(-1, 1, order='F')
# The negative of the angles is needed to implement the inverse (as described above)
gate_y = UniformRotationGate(gate=lambda a: RYGate(a), alpha=angles_y.todok()) # FIXME: removing the -
qc_y.append(gate_y, qargs)
if not no_z_rotations:
# A relative phase correction is pretty intensive: a state preparation on the control
global_phase_correction = MottonenStatePreparationGate(
sparse.dok_matrix(np.exp(1.0j * global_phases.toarray())),
neglect_absolute_value=True
)
qc_z.append(global_phase_correction, qargs=control)
return qc_y, qc_z
def _create_debug_circuit(self, y_angle_matrix, z_angle_matrix, global_phases):
# As the subspace phase correction is a very expensive module, we only want to do it if the
# z rotation matrix is non-zero!
no_z_rotations = abs(sparse.linalg.norm(z_angle_matrix)) < 1e-6
control = QuantumRegister(self.num_controls_qb, "q^c")
target = QuantumRegister(self.num_targets_qb, "q^t")
qc_y = QuantumCircuit(control, target, name=self.name)
qc_z = QuantumCircuit(control, target, name=self.name)
for row in range(y_angle_matrix.shape[0]):
qc_y_row = QuantumCircuit(control, target, name=self.name)
for (_, j), angle in y_angle_matrix.getrow(row).todok().items():
num_extra_control = int(np.floor(np.log2(j + 1)))
num_control = len(control) + num_extra_control
val_control = row + 2 ** len(control) * int(j - (2 ** num_extra_control - 1))
gate = RYGate(angle).control(num_ctrl_qubits=num_control, ctrl_state=val_control)
qargs = list(control) + target[-1:-2 - j:-1]
qc_y_row.append(gate, qargs)
qc_y &= qc_y_row
if not no_z_rotations:
for row in range(z_angle_matrix.shape[0]):
for (_, j), angle in z_angle_matrix.getrow(row).todok().items():
num_extra_control = int(np.floor(np.log2(j + 1)))
num_control = len(control) + num_extra_control
val_control = row + 2 ** len(control) * int(j - (2 ** num_extra_control - 1))
gate = RZGate(angle).control(num_ctrl_qubits=num_control, ctrl_state=val_control)
qargs = list(control) + target[-1:-2 - j:-1]
qc_z.append(gate, qargs)
if not no_z_rotations:
# A relative phase correction is pretty intensive: a state preparation on the control
global_phase_correction = MottonenStatePreparationGate(
sparse.dok_matrix(np.exp(1.0j * global_phases.toarray())),
neglect_absolute_value=True
)
qc_z.append(global_phase_correction, qargs=control)
qc_y.barrier()
qc_z.barrier()
return qc_y, qc_z
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional, Tuple, List, Union
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit import Gate, Instruction, Qubit, InstructionSet
from qiskit.extensions import XGate, CU1Gate
from dc_qiskit_algorithms.Qft import QuantumFourierTransformGate
from . import Qft as qft
class DraperAdderGate(Gate):
def __init__(self, input_a, input_b, length=None):
"""
The Draper adder (arXiv:quant-ph/0008033), provide a and b and make sure to define a size of
a register that can hold a or b
:param input_a: integer a
:param input_b: integer b
:param length: size of qubit registers
:return: tuple of the circuit and the length of the register
"""
a_01s = "{0:b}".format(input_a)
b_01s = "{0:b}".format(input_b)
length = DraperAdderGate.compute_length(input_a, input_b, length)
a_01s = a_01s.zfill(length)
b_01s = b_01s.zfill(length)
super().__init__("add_draper", num_qubits=2*length, params=[input_a, input_b])
self.a_01s = a_01s
self.b_01s = b_01s
def _define(self):
q = QuantumRegister(len(self.a_01s) + len(self.b_01s), "q")
qc = QuantumCircuit(q, name=self.name)
a = q[0:len(self.a_01s)]
b = q[len(self.a_01s):]
for i, c in enumerate(self.a_01s):
if c == '1':
qc.append(XGate(), [a[i]], [])
for i, c in enumerate(self.b_01s):
if c == '1':
qc.append(XGate(), [b[i]], [])
qc.append(QuantumFourierTransformGate(len(a)), a, [])
for b_index in reversed(range(len(b))):
theta_index = 1
for a_index in reversed(range(b_index + 1)):
qc.append(CU1Gate(qft.get_theta(theta_index)), [b[b_index], a[a_index]], [])
theta_index += 1
qc.append(QuantumFourierTransformGate(len(a)).inverse(), a, [])
self.definition = qc
def inverse(self):
return super().inverse()
@staticmethod
def compute_length(input_a, input_b, length=None):
a_01s = "{0:b}".format(input_a)
b_01s = "{0:b}".format(input_b)
length = max(len(a_01s), len(b_01s), length if length is not None else 0)
return length
def add_draper(self, input_a, input_b, qubits, length=None):
# type: (QuantumCircuit, int, int, Union[QuantumRegister, List[Qubit]], Optional[int]) -> InstructionSet
if isinstance(qubits, QuantumRegister):
qubits = list(qubits)
return self.append(DraperAdderGate(input_a, input_b, length), qubits, [])
QuantumCircuit.add_draper = add_draper
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
from typing import List, Union
from bitstring import BitArray
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Qubit
from .UniformRotation import cnry
class FFQramEntry(object):
"""
An DB entry of the FF QRAM scheme
"""
def __init__(self):
"""
Creates an entry with binary data & label as well as an (optional) amplitude
"""
self.probability_amplitude = 0.0 # type: float
self.data = bytes() # type: bytes
self.label = bytes() # type: bytes
def get_bits(self, bin_length=None):
# type: (FFQramEntry) -> str
"""
Get the binary bit representation of data and label
for state basis identification
:return: a bit array
"""
b = self.data + self.label
ba = BitArray(b)
ba = ba.bin.lstrip('0')
ba = ba.zfill(bin_length) if bin_length is not None else ba
return ba
def bus_size(self):
# type: (FFQramEntry) -> int
"""
Returns needed bus size for this entry
:return: the length
"""
return len(self.get_bits(1))
def add_to_circuit(self, qc, bus, register):
# type: (FFQramEntry, QuantumCircuit, Union[QuantumRegister, list], Qubit) -> QuantumCircuit
"""
This method adds the gates to encode this entry into the circuit
:param qc: quantum circuit to apply the entry to
:param bus: the registers for the bus
:param register: the target register for the amplitude
:return: the applied circuit
"""
theta = math.asin(self.probability_amplitude)
if theta == 0:
return qc
bus_register = [] # type: List[Qubit]
if isinstance(bus, QuantumRegister):
bus_register = list(bus)
else:
bus_register = bus
ba = self.get_bits(len(bus_register))
for i, b in enumerate(reversed(ba)):
if b == "0":
qc.x(bus_register[i])
cnry(qc, theta, bus_register, register)
for i, b in enumerate(reversed(ba)):
if b == "0":
qc.x(bus_register[i])
return qc
def __str__(self):
return "FFQramEntry(%.8f, %s)" % (self.probability_amplitude, self.get_bits().bin)
@staticmethod
def _count_set_bits(b):
# type: (bytes) -> int
"""
Returns the number of ones in the byte array
:param b: the data
:return: the count
"""
raise DeprecationWarning("This method is as it stands not functional... there is no way to reconcile this.")
class FFQramDb(List[FFQramEntry]):
"""
The DB object with methods to create circuits
"""
def bus_size(self):
# type: (FFQramDb) -> int
"""
From all entries get the maximum needed bus size
:return: the bus size for the DB
"""
return max([e.bus_size() for e in self])
def add_to_circuit(self, qc, bus, register):
# type: (FFQramDb, QuantumCircuit, Union[QuantumRegister, List[Qubit]], Qubit) -> None
"""
Add the DB to the circuit.
:param qc: the quantum circuit
:param bus: the bus register
:param register: the target register for the amplitudes
:return: the circuit after DB being applied
"""
for entry in self:
entry.add_to_circuit(qc, bus, register)
def add_entry(self, pa, data, label):
# type: (FFQramDb, float, bytes, bytes) -> None
"""
Add an entry to the (classical representation of) the DB.
:param pa: probability amplitude
:param data: binary representation of data
:param label: binary representation of the label
"""
entry = FFQramEntry()
entry.probability_amplitude = pa
entry.data = data
entry.label = label
self.append(entry)
def add_entry_int(self, pa, data, label):
# type: (FFQramDb, float, int, int) -> None
"""
Add an entry to the (classical representation of) the DB.
:param pa: probability amplitude
:param data: the integer value of the data
:param label: the integer value of the label
"""
raise DeprecationWarning("This method is as it stands not functional... there is no way to reconcile this.")
def add_vector(db, vec):
# type: (FFQramDb, List[complex]) -> None
"""
Add a vector to the DB. It makes sense to give an empty DB.
:param db: The FFQRAM DB
:param vec: the vector to be added
"""
import numpy as np
vector = np.asarray(vec)
l2_norm = np.linalg.norm(vector)
unit_vector = vector / l2_norm
number_of_bytes = int(np.ceil(np.log2(len(vector))) // 8 + 1)
for i, v in enumerate(unit_vector):
if abs(v) > 1e-6:
label_as_bytes = (i).to_bytes(number_of_bytes, byteorder='big')
db.add_entry(v, b'', label_as_bytes)
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
from typing import List, Union
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Gate, Instruction, Qubit
from qiskit.extensions import RYGate, RZGate
from scipy import sparse
from scipy.sparse.linalg import norm
from .UniformRotation import UniformRotationGate
def get_alpha_z(omega, n, k):
# type: (sparse.dok_matrix, int, int) -> sparse.dok_matrix
"""
Computes the rotation angles alpha for the z-rotations
:param omega: the input phase
:param n: total number of qubits
:param k: current qubit
:return: a sparse vector
"""
alpha_z_k = sparse.dok_matrix((2 ** (n - k), 1), dtype=np.float64)
for (i, _), om in omega.items():
i += 1
j = int(np.ceil(i * 2 ** (-k)))
s_condition = 2 ** (k - 1) * (2 * j - 1)
s_i = 1.0 if i > s_condition else -1.0
alpha_z_k[j - 1, 0] = alpha_z_k[j - 1, 0] + s_i * om / 2 ** (k - 1)
return alpha_z_k
def get_alpha_y(a, n, k):
# type: (sparse.dok_matrix, int, int) -> sparse.dok_matrix
"""
Computes the rotation angles alpha for the y-rotations
:param a: the input absolute values
:param n: total number of qubits
:param k: current qubit
:return: a sparse vector
"""
alpha = sparse.dok_matrix((2**(n - k), 1), dtype=np.float64)
numerator = sparse.dok_matrix((2 ** (n - k), 1), dtype=np.float64)
denominator = sparse.dok_matrix((2 ** (n - k), 1), dtype=np.float64)
for (i, _), e in a.items():
j = int(math.ceil((i + 1) / 2**k))
l = (i + 1) - (2*j - 1)*2**(k-1)
is_part_numerator = 1 <= l <= 2**(k-1)
if is_part_numerator:
numerator[j - 1, 0] += e*e
denominator[j - 1, 0] += e*e
for (j, _), e in numerator.items():
numerator[j, 0] = np.sqrt(e)
for (j, _), e in denominator.items():
denominator[j, 0] = 1/np.sqrt(e)
pre_alpha = numerator.multiply(denominator) # type: sparse.csr_matrix
for (j, _), e in pre_alpha.todok().items():
alpha[j, 0] = 2*np.arcsin(e)
return alpha
class RZGateNegatedAngle(RZGate):
def __init__(self, phi):
super().__init__(-phi)
class RYGateNegatedAngle(RYGate):
def __init__(self, phi):
super().__init__(-phi)
# noinspection NonAsciiCharacters
class MottonenStatePreparationGate(Gate):
"""Uniform rotation Y gate (Möttönen)."""
def __init__(self, vector, neglect_absolute_value=False):
# type: (Union[sparse.dok_matrix, List[complex], List[float]], bool) -> None
"""
Create the composite gate for the Möttönen state preparation scheme with an input vector, which registers/qubits
to apply it to, and the circuit (if any)
:param vector: the input complex sparse vector
:param neglect_absolute_value: When given a vector, the absolute value is neglected which means that only the
phase/angle is applied (RZ rotations)
"""
if isinstance(vector, list):
vector = sparse.dok_matrix([vector]).transpose()
self.neglect_absolute_value = neglect_absolute_value
num_qubits = int(math.log2(vector.shape[0]))
vector_str = ",".join([f'{v:.2f}' for v in vector.toarray()[:, 0]])
label = f'state({vector_str})' if len(vector) <= 16 else None
super().__init__("state_prep_möttönen", num_qubits=num_qubits, params=[], label=label)
self.vector = vector # type: sparse.dok_matrix
def _define(self):
a = sparse.dok_matrix(self.vector.get_shape()) # type: sparse.dok_matrix
omega = sparse.dok_matrix(self.vector.get_shape()) # type: sparse.dok_matrix
for (i, j), v in self.vector.items():
a[i, j] = np.absolute(v)
omega[i, j] = np.angle(v)
# As the subspace phase correction is a very expensive module, we only want to do it if the
# z rotation matrix is non-zero!
no_z_rotations = abs(norm(omega)) < 1e-3
q = QuantumRegister(self.num_qubits, "qubits")
qc: QuantumCircuit = QuantumCircuit(q, name=self.name)
if not no_z_rotations:
qc_rot_z = self.apply_rot_z(omega, q)
qc = qc.compose(qc_rot_z)
if not self.neglect_absolute_value:
qc_rot_y = self.apply_rot_y(a, q)
qc = qc.compose(qc_rot_y)
self._definition = qc.inverse()
@staticmethod
def apply_rot_y(a, qreg):
# type: (sparse.dok_matrix, QuantumRegister) -> QuantumCircuit
"""
Applies the cascade of y-uniform rotations to the qubits
:param a: the sparse absolute value vector
:param qreg: quantum register to which the scheme are applied
:return: None
"""
qc = QuantumCircuit(qreg, name='apply_rot_y') # type: QuantumCircuit
num_qubits = int(math.log2(a.shape[0]))
for k in range(1, num_qubits + 1):
alpha_y_k = get_alpha_y(a, num_qubits, k) # type: sparse.dok_matrix
control = qreg[k:]
target = qreg[k - 1]
qc.append(UniformRotationGate(gate=RYGateNegatedAngle, alpha=alpha_y_k), control + [target], [])
return qc
@staticmethod
def apply_rot_z(omega, qreg):
# type: (sparse.dok_matrix, QuantumRegister) -> QuantumCircuit
"""
Applies the cascade of z-uniform rotations to the qubits
:param omega: the sparse phase vector
:param qreg: quantum register to which the scheme are applied
:return: None
"""
qc = QuantumCircuit(qreg, name='apply_rot_z') # type: QuantumCircuit
num_qubits = int(math.log2(omega.shape[0]))
for k in range(1, num_qubits + 1):
alpha_z_k = get_alpha_z(omega, num_qubits, k)
control = qreg[k:]
target = qreg[k - 1]
# if len(alpha_z_k) != 0:
qc.append(UniformRotationGate(gate=RZGateNegatedAngle, alpha=alpha_z_k), control + [target], [])
return qc
# noinspection NonAsciiCharacters
def state_prep_möttönen(self, a, qubits):
# type: (QuantumCircuit, Union[List[float], sparse.dok_matrix], Union[List[Qubit], QuantumRegister]) -> Instruction
"""
Convenience function to encapsulate the composite gate of the state preparation
:param self: Quantum circuit to apply this to
:param a: the input vector
:param qubits: the qubits to be transformed
:return: gate just added
"""
if isinstance(qubits, QuantumRegister):
qubits = list(qubits)
if isinstance(a, sparse.dok_matrix):
return self.append(MottonenStatePreparationGate(a), qubits, [])
else:
return self.append(MottonenStatePreparationGate(sparse.dok_matrix([a]).transpose()), qubits)
# noinspection NonAsciiCharacters
def state_prep_möttönen_dg(self, a, qubits):
# type: (QuantumCircuit, Union[List[float], sparse.dok_matrix], Union[List[Qubit], QuantumRegister]) -> Instruction
"""
Convenience function to encapsulate the composite gate of the dagger of the state preparation
:param self: Composite Gate or Quantum circuit to apply this to
:param a: the input vector
:param qubits: the qubits to be transformed
:return: gate or instruction set
"""
return state_prep_möttönen(self, a, qubits).inverse()
# noinspection NonAsciiCharacters
QuantumCircuit.state_prep_möttönen = state_prep_möttönen
# noinspection NonAsciiCharacters
QuantumCircuit.state_prep_möttönen_dg = state_prep_möttönen_dg
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
This module contains the definition of a base class for quantum fourier transforms.
"""
from abc import abstractmethod
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import Pluggable, AquaError
class QFT(Pluggable):
"""Base class for QFT.
This method should initialize the module and its configuration, and
use an exception if a component of the module is
available.
Args:
configuration (dict): configuration dictionary
"""
@abstractmethod
def __init__(self, *args, **kwargs):
super().__init__()
@classmethod
def init_params(cls, params):
qft_params = params.get(Pluggable.SECTION_KEY_QFT)
kwargs = {k: v for k, v in qft_params.items() if k != 'name'}
return cls(**kwargs)
@abstractmethod
def _build_matrix(self):
raise NotImplementedError
@abstractmethod
def _build_circuit(self, qubits=None, circuit=None, do_swaps=True):
raise NotImplementedError
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True):
"""Construct the circuit.
Args:
mode (str): 'matrix' or 'circuit'
qubits (QuantumRegister or qubits): register or qubits to build the circuit on.
circuit (QuantumCircuit): circuit for construction.
do_swaps (bool): include the swaps.
Returns:
The matrix or circuit depending on the specified mode.
"""
if mode == 'circuit':
return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps)
elif mode == 'matrix':
return self._build_matrix()
else:
raise AquaError('Unrecognized mode: {}.'.format(mode))
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from itertools import tee
from typing import List, Tuple, Union, Callable, Iterable
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Gate, Instruction, Qubit, Clbit, InstructionSet
from qiskit.extensions import HGate, RZGate, RYGate, CXGate
from scipy import sparse
log = logging.getLogger('UniformRotation')
# noinspection PyPep8Naming
def binary_codes(number_qubits):
# type: (int) -> List[int]
"""
Convenience function to get a list of numbers from 0 to 2**number_qubits - 1
:param number_qubits: exponent
:return: list of numbers
"""
N = int(2**number_qubits)
return list(range(N))
def gray_code(number):
# type: (int) -> int
"""
Cyclic Gray Code of number
:param number: input number
:return: Gray Code
"""
return (number >> 1) ^ number
# noinspection PyPep8Naming
def matrix_M_entry(row, col):
# type: (int, int) -> float
"""
The matrix for the angle computation
:param row: row number (one based!)
:param col: column number (one based!)
:return: matrix entry
"""
b_and_g = row & gray_code(col)
sum_of_ones = 0
while b_and_g > 0:
if b_and_g & 0b1:
sum_of_ones += 1
b_and_g = b_and_g >> 1
return (-1)**sum_of_ones
def compute_theta(alpha):
# type: (sparse.dok_matrix) -> sparse.dok_matrix
"""
Compute the rotational angles from alpha
:param alpha: the input uniform rotation angles
:return: the single qubit rotation angles
"""
k = np.log2(alpha.shape[0])
factor = 2**(-k)
theta = sparse.dok_matrix(alpha.shape, dtype=np.float64) # type: sparse.dok_matrix
for row in range(alpha.shape[0]):
# Use transpose of M:
entry = sum([matrix_M_entry(col, row) * a for (col, _), a in alpha.items()])
entry *= factor
if abs(entry) > 1e-6:
theta[row, 0] = entry
return theta
def pairwise(iterable):
# type: (Iterable) -> Iterable[Tuple]
"""
Calculates pairwise consecutive pairs of an iterable
s -> (s0,s1), (s1,s2), (s2, s3), ...
:param iterable: any iterable
:return: an iterable of tuples
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
class UniformRotationGate(Gate):
"""Uniform rotation gate (Möttönen)."""
def __init__(self, gate, alpha):
# type: (Callable[[float], Gate], sparse.dok_matrix) -> None
"""
Create new uniform rotation gate.
:param gate: A single qubit rotation gate (typically rx, ry, rz)
:param alpha: The conditional rotation angles
"""
number_of_control_qubits = int(np.ceil(np.log2(alpha.shape[0])))
vector_str = ",".join([f'{v:.2f}' for v in alpha.toarray()[:, 0]])
label = f'uni_rot_{gate(0).name}({vector_str})' if len(alpha) <= 16 else None
super().__init__(f'uni_rot_{gate(0).name}', num_qubits=number_of_control_qubits + 1, params=[], label=label)
self.alpha = alpha # type: sparse.dok_matrix
self.gate = gate # type: Callable[[float], Gate]
def _define(self):
q = QuantumRegister(self.num_qubits, "q")
qc = QuantumCircuit(q, name=self.name)
theta = compute_theta(self.alpha) # type: sparse.dok_matrix
gray_code_rank = self.num_qubits - 1
if gray_code_rank == 0:
qc.append(self.gate(theta[0, 0]), [q[0]], [])
else:
from sympy.combinatorics.graycode import GrayCode
gc = GrayCode(gray_code_rank) # type: GrayCode
current_gray = gc.current
for i in range(gc.selections):
qc.append(self.gate(theta[i, 0]), [q[-1]], [])
next_gray = gc.next(i + 1).current
control_index = int(np.log2(int(current_gray, 2) ^ int(next_gray, 2)))
qc.append(CXGate(), [q[control_index], q[-1]], [])
current_gray = next_gray
self._definition = qc
def uni_rot(self, rotation_gate, alpha, control_qubits, tgt):
# type: (QuantumCircuit, Callable[[float], Gate], Union[List[float], sparse.dok_matrix], Union[List[Qubit],QuantumRegister], Union[Qubit, QuantumRegister]) -> InstructionSet
"""
Apply a generic uniform rotation with rotation gate.
:param self: either a composite gate or a circuit
:param rotation_gate: A single qubit rotation gate
:param alpha: conditional rotation angles
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
if not isinstance(alpha, sparse.dok_matrix):
alpha = sparse.dok_matrix([alpha]).transpose()
if isinstance(tgt, QuantumRegister):
tgt = tgt[0]
if isinstance(control_qubits, QuantumRegister):
control_qubits = list(control_qubits)
return self.append(UniformRotationGate(rotation_gate, alpha), control_qubits + [tgt], [])
def uni_rot_dg(self, rotation_gate, alpha, control_qubits, tgt):
# type: (QuantumCircuit, Callable[[float], Gate], Union[List[float], sparse.dok_matrix], Union[List[Qubit],QuantumRegister], Union[Qubit, QuantumRegister]) -> Instruction
"""
Apply the dagger (inverse) of a generic uniform rotation with rotation gate.
:param self: either a composite gate or a circuit
:param rotation_gate: A single qubit rotation gate
:param alpha: conditional rotation angles
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
return uni_rot(self, rotation_gate, alpha, control_qubits, tgt).inverse()
def unirz(self, alpha, control_qubits, tgt):
# type: (QuantumCircuit, Union[List[float], sparse.dok_matrix], Union[List[Qubit],QuantumRegister], Union[Qubit, QuantumRegister]) -> InstructionSet
"""
Apply a uniform rotation around z.
:param self: either a composite gate or a circuit
:param alpha: conditional rotation angles
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
return uni_rot(self, RZGate, alpha, control_qubits, tgt)
def unirz_dg(self, alpha, control_qubits, tgt):
# type: (QuantumCircuit, Union[List[float], sparse.dok_matrix], Union[List[Qubit],QuantumRegister], Union[Qubit, QuantumRegister]) -> Instruction
"""
Apply dagger (inverse) of a uniform rotation around z.
:param self: either a composite gate or a circuit
:param alpha: conditional rotation angles
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
return unirz(self, alpha, control_qubits, tgt).inverse()
def uniry(self, alpha, control_qubits, tgt):
# type: (QuantumCircuit, Union[List[float], sparse.dok_matrix], Union[List[Qubit],QuantumRegister], Union[Qubit, QuantumRegister]) -> InstructionSet
"""
Apply a uniform rotation around y.
:param self: either a composite gate or a circuit
:param alpha: conditional rotation angles
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
return uni_rot(self, RYGate, alpha, control_qubits, tgt)
def uniry_dg(self, alpha, control_qubits, tgt):
# type: (QuantumCircuit, Union[List[float], sparse.dok_matrix], Union[List[Qubit],QuantumRegister], Union[Qubit, QuantumRegister]) -> Instruction
"""
Apply the dagger (inverse) of a uniform rotation around y.
:param self: either a composite gate or a circuit
:param alpha: conditional rotation angles
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
return uniry(self, alpha, control_qubits, tgt).inverse()
def cnry(self, theta, control_qubits, tgt):
# type: (QuantumCircuit, float, Union[List[Qubit],QuantumRegister], Union[Qubit, QuantumRegister]) -> InstructionSet
"""
Apply a multiple controlled y rotation on the target qubit.
:param self: either a composite gate or a circuit
:param theta: rotation angle
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
length = 2**len(control_qubits)
alpha = sparse.dok_matrix((length, 1), dtype=np.float64)
alpha[-1] = theta
return uniry(self, alpha, control_qubits, tgt)
def cnry_dg(self, theta, control_qubits, tgt):
# type: (QuantumCircuit, float, Union[List[Qubit],QuantumRegister], Union[Qubit, QuantumRegister]) -> Instruction
"""
Apply the dagger (inverse) of a multiple controlled y rotation on the target qubit.
:param self: either a composite gate or a circuit
:param theta: rotation angle
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
return cnry(self, theta, control_qubits, tgt).inverse()
class MultiControlledXGate(Gate):
"""Multi-Controlled X-Gate (via Möttönen)."""
def __init__(self, conditional_case, control_qubits):
# type: (int, int) -> None
"""
Create a new multi-controlled X gate according to the conditional (binary) case
:param conditional_case: binary representation of 0/1 control case
:param control_qubits: control qubits
"""
super().__init__("ccx_uni_rot", params=[conditional_case], num_qubits=control_qubits + 1)
self.conditional_case = conditional_case
self.control_qubits = control_qubits
def _define(self):
q = QuantumRegister(self.num_qubits, "q")
qc = QuantumCircuit(q, name=self.name)
length = 2 ** self.control_qubits
alpha = sparse.dok_matrix((length, 1), dtype=np.float64)
alpha[self.conditional_case] = np.pi
qc.append(HGate(), [q[-1]], [])
qc.append(UniformRotationGate(RYGate, alpha), list(q), [])
qc.append(HGate(), [q[-1]], [])
self.definition = qc
def ccx_uni_rot(self, conditional_case, control_qubits, tgt):
# type: (QuantumCircuit, int, Union[List[Qubit], QuantumRegister], Union[Qubit, QuantumRegister]) -> Instruction
"""
Apply a multi-controlled X gate depending on conditional binary representation
:param self: either a composite gate or a circuit
:param conditional_case: the controlled case (1 or 0) in binary
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
if isinstance(tgt, QuantumRegister):
tgt = tgt[0]
if isinstance(control_qubits, QuantumRegister):
control_qubits = list(control_qubits)
return self.append(MultiControlledXGate(conditional_case, len(control_qubits)), control_qubits + [tgt])
def ccx_uni_rot_dg(self, conditional_case, control_qubits, tgt):
# type: (QuantumCircuit, int, Union[List[Qubit],QuantumRegister], Union[Qubit, QuantumRegister]) -> Instruction
"""
Apply the dagger (inverse) a multi-controlled X gate depending on conditional binary representation
:param self: either a composite gate or a circuit
:param conditional_case: the controlled case (1 or 0) in binary
:param control_qubits: control qubits
:param tgt: target
:return: applied composite gate or circuit
"""
return ccx_uni_rot(self, conditional_case, control_qubits, tgt).inverse()
QuantumCircuit.uniry = uniry
QuantumCircuit.uniry_dg = uniry_dg
QuantumCircuit.unirz = unirz
QuantumCircuit.unirz_dg = unirz_dg
QuantumCircuit.cnry = cnry
QuantumCircuit.cnry_dg = cnry_dg
QuantumCircuit.ccx_uni_rot = ccx_uni_rot
QuantumCircuit.ccx_uni_rot_dg = ccx_uni_rot_dg
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2021 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import unittest
import numpy as np
import qiskit
from ddt import ddt, data as test_data, unpack
from qiskit import QuantumRegister, QuantumCircuit
from qiskit_aer import AerJob
from qiskit_aer.backends.aerbackend import AerBackend
from qiskit.result import Result
from scipy import sparse
from scipy.sparse import linalg
from dc_qiskit_algorithms.ControlledStatePreparation import ControlledStatePreparationGate
logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
@ddt
class AngleMatrixYTests(unittest.TestCase):
@unpack
@test_data(
{'matrix': np.sqrt([
[0.1, 0.2, 0.3, 0.4],
[0.25, 0.25, 0.25, 0.25]
])}
)
def test_angle_matrix_y(self, matrix):
matrix = sparse.dok_matrix(matrix)
abs_matrix = np.abs(matrix)
log.info("Input Matrix (Y):\n" + str(abs_matrix))
iso_gate = ControlledStatePreparationGate(matrix)
angle_matrix = iso_gate._to_angle_matrix_y()
log.info("Final Angle Matrix (Y):\n" + str(angle_matrix.todense()))
# The recovery is done by using a pre factor of 1/2 given the definition of the R_y gate
matrix_recovered = sparse.dok_matrix(matrix.shape)
for row in range(angle_matrix.shape[0]):
matrix_recovered[row, 0] = np.cos(0.5 * angle_matrix[row, 0]) * np.cos(0.5 * angle_matrix[row, 1])
matrix_recovered[row, 1] = np.cos(0.5 * angle_matrix[row, 0]) * np.sin(0.5 * angle_matrix[row, 1])
matrix_recovered[row, 2] = np.sin(0.5 * angle_matrix[row, 0]) * np.cos(0.5 * angle_matrix[row, 2])
matrix_recovered[row, 3] = np.sin(0.5 * angle_matrix[row, 0]) * np.sin(0.5 * angle_matrix[row, 2])
log.info("Recovered Matrix (Y):\n" + str(matrix_recovered.todense()))
self.assertAlmostEqual(linalg.norm(abs_matrix - matrix_recovered), 0.0, delta=1e-13)
@ddt
class AngleMatrixZTests(unittest.TestCase):
@unpack
@test_data(
{
'matrix': np.sqrt([
[-0.25 + 0j, +0.25 + 0j, -0.25 + 0j, +0.25 + 0j],
[+0.25 + 0j, +0.25 + 0j, +0.25 + 0j, +0.25 + 0j]
])
},
{
'matrix': np.sqrt([
[+0.50 + 0j, +0.30 + 0j, +0.20 + 0j, +0.00 + 0j],
[+0.50 + 0j, -0.25 + 0j, +0.25 + 0j, +0.25 + 0j]
])
}
)
def test_angle_matrix_z(self, matrix):
phase_matrix = np.angle(matrix)
matrix = sparse.dok_matrix(matrix)
log.info("Input Phase Matrix (Z):\n" + str(phase_matrix))
iso_gate = ControlledStatePreparationGate(matrix)
angle_matrix, global_phase = iso_gate._to_angle_matrix_z()
angle_matrix = sparse.hstack([global_phase, angle_matrix]).todok()
log.info("Final Angle Matrix (Z):\n" + str(angle_matrix.todense()))
# The recovery is done by using a pre factor of 1/2 given the definition of the R_y gate
matrix_recovered = sparse.dok_matrix(matrix.shape)
for row in range(angle_matrix.shape[0]):
matrix_recovered[row, 0] = np.angle(np.exp(1.0j * angle_matrix[row, 0]) * np.exp(-0.5j * angle_matrix[row, 1]) * np.exp(-0.5j * angle_matrix[row, 2]))
matrix_recovered[row, 1] = np.angle(np.exp(1.0j * angle_matrix[row, 0]) * np.exp(-0.5j * angle_matrix[row, 1]) * np.exp(+0.5j * angle_matrix[row, 2]))
matrix_recovered[row, 2] = np.angle(np.exp(1.0j * angle_matrix[row, 0]) * np.exp(+0.5j * angle_matrix[row, 1]) * np.exp(-0.5j * angle_matrix[row, 3]))
matrix_recovered[row, 3] = np.angle(np.exp(1.0j * angle_matrix[row, 0]) * np.exp(+0.5j * angle_matrix[row, 1]) * np.exp(+0.5j * angle_matrix[row, 3]))
global_phases = np.unique(np.round(phase_matrix - matrix_recovered.todense(), decimals=13), axis=1)
self.assertEqual(global_phases.shape, (matrix_recovered.shape[0], 1))
matrix_recovered_1 = global_phases + matrix_recovered
log.info("Recovered Matrix (Z):\n" + str(matrix_recovered_1))
self.assertAlmostEqual(np.linalg.norm(phase_matrix - matrix_recovered_1), 0.0, delta=1e-13)
@ddt
class ControlledMottonenStatePrepTests(unittest.TestCase):
@unpack
@test_data(
{
'matrix': np.sqrt([
[+0.5, +0.5],
[0.5 * np.exp(1j * np.pi), 0.5 * np.exp(1j * 0)]
]),
'debug_circuit': False
},
{
'matrix': np.sqrt([
[+0.5, +0.5],
[0.5 * np.exp(1j * np.pi), 0.5 * np.exp(1j * 0)]
]),
'debug_circuit': True
},
{
'matrix': np.sqrt([
[+0.5, +0.5],
[+0.6, +0.4],
[+0.7, +0.3],
[+0.9, +0.1]
]),
'debug_circuit': False
},
{
'matrix': np.sqrt([
[+0.5, +0.5],
[+0.6, +0.4],
[+0.7, +0.3],
[+0.9, +0.1]
]),
'debug_circuit': True
},
{
'matrix': np.sqrt([
[+0.50, +0.30, +0.20, +0.00],
[+0.25, +0.25, +0.25, +0.25]
]),
'debug_circuit': False
},
{
'matrix': np.sqrt([
[+0.50, +0.30, +0.20, +0.00],
[+0.25, +0.25, +0.25, +0.25]
]),
'debug_circuit': True
},
{
'matrix': np.sqrt([
[+0.50, +0.30, +0.20, +0.00],
[+0.25, +0.25, +0.25, +0.25],
[+0.10, +0.10, +0.40, +0.40],
[+0.40, +0.10, +0.30, +0.20],
[+0.50, +0.30, +0.20, +0.00],
[+0.25, +0.25, +0.25, +0.25],
[+0.10, +0.10, +0.40, +0.40],
[+0.40, +0.10, +0.30, +0.20]
]),
'debug_circuit': True
},
{
'matrix': np.sqrt([
[+0.50, +0.30, +0.20, +0.00],
[+0.25, +0.25, +0.25, +0.25],
[+0.10, +0.10, +0.40, +0.40],
[+0.40, +0.10, +0.30, +0.20],
[+0.50, +0.30, +0.20, +0.00],
[+0.25, +0.25, +0.25, +0.25],
[+0.10, +0.10, +0.40, +0.40],
[+0.40, +0.10, +0.30, +0.20]
]),
'debug_circuit': False
},
{
'matrix': np.sqrt([
[0.50 * np.exp(1j * 0), 0.30 * np.exp(1j * 0), 0.20 * np.exp(1j * 0), 0.00 * np.exp(1j * 0)],
[0.40 * np.exp(1j * 0), 0.10 * np.exp(-1j * np.pi), 0.25 * np.exp(1j * 0), 0.25 * np.exp(1j * 0)]
]),
'debug_circuit': False
},
{
'matrix': np.sqrt([
[0.50 * np.exp(1j * 0), 0.30 * np.exp(1j * 0), 0.20 * np.exp(1j * 0), 0.00 * np.exp(1j * 0)],
[0.40 * np.exp(1j * 0), 0.10 * np.exp(-1j * np.pi), 0.25 * np.exp(1j * 0), 0.25 * np.exp(1j * 0)]
]),
'debug_circuit': True
}
)
def test_define(self, matrix, debug_circuit):
log.info("STARTING TEST")
control_qubits = int(np.ceil(np.log2(matrix.shape[0])))
target_qubits = int(np.ceil(np.log2(matrix.shape[1])))
# We can compute the expected state vector by assuming we use an equal superposition (hadamard) on the
# control qubits (we need to do that a few lines down) so a factor in the Hadamard factors 2^{-n/2} is needed
# Also, the ordering of the registers is extremely important here. A few lines below, we first add the control
# and then the target qubits. That gives the canonical ordering such that we can do column first ravel (order=F)
theoretical_state_vector: np.ndarray = np.asarray(
matrix.ravel(order='F')
).reshape(-1) * np.power(2, -control_qubits / 2)
log.info(f"Expected State: {theoretical_state_vector.tolist()}")
# As mentioned above the ordering is important for this test!
ctrl_qb = QuantumRegister(control_qubits, name='ctrl')
tgt_qb = QuantumRegister(target_qubits, name='tgt')
qc = QuantumCircuit(ctrl_qb, tgt_qb)
# Here we do the equal superposition on the control register as assumed above.
qc.h(ctrl_qb)
qc.append(
ControlledStatePreparationGate(sparse.dok_matrix(matrix)).set_debug_flag(debug_circuit),
list(ctrl_qb) + list(tgt_qb)
)
drawing = ControlledStatePreparationGate(sparse.dok_matrix(matrix)) \
.set_debug_flag(debug_circuit) \
.definition \
.draw(fold=-1)
log.info(f'Circuit:\n{drawing}')
# The the resulting state vector from the state vector simulator
backend: AerBackend = qiskit.Aer.get_backend('statevector_simulator')
job: AerJob = qiskit.execute(qc, backend)
result: Result = job.result()
vector: np.ndarray = np.asarray(result.get_statevector())
# Computing the test:
# The extracted state from the simulation is allowed to be off by a common (global) phase
# If this is the case, taking the angle difference and correcting it, should give the same vector
correction = np.angle(theoretical_state_vector[0]) - np.angle(vector[0])
vector_phase_corrected = vector * np.exp(1.0j * correction)
log.info(f"Actual State: {vector_phase_corrected.tolist()}")
diff = vector_phase_corrected - theoretical_state_vector
self.assertAlmostEqual(np.linalg.norm(diff), 0.0, places=13)
if log.level == logging.DEBUG:
basic_qc = qiskit.transpile(qc, optimization_level=0, basis_gates=['uni_rot_rz', 'uni_rot_ry', 'state_prep_möttönen', 'h'])
log.debug(f"\n{basic_qc.draw(fold=-1)}")
basic_qc = qiskit.transpile(qc, optimization_level=0, basis_gates=['rz', 'cp', 'cx', 'ry', 'p', 'h'])
log.debug(f"\n{basic_qc.draw(fold=-1)}")
basic_qc = qiskit.transpile(qc, optimization_level=3, basis_gates=['u3', 'u2', 'u1', 'cx'])
log.debug(f"\n{basic_qc.draw(fold=-1)}")
log.debug('Theoretical result:')
log.debug(np.round(theoretical_state_vector, decimals=4).tolist())
log.debug('Absolute:')
log.debug(np.round(np.abs(vector), decimals=4).tolist())
log.debug(np.round(np.abs(theoretical_state_vector), decimals=4).tolist())
log.debug('Angle:')
corrected_angle_vector = correction + np.angle(vector)
corrected_angle_vector = np.fmod(corrected_angle_vector, 2*np.pi)
log.debug(np.round(corrected_angle_vector, decimals=4).tolist())
log.debug(np.round(np.angle(theoretical_state_vector), decimals=4).tolist())
log.debug('TEST:')
angle_diff = corrected_angle_vector - np.angle(theoretical_state_vector)
abs_diff = np.abs(vector) - np.abs(theoretical_state_vector)
log.debug(np.round(abs_diff, decimals=4).tolist())
log.debug(np.round(angle_diff, decimals=4).tolist())
log.debug('Real:')
log.debug(np.round(np.real(vector * np.exp(1.0j * correction)), decimals=4).tolist())
log.debug('Difference:')
log.debug(np.round(diff, decimals=4).tolist())
log.info("ENDING TEST")
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import logging
import qiskit
from ddt import ddt, data as test_data, unpack
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit_aer.backends.aerbackend import AerBackend
import dc_qiskit_algorithms.DraperAdder
logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
log = logging.getLogger('test_DraperAdder')
@ddt
class DraperAdderTwoBitTest(unittest.TestCase):
@test_data(
(0, 0, None), (0, 1, None), (0, 2, None), (0, 3, None),
(1, 0, None), (1, 1, None), (1, 2, None), (1, 3, None),
(2, 0, None), (2, 1, None), (2, 2, None), (2, 3, None),
(3, 0, None), (3, 1, None), (3, 2, None), (3, 3, None),
(0, 0, 2), (0, 1, 2), (0, 2, 2), (0, 3, 2),
(1, 0, 2), (1, 1, 2), (1, 2, 2), (1, 3, 2),
(2, 0, 2), (2, 1, 2), (2, 2, 2), (2, 3, 2),
(3, 0, 2), (3, 1, 2), (3, 2, 2), (3, 3, 2),
(7, 0, None), (7, 1, None), (7, 2, None),
(7, 3, None), (7, 4, None), (7, 5, None),
(7, 6, None), (7, 7, None)
)
# @test_data((7, 1, None), (7, 2, None), (7, 3, None))
@unpack
def test_two_bit_adder(self, a, b, length):
log.info("Testing 'DraperAdder' with a=%d(%s), b=%d(%s).",
a, "{0:b}".format(a), b, "{0:b}".format(b))
length = dc_qiskit_algorithms.DraperAdderGate.compute_length(a, b, length)
qubit_a = QuantumRegister(length, "a")
qubit_b = QuantumRegister(length, "b")
readout_a = ClassicalRegister(length, "c_a")
readout_b = ClassicalRegister(length, "c_b")
qc = QuantumCircuit(qubit_a, qubit_b, readout_a, readout_b, name="draper adder")
qc.add_draper(a, b, list(qubit_a) + list(qubit_b), length)
qc.measure(qubit_a, readout_a)
qc.measure(qubit_b, readout_b)
backend = qiskit.Aer.get_backend('qasm_simulator') # type: AerBackend
job = qiskit.execute(qc, backend, shots=8192)
counts = job.result().get_counts()
result_list = [{'b': k[::-1].split(' ')[1], 'a': k[::-1].split(' ')[0], 'counts': v} for k, v in counts.items()]
log.info(result_list)
self.assertEqual(len(result_list), 1)
data = result_list[0] # type: dict
self.assertEqual(int(data['b'], 2), b, "Register b must be unchanged!")
self.assertEqual(int(data['a'], 2), (a + b) % 2**length, "Addition must be correctly performed!")
if __name__ == '__main__':
unittest.main(verbosity=2)
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from typing import List
import numpy as np
import qiskit
from ddt import ddt, data as test_data, unpack
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.result import Result
from qiskit_aer import StatevectorSimulator, QasmSimulator
from dc_qiskit_algorithms.FlipFlopQuantumRam import FFQramDb, add_vector
@ddt
class FlipFlopQuantumRamnStatePrepTests(unittest.TestCase):
def execute_test(self, vector: List[float]):
probability_vector = [np.absolute(e)**2 for e in vector]
print("Input Vector (state) & its measurement probability:")
print(["{0:.3f}".format(e) for e in vector])
print(["{0:.3f}".format(e) for e in probability_vector])
db = FFQramDb()
add_vector(db, vector)
bus = QuantumRegister(db.bus_size(), "bus")
reg = QuantumRegister(1, "reg")
c_bus = ClassicalRegister(db.bus_size(), "c_bus")
c_reg = ClassicalRegister(1, "c_reg")
qc = QuantumCircuit(bus, reg, c_bus, c_reg, name='state prep')
qc.h(bus)
db.add_to_circuit(qc, bus, reg[0])
local_backend: StatevectorSimulator = qiskit.Aer.get_backend('statevector_simulator')
job = qiskit.execute(qc, backend=local_backend, shots=1)
result = job.result() # type: Result
# State vector
result_state_vector = result.get_statevector('state prep')
print("Full simulated state vector (n+1!)")
print(["{0:.2f}".format(e) for e in result_state_vector])
correct_branch_state = np.asarray(result_state_vector)[8:]
correct_branch_state = correct_branch_state / np.linalg.norm(correct_branch_state)
print("State vector on the correct (1) branch:")
print(["{0:.2f}".format(e) for e in correct_branch_state])
positive_global_phase_all_almost_equal = all(abs(a - e) < 0.02 for a, e in zip(vector, correct_branch_state))
negative_global_phase_all_almost_equal = all(abs(a + e) < 0.02 for a, e in zip(vector, correct_branch_state))
self.assertTrue(positive_global_phase_all_almost_equal or negative_global_phase_all_almost_equal)
# Probability Vector by Measurement
qc.measure(bus, c_bus)
qc.measure(reg, c_reg)
local_qasm_backend: QasmSimulator = qiskit.Aer.get_backend('qasm_simulator')
shots = 2**16
job = qiskit.execute(qc, backend=local_qasm_backend, shots=shots)
result = job.result() # type: Result
counts = result.get_counts('state prep')
measurement_probability_vector = [0.0 for e in probability_vector]
shot_post_measurement = sum(c for b, c in counts.items() if b.startswith("1 "))
print("Probability to be on the correct (1) branch: %.4f" % (shot_post_measurement / shots))
for binary, count in sorted(counts.items()):
[reg, bus] = binary.split(' ')
if reg == '1':
index = int(bus, 2)
probability = float(count) / float(shot_post_measurement)
# print("%s (%d): %.3f" % (bus, index, probability))
measurement_probability_vector[index] = probability
print("Measurement Probability on the correct (1) branch:")
print(["{0:.3f}".format(e) for e in measurement_probability_vector])
for expected, actual in zip(probability_vector, measurement_probability_vector):
self.assertAlmostEqual(expected, actual, delta=0.05)
@unpack
@test_data(
{'vector': [-0.1, 0.2, -0.3, 0.4, -0.5, 0.6, -0.7, 0.8]},
{'vector': [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]}
)
def test_state_preparation(self, vector):
self.check_add_vector(vector)
vector = np.asarray(vector)
vector = (1 / np.linalg.norm(vector)) * vector
self.execute_test(list(vector))
def check_add_vector(self, vector):
unit_vector = np.asarray(vector)
l2_norm = np.linalg.norm(unit_vector)
unit_vector = unit_vector / l2_norm
labels = [i for i, v in enumerate(unit_vector) if abs(v) > 1e-6]
db = FFQramDb()
add_vector(db, vector)
check_labels = [int.from_bytes(e.label, byteorder='big') for e in db]
self.assertListEqual(labels, check_labels)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import unittest
from typing import List
import numpy as np
import qiskit
from qiskit.providers import JobV1
from qiskit_aer import Aer, StatevectorSimulator, QasmSimulator
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from ddt import ddt, data as test_data, unpack
from qiskit.result import Result
import dc_qiskit_algorithms.MottonenStatePreparation
logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
log = logging.getLogger('test_DraperAdder')
# noinspection NonAsciiCharacters
@ddt
class MottonenStatePrepTests(unittest.TestCase):
def execute_test(self, vector: List[float]):
probability_vector = [np.absolute(e)**2 for e in vector]
qubits = int(np.log2(len(vector)))
reg = QuantumRegister(qubits, "reg")
c = ClassicalRegister(qubits, "c")
qc = QuantumCircuit(reg, c, name='state prep')
qc.state_prep_möttönen(vector, reg)
local_backend: StatevectorSimulator = Aer.get_backend('statevector_simulator')
job: JobV1 = qiskit.execute(qc, backend=local_backend, shots=1)
result: Result = job.result()
# State vector
result_state_vector = result.get_statevector('state prep')
print(["{0:.2f}".format(e) for e in result_state_vector])
# Try to find a global phase
global_phase = set([np.angle(v) - np.angle(rv) for v, rv in zip(vector, result_state_vector)
if abs(v) > 1e-3 and abs(rv) > 1e-3])
global_phase = global_phase.pop() or 0.0
result_state_vector = np.exp(1.0j * global_phase) * result_state_vector
for expected, actual in zip(vector, result_state_vector):
self.assertAlmostEqual(actual.imag, 0.0, places=6)
self.assertAlmostEqual(expected, actual.real, places=6)
# Probability vector from state vector
result_probability_vector = [np.absolute(e)**2 for e in result_state_vector]
print(["{0:.3f}".format(e) for e in result_probability_vector])
for expected, actual in zip(probability_vector, result_probability_vector):
self.assertAlmostEqual(expected, actual, places=2)
# Probability Vector by Measurement
qc.measure(reg, c)
local_qasm_backend: QasmSimulator = Aer.get_backend('qasm_simulator')
shots = 2**12
job: JobV1 = qiskit.execute(qc, backend=local_qasm_backend, shots=shots)
result = job.result() # type: Result
counts = result.get_counts('state prep')
measurement_probability_vector = [0.0 for e in result_state_vector]
for binary, count in sorted(counts.items()):
index = int(binary, 2)
probability = float(count) / float(shots)
print("%s (%d): %.3f" % (binary, index, probability))
measurement_probability_vector[index] = probability
print(["{0:.3f}".format(e) for e in measurement_probability_vector])
for expected, actual in zip(probability_vector, measurement_probability_vector):
self.assertAlmostEqual(expected, actual, delta=0.02)
@unpack
@test_data(
{'vector': [-0.1, 0.2, -0.3, 0.4, -0.5, 0.6, -0.7, 0.8]},
{'vector': [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]},
{'vector': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]}
)
def test_state_preparation(self, vector):
vector = np.asarray(vector)
vector = (1 / np.linalg.norm(vector)) * vector
self.execute_test(list(vector))
def test_instantiation(self):
gate = dc_qiskit_algorithms.MottonenStatePreparationGate([1.0, 0.0])
self.assertIsInstance(gate, dc_qiskit_algorithms.MottonenStatePreparationGate)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
https://github.com/carstenblank/dc-qiskit-algorithms
|
carstenblank
|
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import unittest
import qiskit
from ddt import ddt, unpack, data
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute
import qiskit.extensions
from qiskit.result import Result
import dc_qiskit_algorithms
logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
log = logging.getLogger('test_DraperAdder')
@ddt
class MultipleControlledNotGateTest(unittest.TestCase):
@unpack
@data(
{'vector': [-0.1, 0.2, -0.3, 0.4, -0.5, 0.6, -0.7, 0.8]}
)
def test_1(self, vector):
q = QuantumRegister(4)
c = ClassicalRegister(4)
qc = QuantumCircuit(q, c)
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.ccx_uni_rot(7, [q[1], q[2], q[3]], q[0])
qc.measure(q, c)
backend = qiskit.BasicAer.get_backend('qasm_simulator')
job_sim = execute(qc, backend, shots=10000)
sim_result = job_sim.result() # type: Result
counts = sim_result.get_counts(qc) # type: dict
log.info(counts)
self.assertIsNotNone(counts.keys())
self.assertListEqual(list(counts.keys()), ['1111'])
def test_2(self):
q = QuantumRegister(4)
c = ClassicalRegister(4)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[2])
# State now ['0000', '0001', '0100', '0101']
qc.ccx_uni_rot(5, [q[0], q[1], q[2]], q[3])
# State now ['0000', '0001', '0100', '1101']
qc.measure(q, c)
backend = qiskit.BasicAer.get_backend('qasm_simulator')
job_sim = execute(qc, backend, shots=10000)
sim_result = job_sim.result() # type: Result
counts = sim_result.get_counts(qc) # type: dict
log.info(counts)
self.assertIsNotNone(counts.keys())
self.assertListEqual(list(sorted(counts.keys())), ['0000', '0001', '0100', '1101'])
if __name__ == '__main__':
unittest.main(verbosity=2)
|
https://github.com/qiskit-community/qiskit-benchmarks
|
qiskit-community
|
import sys
import site
import os
import importlib
import json
from datetime import datetime
from pprint import pprint
from itertools import chain
from dataclasses import dataclass, asdict
from json import dumps, load, JSONEncoder
from contextlib import suppress
import yaml
import pkg_resources
import importlib_metadata
from importlib_metadata import distribution, files
from qiskit import QuantumCircuit
from qiskit.transpiler.pass_manager_config import PassManagerConfig
from qiskit.transpiler import CouplingMap
import benchmark
class ResultEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, QuantumCircuit):
return obj.name
if isinstance(obj, PassManagerConfig):
return obj.__dict__
if isinstance(obj, CouplingMap):
return obj.get_edges()
return JSONEncoder.default(self, obj)
def test_entry_points(contributions_path, contribution_key, results_path, overwrite=False):
contribution_results = {}
with open(contributions_path) as file:
contributions = yaml.load(file, Loader=yaml.SafeLoader)
entry_points = next(filter(lambda m: contribution_key in m, contributions))[contribution_key]
for one_entry_point in entry_points:
module_fqn, function_name = one_entry_point.split(':')
module = importlib.import_module(module_fqn)
metadata = get_metadata(module)
try:
function = getattr(module, function_name)
if contribution_key not in contribution_results:
contribution_results[contribution_key] = { **asdict(metadata), 'results': [] }
entry_point_results = test(function)
contribution_results[contribution_key]['results'].append((one_entry_point, entry_point_results))
except AttributeError:
notify_cannot_find_entry_point(metadata.author_email, one_entry_point)
results = {}
if os.path.exists(results_path):
with open(results_path, 'r') as file:
with suppress(json.decoder.JSONDecodeError):
results = load(file)
results.update(contribution_results)
with open(results_path, 'w') as file:
file.write(dumps(results, cls=ResultEncoder, indent=2))
def get_metadata(module):
module_path = module.__file__
for dist in pkg_resources.working_set:
for path in get_dist_files(dist):
if module_path == path:
meta = importlib_metadata.metadata(dist.project_name)
return metadata(
name=meta['Name'],
author=meta['Author'],
author_email=meta['Author-email'],
description=meta['Summary'],
timestamp=str(datetime.now()),
version=meta['Version']
)
@dataclass
class metadata:
name: str
description: str
author: str
author_email: str
timestamp: str
version: str
def get_dist_files(dist):
for path in files(dist.project_name):
path = os.path.normpath(os.path.join(dist.location, path))
yield path
def test(function):
return benchmark.test(function)
def notify_cannot_find_entry_point(email, entry_point):
print(f'send "{entry_point} not working" @ {email}')
if __name__ == '__main__':
contributions_path = os.path.join(os.getcwd(), sys.argv[1])
contribution_key = sys.argv[2]
results_path = os.path.join(os.getcwd(), sys.argv[3])
test_entry_points(contributions_path, contribution_key, results_path)
|
https://github.com/qiskit-community/qiskit-benchmarks
|
qiskit-community
|
from qiskit import *
from qiskit.transpiler.pass_manager_config import PassManagerConfig
from qiskit.transpiler import CouplingMap
qr = QuantumRegister(3)
circuit1 = QuantumCircuit(qr, name='circuit1')
circuit1.h(qr)
circuit1.cx(qr[0], qr[1])
circuit1.h(qr[0])
circuit1.cx(qr[0], qr[1])
qr = QuantumRegister(3)
circuit2 = QuantumCircuit(qr, name='circuit2')
circuit2.h(qr)
circuit2.cx(qr[0], qr[1])
circuit2.h(qr[0])
circuit2.cx(qr[1], qr[0])
coupling1 = [[1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4],
[5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10],
[11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12]]
coupling2 = [[1, 0], [1, 2], [2, 3], [4, 3]]
pm_config1 = PassManagerConfig(seed_transpiler=42, basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],
coupling_map=CouplingMap(coupling1))
pm_config2 = PassManagerConfig(seed_transpiler=42, basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],
coupling_map=CouplingMap(coupling2))
pm_config1.name = 'pm_config1'
pm_config2.name = 'pm_config2'
def get_case():
return [(circuit1, pm_config1),
(circuit2, pm_config2)]
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
import numpy as np
from qiskit import *
import matplotlib
qr = QuantumRegister(2)
#measurements from quantum bits = use classical register
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.draw()
# adding quantum gates to create entanglement (Hadamart gate)
circuit.h(qr[0])
%matplotlib inline
circuit.draw(output='mpl')
#two qubit operation control X (logical if)
circuit.cx(qr[0], qr[1])
circuit.draw(output='mpl') #entanglement achieved
#measurement, storing measurements into computational register
circuit.measure(qr,cr)
circuit.draw(output='mpl')
#performance simulations
simulator = Aer.get_backend('qasm_simulator')
execute(circuit, backend = simulator)
result = execute(circuit, backend = simulator).result()
#plotting results
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
#running circuit on quantum computer
IBMQ.load_account()
provider= IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_manila')
job= execute(circuit, backend=qcomp)
from qiskit.tools import job_monitor
job_monitor(job)
result = job.result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
# We import the necessary functions from Qiskit
from qiskit.visualization import plot_bloch_multivector, plot_state_qsphere, visualize_transition
from qiskit import QuantumCircuit, Aer, execute
# We create a quantum circuit with one qubit
qc = QuantumCircuit(1)
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# This code executes a quantum circuit `qc` on a backend and stores the result in the `result` variable.
# The `execute` function is used to run the circuit on the specified backend and returns a job object.
# The `result()` method is then called on the job object to get the result of the execution.
result = execute(qc, backend).result()
# We get the statevector of the quantum circuit
statevector = result.get_statevector(qc)
# We plot the statevector on the Bloch sphere
plot_bloch_multivector(statevector)
plot_state_qsphere(statevector, show_state_phases = True, use_degrees = True)
# We add a Hadamard gate to the circuit
qc.h(0)
visualize_transition(qc)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
# We import necessary libraries from Qiskit
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
# We create a quantum circuit with two qubits and two classical bits
qc = QuantumCircuit(2, 2)
# We apply the CX gate with the first qubit as control and the second qubit as target
control_qubit = 0
target_qubit = 1
qc.cx(control_qubit, target_qubit)
qc.measure([0, 1], [0, 1])
# We visualize the quantum circuit
qc.draw('mpl')
# We simulate the quantum circuit
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator).result()
# We get the measurement results
counts = result.get_counts(qc)
# We visualize the measurement results
plot_histogram(counts)
qc1 = QuantumCircuit(2, 2)
qc1.x(1)
qc1.cx(0, 1)
qc1.measure([0, 1], [0, 1])
qc1.draw('mpl')
# We simulate the quantum circuit
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc1, simulator).result()
# We get the measurement results
counts = result.get_counts(qc1)
# We visualize the measurement results
plot_histogram(counts)
qc2 = QuantumCircuit(2, 2)
qc2.x(0)
qc2.cx(0, 1)
qc2.measure([0, 1], [0, 1])
qc2.draw('mpl')
# We simulate the quantum circuit
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc2, simulator).result()
# We get the measurement results
counts = result.get_counts(qc2)
# We visualize the measurement results
plot_histogram(counts)
magical_circuit = QuantumCircuit(2, 2)
magical_circuit.x(1)
magical_circuit.barrier()
magical_circuit.h(0)
magical_circuit.h(1)
magical_circuit.cx(0, 1)
magical_circuit.h(0)
magical_circuit.h(1)
magical_circuit.barrier()
magical_circuit.measure([0, 1], [0, 1])
magical_circuit.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(magical_circuit, simulator).result()
counts = result.get_counts(magical_circuit)
plot_histogram(counts)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
# We import necessary libraries from Qiskit
from qiskit import QuantumCircuit, Aer, execute
# We create a quantum circuit with one qubit
coin_flip_circuit = QuantumCircuit(1, 1)
# We apply the H-gate (Hadamard gate) to create a superposition
coin_flip_circuit.h(0)
# We measure the qubit
coin_flip_circuit.measure(0, 0)
# We simulate the circuit on a classical simulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(coin_flip_circuit, simulator, shots=1).result()
counts = result.get_counts()
from termcolor import colored
# We print the outcome with colored text and ASCII art
if '0' in counts:
print(colored(" _______ \n / \\ \n| (•) (•) | \n| ^ | \n \\_______/ \n", 'red'))
print(colored("The quantum coin landed on 'Heads' (|0⟩)!", 'red'))
else:
print(colored(" _______ \n / \\ \n| (•) (•) | \n| v | \n \\_______/ \n", 'green'))
print(colored("The quantum coin landed on 'Tails' (|1⟩)!", 'green'))
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram, visualize_transition
qc = QuantumCircuit(1,1)
qc.h(0)
visualize_transition(qc)
qc.measure(0,0)
qc.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
qc3 = QuantumCircuit(1,1)
qc3.x(0)
qc3.h(0)
qc3.draw(output='mpl')
visualize_transition(qc3)
qc3.measure(0,0)
qc3.draw(output='mpl')
result = execute(qc3, backend=simulator, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
qc2 = QuantumCircuit(1,1)
qc2.h(0)
qc2.h(0)
qc2.draw(output='mpl')
visualize_transition(qc2)
qc2.measure(0,0)
result = execute(qc2, backend=simulator, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
from qiskit.visualization import plot_bloch_multivector
qc4 = QuantumCircuit(1,1)
qc4.h(0)
qc4.measure(0,0)
qc4.h(0)
qc4.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
result = execute(qc4, backend).result()
statevector = result.get_statevector(qc4)
plot_bloch_multivector(statevector)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
# We import the necessary functions from Qiskit
from qiskit.visualization import plot_bloch_multivector, visualize_transition
from qiskit import QuantumCircuit, Aer, execute
from math import pi
# We create a quantum circuit with one qubit
qc = QuantumCircuit(1)
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result()
# We get the statevector of the quantum circuit
statevector = result.get_statevector(qc)
# We plot the statevector on the Bloch sphere
plot_bloch_multivector(statevector)
qc.ry(pi/2, 0)
qc.draw(output='mpl')
visualize_transition(qc)
qc1 = QuantumCircuit(1)
qc1.rx(pi/3, 0)
qc1.draw(output='mpl')
visualize_transition(qc1)
qc2 = QuantumCircuit(1)
qc2.rz(pi, 0)
qc2.draw(output='mpl')
visualize_transition(qc2)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram, visualize_transition
quantum_bit = 1
classical_bit = 1
circ = QuantumCircuit(quantum_bit, classical_bit)
circ.x(0)
circ.draw(output='mpl')
visualize_transition(circ)
circ.measure(0, 0)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, backend=simulator, shots=1000).result()
counts = result.get_counts(circ)
plot_histogram(counts)
circ = QuantumCircuit(1, 1)
circ.x(0)
circ.x(0)
circ.draw(output='mpl')
visualize_transition(circ)
circ.measure(0, 0)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, backend=simulator, shots=1000).result()
counts = result.get_counts(circ)
plot_histogram(counts)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
from qiskit import QuantumCircuit
from qiskit.visualization import visualize_transition
qc = QuantumCircuit(1)
qc.y(0)
qc.draw('mpl')
visualize_transition(qc)
qc1 = QuantumCircuit(1)
qc1.x(0)
qc1.y(0)
qc1.draw('mpl')
visualize_transition(qc1)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
from qiskit import QuantumCircuit
from qiskit.visualization import visualize_transition
qc = QuantumCircuit(1)
qc.z(0)
qc.draw('mpl')
visualize_transition(qc)
qc1 = QuantumCircuit(1)
qc1.x(0)
qc1.z(0)
qc1.draw('mpl')
visualize_transition(qc1)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.visualization import plot_histogram, plot_state_qsphere
# We create a quantum circuit with 2 qubits and 2 classical bits
qc1 = QuantumCircuit(2, 2)
# We apply the Hadamard gate to the first qubit
qc1.h(0)
# We apply the CNOT gate to the first and second qubits
qc1.cx(0, 1)
# We draw the circuit
qc1.draw(output='mpl')
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc1, backend).result()
statevector = result.get_statevector()
# We plot the results
plot_state_qsphere(statevector)
# We create a quantum circuit with 2 qubits and 2 classical bits
qc2 = QuantumCircuit(2, 2)
# We initialize the input state to |01>
qc2.x(0)
qc2.barrier()
# We apply the Hadamard gate to the first qubit
qc2.h(0)
# We apply the CNOT gate to the first and second qubits
qc2.cx(0, 1)
qc2.barrier()
# We draw the circuit
qc2.draw(output='mpl')
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc2, backend).result()
statevector = result.get_statevector()
# We plot the results
plot_state_qsphere(statevector)
# We create a quantum circuit with 2 qubits and 2 classical bits
qc3 = QuantumCircuit(2, 2)
# We initialize the input state to |10>
qc3.x(1)
qc3.barrier()
# We apply the Hadamard gate to the first qubit
qc3.h(0)
# We apply the CNOT gate to the first and second qubits
qc3.cx(0, 1)
qc3.barrier()
# We draw the circuit
qc3.draw(output='mpl')
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc3, backend).result()
statevector = result.get_statevector()
# We plot the results
plot_state_qsphere(statevector)
# We create a quantum circuit with 2 qubits and 2 classical bits
qc4 = QuantumCircuit(2, 2)
# We initialize the input state to |11>
qc4.x(0)
qc4.x(1)
qc4.barrier()
# We apply the Hadamard gate to the first qubit
qc4.h(0)
# We apply the CNOT gate to the first and second qubits
qc4.cx(0, 1)
qc4.barrier()
# We draw the circuit
qc4.draw(output='mpl')
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc4, backend).result()
statevector = result.get_statevector()
# We plot the results
plot_state_qsphere(statevector)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
#Assign these values as per your requirements.
global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion
min_qubits=3
max_qubits=31
skip_qubits=1
max_circuits=2
num_shots=1000
method=1 #Use method=2 for another approach of Benchmarking (default->1)
num_resets = 2 # Variable for number of resets to perform after mid circuit measurements (default->1) Only for method-2
input_value=None #assign any number to it to perform benchmark for that number.(Default->None)
Noise_Inclusion = False
saveplots = False
Memory_utilization_plot = True
gate_counts_plots = True
Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2"
backend_name = "FakeGuadalupeV2"
#Change your Specification of Simulator in Declaring Backend Section
#By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2()
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute
import time
import matplotlib.pyplot as plt
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error)
benchmark_name = "Bernstein-Vazirani"
# Selection of basis gate set for transpilation
# Note: selector 1 is a hardware agnostic gate set
basis_selector = 1
basis_gates_array = [
[],
['rx', 'ry', 'rz', 'cx'], # a common basis set, default
['cx', 'rz', 'sx', 'x'], # IBM default basis set
['rx', 'ry', 'rxx'], # IonQ default basis set
['h', 'p', 'cx'], # another common basis set
['u', 'cx'] # general unitaries basis gates
]
np.random.seed(0)
def get_QV(backend):
import json
# Assuming backend.conf_filename is the filename and backend.dirname is the directory path
conf_filename = backend.dirname + "/" + backend.conf_filename
# Open the JSON file
with open(conf_filename, 'r') as file:
# Load the JSON data
data = json.load(file)
# Extract the quantum_volume parameter
QV = data.get('quantum_volume', None)
return QV
def checkbackend(backend_name,Type_of_Simulator):
if Type_of_Simulator == "built_in":
available_backends = []
for i in Aer.backends():
available_backends.append(i.name)
if backend_name in available_backends:
platform = backend_name
return platform
else:
print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!")
print(f"available backends are : {available_backends}")
platform = "qasm_simulator"
return platform
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2":
import qiskit.providers.fake_provider as fake_backends
if hasattr(fake_backends,backend_name) is True:
print(f"Backend {backend_name} is available for type {Type_of_Simulator}.")
backend_class = getattr(fake_backends,backend_name)
backend_instance = backend_class()
return backend_instance
else:
print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!")
if Type_of_Simulator == "FAKEV2":
backend_class = getattr(fake_backends,"FakeSantiagoV2")
else:
backend_class = getattr(fake_backends,"FakeSantiago")
backend_instance = backend_class()
return backend_instance
if Type_of_Simulator == "built_in":
platform = checkbackend(backend_name,Type_of_Simulator)
#By default using "Qasm Simulator"
backend = Aer.get_backend(platform)
QV_=None
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"backend version is {backend.backend_version}")
elif Type_of_Simulator == "FAKE":
basis_selector = 0
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting.
max_qubits=backend.configuration().n_qubits
print(f"{platform} device is capable of running {backend.configuration().n_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
elif Type_of_Simulator == "FAKEV2":
basis_selector = 0
if "V2" not in backend_name:
backend_name = backend_name+"V2"
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.name +"-" +backend.backend_version
max_qubits=backend.num_qubits
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
else:
print("Enter valid Simulator.....")
# saved circuits for display
QC_ = None
Uf_ = None
############### Circuit Definition
def create_oracle(num_qubits, input_size, secret_int):
# Initialize first n qubits and single ancilla qubit
qr = QuantumRegister(num_qubits)
qc = QuantumCircuit(qr, name="Uf")
# perform CX for each qubit that matches a bit in secret string
s = ('{0:0' + str(input_size) + 'b}').format(secret_int)
print("s = ",s)
print("input size in oracle =",input_size)
for i_qubit in range(input_size):
if s[input_size - 1 - i_qubit] == '1':
qc.cx(qr[i_qubit], qr[input_size])
return qc
def BersteinVazirani (num_qubits, secret_int, method = 1):
# size of input is one less than available qubits
input_size = num_qubits - 1
if method == 1:
# allocate qubits
qr = QuantumRegister(num_qubits); cr = ClassicalRegister(input_size)
qc = QuantumCircuit(qr, cr, name=f"bv({method})-{num_qubits}-{secret_int}")
# put ancilla in |1> state
qc.x(qr[input_size])
# start with Hadamard on all qubits, including ancilla
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
qc.barrier()
#generate Uf oracle
Uf = create_oracle(num_qubits, input_size, secret_int)
qc.append(Uf,qr)
qc.barrier()
# start with Hadamard on all qubits, including ancilla
for i_qubit in range(num_qubits):
qc.h(qr[i_qubit])
# uncompute ancilla qubit, not necessary for algorithm
qc.x(qr[input_size])
qc.barrier()
# measure all data qubits
for i in range(input_size):
qc.measure(i, i)
global Uf_
if Uf_ == None or num_qubits <= 6:
if num_qubits < 9: Uf_ = Uf
elif method == 2:
# allocate qubits
qr = QuantumRegister(2); cr = ClassicalRegister(input_size); qc = QuantumCircuit(qr, cr, name="main")
# put ancilla in |-> state
qc.x(qr[1])
qc.h(qr[1])
qc.barrier()
# perform CX for each qubit that matches a bit in secret string
s = ('{0:0' + str(input_size) + 'b}').format(secret_int)
for i in range(input_size):
if s[input_size - 1 - i] == '1':
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.h(qr[0])
qc.measure(qr[0], cr[i])
# Perform num_resets reset operations
qc.reset([0]*num_resets)
# save smaller circuit example for display
global QC_
if QC_ == None or num_qubits <= 6:
if num_qubits < 9: QC_ = qc
# return a handle on the circuit
return qc
# Create an empty noise model
noise_parameters = NoiseModel()
if Type_of_Simulator == "built_in":
# Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5%
depol_one_qb_error = 0.05
depol_two_qb_error = 0.005
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx'])
# Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0%
amp_damp_one_qb_error = 0.0
amp_damp_two_qb_error = 0.0
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx'])
# Add reset noise to all single qubit resets
reset_to_zero_error = 0.005
reset_to_one_error = 0.005
noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"])
# Add readout error
p0given1_error = 0.000
p1given0_error = 0.000
error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]])
noise_parameters.add_all_qubit_readout_error(error_meas)
#print(noise_parameters)
elif Type_of_Simulator == "FAKE"or"FAKEV2":
noise_parameters = NoiseModel.from_backend(backend)
#print(noise_parameters)
## Uniform distribution function commonly used
def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity):
"""
Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks
fidelity: raw fidelity to rescale
floor_fidelity: threshold fidelity which is equivalent to random guessing
new_floor_fidelity: what we rescale the floor_fidelity to
Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0:
1 -> 1;
0.25 -> 0;
0.5 -> 0.3333;
"""
rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1
# ensure fidelity is within bounds (0, 1)
if rescaled_fidelity < 0:
rescaled_fidelity = 0.0
if rescaled_fidelity > 1:
rescaled_fidelity = 1.0
return rescaled_fidelity
def uniform_dist(num_state_qubits):
dist = {}
for i in range(2**num_state_qubits):
key = bin(i)[2:].zfill(num_state_qubits)
dist[key] = 1/(2**num_state_qubits)
return dist
### Analysis methods to be expanded and eventually compiled into a separate analysis.py file
import math, functools
def hellinger_fidelity_with_expected(p, q):
""" p: result distribution, may be passed as a counts distribution
q: the expected distribution to be compared against
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
Qiskit Hellinger Fidelity Function
"""
p_sum = sum(p.values())
q_sum = sum(q.values())
if q_sum == 0:
print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0")
return 0
p_normed = {}
for key, val in p.items():
p_normed[key] = val/p_sum
# if p_sum != 0:
# p_normed[key] = val/p_sum
# else:
# p_normed[key] = 0
q_normed = {}
for key, val in q.items():
q_normed[key] = val/q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed.keys():
total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
# in some situations (error mitigation) this can go negative, use abs value
if total < 0:
print(f"WARNING: using absolute value in fidelity calculation")
total = abs(total)
dist = np.sqrt(total)/np.sqrt(2)
fidelity = (1-dist**2)**2
return fidelity
def polarization_fidelity(counts, correct_dist, thermal_dist=None):
"""
Combines Hellinger fidelity and polarization rescaling into fidelity calculation
used in every benchmark
counts: the measurement outcomes after `num_shots` algorithm runs
correct_dist: the distribution we expect to get for the algorithm running perfectly
thermal_dist: optional distribution to pass in distribution from a uniform
superposition over all states. If `None`: generated as
`uniform_dist` with the same qubits as in `counts`
returns both polarization fidelity and the hellinger fidelity
Polarization from: `https://arxiv.org/abs/2008.11294v1`
"""
num_measured_qubits = len(list(correct_dist.keys())[0])
#print(num_measured_qubits)
counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()}
# calculate hellinger fidelity between measured expectation values and correct distribution
hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist)
# to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits
if num_measured_qubits > 16:
return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity }
# if not provided, generate thermal dist based on number of qubits
if thermal_dist == None:
thermal_dist = uniform_dist(num_measured_qubits)
# set our fidelity rescaling value as the hellinger fidelity for a depolarized state
floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist)
# rescale fidelity result so uniform superposition (random guessing) returns fidelity
# rescaled to 0 to provide a better measure of success of the algorithm (polarization)
new_floor_fidelity = 0
fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity)
return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity }
from matplotlib.patches import Rectangle
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize
from matplotlib.patches import Circle
############### Color Map functions
# Create a selection of colormaps from which to choose; default to custom_spectral
cmap_spectral = plt.get_cmap('Spectral')
cmap_greys = plt.get_cmap('Greys')
cmap_blues = plt.get_cmap('Blues')
cmap_custom_spectral = None
# the default colormap is the spectral map
cmap = cmap_spectral
cmap_orig = cmap_spectral
# current cmap normalization function (default None)
cmap_norm = None
default_fade_low_fidelity_level = 0.16
default_fade_rate = 0.7
# Specify a normalization function here (default None)
def set_custom_cmap_norm(vmin, vmax):
global cmap_norm
if vmin == vmax or (vmin == 0.0 and vmax == 1.0):
print("... setting cmap norm to None")
cmap_norm = None
else:
print(f"... setting cmap norm to [{vmin}, {vmax}]")
cmap_norm = Normalize(vmin=vmin, vmax=vmax)
# Remake the custom spectral colormap with user settings
def set_custom_cmap_style(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
#print("... set custom map style")
global cmap, cmap_custom_spectral, cmap_orig
cmap_custom_spectral = create_custom_spectral_cmap(
fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate)
cmap = cmap_custom_spectral
cmap_orig = cmap_custom_spectral
# Create the custom spectral colormap from the base spectral
def create_custom_spectral_cmap(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
# determine the breakpoint from the fade level
num_colors = 100
breakpoint = round(fade_low_fidelity_level * num_colors)
# get color list for spectral map
spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)]
#print(fade_rate)
# create a list of colors to replace those below the breakpoint
# and fill with "faded" color entries (in reverse)
low_colors = [0] * breakpoint
#for i in reversed(range(breakpoint)):
for i in range(breakpoint):
# x is index of low colors, normalized 0 -> 1
x = i / breakpoint
# get color at this index
bc = spectral_colors[i]
r0 = bc[0]
g0 = bc[1]
b0 = bc[2]
z0 = bc[3]
r_delta = 0.92 - r0
#print(f"{x} {bc} {r_delta}")
# compute saturation and greyness ratio
sat_ratio = 1 - x
#grey_ratio = 1 - x
''' attempt at a reflective gradient
if i >= breakpoint/2:
xf = 2*(x - 0.5)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (yf + 0.5)
else:
xf = 2*(0.5 - x)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (0.5 - yf)
'''
grey_ratio = 1 - math.pow(x, 1/fade_rate)
#print(f" {xf} {yf} ")
#print(f" {sat_ratio} {grey_ratio}")
r = r0 + r_delta * sat_ratio
g_delta = r - g0
b_delta = r - b0
g = g0 + g_delta * grey_ratio
b = b0 + b_delta * grey_ratio
#print(f"{r} {g} {b}\n")
low_colors[i] = (r,g,b,z0)
#print(low_colors)
# combine the faded low colors with the regular spectral cmap to make a custom version
cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:])
#spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)]
#for i in range(10): print(spectral_colors[i])
#print("")
return cmap_custom_spectral
# Make the custom spectral color map the default on module init
set_custom_cmap_style()
# Arrange the stored annotations optimally and add to plot
def anno_volumetric_data(ax, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True):
# sort all arrays by the x point of the text (anno_offs)
global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos
all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos))
x_anno_offs = [a for a,b,c,d,e in all_annos]
y_anno_offs = [b for a,b,c,d,e in all_annos]
anno_labels = [c for a,b,c,d,e in all_annos]
x_annos = [d for a,b,c,d,e in all_annos]
y_annos = [e for a,b,c,d,e in all_annos]
#print(f"{x_anno_offs}")
#print(f"{y_anno_offs}")
#print(f"{anno_labels}")
for i in range(len(anno_labels)):
x_anno = x_annos[i]
y_anno = y_annos[i]
x_anno_off = x_anno_offs[i]
y_anno_off = y_anno_offs[i]
label = anno_labels[i]
if i > 0:
x_delta = abs(x_anno_off - x_anno_offs[i - 1])
y_delta = abs(y_anno_off - y_anno_offs[i - 1])
if y_delta < 0.7 and x_delta < 2:
y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6
#x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1
ax.annotate(label,
xy=(x_anno+0.0, y_anno+0.1),
arrowprops=dict(facecolor='black', shrink=0.0,
width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)),
xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]),
rotation=labelrot,
horizontalalignment='left', verticalalignment='baseline',
color=(0.2,0.2,0.2),
clip_on=True)
if saveplots == True:
plt.savefig("VolumetricPlotSample.jpg")
# Plot one group of data for volumetric presentation
def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True,
x_size=1.0, y_size=1.0, zorder=1, offset_flag=False,
max_depth=0, suppress_low_fidelity=False):
# since data may come back out of order, save point at max y for annotation
i_anno = 0
x_anno = 0
y_anno = 0
# plot data rectangles
low_fidelity_count = True
last_y = -1
k = 0
# determine y-axis dimension for one pixel to use for offset of bars that start at 0
(_, dy) = get_pixel_dims(ax)
# do this loop in reverse to handle the case where earlier cells are overlapped by later cells
for i in reversed(range(len(d_data))):
x = depth_index(d_data[i], depth_base)
y = float(w_data[i])
f = f_data[i]
# each time we star a new row, reset the offset counter
# DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars
# that represent time starting from 0 secs. We offset by one pixel each and center the group
if y != last_y:
last_y = y;
k = 3 # hardcoded for 8 cells, offset by 3
#print(f"{i = } {x = } {y = }")
if max_depth > 0 and d_data[i] > max_depth:
#print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}")
break;
# reject cells with low fidelity
if suppress_low_fidelity and f < suppress_low_fidelity_level:
if low_fidelity_count: break
else: low_fidelity_count = True
# the only time this is False is when doing merged gradation plots
if do_border == True:
# this case is for an array of x_sizes, i.e. each box has different width
if isinstance(x_size, list):
# draw each of the cells, with no offset
if not offset_flag:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder))
# use an offset for y value, AND account for x and width to draw starting at 0
else:
ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder))
# this case is for only a single cell
else:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size))
# save the annotation point with the largest y value
if y >= y_anno:
x_anno = x
y_anno = y
i_anno = i
# move the next bar down (if using offset)
k -= 1
# if no data rectangles plotted, no need for a label
if x_anno == 0 or y_anno == 0:
return
x_annos.append(x_anno)
y_annos.append(y_anno)
anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 )
# adjust radius of annotation circle based on maximum width of apps
anno_max = 10
if w_max > 10:
anno_max = 14
if w_max > 14:
anno_max = 18
scale = anno_max / anno_dist
# offset of text from end of arrow
if scale > 1:
x_anno_off = scale * x_anno - x_anno - 0.5
y_anno_off = scale * y_anno - y_anno
else:
x_anno_off = 0.7
y_anno_off = 0.5
x_anno_off += x_anno
y_anno_off += y_anno
# print(f"... {xx} {yy} {anno_dist}")
x_anno_offs.append(x_anno_off)
y_anno_offs.append(y_anno_off)
anno_labels.append(label)
if do_label:
ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot,
horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2))
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# init arrays to hold annotation points for label spreading
def vplot_anno_init ():
global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# Number of ticks on volumetric depth axis
max_depth_log = 22
# average transpile factor between base QV depth and our depth based on results from QV notebook
QV_transpile_factor = 12.7
# format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1
# (sign handling may be incorrect)
def format_number(num, digits=0):
if isinstance(num, str): num = float(num)
num = float('{:.3g}'.format(abs(num)))
sign = ''
metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1}
for index in metric:
num_check = num / metric[index]
if num_check >= 1:
num = round(num_check, digits)
sign = index
break
numstr = f"{str(num)}"
if '.' in numstr:
numstr = numstr.rstrip('0').rstrip('.')
return f"{numstr}{sign}"
# Return the color associated with the spcific value, using color map norm
def get_color(value):
# if there is a normalize function installed, scale the data
if cmap_norm:
value = float(cmap_norm(value))
if cmap == cmap_spectral:
value = 0.05 + value*0.9
elif cmap == cmap_blues:
value = 0.00 + value*1.0
else:
value = 0.0 + value*0.95
return cmap(value)
# Return the x and y equivalent to a single pixel for the given plot axis
def get_pixel_dims(ax):
# transform 0 -> 1 to pixel dimensions
pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0))
xpix = pixdims[1][0]
ypix = pixdims[0][1]
#determine x- and y-axis dimension for one pixel
dx = (1 / xpix)
dy = (1 / ypix)
return (dx, dy)
############### Helper functions
# return the base index for a circuit depth value
# take the log in the depth base, and add 1
def depth_index(d, depth_base):
if depth_base <= 1:
return d
if d == 0:
return 0
return math.log(d, depth_base) + 1
# draw a box at x,y with various attributes
def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1):
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5*y_size,
zorder=zorder)
# draw a circle at x,y with various attributes
def circle_at(x, y, value, type=1, fill=True):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Circle((x, y), size/2,
alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5)
def box4_at(x, y, value, type=1, fill=True, alpha=1.0):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.3,0.3,0.3)
ec = fc
return Rectangle((x - size/8, y - size/2), size/4, size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.1)
# Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value
def qv_box_at(x, y, qv_width, qv_depth, value, depth_base):
#print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}")
return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width,
edgecolor = (value,value,value),
facecolor = (value,value,value),
fill=True,
lw=1)
def bkg_box_at(x, y, value=0.9):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (value,value,value),
fill=True,
lw=0.5)
def bkg_empty_box_at(x, y):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (1.0,1.0,1.0),
fill=True,
lw=0.5)
# Plot the background for the volumetric analysis
def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"):
if suptitle == None:
suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}"
QV0 = QV
qv_estimate = False
est_str = ""
if QV == 0: # QV = 0 indicates "do not draw QV background or label"
QV = 2048
elif QV < 0: # QV < 0 indicates "add est. to label"
QV = -QV
qv_estimate = True
est_str = " (est.)"
if avail_qubits > 0 and max_qubits > avail_qubits:
max_qubits = avail_qubits
max_width = 13
if max_qubits > 11: max_width = 18
if max_qubits > 14: max_width = 20
if max_qubits > 16: max_width = 24
if max_qubits > 24: max_width = 33
#print(f"... {avail_qubits} {max_qubits} {max_width}")
plot_width = 6.8
plot_height = 0.5 + plot_width * (max_width / max_depth_log)
#print(f"... {plot_width} {plot_height}")
# define matplotlib figure and axis; use constrained layout to fit colorbar to right
fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True)
plt.suptitle(suptitle)
plt.xlim(0, max_depth_log)
plt.ylim(0, max_width)
# circuit depth axis (x axis)
xbasis = [x for x in range(1,max_depth_log)]
xround = [depth_base**(x-1) for x in xbasis]
xlabels = [format_number(x) for x in xround]
ax.set_xlabel('Circuit Depth')
ax.set_xticks(xbasis)
plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor")
# other label options
#plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left')
#plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor")
# circuit width axis (y axis)
ybasis = [y for y in range(1,max_width)]
yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now
ylabels = [str(y) for y in yround] # not used now
#ax.set_ylabel('Circuit Width (Number of Qubits)')
ax.set_ylabel('Circuit Width')
ax.set_yticks(ybasis)
#create simple line plot (not used right now)
#ax.plot([0, 10],[0, 10])
log2QV = math.log2(QV)
QV_width = log2QV
QV_depth = log2QV * QV_transpile_factor
# show a quantum volume rectangle of QV = 64 e.g. (6 x 6)
if QV0 != 0:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base))
else:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base))
# the untranspiled version is commented out - we do not show this by default
# also show a quantum volume rectangle un-transpiled
# ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base))
# show 2D array of volumetric cells based on this QV_transpiled
# DEVNOTE: we use +1 only to make the visuals work; s/b without
# Also, the second arg of the min( below seems incorrect, needs correction
maxprod = (QV_width + 1) * (QV_depth + 1)
for w in range(1, min(max_width, round(QV) + 1)):
# don't show VB squares if width greater than known available qubits
if avail_qubits != 0 and w > avail_qubits:
continue
i_success = 0
for d in xround:
# polarization factor for low circuit widths
maxtest = maxprod / ( 1 - 1 / (2**w) )
# if circuit would fail here, don't draw box
if d > maxtest: continue
if w * d > maxtest: continue
# guess for how to capture how hardware decays with width, not entirely correct
# # reduce maxtext by a factor of number of qubits > QV_width
# # just an approximation to account for qubit distances
# if w > QV_width:
# over = w - QV_width
# maxtest = maxtest / (1 + (over/QV_width))
# draw a box at this width and depth
id = depth_index(d, depth_base)
# show vb rectangles; if not showing QV, make all hollow (or less dark)
if QV0 == 0:
#ax.add_patch(bkg_empty_box_at(id, w))
ax.add_patch(bkg_box_at(id, w, 0.95))
else:
ax.add_patch(bkg_box_at(id, w, 0.9))
# save index of last successful depth
i_success += 1
# plot empty rectangle after others
d = xround[i_success]
id = depth_index(d, depth_base)
ax.add_patch(bkg_empty_box_at(id, w))
# Add annotation showing quantum volume
if QV0 != 0:
t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12,
horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2),
bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1))
# add colorbar to right of plot
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax,
shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7))
return ax
# Function to calculate circuit depth
def calculate_circuit_depth(qc):
# Calculate the depth of the circuit
depth = qc.depth()
return depth
def calculate_transpiled_depth(qc,basis_selector):
# use either the backend or one of the basis gate sets
if basis_selector == 0:
qc = transpile(qc, backend)
else:
basis_gates = basis_gates_array[basis_selector]
qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0)
transpiled_depth = qc.depth()
return transpiled_depth,qc
def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title):
avg_fidelity_means = []
avg_Hf_fidelity_means = []
avg_num_qubits_values = list(fidelity_data.keys())
# Calculate the average fidelity and Hamming fidelity for each unique number of qubits
for num_qubits in avg_num_qubits_values:
avg_fidelity = np.average(fidelity_data[num_qubits])
avg_fidelity_means.append(avg_fidelity)
avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits])
avg_Hf_fidelity_means.append(avg_Hf_fidelity)
return avg_fidelity_means,avg_Hf_fidelity_means
list_of_gates = []
def list_of_standardgates():
import qiskit.circuit.library as lib
from qiskit.circuit import Gate
import inspect
# List all the attributes of the library module
gate_list = dir(lib)
# Filter out non-gate classes (like functions, variables, etc.)
gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)]
# Get method names from QuantumCircuit
circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction)
method_names = [name for name, _ in circuit_methods]
# Map gate class names to method names
gate_to_method = {}
for gate in gates:
gate_class = getattr(lib, gate)
class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name
for method in method_names:
if method == class_name or method == class_name.replace('cr', 'c-r'):
gate_to_method[gate] = method
break
# Add common operations that are not strictly gates
additional_operations = {
'Measure': 'measure',
'Barrier': 'barrier',
}
gate_to_method.update(additional_operations)
for k,v in gate_to_method.items():
list_of_gates.append(v)
def update_counts(gates,custom_gates):
operations = {}
for key, value in gates.items():
operations[key] = value
for key, value in custom_gates.items():
if key in operations:
operations[key] += value
else:
operations[key] = value
return operations
def get_gate_counts(gates,custom_gate_defs):
result = gates.copy()
# Iterate over the gate counts in the quantum circuit
for gate, count in gates.items():
if gate in custom_gate_defs:
custom_gate_ops = custom_gate_defs[gate]
# Multiply custom gate operations by the count of the custom gate in the circuit
for _ in range(count):
result = update_counts(result, custom_gate_ops)
# Remove the custom gate entry as we have expanded it
del result[gate]
return result
dict_of_qc = dict()
custom_gates_defs = dict()
# Function to count operations recursively
def count_operations(qc):
circuit_traverser(qc)
operations = dict()
operations = dict_of_qc[qc.name]
del dict_of_qc[qc.name]
# print("operations :",operations)
# print("dict_of_qc :",dict_of_qc)
for keys in operations.keys():
if keys not in list_of_gates:
for k,v in dict_of_qc.items():
if k in operations.keys():
custom_gates_defs[k] = v
operations=get_gate_counts(operations,custom_gates_defs)
custom_gates_defs.clear()
return operations
def circuit_traverser(qc):
dict_of_qc[qc.name]=dict(qc.count_ops())
for i in qc.data:
if str(i.operation.name) not in list_of_gates:
qc_1 = i.operation.definition
circuit_traverser(qc_1)
def get_memory():
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
max_mem = usage.ru_maxrss/1024 #in MB
return max_mem
def analyzer(num_qubits,s_int):
input_size = num_qubits-1
secret_int = int(s_int)
# create the key that is expected to have all the measurements (for this circuit)
key = format(secret_int, f"0{input_size}b")
# correct distribution is measuring the key 100% of the time
correct_dist = {key: 1.0}
return correct_dist
def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits,
max_circuits=max_circuits, num_shots=num_shots):
creation_times = []
elapsed_times = []
quantum_times = []
circuit_depths = []
transpiled_depths = []
fidelity_data = {}
Hf_fidelity_data = {}
numckts = []
mem_usage = []
algorithmic_1Q_gate_counts = []
algorithmic_2Q_gate_counts = []
transpiled_1Q_gate_counts = []
transpiled_2Q_gate_counts = []
print(f"{benchmark_name} Benchmark Program - {platform}")
#defining all the standard gates supported by qiskit in a list
if gate_counts_plots == True:
list_of_standardgates()
# validate parameters (smallest circuit is 3 qubits)
max_qubits = max(3, max_qubits)
min_qubits = min(max(3, min_qubits), max_qubits)
skip_qubits = max(1, skip_qubits)
# Variable for new qubit group ordering if using mid_circuit measurements
mid_circuit_qubit_group = []
# If using mid_circuit measurements, set transform qubit group to true
transform_qubit_group = True if method ==2 else False
global max_ckts
max_ckts = max_circuits
global min_qbits,max_qbits,skp_qubits
min_qbits = min_qubits
max_qbits = max_qubits
skp_qubits = skip_qubits
print(f"min, max qubits = {min_qubits} {max_qubits}")
# Execute Benchmark Program N times for multiple circuit sizes
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
input_size = num_qubits - 1
fidelity_data[num_qubits] = []
Hf_fidelity_data[num_qubits] = []
num_circuits = min(2**(input_size), max_circuits)
print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}")
numckts.append(num_circuits)
# determine range of secret strings to loop over
if 2**(input_size) <= max_circuits:
s_range = list(range(num_circuits))
else:
s_range = np.random.choice(2**(input_size), num_circuits, False)
for s_int in s_range:
print("*********************************************")
if input_value is not None:
s_int = input_value
# If mid circuit, then add 2 to new qubit group since the circuit only uses 2 qubits
if method == 2:
mid_circuit_qubit_group.append(2)
print(f"qc of {num_qubits} qubits with secret integer {s_int}")
#creation of Quantum Circuit.
ts = time.time()
qc = BersteinVazirani(num_qubits, s_int, method)
#creation time
creation_time = time.time() - ts
creation_times.append(creation_time)
#print(qc)
print(f"creation time = {creation_time*1000} ms")
# Calculate gate count for the algorithmic circuit (excluding barriers and measurements)
if gate_counts_plots == True:
operations = count_operations(qc)
n1q = 0; n2q = 0
if operations != None:
for key, value in operations.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c") or key.startswith("mc"):
n2q += value
else:
n1q += value
algorithmic_1Q_gate_counts.append(n1q)
algorithmic_2Q_gate_counts.append(n2q)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc=qc.decompose()
#print(qc)
# Calculate circuit depth
depth = calculate_circuit_depth(qc)
circuit_depths.append(depth)
# Calculate transpiled circuit depth
transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector)
transpiled_depths.append(transpiled_depth)
#print(qc)
print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}")
if gate_counts_plots == True:
# Calculate gate count for the transpiled circuit (excluding barriers and measurements)
tr_ops = qc.count_ops()
#print("tr_ops = ",tr_ops)
tr_n1q = 0; tr_n2q = 0
if tr_ops != None:
for key, value in tr_ops.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c"): tr_n2q += value
else: tr_n1q += value
transpiled_1Q_gate_counts.append(tr_n1q)
transpiled_2Q_gate_counts.append(tr_n2q)
print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}")
print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}")
#execution
if Type_of_Simulator == "built_in":
#To check if Noise is required
if Noise_Inclusion == True:
noise_model = noise_parameters
else:
noise_model = None
ts = time.time()
job = execute(qc, backend, shots=num_shots, noise_model=noise_model)
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" :
ts = time.time()
job = backend.run(qc,shots=num_shots, noise_model=noise_parameters)
#retrieving the result
result = job.result()
#print(result)
#calculating elapsed time
elapsed_time = time.time() - ts
elapsed_times.append(elapsed_time)
# Calculate quantum processing time
quantum_time = result.time_taken
quantum_times.append(quantum_time)
print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time *1000} ms")
#counts in result object
counts = result.get_counts()
#Correct distribution to compare with counts
correct_dist = analyzer(num_qubits, s_int)
#fidelity calculation comparision of counts and correct_dist
fidelity_dict = polarization_fidelity(counts, correct_dist)
fidelity_data[num_qubits].append(fidelity_dict['fidelity'])
Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity'])
#maximum memory utilization (if required)
if Memory_utilization_plot == True:
max_mem = get_memory()
print(f"Maximum Memory Utilized: {max_mem} MB")
mem_usage.append(max_mem)
print("*********************************************")
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
if method == 1: print("\nQuantum Oracle 'Uf' ="); print(Uf_ if Uf_ != None else " ... too large!")
return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths,
fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts,
transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage)
# Execute the benchmark program, accumulate metrics, and calculate circuit depths
(creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts,
algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run()
# Define the range of qubits for the x-axis
num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits)
print("num_qubits_range =",num_qubits_range)
# Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits
avg_creation_times = []
avg_elapsed_times = []
avg_quantum_times = []
avg_circuit_depths = []
avg_transpiled_depths = []
avg_1Q_algorithmic_gate_counts = []
avg_2Q_algorithmic_gate_counts = []
avg_1Q_Transpiled_gate_counts = []
avg_2Q_Transpiled_gate_counts = []
max_memory = []
start = 0
for num in numckts:
avg_creation_times.append(np.mean(creation_times[start:start+num]))
avg_elapsed_times.append(np.mean(elapsed_times[start:start+num]))
avg_quantum_times.append(np.mean(quantum_times[start:start+num]))
avg_circuit_depths.append(np.mean(circuit_depths[start:start+num]))
avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num]))
if gate_counts_plots == True:
avg_1Q_algorithmic_gate_counts.append((np.mean(algorithmic_1Q_gate_counts[start:start+num])))
avg_2Q_algorithmic_gate_counts.append((np.mean(algorithmic_2Q_gate_counts[start:start+num])))
avg_1Q_Transpiled_gate_counts.append((np.mean(transpiled_1Q_gate_counts[start:start+num])))
avg_2Q_Transpiled_gate_counts.append((np.mean(transpiled_2Q_gate_counts[start:start+num])))
if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num]))
start += num
# Calculate the fidelity data
avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison")
# Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits
# Add labels to the bars
def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"):
for rect in rects:
height = rect.get_height()
ax.annotate(str.format(height), # Formatting to two decimal places
xy=(rect.get_x() + rect.get_width() / 2, height / 2),
xytext=(0, 0),
textcoords="offset points",
ha='center', va=va,color=text_color,rotation=90)
bar_width = 0.3
# Determine the number of subplots and their arrangement
if Memory_utilization_plot and gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30))
# Plotting for both memory utilization and gate counts
# ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available
elif Memory_utilization_plot:
fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30))
# Plotting for memory utilization only
# ax1, ax2, ax3, ax6, ax7 are available
elif gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30))
# Plotting for gate counts only
# ax1, ax2, ax3, ax4, ax5, ax6 are available
else:
fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30))
# Default plotting
# ax1, ax2, ax3, ax6 are available
fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16)
for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000
avg_creation_times[i] *= 1000
ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue')
autolabel(ax1.patches, ax1)
ax1.set_xlabel('Number of Qubits')
ax1.set_ylabel('Average Creation Time (ms)')
ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14)
ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000
avg_elapsed_times[i] *= 1000
for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000
avg_quantum_times[i] *= 1000
Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time')
Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time')
autolabel(Elapsed,ax2,str='{:.1f}')
autolabel(Quantum,ax2,str='{:.1f}')
ax2.set_xlabel('Number of Qubits')
ax2.set_ylabel('Average Time (ms)')
ax2.set_title('Average Time vs Number of Qubits')
ax2.legend()
ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here
Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here
autolabel(Normalized,ax3,str='{:.2f}')
autolabel(Algorithmic,ax3,str='{:.2f}')
ax3.set_xlabel('Number of Qubits')
ax3.set_ylabel('Average Circuit Depth')
ax3.set_title('Average Circuit Depth vs Number of Qubits')
ax3.legend()
if gate_counts_plots == True:
ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_1Q_counts,ax4,str='{}')
autolabel(Algorithmic_1Q_counts,ax4,str='{}')
ax4.set_xlabel('Number of Qubits')
ax4.set_ylabel('Average 1-Qubit Gate Counts')
ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits')
ax4.legend()
ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_2Q_counts,ax5,str='{}')
autolabel(Algorithmic_2Q_counts,ax5,str='{}')
ax5.set_xlabel('Number of Qubits')
ax5.set_ylabel('Average 2-Qubit Gate Counts')
ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits')
ax5.legend()
ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here
Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here
autolabel(Hellinger,ax6,str='{:.2f}')
autolabel(Normalized,ax6,str='{:.2f}')
ax6.set_xlabel('Number of Qubits')
ax6.set_ylabel('Average Value')
ax6.set_title("Fidelity Comparison")
ax6.legend()
if Memory_utilization_plot == True:
ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations")
autolabel(ax7.patches, ax7)
ax7.set_xlabel('Number of Qubits')
ax7.set_ylabel('Maximum Memory Utilized (MB)')
ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14)
plt.tight_layout(rect=[0, 0, 1, 0.96])
if saveplots == True:
plt.savefig("ParameterPlotsSample.jpg")
plt.show()
# Quantum Volume Plot
Suptitle = f"Volumetric Positioning - {platform}"
appname=benchmark_name
if QV_ == None:
QV=2048
else:
QV=QV_
depth_base =2
ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity")
w_data = num_qubits_range
# determine width for circuit
w_max = 0
for i in range(len(w_data)):
y = float(w_data[i])
w_max = max(w_max, y)
d_tr_data = avg_transpiled_depths
f_data = avg_f
plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max)
anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from qiskit.visualization import plot_state_qsphere, plot_histogram
# We create a Quantum Register with 3 qubits.
q = QuantumRegister(3, 'qubit')
# We create a Classical Register with 3 bits.
c = ClassicalRegister(3, 'Classical bit')
# We create a Quantum Circuit
qc = QuantumCircuit(q, c)
# We add x gate to the first qubit
qc.x(q[0])
qc.barrier()
qc.draw(output='mpl')
qc.h(q[1])
qc.cx(q[1], q[2])
qc.barrier()
qc.draw(output='mpl')
qc.cx(q[0], q[1])
qc.h(0)
qc.barrier()
qc.measure(0,0)
qc.measure(1,1)
qc.barrier()
qc.draw(output='mpl')
from math import pi
qc.crx(pi, q[1], q[2]).c_if(c, 1)
qc.crz(pi, q[0], q[2]).c_if(c, 1)
qc.draw(output='mpl')
# We execute the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
result = execute(qc, backend).result()
statevector = result.get_statevector(qc)
plot_state_qsphere(statevector, show_state_phases = True, use_degrees = True)
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
# Replace 'MY_API_TOKEN' with your actual API token
IBMQ.save_account('API_TOKEN', overwrite=True)
# We get the least busy IBM Quantum device
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True))
# We print the name of the least busy backend
print("Least busy backend:", backend.name())
import time
from qiskit.tools.monitor import job_monitor
# We execute the circuit on the least busy backend. Monitor the execution of the job in the queue
backend = provider.get_backend('ibmq_belem')
# We execute the circuit on the backend
start_time = time.time()
job_exp = execute(qc, backend=backend, shots=1024)
job_monitor(job_exp, interval=2)
result_exp = job_exp.result()
counts_exp = result_exp.get_counts(qc)
end_time = time.time()
# We calculate the time taken in minutes and seconds
time_taken = end_time - start_time
minutes, seconds = divmod(time_taken, 60)
# We print the results and the time it took to run the code
print("Counts:", counts_exp)
print("Time taken: {} minutes and {:.2f} seconds".format(int(minutes), seconds))
plot_histogram(counts_exp)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
import sys
sys.path.append('../')
from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\
sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\
sampleCircuitF
from entanglement import Ent
import warnings
warnings.filterwarnings('ignore')
labels = [
'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3',
'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F'
]
samplers = [
sampleCircuitA,
sampleCircuitB1,
sampleCircuitB2,
sampleCircuitB3,
sampleCircuitC,
sampleCircuitD,
sampleCircuitE,
sampleCircuitF
]
q = 4
for layer in range(1, 4):
print(f'qubtis: {q}')
print('-' * 25)
for (label, sampler) in zip(labels, samplers):
expr = Ent(sampler, layer=layer, epoch=3000)
print(f'{label}(layer={layer}): {expr}')
print()
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
import numpy as np
import matplotlib.pyplot as plt
# Constants
electron_wavelength = 0.1 # De Broglie wavelength of electrons
slit_width = 0.1 # Width of each slit
screen_distance = 2.0 # Distance from the slits to the screen
screen_width = 2.0 # Width of the screen
screen_resolution = 800 # Number of pixels on the screen
electron_intensity = 1000 # Number of electrons emitted
# Create a grid of points on the screen
x = np.linspace(-screen_width / 2, screen_width / 2, screen_resolution)
y = np.linspace(-screen_width / 2, screen_width / 2, screen_resolution)
X, Y = np.meshgrid(x, y)
# Initialize an empty intensity matrix
intensity = np.zeros_like(X, dtype=float)
# Simulate the electron impacts on the screen
for _ in range(electron_intensity):
# Randomly select a slit
slit_choice = np.random.choice([-1, 1])
# Randomly choose the impact point on the slit
slit_position = np.random.uniform(-slit_width / 2, slit_width / 2) * slit_choice
# Calculate the corresponding position on the screen
x_position = screen_distance * np.tan(np.arctan2(X - slit_position, screen_distance))
# Filter out positions outside the screen
valid_positions = np.logical_and(x_position >= -screen_width / 2, x_position <= screen_width / 2)
# Accumulate impacts on the screen
intensity += valid_positions
# Create a heatmap of electron impacts
plt.figure(figsize=(8, 6))
plt.imshow(intensity, cmap='hot', extent=(-screen_width / 2, screen_width / 2, -screen_width / 2, screen_width / 2))
plt.colorbar(label='Accumulated Impacts')
plt.title('Double-Slit Experiment Heatmap (Electrons as Particles)')
plt.xlabel('X Position (meters)')
plt.ylabel('Y Position (meters)')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Set up the experiment parameters
d = 0.1 # Width of the slits
wavelength = 0.01 # Wavelength of the waves or particles
L = 1.0 # Distance from the screen to the slits
dx = 0.01 # Spacing for the observation screen in the x-direction
dy = 0.01 # Spacing for the observation screen in the y-direction
x = np.arange(-1.0, 1.0, dx)
y = np.arange(-1.0, 1.0, dy)
X, Y = np.meshgrid(x, y)
# Calculate the intensity at each point on the screen
intensity = (
(np.sin(np.pi * d * X / (wavelength * L))) ** 2
* (np.sin(np.pi * d * Y / (wavelength * L))) ** 2
)
# Calculate the intensity distribution along the x-axis
intensity_x = (
(np.sin(np.pi * d * x / (wavelength * L))) ** 2
)
# Create subplots
fig, axs = plt.subplots(1, 2, figsize=(12, 6))
# Heatmap subplot
axs[0].imshow(intensity, extent=(-1, 1, -1, 1), cmap="hot", origin="lower")
axs[0].set_title("Double-Slit Interference Heat Map")
axs[0].set_xlabel("X Position (m)")
axs[0].set_ylabel("Y Position (m)")
axs[0].grid(False)
# Distribution plot subplot
axs[1].plot(x, intensity_x, color="blue")
axs[1].set_title("Double-Slit Interference Distribution (X-axis)")
axs[1].set_xlabel("X Position (m)")
axs[1].set_ylabel("Intensity")
axs[1].grid(True)
plt.tight_layout() # Ensure proper spacing between subplots
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, FloatSlider
# Define the function that simulates the double-slit experiment
def double_slit_experiment(d, wavelength, L, dx, dy):
# Create a grid of points on the screen
x = np.arange(-1.0, 1.0, dx)
y = np.arange(-1.0, 1.0, dy)
X, Y = np.meshgrid(x, y)
# Calculate the intensity at each point on the screen
intensity = (
(np.sin(np.pi * d * X / (wavelength * L))) ** 2
* (np.sin(np.pi * d * Y / (wavelength * L))) ** 2
)
# Calculate the intensity distribution along the x-axis
intensity_x = (
(np.sin(np.pi * d * x / (wavelength * L))) ** 2
)
# Create subplots
fig, axs = plt.subplots(1, 2, figsize=(12, 6))
# Heatmap subplot
axs[0].imshow(intensity, extent=(-1, 1, -1, 1), cmap="hot", origin="lower")
axs[0].set_title("Double-Slit Interference Heat Map")
axs[0].set_xlabel("X Position (m)")
axs[0].set_ylabel("Y Position (m)")
axs[0].grid(False)
# Distribution plot subplot
axs[1].plot(x, intensity_x, color="blue")
axs[1].set_title("Double-Slit Interference Distribution (X-axis)")
axs[1].set_xlabel("X Position (m)")
axs[1].set_ylabel("Intensity")
axs[1].grid(True)
plt.tight_layout() # Ensure proper spacing between subplots
plt.show()
# Define the interactive sliders for the parameters
d_slider = FloatSlider(min=0.01, max=1.0, step=0.01, value=0.1, description='Slit Width:')
wavelength_slider = FloatSlider(min=0.001, max=0.1, step=0.001, value=0.01, description='Wavelength:')
L_slider = FloatSlider(min=0.1, max=10.0, step=0.1, value=1.0, description='Distance to Screen:')
dx_slider = FloatSlider(min=0.001, max=0.1, step=0.001, value=0.01, description='Screen Spacing (X-axis):')
dy_slider = FloatSlider(min=0.001, max=0.1, step=0.001, value=0.01, description='Screen Spacing (Y-axis):')
# Define the interactive function that updates the plot when the sliders are changed
def update_plot(d, wavelength, L, dx, dy):
double_slit_experiment(d, wavelength, L, dx, dy)
# Create the interactive plot
interact(update_plot, d=d_slider, wavelength=wavelength_slider, L=L_slider, dx=dx_slider, dy=dy_slider)
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
import numpy as np
import pytest
from qiskit import Aer
from qiskit.algorithms.gradients import ReverseEstimatorGradient
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import Estimator
from qiskit.quantum_info import SparsePauliOp
np.random.seed(0)
max_parallel_threads = 12
gpu = False
method = "statevector_gpu"
def generate_circuit(nqubits):
ansatz = TwoLocal(
nqubits,
["rx", "ry", "rz"],
["cx"],
"linear",
reps=3,
flatten=True,
).decompose()
params = np.random.rand(ansatz.num_parameters)
return ansatz, params
def execute_statevector(benchmark, circuit, params):
backend_options = {
"method": method,
"precision": "double",
"max_parallel_threads": max_parallel_threads,
"fusion_enable": True,
"fusion_threshold": 14,
"fusion_max_qubit": 5,
}
circuit = circuit.bind_parameters(params)
backend = Aer.get_backend("statevector_simulator")
backend.set_options(**backend_options)
def evalfunc(backend, circuit):
backend.run(circuit).result()
benchmark(evalfunc, backend, circuit)
def execute_estimator(benchmark, circuit, obs, params):
estimator = Estimator()
def evalfunc(estimator, circuit, obs, params):
estimator.run([circuit], [obs], [params]).result()
benchmark(evalfunc, estimator, circuit, obs, params)
def execute_gradient(benchmark, circuit, obs, params):
estimator_grad = ReverseEstimatorGradient()
def evalfunc(estimator_grad, circuit, obs, params):
estimator_grad.run([circuit], [obs], [params]).result()
benchmark(evalfunc, estimator_grad, circuit, obs, params)
nqubits_list = range(4, 21)
@pytest.mark.parametrize("nqubits", nqubits_list)
def test_statevector(benchmark, nqubits):
benchmark.group = "qiskit_statevector"
circuit, params = generate_circuit(nqubits)
execute_statevector(benchmark, circuit, params)
# @pytest.mark.parametrize("nqubits", nqubits_list)
# def test_estimator(benchmark, nqubits):
# benchmark.group = "qiskit_estimator"
# circuit, params = generate_circuit(nqubits)
# obs = SparsePauliOp.from_list([("Z" * nqubits, 1)])
# execute_estimator(benchmark, circuit, obs, params)
# @pytest.mark.parametrize("nqubits", nqubits_list)
# def test_gradient(benchmark, nqubits):
# benchmark.group = "qiskit_gradient"
# circuit, params = generate_circuit(nqubits)
# obs = SparsePauliOp.from_list([("Z" * nqubits, 1)])
# execute_gradient(benchmark, circuit, obs, params)
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, transpile
from qiskit_qulacs import QulacsProvider
from qiskit_qulacs.qulacs_backend import QulacsBackend
from qiskit.visualization import plot_histogram, plot_state_city
import qiskit.quantum_info as qi
seed = 42
np.random.seed(seed)
provider = QulacsProvider()
qulacs_simulator = provider.get_backend("qulacs_simulator")
qulacs_simulator
qulacs_simulator.available_devices()
# Create circuit
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
# Transpile for simulator
qulacs_simulator = QulacsBackend()
circ = transpile(circ, qulacs_simulator)
# Run and get statevector
result = qulacs_simulator.run(circ).result()
statevector = result.get_statevector()
plot_state_city(statevector, title="Bell state")
result = qulacs_simulator.run(circ, shots=1024, seed_simulator=seed).result()
counts = result.get_counts()
plot_histogram(counts, title="Bell-State counts")
# Run and get memory
result = qulacs_simulator.run(circ, shots=10, seed_simulator=seed).result()
memory = result.get_memory()
print(memory)
# Create circuit
circ = QuantumCircuit(1)
for i in range(1000):
circ.h(0)
qulacs_simulator = QulacsBackend()
backend_options = {
"qco_enable": True, # Enables the QuantumCircuitOptimizer
"qco_method": "light", # Uses light method for circuit optimization from qulacs
}
qulacs_simulator.set_options(**backend_options)
# Run and get statevector
result = qulacs_simulator.run(circ).result()
statevector = result.get_statevector()
print(statevector.real)
import qiskit
qiskit.__version__
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
import numpy as np
from qiskit.circuit.library import IQP
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.quantum_info import SparsePauliOp, random_hermitian
n_qubits = 4
mat = np.real(random_hermitian(n_qubits, seed=1234))
circuit = IQP(mat)
observable = SparsePauliOp("Z" * n_qubits)
print(f">>> Observable: {observable.paulis}")
from qiskit_qulacs.qulacs_backend import QulacsBackend
backend = QulacsBackend()
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_circuit = pm.run(circuit)
isa_observable = observable.apply_layout(isa_circuit.layout)
isa_circuit.draw("mpl")
from qiskit_qulacs.qulacs_estimator import QulacsEstimator
qulacs_estimator = QulacsEstimator()
job = qulacs_estimator.run(isa_circuit, isa_observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
import numpy as np
from qiskit.circuit.library import IQP
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.quantum_info import SparsePauliOp, random_hermitian
n_qubits = 4
mat = np.real(random_hermitian(n_qubits, seed=1234))
circuit = IQP(mat)
circuit.measure_all()
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_circuit = pm.run(circuit)
from qiskit_qulacs.qulacs_sampler import QulacsSampler
qulacs_sampler = QulacsSampler()
job = qulacs_sampler.run(isa_circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-probability distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.visualization import plot_histogram
plot_histogram(result.quasi_dists[0])
import qiskit
qiskit.__version__
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
"""Variational Quantum Eigensolver (VQE) tutorial."""
from IPython.display import clear_output
import matplotlib.pyplot as plt
import numpy as np
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import JordanWignerMapper
from qiskit_nature.second_q.circuit.library import HartreeFock
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature import settings
from qiskit_algorithms.utils import algorithm_globals
from qiskit.circuit.library import EfficientSU2
from qiskit_algorithms.optimizers import L_BFGS_B
from qiskit_algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, VQE
from qiskit_qulacs.qulacs_estimator import QulacsEstimator
from qiskit_qulacs.qulacs_estimator_gradient import QulacsEstimatorGradient
settings.use_pauli_sum_op = False
algorithm_globals.random_seed = 42
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
fermionic_op = problem.hamiltonian.second_q_op()
mapper = JordanWignerMapper()
qubit_op = mapper.map(fermionic_op)
print(qubit_op)
print("Number of qubits:", qubit_op.num_qubits)
print("Number of hamiltonian terms:", len(qubit_op))
# Get reference solution
numpy_solver = NumPyMinimumEigensolver()
calc = GroundStateEigensolver(mapper, numpy_solver)
res_actual = calc.solve(problem)
print(res_actual)
exact_energy = res_actual.eigenvalues[0]
print(f"Expected ground state energy: {exact_energy:.12f} Ha")
# Hartree focks state
num_particles = problem.num_particles
num_spatial_orbitals = problem.num_spatial_orbitals
init_state = HartreeFock(
num_spatial_orbitals=num_spatial_orbitals,
num_particles=num_particles,
qubit_mapper=mapper,
)
# ansatz
ansatz = EfficientSU2(qubit_op.num_qubits, su2_gates=["ry"]).decompose()
# Add the initial state
init_state.barrier()
ansatz = init_state.compose(ansatz)
ansatz.draw("mpl")
intermediate_info = []
def callback(eval_count, parameters, value, std): # pylint: disable=unused-argument
"""
A callback that can be registered with the optimizer to store the intermediate
value and parameters.
"""
intermediate_info.append(value)
clear_output(wait=True)
plt.plot(
intermediate_info,
color="purple",
lw=2,
label=f"Simulated VQE {np.round(value,4)}",
)
plt.ylabel("Energy")
plt.xlabel("Iterations")
# Exact ground state energy value
plt.axhline(
y=exact_energy,
color="tab:red",
ls="--",
lw=2,
label="Target: " + str(np.round(exact_energy, 4)),
)
plt.legend()
plt.grid()
plt.show()
optimizer = L_BFGS_B(maxiter=20)
qulacs_estimator = QulacsEstimator()
qulacs_gradient = QulacsEstimatorGradient()
vqe = VQE(
qulacs_estimator, ansatz, optimizer, callback=callback, gradient=qulacs_gradient
)
result = vqe.compute_minimum_eigenvalue(operator=qubit_op)
print(result)
def rel_err(target, measured):
"""Compute the relative error."""
return abs((target - measured) / target)
# Compute the relative error between the expected ground state energy and the VQE's output
rel_error = rel_err(exact_energy, result.eigenvalue)
print(f"Expected ground state energy: {exact_energy:.12f}")
print(f"Computed ground state energy: {result.eigenvalue:.12f}")
print(f"Relative error: {rel_error:.12f}")
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
"""Util functions for provider"""
import re
import warnings
from math import log2
from typing import Any, Dict, Iterable, List, Set, Tuple
import numpy as np
import psutil
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter, ParameterExpression
from qiskit.circuit import library as lib
from qiskit.circuit.parametervector import ParameterVectorElement
from qiskit.quantum_info import SparsePauliOp
from scipy.sparse import diags
from sympy import lambdify
import qulacs.gate as qg
from qulacs import Observable, ParametricQuantumCircuit, PauliOperator
_EPS = 1e-10 # global variable used to chop very small numbers to zero
# Available system memory
SYSTEM_MEMORY_GB = psutil.virtual_memory().total / (1024**3)
# Max number of qubits
MAX_QUBITS = int(log2(SYSTEM_MEMORY_GB * (1024**3) / 16))
# Defintions of some gates that are not directly defined in qulacs
# The `args` argument is of the form *qubits, *parameters
# The gates defined below currently support only single parameter only
def qgUnitary(*args):
"""
The function `qgUnitary` takes qubits and parameters as input and returns a dense matrix.
Returns:
The function `qgUnitary` is returning a `qg.DenseMatrix` object created with the provided `qubits`
and `parameters`.
"""
qubits = args[:-1]
parameters = args[-1]
return qg.DenseMatrix(qubits, parameters) # pylint: disable=no-member
IsingXX = lambda *args: qg.ParametricPauliRotation(args[:-1], [1, 1], args[-1].real)
IsingYY = lambda *args: qg.ParametricPauliRotation(args[:-1], [2, 2], args[-1].real)
IsingZZ = lambda *args: qg.ParametricPauliRotation(args[:-1], [3, 3], args[-1].real)
ecr_mat = np.array(
[[0, 1, 0, 1j], [1, 0, -1j, 0], [0, 1j, 0, 1], [-1j, 0, 1, 0]]
) / np.sqrt(2)
qgECR = lambda *args: qg.DenseMatrix(args, matrix=ecr_mat)
# These gates in qulacs have positive rotation directions.
# Angles of these gates need to be multiplied by -1 during conversion.
# https://docs.qulacs.org/en/latest/guide/2.0_python_advanced.html#1-qubit-rotating-gate
neg_gates = {"RXGate", "RYGate", "RZGate", "RXXGate", "RYYGate", "RZZGate"}
# Only these gates support trainable parameters
parametric_gates = neg_gates
# Gate addition type
# based on the type of the, one of these two will be used in the qulacs circuit
gate_addition = ["add_gate", "add_parametric_gate"]
QISKIT_OPERATION_MAP = {
qg.X: lib.XGate,
qg.Y: lib.YGate,
qg.Z: lib.ZGate,
qg.H: lib.HGate,
qg.CNOT: lib.CXGate,
qg.CZ: lib.CZGate,
qg.SWAP: lib.SwapGate,
qg.FREDKIN: lib.CSwapGate,
qg.ParametricRX: lib.RXGate, # -theta
qg.ParametricRY: lib.RYGate, # -theta
qg.ParametricRZ: lib.RZGate, # -theta
qg.Identity: lib.IGate,
qg.TOFFOLI: lib.CCXGate,
qg.U1: lib.U1Gate, # deprecated in qiskit, use p gate
qg.U2: lib.U2Gate, # deprecated in qiskit, use u gate
qg.U3: lib.U3Gate, # deprecated in qiskit, use u gate
IsingXX: lib.RXXGate, # -theta
IsingYY: lib.RYYGate, # -theta
IsingZZ: lib.RZZGate, # -theta
qg.S: lib.SGate,
qg.Sdag: lib.SdgGate,
qg.T: lib.TGate,
qg.Tdag: lib.TdgGate,
qg.sqrtX: lib.SXGate,
qg.sqrtXdag: lib.SXdgGate,
qgUnitary: lib.UnitaryGate,
qgECR: lib.ECRGate,
}
inv_map = {v.__name__: k for k, v in QISKIT_OPERATION_MAP.items()}
# Gates with different names but same operation
duplicate_gates = {"UGate": "U3Gate"}
def convert_qiskit_to_qulacs_circuit(qc: QuantumCircuit):
"""
The function `convert_qiskit_to_qulacs_circuit` converts a Qiskit QuantumCircuit to a Qulacs
ParametricQuantumCircuit while handling parameter mapping and gate operations.
Args:
qc (QuantumCircuit): The `qc` is expected to be a QuantumCircuit object from Qiskit.
Returns:
The `convert_qiskit_to_qulacs_circuit` function returns a nested function `circuit_builder` that
takes an optional `params_values` argument. Inside `circuit_builder`, it constructs a
`ParametricQuantumCircuit` based on the input `QuantumCircuit` `qc` provided to the outer function.
"""
def circuit_builder(params_values=[]) -> Tuple[ParametricQuantumCircuit, Dict]:
"""
The `circuit_builder` function converts a Qiskit quantum circuit into a ParametricQuantumCircuit,
handling parameter mapping and supporting trainable parameters.
Args:
params_values: The `params_values` parameter in the `circuit_builder` function is a list that
contains the values of the parameters that will be used to build a quantum circuit. These values
will be used to replace the symbolic parameters in the quantum circuit with concrete numerical
values during the circuit construction process.
Returns:
The `circuit_builder` function returns a ParametricQuantumCircuit and a dictionary containing
information about parameter mapping and parameter expressions.
"""
circuit = ParametricQuantumCircuit(qc.num_qubits)
# parameter mapping
# dictionary from qiskit's quantum circuit parameters to a two element tuple.
# the tuple has an element params_values and its index
# Currently not supporting qiskit's parameter expression
var_ref_map = dict(
zip(qc.parameters, list(zip(params_values, range(qc.num_parameters)))),
)
# Wires from a qiskit circuit have unique IDs, so their hashes are unique too
qc_wires = [hash(q) for q in qc.qubits]
wire_map = dict(zip(qc_wires, range(len(qc_wires))))
# Holds the indices of parameter as they occur during
# circuit conversion. This is used during circuit gradient computation.
param_mapping = []
param_exprs = []
f_args: List[Any] = []
f_params: List[Any] = []
indices: List[int] = []
f_param_names: Set[Any] = set()
flag = False # indicates whether the instruction is parametric
for instruction, qargs, _ in qc.data:
# the new Singleton classes have different names than the objects they represent,
# but base_class.__name__ still matches
instruction_name = getattr(
instruction, "base_class", instruction.__class__
).__name__
instruction_name = duplicate_gates.get(instruction_name, instruction_name)
sign = 1.0 - 2 * (instruction_name in neg_gates)
operation_wires = [wire_map[hash(qubit)] for qubit in qargs]
operation_params = []
flag = False
for p in instruction.params:
if isinstance(p, ParameterExpression) and p.parameters:
f_args = []
f_params = []
indices = []
# Ensure duplicate subparameters are only appended once.
f_param_names = set()
for subparam in p.parameters:
try:
parameter = subparam
argument, index = var_ref_map.get(subparam)
except:
raise ValueError(
"The number of circuit parameters does not match",
" the number of parameter values passed.",
)
if isinstance(subparam, ParameterVectorElement):
# Unfortunately, the names of parameter vector elements
# include square brackets, making them invalid Python
# identifiers and causing compatibility problems with SymPy.
# To solve this issue, we generate a temporary parameter
# that replaces square bracket by underscores.
subparam_name = re.sub(r"\[|\]", "_", str(subparam))
parameter = Parameter(subparam_name)
argument, index = var_ref_map.get(subparam)
# Update the subparam in `p`
p = p.assign(subparam, parameter)
if parameter.name not in f_param_names:
f_param_names.add(parameter.name)
f_params.append(parameter)
f_args.append(argument)
indices.append(index)
f_expr = getattr(p, "_symbol_expr")
if isinstance(p, Parameter):
# If `p` is an instance of `Parameter` then we can
# we do not need to calculate the expression value
operation_params += list(map(lambda x: x * sign, f_args))
else:
# Calculate the expression value using sympy
f = lambdify(f_params, f_expr)
operation_params += [f(*f_args) * sign]
param_mapping += indices
param_exprs += [(f_params, f_expr)]
flag = True
else:
operation_params.append(p * sign)
operation_class = inv_map.get(instruction_name)
try:
getattr(circuit, gate_addition[flag])(
operation_class(*operation_wires, *operation_params) # type: ignore
)
except:
if flag:
raise ValueError(
f"{__name__}: The {instruction_name} does not support trainable parameter.",
f" Consider decomposing {instruction_name} into {parametric_gates}.",
)
warnings.warn(
f"{__name__}: The {instruction_name} instruction is not supported"
" by Qiskit-Qulacs and has not been added to the circuit.",
UserWarning,
)
if qc.global_phase > _EPS:
# add the gphase_mat to the circuit
circuit.add_gate(
qg.SparseMatrix( # pylint: disable=no-member
list(range(qc.num_qubits)),
diags(np.exp(1j * qc.global_phase) * np.ones(2**qc.num_qubits)),
)
)
return circuit, {
"parameter_mapping": param_mapping,
"parameter_exprs": param_exprs,
}
return circuit_builder
def qiskit_to_qulacs(
circuits: List[QuantumCircuit],
) -> Iterable[ParametricQuantumCircuit]:
"""
The function `qiskit_to_qulacs` converts a list of Qiskit quantum circuits
into a generator of Qulacs circuits.
Args:
circuits (List[QuantumCircuit]): The `circuits` parameter is a list of
`QuantumCircuit` objects.
"""
for circuit in circuits:
yield convert_qiskit_to_qulacs_circuit(circuit)()[0]
def convert_sparse_pauliop_to_qulacs_obs(sparse_pauliop: SparsePauliOp):
"""
The function `convert_sparse_pauliop_to_qulacs_obs` converts a
sparse Pauli operator to a Qulacs observable.
Args:
sparse_pauliop: The `sparse_pauliop` parameter is a sparse
representation of a Pauli operator. It is an object that contains
information about the Pauli terms and their coefficients. Each term is
represented by a `PauliTerm` object, which consists of a list of Pauli
operators and their corresponding
Returns:
a Qulacs Observable object.
"""
qulacs_observable = Observable(sparse_pauliop.num_qubits)
for op in sparse_pauliop:
term, coefficient = str(op.paulis[0])[::-1], op.coeffs[0]
pauli_string = ""
for qubit, pauli in enumerate(term):
pauli_string += f"{pauli} {qubit} "
qulacs_observable.add_operator(PauliOperator(pauli_string, coefficient.real))
return qulacs_observable
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
"""QulacsBackend class."""
import copy
import time
import uuid
from collections import Counter
from typing import List, Union
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers import BackendV1 as Backend
from qiskit.providers import JobStatus, Options
from qiskit.providers.models import QasmBackendConfiguration
from qiskit.result import Result
from qiskit.result.models import ExperimentResult, ExperimentResultData
import qulacs
from qulacs.circuit import QuantumCircuitOptimizer
from .adapter import MAX_QUBITS, qiskit_to_qulacs
from .backend_utils import BASIS_GATES, available_devices, generate_config
from .qulacs_job import QulacsJob
from .version import __version__
class QulacsBackend(Backend):
"""QulacsBackend class."""
_BASIS_GATES = BASIS_GATES
_DEFAULT_CONFIGURATION = {
"backend_name": "qulacs_simulator",
"backend_version": __version__,
"n_qubits": MAX_QUBITS,
"url": "https://github.com/Gopal-Dahale/qiskit-qulacs",
"simulator": True,
"local": True,
"conditional": True,
"open_pulse": False,
"memory": True,
"max_shots": int(1e6),
"description": "A Qulacs fast quantum circuit simulator",
"coupling_map": None,
"basis_gates": _BASIS_GATES,
"gates": [],
}
_SIMULATION_DEVICES = ("CPU", "GPU")
_AVAILABLE_DEVICES = None
def __init__(
self, configuration=None, properties=None, provider=None, **backend_options
):
# Update available devices for class
if QulacsBackend._AVAILABLE_DEVICES is None:
QulacsBackend._AVAILABLE_DEVICES = available_devices(
QulacsBackend._SIMULATION_DEVICES
)
# Default configuration
if configuration is None:
configuration = QasmBackendConfiguration.from_dict(
QulacsBackend._DEFAULT_CONFIGURATION
)
super().__init__(
configuration,
provider=provider,
)
# Initialize backend properties
self._properties = properties
# Set options from backend_options dictionary
if backend_options is not None:
self.set_options(**backend_options)
# Quantum circuit optimizer (if needed)
self.qc_opt = QuantumCircuitOptimizer()
self.class_suffix = {
"GPU": "Gpu",
"CPU": "",
}
@classmethod
def _default_options(cls):
return Options(
# Global options
shots=0,
device="CPU",
seed_simulator=None,
# Quantum Circuit Optimizer options
qco_enable=False,
qco_method="light",
qco_max_block_size=2,
)
def __repr__(self):
"""String representation of an QulacsBackend."""
name = self.__class__.__name__
display = f"'{self.name()}'"
return f"{name}({display})"
def available_devices(self):
"""Return the available simulation methods."""
return copy.copy(self._AVAILABLE_DEVICES)
def _execute_circuits_job(self, circuits, states, run_options, job_id=""):
"""Run a job"""
shots = run_options.shots
seed = (
run_options.seed_simulator
if run_options.seed_simulator
else np.random.randint(1000)
)
# Start timer
start = time.time()
expt_results = []
if shots:
for state, circuit in zip(states, circuits):
circuit.update_quantum_state(state)
n = circuit.get_qubit_count()
samples = state.sampling(shots, seed)
bitstrings = [format(x, f"0{n}b") for x in samples]
counts = dict(Counter(bitstrings))
expt_results.append(
ExperimentResult(
shots=shots,
success=True,
status=JobStatus.DONE,
data=ExperimentResultData(counts=counts, memory=bitstrings),
)
)
else:
for state, circuit in zip(states, circuits):
circuit.update_quantum_state(state)
# Statevector
expt_results.append(
ExperimentResult(
shots=shots,
success=True,
status=JobStatus.DONE,
data=ExperimentResultData(
statevector=state.get_vector(),
),
)
)
return Result(
backend_name=self.name(),
backend_version=self.configuration().backend_version,
job_id=job_id,
qobj_id=0,
success=True,
results=expt_results,
status=JobStatus.DONE,
time_taken=time.time() - start,
)
def run(
self,
run_input: Union[QuantumCircuit, List[QuantumCircuit]],
**run_options,
) -> QulacsJob:
run_input = [run_input] if isinstance(run_input, QuantumCircuit) else run_input
run_input = list(qiskit_to_qulacs(run_input))
config = (
generate_config(self.options, run_options) if run_options else self.options
)
# Use GPU if available
if config.device not in self.available_devices():
if config.device == "GPU":
raise ValueError("GPU support not installed. Install qulacs-gpu.")
raise ValueError(f"Device {config.device} not found.")
class_name = f'QuantumState{self.class_suffix.get(config.device, "")}'
state_class = getattr(qulacs, class_name)
# Use Quantum Circuit Optimizer
if config.qco_enable:
if config.qco_method == "light":
for circuit in run_input:
self.qc_opt.optimize_light(circuit)
elif config.qco_method == "greedy":
for circuit in run_input:
self.qc_opt.optimize(circuit, config.qco_max_block_size)
# Create quantum states
states = [state_class(circuit.get_qubit_count()) for circuit in run_input]
# Submit job
job_id = str(uuid.uuid4())
qulacs_job = QulacsJob(
self,
job_id,
self._execute_circuits_job,
circuits=run_input,
states=states,
run_options=config,
)
qulacs_job.submit()
return qulacs_job
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
"""Tests for the Adapter class."""
from unittest import TestCase
import numpy as np
import pytest
import qiskit.circuit.library as lib
from ddt import data, ddt
from qiskit import QuantumCircuit, QuantumRegister, transpile
from qiskit.circuit import Parameter, ParameterVector
from qiskit.circuit.library import PauliEvolutionGate, TwoLocal
from qiskit.quantum_info import SparsePauliOp
from qiskit_aer import Aer
from qiskit_qulacs.adapter import (
convert_qiskit_to_qulacs_circuit,
convert_sparse_pauliop_to_qulacs_obs,
)
from qiskit_qulacs.qulacs_backend import QulacsBackend
from qulacs import Observable, ParametricQuantumCircuit, PauliOperator, QuantumState
# FSim Gate with fixed parameters
# source: https://quantumai.google/reference/python/cirq/FSimGate
fsim_mat = np.array(
[
[1, 0, 0, 0],
[0, np.cos(np.pi / 3), -1j * np.sin(np.pi / 3), 0],
[0, -1j * np.sin(np.pi / 3), np.cos(np.pi / 3), 0],
[0, 0, 0, np.exp(-1j * np.pi / 4)],
]
)
qiskit_standard_gates = [
lib.IGate(),
lib.SXGate(),
lib.XGate(),
lib.CXGate(),
lib.RZGate(Parameter("λ")),
lib.RGate(Parameter("ϴ"), Parameter("φ")),
lib.C3SXGate(),
lib.CCXGate(),
lib.DCXGate(),
lib.CHGate(),
lib.CPhaseGate(Parameter("ϴ")),
lib.CRXGate(Parameter("ϴ")),
lib.CRYGate(Parameter("ϴ")),
lib.CRZGate(Parameter("ϴ")),
lib.CSwapGate(),
lib.CSXGate(),
lib.CUGate(Parameter("ϴ"), Parameter("φ"), Parameter("λ"), Parameter("γ")),
lib.CU1Gate(Parameter("λ")),
lib.CU3Gate(Parameter("ϴ"), Parameter("φ"), Parameter("λ")),
lib.CYGate(),
lib.CZGate(),
lib.CCZGate(),
lib.HGate(),
lib.PhaseGate(Parameter("ϴ")),
lib.RCCXGate(),
lib.RC3XGate(),
lib.RXGate(Parameter("ϴ")),
lib.RXXGate(Parameter("ϴ")),
lib.RYGate(Parameter("ϴ")),
lib.RYYGate(Parameter("ϴ")),
lib.RZZGate(Parameter("ϴ")),
lib.RZXGate(Parameter("ϴ")),
lib.XXMinusYYGate(Parameter("ϴ"), Parameter("φ")),
lib.XXPlusYYGate(Parameter("ϴ"), Parameter("φ")),
lib.ECRGate(),
lib.SGate(),
lib.SdgGate(),
lib.CSGate(),
lib.CSdgGate(),
lib.SwapGate(),
lib.iSwapGate(),
lib.SXdgGate(),
lib.TGate(),
lib.TdgGate(),
lib.UGate(Parameter("ϴ"), Parameter("φ"), Parameter("λ")),
lib.U1Gate(Parameter("λ")),
lib.U2Gate(Parameter("φ"), Parameter("λ")),
lib.U3Gate(Parameter("ϴ"), Parameter("φ"), Parameter("λ")),
lib.YGate(),
lib.ZGate(),
]
def convert_and_check_statevector(testcase, qc, params=[]):
"""
The function converts a Qiskit quantum circuit to a Qulacs circuit,
obtains the statevectors from both frameworks, and checks if they are close.
Args:
testcase: instance of a unittest test case.
qc: quantum circuit in Qiskit.
params: list that contains the parameters to be assigned to the quantum circuit `qc`.
"""
# convert qiskit's quantum circuit to qulacs
qulacs_circuit_builder = convert_qiskit_to_qulacs_circuit(qc)
qulacs_circuit = qulacs_circuit_builder(params)[0]
# Obtaining statevector from qiskit
if params:
qc = qc.assign_parameters(params)
qc.save_statevector()
qiskit_sv = testcase.aer_backend.run(qc).result().get_statevector().data
# Obtaining statevector from qulacs
quantum_state = QuantumState(qulacs_circuit.get_qubit_count())
qulacs_circuit.update_quantum_state(quantum_state)
qulacs_sv = quantum_state.get_vector()
testcase.assertTrue(np.allclose(qiskit_sv, qulacs_sv))
class TestAdapterConverter(TestCase):
"""Tests for the Adapter class."""
def setUp(self):
self.aer_backend = Aer.get_backend("aer_simulator_statevector")
def test_state_preparation_01(self):
"""Tests state_preparation handling of Adapter"""
qulacs_backend = QulacsBackend()
input_state_vector = np.array([np.sqrt(3) / 2, np.sqrt(2) * complex(1, 1) / 4])
qiskit_circuit = QuantumCircuit(1)
qiskit_circuit.prepare_state(input_state_vector, 0)
transpiled_qiskit_circuit = transpile(qiskit_circuit, qulacs_backend)
convert_and_check_statevector(self, transpiled_qiskit_circuit)
def test_state_preparation_00(self):
"""Tests state_preparation handling of Adapter"""
qulacs_backend = QulacsBackend()
input_state_vector = np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])
qiskit_circuit = QuantumCircuit(1)
qiskit_circuit.prepare_state(input_state_vector, 0)
transpiled_qiskit_circuit = transpile(qiskit_circuit, qulacs_backend)
convert_and_check_statevector(self, transpiled_qiskit_circuit)
def test_convert_parametric_qiskit_to_qulacs_circuit(self):
"""Tests convert_qiskit_to_qulacs_circuit works with parametric circuits."""
theta = Parameter("θ")
phi = Parameter("φ")
lam = Parameter("λ")
params = np.array([np.pi, np.pi / 2, np.pi / 3])
qiskit_circuit = QuantumCircuit(1, 1)
qiskit_circuit.rx(theta, 0)
qiskit_circuit.ry(phi, 0)
qiskit_circuit.rz(lam, 0)
qulacs_circuit_builder = convert_qiskit_to_qulacs_circuit(qiskit_circuit)
qulacs_circuit = qulacs_circuit_builder(params)[0]
quantum_state = QuantumState(1)
qulacs_circuit.update_quantum_state(quantum_state)
qulacs_result = quantum_state.get_vector()
# https://qiskit.org/documentation/stubs/qiskit.circuit.QuantumCircuit.html#qiskit.circuit.QuantumCircuit.parameters
# Based on the above docs, the Paramters are sorted alphabetically.
# Therefore θ, φ, λ should be sorted as θ, λ, φ.
# so θ = params[0], λ = params[1], φ = params[2]
# Also, the sign of the rotation is negative in qulacs.
qulacs_circuit_ans = ParametricQuantumCircuit(1)
qulacs_circuit_ans.add_parametric_RX_gate(0, -params[0])
qulacs_circuit_ans.add_parametric_RY_gate(0, -params[2])
qulacs_circuit_ans.add_parametric_RZ_gate(0, -params[1])
quantum_state_ans = QuantumState(1)
qulacs_circuit_ans.update_quantum_state(quantum_state_ans)
qulacs_result_ans = quantum_state_ans.get_vector()
self.assertTrue(np.allclose(qulacs_result, qulacs_result_ans))
def test_longer_parameter_expression(self):
"""Tests parameter expression with arbitrary operations and length"""
theta = Parameter("θ")
phi = Parameter("φ")
lam = Parameter("λ")
values = [0.1, 0.2, 0.3]
qc = QuantumCircuit(1, 1)
qc.rx(phi * np.cos(theta) + lam, 0)
convert_and_check_statevector(self, qc, values)
def test_quantum_circuit_loaded_multiple_times_with_different_arguments(self):
"""Tests that a loaded quantum circuit can be called multiple times with
different arguments."""
theta = Parameter("θ")
angle1 = 0.5
angle2 = -0.5
angle3 = 0
qc = QuantumCircuit(3, 1)
qc.rz(theta, [0])
convert_and_check_statevector(self, qc, [angle1])
convert_and_check_statevector(self, qc, [angle2])
convert_and_check_statevector(self, qc, [angle3])
def test_quantum_circuit_with_bound_parameters(self):
"""Tests loading a quantum circuit that already had bound parameters."""
theta = Parameter("θ")
qc = QuantumCircuit(3, 1)
qc.rz(theta, [0])
qc = qc.assign_parameters({theta: 0.5})
convert_and_check_statevector(self, qc)
def test_unused_parameters_are_ignored(self):
"""Tests that unused parameters are ignored during assignment."""
a, b, c = [Parameter(var) for var in "abc"]
v = ParameterVector("v", 2)
qc = QuantumCircuit(1)
qc.rz(a, 0)
# convert qiskit's quantum circuit to qulacs
qulacs_circuit_builder = convert_qiskit_to_qulacs_circuit(qc)
qulacs_circuit = qulacs_circuit_builder([0.1, 0.2, 0.3, 0.4, 0.5])[0]
# Obtaining statevector from qiskit
qc = qc.assign_parameters([0.1])
qc.save_statevector()
qiskit_sv = self.aer_backend.run(qc).result().get_statevector().data
# Obtaining statevector from qulacs
quantum_state = QuantumState(qulacs_circuit.get_qubit_count())
qulacs_circuit.update_quantum_state(quantum_state)
qulacs_sv = quantum_state.get_vector()
self.assertTrue(np.allclose(qiskit_sv, qulacs_sv))
def test_unused_parameter_vector_items_are_ignored(self):
"""Tests that unused parameter vector items are ignored during assignment."""
a, b, c = [Parameter(var) for var in "abc"]
v = ParameterVector("v", 2)
qc = QuantumCircuit(1)
qc.rz(v[1], 0)
# convert qiskit's quantum circuit to qulacs
qulacs_circuit_builder = convert_qiskit_to_qulacs_circuit(qc)
qulacs_circuit = qulacs_circuit_builder([0.1, 0.2, 0.3, 0.4, 0.5])[0]
# Obtaining statevector from qiskit
qc = qc.assign_parameters([0.1])
qc.save_statevector()
qiskit_sv = self.aer_backend.run(qc).result().get_statevector().data
# Obtaining statevector from qulacs
quantum_state = QuantumState(qulacs_circuit.get_qubit_count())
qulacs_circuit.update_quantum_state(quantum_state)
qulacs_sv = quantum_state.get_vector()
self.assertTrue(np.allclose(qiskit_sv, qulacs_sv))
def test_wires_two_different_quantum_registers(self):
"""Tests loading a circuit with the three-qubit operations supported by PennyLane."""
three_wires = [0, 1, 2]
qr1 = QuantumRegister(2)
qr2 = QuantumRegister(1)
qc = QuantumCircuit(qr1, qr2)
qc.cswap(*three_wires)
convert_and_check_statevector(self, qc)
class TestConverterGates(TestCase):
"""Tests for the Adapter class."""
def setUp(self):
self.aer_backend = Aer.get_backend("aer_simulator_statevector")
def test_u_gate(self):
"""Tests adapter conversion of u gate"""
qiskit_circuit = QuantumCircuit(1)
qiskit_circuit.u(np.pi / 2, np.pi / 3, np.pi / 4, 0)
convert_and_check_statevector(self, qiskit_circuit)
def test_standard_gate_decomp(self):
"""Tests adapter decomposition of all standard gates to forms that can be translated"""
qulacs_backend = QulacsBackend()
for standard_gate in qiskit_standard_gates:
qiskit_circuit = QuantumCircuit(standard_gate.num_qubits)
qiskit_circuit.append(standard_gate, range(standard_gate.num_qubits))
parameters = standard_gate.params
if parameters:
parameter_values = [
(137 / 61) * np.pi / i for i in range(1, len(parameters) + 1)
]
parameter_bindings = dict(zip(parameters, parameter_values))
qiskit_circuit = qiskit_circuit.assign_parameters(parameter_bindings)
transpiled_qiskit_circuit = transpile(qiskit_circuit, qulacs_backend)
with self.subTest(f"Circuit with {standard_gate.name} gate."):
qulacs_job = qulacs_backend.run(transpiled_qiskit_circuit)
qulacs_result = qulacs_job.result().get_statevector()
transpiled_qiskit_circuit.save_statevector()
qiskit_job = self.aer_backend.run(transpiled_qiskit_circuit)
qiskit_result = qiskit_job.result().get_statevector().data
self.assertTrue(np.allclose(qulacs_result, qiskit_result))
def test_exponential_gate_decomp(self):
"""Tests adapter translation of exponential gates"""
qulacs_backend = QulacsBackend()
qiskit_circuit = QuantumCircuit(2)
hamiltonian = SparsePauliOp(["ZZ", "XI"], [1.0, -0.1])
evo = PauliEvolutionGate(hamiltonian, time=2)
qiskit_circuit.append(evo, range(2))
transpiled_qiskit_circuit = transpile(qiskit_circuit, qulacs_backend)
qulacs_job = qulacs_backend.run(transpiled_qiskit_circuit)
qulacs_result = qulacs_job.result().get_statevector()
transpiled_qiskit_circuit.save_statevector()
qiskit_job = self.aer_backend.run(transpiled_qiskit_circuit)
qiskit_result = np.array(qiskit_job.result().get_statevector())
self.assertTrue(np.allclose(qulacs_result, qiskit_result))
def test_unitary_gate(self):
"""Test for unitary gate"""
qiskit_circuit = QuantumCircuit(2)
qiskit_circuit.unitary(fsim_mat, [0, 1])
convert_and_check_statevector(self, qiskit_circuit)
class TestConverterWarningsAndErrors(TestCase):
def test_params_not_passed(self):
"""Tests that a warning is raised if circuit has params but not params passed."""
qc = QuantumCircuit(1)
qc.rx(Parameter("θ"), 0)
with pytest.raises(
ValueError, match="The number of circuit parameters does not match"
):
qulacs_circuit_builder = convert_qiskit_to_qulacs_circuit(qc)
qulacs_circuit_builder()[0]
def test_template_not_supported(self):
"""Tests that a warning is raised if an unsupported instruction was reached."""
qc = TwoLocal(
4,
["rx", "ry", "rz"],
["cz", "cx"],
"linear",
reps=1,
)
params = np.random.uniform(size=qc.num_parameters)
with pytest.raises(
ValueError, match="The Gate does not support trainable parameter"
):
qulacs_circuit_builder = convert_qiskit_to_qulacs_circuit(qc)
qulacs_circuit_builder(params)[0]
def test_unsupported_gate(self):
"""Tests that a warning is raised if an unsupported gate was reached"""
qc = QuantumCircuit(1)
qc.rx(0.1, 0)
qc.measure_all()
with pytest.warns(UserWarning, match="not supported by Qiskit-Qulacs"):
qulacs_circuit_builder = convert_qiskit_to_qulacs_circuit(qc)
qulacs_circuit_builder()[0]
dummy_obs = [Observable(1), Observable(3), Observable(2)]
dummy_obs[0].add_operator(PauliOperator("I 0", 2.0))
dummy_obs[1].add_operator(PauliOperator("Z 0 Y 1 X 2", 1.0))
dummy_obs[2].add_operator(PauliOperator("Y 0 X 1", 3.0))
dummy_obs[2].add_operator(PauliOperator("X 0 Z 1", 7.0))
observable_factories = [
(SparsePauliOp("I", coeffs=[2]), dummy_obs[0]),
(SparsePauliOp("XYZ"), dummy_obs[1]),
(SparsePauliOp(["XY", "ZX"], coeffs=[3, 7]), dummy_obs[2]),
]
@ddt
class TestConverterObservable(TestCase):
"""Tests for the Adapter class."""
@data(*observable_factories)
def test_convert_with_coefficients(self, ops):
"""Tests that a SparsePauliOp can be converted into a PennyLane operator with the default
coefficients.
"""
pauli_op, want_op = ops
have_op = convert_sparse_pauliop_to_qulacs_obs(pauli_op)
assert have_op.to_json() == want_op.to_json()
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
"""Tests for qulacs backend."""
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.circuit.random import random_circuit
from qiskit.result import Result
from qiskit_aer import Aer
from qiskit_qulacs.qulacs_backend import QulacsBackend
from tests.utils import dicts_almost_equal
_EPS = 1e-10 # global variable used to chop very small numbers to zero
class TestQulacsBackend(TestCase):
"""Tests BraketBackend."""
def setUp(self):
self.aer_backend = Aer.get_backend("aer_simulator_statevector")
def test_qulacs_backend_output(self):
"""Test qulacs backend output"""
qulacs_backend = QulacsBackend()
self.assertEqual(qulacs_backend.name(), "qulacs_simulator")
def test_qulacs_backend_circuit(self):
"""Tests qulacs backend with circuit."""
backend = QulacsBackend()
circuits = []
# Circuit 0
q_c = QuantumCircuit(2)
q_c.x(0)
q_c.cx(0, 1)
circuits.append(q_c)
# Circuit 1
q_c = QuantumCircuit(2)
q_c.h(0)
q_c.cx(0, 1)
circuits.append(q_c)
results = []
for circuit in circuits:
results.append(backend.run(circuit).result())
# Result 0
self.assertTrue(
(
np.linalg.norm(results[0].get_statevector() - np.array([0, 0, 0, 1]))
< _EPS
)
)
# Result 1
_00 = np.abs(results[1].get_statevector()[0]) ** 2
_11 = np.abs(results[1].get_statevector()[-1]) ** 2
self.assertTrue(np.allclose([_00, _11], [0.5, 0.5]))
def test_random_circuits(self):
"""Tests with random circuits."""
qulacs_backend = QulacsBackend()
for i in range(1, 10):
with self.subTest(f"Random circuit with {i} qubits."):
qiskit_circuit = random_circuit(i, 5, seed=42)
transpiled_qiskit_circuit = transpile(qiskit_circuit, qulacs_backend)
qulacs_result = (
qulacs_backend.run(transpiled_qiskit_circuit)
.result()
.get_statevector()
)
transpiled_qiskit_circuit.save_statevector()
aer_result = (
self.aer_backend.run(transpiled_qiskit_circuit)
.result()
.get_statevector()
.data
)
self.assertTrue(np.linalg.norm(qulacs_result - aer_result) < _EPS)
def test_single_shot(self):
"""Test single shot run."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
shots = 1
qulacs_backend = QulacsBackend()
result = qulacs_backend.run(bell, shots=shots, seed_simulator=10).result()
self.assertEqual(result.success, True)
def test_against_reference(self):
"""Test data counts output for single circuit run against reference."""
qulacs_backend = QulacsBackend()
shots = 1024
threshold = 0.04 * shots
qc = QuantumCircuit(6)
qc.h(range(6))
qc.cx([0, 1, 2], [3, 4, 5])
counts = (
qulacs_backend.run(qc, shots=shots, seed_simulator=10).result().get_counts()
)
counts = {i: j / shots for i, j in counts.items()}
qc.save_statevector()
target = (
self.aer_backend.run(qc, shots=shots, seed_simulator=10)
.result()
.get_counts()
)
error_msg = dicts_almost_equal(counts, target, threshold)
if error_msg:
msg = self._formatMessage(None, error_msg)
raise self.failureException(msg)
def test_options(self):
"""Test for options"""
backend_options = {
"shots": 3000,
"seed_simulator": 42,
"device": "CPU",
"qco_enable": True,
"qco_method": "greedy",
"qco_max_block_size": 5,
}
with self.subTest("set_options"):
qulacs_backend = QulacsBackend()
qulacs_backend.set_options(**backend_options)
self.assertEqual(qulacs_backend.options.get("shots"), 3000)
self.assertEqual(qulacs_backend.options.get("seed_simulator"), 42)
self.assertEqual(qulacs_backend.options.get("device"), "CPU")
self.assertEqual(qulacs_backend.options.get("qco_enable"), True)
self.assertEqual(qulacs_backend.options.get("qco_method"), "greedy")
self.assertEqual(qulacs_backend.options.get("qco_max_block_size"), 5)
with self.subTest("run"):
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
qulacs_backend = QulacsBackend()
result = qulacs_backend.run(
[bell],
qco_enable=True,
qco_method="light",
).result()
self.assertIsInstance(result, Result)
np.testing.assert_allclose(
result.get_statevector(),
(1 / np.sqrt(2)) * np.array([1.0, 0.0, 0.0, 1.0]),
)
def test_repr(self):
"""Test string repr"""
qulacs_backend = QulacsBackend()
self.assertEqual(str(qulacs_backend), "qulacs_simulator")
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
"""Test Qulacs Estimator Gradients"""
from unittest import TestCase
import numpy as np
import pytest
from ddt import data, ddt
from qiskit import QuantumCircuit, transpile
from qiskit.circuit import Parameter, ParameterVector
from qiskit.circuit.library import EfficientSU2
from qiskit.circuit.library.standard_gates import RXXGate, RYYGate, RZXGate, RZZGate
from qiskit.quantum_info import SparsePauliOp
from qiskit_algorithms.gradients import ReverseEstimatorGradient
from qiskit_qulacs.qulacs_backend import QulacsBackend
from qiskit_qulacs.qulacs_estimator_gradient import QulacsEstimatorGradient
gradient_factories = [QulacsEstimatorGradient]
@ddt
class TestQulacsEstimatorGradient(TestCase):
"""Test Estimator Gradient"""
@data(*gradient_factories)
def test_gradient_operators(self, grad):
"""Test the estimator gradient for different operators"""
a = Parameter("a")
qc = QuantumCircuit(1)
qc.rx(a, 0)
gradient = grad()
op = SparsePauliOp.from_list([("Z", 1)])
correct_result = -1 / np.sqrt(2)
param = [np.pi / 4]
value = gradient.run([qc], [op], [param]).result().gradients[0]
self.assertAlmostEqual(value[0], correct_result, 3)
@data(*gradient_factories)
def test_gradient_efficient_su2(self, grad):
"""Test the estimator gradient for EfficientSU2"""
qc = EfficientSU2(2, reps=1).decompose()
op = SparsePauliOp.from_list([("ZI", 1)])
gradient = grad()
param_list = [
[np.pi / 4 for param in qc.parameters],
[np.pi / 2 for param in qc.parameters],
]
correct_results = [
[
-0.35355339,
-0.70710678,
0,
0.35355339,
0,
-0.70710678,
0,
0,
],
[0, 0, 0, 1, 0, 0, 0, 0],
]
for i, param in enumerate(param_list):
gradients = gradient.run([qc], [op], [param]).result().gradients[0]
np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3)
@data(*gradient_factories)
def test_gradient_2qubit_gate(self, grad):
"""Test the estimator gradient for 2 qubit gates"""
qulacs_backend = QulacsBackend()
for gate in [RXXGate, RYYGate, RZZGate, RZXGate]:
param_list = [[np.pi / 4], [np.pi / 2]]
correct_results = [
[-0.70710678],
[-1],
]
op = SparsePauliOp.from_list([("ZI", 1)])
for i, param in enumerate(param_list):
a = Parameter("a")
qc = QuantumCircuit(2)
gradient = grad()
if gate is RZZGate:
qc.h([0, 1])
qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], [])
qc.h([0, 1])
else:
qc.append(gate(a), [qc.qubits[0], qc.qubits[1]], [])
tqc = transpile(qc, qulacs_backend)
gradients = gradient.run([tqc], [op], [param]).result().gradients[0]
np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3)
@data(*gradient_factories)
def test_gradient_parameters(self, grad):
"""Test the estimator gradient for parameters"""
a = Parameter("a")
b = Parameter("b")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.rx(b, 0)
gradient = grad()
param_list = [[np.pi / 4, np.pi / 2]]
correct_results = [
[-0.70710678],
]
op = SparsePauliOp.from_list([("Z", 1)])
for i, param in enumerate(param_list):
gradients = (
gradient.run([qc], [op], [param], parameters=[[a]])
.result()
.gradients[0]
)
np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3)
# parameter order
with self.subTest(msg="The order of gradients"):
c = Parameter("c")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc.rz(b, 0)
qc.rx(c, 0)
param_list = [[np.pi / 4, np.pi / 2, np.pi / 3]]
correct_results = [
[-0.35355339, 0.61237244, -0.61237244],
[-0.61237244, 0.61237244, -0.35355339],
[-0.35355339, -0.61237244],
[-0.61237244, -0.35355339],
]
param = [[a, b, c], [c, b, a], [a, c], [c, a]]
op = SparsePauliOp.from_list([("Z", 1)])
for i, p in enumerate(param):
gradient = grad()
gradients = (
gradient.run([qc], [op], param_list, parameters=[p])
.result()
.gradients[0]
)
np.testing.assert_allclose(gradients, correct_results[i], atol=1e-3)
@data(*gradient_factories)
def test_gradient_multi_arguments(self, grad):
"""Test the estimator gradient for multiple arguments"""
a = Parameter("a")
b = Parameter("b")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qc2 = QuantumCircuit(1)
qc2.rx(b, 0)
gradient = grad()
param_list = [[np.pi / 4], [np.pi / 2]]
correct_results = [
[-0.70710678],
[-1],
]
op = SparsePauliOp.from_list([("Z", 1)])
gradients = gradient.run([qc, qc2], [op] * 2, param_list).result().gradients
np.testing.assert_allclose(gradients, correct_results, atol=1e-3)
c = Parameter("c")
qc3 = QuantumCircuit(1)
qc3.rx(c, 0)
qc3.ry(a, 0)
param_list2 = [[np.pi / 4], [np.pi / 4, np.pi / 4], [np.pi / 4, np.pi / 4]]
correct_results2 = [
[-0.70710678],
[-0.5],
[-0.5, -0.5],
]
gradients2 = (
gradient.run(
[qc, qc3, qc3], [op] * 3, param_list2, parameters=[[a], [c], None]
)
.result()
.gradients
)
np.testing.assert_allclose(gradients2[0], correct_results2[0], atol=1e-3)
np.testing.assert_allclose(gradients2[1], correct_results2[1], atol=1e-3)
np.testing.assert_allclose(gradients2[2], correct_results2[2], atol=1e-3)
@data(*gradient_factories)
def test_gradient_validation(self, grad):
"""Test estimator gradient's validation"""
a = Parameter("a")
qc = QuantumCircuit(1)
qc.rx(a, 0)
gradient = grad()
param_list = [[np.pi / 4], [np.pi / 2]]
op = SparsePauliOp.from_list([("Z", 1)])
with self.assertRaises(ValueError):
gradient.run([qc], [op], param_list)
with self.assertRaises(ValueError):
gradient.run([qc, qc], [op, op], param_list, parameters=[[a]])
with self.assertRaises(ValueError):
gradient.run([qc, qc], [op], param_list, parameters=[[a]])
with self.assertRaises(ValueError):
gradient.run([qc], [op], [[np.pi / 4, np.pi / 4]])
@data(*gradient_factories)
def test_gradient_with_parameter_vector(self, grad):
"""Tests that the gradient of a circuit with a parameter vector is calculated correctly."""
qiskit_circuit = QuantumCircuit(1)
theta_param = ParameterVector("θ", 2)
theta_val = np.array([np.pi / 4, np.pi / 16])
qiskit_circuit.rx(theta_param[0], 0)
qiskit_circuit.rx(theta_param[1] * 4, 0)
op = SparsePauliOp.from_list([("Z", 1)])
est_grad = grad()
have_gradient = (
est_grad.run([qiskit_circuit], [op], [theta_val]).result().gradients[0]
)
want_gradient = [-1, -4]
assert np.allclose(have_gradient, want_gradient)
@data(*gradient_factories)
def test_gradient_with_parameter_expressions(self, grad):
"""Tests that the gradient of a circuit with parameter expressions is calculated correctly."""
qiskit_circuit = QuantumCircuit(1)
theta_param = ParameterVector("θ", 3)
theta_val = [3 * np.pi / 16, np.pi / 64]
phi_param = Parameter("φ")
phi_val = [np.pi / 8]
# Apply an instruction with a regular parameter.
qiskit_circuit.rx(phi_param, 0)
# Apply an instruction with a parameter vector element.
qiskit_circuit.rx(theta_param[0], 0)
# Apply an instruction with a parameter expression involving one parameter.
qiskit_circuit.rx(theta_param[1] + theta_param[1] + np.cos(theta_param[1]), 0)
op = SparsePauliOp.from_list([("Z", 1)])
est_grad = grad()
qiskit_grad = ReverseEstimatorGradient()
have_gradient = (
est_grad.run([qiskit_circuit], [op], [theta_val + phi_val])
.result()
.gradients[0]
)
want_gradient = (
qiskit_grad.run([qiskit_circuit], [op], [theta_val + phi_val])
.result()
.gradients[0]
)
self.assertTrue(np.allclose(have_gradient, want_gradient))
@ddt
class TestQulacsEstimatorGradientWarningsAndErrors(TestCase):
"""Test Estimator Gradient"""
@data(*gradient_factories)
def test_gradient_with_parameter_expression_having_two_paramters(self, grad):
"""Test gradient when two different parameters are passed in a single expression"""
qiskit_circuit = QuantumCircuit(1)
theta_param = ParameterVector("θ", 2)
# Apply an instruction with a parameter expression involving two parameters.
qiskit_circuit.rx(3 * theta_param[0] + theta_param[1], 0)
op = SparsePauliOp.from_list([("Z", 1)])
est_grad = grad()
with pytest.raises(RuntimeError, match="Variable w.r.t should be given"):
est_grad.run([qiskit_circuit], [op], [[0.2, 0.3]]).result()
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
"""Tests for qulacs sampler."""
from unittest import TestCase
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, UnitaryGate
from qiskit.primitives import SamplerResult
from qiskit.providers import JobStatus
from qiskit_qulacs.qulacs_sampler import QulacsSampler
from tests.utils import dicts_almost_equal
class TestQulacsSampler(TestCase):
"""Test QulacsSampler"""
def setUp(self):
super().setUp()
hadamard = QuantumCircuit(1, 1, name="Hadamard")
hadamard.h(0)
hadamard.measure(0, 0)
bell = QuantumCircuit(2, name="Bell")
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
self._circuit = [hadamard, bell]
self._target = [
{0: 0.5, 1: 0.5},
{0: 0.5, 3: 0.5, 1: 0, 2: 0},
]
self._pqc = RealAmplitudes(num_qubits=2, reps=2).decompose()
self._pqc.measure_all()
self._pqc2 = RealAmplitudes(num_qubits=2, reps=3).decompose()
self._pqc2.measure_all()
self._pqc_params = [[0.0] * 6, [1.0] * 6]
self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}]
self._theta = [
[0, 1, 1, 2, 3, 5],
[1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 4, 5, 6, 7],
]
def _generate_circuits_target(self, indices):
if isinstance(indices, list):
circuits = [self._circuit[j] for j in indices]
target = [self._target[j] for j in indices]
else:
raise ValueError(f"invalid index {indices}")
return circuits, target
def _generate_params_target(self, indices):
if isinstance(indices, int):
params = self._pqc_params[indices]
target = self._pqc_target[indices]
elif isinstance(indices, list):
params = [self._pqc_params[j] for j in indices]
target = [self._pqc_target[j] for j in indices]
else:
raise ValueError(f"invalid index {indices}")
return params, target
def _compare_probs(self, prob, target):
if not isinstance(prob, list):
prob = [prob]
if not isinstance(target, list):
target = [target]
self.assertEqual(len(prob), len(target))
for p, targ in zip(prob, target):
for key, t_val in targ.items():
if key in p:
self.assertAlmostEqual(p[key], t_val, places=1)
else:
self.assertAlmostEqual(t_val, 0, places=1)
def test_sampler_run(self):
"""Test Sampler.run()."""
bell = self._circuit[1]
sampler = QulacsSampler()
job = sampler.run(circuits=[bell])
result = job.result()
self.assertIsInstance(result, SamplerResult)
self._compare_probs(result.quasi_dists, self._target[1])
def test_sample_run_multiple_circuits(self):
"""Test Sampler.run() with multiple circuits."""
# executes three Bell circuits
# Argument `parameters` is optional.
bell = self._circuit[1]
sampler = QulacsSampler()
result = sampler.run([bell, bell, bell]).result()
self._compare_probs(result.quasi_dists[0], self._target[1])
self._compare_probs(result.quasi_dists[1], self._target[1])
self._compare_probs(result.quasi_dists[2], self._target[1])
def test_sampler_run_with_parameterized_circuits(self):
"""Test Sampler.run() with parameterized circuits."""
# parameterized circuit
pqc = self._pqc
pqc2 = self._pqc2
theta1, theta2, theta3 = self._theta
sampler = QulacsSampler()
result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result()
# result of pqc(theta1)
prob1 = {
"00": 0.1309248462975777,
"01": 0.3608720796028448,
"10": 0.09324865232050054,
"11": 0.41495442177907715,
}
error_msg = dicts_almost_equal(
result.quasi_dists[0].binary_probabilities(), prob1
)
if error_msg:
msg = self._formatMessage(None, error_msg)
raise self.failureException(msg)
# result of pqc(theta2)
prob2 = {
"00": 0.06282290651933871,
"01": 0.02877144385576705,
"10": 0.606654494132085,
"11": 0.3017511554928094,
}
error_msg = dicts_almost_equal(
result.quasi_dists[1].binary_probabilities(), prob2
)
if error_msg:
msg = self._formatMessage(None, error_msg)
raise self.failureException(msg)
# result of pqc2(theta3)
prob3 = {
"00": 0.1880263994380416,
"01": 0.6881971261189544,
"10": 0.09326232720582443,
"11": 0.030514147237179892,
}
error_msg = dicts_almost_equal(
result.quasi_dists[2].binary_probabilities(), prob3
)
if error_msg:
msg = self._formatMessage(None, error_msg)
raise self.failureException(msg)
def test_run_1qubit(self):
"""test for 1-qubit cases"""
qc = QuantumCircuit(1)
qc.measure_all()
qc2 = QuantumCircuit(1)
qc2.x(0)
qc2.measure_all()
sampler = QulacsSampler()
result = sampler.run([qc, qc2]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 2)
for i in range(2):
keys, values = zip(*sorted(result.quasi_dists[i].items()))
self.assertTupleEqual(keys, (i,))
np.testing.assert_allclose(values, [1])
def test_run_2qubit(self):
"""test for 2-qubit cases"""
qc0 = QuantumCircuit(2)
qc0.measure_all()
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.measure_all()
qc2 = QuantumCircuit(2)
qc2.x(1)
qc2.measure_all()
qc3 = QuantumCircuit(2)
qc3.x([0, 1])
qc3.measure_all()
sampler = QulacsSampler()
result = sampler.run([qc0, qc1, qc2, qc3]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 4)
for i in range(4):
keys, values = zip(*sorted(result.quasi_dists[i].items()))
self.assertTupleEqual(keys, (i,))
np.testing.assert_allclose(values, [1])
def test_run_single_circuit(self):
"""Test for single circuit case."""
sampler = QulacsSampler()
with self.subTest("No parameter"):
circuit = self._circuit[1]
target = self._target[1]
param_vals = [None, [], [[]], np.array([]), np.array([[]])]
for val in param_vals:
with self.subTest(f"{circuit.name} w/ {val}"):
result = sampler.run(circuit, val).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(len(result.metadata), 1)
with self.subTest("One parameter"):
circuit = QuantumCircuit(1, 1, name="X gate")
param = Parameter("x")
circuit.ry(param, 0)
circuit.measure(0, 0)
target = [{1: 1}]
param_vals = [
[np.pi],
[[np.pi]],
np.array([np.pi]),
np.array([[np.pi]]),
[np.array([np.pi])],
]
for val in param_vals:
with self.subTest(f"{circuit.name} w/ {val}"):
result = sampler.run(circuit, val).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(len(result.metadata), 1)
with self.subTest("More than one parameter"):
circuit = self._pqc
target = [self._pqc_target[0]]
param_vals = [
self._pqc_params[0],
[self._pqc_params[0]],
np.array(self._pqc_params[0]),
np.array([self._pqc_params[0]]),
[np.array(self._pqc_params[0])],
]
for val in param_vals:
with self.subTest(f"{circuit.name} w/ {val}"):
result = sampler.run(circuit, val).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(len(result.metadata), 1)
def test_run_reverse_meas_order(self):
"""test for sampler with reverse measurement order"""
x = Parameter("x")
y = Parameter("y")
qc = QuantumCircuit(3, 3)
qc.rx(x, 0)
qc.rx(y, 1)
qc.x(2)
qc.measure(0, 2)
qc.measure(1, 1)
qc.measure(2, 0)
sampler = QulacsSampler()
result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 2)
# qc({x: 0, y: 0})
keys, values = zip(*sorted(result.quasi_dists[0].items()))
self.assertTupleEqual(keys, (1,))
np.testing.assert_allclose(values, [1])
# qc({x: pi/2, y: 0})
keys, values = zip(*sorted(result.quasi_dists[1].items()))
self.assertTupleEqual(keys, (1, 5))
np.testing.assert_allclose(values, [0.5, 0.5])
def test_run_errors(self):
"""Test for errors with run method"""
qc1 = QuantumCircuit(1)
qc1.measure_all()
qc2 = RealAmplitudes(num_qubits=1, reps=1).decompose()
qc2.measure_all()
qc3 = QuantumCircuit(1)
qc4 = QuantumCircuit(1, 1)
qc5 = QuantumCircuit(1, 1)
with qc5.for_loop(range(5)):
qc5.h(0)
sampler = QulacsSampler()
with self.subTest("set parameter values to a non-parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc1], [[1e2]])
with self.subTest("missing all parameter values for a parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc2], [[]])
with self.subTest("missing some parameter values for a parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc2], [[1e2]])
with self.subTest("too many parameter values for a parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc2], [[1e2]] * 100)
with self.subTest("no classical bits"):
with self.assertRaises(ValueError):
_ = sampler.run([qc3], [[]])
with self.subTest("no measurement"):
with self.assertRaises(ValueError):
_ = sampler.run([qc4], [[]])
with self.subTest("no measurement in control flow"):
with self.assertRaises(ValueError):
_ = sampler.run([qc5], [[]])
def test_run_empty_parameter(self):
"""Test for empty parameter"""
n = 5
qc = QuantumCircuit(n, n - 1)
qc.measure(range(n - 1), range(n - 1))
sampler = QulacsSampler()
with self.subTest("one circuit"):
result = sampler.run([qc], shots=1000).result()
self.assertEqual(len(result.quasi_dists), 1)
for q_d in result.quasi_dists:
quasi_dist = {k: v for k, v in q_d.items() if v != 0.0}
self.assertDictEqual(quasi_dist, {0: 1.0})
self.assertEqual(len(result.metadata), 1)
with self.subTest("two circuits"):
result = sampler.run([qc, qc], shots=1000).result()
self.assertEqual(len(result.quasi_dists), 2)
for q_d in result.quasi_dists:
quasi_dist = {k: v for k, v in q_d.items() if v != 0.0}
self.assertDictEqual(quasi_dist, {0: 1.0})
self.assertEqual(len(result.metadata), 2)
def test_run_numpy_params(self):
"""Test for numpy array as parameter values"""
qc = RealAmplitudes(num_qubits=2, reps=2).decompose()
qc.measure_all()
k = 5
rng = np.random.default_rng(12)
params_array = rng.random((k, qc.num_parameters))
params_list = params_array.tolist()
params_list_array = list(params_array)
sampler = QulacsSampler()
target = sampler.run([qc] * k, params_list).result()
with self.subTest("ndarrary"):
result = sampler.run([qc] * k, params_array).result()
self.assertEqual(len(result.metadata), k)
for i in range(k):
self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i])
with self.subTest("list of ndarray"):
result = sampler.run([qc] * k, params_list_array).result()
self.assertEqual(len(result.metadata), k)
for i in range(k):
self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i])
def test_run_with_shots_option(self):
"""test with shots option."""
params, target = self._generate_params_target([1])
sampler = QulacsSampler()
result = sampler.run(
circuits=[self._pqc], parameter_values=params, shots=1024, seed=15
).result()
self._compare_probs(result.quasi_dists, target)
def test_run_with_shots_option_none(self):
"""test with shots=None option. Seed is ignored then."""
sampler = QulacsSampler()
result_42 = sampler.run(
[self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=42
).result()
result_15 = sampler.run(
[self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=15
).result()
error_msg = dicts_almost_equal(result_42.quasi_dists, result_15.quasi_dists)
if error_msg:
msg = self._formatMessage(None, error_msg)
raise self.failureException(msg)
def test_run_shots_result_size(self):
"""test with shots option to validate the result size"""
n = 10
shots = 100
qc = QuantumCircuit(n)
qc.h(range(n))
qc.measure_all()
sampler = QulacsSampler()
result = sampler.run(qc, [], shots=shots, seed=42).result()
self.assertEqual(len(result.quasi_dists), 1)
self.assertLessEqual(len(result.quasi_dists[0]), shots)
self.assertAlmostEqual(sum(result.quasi_dists[0].values()), 1.0)
def test_primitive_job_status_done(self):
"""test primitive job's status"""
bell = self._circuit[1]
sampler = QulacsSampler()
job = sampler.run(circuits=[bell])
_ = job.result()
self.assertEqual(job.status(), JobStatus.DONE)
def test_options(self):
"""Test for options"""
with self.subTest("init"):
sampler = QulacsSampler(options={"shots": 3000})
self.assertEqual(sampler.options.get("shots"), 3000)
with self.subTest("set_options"):
sampler.set_options(shots=1024, seed=15)
self.assertEqual(sampler.options.get("shots"), 1024)
self.assertEqual(sampler.options.get("seed"), 15)
with self.subTest("run"):
params, target = self._generate_params_target([1])
result = sampler.run([self._pqc], parameter_values=params).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(result.quasi_dists[0].shots, 1024)
def test_circuit_with_unitary(self):
"""Test for circuit with unitary gate."""
gate = UnitaryGate(np.eye(2))
circuit = QuantumCircuit(1)
circuit.append(gate, [0])
circuit.measure_all()
sampler = QulacsSampler()
sampler_result = sampler.run([circuit]).result()
error_msg = dicts_almost_equal(sampler_result.quasi_dists[0], {0: 1, 1: 0})
if error_msg:
msg = self._formatMessage(None, error_msg)
raise self.failureException(msg)
|
https://github.com/LSEG-API-Samples/Article.EikonAPI.Python.OptionPricingUsingQiskitAndEikonDataAPI
|
LSEG-API-Samples
|
import warnings
warnings.filterwarnings("ignore")
import qiskit.tools.jupyter
%qiskit_version_table
import eikon as ek
print("Eikon version: ", ek.__version__)
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import seaborn as sns
import qiskit
from qiskit import Aer, QuantumCircuit
from qiskit_finance.data_providers._base_data_provider import BaseDataProvider
from qiskit.finance.applications.ising import portfolio
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN', overwrite=True)
eikon_key = open("eikon.txt","r")
ek.set_app_key(str(eikon_key.read()))
eikon_key.close()
class EikonDataProvider(BaseDataProvider):
"""
The abstract base class for Eikon data_provider.
"""
def __init__(self, stocks_list, start_date, end_date):
'''
stocks -> List of interested assets
start -> start date to fetch historical data
end ->
'''
super().__init__()
self._stocks = stocks_list
self._start = start_date
self._end = end_date
self._data = []
self.stock_data = pd.DataFrame()
def run(self):
self._data = []
stocks_notfound = []
stock_data = ek.get_timeseries(self._stocks,
start_date=self._start,
end_date=self._end,
interval='daily',
corax='adjusted')
for ticker in self._stocks:
stock_value = stock_data['CLOSE']
self.stock_data[ticker] = stock_data['CLOSE']
if stock_value.dropna().empty:
stocks_notfound.append(ticker)
self._data.append(stock_value)
# List of stocks
stock_list = ['FB.O']
# Start Date
start_date = datetime.datetime(2020,12,1)
# End Date
end_date = datetime.datetime(2021,12,1)
# Set number of equities to the number of stocks
num_assets = len(stock_list)
# Set the risk factor
risk_factor = 0.7
# Set budget
budget = 2
# Scaling of budget penalty term will be dependant on the number of assets
penalty = num_assets
data = EikonDataProvider(stocks_list = stock_list, start_date=start_date, end_date=end_date)
data.run()
# Top 5 rows of data
df = data.stock_data
df.head()
df.describe()
# Closing Price History
fig, ax = plt.subplots(figsize=(15, 8))
ax.plot(df)
plt.title('Close Price History')
plt.xlabel('Date',fontsize =20)
plt.ylabel('Price in USD',fontsize = 20)
ax.legend(df.columns.values)
plt.show()
df.tail()
strike_price = 315 # agreed upon strike price
T = 40 / 253 # 40 days to maturity
S = 310.6 # initial spot price
# vol = 0.4 # volatility of 40%
vol = df['FB.O'].pct_change().std()
r = 0.05 # annual interest rate of 4%
# resulting parameters for log-normal distribution
mu = ((r - 0.5 * vol**2) * T + np.log(S))
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2/2)
variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3*stddev)
high = mean + 3*stddev
low
high
import numpy as np
from qiskit.algorithms import AmplitudeEstimation
from qiskit_finance.circuit.library import EuropeanCallPricingObjective # F
from qiskit.circuit.library import LogNormalDistribution, NormalDistribution
from qiskit_finance.applications import EuropeanCallPricing
from qiskit_finance.applications.estimation import EuropeanCallDelta
from qiskit import Aer
from qiskit.algorithms import IterativeAmplitudeEstimation
provider = IBMQ.load_account()
provider.backends()
backend = provider.get_backend("ibmq_lima")
sim = QuantumInstance(backend=backend, shots=1000)
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 2
distribution = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high))
european_call_pricing = EuropeanCallPricing(num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=0.25, # approximation constant for payoff function
bounds=(low, high),
uncertainty_model=distribution)
problem = european_call_pricing.to_estimation_problem()
problem.state_preparation.draw('mpl', style='iqx')
plt.show()
epsilon = 0.01 # determines final accuracy
alpha = 0.05 # determines how certain we are of the result
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
result = ae.estimate(problem)
conf_int_result = np.array(result.confidence_interval_processed)
print("Esimated value: \t%.4f" % european_call_pricing.interpret(result))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int_result))
x = distribution.values
y = distribution.probabilities
plt.figure(figsize=(6,4))
plt.bar(x, y, width=2)
plt.xticks(x, size=12, rotation=45)
plt.yticks(size=12)
plt.xlabel('Spot Price at Maturity $S_T$ (\$)', size=15)
plt.ylabel('Probability ($\%$)', size=15)
plt.show()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = distribution.values
y = np.maximum(0, x - strike_price)
plt.figure(figsize=(6,4))
plt.plot(x, y, "ro-")
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=12, rotation=45)
plt.yticks(size=12)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(distribution.probabilities, y)
exact_delta = sum(distribution.probabilities[x >= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
european_call_delta = EuropeanCallDelta(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
bounds=(low, high),
uncertainty_model=distribution,
)
european_call_delta._objective.decompose().draw('mpl', style='iqx')
plt.show()
european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits)
european_call_delta_circ.append(distribution, range(num_uncertainty_qubits))
european_call_delta_circ.append(
european_call_delta._objective, range(european_call_delta._objective.num_qubits)
)
european_call_delta_circ.draw('mpl', style='iqx')
plt.show()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_delta.to_estimation_problem()
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval_processed)
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
|
https://github.com/LSEG-API-Samples/Article.EikonAPI.Python.OptionPricingUsingQiskitAndEikonDataAPI
|
LSEG-API-Samples
|
# ! pip install qiskit qiskit-finance==0.2.1
import warnings
warnings.filterwarnings("ignore")
import qiskit.tools.jupyter
%qiskit_version_table
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN', overwrite=True)
# ! pip install eikon
import eikon as ek
print("Eikon version: ", ek.__version__)
eikon_key = open("eikon.txt","r")
ek.set_app_key(str(eikon_key.read()))
eikon_key.close()
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import seaborn as sns
import qiskit
from qiskit import Aer, QuantumCircuit
from qiskit_finance.data_providers._base_data_provider import BaseDataProvider
from qiskit.finance.applications.ising import portfolio
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
class EikonDataProvider(BaseDataProvider):
"""
The abstract base class for Eikon data_provider.
"""
def __init__(self, stocks_list, start_date, end_date):
'''
stocks -> List of interested assets
start -> start date to fetch historical data
end ->
'''
super().__init__()
self._stocks = stocks_list
self._start = start_date
self._end = end_date
self._data = []
self.stock_data = pd.DataFrame()
def run(self):
self._data = []
stocks_notfound = []
stock_data = ek.get_timeseries(self._stocks,
start_date=self._start,
end_date=self._end,
interval='daily',
corax='adjusted')
for ticker in self._stocks:
stock_value = stock_data['CLOSE']
self.stock_data[ticker] = stock_data['CLOSE']
if stock_value.dropna().empty:
stocks_notfound.append(ticker)
self._data.append(stock_value)
# List of stocks
stock_list = ['FB.O']
# Start Date
start_date = datetime.datetime(2020,12,1)
# End Date
end_date = datetime.datetime(2021,12,1)
# Set number of equities to the number of stocks
num_assets = len(stock_list)
# Set the risk factor
risk_factor = 0.7
# Set budget
budget = 2
# Scaling of budget penalty term will be dependant on the number of assets
penalty = num_assets
data = EikonDataProvider(stocks_list = stock_list, start_date=start_date, end_date=end_date)
data.run()
# Top 5 rows of data
df = data.stock_data
df.head()
df.describe()
# Closing Price History
fig, ax = plt.subplots(figsize=(15, 8))
ax.plot(df)
plt.title('Close Price History')
plt.xlabel('Date',fontsize =20)
plt.ylabel('Price in USD',fontsize = 20)
ax.legend(df.columns.values)
plt.show()
df.tail()
strike_price = 315 # agreed upon strike price
T = 40 / 253 # 40 days to maturity
S = 310.6 # initial spot price
# vol = 0.4 # volatility of 40%
vol = df['FB.O'].pct_change().std()
r = 0.05 # annual interest rate of 4%
# resulting parameters for log-normal distribution
mu = ((r - 0.5 * vol**2) * T + np.log(S))
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2/2)
variance = (np.exp(sigma**2) - 1) * np.exp(2*mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3*stddev)
high = mean + 3*stddev
low
high
import numpy as np
from qiskit.algorithms import AmplitudeEstimation
from qiskit_finance.circuit.library import EuropeanCallPricingObjective # F
from qiskit.circuit.library import LogNormalDistribution, NormalDistribution
from qiskit_finance.applications import EuropeanCallPricing
from qiskit_finance.applications.estimation import EuropeanCallDelta
from qiskit import Aer
from qiskit.algorithms import IterativeAmplitudeEstimation
sim = QuantumInstance(Aer.get_backend("aer_simulator"), shots=1000)
# number of qubits to represent the uncertainty
num_uncertainty_qubits = 5
distribution = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high))
european_call_pricing = EuropeanCallPricing(num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=0.25, # approximation constant for payoff function
bounds=(low, high),
uncertainty_model=distribution)
problem = european_call_pricing.to_estimation_problem()
problem.state_preparation.draw('mpl', style='iqx')
plt.show()
epsilon = 0.01 # determines final accuracy
alpha = 0.05 # determines how certain we are of the result
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
result = ae.estimate(problem)
conf_int_result = np.array(result.confidence_interval_processed)
print("Esimated value: \t%.4f" % european_call_pricing.interpret(result))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int_result))
x = distribution.values
y = distribution.probabilities
plt.figure(figsize=(15,6))
plt.bar(x, y, width=0.3)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=10)
plt.grid()
plt.xlabel('Spot Price at Maturity $S_T$ (\$)', size=15)
plt.ylabel('Probability ($\%$)', size=15)
plt.show()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = distribution.values
y = np.maximum(0, x - strike_price)
plt.figure(figsize=(15,6))
plt.plot(x, y, "ro-")
plt.grid()
plt.title("Payoff Function for Call Option", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
exact_value = np.dot(distribution.probabilities, y)
exact_delta = sum(distribution.probabilities[x >= strike_price])
print("exact expected value:\t%.4f" % exact_value)
print("exact delta value: \t%.4f" % exact_delta)
european_call_delta = EuropeanCallDelta(
num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
bounds=(low, high),
uncertainty_model=distribution,
)
european_call_delta._objective.decompose().draw('mpl', style='iqx')
plt.show()
european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits)
european_call_delta_circ.append(distribution, range(num_uncertainty_qubits))
european_call_delta_circ.append(
european_call_delta._objective, range(european_call_delta._objective.num_qubits)
)
european_call_delta_circ.draw('mpl', style='iqx')
plt.show()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_delta.to_estimation_problem()
# construct amplitude estimation
ae_delta = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
result_delta = ae_delta.estimate(problem)
conf_int = np.array(result_delta.confidence_interval_processed)
print("Exact delta: \t%.4f" % exact_delta)
print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
put_distribution = LogNormalDistribution(num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, high))
put_european_call_pricing = EuropeanCallPricing(num_state_qubits=num_uncertainty_qubits,
strike_price=strike_price,
rescaling_factor=0.25, # approximation constant for payoff function
bounds=(low, high),
uncertainty_model=put_distribution)
put_problem = put_european_call_pricing.to_estimation_problem()
epsilon = 0.01 # determines final accuracy
alpha = 0.05 # determines how certain we are of the result
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=sim)
put_result = ae.estimate(put_problem)
put_conf_int_result = np.array(put_result.confidence_interval_processed)
print("Esimated value: \t%.4f" % european_call_pricing.interpret(put_result))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(put_conf_int_result))
x = put_distribution.values
y = put_distribution.probabilities
plt.figure(figsize=(15,6))
plt.bar(x, y, width=0.3)
plt.xticks(x, size=12, rotation=90)
plt.yticks(size=12)
plt.xlabel('Spot Price at Maturity $S_T$ (\$)', size=15)
plt.ylabel('Probability ($\%$)', size=15)
plt.show()
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = distribution.values
y = np.maximum(0, strike_price-x)
plt.figure(figsize=(15,6))
plt.plot(x, y, "ro-")
plt.title("Payoff Function for Put Option", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=12, rotation=90)
plt.yticks(size=12)
plt.show()
# evaluate exact expected value (normalized to the [0, 1] interval)
put_exact_value = np.dot(put_distribution.probabilities, y)
conf_int = np.array(put_result.confidence_interval_processed)
print("Exact Expected Value:\t%.4f" % exact_value)
print("Esimated value: \t%.4f" % european_call_delta.interpret(put_result))
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 5 16:33:48 2022
@author: pejmanjouzdani
"""
# from SimulateMQITE.log_config import logger
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit, transpile
from qiskit import Aer
class AmplitudeClass:
def __init__(self, circ_U, circ_UQU, Q, shots_amplitude, eta, significant_figures, machine_precision=10):
self.Q = Q
self.circ_U = circ_U
self.circ_UQU = circ_UQU
self.shots_amplitude = shots_amplitude
self.eta = eta
self.significant_figures = significant_figures
self.machine_precision = machine_precision
############################ OUTPUTS
#################### |cj|^2 and js upto significant digits
self.df_count = self.getIndexsFromExecute(self.circ_UQU, self.shots_amplitude)
### keep eta of them -> {|c_j|} = df_ampl
### the j's and c_j's from shots and observed bit string --> NO state vector
self.df_ampl = self.getAmplitudes(
pd.DataFrame.copy(self.df_count),
self.eta
)
@staticmethod
def getIndexsFromExecute(circ_UQU, shots, backend = 'qasm_simulator'):
pass
'''
appends classical wires to record measurements
execute the circuit 'shots' time
returns the observed bit-strings and distributions (counts)
[AerSimulator('aer_simulator'),
AerSimulator('aer_simulator_statevector'),
AerSimulator('aer_simulator_density_matrix'),
AerSimulator('aer_simulator_stabilizer'),
AerSimulator('aer_simulator_matrix_product_state'),
AerSimulator('aer_simulator_extended_stabilizer'),
AerSimulator('aer_simulator_unitary'),
AerSimulator('aer_simulator_superop'),
QasmSimulator('qasm_simulator'),
StatevectorSimulator('statevector_simulator'),
UnitarySimulator('unitary_simulator'),
PulseSimulator('pulse_simulator')]
'''
### check if shots are type and value correct
if not isinstance(shots, int):
raise TypeError('shots must be an integer')
if shots<1 or shots>10**8:
raise ValueError('Number of shots is either less than 1 or larger than 10^8')
### check if backend is correct
simulator = Aer.get_backend(backend)
### check the circ Value and Type
### Building measurment circuit
num_qubits = circ_UQU.num_qubits
circ_meas = QuantumCircuit(num_qubits, num_qubits)
circ_meas = circ_meas.compose(circ_UQU)
circ_meas.measure(
[q for q in range(num_qubits)],
[q for q in range(num_qubits)]
)
compiled_circuit = transpile(circ_meas, simulator)
job = simulator.run(compiled_circuit, shots=shots)
result = job.result()
counts = result.get_counts(compiled_circuit)
### Using Pandas dataframe to organize
df_count = pd.DataFrame([counts.int_outcomes()]).T
df_count.columns=['n_j']
return df_count
@staticmethod
def getAmplitudes(df_count,eta ):
'''
return the |c_j| of the most largest amplitudes
'''
chi = df_count.sum()['n_j']
df_count = df_count/chi
df_ampl = df_count.apply(lambda x: np.sqrt(x))
df_ampl.columns=['|c_j|']
return df_ampl
if __name__=='__main__':
pass
from qiskit import QuantumCircuit
################################################################
################################################################
##################### FOR TEST #######################
################################################################
################################################################
################################################################
from BasicFunctions.getRandomQ import getRandomQ
from BasicFunctions.getRandomU import getRandomU
from BasicFunctions.getQCirc import getQCirc
from BasicFunctions.getUQUCirc import getUQUCirc
################################################################
################################################################
seed = 1253
np.random.seed(seed)
################################################################
################################################################
nspins = 12
num_layers =2
num_itr =1
machine_precision = 10
shots_amplitude = 100
eta = 100
significant_figures = 2#np.log10(np.sqrt(shots_amplitude)).astype(int)
TestLevel = 0
circ_U = getRandomU(nspins, num_layers)
Q = getRandomQ(nspins)
circ_UQ = getQCirc(circ_U, Q)
circ_UQU = getUQUCirc(circ_U, circ_UQ)
################################# TEST
###### Constructor
myAmplObj = AmplitudeClass( circ_U, circ_UQU, Q, shots_amplitude, eta, significant_figures, machine_precision=10)
print(myAmplObj.df_count)
print(myAmplObj.df_ampl)
|
https://github.com/JouziP/MQITE
|
JouziP
|
# -*- coding: utf-8 -*-
# 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.
"""
Created on Wed Mar 11 18:03:12 2020
Functional interface to Qasm2 source loading and exporting
Supersede QuantumCircuit member functions
Provide for pluggable qasm translator
Based on conversation with Dr. Luciano Bello
@author: jax
"""
from importlib import import_module
from os import linesep
from typing import List, BinaryIO, TextIO
from qiskit import QuantumCircuit, QiskitError
from qiskit_openqasm2 import Qasm
from .funhelp import qasm_load, qasm_export
def _load_from_string(qasm_src: str or List[str],
loader: str = None,
include_path: str = '') -> QuantumCircuit:
"""
Parameters
----------
qasm_src : str or List[str]
Qasm program source as string or list of string.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is ''.
Raises
------
QiskitError
If unknown loader.
Returns
-------
QuantumCircuit
Circuit factoried from Qasm src.
"""
circ = None
if not loader:
if isinstance(qasm_src, list):
qasm_src = ''.join(s + linesep for s in qasm_src)
qasm = Qasm(data=qasm_src)
circ = qasm_load(qasm)
else:
m_m = import_module(loader)
circ = getattr(m_m, 'load')(data=qasm_src,
include_path=include_path)
return circ
def _load_from_file(filename: str,
loader: str = None,
include_path: str = '') -> QuantumCircuit:
"""
Parameters
----------
filename : str
Filepath to qasm program source.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is ''.
Returns
-------
QuantumCircuit
Circuit factoried from Qasm src.
"""
circ = None
if not loader:
qasm = Qasm(filename=filename)
circ = qasm_load(qasm)
else:
m_m = import_module(loader)
circ = getattr(m_m, 'load')(filename=filename,
include_path=include_path)
return circ
def load(data: str or List[str] = None,
filename: str = None,
loader: str = None,
include_path: str = None) -> QuantumCircuit:
"""
Parameters
----------
data : str or List[str], optional
Qasm program source as string or list of string. The default is None.
filename : str, optional
Filepath to qasm program source. The default is None.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is None.
Raises
------
QiskitError
If both filename and data or neither filename nor data.
Returns
-------
QuantumCircuit
The factoried circuit.
"""
if (not data and not filename) or (data and filename):
raise QiskitError("To load, either filename or data (and not both) must be provided.")
circ = None
if data:
circ = _load_from_string(data, loader=loader, include_path=include_path)
elif filename:
circ = _load_from_file(filename, loader=loader, include_path=include_path)
return circ
def export(qc: QuantumCircuit,
exporter: str = None,
file: BinaryIO or TextIO = None,
filename: str = None,
include_path: str = None,) -> str:
"""
Decompile a QuantumCircuit into Return OpenQASM string
Parameters
----------
qc : QuantumCircuit
Circuit to decompile ("export")
exporter : str, optional
Name of module with functional attribute
export(qc: QuantumCircuit,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
file : BinaryIO or TextIO, optional
File object to write to as well as return str
Written in UTF-8
Caller must close file.
Mutually exclusive with filename=
The default is None.
filename : str, optional
Name of file to write export to as well as return str
Mutually exclusive with file=
The default is None.
include_path: str, optional
Unloader-specific include path for qasm include directives
Raises
------
QiskitError
If both filename and file
Returns
-------
str
OpenQASM source for circuit.
"""
if filename and file:
raise QiskitError("export: file= and filename= are mutually exclusive")
qasm_src = None
if not exporter:
qasm_src = qasm_export(qc)
else:
m_m = import_module(exporter)
qasm_src = getattr(m_m, 'export')(qc, include_path=include_path)
if filename:
f_f = open(filename, 'w')
f_f.write(qasm_src)
f_f.close()
elif file:
if 'b' in file.mode:
file.write(bytes(qasm_src, 'utf-8'))
else:
file.write(qasm_src)
return qasm_src
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 6 12:18:27 2022
@author: pejmanjouzdani
"""
import numpy as np
from qiskit.circuit.exceptions import CircuitError
from qiskit import QuantumCircuit
def getQCirc(circ_U, Q):
#############
# Qiskit error
if not isinstance(circ_U, QuantumCircuit):
raise CircuitError('The circuit is not an instance of the QuantumCircuit')
# TypeError
if not isinstance(Q, np.ndarray):
if not isinstance(Q, list):
raise TypeError(' the provided Pauli string operator is not am instance of list or numpy array ')
#############
circ_Q = QuantumCircuit.copy(circ_U)
#############
# ValueError
### the number of qubits must be the same as number of operators in Q
if not circ_Q.num_qubits == len(Q):
raise ValueError('the number of qubits in the circuit is not the same as the number of Pauli operators in Q')
#############
for (q, o) in enumerate(Q):
if o==0:
pass
if o==1:
circ_Q.x(q)
if o==2:
circ_Q.y(q)
if o==3:
circ_Q.z(q)
return circ_Q
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 6 12:15:52 2022
@author: pejmanjouzdani
"""
import numpy as np
from qiskit import QuantumCircuit
################################################################
################################################################
def getRandomU(nspins, num_layers=10):
circ_U = QuantumCircuit(nspins)
for l in range(num_layers):
for i in range(nspins):
##############
q=np.random.randint(nspins)
g=np.random.randint(1, 4)
p=np.random.uniform(-1,1)
if g==1:
circ_U.rx(p,q)
if g==2:
circ_U.ry(p,q)
if g==2:
circ_U.rz(p,q)
##############
q=np.random.randint(nspins-1)
circ_U.cnot(q, q+1)
return circ_U
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 5 17:10:42 2022
@author: pejmanjouzdani
"""
import numpy as np
import pandas as pd
from BasicFunctions.functions import getState
def getStateVectorValuesOfAmpl( j_list, circ_uhu, significant_figures, machine_precision):
#################### Benchmark
circ_state = getState(circ_uhu, machine_precision)
###
df_ampl_bm = pd.DataFrame(circ_state[j_list, :].round(significant_figures).T.tolist()[0])
df_ampl_bm.columns=['|c_j|']
df_ampl_bm.index = j_list
#### not normalizing !
df_ampl_bm['|c_j|'] = df_ampl_bm['|c_j|'].apply(lambda x: np.sqrt(x*x.conjugate()).real)
return df_ampl_bm
if __name__=='__main__':
from qiskit import QuantumCircuit
from BasicFunctions.getQCirc import getQCirc
from BasicFunctions.getRandomQ import getRandomQ
from BasicFunctions.getRandomU import getRandomU
from BasicFunctions.getUQUCirc import getUQUCirc
seed = 1211
np.random.seed(seed)
################################################################
################################################################
nspins = 10
num_layers =4
num_itr =1
machine_precision = 10
significant_figures = 3
eta = 100
shots = 10**(2*significant_figures)
Q = getRandomQ(nspins)
inputs={}
inputs['nspins']=nspins
inputs['num_layers']=num_layers
inputs['num_itr']=num_itr
inputs['machine_precision']=machine_precision
inputs['significant_figures']=significant_figures
inputs['eta']=eta
inputs['shots']=shots
inputs['Q-list']=Q
circ_U = getRandomU(nspins, num_layers)
circ_Q = getQCirc(circ_U, Q)
circ_UQU = getUQUCirc(circ_U, circ_Q)
print(pd.DataFrame([inputs]).T )
from Amplitude.Amplitude import Amplitude
df_count = Amplitude.getIndexsFromExecute(circ_UQU, shots)
df_ampl = Amplitude.getAmplitudes(df_count, eta)
j_list = df_ampl.index.tolist()
state_vec = getStateVectorValuesOfAmpl( j_list, circ_UQU, significant_figures, machine_precision)
df_qc_vs_bm = pd.concat((df_ampl, state_vec), axis=1)
df_qc_vs_bm.columns = ['QC', 'StVec']
df_qc_vs_bm['diff'] = df_qc_vs_bm['QC'] - df_qc_vs_bm['StVec']
print(df_qc_vs_bm.round(significant_figures))
print('sum diff^2 rounded to significant figures: ' ,
np.round( np.sqrt(sum(df_qc_vs_bm.round(significant_figures)['diff'].apply(lambda x: x**2))), significant_figures))
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 6 12:26:49 2022
@author: pejmanjouzdani
"""
from qiskit import QuantumCircuit
def getUQUCirc(circ_U, circ_Q):
circ_UQU = QuantumCircuit.copy(circ_Q) ## QU|0>
circ_UQU = circ_UQU.compose(QuantumCircuit.copy(circ_U.inverse()) )## U^QU|0>
return circ_UQU ## U^QU|0>
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 4 17:53:16 2022
@author: pejmanjouzdani
"""
import logging
from time import time
class TestCirc:
def __init__(self, func, FLAG=False):
self.func = func
self.func.name = func.__name__
self.FLAG=FLAG
def __call__(self, *args, **kwargs):
#### If the flag is ON
if self.FLAG==True:
try:
results = self.test1(self.func , *args, **kwargs)
except:
raise
# if successful do other tests...
print(results)
return results
#### If the flag is OFF: just run the function
else:
return self.func(*args, **kwargs)
@staticmethod
def test1( func, *args, **kwargs):
pass
# time
start = time()
results = func(*args, **kwargs)
### cmpare with hat is expected using *args etc.
end_time = time()
logging.info('\n %s function takes %s second to run'%(func.name, end_time - start) )
print('\n %s function takes %s second to run'%(func.name, end_time - start))
return results
def test2(self, *args, **kwargs):
NotImplemented
if __name__=='__main__':
from qiskit import QuantumCircuit
from BasicFunctions.functions import getQCirc, getUQUCirc
tested_func= TestCirc(getQCirc, FLAG=True)
number_qubits= 3
Q = [1,2,3]
circ = QuantumCircuit(number_qubits)
circ_Q = tested_func(circ, Q)
|
https://github.com/JouziP/MQITE
|
JouziP
|
# -*- coding: utf-8 -*-
# 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.
"""
Created on Wed Mar 11 18:03:12 2020
Functional interface to Qasm2 source loading and exporting
Supersede QuantumCircuit member functions
Provide for pluggable qasm translator
Based on conversation with Dr. Luciano Bello
@author: jax
"""
from importlib import import_module
from os import linesep
from typing import List, BinaryIO, TextIO
from qiskit import QuantumCircuit, QiskitError
from qiskit_openqasm2 import Qasm
from .funhelp import qasm_load, qasm_export
def _load_from_string(qasm_src: str or List[str],
loader: str = None,
include_path: str = '') -> QuantumCircuit:
"""
Parameters
----------
qasm_src : str or List[str]
Qasm program source as string or list of string.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is ''.
Raises
------
QiskitError
If unknown loader.
Returns
-------
QuantumCircuit
Circuit factoried from Qasm src.
"""
circ = None
if not loader:
if isinstance(qasm_src, list):
qasm_src = ''.join(s + linesep for s in qasm_src)
qasm = Qasm(data=qasm_src)
circ = qasm_load(qasm)
else:
m_m = import_module(loader)
circ = getattr(m_m, 'load')(data=qasm_src,
include_path=include_path)
return circ
def _load_from_file(filename: str,
loader: str = None,
include_path: str = '') -> QuantumCircuit:
"""
Parameters
----------
filename : str
Filepath to qasm program source.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is ''.
Returns
-------
QuantumCircuit
Circuit factoried from Qasm src.
"""
circ = None
if not loader:
qasm = Qasm(filename=filename)
circ = qasm_load(qasm)
else:
m_m = import_module(loader)
circ = getattr(m_m, 'load')(filename=filename,
include_path=include_path)
return circ
def load(data: str or List[str] = None,
filename: str = None,
loader: str = None,
include_path: str = None) -> QuantumCircuit:
"""
Parameters
----------
data : str or List[str], optional
Qasm program source as string or list of string. The default is None.
filename : str, optional
Filepath to qasm program source. The default is None.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is None.
Raises
------
QiskitError
If both filename and data or neither filename nor data.
Returns
-------
QuantumCircuit
The factoried circuit.
"""
if (not data and not filename) or (data and filename):
raise QiskitError("To load, either filename or data (and not both) must be provided.")
circ = None
if data:
circ = _load_from_string(data, loader=loader, include_path=include_path)
elif filename:
circ = _load_from_file(filename, loader=loader, include_path=include_path)
return circ
def export(qc: QuantumCircuit,
exporter: str = None,
file: BinaryIO or TextIO = None,
filename: str = None,
include_path: str = None,) -> str:
"""
Decompile a QuantumCircuit into Return OpenQASM string
Parameters
----------
qc : QuantumCircuit
Circuit to decompile ("export")
exporter : str, optional
Name of module with functional attribute
export(qc: QuantumCircuit,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
file : BinaryIO or TextIO, optional
File object to write to as well as return str
Written in UTF-8
Caller must close file.
Mutually exclusive with filename=
The default is None.
filename : str, optional
Name of file to write export to as well as return str
Mutually exclusive with file=
The default is None.
include_path: str, optional
Unloader-specific include path for qasm include directives
Raises
------
QiskitError
If both filename and file
Returns
-------
str
OpenQASM source for circuit.
"""
if filename and file:
raise QiskitError("export: file= and filename= are mutually exclusive")
qasm_src = None
if not exporter:
qasm_src = qasm_export(qc)
else:
m_m = import_module(exporter)
qasm_src = getattr(m_m, 'export')(qc, include_path=include_path)
if filename:
f_f = open(filename, 'w')
f_f.write(qasm_src)
f_f.close()
elif file:
if 'b' in file.mode:
file.write(bytes(qasm_src, 'utf-8'))
else:
file.write(qasm_src)
return qasm_src
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 13 12:40:38 2022
@author: pejmanjouzdani
"""
# # from SimulateMQITE.log_config import logger
import pandas as pd
import numpy as np
from qiskit import QuantumCircuit
from MultiQubitGate.functions import multiqubit
from BasicFunctions.functions import getBinary
from Phase.PhaseFunctions.computeAmplFromShots import computeAmplFromShots
class Phase:
##### CONSTRUCTOR
def __init__(self,
df_ampl,
nspins,
circ_U,
Q,
significant_figures,
shots,
machine_precision=10,
j_ref=None,
gamma= np.pi/10):
#### static
# self.amplObj = amplObj
self.nspins = nspins
self.circ_U = circ_U ## the U_t circuit
self.Q = Q # the Q Pauli string given in form of an array of 0,...,3
self.significant_figures = significant_figures # significant_figures
self.shots = shots #
self.machine_precision = machine_precision
self.df_ampl = df_ampl# |c_j| in U^QU|0>=\sum_j c_j|j>
self.gamma= gamma
if j_ref==None:
#### choose the ref
j_ref = np.random.randint(0, 2**nspins)
while j_ref in self.df_ampl.index:
j_ref = np.random.randint(0, 2**nspins)
else:
pass
self.j_ref = j_ref
##### OVERWRITING () OPERATOR
def __call__(self, TestLevel=0):
self.getImagPart()
self.getRealPart()
##### TURN C_J TO Y_J
def getY(self, delta):
'''
uses the c_j^(r) and imag to compute the y_j_r and imaginary
'''
NotImplemented
try:
## <0| U^ Q U |0>
Q_expect = self.df_ampl.loc[0]['|c_j|'].real
except:
Q_expect = 0
### norm
norm = 1- 2*delta * Q_expect + delta ** 2
### to avoid devision by zero error
_epsilon = 10**(-1 * 2 * self.significant_figures)
### the actual parameters y_j
c_j_times_delta_real = self.c_real * -( delta / (norm + _epsilon) )
c_j_times_delta_imag = self.c_imag * -( delta / (norm + _epsilon) )
params_real_plus_imag = -c_j_times_delta_real.values + 1j*c_j_times_delta_imag.values
## -y_j^(re) + 1j * y_j^(im)
self.yj_parameters = pd.DataFrame(params_real_plus_imag, columns=['y_j'], index = self.c_real.index) ## -y_j^(r)
### delta * cj the otput that will be passed to update circuit
delta_times_cj = c_j_times_delta_real.values + 1j*c_j_times_delta_imag.values
## delta * ( c_j )
self.delta_times_cj = pd.DataFrame(delta_times_cj, columns=['delta_times_cj'], index = self.c_real.index)
# remove 0 --> double check
try:
self.delta_times_cj = self.delta_times_cj.drop(index=0)
except:
pass
### j_list and delta_times_cj_values
j_list = self.delta_times_cj.loc[self.delta_times_cj['delta_times_cj']!=0].index
delta_times_cj_values = self.delta_times_cj.loc[j_list]
#### returns list of js and list of delta*cj's
return [
j_list.tolist(),
delta_times_cj_values.values.T.tolist()[0]
]
##### Q. COMPUTE IMAG PART OF C_J
def getImagPart(self,):
circ_adj_for_imag_part = self.getImagPart_base_circ(self.nspins, self.circ_U, self.Q, self.j_ref, self.gamma)
#################### for each j2 The T_{j_ref -> j2} is different
indexs = self.df_ampl.index ### the observed bit strings from shots; j's
m1s = self.getMsImag(indexs, self.j_ref, self.nspins,
circ_adj_for_imag_part,
self.shots, self.significant_figures )
c2_2s = self.getC2s(indexs, self.df_ampl, self.significant_figures)
c_imag = self.getComponent(c2_2s, m1s, self.gamma)
c_imag = pd.DataFrame(c_imag, index= indexs).round(self.significant_figures)
c_imag.columns=[ 'c_imag_sim' ]
# ###
m1s = pd.DataFrame(m1s, index= indexs)
m1s.columns=[ 'm1s-imag-sim' ]
c2_2s = pd.DataFrame(c2_2s, index= indexs)
c2_2s.columns=[ 'c2^2' ]
### attribute to the obj
self.c_imag = c_imag
self.m1s_from_imag = m1s
self.c2_2power2__imag = c2_2s
##### Q. COMPUTE REAL PART OF C_J
def getRealPart(self,):
circ_adj_for_real_part = self.getRealPart_base_circ(self.nspins, self.circ_U, self.Q, self.j_ref, self.gamma)
#################### for each j2 The T_{j_ref -> j2} is different
indexs = self.df_ampl.index ### the observed bit strings from shots; j's
m1s = self.getMsReal(indexs, self.j_ref, self.nspins,
circ_adj_for_real_part,
self.shots, self.significant_figures )
c2_2s = self.getC2s(indexs, self.df_ampl, self.significant_figures)
c_real = self.getComponent(c2_2s, m1s, self.gamma)
c_real = pd.DataFrame(c_real, index= indexs).round(self.significant_figures)
c_real.columns=[ 'c_real_sim' ]
# ###
m1s = pd.DataFrame(m1s, index= indexs)
m1s.columns=[ 'm1s-real-sim' ]
c2_2s = pd.DataFrame(c2_2s, index= indexs)
c2_2s.columns=[ 'c2^2' ]
### attribute to the obj
self.c_real = c_real
self.m1s_from_real = m1s
self.c2_2power2__real = c2_2s
########################################### TOOLKIT
@staticmethod
def getComponent(c2_2s, m1s, gamma):
component = lambda m_ref, c2_2 : (m_ref - (1/4) * c2_2 *\
(np.cos(gamma/2)**2) - (1/4)*(np.sin(gamma/2))**2 )/\
((-1/2) * np.cos(gamma/2) * np.sin(gamma/2))
return list(map(component, m1s, c2_2s))
@staticmethod
def getC2s(indexs, df_ampl, significant_figures):
c2_2s = []
for j2 in indexs:
#### amplitude from shots
c2 = df_ampl['|c_j|'][j2]
####
c2_2 = c2**2 ### |c_j|^2
c2_2 = np.round(c2_2, significant_figures)
### collect results
c2_2s.append(c2_2)
return c2_2s
@staticmethod
def getMsReal(indexs, j_ref, nspins, circ_adj, shots, significant_figures):
m1s = []
for j2 in indexs:
circ_uhu_adj = Phase.getRealPart_ref_circ(j_ref, j2, nspins, circ_adj)
#### from shots
m_ref = computeAmplFromShots(circ_uhu_adj, shots, j_ref)
####
m_ref = np.round(m_ref, significant_figures)
### collect results
m1s.append(m_ref)
return m1s
@staticmethod
def getMsImag(indexs, j_ref, nspins, circ_adj, shots, significant_figures):
m1s = []
for j2 in indexs:
circ_uhu_adj = Phase.getImagPart_ref_circ(j_ref, j2, nspins, circ_adj)
#### from shots
m_ref = computeAmplFromShots(circ_uhu_adj, shots, j_ref)
####
m_ref = np.round(m_ref, significant_figures)
### collect results
m1s.append(m_ref)
return m1s
@staticmethod
def computeAmplFromShots(circ_uhu_adj, shots, j_ref):
return computeAmplFromShots(circ_uhu_adj, shots, j_ref)
@staticmethod
def getImagPart_base_circ(nspins, circ_U , Q, j_ref, gamma = np.pi/10):
circ_adj = QuantumCircuit(nspins+1)
circ_adj.ry(gamma, qubit=-1) ### R_gamma
circ_adj.x(qubit=-1) ### X
### U
### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) )
### control-Q ; Ancillary - n target
for (q,o) in enumerate(Q):
if o==1:
circ_adj.cx(-1, q)
if o==2:
circ_adj.cy(-1, q)
if o==3:
circ_adj.cz(-1, q)
### U^
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse())
### control-P_{0 j_ref}
circ_adj.x(qubit=nspins)
J1 = list(getBinary(j_ref, nspins)) + [0]
for (q,o) in enumerate(J1):
if o==1:
circ_adj.cx(nspins, q)
circ_adj.x(nspins)
### H on ancillary
circ_adj.h(nspins)
return circ_adj
@staticmethod
def getImagPart_ref_circ(j_ref, j2,nspins, circ_adj):
#### T Gate
p_12_int = j2^j_ref
## operator
P_12 = getBinary(p_12_int, nspins).tolist()+[0] #bitstring array of p12
mult_gate, op_count = multiqubit(P_12, np.pi/4) # turned into T gate
circ_uhu_adj = circ_adj.compose( mult_gate ) #add to the circuit
return circ_uhu_adj
@staticmethod
def getRealPart_ref_circ(j_ref, j2, nspins, circ_adj):
#### T Gate
p_12_int = j2^j_ref
## operator
P_12 = getBinary(p_12_int, nspins).tolist()+[0] #bitstring array of p12
mult_gate, op_count = multiqubit(P_12, np.pi/4) # turned into T gate
circ_uhu_adj = circ_adj.compose( mult_gate ) #add to the circuit
return circ_uhu_adj
@staticmethod
def getRealPart_base_circ(nspins, circ_U , Q, j_ref, gamma = np.pi/10):
circ_adj = QuantumCircuit(nspins+1)
circ_adj.ry(gamma, qubit=-1) ### R_gamma
circ_adj.x(qubit=-1) ### X
### U
### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) )
### control-Q ; Ancillary - n target
for (q,o) in enumerate(Q):
if o==1:
circ_adj.cx(-1, q)
if o==2:
circ_adj.cy(-1, q)
if o==3:
circ_adj.cz(-1, q)
### U^
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse())
### control-P_{0 j_ref}
circ_adj.x(qubit=nspins)
J1 = list(getBinary(j_ref, nspins)) + [0]
for (q,o) in enumerate(J1):
if o==1:
circ_adj.cx(nspins, q)
circ_adj.x(nspins)
### S and H on ancillary
circ_adj.s(-1)
circ_adj.h(nspins)
return circ_adj
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 13 14:39:39 2022
@author: pejmanjouzdani
"""
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit, transpile
from qiskit import Aer
# from Amplitude.AmplitudeFunctions.getAmplitudes import getAmplitudes
# from Amplitude.AmplitudeFunctions.getIndexsFromExecute import getIndexsFromExecute
from Amplitude.amplitude import AmplitudeClass as Amplitude
def computeAmplFromShots(circ, shots, j_ref, backend = 'qasm_simulator'):
pass
'''
'''
#### FIRST ATTEMPT
df_count = Amplitude.getIndexsFromExecute(circ, shots, backend)
try:
m1 = df_count['n_j'][j_ref]/shots #df_count[0].sum()
# print('------------ RESOLVED AT {shots} SHOTS; FIRST ATTEMPT ---------')
except KeyError :
print('WARNING: FIRST CIRCUIT RUN FAILED !')
print('j_ref is not oobserved in the bitstrings... running the circuit with increased shots')
print(f"Increasing shots from {shots} to {10 * shots}")
print()
#### SECOND ATTEMPT -> INCREASE THE SHOTS
df_count = Amplitude.getIndexsFromExecute(circ, 10*shots, backend)
try:
m1 = df_count['n_j'][j_ref]/shots #df_count[0].sum()
print('------------ RESOLVED AT {10*shots} SHOTS; SECOND ATTEMPT ---------')
except KeyError:
print('WARNING: SECOND CIRCUIT RUN FAILED !')
print('j_ref is not oobserved in the bitstrings in the SECOND circuit run...')
print(f"Increasing shots from {10 * shots} to {100*shots}")
print()
#### THIRD ATTEMPT --> INCREASE SHOTS
df_count = Amplitude.getIndexsFromExecute(circ, 100*shots, backend)
try:
m1 = df_count['n_j'][j_ref]/shots #df_count[0].sum()
print('------------ RESOLVED AT {100*shots} SHOTS; THIRD ATTEMPT ---------')
except:
print('WARNING: THIRD CIRCUIT RUN FAILED !')
print('j_ref is not oobserved in the bitstrings in the THIRD circuit run...')
print(f"Increasing shots from {100 * shots} to {1000 * shots}")
print()
#### FORTH ATTEMPT --> INCREASE SHOTS
df_count = Amplitude.getIndexsFromExecute(circ, 1000*shots, backend)
try:
m1 = df_count['n_j'][j_ref]/shots #df_count[0].sum()
print('------------ RESOLVED AT {1000*shots} SHOTS; FORTH ATTEMPT ---------')
except KeyError:
raise
return m1
if __name__=='__main__':
'''
Testing the function:
create a circ_UQU circuit
'''
from qiskit import QuantumCircuit
from Amplitude.amplitude import AmplitudeClass as Amplitude
from BasicFunctions.functions import getBinary, getState
from MultiQubitGate.functions import multiqubit
################################################################
################################################################
##################### FOR TEST #######################
################################################################
################################################################
################################################################
################################################################
################################################################
def getRandomU(nspins, num_layers=10):
circ = QuantumCircuit(nspins)
for l in range(num_layers):
for i in range(nspins):
##############
q=np.random.randint(nspins)
g=np.random.randint(1, 4)
p=np.random.uniform(-1,1)
if g==1:
circ.rx(p,q)
if g==2:
circ.ry(p,q)
if g==2:
circ.rz(p,q)
##############
q=np.random.randint(nspins-1)
circ.cnot(q, q+1)
return circ
################################################################
################################################################
def getRandomQ(nspins):
Q = np.random.randint(0,2, size=nspins)
return Q
################################################################
################################################################
def getCircUQU(circ, Q):
circ_uhu=QuantumCircuit.copy(circ)
for (q,o) in enumerate(Q):
if o==0:
pass
if o==1:
circ_uhu.x(q)
if o==2:
circ_uhu.y(q)
if o==3:
circ_uhu.z(q)
circ_uhu=circ_uhu.compose(QuantumCircuit.copy(circ).inverse())
return circ_uhu
################################################################
################################################################
seed = 1211
np.random.seed(seed)
################################################################
################################################################
nspins = 2 # >=2
num_layers =2
num_itr =1
machine_precision = 10
shots = 1000000
eta = 100
significant_figures = 3#np.log10(np.sqrt(shots)).astype(int)
circ_U = getRandomU(nspins, num_layers)
Q = getRandomQ(nspins)
circ_UQU = getCircUQU(circ_U, Q)
print(Q)
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 8 18:22:28 2022
Created on Thu Oct 13 10:29:00 2022
@author: pej
"""
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit
from MultiQubitGate.functions import multiqubit
from BasicFunctions.functions import getBinary, getState
from Phase.PhaseFunctions.computeAmplFromShots import computeAmplFromShots
####################################################################
####################################################################
####################################################################
####################################################################
################### When c0 == 0
def getImagPart(df_ampl, ### amplitude |c_j| computed from shots
circ_U,
circ_UQU,
Q,
significant_figure,
nspins,
shots,
j_ref,
machine_precision=10,
):
'''
for the scenario where j_ref=0 is NOT in df_ampl.index
or c_0 == 0
'''
# ################## FOR COMPARISON
# #### df_comp_exact, ### this is exact c_j for benchmark
# circ_state = getState(circ_UQU, machine_precision)
# vec=circ_state[df_ampl.index, : ]
# df_comp_exact = pd.DataFrame(vec, df_ampl.index)
# ##################
circ_adj = QuantumCircuit(nspins+1)
_gamma = np.pi/10
circ_adj.ry(_gamma, qubit=-1) ### R_gamma
circ_adj.x(qubit=-1) ### X
### U
### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) )
### control-Q ; Ancillary - n target
for (q,o) in enumerate(Q):
if o==1:
circ_adj.cx(-1, q)
if o==2:
circ_adj.cy(-1, q)
if o==3:
circ_adj.cz(-1, q)
### U^
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse())
### control-P_{0 j_ref}
circ_adj.x(qubit=nspins)
J1 = list(getBinary(j_ref, nspins)) + [0]
for (q,o) in enumerate(J1):
if o==1:
circ_adj.cx(nspins, q)
circ_adj.x(nspins)
### H on ancillary
circ_adj.h(nspins)
#################### for each j2 The T_{j_ref -> j2} is different
indexs = df_ampl.index ### the observed bit strings from shots; j's
parts_imag= [[ 0]] # ref
part_indexs=[j_ref]
for j2 in indexs:
############################################ LEVEL0
################### LEVEL00
#### T Gate
p_12_int = j2^j_ref
## operator
P_12 = getBinary(p_12_int, nspins).tolist()+[0] #bitstring array of p12
mult_gate, op_count = multiqubit(P_12, np.pi/4) # turned into T gate
circ_uhu_adj = circ_adj.compose( mult_gate ) #add to the circuit
################### LEVEL01
##### from shots
m1, __ = computeAmplFromShots(circ_uhu_adj, shots, j_ref)
m1 = np.round(m1, significant_figure)
#### amplitude from shots
c2_2 = df_ampl[0][j2]**2 ### |c_j|^2
c2_2 = np.round(c2_2, significant_figure)
#### compute the sin of theta
imag_part = (m1 - (1/4) * c2_2**2 * (np.cos(_gamma/2)**2) - (1/4)*(np.sin(_gamma/2))**2 )/ ((-1/2) * np.cos(_gamma/2) * np.sin(_gamma/2))
#### round to allowed prcision
imag_part = np.round(imag_part, significant_figure)
############################################ LEVEL0 END
### collect results
parts_imag.append([ imag_part,
# df_comp_exact[0][j2].imag
])
part_indexs.append(j2)
parts_imag = pd.DataFrame(parts_imag, index= part_indexs).round(significant_figure)
parts_imag.columns=[ 'c_imag_sim',
# 'c_imag_exct'
]
### !!! TODO
### the row corresponding to j_ref must be taken out
return parts_imag
if __name__=='__main__':
pass
from Amplitude.Amplitude import Amplitude
################################################################
################################################################
##################### FOR TEST #######################
################################################################
################################################################
################################################################
################################################################
################################################################
def getRandomU(nspins, num_layers=10):
circ = QuantumCircuit(nspins)
for l in range(num_layers):
for i in range(nspins):
##############
q=np.random.randint(nspins)
g=np.random.randint(1, 4)
p=np.random.uniform(-1,1)
if g==1:
circ.rx(p,q)
if g==2:
circ.ry(p,q)
if g==2:
circ.rz(p,q)
##############
q=np.random.randint(nspins-1)
circ.cnot(q, q+1)
return circ
################################################################
################################################################
def getRandomQ(nspins):
Q = np.random.randint(0,2, size=nspins)
return Q
################################################################
################################################################
def getCircUQU(circ, Q):
circ_uhu=QuantumCircuit.copy(circ)
for (q,o) in enumerate(Q):
if o==0:
pass
if o==1:
circ_uhu.x(q)
if o==2:
circ_uhu.y(q)
if o==3:
circ_uhu.z(q)
circ_uhu=circ_uhu.compose(QuantumCircuit.copy(circ).inverse())
return circ_uhu
################################################################
################################################################
seed = 1211
np.random.seed(seed)
################################################################
################################################################
nspins = 6 # >=2
num_layers =2
num_itr =1
machine_precision = 10
shots = 1000
eta = 100
significant_figures = 3#np.log10(np.sqrt(shots)).astype(int)
circ_U = getRandomU(nspins, num_layers)
Q = getRandomQ(nspins)
circ_UQU = getCircUQU(circ_U, Q)
print('Q=', Q)
## ### amplitude |c_j| computed from shots
localAmplitudeObj = Amplitude(circ_U, circ_UQU, shots, eta, significant_figures, machine_precision)
localAmplitudeObj()
df_ampl = localAmplitudeObj.df_ampl
######## EXCLUDE index 0
try:
df_ampl = df_ampl.drop(index=0)
# df_ampl_bm = df_ampl_bm.drop(index=0)
except:
pass
print('df_ampl')
print(df_ampl)
print()
# print('df_ampl_bm')
# print(df_ampl_bm)
# print()
#### choose the ref
j_ref = np.random.randint(0, 2**nspins)
while j_ref in df_ampl.index:
j_ref = np.random.randint(0, 2**nspins)
print('j_ref = ' , j_ref)
print('number of js = ' , df_ampl.shape[0])
parts_imag = getImagPart(df_ampl, ### amplitude |c_j| computed from shots
circ_U,
circ_UQU,
Q,
significant_figures,
nspins,
shots,
j_ref,
)
print(parts_imag)
# print('\n\n##### sign errors')
# num_error = 0
# for jj in parts_imag.index:
# if parts_imag['c_imag_exct'][jj]>=0 and parts_imag['c_imag_sim'][jj]>=0:
# num_error+= 0
# else:
# if parts_imag['c_imag_exct'][jj]<0 and parts_imag['c_imag_sim'][jj]<0:
# num_error+= 0
# else:
# print(parts_imag['c_imag_exct'][jj], ' ', parts_imag['c_imag_sim'][jj])
# num_error+= 1
# print('error %= ',
# np.round(num_error/parts_imag.shape[0]*100, 2),
# 'num incorrect = ',
# num_error,
# 'total = ',
# parts_imag.shape[0]
# )
# print('\n\n##### L2 norm')
# error_L2 = 0
# for jj in parts_imag.index:
# diff = np.abs(parts_imag['c_imag_exct'][jj] - parts_imag['c_imag_sim'][jj])
# error = diff/( + 10**(-1*significant_figures) + np.abs(parts_imag['c_imag_exct'][jj] ) )
# print(error)
# error_L2+= error/parts_imag.shape[0]
# print('---')
# print(error_L2)
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 6 11:35:58 2022
@author: pejmanjouzdani
"""
import numpy as np
from qiskit import QuantumCircuit
from BasicFunctions.functions import getBinary
def getImagPart_base_circ(nspins, circ_U , Q, j_ref, gamma = np.pi/10):
circ_adj = QuantumCircuit(nspins+1)
circ_adj.ry(gamma, qubit=-1) ### R_gamma
circ_adj.x(qubit=-1) ### X
### U
### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) )
### control-Q ; Ancillary - n target
for (q,o) in enumerate(Q):
if o==1:
circ_adj.cx(-1, q)
if o==2:
circ_adj.cy(-1, q)
if o==3:
circ_adj.cz(-1, q)
### U^
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse())
### control-P_{0 j_ref}
circ_adj.x(qubit=nspins)
J1 = list(getBinary(j_ref, nspins)) + [0]
for (q,o) in enumerate(J1):
if o==1:
circ_adj.cx(nspins, q)
circ_adj.x(nspins)
### H on ancillary
circ_adj.h(nspins)
return circ_adj
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 8 18:22:28 2022
Created on Thu Oct 13 10:29:00 2022
@author: pej
"""
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit
from MultiQubitGate.functions import multiqubit
from BasicFunctions.functions import getBinary, getState
from Phase.PhaseFunctions.computeAmplFromShots import computeAmplFromShots
####################################################################
####################################################################
####################################################################
####################################################################
################### When c0 == 0
def getRealPart(df_ampl, ### amplitude |c_j| computed from shots
circ_U,
circ_UQU,
Q,
significant_figure,
nspins,
shots,
j_ref,
machine_precision=10,
):
'''
for the scenario where j_ref=0 is NOT in df_ampl.index
or c_0 == 0
'''
# ################## FOR COMPARISON
# #### df_comp_exact, ### this is exact c_j for benchmark
# circ_state = getState(circ_UQU, machine_precision)
# vec=circ_state[df_ampl.index, : ]
# df_comp_exact = pd.DataFrame(vec, df_ampl.index)
# ##################
circ_adj = QuantumCircuit(nspins+1)
_gamma = -np.pi/4
circ_adj.ry(_gamma, qubit=-1) ### R_gamma
circ_adj.x(qubit=-1) ### X
### U
### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) )
### control-Q ; Ancillary - n target
for (q,o) in enumerate(Q):
if o==1:
circ_adj.cx(-1, q)
if o==2:
circ_adj.cy(-1, q)
if o==3:
circ_adj.cz(-1, q)
### U^
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse())
### control-P_{0 j_ref}
circ_adj.x(qubit=nspins)
J1 = list(getBinary(j_ref, nspins)) + [0]
for (q,o) in enumerate(J1):
if o==1:
circ_adj.cx(nspins, q)
circ_adj.x(nspins)
### S and H on ancillary
circ_adj.s(-1)
circ_adj.h(nspins)
#################### for each j2 The T_{j_ref -> j2} is different
indexs = df_ampl.index ### the observed bit strings from shots; j's
parts_real= [[ 0]] # ref
part_indexs=[j_ref]
for j2 in indexs:
#### T Gate
p_12_int = j2^j_ref
## operator
P_12 = getBinary(p_12_int, nspins).tolist()+[0] #bitstring array of p12
mult_gate, op_count = multiqubit(P_12, np.pi/4) # turned into T gate
circ_uhu_adj = circ_adj.compose( mult_gate ) #add to the circuit
##### from shots
m1, __ = computeAmplFromShots(circ_uhu_adj, shots, j_ref)
m1 = np.round(m1, significant_figure)
#### amplitude from shots
c2_2 = df_ampl[0][j2]**2 ### |c_j|^2
c2_2 = np.round(c2_2, significant_figure)
#### compute the cos of theta
real_part = (m1 - (1/4) * c2_2**2 * (np.cos(_gamma/2)**2) - (1/4)*(np.sin(_gamma/2))**2 )/ ((-1/2) * np.cos(_gamma/2) * np.sin(_gamma/2))
#### round to allowed prcision
real_part = np.round(real_part, significant_figure)
### collect results
parts_real.append([ real_part,
# df_comp_exact[0][j2].real
])
part_indexs.append(j2)
parts_real = pd.DataFrame(parts_real, index= part_indexs).round(significant_figure)
parts_real.columns=[ 'c_real_sim',
# 'c_real_exct'
]
return parts_real
if __name__=='__main__':
pass
from Amplitude.Amplitude import Amplitude
################################################################
################################################################
##################### FOR TEST #######################
################################################################
################################################################
################################################################
################################################################
################################################################
def getRandomU(nspins, num_layers=10):
circ = QuantumCircuit(nspins)
for l in range(num_layers):
for i in range(nspins):
##############
q=np.random.randint(nspins)
g=np.random.randint(1, 4)
p=np.random.uniform(-1,1)
if g==1:
circ.rx(p,q)
if g==2:
circ.ry(p,q)
if g==2:
circ.rz(p,q)
##############
q=np.random.randint(nspins-1)
circ.cnot(q, q+1)
return circ
################################################################
################################################################
def getRandomQ(nspins):
Q = np.random.randint(0,2, size=nspins)
return Q
################################################################
################################################################
def getCircUQU(circ, Q):
circ_uhu=QuantumCircuit.copy(circ)
for (q,o) in enumerate(Q):
if o==0:
pass
if o==1:
circ_uhu.x(q)
if o==2:
circ_uhu.y(q)
if o==3:
circ_uhu.z(q)
circ_uhu=circ_uhu.compose(QuantumCircuit.copy(circ).inverse())
return circ_uhu
################################################################
################################################################
seed = 1211
np.random.seed(seed)
################################################################
################################################################
nspins = 6 # >=2
num_layers =2
num_itr =1
machine_precision = 10
shots = 1000
eta = 100
significant_figures = 3#np.log10(np.sqrt(shots)).astype(int)
circ_U = getRandomU(nspins, num_layers)
Q = getRandomQ(nspins)
circ_UQU = getCircUQU(circ_U, Q)
print('Q=', Q)
## ### amplitude |c_j| computed from shots
localAmplitudeObj = Amplitude(circ_U, circ_UQU, shots, eta, significant_figures, machine_precision)
localAmplitudeObj()
df_ampl = localAmplitudeObj.df_ampl
######## EXCLUDE index 0
try:
df_ampl = df_ampl.drop(index=0)
except:
pass
print('df_ampl')
print(df_ampl)
print()
#### choose the ref
j_ref = np.random.randint(0, 2**nspins)
while j_ref in df_ampl.index:
j_ref = np.random.randint(0, 2**nspins)
print('j_ref = ' , j_ref)
print('number of js = ' , df_ampl.shape[0])
parts_real = getRealPart(df_ampl, ### amplitude |c_j| computed from shots
circ_U,
circ_UQU,
Q,
significant_figures,
nspins,
shots,
j_ref,
)
print(parts_real)
# print('\n\n##### sign errors')
# num_error = 0
# for jj in parts_real.index:
# if parts_real['c_real_exct'][jj]>=0 and parts_real['c_real_sim'][jj]>=0:
# num_error+= 0
# else:
# if parts_real['c_real_exct'][jj]<0 and parts_real['c_real_sim'][jj]<0:
# num_error+= 0
# else:
# print(parts_real['c_real_exct'][jj], ' ', parts_real['c_real_sim'][jj])
# num_error+= 1
# print('error %= ',
# np.round(num_error/parts_real.shape[0]*100, 2),
# 'num incorrect = ',
# num_error,
# 'total = ',
# parts_real.shape[0]
# )
# print('\n\n##### L2 norm')
# error_L2 = 0
# for jj in parts_real.index:
# diff = np.abs(parts_real['c_real_exct'][jj] - parts_real['c_real_sim'][jj])
# error = diff/( + 10**(-1*significant_figures) + np.abs(parts_real['c_real_exct'][jj] ) )
# print(error)
# error_L2+= error/parts_real.shape[0]
# print('---')
# print(error_L2)
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 6 12:00:14 2022
@author: pejmanjouzdani
"""
import numpy as np
from qiskit import QuantumCircuit
from BasicFunctions.functions import getBinary
def getRealPart_base_circ(nspins, circ_U , Q, j_ref, gamma = np.pi/10):
circ_adj = QuantumCircuit(nspins+1)
circ_adj.ry(gamma, qubit=-1) ### R_gamma
circ_adj.x(qubit=-1) ### X
### U
### attaches U to the q=1 ... q=n qubits, while q=0 is the ancillary
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U) )
### control-Q ; Ancillary - n target
for (q,o) in enumerate(Q):
if o==1:
circ_adj.cx(-1, q)
if o==2:
circ_adj.cy(-1, q)
if o==3:
circ_adj.cz(-1, q)
### U^
circ_adj = circ_adj.compose(QuantumCircuit.copy(circ_U).inverse())
### control-P_{0 j_ref}
circ_adj.x(qubit=nspins)
J1 = list(getBinary(j_ref, nspins)) + [0]
for (q,o) in enumerate(J1):
if o==1:
circ_adj.cx(nspins, q)
circ_adj.x(nspins)
### S and H on ancillary
circ_adj.s(-1)
circ_adj.h(nspins)
return circ_adj
|
https://github.com/JouziP/MQITE
|
JouziP
|
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
# simulate in statevector_simulator
def simulateStatevector(circuit):
backend = Aer.get_backend('statevector_simulator')
result = execute(circuit.remove_final_measurements(inplace=False), backend, shots=1).result()
counts = result.get_counts()
return result.get_statevector(circuit)
# return plot_histogram(counts, color='midnightblue', title="StateVector Histogram")
# simulate in qasm_simulator
def simulateQasm(circuit, count=1024):
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend, shots=count).result()
counts = result.get_counts()
return plot_histogram(counts, color='midnightblue', title="Qasm Histogram")
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 14:12:30 2022
@author: pejmanjouzdani
"""
import numpy as np
import pandas as pd
from qiskit import QuantumCircuit
from BasicFunctions.functions import timing, getBinary, getGateStats
from MultiQubitGate.functions import multiqubit
class UpdateCircuit:
def __init__(self,):
pass
def __call__(self, list_j, list_y_j, circ,):
self.circ_new, self.multigate_gate_stat = self.updateCirc(list_j, list_y_j, circ)
# return self.circ_new, self.multigate_gate_stat
@staticmethod
def updateCirc(list_j, list_y_j, circ,):
nspins = circ.num_qubits
circ_P = QuantumCircuit(nspins)
multigate_gate_stat = pd.DataFrame()
for im in range(len(list_j)):
# print('\n8888888888888888 ')
####### imag
m=list_j[im]
h = getBinary(m, nspins)
### imag part
y_j= list_y_j[im].imag
if np.round(y_j, 4)==0:
pass
else:
mult_gate, op_count = multiqubit(h, y_j)
circ_P = circ_P.compose(mult_gate)
####### REAL
### replace 3 1 with Y
y_j= -list_y_j[im].real
h[np.nonzero(h)[0][0]]=2
if np.round(y_j, 4)==0:
pass
else:
mult_gate, op_count =multiqubit(h, y_j)
####### statistics
multigate_gate_stat = pd.concat((multigate_gate_stat,
pd.DataFrame([op_count], index=[m])) )
circ_P = circ_P.compose(mult_gate)
circ_new = circ_P.compose(circ)
return circ_new, multigate_gate_stat
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# A quantum circuit is composed by quantum and classical bits.
#
# here are the objects that we use to create a quantum circuit in qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
# we use a quantum register to keep our quantum bits.
qreg = QuantumRegister(1) # in this example we will use a single quantum bit
# To get an information from a quantum bit, it must be measured. (More details will appear.)
# The measurement result is stored classically.
# Therefore, we also use a classical regiser with classical bits
creg = ClassicalRegister(1) # in this example we will use a single classical bit
# now we can define our quantum circuit
# it is composed by a quantum and a classical register
mycircuit = QuantumCircuit(qreg,creg)
# we apply operators on quantum bits
# operators are also called as gates
# we apply NOT operator represented as "x" in qiskit
# operator is a part of the circuit, and we should specify the quantum bit as its parameter
mycircuit.x(qreg[0]) # (quantum) bits are enumerated starting from 0
# NOT operator or x-gate is applied to the first qubit of the quantum register
# let's run our codes until now, and then draw our circuit
print("Everything looks fine, let's continue ...")
# in qiskit, the circuit object has a method called "draw"
# it can take different parameters
# we use "matplotlib" -- the first parameter
# we also order the bits by reversing, which helps us to read the output -- the second parameter
# let's draw our circuit now
mycircuit.draw(output='mpl',reverse_bits=True)
# re-execute this cell if you DO NOT see the circuit diagram
# measurement is defined by associating a quantum bit to a classical bit
mycircuit.measure(qreg[0],creg[0])
# the result will be stored in the classical bit
print("Everything looks fine, let's continue ...")
# let's draw the circuit again to see how the measurement is defined
mycircuit.draw() # we use now ASCII art version
# reexecute me if you DO NOT see the circuit diagram
# we are done with designing of our circuit
# now we can execute it
# we execute quantum circuits many times (WHY?)
# we use method "execute" and object "Aer" from qiskit library
from qiskit import execute, Aer
# we create a job object for execution of the circuit
# there are three parameters
# 1. mycircuit
# 2. beckend on which it will be executed: we will use local simulator
# 3. how_many_times will it be executed, let's pick it as 1024
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1024)
# we can get the result of the outcome as follows
counts = job.result().get_counts(mycircuit)
print(counts)
# usually quantum programs produce probabilistic outcomes
#
# My second quantum circuit
#
# we import all at once
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# we will use 4 quantum bits and 4 classical bits
qreg2 = QuantumRegister(4)
creg2 = ClassicalRegister(4)
mycircuit2 = QuantumCircuit(qreg2,creg2)
# We will apply x-gate to the first quantum bit twice
mycircuit2.x(qreg2[0])
mycircuit2.x(qreg2[0])
# We will apply x-gate to the fourth quantum bit once
mycircuit2.x(qreg2[3])
# We will apply x-gate to the third quantum bit three times
mycircuit2.x(qreg2[2])
mycircuit2.x(qreg2[2])
mycircuit2.x(qreg2[2])
# We will apply x-gate to the second quantum bit four times
mycircuit2.x(qreg2[1])
mycircuit2.x(qreg2[1])
mycircuit2.x(qreg2[1])
mycircuit2.x(qreg2[1])
# if the sizes of quantum and classical registers are the same, we can define measurements with a single line of code
mycircuit2.measure(qreg2,creg2)
# then each quantum bit and classical bit is associated with respect to their indices
# let's run our codes until now, and then draw our circuit
print("Everything looks fine, let's continue ...")
mycircuit2.draw(output='mpl',reverse_bits=True)
# re-execute me if you DO NOT see the circuit diagram
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=500)
counts = job.result().get_counts(mycircuit2)
print(counts)
def print_outcomes(counts): # takes a dictionary variable
for outcome in counts: # for each key-value in dictionary
reverse_outcome = ''
for i in outcome: # each string can be considered as a list of characters
reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s)
print(reverse_outcome,"is observed",counts[outcome],"times")
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1024)
counts = job.result().get_counts(mycircuit2) # counts is a dictionary object in python
print_outcomes(counts)
from random import randrange
n = 20
r=randrange(n) # pick a number from the list {0,1,...,n-1}
print(r)
# test this method by using a loop
for i in range(10):
print(randrange(n))
#
# your solution is here
#
# Quantum register with 10 bits
qreg3 = QuantumRegister(10)
creg3 = ClassicalRegister(10)
# Construct the quantum circuit
mycircuit3 = QuantumCircuit(qreg3,creg3)
qubits_idx=[]
# Randomly iterate through bits
for i in range(10):
if(randrange(2) == 1): # 1 is the head
mycircuit3.x(qreg3[i])
qubits_idx.append(i)
# Measure the results
mycircuit3.measure(qreg3,creg3)
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=128)
counts = job.result().get_counts(mycircuit3)
print_outcomes(counts)
# display counts and randomly picked index
print(counts)
print(picked_qubits_idx)
mycircuit3.draw(output='mpl',reverse_bits=True)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# we import all necessary methods and objects
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from random import randrange
# we will use 10 quantum bits and 10 classical bits
qreg3 = QuantumRegister(10)
creg3 = ClassicalRegister(10)
mycircuit3 = QuantumCircuit(qreg3,creg3)
# we will store the index of each qubit to which x-gate is applied
picked_qubits=[]
for i in range(10):
if randrange(2) == 0: # Assume that 0 is Head and 1 is Tail
mycircuit3.x(qreg3[i]) # apply x-gate
print("x-gate is applied to the qubit with index",i)
picked_qubits.append(i) # i is picked
# measurement
mycircuit3.measure(qreg3,creg3)
print("Everything looks fine, let's continue ...")
# draw the circuit
mycircuit3.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit and read the results
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=128)
counts = job.result().get_counts(mycircuit3)
def print_outcomes(counts): # takes a dictionary variable
for outcome in counts: # for each key-value in dictionary
reverse_outcome = ''
for i in outcome: # each string can be considered as a list of characters
reverse_outcome = i + reverse_outcome # each new symbol comes before the old symbol(s)
print(reverse_outcome,"is observed",counts[outcome],"times")
print_outcomes(counts)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# your solution is here
#
from random import randrange
def experiment(n):
num_tails = 0
num_heads = 0
for i in range(n):
if(randrange(2) == 0): # 0 is the head
num_heads += 1
else:
num_tails += 1
return num_heads, num_tails
num_heads1000, num_tails1000 = experiment(1000)
print("Experiment with 1000 flips | heads: " + str(num_heads1000) + " tails: " + str(num_tails1000))
print("Probability | heads: " + str(num_heads1000/1000) + " tails: " + str(num_tails1000/1000))
num_heads10000, num_tails10000 = experiment(10000)
print("Experiment with 10,000 flips | heads: " + str(num_heads10000) + " tails: " + str(num_tails10000))
print("Probability | heads: " + str(num_heads10000/10000) + " tails: " + str(num_tails10000/10000))
num_heads100000, num_tails100000 = experiment(100000)
print("Experiment with 100,000 flips | heads: " + str(num_heads100000) + " tails: " + str(num_tails100000))
print("Probability | heads: " + str(num_heads100000/1000000) + " tails: " + str(num_tails100000/1000000))
#
# your solution is here
#
def experiment(n):
num_tails = 0
num_heads = 0
for i in range(n):
if(randrange(5) < 2): # < 0.4 prob for tail
num_tails += 1
else:
num_heads += 1
return num_heads, num_tails
num_heads1000, num_tails1000 = experiment(1000)
print("Experiment with 1000 flips | heads: " + str(num_heads1000) + " tails: " + str(num_tails1000))
print("Probability | heads: " + str(num_heads1000/1000) + " tails: " + str(num_tails1000/1000))
num_heads10000, num_tails10000 = experiment(10000)
print("Experiment with 10,000 flips | heads: " + str(num_heads10000) + " tails: " + str(num_tails10000))
print("Probability | heads: " + str(num_heads10000/10000) + " tails: " + str(num_tails10000/10000))
num_heads100000, num_tails100000 = experiment(100000)
print("Experiment with 100,000 flips | heads: " + str(num_heads100000) + " tails: " + str(num_tails100000))
print("Probability | heads: " + str(num_heads100000/1000000) + " tails: " + str(num_tails100000/1000000))
# proportion of heads and tails
print(str((num_heads100000)/(num_tails100000)))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
from random import randrange
for experiment in [100,1000,10000,100000]:
heads = tails = 0
for i in range(experiment):
if randrange(2) == 0: heads = heads + 1
else: tails = tails + 1
print("experiment:",experiment)
print("the ratio of #heads/#tails is",(heads/tails),"heads =",heads,"tails = ",tails)
print() # empty line
from random import randrange
# let's pick a random number between {0,1,...,99}
# it is expected to be less than 60 with probability 0.6
# and greater than or equal to 60 with probability 0.4
for experiment in [100,1000,10000,100000]:
heads = tails = 0
for i in range(experiment):
if randrange(100) <60: heads = heads + 1 # with probability 0.6
else: tails = tails + 1 # with probability 0.4
print("experiment:",experiment)
print("the ratio of #heads/#tails is",(heads/tails),"heads =",heads,"tails = ",tails)
print() # empty line
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# OUR SOLUTION
#
# initial case
# We assume that the probability of getting head is 1 at the beginning,
# because Asja will start with one euro.
prob_head = 1
prob_tail = 0
#
# first coin-flip
#
# if the last result was head
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
# if the last result was tail
# we know that prob_tail is 0 at the beginning
# but we still keep these two lines to have the same code for each iteration
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
# update the probabilities at the end of coin toss
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
#
# second coin-flip
#
# we do the same calculations
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
#
# third coin-flip
#
# we do the same calculations
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
# print prob_head and prob_tail
print("the probability of getting head",prob_head)
print("the probability of getting tail",prob_tail)
#
# your solution is here
#
prob_head = 0.00001
prob_tail = 0.99999
def toss(prob_head, prob_tail):
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
return prob_head, prob_tail
# toss the biased coin 10 times
for i in range(10):
prob_head, prob_tail = toss(prob_head, prob_tail)
print("After 10 coin tosses - prob of heads: " + str(prob_head) + " | prob of tails: " + str(prob_tail))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# We copy and paste the previous code
#
# initial case
# We assume that the probability of getting head is 1 at the beginning,
# becasue Asja will start with one euro.
prob_head = 1
prob_tail = 0
number_of_iterations = 10
for i in range(number_of_iterations):
# if the last result was head
new_prob_head_from_head = prob_head * 0.6
new_prob_tail_from_head = prob_head * 0.4
# if the last result was tail
# we know that prob_tail is 0 at the begining
# but we still keep these two lines to have the same code for each iteration
new_prob_head_from_tail = prob_tail * 0.3
new_prob_tail_from_tail = prob_tail * 0.7
# update the probabilities at the end of coin toss
prob_head = new_prob_head_from_head + new_prob_head_from_tail
prob_tail = new_prob_tail_from_head + new_prob_tail_from_tail
# print prob_head and prob_tail
print("the probability of getting head",prob_head)
print("the probability of getting tail",prob_tail)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# your code is here
#
prob_dict = dict()
prob_6 = 1/(7+5+4+2+6+1)
prob_5 = 6/(7+5+4+2+6+1)
prob_4 = 2/(7+5+4+2+6+1)
prob_3 = 4/(7+5+4+2+6+1)
prob_2 = 5/(7+5+4+2+6+1)
prob_1 = 7/(7+5+4+2+6+1)
prob_dict['6'] = prob_6
prob_dict['5'] = prob_5
prob_dict['4'] = prob_4
prob_dict['3'] = prob_3
prob_dict['2'] = prob_2
prob_dict['1'] = prob_1
print(prob_dict)
#
# your solution is here
#
from random import randrange
import numpy as np
state1 = randrange(101)
state2 = randrange(101)
state3 = randrange(101)
state4 = randrange(101)
sum_states = state1 + state2 + state3 + state4
state_vector = list()
state_vector.append(state1/sum_states)
state_vector.append(state2/sum_states)
state_vector.append(state3/sum_states)
state_vector.append(state4/sum_states)
print(state_vector)
state_vector = np.array(state_vector)
# state vector
print("state vector: " + str(np.transpose(state_vector)))
print("all state probs has to sum up to 1: " + str(np.sum(state_vector)))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# all portions are stored in a list
all_portions = [7,5,4,2,6,1];
# let's calculate the total portion
total_portion = 0
for i in range(6):
total_portion = total_portion + all_portions[i]
print("total portion is",total_portion)
# find the weight of one portion
one_portion = 1/total_portion
print("the weight of one portion is",one_portion)
print() # print an empty line
# now we can calculate the probabilities of rolling 1,2,3,4,5, and 6
for i in range(6):
print("the probability of rolling",(i+1),"is",(one_portion*all_portions[i]))
# we will randomly create a probabilistic state
#
# we should be careful about two things:
# 1. a probability value must be between 0 and 1
# 2. the total probability must be 1
#
# let's use a list of size 4
# initial values are zeros
my_state = [0,0,0,0]
normalization_factor = 0 # this will be the summation of four values
# we pick for random values between 0 and 100
from random import randrange
while normalization_factor==0: # the normalization factor cannot be zero
for i in range(4):
my_state[i] = randrange(101) # pick a random value between 0 and (101-1)
normalization_factor += my_state[i]
print("the random values before the normalization",my_state)
# let's normalize each value
for i in range(4): my_state[i] = my_state[i]/normalization_factor
print("the random values after the normalization",my_state)
# let's find their summation
sum = 0
for i in range(4): sum += my_state[i]
print("the summation is",sum)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# your solution is here
#
import numpy as np
random_arr = np.random.randn(3,3)
random_arr = np.abs(random_arr)
sum_elements = np.sum(random_arr)
random_arr = random_arr / sum_elements
print(random_arr)
print("verify the probabilistic state from sum of elements: " + str(np.sum(random_arr)))
#
# your solution is here
#
prob_operator = np.array([[0.6, 0.3], [0.4, 0.7]])
prob_state = np.array([1, 0])
new_prob_state = np.matmul(prob_operator, prob_state)
print("1st state transition: " + str(new_prob_state))
new_prob_state = np.matmul(prob_operator, new_prob_state)
print("2nd state transition: " + str(new_prob_state))
# operator for the test
A = [
[0.4,0.6,0],
[0.2,0.1,0.7],
[0.4,0.3,0.3]
]
# state for test
v = [0.1,0.3,0.6]
#
# your solution is here
#
# v = [1,0,0]
def find_new_state(A, v):
return np.matmul(A, v)
new_state = find_new_state(A, v)
print(new_state)
# the initial state
initial = [0.5, 0, 0.5, 0]
# probabilistic operator for symbol a
A = [
[0.5, 0, 0, 0],
[0.25, 1, 0, 0],
[0, 0, 1, 0],
[0.25, 0, 0, 1]
]
# probabilistic operator for symbol b
B = [
[1, 0, 0, 0],
[0, 1, 0.25, 0],
[0, 0, 0.5, 0],
[0, 0, 0.25, 1]
]
#
# your solution is here
#
def find_new_state(operator, initial):
return np.matmul(operator, initial)
def read_string(string_to_read):
for c in string_to_read:
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# let's start with a zero matrix
A = [
[0,0,0],
[0,0,0],
[0,0,0]
]
# we will randomly pick the entries and then make normalization for each column
# it will be easier to iteratively construct the columns
# you may notice that each column is a probabilistic state
from random import randrange
normalization_factor = [0,0,0] # the normalization factor of each column may be different
for j in range(3): # each column is iteratively constructed
normalization_factor[j] = 0
while normalization_factor[j]==0: # the normalization factor cannot be zero
for i in range(3):
A[i][j] = randrange(101) # pick a random value between 0 and 100
normalization_factor[j] += A[i][j]
# let's print matrix A before the normalization
# the entries are between 0 and 100
print("matrix A before normalization:")
for i in range(3):
print(A[i])
# let's normalize each column
for j in range(3):
for i in range(3):
A[i][j] /= normalization_factor[j] # shorter form of A[i][j] = A[i][j] / normalization_factor[j]
# let's print matrix A after the normalization
print() # print an empty line
print("matrix A after normalization:")
for i in range(3):
print(A[i])
print()
print("the column summations must be 1")
sum = [0,0,0]
for j in range(3):
for i in range(3):
sum[j] += A[i][j]
print(sum)
# Asja's probabilistic operator (coin flip protocol)
A = [
[0.6,0.3],
[0.4,0.7]
]
# one-step evolution of Asja's probabilistic operator on a given probabilistic state
def asja(prelist):
newlist=[0,0]
for i in range(2): # for each row
for j in range(2): # for each column
newlist[i] = newlist[i] + prelist[j] * A[i][j] # summation of pairwise multiplication
return newlist # return the new state
# initial state
state = [1,0]
# after one step
state = asja(state)
print("after one step, the state is",state)
# the new state is correct
# let's check one more step
state = asja(state)
print("after two steps, the state is",state)
# this is also correct
#
# then, let's evolve the system for more steps
for i in [3,6,9,12,24,48,96]:
# start from the initial state
state = [1,0]
for t in range(i): # apply asja t times
state = asja(state)
# print the result
print(state,"after",(t+1),"steps")
def evolve(Op,state):
newstate=[]
for i in range(len(Op)): # for each row
# we calculate the corresponding entry of the new state
newstate.append(0) # we set this value to 0 for the initialization
for j in range(len(state)): # for each element in state
newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications
return newstate # return the new probabilistic state
# test the function
# operator for the test
A = [
[0.4,0.6,0],
[0.2,0.1,0.7],
[0.4,0.3,0.3]
]
# state for test
v = [0.1,0.3,0.6]
newstate = evolve(A,v)
print(newstate)
for step in [5,10,20,40]:
new_state = [0.1,0.3,0.6] # initial state
for i in range(step):
new_state = evolve(A,new_state)
print(new_state)
# change the initial state
for step in [5,10,20,40]:
new_state = [1,0,0] # initial state
for i in range(step):
new_state = evolve(A,new_state)
print(new_state)
# for random number generation
from random import randrange
# we will use evolve function
def evolve(Op,state):
newstate=[]
for i in range(len(Op)): # for each row
newstate.append(0)
for j in range(len(state)): # for each element in state
newstate[i] = newstate[i] + Op[i][j] * state[j] # summation of pairwise multiplications
return newstate # return the new probabilistic state
# the initial state
state = [0.5, 0, 0.5, 0]
# probabilistic operator for symbol a
A = [
[0.5, 0, 0, 0],
[0.25, 1, 0, 0],
[0, 0, 1, 0],
[0.25, 0, 0, 1]
]
# probabilistic operator for symbol b
B = [
[1, 0, 0, 0],
[0, 1, 0.25, 0],
[0, 0, 0.5, 0],
[0, 0, 0.25, 1]
]
#
# your solution is here
#
length = 40
total = 50
# total = 1000 # we will also test our code for 1000 strings
# we will check 5 cases
# let's use a list
cases = [0,0,0,0,0]
for i in range(total): # total number of strings
Na = 0
Nb = 0
string = ""
state = [0.5, 0, 0.5, 0]
for j in range(length): # generate random string
if randrange(2) == 0:
Na = Na + 1 # new symbol is a
string = string + "a"
state = evolve(A,state) # update the probabilistic state by A
else:
Nb = Nb + 1 # new symbol is b
string = string + "b"
state = evolve(B,state) # update the probabilistic state by B
# now we have the final state
p0 = state[0] + state[1] # the probabilities of being in 00 and 01
p1 = state[2] + state[3] # the probabilities of being in 10 and 11
#print() # print an empty line
print("(Na-Nb) is",Na-Nb,"and","(p0-p1) is",p0-p1)
# let's check possible different cases
# start with the case in which both are nonzero
# then their multiplication is nonzero
# let's check the sign of their multiplication
if (Na-Nb) * (p0-p1) < 0:
print("they have opposite sign")
cases[0] = cases[0] + 1
elif (Na-Nb) * (p0-p1) > 0:
print("they have the same sign")
cases[1] = cases[1] + 1
# one of them should be zero
elif (Na-Nb) == 0:
if (p0-p1) == 0:
print("both are zero")
cases[2] = cases[2] + 1
else:
print("(Na-Nb) is zero, but (p0-p1) is nonzero")
cases[3] = cases[3] + 1
elif (p0-p1) == 0:
print("(Na-Nb) is nonzero, while (p0-p1) is zero")
cases[4] = cases[4] + 1
# check the case(s) that are observed and the case(s) that are not observed
print() # print an empty line
print(cases)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-3*np.pi,3*np.pi,0.1) # start,stop,step
y = np.sin(x)
yaxis = 0
plt.axes()
plt.plot(x,y,xaxis)
plt.show()
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define a quantum register with one qubit
qreg1 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg1 = ClassicalRegister(1)
# define our quantum circuit
mycircuit1 = QuantumCircuit(qreg1,creg1)
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit1.h(qreg1[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit1.measure(qreg1,creg1)
print("Everything looks fine, let's continue ...")
# draw the circuit by using ASCII art
mycircuit1.draw()
# draw the circuit by using matplotlib
mycircuit1.draw(output='mpl',reverse_bits=True)
# reexecute this cell if you DO NOT see the circuit diagram
# execute the circuit 10000 times in the local simulator
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=10000)
counts1 = job.result().get_counts(mycircuit1)
print(counts1) # print the outcomes
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define a quantum register with one qubit
qreg2 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg2 = ClassicalRegister(1)
# define our quantum circuit
mycircuit2 = QuantumCircuit(qreg2,creg2)
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit2.h(qreg2[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit once more
mycircuit2.h(qreg2[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit2.measure(qreg2,creg2)
print("Everything looks fine, let's continue ...")
# draw the circuit by using matplotlib
mycircuit2.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit 10000 times in the local simulator
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=10000)
counts2 = job.result().get_counts(mycircuit2)
print(counts2)
#
# your solution is here
#
# start with 1 do the same experiment
# define a quantum register with one qubit
qreg1 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg1 = ClassicalRegister(1)
# define our quantum circuit
mycircuit1 = QuantumCircuit(qreg1,creg1)
# reverse the bit
mycircuit1.x(qreg1[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit1.h(qreg1[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit1.measure(qreg1,creg1)
# get the numbers
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=10000)
counts1 = job.result().get_counts(mycircuit1)
print(counts1) # print the outcomes
# draw the circuit by using ASCII art
mycircuit1.draw()
mycircuit1.draw(output='mpl',reverse_bits=True)
# reexecute this cell if you DO NOT see the circuit diagram
# 2nd experiment with the resersed bit
# define a quantum register with one qubit
qreg2 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg2 = ClassicalRegister(1)
# define our quantum circuit
mycircuit2 = QuantumCircuit(qreg2,creg2)
# reverse the bit start with 1
mycircuit2.x(qreg2[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit2.h(qreg2[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit once more
mycircuit2.h(qreg2[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit2.measure(qreg2,creg2)
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=10000)
counts2 = job.result().get_counts(mycircuit2)
print(counts2)
mycircuit2.draw(output='mpl',reverse_bits=True)
# reexecute this cell if you DO NOT see the circuit diagram
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define a quantum register with one qubit
qreg3 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg3 = ClassicalRegister(1)
# define our quantum circuit
mycircuit3 = QuantumCircuit(qreg3,creg3)
# apply x-gate to the first qubit
mycircuit3.x(qreg3[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit3.h(qreg3[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit3.measure(qreg3,creg3)
print("Everything looks fine, let's continue ...")
# draw the circuit by using matplotlib
mycircuit3.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit and read the results
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=10000)
counts3 = job.result().get_counts(mycircuit3)
print(counts3)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# define a quantum register with one qubit
qreg4 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg4 = ClassicalRegister(1)
# define our quantum circuit
mycircuit4 = QuantumCircuit(qreg4,creg4)
# apply x-gate to the first qubit
mycircuit4.x(qreg4[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit twice
mycircuit4.h(qreg4[0])
mycircuit4.h(qreg4[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit4.measure(qreg4,creg4)
print("Everything looks fine, let's continue ...")
# draw the circuit by using matplotlib
mycircuit4.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit and read the results
job = execute(mycircuit4,Aer.get_backend('qasm_simulator'),shots=10000)
counts4 = job.result().get_counts(mycircuit4)
print(counts4)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# your solution is here
#
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# your code is here
# (you may find the values by hand (in mind) as well)
#
import numpy as np
v = np.array([0, -0.1, 0.3, 0.4, 0.5])
v_square = v ** 2
print(v_square)
a = 1 - np.sum(v_square[1:])
a = np.sqrt(a)
print("a: "+ str(a))
u = np.array([1/np.sqrt(2), -1/np.sqrt(3)])
u_square = u ** 2
print(u_square)
b0 = 1/(1 - np.sum(u_square))
print("b: " + str(b0))
#%%writefile FILENAME.py
# for storing the content of this cell,
# comment out the the first line (by modifying the FILENAME)
# and then execute the cell
#
# later, you can execute your saved content by using %run FILENAME.py
#
#
# you may define your first function in a separate cell
# and then save it to a file for using it later
#
from random import randrange
def random_quantum_state():
# quantum state
quantum_state=[0,0]
r = randrange(101)
r = r / 100
r = np.sqrt(r)
if randrange(2) == 0: # randomly make the value negative
r = -1 * r
quantum_state[0] = r
# second entry
quantum_state[1] = np.sqrt(1 - r**2)
return quantum_state
#
# your code is here
#
quantum_state = random_quantum_state()
print(quantum_state)
hadamard_matrix = np.array([[(1/(np.sqrt(2))), (1/(np.sqrt(2)))],[(1/(np.sqrt(2))), (-1/(np.sqrt(2)))]])
new_quantum_state = np.matmul(hadamard_matrix, np.array(quantum_state))
print(new_quantum_state)
def verify_quantum_state(quantum_state):
square_of_state = np.power(quantum_state, 2)
summation = np.sum(square_of_state)
return np.sqrt(summation)
print(verify_quantum_state(quantum_state))
print("should be close to 1: " + str(verify_quantum_state(new_quantum_state)))
results = []
for test in range(100):
quantum_state = random_quantum_state()
sums = verify_quantum_state(quantum_state)
results.append(sums)
summation = np.sum(np.array(sums))
print(summation)
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# vector |v>
print("vector |v>")
values = [-0.1, -0.3, 0.4, 0.5]
total = 0 # summation of squares
for i in range(len(values)):
total += values[i]**2; # add the square of each value
print("total is ",total)
print("the missing part is",1-total)
print("so, the value of 'a' can be",(1-total)**0.5,"or",-(1-total)**0.5) # square root of the missing part
print()
print("vector |u>")
values = [1/(2**0.5), -1/(3**0.5)]
total = 0 # summation of squares
for i in range(len(values)):
total += values[i]**2; # add the square of each value
print("total is ",total)
print("the missing part is",1-total)
# the missing part is 1/b, square of 1/sqrt(b)
# thus, b is 1/missing_part
print("so, the value of 'b' should be",1/(1-total))
#%%writefile randqstate.py
from random import randrange
# randomly creating a 2-dimensional quantum state
def random_quantum_state():
first_entry = randrange(100)
first_entry = first_entry/100
first_entry = first_entry**0.5 # we found the first value before determining its sign
if randrange(2) == 0: # determine the sign
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_entry = second_entry**0.5
if randrange(2) == 0: # determine the sign
second_entry = -1 * second_entry
return [first_entry,second_entry]
# testing whether a given quantum state is valid
def is_quantum_state(quantum_state):
length_square = 0
for i in range(len(quantum_state)):
length_square += quantum_state[i]**2
print("summation of entry squares is",length_square)
# there might be precision problem
# the length may be very close to 1 but not exactly 1
# so we use the following trick
if (length_square - 1)**2 < 0.00000001: return True
return False # else
# defining a function for Hadamard multiplication
def hadamard(quantum_state):
result_quantum_state = [0,0] # define with zero entries
result_quantum_state[0] = (1/(2**0.5)) * quantum_state[0] + (1/(2**0.5)) * quantum_state[1]
result_quantum_state[1] = (1/(2**0.5)) * quantum_state[0] - (1/(2**0.5)) * quantum_state[1]
return result_quantum_state
# we are ready
for i in range(10):
picked_quantum_state=random_quantum_state()
print(picked_quantum_state,"this is randomly picked quantum state")
new_quantum_state = hadamard(picked_quantum_state)
print(new_quantum_state,"this is new quantum state")
print("Is it valid?",is_quantum_state(new_quantum_state))
print() # print an empty line
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
#
# your solution is here
#
# Find expression to create the states
def expression(a, b, c):
return (1/(a**(0.5) - (b + 2 * (c)**(0.5))**(0.5)))
# Construct the quantum state
quantum_state = [expression(3, 5, 6), expression(3, 7, 12), expression(5, 13, 40), expression(7, 15, 26)]
# Verify validity of the quantum state
# Square root of items must add up to 1 (comes from definition of quantum state)
# Each item correspons probability of observing the system in states |00>, |01>, |10>, |11>
print("The probability of observing the states 00, 01, 10, 11:")
prob = 0
for state in quantum_state:
print("probability of current state " + str(state))
prob += state ** 2
print("Verify validity of state - should be approximately 1: " + str(prob) )
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
#
# your code is here
#
# Registers with 5 bits
qreg1 = QuantumRegister(5)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg1 = ClassicalRegister(5)
# define our quantum circuit
mycircuit1 = QuantumCircuit(qreg1,creg1)
# store index of random z gates
z_gate_idx = []
# apply H gate to every bit
for i in range(5):
mycircuit1.h(qreg1[i])
if randrange(2) == 0: # 0.5 chance apply z gate
mycircuit1.z(qreg1[i])
z_gate_idx.append(i)
# apply h gate again
mycircuit1.h(qreg1[i])
# measure the first qubit, and store the result in the first classical bit
mycircuit1.measure(qreg1,creg1)
# get the numbers
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit1)
print(counts) # print the outcomes
print("z gate applied to: " + str(z_gate_idx))
# It can be seen that Z-gate changes value of the q-bit
# draw the circuit
mycircuit1.draw(output='mpl',reverse_bits=True)
# reexecute this cell if you DO NOT see the circuit diagram
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
def square_roots(a,b,c):
# we iteratively calculate the expression with many square roots
# we start with c and continue with b and a
result = c**0.5 # square root of c
result = 2 * result # 2*sqrt(c)
result = result + b # b + 2*sqrt(c)
result = result**0.5 # square root
result = a**0.5 - result
return result
quantum_state =[
square_roots(3,5,6)**(-1),
square_roots(3,7,12)**(-1),
square_roots(5,13,40)**(-1),
square_roots(7,15,56)**(-1),
] # this is our quantum state
# print the quantum state
print(quantum_state)
print()
print("The probability of observing the states 00, 01, 10, 11:")
total_probability = 0
for i in range(len(quantum_state)):
current_probability = quantum_state[i]**2 # square of the amplitude
print(current_probability)
total_probability = total_probability + current_probability
print()
print("total probability is",total_probability)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
number_of_qubit = 5
# define a quantum register with 5 qubits
qreg = QuantumRegister(number_of_qubit)
# define a classical register with 5 bits
creg = ClassicalRegister(number_of_qubit)
# define our quantum circuit
mycircuit = QuantumCircuit(qreg,creg)
# apply h-gate to all qubits
for i in range(number_of_qubit):
mycircuit.h(qreg[i])
# apply z-gate to randomly picked qubits
for i in range(number_of_qubit):
if randrange(2) == 0: # the qubit with index i is picked to apply z-gate
mycircuit.z(qreg[i])
# apply h-gate to all qubits
for i in range(number_of_qubit):
mycircuit.h(qreg[i])
# measure all qubits
mycircuit.measure(qreg,creg)
print("Everything looks fine, let's continue ...")
# draw the circuit
mycircuit.draw()
# execute the circuit 1000 times in the local simulator
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit)
for outcome in counts: # print the reverse of the outcome
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# we use four pairs of two qubits in order to see all results at once
# the first pair -> qubits with indices 0 and 1
# the second pair -> qubits with indices 2 and 3
# the third pair -> qubits with indices 4 and 5
# the fourth pair -> qubits with indices 6 and 7
qreg = QuantumRegister(8)
creg = ClassicalRegister(8)
mycircuit = QuantumCircuit(qreg,creg)
# the first pair is already in |00>
# the second pair is set to be in |01>
mycircuit.x(qreg[3])
# the third pair is set to be in |10>
mycircuit.x(qreg[4])
# the fourth pair is set to be in |11>
mycircuit.x(qreg[6])
mycircuit.x(qreg[7])
# apply cx to each pair
for i in range(0,8,2): # i = 0,2,4,6
mycircuit.cx(qreg[i],qreg[i+1])
# measure the quantum register
mycircuit.measure(qreg,creg)
print("Everything looks fine, let's continue ...")
# draw the circuit
mycircuit.draw()
# execute the circuit 1000 times in the local simulator
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit)
# print the reverse of the output
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
print()
print("let's also split into the pairs")
for i in range(0,8,2):
print(reverse_outcome[i:i+2])
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
#
# your code is here
#
qreg = QuantumRegister(5)
creg = ClassicalRegister(5)
mycircuit = QuantumCircuit(qreg,creg)
# set each q-bit to 1
for i in range(5):
mycircuit.x(qreg[i])
# Randomly pick pair of q-bits
r0 = randrange(5)
r1 = randrange(5)
while(r0 == r1 or r0+1 == r1 or r0+1 == r1 + 1 or r1+1 == r0):
r0 = randrange(5)
r1 = randrange(5)
# apply cx to selected pairs
for i in range(0,5):
if i == r0 or i == r1:
mycircuit.cx(qreg[i],qreg[i+1])
# measure the quantum register
mycircuit.measure(qreg,creg)
# draw the circuit
mycircuit.draw(output='mpl')
# execute the circuit 1000 times in the local simulator
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit)
# print the reverse of the output
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
print()
print("let's also split into the pairs")
for i in range(0,8,2):
print(reverse_outcome[i:i+2])
print("randomly selected pairs: " + str(r0) + " " + str(r1))
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#
# your code is here
#
# program has 8 q-bits
qreg = QuantumRegister(8)
creg = ClassicalRegister(8)
mycircuit3 = QuantumCircuit(qreg,creg)
# Iteratively initialize q-bits as followa
# the first pair is set to be in |00>
# the second pair is set to be in |01>
mycircuit3.x(qreg[3])
# the third pair is set to be in |10>
mycircuit3.x(qreg[4])
# the third pair is set to be in |11>
mycircuit3.x(qreg[6])
mycircuit3.x(qreg[7])
# apply Hadamard to each pair
# apply cNot to every q-bit
# apply Hadamard to each pair
for i in range(8):
mycircuit3.h(qreg[i])
for i in range(0,8,2): # i = 0,2,4,6
mycircuit3.cx(qreg[i],qreg[i+1])
for i in range(8):
mycircuit3.h(qreg[i])
# measure the quantum register
mycircuit3.measure(qreg,creg)
# draw the circuit
mycircuit3.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit 1000 times in the local simulator
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit3)
# print the reverse of the output
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
print()
print("let's also split into the pairs")
for i in range(0,8,2):
print(reverse_outcome[i:i+2])
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#
# your code is here
#
# program has 8 q-bits
qreg = QuantumRegister(8)
creg = ClassicalRegister(8)
mycircuit4 = QuantumCircuit(qreg,creg)
# Iteratively initialize q-bits as followa
# the first pair is set to be in |00>
# the second pair is set to be in |01>
mycircuit4.x(qreg[3])
# the third pair is set to be in |10>
mycircuit4.x(qreg[4])
# the third pair is set to be in |11>
mycircuit4.x(qreg[6])
mycircuit4.x(qreg[7])
# Apply C-NOT gates to pairs 3 times
# with different order
for i in range(0,8,2): # i = 0,2,4,6
# first q-bit first
mycircuit4.cx(qreg[i],qreg[i+1])
# second q-bit first
mycircuit4.cx(qreg[i+1],qreg[i])
# first q-bit first
mycircuit4.cx(qreg[i],qreg[i+1])
# measure the quantum register
mycircuit4.measure(qreg,creg)
# draw the circuit
mycircuit4.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit 1000 times in the local simulator
job = execute(mycircuit4,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit4)
# print the reverse of the output
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
print()
print("let's also split into the pairs")
for i in range(0,8,2):
print(reverse_outcome[i:i+2])
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
n = 5
m = 4
states_of_qubits = [] # we trace the state of each qubit also by ourselves
qreg1 = QuantumRegister(n) # quantum register with n qubits
creg1 = ClassicalRegister(n) # classical register with n bits
mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers
# set each qubit to |1>
for i in range(n):
mycircuit1.x(qreg1[i]) # apply x-gate (NOT operator)
states_of_qubits.append(1) # the state of each qubit is set to 1
# randomly pick m pairs of qubits
for i in range(m):
controller_qubit = randrange(n)
target_qubit = randrange(n)
# controller and target qubits should be different
while controller_qubit == target_qubit: # if they are the same, we pick the target_qubit again
target_qubit = randrange(n)
# print our picked qubits
print("the indices of the controller and target qubits are",controller_qubit,target_qubit)
# apply cx-gate (CNOT operator)
mycircuit1.cx(qreg1[controller_qubit],qreg1[target_qubit])
# we also trace the results
if states_of_qubits[controller_qubit] == 1: # if the value of the controller qubit is 1,
states_of_qubits[target_qubit] = 1 - states_of_qubits[target_qubit] # then flips the value of the target qubit
# remark that 1-x gives the negation of x
# measure the quantum register
mycircuit1.measure(qreg1,creg1)
print("Everything looks fine, let's continue ...")
# draw the circuit
mycircuit1.draw(output='mpl')
# re-execute this cell if you DO NOT see the circuit diagram
# execute the circuit 100 times in the local simulator
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit1)
# print the reverse of the outcome
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
# the states of the qubits should be as follows based on our own calculation
print(states_of_qubits)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
qreg2 = QuantumRegister(2) # quantum register with 2 qubits
creg2 = ClassicalRegister(2) # classical register with 2 bits
mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers
#initialize the inputs
if input[0]=='1':
mycircuit2.x(qreg2[0]) # set the state of the first qubit to |1>
if input[1]=='1':
mycircuit2.x(qreg2[1]) # set the state of the second qubit to |1>
# apply h-gate to both qubits
mycircuit2.h(qreg2[0])
mycircuit2.h(qreg2[1])
# apply cx(first-qubit,second-qubit)
mycircuit2.cx(qreg2[0],qreg2[1])
# apply h-gate to both qubits
mycircuit2.h(qreg2[0])
mycircuit2.h(qreg2[1])
# measure both qubits
mycircuit2.measure(qreg2,creg2)
# execute the circuit 100 times in the local simulator
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit2)
for outcome in counts: # print the reverse of the outcomes
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("our input is",input,": ",reverse_outcome,"is observed",counts[outcome],"times")
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
qreg3 = QuantumRegister(2) # quantum register with 2 qubits
creg3 = ClassicalRegister(2) # classical register with 2 bits
mycircuit3 = QuantumCircuit(qreg3,creg3) # quantum circuit with quantum and classical registers
#initialize the inputs
if input[0]=='1':
mycircuit3.x(qreg3[0]) # set the value of the first qubit to |1>
if input[1]=='1':
mycircuit3.x(qreg3[1]) # set the value of the second qubit to |1>
# apply cx(first-qubit,second-qubit)
mycircuit3.cx(qreg3[0],qreg3[1])
# apply cx(second-qubit,first-qubit)
mycircuit3.cx(qreg3[1],qreg3[0])
# apply cx(first-qubit,second-qubit)
mycircuit3.cx(qreg3[0],qreg3[1])
mycircuit3.measure(qreg3,creg3)
# execute the circuit 100 times in the local simulator
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit3)
for outcome in counts: # print the reverse of the outcomes
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("our input is",input,": ",reverse_outcome,"is observed",counts[outcome],"times")
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_pairs = ['00','01','10','11']
for pair in all_pairs:
# create a quantum curcuit with two qubits: Asja's and Balvis' qubits.
# both are initially set to |0>.
qreg = QuantumRegister(2) # quantum register with 2 qubits
creg = ClassicalRegister(2) # classical register with 2 bits
mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers
# apply h-gate (Hadamard) to the first qubit.
mycircuit.h(qreg[0])
# apply cx-gate (CNOT) with parameters first-qubit and second-qubit.
mycircuit.cx(qreg[0],qreg[1])
# they are separated now.
# if a is 1, then apply z-gate to the first qubit.
if pair[0]=='1':
mycircuit.z(qreg[0])
# if b is 1, then apply x-gate (NOT) to the first qubit.
if pair[1]=='1':
mycircuit.x(qreg[0])
# Asja sends her qubit to Balvis.
# apply cx-gate (CNOT) with parameters first-qubit and second-qubit.
mycircuit.cx(qreg[0],qreg[1])
# apply h-gate (Hadamard) to the first qubit.
mycircuit.h(qreg[0])
# measure both qubits
mycircuit.measure(qreg,creg)
# compare the results with pair (a,b)
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit)
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("(a,b) is",pair,": ",reverse_outcome,"is observed",counts[outcome],"times")
# draw the circuit
mycircuit.draw(output='mpl',reverse_bits=True)
# reexecute me if you DO NOT see the circuit diagram
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_pairs = ['00','01','10','11']
for pair in all_pairs:
# create a quantum curcuit with two qubits: Asja's and Balvis' qubits.
# both are initially set to |0>.
qreg = QuantumRegister(2) # quantum register with 2 qubits
creg = ClassicalRegister(2) # classical register with 2 bits
mycircuit = QuantumCircuit(qreg,creg) # quantum circuit with quantum and classical registers
# apply h-gate (Hadamard) to the first qubit.
mycircuit.h(qreg[0])
# apply cx-gate (CNOT) with parameters first-qubit and second-qubit.
mycircuit.cx(qreg[0],qreg[1])
# they are separated now.
# if a is 1, then apply z-gate to the first qubit.
if pair[0]=='1':
mycircuit.z(qreg[0])
# if b is 1, then apply x-gate (NOT) to the first qubit.
if pair[1]=='1':
mycircuit.x(qreg[0])
# Asja sends her qubit to Balvis.
# apply cx-gate (CNOT) with parameters first-qubit and second-qubit.
mycircuit.cx(qreg[0],qreg[1])
# apply h-gate (Hadamard) to the first qubit.
mycircuit.h(qreg[0])
# measure both qubits
mycircuit.measure(qreg,creg)
# compare the results with pair (a,b)
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit)
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("(a,b) is",pair,": ",reverse_outcome,"is observed",counts[outcome],"times")
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import the drawing methods
from matplotlib.pyplot import plot, figure
# draw a figure
figure(figsize=(6,6), dpi=60)
# draw the origin
plot(0,0,'ro') # a point in red color
# draw the quantum states as points (in blue color)
plot(1,0,'bo')
plot(0,1,'bo')
plot(-1,0,'bo')
plot(0,-1,'bo')
# import the drawing methods
from matplotlib.pyplot import plot, figure
# draw a figure
figure(figsize=(6,6), dpi=80)
# include our predefined functions
%run qlatvia.py
# draw the axes
draw_axes()
# draw the origin
plot(0,0,'ro') # a point in red color
# draw these quantum states as points (in blue color)
plot(1,0,'bo')
plot(0,1,'bo')
plot(-1,0,'bo')
plot(0,-1,'bo')
# import the drawing methods
from matplotlib.pyplot import figure, arrow
# draw a figure
figure(figsize=(6,6), dpi=80)
# include our predefined functions
%run qlatvia.py
# draw the axes
draw_axes()
# draw the quantum states as vectors (in blue color)
arrow(0,0,0.92,0,head_width=0.04, head_length=0.08, color="blue")
arrow(0,0,0,0.92,head_width=0.04, head_length=0.08, color="blue")
arrow(0,0,-0.92,0,head_width=0.04, head_length=0.08, color="blue")
arrow(0,0,0,-0.92,head_width=0.04, head_length=0.08, color="blue")
# import the drawing methods
from matplotlib.pyplot import plot, figure
# draw a figure
figure(figsize=(6,6), dpi=60)
# draw the origin
plot(0,0,'ro')
# draw the axes
draw_axes()
#
# your solution is here
#
# include our predefined functions
%run qlatvia.py
for i in range(100):
quantum_state = random_quantum_state()
x = quantum_state[0];
y = quantum_state[1];
plot(x,y,'bo')
# import the drawing methods
from matplotlib.pyplot import plot, figure, arrow
# draw a figure
figure(figsize=(6,6), dpi=60)
# include our predefined functions
%run qlatvia.py
# draw the axes
draw_axes()
# draw the origin
plot(0,0,'ro')
#
# your solution is here
#
for i in range(100):
quantum_state = random_quantum_state()
x = quantum_state[0];
y = quantum_state[1];
arrow(0,0,x,y,head_width=0.04,head_length=0.08,color="red")
# import the drawing methods
from matplotlib.pyplot import figure
figure(figsize=(6,6), dpi=80) # size of the figure
# include our predefined functions
%run qlatvia.py
# draw axes
draw_axes()
# draw the unit circle
draw_unit_circle()
# import the drawing methods
from matplotlib.pyplot import figure, text
figure(figsize=(6,6), dpi=80) # size of the figure
# include our predefined functions
%run qlatvia.py
# draw axes
draw_axes()
# randomly determine the points
from random import randrange
for i in range(5):
x = randrange(-100,101)/100
y = randrange(-100,101)/100
string = str(i+1)+". point at ("+str(x)+","+str(y)+")"
print(string)
text(x,y,string)
# %%writefile FILENAME.py
# import the drawing methods
from matplotlib.pyplot import figure, arrow, text
def display_quantum_state(x,y,name):
# draw axes
draw_axes()
# draw the unit circle
draw_unit_circle()
# get the random quantum state
quantum_state = random_quantum_state()
x = quantum_state[0];
y = quantum_state[1];
arrow(0,0,x * 0.90,y * 0.90,head_width=0.04,head_length=0.1,color="red")
# display the name out of unit circle
text(x + 0.1,y + 0.1,name,fontsize=15)
#
# test your function
#
# import the drawing methods
from matplotlib.pyplot import figure
figure(figsize=(6,6), dpi=80) # size of the figure
# include our predefined functions
%run qlatvia.py
# draw axes
draw_axes()
# draw the unit circle
draw_unit_circle()
for i in range(6):
s = random_quantum_state()
display_quantum_state(s[0],s[1],"v"+str(i))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# randomly create a 2-dimensional quantum state
from random import randrange
def random_quantum_state():
first_entry = randrange(101)
first_entry = first_entry/100
first_entry = first_entry**0.5
if randrange(2) == 0:
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_entry = second_entry**0.5
if randrange(2) == 0:
second_entry = -1 * second_entry
return [first_entry,second_entry]
# import the drawing methods
from matplotlib.pyplot import plot, figure
# draw a figure
figure(figsize=(6,6), dpi=60)
# draw the origin
plot(0,0,'ro')
for i in range(100):
# create a random quantum state
quantum_state = random_quantum_state();
# draw a blue point for the random quantum state
x = quantum_state[0];
y = quantum_state[1];
plot(x,y,'bo')
# randomly create a 2-dimensional quantum state
from random import randrange
def random_quantum_state():
first_entry = randrange(101)
first_entry = first_entry/100
first_entry = first_entry**0.5
if randrange(2) == 0:
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_entry = second_entry**0.5
if randrange(2) == 0:
second_entry = -1 * second_entry
return [first_entry,second_entry]
# import the drawing methods
from matplotlib.pyplot import plot, figure, arrow
%run qlatvia.py
# draw a figure
figure(figsize=(6,6), dpi=60)
draw_axes();
# draw the origin
plot(0,0,'ro')
for i in range(100):
# create a random quantum state
quantum_state = random_quantum_state();
# draw a blue vector for the random quantum state
x = quantum_state[0];
y = quantum_state[1];
# shorten the line length to 0.92
# line_length + head_length (0.08) should be 1
x = 0.92 * x
y = 0.92 * y
arrow(0,0,x,y,head_width=0.04,head_length=0.08,color="blue")
# %%writefile FILENAME.py
# import the drawing methods
from matplotlib.pyplot import figure, arrow, text
def display_quantum_state(x,y,name):
x1 = 0.92 * x
y1 = 0.92 * y
arrow(0,0,x1,y1,head_width=0.04,head_length=0.08,color="blue")
x2 = 1.15 * x
y2 = 1.15 * y
text(x2,y2,name)
#
# test your function
#
# import the drawing methods
from matplotlib.pyplot import figure
figure(figsize=(6,6), dpi=80) # size of the figure
# include our predefined functions
%run qlatvia.py
# draw axes
draw_axes()
# draw the unit circle
draw_unit_circle()
for i in range(6):
s = random_quantum_state()
display_quantum_state(s[0],s[1],"v"+str(i))
#draw_quantum_state(s[0],s[1],"v"+str(i))
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
%run qlatvia.py
draw_qubit()
draw_quantum_state(3/5,4/5,"|v>")
%run qlatvia.py
draw_qubit()
draw_quantum_state(3/5,4/5,"|v>")
from matplotlib.pyplot import arrow, text, gca
# the projection on |0>-axis
arrow(0,0,3/5,0,color="blue",linewidth=1.5)
arrow(0,4/5,3/5,0,color="blue",linestyle='dotted')
text(0.1,-0.1,"cos(a)=3/5")
# the projection on |1>-axis
arrow(0,0,0,4/5,color="blue",linewidth=1.5)
arrow(3/5,0,0,4/5,color="blue",linestyle='dotted')
text(-0.1,0.55,"sin(a)=4/5",rotation="90")
# drawing the angle with |0>-axis
from matplotlib.patches import Arc
gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=53) )
text(0.08,0.05,'.',fontsize=30)
text(0.21,0.09,'a')
%run qlatvia.py
draw_qubit()
from math import acos, pi
#
# your solution is here
#
quantum_state = random_quantum_state()
# obtain the degree with x-axis
radian = acos(quantum_state[0])
# convert radians to degree
angle = 360 * radian/(2*pi)
print("angle: " + str(angle) + " degrees")
# verify by visualizing the quantum state
draw_quantum_state(quantum_state[0],quantum_state[1],"s0")
%run qlatvia.py
draw_qubit()
draw_quantum_state(3/5,4/5,"|v1>")
draw_quantum_state(3/5,-4/5,"|v2>")
from matplotlib.pyplot import arrow, text, gca
# the projection on |0>-axis
arrow(0,0,3/5,0,color="blue",linewidth=1.5)
arrow(0,0,3/5,0,color="blue",linewidth=1.5)
arrow(0,4/5,3/5,0,color="blue",linestyle='dotted')
arrow(0,-4/5,3/5,0,color="blue",linestyle='dotted')
text(0.36,0.05,"cos(a)=3/5")
text(0.36,-0.09,"cos($-$a)=3/5")
# the projection on |1>-axis
arrow(0,0,0,4/5,color="blue",linewidth=1.5)
arrow(0,0,0,-4/5,color="blue",linewidth=1.5)
arrow(3/5,0,0,4/5,color="blue",linestyle='dotted')
arrow(3/5,0,0,-4/5,color="blue",linestyle='dotted')
text(-0.1,0.55,"sin(a)=4/5",rotation="90")
text(-0.14,-0.2,"sin($-$a)=$-$4/5",rotation="270")
# drawing the angle with |0>-axis
from matplotlib.patches import Arc
gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=0,theta2=53) )
text(0.08,0.05,'.',fontsize=30)
text(0.21,0.09,'a')
gca().add_patch( Arc((0,0),0.4,0.4,angle=0,theta1=-53,theta2=0) )
text(0.08,-0.07,'.',fontsize=30)
text(0.19,-0.12,'$-$a')
# set the angle
from random import randrange
myangle = randrange(361)
################################################
from matplotlib.pyplot import figure,gca
from matplotlib.patches import Arc
from math import sin,cos,pi
# draw a figure
figure(figsize=(6,6), dpi=60)
%run qlatvia.py
draw_axes()
print("the selected angle is",myangle,"degrees")
ratio_of_arc = ((1000*myangle/360)//1)/1000
print("it is",ratio_of_arc,"of a full circle")
print("its length is",ratio_of_arc,"x 2\u03C0","=",ratio_of_arc*2*pi)
myangle_in_radian = 2*pi*(myangle/360)
print("its radian value is",myangle_in_radian)
gca().add_patch( Arc((0,0),0.2,0.2,angle=0,theta1=0,theta2=myangle,color="red") )
gca().add_patch( Arc((0,0),2,2,angle=0,theta1=0,theta2=myangle,color="blue") )
x = cos(myangle_in_radian)
y = sin(myangle_in_radian)
draw_quantum_state(x,y,"|v>")
%run qlatvia.py
draw_qubit()
from math import acos, pi
#
# your solution is here
#
# get the random quantum state
quantum_state = random_quantum_state()
x, y = quantum_state[0], quantum_state[1]
# obtain the degree with x-axis
radian = acos(x)
# convert radians to degree
angle = 360 * radian/(2*pi)
print("the selected angle is",angle,"degrees")
ratio_of_arc = ((1000*myangle/360)//1)/1000
print("it is",ratio_of_arc,"of a full circle")
print("its length is",ratio_of_arc,"x 2\u03C0","=",ratio_of_arc*2*pi)
angle_in_radian = 2*pi*(angle/360)
print("its radian value is",angle_in_radian)
gca().add_patch( Arc((0,0),0.2,0.2,angle=0,theta1=0,theta2=angle,color="red") )
gca().add_patch( Arc((0,0),2,2,angle=0,theta1=0,theta2=angle,color="blue") )
x = cos(angle_in_radian)
y = sin(angle_in_radian)
# draw the axes
draw_axes()
draw_quantum_state(x,y,"|u>")
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# randomly create a 2-dimensional quantum state
from random import randrange
def random_quantum_state():
first_entry = randrange(101)
first_entry = first_entry/100
first_entry = first_entry**0.5
if randrange(2) == 0:
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_entry = second_entry**0.5
if randrange(2) == 0:
second_entry = -1 * second_entry
return [first_entry,second_entry]
%run qlatvia.py
draw_qubit()
from math import acos, pi
# randomly picking 6 quantum states
for i in range(6):
[x,y]=random_quantum_state() # picking a quantum state
angle_radian = acos(x) # radian of the angle with state |0>
angle_degree = 360*angle_radian/(2*pi) # degree of the angle with state |0>
state_name='|v'+str(i)+'>' # giving a name to the quantum state
draw_quantum_state(x,y,state_name) # drawing the quantum state
print(state_name,'has degree of',angle_degree,"with state |0>") # print the degree of angle with state |0>
# randomly create a 2-dimensional quantum state
from random import randrange
def random_quantum_state():
first_entry = randrange(101)
first_entry = first_entry/100
first_entry = first_entry**0.5
if randrange(2) == 0:
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_entry = second_entry**0.5
if randrange(2) == 0:
second_entry = -1 * second_entry
return [first_entry,second_entry]
# finding the angle of a 2-dimensional quantum state
from math import acos, pi
def angle_quantum_state(x,y):
angle_radian = acos(x) # radian of the angle with state |0>
angle_degree = 360*angle_radian/(2*pi) # degree of the angle with state |0>
# if the second amplitude is negative,
# then angle is (-angle_degree)
# or equivalently 360 + (-angle_degree)
if y<0: angle_degree = 360-angle_degree # degree of the angle
# else degree of the angle is the same as degree of the angle with state |0>
return angle_degree
%run qlatvia.py
draw_qubit()
from math import acos, pi
# randomly picking 6 quantum states
for i in range(4):
[x,y]=random_quantum_state() # picking a quantum state
angle_degree = angle_quantum_state(x,y)
state_name='|v'+str(i)+'>' # giving a name to the quantum state
draw_quantum_state(x,y,state_name) # drawing the quantum state
print(state_name,'has degree of',angle_degree) # print the degree of angle
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# %%writefile FILENAME.py
# your function is here
from math import cos, sin, pi
from random import randrange
def random_quantum_state2():
#
# your codes are here
#
# randomly create quantum states
angle_random = randrange(361)
# get the angles cos, sin
angle_random_radian = (2 * pi * angle_random)/(360)
return [cos(angle_random_radian), sin(angle_random_radian)]
# visually test your function
%run qlatvia.py
draw_qubit()
#
# your solution is here
#
for i in range(100):
[x, y] = random_quantum_state2()
draw_quantum_state(x,y,"")
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# randomly create a 2-dimensional quantum state
from math import cos, sin, pi
from random import randrange
def random_quantum_state2():
angle_degree = randrange(360)
angle_radian = 2*pi*angle/360
return [cos(angle_radian),sin(angle_radian)]
# include our predefined functions
%run qlatvia.py
# draw the axes
draw_qubit()
for i in range(6):
[x,y]=random_quantum_state2()
draw_quantum_state(x,y,"|v"+str(i)+">")
# include our predefined functions
%run qlatvia.py
# draw the axes
draw_qubit()
for i in range(100):
[x,y]=random_quantum_state2()
draw_quantum_state(x,y,"")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.