repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Size pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import Size
from qiskit.test import QiskitTestCase
class TestSizePass(QiskitTestCase):
"""Tests for Depth analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 size"""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = Size()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["size"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
dag = circuit_to_dag(circuit)
pass_ = Size()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["size"], 8)
def test_depth_one(self):
"""A dag with operations in parallel and size 2"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
dag = circuit_to_dag(circuit)
pass_ = Size()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["size"], 2)
def test_size_control_flow(self):
"""A DAG with control flow still gives an estimate."""
qc = QuantumCircuit(5, 1)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)) as else_:
qc.x(1)
qc.cx(2, 3)
with else_:
qc.x(1)
with qc.for_loop(range(3)):
qc.z(2)
with qc.for_loop((4, 0, 1)):
qc.z(2)
with qc.while_loop((qc.clbits[0], True)):
qc.h(0)
qc.measure(0, 0)
pass_ = Size(recurse=True)
pass_(qc)
self.assertEqual(pass_.property_set["size"], 19)
if __name__ == "__main__":
unittest.main()
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.quantum_info import Operator
from qiskit.tools.monitor import job_monitor
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from matplotlib import rcParams
rcParams['text.usetex'] = True
#Useful tool for converting an integer to a binary bit string
def get_bin(x, n=0):
"""
Get the binary representation of x.
Parameters: x (int), n (int, number of digits)"""
return format(x, 'b').zfill(n)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/ashishpatel26/IBM-Quantum-Challenge-Africa-2021
|
ashishpatel26
|
from qiskit import *
from qiskit.visualization import plot_histogram
import numpy as np
def NOT(inp):
"""An NOT gate.
Parameters:
inp (str): Input, encoded in qubit 0.
Returns:
QuantumCircuit: Output NOT circuit.
str: Output value measured from qubit 0.
"""
qc = QuantumCircuit(1, 1) # A quantum circuit with a single qubit and a single classical bit
qc.reset(0)
# We encode '0' as the qubit state |0⟩, and '1' as |1⟩
# Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'
# For an input of '1', we do an x to rotate the |0⟩ to |1⟩
if inp=='1':
qc.x(0)
# barrier between input state and gate operation
qc.barrier()
# Now we've encoded the input, we can do a NOT on it using x
qc.x(0)
#barrier between gate operation and measurement
qc.barrier()
# Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]
qc.measure(0,0)
qc.draw()
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp in ['0', '1']:
qc, out = NOT(inp)
print('NOT with input',inp,'gives output',out)
display(qc.draw())
print('\n')
def XOR(inp1,inp2):
"""An XOR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 1.
"""
qc = QuantumCircuit(2, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
# barrier between input state and gate operation
qc.barrier()
# this is where your program for quantum XOR gate goes
qc.cx(0, 1)
# barrier between input state and gate operation
qc.barrier()
qc.measure(1,0) # output from qubit 1 is measured
#We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
#Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = XOR(inp1, inp2)
print('XOR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def AND(inp1,inp2):
"""An AND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum AND gate goes
qc.ccx(0,1,2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = AND(inp1, inp2)
print('AND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def NAND(inp1,inp2):
"""An NAND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output NAND circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum NAND gate goes
qc.ccx(0,1,2)
if inp=='1':
qc.x(2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = NAND(inp1, inp2)
print('NAND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def OR(inp1,inp2):
"""An OR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum OR gate goes
qc.cx(0, 2)
qc.cx(1, 2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = OR(inp1, inp2)
print('OR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
from qiskit import IBMQ
#IBMQ.save_account("a68a35747d4eccd1d58f275e637909987c789ce5c0edd8a4f43014672bf0301b54b28b1b5f44ba8ff87500777429e1e4ceb79621a6ba248d6cca6bca0e233d23", overwrite=True)
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider('ibm-q')
provider.backends()
import qiskit.tools.jupyter
# run this cell
backend = provider.get_backend('ibmq_quito')
qc_and = QuantumCircuit(3)
qc_and.ccx(0,1,2)
print('AND gate')
display(qc_and.draw())
print('\n\nTranspiled AND gate with all the required connectivity')
qc_and.decompose().draw()
from qiskit.tools.monitor import job_monitor
# run the cell to define AND gate for real quantum system
def AND(inp1, inp2, backend, layout):
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
qc.ccx(0, 1, 2)
qc.barrier()
qc.measure(2, 0)
qc_trans = transpile(qc, backend, initial_layout=layout, optimization_level=3)
job = backend.run(qc_trans, shots=8192)
print(job.job_id())
job_monitor(job)
output = job.result().get_counts()
return qc_trans, output
backend
layout = [0, 1, 2]
output_all = []
qc_trans_all = []
prob_all = []
worst = 1
best = 0
for input1 in ['0','1']:
for input2 in ['0','1']:
qc_trans, output = AND(input1, input2, backend, layout)
output_all.append(output)
qc_trans_all.append(qc_trans)
prob = output[str(int( input1=='1' and input2=='1' ))]/8192
prob_all.append(prob)
print('\nProbability of correct answer for inputs',input1,input2)
print('{:.2f}'.format(prob) )
print('---------------------------------')
worst = min(worst,prob)
best = max(best, prob)
print('')
print('\nThe highest of these probabilities was {:.2f}'.format(best))
print('The lowest of these probabilities was {:.2f}'.format(worst))
print('Transpiled AND gate circuit for ibmq_vigo with input 0 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[0].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[0].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[0]) )
qc_trans_all[0].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 0 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[1].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[1].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[1]) )
qc_trans_all[1].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[2].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[2].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[2]) )
qc_trans_all[2].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[3].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[3].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[3]) )
qc_trans_all[3].draw()
|
https://github.com/nmoran/qiskit-qdrift-quid19
|
nmoran
|
import numpy as np
import matplotlib.pyplot as plt
import math
from qiskit import Aer, IBMQ, QuantumRegister, QuantumCircuit
from qiskit.providers.ibmq import least_busy
from qiskit.providers.aer import noise
# lib from Qiskit Aqua
from qiskit.aqua.operators.common import evolution_instruction
from qiskit.aqua import Operator, QuantumInstance
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import COBYLA, SPSA, L_BFGS_B
from qiskit.aqua.components.variational_forms import RY, RYRZ, SwapRZ
# lib from Qiskit Aqua Chemistry
from qiskit.chemistry import QiskitChemistry
from qiskit.chemistry import FermionicOperator
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry.aqua_extensions.components.variational_forms import UCCSD
from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock
driver = PySCFDriver(atom='H .0 .0 .0; Li .0 .0 1.6', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
nuclear_repulsion_energy = molecule.nuclear_repulsion_energy
num_particles = molecule.num_alpha + molecule.num_beta
num_spin_orbitals = molecule.num_orbitals * 2
print('HF Done')
h1 = molecule.one_body_integrals
h2 = molecule.two_body_integrals
ferOp = FermionicOperator(h1=h1, h2=h2)
qubitOp = ferOp.mapping(map_type='jordan_wigner', threshold=10**-10)
qubitOp.chop(10**-10)
num_terms = len(qubitOp.paulis)
max_term = max([np.abs(qubitOp.paulis[i][0]) for i in range(num_terms)])
error=.01
norm = 0
probs = []
for i in range(len(qubitOp.paulis)):
norm += np.abs(qubitOp.paulis[i][0])
for i in range(len(qubitOp.paulis)):
probs.append(np.abs(qubitOp.paulis[i][0])/norm)
runs = 10
print('start of big loop')
times = np.linspace(.05,.1,10)
qdrift_av_counts=[]
trotter_counts=[]
#iterate through the list of durations
for time_idx in range(len(times)):
qdrift_gate_counts = []
num_time_slices = math.ceil((num_terms*max_term*times[time_idx])**2 / 2*error)
#Iterate (runs) numbers of time to get average data
for run in range(runs):
random_pauli_list=[]
#the number of steps from the norm, time, and error
num_steps = math.ceil((2*norm*times[time_idx])**2 /error)
standard_timestep = times[time_idx]*norm/num_steps
for i in range(num_steps):
idx = np.random.choice(num_terms,p=probs)
#form the list keeping track of the sign of the coefficients
random_pauli_list.append([np.sign(qubitOp.paulis[idx][0])*standard_timestep,qubitOp.paulis[idx][1]])
instruction_qdrift=evolution_instruction(random_pauli_list, evo_time=1, num_time_slices=1, controlled=False, power=1, use_basis_gates=True, shallow_slicing=False)
print('completed {} qdrift evolution_instructions'.format(str(time_idx)))
quantum_registers_qdrift = QuantumRegister(qubitOp.num_qubits)
qc_qdrift = QuantumCircuit(quantum_registers_qdrift)
qc_qdrift.append(instruction_qdrift, quantum_registers_qdrift)
qc_qdrift = qc_qdrift.decompose()
total_qdrift = 0
try:
total_qdrift+=qc_qdrift.count_ops()['cx']
except:
pass
try:
total_qdrift+=qc_qdrift.count_ops()['u1']
except:
pass
try:
total_qdrift+=qc_qdrift.count_ops()['u2']
except:
pass
try:
total_qdrift+=qc_qdrift.count_ops()['u3']
except:
pass
qdrift_gate_counts.append(total_qdrift)
print('start of trotter evolution instruction')
instruction_trotter=evolution_instruction(qubitOp.paulis, evo_time=times[time_idx], num_time_slices=num_time_slices, controlled=False, power=1, use_basis_gates=True, shallow_slicing=False)
print('end of trotter evolution instruction - on to circuit construction')
quantum_registers_trotter = QuantumRegister(qubitOp.num_qubits)
qc_trotter = QuantumCircuit(quantum_registers_trotter)
qc_trotter.append(instruction_trotter, quantum_registers_trotter)
qc_trotter = qc_trotter.decompose()
total_trotter = 0
try:
total_trotter+=qc_trotter.count_ops()['cx']
except:
pass
try:
total_trotter+=qc_trotter.count_ops()['u1']
except:
pass
try:
total_trotter+=qc_trotter.count_ops()['u2']
except:
pass
try:
total_trotter+=qc_trotter.count_ops()['u3']
except:
pass
trotter_counts.append(total_trotter)
qdrift_av_counts.append(sum(qdrift_gate_counts)/len(qdrift_gate_counts))
print('got through {} iterations'.format(str(time_idx)))
plt.plot(times,qdrift_av_counts,label='qdrift_avg_counts')
plt.plot(times,trotter_counts,label = 'trotter_counts')
plt.title('Gates vs Error for Time Evolution')
plt.xlabel("Duration of evolution")
plt.ylabel("Number of Gates")
plt.legend(loc=0)
plt.savefig("LiH_gates_v_time.png", dpi=600)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining Qiskit OpenQASM conversions
"""
import qiskit
from qiskit.qasm2 import dumps as qasm2_dumps
from qbraid.transpiler.annotations import weight
@weight(1)
def qiskit_to_qasm2(circuit: qiskit.QuantumCircuit) -> str:
"""Returns OpenQASM 2 string equivalent to the input Qiskit circuit.
Args:
circuit: Qiskit circuit to convert to OpenQASM 2 string.
Returns:
str: OpenQASM 2 representation of the input Qiskit circuit.
"""
return qasm2_dumps(circuit)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
import sys, getpass
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError
from qiskit import available_backends, execute, register, get_backend
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.qi.qi import state_fidelity
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.u2(pi/2,pi/2,q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.u1(pi/2,q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.u0(pi/2,q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.iden(q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.x(q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.y(q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.z(q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.h(q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.s(q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.sdg(q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.t(q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.tdg(q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.rx(pi/2,q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.ry(pi/2,q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.rz(pi/2,q)
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.cy(q[0],q[1])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.cz(q[0],q[1])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.ch(q[0],q[1])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary']/(0.707+0.707j), 3)
qc = QuantumCircuit(q)
qc.crz(pi/2,q[0],q[1])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.cu1(pi/2,q[0], q[1])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.cu3(pi/2, pi/2, pi/2, q[0], q[1])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.swap(q[0], q[1])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0], q[1], q[2])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
qc = QuantumCircuit(q)
qc.cswap(q[0], q[1], q[2])
circuit_drawer(qc)
job = execute(qc, backend='local_unitary_simulator')
np.round(job.result().get_data(qc)['unitary'], 3)
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.measure(q, c)
circuit_drawer(qc)
job = execute(qc, backend='local_qasm_simulator', shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc)
job = execute(qc, backend='local_qasm_simulator', shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.reset(q[0])
qc.measure(q, c)
circuit_drawer(qc)
job = execute(qc, backend='local_qasm_simulator', shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.reset(q[0])
qc.measure(q, c)
circuit_drawer(qc)
job = execute(qc, backend='local_qasm_simulator', shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
circuit_drawer(qc)
job = execute(qc, backend='local_qasm_simulator', shots=1024)
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q,c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
circuit_drawer(qc)
job = execute(qc, backend='local_qasm_simulator', shots=1024)
job.result().get_counts(qc)
# Initializing a three-qubit quantum state
import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.initialize(desired_vector, [q[0],q[1],q[2]])
circuit_drawer(qc)
job = execute(qc, backend='local_statevector_simulator')
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import random
from qiskit.quantum_info import Statevector
secret = random.randint(0,7) # the owner is randomly picked
secret_string = format(secret, '03b') # format the owner in 3-bit string
oracle = Statevector.from_label(secret_string) # let the oracle know the owner
from qiskit.algorithms import AmplificationProblem
problem = AmplificationProblem(oracle, is_good_state=secret_string)
from qiskit.algorithms import Grover
grover_circuits = []
for iteration in range(1,3):
grover = Grover(iterations=iteration)
circuit = grover.construct_circuit(problem)
circuit.measure_all()
grover_circuits.append(circuit)
# Grover's circuit with 1 iteration
grover_circuits[0].draw()
# Grover's circuit with 2 iterations
grover_circuits[1].draw()
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(circuits=grover_circuits, shots=1000)
result = job.result()
print(result)
from qiskit.tools.visualization import plot_histogram
# Extract bit string with highest probability from results as the answer
result_dict = result.quasi_dists[1].binary_probabilities()
answer = max(result_dict, key=result_dict.get)
print(f"As you can see, the quantum computer returned '{answer}' as the answer with highest probability.\n"
"And the results with 2 iterations have higher probability than the results with 1 iteration."
)
# Plot the results
plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations'])
# Print the results and the correct answer.
print(f"Quantum answer: {answer}")
print(f"Correct answer: {secret_string}")
print('Success!' if answer == secret_string else 'Failure!')
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/AnikenC/JaxifiedQiskit
|
AnikenC
|
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from typing import Optional, Union
import qiskit
from qiskit import IBMQ, pulse
from library.dynamics_backend_estimator import DynamicsBackendEstimator
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-nus', group='default', project='default')
backend = provider.get_backend('ibm_cairo')
estimator = DynamicsBackendEstimator(backend)
|
https://github.com/hritiksauw199/Optimized-Shor-Algorithm-for-factoring
|
hritiksauw199
|
import numpy as np
from numpy import pi
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
#Qiskit's least significant bit has the lowest index (0), thus the circuit will be mirrored through the horizontal
qc.h(2)
#Next, we want to turn this an extra quarter turn if qubit 1 is in the state |1>
qc.cp(pi/2, 1, 2) # CROT from qubit 1 to qubit 2
#And another eighth turn if the least significant qubit (0) is |1>
qc.cp(pi/4, 0, 2) # CROT from qubit 2 to qubit 0
qc.h(1)
qc.cp(pi/2, 0, 1) # CROT from qubit 0 to qubit 1
qc.h(0)
qc.swap(0,2)
qc.draw()
def qft_rotations(circuit, n):
if n == 0: # Exit function if circuit is empty
return circuit
n -= 1 # Indexes start from 0
circuit.h(n) # Apply the H-gate to the most significant qubit
for qubit in range(n):
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cp(pi/2**(n-qubit), qubit, n)
# At the end of our function, we call the same function again on
# the next qubits (we reduced n by one earlier in the function)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qc1 = QuantumCircuit(4)
qft(qc1,4)
qc1.draw()
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5
qc.x(0) # since we need '1' at first qubit and at last qubit
qc.x(2)
qc.draw()
# And let's check the qubit's states using the aer simulator:
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy() # making a copy so that we can work on the original one
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
# we can see the state below as '101'
qft(qc,3)
qc.draw()
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
def inverse_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
return circuit.decompose() # .decompose() allows us to see the individual gates
nqubits = 3
number = 5
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
qc.p(number*pi/4,0)
qc.p(number*pi/2,1)
qc.p(number*pi,2)
qc.draw()
qc_init = qc.copy()
qc_init.save_statevector()
sim = Aer.get_backend("aer_simulator")
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qc = inverse_qft(qc, nqubits)
qc.measure_all()
qc.draw()
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= nqubits
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
shots = 2048
transpiled_qc = transpile(qc, backend, optimization_level=3)
job = backend.run(transpiled_qc, shots=shots)
job_monitor(job)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
problem = QuadraticProgram("sample")
problem.binary_var("x")
problem.binary_var("y")
problem.maximize(linear={"x": 1, "y": -2})
print(problem.prettyprint())
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = NumPyMinimumEigensolver()
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = NumPyMinimumEigensolver()
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
mes = QAOA(optimizer=COBYLA(), quantum_instance=qins)
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
shots = 1000
mes = QAOA(sampler=Sampler(), optimizer=COBYLA())
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
mes = VQE(ansatz=RealAmplitudes(), optimizer=COBYLA(), quantum_instance=qins)
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = SamplingVQE(sampler=Sampler(), ansatz=RealAmplitudes(), optimizer=COBYLA())
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
result = meo.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Estimator
from qiskit_optimization.algorithms import MinimumEigenOptimizer
mes = VQE(estimator=Estimator(), ansatz=RealAmplitudes(), optimizer=COBYLA())
try:
meo = MinimumEigenOptimizer(min_eigen_solver=mes)
except TypeError as ex:
print(ex)
from qiskit import BasicAer
from qiskit.algorithms import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
qaoa = QAOA(optimizer=COBYLA(), quantum_instance=qins)
optimizer = WarmStartQAOAOptimizer(
pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25
)
result = optimizer.solve(problem)
print(result)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer, SlsqpOptimizer
qaoa = QAOA(sampler=Sampler(), optimizer=COBYLA())
optimizer = WarmStartQAOAOptimizer(
pre_solver=SlsqpOptimizer(), relax_for_pre_solver=True, qaoa=qaoa, epsilon=0.25
)
result = optimizer.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization.algorithms import GroverOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, quantum_instance=qins)
result = optimizer.solve(problem)
print(result)
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer
optimizer = GroverOptimizer(num_value_qubits=3, num_iterations=3, sampler=Sampler())
result = optimizer.solve(problem)
print(result)
from qiskit import BasicAer
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer
backend = BasicAer.get_backend("qasm_simulator")
shots = 1000
qins = QuantumInstance(backend=backend, shots=shots)
try:
optimizer = GroverOptimizer(
num_value_qubits=3, num_iterations=3, quantum_instance=qins, sampler=Sampler()
)
# raises an error because both quantum_instance and sampler are set.
except ValueError as ex:
print(ex)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
### Install Qiskit and relevant packages, if needed
### IMPORTANT: Make sure you are on 3.10 > python < 3.12
'''
%pip install qiskit[visualization]==1.0.2
%pip install qiskit-ibm-runtime
%pip install qiskit-aer
%pip install graphviz
%pip install qiskit-serverless -U
%pip install qiskit-transpiler-service -U
'''
%pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U
# Import all in one cell
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.circuit.library import RealAmplitudes
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.visualization import plot_gate_map, plot_circuit_layout, plot_distribution
from qiskit.circuit import ParameterVector
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import (
QiskitRuntimeService,
EstimatorV2 as Estimator,
SamplerV2 as Sampler,
EstimatorOptions
)
import warnings
warnings.filterwarnings('ignore')
# qc-grader should be 0.18.13 (or higher)
import qc_grader
qc_grader.__version__
from qc_grader.challenges.iqc_2024 import grade_lab_bonus_ex1, grade_lab_bonus_ex2, grade_lab_bonus_ex3
def old_amplitude_embedding(num_qubits, bird_index):
"""Create amplitude embedding circuit
Parameters:
num_qubits (int): Number of qubits for the ansatz
bird_index (int): Data index of the bird
Returns:
qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird
"""
def generate_GHZ(qc):
qc.h(0)
for i, j in zip(range(num_qubits-1), range(1,num_qubits)):
qc.cx(i, j)
### Write your code below here ###
qc = QuantumCircuit(num_qubits)
if bird_index < 5:
generate_GHZ(qc)
bin_string = format(bird_index, '0{0}b'.format(num_qubits))
for i in reversed(range(len(bin_string))):
if bin_string[i] == '1':
qc.x(num_qubits-i-1)
### Don't change any code past this line ###
return qc
num_qubits = 50
# Choose a real backend
service = QiskitRuntimeService()
backend = service.backend("ibm_osaka")
# Define a fake backend with the same properties as the real backend
fake_backend = AerSimulator.from_backend(backend)
index_bird = 0 # You can check different birds by changing the index
qc = old_amplitude_embedding(num_qubits, index_bird)
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
transpiled_qc = pm.run(qc)
print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
transpiled_qc.draw(output="mpl", fold=False, idle_wires=False)
def new_amplitude_embedding(num_qubits, bird_index):
"""Create efficient amplitude embedding circuit
Parameters:
num_qubits (int): Number of qubits for the ansatz
bird_index (int): Data index of the bird
Returns:
qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird
"""
### Write your code below here ###
### Don't change any code past this line ###
return qc
num_qubits = 50
index = 0 # Change to different values for testing
qc = new_amplitude_embedding(num_qubits, index)
qc.measure_all()
# Define the backend and the pass manager
aer_sim = AerSimulator(method='matrix_product_state')
pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3)
isa_circuit = pm.run(qc)
# Define the sampler with the number of shots
sampler = Sampler(backend=aer_sim)
result = sampler.run([isa_circuit]).result()
samp_dist = result[0].data.meas.get_counts()
plot_distribution(samp_dist, figsize=(10, 3))
num_qubits = 50
# Choose a real backend
service = QiskitRuntimeService()
backend = service.backend("ibm_kyoto")
# Define a fake backend with the same properties as the real backend
fake_backend = AerSimulator.from_backend(backend)
index_bird = 0 #You can check different birds by changing the index
qc = new_amplitude_embedding(num_qubits, index_bird)
pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)
transpiled_qc = pm.run(qc)
print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
transpiled_qc.draw(output="mpl", fold=False, idle_wires=False)
# Submit your answer using following code
grade_lab_bonus_ex1(new_amplitude_embedding(50,3)) # Expected answer type: QuantumCircuit
def generate_old_ansatz(qubits):
qc = RealAmplitudes(qubits, reps=1, entanglement='pairwise')
return qc
num_qubits = 50
# Choose a real backend
service = QiskitRuntimeService()
backend = service.backend("ibm_kyoto")
# Define a fake backend with the same properties as the real backend
fake_backend = AerSimulator.from_backend(backend)
index_bird = 0 # You can check different birds by changing the index
qc = new_amplitude_embedding(num_qubits, index_bird)
ansatz = generate_old_ansatz(num_qubits)
pm = generate_preset_pass_manager(optimization_level=3, backend=backend)
transpiled_qc = pm.run(qc.compose(ansatz))
print('Depth new mapping + old ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
# transpiled_qc.draw(output="mpl", fold=False, idle_wires=False)
def generate_ansatz(num_qubits):
"""Generate a `RealAmplitudes` ansatz where all qubits are entangled with each other
Parameters:
num_qubits (int): Number of qubits for the ansatz
Returns:
qc (QuantumCircuit): Quantum circuit with the generated ansatz
"""
### Write your code below here ###
### Don't change any code past this line ###
return qc
index_bird = 0 # You can check different birds by changing the index
new_mapping_qc = new_amplitude_embedding(num_qubits, index_bird)
ansatz = generate_ansatz(num_qubits)
pm = generate_preset_pass_manager(optimization_level=3, backend=backend)
transpiled_qc = pm.run(new_mapping_qc.compose(ansatz))
print('Depth new mapping + new ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2))
# transpiled_qc.draw(output="mpl", fold=False, idle_wires=False)
# Submit your answer using following code
grade_lab_bonus_ex2(transpiled_qc) # Expected answer type: QuantumCircuit
# Generate this to match your ansatz
source_list = # Add your code here
def generalize_optimal_params(num_qubits, ansatz, source_list):
"""Generate a `list of optimal parameters for N qubits
Parameters:
num_qubits (int): Number of qubits for the ansatz
ansatz (QuantumCircuit): Ansatz for our VQC
source_list (list): List of qubits used as source to entangle other qubits
Returns:
opt_params (list): List of optimal parameters generated for N qubits
"""
opt_params = np.zeros(ansatz.num_parameters)
for i in range(ansatz.num_parameters//2):
if i in source_list:
opt_params[i] = np.pi
return opt_params
def test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend):
"""Tests the shallow VQC on a QPU
Parameters:
num_qubits (int): Number of qubits for the ansatz
list_labels (list): List of labels
obs: (SparsePauliOp): Observable
opt_params (ndarray): Array of optimized parameters
options (EstimatorOptions): Options for Estimator primitive
backend (Backend): Real backend from IBM Quantum to run the job
Returns:
job_id (str): Job ID for Quantum job
"""
### Write your code below here ###
### Don't change any code past this line ###
return job_id
def retrieve_job(job_id):
"""Retrieve test results from job id
Parameters:
job_id (str): Job ID
Returns:
results_test (list): List of test results
errors_test (list): List of test errors
"""
job = service.job(job_id)
results_test = []
errors_test = []
for result in job.result():
results_test.append(abs(abs(result.data.evs)-1)) #COST FUNCTION HAS A -1 NOW!!!
errors_test.append(abs(result.data.stds))
return results_test, errors_test
def test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, backend):
"""Tests the shallow VQC on a QPU
Parameters:
num_qubits (int): Number of qubits for the ansatz
list_labels (list): List of labels
obs: (SparsePauliOp): Observable
opt_params (ndarray): Array of optimized parameters
options (EstimatorOptions): Options for Estimator primitive
backend (Backend): AerSimulator backend to run the job
Returns:
results_test (list): List of test results
"""
results_test = []
### Write your code below here ###
### Don't change any code past this line ###
result = job.result()[0].data.evs
results_test.append(abs(abs(result)-1)) # COST FUNCTION NOW HAS A -1!!!
return results_test
def compute_performance(result_list, list_labels):
"""Return the performance of the classifier
Parameters:
result_list (list): List of results
list_labels (list): List of labels
Returns:
performance (float): Performance of the classifier
"""
### Write your code below here ###
### Don't change any code past this line ###
return performance
num_qubits = 50
aer_sim = AerSimulator(method='matrix_product_state')
pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3)
isa_circuit = pm.run(new_mapping_qc)
list_labels = np.append(np.ones(5), np.zeros(5))
obs = SparsePauliOp("Z"*num_qubits)
opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list)
options = EstimatorOptions()
results_test_aer_sim = test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, aer_sim)
fig, ax = plt.subplots(1, 1, figsize=(7,5))
ax.set_title('Cost on test data MPS')
ax.set_ylabel('Cost')
ax.set_xlabel('State index')
print(f"Performance for resilience 0: {compute_performance(results_test_aer_sim, list_labels)}")
ax.plot(results_test_aer_sim, 'o-', color='tab:red', label='MPS Num qubits = ' + str(num_qubits))
ax.plot(list_labels, 'k-', label='Labels')
ax.legend()
# Submit your answer using following code
grade_lab_bonus_ex3(results_test_aer_sim) # Expected variable types: List
service = QiskitRuntimeService()
backend = service.backend("select_your_device")
# RUN JOBS
num_qubits = 50
obs = SparsePauliOp("Z"*num_qubits)
opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list)
for resilience in [0,1]:
DD = True
options = EstimatorOptions(default_shots = 5_000,
optimization_level=0,
resilience_level=resilience)
options.dynamical_decoupling.enable = DD
options.dynamical_decoupling.sequence_type = 'XpXm'
# OPTIONAL
# options.resilience.zne_mitigation = True
# options.resilience.zne.noise_factors = (1, 1.2, 1.5)
# options.resilience.zne.extrapolator = ('exponential', 'linear', 'polynomial_degree_2') #order matters
job_id = test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend)
results_test_0_DD, errors_test_0_DD = retrieve_job('Enter your JobID for resilience level 0')
results_test_1_DD, errors_test_1_DD = retrieve_job('Enter your JobID for resilience level 1')
fig, ax = plt.subplots(1, 1, figsize=(7,5))
ax.set_title(f'Test of a {num_qubits} qubit VQC on {backend.name}')
ax.set_ylabel('Cost')
ax.set_xlabel('State index')
print(f"Performance for no DD + no TREX: {compute_performance(results_test_0_DD, list_labels):.3f}")
print(f"Performance for DD + TREX: {compute_performance(results_test_1_DD, list_labels):.3f}")
ax.errorbar(range(10), results_test_0_DD, fmt='--o', yerr=errors_test_0_DD, color='tab:orange', label=f'{backend.name} RL=0 shots={options.default_shots} DD={options.dynamical_decoupling.enable}')
ax.errorbar(range(10), results_test_1_DD, fmt='--o', yerr=errors_test_1_DD, color='tab:blue', label=f'{backend.name} RL=1 shots={options.default_shots} DD={options.dynamical_decoupling.enable}')
ax.plot(list_labels, 'k-', label='Labels')
ax.legend()
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
from pprint import pprint
import math
# importing the QISKit
from qiskit import QuantumProgram
# To use API
#import Qconfig
# Definition of matchgate
def gate_mu3(qcirc,theta,phi,lam,a,b):
qcirc.cx(a,b)
qcirc.cu3(theta,phi,lam,b,a)
qcirc.cx(a,b)
# Number of qubits (should be odd)
n_nodes = 5
# Number of steps
n_step = 2
# Histogram
hist = True
# Quantum Sphere
#hist = False
# Creating Programs
qp = QuantumProgram()
# Creating Registers
qr = qp.create_quantum_register('qr', n_nodes)
cr = qp.create_classical_register('cr', n_nodes)
# Creating Circuits
qc = qp.create_circuit('QWalk', [qr], [cr])
# Initial state
qc.x(qr[0])
# Creating of two partitions with M1' and M2
# Repeating that n_step times
for k in range(0,n_step):
for i in range(0,n_nodes-1,2):
gate_mu3(qc,math.pi, math.pi, 0, qr[i], qr[i+1])
for i in range(1,n_nodes,2):
gate_mu3(qc,math.pi/2, 0, 0, qr[i], qr[i+1])
if hist:
for i in range(0,n_nodes):
qc.measure(qr[i], cr[i])
# To print the circuit
# QASM_source = qp.get_qasm('QWalk')
# print(QASM_source)
# To use API
# qp.set_api(Qconfig.APItoken, Qconfig.config['url'])
backend = 'local_qasm_simulator'
if hist:
shots = 4096
else:
shots = 1 # backend 'trick': produces amplitudes instead of probabilities
qobj=qp.compile(['QWalk'], backend = backend, shots = shots ) # Compile quantum walk
result = qp.run(qobj)
print(result)
# execute this cell twice to see the result due to an issue with matplotlib
# import state tomography functions
from qiskit.tools.visualization import plot_histogram, plot_state
import numpy as np
if hist:
plot_histogram(result.get_counts('QWalk'))
else:
data_ampl = result.get_data('QWalk')
state_walk = data_ampl['quantum_state']
rho_walk = np.outer(state_walk,state_walk.conj())
plot_state(rho_walk,'qsphere')
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
'''
This program sets up the circuits for the randamised benchmarking routine
'''
import qiskit
import numpy as np
import os, shutil
import matplotlib.pyplot as plt
from matplotlib.pyplot import draw, show
import qiskit.ignis.verification.randomized_benchmarking as rb
from qiskit_aer.noise import NoiseModel
from qiskit_aer.noise.errors.standard_errors import depolarizing_error, thermal_relaxation_error
os.environ["QT_QPA_PLATFORM"] = "xcb" # for Linux only
folder_RBM = os.getcwd()+'/RBM/'
if not os.path.exists(folder_RBM):
os.makedirs(folder_RBM)
else:
shutil.rmtree(folder_RBM)
os.makedirs(folder_RBM)
## Generate RB circuits (2Q RB)
# number of qubits
nQ=3
rb_opts = {}
# Number of Cliffords in the sequence
rb_opts['length_vector'] = [1, 10, 20, 50, 75, 100, 125, 150, 175, 200]
# Number of seeds (random sequences)
rb_opts['nseeds'] = 5
# Default pattern
rb_opts['rb_pattern'] = [ [0, 1, 2] ]
rb_circs, xdata = rb.randomized_benchmarking_seq(**rb_opts)
print(len(rb_circs))
for i in range(len(rb_circs)):
for n, circuit in enumerate(rb_circs[i]):
filename = str(folder_RBM+'seed_'+str(i)+'_m_'+str(rb_opts['length_vector'][n]+1)+'.qasm')
circuit.qasm(filename=filename)
# Run on a noisy simulator
noise_model = NoiseModel()
# Depolarizing error on the gates u2, u3 and cx (assuming the u1 is virtual-Z gate and no error)
p1Q = 0.002
p2Q = 0.01
noise_model.add_all_qubit_quantum_error(depolarizing_error(p1Q, 1), 'u2')
noise_model.add_all_qubit_quantum_error(depolarizing_error(2 * p1Q, 1), 'u3')
noise_model.add_all_qubit_quantum_error(depolarizing_error(p2Q, 2), 'cx')
backend = qiskit.Aer.get_backend('qasm_simulator')
# Create the RB fitter
backend = qiskit.Aer.get_backend('qasm_simulator')
basis_gates = ['u1','u2','u3','cx']
shots = 200
transpiled_circs_list = []
rb_fit = rb.RBFitter(None, xdata, rb_opts['rb_pattern'])
for rb_seed, rb_circ_seed in enumerate(rb_circs):
print('Compiling seed %d'%rb_seed)
new_rb_circ_seed = qiskit.compiler.transpile(rb_circ_seed, basis_gates=basis_gates)
transpiled_circs_list.append(new_rb_circ_seed)
print('Simulating seed %d'%rb_seed)
## THIS ONE IS FROM OUR RESULTS NOT THE BACKEND
job = qiskit.execute(new_rb_circ_seed,
backend,
shots=shots,
noise_model=noise_model)
# Add data to the fitter
rb_fit.add_data(job.result())
print('After seed %d, alpha: %f, EPC: %f'%(rb_seed,rb_fit.fit[0]['params'][1], rb_fit.fit[0]['epc']))
plt.figure(figsize=(8, 6))
ax = plt.subplot(1, 1, 1)
# Plot the essence by calling plot_rb_data
rb_fit.plot_rb_data(0, ax=ax, add_label=True, show_plt=False)
# Add title and label
ax.set_title('%d Qubit RB'%(nQ), fontsize=18)
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver()
problem = driver.run()
fermionic_op = problem.hamiltonian.second_q_op()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
qubit_jw_op = mapper.map(fermionic_op)
print(qubit_jw_op)
from qiskit_nature.second_q.mappers import ParityMapper
mapper = ParityMapper()
qubit_p_op = mapper.map(fermionic_op)
print(qubit_p_op)
mapper = ParityMapper(num_particles=problem.num_particles)
qubit_op = mapper.map(fermionic_op)
print(qubit_op)
tapered_mapper = problem.get_tapered_mapper(mapper)
print(type(tapered_mapper))
qubit_op = tapered_mapper.map(fermionic_op)
print(qubit_op)
from qiskit_nature.second_q.circuit.library import HartreeFock
hf_state = HartreeFock(2, (1, 1), JordanWignerMapper())
hf_state.draw()
from qiskit_nature.second_q.mappers import InterleavedQubitMapper
interleaved_mapper = InterleavedQubitMapper(JordanWignerMapper())
hf_state = HartreeFock(2, (1, 1), interleaved_mapper)
hf_state.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/abhishekchak52/quantum-computing-course
|
abhishekchak52
|
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
import qiskit
from qiskit import QuantumCircuit, execute
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
from qiskit.visualization import *
from qiskit.quantum_info import *
success_msg = 'Your answer is correct.'
fail_msg = 'Your answer is not correct. Please try again.'
basis_gates = ['id', 'x', 'y', 'z', 's', 't', 'sdg', 'tdg', 'h', 'p', 'sx' ,'r', 'rx', 'ry', 'rz', 'u', 'u1', 'u2', 'u3', 'cx', 'barrier', 'measure', 'snapshot']
qc1 = QuantumCircuit(3)
# Insert gates below to create the state
# Do not change below this line. You do not need to add an additional measurement.
qc1.measure_all()
qc1.draw('mpl')
try:
assert list(qc1.count_ops()) != [], "Circuit cannot be empty"
assert set(qc1.count_ops().keys()).difference(basis_gates) == set(), f"Only the following basic gates are allowed: {basis_gates}"
assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in qc1.data[-3:len(qc1.data)]]), "Measurement must be the last operation in a circuit."
sv_check = Statevector.from_instruction(qc1.remove_final_measurements(inplace=False)).equiv((Statevector.from_label('000')+Statevector.from_label('111'))/np.sqrt(2))
assert sv_check, "You did not prepare the correct state."
job = execute(qc1, backend=QasmSimulator(), shots=1024, seed_simulator=0)
counts = job.result().get_counts()
print(success_msg if (sv_check) else fail_msg)
except AssertionError as e:
print(f'Your code has an error: {e.args[0]}')
except Exception as e:
print(f'This error occured: {e.args[0]}')
plot_histogram(counts)
def superdense_coding_circ(bitstr):
'''
bitstr is a 2-character string with possible values '00', '01', '10', '11'
'''
qc2 = QuantumCircuit(2)
# Enter your code below this line
# Prepare a Bell state B_00 below
# Do not remove the following line
qc2.snapshot('1')
# Apply single-qubit gates only on q_0 to encode the bitstring
# Do not remove the following line
qc2.snapshot('2')
# Apply gates to change to the Bell basis
# Do not remove the following line
qc2.snapshot('3')
# Do not change below this line. You do not need to add an additional measurement.
qc2.measure_all()
return qc2
b00_sv = (Statevector.from_label('00')+Statevector.from_label('11'))/np.sqrt(2)
b01_sv = (Statevector.from_label('01')+Statevector.from_label('10'))/np.sqrt(2)
b10_sv = (Statevector.from_label('00')-Statevector.from_label('11'))/np.sqrt(2)
b11_sv = (Statevector.from_label('01')-Statevector.from_label('10'))/np.sqrt(2)
bell_states_sv = [b00_sv, b01_sv, b10_sv, b11_sv]
basis_states = ['00', '01', '10', '11']
bell_dict = dict(zip(basis_states, bell_states_sv))
enc_dec_mat = np.zeros((len(basis_states),len(basis_states)))
try:
for state in basis_states:
sv_checks = []
qc = superdense_coding_circ(state)
assert list(qc.count_ops()) != [], f" Bitstring {state}: Circuit cannot be empty"
assert qc.count_ops()['measure'] <= 2, f" Bitstring {state}: Please remove extra measurements"
assert qc.count_ops()['snapshot'] == 3, f" Bitstring {state}: Please do not add or remove snapshots"
assert set(qc.count_ops().keys()).difference(basis_gates) == set(), f" Bitstring {state}: Only the following basic gates are allowed: {basis_gates}"
assert all([type(gate[0]) == qiskit.circuit.measure.Measure for gate in qc.data[-2:len(qc.data)]]), f" Bitstring {state}: Measurement must be the last operation in a circuit."
result = execute(qc.reverse_bits(),backend=QasmSimulator(), shots=1).result().get_counts().most_frequent()
assert state == result, f" Bitstring {state}: Your encoding is not correct"
enc_dec_mat[int(state,2), int(result,2)] = 1
sv = execute(qc.reverse_bits(), backend=StatevectorSimulator()).result().data()['snapshots']['statevector']
sv_checks.append(b00_sv.equiv(sv['1'][0]))
sv_checks.append(bell_dict[state].equiv(sv['2'][0]))
sv_checks.append(Statevector.from_label(state).equiv(sv['3'][0]))
assert all(np.diag(enc_dec_mat) == np.ones(4)), "Your encoding is not correct"
plt.matshow(enc_dec_mat, cmap='binary')
plt.title('Superdense Coding Matrix')
plt.xlabel("Alice's encoded bits", fontsize=14)
plt.ylabel("Bob's decoded bits", fontsize=14)
plt.xticks(ticks=range(4), labels=basis_states, fontsize=12)
plt.yticks(ticks=range(4), labels=basis_states, fontsize=12)
circ_check = all(sv_checks)
assert circ_check, "Your circuit does not work for all bitstrings"
print(success_msg if circ_check else fail_msg)
except AssertionError as e:
print(f'Your code has an error: {e.args[0]}')
except Exception as e:
print(f'This error occured: {e.args[0]}')
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import qiskit_alt
qiskit_alt.project.ensure_init()
# The following line would also initialize qiskit_alt behind the scenes, but we have made it explicity above.
# import qiskit_alt.electronic_structure
from qiskit.providers import aer # make sure this is available
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit.algorithms import VQE
from qiskit.circuit.library import TwoLocal
from qiskit.utils import QuantumInstance
from qiskit import Aer
from qiskit.algorithms.optimizers import COBYLA
import qiskit_alt, qiskit_alt.electronic_structure # already done above, but this does not hurt
from qiskit_alt.pauli_operators import PauliSum_to_SparsePauliOp
from qiskit.opflow import PauliSumOp
geometry = [["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]]
basis="sto3g"
molecule = Molecule(
geometry=geometry, charge=0, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis=basis, driver_type=ElectronicStructureDriverType.PYSCF
)
es_problem = ElectronicStructureProblem(driver)
second_q_op= es_problem.second_q_ops()
qubit_converter = QubitConverter(mapper=JordanWignerMapper())
qubit_op = qubit_converter.convert(second_q_op[0])
# Print the underlying data stored backing qubit_op
qubit_op.primitive.simplify()
# Compute the Fermionic operator of the molecule
fermi_op = qiskit_alt.electronic_structure.fermionic_hamiltonian(geometry, basis)
# Convert the Fermionic operator to a Pauli operator using the Jordan-Wigner transform
pauli_op = qiskit_alt.electronic_structure.jordan_wigner(fermi_op)
type(pauli_op)
pauli_op.simplify()
(pauli_op - qubit_op.primitive).simplify()
fermi_op[1] # In qiskit_alt, the Fermi operator carries the identity term
nuclear_energy_term = fermi_op[1].coeff
nuclear_energy_term
# Define the ansatz
ansatz = TwoLocal(
rotation_blocks=["h", "rx"],
entanglement_blocks="cz",
entanglement="full",
reps=2,
parameter_prefix="y",
)
# Initialize the COBYLA optimizer
optimizer = COBYLA(maxiter=500)
# Select the backend for the quantum_instance
backend = QuantumInstance(Aer.get_backend('statevector_simulator'),
seed_simulator=100,
seed_transpiler=100)
# Run VQE algorithm
vqe = VQE(ansatz = ansatz,
optimizer = optimizer,
quantum_instance = backend)
# Compute the ground-state energy of the molecule
nature_result = vqe.compute_minimum_eigenvalue(operator=qubit_op)
nature_energy = nature_result.eigenvalue.real + nuclear_energy_term # Include constant term that is normally thrown away
print("The ground-state energy of the Hydrogen molecule is {} Hatree".format(round(nature_energy,3)))
# Convert the Pauli operator into a sum of Pauli operators, the required input format
pauli_sum_op = PauliSumOp(pauli_op)
# Compute the ground-state energy of the molecule
alt_result = vqe.compute_minimum_eigenvalue(operator=pauli_sum_op)
print("The ground-state energy of the Hydrogen molecule is {} Hatree".format(round(alt_result.eigenvalue.real,3)))
|
https://github.com/unif2/Quantum-Computing-Mentorship-Task-4-Code
|
unif2
|
import numpy as np
from numpy import kron
import qiskit as qk
def decomposition(H):
"""Decompose any 4x4 Hermitian matrix into a sum of tensor products of two Pauli matrices
"""
identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128)
x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128)
y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128)
z = np.array([[1, 0], [0, -1]], dtype=np.complex128)
S = [identity, x, y, z]
labels = ['I', 'sigma_x', 'sigma_y', 'sigma_z']
d = {'00': 'I product I', '01': 'I product sigma_x', '02': 'I product sigma_y', '03': 'I product sigma_z',
'10': 'sigma_x product I', '11': 'sigma_x product sigma_x', '12': 'sigma_x product sigma_y',
'13': 'sigma_x product sigma_z', '20': 'sigma_y product I', '21': 'sigma_y product sigma_x',
'22': 'sigma_y product sigma_y', '23': 'sigma_y product sigma_z', '30': 'sigma_z product I',
'31': 'sigma_z product sigma_x', '32': 'sigma_z product sigma_y', '33': 'sigma_z product sigma_z'}
for i in range(4):
for j in range(4):
a_ij = 0.25 * np.dot(kron(S[i], S[j]), H).trace()
if a_ij != 0.0:
print(str(a_ij) + ' * ' + d[str(i)+str(j)])
H = np.array([[0,0,0,0],[0,-1,1,0],[0,1,-1,0],[0,0,0,0]])
decomposition(H)
def prepare_state(theta, n=3):
"""
Prepare three 2-qubit states with 3 associated quantum registers, 3 associated classical registers,
and 3 quantum circuits. We will prepare the state with the ansatz mentioned in the notes in which we act on
the first qubit with the Hadamard operator, then with the R_z operator, then we act on the 2-qubit state
with the CNOT gate, and then on the second qubit in each terms of the superposition with the sigma_x operator.
After that, we will take the first circuit and act on each qubit with the R_y(pi/2) operator, and take the second
circuit and act on each qubit with the R_x(-pi/2) operator as explained in the notes. We do this so that those
qubits will be in the basis of eigenvectors of sigma_x and sigma_y as explained in the notes. We can measure
the qubits in the other circuit as-is because we need the expectation value of sigma_z and the qubits are already
in the computational basis.
"""
qr0 = qk.QuantumRegister(2)
cr0 = qk.ClassicalRegister(2)
qc0 = qk.QuantumCircuit(qr0,cr0)
qr1 = qk.QuantumRegister(2)
cr1 = qk.ClassicalRegister(2)
qc1 = qk.QuantumCircuit(qr1,cr1)
qr2 = qk.QuantumRegister(2)
cr2 = qk.ClassicalRegister(2)
qc2 = qk.QuantumCircuit(qr2,cr2)
qregisters = [qr0,qr1,qr2]
cregisters = [cr0,cr1,cr2]
qcircuits = [qc0,qc1,qc2]
for i in range(n):
qcircuits[i].h(qregisters[i][0])
for i in range(n):
qcircuits[i].rz(theta, qregisters[i][0])
for i in range(n):
qcircuits[i].cx(qregisters[i][0], qregisters[i][1])
for i in range(n):
qcircuits[i].x(qregisters[i][1])
qcircuits[0].ry((np.pi)/2, qregisters[0][0])
qcircuits[0].ry((np.pi)/2, qregisters[0][1])
qcircuits[1].rx(-(np.pi)/2, qregisters[1][0])
qcircuits[1].rx(-(np.pi)/2, qregisters[1][1])
return qregisters, cregisters, qcircuits
qregisters, cregisters, qcircuits = prepare_state(np.pi, n=3)
qcircuits[0].draw(output='mpl')
qcircuits[1].draw(output='mpl')
qcircuits[2].draw(output='mpl')
def expectation(qcircuits, cregisters, qregisters, n_shots, n=3):
"""
For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Multiply
each of the three expectation values by 0.5, add them up, and subtract -0.5. Return the result.
"""
expect = -0.5
for i in range(n):
qcircuits[i].measure(qregisters[i],cregisters[i])
qk.Aer.backends()
sim = qk.Aer.get_backend('qasm_simulator')
res = qk.execute(qcircuits[i], sim, shots=n_shots).result()
counts = res.get_counts()
sum = 0
for k,v in counts.items():
if k=='01' or k=='10':
sum += (-1)*v/n_shots
elif k=='00' or k=='11':
sum += v/n_shots
sum = 0.5*sum
expect += sum
return expect
# Consider 100 values of theta, between 0 and Pi. This theta is the one used in state preparation.
thetas = np.linspace(0, np.pi, 100)
# For each theta, store the resulting expectation value in results
results = []
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = expectation(qcircuits, cregisters, qregisters, 5000, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
from qiskit import IBMQ
#IBMQ.delete_account()
IBMQ.save_account('my IBM token', overwrite=True)
IBMQ.load_account()
provider = IBMQ.get_provider()
procs=provider.backends(operational=True, simulator=False)
from qiskit.tools.jupyter import *
%qiskit_backend_overview
from qiskit.tools import monitor
backend = qk.providers.ibmq.least_busy([p for p in procs if len(p.properties().qubits) >= 2])
from qiskit.tools.monitor import backend_overview, backend_monitor
backend_monitor(backend)
def q_expectation(qcircuits, cregisters, qregisters, n_shots, n=3):
"""
For each circuit, execute and measure it using the classical simulator 5000 times as explained above. Multiply
each of the three expectation values by 0.5, add them up, and subtract -0.5. Return the result.
"""
expect = -0.5
for i in range(n):
qcircuits[i].measure(qregisters[i],cregisters[i])
qk.Aer.backends()
sim = qk.Aer.get_backend('qasm_simulator')
res = qk.execute(qcircuits[i], backend=backend, shots=n_shots).result()
#mon = monitor.job_monitor(res)
counts = res.get_counts()
sum = 0
for k,v in counts.items():
if k=='01' or k=='10':
sum += (-1)*v/n_shots
elif k=='00' or k=='11':
sum += v/n_shots
sum = 0.5*sum
expect += sum
return expect
# Consider 10 values of theta, between 0 and Pi. This theta is the one used in state preparation.
thetas = np.linspace(0, np.pi, 10)
# Use n_shots = 100
results = []
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = q_expectation(qcircuits, cregisters, qregisters, 100, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
# Use n_shots = 1000
results = []
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = q_expectation(qcircuits, cregisters, qregisters, 1000, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
# Use n_shots = 5000
results = []
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = q_expectation(qcircuits, cregisters, qregisters, 5000, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
# Use n_shots = 8192 = max allowed
results = []
thetas = [np.pi]
# For each theta, find the expectation value
for theta in thetas:
qregisters, cregisters, qcircuits = prepare_state(theta, n=3)
expect = q_expectation(qcircuits, cregisters, qregisters, 8192, n=3)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
def decomposition(H):
"""Decompose any 4x4 Hermitian matrix into a sum of tensor products of two Pauli matrices
"""
A_ij = []
identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128)
x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128)
y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128)
z = np.array([[1, 0], [0, -1]], dtype=np.complex128)
S = [identity, x, y, z]
labels = ['I', 'sigma_x', 'sigma_y', 'sigma_z']
d = {'00': 'I product I', '01': 'I product sigma_x', '02': 'I product sigma_y', '03': 'I product sigma_z',
'10': 'sigma_x product I', '11': 'sigma_x product sigma_x', '12': 'sigma_x product sigma_y', '13': 'sigma_x product sigma_z',
'20': 'sigma_y product I', '21': 'sigma_y product sigma_x', '22': 'sigma_y product sigma_y', '23': 'sigma_y product sigma_z',
'30': 'sigma_z product I', '31': 'sigma_z product sigma_x', '32': 'sigma_z product sigma_y', '33': 'sigma_z product sigma_z'}
for i in range(4):
for j in range(4):
a_ij = 0.25 * np.dot(kron(S[i], S[j]), H).trace()
A_ij.append(a_ij)
if a_ij != 0.0:
print(str(a_ij) + ' * ' + d[str(i)+str(j)])
return np.asarray(A_ij).reshape(4,4)
def prepare_state2(A, theta):
qregisters = []
cregisters = []
qcircuits = []
identity = np.array([[1, 0],[ 0, 1]], dtype=np.complex128)
x = np.array([[0, 1], [ 1, 0]], dtype=np.complex128)
y = np.array([[0, -1j],[1j, 0]], dtype=np.complex128)
z = np.array([[1, 0], [0, -1]], dtype=np.complex128)
d = {}
for i in range(4):
for j in range(4):
if A[i,j] != 0:
if i !=0 and j!=0:
qr = qk.QuantumRegister(2)
cr = qk.ClassicalRegister(2)
qc = qk.QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.rz(theta, qr[0])
qc.cx(qr[0], qr[1])
qc.x(qr[1])
if i==1:
qc.ry((np.pi)/2, qr[0])
if i==2:
qc.rx(-(np.pi)/2, qr[0])
if j==1:
qc.ry((np.pi)/2, qr[1])
if j==2:
qc.rx(-(np.pi)/2, qr[1])
qregisters.append(qr)
cregisters.append(cr)
qcircuits.append(qc)
d[(i,j)] = [qregisters, cregisters, qcircuits]
if i == 0 and j != 0:
qr = qk.QuantumRegister(2)
cr = qk.ClassicalRegister(2)
qc = qk.QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.rz(theta, qr[0])
qc.cx(qr[0], qr[1])
qc.x(qr[1])
if j==1:
qc.ry((np.pi)/2, qr[1])
if j==2:
qc.rx(-(np.pi)/2, qr[1])
qregisters.append(qr)
cregisters.append(cr)
qcircuits.append(qc)
d[(i,j)] = [qregisters, cregisters, qcircuits]
if i != 0 and j == 0:
qr = qk.QuantumRegister(2)
cr = qk.ClassicalRegister(2)
qc = qk.QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.rz(theta, qr[0])
qc.cx(qr[0], qr[1])
qc.x(qr[1])
if i==1:
qc.ry((np.pi)/2, qr[0])
if i==2:
qc.rx(-(np.pi)/2, qr[0])
qregisters.append(qr)
cregisters.append(cr)
qcircuits.append(qc)
d[(i,j)] = [qregisters, cregisters, qcircuits]
return d, A
def expectation2(d, A, n_shots):
"""
For each circuit, execute and measure it using the classical simulator 5000 times as explained above.
Return the result.
"""
expect = A[0,0]
qk.Aer.backends()
sim = qk.Aer.get_backend('qasm_simulator')
for k,v in d.items():
for i in range(len(v[2])):
v[2][i].measure(v[0][i],v[1][i])
res = qk.execute(v[2][i], sim, shots=n_shots).result()
counts = res.get_counts()
sum = 0
for m,n in counts.items():
if m=='01' or m=='10':
sum += (-1)*n/n_shots
elif m=='00' or m=='11':
sum += n/n_shots
sum = A[k[0],k[1]]*sum
expect += sum
return expect
thetas = np.linspace(0, np.pi, 100)
H = np.array([[0,0,0,0],[0,-1,1,0],[0,1,-1,0],[0,0,0,0]])
A = decomposition(H)
# For each theta, store the resulting expectation value in results
results = []
# For each theta, find the expectation value
for theta in thetas:
d, A = prepare_state2(A, theta)
expect = expectation2(d, A, 5000)
results.append(expect)
# Sort the results in ascending order. The first one is your minimum eigenvalue.
results.sort()
print("The minimum eigenvalue is: {}.".format(results[0]))
# -5??!! Maybe I missed something in my logic. Will continue to look into this. :-)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module to simulate fermionic circuits."""
from typing import List, Tuple, Optional
import numpy as np
from scipy.sparse import csc_matrix
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_cold_atom.base_circuit_solver import BaseCircuitSolver
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.fermions.fermionic_state import FermionicState
from qiskit_cold_atom.fermions.fermionic_basis import FermionicBasis
from qiskit_cold_atom.fermions.fermion_gate_library import FermionicGate
class FermionCircuitSolver(BaseCircuitSolver):
"""
Numerically simulate fermionic systems by exactly computing the time
evolution under unitary operations generated by fermionic Hamiltonians.
"""
def __init__(
self,
shots: Optional[int] = None,
seed: Optional[int] = None,
num_species: int = 1,
):
"""
Args:
shots: amount of shots for the measurement simulation;
if not None, measurements are performed
seed: seed for the RNG for the measurement simulation
num_species: number of different fermionic species, defaults to 1 for a single type of
(spinless) fermions, 2 for spin-1/2 fermions etc. If > 1, the solver will check for
conservation of the particle number per fermionic species in order to reduce the
Hilbert space dimension of the simulation
"""
self._basis = None
self.num_species = num_species
super().__init__(shots=shots, seed=seed)
@property
def basis(self) -> FermionicBasis:
"""
Return the basis of fermionic occupation number states. This basis is updated via the
setter whenever a new circuit is passed to __call__.
"""
return self._basis
@basis.setter
def basis(self, basis: FermionicBasis):
"""
Set the basis of the simulation and check its dimensions.
Args:
basis: The new basis.
Raises:
QiskitColdAtomError: If the dimension of the basis is too large.
"""
if basis.dimension > self.max_dimension:
raise QiskitColdAtomError(
f"Dimension {basis.dimension} exceeds the maximum "
f"allowed dimension {self.max_dimension}."
)
self._basis = basis
def preprocess_circuit(self, circuit: QuantumCircuit):
"""
Pre-processing fermionic circuits includes setting up the basis for the simulation
by extracting the size, particle number and spin conservation from the circuit.
Args:
circuit: A fermionic quantum circuit for which to setup a basis.
"""
initial_occupations = FermionicState.initial_state(circuit, self.num_species)
_, spin_conservation = self._check_conservations(circuit)
self.basis = FermionicBasis.from_state(initial_occupations, spin_conservation)
self._dim = self.basis.dimension
def get_initial_state(self, circuit: QuantumCircuit) -> csc_matrix:
"""
Return the initial state of the quantum circuit as a sparse column vector.
Args:
circuit: The circuit for which to extract the initial_state.
Returns:
The initial state of the circuit as a sparse matrix.
"""
init_state = FermionicState.initial_state(circuit, self.num_species)
initial_occs = init_state.occupations_flat
initial_index = self.basis.get_occupations().index(initial_occs)
initial_state = csc_matrix(
([1 + 0j], ([initial_index], [0])),
shape=(self.basis.dimension, 1),
dtype=complex,
)
return initial_state
def _embed_operator(
self, operator: FermionicOp, num_wires: int, qargs: List[int]
) -> FermionicOp:
"""
Turn a FermionicOp operator that acts on the wires given in qargs into an operator
that acts on the entire state space of the circuit by padding with identities "I" on the
remaining wires
Args:
operator: FermionicOp describing the generating Hamiltonian of a gate
num_wires: The total number of wires in which the operator should be embedded into
qargs: The wire indices the gate acts on
Returns:
FermionicOp, an operator acting on the entire quantum register of the Circuit
Raises:
QiskitColdAtomError:
- If the given operator is not a FermionicOp
- If the size of the operator does not match the given qargs
"""
if not isinstance(operator, FermionicOp):
raise QiskitColdAtomError(
f"Expected FermionicOp; got {type(operator).__name__} instead."
)
if operator.num_spin_orbitals != len(qargs):
raise QiskitColdAtomError(
f"length of gate labels {operator.num_spin_orbitals} does not match "
f"qargs {qargs} of the gates"
)
embedded_terms = []
for partial_label, factor in operator.terms():
embedded_terms.append((operator._permute_term(partial_label, qargs), factor))
reordered_op = FermionicOp.from_terms(embedded_terms)
reordered_op.num_spin_orbitals = num_wires
return reordered_op
def _check_conservations(self, circuit: QuantumCircuit) -> Tuple[bool, bool]:
"""
Check if the fermionic operators defined in the circuit conserve the total particle number
(i.e. there are as many creation operators as annihilation operators) and the particle
number per spin species (e.g. there are as many up/down creation operators as there are
up/down annihilation operators).
Args:
circuit: A quantum circuit with fermionic gates
Returns:
particle_conservation: True if the particle number is conserved in the circuit
spin_conservation: True if the particle number is conserved for each spin species
Raises:
QiskitColdAtomError:
- If an operator in the circuit is not a FermionicOp.
- If the length of the fermionic operators does not match the system size.
- If the circuit has a number of wires that is not a multiple of the number
of fermionic species.
"""
particle_conservation = True
spin_conservation = True
for fermionic_op in self.to_operators(circuit):
if not isinstance(fermionic_op, FermionicOp):
raise QiskitColdAtomError("operators need to be given as FermionicOp")
if fermionic_op.num_spin_orbitals != circuit.num_qubits:
raise QiskitColdAtomError(
f"Expected length {circuit.num_qubits} for fermionic operator; "
f"received {fermionic_op.num_spin_orbitals}."
)
for opstring, _ in fermionic_op.terms():
op_types = [op for op, _ in opstring]
num_creators = op_types.count("+")
num_annihilators = op_types.count("-")
if num_creators != num_annihilators:
return False, False
if self.num_species > 1:
if circuit.num_qubits % self.num_species != 0:
raise QiskitColdAtomError(
f"The number of wires in the circuit {circuit.num_qubits} is not a "
f"multiple of the {self.num_species} fermionic species number."
)
sites = circuit.num_qubits // self.num_species
# check if the particle number is conserved for each spin species
for i in range(self.num_species):
spin_range = range(i * sites, (i + 1) * sites)
op_types_in_range = [op for op, idx in opstring if idx in spin_range]
num_creators = op_types_in_range.count("+")
num_annihilators = op_types_in_range.count("-")
if num_creators != num_annihilators:
spin_conservation = False
break
return particle_conservation, spin_conservation
def operator_to_mat(self, operator: FermionicOp) -> csc_matrix:
"""Convert the fermionic operator to a sparse matrix.
Args:
operator: fermionic operator of which to compute the matrix representation
Returns:
scipy.sparse matrix of the Hamiltonian
"""
return FermionicGate.operator_to_mat(operator, self.num_species, self._basis)
def draw_shots(self, measurement_distribution: List[float]) -> List[str]:
"""
Helper function to draw counts from a given distribution of measurement outcomes.
Args:
measurement_distribution: List of probabilities of the individual measurement outcomes
Returns:
a list of individual measurement results, e.g. ["011000", "100010", ...]
The outcome of each shot is denoted by a binary string of the occupations of the individual
modes in little endian convention
Raises:
QiskitColdAtomError:
- If the length of the given probabilities does not match the expected Hilbert space
dimension.
- If the number of shots self.shots has not been specified.
"""
meas_dim = len(measurement_distribution)
if meas_dim != self.dim:
raise QiskitColdAtomError(
f"Dimension of the measurement probabilities {meas_dim} does not "
f"match the dimension expected by the solver, {self.dim}"
)
if self.shots is None:
raise QiskitColdAtomError(
"The number of shots has to be set before drawing measurements"
)
# list all possible outcomes as strings '001011', reversing the order of the wires
# to comply with Qiskit's ordering convention
outcome_strings = ["".join(map(str, k)) for k in self.basis.get_occupations()]
# Draw measurements:
meas_results = np.random.choice(outcome_strings, self.shots, p=measurement_distribution)
return meas_results.tolist()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
cos(-2*pi/3), sin(-2*pi/3), cos(-4*pi/3), sin(-4*pi/3), cos(-8*pi/3), sin(-8*pi/3)
|
https://github.com/C2QA/bosonic-qiskit
|
C2QA
|
# To use the package locally, add the C2QA repository's root folder to the path prior to importing c2qa.
import os
import sys
module_path = os.path.abspath(os.path.join("../.."))
if module_path not in sys.path:
sys.path.append(module_path)
# Import packages that will be used
import c2qa
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumRegister, ClassicalRegister
from qiskit.circuit.library import RGate
# To prepare a cat state, we first set our initial parameters: we need one qumode and one ancillary qubit. We will also
# need to set a cutoff for our qumode.
Nmodes=1
Nqubits = 1
cutoff = 2**4 # The photon number at which to truncate the Hilbert space. Our basis will consist of Fock states |0> to |cutoff-1>
alpha = 3/np.sqrt(2)
# Instantiate the Qumode register
qmr = c2qa.QumodeRegister(num_qumodes=Nmodes, num_qubits_per_qumode=int(np.ceil(np.log2(cutoff))))
# Instantiate a Qubit and Classical register
qbr = QuantumRegister(Nqubits)
cbr = ClassicalRegister(Nqubits)
# Initialize a CVCircuit, which includes both the qumode register as well as the qubit register
circuit = c2qa.CVCircuit(qmr, qbr, cbr)
# Compose cat state prep circuit
circuit.h(qbr[0])
circuit.cv_c_d(alpha,qmr[0],qbr[0])
circuit.h(qbr[0])
circuit.measure(qbr[0],cbr[0])
# Now draw the circuit using Qiskit's draw() function
# circuit.draw(scale=1, output = 'mpl', fold = 32, filename = 'figures/Catcircuit.png')
# Now simulate the circuit to retrieve the final density matrix.
stateop, _, _ = c2qa.util.simulate(circuit)
# Use Bosonic Qiskit's built-in plot_wigner function, which traces out the qubit and displays the Wigner (phase-space)
# representation of the qumode state.
fig = c2qa.wigner.plot_wigner(circuit, stateop, dpi = 300)
# We can also print out the occupancy of the modes and their complex amplitudes.
c2qa.util.stateread(stateop,1,1,cutoff);
# Let's first import the GKP parameters
GKP_params = np.load('GKP_params.npz')
# Set some initial parameters:
Nmodes=1 # The number of qumodes
Nqubits = 1 # The number of qubits
cutoff = 2**5 # The qumode cutoff
# Instantiate the Qumode register
qmr = c2qa.QumodeRegister(num_qumodes=1, num_qubits_per_qumode=int(np.ceil(np.log2(cutoff))))
# Instantiate a Qubit register
qbr = QuantumRegister(Nqubits)
# Initialize a CVCircuit, which includes both the qumode register as well as the qubit register
circuit = c2qa.CVCircuit(qmr, qbr)
# Now append gates to the circuit. Here, we append multiple layers, each with a single qubit RGate, followed by
# a conditional displacement and an X gate (which together form the "echoed-conditional displacement" -- for more info,
# see https://www.nature.com/articles/s41567-022-01776-9.
for beta, phi, theta in zip(GKP_params['betas'], GKP_params['phis'], GKP_params['thetas']):
circuit.append(RGate(theta,phi),[qbr[0]])
circuit.cv_c_d(beta/2,qmr[0],qbr[0])
circuit.x(qbr[0])
# Now draw the circuit using Qiskit's draw() function
# circuit.draw(scale=0.6, output = 'mpl', fold = 32, filename = 'figures/GKPcircuit.png')
# Now simulate the circuit to retrieve the final density matrix.
stateop, _, _ = c2qa.util.simulate(circuit)
# Use Bosonic Qiskit's built-in plot_wigner function, which traces out the qubit and displays the Wigner (phase-space)
# representation of the qumode state.
fig = c2qa.wigner.plot_wigner(circuit, stateop, dpi = 300)
# Let's first define a function which constructs our approximation to e^{-iH*dt}
def createU2U1(Nsites,Nbosons, cutoff, U, J, dt):
from qiskit.converters import circuit_to_gate
from qiskit.circuit import Parameter
qmr = c2qa.QumodeRegister(num_qumodes=Nsites, num_qubits_per_qumode=int(np.ceil(np.log2(cutoff))))
circuit = c2qa.CVCircuit(qmr)
# First apply U1: Apply beamsplitters in brickwork layout
theta = -J*dt
for i in range(0,len(qmr)-1,2):
circuit.cv_bs(-theta,qmr[i],qmr[i+1])
for i in range(1,len(qmr)-1,2):
circuit.cv_bs(-theta,qmr[i],qmr[i+1])
# Now apply U2: Use SNAP gate for each site and Fock state
theta = (U/2)*dt
for i in range(0,len(qmr)): # For each site
for n in range(2,cutoff): # For each Fock state
circuit.cv_snap(-theta*n*(n-1),n,qmr[i]) # Apply SNAP with phase proportional to n*(n-1)
return circuit_to_gate(circuit,label = 'U2 U1')
# Let's simulate a Bose-Hubbard model with Nsites for the simple case where we have Nbosons loaded into the lattice
Nsites = 4
Nbosons = 4
cutoff = Nbosons + 1
# Initialize the qumode register
qmr = c2qa.QumodeRegister(num_qumodes=Nsites, num_qubits_per_qumode=int(np.ceil(np.log2(cutoff))))
circuit = c2qa.CVCircuit(qmr)
# Choose parameters
J = 1
U = 0.1
dt = 0.2
t_array = np.arange(0,13*dt,dt)
# Create U2U1, which carries out a single time step of length dt
U2U1 = createU2U1(Nsites, Nbosons, cutoff, U, J, dt)
# Initialize the left-most and right-most mode to each have two bosons initially
circuit.cv_initialize(2, qmr[0])
circuit.cv_initialize(2, qmr[3])
# Loop through each time step and simulate
occupancy_list = np.zeros((len(t_array),Nsites))
for i in range(0,len(t_array)):
print('Timestep ' + str(int(i+1)) + '/' + str(len(t_array)))
circuit.append(U2U1,qmr[:])
stateop, _, _ = c2qa.util.simulate(circuit)
# Print out occupancy
occupancy, _ = c2qa.util.stateread(stateop, 0, Nsites, cutoff, verbose=False,little_endian=True)
occupancy_list[i,:]=np.array(occupancy[0])
occupancy_largeJ = occupancy_list
plt.set_cmap("magma")
fig = plt.figure(figsize = (4,8))
plt.pcolormesh([0,1,2,3],np.arange(0,len(t_array)),occupancy_largeJ,linewidth=0,rasterized=True,shading='auto')
plt.title("$J=$" + str(J) + ", $U=$" + str(0.1))
plt.xticks([0,1,2,3])
plt.xlabel("Qumode")
plt.ylabel("Time ($dt$)")
plt.clim(0,2)
cbar = plt.colorbar(orientation='vertical',ax=plt.gca())
cbar.ax.get_yaxis().labelpad = 20
cbar.set_ticks([0,0.5,1,1.5,2])
cbar.set_label("Mode occupation", rotation=270)
plt.tight_layout()
# As usual, first define how many qumodes we want, and how many qubits we should use to represent each (equivalent to choosing a cutoff)
num_qumodes = 1
num_qubits_per_qumode = 4
qmr = c2qa.QumodeRegister(num_qumodes, num_qubits_per_qumode)
circuit = c2qa.CVCircuit(qmr)
# First initialize the qumode in Fock state |3>
circuit.cv_initialize(3, qmr[0])
# Let's now apply a displacement gate. Bosonic Qiskit allows a user to specify the gate duration in user-specified units (which
# will be used to calculate the loss probability at each time step). Let's go with a 100ns gate duration.
circuit.cv_d(1.5, qmr[0], duration=100, unit="ns")
# Now set a loss rate -- make it large enough such that we can actually see the loss
photon_loss_rate = 0.02 # This is a loss rate in units of 1/ns
time_unit = "ns"
noise_pass = c2qa.kraus.PhotonLossNoisePass(photon_loss_rates=photon_loss_rate, circuit=circuit, time_unit=time_unit)
# The noise pass can then be passed into simulate
state, result, _ = c2qa.util.simulate(circuit, noise_passes=noise_pass)
# Alternatively, we can animate our circuit using the animate_wigner() function built-into bosonic qiskit.
wigner_filename = "figures/photon_loss.mp4"
c2qa.animate.animate_wigner(
circuit,
animation_segments=200,
# file=wigner_filename,
noise_passes=noise_pass
)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""General spin simulator backend."""
from typing import Union, List, Dict, Any, Optional
import uuid
from fractions import Fraction
import warnings
import time
import datetime
from qiskit.providers.models import BackendConfiguration
from qiskit.providers import Options
from qiskit import QuantumCircuit
from qiskit.result import Result
from qiskit.circuit.measure import Measure
from qiskit_aer import AerJob
from qiskit_cold_atom.spins.spin_circuit_solver import SpinCircuitSolver
from qiskit_cold_atom.spins.base_spin_backend import BaseSpinBackend
from qiskit_cold_atom.circuit_tools import CircuitTools
class SpinSimulator(BaseSpinBackend):
"""A simulator to simulate general spin circuits.
This general spin simulator backend simulates spin circuits with gates that have
generators described by spin Hamiltonians. It computes the statevector and unitary
of a circuit and simulates measurements.
"""
# Default configuration of the backend if the user does not provide one.
__DEFAULT_CONFIGURATION__ = {
"backend_name": "spin_simulator",
"backend_version": "0.0.1",
"n_qubits": None,
"basis_gates": None,
"gates": [],
"local": True,
"simulator": True,
"conditional": False,
"open_pulse": False,
"memory": True,
"max_shots": 1e5,
"coupling_map": None,
"description": "a base simulator for spin circuits. Instead of a qubit, each wire represents a "
"single high-dimensional spin",
}
def __init__(self, config_dict: Optional[Dict[str, Any]] = None, provider=None):
"""
Initialize the backend from a configuration dictionary.
Args:
config_dict: Configuration dictionary of the backend. If None is given
a default is assumed.
"""
if config_dict is None:
config_dict = self.__DEFAULT_CONFIGURATION__
super().__init__(
configuration=BackendConfiguration.from_dict(config_dict), provider=provider
)
@classmethod
def _default_options(cls):
return Options(shots=1)
def _execute(self, data: Dict[str, Any], job_id: str = "") -> Result:
"""
Helper function to execute a job. The circuit and all relevant parameters are
given in the data dict. Performs validation checks on the received circuits
and utilizes the SpinCircuitSolver to perform the numerical simulations.
Args:
data: Data dictionary that that contains the experiments to simulate, given in the shape:
data = {
"num_species": int,
"shots": int,
"seed": int,
"experiments": Dict[str, QuantumCircuit],
}
job_id: The job id assigned by the run method
Returns:
result: A qiskit job result.
"""
# Start timer
start = time.time()
output = {"results": []}
spin = data["spin"]
shots = data["shots"]
seed = data["seed"]
solver = SpinCircuitSolver(spin, shots, seed)
for exp_i, exp_name in enumerate(data["experiments"]):
experiment = data["experiments"][exp_name]
circuit = experiment["circuit"]
# perform compatibility checks with the backend configuration in case gates and supported
# instructions are constrained by the backend's configuration
if self.configuration().gates and self.configuration().supported_instructions:
CircuitTools.validate_circuits(circuits=circuit, backend=self, shots=shots)
# check whether all wires are measured
measured_wires = set()
for inst in circuit.data:
if isinstance(inst[0], Measure):
for wire in inst[1]:
index = circuit.qubits.index(wire)
if index in measured_wires:
warnings.warn(
f"Wire {index} has already been measured, "
f"second measurement is ignored"
)
else:
measured_wires.add(index)
if measured_wires and len(measured_wires) != len(circuit.qubits):
warnings.warn(
f"Number of wires in the circuit ({len(circuit.qubits)}) does not equal the "
f"number of wires with measurement instructions ({len(measured_wires)}). "
f"{self.__class__.__name__} only supports measurement of the entire quantum "
"register which will be performed instead."
)
if not measured_wires:
solver.shots = None
simulation_result = solver(circuit)
output["results"].append(
{
"header": {"name": exp_name, "random_seed": seed},
"shots": shots,
"spin": spin,
"status": "DONE",
"success": True,
}
)
# add the simulation result at the correct place in the result dictionary
output["results"][exp_i]["data"] = simulation_result
output["job_id"] = job_id
output["date"] = datetime.datetime.now().isoformat()
output["backend_name"] = self.name()
output["backend_version"] = self.configuration().backend_version
output["time_taken"] = time.time() - start
output["success"] = True
output["qobj_id"] = None
return Result.from_dict(output)
# pylint: disable=arguments-differ, unused-argument
def run(
self,
circuits: Union[QuantumCircuit, List[QuantumCircuit]],
shots: int = 1000,
spin: Union[float, Fraction] = Fraction(1, 2),
seed: Optional[int] = None,
**run_kwargs,
) -> AerJob:
"""
Run the simulator with a variable length of the individual spins.
Args:
circuits: A list of quantum circuits.
shots: The number of shots to measure.
spin: The spin length of the simulated system which must be a positive
integer or half-integer. Defaults to 1/2 which is equivalent to qubits.
seed: The seed for the simulator.
run_kwargs: Additional keyword arguments that might be passed down when calling
qiskit.execute() which will have no effect on this backend.
Returns:
aer_job: a job object containing the result of the simulation
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
data = {"spin": spin, "shots": shots, "seed": seed, "experiments": {}}
for idx, circuit in enumerate(circuits):
data["experiments"]["experiment_%i" % idx] = {
"circuit": circuit,
}
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._execute, data)
aer_job.submit()
return aer_job
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
import matplotlib.pyplot as plt
from copy import deepcopy
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile, Aer, IBMQ, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
from tqdm.notebook import tqdm
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
import qiskit.quantum_info as qi
from qc_grader.challenges.spring_2022.helpers import generate_XX, generate_YY, generate_disordered_tb_instruction
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
import pylatexenc
import IPython
t = Parameter('t')
XX = generate_XX(t)
YY = generate_YY(t)
from scipy.special import jv
t_test = 20
r = np.linspace(-50,50,101)
gaussian = np.exp(-r**2/t_test) / np.sum(np.exp(-r**2/t_test))
bessel = np.abs(jv(r,2*t_test))**2 / np.sum(np.abs(jv(r,2*t_test))**2)
plt.figure(facecolor='white')
plt.plot(r, gaussian, label=r'Gaussian function')
plt.plot(r, bessel, label=r'Bessel function')
plt.xlabel('Position')
plt.ylabel('Probability density')
plt.legend()
plt.show()
num_qubits = 5 ## DO NOT EDIT
Trot_tb_qr = QuantumRegister(num_qubits)
Trot_tb_qc = QuantumCircuit(Trot_tb_qr, name='Trot')
###EDIT CODE BELOW
for j in [0,2]:
Trot_tb_qc.append(YY, [Trot_tb_qr[j], Trot_tb_qr[j+1]])
Trot_tb_qc.append(XX, [Trot_tb_qr[j], Trot_tb_qr[j+1]])
for i in [1,3]:
Trot_tb_qc.append(YY, [Trot_tb_qr[i], Trot_tb_qr[i+1]])
Trot_tb_qc.append(XX, [Trot_tb_qr[i], Trot_tb_qr[i+1]])
###DO NOT EDIT BELOW
Trot_tb_gate = Trot_tb_qc.to_instruction()
Trot_tb_qc.draw(output='mpl')
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex2a
grade_ex2a(Trot_tb_qc)
delta_t=0.15 # DO NOT EDIT
time_steps=np.arange(1,20,1) # DO NOT EDIT
circuits=[]
for n_steps in time_steps:
qr = QuantumRegister(num_qubits)
cr = ClassicalRegister(num_qubits)
qc = QuantumCircuit(qr,cr)
###EDIT CODE BELOW
qc.x([0])
###DO NOT EDIT BELOW
for _ in range(n_steps):
qc.append(Trot_tb_gate, [i for i in range(num_qubits)])
qc = qc.bind_parameters({t: delta_t})
circuits.append(qc)
from qiskit import transpile
# Use Aer's statevector simulator
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend_sim = Aer.get_backend('statevector_simulator')
probability_density=[]
for circ in tqdm(circuits):
transpiled_circ=transpile(circ, backend_sim, optimization_level=3)
job_sim = backend_sim.run(transpiled_circ)
# Grab the results from the job.
result_sim = job_sim.result()
outputstate = result_sim.get_statevector(transpiled_circ, decimals=5)
ps=[]
###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit)
probs=[]
for i in range(num_qubits):
prob=outputstate.probabilities([i]) # type(..) >> list
probs.append(prob)
for elem in probs:
excited=elem[1]
ps.append(excited)
###DO NOT EDIT BELOW
probability_density.append(ps)
probability_density=np.array(probability_density)
plt.figure(figsize=(3,5), facecolor='white')
plt.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t, probability_density)
plt.xlabel('Qubit index')
plt.ylabel('Time (1/J)')
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex2b
grade_ex2b(probability_density)
from qiskit.tools.monitor import job_monitor
from qiskit import IBMQ
# Loading your IBM Quantum account
IBMQ.load_account()
IBMQ.providers() # see a list of providers you have access to
# Get the special provider assigned to you using information from the output above
hub_name = 'qc-spring-22-4' # e.g. 'qc-spring-22-1'
group_name = 'group-2' # e.g. 'group-2'
project_name = 'recrrGhzxg3VULGQS' # e.g. 'recPdHH04wfWiNHjG'
provider = IBMQ.get_provider(hub=hub_name, group=group_name, project=project_name)
# Get `ibm_nairobi` backend from the provider
backend_name = 'ibm_nairobi'
backend = provider.get_backend(backend_name)
backend # See details of the `ibm_nairobi` quantum system
initial_layout=[0 , 1 , 3 , 5 , 4]
hardware_transpiled_circuits=[]
for circ in circuits:
hardware_circ=deepcopy(circ)
hardware_circ.barrier()
hardware_circ.measure(range(num_qubits), range(num_qubits))
hardware_transpiled_circuits.append(transpile(hardware_circ, backend, initial_layout=initial_layout, optimization_level=3))
shots=1024
job = execute(hardware_transpiled_circuits, backend=backend, shots=shots)
job_monitor(job)
print('Job ID', job.job_id())
qc = QuantumCircuit(5,1)
qc.x([0])
qc.measure(0,0) # Measuring only qubit 0 (q_0) and storing the measurement result in classical bit (a.k.a register) 0.
jobs = execute(qc,backend,shots=1024) # Sending job to ibm_nairobi.
counts = jobs.result().get_counts(qc)
probs = {key:value/shots for key, value in counts.items()}
print(qc)
print(counts)
print(probs)
experiment_results=backend.retrieve_job('629c26b701885c41f6f358c2').result()
i=0
for output in experiment_results.get_counts(): # Doing a for through each measurement (each new experiment).
print(f'output: {type(output)}\n')
print(output, '\n')
#print(output.keys()) # Type >> <class 'dict_keys'>
print(f"Number of Basis states/prob. amp.: {len(output)}.\n")
i+=1
if i == 2:
break
type(experiment_results.get_counts()), len(experiment_results.get_counts())
# There are 19 dictionaries. Each dict. corresponds to an average measurement trial.
for output in experiment_results.get_counts():
for key, value in output.items():
print(key, value)
print('')
print(output.keys())
break
Z = np.random.rand(2, 2)
Z
Z.shape, len(Z)
plt.pcolormesh(Z)
Z.tolist()
plt.pcolormesh(Z.tolist())
experiment_results=job.result()
#experiment_results=backend.retrieve_job('629c26b701885c41f6f358c2').result()
probability_density_exp=[]
for output in experiment_results.get_counts():
ps=[]
###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit)
for key in ['00001', '00010', '00100', '01000', '10000']:
try:
count=float(output.get(key))
prob=(count/shots)
except:
prob=0
ps.append(prob)
###DO NOT EDIT BELOW
probability_density_exp.append(ps)
plt.figure(figsize=(3,5), facecolor='white')
plt.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t, probability_density_exp)
plt.xlabel('Qubit index')
plt.ylabel('Time (1/J)')
beta=(np.sqrt(5)-1)/2 # DO NOT EDIT
AA_patern=np.cos(2*np.pi*beta*np.arange(num_qubits)) # DO NOT EDIT
plt.plot(np.linspace(-0.5,4.5,101), np.cos(2*np.pi*beta*np.linspace(-0.5,4.5,101)), '--')
plt.plot(np.arange(num_qubits), AA_patern, 'o', label=r'$\epsilon_i$')
plt.xlabel('Position')
plt.ylabel('Energy')
plt.legend()
plt.title('Aubry-Andre potential')
plt.show()
Trot_qr_disorder = QuantumRegister(num_qubits)
Trot_qc_disorder = QuantumCircuit(Trot_qr_disorder, name='Trot disorder')
Trot_qc_disorder.append(Trot_tb_gate,[0,1,2,3,4])
deltas=[Parameter('delta_{:d}'.format(idx)) for idx in range(num_qubits)]
###EDIT CODE BELOW (add a parametric disorder to each qubit)
for i in range(0, num_qubits):
Trot_qc_disorder.rz(2*deltas[i]*t,i) # (angles, qubits).
###DO NOT EDIT BELOW
# Convert custom quantum circuit into a gate
Trot_disorder_gate = Trot_qc_disorder.to_instruction()
Trot_qc_disorder.draw(output='mpl')
delta_t=0.15
time_steps=np.arange(1,20,1)
W=2 # DO NOT EDIT
disorders=W*AA_patern # DO NOT EDIT
disorder_circuits=[]
for n_steps in time_steps:
qr = QuantumRegister(num_qubits)
cr = ClassicalRegister(num_qubits)
qc = QuantumCircuit(qr, cr)
qc.x(0)
for _ in range(n_steps):
qc.append(Trot_disorder_gate, [i for i in range(num_qubits)])
qc = qc.bind_parameters({t: delta_t})
qc = qc.bind_parameters({deltas[idx]: disorders[idx] for idx in range(num_qubits)})
disorder_circuits.append(qc)
from qiskit import transpile
# Use Aer's statevector simulator
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend_sim = Aer.get_backend('statevector_simulator')
probability_density_localization=[]
for circ in tqdm(disorder_circuits):
transpiled_circ=transpile(circ, backend_sim, optimization_level=3)
job_sim = backend_sim.run(transpiled_circ)
# Grab the results from the job.
result_sim = job_sim.result()
outputstate = result_sim.get_statevector(transpiled_circ, decimals=5)
ps=[]
###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit)
probs=[]
for i in range(num_qubits):
prob=outputstate.probabilities([i]) # type(..) >> list
probs.append(prob)
for elem in probs:
excited=elem[1]
ps.append(excited)
###DO NOT EDIT BELOW
probability_density_localization.append(ps)
probability_density_localization=np.array(probability_density_localization)
plt.figure(figsize=(3,5), facecolor='white')
plt.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t ,probability_density_localization)
plt.xlabel('Qubit index')
plt.ylabel('Time (1/J)')
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex2c
grade_ex2c(probability_density_localization)
from qiskit.tools.monitor import job_monitor
provider = IBMQ.load_account()
provider = IBMQ.get_provider(hub='qc-spring-22-4', group='group-2', project='recrrGhzxg3VULGQS')
backend = provider.get_backend('ibm_nairobi')
initial_layout=[0 , 1 , 3 , 5 , 4]
hardware_transpiled_circuits_disordered=[]
for circ in disorder_circuits:
hardware_circ=deepcopy(circ)
hardware_circ.barrier()
hardware_circ.measure(range(num_qubits), range(num_qubits))
hardware_transpiled_circuits_disordered.append(transpile(hardware_circ, backend, initial_layout=initial_layout, optimization_level=3))
shots=1024
job_disorder = execute(hardware_transpiled_circuits_disordered, backend=backend, shots=shots)
job_monitor(job_disorder)
print('Job ID', job_disorder.job_id())
disorder_experiment_results=job_disorder.result()
#disorder_experiment_results=backend.retrieve_job('6290b7ce4bb9753402efaa20').result()
disorder_probability_density_exp=[]
for output in disorder_experiment_results.get_counts():
ps=[]
###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit)
for key in ['00001', '00010', '00100', '01000', '10000']:
try:
count=float(output.get(key))
prob=(count/shots)
except:
prob=0
ps.append(prob)
###DO NOT EDIT BELOW
disorder_probability_density_exp.append(ps)
plt.figure(figsize=(3,5), facecolor='white')
plt.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t, disorder_probability_density_exp)
plt.xlabel('Qubit index')
plt.ylabel('Time (1/J)')
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[k] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+=float(weight_matrix[i][j])*float(bitstring[i])*(1-float(bitstring[j]))
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic=qubo_matrix,linear=qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qmsc = 0.0
for k in range(size):
qmsc+=qubo_matrix[j,k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qmsc),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i] * qubo_matrix[j,k] * 0.5, j, k)
# Apply single qubit X - rotations with angle 2beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
measured_cuts = sorted(measured_cuts, reverse = True)
new_size = np.ceil(num_shots*cvar)
for i in range(int(new_size)):
energy += measured_cuts[i]
energy /= new_size
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import ParityMapper
from qiskit_nature.second_q.properties import ParticleNumber
from qiskit_nature.second_q.transformers import ActiveSpaceTransformer
bond_distance = 2.5 # in Angstrom
# specify driver
driver = PySCFDriver(
atom=f"Li 0 0 0; H 0 0 {bond_distance}",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
# specify active space transformation
active_space_trafo = ActiveSpaceTransformer(
num_electrons=problem.num_particles, num_spatial_orbitals=3
)
# transform the electronic structure problem
problem = active_space_trafo.transform(problem)
# construct the parity mapper with 2-qubit reduction
qubit_mapper = ParityMapper(num_particles=problem.num_particles)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms.ground_state_solvers import GroundStateEigensolver
np_solver = NumPyMinimumEigensolver()
np_groundstate_solver = GroundStateEigensolver(qubit_mapper, np_solver)
np_result = np_groundstate_solver.solve(problem)
target_energy = np_result.total_energies[0]
print(np_result)
from qiskit.circuit.library import EfficientSU2
ansatz = EfficientSU2(num_qubits=4, reps=1, entanglement="linear", insert_barriers=True)
ansatz.decompose().draw("mpl", style="iqx")
import numpy as np
from qiskit.utils import algorithm_globals
# fix random seeds for reproducibility
np.random.seed(5)
algorithm_globals.random_seed = 5
from qiskit.algorithms.optimizers import SPSA
optimizer = SPSA(maxiter=100)
initial_point = np.random.random(ansatz.num_parameters)
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.primitives import Estimator
estimator = Estimator()
local_vqe = VQE(
estimator,
ansatz,
optimizer,
initial_point=initial_point,
)
local_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, local_vqe)
local_vqe_result = local_vqe_groundstate_solver.solve(problem)
print(local_vqe_result)
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(group="open") # replace by your runtime provider
backend = provider.get_backend("ibmq_qasm_simulator") # select a backend that supports the runtime
from qiskit_nature.runtime import VQEClient
runtime_vqe = VQEClient(
ansatz=ansatz,
optimizer=optimizer,
initial_point=initial_point,
provider=provider,
backend=backend,
shots=1024,
measurement_error_mitigation=True,
) # use a complete measurement fitter for error mitigation
runtime_vqe_groundstate_solver = GroundStateEigensolver(qubit_mapper, runtime_vqe)
runtime_vqe_result = runtime_vqe_groundstate_solver.solve(problem)
print(runtime_vqe_result)
runtime_result = runtime_vqe_result.raw_result
history = runtime_result.optimizer_history
loss = history["energy"]
import matplotlib.pyplot as plt
plt.rcParams["font.size"] = 14
# plot loss and reference value
plt.figure(figsize=(12, 6))
plt.plot(loss + runtime_vqe_result.nuclear_repulsion_energy, label="Runtime VQE")
plt.axhline(y=target_energy + 0.2, color="tab:red", ls=":", label="Target + 200mH")
plt.axhline(y=target_energy, color="tab:red", ls="--", label="Target")
plt.legend(loc="best")
plt.xlabel("Iteration")
plt.ylabel("Energy [H]")
plt.title("VQE energy");
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit.primitives import Estimator
from qiskit.algorithms.gradients import ParamShiftEstimatorGradient
estimator = Estimator()
ps = ParamShiftEstimatorGradient(estimator)
from qiskit.circuit.library import EfficientSU2
from qiskit.quantum_info import SparsePauliOp
def ising_hamiltonian(num_qubits):
return SparsePauliOp.from_sparse_list(
[("ZZ", [i, i + 1], 1) for i in range(num_qubits - 1)] + [("X", [i], -1) for i in range(num_qubits)],
num_qubits=num_qubits
)
num_qubits = 3
hamiltonian = ising_hamiltonian(num_qubits)
print(hamiltonian)
circuit = EfficientSU2(num_qubits, reps=1).decompose()
print(circuit.draw())
import numpy as np
values = np.random.random(circuit.num_parameters)
gradient = ps.run([circuit], [hamiltonian], [values]).result()
print(gradient.gradients[0])
from qiskit.algorithms.gradients import ReverseEstimatorGradient
reverse = ReverseEstimatorGradient() # classical calculation, not primitive-based!
gradient = reverse.run([circuit], [hamiltonian], [values]).result()
print(gradient.gradients[0])
import time
import numpy as np
from qiskit.circuit.library import EfficientSU2
def time_gradients(num_layers, gradient, num_qubits=5, averages=5):
circuit = EfficientSU2(num_qubits, reps=num_layers).decompose()
hamiltonian = ising_hamiltonian(num_qubits)
values = np.linspace(1, 2, num=circuit.num_parameters)
timings = []
for _ in range(averages):
start = time.time()
__ = gradient.run([circuit], [hamiltonian], [values]).result()
timings.append(time.time() - start)
return np.mean(timings), np.std(timings)
layers = [2, 4, 6, 8, 10]
num_qubits = 5
ps_times = np.array([time_gradients(num_layers, ps) for num_layers in layers])
rev_times = np.array([time_gradients(num_layers, reverse) for num_layers in layers])
import matplotlib.pyplot as plt
num_parameters = (np.array(layers) + 1) * 2 * num_qubits
plt.figure(figsize=(12, 6))
plt.plot(num_parameters, ps_times[:, 0], color="royalblue", label="circuit-based")
plt.fill_between(num_parameters, ps_times[:, 0] - ps_times[:, 1], ps_times[:, 0] + ps_times[:, 1], color="royalblue", alpha=0.2)
plt.plot(num_parameters, rev_times[:, 0], color="seagreen", label="reverse")
plt.fill_between(num_parameters, rev_times[:, 0] - rev_times[:, 1], rev_times[:, 0] + rev_times[:, 1], color="seagreen", alpha=0.2)
plt.title("Gradient benchmark")
plt.xlabel("number of parameters")
plt.ylabel("runtime in seconds");
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import GradientDescent
from qiskit.algorithms.time_evolvers.variational import RealMcLachlanPrinciple
def time_vqe(num_layers, gradient, num_qubits=4):
circuit = EfficientSU2(num_qubits, reps=num_layers).decompose()
hamiltonian = ising_hamiltonian(num_qubits)
optimizer = GradientDescent(maxiter=100)
initial_point = np.zeros(circuit.num_parameters)
vqe = VQE(estimator, circuit, optimizer, gradient=gradient, initial_point=initial_point)
start = time.time()
_ = vqe.compute_minimum_eigenvalue(hamiltonian)
took = time.time() - start
print("done in", took)
return took
num_qubits = 4
layers = [2, 4, 6, 8, 10, 12]
num_parameters = (np.array(layers) + 1) * 2 * num_qubits
vqe_ps_times = np.array([time_vqe(num_layers, ps) for num_layers in layers])
# vqe_ps_times = np.load("vqe_ps_times.npy")
vqe_rev_times = np.array([time_vqe(num_layers, reverse) for num_layers in layers])
# vqe_rev_times = np.load("vqe_rev_times.npy")
plt.figure(figsize=(12, 6))
plt.plot(num_parameters, vqe_ps_times / 60, color="royalblue", marker="o", label="circuit-based")
plt.plot(num_parameters, vqe_rev_times / 60, color="seagreen", marker="v", label="reverse")
plt.legend(loc="best")
plt.title("VQE with 100 steps")
plt.xlabel("number of parameters")
plt.ylabel("time in minutes");
from qiskit.algorithms.gradients import ReverseQGT
from qiskit.algorithms.time_evolvers import VarQRTE, TimeEvolutionProblem
from qiskit.algorithms.time_evolvers.variational import RealMcLachlanPrinciple
def time_varqte(num_layers, estimator, gradient, qgt, num_qubits=5, averages=1):
circuit = EfficientSU2(num_qubits, reps=num_layers).decompose()
hamiltonian = ising_hamiltonian(num_qubits)
problem = TimeEvolutionProblem(hamiltonian, time=1)#, aux_operators=[hamiltonian])
principle = RealMcLachlanPrinciple(qgt, gradient)
initial_values = np.zeros(circuit.num_parameters)
varqte = VarQRTE(circuit, initial_values, principle, estimator=estimator, num_timesteps=100)
start = time.time()
_ = varqte.evolve(problem)
took = time.time() - start
print("done in", took)
return took
from qiskit.algorithms.gradients import LinCombEstimatorGradient, LinCombQGT
num_qubits = 4
layers = [2, 4, 6, 8]
num_parameters = (np.array(layers) + 1) * 2 * num_qubits
lcu_qgt = LinCombQGT(estimator)
lcu = LinCombEstimatorGradient(estimator)
# varqte_times = np.array([time_varqte(num_layers, estimator, lcu, lcu_qgt) for num_layers in layers])
varqte_times = np.load("varqte_times.npy")
rev_qgt = ReverseQGT()
# revqte_times = np.array([time_varqte(num_layers, estimator, reverse, rev_qgt) for num_layers in layers])
revqte_times = np.load("revqte_times.npy")
plt.figure(figsize=(12, 6))
plt.plot(num_parameters[:len(varqte_times)], varqte_times / 60, color="royalblue", marker="o", label="circuit-based")
plt.plot(num_parameters, revqte_times / 60, color="seagreen", marker="v", label="reverse")
plt.legend(loc="best")
plt.title("VarQTE with 100 timesteps")
plt.xlabel("number of parameters")
plt.ylabel("time in minutes");
|
https://github.com/mcoggins96/Quantum-Computing-UK-Repository
|
mcoggins96
|
print('\nGrovers Algorithm')
print('------------------\n')
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute,IBMQ
import math
IBMQ.enable_account('Enter API token')
provider = IBMQ.get_provider(hub='ibm-q')
pi = math.pi
q = QuantumRegister(4,'q')
c = ClassicalRegister(4,'c')
qc = QuantumCircuit(q,c)
print('\nInitialising Circuit...\n')
### Initialisation ###
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
print('\nPreparing Oracle circuit....\n')
### 0000 Oracle ###
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
'''
### 0001 Oracle ###
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
'''
'''
### 0010 Oracle ###
qc.x(q[0])
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[2])
qc.x(q[3])
'''
'''
### 0011 Oracle ###
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[2])
qc.x(q[3])
'''
'''
### 0100 Oracle ###
qc.x(q[0])
qc.x(q[1])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[3])
'''
'''
### 0101 Oracle ###
qc.x(q[1])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[1])
qc.x(q[3])
'''
'''
### 0110 Oracle ###
qc.x(q[0])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[3])
'''
'''
### 0111 Oracle ###
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[3])
'''
'''
### 1000 Oracle ###
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
'''
'''
### 1001 Oracle ###
qc.x(q[1])
qc.x(q[2])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[1])
qc.x(q[2])
'''
'''
### 1010 Oracle ###
qc.x(q[0])
qc.x(q[2])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[2])
'''
'''
### 1011 Oracle ###
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[3])
'''
'''
### 1100 Oracle ###
qc.x(q[0])
qc.x(q[1])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
'''
'''
### 1101 Oracle ###
qc.x(q[1])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[1])
'''
'''
### 1110 Oracle ###
qc.x(q[0])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
'''
'''
###1111 Oracle###
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
'''
print('\nPreparing Amplification circuit....\n')
#### Amplification ####
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.cu1(pi/4, q[0], q[3])
qc.cx(q[0], q[1])
qc.cu1(-pi/4, q[1], q[3])
qc.cx(q[0], q[1])
qc.cu1(pi/4, q[1], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.cx(q[1], q[2])
qc.cu1(-pi/4, q[2], q[3])
qc.cx(q[0], q[2])
qc.cu1(pi/4, q[2], q[3])
qc.x(q[0])
qc.x(q[1])
qc.x(q[2])
qc.x(q[3])
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
### Measurment ###
qc.barrier(q)
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.measure(q[2], c[2])
qc.measure(q[3], c[3])
backend = provider.get_backend('ibmq_qasm_simulator')
print('\nExecuting job....\n')
job = execute(qc, backend, shots=100)
result = job.result()
counts = result.get_counts(qc)
print('RESULT: ',counts,'\n')
print('Press any key to close')
input()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc)
|
https://github.com/klebermagno/Quantum-Algorithm
|
klebermagno
|
from qiskit import ClassicalRegister, QuantumRegister
from qiskit import QuantumCircuit, execute
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
job_sim = execute(qc, "local_qasm_simulator")
sim_result = job_sim.result()
print(sim_result.get_counts(qc))
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
from qiskit import QuantumCircuit
from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle
class BernsteinVazirani:
@classmethod
def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit:
# Construct secret number oracle
secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode)
num_of_qubits = secret_number_oracle.num_qubits
# Construct circuit according to the length of the number
dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Apply H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_before_oracle.h(qubit)
# Put output qubit in state |->
dj_circuit_before_oracle.x(num_of_qubits - 1)
dj_circuit_before_oracle.h(num_of_qubits - 1)
dj_circuit += dj_circuit_before_oracle
# Add oracle
dj_circuit += secret_number_oracle
dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Repeat H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_after_oracle.h(qubit)
dj_circuit_after_oracle.barrier()
# Measure
for i in range(num_of_qubits - 1):
dj_circuit_after_oracle.measure(i, i)
dj_circuit += dj_circuit_after_oracle
if not eval_mode:
print("Circuit before the oracle\n")
print(QuantumCircuit.draw(dj_circuit_before_oracle))
print("Circuit after the oracle\n")
print(QuantumCircuit.draw(dj_circuit_after_oracle))
print(dj_circuit)
return dj_circuit
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import numpy as np
from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import plot_histogram, plot_state_city
from qiskit import Aer, IBMQ
def increment_gate(qc, q, qcoin):
qc.ccx(qcoin, q[0], q[1])
qc.cx(qcoin, q[0])
return qc
def decrement_gate(qc, q, qcoin):
qc.x(q)
qc.x(qcoin)
increment_gate(qc, q, qcoin)
qc.x(qcoin)
qc.x(q)
return qc
n = 2
qnodes = QuantumRegister(n,'qc')
qcoin = QuantumRegister(1,'qcoin')
cnodes = ClassicalRegister(n,'cr')
qc = QuantumCircuit(qnodes, qcoin, cnodes)
# Apply Coin
qc.h(qcoin[0])
# Initial state
qc.x(0)
increment_gate(qc, qnodes, qcoin)
decrement_gate(qc, qnodes, qcoin)
qc.measure(qnodes, cnodes)
qc.draw('mpl')
# Single Shot, just to test!
import matplotlib as mpl
backend = Aer.get_backend("qasm_simulator")
result = execute(qc, backend=backend).result()
plot_histogram(result.get_counts())
# Here goes the magic
n = 2
qnodes = QuantumRegister(n,'qc')
qcoin = QuantumRegister(1,'qcoin')
cnodes = ClassicalRegister(n,'cr')
qc = QuantumCircuit(qnodes, qcoin, cnodes)
steps = 51
def runQWC(qc, steps):
for i in range(steps):
qc.h(qcoin[0])
increment_gate(qc, qnodes, qcoin)
decrement_gate(qc, qnodes, qcoin)
qc.measure(qnodes, cnodes)
return qc
qc = runQWC(qc, steps)
backend = Aer.get_backend("qasm_simulator")
result = execute(qc, backend=backend).result()
plot_histogram(result.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import NormalDistribution
# can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example.
A = np.eye(2)
b = np.zeros(2)
# specify the number of qubits that are used to represent the different dimenions of the uncertainty model
num_qubits = [2, 2]
# specify the lower and upper bounds for the different dimension
low = [0, 0]
high = [0.12, 0.24]
mu = [0.12, 0.24]
sigma = 0.01 * np.eye(2)
# construct corresponding distribution
bounds = list(zip(low, high))
u = NormalDistribution(num_qubits, mu, sigma, bounds)
# plot contour of probability density function
x = np.linspace(low[0], high[0], 2 ** num_qubits[0])
y = np.linspace(low[1], high[1], 2 ** num_qubits[1])
z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1])
plt.contourf(x, y, z)
plt.xticks(x, size=15)
plt.yticks(y, size=15)
plt.grid()
plt.xlabel("$r_1$ (%)", size=15)
plt.ylabel("$r_2$ (%)", size=15)
plt.colorbar()
plt.show()
# specify cash flow
cf = [1.0, 2.0]
periods = range(1, len(cf) + 1)
# plot cash flow
plt.bar(periods, cf)
plt.xticks(periods, size=15)
plt.yticks(size=15)
plt.grid()
plt.xlabel("periods", size=15)
plt.ylabel("cashflow ($)", size=15)
plt.show()
# estimate real value
cnt = 0
exact_value = 0.0
for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])):
for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])):
prob = u.probabilities[cnt]
for t in range(len(cf)):
# evaluate linear approximation of real value w.r.t. interest rates
exact_value += prob * (
cf[t] / pow(1 + b[t], t + 1)
- (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2)
)
cnt += 1
print("Exact value: \t%.4f" % exact_value)
# specify approximation factor
c_approx = 0.125
# create fixed income pricing application
from qiskit_finance.applications.estimation import FixedIncomePricing
fixed_income = FixedIncomePricing(
num_qubits=num_qubits,
pca_matrix=A,
initial_interests=b,
cash_flow=cf,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=u,
)
fixed_income._objective.draw()
fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits)
# load probability distribution
fixed_income_circ.append(u, range(u.num_qubits))
# apply function
fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits))
fixed_income_circ.draw()
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
# construct amplitude estimation
problem = fixed_income.to_estimation_problem()
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % exact_value)
print("Estimated value: \t%.4f" % (fixed_income.interpret(result)))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
|
hamburgerguy
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
ghz.draw(output='mpl')
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2023 Qiskit on IQM developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This file is an example of using Qiskit on IQM to execute a simple but non-trivial quantum circuit on an IQM quantum
computer. See the Qiskit on IQM user guide for instructions:
https://iqm-finland.github.io/qiskit-on-iqm/user_guide.html
"""
import argparse
from qiskit import QuantumCircuit, execute
from iqm.qiskit_iqm.iqm_provider import IQMProvider
def bell_measure(server_url: str) -> dict[str, int]:
"""Execute a circuit that prepares and measures a Bell state.
Args:
server_url: URL of the IQM Cortex server used for execution
Returns:
a mapping of bitstrings representing qubit measurement results to counts for each result
"""
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
return execute(circuit, IQMProvider(server_url).get_backend(), shots=1000).result().get_counts()
if __name__ == '__main__':
argparser = argparse.ArgumentParser()
argparser.add_argument(
'--cortex_server_url',
help='URL of the IQM Cortex server',
default='https://demo.qc.iqm.fi/cocos',
)
print(bell_measure(argparser.parse_args().cortex_server_url))
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Isometry tests."""
import unittest
import numpy as np
from ddt import ddt, data
from qiskit.quantum_info.random import random_unitary
from qiskit import BasicAer
from qiskit import QuantumCircuit
from qiskit import QuantumRegister
from qiskit import execute
from qiskit.test import QiskitTestCase
from qiskit.compiler import transpile
from qiskit.quantum_info import Operator
from qiskit.extensions.quantum_initializer.isometry import Isometry
@ddt
class TestIsometry(QiskitTestCase):
"""Qiskit isometry tests."""
@data(
np.eye(2, 2),
random_unitary(2, seed=868540).data,
np.eye(4, 4),
random_unitary(4, seed=16785).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=660477).data,
np.eye(4, 4)[:, np.random.RandomState(seed=719010).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=544326).permutation(8)],
random_unitary(8, seed=247924).data[:, 0:4],
random_unitary(8, seed=765720).data,
random_unitary(16, seed=278663).data,
random_unitary(16, seed=406498).data[:, 0:8],
)
def test_isometry(self, iso):
"""Tests for the decomposition of isometries from m to n qubits"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
num_q_input = int(np.log2(iso.shape[1]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
qc.isometry(iso, q[:num_q_input], q[num_q_input:])
# Verify the circuit can be decomposed
self.assertIsInstance(qc.decompose(), QuantumCircuit)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
iso_from_circuit = unitary[::, 0 : 2**num_q_input]
iso_desired = iso
self.assertTrue(np.allclose(iso_from_circuit, iso_desired))
@data(
np.eye(2, 2),
random_unitary(2, seed=99506).data,
np.eye(4, 4),
random_unitary(4, seed=673459).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=124090).data,
np.eye(4, 4)[:, np.random.RandomState(seed=889848).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=94795).permutation(8)],
random_unitary(8, seed=986292).data[:, 0:4],
random_unitary(8, seed=632121).data,
random_unitary(16, seed=623107).data,
random_unitary(16, seed=889326).data[:, 0:8],
)
def test_isometry_tolerance(self, iso):
"""Tests for the decomposition of isometries from m to n qubits with a custom tolerance"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
num_q_input = int(np.log2(iso.shape[1]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
# Compute isometry with custom tolerance
qc.isometry(iso, q[:num_q_input], q[num_q_input:], epsilon=1e-3)
# Verify the circuit can be decomposed
self.assertIsInstance(qc.decompose(), QuantumCircuit)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
iso_from_circuit = unitary[::, 0 : 2**num_q_input]
self.assertTrue(np.allclose(iso_from_circuit, iso))
@data(
np.eye(2, 2),
random_unitary(2, seed=272225).data,
np.eye(4, 4),
random_unitary(4, seed=592640).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=714210).data,
np.eye(4, 4)[:, np.random.RandomState(seed=719934).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=284469).permutation(8)],
random_unitary(8, seed=656745).data[:, 0:4],
random_unitary(8, seed=583813).data,
random_unitary(16, seed=101363).data,
random_unitary(16, seed=583429).data[:, 0:8],
)
def test_isometry_inverse(self, iso):
"""Tests for the inverse of isometries from m to n qubits"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
qc.append(Isometry(iso, 0, 0), q)
qc.append(Isometry(iso, 0, 0).inverse(), q)
result = Operator(qc)
np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0]))
if __name__ == "__main__":
unittest.main()
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.visualization import *
import matplotlib.pyplot as plt
from qutip import *
qc = QuantumCircuit(2)
qc.h(0)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]])
I = np.eye(2)
np.kron(I,H)
qc = QuantumCircuit(2)
qc.h(1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]])
I = np.eye(2)
np.kron(H,I)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.h(0)
qc.h(1)
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]])
np.kron(H,H)
qc = QuantumCircuit(2)
qc.barrier()
qc0 = qc.copy()
qc.h(0)
qc.x(1)
qc.barrier()
qc1 = qc.copy()
qc.y(0)
qc.h(1)
qc.barrier()
qc2 = qc.copy()
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
H = np.array([[ 0.707+0.j, 0.707-0.j],[ 0.707+0.j, -0.707+0.j]])
X = sigmax()
Y = sigmay()
XKH = np.kron(X,H)
HKY = np.kron(H,Y)
np.dot(HKY,XKH)
backend = Aer.get_backend('statevector_simulator')
qc_vec = []
for qc in [qc0,qc1,qc2]:
out = execute(qc,backend).result().get_statevector()
qc_vec.append(out)
print(out)
qca = QuantumCircuit(1)
qca.barrier()
qca0 = qca.copy()
qca.h(0)
qca.barrier()
qca1 = qca.copy()
qca.y(0)
qca.barrier()
qca2 = qca.copy()
qca.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
qca_vec = []
for qc in [qca0,qca1,qca2]:
out = execute(qc,backend).result().get_statevector()
qca_vec.append(out)
print(out)
qcb = QuantumCircuit(1)
qcb.barrier()
qcb0 = qcb.copy()
qcb.x(0)
qcb.barrier()
qcb1 = qcb.copy()
qcb.h(0)
qcb.barrier()
qcb2 = qcb.copy()
qcb.draw(output='mpl')
backend = Aer.get_backend('statevector_simulator')
qcb_vec = []
for qc in [qcb0,qcb1,qcb2]:
out = execute(qc,backend).result().get_statevector()
qcb_vec.append(out)
print(out)
for qcv,qcav,qcbv in zip(qc_vec,qca_vec,qcb_vec):
print(qcv,"|", np.kron(qcbv,qcav))
|
https://github.com/jwalaQ/my-qiskit-textbook-solutions
|
jwalaQ
|
from qiskit import QuantumCircuit,Aer,execute
from qiskit.circuit import Gate
from math import pi,sqrt
qc = QuantumCircuit(2)
qc.x(0)
qc.h([0,1])
qc.barrier()
qc.h([0,1])
qc.cx(0,1)
qc.cx(1,0)
qc.cx(0,1)
qc.h([0,1])
qc.draw('mpl')
backend_s = Aer.get_backend('statevector_simulator')
job = execute(qc,backend_s).result()
sv = job.get_statevector()
from qiskit_textbook.tools import array_to_latex
array_to_latex(sv)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
# !pip install --upgrade pip
# !pip uninstall tensorflow --y
# !pip install tensorflow
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
# load csv file
import pandas as pd
# numpy to the seed
import numpy as np
# load csv fileframework to neural networks
import tensorflow as tf
#Method forthe neural network
from keras.regularizers import l2
from keras.models import Sequential
from keras.layers import Dense, Dropout
#save as image the model summary
from keras.utils.vis_utils import plot_model
# librariesto plot
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.preprocessing import StandardScaler
# demonstration of calculating metrics for a neural network model using sklearn
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import roc_auc_score
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
data_train = pd.read_csv("fair_train.csv")
X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values
data_test = pd.read_csv("classic_test.csv")
X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values
(X_train.shape, y_train.shape),(X_test.shape, y_test.shape)
np.random.seed(123)
tf.random.set_seed(123)
scale = StandardScaler()
scale.fit(X_train)
X_train_std = scale.transform(X_train)
X_test_std = scale.transform(X_test)
X_train_std[1], y_train[1]
model = Sequential()
model.add(Dense(25, input_dim=16, activation='relu', kernel_regularizer=l2(1e-6),kernel_initializer="glorot_normal"))
model.add(Dropout(0.5))
model.add(Dense(8, activation='relu',kernel_regularizer=l2(1e-6), kernel_initializer="glorot_normal"))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid',kernel_regularizer=l2(1e-6), kernel_initializer="glorot_normal"))
plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)
# Compile model
auc = tf.keras.metrics.AUC()
model.compile(loss='binary_crossentropy', optimizer="Adam", metrics=['accuracy',auc])
model_history = model.fit(X_train_std, y_train, epochs=100,
batch_size=32,
validation_split=0.2, shuffle=True)
train_pred = model.predict(X_train_std)
test_pred = model.predict(X_test_std)
y_train_pred = (model.predict(X_train_std) > 0.5).astype("int32")
y_test_pred = (model.predict(X_test_std) > 0.5).astype("int32")
accuracy = accuracy_score(y_train, y_train_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_train, y_train_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_train, y_train_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_train, y_train_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_train, y_train_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_train, y_train_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
train_matrix = confusion_matrix(y_train, y_train_pred)
print(train_matrix)
ax = sns.heatmap(train_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
plt.show()
accuracy = accuracy_score(y_test, y_test_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_test, y_test_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_test, y_test_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test, y_test_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_test, y_test_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_test, y_test_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
test_matrix = confusion_matrix(y_test, y_test_pred)
print(test_matrix)
ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import pylab
from qiskit_chemistry import QiskitChemistry
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': '', 'basis': 'sto3g'},
'operator': {'name': 'hamiltonian', 'qubit_mapping': 'parity',
'two_qubit_reduction': True, 'freeze_core': True, 'orbital_reduction': []},
'algorithm': {'name': 'ExactEigensolver'}
}
molecule = 'H .0 .0 -{0}; Be .0 .0 .0; H .0 .0 {0}'
reductions = [[], [-2, -1], [-3, -2], [-4, -3], [-1], [-2], [-3], [-4]]
pts = [x * 0.1 for x in range(6, 20)]
pts += [x * 0.25 for x in range(8, 16)]
pts += [4.0]
energies = np.empty([len(reductions), len(pts)])
distances = np.empty(len(pts))
print('Processing step __', end='')
for i, d in enumerate(pts):
print('\b\b{:2d}'.format(i), end='', flush=True)
qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d)
for j in range(len(reductions)):
qiskit_chemistry_dict['operator']['orbital_reduction'] = reductions[j]
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
energies[j][i] = result['energy']
distances[i] = d
print(' --- complete')
print('Distances: ', distances)
print('Energies:', energies)
pylab.rcParams['figure.figsize'] = (12, 8)
for j in range(len(reductions)):
pylab.plot(distances, energies[j], label=reductions[j])
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('BeH2 Ground State Energy')
pylab.legend(loc='upper right')
pylab.rcParams['figure.figsize'] = (12, 8)
for j in range(len(reductions)):
pylab.plot(distances, np.subtract(energies[j], energies[0]), label=reductions[j])
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('Energy difference compared to no reduction []')
pylab.legend(loc='upper left')
pylab.rcParams['figure.figsize'] = (6, 4)
for j in range(1, len(reductions)):
pylab.plot(distances, np.subtract(energies[j], energies[0]), color=[1.0, 0.6, 0.2], label=reductions[j])
pylab.ylim(0, 0.4)
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('Energy difference compared to no reduction []')
pylab.legend(loc='upper left')
pylab.show()
e_nofreeze = np.empty(len(pts))
qiskit_chemistry_dict['operator']['orbital_reduction'] = []
qiskit_chemistry_dict['operator']['freeze_core'] = False
for i, d in enumerate(pts):
print('\b\b{:2d}'.format(i), end='', flush=True)
qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d)
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
e_nofreeze[i] = result['energy']
print(e_nofreeze)
pylab.rcParams['figure.figsize'] = (8, 6)
pylab.plot(distances, energies[0], label='Freeze Core: True')
pylab.plot(distances, e_nofreeze, label='Freeze Core: False')
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('Energy difference, no reduction [], freeze core true/false')
pylab.legend(loc='upper right')
pylab.show()
pylab.title('Energy difference of freeze core True from False')
pylab.plot(distances, np.subtract(energies[0], e_nofreeze), label='Freeze Core: False')
pylab.show()
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the DenseLayout pass"""
import unittest
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit import Parameter, Qubit
from qiskit.circuit.library import CXGate, UGate, ECRGate, RZGate
from qiskit.transpiler import CouplingMap, Target, InstructionProperties, TranspilerError
from qiskit.transpiler.passes import DenseLayout
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeTokyo
from qiskit.transpiler.passes.layout.dense_layout import _build_error_matrix
class TestDenseLayout(QiskitTestCase):
"""Tests the DenseLayout pass"""
def setUp(self):
super().setUp()
self.cmap20 = FakeTokyo().configuration().coupling_map
self.target_19 = Target()
rng = np.random.default_rng(12345)
instruction_props = {
edge: InstructionProperties(
duration=rng.uniform(1e-7, 1e-6), error=rng.uniform(1e-4, 1e-3)
)
for edge in CouplingMap.from_heavy_hex(3).get_edges()
}
self.target_19.add_instruction(CXGate(), instruction_props)
def test_5q_circuit_20q_coupling(self):
"""Test finds dense 5q corner in 20q coupling map."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 11)
self.assertEqual(layout[qr[1]], 10)
self.assertEqual(layout[qr[2]], 6)
self.assertEqual(layout[qr[3]], 5)
self.assertEqual(layout[qr[4]], 0)
def test_6q_circuit_20q_coupling(self):
"""Test finds dense 5q corner in 20q coupling map."""
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0[0], qr1[2])
circuit.cx(qr1[1], qr0[2])
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr0[0]], 11)
self.assertEqual(layout[qr0[1]], 10)
self.assertEqual(layout[qr0[2]], 6)
self.assertEqual(layout[qr1[0]], 5)
self.assertEqual(layout[qr1[1]], 1)
self.assertEqual(layout[qr1[2]], 0)
def test_5q_circuit_19q_target_with_noise(self):
"""Test layout works finds a dense 5q subgraph in a 19q heavy hex target."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(target=self.target_19)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 9)
self.assertEqual(layout[qr[1]], 3)
self.assertEqual(layout[qr[2]], 11)
self.assertEqual(layout[qr[3]], 15)
self.assertEqual(layout[qr[4]], 4)
def test_5q_circuit_19q_target_without_noise(self):
"""Test layout works finds a dense 5q subgraph in a 19q heavy hex target with no noise."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
instruction_props = {edge: None for edge in CouplingMap.from_heavy_hex(3).get_edges()}
noiseless_target = Target()
noiseless_target.add_instruction(CXGate(), instruction_props)
pass_ = DenseLayout(target=noiseless_target)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 1)
self.assertEqual(layout[qr[1]], 13)
self.assertEqual(layout[qr[2]], 0)
self.assertEqual(layout[qr[3]], 9)
self.assertEqual(layout[qr[4]], 3)
def test_ideal_target_no_coupling(self):
"""Test pass fails as expected if a target without edge constraints exists."""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
target = Target(num_qubits=19)
target.add_instruction(CXGate())
layout_pass = DenseLayout(target=target)
with self.assertRaises(TranspilerError):
layout_pass.run(dag)
def test_target_too_small_for_circuit(self):
"""Test error is raised when target is too small for circuit."""
target = Target()
target.add_instruction(
CXGate(), {edge: None for edge in CouplingMap.from_line(3).get_edges()}
)
dag = circuit_to_dag(QuantumCircuit(5))
layout_pass = DenseLayout(target=target)
with self.assertRaises(TranspilerError):
layout_pass.run(dag)
def test_19q_target_with_noise_error_matrix(self):
"""Test the error matrix construction works for a just cx target."""
expected_error_mat = np.zeros((19, 19))
for qargs, props in self.target_19["cx"].items():
error = props.error
expected_error_mat[qargs[0]][qargs[1]] = error
error_mat = _build_error_matrix(
self.target_19.num_qubits,
{i: i for i in range(self.target_19.num_qubits)},
target=self.target_19,
)[0]
np.testing.assert_array_equal(expected_error_mat, error_mat)
def test_multiple_gate_error_matrix(self):
"""Test error matrix ona small target with multiple gets on each qubit generates"""
target = Target(num_qubits=3)
phi = Parameter("phi")
lam = Parameter("lam")
theta = Parameter("theta")
target.add_instruction(
RZGate(phi), {(i,): InstructionProperties(duration=0, error=0) for i in range(3)}
)
target.add_instruction(
UGate(theta, phi, lam),
{(i,): InstructionProperties(duration=1e-7, error=1e-2) for i in range(3)},
)
cx_props = {
(0, 1): InstructionProperties(error=1e-3),
(0, 2): InstructionProperties(error=1e-3),
(1, 0): InstructionProperties(error=1e-3),
(1, 2): InstructionProperties(error=1e-3),
(2, 0): InstructionProperties(error=1e-3),
(2, 1): InstructionProperties(error=1e-3),
}
target.add_instruction(CXGate(), cx_props)
ecr_props = {
(0, 1): InstructionProperties(error=2e-2),
(1, 2): InstructionProperties(error=2e-2),
(2, 0): InstructionProperties(error=2e-2),
}
target.add_instruction(ECRGate(), ecr_props)
expected_error_matrix = np.array(
[
[1e-2, 2e-2, 1e-3],
[1e-3, 1e-2, 2e-2],
[2e-2, 1e-3, 1e-2],
]
)
error_mat = _build_error_matrix(
target.num_qubits, {i: i for i in range(target.num_qubits)}, target=target
)[0]
np.testing.assert_array_equal(expected_error_matrix, error_mat)
def test_5q_circuit_20q_with_if_else(self):
"""Test layout works finds a dense 5q subgraph in a 19q heavy hex target."""
qr = QuantumRegister(5, "q")
cr = ClassicalRegister(5)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
false_body = QuantumCircuit(qr, cr)
true_body.cx(qr[0], qr[3])
true_body.cx(qr[3], qr[4])
false_body.cx(qr[3], qr[1])
false_body.cx(qr[0], qr[2])
circuit.if_else((cr, 0), true_body, false_body, qr, cr)
circuit.cx(0, 4)
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[qr[0]], 11)
self.assertEqual(layout[qr[1]], 10)
self.assertEqual(layout[qr[2]], 6)
self.assertEqual(layout[qr[3]], 5)
self.assertEqual(layout[qr[4]], 0)
def test_loose_bit_circuit(self):
"""Test dense layout works with loose bits outside a register."""
bits = [Qubit() for _ in range(5)]
circuit = QuantumCircuit()
circuit.add_bits(bits)
circuit.h(3)
circuit.cx(3, 4)
circuit.cx(3, 2)
circuit.cx(3, 0)
circuit.cx(3, 1)
dag = circuit_to_dag(circuit)
pass_ = DenseLayout(CouplingMap(self.cmap20))
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual(layout[bits[0]], 11)
self.assertEqual(layout[bits[1]], 10)
self.assertEqual(layout[bits[2]], 6)
self.assertEqual(layout[bits[3]], 5)
self.assertEqual(layout[bits[4]], 0)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
# required imports:
from qiskit.visualization import array_to_latex
from qiskit.quantum_info import Statevector, random_statevector
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, CXGate
import numpy as np
ket0 = [[1],[0]]
array_to_latex(ket0)
bra0 = [1,0]
array_to_latex(bra0)
ket1 = [[0],[1]]# put your answer answer here for |1⟩
bra1 = [0,1]# put answer here for ⟨1|
from qc_grader.challenges.qgss_2023 import grade_lab1_ex1
grade_lab1_ex1([ket1, bra1])
sv_bra0 = Statevector(bra0)
sv_bra0
sv_bra0.draw('latex')
sv_eq = Statevector([1/2, 3/4, 4/5, 6/8])
sv_eq.draw('latex')
sv_eq.is_valid()
from math import sqrt
sv_valid = Statevector([1/sqrt(2),1/sqrt(2)])
sv_valid.is_valid()# create your statevector here
from qc_grader.challenges.qgss_2023 import grade_lab1_ex2
grade_lab1_ex2(sv_valid)
op_bra0 = Operator(bra0)
op_bra0
op_ket0 = Operator(ket0)
op_bra0.tensor(op_ket0)
braket = np.dot(op_bra0,op_ket0)
array_to_latex(braket)
ketbra = np.outer(ket0,bra0)
array_to_latex(ketbra)
braket = np.dot(op_bra0,op_ket0)
array_to_latex(braket)
bra1ket0 = np.dot(bra1, ket0)# put your answer for ⟨1|0⟩ here
bra0ket1 = np.dot(bra0, ket1) # put your answer for ⟨0|1⟩ here
bra1ket1 = np.dot(bra1, ket1)# put your answer for ⟨1|1⟩ here
ket1bra0 = np.outer(ket1, bra0)# put your answer for |1⟩⟨0| here
ket0bra1 = np.outer(ket0, bra1)# put your answer for |0⟩⟨1| here
ket1bra1 = np.outer(ket1, bra1)# put your answer for |1⟩⟨1| here
from qc_grader.challenges.qgss_2023 import grade_lab1_ex3
grade_lab1_ex3([bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1])
np.dot(bra1, ket0)
# add or remove your answer from this list
answer = ['a']
from qc_grader.challenges.qgss_2023 import grade_lab1_ex4
grade_lab1_ex4(answer)
m1 = Operator([[1,1],[0,0]])
array_to_latex(m1)
m3 = Operator([[0,1],[1,0]])
array_to_latex(m3)
array_to_latex(m1@ket0)
m2 = Operator([[1, 0],
[0, 1]])
# create an operator for m2 here
m4 = Operator([[0, 0],
[1, 1]])# create and operator for m4 here
from qc_grader.challenges.qgss_2023 import grade_lab1_ex5
grade_lab1_ex5([m2, m4])
cnot = CXGate()
array_to_latex(cnot)
m3.is_unitary()
random = Operator(np.array([[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, 0.44607116+0.50778085j,
-0.14128434-0.1523741j ],
[ 0.16855994+0.12151822j, 0.55868196+0.38038841j, -0.12151822+0.16855994j,
-0.38038841+0.55868196j],
[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, -0.44607116-0.50778085j,
0.14128434+0.1523741j ],
[ 0.16855994+0.12151822j, 0.55868196+0.38038841j, 0.12151822-0.16855994j,
0.38038841-0.55868196j]]))
random.is_unitary()
non_unitary_op = Operator(np.array([[1/2,9],[9/5,2]]))# create your operator here
non_unitary_op.is_unitary()
from qc_grader.challenges.qgss_2023 import grade_lab1_ex6
grade_lab1_ex6(non_unitary_op)
pauli_x = Pauli('X')
array_to_latex(pauli_x)
pauli_y = Pauli('Y')
array_to_latex(pauli_y)
pauli_z = Pauli('Z')
array_to_latex(pauli_z)
op_x = Operator(pauli_x)
op_x
op_new = np.dot(op_x,ket0)
array_to_latex(op_new)
result = np.dot(Operator(pauli_z), ket1)# do your operations here
from qc_grader.challenges.qgss_2023 import grade_lab1_ex7
grade_lab1_ex7(result)
hadamard = HGate()
array_to_latex(hadamard)
hop = Operator(hadamard)
hop.is_unitary()
bell = QuantumCircuit(2)
bell.h(0) # apply an H gate to the circuit
bell.cx(0,1) # apply a CNOT gate to the circuit
bell.draw(output="mpl")
bell_op = Operator(bell)
array_to_latex(bell_op)
ghz = QuantumCircuit(3)
##############################
# add gates to your circuit here
ghz.h(0)
ghz.cx(0,1)
ghz.cx(1,2)
##############################
ghz.draw(output='mpl')
from qc_grader.challenges.qgss_2023 import grade_lab1_ex8
grade_lab1_ex8(ghz)
plus_state = Statevector.from_label("+")
plus_state.draw('latex')
plus_state
plus_state.probabilities_dict()
# run this cell multiple times to show collapsing into one state or the other
res = plus_state.measure()
res
qc = QuantumCircuit(1,1)
qc.h(0)
qc.measure(0, 0)
qc.draw(output="mpl")
sv_bell = Statevector([np.sqrt(1/2), 0, 0, np.sqrt(1/2)])
sv_bell.draw('latex')
sv_bell.probabilities_dict()
sv_bell = Statevector([np.sqrt(1/2), 0, 0, - np.sqrt(1/2)])
sv_psi_plus = Statevector([1 / 2**0.5, 0, 0, 1 / 2**0.5])# create a statevector for |𝜓+⟩ here
prob_psi_plus = sv_psi_plus.probabilities_dict() # find the measurement probabilities for |𝜓+⟩ here
sv_psi_minus = Statevector([1 / 2**0.5, 0, 0, -1 / 2**0.5]) # create a statevector for |𝜓−⟩ here
prob_psi_minus = sv_psi_minus.probabilities_dict()# find the measurement probabilities for |𝜓−⟩ here
sv_phi_minus = Statevector([0, 1 / 2**0.5, -1 / 2**0.5, 0])# create a statevector for |𝜙−⟩ here
prob_phi_minus = sv_phi_minus.probabilities_dict()# find the measurement probabilities for |𝜙−⟩ here
from qc_grader.challenges.qgss_2023 import grade_lab1_ex9
grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus])
qft = QuantumCircuit(2)
##############################
# add gates to your circuit here
qft.h(1)
qft.cp(np.pi/2, 0, 1)
qft.h(0)
qft.swap(0, 1)
##############################
qft.draw(output='mpl')
from qc_grader.challenges.qgss_2023 import grade_lab1_ex10
grade_lab1_ex10(qft)
U = Operator(qft)
array_to_latex(U)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import re
import itertools
import numpy as np
import random
random.seed(42)
import mitiq
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.ignis.mitigation import expectation_value
# Pauli Twirling
def pauli_twirling(circ: QuantumCircuit) -> QuantumCircuit:
"""
[internal function]
This function takes a quantum circuit and return a new quantum circuit with Pauli Twirling around the CNOT gates.
Args:
circ: QuantumCircuit
Returns:
QuantumCircuit
"""
def apply_pauli(num: int, qb: int) -> str:
if (num == 0):
return f''
elif (num == 1):
return f'x q[{qb}];\n'
elif (num == 2):
return f'y q[{qb}];\n'
else:
return f'z q[{qb}];\n'
paulis = [(i,j) for i in range(0,4) for j in range(0,4)]
paulis.remove((0,0))
paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)]
new_circ = ''
ops = circ.qasm().splitlines(True) #! split the quantum circuit into qasm operators
for op in ops:
if (op[:2] == 'cx'): # add Pauli Twirling around the CNOT gate
num = random.randrange(len(paulis))
qbs = re.findall('q\[(.)\]', op)
new_circ += apply_pauli(paulis[num][0], qbs[0])
new_circ += apply_pauli(paulis[num][1], qbs[1])
new_circ += op
new_circ += apply_pauli(paulis_map[num][0], qbs[0])
new_circ += apply_pauli(paulis_map[num][1], qbs[1])
else:
new_circ += op
return QuantumCircuit.from_qasm_str(new_circ)
def zne_wrapper(qcs, scale_factors = [1.0, 2.0, 3.0], pt = False):
"""
This function outputs the circuit list for zero-noise extrapolation.
Args:
qcs: List[QuantumCircuit], the input quantum circuits.
scale_factors: List[float], to what extent the noise scales are investigated.
pt: bool, whether add Pauli Twirling or not.
Returns:
folded_qcs: List[QuantumCircuit]
"""
folded_qcs = [] #! ZNE用の回路
for qc in qcs:
folded_qcs.append([mitiq.zne.scaling.fold_gates_at_random(qc, scale) for scale in scale_factors]) #! ここでmitiqを使用
folded_qcs = list(itertools.chain(*folded_qcs)) #! folded_qcsを平坦化
if pt:
folded_qcs = [pauli_twirling(circ) for circ in folded_qcs]
return folded_qcs
def make_stf_basis(n, basis_elements = ["X","Y","Z"]):
"""
[internal function]
This function outputs all the combinations of length n string for given basis_elements.
When basis_elements is X, Y, and Z (default), the output becomes the n-qubit Pauli basis.
Args:
n: int
basis_elements: List[str]
Returns:
basis: List[str]
"""
if n == 1:
return basis_elements
basis = []
for i in basis_elements:
sub_basis = make_stf_basis(n - 1, basis_elements)
basis += [i + j for j in sub_basis]
return basis
def reduce_hist(hist, poses):
"""
[internal function]
This function returns the reduced histogram to the designated positions.
Args:
hist: Dict[str, float]
poses: List[int]
Returns:
ret_hist: Dict[str, float]
"""
n = len(poses)
ret_hist = {format(i, "0" + str(n) + "b"): 0 for i in range(1 << n)}
for k, v in hist.items():
pos = ""
for i in range(n):
pos += k[poses[i]]
ret_hist[pos] += v
return ret_hist
def make_stf_expvals(n, stf_hists):
"""
[internal function]
This function create the expectations under expanded basis, which are used to reconstruct the density matrix.
Args:
n: int, the size of classical register in the measurement results.
stf_hists: List[Dict[str, float]], the input State Tomography Fitter histograms.
Returns:
st_expvals: List[float], the output State Tomography expectation values.
"""
assert len(stf_hists) == 3 ** n
stf_basis = make_stf_basis(n, basis_elements=["X","Y","Z"])
st_basis = make_stf_basis(n, basis_elements=["I","X","Y","Z"])
stf_hists_dict = {basis: hist for basis, hist in zip(stf_basis, stf_hists)}
st_hists_dict = {basis: stf_hists_dict.get(basis, None) for basis in st_basis}
# remaining
for basis in sorted(set(st_basis) - set(stf_basis)):
if basis == "I" * n:
continue
reduction_poses = []
reduction_basis = ""
for i, b in enumerate(basis):
if b != "I":
reduction_poses.append(n - 1 - i) # big endian
reduction_basis += b # こっちはそのまま(なぜならラベルはlittle endianだから)
else:
reduction_basis += "Z"
st_hists_dict[basis] = reduce_hist(stf_hists_dict[reduction_basis], reduction_poses)
st_expvals = dict()
for basis, hist in st_hists_dict.items():
if basis == "I" * n:
st_expvals[basis] = 1.0
continue
st_expvals[basis], _ = expectation_value(hist)
return st_expvals
def zne_decoder(n, result, scale_factors=[1.0, 2.0, 3.0], fac_type="lin"):
"""
This function applies the zero-noise extrapolation to the measured results and output the mitigated zero-noise expectation values.
Args:
n: int, the size of classical register in the measurement results.
result: Result, the returned results from job.
scale_factors: List[float], this should be the same as the zne_wrapper.
fac_type: str, "lin" or "exp", whether to use LinFactory option or ExpFactory option in mitiq, to extrapolate the expectation values.
Returns:
zne_expvals: List[float], the mitigated zero-noise expectation values.
"""
hists = result.get_counts()
num_scale_factors = len(scale_factors)
assert len(hists) % num_scale_factors == 0
scale_wise_expvals = [] # num_scale_factors * 64
for i in range(num_scale_factors):
scale_wise_hists = [hists[3 * j + i] for j in range(len(hists) // num_scale_factors)]
st_expvals = make_stf_expvals(n, scale_wise_hists)
scale_wise_expvals.append( list(st_expvals.values()) )
scale_wise_expvals = np.array(scale_wise_expvals)
linfac = mitiq.zne.inference.LinearFactory(scale_factors)
expfac = mitiq.zne.ExpFactory(scale_factors)
zne_expvals = []
for i in range(4 ** n):
if fac_type == "lin":
zne_expvals.append( linfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) )
else:
zne_expvals.append( expfac.extrapolate(scale_factors, scale_wise_expvals[:, i]) )
return zne_expvals
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram
game_circuit = QuantumCircuit(2,1)
#game_circuit
game_circuit.clear()
game_circuit.h(0)
game_circuit.h(1)
game_circuit.cx(0,1)
game_circuit.h(1)
game_circuit.measure(1,0)
game_circuit.draw('mpl')
#running on ibm simulator
aer_sim=Aer.get_backend('aer_simulator')
shots=1024
qobj=assemble(game_circuit, shots=1024)
results=aer_sim.run(qobj).result()
counts=results.get_counts()
plot_histogram(counts)
#running on quantum computer
#signing in to ibm using api token
IBMQ.save_account('eb51948e03130da6b3212b337a0276eb3ddfb106e6e3ff49388aaf14efdded08d2624fa55f7d7158e02266b904d46424988e127c44056949754947d624319860')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True))
print(backend)
t_qc = transpile(game_circuit, backend, optimization_level=3)#transpile=assembling the circuit and everything
job = backend.run(t_qc)#backend means device
job_monitor(job)
exp_result = job.result()
exp_counts = exp_result.get_counts(game_circuit)
print(exp_counts)
plot_histogram(exp_counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager
circ = QuantumCircuit(3)
circ.ccx(0, 1, 2)
circ.draw(output='mpl')
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u1', 'u2', 'u3', 'cx'])
pm = PassManager(pass_)
new_circ = pm.run(circ)
new_circ.draw(output='mpl')
from qiskit.transpiler import passes
[pass_ for pass_ in dir(passes) if pass_[0].isupper()]
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
circuit = QuantumCircuit(7)
circuit.h(3)
circuit.cx(0, 6)
circuit.cx(6, 0)
circuit.cx(0, 1)
circuit.cx(3, 1)
circuit.cx(3, 0)
coupling_map = CouplingMap(couplinglist=coupling)
bs = BasicSwap(coupling_map=coupling_map)
pass_manager = PassManager(bs)
basic_circ = pass_manager.run(circuit)
ls = LookaheadSwap(coupling_map=coupling_map)
pass_manager = PassManager(ls)
lookahead_circ = pass_manager.run(circuit)
ss = StochasticSwap(coupling_map=coupling_map)
pass_manager = PassManager(ss)
stochastic_circ = pass_manager.run(circuit)
circuit.draw(output='mpl')
basic_circ.draw(output='mpl')
lookahead_circ.draw(output='mpl')
stochastic_circ.draw(output='mpl')
import math
from qiskit.providers.fake_provider import FakeTokyo
backend = FakeTokyo() # mimics the tokyo device in terms of coupling map and basis gates
qc = QuantumCircuit(10)
random_state = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0)]
qc.initialize(random_state, range(4))
qc.draw()
optimized_0 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=0)
print('gates = ', optimized_0.count_ops())
print('depth = ', optimized_0.depth())
optimized_1 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=1)
print('gates = ', optimized_1.count_ops())
print('depth = ', optimized_1.depth())
optimized_2 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=2)
print('gates = ', optimized_2.count_ops())
print('depth = ', optimized_2.depth())
optimized_3 = transpile(qc, backend=backend, seed_transpiler=11, optimization_level=3)
print('gates = ', optimized_3.count_ops())
print('depth = ', optimized_3.depth())
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
circ.draw(output='mpl')
from qiskit.converters import circuit_to_dag
from qiskit.tools.visualization import dag_drawer
dag = circuit_to_dag(circ)
dag_drawer(dag)
dag.op_nodes()
node = dag.op_nodes()[3]
print("node name: ", node.name)
print("node op: ", node.op)
print("node qargs: ", node.qargs)
print("node cargs: ", node.cargs)
print("node condition: ", node.op.condition)
from qiskit.circuit.library import HGate
dag.apply_operation_back(HGate(), qargs=[q[0]])
dag_drawer(dag)
from qiskit.circuit.library import CCXGate
dag.apply_operation_front(CCXGate(), qargs=[q[0], q[1], q[2]], cargs=[])
dag_drawer(dag)
from qiskit.circuit.library import CHGate, U2Gate, CXGate
mini_dag = DAGCircuit()
p = QuantumRegister(2, "p")
mini_dag.add_qreg(p)
mini_dag.apply_operation_back(CHGate(), qargs=[p[1], p[0]])
mini_dag.apply_operation_back(U2Gate(0.1, 0.2), qargs=[p[1]])
# substitute the cx node with the above mini-dag
cx_node = dag.op_nodes(op=CXGate).pop()
dag.substitute_node_with_dag(node=cx_node, input_dag=mini_dag, wires=[p[0], p[1]])
dag_drawer(dag)
from qiskit.converters import dag_to_circuit
circuit = dag_to_circuit(dag)
circuit.draw(output='mpl')
from copy import copy
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler import Layout
from qiskit.circuit.library import SwapGate
class BasicSwap(TransformationPass):
"""Maps (with minimum effort) a DAGCircuit onto a `coupling_map` adding swap gates."""
def __init__(self,
coupling_map,
initial_layout=None):
"""Maps a DAGCircuit onto a `coupling_map` using swap gates.
Args:
coupling_map (CouplingMap): Directed graph represented a coupling map.
initial_layout (Layout): initial layout of qubits in mapping
"""
super().__init__()
self.coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self, dag):
"""Runs the BasicSwap pass on `dag`.
Args:
dag (DAGCircuit): DAG to map.
Returns:
DAGCircuit: A mapped DAG.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG.
"""
new_dag = DAGCircuit()
for qreg in dag.qregs.values():
new_dag.add_qreg(qreg)
for creg in dag.cregs.values():
new_dag.add_creg(creg)
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
canonical_register = dag.qregs['q']
trivial_layout = Layout.generate_trivial_layout(canonical_register)
current_layout = trivial_layout.copy()
for layer in dag.serial_layers():
subdag = layer['graph']
for gate in subdag.two_qubit_ops():
physical_q0 = current_layout[gate.qargs[0]]
physical_q1 = current_layout[gate.qargs[1]]
if self.coupling_map.distance(physical_q0, physical_q1) != 1:
# Insert a new layer with the SWAP(s).
swap_layer = DAGCircuit()
swap_layer.add_qreg(canonical_register)
path = self.coupling_map.shortest_undirected_path(physical_q0, physical_q1)
for swap in range(len(path) - 2):
connected_wire_1 = path[swap]
connected_wire_2 = path[swap + 1]
qubit_1 = current_layout[connected_wire_1]
qubit_2 = current_layout[connected_wire_2]
# create the swap operation
swap_layer.apply_operation_back(SwapGate(),
qargs=[qubit_1, qubit_2],
cargs=[])
# layer insertion
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(swap_layer, qubits=order)
# update current_layout
for swap in range(len(path) - 2):
current_layout.swap(path[swap], path[swap + 1])
order = current_layout.reorder_bits(new_dag.qubits)
new_dag.compose(subdag, qubits=order)
return new_dag
q = QuantumRegister(7, 'q')
in_circ = QuantumCircuit(q)
in_circ.h(q[0])
in_circ.cx(q[0], q[4])
in_circ.cx(q[2], q[3])
in_circ.cx(q[6], q[1])
in_circ.cx(q[5], q[0])
in_circ.rz(0.1, q[2])
in_circ.cx(q[5], q[0])
from qiskit.transpiler import PassManager
from qiskit.transpiler import CouplingMap
from qiskit import BasicAer
pm = PassManager()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
pm.append([BasicSwap(coupling_map)])
out_circ = pm.run(in_circ)
in_circ.draw(output='mpl')
out_circ.draw(output='mpl')
import logging
logging.basicConfig(level='DEBUG')
from qiskit.providers.fake_provider import FakeTenerife
log_circ = QuantumCircuit(2, 2)
log_circ.h(0)
log_circ.h(1)
log_circ.h(1)
log_circ.x(1)
log_circ.cx(0, 1)
log_circ.measure([0,1], [0,1])
backend = FakeTenerife()
transpile(log_circ, backend);
logging.getLogger('qiskit.transpiler').setLevel('INFO')
transpile(log_circ, backend);
# Change log level back to DEBUG
logging.getLogger('qiskit.transpiler').setLevel('DEBUG')
# Transpile multiple circuits
circuits = [log_circ, log_circ]
transpile(circuits, backend);
formatter = logging.Formatter('%(name)s - %(processName)-10s - %(levelname)s: %(message)s')
handler = logging.getLogger().handlers[0]
handler.setFormatter(formatter)
transpile(circuits, backend);
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Dirac231/BCHamming
|
Dirac231
|
from qiskit import *
from unireedsolomon import *
from matplotlib import *
from math import *
from collections import defaultdict
import numpy as np
from numpy.polynomial import Polynomial
from qiskit.providers.aer import AerSimulator
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.noise import NoiseModel
#NOISE MODULE
#Needed in order to load the ibm-mps simulator for an optimal simulation
provider = IBMQ.load_account()
##the following adds the noise model that is based on ibmq_vigo
backend = provider.get_backend('ibmq_16_melbourne')
noise_model = NoiseModel.from_backend(backend) #noise model from real machines
##The following adds custom noise model to the circuit
# Error probabilities
#prob_1 = 0.001 # x error
#prob_2 = 0.01 # depolarizing error
# Depolarizing quantum errors
#error_1 = noise.depolarizing_error(prob_1, 1)
#error_2 = noise.depolarizing_error(prob_2, 2)
#error_1 = NoiseModel.depolarizing_error(prob_1, 1)
#error_2 = NoiseModel.depolarizing_error(prob_2, 2)
# Get basis gates from noise model
basis_gates = noise_model.basis_gates
basis_gates = ['cx', 'id', 'u1', 'sx', 'x']
#--------------------------------------------------------------------------------------
#PARAMETERS SETUP
#Parameters of the classical code used to generate the optimal quantum code.
#The code is built so that everything is a function of k_cl, the order of the finite field.
#The initial state is read from the file states.txt
def init_decoder():
global initial_state, k_cl, delta, K, ENC, encode_reg, ecc, shots, fourier, inv_fourier,provider
provider = IBMQ.load_account()
initial_state = np.loadtxt('states.txt')
k_cl = len(initial_state) #Order of the finite field in terms of powers of 2, corresponds to the amount of qbits sent
delta = floor((2**k_cl-1)/2+2) #Classical optimal minimum distance of the code
K = (2**k_cl) - delta #Number of classical bits sent, directly related to the error-correcting capability of the code ecc = floor((K+1)/2)
ENC = k_cl*(2**k_cl - 1) #Total encoding Qbits needed
encode_reg = QuantumRegister(ENC+2*k_cl*K) #Quantum Register used to construct the full circuit
ecc = floor((K+1)/2) #Maximum error correction capability per symbol
shots = 100
#Initialization of the parameters is completed
print("")
print("Reading from file: found ",k_cl," Qbits: \n")
print("Parameters of the code: ")
print("-------------------------------------------")
print("Encoding Qbits: ", ENC)
print("Sent Qbits: ", k_cl*(2**k_cl-1-2*K))
print("Maximum error-correcting: ", ecc, "/Symbol = ", ecc*k_cl, "/Encoded Qbit")
print("-------------------------------------------")
#--------------------------------------------------------------------------------------
#QTF IMPLEMENTATION
#A quantum fourier transform is used both for encoding and decoding purposes
fourier = QFT(num_qubits=ENC, approximation_degree=0, do_swaps=True, inverse=False, insert_barriers=False, name='qft')
inv_fourier = QFT(num_qubits=ENC, approximation_degree=0, do_swaps=True, inverse=True, insert_barriers=False, name='qft-inverse')
#-----------------------------------------------------------------------------------
#SIMULATES THE CIRCUIT
def simulate(qc):
"""Simulates the circuit using the cloud-computing services of IBMq, this is always the recommended choice to run simulations"""
provider = IBMQ.get_provider(hub='ibm-q')
backend=provider.get_backend('simulator_mps')
result = execute(circ, backend,shots=shots,
basis_gates=basis_gates,
noise_model=noise_model).result() #add noise module
print('Simulation Success: {}'.format(result.success))
print("Time taken: {} sec".format(result.time_taken))
counts = result.get_counts(0)
return counts
#------------------------------------------------------------------------------------
#MEASURE FUNCTIONS
def measure_encoding(qc):
"""Measure the Qbits used in the encoding, i.e. if the lenght is 3, the first 21 Qbits"""
cr = ClassicalRegister(ENC, 'encoded')
qc.add_register(cr)
for i in range(0, ENC):
qc.measure(i,cr[i])
results = simulate(qc)
encoded = max(results, key=results.get)
return encoded
def get_qbits(qc):
"""Measure the Qbits with the message, i.e. if the lenght is 3, the first 3 Qbits"""
cr = ClassicalRegister(k_cl*(2**k_cl-1-2*K), 'out')
qc.add_register(cr)
for i in range(0,k_cl):
qc.measure(i, cr[i])
for i in range(k_cl*(K + 1), ENC-k_cl*K):
qc.measure(i, cr[i])
results = simulate(qc)
qbits = max(results, key=results.get)
return qbits,results
def get_syndrome(qc):
"""Measure the Qbits with the syndrome, i.e. if the lenght is 3, the last 18 Qbits"""
cr = ClassicalRegister(2*k_cl*K)
qc.add_register(cr)
for i in range(0, 2*k_cl*K):
qc.measure(ENC+i,cr[i])
#orders the syndromes in descending order in term of the occurrences
ordered_res = {k: v for k, v in sorted(simulate(qc).items(), key=lambda item: item[1])}
syndromes = list(ordered_res)[::-1]
return syndromes
#------------------------------------------------------------------------------------
#GIVEN THE CLASSICAL SYNDROME, RETURNS THE POSITIONS OF THE ERRORS USING CLASSICAL BERLEKAMP-MASSEY
#Performs a Berlekamp-Massey algorithm in order to find the error locator polynomial relative to the syndrome#
def error_string(classical_syn):
k1 = int(ENC/k_cl)
k2 = int(((ENC-K*k_cl)/k_cl))
prime = int(hex(find_prime_polynomials(c_exp=k_cl,single=True)),16)
coder = rs.RSCoder(k1, k2, prim=prime,c_exp=k_cl)
error_bf, sigma_bf = coder._berlekamp_massey_fast(coder._list2gfpoly(str(classical_syn)))
eval_tmp_bf, bf = coder._chien_search_faster(error_bf)
Y = coder._forney(sigma_bf, eval_tmp_bf)
Elist = []
if(classical_syn != "0"*k_cl):
if len(Y) >= len(bf):
for i in range(coder.gf2_charac):
if i in bf:
Elist.append(Y[bf.index(i)])
E = Polynomial( Elist[::-1])
error_bits = [bin(int(i))[2:] for i in Elist]
s = ""
for i in range(len(error_bits)):
s += error_bits[i]
s = s[::-1]
return s
else:
return ""
def error_locator(syn):
"""take the syndrome computed by the quantum circuit and apply error_string"""
for x in syn:
BFsyndrome = oct(int((x[::-1])[:k_cl*K],2))[2:] #bit flip syndrome string
PFsyndrome = oct(int((x[::-1])[k_cl*K:],2))[2:] #phase flip syndrome string
#Performs the error locator finding for each measured syndrome, if a error occurs, it computes the errors associated with the next most probable syndrome
try: #uses functions in the unireedsolomon library to compute the error locations bf, pf
bf = error_string(BFsyndrome)
pf = error_string(PFsyndrome)
return bf,pf,x
except (RSCodecError,ValueError):
continue
print("No valid syndrome was found, too many errors try increasing the number of shots.")
exit()
#------------------------------------------------------------------------------------
"""ENCODING: takes a message and return the circuit that encodes it"""
def encoder(initial_state):
"""Takes a message and return the circuit that encodes it"""
qc = QuantumCircuit(encode_reg)
for i in range(0,k_cl):
qc.initialize(initial_state[i], i)
for i in range(k_cl*(K + 1), ENC-k_cl*K):
qc.initialize(initial_state[i], i)
for i in range(ENC - k_cl*K,ENC):
qc.h(i)
qc.append(inv_fourier, encode_reg[:ENC])
return qc
#CIRCUIT TO COMPUTE THE SYNDROME
def decoder(qc):
"""Takes the ecoding circuit, computes the syndrome and corrects the message"""
qc.append(fourier, encode_reg[:ENC])
for i in range(k_cl+1,k_cl*(K+1)+1):
qc.cx(i-1, i+ENC-k_cl-1)
for i in range(ENC -k_cl*K, ENC):
qc.h(i)
for i in range(ENC-k_cl*K-1,ENC-1):
qc.cx(i+1, i+ENC-k_cl+1)
for i in range(ENC -k_cl*K-1, ENC-1):
qc.h(i+1)
qc.append(inv_fourier, encode_reg[:ENC])
syn = get_syndrome(qc)
bf,pf,x = error_locator(syn)
if(bf != "1" or x[:k_cl*K] != "0"*k_cl*K):
for i in range(len(bf)):
if (bf[i] == "1"):
qc.x(i)
if (pf != "1" or x[k_cl*K:] != "0"*k_cl*K):
for i in range(ENC):
qc.h(i)
for i in range(len(pf)):
if (pf[i] == "1"):
qc.z(i)
for i in range(ENC):
qc.h(i)
qc.append(fourier, encode_reg[:ENC])
message,occurrences = get_qbits(qc)
occurrences = zip([x[:3][::-1] for x in occurrences.keys()] , list(occurrences.values()))
D = defaultdict(int)
for k,v in occurrences:
D[k]+= int(v)
occurrences = dict(D)
return qc,message,x,occurrences
#------------------------------------------------------------------------------------
def send_message(initial_state):
"""Auxiliary testing function, sends the message contained in the file states.txt and returns the simulation circuit."""
qc = encoder(initial_state) #Classical optimal minimum distance of the code
#INSERT ERRORS HERE: (such as qc.x(4) or z-errors)
qc,retrieved,syn,occurrences = decoder(qc)
plot_histogram(occurrences, color='midnightblue', title="Message occurrences").savefig("histogram.png")
print("Most probable message: ", retrieved[:3][::-1])
print("Occurrences: ", occurrences)
print("Compared with: ")
for i in initial_state:
print(i,"\n")
print("Syndrome was: ", syn[::-1])
qc.draw(output='mpl', filename='prova.png')
return qc
#------------------------------------------------------------------------------------
qc = send_message(initial_state)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
from qiskit_cold_atom.fermions import FermionSimulator
# initialize the generic fermionic simulator backend
backend = FermionSimulator()
from qiskit import QuantumCircuit
circ1 = QuantumCircuit(4) # Create a quantum circuit describing four fermionic modes.
circ1.fload([1, 2]) # Load fermions into modes 1 and 2.
circ1.draw(output="mpl", style="clifford")
circ1.measure_all()
job = backend.run(circ1) # defaults to 1000 shots taken
print(job.result().get_counts())
circ2 = backend.initialize_circuit([1, 0, 1])
circ2.draw(output="mpl", style="clifford")
print(f"First circuit's register: {circ1.qregs}")
print(f"Second circuit's register: {circ2.qregs}")
from qiskit_nature.second_q.operators import FermionicOp
import numpy as np
# define the Hamiltonian as a FermionicOp
H_swap = np.pi / 2 * FermionicOp({"+_0 -_1": 1, "-_0 +_1": -1}, num_spin_orbitals=2)
from qiskit_cold_atom.fermions import FermionicGate
swap_fermions = FermionicGate(name="swap_fermion", num_modes=2, generator=H_swap)
circ = backend.initialize_circuit([1, 0, 1, 0])
circ.append(swap_fermions, qargs=[0, 1])
circ.append(swap_fermions, qargs=[2, 3])
circ.append(swap_fermions, qargs=[1, 2])
circ.measure_all()
# circ.draw(output='mpl', scale=0.8)
job = backend.run(circ)
print(job.result().get_counts())
# define a gate which will create superposition in the circuit
split_fermions = FermionicGate(name="split_fermion", num_modes=2, generator=H_swap / 2)
qc_sup = backend.initialize_circuit([1, 0, 0])
qc_sup.append(split_fermions, qargs=[0, 1])
qc_sup.append(swap_fermions, qargs=[1, 2])
qc_sup.measure_all()
qc_sup.draw(output="mpl", style="clifford", scale=0.8)
from qiskit.visualization import plot_histogram
job_sup = backend.run(qc_sup)
plot_histogram(job_sup.result().get_counts(), figsize=(5, 3))
qc = backend.initialize_circuit([1, 0, 0, 1])
qc.append(split_fermions, qargs=[0, 1])
qc.append(swap_fermions, qargs=[2, 3])
qc.append(swap_fermions, qargs=[0, 1])
qc.append(split_fermions, qargs=[2, 3])
qc.append(swap_fermions, qargs=[0, 2])
qc.measure_all()
job = backend.run(qc, shots=10, seed=1234)
# access the counts
print("counts :", job.result().get_counts())
# access the memory of individual outcomes
print("\nmemory :", job.result().get_memory())
# access the statevector
print("\nstatevector :", job.result().get_statevector())
# accedd the unitary
print("\ncircuit unitary : \n", job.result().get_unitary())
qc.draw(output="mpl", style="clifford")
print(backend.get_basis(qc))
corr = FermionicOp({"+_0 -_0 +_2 -_2": 1}, num_spin_orbitals=4) + FermionicOp(
{"-_0 +_0 -_2 +_2": 1}, num_spin_orbitals=4
)
exp_val = backend.measure_observable_expectation(qc, observable=corr, shots=1000)
print(exp_val)
import numpy as np
from qiskit_cold_atom.fermions import (
FfsimBackend,
Hop,
Interaction,
Phase,
)
# initialize the ffsim backend
backend = FfsimBackend()
# set the number of orbitals and occupancies
norb = 8
nocc = norb // 4
nvrt = norb - nocc
occ_a = [1] * nocc + [0] * nvrt
occ_b = [1] * nocc + [0] * nvrt
occupations = [occ_a, occ_b]
# set parameters for fermionic gates
hopping = np.ones(norb - 1)
interaction = 1.0
mu = np.ones(norb)
# construct a circuit with some fermionic gates
circuit = backend.initialize_circuit(occupations)
circuit.append(Hop(2 * norb, hopping), list(range(2 * norb)))
circuit.append(Interaction(2 * norb, interaction), list(range(2 * norb)))
circuit.append(Phase(2 * norb, mu), list(range(2 * norb)))
circuit.measure_all()
# run the circuit and retrieve the measurement counts
job = backend.run(circuit, shots=10, seed=1234, num_species=2)
# access the counts
print("counts :", job.result().get_counts())
# access the memory of individual outcomes
print("\nmemory :", job.result().get_memory())
# print the length of the statevector
print("\nstatevector length :", len(job.result().get_statevector()))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""SummedOp Class"""
from typing import List, Union, cast, Dict
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import ParameterExpression
from qiskit.opflow.exceptions import OpflowError
from qiskit.opflow.list_ops.list_op import ListOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.utils.deprecation import deprecate_func
class SummedOp(ListOp):
"""Deprecated: A class for lazily representing sums of Operators. Often Operators cannot be
efficiently added to one another, but may be manipulated further so that they can be
later. This class holds logic to indicate that the Operators in ``oplist`` are meant to
be added together, and therefore if they reach a point in which they can be, such as after
evaluation or conversion to matrices, they can be reduced by addition."""
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self,
oplist: List[OperatorBase],
coeff: Union[complex, ParameterExpression] = 1.0,
abelian: bool = False,
) -> None:
"""
Args:
oplist: The Operators being summed.
coeff: A coefficient multiplying the operator
abelian: Indicates whether the Operators in ``oplist`` are known to mutually commute.
"""
super().__init__(oplist, combo_fn=lambda x: np.sum(x, axis=0), coeff=coeff, abelian=abelian)
@property
def num_qubits(self) -> int:
return self.oplist[0].num_qubits
@property
def distributive(self) -> bool:
return True
@property
def settings(self) -> Dict:
"""Return settings."""
return {"oplist": self._oplist, "coeff": self._coeff, "abelian": self._abelian}
def add(self, other: OperatorBase) -> "SummedOp":
"""Return Operator addition of ``self`` and ``other``, overloaded by ``+``.
Note:
This appends ``other`` to ``self.oplist`` without checking ``other`` is already
included or not. If you want to simplify them, please use :meth:`simplify`.
Args:
other: An ``OperatorBase`` with the same number of qubits as self, and in the same
'Operator', 'State function', or 'Measurement' category as self (i.e. the same type
of underlying function).
Returns:
A ``SummedOp`` equivalent to the sum of self and other.
"""
self_new_ops = (
self.oplist if self.coeff == 1 else [op.mul(self.coeff) for op in self.oplist]
)
if isinstance(other, SummedOp):
other_new_ops = (
other.oplist if other.coeff == 1 else [op.mul(other.coeff) for op in other.oplist]
)
else:
other_new_ops = [other]
return SummedOp(self_new_ops + other_new_ops)
def collapse_summands(self) -> "SummedOp":
"""Return Operator by simplifying duplicate operators.
E.g., ``SummedOp([2 * X ^ Y, X ^ Y]).collapse_summands() -> SummedOp([3 * X ^ Y])``.
Returns:
A simplified ``SummedOp`` equivalent to self.
"""
# pylint: disable=cyclic-import
from ..primitive_ops.primitive_op import PrimitiveOp
oplist = [] # type: List[OperatorBase]
coeffs = [] # type: List[Union[int, float, complex, ParameterExpression]]
for op in self.oplist:
if isinstance(op, PrimitiveOp):
new_op = PrimitiveOp(op.primitive)
new_coeff = op.coeff * self.coeff
if new_op in oplist:
index = oplist.index(new_op)
coeffs[index] += new_coeff
else:
oplist.append(new_op)
coeffs.append(new_coeff)
else:
if op in oplist:
index = oplist.index(op)
coeffs[index] += self.coeff
else:
oplist.append(op)
coeffs.append(self.coeff)
return SummedOp([op * coeff for op, coeff in zip(oplist, coeffs)])
# TODO be smarter about the fact that any two ops in oplist could be evaluated for sum.
def reduce(self) -> OperatorBase:
"""Try collapsing list or trees of sums.
Tries to sum up duplicate operators and reduces the operators
in the sum.
Returns:
A collapsed version of self, if possible.
"""
if len(self.oplist) == 0:
return SummedOp([], coeff=self.coeff, abelian=self.abelian)
# reduce constituents
reduced_ops = sum(op.reduce() for op in self.oplist) * self.coeff
# group duplicate operators
if isinstance(reduced_ops, SummedOp):
reduced_ops = reduced_ops.collapse_summands()
# pylint: disable=cyclic-import
from ..primitive_ops.pauli_sum_op import PauliSumOp
if isinstance(reduced_ops, PauliSumOp):
reduced_ops = reduced_ops.reduce()
if isinstance(reduced_ops, SummedOp) and len(reduced_ops.oplist) == 1:
return reduced_ops.oplist[0]
else:
return cast(OperatorBase, reduced_ops)
def to_circuit(self) -> QuantumCircuit:
"""Returns the quantum circuit, representing the SummedOp. In the first step,
the SummedOp is converted to MatrixOp. This is straightforward for most operators,
but it is not supported for operators containing parameterized PrimitiveOps (in that case,
OpflowError is raised). In the next step, the MatrixOp representation of SummedOp is
converted to circuit. In most cases, if the summands themselves are unitary operators,
the SummedOp itself is non-unitary and can not be converted to circuit. In that case,
ExtensionError is raised in the underlying modules.
Returns:
The circuit representation of the summed operator.
Raises:
OpflowError: if SummedOp can not be converted to MatrixOp (e.g. SummedOp is composed of
parameterized PrimitiveOps).
"""
# pylint: disable=cyclic-import
from ..primitive_ops.matrix_op import MatrixOp
matrix_op = self.to_matrix_op()
if isinstance(matrix_op, MatrixOp):
return matrix_op.to_circuit()
raise OpflowError(
"The SummedOp can not be converted to circuit, because to_matrix_op did "
"not return a MatrixOp."
)
def to_matrix_op(self, massive: bool = False) -> "SummedOp":
"""Returns an equivalent Operator composed of only NumPy-based primitives, such as
``MatrixOp`` and ``VectorStateFn``."""
accum = self.oplist[0].to_matrix_op(massive=massive)
for i in range(1, len(self.oplist)):
accum += self.oplist[i].to_matrix_op(massive=massive)
return cast(SummedOp, accum * self.coeff)
def to_pauli_op(self, massive: bool = False) -> "SummedOp":
# pylint: disable=cyclic-import
from ..state_fns.state_fn import StateFn
pauli_sum = SummedOp(
[
op.to_pauli_op(massive=massive) # type: ignore
if not isinstance(op, StateFn)
else op
for op in self.oplist
],
coeff=self.coeff,
abelian=self.abelian,
).reduce()
if isinstance(pauli_sum, SummedOp):
return pauli_sum
return pauli_sum.to_pauli_op() # type: ignore
def equals(self, other: OperatorBase) -> bool:
"""Check if other is equal to self.
Note:
This is not a mathematical check for equality.
If ``self`` and ``other`` implement the same operation but differ
in the representation (e.g. different type of summands)
``equals`` will evaluate to ``False``.
Args:
other: The other operator to check for equality.
Returns:
True, if other and self are equal, otherwise False.
Examples:
>>> from qiskit.opflow import X, Z
>>> 2 * X == X + X
True
>>> X + Z == Z + X
True
"""
self_reduced, other_reduced = self.reduce(), other.reduce()
if not isinstance(other_reduced, type(self_reduced)):
return False
# check if reduced op is still a SummedOp
if not isinstance(self_reduced, SummedOp):
return self_reduced == other_reduced
self_reduced = cast(SummedOp, self_reduced)
other_reduced = cast(SummedOp, other_reduced)
if len(self_reduced.oplist) != len(other_reduced.oplist):
return False
# absorb coeffs into the operators
if self_reduced.coeff != 1:
self_reduced = SummedOp([op * self_reduced.coeff for op in self_reduced.oplist])
if other_reduced.coeff != 1:
other_reduced = SummedOp([op * other_reduced.coeff for op in other_reduced.oplist])
# compare independent of order
return all(any(i == j for j in other_reduced) for i in self_reduced)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit.utils.deprecation import deprecate_function
from qiskit.utils.deprecation import deprecate_arguments
class DummyClass:
"""This is short description. Let's make it
multiline"""
def __init__(self, arg1: int = None, arg2: [int] = None):
self.arg1 = arg1
self.arg2 = arg2
@deprecate_function(
"The DummyClass.foo() method is being deprecated. Use the DummyClass.some_othermethod()",
since="1.2.3",
)
def foo_deprecated(self, index_arg2: int):
"""A multi-line
docstring.
Here are more details.
Args:
index_arg2: `index_arg2` description
Returns:
int: returns `arg2[index_arg2]`
Raises:
QiskitError: if `len(self.arg2) < index_arg2`
"""
if len(self.arg2) < index_arg2:
raise QiskitError("there is an error")
return self.arg2[index_arg2]
@deprecate_arguments({"if_arg1": "other_if_arg1"}, since="1.2.3")
def bar_with_deprecated_arg(
self, if_arg1: int = None, index_arg2: int = None, other_if_arg1: int = None
):
"""
A multi-line short
docstring.
This is the long description
Args:
if_arg1: `if_arg1` description with
multi-line
index_arg2: `index_arg2` description
other_if_arg1: `other_if_arg1` description
Returns:
int or None: if `if_arg1 == self.arg1`, returns `arg2[index_arg2]`
"""
if other_if_arg1 == self.arg1 or if_arg1 == self.arg1:
return self.arg2[index_arg2]
return None
d = DummyClass(1, [1,2])
d.foo_deprecated(0)
print(d.foo_deprecated.__doc__)
d.bar_with_deprecated_arg(if_arg1=0)
d.bar_with_deprecated_arg(other_if_arg1=0)
print(d.bar_with_deprecated_arg.__doc__)
def f():
"""Normal docstring"""
pass
deprecate_function("deprecation message", since="1.2.3")(f)
print(f.__doc__)
def f():
"""Normal docstring"""
pass
deprecate_function("deprecation message", modify_docstring=False, since="1.2.3")(f)
print(f.__doc__)
def f():
"""Normal docstring"""
pass
deprecate_function("deprecation message", modify_docstring=True)(f)
print(f.__doc__)
from qiskit import __version__
def f():
"""Normal docstring"""
pass
deprecate_function("deprecation message", modify_docstring=True, since=__version__)(f)
print(f.__doc__)
|
https://github.com/AdityaZade/QuantumDecoder
|
AdityaZade
|
from qiskit import *
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
secretnumber='101001'
circuit=QuantumCircuit(len(secretnumber)+1,len(secretnumber))
# circuit.h([0,1,2,3,4,5])
# circuit.x(6)
# circuit.h(6)
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.z(len(secretnumber))
circuit.draw(output='mpl')
circuit.barrier()
for i,check in enumerate(reversed(secretnumber)):
if check == '1':
circuit.cx(i,len(secretnumber))
# circuit.cx(5,6)
# circuit.cx(2,6)
# circuit.cx(0,6)
circuit.draw(output='mpl')
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.draw(output='mpl')
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output='mpl')
simulator=Aer.get_backend('qasm_simulator')
result=execute(circuit,backend=simulator,shots=1).result()
count=result.get_counts()
print(count)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test -CZ-CX- joint synthesis function."""
import unittest
from test import combine
import numpy as np
from ddt import ddt
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford
from qiskit.synthesis.linear_phase.cx_cz_depth_lnn import synth_cx_cz_depth_line_my
from qiskit.synthesis.linear import (
synth_cnot_depth_line_kms,
random_invertible_binary_matrix,
)
from qiskit.synthesis.linear.linear_circuits_utils import check_lnn_connectivity
from qiskit.test import QiskitTestCase
@ddt
class TestCXCZSynth(QiskitTestCase):
"""Test the linear reversible circuit synthesis functions."""
@combine(num_qubits=[3, 4, 5, 6, 7, 8, 9, 10])
def test_cx_cz_synth_lnn(self, num_qubits):
"""Test the CXCZ synthesis code for linear nearest neighbour connectivity."""
seed = 1234
rng = np.random.default_rng(seed)
num_gates = 10
num_trials = 8
for _ in range(num_trials):
# Generate a random CZ circuit
mat_z = np.zeros((num_qubits, num_qubits))
cir_z = QuantumCircuit(num_qubits)
for _ in range(num_gates):
i = rng.integers(num_qubits)
j = rng.integers(num_qubits)
if i != j:
cir_z.cz(i, j)
if j > i:
mat_z[i][j] = (mat_z[i][j] + 1) % 2
else:
mat_z[j][i] = (mat_z[j][i] + 1) % 2
# Generate a random CX circuit
mat_x = random_invertible_binary_matrix(num_qubits, seed=rng)
mat_x = np.array(mat_x, dtype=bool)
cir_x = synth_cnot_depth_line_kms(mat_x)
# Joint Synthesis
cir_zx_test = QuantumCircuit.compose(cir_z, cir_x)
cir_zx = synth_cx_cz_depth_line_my(mat_x, mat_z)
# Check that the output circuit 2-qubit depth is at most 5n
depth2q = cir_zx.depth(filter_function=lambda x: x.operation.num_qubits == 2)
self.assertTrue(depth2q <= 5 * num_qubits)
# Check that the output circuit has LNN connectivity
self.assertTrue(check_lnn_connectivity(cir_zx))
# Assert that we get the same elements as other methods
self.assertEqual(Clifford(cir_zx), Clifford(cir_zx_test))
if __name__ == "__main__":
unittest.main()
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
# import SymPy and define symbols
import sympy as sp
sp.init_printing(use_unicode=True)
wr = sp.Symbol('\omega_r') # resonator frequency
wq = sp.Symbol('\omega_q') # qubit frequency
g = sp.Symbol('g', real=True) # vacuum Rabi coupling
Delta = sp.Symbol('Delta', real=True) # wr - wq; defined later
# import operator relations and define them
from sympy.physics.quantum.boson import BosonOp
a = BosonOp('a') # resonator photon annihilation operator
from sympy.physics.quantum import pauli, Dagger, Commutator
from sympy.physics.quantum.operatorordering import normal_ordered_form
# Pauli matrices
sx = pauli.SigmaX()
sy = pauli.SigmaY()
sz = pauli.SigmaZ()
# qubit raising and lowering operators
splus = pauli.SigmaPlus()
sminus = pauli.SigmaMinus()
# define J-C Hamiltonian in terms of diagonal and non-block diagonal terms
H0 = wr*Dagger(a)*a - (1/2)*wq*sz;
H1 = 0
H2 = g*(Dagger(a)*sminus + a*splus);
HJC = H0 + H1 + H2; HJC # print
# using the above method for finding the ansatz
eta = Commutator(H0, H2); eta
pauli.qsimplify_pauli(normal_ordered_form(eta.doit().expand()))
A = sp.Symbol('A')
B = sp.Symbol('B')
eta = A * Dagger(a) * sminus - B * a * splus;
pauli.qsimplify_pauli(normal_ordered_form(Commutator(H0, eta).doit().expand()))
H2
S1 = eta.subs(A, g/Delta)
S1 = S1.subs(B, g/Delta); S1.factor()
Heff = H0 + H1 + 0.5*pauli.qsimplify_pauli(normal_ordered_form(Commutator(H2, S1).doit().expand())).simplify(); Heff
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The sweep will be centered around the estimated qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
# scale factor to remove factors of 10 from the data
scale_factor = 1e-14
# We will sweep 40 MHz around the estimated frequency
frequency_span_Hz = 40 * MHz
# in steps of 1 MHz.
frequency_step_Hz = 1 * MHz
# We will sweep 20 MHz above and 20 MHz below the estimated frequency
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
# Construct an np array of the frequencies for our experiment
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \
in steps of {frequency_step_Hz / MHz} MHz.")
from qiskit import pulse # This is where we access all of our Pulse features!
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=[qubit])
x_pulse = inst_sched_map.get('x', qubits=[qubit])
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Create the base schedule
# Start with drive pulse acting on the drive channel
schedule = pulse.Schedule(name='Frequency sweep')
schedule += x_pulse
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
schedule += measure << schedule.duration
# Create the frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz*GHz
schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz]
schedule.draw(label=True, scaling=0.8)
from qiskit import assemble
frequency_sweep_program = assemble(schedule,
backend=backend,
meas_level=1,
meas_return='avg',
shots=1024,
schedule_los=schedule_frequencies)
# RUN the job on a real device
#job = backend.run(rabi_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive result from previous run
job = backend.retrieve_job('5ef3b081fbc24b001275b03b')
frequency_sweep_results = job.result()
import matplotlib.pyplot as plt
plt.style.use('dark_background')
sweep_values = []
for i in range(len(frequency_sweep_results.results)):
# Get the results from the ith experiment
res = frequency_sweep_results.get_memory(i)*scale_factor
# Get the results for `qubit` from this experiment
sweep_values.append(res[qubit])
plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') # plot real part of sweep values
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured signal [a.u.]")
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(frequencies_GHz,
np.real(sweep_values),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[5, 4.975, 1, 3] # initial parameters for curve_fit
)
plt.scatter(frequencies_GHz, np.real(sweep_values), color='white')
plt.plot(frequencies_GHz, y_fit, color='red')
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
# Create the schedules for 0 and 1
schedule_0 = pulse.Schedule(name='0')
schedule_0 += measure
schedule_1 = pulse.Schedule(name='1')
schedule_1 += x_pulse
schedule_1 += measure << schedule_1.duration
schedule_0.draw()
schedule_1.draw()
frequency_span_Hz = 320 * kHz
frequency_step_Hz = 8 * kHz
center_frequency_Hz = backend_defaults.meas_freq_est[qubit]
print(f"Qubit {qubit} has an estimated readout frequency of {center_frequency_Hz / GHz} GHz.")
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz\
in steps of {frequency_step_Hz / MHz} MHz.")
num_shots_per_frequency = 2048
frequencies_Hz = frequencies_GHz*GHz
schedule_los = [{meas_chan: freq} for freq in frequencies_Hz]
cavity_sweep_0 = assemble(schedule_0,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_los)
cavity_sweep_1 = assemble(schedule_1,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_los)
# RUN the job on a real device
#job_0 = backend.run(cavity_sweep_0)
#job_monitor(job_0)
#job_0.error_message()
#job_1 = backend.run(cavity_sweep_1)
#job_monitor(job_1)
#job_1.error_message()
# OR retreive result from previous run
job_0 = backend.retrieve_job('5efa5b447c0d6800137fff1c')
job_1 = backend.retrieve_job('5efa6b2720eee10013be46b4')
cavity_sweep_0_results = job_0.result()
cavity_sweep_1_results = job_1.result()
scale_factor = 1e-14
sweep_values_0 = []
for i in range(len(cavity_sweep_0_results.results)):
res_0 = cavity_sweep_0_results.get_memory(i)*scale_factor
sweep_values_0.append(res_0[qubit])
sweep_values_1 = []
for i in range(len(cavity_sweep_1_results.results)):
res_1 = cavity_sweep_1_results.get_memory(i)*scale_factor
sweep_values_1.append(res_1[qubit])
plotx = frequencies_Hz/kHz
ploty_0 = np.abs(sweep_values_0)
ploty_1 = np.abs(sweep_values_1)
plt.plot(plotx, ploty_0, color='blue', marker='.') # plot real part of sweep values
plt.plot(plotx, ploty_1, color='red', marker='.') # plot real part of sweep values
plt.legend([r'$\vert0\rangle$', r'$\vert1\rangle$'])
plt.grid()
plt.xlabel("Frequency [kHz]")
plt.ylabel("Measured signal [a.u.]")
plt.yscale('log')
plt.show()
|
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
|
ronitd2002
|
import json
import logging
import numpy as np
import warnings
from functools import wraps
from typing import Any, Callable, Optional, Tuple, Union
from qiskit import IBMQ, QuantumCircuit, assemble
from qiskit.circuit import Barrier, Gate, Instruction, Measure
from qiskit.circuit.library import UGate, U3Gate, CXGate
from qiskit.providers.ibmq import AccountProvider, IBMQProviderError
from qiskit.providers.ibmq.job import IBMQJob
def get_provider() -> AccountProvider:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ibmq_logger = logging.getLogger('qiskit.providers.ibmq')
current_level = ibmq_logger.level
ibmq_logger.setLevel(logging.ERROR)
# get provider
try:
provider = IBMQ.get_provider()
except IBMQProviderError:
provider = IBMQ.load_account()
ibmq_logger.setLevel(current_level)
return provider
def get_job(job_id: str) -> Optional[IBMQJob]:
try:
job = get_provider().backends.retrieve_job(job_id)
return job
except Exception:
pass
return None
def circuit_to_json(qc: QuantumCircuit) -> str:
class _QobjEncoder(json.encoder.JSONEncoder):
def default(self, obj: Any) -> Any:
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder)
def circuit_to_dict(qc: QuantumCircuit) -> dict:
qobj = assemble(qc)
return qobj.to_dict()
def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]:
try:
job_id = job.job_id() if isinstance(job, IBMQJob) else job
download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url']
result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url']
return download_url, result_url
except Exception:
return None, None
def cached(key_function: Callable) -> Callable:
def _decorator(f: Any) -> Callable:
f.__cache = {}
@wraps(f)
def _decorated(*args: Any, **kwargs: Any) -> int:
key = key_function(*args, **kwargs)
if key not in f.__cache:
f.__cache[key] = f(*args, **kwargs)
return f.__cache[key]
return _decorated
return _decorator
def gate_key(gate: Gate) -> Tuple[str, int]:
return gate.name, gate.num_qubits
@cached(gate_key)
def gate_cost(gate: Gate) -> int:
if isinstance(gate, (UGate, U3Gate)):
return 1
elif isinstance(gate, CXGate):
return 10
elif isinstance(gate, (Measure, Barrier)):
return 0
return sum(map(gate_cost, (g for g, _, _ in gate.definition.data)))
def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int:
print('Computing cost...')
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction):
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
return sum(map(gate_cost, (g for g, _, _ in circuit_data)))
def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool:
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction) and circuit.definition is not None:
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
for g, _, _ in circuit_data:
if isinstance(g, (Barrier, Measure)):
continue
elif isinstance(g, Gate):
if g.num_qubits > 1:
return True
elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g):
return True
return False
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import IntegerComparator
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
# set problem parameters
n_z = 2
z_max = 2
z_values = np.linspace(-z_max, z_max, 2**n_z)
p_zeros = [0.15, 0.25]
rhos = [0.1, 0.05]
lgd = [1, 2]
K = len(p_zeros)
alpha = 0.05
from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI
u = GCI(n_z, z_max, p_zeros, rhos)
u.draw()
u_measure = u.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(u_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# analyze uncertainty circuit and determine exact solutions
p_z = np.zeros(2**n_z)
p_default = np.zeros(K)
values = []
probabilities = []
num_qubits = u.num_qubits
for i, prob in binary_probabilities.items():
# extract value of Z and corresponding probability
i_normal = int(i[-n_z:], 2)
p_z[i_normal] += prob
# determine overall default probability for k
loss = 0
for k in range(K):
if i[K - k - 1] == "1":
p_default[k] += prob
loss += lgd[k]
values += [loss]
probabilities += [prob]
values = np.array(values)
probabilities = np.array(probabilities)
expected_loss = np.dot(values, probabilities)
losses = np.sort(np.unique(values))
pdf = np.zeros(len(losses))
for i, v in enumerate(losses):
pdf[i] += sum(probabilities[values == v])
cdf = np.cumsum(pdf)
i_var = np.argmax(cdf >= 1 - alpha)
exact_var = losses[i_var]
exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :])
print("Expected Loss E[L]: %.4f" % expected_loss)
print("Value at Risk VaR[L]: %.4f" % exact_var)
print("P[L <= VaR[L]]: %.4f" % cdf[exact_var])
print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar)
# plot loss PDF, expected loss, var, and cvar
plt.bar(losses, pdf)
plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]")
plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)")
plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)")
plt.legend(fontsize=15)
plt.xlabel("Loss L ($)", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Loss Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for Z
plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8)
plt.grid()
plt.xlabel("Z value", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Z Distribution", size=20)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# plot results for default probabilities
plt.bar(range(K), p_default)
plt.xlabel("Asset", size=15)
plt.ylabel("probability (%)", size=15)
plt.title("Individual Default Probabilities", size=20)
plt.xticks(range(K), size=15)
plt.yticks(size=15)
plt.grid()
plt.show()
# add Z qubits with weight/loss 0
from qiskit.circuit.library import WeightedAdder
agg = WeightedAdder(n_z + K, [0] * n_z + lgd)
from qiskit.circuit.library import LinearAmplitudeFunction
# define linear objective function
breakpoints = [0]
slopes = [1]
offsets = [0]
f_min = 0
f_max = sum(lgd)
c_approx = 0.25
objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slope=slopes,
offset=offsets,
# max value that can be reached by the qubit register (will not always be reached)
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u.to_gate(), qr_state)
# aggregate
state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:])
# uncompute aggregation
state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
# draw the circuit
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
value += prob
print("Exact Expected Loss: %.4f" % expected_loss)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % objective.post_processing(value))
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
# print results
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % expected_loss)
print("Estimated value:\t%.4f" % result.estimation_processed)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
# set x value to estimate the CDF
x_eval = 2
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
comparator.draw()
def get_cdf_circuit(x_eval):
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_compare = QuantumRegister(1, "compare")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# comparator objective function
comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False)
state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
return state_preparation
state_preparation = get_cdf_circuit(x_eval)
state_preparation.draw()
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
var_prob = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1":
var_prob += prob
print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob)
print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval])
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)])
# construct amplitude estimation
ae_cdf = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cdf = ae_cdf.estimate(problem)
# print results
conf_int = np.array(result_cdf.confidence_interval)
print("Exact value: \t%.4f" % cdf[x_eval])
print("Estimated value:\t%.4f" % result_cdf.estimation)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"):
# construct amplitude estimation
state_preparation = get_cdf_circuit(x_eval)
problem = EstimationProblem(
state_preparation=state_preparation, objective_qubits=[len(qr_state)]
)
ae_var = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_var = ae_var.estimate(problem)
return result_var.estimation
def bisection_search(
objective, target_value, low_level, high_level, low_value=None, high_value=None
):
"""
Determines the smallest level such that the objective value is still larger than the target
:param objective: objective function
:param target: target value
:param low_level: lowest level to be considered
:param high_level: highest level to be considered
:param low_value: value of lowest level (will be evaluated if set to None)
:param high_value: value of highest level (will be evaluated if set to None)
:return: dictionary with level, value, num_eval
"""
# check whether low and high values are given and evaluated them otherwise
print("--------------------------------------------------------------------")
print("start bisection search for target value %.3f" % target_value)
print("--------------------------------------------------------------------")
num_eval = 0
if low_value is None:
low_value = objective(low_level)
num_eval += 1
if high_value is None:
high_value = objective(high_level)
num_eval += 1
# check if low_value already satisfies the condition
if low_value > target_value:
return {
"level": low_level,
"value": low_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif low_value == target_value:
return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"}
# check if high_value is above target
if high_value < target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "returned low value",
}
elif high_value == target_value:
return {
"level": high_level,
"value": high_value,
"num_eval": num_eval,
"comment": "success",
}
# perform bisection search until
print("low_level low_value level value high_level high_value")
print("--------------------------------------------------------------------")
while high_level - low_level > 1:
level = int(np.round((high_level + low_level) / 2.0))
num_eval += 1
value = objective(level)
print(
"%2d %.3f %2d %.3f %2d %.3f"
% (low_level, low_value, level, value, high_level, high_value)
)
if value >= target_value:
high_level = level
high_value = value
else:
low_level = level
low_value = value
# return high value after bisection search
print("--------------------------------------------------------------------")
print("finished bisection search")
print("--------------------------------------------------------------------")
return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"}
# run bisection search to determine VaR
objective = lambda x: run_ae_for_cdf(x)
bisection_result = bisection_search(
objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1
)
var = bisection_result["level"]
print("Estimated Value at Risk: %2d" % var)
print("Exact Value at Risk: %2d" % exact_var)
print("Estimated Probability: %.3f" % bisection_result["value"])
print("Exact Probability: %.3f" % cdf[exact_var])
# define linear objective
breakpoints = [0, var]
slopes = [0, 1]
offsets = [0, 0] # subtract VaR and add it later to the estimate
f_min = 0
f_max = 3 - var
c_approx = 0.25
cvar_objective = LinearAmplitudeFunction(
agg.num_sum_qubits,
slopes,
offsets,
domain=(0, 2**agg.num_sum_qubits - 1),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
cvar_objective.draw()
# define the registers for convenience and readability
qr_state = QuantumRegister(u.num_qubits, "state")
qr_sum = QuantumRegister(agg.num_sum_qubits, "sum")
qr_carry = QuantumRegister(agg.num_carry_qubits, "carry")
qr_obj = QuantumRegister(1, "objective")
qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work")
# define the circuit
state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A")
# load the random variable
state_preparation.append(u, qr_state)
# aggregate
state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:])
# linear objective function
state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:])
# uncompute aggregation
state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:])
state_preparation_measure = state_preparation.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(state_preparation_measure)
binary_probabilities = job.result().quasi_dists[0].binary_probabilities()
# evaluate the result
value = 0
for i, prob in binary_probabilities.items():
if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1":
value += prob
# normalize and add VaR to estimate
value = cvar_objective.post_processing(value)
d = 1.0 - bisection_result["value"]
v = value / d if d != 0 else 0
normalized_value = v + var
print("Estimated CVaR: %.4f" % normalized_value)
print("Exact CVaR: %.4f" % exact_cvar)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=state_preparation,
objective_qubits=[len(qr_state)],
post_processing=cvar_objective.post_processing,
)
# construct amplitude estimation
ae_cvar = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result_cvar = ae_cvar.estimate(problem)
# print results
d = 1.0 - bisection_result["value"]
v = result_cvar.estimation_processed / d if d != 0 else 0
print("Exact CVaR: \t%.4f" % exact_cvar)
print("Estimated CVaR:\t%.4f" % (v + var))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(3, 'q')
anc = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, anc, cr)
qc.x(anc[0])
qc.h(anc[0])
qc.h(qr[0:3])
qc.cx(qr[0:3], anc[0])
qc.h(qr[0:3])
qc.barrier(qr)
qc.measure(qr, cr)
qc.draw('mpl')
|
https://github.com/NicoGiamm/Quantum_computing
|
NicoGiamm
|
import cirq
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15,10)
q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)]
circuit = cirq.Circuit()
#entagling the 2 quibits in different laboratories
#and preparing the qubit to send
circuit.append(cirq.H(q0))
circuit.append(cirq.H(q1))
circuit.append(cirq.CNOT(q1, q2))
#entangling the qubit we want to send to the one in the first laboratory
circuit.append(cirq.CNOT(q0, q1))
circuit.append(cirq.H(q0))
#measurements
circuit.append(cirq.measure(q0, q1))
#last transformations to obtain the qubit information
circuit.append(cirq.CNOT(q1, q2))
circuit.append(cirq.CZ(q0, q2))
#measure of the qubit in the receiving laboratory along z axis
circuit.append(cirq.measure(q2, key = 'Z'))
circuit
#starting simulation
sim = cirq.Simulator()
results = sim.run(circuit, repetitions=100)
sns.histplot(results.measurements['Z'], discrete = True)
100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z'])
#in qiskit the qubits are integrated in the circuit
qc = QuantumCircuit(3, 1)
#entangling
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.cx(0, 1)
#setting for measurment
qc.h(0)
qc.measure([0,1], [0,0])
#transformation to obtain qubit sent
qc.cx(1, 2)
qc.cz(0, 2)
qc.measure(2, 0)
print(qc)
#simulation
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=100)
res = job.result().get_counts(qc)
plt.bar(res.keys(), res.values())
res
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.circuit.quantumcircuitdata import CircuitInstruction
from qiskit.circuit import Measure
from qiskit.circuit.library import HGate, CXGate
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
instructions = [
CircuitInstruction(HGate(), [qr[0]], []),
CircuitInstruction(CXGate(), [qr[0], qr[1]], []),
CircuitInstruction(Measure(), [qr[0]], [cr[0]]),
CircuitInstruction(Measure(), [qr[1]], [cr[1]]),
]
circuit = QuantumCircuit.from_instructions(instructions)
circuit.draw("mpl")
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Example use of the initialize gate to prepare arbitrary pure states.
"""
import math
from qiskit import QuantumCircuit, execute, BasicAer
###############################################################
# Make a quantum circuit for state initialization.
###############################################################
circuit = QuantumCircuit(4, 4, name="initializer_circ")
desired_vector = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0),
]
circuit.initialize(desired_vector, [0, 1, 2, 3])
circuit.measure([0, 1, 2, 3], [0, 1, 2, 3])
print(circuit)
###############################################################
# Execute on a simulator backend.
###############################################################
shots = 10000
# Desired vector
print("Desired probabilities: ")
print([format(abs(x * x), ".3f") for x in desired_vector])
# Initialize on local simulator
sim_backend = BasicAer.get_backend("qasm_simulator")
job = execute(circuit, sim_backend, shots=shots)
result = job.result()
counts = result.get_counts(circuit)
qubit_strings = [format(i, "04b") for i in range(2**4)]
print("Probabilities from simulator: ")
print([format(counts.get(s, 0) / shots, ".3f") for s in qubit_strings])
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Stinespring quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info import Stinespring
from .channel_test_case import ChannelTestCase
class TestStinespring(ChannelTestCase):
"""Tests for Stinespring channel representation."""
def test_init(self):
"""Test initialization"""
# Initialize from unitary
chan = Stinespring(self.UI)
assert_allclose(chan.data, self.UI)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Stinespring
chan = Stinespring(self.depol_stine(0.5))
assert_allclose(chan.data, self.depol_stine(0.5))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Non-CPTP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
chan = Stinespring((stine_l, stine_r))
assert_allclose(chan.data, (stine_l, stine_r))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize with redundant second op
chan = Stinespring((stine_l, stine_l))
assert_allclose(chan.data, stine_l)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Stinespring, stine_l, input_dims=4, output_dims=4)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Stinespring(circuit)
target = Stinespring(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Stinespring, circuit)
def test_equal(self):
"""Test __eq__ method"""
stine = tuple(self.rand_matrix(4, 2) for _ in range(2))
self.assertEqual(Stinespring(stine), Stinespring(stine))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = Stinespring(mat)
cpy = orig.copy()
cpy._data[0][0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Stinespring(self.depol_stine(0.5)).is_cptp())
self.assertTrue(Stinespring(self.UX).is_cptp())
# Non-CP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
self.assertFalse(Stinespring((stine_l, stine_r)).is_cptp())
self.assertFalse(Stinespring(self.UI + self.UX).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
stine_l, stine_r = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring list
targ = Stinespring(stine_l.conj(), output_dims=4)
chan1 = Stinespring(stine_l, output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
# Double Stinespring list
targ = Stinespring((stine_l.conj(), stine_r.conj()), output_dims=4)
chan1 = Stinespring((stine_l, stine_r), output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
def test_transpose(self):
"""Test transpose method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T, 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T, stine_r.T), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_adjoint(self):
"""Test adjoint method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T.conj(), 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T.conj(), stine_r.T.conj()), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, Stinespring(np.eye(4)))
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_dot(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
rho_targ = rho_init.evolve(Stinespring(self.UZ))
self.assertEqual(rho_init.evolve(chan1.dot(chan2)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan2), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan1.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan1), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
self.assertEqual(rho_init.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan2 @ chan1), rho_targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2, front=True)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1, front=True)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.tensor(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
rho_init = DensityMatrix(np.diag([1, 0]))
p_id = 0.9
chan1 = Stinespring(self.depol_stine(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan = chan1.power(3)
rho_targ = rho_init & chan1 & chan1 & chan1
self.assertEqual(rho_init & chan, rho_targ)
rho_targ = rho_init & Stinespring(self.depol_stine(1 - p_id3))
self.assertEqual(rho_init & chan, rho_targ)
def test_add(self):
"""Test add method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) + (rho_init & chan2)
chan = chan1._add(chan2)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 + chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 2 * (rho_init & chan)
chan = chan._add(chan)
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_subtract(self):
"""Test subtract method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) - (rho_init & chan2)
chan = chan1 - chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 0 * (rho_init & chan)
chan = chan - chan
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_add_qargs(self):
"""Test add method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_sub_qargs(self):
"""Test sub method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_multiply(self):
"""Test multiply method."""
# Random initial state and Stinespring ops
rho_init = DensityMatrix(self.rand_rho(2))
val = 0.5
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring set
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan1)
chan = chan1._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan1
self.assertEqual(rho_init.evolve(chan), rho_targ)
rho_targ = (rho_init & chan1) * val
chan = chan1 * val
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Double Stinespring set
chan2 = Stinespring((stine1, stine2), input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan2)
chan = chan2._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Stinespring(self.depol_stine(1))
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
rho_init = DensityMatrix(np.diag([1, 0]))
rho_targ = DensityMatrix(np.diag([-0.5, -0.5]))
chan = -Stinespring(self.depol_stine(1))
self.assertEqual(rho_init.evolve(chan), rho_targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
all_pairs = ['00','01','10','11']
for pair in all_pairs:
#
# your code is here
#
|
https://github.com/jakelishman/qiskit-qasm2
|
jakelishman
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import io
import math
import os
import pathlib
import pickle
import shutil
import tempfile
import unittest
import ddt
import qiskit.qasm2
from qiskit import qpy
from qiskit.circuit import (
ClassicalRegister,
Gate,
Parameter,
QuantumCircuit,
QuantumRegister,
Qubit,
library as lib,
)
from qiskit.test import QiskitTestCase
from . import gate_builder
class TestEmpty(QiskitTestCase):
def test_allows_empty(self):
self.assertEqual(qiskit.qasm2.loads(""), QuantumCircuit())
class TestVersion(QiskitTestCase):
def test_complete_version(self):
program = "OPENQASM 2.0;"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed, QuantumCircuit())
def test_incomplete_version(self):
program = "OPENQASM 2;"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(parsed, QuantumCircuit())
def test_after_comment(self):
program = """
// hello, world
OPENQASM 2.0;
qreg q[2];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
class TestRegisters(QiskitTestCase):
def test_qreg(self):
program = "qreg q1[2]; qreg q2[1]; qreg q3[4];"
parsed = qiskit.qasm2.loads(program)
regs = [QuantumRegister(2, "q1"), QuantumRegister(1, "q2"), QuantumRegister(4, "q3")]
self.assertEqual(list(parsed.qregs), regs)
self.assertEqual(list(parsed.cregs), [])
def test_creg(self):
program = "creg c1[2]; creg c2[1]; creg c3[4];"
parsed = qiskit.qasm2.loads(program)
regs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2"), ClassicalRegister(4, "c3")]
self.assertEqual(list(parsed.cregs), regs)
self.assertEqual(list(parsed.qregs), [])
def test_interleaved_registers(self):
program = "qreg q1[3]; creg c1[2]; qreg q2[1]; creg c2[1];"
parsed = qiskit.qasm2.loads(program)
qregs = [QuantumRegister(3, "q1"), QuantumRegister(1, "q2")]
cregs = [ClassicalRegister(2, "c1"), ClassicalRegister(1, "c2")]
self.assertEqual(list(parsed.qregs), qregs)
self.assertEqual(list(parsed.cregs), cregs)
def test_registers_after_gate(self):
program = "qreg before[2]; CX before[0], before[1]; qreg after[2]; CX after[0], after[1];"
parsed = qiskit.qasm2.loads(program)
before = QuantumRegister(2, "before")
after = QuantumRegister(2, "after")
qc = QuantumCircuit(before, after)
qc.cx(before[0], before[1])
qc.cx(after[0], after[1])
self.assertEqual(parsed, qc)
def test_empty_registers(self):
program = "qreg q[0]; creg c[0];"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "q"), ClassicalRegister(0, "c"))
self.assertEqual(parsed, qc)
@ddt.ddt
class TestGateApplication(QiskitTestCase):
def test_builtin_single(self):
program = """
qreg q[2];
U(0, 0, 0) q[0];
CX q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.u(0, 0, 0, 0)
qc.cx(0, 1)
self.assertEqual(parsed, qc)
def test_builtin_1q_broadcast(self):
program = "qreg q[2]; U(0, 0, 0) q;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.u(0, 0, 0, 0)
qc.u(0, 0, 0, 1)
self.assertEqual(parsed, qc)
def test_builtin_2q_broadcast(self):
program = """
qreg q1[2];
qreg q2[2];
CX q1[0], q2;
barrier;
CX q1, q2[1];
barrier;
CX q1, q2;
"""
parsed = qiskit.qasm2.loads(program)
q1 = QuantumRegister(2, "q1")
q2 = QuantumRegister(2, "q2")
qc = QuantumCircuit(q1, q2)
qc.cx(q1[0], q2[0])
qc.cx(q1[0], q2[1])
qc.barrier()
qc.cx(q1[0], q2[1])
qc.cx(q1[1], q2[1])
qc.barrier()
qc.cx(q1[0], q2[0])
qc.cx(q1[1], q2[1])
self.assertEqual(parsed, qc)
def test_3q_broadcast(self):
program = """
include "qelib1.inc";
qreg q1[2];
qreg q2[2];
qreg q3[2];
ccx q1, q2[0], q3[1];
ccx q1[1], q2, q3[0];
ccx q1[0], q2[1], q3;
barrier;
ccx q1, q2, q3[1];
ccx q1[1], q2, q3;
ccx q1, q2[1], q3;
barrier;
ccx q1, q2, q3;
"""
parsed = qiskit.qasm2.loads(program)
q1 = QuantumRegister(2, "q1")
q2 = QuantumRegister(2, "q2")
q3 = QuantumRegister(2, "q3")
qc = QuantumCircuit(q1, q2, q3)
qc.ccx(q1[0], q2[0], q3[1])
qc.ccx(q1[1], q2[0], q3[1])
qc.ccx(q1[1], q2[0], q3[0])
qc.ccx(q1[1], q2[1], q3[0])
qc.ccx(q1[0], q2[1], q3[0])
qc.ccx(q1[0], q2[1], q3[1])
qc.barrier()
qc.ccx(q1[0], q2[0], q3[1])
qc.ccx(q1[1], q2[1], q3[1])
qc.ccx(q1[1], q2[0], q3[0])
qc.ccx(q1[1], q2[1], q3[1])
qc.ccx(q1[0], q2[1], q3[0])
qc.ccx(q1[1], q2[1], q3[1])
qc.barrier()
qc.ccx(q1[0], q2[0], q3[0])
qc.ccx(q1[1], q2[1], q3[1])
self.assertEqual(parsed, qc)
@ddt.data(True, False)
def test_broadcast_against_empty_register(self, conditioned):
cond = "if (cond == 0) " if conditioned else ""
program = f"""
OPENQASM 2;
include "qelib1.inc";
qreg q1[1];
qreg q2[1];
qreg empty1[0];
qreg empty2[0];
qreg empty3[0];
creg cond[1];
// None of the following statements should produce any gate applications.
{cond}h empty1;
{cond}cx q1[0], empty1;
{cond}cx empty1, q2[0];
{cond}cx empty1, empty2;
{cond}ccx empty1, q1[0], q2[0];
{cond}ccx q1[0], empty2, q2[0];
{cond}ccx q1[0], q2[0], empty3;
{cond}ccx empty1, empty2, q1[0];
{cond}ccx empty1, q1[0], empty2;
{cond}ccx q1[0], empty1, empty2;
{cond}ccx empty1, empty2, empty3;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(
QuantumRegister(1, "q1"),
QuantumRegister(1, "q2"),
QuantumRegister(0, "empty1"),
QuantumRegister(0, "empty2"),
QuantumRegister(0, "empty3"),
ClassicalRegister(1, "cond"),
)
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
qreg q[2];
creg cond[1];
if (cond == 0) U(0, 0, 0) q[0];
if (cond == 1) CX q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), cond)
qc.u(0, 0, 0, 0).c_if(cond, 0)
qc.cx(1, 0).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_conditioned_broadcast(self):
program = """
qreg q1[2];
qreg q2[2];
creg cond[1];
if (cond == 0) U(0, 0, 0) q1;
if (cond == 1) CX q1[0], q2;
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
q1 = QuantumRegister(2, "q1")
q2 = QuantumRegister(2, "q2")
qc = QuantumCircuit(q1, q2, cond)
qc.u(0, 0, 0, q1[0]).c_if(cond, 0)
qc.u(0, 0, 0, q1[1]).c_if(cond, 0)
qc.cx(q1[0], q2[0]).c_if(cond, 1)
qc.cx(q1[0], q2[1]).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_constant_folding(self):
# Most expression-related things are tested in `test_expression.py` instead.
program = """
qreg q[1];
U(4 + 3 * 2 ^ 2, cos(pi) * (1 - ln(1)), 2 ^ 3 ^ 2) q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.u(16.0, -1.0, 512.0, 0)
self.assertEqual(parsed, qc)
def test_call_defined_gate(self):
program = """
gate my_gate a {
U(0, 0, 0) a;
}
qreg q[2];
my_gate q[0];
my_gate q;
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit()])
my_gate_def.u(0, 0, 0, 0)
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0])
qc.append(my_gate(), [0])
qc.append(my_gate(), [1])
self.assertEqual(parsed, qc)
def test_parameterless_gates_accept_parentheses(self):
program = """
qreg q[2];
CX q[0], q[1];
CX() q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.cx(0, 1)
qc.cx(1, 0)
self.assertEqual(parsed, qc)
class TestGateDefinition(QiskitTestCase):
def test_simple_definition(self):
program = """
gate not_bell a, b {
U(0, 0, 0) a;
CX a, b;
}
qreg q[2];
not_bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
not_bell_def = QuantumCircuit([Qubit(), Qubit()])
not_bell_def.u(0, 0, 0, 0)
not_bell_def.cx(0, 1)
not_bell = gate_builder("not_bell", [], not_bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(not_bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
gate not_bell a, b {
U(0, 0, 0) a;
CX a, b;
}
qreg q[2];
creg cond[1];
if (cond == 0) not_bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
not_bell_def = QuantumCircuit([Qubit(), Qubit()])
not_bell_def.u(0, 0, 0, 0)
not_bell_def.cx(0, 1)
not_bell = gate_builder("not_bell", [], not_bell_def)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), cond)
qc.append(not_bell().c_if(cond, 0), [0, 1])
self.assertEqual(parsed, qc)
def test_constant_folding_in_definition(self):
program = """
gate bell a, b {
U(pi/2, 0, pi) a;
CX a, b;
}
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.u(math.pi / 2, 0, math.pi, 0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_parameterised_gate(self):
# Most of the tests of deep parameter expressions are in `test_expression.py`.
program = """
gate my_gate(a, b) c {
U(a, b, a + 2 * b) c;
}
qreg q[1];
my_gate(0.25, 0.5) q[0];
my_gate(0.5, 0.25) q[0];
"""
parsed = qiskit.qasm2.loads(program)
a, b = Parameter("a"), Parameter("b")
my_gate_def = QuantumCircuit([Qubit()])
my_gate_def.u(a, b, a + 2 * b, 0)
my_gate = gate_builder("my_gate", [a, b], my_gate_def)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(my_gate(0.25, 0.5), [0])
qc.append(my_gate(0.5, 0.25), [0])
self.assertEqual(parsed, qc)
# Also check the decomposition has come out exactly as expected. The floating-point
# assertions are safe as exact equality checks because there are no lossy operations with
# these parameters, and the answer should be exact.
decomposed = qc.decompose()
self.assertEqual(decomposed.data[0].operation.name, "u")
self.assertEqual(list(decomposed.data[0].operation.params), [0.25, 0.5, 1.25])
self.assertEqual(decomposed.data[1].operation.name, "u")
self.assertEqual(list(decomposed.data[1].operation.params), [0.5, 0.25, 1.0])
def test_parameterless_gate_with_parentheses(self):
program = """
gate my_gate() a {
U(0, 0, 0) a;
}
qreg q[1];
my_gate q[0];
my_gate() q[0];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit()])
my_gate_def.u(0, 0, 0, 0)
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(my_gate(), [0])
qc.append(my_gate(), [0])
self.assertEqual(parsed, qc)
def test_access_includes_in_definition(self):
program = """
include "qelib1.inc";
gate bell a, b {
h a;
cx a, b;
}
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_access_previous_defined_gate(self):
program = """
include "qelib1.inc";
gate bell a, b {
h a;
cx a, b;
}
gate second_bell a, b {
bell b, a;
}
qreg q[2];
second_bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
second_bell_def = QuantumCircuit([Qubit(), Qubit()])
second_bell_def.append(bell(), [1, 0])
second_bell = gate_builder("second_bell", [], second_bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(second_bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_qubits_lookup_differently_to_gates(self):
# The spec is somewhat unclear on this, and this leads to super weird text, but it's
# technically unambiguously resolvable and this is more permissive.
program = """
include "qelib1.inc";
gate bell h, cx {
h h;
cx h, cx;
}
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_parameters_lookup_differently_to_gates(self):
# The spec is somewhat unclear on this, and this leads to super weird text, but it's
# technically unambiguously resolvable and this is more permissive.
program = """
include "qelib1.inc";
gate shadow(rx, rz) a {
rz(rz) a;
rx(rx) a;
}
qreg q[1];
shadow(0.5, 2.0) q[0];
"""
parsed = qiskit.qasm2.loads(program)
rx, rz = Parameter("rx"), Parameter("rz")
shadow_def = QuantumCircuit([Qubit()])
shadow_def.rz(rz, 0)
shadow_def.rx(rx, 0)
shadow = gate_builder("shadow", [rx, rz], shadow_def)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(shadow(0.5, 2.0), [0])
self.assertEqual(parsed, qc)
def test_unused_parameters_convert_correctly(self):
# The main risk here is that there might be lazy application in the gate definition
# bindings, and we might accidentally try and bind parameters that aren't actually in the
# definition.
program = """
gate my_gate(p) q {
U(0, 0, 0) q;
}
qreg q[1];
my_gate(0.5) q[0];
"""
parsed = qiskit.qasm2.loads(program)
# No top-level circuit equality test here, because all the internals of gate application are
# an implementation detail, and we don't want to tie the tests and implementation together
# too closely.
self.assertEqual(list(parsed.qregs), [QuantumRegister(1, "q")])
self.assertEqual(list(parsed.cregs), [])
self.assertEqual(len(parsed.data), 1)
self.assertEqual(parsed.data[0].qubits, (parsed.qubits[0],))
self.assertEqual(parsed.data[0].clbits, ())
self.assertEqual(parsed.data[0].operation.name, "my_gate")
self.assertEqual(list(parsed.data[0].operation.params), [0.5])
decomposed = QuantumCircuit(QuantumRegister(1, "q"))
decomposed.u(0, 0, 0, 0)
self.assertEqual(parsed.decompose(), decomposed)
def test_qubit_barrier_in_definition(self):
program = """
gate my_gate a, b {
barrier a;
barrier b;
barrier a, b;
}
qreg q[2];
my_gate q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.barrier(0)
my_gate_def.barrier(1)
my_gate_def.barrier([0, 1])
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0, 1])
self.assertEqual(parsed, qc)
def test_bare_barrier_in_definition(self):
program = """
gate my_gate a, b {
barrier;
}
qreg q[2];
my_gate q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.barrier(my_gate_def.qubits)
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0, 1])
self.assertEqual(parsed, qc)
def test_duplicate_barrier_in_definition(self):
program = """
gate my_gate a, b {
barrier a, a;
barrier b, a, b;
}
qreg q[2];
my_gate q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.barrier(0)
my_gate_def.barrier([1, 0])
my_gate = gate_builder("my_gate", [], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(), [0, 1])
self.assertEqual(parsed, qc)
def test_pickleable(self):
program = """
include "qelib1.inc";
gate my_gate(a) b, c {
rz(2 * a) b;
h b;
cx b, c;
}
qreg q[2];
my_gate(0.5) q[0], q[1];
my_gate(0.25) q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
a = Parameter("a")
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.rz(2 * a, 0)
my_gate_def.h(0)
my_gate_def.cx(0, 1)
my_gate = gate_builder("my_gate", [a], my_gate_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate(0.5), [0, 1])
qc.append(my_gate(0.25), [1, 0])
self.assertEqual(parsed, qc)
with io.BytesIO() as fptr:
pickle.dump(parsed, fptr)
fptr.seek(0)
loaded = pickle.load(fptr)
self.assertEqual(parsed, loaded)
def test_qpy_single_call_roundtrip(self):
program = """
include "qelib1.inc";
gate my_gate(a) b, c {
rz(2 * a) b;
h b;
cx b, c;
}
qreg q[2];
my_gate(0.5) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
# QPY won't persist custom gates by design choice, so instead let us check against the
# explicit form it uses.
my_gate_def = QuantumCircuit([Qubit(), Qubit()])
my_gate_def.rz(1.0, 0)
my_gate_def.h(0)
my_gate_def.cx(0, 1)
my_gate = Gate("my_gate", 2, [0.5])
my_gate.definition = my_gate_def
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate, [0, 1])
with io.BytesIO() as fptr:
qpy.dump(parsed, fptr)
fptr.seek(0)
loaded = qpy.load(fptr)[0]
self.assertEqual(loaded, qc)
# See https://github.com/Qiskit/qiskit-terra/issues/8941
@unittest.expectedFailure
def test_qpy_double_call_roundtrip(self):
program = """
include "qelib1.inc";
gate my_gate(a) b, c {
rz(2 * a) b;
h b;
cx b, c;
}
qreg q[2];
my_gate(0.5) q[0], q[1];
my_gate(0.25) q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
my_gate1_def = QuantumCircuit([Qubit(), Qubit()])
my_gate1_def.rz(1.0, 0)
my_gate1_def.h(0)
my_gate1_def.cx(0, 1)
my_gate1 = Gate("my_gate", 2, [0.5])
my_gate1.definition = my_gate1_def
my_gate2_def = QuantumCircuit([Qubit(), Qubit()])
my_gate2_def.rz(0.5, 0)
my_gate2_def.h(0)
my_gate2_def.cx(0, 1)
my_gate2 = Gate("my_gate", 2, [0.25])
my_gate2.definition = my_gate2_def
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(my_gate1, [0, 1])
qc.append(my_gate2, [1, 0])
with io.BytesIO() as fptr:
qpy.dump(parsed, fptr)
fptr.seek(0)
loaded = qpy.load(fptr)[0]
self.assertEqual(loaded, qc)
class TestOpaque(QiskitTestCase):
def test_simple(self):
program = """
opaque my_gate a;
opaque my_gate2() a;
qreg q[2];
my_gate q[0];
my_gate() q[1];
my_gate2 q[0];
my_gate2() q[1];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(Gate("my_gate", 1, []), [0])
qc.append(Gate("my_gate", 1, []), [1])
qc.append(Gate("my_gate2", 1, []), [0])
qc.append(Gate("my_gate2", 1, []), [1])
self.assertEqual(parsed, qc)
def test_parameterised(self):
program = """
opaque my_gate(a, b) c, d;
qreg q[2];
my_gate(0.5, 0.25) q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(Gate("my_gate", 2, [0.5, 0.25]), [1, 0])
self.assertEqual(parsed, qc)
class TestBarrier(QiskitTestCase):
def test_single_register_argument(self):
program = """
qreg first[3];
qreg second[3];
barrier first;
barrier second;
"""
parsed = qiskit.qasm2.loads(program)
first = QuantumRegister(3, "first")
second = QuantumRegister(3, "second")
qc = QuantumCircuit(first, second)
qc.barrier(first)
qc.barrier(second)
self.assertEqual(parsed, qc)
def test_single_qubit_argument(self):
program = """
qreg first[3];
qreg second[3];
barrier first[1];
barrier second[0];
"""
parsed = qiskit.qasm2.loads(program)
first = QuantumRegister(3, "first")
second = QuantumRegister(3, "second")
qc = QuantumCircuit(first, second)
qc.barrier(first[1])
qc.barrier(second[0])
self.assertEqual(parsed, qc)
def test_empty_circuit_empty_arguments(self):
program = "barrier;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit()
self.assertEqual(parsed, qc)
def test_one_register_circuit_empty_arguments(self):
program = "qreg q1[2]; barrier;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q1"))
qc.barrier(qc.qubits)
self.assertEqual(parsed, qc)
def test_multi_register_circuit_empty_arguments(self):
program = "qreg q1[2]; qreg q2[3]; qreg q3[1]; barrier;"
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(
QuantumRegister(2, "q1"), QuantumRegister(3, "q2"), QuantumRegister(1, "q3")
)
qc.barrier(qc.qubits)
self.assertEqual(parsed, qc)
def test_include_empty_register(self):
program = """
qreg q[2];
qreg empty[0];
barrier empty;
barrier q, empty;
barrier;
"""
parsed = qiskit.qasm2.loads(program)
q = QuantumRegister(2, "q")
qc = QuantumCircuit(q, QuantumRegister(0, "empty"))
qc.barrier(q)
qc.barrier(qc.qubits)
self.assertEqual(parsed, qc)
def test_allows_duplicate_arguments(self):
# There's nothing in the paper that implies this should be forbidden.
program = """
qreg q1[3];
qreg q2[2];
barrier q1, q1;
barrier q1[0], q1;
barrier q1, q1[0];
barrier q1, q2, q1;
"""
parsed = qiskit.qasm2.loads(program)
q1 = QuantumRegister(3, "q1")
q2 = QuantumRegister(2, "q2")
qc = QuantumCircuit(q1, q2)
qc.barrier(q1)
qc.barrier(q1)
qc.barrier(q1)
qc.barrier(q1, q2)
self.assertEqual(parsed, qc)
class TestMeasure(QiskitTestCase):
def test_single(self):
program = """
qreg q[1];
creg c[1];
measure q[0] -> c[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"), ClassicalRegister(1, "c"))
qc.measure(0, 0)
self.assertEqual(parsed, qc)
def test_broadcast(self):
program = """
qreg q[2];
creg c[2];
measure q -> c;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"))
qc.measure(0, 0)
qc.measure(1, 1)
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
qreg q[2];
creg c[2];
creg cond[1];
if (cond == 0) measure q[0] -> c[0];
if (cond == 1) measure q -> c;
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"), cond)
qc.measure(0, 0).c_if(cond, 0)
qc.measure(0, 0).c_if(cond, 1)
qc.measure(1, 1).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_broadcast_against_empty_register(self):
program = """
qreg q_empty[0];
creg c_empty[0];
measure q_empty -> c_empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "q_empty"), ClassicalRegister(0, "c_empty"))
self.assertEqual(parsed, qc)
def test_conditioned_broadcast_against_empty_register(self):
program = """
qreg q_empty[0];
creg c_empty[0];
creg cond[1];
if (cond == 0) measure q_empty -> c_empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(
QuantumRegister(0, "q_empty"),
ClassicalRegister(0, "c_empty"),
ClassicalRegister(1, "cond"),
)
self.assertEqual(parsed, qc)
class TestReset(QiskitTestCase):
def test_single(self):
program = """
qreg q[1];
reset q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.reset(0)
self.assertEqual(parsed, qc)
def test_broadcast(self):
program = """
qreg q[2];
reset q;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.reset(0)
qc.reset(1)
self.assertEqual(parsed, qc)
def test_conditioned(self):
program = """
qreg q[2];
creg cond[1];
if (cond == 0) reset q[0];
if (cond == 1) reset q;
"""
parsed = qiskit.qasm2.loads(program)
cond = ClassicalRegister(1, "cond")
qc = QuantumCircuit(QuantumRegister(2, "q"), cond)
qc.reset(0).c_if(cond, 0)
qc.reset(0).c_if(cond, 1)
qc.reset(1).c_if(cond, 1)
self.assertEqual(parsed, qc)
def test_broadcast_against_empty_register(self):
program = """
qreg empty[0];
reset empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "empty"))
self.assertEqual(parsed, qc)
def test_conditioned_broadcast_against_empty_register(self):
program = """
qreg empty[0];
creg cond[1];
if (cond == 0) reset empty;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(0, "empty"), ClassicalRegister(1, "cond"))
self.assertEqual(parsed, qc)
class TestInclude(QiskitTestCase):
def setUp(self):
super().setUp()
self.tmp_dir = pathlib.Path(tempfile.mkdtemp())
def tearDown(self):
# Doesn't really matter if the removal fails, since this was a tempdir anyway; it'll get
# cleaned up by the OS at some point.
shutil.rmtree(self.tmp_dir, ignore_errors=True)
super().tearDown()
def test_qelib1_include(self):
program = """
include "qelib1.inc";
qreg q[3];
u3(0.5, 0.25, 0.125) q[0];
u2(0.5, 0.25) q[0];
u1(0.5) q[0];
cx q[0], q[1];
id q[0];
x q[0];
y q[0];
z q[0];
h q[0];
s q[0];
sdg q[0];
t q[0];
tdg q[0];
rx(0.5) q[0];
ry(0.5) q[0];
rz(0.5) q[0];
cz q[0], q[1];
cy q[0], q[1];
ch q[0], q[1];
ccx q[0], q[1], q[2];
crz(0.5) q[0], q[1];
cu1(0.5) q[0], q[1];
cu3(0.5, 0.25, 0.125) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(3, "q"))
qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0])
qc.append(lib.U2Gate(0.5, 0.25), [0])
qc.append(lib.U1Gate(0.5), [0])
qc.append(lib.CXGate(), [0, 1])
qc.append(lib.UGate(0, 0, 0), [0]) # Stand-in for id.
qc.append(lib.XGate(), [0])
qc.append(lib.YGate(), [0])
qc.append(lib.ZGate(), [0])
qc.append(lib.HGate(), [0])
qc.append(lib.SGate(), [0])
qc.append(lib.SdgGate(), [0])
qc.append(lib.TGate(), [0])
qc.append(lib.TdgGate(), [0])
qc.append(lib.RXGate(0.5), [0])
qc.append(lib.RYGate(0.5), [0])
qc.append(lib.RZGate(0.5), [0])
qc.append(lib.CZGate(), [0, 1])
qc.append(lib.CYGate(), [0, 1])
qc.append(lib.CHGate(), [0, 1])
qc.append(lib.CCXGate(), [0, 1, 2])
qc.append(lib.CRZGate(0.5), [0, 1])
qc.append(lib.CU1Gate(0.5), [0, 1])
qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1])
self.assertEqual(parsed, qc)
def test_qelib1_after_gate_definition(self):
program = """
gate bell a, b {
U(pi/2, 0, pi) a;
CX a, b;
}
include "qelib1.inc";
qreg q[2];
bell q[0], q[1];
rx(0.5) q[0];
bell q[1], q[0];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.u(math.pi / 2, 0, math.pi, 0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
qc.rx(0.5, 0)
qc.append(bell(), [1, 0])
self.assertEqual(parsed, qc)
def test_include_can_define_version(self):
include = """
OPENQASM 2.0;
qreg inner_q[2];
"""
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write(include)
program = """
OPENQASM 2.0;
include "include.qasm";
"""
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
qc = QuantumCircuit(QuantumRegister(2, "inner_q"))
self.assertEqual(parsed, qc)
def test_can_define_gates(self):
include = """
gate bell a, b {
h a;
cx a, b;
}
"""
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write(include)
program = """
OPENQASM 2.0;
include "qelib1.inc";
include "include.qasm";
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_nested_include(self):
inner = "creg c[2];"
with open(self.tmp_dir / "inner.qasm", "w") as fp:
fp.write(inner)
outer = """
qreg q[2];
include "inner.qasm";
"""
with open(self.tmp_dir / "outer.qasm", "w") as fp:
fp.write(outer)
program = """
OPENQASM 2.0;
include "outer.qasm";
"""
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
qc = QuantumCircuit(QuantumRegister(2, "q"), ClassicalRegister(2, "c"))
self.assertEqual(parsed, qc)
def test_first_hit_is_used(self):
empty = self.tmp_dir / "empty"
empty.mkdir()
first = self.tmp_dir / "first"
first.mkdir()
with open(first / "include.qasm", "w") as fp:
fp.write("qreg q[1];")
second = self.tmp_dir / "second"
second.mkdir()
with open(second / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
parsed = qiskit.qasm2.loads(program, include_path=(empty, first, second))
qc = QuantumCircuit(QuantumRegister(1, "q"))
self.assertEqual(parsed, qc)
def test_qelib1_ignores_search_path(self):
with open(self.tmp_dir / "qelib1.inc", "w") as fp:
fp.write("qreg not_used[2];")
program = 'include "qelib1.inc";'
parsed = qiskit.qasm2.loads(program, include_path=(self.tmp_dir,))
qc = QuantumCircuit()
self.assertEqual(parsed, qc)
def test_include_from_current_directory(self):
include = """
qreg q[2];
"""
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write(include)
program = """
OPENQASM 2.0;
include "include.qasm";
"""
prevdir = os.getcwd()
os.chdir(self.tmp_dir)
try:
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
finally:
os.chdir(prevdir)
def test_load_searches_source_directory(self):
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm")
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
def test_load_searches_source_directory_last(self):
first = self.tmp_dir / "first"
first.mkdir()
with open(first / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg not_used[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
parsed = qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_path=(first,))
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
def test_load_searches_source_directory_prepend(self):
first = self.tmp_dir / "first"
first.mkdir()
with open(first / "include.qasm", "w") as fp:
fp.write("qreg not_used[2];")
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
parsed = qiskit.qasm2.load(
self.tmp_dir / "program.qasm", include_path=(first,), include_input_directory="prepend"
)
qc = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(parsed, qc)
def test_load_can_ignore_source_directory(self):
with open(self.tmp_dir / "include.qasm", "w") as fp:
fp.write("qreg q[2];")
program = 'include "include.qasm";'
with open(self.tmp_dir / "program.qasm", "w") as fp:
fp.write(program)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unable to find 'include.qasm'"):
qiskit.qasm2.load(self.tmp_dir / "program.qasm", include_input_directory=None)
@ddt.ddt
class TestCustomInstructions(QiskitTestCase):
def test_qelib1_include_overridden(self):
program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
u3(0.5, 0.25, 0.125) q[0];
u2(0.5, 0.25) q[0];
u1(0.5) q[0];
cx q[0], q[1];
id q[0];
x q[0];
y q[0];
z q[0];
h q[0];
s q[0];
sdg q[0];
t q[0];
tdg q[0];
rx(0.5) q[0];
ry(0.5) q[0];
rz(0.5) q[0];
cz q[0], q[1];
cy q[0], q[1];
ch q[0], q[1];
ccx q[0], q[1], q[2];
crz(0.5) q[0], q[1];
cu1(0.5) q[0], q[1];
cu3(0.5, 0.25, 0.125) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(3, "q"))
qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0])
qc.append(lib.U2Gate(0.5, 0.25), [0])
qc.append(lib.U1Gate(0.5), [0])
qc.append(lib.CXGate(), [0, 1])
qc.append(lib.IGate(), [0])
qc.append(lib.XGate(), [0])
qc.append(lib.YGate(), [0])
qc.append(lib.ZGate(), [0])
qc.append(lib.HGate(), [0])
qc.append(lib.SGate(), [0])
qc.append(lib.SdgGate(), [0])
qc.append(lib.TGate(), [0])
qc.append(lib.TdgGate(), [0])
qc.append(lib.RXGate(0.5), [0])
qc.append(lib.RYGate(0.5), [0])
qc.append(lib.RZGate(0.5), [0])
qc.append(lib.CZGate(), [0, 1])
qc.append(lib.CYGate(), [0, 1])
qc.append(lib.CHGate(), [0, 1])
qc.append(lib.CCXGate(), [0, 1, 2])
qc.append(lib.CRZGate(0.5), [0, 1])
qc.append(lib.CU1Gate(0.5), [0, 1])
qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1])
self.assertEqual(parsed, qc)
# Also test that the output matches what Qiskit puts out.
from_qiskit = QuantumCircuit.from_qasm_str(program)
self.assertEqual(parsed, from_qiskit)
def test_qelib1_sparse_overrides(self):
"""Test that the qelib1 special import still works as expected when a couple of gates in the
middle of it are custom. As long as qelib1 is handled specially, there is a risk that this
handling will break in weird ways when custom instructions overlap it."""
program = """
include "qelib1.inc";
qreg q[3];
u3(0.5, 0.25, 0.125) q[0];
u2(0.5, 0.25) q[0];
u1(0.5) q[0];
cx q[0], q[1];
id q[0];
x q[0];
y q[0];
z q[0];
h q[0];
s q[0];
sdg q[0];
t q[0];
tdg q[0];
rx(0.5) q[0];
ry(0.5) q[0];
rz(0.5) q[0];
cz q[0], q[1];
cy q[0], q[1];
ch q[0], q[1];
ccx q[0], q[1], q[2];
crz(0.5) q[0], q[1];
cu1(0.5) q[0], q[1];
cu3(0.5, 0.25, 0.125) q[0], q[1];
"""
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("id", 0, 1, lib.IGate),
qiskit.qasm2.CustomInstruction("h", 0, 1, lib.HGate),
qiskit.qasm2.CustomInstruction("crz", 1, 2, lib.CRZGate),
],
)
qc = QuantumCircuit(QuantumRegister(3, "q"))
qc.append(lib.U3Gate(0.5, 0.25, 0.125), [0])
qc.append(lib.U2Gate(0.5, 0.25), [0])
qc.append(lib.U1Gate(0.5), [0])
qc.append(lib.CXGate(), [0, 1])
qc.append(lib.IGate(), [0])
qc.append(lib.XGate(), [0])
qc.append(lib.YGate(), [0])
qc.append(lib.ZGate(), [0])
qc.append(lib.HGate(), [0])
qc.append(lib.SGate(), [0])
qc.append(lib.SdgGate(), [0])
qc.append(lib.TGate(), [0])
qc.append(lib.TdgGate(), [0])
qc.append(lib.RXGate(0.5), [0])
qc.append(lib.RYGate(0.5), [0])
qc.append(lib.RZGate(0.5), [0])
qc.append(lib.CZGate(), [0, 1])
qc.append(lib.CYGate(), [0, 1])
qc.append(lib.CHGate(), [0, 1])
qc.append(lib.CCXGate(), [0, 1, 2])
qc.append(lib.CRZGate(0.5), [0, 1])
qc.append(lib.CU1Gate(0.5), [0, 1])
qc.append(lib.CU3Gate(0.5, 0.25, 0.125), [0, 1])
self.assertEqual(parsed, qc)
def test_user_gate_after_overidden_qelib1(self):
program = """
include "qelib1.inc";
qreg q[1];
opaque my_gate q;
my_gate q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(Gate("my_gate", 1, []), [0])
self.assertEqual(parsed, qc)
def test_qiskit_extra_builtins(self):
program = """
qreg q[5];
u(0.5 ,0.25, 0.125) q[0];
p(0.5) q[0];
sx q[0];
sxdg q[0];
swap q[0], q[1];
cswap q[0], q[1], q[2];
crx(0.5) q[0], q[1];
cry(0.5) q[0], q[1];
cp(0.5) q[0], q[1];
csx q[0], q[1];
cu(0.5, 0.25, 0.125, 0.0625) q[0], q[1];
rxx(0.5) q[0], q[1];
rzz(0.5) q[0], q[1];
rccx q[0], q[1], q[2];
rc3x q[0], q[1], q[2], q[3];
c3x q[0], q[1], q[2], q[3];
c3sqrtx q[0], q[1], q[2], q[3];
c4x q[0], q[1], q[2], q[3], q[4];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(5, "q"))
qc.append(lib.UGate(0.5, 0.25, 0.125), [0])
qc.append(lib.PhaseGate(0.5), [0])
qc.append(lib.SXGate(), [0])
qc.append(lib.SXdgGate(), [0])
qc.append(lib.SwapGate(), [0, 1])
qc.append(lib.CSwapGate(), [0, 1, 2])
qc.append(lib.CRXGate(0.5), [0, 1])
qc.append(lib.CRYGate(0.5), [0, 1])
qc.append(lib.CPhaseGate(0.5), [0, 1])
qc.append(lib.CSXGate(), [0, 1])
qc.append(lib.CUGate(0.5, 0.25, 0.125, 0.0625), [0, 1])
qc.append(lib.RXXGate(0.5), [0, 1])
qc.append(lib.RZZGate(0.5), [0, 1])
qc.append(lib.RCCXGate(), [0, 1, 2])
qc.append(lib.RC3XGate(), [0, 1, 2, 3])
qc.append(lib.C3XGate(), [0, 1, 2, 3])
qc.append(lib.C3SXGate(), [0, 1, 2, 3])
qc.append(lib.C4XGate(), [0, 1, 2, 3, 4])
self.assertEqual(parsed, qc)
# There's also the 'u0' gate, but this is weird so we don't wildly care what its definition
# is and it has no Qiskit equivalent, so we'll just test that it using it doesn't produce an
# error.
parsed = qiskit.qasm2.loads(
"qreg q[1]; u0(1) q[0];", custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
self.assertEqual(parsed.data[0].operation.name, "u0")
def test_qiskit_override_delay_opaque(self):
program = """
opaque delay(t) q;
qreg q[1];
delay(1) q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.delay(1, 0, unit="dt")
self.assertEqual(parsed, qc)
def test_qiskit_override_u0_opaque(self):
program = """
opaque u0(n) q;
qreg q[1];
u0(2) q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.id(0)
qc.id(0)
self.assertEqual(parsed.decompose(), qc)
def test_can_override_u(self):
program = """
qreg q[1];
U(0.5, 0.25, 0.125) q[0];
"""
class MyGate(Gate):
def __init__(self, a, b, c):
super().__init__("u", 1, [a, b, c])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("U", 3, 1, MyGate, builtin=True)],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5, 0.25, 0.125), [0])
self.assertEqual(parsed, qc)
def test_can_override_cx(self):
program = """
qreg q[2];
CX q[0], q[1];
"""
class MyGate(Gate):
def __init__(self):
super().__init__("cx", 2, [])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 2, MyGate, builtin=True)],
)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(MyGate(), [0, 1])
self.assertEqual(parsed, qc)
@ddt.data(lambda x: x, reversed)
def test_can_override_both_builtins_with_other_gates(self, order):
program = """
gate unimportant q {}
qreg q[2];
U(0.5, 0.25, 0.125) q[0];
CX q[0], q[1];
"""
class MyUGate(Gate):
def __init__(self, a, b, c):
super().__init__("u", 1, [a, b, c])
class MyCXGate(Gate):
def __init__(self):
super().__init__("cx", 2, [])
custom = [
qiskit.qasm2.CustomInstruction("unused", 0, 1, lambda: Gate("unused", 1, [])),
qiskit.qasm2.CustomInstruction("U", 3, 1, MyUGate, builtin=True),
qiskit.qasm2.CustomInstruction("CX", 0, 2, MyCXGate, builtin=True),
]
custom = order(custom)
parsed = qiskit.qasm2.loads(program, custom_instructions=custom)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(MyUGate(0.5, 0.25, 0.125), [0])
qc.append(MyCXGate(), [0, 1])
self.assertEqual(parsed, qc)
def test_custom_builtin_gate(self):
program = """
qreg q[1];
builtin(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("builtin", 1, [a])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True)
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_builtin_as_gate(self):
program = """
qreg q[1];
gate builtin(t) q {}
builtin(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("builtin", 1, [a])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True)
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_builtin_as_opaque(self):
program = """
qreg q[1];
opaque builtin(t) q;
builtin(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("builtin", 1, [a])
parsed = qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 1, 1, MyGate, builtin=True)
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_custom_as_gate(self):
program = """
qreg q[1];
gate my_gate(t) q {}
my_gate(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("my_gate", 1, [a])
parsed = qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)]
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
def test_can_define_custom_as_opaque(self):
program = """
qreg q[1];
opaque my_gate(t) q;
my_gate(0.5) q[0];
"""
class MyGate(Gate):
def __init__(self, a):
super().__init__("my_gate", 1, [a])
parsed = qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 1, 1, MyGate)]
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.append(MyGate(0.5), [0])
self.assertEqual(parsed, qc)
class TestCustomClassical(QiskitTestCase):
def test_qiskit_extensions(self):
program = """
include "qelib1.inc";
qreg q[1];
rx(asin(0.3)) q[0];
ry(acos(0.3)) q[0];
rz(atan(0.3)) q[0];
"""
parsed = qiskit.qasm2.loads(program, custom_classical=qiskit.qasm2.LEGACY_CUSTOM_CLASSICAL)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.rx(math.asin(0.3), 0)
qc.ry(math.acos(0.3), 0)
qc.rz(math.atan(0.3), 0)
self.assertEqual(parsed, qc)
def test_zero_parameter_custom(self):
program = """
qreg q[1];
U(f(), 0, 0) q[0];
"""
parsed = qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: 0.2)]
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.u(0.2, 0, 0, 0)
self.assertEqual(parsed, qc)
def test_multi_parameter_custom(self):
program = """
qreg q[1];
U(f(0.2), g(0.4, 0.1), h(1, 2, 3)) q[0];
"""
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 1, lambda x: 1 + x),
qiskit.qasm2.CustomClassical("g", 2, math.atan2),
qiskit.qasm2.CustomClassical("h", 3, lambda x, y, z: z - y + x),
],
)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.u(1.2, math.atan2(0.4, 0.1), 2, 0)
self.assertEqual(parsed, qc)
def test_use_in_gate_definition(self):
# pylint: disable=invalid-name
program = """
gate my_gate(a, b) q {
U(f(a, b), g(f(b, f(b, a))), b) q;
}
qreg q[1];
my_gate(0.5, 0.25) q[0];
my_gate(0.25, 0.5) q[0];
"""
f = lambda x, y: x - y
g = lambda x: 2 * x
parsed = qiskit.qasm2.loads(
program,
custom_classical=[
qiskit.qasm2.CustomClassical("f", 2, f),
qiskit.qasm2.CustomClassical("g", 1, g),
],
)
first_gate = parsed.data[0].operation
second_gate = parsed.data[1].operation
self.assertEqual(list(first_gate.params), [0.5, 0.25])
self.assertEqual(list(second_gate.params), [0.25, 0.5])
self.assertEqual(
list(first_gate.definition.data[0].operation.params),
[
f(0.5, 0.25),
g(f(0.25, f(0.25, 0.5))),
0.25,
],
)
self.assertEqual(
list(second_gate.definition.data[0].operation.params),
[
f(0.25, 0.5),
g(f(0.5, f(0.5, 0.25))),
0.5,
],
)
@ddt.ddt
class TestStrict(QiskitTestCase):
@ddt.data(
"gate my_gate(p0, p1$) q0, q1 {}",
"gate my_gate(p0, p1) q0, q1$ {}",
"opaque my_gate(p0, p1$) q0, q1;",
"opaque my_gate(p0, p1) q0, q1$;",
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125$) q[0], q[1];',
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1]$;',
"qreg q[2]; barrier q[0], q[1]$;",
'include "qelib1.inc"; qreg q[1]; rx(sin(pi$)) q[0];',
)
def test_trailing_comma(self, program):
without = qiskit.qasm2.loads("OPENQASM 2.0;\n" + program.replace("$", ""), strict=True)
with_ = qiskit.qasm2.loads(program.replace("$", ","), strict=False)
self.assertEqual(with_, without)
def test_trailing_semicolon_after_gate(self):
program = """
include "qelib1.inc";
gate bell a, b {
h a;
cx a, b;
}; // <- the important bit of the test
qreg q[2];
bell q[0], q[1];
"""
parsed = qiskit.qasm2.loads(program)
bell_def = QuantumCircuit([Qubit(), Qubit()])
bell_def.h(0)
bell_def.cx(0, 1)
bell = gate_builder("bell", [], bell_def)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.append(bell(), [0, 1])
self.assertEqual(parsed, qc)
def test_empty_statement(self):
# This is allowed more as a side-effect of allowing the trailing semicolon after gate
# definitions.
program = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
h q[0];
;
cx q[0], q[1];
;;;;
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(2, "q"))
qc.h(0)
qc.cx(0, 1)
self.assertEqual(parsed, qc)
def test_single_quoted_path(self):
program = """
include 'qelib1.inc';
qreg q[1];
h q[0];
"""
parsed = qiskit.qasm2.loads(program)
qc = QuantumCircuit(QuantumRegister(1, "q"))
qc.h(0)
self.assertEqual(parsed, qc)
|
https://github.com/suvoooo/Qubits-Qiskit
|
suvoooo
|
# !pip3 install qiskit
import numpy as np
import qiskit as q
### build a circuit for 3 qubits
qr = q.QuantumRegister(3)
circ = q.QuantumCircuit(qr)
### add the first H gate (in qiskit east significant bit has the lowest index)
circ.h(qr[2])
### add the controlled phase gate
circ.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2
### add the next cp gate
circ.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2
### repeat the process for qubit 1
circ.h(qr[1])
circ.cp(np.pi/2, qr[0], qr[1])
### add the final h gate
circ.h(qr[0])
### finally swap the bits 0 th, and 2nd qubit
circ.swap(qr[0], qr[2])
circ.draw()
from google.colab import drive
drive.mount('/content/drive')
# !pip install pylatexenc
path='/content/drive/My Drive/Colab Notebooks/'
style = {'backgroundcolor': 'lavender', 'dpi':200, 'subfontsize':10}
circ.draw('mpl', scale=0.8, style=style, filename=path+'qfouriert_3bits.png')
qr = q.QuantumRegister(3)
circ1 = q.QuantumCircuit(qr)
### encode the state 110 at first
circ1.x(qr[2])
circ1.x(qr[1])
### repeat what's done before
### add the first H gate (in qiskit east significant bit has the lowest index)
circ1.h(qr[2])
### add the controlled phase gate
circ1.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2
### add the next cp gate
circ1.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2
### repeat the process for qubit 1
circ1.h(qr[1])
circ1.cp(np.pi/2, qr[0], qr[1])
### add the final h gate
circ1.h(qr[0])
### finally swap the bits 0 th, and 2nd qubit
circ1.swap(qr[0], qr[2])
circ1.draw()
circ1.save_statevector()
qasm_sim = q.Aer.get_backend('qasm_simulator')
statevector = qasm_sim.run(circ1).result().get_statevector()
q.visualization.plot_bloch_multivector(statevector)
qr = q.QuantumRegister(3)
circ2 = q.QuantumCircuit(qr)
### encode the state 101 at first
circ2.x(qr[2])
circ2.x(qr[0])
### repeat what's done before
### add the first H gate (in qiskit east significant bit has the lowest index)
circ2.h(qr[2])
### add the controlled phase gate
circ2.cp(np.pi/2, qr[1], qr[2]) # based on qubit 1 apply 2pi/2**(k-1) rotation to qubit 2
### add the next cp gate
circ2.cp(np.pi/4, qr[0], qr[2]) # based on qubit 0 apply 2pi/2**(k-1) rotation to qubit 2
### repeat the process for qubit 1
circ2.h(qr[1])
circ2.cp(np.pi/2, qr[0], qr[1])
### add the final h gate
circ2.h(qr[0])
### finally swap the bits 0 th, and 2nd qubit
circ2.swap(qr[0], qr[2])
circ2.draw()
circ2.save_statevector()
qasm_sim = q.Aer.get_backend('qasm_simulator')
statevector2 = qasm_sim.run(circ2).result().get_statevector()
q.visualization.plot_bloch_multivector(statevector2)
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# set the length of the $n$-bit string.
n = 2
# set the oracle, b for balanced, c for constant
oracle = "b"
# if the oracle is balanced, set the hidden bitstring, b
if oracle == "b":
b = 3 # np.random.randint(1,2**n) uncomment for a random value
# if the oracle is constant, set c = 0 or 1 randomly.
if oracle == "c":
c = np.random.randint(2)
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1)
cr = ClassicalRegister(n)
djCircuit = QuantumCircuit(qr, cr)
barriers = True
# Since all qubits are initialized to |0>, we need to flip the second register qubit to the the |1> state
djCircuit.x(qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to all qubits
djCircuit.h(qr)
# Apply barrier
if barriers:
djCircuit.barrier()
# Query the oracle
if oracle == "c": # if the oracle is constant, return c
if c == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # otherwise, the oracle is balanced and it returns the inner product of the input with b (non-zero bitstring)
for i in range(n):
if (b & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to the first register after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measure the first register
for i in range(n):
djCircuit.measure(qr[i], cr[i])
djCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(djCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(djCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile, QuantumCircuit
import qiskit.quantum_info as qi
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, amplitude_damping_error
from qiskit.tools.visualization import plot_histogram
# CNOT matrix operator with qubit-0 as control and qubit-1 as target
cx_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]])
# iSWAP matrix operator
iswap_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1]])
# CNOT in terms of iSWAP and single-qubit gates
cx_circ = QuantumCircuit(2, name='cx<iSWAP>')
# Add gates
cx_circ.sdg(1)
cx_circ.h(1)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.sdg(0)
cx_circ.h(0)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.s(1)
print(cx_circ)
# Simulate the unitary for the circuit using Operator:
unitary = qi.Operator(cx_circ)
print(unitary)
f_ave = qi.average_gate_fidelity(cx_op, unitary)
print("Average Gate Fidelity: F = {:f}".format(f_ave))
'unitary' in AerSimulator().configuration().basis_gates
# Error parameters
param_q0 = 0.05 # damping parameter for qubit-0
param_q1 = 0.1 # damping parameter for qubit-1
# Construct the error
qerror_q0 = amplitude_damping_error(param_q0)
qerror_q1 = amplitude_damping_error(param_q1)
iswap_error = qerror_q1.tensor(qerror_q0)
# Build the noise model by adding the error to the "iswap" gate
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap')
noise_model.add_basis_gates(['unitary'])
print(noise_model.basis_gates)
# Bell state circuit where iSWAPS should be inserted at barrier locations
bell_circ = QuantumCircuit(2, 2, name='bell')
bell_circ.h(0)
bell_circ.append(cx_circ, [0, 1])
bell_circ.measure([0,1], [0,1])
print(bell_circ)
# Create ideal simulator backend and transpile circuit
sim_ideal = AerSimulator()
tbell_circ = transpile(bell_circ, sim_ideal)
ideal_result = sim_ideal.run(tbell_circ).result()
ideal_counts = ideal_result.get_counts(0)
plot_histogram(ideal_counts,
title='Ideal output for iSWAP bell-state preparation')
# Create noisy simulator and transpile circuit
sim_noise = AerSimulator(noise_model=noise_model)
tbell_circ_noise = transpile(bell_circ, sim_noise)
# Run on the simulator without noise
noise_result = sim_noise.run(tbell_circ_noise).result()
noise_counts = noise_result.get_counts(bell_circ)
plot_histogram(noise_counts,
title='Noisy output for iSWAP bell-state preparation')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-alt
|
qiskit-community
|
import subprocess
import shutil
import os
# Include these lines if we run all files in one process
import qiskit_alt
qiskit_alt.project.ensure_init()
bench_scripts = [
"fermionic_alt_time.py",
"fermionic_nature_time.py",
"from_matrix_alt.py",
"from_matrix_quantum_info.py",
"jordan_wigner_alt_time.py",
"jordan_wigner_nature_time.py",
"pauli_from_list_alt.py",
"pauli_from_list_qinfo.py",
]
_python = shutil.which("python")
## Run each benchmark script in a separate process
def run_bench(fname):
dirname = os.path.dirname(os.path.abspath(__file__))
full = os.path.join(dirname, fname)
res = subprocess.run(
[_python, full], check=True, capture_output=True, encoding='utf8'
).stdout
print(res)
def exec_full_dir(fname):
dirname = os.path.dirname(os.path.abspath(__file__))
filepath = os.path.join(dirname, fname)
exec_full(filepath)
def exec_full(filepath):
global_namespace = {
"__file__": filepath,
"__name__": "__main__",
}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
for fname in bench_scripts:
print(fname)
exec_full_dir(fname)
print()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Controlled-RY (cry) and Multiple-Control RY (mcry) Gates
"""
import logging
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.aqua import AquaError
from qiskit.aqua.utils.circuit_utils import is_qubit
logger = logging.getLogger(__name__)
def cry(self, theta, q_control, q_target):
"""
Apply Controlled-RY (cry) Gate.
Args:
self (QuantumCircuit): The circuit to apply the ch gate on.
theta (float): The rotation angle.
q_control ((QuantumRegister, int)): The control qubit.
q_target ((QuantumRegister, int)): The target qubit.
"""
if not is_qubit(q_control):
raise AquaError('A qubit is expected for the control.')
if not self.has_register(q_control[0]):
raise AquaError('The control qubit is expected to be part of the circuit.')
if not is_qubit(q_target):
raise AquaError('A qubit is expected for the target.')
if not self.has_register(q_target[0]):
raise AquaError('The target qubit is expected to be part of the circuit.')
if q_control == q_target:
raise AquaError('The control and target need to be different qubits.')
self.u3(theta / 2, 0, 0, q_target)
self.cx(q_control, q_target)
self.u3(-theta / 2, 0, 0, q_target)
self.cx(q_control, q_target)
return self
def mcry(self, theta, q_controls, q_target, q_ancillae):
"""
Apply Multiple-Control RY (mcry) Gate.
Args:
self (QuantumCircuit): The circuit to apply the ch gate on.
theta (float): The rotation angle.
q_controls (QuantumRegister | (QuantumRegister, int)): The control qubits.
q_target ((QuantumRegister, int)): The target qubit.
q_ancillae (QuantumRegister | (QuantumRegister, int)): The ancillary qubits.
"""
# check controls
if isinstance(q_controls, QuantumRegister):
control_qubits = [qb for qb in q_controls]
elif isinstance(q_controls, list):
control_qubits = q_controls
else:
raise AquaError('The mcry gate needs a list of qubits or a quantum register for controls.')
# check target
if is_qubit(q_target):
target_qubit = q_target
else:
raise AquaError('The mcry gate needs a single qubit as target.')
# check ancilla
if q_ancillae is None:
ancillary_qubits = []
elif isinstance(q_ancillae, QuantumRegister):
ancillary_qubits = [qb for qb in q_ancillae]
elif isinstance(q_ancillae, list):
ancillary_qubits = q_ancillae
else:
raise AquaError('The mcry gate needs None or a list of qubits or a quantum register for ancilla.')
all_qubits = control_qubits + [target_qubit] + ancillary_qubits
self._check_qargs(all_qubits)
self._check_dups(all_qubits)
self.u3(theta / 2, 0, 0, q_target)
self.mct(q_controls, q_target, q_ancillae)
self.u3(-theta / 2, 0, 0, q_target)
self.mct(q_controls, q_target, q_ancillae)
return self
QuantumCircuit.cry = cry
QuantumCircuit.mcry = mcry
|
https://github.com/Aurelien-Pelissier/IBMQ-Quantum-Programming
|
Aurelien-Pelissier
|
from qiskit import*
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
quantum_register = QuantumRegister(2) # Linhas do circuito / numeros de Qbit no circuito
""" Para medir, em mecanica quântica, ao medir um Qbit nós destruimos a informação daquele estado
e armazenamos ela em um bit clássico """
classic_register = ClassicalRegister(2)
first_circuit = QuantumCircuit(quantum_register, classic_register) # Constrói o circuito
first_circuit.draw(output = 'mpl') # Desenha o circuito, funciona no app da IBM
first_circuit.h(quantum_register[0]) # Aplicando a primeira gate no primeira linha, gate hadarmat
# Aplicando a porta CNOT
###
first_circuit.draw(output = 'mpl')
###
first_circuit.cx(quantum_register[0], quantum_register[1]) #CNOT faz operação tensorial entre o Qbit
#de controle na linha zero, e o outro é o Qbit alvo
###
first_circuit.draw(output = 'mpl')
###
first_circuit.measure(quantum_register, classic_register) # para extrair a medida
###
first_circuit.draw(output = 'mpl')
###
simulator = QasmSimulator() # Simulador que vai realizar os calculos para nós
result = execute(first_circuit, backend= simulator).result()
counts = result.get_counts(first_circuit)
first_circuit.draw(output='mpl')
plot_histogram(counts)
plt.ylabel(counts)
plt.show()
"""
IBMQ.load_account()
host = IBMQ.get_provider('ibm-q')
quantum_computer = host.get_backend('ibmq_belem')
result_qcomputer = execute(first_circuit, backend= quantum_computer)
job_monitor(result_qcomputer)
result = result_qcomputer.result()
plot_histogram(result.get_counts(first_circuit))
plt.ylabel(counts)
plt.show()
"""
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXDebugging())
|
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/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
from qiskit import Aer
from qiskit.transpiler import PassManager
from qiskit_aqua import Operator, QuantumInstance
from qiskit_aqua.algorithms.adaptive import VQE
from qiskit_aqua.algorithms.classical import ExactEigensolver
from qiskit_aqua.components.optimizers import L_BFGS_B
from qiskit_aqua.components.variational_forms import RYRZ
from qiskit_chemistry import FermionicOperator
from qiskit_chemistry.drivers import PySCFDriver, UnitsType
# using driver to get fermionic Hamiltonian
# PySCF example
driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
molecule = driver.run()
# get fermionic operator and mapping to qubit operator
ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
qubitOp = ferOp.mapping(map_type='JORDAN_WIGNER', threshold=0.00000001)
qubitOp.to_matrix()
qubitOp.chop(10**-10)
# If you do not install any driver and would like to start with a random Hamiltonian
# SIZE=4
# matrix = np.random.random((SIZE,SIZE))
# qubitOp = Operator(matrix=matrix)
# Using exact eigensolver to get the smallest eigenvalue
exact_eigensolver = ExactEigensolver(qubitOp, k=1)
ret = exact_eigensolver.run()
print('The exact ground state energy is: {}'.format(ret['eigvals'][0].real))
# setup VQE
# setup optimizer, use L_BFGS_B optimizer for example
lbfgs = L_BFGS_B(maxfun=1000, factr=10, iprint=10)
# setup variational form generator (generate trial circuits for VQE)
var_form = RYRZ(qubitOp.num_qubits, 5, entangler_map = {0: [1], 1:[2], 2:[3]})
# setup VQE with operator, variational form, and optimizer
vqe_algorithm = VQE(qubitOp, var_form, lbfgs, 'matrix')
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, pass_manager=PassManager())
results = vqe_algorithm.run(quantum_instance)
print("Minimum value: {}".format(results['eigvals'][0].real))
print("Parameters: {}".format(results['opt_params']))
|
https://github.com/hkhetawat/QArithmetic
|
hkhetawat
|
# Import the Qiskit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from QArithmetic import sub_ripple
# Input N
N = 4
a = QuantumRegister(N)
b = QuantumRegister(N+1)
ca = ClassicalRegister(N)
cb = ClassicalRegister(N+1)
qc = QuantumCircuit(a, b, ca, cb)
# Input Superposition
# a = 1110
qc.x(a[1])
qc.x(a[2])
qc.x(a[3])
# b = 01011
qc.x(b[0])
qc.x(b[1])
qc.x(b[3])
sub_ripple(qc, a, b, N)
qc.measure(a, ca)
qc.measure(b, cb)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the VF2Layout pass"""
import rustworkx
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import ControlFlowOp
from qiskit.circuit.library import CXGate, XGate
from qiskit.transpiler import CouplingMap, Layout, TranspilerError
from qiskit.transpiler.passes.layout.vf2_post_layout import VF2PostLayout, VF2PostLayoutStopReason
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeLima, FakeYorktown, FakeLimaV2, FakeYorktownV2
from qiskit.circuit import Qubit
from qiskit.compiler.transpiler import transpile
from qiskit.transpiler.target import Target, InstructionProperties
class TestVF2PostLayout(QiskitTestCase):
"""Tests the VF2Layout pass"""
seed = 42
def assertLayout(self, dag, coupling_map, property_set):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(
property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
)
layout = property_set["post_layout"]
edges = coupling_map.graph.edge_list()
def run(dag, wire_map):
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
continue
physical_q0 = wire_map[gate.qargs[0]]
physical_q1 = wire_map[gate.qargs[1]]
self.assertTrue((physical_q0, physical_q1) in edges)
for node in dag.op_nodes(ControlFlowOp):
for block in node.op.blocks:
inner_wire_map = {
inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
}
run(circuit_to_dag(block), inner_wire_map)
run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout})
def assertLayoutV2(self, dag, target, property_set):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(
property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
)
layout = property_set["post_layout"]
def run(dag, wire_map):
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate) or isinstance(gate.op, ControlFlowOp):
continue
physical_q0 = wire_map[gate.qargs[0]]
physical_q1 = wire_map[gate.qargs[1]]
qargs = (physical_q0, physical_q1)
self.assertTrue(target.instruction_supported(gate.name, qargs))
for node in dag.op_nodes(ControlFlowOp):
for block in node.op.blocks:
inner_wire_map = {
inner: wire_map[outer] for outer, inner in zip(node.qargs, block.qubits)
}
run(circuit_to_dag(block), inner_wire_map)
run(dag, {bit: layout[bit] for bit in dag.qubits if bit in layout})
def test_no_constraints(self):
"""Test we raise at runtime if no target or coupling graph specified."""
qc = QuantumCircuit(2)
empty_pass = VF2PostLayout()
with self.assertRaises(TranspilerError):
empty_pass.run(circuit_to_dag(qc))
def test_no_backend_properties(self):
"""Test we raise at runtime if no properties are provided with a coupling graph."""
qc = QuantumCircuit(2)
empty_pass = VF2PostLayout(coupling_map=CouplingMap([(0, 1), (1, 2)]))
with self.assertRaises(TranspilerError):
empty_pass.run(circuit_to_dag(qc))
def test_empty_circuit(self):
"""Test no solution found for empty circuit"""
qc = QuantumCircuit(2, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_empty_circuit_v2(self):
"""Test no solution found for empty circuit with v2 backend"""
qc = QuantumCircuit(2, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_skip_3q_circuit(self):
"""Test that the pass is a no-op on circuits with >2q gates."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_skip_3q_circuit_control_flow(self):
"""Test that the pass is a no-op on circuits with >2q gates."""
qc = QuantumCircuit(3)
with qc.for_loop((1,)):
qc.ccx(0, 1, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_skip_3q_circuit_v2(self):
"""Test that the pass is a no-op on circuits with >2q gates with a target."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_skip_3q_circuit_control_flow_v2(self):
"""Test that the pass is a no-op on circuits with >2q gates with a target."""
qc = QuantumCircuit(3)
with qc.for_loop((1,)):
qc.ccx(0, 1, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_best_mapping_ghz_state_full_device_multiple_qregs(self):
"""Test best mappings with multiple registers"""
backend = FakeLima()
qr_a = QuantumRegister(2)
qr_b = QuantumRegister(3)
qc = QuantumCircuit(qr_a, qr_b)
qc.h(qr_a[0])
qc.cx(qr_a[0], qr_a[1])
qc.cx(qr_a[0], qr_b[0])
qc.cx(qr_a[0], qr_b[1])
qc.cx(qr_a[0], qr_b[2])
qc.measure_all()
tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial")
initial_layout = tqc._layout
dag = circuit_to_dag(tqc)
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktown()
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
tqc = transpile(circuit, backend, layout_method="dense")
initial_layout = tqc._layout
dag = circuit_to_dag(tqc)
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend_controlflow(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktown()
circuit = QuantumCircuit(2, 1)
with circuit.for_loop((1,)):
circuit.cx(1, 0) # qr1 -> qr0
with circuit.if_test((circuit.clbits[0], True)) as else_:
pass
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(1, 0) # qr1 -> qr0
initial_layout = Layout(dict(enumerate(circuit.qubits)))
circuit._layout = initial_layout
dag = circuit_to_dag(circuit)
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend_max_trials(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
max_trials = 11
backend = FakeYorktown()
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
tqc = transpile(circuit, backend, layout_method="dense")
initial_layout = tqc._layout
dag = circuit_to_dag(tqc)
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
pass_ = VF2PostLayout(
coupling_map=cmap, properties=props, seed=self.seed, max_trials=max_trials
)
with self.assertLogs(
"qiskit.transpiler.passes.layout.vf2_post_layout", level="DEBUG"
) as cm:
pass_.run(dag)
self.assertIn(
f"DEBUG:qiskit.transpiler.passes.layout.vf2_post_layout:Trial {max_trials} "
f"is >= configured max trials {max_trials}",
cm.output,
)
self.assertLayout(dag, cmap, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_best_mapping_ghz_state_full_device_multiple_qregs_v2(self):
"""Test best mappings with multiple registers"""
backend = FakeLimaV2()
qr_a = QuantumRegister(2)
qr_b = QuantumRegister(3)
qc = QuantumCircuit(qr_a, qr_b)
qc.h(qr_a[0])
qc.cx(qr_a[0], qr_a[1])
qc.cx(qr_a[0], qr_b[0])
qc.cx(qr_a[0], qr_b[1])
qc.cx(qr_a[0], qr_b[2])
qc.measure_all()
tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial")
initial_layout = tqc._layout
dag = circuit_to_dag(tqc)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend_v2(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktownV2()
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
tqc = transpile(circuit, backend, layout_method="dense")
initial_layout = tqc._layout
dag = circuit_to_dag(tqc)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend_v2_control_flow(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktownV2()
circuit = QuantumCircuit(2, 1)
with circuit.for_loop((1,)):
circuit.cx(1, 0) # qr1 -> qr0
with circuit.if_test((circuit.clbits[0], True)) as else_:
pass
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(1, 0) # qr1 -> qr0
initial_layout = Layout(dict(enumerate(circuit.qubits)))
circuit._layout = initial_layout
dag = circuit_to_dag(circuit)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_target_invalid_2q_gate(self):
"""Test that we don't find a solution with a gate outside target."""
backend = FakeYorktownV2()
qc = QuantumCircuit(2)
qc.ecr(0, 1)
dag = circuit_to_dag(qc)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertEqual(
pass_.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_target_invalid_2q_gate_control_flow(self):
"""Test that we don't find a solution with a gate outside target."""
backend = FakeYorktownV2()
qc = QuantumCircuit(2)
with qc.for_loop((1,)):
qc.ecr(0, 1)
dag = circuit_to_dag(qc)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed)
pass_.run(dag)
self.assertEqual(
pass_.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_target_no_error(self):
"""Test that running vf2layout on a pass against a target with no error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2PostLayout(target=target)
circuit = QuantumCircuit(2)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
self.assertNotIn("post_layout", vf2_pass.property_set)
def test_target_some_error(self):
"""Test that running vf2layout on a pass against a target with some error rates works."""
n_qubits = 15
target = Target()
target.add_instruction(
XGate(), {(i,): InstructionProperties(error=0.00123) for i in range(n_qubits)}
)
target.add_instruction(CXGate(), {(i, i + 1): None for i in range(n_qubits - 1)})
vf2_pass = VF2PostLayout(target=target, seed=1234, strict_direction=False)
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
dag = circuit_to_dag(circuit)
vf2_pass.run(dag)
# No layout selected because nothing will beat initial layout
self.assertNotIn("post_layout", vf2_pass.property_set)
class TestVF2PostLayoutScoring(QiskitTestCase):
"""Test scoring heuristic function for VF2PostLayout."""
def test_empty_score(self):
"""Test error rate is 0 for empty circuit."""
bit_map = {}
reverse_bit_map = {}
im_graph = rustworkx.PyDiGraph()
backend = FakeYorktownV2()
vf2_pass = VF2PostLayout(target=backend.target)
layout = Layout()
score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph)
self.assertEqual(0, score)
def test_all_1q_score(self):
"""Test error rate for all 1q input."""
bit_map = {Qubit(): 0, Qubit(): 1}
reverse_bit_map = {v: k for k, v in bit_map.items()}
im_graph = rustworkx.PyDiGraph()
im_graph.add_node({"sx": 1})
im_graph.add_node({"sx": 1})
backend = FakeYorktownV2()
vf2_pass = VF2PostLayout(target=backend.target)
layout = Layout(bit_map)
score = vf2_pass._score_layout(layout, bit_map, reverse_bit_map, im_graph)
self.assertAlmostEqual(0.002925, score, places=5)
class TestVF2PostLayoutUndirected(QiskitTestCase):
"""Tests the VF2Layout pass"""
seed = 42
def assertLayout(self, dag, coupling_map, property_set):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(
property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
)
layout = property_set["post_layout"]
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate):
continue
physical_q0 = layout[gate.qargs[0]]
physical_q1 = layout[gate.qargs[1]]
self.assertTrue(coupling_map.graph.has_edge(physical_q0, physical_q1))
def assertLayoutV2(self, dag, target, property_set):
"""Checks if the circuit in dag was a perfect layout in property_set for the given
coupling_map"""
self.assertEqual(
property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.SOLUTION_FOUND
)
layout = property_set["post_layout"]
for gate in dag.two_qubit_ops():
if dag.has_calibration_for(gate):
continue
physical_q0 = layout[gate.qargs[0]]
physical_q1 = layout[gate.qargs[1]]
qargs = (physical_q0, physical_q1)
self.assertTrue(target.instruction_supported(gate.name, qargs))
def test_no_constraints(self):
"""Test we raise at runtime if no target or coupling graph specified."""
qc = QuantumCircuit(2)
empty_pass = VF2PostLayout(strict_direction=False)
with self.assertRaises(TranspilerError):
empty_pass.run(circuit_to_dag(qc))
def test_no_backend_properties(self):
"""Test we raise at runtime if no properties are provided with a coupling graph."""
qc = QuantumCircuit(2)
empty_pass = VF2PostLayout(
coupling_map=CouplingMap([(0, 1), (1, 2)]), strict_direction=False
)
with self.assertRaises(TranspilerError):
empty_pass.run(circuit_to_dag(qc))
def test_empty_circuit(self):
"""Test no solution found for empty circuit"""
qc = QuantumCircuit(2, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_empty_circuit_v2(self):
"""Test no solution found for empty circuit with v2 backend"""
qc = QuantumCircuit(2, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"],
VF2PostLayoutStopReason.NO_SOLUTION_FOUND,
)
def test_skip_3q_circuit(self):
"""Test that the pass is a no-op on circuits with >2q gates."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
backend = FakeLima()
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_skip_3q_circuit_v2(self):
"""Test that the pass is a no-op on circuits with >2q gates with a target."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
backend = FakeLimaV2()
vf2_pass = VF2PostLayout(target=backend.target, strict_direction=False)
vf2_pass.run(circuit_to_dag(qc))
self.assertEqual(
vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q
)
def test_best_mapping_ghz_state_full_device_multiple_qregs(self):
"""Test best mappings with multiple registers"""
backend = FakeLima()
qr_a = QuantumRegister(2)
qr_b = QuantumRegister(3)
qc = QuantumCircuit(qr_a, qr_b)
qc.h(qr_a[0])
qc.cx(qr_a[0], qr_a[1])
qc.cx(qr_a[0], qr_b[0])
qc.cx(qr_a[0], qr_b[1])
qc.cx(qr_a[0], qr_b[2])
qc.measure_all()
tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial")
initial_layout = tqc._layout
dag = circuit_to_dag(tqc)
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
pass_ = VF2PostLayout(
coupling_map=cmap, properties=props, seed=self.seed, strict_direction=False
)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktown()
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
tqc = transpile(circuit, backend, layout_method="dense")
initial_layout = tqc._layout
dag = circuit_to_dag(tqc)
cmap = CouplingMap(backend.configuration().coupling_map)
props = backend.properties()
pass_ = VF2PostLayout(
coupling_map=cmap, properties=props, seed=self.seed, strict_direction=False
)
pass_.run(dag)
self.assertLayout(dag, cmap, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_best_mapping_ghz_state_full_device_multiple_qregs_v2(self):
"""Test best mappings with multiple registers"""
backend = FakeLimaV2()
qr_a = QuantumRegister(2)
qr_b = QuantumRegister(3)
qc = QuantumCircuit(qr_a, qr_b)
qc.h(qr_a[0])
qc.cx(qr_a[0], qr_a[1])
qc.cx(qr_a[0], qr_b[0])
qc.cx(qr_a[0], qr_b[1])
qc.cx(qr_a[0], qr_b[2])
qc.measure_all()
tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial")
initial_layout = tqc._layout
dag = circuit_to_dag(tqc)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
def test_2q_circuit_5q_backend_v2(self):
"""A simple example, without considering the direction
0 - 1
qr1 - qr0
"""
backend = FakeYorktownV2()
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0]) # qr1 -> qr0
tqc = transpile(circuit, backend, layout_method="dense")
initial_layout = tqc._layout
dag = circuit_to_dag(tqc)
pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False)
pass_.run(dag)
self.assertLayoutV2(dag, backend.target, pass_.property_set)
self.assertNotEqual(pass_.property_set["post_layout"], initial_layout)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
qc.draw('mpl')
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for Pauli operator class."""
import re
import unittest
import itertools as it
from functools import lru_cache
import numpy as np
from ddt import ddt, data, unpack
from qiskit import QuantumCircuit
from qiskit.exceptions import QiskitError
from qiskit.circuit.library import (
IGate,
XGate,
YGate,
ZGate,
HGate,
SGate,
SdgGate,
CXGate,
CZGate,
CYGate,
SwapGate,
)
from qiskit.circuit.library.generalized_gates import PauliGate
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.random import random_clifford, random_pauli
from qiskit.quantum_info.operators import Pauli, Operator
LABEL_REGEX = re.compile(r"(?P<coeff>[+-]?1?[ij]?)(?P<pauli>[IXYZ]*)")
PHASE_MAP = {"": 0, "-i": 1, "-": 2, "i": 3}
def _split_pauli_label(label):
match_ = LABEL_REGEX.fullmatch(label)
return match_["pauli"], match_["coeff"]
def _phase_from_label(label):
coeff = LABEL_REGEX.fullmatch(label)["coeff"] or ""
return PHASE_MAP[coeff.replace("+", "").replace("1", "").replace("j", "i")]
@lru_cache(maxsize=8)
def pauli_group_labels(nq, full_group=True):
"""Generate list of the N-qubit pauli group string labels"""
labels = ["".join(i) for i in it.product(("I", "X", "Y", "Z"), repeat=nq)]
if full_group:
labels = ["".join(i) for i in it.product(("", "-i", "-", "i"), labels)]
return labels
def operator_from_label(label):
"""Construct operator from full Pauli group label"""
pauli, coeff = _split_pauli_label(label)
coeff = (-1j) ** _phase_from_label(coeff)
return coeff * Operator.from_label(pauli)
@ddt
class TestPauliConversions(QiskitTestCase):
"""Test representation conversions of Pauli"""
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_labels(self, label):
"""Test round trip label conversion"""
pauli = Pauli(label)
self.assertEqual(Pauli(str(pauli)), pauli)
@data("S", "XX-")
def test_invalid_labels(self, label):
"""Test raise if invalid labels are supplied"""
with self.assertRaises(QiskitError):
Pauli(label)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_operator(self, label):
"""Test Pauli operator conversion"""
value = Operator(Pauli(label))
target = operator_from_label(label)
self.assertEqual(value, target)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_matrix_sparse(self, label):
"""Test Pauli operator conversion"""
spmat = Pauli(label).to_matrix(sparse=True)
value = Operator(spmat.todense())
target = operator_from_label(label)
self.assertEqual(value, target)
@data(*pauli_group_labels(1), *pauli_group_labels(2))
def test_to_instruction(self, label):
"""Test Pauli to instruction"""
pauli = Pauli(label)
value = Operator(pauli.to_instruction())
target = Operator(pauli)
self.assertEqual(value, target)
@data((IGate(), "I"), (XGate(), "X"), (YGate(), "Y"), (ZGate(), "Z"))
@unpack
def test_init_single_pauli_gate(self, gate, label):
"""Test initialization from Pauli basis gates"""
self.assertEqual(str(Pauli(gate)), label)
@data("IXYZ", "XXY", "ZYX", "ZI", "Y")
def test_init_pauli_gate(self, label):
"""Test initialization from Pauli basis gates"""
pauli = Pauli(PauliGate(label))
self.assertEqual(str(pauli), label)
@ddt
class TestPauliProperties(QiskitTestCase):
"""Test Pauli properties"""
@data("I", "XY", "XYZ", "IXYZ", "IXYZX")
def test_len(self, label):
"""Test __len__ method"""
self.assertEqual(len(Pauli(label)), len(label))
@data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1)))
@unpack
def test_equal(self, label1, label2):
"""Test __eq__ method"""
pauli1 = Pauli(label1)
pauli2 = Pauli(label2)
target = (
np.all(pauli1.z == pauli2.z)
and np.all(pauli1.x == pauli2.x)
and pauli1.phase == pauli2.phase
)
self.assertEqual(pauli1 == pauli2, target)
@data(*it.product(pauli_group_labels(1, full_group=False), pauli_group_labels(1)))
@unpack
def test_equiv(self, label1, label2):
"""Test equiv method"""
pauli1 = Pauli(label1)
pauli2 = Pauli(label2)
target = np.all(pauli1.z == pauli2.z) and np.all(pauli1.x == pauli2.x)
self.assertEqual(pauli1.equiv(pauli2), target)
@data(*pauli_group_labels(1))
def test_phase(self, label):
"""Test phase attribute"""
pauli = Pauli(label)
_, coeff = _split_pauli_label(str(pauli))
target = _phase_from_label(coeff)
self.assertEqual(pauli.phase, target)
@data(*((p, q) for p in ["I", "X", "Y", "Z"] for q in range(4)))
@unpack
def test_phase_setter(self, pauli, phase):
"""Test phase setter"""
pauli = Pauli(pauli)
pauli.phase = phase
_, coeff = _split_pauli_label(str(pauli))
value = _phase_from_label(coeff)
self.assertEqual(value, phase)
def test_x_setter(self):
"""Test phase attribute"""
pauli = Pauli("II")
pauli.x = True
self.assertEqual(pauli, Pauli("XX"))
def test_z_setter(self):
"""Test phase attribute"""
pauli = Pauli("II")
pauli.z = True
self.assertEqual(pauli, Pauli("ZZ"))
@data(
*(
("IXYZ", i)
for i in [0, 1, 2, 3, slice(None, None, None), slice(None, 2, None), [0, 3], [2, 1, 3]]
)
)
@unpack
def test_getitem(self, label, qubits):
"""Test __getitem__"""
pauli = Pauli(label)
value = str(pauli[qubits])
val_array = np.array(list(reversed(label)))[qubits]
target = "".join(reversed(val_array.tolist()))
self.assertEqual(value, target, msg=f"indices = {qubits}")
@data(
(0, "iY", "iIIY"),
([1, 0], "XZ", "IZX"),
(slice(None, None, None), "XYZ", "XYZ"),
(slice(None, None, -1), "XYZ", "ZYX"),
)
@unpack
def test_setitem(self, qubits, value, target):
"""Test __setitem__"""
pauli = Pauli("III")
pauli[qubits] = value
self.assertEqual(str(pauli), target)
def test_insert(self):
"""Test insert method"""
pauli = Pauli("III")
pauli = pauli.insert([2, 0, 4], "XYZ")
self.assertEqual(str(pauli), "IXIZIY")
def test_delete(self):
"""Test delete method"""
pauli = Pauli("IXYZ")
pauli = pauli.delete([0, 2])
self.assertEqual(str(pauli), "IY")
@ddt
class TestPauli(QiskitTestCase):
"""Tests for Pauli operator class."""
@data(*pauli_group_labels(2))
def test_conjugate(self, label):
"""Test conjugate method."""
value = Pauli(label).conjugate()
target = operator_from_label(label).conjugate()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_transpose(self, label):
"""Test transpose method."""
value = Pauli(label).transpose()
target = operator_from_label(label).transpose()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_adjoint(self, label):
"""Test adjoint method."""
value = Pauli(label).adjoint()
target = operator_from_label(label).adjoint()
self.assertEqual(Operator(value), target)
@data(*pauli_group_labels(2))
def test_inverse(self, label):
"""Test inverse method."""
pauli = Pauli(label)
value = pauli.inverse()
target = pauli.adjoint()
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(2, full_group=False), repeat=2))
@unpack
def test_dot(self, label1, label2):
"""Test dot method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.dot(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.dot(op2)
self.assertEqual(value, target)
target = op1 @ op2
self.assertEqual(value, target)
@data(*pauli_group_labels(1))
def test_dot_qargs(self, label2):
"""Test dot method with qargs."""
label1 = "-iXYZ"
p1 = Pauli(label1)
p2 = Pauli(label2)
qargs = [0]
value = Operator(p1.dot(p2, qargs=qargs))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.dot(op2, qargs=qargs)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(2, full_group=False), repeat=2))
@unpack
def test_compose(self, label1, label2):
"""Test compose method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.compose(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.compose(op2)
self.assertEqual(value, target)
@data(*pauli_group_labels(1))
def test_compose_qargs(self, label2):
"""Test compose method with qargs."""
label1 = "-XYZ"
p1 = Pauli(label1)
p2 = Pauli(label2)
qargs = [0]
value = Operator(p1.compose(p2, qargs=qargs))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.compose(op2, qargs=qargs)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(1, full_group=False), repeat=2))
@unpack
def test_tensor(self, label1, label2):
"""Test tensor method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.tensor(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.tensor(op2)
self.assertEqual(value, target)
@data(*it.product(pauli_group_labels(1, full_group=False), repeat=2))
@unpack
def test_expand(self, label1, label2):
"""Test expand method."""
p1 = Pauli(label1)
p2 = Pauli(label2)
value = Operator(p1.expand(p2))
op1 = operator_from_label(label1)
op2 = operator_from_label(label2)
target = op1.expand(op2)
self.assertEqual(value, target)
@data("II", "XI", "YX", "ZZ", "YZ")
def test_power(self, label):
"""Test power method."""
iden = Pauli("II")
op = Pauli(label)
self.assertTrue(op**2, iden)
@data(1, 1.0, -1, -1.0, 1j, -1j)
def test_multiply(self, val):
"""Test multiply method."""
op = val * Pauli(([True, True], [False, False], 0))
phase = (-1j) ** op.phase
self.assertEqual(phase, val)
op = Pauli(([True, True], [False, False], 0)) * val
phase = (-1j) ** op.phase
self.assertEqual(phase, val)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
op = Pauli("XYZ")
self.assertRaises(QiskitError, op._multiply, 2)
@data(0, 1, 2, 3)
def test_negate(self, phase):
"""Test negate method"""
op = Pauli(([False], [True], phase))
neg = -op
self.assertTrue(op.equiv(neg))
self.assertEqual(neg.phase, (op.phase + 2) % 4)
@data(*it.product(pauli_group_labels(1, False), repeat=2))
@unpack
def test_commutes(self, p1, p2):
"""Test commutes method"""
P1 = Pauli(p1)
P2 = Pauli(p2)
self.assertEqual(P1.commutes(P2), P1.dot(P2) == P2.dot(P1))
@data(*it.product(pauli_group_labels(1, False), repeat=2))
@unpack
def test_anticommutes(self, p1, p2):
"""Test anticommutes method"""
P1 = Pauli(p1)
P2 = Pauli(p2)
self.assertEqual(P1.anticommutes(P2), P1.dot(P2) == -P2.dot(P1))
@data(
*it.product(
(IGate(), XGate(), YGate(), ZGate(), HGate(), SGate(), SdgGate()),
pauli_group_labels(1, False),
)
)
@unpack
def test_evolve_clifford1(self, gate, label):
"""Test evolve method for 1-qubit Clifford gates."""
op = Operator(gate)
pauli = Pauli(label)
value = Operator(pauli.evolve(gate))
value_h = Operator(pauli.evolve(gate, frame="h"))
value_s = Operator(pauli.evolve(gate, frame="s"))
value_inv = Operator(pauli.evolve(gate.inverse()))
target = op.adjoint().dot(pauli).dot(op)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
@data(*it.product((CXGate(), CYGate(), CZGate(), SwapGate()), pauli_group_labels(2, False)))
@unpack
def test_evolve_clifford2(self, gate, label):
"""Test evolve method for 2-qubit Clifford gates."""
op = Operator(gate)
pauli = Pauli(label)
value = Operator(pauli.evolve(gate))
value_h = Operator(pauli.evolve(gate, frame="h"))
value_s = Operator(pauli.evolve(gate, frame="s"))
value_inv = Operator(pauli.evolve(gate.inverse()))
target = op.adjoint().dot(pauli).dot(op)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
@data(
*it.product(
(
IGate(),
XGate(),
YGate(),
ZGate(),
HGate(),
SGate(),
SdgGate(),
CXGate(),
CYGate(),
CZGate(),
SwapGate(),
),
[int, np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32, np.int64, np.uint64],
)
)
@unpack
def test_phase_dtype_evolve_clifford(self, gate, dtype):
"""Test phase dtype for evolve method for Clifford gates."""
z = np.ones(gate.num_qubits, dtype=bool)
x = np.ones(gate.num_qubits, dtype=bool)
phase = (np.sum(z & x) % 4).astype(dtype)
paulis = Pauli((z, x, phase))
evo = paulis.evolve(gate)
self.assertEqual(evo.phase.dtype, dtype)
def test_evolve_clifford_qargs(self):
"""Test evolve method for random Clifford"""
cliff = random_clifford(3, seed=10)
op = Operator(cliff)
pauli = random_pauli(5, seed=10)
qargs = [3, 0, 1]
value = Operator(pauli.evolve(cliff, qargs=qargs))
value_h = Operator(pauli.evolve(cliff, qargs=qargs, frame="h"))
value_s = Operator(pauli.evolve(cliff, qargs=qargs, frame="s"))
value_inv = Operator(pauli.evolve(cliff.adjoint(), qargs=qargs))
target = Operator(pauli).compose(op.adjoint(), qargs=qargs).dot(op, qargs=qargs)
self.assertEqual(value, target)
self.assertEqual(value, value_h)
self.assertEqual(value_inv, value_s)
def test_barrier_delay_sim(self):
"""Test barrier and delay instructions can be simulated"""
target_circ = QuantumCircuit(2)
target_circ.x(0)
target_circ.y(1)
target = Pauli(target_circ)
circ = QuantumCircuit(2)
circ.x(0)
circ.delay(100, 0)
circ.barrier([0, 1])
circ.y(1)
value = Pauli(circ)
self.assertEqual(value, target)
@data(("", 0), ("-", 2), ("i", 3), ("-1j", 1))
@unpack
def test_zero_qubit_pauli_construction(self, label, phase):
"""Test that Paulis of zero qubits can be constructed."""
expected = Pauli(label + "X")[0:0] # Empty slice from a 1q Pauli, which becomes phaseless
expected.phase = phase
test = Pauli(label)
self.assertEqual(expected, test)
if __name__ == "__main__":
unittest.main()
|
https://github.com/tombillo1/QuantumCompDemo
|
tombillo1
|
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Shor
N = 15
shor = Shor(N)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
ret = shor.run(quantum_instance)
print("The list of factors of {} as computed by the Shor's algorithm is {}.".format(N, ret['factors'][0]))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017--2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Clifford operator class.
"""
from __future__ import annotations
import functools
import itertools
import re
from typing import Literal
import numpy as np
from qiskit.circuit import Instruction, QuantumCircuit
from qiskit.circuit.library.standard_gates import HGate, IGate, SGate, XGate, YGate, ZGate
from qiskit.circuit.operation import Operation
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.operators.base_operator import BaseOperator
from qiskit.quantum_info.operators.mixins import AdjointMixin, generate_apidocs
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.scalar_op import ScalarOp
from qiskit.quantum_info.operators.symplectic.base_pauli import _count_y
from qiskit.utils.deprecation import deprecate_func
from qiskit.synthesis.linear import calc_inverse_matrix
from .base_pauli import BasePauli
from .clifford_circuits import _append_circuit, _append_operation
from .stabilizer_table import StabilizerTable
class Clifford(BaseOperator, AdjointMixin, Operation):
"""An N-qubit unitary operator from the Clifford group.
**Representation**
An *N*-qubit Clifford operator is stored as a length *2N × (2N+1)*
boolean tableau using the convention from reference [1].
* Rows 0 to *N-1* are the *destabilizer* group generators
* Rows *N* to *2N-1* are the *stabilizer* group generators.
The internal boolean tableau for the Clifford
can be accessed using the :attr:`tableau` attribute. The destabilizer or
stabilizer rows can each be accessed as a length-N Stabilizer table using
:attr:`destab` and :attr:`stab` attributes.
A more easily human readable representation of the Clifford operator can
be obtained by calling the :meth:`to_dict` method. This representation is
also used if a Clifford object is printed as in the following example
.. code-block::
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford
# Bell state generation circuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
cliff = Clifford(qc)
# Print the Clifford
print(cliff)
# Print the Clifford destabilizer rows
print(cliff.to_labels(mode="D"))
# Print the Clifford stabilizer rows
print(cliff.to_labels(mode="S"))
.. parsed-literal::
Clifford: Stabilizer = ['+XX', '+ZZ'], Destabilizer = ['+IZ', '+XI']
['+IZ', '+XI']
['+XX', '+ZZ']
**Circuit Conversion**
Clifford operators can be initialized from circuits containing *only* the
following Clifford gates: :class:`~qiskit.circuit.library.IGate`,
:class:`~qiskit.circuit.library.XGate`, :class:`~qiskit.circuit.library.YGate`,
:class:`~qiskit.circuit.library.ZGate`, :class:`~qiskit.circuit.library.HGate`,
:class:`~qiskit.circuit.library.SGate`, :class:`~qiskit.circuit.library.SdgGate`,
:class:`~qiskit.circuit.library.SXGate`, :class:`~qiskit.circuit.library.SXdgGate`,
:class:`~qiskit.circuit.library.CXGate`, :class:`~qiskit.circuit.library.CZGate`,
:class:`~qiskit.circuit.library.CYGate`, :class:`~qiskit.circuit.library.DXGate`,
:class:`~qiskit.circuit.library.SwapGate`, :class:`~qiskit.circuit.library.iSwapGate`,
:class:`~qiskit.circuit.library.ECRGate`, :class:`~qiskit.circuit.library.LinearFunction`,
:class:`~qiskit.circuit.library.PermutationGate`.
They can be converted back into a :class:`~qiskit.circuit.QuantumCircuit`,
or :class:`~qiskit.circuit.Gate` object using the :meth:`~Clifford.to_circuit`
or :meth:`~Clifford.to_instruction` methods respectively. Note that this
decomposition is not necessarily optimal in terms of number of gates.
.. note::
A minimally generating set of gates for Clifford circuits is
the :class:`~qiskit.circuit.library.HGate` and
:class:`~qiskit.circuit.library.SGate` gate and *either* the
:class:`~qiskit.circuit.library.CXGate` or
:class:`~qiskit.circuit.library.CZGate` two-qubit gate.
Clifford operators can also be converted to
:class:`~qiskit.quantum_info.Operator` objects using the
:meth:`to_operator` method. This is done via decomposing to a circuit, and then
simulating the circuit as a unitary operator.
References:
1. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*,
Phys. Rev. A 70, 052328 (2004).
`arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_
"""
_COMPOSE_PHASE_LOOKUP = None
_COMPOSE_1Q_LOOKUP = None
def __array__(self, dtype=None):
if dtype:
return np.asarray(self.to_matrix(), dtype=dtype)
return self.to_matrix()
def __init__(self, data, validate=True, copy=True):
"""Initialize an operator object."""
# pylint: disable=cyclic-import
from qiskit.circuit.library import LinearFunction, PermutationGate
# Initialize from another Clifford
if isinstance(data, Clifford):
num_qubits = data.num_qubits
self.tableau = data.tableau.copy() if copy else data.tableau
# Initialize from ScalarOp as N-qubit identity discarding any global phase
elif isinstance(data, ScalarOp):
if not data.num_qubits or not data.is_unitary():
raise QiskitError("Can only initialize from N-qubit identity ScalarOp.")
num_qubits = data.num_qubits
self.tableau = np.fromfunction(
lambda i, j: i == j, (2 * num_qubits, 2 * num_qubits + 1)
).astype(bool)
# Initialize from LinearFunction
elif isinstance(data, LinearFunction):
num_qubits = len(data.linear)
self.tableau = self.from_linear_function(data)
# Initialize from PermutationGate
elif isinstance(data, PermutationGate):
num_qubits = len(data.pattern)
self.tableau = self.from_permutation(data)
# Initialize from a QuantumCircuit or Instruction object
elif isinstance(data, (QuantumCircuit, Instruction)):
num_qubits = data.num_qubits
self.tableau = Clifford.from_circuit(data).tableau
# DEPRECATED: data is StabilizerTable
elif isinstance(data, StabilizerTable):
self.tableau = self._stack_table_phase(data.array, data.phase)
num_qubits = data.num_qubits
# Initialize StabilizerTable directly from the data
else:
if isinstance(data, (list, np.ndarray)) and np.asarray(data, dtype=bool).ndim == 2:
data = np.array(data, dtype=bool, copy=copy)
if data.shape[0] == data.shape[1]:
self.tableau = self._stack_table_phase(
data, np.zeros(data.shape[0], dtype=bool)
)
num_qubits = data.shape[0] // 2
elif data.shape[0] + 1 == data.shape[1]:
self.tableau = data
num_qubits = data.shape[0] // 2
else:
raise QiskitError("")
else:
n_paulis = len(data)
symp = self._from_label(data[0])
num_qubits = len(symp) // 2
tableau = np.zeros((n_paulis, len(symp)), dtype=bool)
tableau[0] = symp
for i in range(1, n_paulis):
tableau[i] = self._from_label(data[i])
self.tableau = tableau
# Validate table is a symplectic matrix
if validate and not Clifford._is_symplectic(self.symplectic_matrix):
raise QiskitError(
"Invalid Clifford. Input StabilizerTable is not a valid symplectic matrix."
)
# Initialize BaseOperator
super().__init__(num_qubits=num_qubits)
@property
def name(self):
"""Unique string identifier for operation type."""
return "clifford"
@property
def num_clbits(self):
"""Number of classical bits."""
return 0
def __repr__(self):
return f"Clifford({repr(self.tableau)})"
def __str__(self):
return (
f'Clifford: Stabilizer = {self.to_labels(mode="S")}, '
f'Destabilizer = {self.to_labels(mode="D")}'
)
def __eq__(self, other):
"""Check if two Clifford tables are equal"""
return super().__eq__(other) and (self.tableau == other.tableau).all()
def copy(self):
return type(self)(self, validate=False, copy=True)
# ---------------------------------------------------------------------
# Attributes
# ---------------------------------------------------------------------
# pylint: disable=bad-docstring-quotes
@deprecate_func(
since="0.24.0",
additional_msg="Instead, index or iterate through the Clifford.tableau attribute.",
)
def __getitem__(self, key):
"""Return a stabilizer Pauli row"""
return self.table.__getitem__(key)
@deprecate_func(since="0.24.0", additional_msg="Use Clifford.tableau property instead.")
def __setitem__(self, key, value):
"""Set a stabilizer Pauli row"""
self.tableau.__setitem__(key, self._stack_table_phase(value.array, value.phase))
@property
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.stab and Clifford.destab properties instead.",
is_property=True,
)
def table(self):
"""Return StabilizerTable"""
return StabilizerTable(self.symplectic_matrix, phase=self.phase)
@table.setter
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.stab and Clifford.destab properties instead.",
is_property=True,
)
def table(self, value):
"""Set the stabilizer table"""
# Note this setter cannot change the size of the Clifford
# It can only replace the contents of the StabilizerTable with
# another StabilizerTable of the same size.
if not isinstance(value, StabilizerTable):
value = StabilizerTable(value)
self.symplectic_matrix = value._table._array
self.phase = value._table._phase
@property
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.stab properties instead.",
is_property=True,
)
def stabilizer(self):
"""Return the stabilizer block of the StabilizerTable."""
array = self.tableau[self.num_qubits : 2 * self.num_qubits, :-1]
phase = self.tableau[self.num_qubits : 2 * self.num_qubits, -1].reshape(self.num_qubits)
return StabilizerTable(array, phase)
@stabilizer.setter
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.stab properties instead.",
is_property=True,
)
def stabilizer(self, value):
"""Set the value of stabilizer block of the StabilizerTable"""
if not isinstance(value, StabilizerTable):
value = StabilizerTable(value)
self.tableau[self.num_qubits : 2 * self.num_qubits, :-1] = value.array
@property
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.destab properties instead.",
is_property=True,
)
def destabilizer(self):
"""Return the destabilizer block of the StabilizerTable."""
array = self.tableau[0 : self.num_qubits, :-1]
phase = self.tableau[0 : self.num_qubits, -1].reshape(self.num_qubits)
return StabilizerTable(array, phase)
@destabilizer.setter
@deprecate_func(
since="0.24.0",
additional_msg="Use Clifford.destab properties instead.",
is_property=True,
)
def destabilizer(self, value):
"""Set the value of destabilizer block of the StabilizerTable"""
if not isinstance(value, StabilizerTable):
value = StabilizerTable(value)
self.tableau[: self.num_qubits, :-1] = value.array
@property
def symplectic_matrix(self):
"""Return boolean symplectic matrix."""
return self.tableau[:, :-1]
@symplectic_matrix.setter
def symplectic_matrix(self, value):
self.tableau[:, :-1] = value
@property
def phase(self):
"""Return phase with boolean representation."""
return self.tableau[:, -1]
@phase.setter
def phase(self, value):
self.tableau[:, -1] = value
@property
def x(self):
"""The x array for the symplectic representation."""
return self.tableau[:, 0 : self.num_qubits]
@x.setter
def x(self, value):
self.tableau[:, 0 : self.num_qubits] = value
@property
def z(self):
"""The z array for the symplectic representation."""
return self.tableau[:, self.num_qubits : 2 * self.num_qubits]
@z.setter
def z(self, value):
self.tableau[:, self.num_qubits : 2 * self.num_qubits] = value
@property
def destab(self):
"""The destabilizer array for the symplectic representation."""
return self.tableau[: self.num_qubits, :]
@destab.setter
def destab(self, value):
self.tableau[: self.num_qubits, :] = value
@property
def destab_x(self):
"""The destabilizer x array for the symplectic representation."""
return self.tableau[: self.num_qubits, : self.num_qubits]
@destab_x.setter
def destab_x(self, value):
self.tableau[: self.num_qubits, : self.num_qubits] = value
@property
def destab_z(self):
"""The destabilizer z array for the symplectic representation."""
return self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits]
@destab_z.setter
def destab_z(self, value):
self.tableau[: self.num_qubits, self.num_qubits : 2 * self.num_qubits] = value
@property
def destab_phase(self):
"""Return phase of destabilizer with boolean representation."""
return self.tableau[: self.num_qubits, -1]
@destab_phase.setter
def destab_phase(self, value):
self.tableau[: self.num_qubits, -1] = value
@property
def stab(self):
"""The stabilizer array for the symplectic representation."""
return self.tableau[self.num_qubits :, :]
@stab.setter
def stab(self, value):
self.tableau[self.num_qubits :, :] = value
@property
def stab_x(self):
"""The stabilizer x array for the symplectic representation."""
return self.tableau[self.num_qubits :, : self.num_qubits]
@stab_x.setter
def stab_x(self, value):
self.tableau[self.num_qubits :, : self.num_qubits] = value
@property
def stab_z(self):
"""The stabilizer array for the symplectic representation."""
return self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits]
@stab_z.setter
def stab_z(self, value):
self.tableau[self.num_qubits :, self.num_qubits : 2 * self.num_qubits] = value
@property
def stab_phase(self):
"""Return phase of stabilizer with boolean representation."""
return self.tableau[self.num_qubits :, -1]
@stab_phase.setter
def stab_phase(self, value):
self.tableau[self.num_qubits :, -1] = value
# ---------------------------------------------------------------------
# Utility Operator methods
# ---------------------------------------------------------------------
def is_unitary(self):
"""Return True if the Clifford table is valid."""
# A valid Clifford is always unitary, so this function is really
# checking that the underlying Stabilizer table array is a valid
# Clifford array.
return Clifford._is_symplectic(self.symplectic_matrix)
# ---------------------------------------------------------------------
# BaseOperator Abstract Methods
# ---------------------------------------------------------------------
def conjugate(self):
return Clifford._conjugate_transpose(self, "C")
def adjoint(self):
return Clifford._conjugate_transpose(self, "A")
def transpose(self):
return Clifford._conjugate_transpose(self, "T")
def tensor(self, other: Clifford) -> Clifford:
if not isinstance(other, Clifford):
other = Clifford(other)
return self._tensor(self, other)
def expand(self, other: Clifford) -> Clifford:
if not isinstance(other, Clifford):
other = Clifford(other)
return self._tensor(other, self)
@classmethod
def _tensor(cls, a, b):
n = a.num_qubits + b.num_qubits
tableau = np.zeros((2 * n, 2 * n + 1), dtype=bool)
clifford = cls(tableau, validate=False)
clifford.destab_x[: b.num_qubits, : b.num_qubits] = b.destab_x
clifford.destab_x[b.num_qubits :, b.num_qubits :] = a.destab_x
clifford.destab_z[: b.num_qubits, : b.num_qubits] = b.destab_z
clifford.destab_z[b.num_qubits :, b.num_qubits :] = a.destab_z
clifford.stab_x[: b.num_qubits, : b.num_qubits] = b.stab_x
clifford.stab_x[b.num_qubits :, b.num_qubits :] = a.stab_x
clifford.stab_z[: b.num_qubits, : b.num_qubits] = b.stab_z
clifford.stab_z[b.num_qubits :, b.num_qubits :] = a.stab_z
clifford.phase[: b.num_qubits] = b.destab_phase
clifford.phase[b.num_qubits : n] = a.destab_phase
clifford.phase[n : n + b.num_qubits] = b.stab_phase
clifford.phase[n + b.num_qubits :] = a.stab_phase
return clifford
def compose(
self,
other: Clifford | QuantumCircuit | Instruction,
qargs: list | None = None,
front: bool = False,
) -> Clifford:
if qargs is None:
qargs = getattr(other, "qargs", None)
# If other is a QuantumCircuit we can more efficiently compose
# using the _append_circuit method to update each gate recursively
# to the current Clifford, rather than converting to a Clifford first
# and then doing the composition of tables.
if not front:
if isinstance(other, QuantumCircuit):
return _append_circuit(self.copy(), other, qargs=qargs)
if isinstance(other, Instruction):
return _append_operation(self.copy(), other, qargs=qargs)
if not isinstance(other, Clifford):
# Not copying is safe since we're going to drop our only reference to `other` at the end
# of the function.
other = Clifford(other, copy=False)
# Validate compose dimensions
self._op_shape.compose(other._op_shape, qargs, front)
# Pad other with identities if composing on subsystem
other = self._pad_with_identity(other, qargs)
left, right = (self, other) if front else (other, self)
if self.num_qubits == 1:
return self._compose_1q(left, right)
return self._compose_general(left, right)
@classmethod
def _compose_general(cls, first, second):
# Correcting for phase due to Pauli multiplication. Start with factors of -i from XZ = -iY
# on individual qubits, and then handle multiplication between each qubitwise pair.
ifacts = np.sum(second.x & second.z, axis=1, dtype=int)
x1, z1 = first.x.astype(np.uint8), first.z.astype(np.uint8)
lookup = cls._compose_lookup()
# The loop is over 2*n_qubits entries, and the entire loop is cubic in the number of qubits.
for k, row2 in enumerate(second.symplectic_matrix):
x1_select = x1[row2]
z1_select = z1[row2]
x1_accum = np.logical_xor.accumulate(x1_select, axis=0).astype(np.uint8)
z1_accum = np.logical_xor.accumulate(z1_select, axis=0).astype(np.uint8)
indexer = (x1_select[1:], z1_select[1:], x1_accum[:-1], z1_accum[:-1])
ifacts[k] += np.sum(lookup[indexer])
p = np.mod(ifacts, 4) // 2
phase = (
(np.matmul(second.symplectic_matrix, first.phase, dtype=int) + second.phase + p) % 2
).astype(bool)
data = cls._stack_table_phase(
(np.matmul(second.symplectic_matrix, first.symplectic_matrix, dtype=int) % 2).astype(
bool
),
phase,
)
return Clifford(data, validate=False, copy=False)
@classmethod
def _compose_1q(cls, first, second):
# 1-qubit composition can be done with a simple lookup table; there are 24 elements in the
# 1q Clifford group, so 576 possible combinations, which is small enough to look up.
if cls._COMPOSE_1Q_LOOKUP is None:
# The valid tables for 1q Cliffords.
tables_1q = np.array(
[
[[False, True], [True, False]],
[[False, True], [True, True]],
[[True, False], [False, True]],
[[True, False], [True, True]],
[[True, True], [False, True]],
[[True, True], [True, False]],
]
)
phases_1q = np.array([[False, False], [False, True], [True, False], [True, True]])
# Build the lookup table.
cliffords = [
cls(cls._stack_table_phase(table, phase), validate=False, copy=False)
for table, phase in itertools.product(tables_1q, phases_1q)
]
cls._COMPOSE_1Q_LOOKUP = {
(cls._hash(left), cls._hash(right)): cls._compose_general(left, right)
for left, right in itertools.product(cliffords, repeat=2)
}
return cls._COMPOSE_1Q_LOOKUP[cls._hash(first), cls._hash(second)].copy()
@classmethod
def _compose_lookup(
cls,
):
if cls._COMPOSE_PHASE_LOOKUP is None:
# A lookup table for calculating phases. The indices are
# current_x, current_z, running_x_count, running_z_count
# where all counts taken modulo 2.
lookup = np.zeros((2, 2, 2, 2), dtype=int)
lookup[0, 1, 1, 0] = lookup[1, 0, 1, 1] = lookup[1, 1, 0, 1] = -1
lookup[0, 1, 1, 1] = lookup[1, 0, 0, 1] = lookup[1, 1, 1, 0] = 1
lookup.setflags(write=False)
cls._COMPOSE_PHASE_LOOKUP = lookup
return cls._COMPOSE_PHASE_LOOKUP
# ---------------------------------------------------------------------
# Representation conversions
# ---------------------------------------------------------------------
def to_dict(self):
"""Return dictionary representation of Clifford object."""
return {
"stabilizer": self.to_labels(mode="S"),
"destabilizer": self.to_labels(mode="D"),
}
@classmethod
def from_dict(cls, obj):
"""Load a Clifford from a dictionary"""
labels = obj.get("destabilizer") + obj.get("stabilizer")
n_paulis = len(labels)
symp = cls._from_label(labels[0])
tableau = np.zeros((n_paulis, len(symp)), dtype=bool)
tableau[0] = symp
for i in range(1, n_paulis):
tableau[i] = cls._from_label(labels[i])
return cls(tableau)
def to_matrix(self):
"""Convert operator to Numpy matrix."""
return self.to_operator().data
@classmethod
def from_matrix(cls, matrix: np.ndarray) -> Clifford:
"""Create a Clifford from a unitary matrix.
Note that this function takes exponentially long time w.r.t. the number of qubits.
Args:
matrix (np.array): A unitary matrix representing a Clifford to be converted.
Returns:
Clifford: the Clifford object for the unitary matrix.
Raises:
QiskitError: if the input is not a Clifford matrix.
"""
tableau = cls._unitary_matrix_to_tableau(matrix)
if tableau is None:
raise QiskitError("Non-Clifford matrix is not convertible")
return cls(tableau)
@classmethod
def from_linear_function(cls, linear_function):
"""Create a Clifford from a Linear Function.
If the linear function is represented by a nxn binary invertible matrix A,
then the corresponding Clifford has symplectic matrix [[A^t, 0], [0, A^{-1}]].
Args:
linear_function (LinearFunction): A linear function to be converted.
Returns:
Clifford: the Clifford object for this linear function.
"""
mat = linear_function.linear
mat_t = np.transpose(mat)
mat_i = calc_inverse_matrix(mat)
dim = len(mat)
zero = np.zeros((dim, dim), dtype=int)
symplectic_mat = np.block([[mat_t, zero], [zero, mat_i]])
phase = np.zeros(2 * dim, dtype=int)
tableau = cls._stack_table_phase(symplectic_mat, phase)
return tableau
@classmethod
def from_permutation(cls, permutation_gate):
"""Create a Clifford from a PermutationGate.
Args:
permutation_gate (PermutationGate): A permutation to be converted.
Returns:
Clifford: the Clifford object for this permutation.
"""
pat = permutation_gate.pattern
dim = len(pat)
symplectic_mat = np.zeros((2 * dim, 2 * dim), dtype=int)
for i, j in enumerate(pat):
symplectic_mat[j, i] = True
symplectic_mat[j + dim, i + dim] = True
phase = np.zeros(2 * dim, dtype=bool)
tableau = cls._stack_table_phase(symplectic_mat, phase)
return tableau
def to_operator(self) -> Operator:
"""Convert to an Operator object."""
return Operator(self.to_instruction())
@classmethod
def from_operator(cls, operator: Operator) -> Clifford:
"""Create a Clifford from a operator.
Note that this function takes exponentially long time w.r.t. the number of qubits.
Args:
operator (Operator): An operator representing a Clifford to be converted.
Returns:
Clifford: the Clifford object for the operator.
Raises:
QiskitError: if the input is not a Clifford operator.
"""
tableau = cls._unitary_matrix_to_tableau(operator.to_matrix())
if tableau is None:
raise QiskitError("Non-Clifford operator is not convertible")
return cls(tableau)
def to_circuit(self):
"""Return a QuantumCircuit implementing the Clifford.
For N <= 3 qubits this is based on optimal CX cost decomposition
from reference [1]. For N > 3 qubits this is done using the general
non-optimal compilation routine from reference [2].
Return:
QuantumCircuit: a circuit implementation of the Clifford.
References:
1. S. Bravyi, D. Maslov, *Hadamard-free circuits expose the
structure of the Clifford group*,
`arXiv:2003.09412 [quant-ph] <https://arxiv.org/abs/2003.09412>`_
2. S. Aaronson, D. Gottesman, *Improved Simulation of Stabilizer Circuits*,
Phys. Rev. A 70, 052328 (2004).
`arXiv:quant-ph/0406196 <https://arxiv.org/abs/quant-ph/0406196>`_
"""
from qiskit.synthesis.clifford import synth_clifford_full
return synth_clifford_full(self)
def to_instruction(self):
"""Return a Gate instruction implementing the Clifford."""
return self.to_circuit().to_gate()
@staticmethod
def from_circuit(circuit: QuantumCircuit | Instruction) -> Clifford:
"""Initialize from a QuantumCircuit or Instruction.
Args:
circuit (QuantumCircuit or ~qiskit.circuit.Instruction):
instruction to initialize.
Returns:
Clifford: the Clifford object for the instruction.
Raises:
QiskitError: if the input instruction is non-Clifford or contains
classical register instruction.
"""
if not isinstance(circuit, (QuantumCircuit, Instruction)):
raise QiskitError("Input must be a QuantumCircuit or Instruction")
# Initialize an identity Clifford
clifford = Clifford(np.eye(2 * circuit.num_qubits), validate=False)
if isinstance(circuit, QuantumCircuit):
clifford = _append_circuit(clifford, circuit)
else:
clifford = _append_operation(clifford, circuit)
return clifford
@staticmethod
def from_label(label: str) -> Clifford:
"""Return a tensor product of single-qubit Clifford gates.
Args:
label (string): single-qubit operator string.
Returns:
Clifford: The N-qubit Clifford operator.
Raises:
QiskitError: if the label contains invalid characters.
Additional Information:
The labels correspond to the single-qubit Cliffords are
* - Label
- Stabilizer
- Destabilizer
* - ``"I"``
- +Z
- +X
* - ``"X"``
- -Z
- +X
* - ``"Y"``
- -Z
- -X
* - ``"Z"``
- +Z
- -X
* - ``"H"``
- +X
- +Z
* - ``"S"``
- +Z
- +Y
"""
# Check label is valid
label_gates = {
"I": IGate(),
"X": XGate(),
"Y": YGate(),
"Z": ZGate(),
"H": HGate(),
"S": SGate(),
}
if re.match(r"^[IXYZHS\-+]+$", label) is None:
raise QiskitError("Label contains invalid characters.")
# Initialize an identity matrix and apply each gate
num_qubits = len(label)
op = Clifford(np.eye(2 * num_qubits, dtype=bool))
for qubit, char in enumerate(reversed(label)):
op = _append_operation(op, label_gates[char], qargs=[qubit])
return op
def to_labels(self, array: bool = False, mode: Literal["S", "D", "B"] = "B"):
r"""Convert a Clifford to a list Pauli (de)stabilizer string labels.
For large Clifford converting using the ``array=True``
kwarg will be more efficient since it allocates memory for
the full Numpy array of labels in advance.
.. list-table:: Stabilizer Representations
:header-rows: 1
* - Label
- Phase
- Symplectic
- Matrix
- Pauli
* - ``"+I"``
- 0
- :math:`[0, 0]`
- :math:`\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}`
- :math:`I`
* - ``"-I"``
- 1
- :math:`[0, 0]`
- :math:`\begin{bmatrix} -1 & 0 \\ 0 & -1 \end{bmatrix}`
- :math:`-I`
* - ``"X"``
- 0
- :math:`[1, 0]`
- :math:`\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}`
- :math:`X`
* - ``"-X"``
- 1
- :math:`[1, 0]`
- :math:`\begin{bmatrix} 0 & -1 \\ -1 & 0 \end{bmatrix}`
- :math:`-X`
* - ``"Y"``
- 0
- :math:`[1, 1]`
- :math:`\begin{bmatrix} 0 & 1 \\ -1 & 0 \end{bmatrix}`
- :math:`iY`
* - ``"-Y"``
- 1
- :math:`[1, 1]`
- :math:`\begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}`
- :math:`-iY`
* - ``"Z"``
- 0
- :math:`[0, 1]`
- :math:`\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}`
- :math:`Z`
* - ``"-Z"``
- 1
- :math:`[0, 1]`
- :math:`\begin{bmatrix} -1 & 0 \\ 0 & 1 \end{bmatrix}`
- :math:`-Z`
Args:
array (bool): return a Numpy array if True, otherwise
return a list (Default: False).
mode (Literal["S", "D", "B"]): return both stabilizer and destabilizer if "B",
return only stabilizer if "S" and return only destabilizer if "D".
Returns:
list or array: The rows of the StabilizerTable in label form.
Raises:
QiskitError: if stabilizer and destabilizer are both False.
"""
if mode not in ("S", "B", "D"):
raise QiskitError("mode must be B, S, or D.")
size = 2 * self.num_qubits if mode == "B" else self.num_qubits
offset = self.num_qubits if mode == "S" else 0
ret = np.zeros(size, dtype=f"<U{1 + self.num_qubits}")
for i in range(size):
z = self.tableau[i + offset, self.num_qubits : 2 * self.num_qubits]
x = self.tableau[i + offset, 0 : self.num_qubits]
phase = int(self.tableau[i + offset, -1]) * 2
label = BasePauli._to_label(z, x, phase, group_phase=True)
if label[0] != "-":
label = "+" + label
ret[i] = label
if array:
return ret
return ret.tolist()
# ---------------------------------------------------------------------
# Internal helper functions
# ---------------------------------------------------------------------
def _hash(self):
"""Produce a hashable value that is unique for each different Clifford. This should only be
used internally when the classes being hashed are under our control, because classes of this
type are mutable."""
return np.packbits(self.tableau).tobytes()
@staticmethod
def _is_symplectic(mat):
"""Return True if input is symplectic matrix."""
# Condition is
# table.T * [[0, 1], [1, 0]] * table = [[0, 1], [1, 0]]
# where we are block matrix multiplying using symplectic product
dim = len(mat) // 2
if mat.shape != (2 * dim, 2 * dim):
return False
one = np.eye(dim, dtype=int)
zero = np.zeros((dim, dim), dtype=int)
seye = np.block([[zero, one], [one, zero]])
arr = mat.astype(int)
return np.array_equal(np.mod(arr.T.dot(seye).dot(arr), 2), seye)
@staticmethod
def _conjugate_transpose(clifford, method):
"""Return the adjoint, conjugate, or transpose of the Clifford.
Args:
clifford (Clifford): a clifford object.
method (str): what function to apply 'A', 'C', or 'T'.
Returns:
Clifford: the modified clifford.
"""
ret = clifford.copy()
if method in ["A", "T"]:
# Apply inverse
# Update table
tmp = ret.destab_x.copy()
ret.destab_x = ret.stab_z.T
ret.destab_z = ret.destab_z.T
ret.stab_x = ret.stab_x.T
ret.stab_z = tmp.T
# Update phase
ret.phase ^= clifford.dot(ret).phase
if method in ["C", "T"]:
# Apply conjugate
ret.phase ^= np.mod(_count_y(ret.x, ret.z), 2).astype(bool)
return ret
def _pad_with_identity(self, clifford, qargs):
"""Pad Clifford with identities on other subsystems."""
if qargs is None:
return clifford
padded = Clifford(np.eye(2 * self.num_qubits, dtype=bool), validate=False, copy=False)
inds = list(qargs) + [self.num_qubits + i for i in qargs]
# Pad Pauli array
for i, pos in enumerate(qargs):
padded.tableau[inds, pos] = clifford.tableau[:, i]
padded.tableau[inds, self.num_qubits + pos] = clifford.tableau[
:, clifford.num_qubits + i
]
# Pad phase
padded.phase[inds] = clifford.phase
return padded
@staticmethod
def _stack_table_phase(table, phase):
return np.hstack((table, phase.reshape(len(phase), 1)))
@staticmethod
def _from_label(label):
phase = False
if label[0] in ("-", "+"):
phase = label[0] == "-"
label = label[1:]
num_qubits = len(label)
symp = np.zeros(2 * num_qubits + 1, dtype=bool)
xs = symp[0:num_qubits]
zs = symp[num_qubits : 2 * num_qubits]
for i, char in enumerate(label):
if char not in ["I", "X", "Y", "Z"]:
raise QiskitError(
f"Pauli string contains invalid character: {char} not in ['I', 'X', 'Y', 'Z']."
)
if char in ("X", "Y"):
xs[num_qubits - 1 - i] = True
if char in ("Z", "Y"):
zs[num_qubits - 1 - i] = True
symp[-1] = phase
return symp
@staticmethod
def _pauli_matrix_to_row(mat, num_qubits):
"""Generate a binary vector (a row of tableau representation) from a Pauli matrix.
Return None if the non-Pauli matrix is supplied."""
# pylint: disable=too-many-return-statements
def find_one_index(x, decimals=6):
indices = np.where(np.round(np.abs(x), decimals) == 1)
return indices[0][0] if len(indices[0]) == 1 else None
def bitvector(n, num_bits):
return np.array([int(digit) for digit in format(n, f"0{num_bits}b")], dtype=bool)[::-1]
# compute x-bits
xint = find_one_index(mat[0, :])
if xint is None:
return None
xbits = bitvector(xint, num_qubits)
# extract non-zero elements from matrix (rounded to 1, -1, 1j or -1j)
entries = np.empty(len(mat), dtype=complex)
for i, row in enumerate(mat):
index = find_one_index(row)
if index is None:
return None
expected = xint ^ i
if index != expected:
return None
entries[i] = np.round(mat[i, index])
# compute z-bits
zbits = np.empty(num_qubits, dtype=bool)
for k in range(num_qubits):
sign = np.round(entries[2**k] / entries[0])
if sign == 1:
zbits[k] = False
elif sign == -1:
zbits[k] = True
else:
return None
# compute phase
phase = None
num_y = sum(xbits & zbits)
positive_phase = (-1j) ** num_y
if entries[0] == positive_phase:
phase = False
elif entries[0] == -1 * positive_phase:
phase = True
if phase is None:
return None
# validate all non-zero elements
coef = ((-1) ** phase) * positive_phase
ivec, zvec = np.ones(2), np.array([1, -1])
expected = coef * functools.reduce(np.kron, [zvec if z else ivec for z in zbits[::-1]])
if not np.allclose(entries, expected):
return None
return np.hstack([xbits, zbits, phase])
@staticmethod
def _unitary_matrix_to_tableau(matrix):
# pylint: disable=invalid-name
num_qubits = int(np.log2(len(matrix)))
stab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool)
for i in range(num_qubits):
label = "I" * (num_qubits - i - 1) + "X" + "I" * i
Xi = Operator.from_label(label).to_matrix()
target = matrix @ Xi @ np.conj(matrix).T
row = Clifford._pauli_matrix_to_row(target, num_qubits)
if row is None:
return None
stab[i] = row
destab = np.empty((num_qubits, 2 * num_qubits + 1), dtype=bool)
for i in range(num_qubits):
label = "I" * (num_qubits - i - 1) + "Z" + "I" * i
Zi = Operator.from_label(label).to_matrix()
target = matrix @ Zi @ np.conj(matrix).T
row = Clifford._pauli_matrix_to_row(target, num_qubits)
if row is None:
return None
destab[i] = row
tableau = np.vstack([stab, destab])
return tableau
# Update docstrings for API docs
generate_apidocs(Clifford)
|
https://github.com/MarvOdo/Quantum-Counting
|
MarvOdo
|
#Implementation of Quantum Counting Algorithm in Qiskit
#By Marvin Odobashi
import numpy as np
from qiskit import *
from qiskit.circuit.library.standard_gates import ZGate
#qubits that determine precision of algorithm
p = 7
#qubits to represent possible inputs to Boolean Function
n = 4
upper = QuantumRegister(p, 'upper')
#1 ancilla qubit to phase shift "correct" states with oracle
lower = QuantumRegister(n+1, 'lower')
measurements = ClassicalRegister(p, 'measurements')
qc = QuantumCircuit(upper, lower, measurements)
#There exists some unknown n-bit input Boolean Function F: {0, 1}^n -> {0, 1}
#Assume we have this oracle that will phase shift solution states
#In this speific case I have picked n=4, but the "solution state selectors" have been defined for a general n
def oracle(qc):
w = qc.width()
#controlled z gate (phase shift state if it is a solution)
ctrlz = ZGate().control(w-1)
#ctrlz for |1111..>
qc.append(ctrlz, range(w))
#ctrlz for |0000..>
qc.x(range(w-1))
qc.append(ctrlz, range(w))
qc.x(range(w-1))
#ctrlz for |10..01>
qc.x(range(1, w-2))
qc.append(ctrlz, range(w))
qc.x(range(1, w-2))
#ctrlz for |01..10>
qc.x([0, w-2])
qc.append(ctrlz, range(w))
qc.x([0, w-2])
#ctrlz for |0111..>
#qc.x([0])
#qc.append(ctrlz, range(w))
#qc.x([0])
#ctrlz for |1011..>
#qc.x([1])
#qc.append(ctrlz, range(w))
#qc.x([1])
return qc
#Grover operator to be repeated
def grover(qc):
w = qc.width()
#oracle
qc = oracle(qc)
#Hadamard-All
qc.h(range(w-1))
#Check if all are 0
ctrlz = ZGate().control(w-1)
qc.x(range(w-1))
qc.append(ctrlz, range(w))
qc.x(range(w-1))
#Hadamard-All
qc.h(range(w-1))
return qc
from qiskit.circuit.library import QFT
#quantum counting
def quantumCount(qc):
#create controlled gate version of grover operation
ctrlGrover = grover(QuantumCircuit(lower)).to_gate(label='CG').control(1)
#initialize circuit, flip last (ancilla) qubit so it can be used for phase shifting by oracle
qc.h(upper)
qc.h(lower[0:-1])
qc.x(lower[-1])
#repeat controlled grover 2^i times for i in {0, p-1}
for i in range(p):
for j in range(2**i):
#controlled grover, ith upper qubit as control, lower register is operated on
qc.append(ctrlGrover, [qc.qubits[i]] + qc.qubits[p:])
#apply inverse QFT on upper register
#using built-in QFT for convenience
iqft = QFT(num_qubits=p, inverse=True).to_gate(label='iQFT')
qc.append(iqft, qc.qubits[:p])
#measure upper register
qc.measure(range(p), range(p))
return qc
#full circuit
final = quantumCount(qc)
#final.draw('mpl')
from qiskit import transpile
from qiskit.providers.aer import AerSimulator
backend = AerSimulator()
qc_compiled = transpile(final, backend)
job_sim = backend.run(qc_compiled, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
#from qiskit.visualization import plot_histogram
#plot_histogram(counts)
#take highest counted state
measured_n = int(max(counts, key=counts.get), 2)
#get theta
theta = 2*np.pi*measured_n/(2**p)
#compute number of solutions
num_sol = (2**n)*np.cos(theta/2)**2
#compute error (formula from https://qiskit.org/textbook/ch-algorithms/quantum-counting.html#finding_m)
N = 2**n
M = N * np.sin(theta / 2)**2
error = (np.sqrt(2*M*N) + N/(2**(p)))*(2**(-p+1))
print(f"""Actual Number of Solutions = 4\n
Quantum Counting Number of Solutions = {num_sol:.1f}\n
Quantum Counting Error < {error:.2f}""")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.draw('mpl')
|
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
|
AbdulahAmer
|
# Do not forget to Import Qiskit
from qiskit.visualization import *
from qiskit import *
S_simulator=Aer.backends(name='statevector_simulator')[0]
M_simulator=Aer.backends(name='qasm_simulator')[0]
# We will have two top qubits (n=2) and one bottom qubit so our circuit
# will have 3 qubits in total.
# Initialize ***
grover = QuantumCircuit(3,3)
# put the last qubit into the |1> state.
one=[0,1]
grover.initialize(one, 1)
#barrier to seperate steps for organization
grover.barrier()
# Apply H to all the gates ***
grover.h(0)
grover.h(1)
grover.h(2)
#barrier to seperate steps for organization
grover.barrier()
#Black box Oracle ***
grover.append(circuit.library.MCXGate(2, ctrl_state='10'), [0,1,2])
grover.barrier()
# Phase Shift ***
# Apply H to top qubits
grover.h(0)
grover.h(1)
# Apply X to top qubits
grover.x(0)
grover.x(1)
#barrier for organization
grover.barrier()
# H on second qubit
grover.h(1)
#barrier for organization
grover.barrier()
# Cnot on first and second qubits
grover.cx(0,1)
# barrier for organization
grover.barrier()
# H on second qubit
grover.h(1)
#barrier
grover.barrier()
# X on first and second qubits
grover.x(0)
grover.x(1)
#barrier
grover.barrier()
# Apply H at the end ***
grover.h(0)
grover.h(1)
grover.h(2)
# barrier
grover.barrier()
# measure all the qubits and put the measurements in their corresponding classical bits
grover.measure([0,1,2], [0,1,2])
#draw it out
grover.draw(output='mpl')
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
from sklearn.datasets import load_iris
import pennylane as qml
import numpy as np
from pennylane.optimize import AdamOptimizer
import matplotlib.pyplot as plt
X, Y = load_iris(return_X_y=True)
X_train_0 = X[0:30]
X_train_1 = X[50:80]
X_train = np.vstack((X_train_0, X_train_1))
Y_train_0 = Y[0:30]
Y_train_1 = Y[50:80]
Y_train = np.vstack((Y_train_0, Y_train_1)).flatten()
X, Y = load_iris(return_X_y=True)
X_test_0 = X[30:50]
X_test_1 = X[80:100]
X_test = np.vstack((X_test_0, X_test_1))
Y_test_0 = Y[30:50]
Y_test_1 = Y[80:100]
Y_test = np.vstack((Y_test_0, Y_test_1)).flatten()
X_train = (X_train - X_train.min(axis=0)) / (X_train.max(axis=0) - X_train.min(axis=0))
X_test = (X_test - X_test.min(axis=0)) / (X_test.max(axis=0) - X_test.min(axis=0))
qubits_num = 4
layers_num = 2
dev = qml.device("default.qubit",wires=qubits_num)
class VQC:
def __init__(self):
# 3 => U3(theta, phi, lambda)
self.params = (0.01 * np.random.randn(layers_num, qubits_num, 3))
params = [-0.61058476, -0.23619078, -0.67559108]
self.params = [
[params, params, params, params],
[params, params, params, params],
]
self.bestparams = self.params
self.bestcost = 10
self.opt = AdamOptimizer(0.125)
self.weights = []
self.costs = []
self.accuracies = []
def fit(self, X_train, Y_train, epoch=300):
batch_size = 20
for turn in range(epoch):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train), (batch_size,))
X_train_batch = X_train[batch_index]
Y_train_batch = Y_train[batch_index]
self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params)
cost_now = cost(self.params, X_train, Y_train)
acc_now = accuracy(self.params, X_train, Y_train)
if cost_now < self.bestcost:
self.bestcost = cost_now
self.bestparams = self.params
self.weights.append(self.params)
self.costs.append(cost_now)
self.accuracies.append(acc_now)
print(
"Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format(
turn, cost_now, acc_now * 100
))
def score(self, X_test, Y_test):
predictions = [ predict(self.bestparams, data) for data in X_test ]
acc = accuracy(self.bestparams, X_test, Y_test)
print("FINAL ACCURACY: {:0.2f}%".format(acc * 100))
@qml.qnode(dev)
def circuit(params, data):
angles = [ i * np.pi for i in data ]
for i in range(qubits_num):
qml.RX(angles[i], wires=i)
qml.Rot( *params[0, i], wires=i )
qml.CZ(wires=[1, 0])
qml.CZ(wires=[1, 2])
qml.CZ(wires=[2, 3])
qml.CZ(wires=[0, 3])
for i in range(qubits_num):
qml.Rot( *params[1, i], wires=i )
# PauliZ measure => 1 -> |0> while -1 -> |1>
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)), qml.expval(qml.PauliZ(3))
import qiskit
import numpy as np
from qiskit import QuantumCircuit
from qiskit import Aer, execute
unitary_backend = Aer.get_backend('unitary_simulator')
qasm_backend = Aer.get_backend('qasm_simulator')
def predict(params, data):
qcircuit = QuantumCircuit(4, 4)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[2], qubits[3])
qcircuit.cz(qubits[0], qubits[3])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
# the measurement
qcircuit.measure([0, 1, 2, 3], [0, 1, 2, 3])
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
p1 = (counts.get('1000', 0) + counts.get('1001', 0) + counts.get('1010', 0) + counts.get('1011',0) + \
counts.get('1100',0) + counts.get('1101',0) + counts.get('1110',0) + counts.get('1111',0)) / shots
if p1 > 0.5:
return 1
else:
return 0
def cost(weights, datas, labels):
loss = 0
for i, data in enumerate(datas):
# like [-1, 1, 1]
measured = circuit(weights, data)
p = measured[0]
if labels[i] == 0:
loss += (1 - p) ** 2
else:
loss += (-1 - p) ** 2
return loss / len(datas)
def accuracy(weights, datas, labels):
predictions = [ predict(weights, data) for data in datas ]
acc = 0
for i, p in enumerate(predictions):
if p == labels[i]:
acc += 1
return acc / len(predictions)
vqc = VQC()
vqc.fit(X_train, Y_train, epoch=1)
print(vqc.weights[26])
vqc.bestparams = vqc.weights[26]
vqc.score(X_test, Y_test)
vqc.score(X_train, Y_train)
vqc.bestparams
def createCircuit(params, data):
qcircuit = QuantumCircuit(4, 4)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[2], qubits[3])
qcircuit.cz(qubits[0], qubits[3])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
return qcircuit
vqc.bestparams
qcircuit = createCircuit(vqc.bestparams, X_train[0])
qcircuit.draw(output='mpl')
print(X_train[15])
print(Y_train[15])
print(X_train[35])
print(Y_train[35])
circuit = QuantumCircuit(1, 1)
qubits = circuit.qubits
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
import math
# importing Qiskit
from qiskit import Aer, transpile, assemble
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.circuit.library import QFT
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_bloch_multivector
def qft_dagger(qc, n):
"""n-qubit QFTdagger the first n qubits in circ"""
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-math.pi/float(2**(j-m)), m, j)
qc.h(j)
#Modified to remove prints
def generalised_qpe_timing(amt_estimation_qubits, angle, shots=4096):
# Create and set up circuit
qpe3 = QuantumCircuit(amt_estimation_qubits+1, amt_estimation_qubits)
# Apply H-Gates to counting qubits:
for qubit in range(amt_estimation_qubits):
qpe3.h(qubit)
# Prepare our eigenstate |psi>:
qpe3.x(amt_estimation_qubits)
repetitions = 1
for counting_qubit in range(amt_estimation_qubits):
for i in range(repetitions):
qpe3.cp(angle, counting_qubit, amt_estimation_qubits);
repetitions *= 2
# Do the inverse QFT:
qft_dagger(qpe3, amt_estimation_qubits)
# Measure of course!
qpe3.barrier()
for n in range(amt_estimation_qubits):
qpe3.measure(n,n)
#print(qpe3)
# Let's see the results!
aer_sim = Aer.get_backend('aer_simulator')
t_qpe3 = transpile(qpe3, aer_sim)
qobj = assemble(t_qpe3, shots=shots)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
##return(plot_histogram(answer))
##comment out the return if you want to see the histogram
## do not output value to not skew timing
return ((int(answer.most_frequent(), 2)/2**amt_estimation_qubits))
generalised_qpe_timing(8,(2*math.pi/3),10000)
#generalised_qpe(2,(2*math.pi/4))
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
%timeit -p 8 -r 1 -n 1 generalised_qpe_timing(8,(2*math.pi/3),10000)
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
import numpy as np
import copy
from qiskit_experiments.library import StandardRB, InterleavedRB
from qiskit_experiments.framework import ParallelExperiment
from qiskit_experiments.library.randomized_benchmarking import RBUtils
import qiskit.circuit.library as circuits
# import the bayesian packages
import pymc3 as pm
import arviz as az
import qiskit_bayesian_fitter as bf
# define backend
from qiskit.providers.aer import AerSimulator
from qiskit.test.mock import FakeParis
backend = AerSimulator.from_backend(FakeParis())
# describe RB experiment
qubits = [0]
lengths = np.arange(1, 2500, 250)
num_samples = 10
seed = 3018
exp1 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed)
expdata1 = exp1.run(backend).block_for_results()
results1 = expdata1.analysis_results()
#prepare circuits
exp1 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed)
#run
expdata1 = exp1.run(backend).block_for_results()
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
m_len = len(lengths)
interleaved_gate = "" # for plot title
experiment_type = expdata1._data[0]['metadata']['experiment_type']
physical_qubits = expdata1._data[0]['metadata']['physical_qubits']
shots = expdata1._data[0]['shots']
# to compare ultimately: EPC and sigma(EPC) by LSF
epc_est_fm = expdata1.analysis_results()[2].value.value
epc_est_fm_err = expdata1.analysis_results()[2].value.stderr
# get count data and other values from expdata1
Y = bf.get_GSP_counts(expdata1._data, m_len,
range(num_samples))
X = np.copy(lengths)
y_mean = np.mean(Y, axis = 0)/shots
sigma_y = np.std(Y, axis = 0)/shots
model = "hierarchical model"
# priors for unknown model parameters
T_priors = expdata1.analysis_results()[0].value.value
print(T_priors)
testval_s = 0.001
upper_s = 0.004
lower_s = 0.0001
alpha_Gamma = 10
beta_Gamma = 10000
h_model = bf.create_model(T_priors, X, Y, shots, scale,
testval_s = testval_s ,upper_s = upper_s, lower_s = lower_s,
s_prior = "Gamma", alpha_Gamma = alpha_Gamma, beta_Gamma = beta_Gamma)
# model graph
pm.model_to_graphviz(h_model)
# sample
with h_model:
trace_h = pm.sample(draws = 4000, tune= 1000, target_accept=.99,
return_inferencedata=True)
with h_model:
az.plot_trace(trace_h);
with h_model:
az.plot_posterior(trace_h, var_names = ["Tying_Parameters","σ_Beta","EPC"], round_to = 4, figsize = [16, 8]);
# look at the posterior values of the hyperparameters:
with h_model:
# (hdi_prob=.94 is default)
azt_summary = az.summary(trace_h, round_to=12,
var_names = ["Tying_Parameters", "σ_Beta","EPC"],
kind="stats")
azt_summary
# for comparison
# reference
epc_calib = np.nan
# bayesian
epc_est_a = azt_summary['mean']['EPC']
epc_est_a_err = azt_summary['sd']['EPC']
# frequentist
epc_est_fm = expdata1.analysis_results()[2].value.value
epc_est_fm_err = expdata1.analysis_results()[2].value.stderr
epc_title = experiment_type +', qubit(s):' + str(physical_qubits)\
+', backend: '+backend.name() + "\n Bayesian "+model
bf.plot_epc(h_model, trace_h, epc_calib, epc_est_a,
epc_est_a_err, epc_est_fm, epc_est_fm_err, epc_title)
# backend's recorded EPG
error_dic = RBUtils.get_error_dict_from_backend(backend, qubits)
# get the EPG values
EPG_dic = {}
REF_dic = {}
for i in range(3,6):
EPG_key = expdata1.analysis_results()[i].name
EPG_dic[EPG_key] = expdata1.analysis_results()[i].value.value
for elem in (error_dic):
if 'EPG_' + elem[1] == EPG_key:
REF_dic[EPG_key] = error_dic[elem]
# compare LSF and SMC
print("Model: Frequentist Bayesian Reference")
print("________________________________________________________")
print("EPC {0:1.3e} {1:1.3e} {2:1.3e}"
.format(epc_est_fm, epc_est_a, epc_calib ))
print("± sd ± {0:1.3e} ± {1:1.3e} "
.format(epc_est_fm_err, epc_est_a_err))
for i, (gate,EPG) in enumerate(EPG_dic.items()):
print("{0:<12}{1:1.3e} {2:1.3e} {3:1.3e} "
.format(gate, EPG, EPG*epc_est_a/epc_est_fm,
REF_dic[gate]))
# prepare box for GSP plot
texto = "alpha = {0:7.4f} ± {1:1.4e}"\
.format(azt_summary['mean']['Tying_Parameters[1]'],
azt_summary['sd']['Tying_Parameters[1]']) + "\n"
texto += "EPC = {0:1.4e} ± {1:1.4e}"\
.format(azt_summary['mean']['EPC'],
azt_summary['sd']['EPC']) + "\n"
for i, (gate,EPG) in enumerate(EPG_dic.items()):
texto += " {0:<8} = {1:1.4e} "\
.format(gate.ljust(6), EPG*epc_est_a/epc_est_fm) + "\n"
texto += " Fit χ² = {0:7.4f} "\
.format(bf.reduced_chisquare(y_mean, sigma_y, trace_h))
bounds_rmk, y1, y1_min, y1_max = bf.prepare_data_GSP_plot(h_model, trace_h, HDI = False)
title = experiment_type +', ' + interleaved_gate\
+ str(physical_qubits)\
+', backend: '+backend.name()+\
"\n Bayesian "+model+" "+ bounds_rmk
bf.gsp_plot(scale, lengths, num_samples, shots, texto, title,
y1, y1_min, y1_max, y2=None, y2_min=None, y2_max=None, Y1=Y, Y2=None,
first_curve = "Calculated values", second_curve = None)
# View data for frequentist model
display(expdata1.figure(0))
lengths = np.arange(1, 200, 15)
num_samples = 10
seed = 3018
qubits = (1,4)
# Run a 1-qubit RB expriment on qubits 1, 4 to determine the error-per-gate of 1-qubit gates
expdata_1q = {}
epg_1q = []
lengths_1_qubit = np.arange(1, 2500, 250)
for qubit in qubits:
exp = StandardRB([qubit], lengths_1_qubit, num_samples=num_samples, seed=seed)
expdata = exp.run(backend).block_for_results()
expdata_1q[qubit] = expdata
epg_1q += expdata.analysis_results()
# Run an RB experiment on qubits 1, 4
exp2 = StandardRB(qubits, lengths, num_samples=num_samples, seed=seed)
# Use the EPG data of the 1-qubit runs to ensure correct 2-qubit EPG computation
exp2.set_analysis_options(epg_1_qubit=epg_1q)
# Run the 2-qubit experiment
expdata2 = exp2.run(backend).block_for_results()
# View result data
results2 = expdata2.analysis_results()
# Compare the computed EPG of the cx gate with the backend's recorded cx gate error:
expected_epg = RBUtils.get_error_dict_from_backend(backend, qubits)[(qubits, 'cx')]
exp2_epg = expdata2.analysis_results("EPG_cx").value
print("Backend's reported EPG of the cx gate:", expected_epg)
print("Experiment computed EPG of the cx gate:", exp2_epg)
trace_1q = {}
scale_1q = .5
for qubit in qubits:
Y = bf.get_GSP_counts(expdata_1q[qubit]._data, len(lengths_1_qubit),
range(num_samples))
X = np.copy(lengths_1_qubit)
shots_1_qubit = expdata_1q[qubit]._data[0]['shots']
T_priors = expdata_1q[qubit].analysis_results()[0].value.value
testval_s = 0.001
upper_s = 0.004
lower_s = 0.0001
alpha_Gamma = 10
beta_Gamma = 10000
h1_model = bf.create_model(T_priors, X, Y, shots_1_qubit, scale_1q,
testval_s = testval_s ,upper_s = upper_s, lower_s = lower_s,
s_prior = "Gamma", alpha_Gamma = alpha_Gamma, beta_Gamma = beta_Gamma)
with h1_model:
trace_h1 = pm.sample(draws = 4000, tune= 1000, target_accept=.99,
return_inferencedata=True)
trace_1q[qubit] = trace_h1
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
m_len = len(lengths)
interleaved_gate = "" # for plot title
experiment_type = expdata2._data[0]['metadata']['experiment_type']
physical_qubits = expdata2._data[0]['metadata']['physical_qubits']
shots = expdata2._data[0]['shots']
# get count data and other values from expdata2
Y = bf.get_GSP_counts(expdata2._data, m_len,
range(num_samples))
X = np.copy(lengths)
y_mean = np.mean(Y, axis = 0)/shots
sigma_y = np.std(Y, axis = 0)/shots
model = "hierarchical model"
# priors for unknown model parameters
T_priors = expdata2.analysis_results()[0].value.value
print(T_priors)
testval_s = 0.0025
upper_s = 0.005
lower_s = 0.0005
alpha_Gamma = 5
beta_Gamma = 2000
h2_model = bf.create_model(T_priors, X, Y, shots, scale,
testval_s = testval_s ,upper_s = upper_s, lower_s = lower_s,
s_prior = "Gamma", alpha_Gamma = alpha_Gamma, beta_Gamma = beta_Gamma)
# model graph
pm.model_to_graphviz(h2_model)
# sample
with h2_model:
trace_h2 = pm.sample(draws = 4000, tune= 1000, target_accept=.99,
return_inferencedata=True)
with h2_model:
az.plot_trace(trace_h2);
with h2_model:
az.plot_posterior(trace_h2, var_names = ["Tying_Parameters","σ_Beta","EPC"], round_to = 4, figsize = [16, 8]);
# look at the posterior values of the hyperparameters:
with h2_model:
# (hdi_prob=.94 is default)
azt2_summary = az.summary(trace_h2, round_to=12,
var_names = ["Tying_Parameters", "σ_Beta","EPC"],
kind="stats")
azt2_summary
# for comparison
# reference
epc_calib = np.nan
# bayesian
epc_est_a = azt2_summary['mean']['EPC']
epc_est_a_err = azt2_summary['sd']['EPC']
# frequentist
epc_est_fm = expdata2.analysis_results()[2].value.value
epc_est_fm_err = expdata2.analysis_results()[2].value.stderr
epc_title = experiment_type +', qubit(s):' + str(physical_qubits)\
+', backend: '+backend.name() + "\n Bayesian "+model
bf.plot_epc(h2_model, trace_h2, epc_calib, epc_est_a,
epc_est_a_err, epc_est_fm, epc_est_fm_err, epc_title)
# obtain posterior values of the hyperparameters:
azts_1q = []
for i_qubit, qubit in enumerate(qubits):
with h2_model:
# (hdi_prob=.94 is default)
azts_1q.append( az.summary(trace_1q[qubit], round_to=12,
var_names = ["Tying_Parameters", "σ_Beta","EPC"],
kind="stats") )
# retrieve gates per clifford from frequentist results
alpha_1q = [epg_1q[1].value.value, epg_1q[7].value.value]
epc_2_qubit = expdata2.analysis_results()[2].value.value
alpha_c_1q = 1 / 5 * (alpha_1q[0] + alpha_1q[1] + 3 * alpha_1q[0] * alpha_1q[1])
alpha_c_2q = (1 - 4 / 3 * epc_2_qubit) / alpha_c_1q
n_gate_2q = 3 / 4 * (1 - alpha_c_2q) / exp2_epg.value
# calculate epg cx from the bayesian results
alpha_1q_b = [azts_1q[0]['mean']['Tying_Parameters[1]'],
azts_1q[1]['mean']['Tying_Parameters[1]']]
epc_2_qubit_b = azt2_summary['mean']['EPC']
alpha_c_1q_b = 1 / 5 * (alpha_1q_b[0] + alpha_1q_b[1] + 3 * alpha_1q_b[0] * alpha_1q_b[1])
alpha_c_2q_b = (1 - 4 / 3 * epc_2_qubit_b) / alpha_c_1q_b
epg_cx = 3 / 4 * (1 - alpha_c_2q_b) / n_gate_2q
# compare LSF and SMC
print("Model: Frequentist Bayesian Reference")
print("________________________________________________________")
print("EPC {0:1.3e} {1:1.3e} -----"
.format(epc_est_fm, epc_est_a ))
print("± sd ± {0:1.3e} ± {1:1.3e} "
.format(epc_est_fm_err, epc_est_a_err))
print("EPG_cx {0:1.3e} {1:1.3e} {2:1.3e}"
.format(exp2_epg.value, epg_cx, expected_epg))
# prepare box for GSP plot
texto = " alpha = {0:7.4f} ± {1:1.4e}"\
.format(azt2_summary['mean']['Tying_Parameters[1]'],
azt2_summary['sd']['Tying_Parameters[1]']) + "\n"
texto += " EPC = {0:1.4e} ± {1:1.4e}"\
.format(azt2_summary['mean']['EPC'],
azt2_summary['sd']['EPC']) + "\n"
texto += " EPG_cx = {0:7.4f}"\
.format(epg_cx) + "\n"
texto += " Fit χ² = {0:7.4f} "\
.format(bf.reduced_chisquare(y_mean, sigma_y, trace_h2))
bounds_rmk, y1, y1_min, y1_max = bf.prepare_data_GSP_plot(h2_model, trace_h2)
title = experiment_type +', ' + interleaved_gate\
+ str(physical_qubits)\
+', backend: '+backend.name()+\
"\n Bayesian "+model+" "+ bounds_rmk
bf.gsp_plot(scale, lengths, num_samples, shots, texto, title,
y1, y1_min, y1_max, y2=None, y2_min=None, y2_max=None, Y1=Y, Y2=None,
first_curve = "Calculated values", second_curve = None)
# View result for frequentist model
display(expdata2.figure(0))
interleaved_gate = "x"
interleaved_circuit = circuits.XGate()
qubits = [0]
lengths = np.arange(1, 2500, 250)
testval_s = 0.001
upper_s = 0.004
lower_s = 0.0005
alpha_Gamma = 10
beta_Gamma = 10000
num_samples = 10
seed = 41730
epc_calib = REF_dic['EPG_' + interleaved_gate]
print('EPC reference: {0:1.4e}'.format(epc_calib))
#prepare circuits
int1exp = InterleavedRB(interleaved_circuit, qubits,
lengths, num_samples=num_samples, seed=seed)
#run
int1expdata = int1exp.run(backend).block_for_results()
experiment_type = int1expdata._data[0]['metadata']['experiment_type']
physical_qubits = int1expdata._data[0]['metadata']['physical_qubits']
shots = int1expdata._data[0]['shots']
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
m_len = len(lengths)
# get count data and other values from int1expdata
Y = bf.get_GSP_counts(int1expdata._data, 2*m_len,
range(num_samples))
# get RvsI_h and IvsR_h
RvsI_h = np.ones(2*m_len)
for i_data in range(2*m_len):
if int1expdata._data[i_data]['metadata']['interleaved']:
RvsI_h[i_data] = 0.
IvsR_h = (RvsI_h + 1.) %2
X0 = np.tile(lengths,2)
X = np.vstack((X0,RvsI_h,IvsR_h))
y_mean = np.mean(Y, axis = 0)/shots
sigma_y = np.std(Y, axis = 0)/shots
model = "hierarchical model"
# priors for unknown model parameters
T_priors = int1expdata.analysis_results()[0].value.value
print(T_priors)
hv1 = bf.create_model(T_priors, X, Y, shots, scale,
testval_s = testval_s, upper_s = upper_s, lower_s = lower_s,
s_prior = "Gamma", alpha_Gamma = alpha_Gamma, beta_Gamma = beta_Gamma)
# model graph
pm.model_to_graphviz(hv1)
# sample
with hv1:
trace_hv1 = pm.sample(draws = 4000, tune= 1000, target_accept=.99,
return_inferencedata=True)
with hv1:
az.plot_trace(trace_hv1);
with hv1:
az.plot_posterior(trace_hv1, var_names = ["Tying_Parameters","σ_Beta","EPC"], round_to = 4, figsize = [16, 8]);
# look at the posterior values of the hyperparameters:
with hv1:
# (hdi_prob=.94 is default)
aztv1_summary = az.summary(trace_hv1, round_to=12,
var_names = ["Tying_Parameters","σ_Beta","EPC"],
kind="stats")
aztv1_summary
# for comparison
# bayesian
epc_est_a = aztv1_summary['mean']['EPC']
epc_est_a_err = aztv1_summary['sd']['EPC']
# frequentist
epc_est_fm = int1expdata.analysis_results()[3].value.value
epc_est_fm_err = int1expdata.analysis_results()[3].value.stderr
epc_title = experiment_type +', ' + interleaved_gate \
+ " qubit(s):" + str(physical_qubits)\
+', backend: '+ backend.name() + "\n Bayesian "+model
bf.plot_epc(hv1, trace_hv1, epc_calib, epc_est_a,
epc_est_a_err, epc_est_fm, epc_est_fm_err, epc_title)
# compare LSF and SMC
print("Model: Frequentist Bayesian Reference")
print("__________________________________________________________")
print("EPC {0:1.3e} {1:1.3e} {2:1.3e}"
.format(epc_est_fm,epc_est_a,epc_calib ))
print("± sd ± {0:1.3e} ± {1:1.3e} "
.format(epc_est_fm_err, epc_est_a_err))
# for WIP
import importlib
importlib.reload(bf)
# obtain data for plot
bounds_rmk, y1, y1_min, y1_max, y2, y2_min, y2_max, Y1, Y2 = \
bf.prepare_two_curves_GSP_plot(hv1, trace_hv1, X, Y, HDI = False)
reduced_chisq = bf.reduced_chisquare(y_mean, sigma_y, trace_hv1)
texto = bf.get_box_interleaved(aztv1_summary, reduced_chisq)
title = experiment_type +', ' + interleaved_gate\
+ str(physical_qubits)\
+', backend: '+backend.name()+\
"\n Bayesian "+model+" "+ bounds_rmk
# plot
bf.gsp_plot(scale, lengths, num_samples, shots, texto, title,
y1, y1_min, y1_max, y2, y2_min, y2_max, Y1, Y2,
first_curve = "Standard", second_curve = "Interleaved")
# View result for frequentist model
display(int1expdata.figure(0))
interleaved_gate = "cx"
interleaved_circuit = circuits.CXGate()
qubits = [1,4]
lengths = np.arange(1, 200, 15)
testval_s = 0.0025
upper_s = 0.005
lower_s = 0.0005
alpha_Gamma = 5
beta_Gamma = 2000
num_samples = 10
seed = 3018
epc_calib = expected_epg
print('EPC reference: {0:1.4e}'.format(epc_calib))
#prepare circuits
int_exp = InterleavedRB(interleaved_circuit, qubits,
lengths, num_samples=num_samples, seed=seed)
#run
int_expdata = int_exp.run(backend).block_for_results()
experiment_type = int_expdata._data[0]['metadata']['experiment_type']
physical_qubits = int_expdata._data[0]['metadata']['physical_qubits']
shots = int_expdata._data[0]['shots']
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
m_len = len(lengths)
# get count data and other values from int_expdata
Y = bf.get_GSP_counts(int_expdata._data, 2*m_len,
range(num_samples))
# get RvsI_h and IvsR_h
RvsI_h = np.ones(2*m_len)
for i_data in range(2*m_len):
if int_expdata._data[i_data]['metadata']['interleaved']:
RvsI_h[i_data] = 0.
IvsR_h = (RvsI_h + 1.) %2
X0 = np.tile(lengths,2)
X = np.vstack((X0,RvsI_h,IvsR_h))
y_mean = np.mean(Y, axis = 0)/shots
sigma_y = np.std(Y, axis = 0)/shots
model = "hierarchical model"
# priors for unknown model parameters
T_priors = int_expdata.analysis_results()[0].value.value
print(T_priors)
hv2 = bf.create_model(T_priors, X, Y, shots, scale,
testval_s = testval_s, upper_s = upper_s, lower_s = lower_s,
s_prior = "Gamma", alpha_Gamma = alpha_Gamma, beta_Gamma = beta_Gamma)
# model graph
pm.model_to_graphviz(hv2)
# sample
with hv2:
trace_hv2 = pm.sample(draws = 4000, tune= 1000, target_accept=.99,
return_inferencedata=True)
with hv2:
az.plot_trace(trace_hv2);
with hv2:
az.plot_posterior(trace_hv2, var_names = ["Tying_Parameters","σ_Beta","EPC"], round_to = 4, figsize = [16, 8]);
# look at the posterior values of the hyperparameters:
with hv2:
# (hdi_prob=.94 is default)
aztv2_summary = az.summary(trace_hv2, round_to=12,
var_names = ["Tying_Parameters","σ_Beta","EPC"],
kind="stats")
aztv2_summary
# for comparison
# bayesian
epc_est_a = aztv2_summary['mean']['EPC']
epc_est_a_err = aztv2_summary['sd']['EPC']
# frequentist
epc_est_fm = int_expdata.analysis_results()[3].value.value
epc_est_fm_err = int_expdata.analysis_results()[3].value.stderr
epc_title = experiment_type +', ' + interleaved_gate \
+ " qubit(s):" + str(physical_qubits)\
+', backend: '+ backend.name() + "\n Bayesian "+model
bf.plot_epc(hv2, trace_hv2, epc_calib, epc_est_a,
epc_est_a_err, epc_est_fm, epc_est_fm_err, epc_title)
# compare LSF and SMC
print("Model: Frequentist Bayesian Reference")
print("__________________________________________________________")
print("EPC {0:1.3e} {1:1.3e} {2:1.3e}"
.format(epc_est_fm,epc_est_a,epc_calib ))
print("± sd ± {0:1.3e} ± {1:1.3e} "
.format(epc_est_fm_err, epc_est_a_err))
# obtain data for plot
bounds_rmk, y1, y1_min, y1_max, y2, y2_min, y2_max, Y1, Y2 = \
bf.prepare_two_curves_GSP_plot(hv2, trace_hv2, X, Y, HDI = False)
reduced_chisq = bf.reduced_chisquare(y_mean, sigma_y, trace_hv2)
texto = bf.get_box_interleaved(aztv2_summary, reduced_chisq)
title = experiment_type +', ' + interleaved_gate\
+ str(physical_qubits)\
+', backend: '+backend.name()+\
"\n Bayesian "+model+" "+ bounds_rmk
# plot
bf.gsp_plot(scale, lengths, num_samples, shots, texto, title,
y1, y1_min, y1_max, y2, y2_min, y2_max, Y1, Y2,
first_curve = "Standard", second_curve = "Interleaved")
# View result for frequentist model
display(int_expdata.figure(0))
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from matplotlib import pyplot as plt
import numpy as np
from qiskit import *
from qiskit.visualization import plot_bloch_vector
plt.figure()
ax = plt.gca()
ax.quiver([3], [5], angles='xy', scale_units='xy', scale=1)
ax.set_xlim([-1, 10])
ax.set_ylim([-1, 10])
plt.draw()
plt.show()
plot_bloch_vector([1, 0, 0])
plot_bloch_vector([0, 0, 0])
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
"""
Deutsch-Jozsa Benchmark Program - QSim
"""
import sys
import time
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
sys.path[1:1] = [ "_common", "_common/qsim" ]
sys.path[1:1] = [ "../../_common", "../../_common/qsim" ]
import execute as ex
import metrics as metrics
from execute import BenchmarkResult
# Benchmark Name
benchmark_name = "Deutsch-Jozsa"
np.random.seed(0)
verbose = False
# saved circuits for display
QC_ = None
C_ORACLE_ = None
B_ORACLE_ = None
############### Circuit Definition
# Create a constant oracle, appending gates to given circuit
def constant_oracle (input_size, num_qubits):
#Initialize first n qubits and single ancilla qubit
qc = QuantumCircuit(num_qubits, name=f"Uf")
output = np.random.randint(2)
if output == 1:
qc.x(input_size)
global C_ORACLE_
if C_ORACLE_ == None or num_qubits <= 6:
if num_qubits < 9: C_ORACLE_ = qc
return qc
# Create a balanced oracle.
# Perform CNOTs with each input qubit as a control and the output bit as the target.
# Vary the input states that give 0 or 1 by wrapping some of the controls in X-gates.
def balanced_oracle (input_size, num_qubits):
#Initialize first n qubits and single ancilla qubit
qc = QuantumCircuit(num_qubits, name=f"Uf")
b_str = "10101010101010101010" # permit input_string up to 20 chars
for qubit in range(input_size):
if b_str[qubit] == '1':
qc.x(qubit)
qc.barrier()
for qubit in range(input_size):
qc.cx(qubit, input_size)
qc.barrier()
for qubit in range(input_size):
if b_str[qubit] == '1':
qc.x(qubit)
global B_ORACLE_
if B_ORACLE_ == None or num_qubits <= 6:
if num_qubits < 9: B_ORACLE_ = qc
return qc
# Create benchmark circuit
def DeutschJozsa (num_qubits, type):
# Size of input is one less than available qubits
input_size = num_qubits - 1
# allocate qubits
qr = QuantumRegister(num_qubits)
cr = ClassicalRegister(input_size)
qc = QuantumCircuit(qr, cr, name=f"dj-{num_qubits}-{type}")
for qubit in range(input_size):
qc.h(qubit)
qc.x(input_size)
qc.h(input_size)
qc.barrier()
# Add a constant or balanced oracle function
if type == 0: Uf = constant_oracle(input_size, num_qubits)
else: Uf = balanced_oracle(input_size, num_qubits)
qc.append(Uf, qr)
qc.barrier()
for qubit in range(num_qubits):
qc.h(qubit)
# uncompute ancilla qubit, not necessary for algorithm
qc.x(input_size)
qc.barrier()
for i in range(input_size):
qc.measure(i, i)
# save smaller circuit and oracle subcircuit example for display
global QC_
if QC_ == None or num_qubits <= 6:
if num_qubits < 9: QC_ = qc
# return a handle to the circuit
return qc
############### Result Data Analysis
# Analyze and print measured results
# Expected result is always the type, so fidelity calc is simple
def analyze_and_print_result(qc, result, num_qubits, type, num_shots):
# Size of input is one less than available qubits
input_size = num_qubits - 1
if result.backend_name == 'dm_simulator':
benchmark_result = BenchmarkResult(result, num_shots)
probs = benchmark_result.get_probs(num_shots) # get results as measured probability
else:
probs = result.get_counts(qc) # get results as measured counts
if verbose: print(f"For type {type} measured: {probs}")
# create the key that is expected to have all the measurements (for this circuit)
if type == 0: key = '0'*input_size
else: key = '1'*input_size
# correct distribution is measuring the key 100% of the time
correct_dist = {key: 1.0}
# use our polarization fidelity rescaling
fidelity = metrics.polarization_fidelity(probs, correct_dist)
return probs, fidelity
def run(min_qubits=3, max_qubits=8, skip_qubits=1, max_circuits=3, num_shots=1000,
backend_id='dm_simulator', provider_backend=None, exec_options=None, context=None):
print(f"{benchmark_name} Benchmark Program - QSim")
# 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)
#print(f"min, max qubits = {min_qubits} {max_qubits}")
# Create context identifier
if context is None:
context = f"{benchmark_name} Benchmark"
# Initialize metrics module
metrics.init_metrics()
# Define custom result handler
def execution_handler (qc, result, num_qubits, type, num_shots):
# determine fidelity of result set
num_qubits = int(num_qubits)
counts, fidelity = analyze_and_print_result(qc, result, num_qubits, int(type), num_shots)
metrics.store_metric(num_qubits, type, 'fidelity', fidelity)
# Initialize execution module using the execution result handler above and specified backend_id
ex.init_execution(execution_handler)
ex.set_execution_target(backend_id, provider_backend=provider_backend,
exec_options=exec_options,
context=context)
# Execute Benchmark Program N times for multiple circuit sizes
# Accumulate metrics asynchronously as circuits complete
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
input_size = num_qubits - 1
# Determine number of circuits to execute for this group
num_circuits = min(2, max_circuits)
print(f"************\nExecuting [{num_circuits}] circuits with num_qubits = {num_qubits}")
# Loop over only 2 circuits
for type in range(num_circuits):
# Create the circuit for given qubit size and secret string, store time metric
ts = time.time()
qc = DeutschJozsa(num_qubits, type).reverse_bits() # reverse_bits() is applying to handle the change in endianness
print(f"DJ Circuit for qubit size of {num_qubits} and type {type} : \n{qc} ")
metrics.store_metric(num_qubits, type, 'create_time', time.time() - ts)
# Collapse the sub-circuit levels used in this benchmark (for qiskit)
qc2 = qc.decompose()
# Submit circuit for execution on target (simulator, cloud simulator, or hardware)
ex.submit_circuit(qc2, num_qubits, type, num_shots)
# Wait for some active circuits to complete; report metrics when groups complete
ex.throttle_execution(metrics.finalize_group)
# Wait for all active circuits to complete; report metrics when groups complete
ex.finalize_execution(metrics.finalize_group)
##########
# Print a sample circuit
# print("Sample Circuit:"); print(QC_ if QC_ is not None else " ... too large!")
print("\nConstant Oracle 'Uf' ="); print(C_ORACLE_ if C_ORACLE_ is not None else " ... too large or not used!")
print("\nBalanced Oracle 'Uf' ="); print(B_ORACLE_ if B_ORACLE_ is not None else " ... too large or not used!")
# Plot metrics for all circuit sizes
metrics.plot_metrics(f"Benchmark Results - {benchmark_name} - QSim")
# if main, execute method
if __name__ == '__main__': run()
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
import cirq
except ImportError:
print("installing cirq...")
!pip install cirq --quiet
print("installed cirq.")
import cirq
import random
import matplotlib.pyplot as plt
import numpy as np
def make_quantum_teleportation_circuit(gate):
"""Returns a circuit for quantum teleportation.
This circuit 'teleports' a random qubit state prepared by
the input gate from Alice to Bob.
"""
circuit = cirq.Circuit()
# Get the three qubits involved in the teleportation protocol.
msg = cirq.NamedQubit("Message")
alice = cirq.NamedQubit("Alice")
bob = cirq.NamedQubit("Bob")
# The input gate prepares the message to send.
circuit.append(gate(msg))
# Create a Bell state shared between Alice and Bob.
circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)])
# Bell measurement of the Message and Alice's entangled qubit.
circuit.append([cirq.CNOT(msg, alice), cirq.H(msg), cirq.measure(msg, alice)])
# Uses the two classical bits from the Bell measurement to recover the
# original quantum message on Bob's entangled qubit.
circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)])
return circuit
"""Visualize the teleportation circuit."""
# Gate to put the message qubit in some state to send.
gate = cirq.X ** 0.25
# Create the teleportation circuit.
circuit = make_quantum_teleportation_circuit(gate)
print("Teleportation circuit:\n")
print(circuit)
"""Display the Bloch vector of the message qubit."""
message = cirq.Circuit(gate.on(cirq.NamedQubit("Message"))).final_state_vector()
message_bloch_vector = cirq.bloch_vector_from_state_vector(message, index=0)
print("Bloch vector of message qubit:")
print(np.round(message_bloch_vector, 3))
"""Simulate the teleportation circuit and get the final state of Bob's qubit."""
# Get a simulator.
sim = cirq.Simulator()
# Simulate the teleportation circuit.
result = sim.simulate(circuit)
# Get the Bloch vector of Bob's qubit.
bobs_bloch_vector = cirq.bloch_vector_from_state_vector(result.final_state_vector, index=1)
print("Bloch vector of Bob's qubit:")
print(np.round(bobs_bloch_vector, 3))
# Verify they are the same state!
np.testing.assert_allclose(bobs_bloch_vector, message_bloch_vector, atol=1e-7)
def make_qft(qubits):
"""Generator for the QFT on a list of qubits.
For four qubits, the answer is:
┌───────┐ ┌────────────┐ ┌───────┐
0: ───H───@────────@───────────@───────────────────────────────────────
│ │ │
1: ───────@^0.5────┼─────H─────┼──────@─────────@──────────────────────
│ │ │ │
2: ────────────────@^0.25──────┼──────@^0.5─────┼─────H────@───────────
│ │ │
3: ────────────────────────────@^(1/8)──────────@^0.25─────@^0.5───H───
└───────┘ └────────────┘ └───────┘
"""
# Your code here!
def make_qft(qubits):
"""Generator for the QFT on a list of qubits."""
qreg = list(qubits)
while len(qreg) > 0:
q_head = qreg.pop(0)
yield cirq.H(q_head)
for i, qubit in enumerate(qreg):
yield (cirq.CZ ** (1 / 2 ** (i + 1)))(qubit, q_head)
"""Visually check the QFT circuit."""
qubits = cirq.LineQubit.range(4)
qft = cirq.Circuit(make_qft(qubits))
print(qft)
"""Use the built-in QFT in Cirq."""
qft_operation = cirq.qft(*qubits, without_reverse=True)
qft_cirq = cirq.Circuit(qft_operation)
print(qft_cirq)
"""Check equality of the 'manual' and 'built-in' QFTs."""
np.testing.assert_allclose(cirq.unitary(qft), cirq.unitary(qft_cirq))
def make_qft_inverse(qubits):
"""Generator for the inverse QFT on a list of qubits.
For four qubits, the answer is:
┌────────┐ ┌──────────────┐ ┌────────┐
0: ───H───@─────────@────────────@───────────────────────────────────────────×───
│ │ │ │
1: ───────@^-0.5────┼──────H─────┼───────@──────────@────────────────────×───┼───
│ │ │ │ │ │
2: ─────────────────@^-0.25──────┼───────@^-0.5─────┼──────H────@────────×───┼───
│ │ │ │
3: ──────────────────────────────@^(-1/8)───────────@^-0.25─────@^-0.5───H───×───
└────────┘ └──────────────┘ └────────┘
"""
# Your code here!
def make_qft_inverse(qubits):
"""Generator for the inverse QFT on a list of qubits."""
qreg = list(qubits)[::-1]
while len(qreg) > 0:
q_head = qreg.pop(0)
yield cirq.H(q_head)
for i, qubit in enumerate(qreg):
yield (cirq.CZ ** (-1 / 2 ** (i + 1)))(qubit, q_head)
"""Visually check the inverse QFT circuit."""
qubits = cirq.LineQubit.range(4)
iqft = cirq.Circuit(make_qft_inverse(qubits))
print(iqft)
"""Use the built-in inverse QFT in Cirq."""
iqft_operation = cirq.qft(*qubits, inverse=True, without_reverse=True)
iqft_cirq = cirq.Circuit(iqft_operation)
print(iqft_cirq)
"""Check equality of the 'manual' and 'built-in' inverse QFTs."""
np.testing.assert_allclose(cirq.unitary(iqft), cirq.unitary(iqft_cirq))
"""Set up the unitary and number of bits to use in phase estimation."""
# Value of θ which appears in the definition of the unitary U above.
# Try different values.
theta = 0.234
# Define the unitary U.
U = cirq.Z ** (2 * theta)
# Accuracy of the estimate for theta. Try different values.
n_bits = 3
"""Build the first part of the circuit for phase estimation."""
# Get qubits for the phase estimation circuit.
qubits = cirq.LineQubit.range(n_bits)
u_bit = cirq.NamedQubit('u')
# Build the first part of the phase estimation circuit.
phase_estimator = cirq.Circuit(cirq.H.on_each(*qubits))
for i, bit in enumerate(qubits):
phase_estimator.append(cirq.ControlledGate(U).on(bit, u_bit) ** (2 ** (n_bits - i - 1)))
print(phase_estimator)
"""Build the last part of the circuit (inverse QFT) for phase estimation."""
# Do the inverse QFT.
phase_estimator.append(make_qft_inverse(qubits[::-1]))
# Add measurements to the end of the circuit
phase_estimator.append(cirq.measure(*qubits, key='m'))
print(phase_estimator)
"""Set the input state of the eigenvalue register."""
# Add gate to change initial state to |1>.
phase_estimator.insert(0, cirq.X(u_bit))
print(phase_estimator)
"""Simulate the circuit and convert from measured bit values to estimated θ values."""
# Simulate the circuit.
sim = cirq.Simulator()
result = sim.run(phase_estimator, repetitions=10)
# Convert from output bitstrings to estimate θ values.
theta_estimates = np.sum(2 ** np.arange(n_bits) * result.measurements['m'], axis=1) / 2**n_bits
print(theta_estimates)
def phase_estimation(theta, n_bits, n_reps=10, prepare_eigenstate_gate=cirq.X):
"""Runs the phase estimate algorithm for unitary U=Z^{2θ} with n_bits qubits."""
# Define qubit registers.
qubits = cirq.LineQubit.range(n_bits)
u_bit = cirq.NamedQubit('u')
# Define the unitary U.
U = cirq.Z ** (2 * theta)
# Your code here!
# ...
# Gate to choose initial state for the u_bit. Placing X here chooses the |1> state.
phase_estimator.insert(0, prepare_eigenstate_gate.on(u_bit))
# You code here!
# theta_estimates = ...
return theta_estimates
def phase_estimation(theta, n_bits, n_reps=10, prepare_eigenstate_gate=cirq.X):
# Define qubit registers.
qubits = cirq.LineQubit.range(n_bits)
u_bit = cirq.NamedQubit('u')
# Define the unitary U.
U = cirq.Z ** (2 * theta)
# Start with Hadamards on every qubit.
phase_estimator = cirq.Circuit(cirq.H.on_each(*qubits))
# Do the controlled powers of the unitary U.
for i, bit in enumerate(qubits):
phase_estimator.append(cirq.ControlledGate(U).on(bit, u_bit) ** (2 ** (n_bits - 1 - i)))
# Do the inverse QFT.
phase_estimator.append(make_qft_inverse(qubits[::-1]))
# Add measurements.
phase_estimator.append(cirq.measure(*qubits, key='m'))
# Gate to choose initial state for the u_bit. Placing X here chooses the |1> state.
phase_estimator.insert(0, prepare_eigenstate_gate.on(u_bit))
# Code to simulate measurements
sim = cirq.Simulator()
result = sim.run(phase_estimator, repetitions=n_reps)
# Convert measurements into estimates of theta
theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits
return theta_estimates
"""Analyze convergence vs n_bits."""
# Set the value of theta. Try different values.
theta = 0.123456
max_nvals = 16
nvals = np.arange(1, max_nvals, step=1)
# Get the estimates at each value of n.
estimates = []
for n in nvals:
estimate = phase_estimation(theta=theta, n_bits=n, n_reps=1)[0]
estimates.append(estimate)
"""Plot the results."""
plt.style.use("seaborn-whitegrid")
plt.plot(nvals, estimates, "--o", label="Phase estimation")
plt.axhline(theta, label="True value", color="black")
plt.legend()
plt.xlabel("Number of bits")
plt.ylabel(r"$\theta$");
"""Run phase estimation without starting in an eigenstate."""
# Value of theta.
theta = 0.123456
# Number of qubits.
n = 4
# Run phase estimation starting in the state H|0⟩ = |+⟩.
res = phase_estimation(theta=theta, n_bits=n, n_reps=10, prepare_eigenstate_gate=cirq.H)
print(res)
"""Get qubits to use in the circuit for Grover's algorithm."""
# Number of qubits n.
nqubits = 2
# Get qubit registers.
qubits = cirq.LineQubit.range(nqubits)
ancilla = cirq.NamedQubit("Ancilla")
def make_oracle(qubits, ancilla, xprime):
"""Implements the function {f(x) = 1 if x == x', f(x) = 0 if x != x'}."""
# For x' = (1, 1), the oracle is just a Toffoli gate.
# For a general x', we negate the zero bits and implement a Toffoli.
# Negate zero bits, if necessary.
yield (cirq.X(q) for (q, bit) in zip(qubits, xprime) if not bit)
# Do the Toffoli.
yield (cirq.TOFFOLI(qubits[0], qubits[1], ancilla))
# Negate zero bits, if necessary.
yield (cirq.X(q) for (q, bit) in zip(qubits, xprime) if not bit)
def grover_iteration(qubits, ancilla, oracle):
"""Performs one round of the Grover iteration."""
circuit = cirq.Circuit()
# Create an equal superposition over input qubits.
circuit.append(cirq.H.on_each(*qubits))
# Put the output qubit in the |-⟩ state.
circuit.append([cirq.X(ancilla), cirq.H(ancilla)])
# Query the oracle.
circuit.append(oracle)
# Construct Grover operator.
circuit.append(cirq.H.on_each(*qubits))
circuit.append(cirq.X.on_each(*qubits))
circuit.append(cirq.H.on(qubits[1]))
circuit.append(cirq.CNOT(qubits[0], qubits[1]))
circuit.append(cirq.H.on(qubits[1]))
circuit.append(cirq.X.on_each(*qubits))
circuit.append(cirq.H.on_each(*qubits))
# Measure the input register.
circuit.append(cirq.measure(*qubits, key="result"))
return circuit
"""Select a 'marked' bitstring x' at random."""
xprime = [random.randint(0, 1) for _ in range(nqubits)]
print(f"Marked bitstring: {xprime}")
"""Create the circuit for Grover's algorithm."""
# Make oracle (black box)
oracle = make_oracle(qubits, ancilla, xprime)
# Embed the oracle into a quantum circuit implementing Grover's algorithm.
circuit = grover_iteration(qubits, ancilla, oracle)
print("Circuit for Grover's algorithm:")
print(circuit)
"""Simulate the circuit for Grover's algorithm and check the output."""
# Helper function.
def bitstring(bits):
return "".join(str(int(b)) for b in bits)
# Sample from the circuit a couple times.
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=10)
# Look at the sampled bitstrings.
frequencies = result.histogram(key="result", fold_func=bitstring)
print('Sampled results:\n{}'.format(frequencies))
# Check if we actually found the secret value.
most_common_bitstring = frequencies.most_common(1)[0][0]
print("\nMost common bitstring: {}".format(most_common_bitstring))
print("Found a match? {}".format(most_common_bitstring == bitstring(xprime)))
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Stochastic Swap pass"""
import unittest
import numpy.random
from ddt import ddt, data
from qiskit.transpiler.passes import StochasticSwap
from qiskit.transpiler import CouplingMap, PassManager, Layout
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.test._canonical import canonicalize_control_flow
from qiskit.transpiler.passes.utils import CheckMap
from qiskit.circuit.random import random_circuit
from qiskit.providers.fake_provider import FakeMumbai, FakeMumbaiV2
from qiskit.compiler.transpiler import transpile
from qiskit.circuit import ControlFlowOp, Clbit, CASE_DEFAULT
from qiskit.circuit.classical import expr
@ddt
class TestStochasticSwap(QiskitTestCase):
"""
Tests the StochasticSwap pass.
All of the tests use a fixed seed since the results
may depend on it.
"""
def test_trivial_case(self):
"""
q0:--(+)-[H]-(+)-
| |
q1:---.-------|--
|
q2:-----------.--
Coupling map: [1]--[0]--[2]
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_trivial_in_same_layer(self):
"""
q0:--(+)--
|
q1:---.---
q2:--(+)--
|
q3:---.---
Coupling map: [0]--[1]--[2]--[3]
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_permute_wires_1(self):
"""
q0:--------
q1:---.----
|
q2:--(+)---
Coupling map: [1]--[0]--[2]
q0:--x-(+)-
| |
q1:--|--.--
|
q2:--x-----
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 11)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[2])
expected.cx(qr[1], qr[0])
self.assertEqual(circuit_to_dag(expected), after)
def test_permute_wires_2(self):
"""
qr0:---.---[H]--
|
qr1:---|--------
|
qr2:--(+)-------
Coupling map: [0]--[1]--[2]
qr0:----.---[H]-
|
qr1:-x-(+)------
|
qr2:-x----------
"""
coupling = CouplingMap([[1, 0], [1, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 11)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[2])
expected.cx(qr[0], qr[1])
expected.h(qr[0])
self.assertEqual(expected, dag_to_circuit(after))
def test_permute_wires_3(self):
"""
qr0:--(+)---.--
| |
qr1:---|----|--
| |
qr2:---|----|--
| |
qr3:---.---(+)-
Coupling map: [0]--[1]--[2]--[3]
qr0:-x------------
|
qr1:-x--(+)---.---
| |
qr2:-x---.---(+)--
|
qr3:-x------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[2], qr[3])
expected.cx(qr[1], qr[2])
expected.cx(qr[2], qr[1])
self.assertEqual(circuit_to_dag(expected), after)
def test_permute_wires_4(self):
"""No qubit label permutation occurs if the first
layer has only single-qubit gates. This is suboptimal
but seems to be the current behavior.
qr0:------(+)--
|
qr1:-------|---
|
qr2:-------|---
|
qr3:--[H]--.---
Coupling map: [0]--[1]--[2]--[3]
qr0:------X---------
|
qr1:------X-(+)-----
|
qr2:------X--.------
|
qr3:-[H]--X---------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.h(qr[3])
expected.swap(qr[2], qr[3])
expected.swap(qr[0], qr[1])
expected.cx(qr[2], qr[1])
self.assertEqual(circuit_to_dag(expected), after)
def test_permute_wires_5(self):
"""This is the same case as permute_wires_4
except the single qubit gate is after the two-qubit
gate, so the layout is adjusted.
qr0:--(+)------
|
qr1:---|-------
|
qr2:---|-------
|
qr3:---.--[H]--
Coupling map: [0]--[1]--[2]--[3]
qr0:-x-----------
|
qr1:-x--(+)------
|
qr2:-x---.--[H]--
|
qr3:-x-----------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[2], qr[3])
expected.cx(qr[2], qr[1])
expected.h(qr[2])
self.assertEqual(circuit_to_dag(expected), after)
def test_all_single_qubit(self):
"""Test all trivial layers."""
coupling = CouplingMap([[0, 1], [1, 2], [1, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circ = QuantumCircuit(qr, cr)
circ.h(qr)
circ.z(qr)
circ.s(qr)
circ.t(qr)
circ.tdg(qr)
circ.measure(qr[0], cr[0]) # intentional duplicate
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
dag = circuit_to_dag(circ)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_overoptimization_case(self):
"""Check mapper overoptimization.
The mapper should not change the semantics of the input.
An overoptimization introduced issue #81:
https://github.com/Qiskit/qiskit-terra/issues/81
"""
coupling = CouplingMap([[0, 2], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.y(qr[1])
circuit.z(qr[2])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.s(qr[1])
circuit.t(qr[2])
circuit.h(qr[3])
circuit.cx(qr[1], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
circuit.measure(qr[2], cr[2])
circuit.measure(qr[3], cr[3])
dag = circuit_to_dag(circuit)
# ┌───┐ ┌─┐
# q_0: | 0 >┤ X ├────────────■───────────────────────────┤M├─────────
# └───┘┌───┐ ┌─┴─┐ ┌───┐ └╥┘┌─┐
# q_1: | 0 >─────┤ Y ├─────┤ X ├─────┤ S ├────────────■───╫─┤M├──────
# └───┘┌───┐└───┘ └───┘┌───┐ ┌─┴─┐ ║ └╥┘┌─┐
# q_2: | 0 >──────────┤ Z ├───────■───────┤ T ├─────┤ X ├─╫──╫─┤M├───
# └───┘ ┌─┴─┐ └───┘┌───┐└───┘ ║ ║ └╥┘┌─┐
# q_3: | 0 >────────────────────┤ X ├──────────┤ H ├──────╫──╫──╫─┤M├
# └───┘ └───┘ ║ ║ ║ └╥┘
# c_0: 0 ══════════════════════════════════════════════╩══╬══╬══╬═
# ║ ║ ║
# c_1: 0 ═════════════════════════════════════════════════╩══╬══╬═
# ║ ║
# c_2: 0 ════════════════════════════════════════════════════╩══╬═
# ║
# c_3: 0 ═══════════════════════════════════════════════════════╩═
#
expected = QuantumCircuit(qr, cr)
expected.z(qr[2])
expected.y(qr[1])
expected.x(qr[0])
expected.swap(qr[0], qr[2])
expected.cx(qr[2], qr[1])
expected.swap(qr[0], qr[2])
expected.cx(qr[2], qr[3])
expected.s(qr[1])
expected.t(qr[2])
expected.h(qr[3])
expected.measure(qr[0], cr[0])
expected.cx(qr[1], qr[2])
expected.measure(qr[3], cr[3])
expected.measure(qr[1], cr[1])
expected.measure(qr[2], cr[2])
expected_dag = circuit_to_dag(expected)
# ┌───┐ ┌─┐
# q_0: ┤ X ├─X───────X──────┤M├────────────────
# ├───┤ │ ┌───┐ │ ┌───┐└╥┘ ┌─┐
# q_1: ┤ Y ├─┼─┤ X ├─┼─┤ S ├─╫────────■──┤M├───
# ├───┤ │ └─┬─┘ │ └───┘ ║ ┌───┐┌─┴─┐└╥┘┌─┐
# q_2: ┤ Z ├─X───■───X───■───╫─┤ T ├┤ X ├─╫─┤M├
# └───┘ ┌─┴─┐ ║ ├───┤└┬─┬┘ ║ └╥┘
# q_3: ────────────────┤ X ├─╫─┤ H ├─┤M├──╫──╫─
# └───┘ ║ └───┘ └╥┘ ║ ║
# c: 4/══════════════════════╩════════╩═══╩══╩═
# 0 3 1 2
#
# Layout --
# {qr[0]: 0,
# qr[1]: 1,
# qr[2]: 2,
# qr[3]: 3}
pass_ = StochasticSwap(coupling, 20, 19)
after = pass_.run(dag)
self.assertEqual(expected_dag, after)
def test_already_mapped(self):
"""Circuit not remapped if matches topology.
See: https://github.com/Qiskit/qiskit-terra/issues/342
"""
coupling = CouplingMap(
[
[1, 0],
[1, 2],
[2, 3],
[3, 4],
[3, 14],
[5, 4],
[6, 5],
[6, 7],
[6, 11],
[7, 10],
[8, 7],
[9, 8],
[9, 10],
[11, 10],
[12, 5],
[12, 11],
[12, 13],
[13, 4],
[13, 14],
[15, 0],
[15, 0],
[15, 2],
[15, 14],
]
)
qr = QuantumRegister(16, "q")
cr = ClassicalRegister(16, "c")
circ = QuantumCircuit(qr, cr)
circ.cx(qr[3], qr[14])
circ.cx(qr[5], qr[4])
circ.h(qr[9])
circ.cx(qr[9], qr[8])
circ.x(qr[11])
circ.cx(qr[3], qr[4])
circ.cx(qr[12], qr[11])
circ.cx(qr[13], qr[4])
for j in range(16):
circ.measure(qr[j], cr[j])
dag = circuit_to_dag(circ)
pass_ = StochasticSwap(coupling, 20, 13)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(circ), after)
def test_congestion(self):
"""Test code path that falls back to serial layers."""
coupling = CouplingMap([[0, 1], [1, 2], [1, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circ = QuantumCircuit(qr, cr)
circ.cx(qr[1], qr[2])
circ.cx(qr[0], qr[3])
circ.measure(qr[0], cr[0])
circ.h(qr)
circ.cx(qr[0], qr[1])
circ.cx(qr[2], qr[3])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
dag = circuit_to_dag(circ)
# Input:
# ┌─┐┌───┐ ┌─┐
# q_0: |0>─────────────────■──────────────────┤M├┤ H ├──■─────┤M├
# ┌───┐ │ └╥┘└───┘┌─┴─┐┌─┐└╥┘
# q_1: |0>──■───────┤ H ├──┼───────────────────╫──────┤ X ├┤M├─╫─
# ┌─┴─┐┌───┐└───┘ │ ┌─┐ ║ └───┘└╥┘ ║
# q_2: |0>┤ X ├┤ H ├───────┼─────────■─────┤M├─╫────────────╫──╫─
# └───┘└───┘ ┌─┴─┐┌───┐┌─┴─┐┌─┐└╥┘ ║ ║ ║
# q_3: |0>───────────────┤ X ├┤ H ├┤ X ├┤M├─╫──╫────────────╫──╫─
# └───┘└───┘└───┘└╥┘ ║ ║ ║ ║
# c_0: 0 ═══════════════════════════════╬══╬══╩════════════╬══╩═
# ║ ║ ║
# c_1: 0 ═══════════════════════════════╬══╬═══════════════╩════
# ║ ║
# c_2: 0 ═══════════════════════════════╬══╩════════════════════
# ║
# c_3: 0 ═══════════════════════════════╩═══════════════════════
#
# Expected output (with seed 999):
# ┌───┐ ┌─┐
# q_0: ───────X──┤ H ├─────────────────X──────┤M├──────
# │ └───┘ ┌─┐ ┌───┐ │ ┌───┐└╥┘ ┌─┐
# q_1: ──■────X────■───────┤M├─X─┤ X ├─X─┤ X ├─╫────┤M├
# ┌─┴─┐┌───┐ │ └╥┘ │ └─┬─┘┌─┐└─┬─┘ ║ └╥┘
# q_2: ┤ X ├┤ H ├──┼────────╫──┼───■──┤M├──┼───╫─────╫─
# └───┘└───┘┌─┴─┐┌───┐ ║ │ ┌───┐└╥┘ │ ║ ┌─┐ ║
# q_3: ──────────┤ X ├┤ H ├─╫──X─┤ H ├─╫───■───╫─┤M├─╫─
# └───┘└───┘ ║ └───┘ ║ ║ └╥┘ ║
# c: 4/═════════════════════╩══════════╩═══════╩══╩══╩═
# 0 2 3 0 1
#
# Target coupling graph:
# 2
# |
# 0 - 1 - 3
expected = QuantumCircuit(qr, cr)
expected.cx(qr[1], qr[2])
expected.h(qr[2])
expected.swap(qr[0], qr[1])
expected.h(qr[0])
expected.cx(qr[1], qr[3])
expected.h(qr[3])
expected.measure(qr[1], cr[0])
expected.swap(qr[1], qr[3])
expected.cx(qr[2], qr[1])
expected.h(qr[3])
expected.swap(qr[0], qr[1])
expected.measure(qr[2], cr[2])
expected.cx(qr[3], qr[1])
expected.measure(qr[0], cr[3])
expected.measure(qr[3], cr[0])
expected.measure(qr[1], cr[1])
expected_dag = circuit_to_dag(expected)
pass_ = StochasticSwap(coupling, 20, 999)
after = pass_.run(dag)
self.assertEqual(expected_dag, after)
def test_only_output_cx_and_swaps_in_coupling_map(self):
"""Test that output DAG contains only 2q gates from the the coupling map."""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.measure(qr, cr)
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling, 20, 5)
after = pass_.run(dag)
valid_couplings = [{qr[a], qr[b]} for (a, b) in coupling.get_edges()]
for _2q_gate in after.two_qubit_ops():
self.assertIn(set(_2q_gate.qargs), valid_couplings)
def test_len_cm_vs_dag(self):
"""Test error if the coupling map is smaller than the dag."""
coupling = CouplingMap([[0, 1], [1, 2]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[3])
circuit.measure(qr, cr)
dag = circuit_to_dag(circuit)
pass_ = StochasticSwap(coupling)
with self.assertRaises(TranspilerError):
_ = pass_.run(dag)
def test_single_gates_omitted(self):
"""Test if single qubit gates are omitted."""
coupling_map = [[0, 1], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [3, 4], [4, 3]]
# q_0: ──■──────────────────
# │
# q_1: ──┼─────────■────────
# │ ┌─┴─┐
# q_2: ──┼───────┤ X ├──────
# │ ┌────┴───┴─────┐
# q_3: ──┼──┤ U(1,1.5,0.7) ├
# ┌─┴─┐└──────────────┘
# q_4: ┤ X ├────────────────
# └───┘
qr = QuantumRegister(5, "q")
cr = ClassicalRegister(5, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[4])
circuit.cx(qr[1], qr[2])
circuit.u(1, 1.5, 0.7, qr[3])
# q_0: ─────────────────X──────
# │
# q_1: ───────■─────────X───■──
# ┌─┴─┐ │
# q_2: ─────┤ X ├───────────┼──
# ┌────┴───┴─────┐ ┌─┴─┐
# q_3: ┤ U(1,1.5,0.7) ├─X─┤ X ├
# └──────────────┘ │ └───┘
# q_4: ─────────────────X──────
expected = QuantumCircuit(qr, cr)
expected.cx(qr[1], qr[2])
expected.u(1, 1.5, 0.7, qr[3])
expected.swap(qr[0], qr[1])
expected.swap(qr[3], qr[4])
expected.cx(qr[1], qr[3])
expected_dag = circuit_to_dag(expected)
stochastic = StochasticSwap(CouplingMap(coupling_map), seed=0)
after = PassManager(stochastic).run(circuit)
after = circuit_to_dag(after)
self.assertEqual(expected_dag, after)
@ddt
class TestStochasticSwapControlFlow(QiskitTestCase):
"""Tests for control flow in stochastic swap."""
def test_pre_if_else_route(self):
"""test swap with if else controlflow construct"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.measure(2, 2)
true_body = QuantumCircuit(qreg, creg[[2]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[2]])
false_body.x(4)
qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[2]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=82).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(2, 2)
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[2]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[2]])
efalse_body.x(1)
new_order = [1, 0, 2, 3, 4]
expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[2]])
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_if_else_route_post_x(self):
"""test swap with if else controlflow construct; pre-cx and post x"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.measure(2, 2)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[0]])
qc.x(1)
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=431).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(1, 2)
new_order = [0, 2, 1, 3, 4]
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
efalse_body.x(1)
expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]])
expected.x(2)
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_post_if_else_route(self):
"""test swap with if else controlflow construct; post cx"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(3)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.barrier(qreg)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.cx(0, 2)
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=6508).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]])
efalse_body.x(1)
expected.barrier(qreg)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]])
expected.barrier(qreg)
expected.swap(0, 1)
expected.cx(1, 2)
expected.barrier(qreg)
expected.measure(qreg, creg[[1, 0, 2, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_if_else2(self):
"""test swap with if else controlflow construct; cx in if statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(0)
false_body = QuantumCircuit(qreg, creg[[0]])
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=38).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(1, 0)
etrue_body = QuantumCircuit(qreg[[1]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[1]], creg[[0]])
new_order = [1, 0, 2, 3, 4]
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1]], creg[[0]])
expected.barrier(qreg)
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_intra_if_else_route(self):
"""test swap with if else controlflow construct"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=8).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.swap(0, 1)
etrue_body.cx(1, 2)
etrue_body.swap(1, 2)
etrue_body.swap(3, 4)
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.swap(0, 1)
efalse_body.swap(1, 2)
efalse_body.swap(3, 4)
efalse_body.cx(2, 3)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
new_order = [1, 2, 0, 4, 3]
expected.measure(qreg, creg[new_order])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_intra_if_else(self):
"""test swap with if else controlflow construct; cx in if statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)])
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=2, trials=20).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
etrue_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]])
efalse_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]])
expected.h(0)
expected.x(1)
expected.swap(0, 1)
expected.cx(1, 2)
expected.measure(1, 0)
etrue_body.cx(0, 1)
etrue_body.swap(2, 3)
etrue_body.swap(0, 1)
efalse_body.swap(0, 1)
efalse_body.swap(2, 3)
efalse_body.cx(1, 2)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 2, 3, 4]], creg[[0]])
expected.measure(qreg, creg[[1, 2, 0, 4, 3]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_pre_intra_post_if_else(self):
"""test swap with if else controlflow construct; cx before, in, and after if
statement"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.cx(0, 4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.h(3)
qc.cx(3, 0)
qc.barrier()
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=1).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.cx(0, 1)
etrue_body.swap(0, 1)
etrue_body.swap(4, 3)
etrue_body.swap(2, 3)
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.swap(0, 1)
efalse_body.swap(3, 4)
efalse_body.swap(2, 3)
efalse_body.cx(1, 2)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[0, 1, 2, 3, 4]], creg[[0]])
expected.swap(1, 2)
expected.h(4)
expected.swap(3, 4)
expected.cx(3, 2)
expected.barrier()
expected.measure(qreg, creg[[2, 4, 0, 3, 1]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_if_expr(self):
"""Test simple if conditional with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
body = QuantumCircuit(4)
body.cx(0, 1)
body.cx(0, 2)
body.cx(0, 3)
qc = QuantumCircuit(4, 2)
qc.if_test(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_if_else_expr(self):
"""Test simple if/else conditional with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
true = QuantumCircuit(4)
true.cx(0, 1)
true.cx(0, 2)
true.cx(0, 3)
false = QuantumCircuit(4)
false.cx(3, 0)
false.cx(3, 1)
false.cx(3, 2)
qc = QuantumCircuit(4, 2)
qc.if_else(expr.logic_and(qc.clbits[0], qc.clbits[1]), true, false, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_no_layout_change(self):
"""test controlflow with no layout change needed"""
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.cx(0, 2)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(2)
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.x(4)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.barrier(qreg)
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=23).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.swap(1, 2)
expected.cx(0, 1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg[[1, 4]], creg[[0]])
etrue_body.x(0)
efalse_body = QuantumCircuit(qreg[[1, 4]], creg[[0]])
efalse_body.x(1)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 4]], creg[[0]])
expected.barrier(qreg)
expected.measure(qreg, creg[[0, 2, 1, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
@data(1, 2, 3)
def test_for_loop(self, nloops):
"""test stochastic swap with for_loop"""
# if the loop has only one iteration it isn't necessary for the pass
# to swap back to the starting layout. This test would check that
# optimization.
num_qubits = 3
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
for_body = QuantumCircuit(qreg)
for_body.cx(0, 2)
loop_parameter = None
qc.for_loop(range(nloops), loop_parameter, for_body, qreg, [])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=687).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
efor_body = QuantumCircuit(qreg)
efor_body.swap(0, 1)
efor_body.cx(1, 2)
efor_body.swap(0, 1)
loop_parameter = None
expected.for_loop(range(nloops), loop_parameter, efor_body, qreg, [])
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_while_loop(self):
"""test while loop"""
num_qubits = 4
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(len(qreg))
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
while_body = QuantumCircuit(qreg, creg)
while_body.reset(qreg[2:])
while_body.h(qreg[2:])
while_body.cx(0, 3)
while_body.measure(qreg[3], creg[3])
qc.while_loop((creg, 0), while_body, qc.qubits, qc.clbits)
qc.barrier()
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
ewhile_body = QuantumCircuit(qreg, creg[:])
ewhile_body.reset(qreg[2:])
ewhile_body.h(qreg[2:])
ewhile_body.swap(0, 1)
ewhile_body.swap(2, 3)
ewhile_body.cx(1, 2)
ewhile_body.measure(qreg[2], creg[3])
ewhile_body.swap(1, 0)
ewhile_body.swap(3, 2)
expected.while_loop((creg, 0), ewhile_body, expected.qubits, expected.clbits)
expected.barrier()
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_while_loop_expr(self):
"""Test simple while loop with an `Expr` condition."""
coupling = CouplingMap.from_line(4)
body = QuantumCircuit(4)
body.cx(0, 1)
body.cx(0, 2)
body.cx(0, 3)
qc = QuantumCircuit(4, 2)
qc.while_loop(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], [])
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=58).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
def test_switch_single_case(self):
"""Test routing of 'switch' with just a single case."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
expected.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg[:])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_nonexhaustive(self):
"""Test routing of 'switch' with several but nonexhaustive cases."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.cx(3, 1)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.cx(4, 2)
qc.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.swap(1, 2)
case1.cx(3, 2)
case1.swap(1, 2)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.swap(3, 4)
case2.cx(3, 2)
case2.swap(3, 4)
expected.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@data((0, 1, 2, 3), (CASE_DEFAULT,))
def test_switch_exhaustive(self, labels):
"""Test routing of 'switch' with exhaustive cases; we should not require restoring the
layout afterwards."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(2, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
expected.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_nonexhaustive_expr(self):
"""Test routing of 'switch' with an `Expr` target and several but nonexhaustive cases."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(3, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.cx(3, 1)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.cx(4, 2)
qc.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg, creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
case0.swap(0, 1)
case1 = QuantumCircuit(qreg, creg[:])
case1.cx(1, 2)
case1.cx(2, 3)
case1.swap(1, 2)
case1.cx(3, 2)
case1.swap(1, 2)
case2 = QuantumCircuit(qreg, creg[:])
case2.cx(2, 3)
case2.cx(3, 4)
case2.swap(3, 4)
case2.cx(3, 2)
case2.swap(3, 4)
expected.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@data((0, 1, 2, 3), (CASE_DEFAULT,))
def test_switch_exhaustive_expr(self, labels):
"""Test routing of 'switch' with exhaustive cases on an `Expr` target; we should not require
restoring the layout afterwards."""
qreg = QuantumRegister(5, "q")
creg = ClassicalRegister(2, "c")
qc = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.cx(2, 0)
qc.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg)
coupling = CouplingMap.from_line(len(qreg))
pass_ = StochasticSwap(coupling, seed=58)
test = pass_(qc)
check = CheckMap(coupling)
check(test)
self.assertTrue(check.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:])
case0.cx(0, 1)
case0.cx(1, 2)
case0.swap(0, 1)
case0.cx(2, 1)
expected.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_nested_inner_cnot(self):
"""test swap in nested if else controlflow construct; swap in inner"""
seed = 1
num_qubits = 3
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
check_map_pass = CheckMap(coupling)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.x(0)
for_body = QuantumCircuit(qreg)
for_body.delay(10, 0)
for_body.barrier(qreg)
for_body.cx(0, 2)
loop_parameter = None
true_body.for_loop(range(3), loop_parameter, for_body, qreg, [])
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.y(0)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=seed).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.x(0)
efor_body = QuantumCircuit(qreg)
efor_body.delay(10, 0)
efor_body.barrier(qreg)
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(1, 2)
etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg, [])
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.y(0)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg)
self.assertEqual(dag_to_circuit(cdag), expected)
def test_nested_outer_cnot(self):
"""test swap with nested if else controlflow construct; swap in outer"""
seed = 200
num_qubits = 5
qreg = QuantumRegister(num_qubits, "q")
creg = ClassicalRegister(num_qubits)
coupling = CouplingMap.from_line(num_qubits)
qc = QuantumCircuit(qreg, creg)
qc.h(0)
qc.x(1)
qc.measure(0, 0)
true_body = QuantumCircuit(qreg, creg[[0]])
true_body.cx(0, 2)
true_body.x(0)
for_body = QuantumCircuit(qreg)
for_body.delay(10, 0)
for_body.barrier(qreg)
for_body.cx(1, 3)
loop_parameter = None
true_body.for_loop(range(3), loop_parameter, for_body, qreg, [])
false_body = QuantumCircuit(qreg, creg[[0]])
false_body.y(0)
qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]])
qc.measure(qreg, creg)
dag = circuit_to_dag(qc)
cdag = StochasticSwap(coupling, seed=seed).run(dag)
check_map_pass = CheckMap(coupling)
check_map_pass.run(cdag)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qreg, creg)
expected.h(0)
expected.x(1)
expected.measure(0, 0)
etrue_body = QuantumCircuit(qreg, creg[[0]])
etrue_body.swap(1, 2)
etrue_body.cx(0, 1)
etrue_body.x(0)
efor_body = QuantumCircuit(qreg)
efor_body.delay(10, 0)
efor_body.barrier(qreg)
efor_body.cx(2, 3)
etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg[[0, 1, 2, 3, 4]], [])
efalse_body = QuantumCircuit(qreg, creg[[0]])
efalse_body.y(0)
efalse_body.swap(1, 2)
expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]])
expected.measure(qreg, creg[[0, 2, 1, 3, 4]])
self.assertEqual(dag_to_circuit(cdag), expected)
def test_disjoint_looping(self):
"""Test looping controlflow on different qubit register"""
num_qubits = 4
cm = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(num_qubits, "q")
qc = QuantumCircuit(qr)
loop_body = QuantumCircuit(2)
loop_body.cx(0, 1)
qc.for_loop((0,), None, loop_body, [0, 2], [])
cqc = StochasticSwap(cm, seed=0)(qc)
expected = QuantumCircuit(qr)
efor_body = QuantumCircuit(qr[[0, 1, 2]])
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(1, 2)
expected.for_loop((0,), None, efor_body, [0, 1, 2], [])
self.assertEqual(cqc, expected)
def test_disjoint_multiblock(self):
"""Test looping controlflow on different qubit register"""
num_qubits = 4
cm = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(num_qubits, "q")
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(3, 1)
true_body.cx(0, 1)
false_body = QuantumCircuit(3, 1)
false_body.cx(0, 2)
qc.if_else((cr[0], 1), true_body, false_body, [0, 1, 2], [0])
cqc = StochasticSwap(cm, seed=353)(qc)
expected = QuantumCircuit(qr, cr)
etrue_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]])
etrue_body.cx(0, 1)
etrue_body.swap(0, 1)
efalse_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]])
efalse_body.swap(0, 1)
efalse_body.cx(1, 2)
expected.if_else((cr[0], 1), etrue_body, efalse_body, [0, 1, 2], cr[[0]])
self.assertEqual(cqc, expected)
def test_multiple_ops_per_layer(self):
"""Test circuits with multiple operations per layer"""
num_qubits = 6
coupling = CouplingMap.from_line(num_qubits)
check_map_pass = CheckMap(coupling)
qr = QuantumRegister(num_qubits, "q")
qc = QuantumCircuit(qr)
# This cx and the for_loop are in the same layer.
qc.cx(0, 2)
with qc.for_loop((0,)):
qc.cx(3, 5)
cqc = StochasticSwap(coupling, seed=0)(qc)
check_map_pass(cqc)
self.assertTrue(check_map_pass.property_set["is_swap_mapped"])
expected = QuantumCircuit(qr)
expected.swap(0, 1)
expected.cx(1, 2)
efor_body = QuantumCircuit(qr[[3, 4, 5]])
efor_body.swap(1, 2)
efor_body.cx(0, 1)
efor_body.swap(2, 1)
expected.for_loop((0,), None, efor_body, [3, 4, 5], [])
self.assertEqual(cqc, expected)
def test_if_no_else_restores_layout(self):
"""Test that an if block with no else branch restores the initial layout. If there is an
else branch, we don't need to guarantee this."""
qc = QuantumCircuit(8, 1)
with qc.if_test((qc.clbits[0], False)):
# Just some arbitrary gates with no perfect layout.
qc.cx(3, 5)
qc.cx(4, 6)
qc.cx(1, 4)
qc.cx(7, 4)
qc.cx(0, 5)
qc.cx(7, 3)
qc.cx(1, 3)
qc.cx(5, 2)
qc.cx(6, 7)
qc.cx(3, 2)
qc.cx(6, 2)
qc.cx(2, 0)
qc.cx(7, 6)
coupling = CouplingMap.from_line(8)
pass_ = StochasticSwap(coupling, seed=2022_10_13)
transpiled = pass_(qc)
# Check the pass claims to have done things right.
initial_layout = Layout.generate_trivial_layout(*qc.qubits)
self.assertEqual(initial_layout, pass_.property_set["final_layout"])
# Check that pass really did do it right.
inner_block = transpiled.data[0].operation.blocks[0]
running_layout = initial_layout.copy()
for instruction in inner_block:
if instruction.operation.name == "swap":
running_layout.swap(*instruction.qubits)
self.assertEqual(initial_layout, running_layout)
@ddt
class TestStochasticSwapRandomCircuitValidOutput(QiskitTestCase):
"""Assert the output of a transpilation with stochastic swap is a physical circuit."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.backend = FakeMumbai()
cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map}
cls.basis_gates = set(cls.backend.configuration().basis_gates)
cls.basis_gates.update(["for_loop", "while_loop", "if_else"])
def assert_valid_circuit(self, transpiled):
"""Assert circuit complies with constraints of backend."""
self.assertIsInstance(transpiled, QuantumCircuit)
self.assertIsNotNone(getattr(transpiled, "_layout", None))
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name in {"barrier", "measure"}:
continue
self.assertIn(instruction.operation.name, self.basis_gates)
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
if not isinstance(instruction.operation, ControlFlowOp):
if len(qargs) > 2 or len(qargs) < 0:
raise Exception("Invalid number of qargs for instruction")
if len(qargs) == 2:
self.assertIn(qargs, self.coupling_edge_set)
else:
self.assertLessEqual(qargs[0], 26)
else:
for block in instruction.operation.blocks:
self.assertEqual(block.num_qubits, len(instruction.qubits))
self.assertEqual(block.num_clbits, len(instruction.clbits))
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
# Assert routing ran.
_visit_block(
transpiled,
qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)},
)
@data(*range(1, 27))
def test_random_circuit_no_control_flow(self, size):
"""Test that transpiled random circuits without control flow are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
tqc = transpile(
circuit,
self.backend,
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
@data(*range(1, 27))
def test_random_circuit_no_control_flow_target(self, size):
"""Test that transpiled random circuits without control flow are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
tqc = transpile(
circuit,
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
target=FakeMumbaiV2().target,
)
self.assert_valid_circuit(tqc)
@data(*range(4, 27))
def test_random_circuit_for_loop(self, size):
"""Test that transpiled random circuits with nested for loops are physical circuits."""
circuit = random_circuit(size, 3, measure=False, seed=12342)
for_block = random_circuit(3, 2, measure=False, seed=12342)
inner_for_block = random_circuit(2, 1, measure=False, seed=12342)
with circuit.for_loop((1,)):
with circuit.for_loop((1,)):
circuit.append(inner_for_block, [0, 3])
circuit.append(for_block, [1, 0, 2])
circuit.measure_all()
tqc = transpile(
circuit,
self.backend,
basis_gates=list(self.basis_gates),
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
@data(*range(6, 27))
def test_random_circuit_if_else(self, size):
"""Test that transpiled random circuits with if else blocks are physical circuits."""
circuit = random_circuit(size, 3, measure=True, seed=12342)
if_block = random_circuit(3, 2, measure=True, seed=12342)
else_block = random_circuit(2, 1, measure=True, seed=12342)
rng = numpy.random.default_rng(seed=12342)
inner_clbit_count = max((if_block.num_clbits, else_block.num_clbits))
if inner_clbit_count > circuit.num_clbits:
circuit.add_bits([Clbit() for _ in [None] * (inner_clbit_count - circuit.num_clbits)])
clbit_indices = list(range(circuit.num_clbits))
rng.shuffle(clbit_indices)
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.append(if_block, [0, 2, 1], clbit_indices[: if_block.num_clbits])
with else_:
circuit.append(else_block, [2, 5], clbit_indices[: else_block.num_clbits])
tqc = transpile(
circuit,
self.backend,
basis_gates=list(self.basis_gates),
routing_method="stochastic",
layout_method="dense",
seed_transpiler=12342,
)
self.assert_valid_circuit(tqc)
if __name__ == "__main__":
unittest.main()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
# YOUR CODE HERE
encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4)
ex1_circuit =encode_map_x.bind_parameters(x)
ex1_circuit.draw(output='mpl')
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4)
zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y)
backend =Aer.get_backend('qasm_simulator')
job = execute(zz_circuit_x2,backend,shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts_x2 = job.result().get_counts(zz_circuit_x2)
amplitude= counts_x2['00']/sum(counts_x2.values())
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
import random
import numpy as np
from qiskit import QuantumCircuit
from QiskitPBT.case_studies.grovers_algorithm.grovers_algorithm import grovers_algorithm
from QiskitPBT.case_studies.grovers_algorithm.grovers_algorithm_helpers import RandomGroversOracleMarkedStatesPairGenerator
from QiskitPBT.property import Property
class GroversAlgorithmMostFrequentNotMarkedIfTooManyMarked(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
return [RandomGroversOracleMarkedStatesPairGenerator(4, 7, "too_many")]
# specify the preconditions for the test
def preconditions(self, oracle_pair):
oracle, marked_states = oracle_pair
# need more than half for this property to hold
if len(marked_states) < 2**(oracle.num_qubits//2):
return False
return True
# specify the operations to be performed on the input
def operations(self, oracle_pair):
oracle, marked_states = oracle_pair
# for this case to work out, we need to apply at least 1 grover iteration (we would otherwise get 0)
n_iterations = 1
circ = grovers_algorithm(oracle, n_iterations)
# invert most frequent list to get the list of states that are not marked
not_marked_states = list(set(range(2**(circ.num_qubits-1))) - set(marked_states))
not_marked_binary_states = []
# marked states to binary strings to check
for state in not_marked_states:
binary = bin(state)[2:]
binary = '0' * (oracle.num_qubits - 1 - len(binary)) + binary
binary = binary[::-1]
not_marked_binary_states.append(binary)
# TODO: need to implement this assert most frequent, or something like it, all i know about the output state
# is that the most frequent state should be from the list of marked, and (roughly) all should have the same distribution
# but maybe testing that is not easy to implement with what we have
self.statistical_analysis.assert_most_frequent(self, list(range(circ.num_qubits-1)), circ, not_marked_binary_states, basis=["z"])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import random
from qiskit.quantum_info import Statevector
secret = random.randint(0,7) # the owner is randomly picked
secret_string = format(secret, '03b') # format the owner in 3-bit string
oracle = Statevector.from_label(secret_string) # let the oracle know the owner
from qiskit.algorithms import AmplificationProblem
problem = AmplificationProblem(oracle, is_good_state=secret_string)
from qiskit.algorithms import Grover
grover_circuits = []
for iteration in range(1,3):
grover = Grover(iterations=iteration)
circuit = grover.construct_circuit(problem)
circuit.measure_all()
grover_circuits.append(circuit)
# Grover's circuit with 1 iteration
grover_circuits[0].draw()
# Grover's circuit with 2 iterations
grover_circuits[1].draw()
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(circuits=grover_circuits, shots=1000)
result = job.result()
print(result)
from qiskit.tools.visualization import plot_histogram
# Extract bit string with highest probability from results as the answer
result_dict = result.quasi_dists[1].binary_probabilities()
answer = max(result_dict, key=result_dict.get)
print(f"As you can see, the quantum computer returned '{answer}' as the answer with highest probability.\n"
"And the results with 2 iterations have higher probability than the results with 1 iteration."
)
# Plot the results
plot_histogram(result.quasi_dists, legend=['1 iteration', '2 iterations'])
# Print the results and the correct answer.
print(f"Quantum answer: {answer}")
print(f"Correct answer: {secret_string}")
print('Success!' if answer == secret_string else 'Failure!')
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_histogram
# Use Aer's qasm_simulator
simulator = QasmSimulator()
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# compile the circuit down to low-level QASM instructions
# supported by the backend (not needed for simple circuits)
compiled_circuit = transpile(circuit, simulator)
# Execute the circuit on the qasm simulator
job = simulator.run(compiled_circuit, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(compiled_circuit)
# print("\nTotal count for 00 and 11 are:",counts)
# Draw the ci
circuit.draw(output="latex", filename="printing.png")
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
import numpy as np
import time
from qiskit_experiments.library import StandardRB, InterleavedRB
from qiskit_experiments.framework import ParallelExperiment
from qiskit_experiments.library.randomized_benchmarking import RBUtils
import qiskit.circuit.library as circuits
# for retrieving gate Reference
from datetime import datetime
import qiskit.providers.aer.noise.device as dv
# import the bayesian packages
import pymc3 as pm
import arviz as az
import qiskit_bayesian_fitter as bf
simulation = True # make your choice here
if simulation:
from qiskit.providers.aer import AerSimulator
from qiskit.test.mock import FakeParis
backend = AerSimulator.from_backend(FakeParis())
else:
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_bogota') # type here hardware backend
# describe RB experiment (accept 1-qubit or 2-qubit interleaved gate)
is_1_qubit = False
if is_1_qubit:
interleaved_gate = "x"
interleaved_circuit = circuits.XGate()
qubits = [0]
lengths = np.arange(1, 2500, 250)
testval_s = 0.001
upper_s = 0.004
lower_s = 0.0005
alpha_Gamma = 10
beta_Gamma = 10000
else:
interleaved_gate = "cx"
interleaved_circuit = circuits.CXGate()
qubits = [1,4]
lengths = np.arange(1, 200, 15)
testval_s = 0.0025
upper_s = 0.005
lower_s = 0.0005
alpha_Gamma = 5
beta_Gamma = 2000
num_samples = 10
seed = 194606
# get the backend's referencevalue
t = None # enter t in datetime format if necessary
# use properties(datetime=t) if t is defined
e_list = dv.gate_error_values(backend.properties())
epc_calib = np.nan
for tuple_e in e_list:
if tuple_e[0] == interleaved_gate and tuple_e[1] == qubits:
epc_calib = tuple_e[2]
print('EPC reference: {0:1.4e}'.format(epc_calib))
#prepare circuits
int_exp = InterleavedRB(interleaved_circuit, qubits,
lengths, num_samples=num_samples, seed=seed)
#run
print("start experiments",time.strftime('%d/%m/%Y %H:%M:%S'))
int_expdata = int_exp.run(backend).block_for_results()
print(" end experiments",time.strftime('%d/%m/%Y %H:%M:%S'))
experiment_type = int_expdata._data[0]['metadata']['experiment_type']
physical_qubits = int_expdata._data[0]['metadata']['physical_qubits']
shots = int_expdata._data[0]['shots']
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
m_len = len(lengths)
# get count data and other values from int_expdata
Y = bf.get_GSP_counts(int_expdata._data, 2*m_len,
range(num_samples))
# get RvsI_h and IvsR_h
RvsI_h = np.ones(2*m_len)
for i_data in range(2*m_len):
if int_expdata._data[i_data]['metadata']['interleaved']:
RvsI_h[i_data] = 0.
IvsR_h = (RvsI_h + 1.) %2
X0 = np.tile(lengths,2)
X = np.vstack((X0,RvsI_h,IvsR_h))
y_mean = np.mean(Y, axis = 0)/shots
sigma_y = np.std(Y, axis = 0)/shots
model = "hierarchical model"
# priors for unknown model parameters
T_priors = int_expdata.analysis_results()[0].value.value
print(T_priors)
h_model = bf.create_model(T_priors, X, Y, shots, scale,
testval_s = testval_s, upper_s = upper_s, lower_s = lower_s,
s_prior = "Gamma", alpha_Gamma = alpha_Gamma, beta_Gamma = beta_Gamma)
# model graph
pm.model_to_graphviz(h_model)
# sample
with h_model:
trace_h = pm.sample(draws = 4000, tune= 1000, target_accept=.99,
return_inferencedata=True)
with h_model:
az.plot_trace(trace_h);
with h_model:
az.plot_posterior(trace_h, var_names = ["Tying_Parameters","σ_Beta","EPC"], round_to = 4, figsize = [16, 8]);
# look at the posterior values of the hyperparameters:
with h_model:
# (hdi_prob=.94 is default)
azt_summary = az.summary(trace_h, round_to=12,
var_names = ["Tying_Parameters","σ_Beta","EPC"],
kind="stats")
azt_summary
# for comparison
# bayesian
epc_est_a = azt_summary['mean']['EPC']
epc_est_a_err = azt_summary['sd']['EPC']
# frequentist
epc_est_fm = int_expdata.analysis_results()[3].value.value
epc_est_fm_err = int_expdata.analysis_results()[3].value.stderr
epc_title = experiment_type +', ' + interleaved_gate \
+ " qubit(s):" + str(physical_qubits)\
+', backend: '+ backend.name() + "\n Bayesian "+model
bf.plot_epc(h_model, trace_h, epc_calib, epc_est_a,
epc_est_a_err, epc_est_fm, epc_est_fm_err, epc_title)
# compare LSF and SMC
print("Model: Frequentist Bayesian Reference")
print("__________________________________________________________")
print("EPC {0:1.3e} {1:1.3e} {2:1.3e}"
.format(epc_est_fm,epc_est_a,epc_calib ))
print("± sd ± {0:1.3e} ± {1:1.3e} "
.format(epc_est_fm_err, epc_est_a_err))
def calc_chisquare(ydata, sigma, ycalc):
r = ydata - ycalc
chisq = np.sum((r / sigma) ** 2)
return chisq
# GSP plot
# perform reduced χ² value calculation for Bayes hierarchical
mean_h = trace_h.posterior.mean(dim=['chain', 'draw'])
theta_stacked = mean_h.θ.values
NDF_h = m_len*2 - 4 - 1 # (-1 is for σ_Beta)
chisq_h = calc_chisquare(y_mean, sigma_y, theta_stacked)/NDF_h
#box:
texto = " alpha = {0:7.4f} ± {1:1.4e}"\
.format(azt_summary['mean']['Tying_Parameters[1]'],
azt_summary['sd']['Tying_Parameters[1]']) + "\n"
texto +=" alpha_c = {0:7.4f} ± {1:1.4e}"\
.format(azt_summary['mean']['Tying_Parameters[2]'],
azt_summary['sd']['Tying_Parameters[2]']) + "\n"
texto +=" EPC = {0:7.4f} ± {1:1.4e}"\
.format(azt_summary['mean']['EPC'],
azt_summary['sd']['EPC']) + "\n"
texto +=" Fit χ² = {0:7.4f} "\
.format(chisq_h)
# obtain data for plot
bounds_rmk, y1, y1_min, y1_max, y2, y2_min, y2_max, Y1, Y2 = \
bf.prepare_two_curves_GSP_plot(h_model, trace_h, X, Y, HDI = False)
# title
title = experiment_type +', ' + interleaved_gate\
+ str(physical_qubits)\
+', backend: '+backend.name()+\
"\n Bayesian "+model+" "+ bounds_rmk
# plot
bf.gsp_plot(scale, lengths, num_samples, shots, texto, title,
y1, y1_min, y1_max, y2, y2_min, y2_max, Y1, Y2,
first_curve = "Standard", second_curve = "Interleaved")
# View result for frequentist model
display(int_expdata.figure(0))
|
https://github.com/adelshb/Quantum-Machine-Learning-for-Titanic-on-IBM-Q
|
adelshb
|
from qiskit import Aer, QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit_machine_learning.neural_networks import CircuitQNN
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from titanicibmq.titanic_data import *
# Install a pip package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install sklearn
from sklearn.decomposition import PCA
# Load the data
datapath="data/"
data, __ = titanic(datapath=datapath)
data.sample(frac=1)
X = data.drop("Survived", axis=1).values
pca = PCA(n_components=2)
Xpca = pca.fit_transform(X)
split_ratio = 0.2
X_train = Xpca[int(data.shape[0]*split_ratio):,:]
X_test = Xpca[:int(data.shape[0]*split_ratio),:]
y_train = data.iloc[int(data.shape[0]*split_ratio):,:]["Survived"].values
y_test = data.iloc[:int(data.shape[0]*split_ratio),:]["Survived"].values
def get_interpret(num_classes):
def parity(x, num_classes=num_classes):
return '{:b}'.format(x).count('1') % num_classes
return parity
def parity(x):
return '{:b}'.format(x).count('1') % 2
quantum_instance = QuantumInstance(Aer.get_backend('statevector_simulator'), shots=100)
optimizer = COBYLA(maxiter=100)
feature_map = ZZFeatureMap(feature_dimension=X_train.shape[1], reps=1)
ansatz = RealAmplitudes(num_qubits=feature_map._num_qubits, reps=1)
qc = QuantumCircuit(feature_map._num_qubits)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qnn = CircuitQNN(circuit= qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
sparse=False,
sampling=False,
interpret=parity,
output_shape=len(np.unique(y_train, axis=0)),
gradient=None,
quantum_instance=quantum_instance)
cc = NeuralNetworkClassifier(neural_network=qnn,
optimizer=optimizer)
cc.fit(X_train, y_train)
# Model accuracy
acc_train = cc.score(X_train, y_train)
acc_test = cc.score(X_test, y_test)
print("Accuracy on training dataset: {}.".format(acc_train))
print("Accuracy on testing dataset: {}.".format(acc_test))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
circ.draw(output='mpl')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.