repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Kraus 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 Kraus
from .channel_test_case import ChannelTestCase
class TestKraus(ChannelTestCase):
"""Tests for Kraus channel representation."""
def test_init(self):
"""Test initialization"""
# Initialize from unitary
chan = Kraus(self.UI)
assert_allclose(chan.data, [self.UI])
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Kraus
chan = Kraus(self.depol_kraus(0.5))
assert_allclose(chan.data, self.depol_kraus(0.5))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Non-CPTP
kraus_l, kraus_r = [self.UI, self.UX], [self.UY, self.UZ]
chan = Kraus((kraus_l, kraus_r))
assert_allclose(chan.data, (kraus_l, kraus_r))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize with redundant second op
chan = Kraus((kraus_l, kraus_l))
assert_allclose(chan.data, kraus_l)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from rectangular
kraus = [np.zeros((4, 2))]
chan = Kraus(kraus)
assert_allclose(chan.data, kraus)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Kraus, kraus, input_dims=4, output_dims=4)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Kraus(circuit)
target = Kraus(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, Kraus, circuit)
def test_equal(self):
"""Test __eq__ method"""
kraus = [self.rand_matrix(2, 2) for _ in range(2)]
self.assertEqual(Kraus(kraus), Kraus(kraus))
def test_copy(self):
"""Test copy method"""
mat = np.eye(2)
with self.subTest("Deep copy"):
orig = Kraus(mat)
cpy = orig.copy()
cpy._data[0][0][0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Kraus(mat)
clone = copy.copy(orig)
clone._data[0][0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Kraus(mat)
clone = copy.copy(orig)
clone._data[0][0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Kraus(self.depol_kraus(0.5)).is_cptp())
self.assertTrue(Kraus(self.UX).is_cptp())
# Non-CPTP should return false
self.assertFalse(Kraus(([self.UI], [self.UX])).is_cptp())
self.assertFalse(Kraus([self.UI, self.UX]).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus list
targ = Kraus([np.conjugate(k) for k in kraus_l])
chan1 = Kraus(kraus_l)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
# Double Kraus list
targ = Kraus(([np.conjugate(k) for k in kraus_l], [np.conjugate(k) for k in kraus_r]))
chan1 = Kraus((kraus_l, kraus_r))
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
def test_transpose(self):
"""Test transpose method."""
kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus list
targ = Kraus([np.transpose(k) for k in kraus_l])
chan1 = Kraus(kraus_l)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double Kraus list
targ = Kraus(([np.transpose(k) for k in kraus_l], [np.transpose(k) for k in kraus_r]))
chan1 = Kraus((kraus_l, kraus_r))
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_adjoint(self):
"""Test adjoint method."""
kraus_l, kraus_r = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus list
targ = Kraus([np.transpose(k).conj() for k in kraus_l])
chan1 = Kraus(kraus_l)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double Kraus list
targ = Kraus(
([np.transpose(k).conj() for k in kraus_l], [np.transpose(k).conj() for k in kraus_r])
)
chan1 = Kraus((kraus_l, kraus_r))
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, Kraus(np.eye(2)).compose, Kraus(np.eye(4)))
self.assertRaises(QiskitError, Kraus(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Kraus(self.UX)
chan2 = Kraus(self.UY)
chan = chan1.compose(chan2)
targ = rho & Kraus(self.UZ)
self.assertEqual(rho & chan, targ)
# 50% depolarizing channel
chan1 = Kraus(self.depol_kraus(0.5))
chan = chan1.compose(chan1)
targ = rho & Kraus(self.depol_kraus(0.75))
self.assertEqual(rho & chan, targ)
# Compose different dimensions
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4)
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = rho & chan1 & chan2
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho & chan, targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho & chan, targ)
def test_dot(self):
"""Test dot method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Kraus(self.UX)
chan2 = Kraus(self.UY)
targ = rho.evolve(Kraus(self.UZ))
self.assertEqual(rho.evolve(chan1.dot(chan2)), targ)
self.assertEqual(rho.evolve(chan1 @ chan2), targ)
# 50% depolarizing channel
chan1 = Kraus(self.depol_kraus(0.5))
targ = rho & Kraus(self.depol_kraus(0.75))
self.assertEqual(rho.evolve(chan1.dot(chan1)), targ)
self.assertEqual(rho.evolve(chan1 @ chan1), targ)
# Compose different dimensions
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4)
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = rho & chan1 & chan2
self.assertEqual(rho.evolve(chan2.dot(chan1)), targ)
self.assertEqual(rho.evolve(chan2 @ chan1), targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Kraus(self.UX)
chan2 = Kraus(self.UY)
chan = chan1.compose(chan2, front=True)
targ = rho & Kraus(self.UZ)
self.assertEqual(rho & chan, targ)
# 50% depolarizing channel
chan1 = Kraus(self.depol_kraus(0.5))
chan = chan1.compose(chan1, front=True)
targ = rho & Kraus(self.depol_kraus(0.75))
self.assertEqual(rho & chan, targ)
# Compose different dimensions
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(4, 2, 4)
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = rho & chan1 & chan2
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho & chan, 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 = Kraus(self.UI)
chan2 = Kraus(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 & 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 & chan, rho_targ)
# Completely depolarizing
chan_dep = Kraus(self.depol_kraus(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 & 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 = Kraus(self.UI)
chan2 = Kraus(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 & 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 & chan, rho_targ)
# Completely depolarizing
chan_dep = Kraus(self.depol_kraus(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 & chan, rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
rho = DensityMatrix(np.diag([1, 0]))
p_id = 0.9
chan = Kraus(self.depol_kraus(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = chan.power(3)
targ3a = rho & chan & chan & chan
self.assertEqual(rho & chan3, targ3a)
targ3b = rho & Kraus(self.depol_kraus(1 - p_id3))
self.assertEqual(rho & chan3, targ3b)
def test_add(self):
"""Test add method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Random Single-Kraus maps
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = (rho & chan1) + (rho & chan2)
chan = chan1._add(chan2)
self.assertEqual(rho & chan, targ)
chan = chan1 + chan2
self.assertEqual(rho & chan, targ)
# Random Single-Kraus maps
chan = Kraus((kraus1, kraus2))
targ = 2 * (rho & chan)
chan = chan._add(chan)
self.assertEqual(rho & chan, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
kraus = self.rand_kraus(8, 8, 4)
kraus0 = self.rand_kraus(2, 2, 4)
op = Kraus(kraus)
op0 = Kraus(kraus0)
eye = Kraus(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))
kraus = self.rand_kraus(8, 8, 4)
kraus0 = self.rand_kraus(2, 2, 4)
op = Kraus(kraus)
op0 = Kraus(kraus0)
eye = Kraus(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_subtract(self):
"""Test subtract method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Random Single-Kraus maps
chan1 = Kraus(kraus1)
chan2 = Kraus(kraus2)
targ = (rho & chan1) - (rho & chan2)
chan = chan1 - chan2
self.assertEqual(rho & chan, targ)
# Random Single-Kraus maps
chan = Kraus((kraus1, kraus2))
targ = 0 * (rho & chan)
chan = chan - chan
self.assertEqual(rho & chan, targ)
def test_multiply(self):
"""Test multiply method."""
# Random initial state and Kraus ops
rho = DensityMatrix(self.rand_rho(2))
val = 0.5
kraus1, kraus2 = self.rand_kraus(2, 4, 4), self.rand_kraus(2, 4, 4)
# Single Kraus set
chan1 = Kraus(kraus1)
targ = val * (rho & chan1)
chan = chan1._multiply(val)
self.assertEqual(rho & chan, targ)
chan = val * chan1
self.assertEqual(rho & chan, targ)
targ = (rho & chan1) * val
chan = chan1 * val
self.assertEqual(rho & chan, targ)
# Double Kraus set
chan2 = Kraus((kraus1, kraus2))
targ = val * (rho & chan2)
chan = chan2._multiply(val)
self.assertEqual(rho & chan, targ)
chan = val * chan2
self.assertEqual(rho & chan, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Kraus(self.depol_kraus(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 = DensityMatrix(np.diag([1, 0]))
targ = DensityMatrix(np.diag([-0.5, -0.5]))
chan = -Kraus(self.depol_kraus(1))
self.assertEqual(rho & chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
dag_drawer(dag)
|
https://github.com/rochisha0/stock-picking
|
rochisha0
|
from qiskit.finance.data_providers import RandomDataProvider
import numpy as np
import matplotlib.pyplot as plt
import datetime
import pandas as pd
from nsepy import get_history
from docplex.mp.model import Model
from qiskit.optimization import QuadraticProgram
from qiskit.optimization.converters import LinearEqualityToPenalty
from qiskit.aqua.algorithms import NumPyMinimumEigensolver
import pennylane as qml
assets = [ 'INFY', 'TCS', 'YESBANK']
stockStartDate = datetime.date(2018,8,20)
stockEndDate = datetime.date(2019,8,20)
df = pd.DataFrame()
for stock in assets:
df[stock] = get_history(symbol=stock, start=stockStartDate, end=stockEndDate)['Close']
returns = df.pct_change()
cov_matrix_annual = returns.cov() * 249
mu = returns.mean().to_numpy() #expected returns
sigma = cov_matrix_annual.to_numpy() #covariance
q = 0.1 # set risk factor
budget = 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
mdl = Model('docplex model')
x = mdl.binary_var_list(num_assets)
# set objective function:
#
# maximize { mu^T * x - q * x^T * sigma * x }
#
objective = mdl.sum([mu[i] * x[i] for i in range(num_assets)]) # mu^T * x
objective -= q * mdl.sum([sigma[i][j]*x[i]*x[j] for i in range(num_assets) for j in range(num_assets)])
mdl.maximize(objective)
# add budget constraint:
#
# 1^T * x == budget
#
cost = mdl.sum([x[i] for i in range(num_assets)])
mdl.add_constraint(cost == budget, ctname='budget')
# converting to Quadratic Program
mod = QuadraticProgram()
mod.from_docplex(mdl)
#removing the constraint to create the QUBO
lineq2penalty = LinearEqualityToPenalty(penalty)
qubo = lineq2penalty.convert(mod)
#converting QUBO to an Ising Hamiltonian
H, offset = qubo.to_ising()
H.num_qubits
H = H.to_legacy_op()
H.print_details()
def ansatz(theta):
qml.RX(theta[0], wires=0)
qml.RX(theta[1], wires=1)
qml.RX(theta[2], wires=2)
qml.CNOT(wires=[0,1])
qml.CNOT(wires=[0,2])
qml.CNOT(wires=[1,2])
qml.RX(theta[3], wires=0)
qml.RX(theta[4], wires=1)
qml.RX(theta[5], wires=2)
qml.CNOT(wires=[0,1])
qml.CNOT(wires=[0,2])
qml.CNOT(wires=[1,2])
qml.RX(theta[6], wires=0)
qml.RX(theta[7], wires=1)
qml.RX(theta[8], wires=2)
return ansatz
dev1 = qml.device("qiskit.aer", wires=3)
@qml.qnode(dev1)
def circuit_IIZ(params):
ansatz(params)
return qml.expval(qml.Identity(0)@qml.Identity(1)@qml.PauliZ(2))
@qml.qnode(dev1)
def circuit_IZI(params):
ansatz(params)
return qml.expval(qml.Identity(0)@qml.PauliZ(1)@qml.Identity(2))
@qml.qnode(dev1)
def circuit_ZII(params):
ansatz(params)
return qml.expval(qml.PauliZ(0)@qml.Identity(1)@qml.Identity(2))
@qml.qnode(dev1)
def circuit_IZZ(params):
ansatz(params)
return qml.expval(qml.Identity(0)@qml.PauliZ(1)@qml.PauliZ(2))
@qml.qnode(dev1)
def circuit_ZIZ(params):
ansatz(params)
return qml.expval(qml.PauliZ(0)@qml.Identity(1)@qml.PauliZ(2))
@qml.qnode(dev1)
def circuit_ZZI(params):
ansatz(params)
return qml.expval(qml.PauliZ(0)@qml.PauliZ(1)@qml.Identity(2))
def pauli_operator_to_dict(pauli_operator):
d = pauli_operator.to_dict()
paulis = d['paulis']
paulis_dict = {}
for x in paulis:
label = x['label']
coeff = x['coeff']['real']
paulis_dict[label] = coeff
return paulis_dict
pauli_dict = pauli_operator_to_dict(H)
def vqe(parameters):
expval_ZII = pauli_dict['ZII'] * circuit_ZII(parameters)
expval_IIZ = pauli_dict['IIZ'] * circuit_IIZ(parameters)
expval_IZI = pauli_dict['IZI'] * circuit_IZI(parameters)
expval_ZZI = pauli_dict['ZZI'] * circuit_ZZI(parameters)
expval_ZIZ = pauli_dict['ZIZ'] * circuit_ZIZ(parameters)
expval_IZZ = pauli_dict['IZZ'] * circuit_IZZ(parameters)
# summing the measurement results
classical_adder = expval_ZII + expval_IIZ + expval_ZIZ + expval_ZZI + expval_ZIZ + expval_IZZ
return classical_adder
opt = qml.GradientDescentOptimizer(stepsize=0.5)
value = []
# optimize parameters in objective
params = np.random.rand(9)*2
init_params = params
steps = 100
for i in range(steps):
params = opt.step(vqe, params)
value.append(vqe(params))
plt.bar(['000', '001', '010', '011', '100', '101', '110', '111'], final_circ(params))
@qml.qnode(dev1)
def final_circ(params):
ansatz(params)
return qml.probs(wires=[0,1,2])
params
plt.bar(['000', '001', '010', '011', '100', '101', '110', '111'], final_circ(params), color='midnightblue')
pauli_dict
H.print_details()
from qiskit import QuantumCircuit
circ = QuantumCircuit(3)
circ.rx(params[0], 0)
circ.rx(params[1], 1)
circ.rx(params[2], 2)
circ.cx(0,1)
circ.cx(0,2)
circ.cx(1,2)
circ.rx(params[3], 0)
circ.rx(params[4], 1)
circ.rx(params[5], 2)
circ.cx(0,1)
circ.cx(0,2)
circ.cx(1,2)
circ.rx(params[6], 0)
circ.rx(params[7], 1)
circ.rx(params[8], 2)
circ.draw('mpl')
|
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 the converters."""
import math
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Gate, Qubit
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
class TestCircuitToGate(QiskitTestCase):
"""Test QuantumCircuit to Gate"""
def test_simple_circuit(self):
"""test simple circuit"""
qr1 = QuantumRegister(4, "qr1")
qr2 = QuantumRegister(3, "qr2")
qr3 = QuantumRegister(3, "qr3")
circ = QuantumCircuit(qr1, qr2, qr3)
circ.cx(qr1[1], qr2[2])
gate = circ.to_gate()
q = QuantumRegister(10, "q")
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.definition[0].qubits, (q[1], q[6]))
def test_circuit_with_registerless_bits(self):
"""Test a circuit with registerless bits can be converted to a gate."""
qr1 = QuantumRegister(2)
qubits = [Qubit(), Qubit(), Qubit()]
qr2 = QuantumRegister(3)
circ = QuantumCircuit(qr1, qubits, qr2)
circ.cx(3, 5)
gate = circ.to_gate()
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.num_qubits, len(qr1) + len(qubits) + len(qr2))
gate_definition = gate.definition
cx = gate_definition.data[0]
self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
def test_circuit_with_overlapping_registers(self):
"""Test that the conversion works when the given circuit has bits that are contained in more
than one register."""
qubits = [Qubit() for _ in [None] * 10]
qr1 = QuantumRegister(bits=qubits[:6])
qr2 = QuantumRegister(bits=qubits[4:])
circ = QuantumCircuit(qubits, qr1, qr2)
circ.cx(3, 5)
gate = circ.to_gate()
self.assertIsInstance(gate, Gate)
self.assertEqual(gate.num_qubits, len(qubits))
gate_definition = gate.definition
cx = gate_definition.data[0]
self.assertEqual(cx.qubits, (gate_definition.qubits[3], gate_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
def test_raises(self):
"""test circuit which can't be converted raises"""
circ1 = QuantumCircuit(3)
circ1.x(0)
circ1.cx(0, 1)
circ1.barrier()
circ2 = QuantumCircuit(1, 1)
circ2.measure(0, 0)
circ3 = QuantumCircuit(1)
circ3.x(0)
circ3.reset(0)
with self.assertRaises(QiskitError): # TODO: accept barrier
circ1.to_gate()
with self.assertRaises(QiskitError): # measure and reset are not valid
circ2.to_gate()
def test_generated_gate_inverse(self):
"""Test inverse of generated gate works."""
qr1 = QuantumRegister(2, "qr1")
circ = QuantumCircuit(qr1)
circ.cx(qr1[1], qr1[0])
gate = circ.to_gate()
out_gate = gate.inverse()
self.assertIsInstance(out_gate, Gate)
def test_to_gate_label(self):
"""Test label setting."""
qr1 = QuantumRegister(2, "qr1")
circ = QuantumCircuit(qr1, name="a circuit name")
circ.cx(qr1[1], qr1[0])
gate = circ.to_gate(label="a label")
self.assertEqual(gate.label, "a label")
def test_zero_operands(self):
"""Test that a gate can be created, even if it has zero operands."""
base = QuantumCircuit(global_phase=math.pi)
gate = base.to_gate()
self.assertEqual(gate.num_qubits, 0)
self.assertEqual(gate.num_clbits, 0)
self.assertEqual(gate.definition, base)
compound = QuantumCircuit(1)
compound.append(gate, [], [])
np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
def gell_mann(d, g, j, k):
gm = np.zeros((d,d), dtype= complex)
if g == 'i': # identity
for j in range(0,d):
gm[j,j] = 1
elif g == 'd': # diagonal
nt = math.sqrt(2/(j*(j+1)))
for m in range(0,j):
gm[m,m] = nt
gm[j,j] = -j*nt
elif g == 's': # symmetric
gm[j-1,k-1] = 1; gm[k-1,j-1] = 1
elif g == 'a': # anti-symmetric
gm[j-1,k-1] = -1j; gm[k-1,j-1] = 1j
return gm
gell_mann(2, 'i', 0, 0), gell_mann(2, 'd', 1, 1), gell_mann(2, 's', 1, 2), gell_mann(2, 'a', 1, 2)
def bloch_vector(A):
d = A.shape[0]; bv = np.zeros((d**2-1), dtype = complex)
#bv[0] = trace(d,A)
for j in range(1,d): # diagonal
bv[j-1] = 0
for k in range(1,j+1):
bv[j-1] += A[k-1,k-1]
bv[j-1] -= j*A[j,j]
bv[j-1] *= math.sqrt(2/(j*(j+1)))
for k in range(1,d): # symmetric
for l in range(k+1,d+1):
j += 1
bv[j-1] = A[l-1,k-1] + A[k-1,l-1]
for k in range(1,d): # anti-symmetric
for l in range(k+1,d+1):
j += 1
bv[j-1] = -1j*(A[l-1,k-1] - A[k-1,l-1])
return bv.real
s0 = np.array([[1,0],[0,1]]); s1 = np.array([[0,1],[1,0]])
s2 = np.array([[0,-1j],[1j,0]]); s3 = np.array([[1,0],[0,-1]])
A = 0.5*(s0 + 0.1*s1 + 0.2*s2 + 0.3*s3); bloch_vector(A)
def corr_mat_dd(da, db, M):
cmdd = np.zeros((da-1,db-1), dtype = complex)
for j in range(1,da):
for k in range(1,db):
for m in range(1,j+1):
for n in range(1,k+1):
cmdd[j-1,k-1] += M[(m-1)*db+(n-1),(m-1)*db+(n-1)]
m = j+1
for n in range(1,k+1):
cmdd[j-1,k-1] -= j*M[(m-1)*db+(n-1),(m-1)*db+(n-1)]
n = k+1
for m in range(1,j+1):
cmdd[j-1,k-1] -= k*M[(m-1)*db+(n-1),(m-1)*db+(n-1)]
m = j+1
n = k+1
cmdd[j-1,k-1] += j*k*M[(m-1)*db+(n-1),(m-1)*db+(n-1)]
cmdd[j-1,k-1] *= 2/sqrt(j*(j+1)*k*(k+1))
return cmdd.real
def Pauli(j):
if j == 0:
return np.array([[1,0],[0,1]])
elif j == 1:
return np.array([[0,1],[1,0]])
elif j == 2:
return np.array([[0,-1j],[1j,0]])
elif j == 3:
return np.array([[1,0],[0,-1]])
def rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33):
return (1/4)*(tp(Pauli(0),Pauli(0)) + b1*tp(Pauli(0),Pauli(1)) + b2*tp(Pauli(0),Pauli(2)) + b3*tp(Pauli(0),Pauli(3))
+ a1*tp(Pauli(1),Pauli(0)) + c11*tp(Pauli(1),Pauli(1)) + c12*tp(Pauli(1),Pauli(2)) + c13*tp(Pauli(1),Pauli(3))
+ a2*tp(Pauli(2),Pauli(0)) + c21*tp(Pauli(2),Pauli(1)) + c22*tp(Pauli(2),Pauli(2)) + c23*tp(Pauli(2),Pauli(3))
+ a3*tp(Pauli(3),Pauli(0)) + c31*tp(Pauli(3),Pauli(1)) + c32*tp(Pauli(3),Pauli(2)) + c33*tp(Pauli(3),Pauli(3)))
a1, a2, a3, b1, b2, b3 = 0.11, 0.12, 0.13, 0.25, 0.26, 0.27
c11, c12, c13, c21, c22, c23, c31, c32, c33 = 0.11, 0.12, 0.13, 0.21, 0.22, 0.23, 0.31, 0.32, 0.33
corr_mat_dd(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33))
def corr_mat_ds(da, db, M):
cmds = np.zeros((da-1,db*(db-1)//2), dtype = complex)
for j in range(1,da):
n = 0
for k in range(1,db):
for l in range(k+1,db+1):
n += 1
for m in range(1,j+1):
cmds[j-1,n-1] += (M[(m-1)*db+(l-1),(m-1)*db+(k-1)] + M[(m-1)*db+(k-1),(m-1)*db+(l-1)])
m = j+1
cmds[j-1,n-1] -= j*(M[(m-1)*db+(l-1),(m-1)*db+(k-1)] + M[(m-1)*db+(k-1),(m-1)*db+(l-1)])
cmds[j-1,n-1] *= sqrt(2/(j*(j+1)))
return cmds.real
corr_mat_ds(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33))
def corr_mat_da(da, db, M):
cmda = np.zeros((da-1,db*(db-1)//2), dtype = complex)
for j in range(1,da):
n = 0
for k in range(1,db):
for l in range(k+1,db+1):
n += 1
for m in range(1,j+1):
cmda[j-1,n-1] += (M[(m-1)*db+(l-1),(m-1)*db+(k-1)] - M[(m-1)*db+(k-1),(m-1)*db+(l-1)])
m = j+1
cmda[j-1,n-1] -= j*(M[(m-1)*db+(l-1),(m-1)*db+(k-1)] - M[(m-1)*db+(k-1),(m-1)*db+(l-1)])
cmda[j-1,n-1] *= -1j*sqrt(2/(j*(j+1)))
return cmda.real
corr_mat_da(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33))
def corr_mat_sd(da, db, M):
cmsd = np.zeros((da*(da-1)//2,db-1), dtype = complex)
n = 0
for k in range(1,da):
for l in range(k+1,da+1):
n += 1
for j in range(1,db):
for m in range(1,j+1):
cmsd[n-1,j-1] += (M[(l-1)*db+(m-1),(k-1)*db+(m-1)] + M[(k-1)*db+(m-1),(l-1)*db+(m-1)])
m = j+1
cmsd[n-1,j-1] -= j*(M[(l-1)*db+(m-1),(k-1)*db+(m-1)] + M[(k-1)*db+(m-1),(l-1)*db+(m-1)])
cmsd[n-1,j-1] *= sqrt(2/(j*(j+1)))
return cmsd.real
corr_mat_sd(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33))
def corr_mat_ad(da, db, M):
cmad = np.zeros((da*(da-1)//2,db-1), dtype = complex)
n = 0
for k in range(1,da):
for l in range(k+1,da+1):
n += 1
for j in range(1,db):
for m in range(1,j+1):
cmad[n-1,j-1] += (M[(l-1)*db+m-1,(k-1)*db+m-1] - M[(k-1)*db+m-1,(l-1)*db+m-1])
m = j+1
cmad[n-1,j-1] -= j*(M[(l-1)*db+m-1,(k-1)*db+m-1] - M[(k-1)*db+m-1,(l-1)*db+m-1])
cmad[n-1,j-1] *= -1j*sqrt(2/(j*(j+1)))
return cmad.real
corr_mat_ad(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33))
def corr_mat_ss(da, db, M):
cmss = np.zeros((da*(da-1)//2,db*(db-1)//2), dtype = complex)
p = 0
for k in range(1,da):
for l in range(k+1,da+1):
p += 1
q = 0
for m in range(1,db):
for n in range(m+1,db+1):
q += 1
cmss[p-1,q-1] += (M[(l-1)*db+n-1,(k-1)*db+m-1] + M[(k-1)*db+m-1,(l-1)*db+n-1])
cmss[p-1,q-1] += (M[(l-1)*db+m-1,(k-1)*db+n-1] + M[(k-1)*db+n-1,(l-1)*db+m-1])
return cmss.real
corr_mat_ss(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33))
def corr_mat_sa(da, db, M):
cmsa = np.zeros((da*(da-1)//2,db*(db-1)//2), dtype = complex)
p = 0
for k in range(1,da):
for l in range(k+1,da+1):
p += 1
q = 0
for m in range(1,db):
for n in range(m+1,db+1):
q += 1
cmsa[p-1,q-1] -= 1j*(M[(l-1)*db+n-1,(k-1)*db+m-1] - M[(k-1)*db+m-1,(l-1)*db+n-1])
cmsa[p-1,q-1] -= 1j*(M[(k-1)*db+n-1,(l-1)*db+m-1] - M[(l-1)*db+m-1,(k-1)*db+n-1])
return cmsa.real
simplify(corr_mat_sa(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33)))
def corr_mat_as(da, db, M):
cmas = np.zeros((da*(da-1)//2,db*(db-1)//2), dtype = complex)
p = 0
for k in range(1,da):
for l in range(k+1,da+1):
p += 1
q = 0
for m in range(1,db):
for n in range(m+1,db+1):
q += 1
cmas[p-1,q-1] -= 1j*(M[(l-1)*db+n-1,(k-1)*db+m-1] - M[(k-1)*db+m-1,(l-1)*db+n-1])
cmas[p-1,q-1] -= 1j*(M[(l-1)*db+m-1,(k-1)*db+n-1] - M[(k-1)*db+n-1,(l-1)*db+m-1])
return cmas.real
simplify(corr_mat_as(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33)))
def corr_mat_aa(da, db, M):
cmaa = np.zeros((da*(da-1)//2,db*(db-1)//2), dtype = complex)
p = 0
for k in range(1,da):
for l in range(k+1,da+1):
p += 1
q = 0
for m in range(1,db):
for n in range(m+1,db+1):
q += 1
cmaa[p-1,q-1] += (M[(l-1)*db+m-1,(k-1)*db+n-1] + M[(k-1)*db+n-1,(l-1)*db+m-1])
cmaa[p-1,q-1] -= (M[(l-1)*db+n-1,(k-1)*db+m-1] + M[(k-1)*db+m-1,(l-1)*db+n-1])
return cmaa.real
corr_mat_aa(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33))
def corr_mat(da, db, M):
dda = int((da*(da-1))/2); ddb = int((db*(db-1))/2); cm = np.zeros((da**2-1,db**2-1))
k = -1; l = -1
cmdd = corr_mat_dd(da, db, M); cmds = corr_mat_ds(da, db, M); cmda = corr_mat_da(da, db, M)
for m in range(0,da-1):
k += 1
for n in range(0,db-1): # diagonal-diagonal
l += 1; cm[k,l] = cmdd[m,n]
for n in range(0,ddb): # diagonal-symmetric
l += 1; cm[k,l] = cmds[m,n]
for n in range(0,ddb): # diagonal-antisymmetric
l += 1; cm[k,l] = cmda[m,n]
cmsd = corr_mat_sd(da, db, M); cmss = corr_mat_ss(da, db, M); cmsa = corr_mat_sa(da, db, M)
l = -1
for m in range(0,dda):
k += 1
for n in range(0,db-1): # symmetric-diagonal
l += 1; cm[k,l] = cmsd[m,n]
for n in range(0,ddb): # symmetric-symmetric
l += 1; cm[k,l] = cmss[m,n]
for n in range(0,ddb): # symmetric-antisymmetric
l += 1; cm[k,l] = cmsa[m,n]
cmad = corr_mat_ad(da, db, M); cmas = corr_mat_as(da, db, M); cmaa = corr_mat_aa(da, db, M)
l = -1
for m in range(0,dda):
k += 1
for n in range(0,db-1): # antisymmetric-diagonal
l += 1; cm[k,l] = cmad[m,n]
for n in range(0,ddb): # antisymmetric-symmetric
l += 1; cm[k,l] = cmas[m,n]
for n in range(0,ddb): # antisymmetric-antisymmetric
l += 1; cm[k,l] = cmaa[m,n]
return cm.real
simplify(corr_mat(2,2,rho2qb(a1, a2, a3, b1, b2, b3, c11, c12, c13, c21, c22, c23, c31, c32, c33)))
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import Operator, run_algorithm, get_algorithm_instance
from qiskit_aqua.input import get_input_instance
from qiskit_aqua.translators.ising import maxcut, tsp
# setup aqua logging
import logging
from qiskit_aqua._logging import set_logging_config, build_logging_config
# set_logging_config(build_logging_config(logging.DEBUG)) # choose INFO, DEBUG to see the log
# ignoring deprecation errors on matplotlib
import warnings
import matplotlib.cbook
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
from qiskit import IBMQ
IBMQ.load_accounts()
# Generating a graph of 4 nodes
n=4 # Number of nodes in graph
G=nx.Graph()
G.add_nodes_from(np.arange(0,n,1))
elist=[(0,1,1.0),(0,2,1.0),(0,3,1.0),(1,2,1.0),(2,3,1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ['r' for node in G.nodes()]
pos = nx.spring_layout(G)
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
# Computing the weight matrix from the random graph
w = np.zeros([n,n])
for i in range(n):
for j in range(n):
temp = G.get_edge_data(i,j,default=0)
if temp != 0:
w[i,j] = temp['weight']
print(w)
best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i,j]*x[i]*(1-x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
print('case = ' + str(x)+ ' cost = ' + str(cost))
colors = ['r' if xbest_brute[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)
print('\nBest solution = ' + str(xbest_brute) + ' cost = ' + str(best_cost_brute))
qubitOp, offset = maxcut.get_maxcut_qubitops(w)
algo_input = get_input_instance('EnergyInput')
algo_input.qubit_op = qubitOp
#Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
algorithm_cfg = {
'name': 'ExactEigensolver',
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, w))
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'SPSA',
'max_trials': 300
}
var_form_cfg = {
'name': 'RY',
'depth': 5,
'entanglement': 'linear'
}
params = {
'problem': {'name': 'ising', 'random_seed': 10598},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg,
'backend': {'name': 'statevector_simulator'}
}
result = run_algorithm(params, algo_input)
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, w))
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
# run quantum algorithm with shots
params['algorithm']['operator_mode'] = 'grouped_paulis'
params['backend']['name'] = 'qasm_simulator'
params['backend']['shots'] = 1024
result = run_algorithm(params, algo_input)
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, w))
plot_histogram(result['eigvecs'][0])
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
nx.draw_networkx(G, node_color=colors, node_size=600, alpha = .8, pos=pos)
|
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/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Test circuits and reference outputs for measure instruction.
"""
from numpy import array
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Instruction
# Backwards compatibility for Terra <= 0.13
if not hasattr(QuantumCircuit, 'i'):
QuantumCircuit.i = QuantumCircuit.iden
# ==========================================================================
# Single-qubit measurements with deterministic output
# ==========================================================================
def measure_circuits_deterministic(allow_sampling=True):
"""Measure test circuits with deterministic count output."""
circuits = []
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
# Measure |00> state
circuit = QuantumCircuit(qr, cr)
circuit.barrier(qr)
circuit.measure(qr, cr)
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
# Measure |01> state
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.barrier(qr)
circuit.measure(qr, cr)
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
# Measure |10> state
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[1])
circuit.barrier(qr)
circuit.measure(qr, cr)
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
# Measure |11> state
circuit = QuantumCircuit(qr, cr)
circuit.x(qr)
circuit.barrier(qr)
circuit.measure(qr, cr)
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
return circuits
def measure_counts_deterministic(shots, hex_counts=True):
"""Measure test circuits reference counts."""
targets = []
if hex_counts:
# Measure |00> state
targets.append({'0x0': shots})
# Measure |01> state
targets.append({'0x1': shots})
# Measure |10> state
targets.append({'0x2': shots})
# Measure |11> state
targets.append({'0x3': shots})
else:
# Measure |00> state
targets.append({'00': shots})
# Measure |01> state
targets.append({'01': shots})
# Measure |10> state
targets.append({'10': shots})
# Measure |11> state
targets.append({'11': shots})
return targets
def measure_memory_deterministic(shots, hex_counts=True):
"""Measure test circuits reference memory."""
targets = []
if hex_counts:
# Measure |00> state
targets.append(shots * ['0x0'])
# Measure |01> state
targets.append(shots * ['0x1'])
# Measure |10> state
targets.append(shots * ['0x2'])
# Measure |11> state
targets.append(shots * ['0x3'])
else:
# Measure |00> state
targets.append(shots * ['00'])
# Measure |01> state
targets.append(shots * ['01'])
# Measure |10> state
targets.append(shots * ['10'])
# Measure |11> state
targets.append(shots * ['11'])
return targets
def measure_statevector_deterministic():
"""Measure test circuits reference counts."""
targets = []
# Measure |00> state
targets.append(array([1, 0, 0, 0]))
# Measure |01> state
targets.append(array([0, 1, 0, 0]))
# Measure |10> state
targets.append(array([0, 0, 1, 0]))
# Measure |11> state
targets.append(array([0, 0, 0, 1]))
return targets
# ==========================================================================
# Single-qubit measurements with non-deterministic output
# ==========================================================================
def measure_circuits_nondeterministic(allow_sampling=True):
""""Measure test circuits with non-deterministic count output."""
circuits = []
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
# Measure |++> state (sampled)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
circuit.barrier(qr)
circuit.measure(qr, cr)
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
return circuits
def measure_counts_nondeterministic(shots, hex_counts=True):
"""Measure test circuits reference counts."""
targets = []
if hex_counts:
# Measure |++> state
targets.append({'0x0': shots / 4, '0x1': shots / 4,
'0x2': shots / 4, '0x3': shots / 4})
else:
# Measure |++> state
targets.append({'00': shots / 4, '01': shots / 4,
'10': shots / 4, '11': shots / 4})
return targets
# ==========================================================================
# Multi-qubit measurements with deterministic output
# ==========================================================================
def multiqubit_measure_circuits_deterministic(allow_sampling=True):
"""Multi-qubit measure test circuits with deterministic count output."""
circuits = []
def measure_n(num_qubits):
"""Multi-qubit measure instruction."""
return Instruction("measure", num_qubits, num_qubits, [])
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[1])
circuit.barrier(qr)
circuit.append(measure_n(2), [0, 1], [0, 1])
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
# 3-qubit measure |101>
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.x(qr[2])
circuit.barrier(qr)
circuit.append(measure_n(3), [0, 1, 2], [0, 1, 2])
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
# 4-qubit measure |1010>
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[1])
circuit.x(qr[3])
circuit.barrier(qr)
circuit.append(measure_n(4), [0, 1, 2, 3], [0, 1, 2, 3])
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
return circuits
def multiqubit_measure_counts_deterministic(shots, hex_counts=True):
"""Multi-qubit measure test circuits reference counts."""
targets = []
if hex_counts:
# 2-qubit measure |10>
targets.append({'0x2': shots})
# 3-qubit measure |101>
targets.append({'0x5': shots})
# 4-qubit measure |1010>
targets.append({'0xa': shots})
else:
# 2-qubit measure |10>
targets.append({'10': shots})
# 3-qubit measure |101>
targets.append({'101': shots})
# 4-qubit measure |1010>
targets.append({'1010': shots})
return targets
def multiqubit_measure_memory_deterministic(shots, hex_counts=True):
"""Multi-qubit measure test circuits reference memory."""
targets = []
if hex_counts:
# 2-qubit measure |10>
targets.append(shots * ['0x2'])
# 3-qubit measure |101>
targets.append(shots * ['0x5'])
# 4-qubit measure |1010>
targets.append(shots * ['0xa'])
else:
# 2-qubit measure |10>
targets.append(shots * ['10'])
# 3-qubit measure |101>
targets.append(shots * ['101'])
# 4-qubit measure |1010>
targets.append(shots * ['1010'])
return targets
def multiqubit_measure_statevector_deterministic():
"""Multi-qubit measure test circuits reference counts."""
targets = []
# 2-qubit measure |10>
targets.append(array([0, 0, 1, 0]))
# 3-qubit measure |101>
targets.append(array([0, 0, 0, 0, 0, 1, 0, 0]))
# 4-qubit measure |1010>
targets.append(array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]))
return targets
# ==========================================================================
# Multi-qubit measurements with non-deterministic output
# ==========================================================================
def multiqubit_measure_circuits_nondeterministic(allow_sampling=True):
"""Multi-qubit measure test circuits with non-deterministic count output."""
circuits = []
def measure_n(num_qubits):
"""Multi-qubit measure instruction."""
return Instruction("measure", num_qubits, num_qubits, [])
# 2-qubit measure |++>
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.barrier(qr)
circuit.append(measure_n(2), [0, 1], [0, 1])
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
# 3-qubit measure |++0>
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.barrier(qr)
circuit.append(measure_n(3), [0, 1, 2], [0, 1, 2])
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
return circuits
def multiqubit_measure_counts_nondeterministic(shots, hex_counts=True):
"""Multi-qubit measure test circuits reference counts."""
targets = []
if hex_counts:
# 2-qubit measure |++>
targets.append({'0x0': shots / 4, '0x1': shots / 4,
'0x2': shots / 4, '0x3': shots / 4})
# 3-qubit measure |0++>
targets.append({'0x0': shots / 4, '0x1': shots / 4,
'0x2': shots / 4, '0x3': shots / 4})
else:
# 2-qubit measure |++>
targets.append({'00': shots / 4, '01': shots / 4,
'10': shots / 4, '11': shots / 4})
# 3-qubit measure |0++>
targets.append({'000': shots / 4, '001': shots / 4,
'010': shots / 4, '011': shots / 4})
return targets
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# A jupyter notebook is composed by one or more cells.
# There are two main cells: Code and Markdown.
# A code cell is used to write and execute your codes.
# A markdown cell is used to write text descriptions, notes, formulas or include graphics and images.
# On a markdown cell, you can format your content by using Markdown, HTML, or LaTeX codes.
# During our tutorial, you are expected to write only python codes.
# Interested readers may also use markdown cells, but it is not necesary to complete our tutorial.
#
# We explain basic usage of cells in Jupyter notebooks here
#
# This is the first cell in this notebook.
# You can write Python code here,
# and then EXECUTE/RUN it by
# 1) pressing CTRL+ENTER or SHIFT+ENTER
# 2) clicking "Run" on the menu
# here are few lines of python code
print("hello world")
str="*"
for i in range(10):
print(str)
str+="*"
# after executing this cell, the outcomes will immedeately appear after this cell
# you can change the range above and re-run this cell
# This is the second cell in this notebook.
#
# By using menu item "Insert", you can add a new cell before or after the active cell.
# When a cell is selected, you may delete it by using menu item "Edit".
#
# As you may notice, there are other editing options under "Edit",
# for example, copy/cut-paste cells and split-merge cells.
#
%%writefile first.py
print("hello world")
str="*"
for i in range(5):
print(str)
str+="*"
%run first.py
# %load first.py
print("hello world")
str="*"
for i in range(5):
print(str)
str+="*"
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.opflow import I, X, Y, Z
print(I, X, Y, Z)
print(1.5 * I)
print(2.5 * X)
print(X + 2.0 * Y)
print(X^Y^Z)
print(X @ Y @ Z)
print((X + Y) @ (Y + Z))
print((X + Y) ^ (Y + Z))
(I, X)
2.0 * X^Y^Z
print(1.1 * ((1.2 * X)^(Y + (1.3 * Z))))
from qiskit.opflow import (StateFn, Zero, One, Plus, Minus, H,
DictStateFn, VectorStateFn, CircuitStateFn, OperatorStateFn)
print(Zero, One)
print(Plus, Minus)
print(Zero.eval('0'))
print(Zero.eval('1'))
print(One.eval('1'))
print(Plus.eval('0'))
print(Minus.eval('1'))
One.adjoint()
~One
(2.0 + 3.0j) * Zero
print(Zero + One)
import math
v_zero_one = (Zero + One) / math.sqrt(2)
print(v_zero_one)
print(Plus + Minus)
print(~One @ One)
(~One @ One).eval()
(~v_zero_one @ v_zero_one).eval()
(~Minus @ One).eval()
print((~One).compose(One))
(~One).eval(One)
print(Zero^Plus)
print((Zero^Plus).to_circuit_op())
print(600 * ((One^5) + (Zero^5)))
print((One^Zero)^3)
print(((Plus^Minus)^2).to_matrix_op())
print(((Plus^One)^2).to_circuit_op())
print(((Plus^One)^2).to_matrix_op().sample())
print(StateFn({'0':1}))
print(StateFn({'0':1}) == Zero)
print(StateFn([0,1,1,0]))
from qiskit.circuit.library import RealAmplitudes
print(StateFn(RealAmplitudes(2)))
from qiskit.opflow import X, Y, Z, I, CX, T, H, S, PrimitiveOp
X
print(X.eval('0'))
X.eval('0').eval('1')
print(CX)
print(CX.to_matrix().real) # The imaginary part vanishes.
CX.eval('01') # 01 is the one in decimal. We get the first column.
CX.eval('01').eval('11') # This returns element with (zero-based) index (1, 3)
print(X @ One)
(X @ One).eval()
X.eval(One)
print(((~One^2) @ (CX.eval('01'))).eval())
print(((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2)
print((((H^5) @ ((CX^2)^I) @ (I^(CX^2)))**2) @ (Minus^5))
print(((H^I^I)@(X^I^I)@Zero))
print(~One @ Minus)
from qiskit.opflow import ListOp
print((~ListOp([One, Zero]) @ ListOp([One, Zero])))
print((~ListOp([One, Zero]) @ ListOp([One, Zero])).reduce())
print(StateFn(Z).adjoint())
StateFn(Z).adjoint()
print(StateFn(Z).adjoint().eval(Zero))
print(StateFn(Z).adjoint().eval(One))
print(StateFn(Z).adjoint().eval(Plus))
import numpy as np
from qiskit.opflow import I, X, Y, Z, H, CX, Zero, ListOp, PauliExpectation, PauliTrotterEvolution, CircuitSampler, MatrixEvolution, Suzuki
from qiskit.circuit import Parameter
from qiskit import Aer
two_qubit_H2 = (-1.0523732 * I^I) + \
(0.39793742 * I^Z) + \
(-0.3979374 * Z^I) + \
(-0.0112801 * Z^Z) + \
(0.18093119 * X^X)
print(two_qubit_H2)
evo_time = Parameter('θ')
evolution_op = (evo_time*two_qubit_H2).exp_i()
print(evolution_op) # Note, EvolvedOps print as exponentiations
print(repr(evolution_op))
h2_measurement = StateFn(two_qubit_H2).adjoint()
print(h2_measurement)
bell = CX @ (I ^ H) @ Zero
print(bell)
evo_and_meas = h2_measurement @ evolution_op @ bell
print(evo_and_meas)
trotterized_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=1)).convert(evo_and_meas)
# We can also set trotter_mode='suzuki' or leave it empty to default to first order Trotterization.
print(trotterized_op)
bound = trotterized_op.bind_parameters({evo_time: .5})
bound[1].to_circuit().draw()
# Note that XX was the only non-diagonal measurement in our H2 Observable
print(PauliExpectation(group_paulis=False).convert(h2_measurement))
print(PauliExpectation().convert(h2_measurement))
diagonalized_meas_op = PauliExpectation().convert(trotterized_op)
print(diagonalized_meas_op)
evo_time_points = list(range(8))
h2_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points})
h2_trotter_expectations.eval()
sampler = CircuitSampler(backend=Aer.get_backend('aer_simulator'))
# sampler.quantum_instance.run_config.shots = 1000
sampled_trotter_exp_op = sampler.convert(h2_trotter_expectations)
sampled_trotter_energies = sampled_trotter_exp_op.eval()
print('Sampled Trotterized energies:\n {}'.format(np.real(sampled_trotter_energies)))
print('Before:\n')
print(h2_trotter_expectations.reduce()[0][0])
print('\nAfter:\n')
print(sampled_trotter_exp_op[0][0])
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import *
from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
from qiskit.visualization import plot_state_qsphere
def BuildBell(x, y):
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
if x == 1:
U.cz(0, 1)
if y == 1:
U.x(1)
U = U.to_gate()
U.name = 'Build Bell'
#ctl_U = U.control() make it a controlled gate
return U
backend = BasicAer.get_backend('statevector_simulator')
n = 2
#bell state 00
[x, y] = [0, 0]
b00 = QuantumCircuit(n, n)
b00.append(BuildBell(x, y), range(n))
#bell state 01
[x, y] = [0, 1]
b01 = QuantumCircuit(n, n)
b01.append(BuildBell(x, y), range(n))
#bell state 10
[x, y] = [1, 0]
b10 = QuantumCircuit(n, n)
b10.append(BuildBell(x, y), range(n))
#bell state 11
[x, y] = [1, 1]
b11 = QuantumCircuit(n, n)
b11.append(BuildBell(x, y), range(n))
bqs00 = execute(b00, backend).result()
bqs01 = execute(b01, backend).result()
bqs10 = execute(b10, backend).result()
bqs11 = execute(b11, backend).result()
#GENERAL CIRCUIT b_00
bxy = QuantumCircuit(n, n)
bxy.h(0)
bxy.cx(0, 1)
bxy.measure(range(n), range(n))
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(bxy, backend=backend, shots=atp).result()
ans = res.get_counts()
bxy.draw('mpl')
plot_histogram(ans)
plot_state_qsphere(bqs00.get_statevector(b00)) #bell state 00 qsphere
plot_state_qsphere(bqs01.get_statevector(b01)) #bell state 01 qsphere
plot_state_qsphere(bqs10.get_statevector(b10)) #bell state 10 qsphere
plot_state_qsphere(bqs11.get_statevector(b11)) #bell state 11 qsphere
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, assemble, Aer
from qiskit.tools.visualization import plot_histogram
from math import pi
import matplotlib.pyplot as plt
### Conditioned gates: the c_if method
# example: execute X gate if value of classical register is 0
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
qc = QuantumCircuit(q,c)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(c, 0)
qc.draw('mpl')#.show()
# example: perform bit flip on third qubit when measurement of q0 and q1 are both 1
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.barrier()
qc.measure(q,c)
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw('mpl')#.show()
### Iterative Phase Estimation (IPE)
nq = 2
m = 2
q = QuantumRegister(nq, 'q')
c = ClassicalRegister(m, 'c')
qc_S = QuantumCircuit(q,c)
## First iteration
# initialization
qc_S.h(0)
qc_S.x(1)
qc_S.draw('mpl')#.show()
# apply controlled-U gates
cu_circ = QuantumCircuit(2)
cu_circ.cp(pi/2,0,1)
cu_circ.draw('mpl')#.show()
for _ in range(2**(m-1)):
qc_S.cp(pi/2,0,1)
qc_S.draw('mpl')#.show()
# measure in X-basis
def x_measurement(qc, qubit, cbit):
"""Measures 'qubit' in the X-basis, and stores the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, q[0], c[0])
qc_S.draw('mpl')#.show()
## Subsequent iterations
# initialization with reset
qc_S.reset(0)
qc_S.h(0)
qc_S.draw('mpl')#.show()
# phase correction
qc_S.p(-pi/2,0).c_if(c,1)
qc_S.draw('mpl')#.show()
# apply control-U gates and x measurement
for _ in range(2**(m-2)):
qc_S.cp(pi/2,0,1)
x_measurement(qc_S, q[0], c[1])
qc_S.draw('mpl')#.show()
## Execute circuit on simulator
sim = Aer.get_backend('qasm_simulator')
count0 = execute(qc_S, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
plt.tight_layout()
plt.show()
### IPE example with a 2-qubit gate
# initialize circuit with 3 qubits
nq = 3 # number of qubits
m = 3 # number of classical bits
q = QuantumRegister(nq, 'q')
c = ClassicalRegister(m, 'c')
qc = QuantumCircuit(q,c)
## First Step
# initialization
qc.h(0)
qc.x([1,2])
qc.draw('mpl')#.show()
# apply controlled-U gates
cu_circ = QuantumCircuit(nq)
cu_circ.mcp(pi/4,[0,1], 2)
cu_circ.draw('mpl')#.show()
# apply 2^t times MCP(pi/4)
for _ in range(2**(m-1)):
qc.mcp(pi/4,[0,1],2)
qc.draw('mpl')#.show()
# measure in x basis
x_measurement(qc, q[0], c[0])
qc.draw('mpl')#.show()
## Second Step
# initialization with reset
qc.reset(0)
qc.h(0)
qc.draw('mpl')#.show()
# phase correction
qc.p(-pi/2,0).c_if(c,1)
qc.draw('mpl')#.show()
# apply Control-U gates and measure in x basis
for _ in range(2**(m-2)):
qc.mcp(pi/4, [0,1], 2)
x_measurement(qc, q[0], c[1])
qc.draw('mpl')#.show()
## Third Step
# initialization
qc.reset(0)
qc.h(0)
# phase correction
qc.p(-pi/4,0).c_if(c,1)
qc.p(-pi/2,0).c_if(c,2)
qc.p(-3*pi/4,0).c_if(c,3)
# controlled-U operations
for _ in range(2**(m-3)):
qc.mcp(pi/4,[0,1],2)
# X measurement
qc.h(0)
qc.measure(0,2)
qc.draw('mpl').show()
# execute circuit on simulator
count0 = execute(qc, sim).result().get_counts()
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
plt.tight_layout()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Unit tests for conversions between Cirq circuits and Qiskit circuits.
"""
import cirq
import numpy as np
import pytest
import qiskit
from cirq import Circuit, LineQubit, ops, testing
from qiskit import QuantumCircuit
from qiskit.circuit.random import random_circuit
from qbraid.interface import circuits_allclose
from qbraid.programs import load_program
from qbraid.programs.exceptions import QasmError
from qbraid.transpiler.conversions.cirq import cirq_to_qasm2
from qbraid.transpiler.conversions.qasm2 import qasm2_to_cirq
from qbraid.transpiler.conversions.qasm3 import qasm3_to_qiskit
from qbraid.transpiler.conversions.qiskit import qiskit_to_qasm2, qiskit_to_qasm3
from qbraid.transpiler.converter import transpile
from qbraid.transpiler.exceptions import CircuitConversionError
from ..cirq_utils import _equal
def test_bell_state_to_from_circuits():
"""Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit
with a Bell state circuit.
"""
qreg = cirq.LineQubit.range(2)
cirq_circuit = cirq.Circuit([cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])])
qiskit_circuit = transpile(cirq_circuit, "qiskit") # Qiskit from Cirq
circuit_cirq = transpile(qiskit_circuit, "cirq") # Cirq from Qiskit
assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary())
def test_bell_state_to_qiskit():
"""Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit
with a Bell state circuit."""
qreg = LineQubit.range(2)
cirq_circuit = Circuit([ops.H.on(qreg[0]), ops.CNOT.on(qreg[0], qreg[1])])
qiskit_circuit = transpile(cirq_circuit, "qiskit")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
@pytest.mark.parametrize("num_qubits", [1, 2, 3, 4, 5])
def test_random_circuit_to_qiskit(num_qubits):
"""Tests converting random Cirq circuits to Qiskit circuits."""
for _ in range(10):
cirq_circuit = testing.random_circuit(
qubits=num_qubits,
n_moments=np.random.randint(1, 6),
op_density=1,
random_state=np.random.randint(1, 10),
)
qiskit_circuit = transpile(cirq_circuit, "qiskit")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_bell_state_to_from_qasm():
"""Tests cirq.Circuit --> QASM string --> cirq.Circuit
with a Bell state circuit.
"""
qreg = cirq.LineQubit.range(2)
cirq_circuit = cirq.Circuit([cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])])
qasm = cirq_to_qasm2(cirq_circuit) # Qasm from Cirq
circuit_cirq = qasm2_to_cirq(qasm)
assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary())
def test_random_circuit_to_from_circuits():
"""Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit
with a random two-qubit circuit.
"""
cirq_circuit = cirq.testing.random_circuit(
qubits=2, n_moments=10, op_density=0.99, random_state=1
)
qiskit_circuit = transpile(cirq_circuit, "qiskit")
circuit_cirq = transpile(qiskit_circuit, "cirq")
assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary())
def test_random_circuit_to_from_qasm():
"""Tests cirq.Circuit --> QASM string --> cirq.Circuit
with a random one-qubit circuit.
"""
circuit_0 = cirq.testing.random_circuit(qubits=2, n_moments=10, op_density=0.99, random_state=2)
qasm = cirq_to_qasm2(circuit_0)
circuit_1 = qasm2_to_cirq(qasm)
u_0 = circuit_0.unitary()
u_1 = circuit_1.unitary()
assert cirq.equal_up_to_global_phase(u_0, u_1)
@pytest.mark.parametrize("as_qasm", (True, False))
def test_convert_with_barrier(as_qasm):
"""Tests converting a Qiskit circuit with a barrier to a Cirq circuit."""
n = 5
qiskit_circuit = qiskit.QuantumCircuit(qiskit.QuantumRegister(n))
qiskit_circuit.barrier()
if as_qasm:
cirq_circuit = qasm2_to_cirq(qiskit_to_qasm2(qiskit_circuit))
else:
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert _equal(cirq_circuit, cirq.Circuit())
@pytest.mark.parametrize("as_qasm", (True, False))
def test_convert_with_multiple_barriers(as_qasm):
"""Tests converting a Qiskit circuit with barriers to a Cirq circuit."""
n = 1
num_ops = 10
qreg = qiskit.QuantumRegister(n)
qiskit_circuit = qiskit.QuantumCircuit(qreg)
for _ in range(num_ops):
qiskit_circuit.h(qreg)
qiskit_circuit.barrier()
if as_qasm:
cirq_circuit = qasm2_to_cirq(qiskit_to_qasm2(qiskit_circuit))
else:
cirq_circuit = transpile(qiskit_circuit, "cirq")
qbit = cirq.LineQubit(0)
correct = cirq.Circuit(cirq.ops.H.on(qbit) for _ in range(num_ops))
assert _equal(cirq_circuit, correct)
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_bell_state_from_qiskit():
"""Tests qiskit.QuantumCircuit --> cirq.Circuit
with a Bell state circuit.
"""
qiskit_circuit = QuantumCircuit(2)
qiskit_circuit.h(0)
qiskit_circuit.cx(0, 1)
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_common_gates_from_qiskit():
"""Tests converting standard gates from Qiskit to Cirq."""
qiskit_circuit = QuantumCircuit(4)
qiskit_circuit.h([0, 1, 2, 3])
qiskit_circuit.x([0, 1])
qiskit_circuit.y(2)
qiskit_circuit.z(3)
qiskit_circuit.s(0)
qiskit_circuit.sdg(1)
qiskit_circuit.t(2)
qiskit_circuit.tdg(3)
qiskit_circuit.rx(np.pi / 4, 0)
qiskit_circuit.ry(np.pi / 2, 1)
qiskit_circuit.rz(3 * np.pi / 4, 2)
qiskit_circuit.p(np.pi / 8, 3)
qiskit_circuit.sx(0)
qiskit_circuit.sxdg(1)
qiskit_circuit.iswap(2, 3)
qiskit_circuit.swap([0, 1], [2, 3])
qiskit_circuit.cx(0, 1)
qiskit_circuit.cp(np.pi / 4, 2, 3)
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
@pytest.mark.parametrize("qubits", ([0, 1], [1, 0]))
def test_crz_gate_from_qiskit(qubits):
"""Tests converting controlled Rz gate from Qiskit to Cirq."""
qiskit_circuit = QuantumCircuit(2)
qiskit_circuit.crz(np.pi / 4, *qubits)
cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True)
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
@pytest.mark.parametrize("qubits", ([0, 1], [1, 0]))
@pytest.mark.parametrize("theta", (0, 2 * np.pi, np.pi / 2, np.pi / 4))
def test_rzz_gate_from_qiskit(qubits, theta):
"""Tests converting Rzz gate from Qiskit to Cirq."""
qiskit_circuit = QuantumCircuit(2)
qiskit_circuit.rzz(theta, *qubits)
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_iswap_gate_from_qiskit():
"""Tests converting iSwap gate from Qiskit to Cirq."""
qiskit_circuit = QuantumCircuit(2)
qiskit_circuit.h([0, 1])
qiskit_circuit.iswap(0, 1)
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_qiskit_roundtrip():
"""Test converting qiskit gates that previously failed qiskit roundtrip test."""
qiskit_circuit = QuantumCircuit(3)
qiskit_circuit.ccz(0, 1, 2)
qiskit_circuit.ecr(1, 2)
qiskit_circuit.cs(2, 0)
cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True)
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=False)
def test_qiskit_roundtrip_noncontig():
"""Test converting gates that previously failed qiskit roundtrip test
with non-contiguous qubits."""
qiskit_circuit = QuantumCircuit(4)
qiskit_circuit.ccz(0, 1, 2)
qiskit_circuit.ecr(1, 2)
qiskit_circuit.cs(2, 0)
cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True)
qprogram = load_program(cirq_circuit)
qprogram.remove_idle_qubits()
qiskit_contig = qprogram.program
assert circuits_allclose(qiskit_contig, cirq_circuit, strict_gphase=False)
def test_100_random_qiskit():
"""Test converting 100 random qiskit circuits to cirq."""
for _ in range(100):
qiskit_circuit = random_circuit(4, 1)
cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True)
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=False)
def test_qiskit_to_from_qasm3():
"""Test converting qiskit circuit to/from OpenQASM 3.0 string"""
circuit_in = QuantumCircuit(2)
circuit_in.h(0)
circuit_in.cx(0, 1)
qasm3_str = qiskit_to_qasm3(circuit_in)
circuit_out = qasm3_to_qiskit(qasm3_str)
assert circuits_allclose(circuit_in, circuit_out, strict_gphase=True)
def test_raise_circuit_conversion_error():
"""Tests raising error for unsupported gates."""
with pytest.raises(CircuitConversionError):
probs = np.random.uniform(low=0, high=0.5)
cirq_circuit = Circuit(ops.PhaseDampingChannel(probs).on(*LineQubit.range(1)))
transpile(cirq_circuit, "qiskit")
def test_raise_qasm_error():
"""Test raising error for unsupported gates."""
with pytest.raises(QasmError):
qiskit_circuit = QuantumCircuit(1)
qiskit_circuit.delay(300, 0)
qasm2 = qiskit_to_qasm2(qiskit_circuit)
_ = qasm2_to_cirq(qasm2)
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, QuantumRegister
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
#you can also use
#qc.measure_all() OR
#qc.measure([0], [0])
qc.draw('mpl')
sim = Aer.get_backend('qasm_simulator')
job = execute(qc, sim, shots=1024)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
#QASM SIMULATOR NEEDS MEASUREMENT AND COUNTS AS INPUT NOT STATE
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0], q[1], q[2])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cswap(q[0], q[1], q[2])
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/ohadlev77/sat-circuits-engine
|
ohadlev77
|
# Copyright 2022-2023 Ohad Lev.
# 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,
# or in the root directory of this package("LICENSE.txt").
# 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.
"""
SATCircuit class.
"""
from typing import Optional
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from sat_circuits_engine.circuit.grover_constraints_operator import GroverConstraintsOperator
from sat_circuits_engine.circuit.grover_diffuser import GroverDiffuser
class SATCircuit(QuantumCircuit):
"""
Assembles an overall circuit for the given SAT problem from the building blocks:
- Input state preparation.
- Grover's iterator - consists of:
* `GroverConstraintsOperator` object (Grover's operator).
* `GroverDiffuser` object (Grover's diffuser).
- Measurement.
"""
def __init__(
self,
num_input_qubits: int,
grover_constraints_operator: GroverConstraintsOperator,
iterations: Optional[int] = None,
insert_barriers: Optional[bool] = True,
) -> None:
"""
Args:
num_input_qubits (int): the number of qubits in the input register.
grover_constraints_operator (GroverConstraintsOperator): a child object of `QuantumCircuit`
which is Grover's operator implementation for the specific constraints entered by the user.
iterations (Optional[int] = None): number of required iterations over Grover's iterator.
# If `None` (default) - the number of iterations is unknown and a dynamic
circuit approach should be applied (TODO THIS IS A FUTURE FEATURE).
insert_barriers (Optional[bool] = True): if True, barriers will be inserted
to separate between segments and iterations.
"""
self.num_input_qubits = num_input_qubits
self.operator = grover_constraints_operator
self.iterations = iterations
self.insert_barriers = insert_barriers
# Total number of auxiliary qubits (of all kinds)
self.total_aux_width = (
self.operator.comparison_aux_width
+ self.operator.left_aux_width
+ self.operator.right_aux_width
)
self.input_reg = QuantumRegister(num_input_qubits, "input_reg")
self.aux_reg = QuantumRegister(self.total_aux_width, "aux_reg")
self.out_reg = QuantumRegister(self.operator.out_qubits_amount, "out_reg")
self.ancilla = QuantumRegister(1, "ancilla")
self.results = ClassicalRegister(num_input_qubits, "results")
# Input, auxiliary and out Qubit objects stacked in one list
self.input_aux_out_qubits = self.input_reg[:] + self.aux_reg[:] + self.out_reg[:]
diffuser_ancillas = len(self.input_aux_out_qubits) - num_input_qubits
self.diffuser = GroverDiffuser(
num_input_qubits=num_input_qubits, num_ancilla_qubits=diffuser_ancillas
)
# No `iterations` specified = dynamic circuit
# TODO this feature is not supported yet and shouldn't be used
if iterations is None:
# Register to apply weak measurements with
self.probe = QuantumRegister(1, "probe")
self.probe_result = ClassicalRegister(1, "probe_result")
super().__init__(
self.input_reg,
self.aux_reg,
self.out_reg,
self.ancilla,
self.probe,
self.results,
self.probe_result,
)
# Initializing input state
self.set_init_state()
# Applying dynamic while loop over Grover's iterator coditioned by `probe`
self.dynamic_loop()
# `iterations` specified = static circuit
else:
super().__init__(
self.input_reg,
self.aux_reg,
self.out_reg,
self.ancilla,
self.results,
)
# Initializing input state
self.set_init_state()
# Appending `iterations` iterations over Grover's iterator
for _ in range(iterations):
self.add_iteration()
def dynamic_loop(self) -> None:
"""
TODO this feature is not supported yet and shouldn't be used.
"""
condition = (self.probe_result, 0)
qargs_with_probe = self.input_aux_out_qubits[:] + self.probe[:]
with self.while_loop(condition):
self.append(self.diffuser, qargs=self.input_aux_out_qubits)
self.add_iteration()
self.append(self.operator, qargs=qargs_with_probe)
self.measure(self.probe, self.probe_result)
def set_init_state(self) -> None:
"""
Setting the input register to 2^(self.num_input_qubits) = N equal superposition of states,
and the ancilla to an eigenstate of the NOT gate: |->.
"""
self.h(self.input_reg)
self.x(self.ancilla)
self.h(self.ancilla)
if self.insert_barriers:
self.barrier()
def add_iteration(self) -> None:
"""
Appends an iteration over Grover's iterator (`operator` + `diffuser`) to `self`.
"""
qargs_with_ancilla = self.input_aux_out_qubits[:] + self.ancilla[:]
self.append(self.operator, qargs=qargs_with_ancilla)
self.append(self.diffuser, qargs=self.input_aux_out_qubits)
if self.insert_barriers:
self.barrier()
def add_input_reg_measurement(self) -> None:
"""
Appends a final measurement of the input register to `self`.
"""
self.measure(self.input_reg, self.results)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Kraus, SuperOp
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,
pauli_error, depolarizing_error, thermal_relaxation_error)
# Construct a 1-qubit bit-flip and phase-flip errors
p_error = 0.05
bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])
phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])
print(bit_flip)
print(phase_flip)
# Compose two bit-flip and phase-flip errors
bitphase_flip = bit_flip.compose(phase_flip)
print(bitphase_flip)
# Tensor product two bit-flip and phase-flip errors with
# bit-flip on qubit-0, phase-flip on qubit-1
error2 = phase_flip.tensor(bit_flip)
print(error2)
# Convert to Kraus operator
bit_flip_kraus = Kraus(bit_flip)
print(bit_flip_kraus)
# Convert to Superoperator
phase_flip_sop = SuperOp(phase_flip)
print(phase_flip_sop)
# Convert back to a quantum error
print(QuantumError(bit_flip_kraus))
# Check conversion is equivalent to original error
QuantumError(bit_flip_kraus) == bit_flip
# Measurement miss-assignement probabilities
p0given1 = 0.1
p1given0 = 0.05
ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]])
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates
error = depolarizing_error(0.05, 1)
noise_model.add_all_qubit_quantum_error(error, ['u1', 'u2', 'u3'])
# Print noise model info
print(noise_model)
# Create an empty noise model
noise_model = NoiseModel()
# Add depolarizing error to all single qubit u1, u2, u3 gates on qubit 0 only
error = depolarizing_error(0.05, 1)
noise_model.add_quantum_error(error, ['u1', 'u2', 'u3'], [0])
# Print noise model info
print(noise_model)
# System Specification
n_qubits = 4
circ = QuantumCircuit(n_qubits)
# Test Circuit
circ.h(0)
for qubit in range(n_qubits - 1):
circ.cx(qubit, qubit + 1)
circ.measure_all()
print(circ)
# Ideal simulator and execution
sim_ideal = AerSimulator()
result_ideal = sim_ideal.run(circ).result()
plot_histogram(result_ideal.get_counts(0))
# Example error probabilities
p_reset = 0.03
p_meas = 0.1
p_gate1 = 0.05
# QuantumError objects
error_reset = pauli_error([('X', p_reset), ('I', 1 - p_reset)])
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = pauli_error([('X',p_gate1), ('I', 1 - p_gate1)])
error_gate2 = error_gate1.tensor(error_gate1)
# Add errors to noise model
noise_bit_flip = NoiseModel()
noise_bit_flip.add_all_qubit_quantum_error(error_reset, "reset")
noise_bit_flip.add_all_qubit_quantum_error(error_meas, "measure")
noise_bit_flip.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
noise_bit_flip.add_all_qubit_quantum_error(error_gate2, ["cx"])
print(noise_bit_flip)
# Create noisy simulator backend
sim_noise = AerSimulator(noise_model=noise_bit_flip)
# Transpile circuit for noisy basis gates
circ_tnoise = transpile(circ, sim_noise)
# Run and get counts
result_bit_flip = sim_noise.run(circ_tnoise).result()
counts_bit_flip = result_bit_flip.get_counts(0)
# Plot noisy output
plot_histogram(counts_bit_flip)
# T1 and T2 values for qubits 0-3
T1s = np.random.normal(50e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
T2s = np.random.normal(70e3, 10e3, 4) # Sampled from normal distribution mean 50 microsec
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(4)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
# Run the noisy simulation
sim_thermal = AerSimulator(noise_model=noise_thermal)
# Transpile circuit for noisy basis gates
circ_tthermal = transpile(circ, sim_thermal)
# Run and get counts
result_thermal = sim_thermal.run(circ_tthermal).result()
counts_thermal = result_thermal.get_counts(0)
# Plot noisy output
plot_histogram(counts_thermal)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
qreg1 = QuantumRegister(2) # quantum register with 2 qubits
creg1 = ClassicalRegister(2) # classical register with 2 bits
mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers
# the first qubit is in |0>
# set the second qubit to |1>
mycircuit1.x(qreg1[1]) # apply x-gate (NOT operator)
# apply Hadamard to both qubits.
mycircuit1.h(qreg1[0])
mycircuit1.h(qreg1[1])
# apply CNOT operator, where the controller qubit is the first qubit and the target qubit is the second qubit.
mycircuit1.cx(qreg1[0],qreg1[1])
# apply Hadamard to both qubits.
mycircuit1.h(qreg1[0])
mycircuit1.h(qreg1[1])
# measure both qubits
mycircuit1.measure(qreg1,creg1)
# execute the circuit 100 times in the local simulator
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit1)
# print the reverse of the outcome
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print("We start in quantum state 01, and",reverse_outcome,"is observed",counts[outcome],"times")
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# Create a circuit with 7 qubits.
n = 7
qreg2 = QuantumRegister(n) # quantum register with 7 qubits
creg2 = ClassicalRegister(n) # classical register with 7 bits
mycircuit2 = QuantumCircuit(qreg2,creg2) # quantum circuit with quantum and classical registers
# the first six qubits are already in |0>
# set the last qubit to |1>
mycircuit2.x(qreg2[n-1]) # apply x-gate (NOT operator)
# apply Hadamard to all qubits.
for i in range(n):
mycircuit2.h(qreg2[i])
# apply CNOT operator (first-qubit,last-qubit)
# apply CNOT operator (fourth-qubit,last-qubit)
# apply CNOT operator (fifth-qubit,last-qubit)
mycircuit2.cx(qreg2[0],qreg2[n-1])
mycircuit2.cx(qreg2[3],qreg2[n-1])
mycircuit2.cx(qreg2[4],qreg2[n-1])
# apply Hadamard to all qubits.
for i in range(n):
mycircuit2.h(qreg2[i])
# measure all qubits
mycircuit2.measure(qreg2,creg2)
# execute the circuit 100 times in the local simulator
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(mycircuit2)
# print the reverse of the outcome
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
for i in range(len(reverse_outcome)):
print("the final value of the qubit nr.",(i+1),"is",reverse_outcome[i])
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
### removed x gate ###
pass
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/jvscursulim/qamp_fall22_project
|
jvscursulim
|
import numpy as np
from frqi import FRQI
from qiskit import execute
from qiskit.providers.aer.backends import AerSimulator
from skimage import data
from skimage.transform import resize
class TestFRQI:
GATE_SET = {"h", "x", "measure", "barrier", "ccry"}
SHOTS = 8192
BACKEND = AerSimulator()
FRQI = FRQI()
IMAGE1 = np.array([[0, 0], [0, 0]])
IMAGE2 = np.array([[1, 1], [1, 1]])
IMAGE3 = np.array([[0.5, 0.5], [0.5, 0.5]])
ASTRONAUT = resize(data.astronaut(), (2, 2))
def test_result_image1(self):
expected_keys = ["0 00", "0 01", "0 10", "0 11"]
qc = self.FRQI.image_quantum_circuit(image=self.IMAGE1, measurements=True)
counts = (
execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS)
.result()
.get_counts()
)
result = [int(key in expected_keys) for key, _ in counts.items()]
true_list = np.ones(len(expected_keys))
assert np.allclose(result, true_list)
def test_result_image2(self):
expected_keys = ["1 00", "1 01", "1 10", "1 11"]
qc = self.FRQI.image_quantum_circuit(image=self.IMAGE2, measurements=True)
counts = (
execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS)
.result()
.get_counts()
)
result = [int(key in expected_keys) for key, _ in counts.items()]
true_list = np.ones(len(expected_keys))
assert np.allclose(result, true_list)
def test_result_image3(self):
expected_keys = ["0 00", "0 01", "0 10", "0 11", "1 00", "1 01", "1 10", "1 11"]
qc = self.FRQI.image_quantum_circuit(image=self.IMAGE3, measurements=True)
counts = (
execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS)
.result()
.get_counts()
)
result = [int(key in expected_keys) for key, _ in counts.items()]
true_list = np.ones(len(expected_keys))
assert np.allclose(result, true_list)
def test_result_rgb_image(self):
expected_keys = [
"0 0 0 00",
"0 0 0 01",
"0 0 0 10",
"0 0 0 11",
"0 0 1 00",
"0 0 1 01",
"0 0 1 10",
"0 0 1 11",
"0 1 0 00",
"0 1 0 01",
"0 1 0 10",
"0 1 0 11",
"0 1 1 00",
"0 1 1 01",
"0 1 1 10",
"0 1 1 11",
"1 0 0 00",
"1 0 0 01",
"1 0 0 10",
"1 0 0 11",
"1 0 1 00",
"1 0 1 01",
"1 0 1 10",
"1 0 1 11",
"1 1 0 00",
"1 1 0 01",
"1 1 0 10",
"1 1 0 11",
"1 1 1 00",
"1 1 1 01",
"1 1 1 10",
"1 1 1 11",
]
qc = self.FRQI.image_quantum_circuit(image=self.ASTRONAUT, measurements=True)
counts = (
execute(experiments=qc, backend=self.BACKEND, shots=self.SHOTS)
.result()
.get_counts()
)
result = [int(key in expected_keys) for key, _ in counts.items()]
true_list = np.ones(len(expected_keys))
assert np.allclose(result, true_list)
def test_image_qc_gates(self):
qc = self.FRQI.image_quantum_circuit(image=self.IMAGE1, measurements=True)
qc_rgb = self.FRQI.image_quantum_circuit(
image=self.ASTRONAUT, measurements=True
)
circuit_gates = list(qc.count_ops())
result_test_gates = [gate in self.GATE_SET for gate in circuit_gates]
circuit_gates_rgb = list(qc_rgb.count_ops())
result_test_gates_rgb = [gate in self.GATE_SET for gate in circuit_gates_rgb]
gates_true_list = np.ones(len(result_test_gates))
assert np.allclose(result_test_gates, gates_true_list)
assert np.allclose(result_test_gates_rgb, gates_true_list)
def test_image_qc_gate_count(self):
qc = self.FRQI.image_quantum_circuit(image=self.IMAGE1, measurements=True)
qc_rgb = self.FRQI.image_quantum_circuit(
image=self.ASTRONAUT, measurements=True
)
qc_gates_dict = dict(qc.count_ops())
del qc_gates_dict["barrier"]
qc_gates_dict_rgb = dict(qc_rgb.count_ops())
del qc_gates_dict_rgb["barrier"]
aux_bin_list = [
bin(i)[2:] for i in range(self.IMAGE1.shape[0] * self.IMAGE1.shape[1])
]
aux_len_bin_list = [len(binary) for binary in aux_bin_list]
max_length = max(aux_len_bin_list)
binary_list = []
for bnum in aux_bin_list:
if len(bnum) < max_length:
new_binary = ""
for _ in range(max_length - len(bnum)):
new_binary += "0"
new_binary += bnum
binary_list.append(new_binary)
else:
binary_list.append(bnum)
hadamard_count = qc.qregs[0].size
measure_count = qc.cregs[0].size + qc.cregs[1].size
mcry_count = 2 * qc.qregs[0].size
x_count = np.array(
[2 * str.count(bnumber, "0") for bnumber in binary_list]
).sum()
qc_count_gate_list = [
qc_gates_dict["h"],
qc_gates_dict["measure"],
qc_gates_dict["x"],
qc_gates_dict["ccry"],
]
qc_rgb_count_gate_list = [
qc_gates_dict_rgb["h"],
qc_gates_dict_rgb["measure"],
qc_gates_dict_rgb["x"],
qc_gates_dict_rgb["ccry"],
]
count_gate_list = [hadamard_count, measure_count, x_count, mcry_count]
count_gate_list_rgb = [
hadamard_count,
measure_count + 2,
3 * x_count,
3 * mcry_count,
]
assert np.allclose(qc_count_gate_list, count_gate_list)
assert np.allclose(qc_rgb_count_gate_list, count_gate_list_rgb)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
with pulse.build(name='my_example') as my_program:
# Add instructions here
pass
my_program
from qiskit.pulse import DriveChannel
channel = DriveChannel(0)
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend=backend, name='backend_aware') as backend_aware_program:
channel = pulse.drive_channel(0)
print(pulse.num_qubits())
# Raises an error as backend only has 5 qubits
#pulse.drive_channel(100)
with pulse.build(backend) as delay_5dt:
pulse.delay(5, channel)
from qiskit.pulse import library
amp = 1
sigma = 10
num_samples = 128
gaus = pulse.library.Gaussian(num_samples, amp, sigma,
name="Parametric Gaus")
gaus.draw()
import numpy as np
times = np.arange(num_samples)
gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2))
gaus = library.Waveform(gaussian_samples, name="WF Gaus")
gaus.draw()
gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus")
gaus.draw()
with pulse.build() as schedule:
pulse.play(gaus, channel)
schedule.draw()
with pulse.build() as schedule:
pulse.play([0.001*i for i in range(160)], channel)
schedule.draw()
with pulse.build(backend) as schedule:
pulse.set_frequency(4.5e9, channel)
with pulse.build(backend) as schedule:
pulse.shift_phase(np.pi, channel)
from qiskit.pulse import Acquire, AcquireChannel, MemorySlot
with pulse.build(backend) as schedule:
pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0))
with pulse.build(backend, name='Left align example') as program:
with pulse.align_left():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Right align example') as program:
with pulse.align_right():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
gaussian_pulse = library.gaussian(100, 0.5, 20)
with pulse.align_equispaced(2*gaussian_pulse.duration):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
with pulse.align_sequential():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Offset example') as program:
with pulse.phase_offset(3.14, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
with pulse.frequency_offset(10e6, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
program.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Alice-Bob-SW/emulation-examples
|
Alice-Bob-SW
|
from matplotlib import pyplot as plt
import numpy as np
import scipy as sp
from tqdm.notebook import tqdm
import warnings
# set default plot parameters
plt.rcParams.update({
'figure.facecolor': 'white',
'axes.facecolor': 'white',
'font.family': 'serif',
'font.size': 16,
'figure.dpi': 72.0,
'xtick.direction': 'in',
'ytick.direction': 'in',
'xtick.major.size': 5.0,
'xtick.minor.size': 2.5,
'ytick.major.size': 5.0,
'ytick.minor.size': 2.5,
'xtick.minor.visible': True,
'ytick.minor.visible': True,
'axes.grid': True,
'axes.titlesize': 'larger',
'axes.labelsize': 'larger',
'legend.fontsize': 'larger',
'grid.color': 'gray',
'grid.linestyle': '--',
'grid.alpha': 0.3,
'lines.linewidth': 1.0,
'figure.figsize': (16, 8)
})
def fitted_curve(t, T, a, b):
return a * np.exp(- t / T) + b
def fit_typical_time(delay_durations, probs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
opt, _ = sp.optimize.curve_fit(
fitted_curve, delay_durations, probs,
p0=[np.median(delay_durations), probs[0] - probs[-1], probs[-1]],
method='trf'
)
return opt
from qiskit_alice_bob_provider.local.provider import AliceBobLocalProvider
provider = AliceBobLocalProvider()
provider.backends()
backend = provider.get_backend('EMU:1Q:LESCANNE_2020')
from qiskit import QuantumCircuit, execute
def build_bit_flip_circuit(delay_duration_us: float) -> QuantumCircuit:
circ = QuantumCircuit(1, 1)
circ.reset(0)
circ.delay(delay_duration_us, 0, unit='us')
circ.measure(0, 0)
return circ
circ = build_bit_flip_circuit(10)
circ.draw('mpl')
nbars = range(1, 8)
delay_durations_us = np.logspace(1, 4, 10)
shots = 10000
tbf_fitted = []
for nbar in tqdm(nbars):
jobs = []
backend = provider.get_backend('EMU:1Q:LESCANNE_2020', average_nb_photons=nbar)
for delay_duration_us in delay_durations_us:
circ = build_bit_flip_circuit(delay_duration_us)
jobs.append(execute(circ, backend, shots=shots))
results = [job.result() for job in jobs]
flip_fractions = [r.get_counts().get('1', 0) / shots for r in results]
Tbf, a, b = fit_typical_time(delay_durations_us, flip_fractions)
tbf_fitted.append(Tbf)
plt.figure()
plt.title('$T_{bf}=f(\\bar{n})$')
plt.xlabel('$\\bar{n} = |\\alpha|^2$ (number of photons)')
plt.ylabel('$T_{bf}$ [$\mu s$]')
plt.plot([1, 3.5], [3.1e1, 1.2e3], c='k', lw=2, label='x 4.2 per photon')
plt.plot([2.4, 7.1], [1e3, 1e3], c='k', ls='--', lw=2, label='Saturation at 1ms')
plt.scatter(nbars, tbf_fitted, facecolors='none', edgecolors='tab:blue', s=100, lw=3, label='Simulation results')
plt.legend(loc='lower right')
plt.semilogy()
plt.show()
def build_phase_flip_circuit(delay_duration_us: float) -> QuantumCircuit:
circ = QuantumCircuit(1, 1)
circ.initialize('+')
circ.delay(delay_duration_us, 0, unit='us')
circ.measure_x(0, 0)
return circ
circ = build_phase_flip_circuit(10)
circ.draw('mpl')
nbars = range(1, 8)
delay_durations_us = np.logspace(-2, 2, 10)
shots = 10000
tpf_fitted = []
for nbar in tqdm(nbars):
jobs = []
backend = provider.get_backend('EMU:1Q:LESCANNE_2020', average_nb_photons=nbar)
for delay_duration_us in delay_durations_us:
circ = build_phase_flip_circuit(delay_duration_us)
jobs.append(execute(circ, backend, shots=shots))
results = [job.result() for job in jobs]
flip_fractions = [r.get_counts().get('1', 0) / shots for r in results]
Tpf, a, b = fit_typical_time(delay_durations_us, flip_fractions)
tpf_fitted.append(Tpf)
plt.figure()
plt.title('$\Gamma_{pf}=f(\\bar{n})$')
plt.plot([1, 7], [0.17, 1.01], c='k', lw=2, label='Linear increase of phase-flip rate')
plt.scatter(nbars, 0.5 / np.array(tpf_fitted), facecolors='none', edgecolors='tab:blue', s=100, lw=3, label='Simulation results')
plt.xlabel('$\\bar{n} = |\\alpha|^2$ (number of photons)')
plt.ylabel('$\Gamma_{pf}/2\pi$ [MHz]')
plt.legend(loc='lower right')
plt.show()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors)
print("created zne_qcs (length:", len(zne_qcs), ")")
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
jobs.append(job)
# QREM
shots = 1 << 13
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Statevector
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.estimation import EuropeanCallPricing
from qiskit_finance.circuit.library import NormalDistribution
# Set upper and lower data values
bounds = np.array([0.0, 7.0])
# Set number of qubits used in the uncertainty model
num_qubits = 3
# Load the trained circuit parameters
g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]
# Set an initial state for the generator circuit
init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds)
# construct the variational form
var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1)
# keep a list of the parameters so we can associate them to the list of numerical values
# (otherwise we need a dictionary)
theta = var_form.ordered_parameters
# compose the generator circuit, this is the circuit loading the uncertainty model
g_circuit = init_dist.compose(var_form)
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2
# set the approximation scaling for the payoff function
c_approx = 0.25
# Evaluate trained probability distribution
values = [
bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits)
]
uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params)))
amplitudes = Statevector.from_instruction(uncertainty_model).data
x = np.array(values)
y = np.abs(amplitudes) ** 2
# Sample from target probability distribution
N = 100000
log_normal = np.random.lognormal(mean=1, sigma=1, size=N)
log_normal = np.round(log_normal)
log_normal = log_normal[log_normal <= 7]
log_normal_samples = []
for i in range(8):
log_normal_samples += [np.sum(log_normal == i)]
log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples))
# Plot distributions
plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue")
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.plot(
log_normal_samples,
"-o",
color="deepskyblue",
label="target distribution",
linewidth=4,
markersize=12,
)
plt.legend(loc="best")
plt.show()
# Evaluate payoff for different distributions
payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5])
ep = np.dot(log_normal_samples, payoff)
print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep)
ep_trained = np.dot(y, payoff)
print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained)
# Plot exact payoff function (evaluated on the grid of the trained uncertainty model)
x = np.array(values)
y_strike = np.maximum(0, x - strike_price)
plt.plot(x, y_strike, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# construct circuit for payoff function
european_call_pricing = EuropeanCallPricing(
num_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % ep_trained)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
#Program 1.1 The first quantum program
from qiskit import QuantumCircuit
print("Hello, Qubit!")
qc = QuantumCircuit(1,1)
qc.measure([0], [0])
print("This is a quantum circuit of 1 qubit and 1 bit:")
qc.draw('mpl')
#Program 1.2 Design a quantum circuit with 5 qubits and 3 classical bits
from qiskit import QuantumCircuit
print("This is a quantum circuit of 5 qubits and 2 bits:")
qc = QuantumCircuit(5, 2)
qc.measure([1,3], [0,1])
qc.draw('mpl')
#Program 1.3 Name and label quantum bits and classical bits
from qiskit import QuantumRegister,ClassicalRegister,QuantumCircuit
qrx = QuantumRegister(3,'x')
qry = QuantumRegister(2,'y')
qrz = QuantumRegister(1,'z')
cr = ClassicalRegister(4,'c')
qc = QuantumCircuit(qrx,qry,qrz,cr)
qc.measure([qrx[1],qrx[2]], [cr[0],cr[1]])
qc.measure([4,5], [2,3])
qc.draw('mpl')
#Program 1.4 Transpile and execute quantum circuit on simulator
from qiskit import QuantumCircuit, transpile, execute
from qiskit.providers.aer import AerSimulator
sim = AerSimulator()
qc = QuantumCircuit(1, 1)
qc.measure([0], [0])
print(qc)
cqc = transpile(qc, sim)
job=execute(cqc, backend=sim, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",counts)
#Program 1.5 Execute quantum circuit (program) on simulator
from qiskit import QuantumCircuit, execute
from qiskit.providers.aer import AerSimulator
sim = AerSimulator()
qc = QuantumCircuit(1, 1)
qc.measure([0], [0])
print(qc)
job=execute(qc, backend=sim, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",counts)
#Program 1.6 Execute quantum circuit (program) on least busy quantum computer
from qiskit import QuantumCircuit, IBMQ, execute
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
qc = QuantumCircuit(1, 1)
qc.measure([0], [0])
print(qc)
IBMQ.save_account('your_token',overwrite=True)
IBMQ.load_account()
provider=IBMQ.get_provider(group='open')
print(provider)
qcomp = least_busy(provider.backends(simulator=False))
print("The least busy quantum computer is:",qcomp)
job=execute(qc, backend=qcomp, shots=1000)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",counts)
#Program 1.7 Execute quantum circuit (program) on proper quantum computer
from qiskit import QuantumCircuit, IBMQ, execute
from qiskit.tools.monitor import job_monitor
qc = QuantumCircuit(1, 1)
qc.measure([0], [0])
print(qc)
#IBMQ.save_account('......',overwrite=True)
#IBMQ.load_account()
provider = IBMQ.get_provider(group='open')
qcomp = provider.get_backend('ibmq_lima')
job=execute(qc, backend=qcomp, shots=1000)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/prototype-qrao
|
qiskit-community
|
%matplotlib inline
import numpy as np
import networkx as nx
from tqdm.notebook import tqdm
from docplex.mp.model import Model
from qiskit_optimization.translators import from_docplex_mp
from qrao.encoding import QuantumRandomAccessEncoding, EncodingCommutationVerifier
num_nodes = 6
elist = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0), (0, 3), (1, 4), (2, 4)]
edges = np.zeros((num_nodes, num_nodes))
for i, j in elist:
edges[i, j] = (i + 1) * (j + 2)
mod = Model("maxcut")
nodes = list(range(num_nodes))
var = [mod.binary_var(name="x" + str(i)) for i in nodes]
mod.maximize(
mod.sum(
edges[i, j] * (1 - (2 * var[i] - 1) * (2 * var[j] - 1))
for i in nodes
for j in nodes
)
)
graph = nx.from_edgelist(elist)
nx.draw(graph)
problem = from_docplex_mp(mod)
print(problem)
encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3)
encoding.encode(problem)
print("Encoded Problem:\n=================")
print(encoding.qubit_op) # The Hamiltonian without the offset
print("Offset = ", encoding.offset)
print("Variables encoded on each qubit: ", encoding.q2vars)
verifier = EncodingCommutationVerifier(encoding)
progress_bar = tqdm(verifier)
for str_dvars, obj_val, encoded_obj_val in progress_bar:
if not np.isclose(encoded_obj_val, obj_val, atol=1e-4):
progress_bar.disp(bar_style="danger")
raise Exception( # pylint: disable=broad-exception-raised
f"Violation identified: {str_dvars} evaluates to {obj_val} "
f"but the encoded problem evaluates to {encoded_obj_val}."
)
import qiskit.tools.jupyter # pylint: disable=unused-import,wrong-import-order
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from random import randrange
A = []
B = []
for i in range(3):
A.append([])
B.append([])
for j in range(4):
A[i].append(randrange(-5,6))
B[i].append(randrange(-5,6))
print("A is",A)
print("B is",B)
C = []
for i in range(3):
C.append([])
for j in range(4):
C[i].append( 3*A[i][j]-2*B[i][j])
print("C is 3A - 2B")
print("C is",C)
M = [
[-2,3,0,4],
[-1,1,5,9]
]
N =[
[1,2,3],
[4,5,6],
[7,8,9]
]
# create the transpose of M as a zero matrix
# its dimension is (4x2)
MT = []
for i in range(4):
MT.append([])
for j in range(2):
MT[i].append(0)
# create the transpose of N as a zero matrix
# its dimension is (3x3)
NT = []
for i in range(3):
NT.append([])
for j in range(3):
NT[i].append(0)
# calculate the MT
for i in range(2):
for j in range(4):
MT[j][i]=M[i][j] # check the indices
print("M is")
for i in range(len(M)):
print(M[i])
print()
print("Transpose of M is")
for i in range(len(MT)):
print(MT[i])
print()
# calculate the NT
for i in range(3):
for j in range(3):
NT[j][i]=N[i][j] # check the indices
print("N is")
for i in range(len(N)):
print(N[i])
print()
print("Transpose of N is")
for i in range(len(NT)):
print(NT[i])
N = [
[-1,1,2],
[0,-2,-3],
[3,2,5],
[0,2,-2]
]
u = [2,-1,3]
uprime =[]
print("N is")
for i in range(len(N)):
print(N[i])
print()
print("u is",u)
for i in range(len(N)): # the number of rows of N
S = 0 # summation of pairwise multiplications
for j in range(len(u)): # the dimension of u
S = S + N[i][j] * u[j]
uprime.append(S)
print()
print("u' is",uprime)
# matrix M
M = [
[-1,0,1],
[-2,-1,2],
[1,2,-2]
]
# matrix N
N = [
[0,2,1],
[3,-1,-2],
[-1,1,0]
]
# matrix K
K = []
for i in range(3):
K.append([])
for j in range(3):
# here we calculate K[i][j]
# inner product of i-th row of M with j-th row of N
S = 0
for k in range(3):
S = S + M[i][k] * N[k][j]
K[i].append(S)
print("M is")
for i in range(len(M)):
print(M[i])
print()
print("N is")
for i in range(len(N)):
print(N[i])
print()
print("K is")
for i in range(len(K)):
print(K[i])
from random import randrange
A = []
B = []
AB = []
BA = []
DIFF = []
# create A, B, AB, BA, DIFF together
for i in range(2):
A.append([])
B.append([])
AB.append([])
BA.append([])
DIFF.append([])
for j in range(2):
A[i].append(randrange(-10,10)) # the elements of A are random
B[i].append(randrange(-10,10)) # the elements of B are random
AB[i].append(0) # the elements of AB are initially set to zeros
BA[i].append(0) # the elements of BA are initially set to zeros
DIFF[i].append(0) # the elements of DIFF are initially set to zeros
print("A =",A)
print("B =",B)
print() # print a line
print("AB, BA, and DIFF are initially zero matrices")
print("AB =",AB)
print("BA =",BA)
print("DIFF =",BA)
# let's find AB
for i in range(2):
for j in range(2):
# remark that AB[i][j] is already 0, and so we can directly add all pairwise multiplications
for k in range(2):
AB[i][j] = AB[i][j] + A[i][k] * B[k][j] # each multiplication is added
print() # print a line
print("AB =",AB)
# let's find BA
for i in range(2):
for j in range(2):
# remark that BA[i][j] is already 0, and so we can directly add all pairwise multiplications
for k in range(2):
BA[i][j] = BA[i][j] + B[i][k] * A[k][j] # each multiplication is added
print("BA =",BA)
# let's calculate DIFF = AB- BA
for i in range(2):
for j in range(2):
DIFF[i][j] = AB[i][j] - BA[i][j]
print() # print a line
print("DIFF = AB - BA =",DIFF)
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
#program 6.1a Define classical oracle f1 for unstructured search
def f1(x):
if x=='01':
return '1'
else:
return '0'
print(f1('00'),f1('01'),f1('10'),f1('11'))
#program 6.1b Define classical oracle f2 for unstructured search
def f2(x):
if x=='001':
return '1'
else:
return '0'
print(f2('000'),f2('001'),f2('010'),f2('011'),f2('100'),f2('101'),f2('110'),f2('111'))
#program 6.1c Define classical oracle f3 for unstructured search
def f3(x):
if x=='101':
return '1'
else:
return '0'
print(f3('000'),f3('001'),f3('010'),f3('011'),f3('100'),f3('101'),f3('110'),f3('111'))
#Program 6.1d Solve unstructured search prob. with classical code
import itertools
def unstructured_search(f,n):
iter = itertools.product([0,1], repeat=n)
lst = [''.join(map(str, item)) for item in iter]
for s in lst:
if f(s)=='1':
return s
print(unstructured_search(f1,2))
print(unstructured_search(f2,3))
print(unstructured_search(f3,3))
#Program 6.2 Define quantum oracle for input solution='00'
from qiskit import QuantumRegister,QuantumCircuit
qrx = QuantumRegister(2,'x')
qc = QuantumCircuit(qrx)
qc.x([0,1])
qc.cz(0,1)
qc.x([0,1])
print("The quantum circuit of phase oracle for input solution='00':")
qc.draw('mpl')
#Program 6.3 Define quantum oracle for input solution='01'
from qiskit import QuantumRegister,QuantumCircuit
qrx = QuantumRegister(2,'x')
qc = QuantumCircuit(qrx)
qc.x(1)
qc.cz(0,1)
qc.x(1)
print("The quantum circuit of phase oracle for input solution='01':")
qc.draw('mpl')
#Program 6.4 Define quantum oracle for input solution='10'
from qiskit import QuantumRegister,QuantumCircuit
qrx = QuantumRegister(2,'x')
qc = QuantumCircuit(qrx)
qc.x(0)
qc.cz(1,0)
qc.x(0)
print("The quantum circuit of phase oracle for input solution='10':")
qc.draw('mpl')
#Program 6.5 Define quantum oracle for input solution='11'
from qiskit import QuantumRegister,QuantumCircuit
qrx = QuantumRegister(2,'x')
qc = QuantumCircuit(qrx)
qc.cz(1,0)
print("The quantum circuit of phase oracle for input solution='11':")
qc.draw('mpl')
#Program 6.6 Grover alg. with oracle for input solution='10'
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(2,2)
qc.h([0,1])
qc.barrier()
qc.x(0)
qc.cz(1,0)
qc.x(0)
qc.barrier()
qc.h([0,1])
qc.x([0,1])
qc.cz(0,1)
qc.x([0,1])
qc.h([0,1])
qc.barrier()
qc.measure([0,1],[0,1])
print("The quantum circuit of Grover's algorithm for input solution='10':")
display(qc.draw('mpl'))
sim = AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",counts)
display(plot_histogram(counts))
#Program 6.7 Grover alg. with oracle for input solution='101'
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
from math import pi
qc = QuantumCircuit(3,3)
qc.h([0,1,2])
qc.barrier()
for repeat in range(2):
qc.x(1)
qc.mcp(pi,[0,1],2)
qc.x(1)
qc.barrier()
qc.h([0,1,2])
qc.x([0,1,2])
qc.mcp(pi,[0,1],2)
qc.x([0,1,2])
qc.h([0,1,2])
qc.barrier()
qc.measure([0,1,2],[0,1,2])
print("The quantum circuit of Grover's algorithm for input solution='101':")
display(qc.draw('mpl'))
sim = AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print("Total counts for qubit states are:",counts)
display(plot_histogram(counts))
#Program 6.8 Solve Hamiltonian cycle prob. for clique-4 with Grover alg.
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
from math import pi
qc = QuantumCircuit(6,6)
qc.h(range(6))
qc.barrier()
for repeat in range(3):
qc.x([4,5])
qc.mcp(pi,list(range(5)),5)
qc.x([4,5])
qc.barrier()
qc.x([1,3])
qc.mcp(pi,list(range(5)),5)
qc.x([1,3])
qc.barrier()
qc.x([0,2])
qc.mcp(pi,list(range(5)),5)
qc.x([0,2])
qc.barrier()
qc.h(range(6))
qc.x(range(6))
qc.mcp(pi,list(range(5)),5)
qc.x(range(6))
qc.h(range(6))
qc.barrier()
qc.measure(range(6),range(6))
print("The quantum circuit of Grover's algorithm:")
display(qc.draw('mpl'))
sim = AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result = job.result()
counts = result.get_counts(qc)
display(plot_histogram(counts))
print("Total counts for qubit states are:",counts)
sorted_counts=sorted(counts.items(),key=lambda x:x[1], reverse=True)
print("The solutions to the Hamiltonian cycle problem are:")
#find_all_ones=lambda s:[x for x in range(s.find('1'), len(s)) if s[x]=='1']
find_all_ones=lambda s:[x for x in range(len(s)) if s[x]=='1']
for i in range(3): #It is konw there are (4-1)!/2=3 solutions
scstr=sorted_counts[i][0] #scstr: string in sorted_counts
print(scstr,end=' (')
reverse_scstr=scstr[::-1] #reverse scstr for LSB at the right
all_ones=find_all_ones(reverse_scstr)
for one in all_ones[0:-1]:
print('e'+str(one)+'->',end='')
print('e'+str(all_ones[-1])+')')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# Import general libraries (needed for functions)
import numpy as np
import time
# Import Qiskit classes
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.providers.aer import noise
from qiskit.tools.visualization import plot_histogram
# Import measurement calibration functions
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,
CompleteMeasFitter, MeasurementFilter)
# Generate the calibration circuits
qr = qiskit.QuantumRegister(5)
meas_calibs, state_labels = complete_meas_cal(qubit_list=[2,3,4], qr=qr, circlabel='mcal')
state_labels
# Execute the calibration circuits without noise
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000)
cal_results = job.result()
# The calibration matrix without noise is the identity matrix
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
# Generate a noise model for the 5 qubits
noise_model = noise.NoiseModel()
for qi in range(5):
read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],[0.25,0.75]])
noise_model.add_readout_error(read_err, [qi])
# Execute the calibration circuits
backend = qiskit.Aer.get_backend('qasm_simulator')
job = qiskit.execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model)
cal_results = job.result()
# Calculate the calibration matrix with the noise model
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
# Plot the calibration matrix
meas_fitter.plot_calibration()
# What is the measurement fidelity?
print("Average Measurement Fidelity: %f" % meas_fitter.readout_fidelity())
# What is the measurement fidelity of Q0?
print("Average Measurement Fidelity of Q0: %f" % meas_fitter.readout_fidelity(
label_list = [['000','001','010','011'],['100','101','110','111']]))
# Make a 3Q GHZ state
cr = ClassicalRegister(3)
ghz = QuantumCircuit(qr, cr)
ghz.h(qr[2])
ghz.cx(qr[2], qr[3])
ghz.cx(qr[3], qr[4])
ghz.measure(qr[2],cr[0])
ghz.measure(qr[3],cr[1])
ghz.measure(qr[4],cr[2])
job = qiskit.execute([ghz], backend=backend, shots=5000, noise_model=noise_model)
results = job.result()
# Results without mitigation
raw_counts = results.get_counts()
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(results)
mitigated_counts = mitigated_results.get_counts(0)
from qiskit.tools.visualization import *
plot_histogram([raw_counts, mitigated_counts], legend=['raw', 'mitigated'])
|
https://github.com/mareksubocz/QRBM-qiskit
|
mareksubocz
|
from qiskit import IBMQ
# IBMQ.save_account(MY_API_TOKEN)
import qiskit
qiskit.__version__
import scipy
import numpy as np
import random
from sklearn import preprocessing
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info.operators import Operator
from qiskit import(QuantumCircuit, execute, Aer)
from qiskit.visualization import plot_histogram
from qiskit.extensions import Initialize # Import the Inititialize function
from qiskit.aqua.circuits.gates import multi_control_toffoli_gate
from qiskit.aqua.circuits.gates import multi_control_multi_target_gate
# JUŻ NIEPOTRZEBNE - TUTAJ BYŁY HIPERPARAMETRY OBWODU TESOWEGO
# #definicja rozmiaru sieci
# visible = 1
# hidden = 1
# ancilla = visible-1
# #definicja wejścia (x) oraz inicjalizacja macierzy wag
# x = np.array([random.uniform(0, 1) for n in range(visible)])
# weight_matrix = np.random.rand(visible, hidden) * np.pi
# JUŻ NIEPOTRZEBNE - TUTAJ BYŁ BUDOWANY OBWÓD TESTOWY
# # definicja obwodu (linii qubitów)
# # qc = QuantumCircuit(visible + hidden, visible)
# qr = QuantumRegister(visible + hidden + ancilla, 'q')
# cr = ClassicalRegister(visible + hidden, 'c')
# qc = QuantumCircuit(qr, cr)
# # inicjalizacja wartości qubitów wejściowych (x) na razie randomowa
# initial_state = [[np.sqrt(x[i]), np.sqrt(1-x[i])] for i in range(len(x))]
# # inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
# for i in range(visible):
# initialize_qubit = Initialize(initial_state[i])
# qc.append(initialize_qubit, [i])
# qc.h(i)
# # ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
# for i in range(hidden):
# for j in range(visible):
# qc.rz(weight_matrix[j][i], j)
# multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible)], qr[visible + i], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
# # bramki Hadamarda na warstwie ukrytej
# for i in range(hidden):
# qc.h(visible + i)
# # pomiar linii visible
# qc.measure(list(range(visible, visible+hidden)), list(range(visible, visible+hidden)))
# ### OBWÓD DRUGĄ STRONĘ
# # wyzerowanie wartości qubitów visible
# for i in range(visible):
# initialize_qubit = Initialize([1, 0])
# qc.append(initialize_qubit, [i])
# # bramka Hadamarda na qubitach hidden
# for i in range(visible, hidden + visible):
# qc.h(i)
# #odwrócone rotacje i CNOTy
# for i in range(hidden):
# for j in range(visible):
# multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible, visible + hidden)], qr[j], [qr[k] for k in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
# qc.rz(-weight_matrix[j][hidden - 1 - i], j)
# # bramka Hadamarda i pomiar na qubitach visible
# for i in range(visible):
# qc.h(i)
# qc.measure(list(range(visible)), list(range(visible)))
# EKSPERYMNET Z TESTOWYM UKŁADEM - JUŻ NIEPOTRZEBNY
# # Use Aer's qasm_simulator
# simulator = Aer.get_backend('qasm_simulator')
# # Execute the circuit on the qasm simulator
# job = execute(qc, simulator, shots=1000)
# # Grab results from the job
# result = job.result()
# # Returns counts
# counts = result.get_counts(qc)
# print("\nTotal count for 0 and 1 are:",counts)
# # qc.draw(output='mpl')
# qc.draw()
# # komórka do testowania wieloqubitowej bramki CNOT - JUŻ NIEPOTRZEBNA BO BRAMKA DZIAŁA
# # NIE ZALEŻNA OD WŁAŚCIWEJ SIECI
# # work = ancilla
# def n_control_gate(qc, target, control: list, work: list, gate_type):
# if len(control) - len(work) != 1:
# raise Exception("Wrong number of control or work qubits!")
# qc.toffoli(control[0], control[1], work[0])
# control_left = control[2:]
# for i, c_bit in enumerate(control_left):
# qc.toffoli(c_bit, work[i], work[i+1])
# qc.gate_type(work[-1], target)
# for i, c_bit in reversed(list(enumerate(control_left))):
# qc.toffoli(c_bit, work[i], work[i+1])
# qc.toffoli(control[0], control[1], work[0])
# visible = 2
# hidden = 2
# ancilla = visible - 1
# # qr_visible = QuantumRegister(visible, 'visible')
# # qr_hidden = QuantumRegister(hidden, 'hidden')
# # cr = ClassicalRegister(3, 'c')
# # if visible > 2:
# # anc = QuantumRegister(visible - 2, 'ancilla')
# # qc = QuantumCircuit(qr_visible, qr_hidden, anc, cr)
# # else:
# # qc = QuantumCircuit(qr_visible, qr_hidden, cr)
# # qr_visible = QuantumRegister(visible, 'visible')
# qr = QuantumRegister(visible + hidden + ancilla, 'q')
# cr = ClassicalRegister(3, 'c')
# qc = QuantumCircuit(qr, cr)
# for i in range(visible + hidden):
# initialize_qubit = Initialize([0, 1])
# qc.append(initialize_qubit, [i])
# # initialize_qubit = Initialize([1, 0])
# # qc.append(initialize_qubit, [2])
# # for i in range(hidden):
# # for j in range(visible):
# # qc.rz(weight_matrix[j][i], j)
# print(list(range(visible)) + [visible + 0])
# print(list(range(visible+hidden, visible+hidden+ancilla)))
# # multi_control_multi_target_gate.mcmt(qc, list(range(visible)), [], QuantumCircuit.cx, [visible])
# # print([qr_visible[i] for i in range(visible)])
# # print([anc[i] for i in range(ancilla)])
# # print([qr_hidden[i] for i in range(hidden)])
# for j in range(hidden):
# multi_control_multi_target_gate.mcmt(qc, [qr[i] for i in range(visible)], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], QuantumCircuit.cx, [qr[visible + j]])
# # multi_control_multi_target_gate.mcmt(qc, [qr_visible[i] for i in range(visible)], [anc[i] for i in range(ancilla)], QuantumCircuit.cx, [qr_hidden[0]])
# # qc.measure(list(range(visible+hidden)), list(range(visible + hidden)))
# # (qc, list(range(visible)) + [visible + 0], qancilla = 6)
# # Use Aer's qasm_simulator
# simulator = Aer.get_backend('qasm_simulator')
# # Execute the circuit on the qasm simulator
# job = execute(qc, simulator, shots=1000)
# # Grab results from the job
# result = job.result()
# # Returns counts
# counts = result.get_counts(qc)
# print("\nTotal count for 0 and 1 are:",counts)
# qc.draw()
# TO JUŻ NIEPOTRZEBNE - NIE DZIAŁA TEN SPOSÓB Z ARTYKUŁU
# print(weight_matrix, '\n')
# sinus_matrix = np.sin(weight_matrix + np.pi/4)
# print(sinus_matrix, '\n')
# print(sinus_matrix.prod(axis = 0), '\n')
# phi = np.arcsin(sinus_matrix.prod(axis = 0))
# print(phi, '\n')
# psi = phi + np.pi/4
# print(psi, '\n')
# ph = np.sin(psi)**2
# print(ph, '\n')
# # ph_normalized = preprocessing.normalize([ph], norm = 'l1')[0]
# # print(ph_normalized)
def exctract_single_qubit_measurment(dict_of_counts, qubit_range):
# print(dict_of_counts)
# print(len(list(dict_of_counts.keys())[0]))
num_qubits = len(list(dict_of_counts.keys())[0])
# result = np.zeros(len(qubit_range))
result = np.zeros(num_qubits)
# print(result)
for el in dict_of_counts:
for i in range(num_qubits):
# print("i", i)
# print("el[i]", el[i])
if i in qubit_range and el[i] == '1':
result[i] += dict_of_counts[el]
# print(result)
# print(result[qubit_range])
return result[qubit_range]
def create_dataset(dataset_size):
dataset = []
for i in range(dataset_size):
x = np.array([random.choice([0,1]), random.choice([0,1])])
y = 1
if np.array_equal(x, np.array([0,0])):
y = 0
dataset.append({"x": x, "y": y})
return dataset
dataset = create_dataset(4)
print(dataset)
def circuit_function(qc, weight_matrix):
qc.data = []
# inicjalizacja wartości qubitów wejściowych (x)
initial_state = [[np.sqrt(1-x[i]), np.sqrt(x[i])] for i in range(len(x))]
# inicjalizacja wartości qubitów wejściowych i bramka Hadamarda
for i in range(visible):
initialize_qubit = Initialize(initial_state[i])
qc.append(initialize_qubit, [i])
qc.h(i)
# ciąg bramek CNOT i bramek rotacji R (zależnych od parametrów)
for i in range(hidden):
for j in range(visible):
qc.ry(weight_matrix[j][i], j)
multi_control_toffoli_gate.mct(qc, [qr[k] for k in range(visible)], qr[visible + i], [qr[i] for i in range(visible + hidden, visible + hidden + ancilla)], mode='basic')
# bramki Hadamarda na warstwie ukrytej
# for i in range(hidden):
# qc.h(visible + i)
# pomiar linii visible
qc.measure(list(range(visible, visible+hidden)), list(range(hidden)))
#eksperyment:
#symylator
simulator = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator
job = execute(qc, simulator, shots=num_shots)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(qc)
# print(counts)
ph = exctract_single_qubit_measurment(counts, list(range(hidden))) / num_shots
# print("\nProbabilities are:",ph)
return ph[0]
epsilon = 0.01
def update2(ph, expected_ph, weight_matrix, lr):
gradient = []
for i, row in enumerate(weight_matrix):
gradient_row = []
for j, el in enumerate(row):
weight_matrix[i][j] += epsilon
result_plus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] -= 2*epsilon
result_minus = circuit_function(qc, weight_matrix)
weight_matrix[i][j] += epsilon
# result_zero = circuit_function(qc, weight_matrix)
# print("ph", result_zero)
# print("exp_ph", expected_ph)
# print("el final:", el)
# print(result_plus - result_minus)
result = (result_plus - result_minus)/(2*epsilon) * lr * (ph - expected_ph)
gradient_row.append(result)
gradient.append(gradient_row)
# print("gradient", gradient)
weight_matrix = weight_matrix - gradient
return weight_matrix
# update2()
# template do uczenia
import matplotlib.pyplot as plt
%matplotlib inline
def update(exp_ph, ph):
global weight_matrix
# #obliczanie prawdopodobieństwa p(|h>) ze wzoru
# sinus_matrix = np.sin(weight_matrix + np.pi/4)
# phi = np.arcsin(sinus_matrix.prod(axis = 0))
# # print('phi', phi)
# psi = phi + np.pi/4
# # print('psi', psi)
# ph = np.sin(psi)**2
# # print('ph', ph)
#obliczanie gradientu i,k
S = 1/(np.sqrt(1-(np.sin(phi))**2))
# print("S", S)
T = np.sin(phi) * np.sum(1/np.tan(weight_matrix + np.pi/4), axis = 0)
# print("T", T)
# print("sum products", (exp_ph - ph) * ph * np.cos(2*psi) * S * T)
gradient = np.zeros(hidden)
for k in range(hidden):
gradient[k] = np.sum( (exp_ph - ph) * ph * np.cos(2*psi) * S * T[k])
# print("gradient = ", gradient)
# print([gradient] * len(weight_matrix))
weight_matrix = weight_matrix + ([gradient] * len(weight_matrix))
#definicja rozmiaru sieci
visible = 2
hidden = 1
ancilla = visible-1
#definicja wejścia (x)oraz inicjalizacja macierzy wag
# x = np.array([random.uniform(0, 1) for n in range(visible)])
dataset = create_dataset(10)
print(dataset[0]["x"][0])
print(dataset[0]["x"][1])
print([n for n in range(visible)])
weight_matrix = np.random.rand(visible, hidden) * np.pi
#definicja parametrów uczenia
num_shots = 1000
num_epochs = 100
qr = QuantumRegister(visible + hidden + ancilla, 'q')
cr = ClassicalRegister(hidden, 'c')
qc = QuantumCircuit(qr, cr)
cost_function_data = []
lr = 0.05
for epoch in range(num_epochs):
print("epoch: ", epoch)
for i, element in enumerate(dataset):
# print(element)
x = np.array([dataset[i]["x"][n] for n in range(visible)])
exp_ph = dataset[i]["y"]
ph = circuit_function(qc, weight_matrix)
weight_matrix = update2(ph, exp_ph, weight_matrix, lr)
# print("exp_ph", exp_ph, "ph", ph, "weight_matrix", weight_matrix, "cost_function", 0.5 * (ph - exp_ph)**2)
cost_function_data.append(0.5 * (ph - exp_ph)**2)
qc.draw()
plt.xlabel('number of epochs')
plt.ylabel('cost')
plt.plot(cost_function_data)
qc.draw()
|
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-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/iasebsil83/Grozzle
|
iasebsil83
|
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>)
out of four possible values."""
#import numpy and plot library
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
# define variables, 1) initialize qubits to zero
n = 2
grover_circuit = QuantumCircuit(n)
#define initialization function
def initialize_s(qc, qubits):
'''Apply a H-gate to 'qubits' in qc'''
for q in qubits:
qc.h(q)
return qc
### begin grovers circuit ###
#2) Put qubits in equal state of superposition
grover_circuit = initialize_s(grover_circuit, [0,1])
# 3) Apply oracle reflection to marked instance x_0 = 3, (|11>)
grover_circuit.cz(0,1)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
# 4) apply additional reflection (diffusion operator)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
# 5) measure the qubits
grover_circuit.measure_all()
# Load IBM Q account and get the least busy backend device
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
from qiskit.tools.monitor import job_monitor
job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
#highest amplitude should correspond with marked value x_0 (|11>)
|
https://github.com/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/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
from ibm_quantum_widgets import draw_circuit
circuit = QuantumCircuit(2,2)
circuit
circuit.draw(output='mpl')
circuit.x(0)
circuit.draw(output='mpl')
circuit.h(0)
circuit.draw(output='mpl')
circuit.cx(0,1)
circuit.draw(output='mpl')
circuit.measure([0,1],[1,1])
circuit.draw(output='mpl')
draw_circuit(circuit)
simulator = Aer.get_backend('qasm_simulator')
simulator
job = execute(circuit, backend=simulator, shots=1024)
job
result = job.result()
result
counts = result.get_counts()
counts
plot_histogram(counts)
|
https://github.com/jeevesh2002/QuantumKatasQiskit
|
jeevesh2002
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(1)
# print the statevector
print(f"Initial Statevector: {Statevector.from_instruction(circuit).data}\n\n")
# Add an X gate followed by a H gate to put the qubit in |-> state
circuit.x(0)
circuit.h(0)
print("After putting the qubit in |-> state\n\n")
# print the statevector
print("Final Statevector: ", Statevector.from_instruction(circuit).data)
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Statevector
# Create a Quantum Register with 3 qubits
q = QuantumRegister(3)
# Create a Quantum Circuit acting on the q register to demonstrate the GHZ state
circuit = QuantumCircuit(q)
# Add a H gate on qubit 0, putting this qubit in superposition.
circuit.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(q[0], q[1])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2
circuit.cx(q[0], q[2])
from qiskit.quantum_info import Statevector
# Set the intial state of the simulator to the ground state using from_int
state = Statevector.from_int(0, 2**3)
# Evolve the state by the quantum circuit
state = state.evolve(circuit)
#draw using latex
state.draw('latex')
from qiskit.visualization import array_to_latex
#Alternative way of representing in latex
array_to_latex(state)
state.draw('qsphere')
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
#General imports
import numpy as np
#Operator Imports
from qiskit.opflow import Z, X, I, StateFn, CircuitStateFn, SummedOp
from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian
#Circuit imports
from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression
from qiskit.circuit.library import EfficientSU2
# Instantiate the quantum state
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Instantiate the Hamiltonian observable
H = (2 * X) + Z
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Print the operator corresponding to the expectation value
print(op)
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi}
# Convert the operator and the gradient target params into the respective operator
grad = Gradient().convert(operator = op, params = params)
# Print the operator corresponding to the Gradient
print(grad)
# Assign the parameters and evaluate the gradient
grad_result = grad.assign_parameters(value_dict).eval()
print('Gradient', grad_result)
# Define the Hamiltonian with fixed coefficients
H = 0.5 * X - 1 * Z
# Define the parameters w.r.t. we want to compute the gradients
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = { a: np.pi / 4, b: np.pi}
# Combine the Hamiltonian observable and the state into an expectation value operator
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
print(op)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameters using
# the parameter shift method.
state_grad = Gradient(grad_method='param_shift').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with parameter shift', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the linear combination of unitaries method.
state_grad = Gradient(grad_method='lin_comb').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with the linear combination method', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the finite difference method.
state_grad = Gradient(grad_method='fin_diff').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with finite difference', state_grad_result)
# Besides the method to compute the circuit gradients resp. QFI, a regularization method can be chosen:
# `ridge` or `lasso` with automatic parameter search or `perturb_diag_elements` or `perturb_diag`
# which perturb the diagonal elements of the QFI.
nat_grad = NaturalGradient(grad_method='lin_comb', qfi_method='lin_comb_full', regularization='ridge').convert(
operator=op, params=params)
# Assign the parameters and evaluate the gradient
nat_grad_result = nat_grad.assign_parameters(value_dict).eval()
print('Natural gradient computed with linear combination of unitaries', nat_grad_result)
# Instantiate the Hamiltonian observable
H = X
# Instantiate the quantum state with two parameters
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Convert the operator and the hessian target coefficients into the respective operator
hessian = Hessian().convert(operator = op, params = [a, b])
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi/4}
# Assign the parameters and evaluate the Hessian w.r.t. the Hamiltonian coefficients
hessian_result = hessian.assign_parameters(value_dict).eval()
print('Hessian \n', np.real(np.array(hessian_result)))
# Define parameters
params = [a, b]
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='param_shift').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the parameter shift method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='lin_comb').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the linear combination of unitaries method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian using finite difference
state_hess = Hessian(hess_method='fin_diff').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed with finite difference\n', (np.array(hessian_result)))
# Wrap the quantum circuit into a CircuitStateFn
state = CircuitStateFn(primitive=qc, coeff=1.)
# Convert the state and the parameters into the operator object that represents the QFI
qfi = QFI(qfi_method='lin_comb_full').convert(operator=state, params=params)
# Define the values for which the QFI is to be computed
values_dict = {a: np.pi / 4, b: 0.1}
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('full QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'block_diagonal'
qfi = QFI('overlap_block_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Block-diagonal QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'diagonal'
qfi = QFI('overlap_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Diagonal QFI \n', np.real(np.array(qfi_result)))
# Execution Imports
from qiskit import Aer
from qiskit.utils import QuantumInstance
# Algorithm Imports
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import CG
from qiskit.opflow import I, X, Z
from qiskit.circuit import QuantumCircuit, ParameterVector
from scipy.optimize import minimize
# Instantiate the system Hamiltonian
h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X)
# This is the target energy
h2_energy = -1.85727503
# Define the Ansatz
wavefunction = QuantumCircuit(2)
params = ParameterVector('theta', length=8)
it = iter(params)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
wavefunction.cx(0, 1)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
# Define the expectation value corresponding to the energy
op = ~StateFn(h2_hamiltonian) @ StateFn(wavefunction)
grad = Gradient(grad_method='lin_comb')
qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector'),
shots=1,
seed_simulator=2,
seed_transpiler=2)
#Conjugate Gradient algorithm
optimizer = CG(maxiter=50)
# Gradient callable
vqe = VQE(wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=qi_sv)
result = vqe.compute_minimum_eigenvalue(h2_hamiltonian)
print('Result:', result.optimal_value, 'Reference:', h2_energy)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/epelaaez/QuantumLibrary
|
epelaaez
|
# To clean enviroment variables
%reset
import numpy as np
import pandas as pd
import folium
import matplotlib.pyplot as plt
try:
import cplex
from cplex.exceptions import CplexError
except:
print("Warning: Cplex not found.")
import math
from qiskit.utils import algorithm_globals
from qiskit_algorithms import SamplingVQE
from qiskit_algorithms.optimizers import SPSA
from qiskit.circuit.library import RealAmplitudes
from qiskit.primitives import Sampler
df = pd.read_csv("uscities.csv")
columnsNeeded = ["city", "lat", "lng"]
# Inicialization of variables
locationsNumber = 15 # OJO que en local me crashea si sobrepaso 5
coordenatesDf = df[columnsNeeded].iloc[:locationsNumber]
n = coordenatesDf.shape[0] # number of nodes + depot (n+1)
K = 3 # number of vehicles
print(coordenatesDf)
# Initialize instance values by calculate the squared Euclidean distances between a set of coordinates
# represented in the dataframe.
def generate_instance(coordenatesDf):
n = coordenatesDf.shape[0]
xc = coordenatesDf["lat"]
yc = coordenatesDf["lng"]
loc = coordenatesDf["city"]
instance = np.zeros([n, n])
for ii in range(0, n):
for jj in range(ii + 1, n):
instance[ii, jj] = (xc[ii] - xc[jj]) ** 2 + (yc[ii] - yc[jj]) ** 2
instance[jj, ii] = instance[ii, jj]
return xc, yc, instance, loc
# Initialize the problem by randomly generating the instance
lat, lng, instance, loc = generate_instance(coordenatesDf)
print(lat, lng, loc, instance)
#print(instance)
class ClassicalOptimizer:
def __init__(self, instance, n, K):
self.instance = instance
self.n = n # number of nodes
self.K = K # number of vehicles
def compute_allowed_combinations(self):
f = math.factorial
return f(self.n) / f(self.K) / f(self.n - self.K)
def cplex_solution(self):
# refactoring
instance = self.instance
n = self.n
K = self.K
my_obj = list(instance.reshape(1, n**2)[0]) + [0.0 for x in range(0, n - 1)]
my_ub = [1 for x in range(0, n**2 + n - 1)]
my_lb = [0 for x in range(0, n**2)] + [0.1 for x in range(0, n - 1)]
my_ctype = "".join(["I" for x in range(0, n**2)]) + "".join(
["C" for x in range(0, n - 1)]
)
my_rhs = (
2 * ([K] + [1 for x in range(0, n - 1)])
+ [1 - 0.1 for x in range(0, (n - 1) ** 2 - (n - 1))]
+ [0 for x in range(0, n)]
)
my_sense = (
"".join(["E" for x in range(0, 2 * n)])
+ "".join(["L" for x in range(0, (n - 1) ** 2 - (n - 1))])
+ "".join(["E" for x in range(0, n)])
)
try:
my_prob = cplex.Cplex()
self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs)
my_prob.solve()
except CplexError as exc:
print(exc)
return
x = my_prob.solution.get_values()
x = np.array(x)
cost = my_prob.solution.get_objective_value()
return x, cost
def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs):
n = self.n
prob.objective.set_sense(prob.objective.sense.minimize)
prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype)
prob.set_log_stream(None)
prob.set_error_stream(None)
prob.set_warning_stream(None)
prob.set_results_stream(None)
rows = []
for ii in range(0, n):
col = [x for x in range(0 + n * ii, n + n * ii)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
for ii in range(0, n):
col = [x for x in range(0 + ii, n**2, n)]
coef = [1 for x in range(0, n)]
rows.append([col, coef])
# Sub-tour elimination constraints:
for ii in range(0, n):
for jj in range(0, n):
if (ii != jj) and (ii * jj > 0):
col = [ii + (jj * n), n**2 + ii - 1, n**2 + jj - 1]
coef = [1, 1, -1]
rows.append([col, coef])
for ii in range(0, n):
col = [(ii) * (n + 1)]
coef = [1]
rows.append([col, coef])
prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs)
# Instantiate the classical optimizer class
classical_optimizer = ClassicalOptimizer(instance, n, K)
# Print number of feasible solutions
print("Number of feasible solutions = " + str(classical_optimizer.compute_allowed_combinations()))
# Solve the problem in a classical fashion via CPLEX
x = None
z = None
try:
x, classical_cost = classical_optimizer.cplex_solution()
# Put the solution in the z variable
z = [x[ii] for ii in range(n**2) if ii // n != ii % n]
# Print the solution
print(z)
except:
print("CPLEX may be missing.")
m = folium.Map(location=[39.487660, -97.594333], zoom_start=0)
marker_icon1 = folium.Icon(color = "red")
for i in range(len(lat)):
if (i == 0):
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m)
else:
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m)
for ii in range(0, n**2):
if x[ii] > 0:
ix = ii // n
iy = ii % n
folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m)
m
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
class QuantumOptimizer:
def __init__(self, instance, n, K):
self.instance = instance
self.n = n
self.K = K
def binary_representation(self, x_sol=0):
instance = self.instance
n = self.n
K = self.K
A = np.max(instance) * 100 # A parameter of cost function
# Determine the weights w
instance_vec = instance.reshape(n**2)
w_list = [instance_vec[x] for x in range(n**2) if instance_vec[x] > 0]
w = np.zeros(n * (n - 1))
for ii in range(len(w_list)):
w[ii] = w_list[ii]
# Some variables I will use
Id_n = np.eye(n)
Im_n_1 = np.ones([n - 1, n - 1])
Iv_n_1 = np.ones(n)
Iv_n_1[0] = 0
Iv_n = np.ones(n - 1)
neg_Iv_n_1 = np.ones(n) - Iv_n_1
v = np.zeros([n, n * (n - 1)])
for ii in range(n):
count = ii - 1
for jj in range(n * (n - 1)):
if jj // (n - 1) == ii:
count = ii
if jj // (n - 1) != ii and jj % (n - 1) == count:
v[ii][jj] = 1.0
vn = np.sum(v[1:], axis=0)
# Q defines the interactions between variables
Q = A * (np.kron(Id_n, Im_n_1) + np.dot(v.T, v))
# g defines the contribution from the individual variables
g = (
w
- 2 * A * (np.kron(Iv_n_1, Iv_n) + vn.T)
- 2 * A * K * (np.kron(neg_Iv_n_1, Iv_n) + v[0].T)
)
# c is the constant offset
c = 2 * A * (n - 1) + 2 * A * (K**2)
try:
max(x_sol)
# Evaluates the cost distance from a binary representation of a path
fun = (
lambda x: np.dot(np.around(x), np.dot(Q, np.around(x)))
+ np.dot(g, np.around(x))
+ c
)
cost = fun(x_sol)
except:
cost = 0
return Q, g, c, cost
def construct_problem(self, Q, g, c) -> QuadraticProgram:
qp = QuadraticProgram()
for i in range(n * (n - 1)):
qp.binary_var(str(i))
qp.objective.quadratic = Q
qp.objective.linear = g
qp.objective.constant = c
return qp
def solve_problem(self, qp):
algorithm_globals.random_seed = 10598
#vqe = SamplingVQE(sampler=Sampler(), optimizer=SPSA(), ansatz=RealAmplitudes())
#optimizer = MinimumEigenOptimizer(min_eigen_solver=vqe)
meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver())
result = meo.solve(qp)
# compute cost of the obtained result
_, _, _, level = self.binary_representation(x_sol=result.x)
return result.x, level
# Instantiate the quantum optimizer class with parameters:
quantum_optimizer = QuantumOptimizer(instance, n, K)
# Check if the binary representation is correct
try:
if z is not None:
Q, g, c, binary_cost = quantum_optimizer.binary_representation(x_sol=z)
print("Binary cost:", binary_cost, "classical cost:", classical_cost)
if np.abs(binary_cost - classical_cost) < 0.01:
print("Binary formulation is correct")
else:
print("Error in the binary formulation")
else:
print("Could not verify the correctness, due to CPLEX solution being unavailable.")
Q, g, c, binary_cost = quantum_optimizer.binary_representation()
print("Binary cost:", binary_cost)
except NameError as e:
print("Warning: Please run the cells above first.")
print(e)
qp = quantum_optimizer.construct_problem(Q, g, c)
print(qp)
#quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp)
quantum_solution, quantum_cost = quantum_optimizer.solve_problem(qp)
print(quantum_solution, quantum_cost)
print(classical_cost)
m = folium.Map(location=[39.487660, -97.594333], zoom_start=0)
marker_icon1 = folium.Icon(color = "red")
for i in range(len(lat)):
if (i == 0):
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m)
else:
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m)
for ii in range(0, n**2):
if x[ii] > 0:
ix = ii // n
iy = ii % n
folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m)
m
print(quantum_cost)
x_quantum = np.zeros(n**2)
kk = 0
for ii in range(n**2):
if ii // n != ii % n:
x_quantum[ii] = quantum_solution[kk]
kk += 1
m = folium.Map(location=[39.487660, -97.594333], zoom_start=0)
marker_icon1 = folium.Icon(color = "red")
for i in range(len(lat)):
if (i == 0):
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}", icon=marker_icon1).add_to(m)
else:
folium.Marker(location=[lat[i], lng[i]], tooltip=f"Location: {loc[i]}, Order: {i}").add_to(m)
for ii in range(0, n**2):
if x_quantum[ii] > 0:
ix = ii // n
iy = ii % n
folium.PolyLine([(lat[ix], lng[ix]), (lat[iy], lng[iy])], color="blue").add_to(m)
m
algorithms = ("Classic", "Quantum")
data = {
'K = 1': (2249.2068134000006, 1706.2245994000696),
'k = 2': (2771.940853740001, 1845.127222779207),
'K = 3': (3981.1556002800016, 3981.155600280501),
}
x = np.arange(len(algorithms)) # the label locations
width = 0.25 # the width of the bars
multiplier = 0
fig, ax = plt.subplots(layout='constrained')
for attribute, measurement in data.items():
offset = width * multiplier
rects = ax.bar(x + offset, measurement, width, label=attribute)
ax.bar_label(rects, padding=3)
multiplier += 1
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Length (mm)')
ax.set_title('Comparision of Quantum and Classical Cost')
ax.set_xticks(x + width, algorithms)
ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 5000)
plt.show()
|
https://github.com/qwqmlf/qwgc
|
qwqmlf
|
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.3.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Quantum Walk Graph Classifier
# 今回の成果物である量子ウォークにおけるグラフの分類器に関するチュートリアル
# +
import numpy as np
import random
import copy
import sys
import networkx as nx
import matplotlib.pyplot as plt
from numpy import pi
from tqdm import trange
from grakel import datasets, Graph
from sklearn.model_selection import KFold
sys.path.append("../")
from qwgc.QWGC import QWGC
# -
# # 量子ウォーク
# このプロジェクトにおける肝となる量子アルゴリズムである量子ウォークというものについてです。詳しくは我々の[プロジェクトページ](https://qwqmlf.github.io/QuantumFrontier/article)をご覧ください。今回は[MUTAG](https://rdrr.io/cran/QSARdata/man/mutagen.html)と呼ばれるデータセットを用いて、量子ウォークがグラフ上で行われるということがどういうことなのかということについて見ていきます。
# MUTAGを取ってくる
Data = datasets.fetch_dataset('MUTAG', verbose=False)
data_x, data_y = np.array(Data.data), np.array(Data.target)
# まずはMUTAGとはどのようなデータなのかという点について見ていきます。代表として先頭10データを可視化していきたいと思います。
# visualization of data
subtract = 0
lens = []
for d, l in zip(data_x[:10], data_y[:10]):
print(l)
plt.figure(figsize=(10, 10))
G = nx.DiGraph()
connection = d[0]
nodesize = [(i+1)**800 for i in d[1].values()]
edge_weight = d[2]
lens.append(len([i for i in d[1].values()]))
adjacency = Graph(connection).get_adjacency_matrix()
nodes = np.array([str(i+1) for i, _ in enumerate(adjacency)])
edges = []
weight = []
for i, v in edge_weight.items():
ed = [str(st-subtract) for st in list(i)]
ed.append(v+1)
edges.append(tuple(ed))
subtract = max(d[1].keys())
G.add_nodes_from(nodes)
G.add_weighted_edges_from(edges)
pos = nx.kamada_kawai_layout(G)
edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
nx.draw_networkx(G, pos, with_labels=True, alpha=0.8)
plt.show()
# これらがMUTAGと呼ばれている変異原性があるのかないのかというデータセットになります。10から30程度のノード数を持ったグラフデータの集まりで、各ノードはある元素を表していて、各リンクは元素間の結合を表しています。各リンクの間についているラベルはその結合がどのような結合なのかということを表しています。ではここの上で量子ウォークを行うと、どのような状態がえられるのかということを見ていきたいと思います。
# 今回のプログラムはこちらの論文を参考としています。[Barr, Katie, Toby Fleming, and Viv Kendon. "Simulation methods for quantum walks on graphs applied to perfect state transfer and formal language recognition." Proceedings of the 2013 workshop on complex systems modelling and simulation, Milan, Italy. 2013.]
# まずは量子ウォーカーが1ステップ進んだ時を考えます。スタートは全て0ノードです。
# +
from qwgc.preprocess.qwalk import QuantumWalk
# 対象のデータ
data = data_x[0]
label = data_y[0]
# 隣接行列
adjacency = Graph(data[0]).get_adjacency_matrix()
count = np.count_nonzero(adjacency)//2
# 量子ウォークのハイパーパラメータ
step = 1
# 次数が2の場合のコインのパラメータ(今回は簡単のために全てアダマールコイン)
coin = np.kron(np.identity(count), 1/np.sqrt(2)*np.array([[1, 1], [1, -1]]))
# 初期状態 (0からスタート)
initial = None
# 量子ウォーカーが測定される確率
qwalk = QuantumWalk(initial, coin, adjacency)
qwalk.n_steps(step)
probs = qwalk.calc_probs()
# 描画
plt.figure(figsize=(10, 10))
G = nx.DiGraph()
# ノードの大きさで確率を表す
connection = data[0]
nodesize = [(i+0.1)*800 for i in probs]
edge_weight = data[2]
nodes = np.array([str(i+1) for i, _ in enumerate(adjacency)])
edges = []
weight = []
for i, v in edge_weight.items():
ed = [str(st) for st in list(i)]
ed.append(v+1)
edges.append(tuple(ed))
subtract = max(data[1].keys())
G.add_nodes_from(nodes)
G.add_weighted_edges_from(edges)
pos = nx.spring_layout(G)
edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
nx.draw_networkx(G, pos, with_labels=True, alpha=0.8, node_size=nodesize)
plt.show()
# -
# このように初期のノードから隣り合った二つのノードにおいて量子ウォーカーが観測されうるのがわかるかと思います。
# もう少しステップを進めてみます。
def draw(nodesize):
plt.figure(figsize=(10, 10))
G = nx.DiGraph()
# ノードの大きさで確率を表す
connection = data[0]
nodesize = [(i)*800 for i in probs]
edge_weight = data[2]
nodes = np.array([str(i+1) for i, _ in enumerate(adjacency)])
edges = []
weight = []
for i, v in edge_weight.items():
ed = [str(st) for st in list(i)]
ed.append(v+1)
edges.append(tuple(ed))
subtract = max(data[1].keys())
G.add_nodes_from(nodes)
G.add_weighted_edges_from(edges)
pos = nx.spring_layout(G)
edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
nx.draw_networkx(G, pos, with_labels=True, alpha=0.8, node_size=nodesize)
plt.show()
data = data_x[0]
label = data_y[0]
# 隣接行列
adjacency = Graph(data[0]).get_adjacency_matrix()
count = np.count_nonzero(adjacency)//2
# 量子ウォークのハイパーパラメータ
for step in range(1, 10):
# 次数が2の場合のコインのパラメータ(今回は簡単のために全てアダマールコイン)
coin = np.kron(np.identity(count), 1/np.sqrt(2)*np.array([[1, 1], [1, -1]]))
# 初期状態 (0からスタート)
initial = None
# 量子ウォーカーが測定される確率
qwalk = QuantumWalk(initial, coin, adjacency)
qwalk.n_steps(step)
probs = qwalk.calc_probs()
draw(probs)
# やや見辛いですが、少しずつ観測される確率が広がっていっていることがわかると思います。
# # 分類回路
# これらを実際に量子回路に流して分類を行なっていきます。
from qwgc.preprocess.qwfilter import QWfilter
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, transpile
data = data_x[0]
label = data_y[0]
# filter
u3param = [pi, 0, pi/2]
# step
step = 3
# initial 重ね合わせを初期状態として利用
initial = "super"
qwfilter = QWfilter(u3param, step, initial)
# 今回は測定をせずに、振幅をそのまま量子回路にマッピングを行います。
amplitude = qwfilter.single_amplitude(data)
# これにより特定のステップが終了した後の量子ウォークの確率振幅を取り出すことができました。これをqiskitのinitialize関数というものを用いて量子ビットに情報として入れていきます。またこの時$2^n$の大きさのベクトルである必要があることから0埋めを行います。
la = len(amplitude)
new_amplitude = list(amplitude) + [0 for i in range(64 - 38)]
print(len(new_amplitude))
nq = 6
# 量子レジスタの定義
qr = QuantumRegister(nq, name="quantum walk")
ancilla = QuantumRegister(2, name="ancilla")
# 古典レジスタの定義
cr = ClassicalRegister(2)
# 量子回路の定義
qc = QuantumCircuit(qr, ancilla, cr)
qc.draw(output='mpl')
# このように合計8量子ビットを用意しました。このうち上6つが量子ウォークのデータ(実際の実験ではこの部分が7個になっています。)、下2つが補助の量子ビットになっています。ここに量子ウォーク後の確率振幅を入れていきます。
qc.initialize(new_amplitude, qr)
# そして、パラメータを初期化し、補助量子ビットに制御Ryゲートを用いてマッピングを行なっていきます。
# 回転角を初期化
theta = [np.random.uniform(-pi, pi) for i in range(nq)]
for ith, th in enumerate(theta):
qc.cry(th, qr[ith], ancilla[ith%2])
qc.draw(output="mpl")
# 最後に補助量子ビットを測定します。
qc.measure(ancilla, cr)
# この測定によって、このグラフがどのクラスに分類されるのかということを見ていきます。今回は01をクラス-1、(つまり変異原性の性質が陰性)10をクラスの1(性質が陽性)とします。
backend = Aer.get_backend("qasm_simulator")
shots = 1024
job = execute(qc, backend=backend, shots=shots)
counts = job.result().get_counts(qc)
dinom = counts.get('01', 0) + counts.get('10', 0) + 1e-10
print("クラス-1である確率:", counts.get('01', 0)/dinom, "クラス1である確率:", counts.get('10', 0)/dinom)
if counts.get('01', 0)/dinom > counts.get('10', 0)/dinom:
answer = -1
else:
answer = 1
print("このグラフはクラス ", answer, "です.")
# このような分類結果になります。これを実際のラベルと比較をしてみます。
print("正解は", data_y[1], "です。")
# これらを全てのデータに対して行い、エラーを計算し実際にパラメータのアップデートを行なっていきます。
|
https://github.com/Quantum-Ducks/QuBayes
|
Quantum-Ducks
|
import numpy as np
import matplotlib.pyplot as plt
import operator
from qiskit.tools.visualization import plot_bloch_multivector
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit import QuantumCircuit, Aer, execute, IBMQ
import import_ipynb
import circuitgenerator as circ
def determine_color(state):
if state == '0':
color='red'
elif state=='1':
color='green'
elif state=='2':
color='forestgreen'
elif state=='3':
color='darkgreen'
return color
def make_counts_hist(counts_results):
probabilities = np.array([counts_results[k] for k in counts_results]) / sum(counts_results.values())
print(probabilities)
plt.bar(list(counts_results.keys()), counts_results.values())
plt.ylabel('Counts')
plt.xticks(list(counts_results.keys()), [None])
xpos_text = -0.3
for key in counts_results:
Cstate=key[0]
Bstate=key[1]
Astate=key[2]
Ccolor, Bcolor, Acolor = determine_color(Cstate, Bstate, Astate)
plt.text(xpos_text, -200,'Cases', color=Ccolor)
plt.text(xpos_text, -400, 'Tests', color=Bcolor)
plt.text(xpos_text, -600,'Home', color=Acolor)
xpos_text += 1
plt.show()
return
def get_marginal_probabilities(state_counts, whichstate=0):
#state_counts: dict, counts for each state from network result (should have 2^n entries)
#whichstate: integer representing the state that you want the marginal probability of (for a 2-state system this
#could be 0 or 1).
#marg_probs: array of length n, marginal probabilities that each qubit is whichstate,
#from most significant to least significant qubit
n = len(list(state_counts.keys())[0]) #number of qubits
prob = np.zeros(n)
total = sum(state_counts.values())
for i in range(n):
for key in state_counts:
if int(key[i]) == whichstate:
prob[i] += state_counts[key]
prob[i] = prob[i]/total
return prob
def make_prob_hist(counts_results, var_labels, top_n_probs='all', whichvar=['all',2], probdict={}):
"""
INPUTS: counts_results: dictionary from circuitgenerator where keys are multi-qubit states and values are counts
var_labels: IF WHICHVAR[0] = 'all': list of strings of variable names. Order of variable names in var_labels needs to be the same
as the order of variables in a multi-qubit state in counts_results
IF WHICHVAR[0] is not 'all': list of strings of state names for the variable chosen in whichvar
top_n_probs: optional. So that you can make a histogram of n most likely probabilities. Default='all'.
Change to integer if you only want top n
whichvar: list- first entry integer giving index of the variable in a key of counts_results that you want to marginal
probabilities for. Default='all' includes all variables and doesn't calculate marginal probabilities.
Second entry is the number of states that variable can be in. Default is 2 states.
probdict: dictionary of probabilities you want a histogram of. keys will be label on x axis and values will
be probabilities.
"""
if probdict == {}:
counts_results = dict(sorted(counts_results.items(), key=operator.itemgetter(1),reverse=True)) #sorts dictionary by decreasing counts
probabilities = np.array([counts_results[k] for k in counts_results]) / sum(counts_results.values())
else: #this example is to plot most probable ways to get decreasing deaths or cases
probabilities = probdict
plt.bar(probabilities.keys(), probabilities.values())
plt.ylabel('Probability')
plt.xticks(rotation=90)
plt.title('Most Probable ')
plt.show()
return
if (top_n_probs == 'all') & (whichvar[0] == 'all'):
plt.bar(np.arange(len(counts_results)), probabilities)
plt.ylabel('Probability')
plt.xticks(np.arange(len(counts_results)), [None])
xpos_text = -0.3
for key in counts_results:
for i in range(len(key)):
state=key[i]
color = determine_color(state)
plt.text(xpos_text, -0.03-0.02*i,var_labels[i], color=color)
xpos_text += 1
plt.show()
elif (top_n_probs != 'all') & (whichvar[0] == 'all'):
plt.bar(np.arange(top_n_probs), probabilities[0:top_n_probs])
plt.ylabel('Probability')
plt.xticks(np.arange(top_n_probs), [None])
xpos_text = -0.3
counter = 0
for key in counts_results:
if counter < top_n_probs:
for i in range(len(key)):
state=key[i]
color = determine_color(state)
plt.text(xpos_text, -0.03-0.02*i,var_labels[i], color=color)
xpos_text += 1
counter += 1
plt.show()
elif (top_n_probs == 'all') & (whichvar[0] != 'all'):
pvar = []
for i in range(whichvar[1]):
pvar.append(get_marginal_probabilities(counts_results, whichstate=i)[whichvar[0]])
plt.bar(np.arange(whichvar[1]), pvar)
plt.ylabel('Probability')
plt.xticks(np.arange(whichvar[1]), [None])
xpos_text = -0.3
for i in range(len(pvar)):
state = i
color = determine_color(str(state))
plt.text(xpos_text, -0.07,var_labels[i], color=color)
xpos_text += 1
plt.show()
elif (top_n_probs != 'all') & (whichvar[0] != 'all'):
pvar = []
for i in range(whichvar[1]):
pvar.append(get_marginal_probabilities(counts_results, whichstate=i)[whichvar[0]])
numbars = min(whichvar[1], top_n_probs)
plt.bar(np.arange(numbars), pvar)
plt.ylabel('Probability')
plt.xticks(np.arange(numbars), [None])
xpos_text = -0.3
for i in range(numbars):
state = i
color = determine_color(str(state))
plt.text(xpos_text, -0.07,var_labels[i], color=color)
xpos_text += 1
plt.show()
return
results = {'000': 2783, '001': 1240, '100': 603, '111': 815, '110': 294, '010': 1712, '101': 485, '011': 260}
results_maxtomin = {'000': 2783, '010': 1712, '001': 1240, '111': 815, '100': 603, '101': 485, '110': 294, '011': 260}
graph = {'StayAtHome': ([], [0.645, 0.355]), 'Testing': ([], [0.62, 0.38]), 'Cases': (['StayAtHome', 'Testing'], [0.8181818181818182, 0.18181818181818182, 0.8412698412698413, 0.15873015873015872, 0.7068965517241379, 0.29310344827586204, 0.23076923076923078, 0.7692307692307693])}
alabio_counts_results = {'0001010100100101': 8, '0001101100011011': 2, '0101010011010100': 2, '0000111101100001': 1, '0001011000101011': 1, '0001111011100111': 1, '0000111001001000': 1, '0000110101000100': 1, '0001101101011000': 6, '0001110101010000': 1, '0000010001001001': 1, '0000001001011010': 1, '0000110101010100': 4, '0001110010011001': 2, '0001100110011010': 2, '0000101111101000': 16, '0011000011111001': 1, '1001010010101000': 9, '0000110110101011': 2, '0000000101001000': 2, '0000110101001000': 1, '1000000110010101': 1, '0001111011101010': 1, '1001111100011010': 2, '0000110000101010': 2, '0001001011010100': 3, '0000011010011000': 3, '0001000001110100': 1, '0001001101101010': 12, '0010101101010100': 1, '1000100000111000': 1, '0000101000101001': 6, '0001000101010100': 1, '0000110100011010': 6, '0000001111011010': 1, '0000010010011011': 1, '0001000100010001': 1, '0100010110100101': 3, '0000000101101001': 11, '1111010101010111': 3, '0000000000101000': 7, '0001011010111010': 1, '0001100000101010': 2, '1001111001011001': 1, '0001001011101011': 5, '0000011100100001': 1, '0000011101011001': 4, '1101011100100100': 1, '0001110100011011': 1, '0001000011001010': 1, '0001010100001000': 2, '0010011011100100': 3, '0000010110011010': 1, '0000110011001010': 1, '0000011011010101': 1, '0000010001100110': 1, '1010100010111001': 1, '1000000011011011': 1, '0000010010011000': 4, '0001111101111010': 1, '0000101111011010': 2, '0000110011011010': 2, '0001001010101011': 4, '1100000101100101': 2, '0000100111011001': 5, '0111010010111001': 1, '0001000111101001': 14, '1000100010011010': 1, '0101110111100101': 2, '0000110011010101': 2, '0001110100111010': 2, '0000001100011001': 1, '0001011010010010': 1, '0001001100101011': 5, '0000111110101000': 11, '0001100101100100': 3, '0000110100011011': 1, '0000011000101001': 2, '0000010101011001': 6, '0001100110010101': 2, '0000010101001000': 1, '0001110110101010': 4, '0000110000100110': 1, '0000011001101010': 3, '0000000100101011': 3, '0001111011011011': 2, '1001111001101000': 5, '1111111100101010': 3, '0001001100001011': 1, '1001010101100101': 1, '0110001000100100': 2, '1000101011011010': 2, '0000010011101010': 3, '0000010100100110': 1, '0001110010011010': 1, '0000111100101000': 9, '0110110010111001': 2, '0001000110111001': 1, '0001110100101011': 1, '0001000101010001': 1, '1000101011101010': 3, '0000010011010100': 1, '0000100101001001': 2, '0000100101100000': 2, '1001010010101011': 2, '0000100110011001': 5, '0000111100001010': 1, '0000111101000101': 1, '0111011101101011': 6, '1110101010100100': 1, '0100001100010110': 1, '0011001010100101': 3, '0000000010101000': 12, '0000001011011001': 7, '0000000000011010': 1, '0001110110101000': 7, '0000101010101010': 6, '0000111111101011': 2, '0010010100100100': 1, '0101011011101001': 14, '0011111011101000': 2, '0001111110011000': 5, '0001011010010000': 1, '0000101101011000': 17, '0001011001101010': 2, '0000100001101010': 4, '0001000100100110': 1, '0000011100101000': 6, '0001010001100101': 1, '0000101111011001': 6, '0001010010111010': 1, '0001011010010101': 3, '0001100000101000': 3, '1001010110101011': 1, '0000111110101011': 1, '0100110010010100': 1, '0000010110100100': 1, '0001111111101010': 2, '0001110011011000': 7, '0001011110101011': 2, '0000110110001001': 1, '0001010000100101': 1, '0001100110100100': 3, '0001010110001001': 1, '0000001101001001': 1, '0001111000101000': 1, '0001100001011001': 2, '0001001001101001': 11, '0000101000101010': 3, '0001110000011000': 1, '0000001011011010': 1, '0001010110111000': 3, '1001010110101001': 2, '0000011010011010': 1, '0111011100101011': 7, '0000110100100100': 1, '0000011101111001': 1, '0001011111101000': 13, '0000010010101010': 3, '0001110111101011': 1, '0000001011010111': 1, '0000100010100100': 2, '0000111111010010': 1, '0000000100111000': 1, '0001010011011010': 5, '0000001111011001': 2, '0000101101010011': 1, '0000110011101001': 11, '0000110111011010': 1, '0010111110010101': 2, '0111010010100100': 3, '0000011010011011': 2, '0000111011011000': 5, '0010111010101000': 20, '0001001000110101': 1, '1110101001100100': 2, '0110111100010110': 1, '1100101011101001': 11, '0001000001101001': 6, '0000010111100110': 1, '0000001111010111': 1, '0000110101011000': 19, '0001000111010000': 1, '0000000111111001': 1, '0001000011011000': 25, '0000100001010100': 1, '0001001100011011': 1, '0001011011100110': 2, '0000110101100101': 4, '0001100100101010': 3, '0001100101101000': 16, '0000110001101000': 14, '0000110110101001': 11, '0001001110101000': 10, '0001000011101011': 4, '0000110100011001': 11, '0000110101101001': 20, '0000111100111001': 1, '0000110000101000': 11, '0001100010011001': 2, '0001100010011010': 1, '1001010101101001': 14, '0110000000100101': 1, '0001010111101011': 3, '0000110101001001': 2, '1100101010101001': 7, '0010110100100100': 2, '0000110111010100': 1, '0001000101111001': 1, '0100110111100101': 3, '0001010100011000': 29, '0000011000010000': 1, '0000111011010111': 1, '0001110100011000': 7, '1101011100100101': 2, '0000010110001001': 1, '0000000011011001': 1, '0000011111011010': 3, '0001101010011001': 3, '0111011100010110': 2, '0000110010011000': 13, '0001001110101011': 4, '0001111100011001': 2, '0001000101000110': 1, '0000001101100100': 2, '0000000010100001': 1, '1000001100011000': 4, '0000110011011011': 3, '0000010111010111': 1, '0001000110110100': 1, '1000100000101001': 1, '0110001011010100': 1, '0001000111100011': 1, '0001010111001000': 3, '0001110101111000': 2, '0101001110010101': 2, '0000000001011010': 1, '0000000101101010': 2, '0001000111101010': 8, '0001100101011001': 10, '0000110111001001': 1, '0001000010010001': 1, '0000110000111000': 2, '0001111110001000': 1, '0001000111100100': 2, '0001101011010101': 1, '0001000001101011': 7, '0001010101111010': 2, '0000001110011001': 2, '0001011010100110': 2, '0000101100011000': 11, '0001011110011000': 11, '0111000000010111': 1, '0010110101100100': 2, '0001011001010110': 1, '0001001000111000': 1, '0001011101010001': 1, '0001100011011001': 4, '0010101111010101': 1, '0010111011100100': 1, '0001101100100000': 2, '0001011101110001': 1, '0001101110101000': 8, '0001110100101001': 9, '0001010011010000': 1, '0001100011100000': 1, '0000111011111011': 1, '0001010101100110': 2, '0001100110101001': 6, '0001001100101010': 11, '0001011110111000': 2, '0001100110011001': 4, '0101011101101000': 18, '1001010110011001': 2, '0001010011011011': 1, '0000000101010100': 1, '0001001000011000': 9, '0101100100100101': 2, '0000111111011010': 2, '0001101101100110': 1, '1100100101100111': 1, '1000000110101011': 1, '0100000011010100': 1, '0000011000100111': 2, '0001111010111000': 3, '0001001101010001': 1, '0000100110010101': 1, '0000110101100001': 1, '0001110011010101': 1, '0000100101001000': 1, '1100100101100101': 3, '0001111010010101': 1, '0001011100101001': 23, '0001010110001010': 1, '0001011010101011': 6, '1001010101110100': 2, '0000111101011011': 2, '0001010001011001': 5, '0000010000101000': 3, '0000100111010101': 2, '0001111101011000': 6, '0001010111100100': 4, '0001011010011001': 9, '0101010101010100': 1, '0000001000011001': 3, '1001111100011001': 2, '0001101010011010': 2, '0001111011010000': 1, '0000110110010011': 1, '0000100001101000': 12, '0001010011101011': 4, '0001110101011001': 4, '1000000011101000': 9, '0001010110101000': 22, '0001000011100110': 3, '0100010111010101': 1, '0000010100100101': 2, '0000110101011011': 5, '0001101001101010': 1, '0001000111111001': 1, '0110110010100100': 4, '0000110100101001': 24, '0001001001100101': 2, '0011111100100100': 3, '0000110001011000': 7, '1000001100011001': 3, '0001110111100100': 1, '0000110011010110': 1, '0000000000011011': 2, '0001100000111011': 1, '0001011000011001': 6, '0000011100011011': 2, '0010111100100100': 2, '0001101100001000': 3, '1001010011001000': 1, '0000111001011011': 1, '0001011101100110': 2, '0000110111101011': 1, '0000101100111000': 1, '0001000101111000': 2, '0000101001101010': 2, '0000000101110101': 1, '0101011011100101': 2, '0011101010101000': 9, '1011111011101000': 5, '1001010110101000': 9, '1001010101100100': 5, '1111111100010110': 1, '0001011110010101': 2, '0000010010011001': 3, '0001001101101011': 6, '0001101011011010': 2, '0000001101111010': 1, '0000110001010100': 1, '0000010110011001': 1, '0000000100011000': 11, '0000010000001001': 1, '0001001001101010': 3, '0001000100010101': 4, '0001001011011001': 13, '0100111010101001': 15, '0000100101101011': 3, '1000000010100100': 1, '0001100010100110': 1, '0000010101100101': 2, '1000101001111000': 2, '1001010110011011': 1, '0001000011111000': 4, '0000011001101011': 1, '0000110100011000': 14, '0100001011101001': 4, '1001010101011000': 12, '0101110011100101': 2, '0001100011100100': 4, '0000011110111000': 1, '1011001101010100': 2, '1000101011000100': 1, '0000010100100010': 1, '0001001000101001': 6, '0000111110011001': 5, '0001100100010100': 2, '0000100101101010': 8, '0000111010100110': 1, '0000011001101000': 2, '0110110011111001': 1, '0001110001011001': 2, '0000110011110100': 1, '0101000101100101': 10, '1000001100101011': 2, '0000100010011010': 1, '0100011101101000': 5, '0000000010010100': 1, '0001110100101010': 3, '0000010111010100': 1, '1001010101100110': 2, '0001010111101010': 7, '0001111111011011': 1, '0001100010100001': 1, '0011101010100100': 1, '0001001011001000': 1, '0000010101101000': 22, '0001010100010101': 4, '0000111100010100': 2, '0000011100011010': 4, '0000010010100111': 1, '0001001010100110': 1, '0000111111000110': 1, '0001010000100100': 1, '0000100011101010': 2, '0000100011011011': 1, '0001000000001001': 1, '0001010101101001': 18, '0001110101001010': 1, '0000111101100111': 1, '0000010000100101': 1, '0001001100011010': 4, '0001011001101000': 9, '1110101001101011': 1, '0001001110111001': 1, '0000011010111000': 1, '0001000111100101': 3, '0000010101111000': 1, '0001111011011010': 1, '1001010101001001': 1, '0001101010011000': 5, '0001101111011010': 2, '0000000101011001': 7, '0001010001101000': 16, '0001110100100100': 3, '0000010101101010': 3, '1001010011011000': 5, '0001010111011011': 2, '0001000100101010': 10, '0001000100001011': 1, '0000011011101010': 4, '0000110010101000': 26, '0001111100101000': 5, '0001101010001001': 1, '0000100110100100': 3, '0000111000101000': 4, '0011001100010100': 2, '1110101011010110': 1, '0000010100011011': 2, '0110100000100101': 1, '0000011100010100': 1, '1000000011011000': 7, '0000101001101001': 4, '0000110010011010': 3, '1100101101010110': 1, '0001001100011000': 21, '0000011101001001': 1, '0000010101011010': 3, '1000101011010101': 1, '1100100111010111': 1, '0001101101011001': 2, '0000010100010101': 3, '0000111101011010': 5, '0100010110010101': 1, '0001011101011001': 20, '0001101100101000': 12, '0000011110011011': 2, '0000001110101010': 1, '0000100110001000': 2, '0000111000010000': 1, '0000111100011001': 8, '0011000010111001': 1, '0001011111010000': 1, '0111000101010110': 1, '0001001101101001': 26, '0001100111111011': 1, '0001110100100101': 1, '0001010110101010': 2, '0000111001011001': 4, '0000111010011001': 4, '0000111001011000': 5, '0110101011010100': 1, '0001011110101010': 4, '0100000010101001': 6, '0001010100011010': 3, '0001010011100111': 2, '0001001101100010': 1, '0001110101100100': 2, '0000011111011011': 1, '0001000110010100': 2, '0001010001001010': 2, '0001011110010001': 1, '0001000010011000': 20, '0001000100100100': 8, '0000110001100000': 1, '0000101000010111': 1, '0001000010111011': 1, '1111010111100100': 1, '0011101100010100': 2, '0000001011001000': 1, '0011000010010000': 2, '0000111000010100': 1, '0000101010110100': 1, '0001001001011011': 1, '0000010001010101': 1, '0000101111011000': 10, '0110110011010100': 1, '0001000101011001': 15, '0000110000001000': 1, '1000001100101001': 5, '0001100101001001': 2, '0001100011011000': 4, '0001000110011011': 1, '0000110111101000': 15, '0001000101101011': 4, '0001010011101010': 5, '0001000100100000': 1, '0000000100101001': 11, '0000111101001001': 1, '0000010010010001': 2, '0001000001101010': 8, '0000100110001001': 1, '0000001000011000': 3, '0001111111101000': 7, '0000110011010111': 1, '0001001000010100': 3, '0000111010010000': 1, '0000011111111001': 1, '0001001110100100': 4, '0000110100111001': 2, '0001110010011011': 3, '0001000011000100': 1, '0001101000101001': 2, '1000000010101011': 2, '0001101001011001': 1, '0001100001101001': 2, '0000110100111000': 3, '0001000010111000': 2, '1001010010011000': 3, '0101011110010100': 2, '0110000011100111': 1, '0001000011100000': 1, '0001000100001000': 4, '0011001011100100': 1, '0001101000011010': 1, '0000100011010101': 2, '0000100101010101': 3, '0111101010010100': 1, '0101001000100110': 2, '0001101110111010': 1, '0000001101010100': 1, '0001010111100110': 3, '0000000100001001': 1, '0001000100011000': 27, '0001010001101010': 7, '0001011100011001': 10, '1001010011101001': 5, '0110111100101011': 2, '0001010000011001': 6, '0011001011101000': 26, '0110000001100100': 1, '0000100110011011': 1, '0001100001101011': 1, '0001001110011011': 1, '0000111010011011': 4, '0000000001101011': 2, '0000110111100000': 1, '0001010011011000': 16, '0001000011011001': 21, '1011011101100100': 4, '0001011100001000': 3, '0000011110011010': 2, '0000010111101000': 8, '0001101000011000': 1, '1000000010100110': 1, '0000010111100100': 1, '0001010100111001': 2, '1000101011100000': 1, '0000000001011001': 4, '0001100010100100': 2, '0001010101100000': 1, '0000011001101001': 4, '0000111110000110': 1, '1000001100010111': 1, '0000100100111010': 1, '0000001101101011': 1, '0001111111011001': 3, '0001001011010000': 1, '0001010001010100': 1, '0001100110111001': 1, '0000110010010101': 3, '0000101100001010': 1, '0000001010011001': 4, '0001011011101011': 2, '0000010110010100': 1, '0000110100010000': 1, '0000101001011000': 1, '0000110110111011': 1, '0101001010101001': 24, '0001101101100101': 2, '0000010101011000': 6, '0001000000011001': 7, '0000110100001001': 2, '0000010100101010': 8, '1001010010101010': 4, '0000111110101010': 3, '0000111110110101': 1, '0111110101010110': 1, '1000101011010100': 1, '0001011101011010': 8, '0000101000001000': 2, '0000111111110100': 1, '0011001010101000': 21, '0001010001011011': 1, '0000010110100000': 1, '0000001100011011': 3, '0000000100101010': 5, '0000100101110111': 1, '1000000110011001': 2, '0001001000111001': 1, '0000101100001011': 1, '0101111101101000': 8, '0000110011110110': 1, '0101111011100101': 1, '0000011101010010': 1, '0101010111010101': 1, '0101100100010100': 1, '0001000110011001': 8, '0001000111111011': 1, '0001100001011000': 3, '0001110101011000': 11, '0000101101110111': 1, '0001010010010001': 1, '0001010111111000': 4, '0000101100101001': 16, '0001011100001001': 1, '0000111000001001': 1, '0001000110101010': 5, '1000000011011001': 1, '0000100010011000': 12, '0110000000100100': 2, '0001000110101000': 29, '0001100101011011': 1, '0001100010100000': 3, '0000010100111000': 1, '0000110011011001': 5, '0001110101101011': 3, '0111100000100100': 3, '0010111011101000': 20, '0000111001101000': 10, '0001001100001001': 2, '0001010111111001': 1, '0000001001101001': 2, '0110101011111000': 1, '0011110010100100': 2, '0000001101101001': 9, '0001000010010100': 2, '0000010010010100': 2, '0000110001011011': 1, '0001011111011010': 1, '0000000101101000': 16, '0001010010100110': 2, '0001000000101010': 2, '0001010000001010': 2, '0000010010101000': 17, '1001010101101000': 33, '0001011101010011': 1, '0000101000011010': 1, '0000011110011001': 1, '0000101100001001': 1, '0000001100011000': 7, '0000011000101010': 1, '0000000111001000': 1, '0111011101010110': 1, '0000101010011001': 5, '0100000100100101': 1, '0000101011011001': 2, '1000100010101000': 6, '0001011110001001': 3, '0000001011101010': 3, '0000100011111000': 2, '0001110001101010': 3, '0000000000101001': 3, '0000111010101010': 3, '0000110010110100': 1, '0000110100101010': 7, '0000111010010110': 1, '0001001010100010': 1, '0100011100100101': 1, '0000101110101011': 1, '0001001111001010': 2, '0001001111011001': 4, '0001000011101000': 34, '1001010110111000': 2, '0000101010010101': 1, '0001011001011000': 7, '0001000101100100': 5, '0000110001101001': 7, '0101101011010100': 1, '0000111111100100': 1, '0101000100010100': 2, '0001101100100100': 1, '0000100011101000': 25, '0001010001011010': 2, '0000000000010101': 1, '0000110010001010': 1, '0000101110100100': 4, '0000011111001001': 1, '0000110101101010': 9, '0001000111100001': 1, '0000111011011011': 3, '0111000101100111': 1, '0001101110101001': 3, '0101010011100101': 9, '1111111101101010': 1, '0001011100010000': 1, '0001110101011010': 1, '1001010010101001': 4, '0001010100101011': 11, '0001000101001000': 4, '0000001010111010': 1, '0001011101010100': 4, '0000100010000101': 1, '0001010001111001': 2, '0000110011111010': 1, '0001111100011010': 1, '1000101011011011': 1, '0001010110111001': 1, '0001010100001010': 2, '0000111001101001': 5, '0001011100101000': 28, '0001000111011001': 8, '0111011100010101': 1, '0110111100111000': 2, '0000000010011000': 4, '0000111110100100': 1, '0011101011101000': 7, '0010100100010100': 2, '0001110101100101': 4, '0001110001010100': 1, '0001000011010100': 2, '0000011101011011': 1, '0001010010111000': 3, '0000000101011000': 11, '0001011111011000': 7, '0000011111101010': 2, '0000100110011000': 5, '0000100100110110': 1, '0001000011010111': 2, '0001001111100101': 1, '0111001000100100': 3, '0000011111011001': 1, '0000011011011010': 1, '0001000111101000': 22, '1000100010101011': 2, '0000000111011001': 2, '0001001011011011': 2, '0001010110001000': 2, '0001011100100000': 1, '0000011001011000': 2, '0001101100010010': 1, '0001101101101010': 1, '0000101010111001': 1, '0001010001011000': 10, '0001000101001011': 2, '0000001011101011': 2, '0011111010101000': 9, '0001011001011001': 2, '0000111111011001': 6, '0001110110101001': 8, '0000111111010110': 1, '0000101101010000': 1, '0000010010110011': 1, '0000000100011001': 3, '0000000010010111': 1, '0000011011110101': 1, '0000011001011011': 1, '0100101000101000': 13, '0100000011101001': 1, '0110101000100100': 1, '0000100011100100': 4, '0100111100100101': 2, '0000011100011000': 10, '0001010101010101': 3, '0000001010001001': 1, '0000110101111001': 2, '0000110000011010': 1, '0100111011100101': 2, '0000110001010001': 1, '0001010010101000': 33, '0001110000101001': 3, '0000100011100000': 1, '0001000011101010': 11, '0000111010100001': 2, '0000101101101001': 15, '0000001001101010': 1, '0000100001011000': 7, '0001011011001001': 1, '0000100001011011': 1, '0000011101100000': 1, '1100100100100101': 2, '0001001001010101': 1, '0000110100100101': 5, '0000100001101001': 6, '1001111100101001': 1, '0001000111011011': 3, '1000100010110110': 1, '0000110011111000': 1, '0001001101101000': 37, '0000111101010100': 4, '1111010011111001': 3, '0011110011100100': 3, '1110101001010101': 1, '0001100010000001': 1, '0001001111011010': 6, '0000100111001000': 2, '0000101111100010': 1, '1000001100101000': 4, '1001010101111000': 1, '0000100100101001': 15, '0001010101011010': 3, '0000101100100000': 2, '1100101010100100': 1, '1111010111010100': 1, '1001010101011011': 3, '0000001100101001': 7, '0000111101001000': 2, '0000010010101011': 2, '0111000000010101': 1, '1110101011010100': 1, '0001001100010111': 1, '0000111000011000': 5, '1000100000101000': 8, '1001010010011001': 2, '0100011100101000': 7, '0001001100110100': 3, '0000100111110100': 1, '0000110111011000': 9, '0000000010000100': 1, '0001011011110101': 1, '0000010001100100': 1, '0000011011001000': 1, '0000010011101011': 1, '0001011001001000': 1, '0100011101100101': 2, '0000000100001000': 3, '0000010010011010': 3, '0001001011101010': 9, '0101111101100101': 1, '0001110000011011': 1, '0001001000010101': 1, '0001001111100100': 4, '0001000001011010': 4, '0111011010100101': 1, '0001100001011010': 2, '0010001101010100': 1, '0000001110011000': 2, '0001101011101011': 1, '0001111101011001': 5, '0001010010011000': 16, '1011011011101000': 27, '0001010000101010': 4, '0000110000111001': 1, '0000101100011010': 2, '0001011011010101': 2, '0011010100100100': 6, '0001011101111001': 2, '0001000111010100': 2, '0010101010100111': 1, '0001010100111011': 1, '0000011000101000': 2, '0001011110001000': 3, '0001110100111000': 2, '0010001011101000': 5, '0000110010011001': 7, '0100100011010100': 1, '0000010100011010': 1, '0000110110101000': 10, '0110111101101010': 8, '0000101100101011': 6, '0001100110100011': 1, '0001000010001001': 1, '0001101101110001': 1, '0000010101011011': 2, '0100000010010100': 1, '0101101011101001': 4, '0101001000101000': 10, '0001011010001000': 2, '0001110001101011': 2, '0001101101101011': 3, '0000101100001000': 1, '0000000101111001': 1, '0001101110101010': 1, '0001000001011001': 5, '1000000010101010': 1, '0000100111000110': 1, '0000001111011000': 2, '0001000010011001': 7, '0001010111101001': 14, '0100011101100100': 2, '0101000011101001': 10, '0000100100100110': 1, '0000110011101011': 2, '0000110100110100': 1, '0101111111010100': 2, '1100100101010100': 3, '0000101110101010': 2, '0101000011100101': 1, '0001100011010100': 2, '0001110011110100': 1, '0000101101101010': 2, '0101100101100101': 1, '0001000111101011': 1, '0000000101010000': 1, '0001010110101011': 2, '0101110101010100': 1, '0000000001101010': 1, '0000101100010000': 1, '0000011111101001': 2, '0000001101011000': 13, '0011011100100100': 1, '0001111011101011': 5, '0000001011010101': 1, '0001001101100000': 3, '0000100000101010': 3, '0001010101101000': 30, '0000000001011000': 2, '0000010011101001': 14, '0001001110101001': 10, '1001010101010001': 1, '0000100000100111': 1, '0001001000011001': 4, '0001001011111001': 1, '0001000000011010': 1, '0000101100101000': 25, '0001001111111011': 1, '0000010001011000': 2, '0001011101101001': 19, '0001111111011000': 2, '0100111010100101': 1, '0000100011011001': 8, '0000110010010110': 1, '0001111010111001': 3, '0001101100011000': 13, '0001011101011000': 17, '0000011110101001': 10, '1000100000011001': 1, '0001001110100101': 1, '0000110011101010': 5, '0101111100100100': 1, '0001011100011011': 3, '0000110010100110': 1, '1001010011010101': 1, '0001000010000100': 2, '0110001011111000': 1, '0001011100010100': 2, '0001101100100011': 1, '0001100001010010': 1, '0000011011111000': 1, '1111010011100100': 3, '0001110010101000': 13, '0000101111111000': 1, '0000101100010100': 2, '0000001111100100': 2, '0000100010101011': 5, '0001011111011011': 2, '0001010110011001': 9, '0000100110101000': 12, '0000011010101011': 2, '0000110000011000': 5, '0001011011011011': 1, '0001001111101000': 12, '0000011001100100': 2, '0001000010101000': 39, '0000111101101000': 5, '1011010011100100': 3, '0110001010010100': 1, '0001100000101001': 4, '0000110010101011': 3, '0110111100010101': 5, '0001001010001011': 1, '1000100010101001': 3, '0110110100010111': 1, '0001010010011001': 17, '1010000011100101': 2, '0000100011001000': 3, '0000000011011011': 1, '0001100100010101': 1, '0001001000101010': 3, '0111101101010110': 1, '0000100101001010': 2, '0110010101010110': 1, '0000111000111000': 1, '0111011100111000': 6, '0001011110010111': 1, '0000100011010111': 1, '1110000101010110': 1, '0000111101010000': 2, '0000100001101011': 2, '0001010100101000': 57, '0001100110101000': 3, '0001000010100000': 2, '0001001000011010': 2, '0000100110100101': 4, '0001010111111010': 1, '0001000101011000': 28, '1011011010101000': 30, '0001001101010101': 1, '0000110110011000': 6, '0000110001101011': 1, '0110010100010110': 1, '0001000111010101': 1, '0100100110010100': 2, '0001011000101000': 10, '0001001100111000': 3, '0001101111101000': 7, '0000100100101000': 25, '1001010011011011': 1, '0001001010001001': 1, '0001110111101000': 7, '0000110010101001': 14, '0001010000101001': 19, '0000010011011000': 5, '0000001100100100': 2, '0001110010010100': 1, '1001010101001000': 2, '0000110000010100': 1, '0001100101101001': 12, '0010011101100100': 1, '0001010100001001': 1, '0001011000011010': 3, '0000111110001000': 1, '0001010101000100': 1, '0000001001100101': 1, '0000011111101011': 1, '0000100011011000': 13, '0000010000010000': 1, '0000101110100101': 2, '0000100100100000': 1, '0001001011100001': 1, '0000110010111000': 2, '0000101101011010': 3, '0001110010100110': 2, '0101001011010100': 1, '0000110111001000': 1, '0001001100101001': 26, '0000000100010100': 1, '0001001111100001': 2, '0001010010011011': 4, '0001110101101000': 15, '0100011110010100': 2, '0001111010011010': 1, '0001010100100000': 3, '0000000100100100': 3, '0001011111101010': 3, '0001010011110101': 1, '1000000110101000': 12, '1000101011000101': 1, '0001100101010101': 1, '0010001101111001': 1, '0001111101011010': 1, '0000100111100011': 1, '0001110110101011': 1, '0001011100011010': 4, '0000001101101010': 1, '1101010100010100': 3, '0000000111100100': 2, '0000010100111010': 1, '0100101001101000': 13, '0000101010010100': 3, '0101011010101001': 14, '0001001001011001': 4, '0001100000011011': 2, '0010101010101000': 23, '0001000010101001': 16, '0001011010001001': 2, '0001110010010101': 2, '0001001010011010': 1, '0001110100100111': 1, '0001101100111011': 1, '0001010001111000': 1, '0001010101010100': 1, '0000000100011010': 6, '0001000110100100': 1, '0000000111011011': 1, '0000110100100110': 2, '0001010011100110': 2, '0001110110011011': 1, '0100110110100100': 1, '1000000110100000': 1, '1000000110011011': 1, '0001110001101000': 5, '0000010110101010': 1, '0001010111010111': 1, '0001011111010110': 1, '0111000001100100': 1, '1000000011010101': 1, '0001000011011010': 8, '0000010110010111': 1, '0001110101101001': 17, '1001111001101001': 4, '1001010011101000': 8, '0001011101001000': 1, '0001110110011000': 4, '0110110011100100': 1, '1000101000010100': 1, '1000101011101011': 4, '0000001100101000': 9, '0001101011011000': 5, '0001100100011000': 6, '0000101100110100': 1, '0001010010010000': 2, '0001010010001001': 1, '0001101011011001': 2, '0001111111100100': 1, '0001111100101001': 4, '0011010110100100': 1, '0111011100101010': 12, '0000001111011011': 1, '0001010111000110': 1, '0001011100000000': 1, '0111001010010100': 1, '0110100001100100': 2, '0000100000001001': 1, '0000100100010011': 1, '1000000110101001': 5, '0110010110100100': 1, '0100111011101001': 14, '0001101110100100': 2, '0001001010100001': 1, '0101000010101001': 12, '1000101011011001': 6, '0101000100100101': 1, '0000101110010110': 1, '0001011101011011': 4, '0001010000010100': 1, '0001001101100100': 2, '0001110111011010': 2, '0001010111011010': 5, '0000101011011000': 1, '0001100011110111': 1, '0001000101101010': 13, '0100111100101000': 9, '0000000011101011': 1, '0000010000011011': 1, '0001010000011000': 7, '0001101010100000': 1, '0000000001111001': 1, '0000011101011000': 14, '1000000011111000': 1, '0001010101101011': 3, '0110111100101010': 4, '0000100010010100': 1, '0000101000011001': 3, '0001001101001001': 1, '0000100000011000': 3, '0000111000011010': 1, '0000100001011001': 1, '0001111000011000': 1, '0011000011100101': 3, '0110100010100111': 1, '0001000101100010': 1, '0111101010100100': 1, '0110100001010111': 1, '0001010010011010': 4, '0000010101110111': 1, '0100100011100101': 1, '0000000011101001': 2, '0000110101100100': 2, '0010011011101000': 10, '1001010101111001': 1, '0000110011001000': 4, '0001001111011000': 8, '0000010101100100': 4, '0101100011010100': 1, '0111111100010100': 1, '0001101100010101': 1, '0000001111101011': 3, '0100010010100101': 1, '0000110011100110': 1, '0001110111011000': 4, '0001001000001011': 1, '0000111011011001': 6, '0000111111101001': 8, '0001001110011010': 4, '0000001111101000': 10, '1000100010011000': 7, '0101110110010101': 1, '0000101010011011': 1, '0001011000101001': 7, '0010011010101000': 7, '0110100111100110': 2, '0000000001101000': 3, '0110011100100110': 1, '0000011110101000': 6, '0000011110101010': 4, '0100000010100101': 1, '0001101101101000': 14, '0100101100100111': 1, '0000010111101001': 6, '0001100010101000': 16, '0000111110011010': 1, '0001000111111000': 2, '0001110101001001': 1, '1000000010101000': 3, '0001010110110100': 1, '0001000110101001': 16, '0001110010101010': 3, '0001101110011000': 8, '0100010111100100': 1, '1001010101011010': 5, '0000110000101011': 2, '0001001100101000': 38, '0000110010100111': 2, '0001000111011000': 10, '0111100100010110': 1, '0000100101011001': 19, '0001111010101010': 2, '0000100110101010': 2, '0100011000100101': 1, '0000001100010101': 1, '0001101111101011': 1, '0001100111011011': 3, '0000110001001000': 2, '0000101100100101': 3, '0000010101101001': 8, '0001100100101011': 2, '1000000010101001': 2, '0000110111011001': 6, '0000111010010100': 1, '0100110100010100': 5, '0001110011011010': 1, '0001111111100110': 1, '1000000110111000': 1, '0000101001011001': 2, '0000010010101001': 15, '0001111100111010': 1, '1000001100100101': 2, '0001011111100101': 2, '0000010010010111': 1, '0100110110100101': 6, '0001100000100110': 2, '0001011110101001': 12, '0001100010101011': 2, '0000100101010000': 2, '0001100101100000': 1, '0001011001100100': 1, '0000000010100110': 1, '0110011100101011': 2, '0001001010010101': 3, '0000100110101011': 1, '0100111101101000': 15, '0000001000101001': 4, '1010001011101000': 8, '0001111011010101': 1, '0000100101011010': 3, '0000011101101000': 6, '0001001111011011': 1, '0001110011101010': 3, '1001010101100000': 1, '0001001101111010': 1, '0000011111100100': 3, '0001011110100000': 1, '0001001101010000': 1, '0001010001101011': 4, '1000000011010100': 1, '0001100011101000': 12, '0001110011100000': 2, '0110110100010110': 1, '1000001100101010': 1, '0000011011100111': 1, '0001110101010100': 1, '0011100101010100': 2, '0000010100100100': 3, '1000100010100100': 1, '0101101000101000': 8, '0001000011101001': 10, '0001100101011000': 4, '0001001110101010': 6, '0101001100100111': 1, '0000010011011011': 1, '0000100010101001': 5, '0001100100111011': 1, '0001110001101001': 2, '0000100010111000': 1, '0001100000000100': 1, '0001000100111000': 2, '1001010011010001': 1, '0001001010001000': 1, '0110011100111000': 3, '0001010000101000': 25, '0000110100101000': 39, '0000110101000101': 1, '0001010011101000': 31, '0000101111010100': 1, '0011110110100100': 1, '0001011001101001': 10, '0111011011100101': 1, '0001011010100000': 2, '0000110100100000': 1, '0000001101101000': 16, '1000000011101001': 5, '0000011101010000': 1, '0000010011101000': 19, '0110100001100101': 1, '0100110010100101': 2, '0000111010111001': 1, '0001001010100000': 1, '0001010110010111': 3, '0001100100001011': 1, '0000000101101011': 1, '0001010000001000': 1, '0000001101111000': 1, '0000001011000101': 1, '0000100100101011': 6, '0001101110100110': 1, '0001110011101001': 7, '0000110101100000': 4, '0111011101101010': 7, '0001100101010000': 1, '0001010111011000': 14, '0000100100100100': 4, '0000110001011001': 3, '0000111100100111': 1, '0101000010111001': 1, '0001001001011000': 10, '0000101101011001': 10, '0000111011110100': 1, '0001101100101011': 3, '0000110000111011': 1, '0110011101111000': 1, '0001001100100110': 3, '0111101010010101': 2, '0001110000011001': 2, '0001010010101011': 8, '0001011011111000': 1, '0001100111011000': 2, '0001001010011001': 17, '0100011011101001': 11, '0000100111111000': 1, '1001111100101000': 3, '0110111101010101': 2, '0110001010100100': 3, '0001011010011010': 4, '0001100101101011': 2, '0000101010000100': 1, '0000011111001000': 2, '0010111010100100': 6, '0001011111001001': 1, '0011000101010111': 1, '0001011101111010': 2, '0100001100100111': 1, '0101100011010110': 1, '0001000000101001': 11, '0111010011100100': 1, '0000001111101001': 3, '0000100100101010': 11, '0000110110001000': 1, '0001111000101001': 1, '0000000010111011': 1, '0000011010011001': 6, '0001000010101011': 7, '0101100010101001': 3, '1001010101000100': 1, '1010000010100101': 2, '0001000101100000': 2, '0100111101100100': 3, '0001111011011001': 3, '0001111111101011': 1, '0000100100111001': 3, '0001101101010101': 1, '0001010101100101': 4, '0001101111011001': 2, '0000000101100100': 5, '0001000100011010': 7, '0000011100101001': 10, '0111000000100100': 2, '0000100111101001': 12, '0000010100101011': 3, '0001010000010101': 2, '0000011011011000': 10, '0000011000011000': 2, '0000111001101010': 1, '0001011011011010': 2, '0000001101100101': 1, '0011011110010101': 2, '0000011011011001': 4, '0001110011101011': 6, '0000010100011000': 12, '0000100101111000': 3, '0000010000010100': 1, '0000110011011000': 16, '0000010110011000': 6, '0001110011010100': 2, '1001010011011001': 2, '0001000110100101': 1, '0010101011101000': 15, '0001001101110101': 1, '0001100111101000': 7, '0000001000011011': 1, '0000101111100100': 1, '0010001011100101': 1, '0110001001101011': 1, '0111000011100111': 1, '0000000100100110': 1, '0001111110101000': 8, '1000000110011010': 2, '0000111111101000': 11, '0000110001001010': 1, '0100011011100101': 1, '0011110101100100': 1, '0000001101011001': 5, '0001110011011001': 2, '1101011100101000': 20, '0001110010011000': 5, '0000100100011000': 21, '0001011001001001': 1, '0001100000011010': 1, '1000100000011000': 4, '0001000111010010': 1, '0011000100010100': 2, '0000001010110101': 1, '0100100010101001': 9, '0001000101101001': 34, '0000100111011010': 1, '0111000110000101': 1, '0000101000111000': 1, '0000010000011000': 3, '0001101101011011': 2, '0101011111010100': 1, '0001111011111010': 1, '0001100100011010': 2, '0001011111011001': 1, '0001010011010100': 4, '0001011001001010': 1, '0001101100100101': 2, '0000010000011001': 2, '0000111110011011': 1, '1000000110011000': 2, '0000100111100101': 2, '0001010100100100': 1, '0000100101101000': 32, '0001100100101001': 10, '0001010100101001': 36, '0001011001011011': 1, '0001111101011011': 2, '1000000110010100': 1, '0000110111101010': 6, '0000100001100110': 1, '1001010101011001': 10, '0111110011100100': 2, '0001111000011010': 1, '0001000001101000': 16, '0001101110011001': 2, '0001000010100100': 5, '0000110100100001': 1, '0000001001001000': 1, '0110011101101011': 1, '0001111110011010': 1, '0001100111010100': 2, '0001000011010101': 1, '1000100000100001': 1, '0001001010101010': 7, '0001011001011010': 1, '0000101110011000': 4, '0001001100010100': 3, '0001001011011000': 16, '0000100011101001': 8, '1110100000100100': 3, '0001011100011000': 20, '0001001110011000': 5, '0001110110001011': 1, '0000101001111010': 1, '0100001010100100': 1, '0001111010011000': 3, '0000000101100000': 1, '0000100100011010': 4, '0000111011010100': 1, '0001001101100101': 7, '0001110110100110': 1, '0001110100101000': 18, '0101000011010110': 2, '0001110010110001': 1, '1101111010101001': 1, '0001011011001000': 2, '0111001100010101': 2, '0001001100100101': 4, '0001001110011001': 11, '0000001100110110': 1, '0001010110011000': 7, '0001011011101010': 7, '0001101100101001': 12, '1001010101101011': 2, '0000000011011000': 6, '0001001011011010': 4, '0000001010011010': 2, '0001111101101000': 5, '0001010110101001': 9, '0000001111101010': 1, '0001100010101010': 3, '1110000111100110': 1, '0000110001011010': 1, '0000111111011000': 5, '0100000100010100': 1, '0111000001100101': 1, '0000100000110100': 1, '0001001100100001': 1, '0001100100111010': 2, '0001011010010100': 1, '0000001011110000': 1, '0000101010011000': 13, '0000110000010101': 1, '0000111111111000': 1, '0101111101100100': 1, '0111101010111000': 1, '0001001001011010': 3, '0000000100010101': 1, '0000001100011010': 2, '0110111101101011': 2, '0000011110011000': 1, '0000010111101011': 2, '0101111100101000': 4, '0000000010011010': 1, '0000011111111000': 1, '0001101101100100': 1, '0001001001010100': 1, '0001000011011011': 5, '0110011101101010': 2, '0001001111001000': 1, '0001010111100111': 1, '0000001110100001': 1, '0000000011100100': 2, '0000001011010100': 1, '0001101111011000': 4, '0000010111001001': 1, '0000101110010100': 1, '0001011010011000': 18, '0001000110011000': 7, '0010100011010000': 2, '1110101011111000': 1, '1011001101111001': 1, '0001110111101001': 5, '0011001100111001': 1, '0001111100000100': 2, '0001000011001000': 1, '0001100001101000': 1, '0001001110001010': 1, '0000000011101000': 6, '0000001110100101': 1, '0001010001100100': 2, '0001000010111010': 1, '0000010001101000': 7, '0000101101100101': 3, '1110101011100100': 1, '0001000001011011': 1, '0001010111011001': 13, '0110011100101010': 3, '0110101001010101': 1, '0000110111101001': 9, '0001010100110101': 1, '0000100010101000': 13, '0111001011010110': 2, '0001001111101011': 1, '0001000101001001': 2, '0000001001011001': 1, '0001101111100000': 1, '0000101101111010': 1, '0001100000100000': 1, '0001011111100100': 1, '0000111011101011': 3, '0000011111011000': 2, '0001101100101010': 1, '0000100011110100': 1, '0110111101111000': 3, '0001100100101000': 17, '0100011010101001': 6, '0001011000010100': 2, '0000010000101011': 1, '0000101110101001': 2, '0001011000100001': 1, '0001001101001000': 1, '0100001110010100': 1, '0001000010101010': 9, '0001101001111001': 1, '0001010001101001': 12, '0111100011100111': 1, '0000010010110100': 1, '0111001011111000': 2, '0000100101101001': 20, '0001001101110111': 1, '0001110010101011': 3, '0111101001101011': 1, '0000110100010101': 4, '0001000101111010': 1, '1000000110100101': 1, '0001010001001011': 1, '0000010000101010': 3, '0000111011000100': 1, '1000101001101010': 1, '0011010101100100': 4, '0001100101011010': 1, '0001001100100100': 8, '0001001100000100': 1, '0001011000011000': 6, '0001110010000100': 1, '0001101101111000': 2, '0000000100111001': 1, '0001000001001011': 1, '0001000101011011': 4, '0000110101101000': 13, '0000011110110100': 1, '0001000010010101': 1, '0001011010111001': 1, '0000101101100100': 1, '0000101010110101': 1, '0000101011100110': 2, '0000010001101011': 1, '0001001111101010': 4, '0001001100001000': 2, '0000101010100110': 1, '0001100100011001': 5, '0011000011010000': 1, '0000010001101001': 3, '0000100111100100': 7, '0001001000100111': 1, '0001111101101001': 9, '0000011010101010': 1, '0000010000011010': 1, '0000101101011011': 2, '0000000100010010': 1, '0000001010101011': 1, '0000000001101001': 6, '0000010100101000': 22, '0001000100010100': 2, '0000100000010001': 1, '0000101100110110': 1, '0001110111011001': 1, '0001111010011001': 1, '0000110010101010': 6, '0100001011100100': 1, '0000001000101010': 2, '0101000010100101': 2, '0001111100011000': 4, '0001111011010111': 1, '0001011101110100': 2, '0000001101011011': 2, '0000100011101011': 4, '0001000100101001': 34, '0001000110011010': 5, '0110111101100110': 2, '0001111110011001': 2, '0000111000111010': 1, '0000011001011010': 1, '0100111100100100': 4, '0001000100011001': 13, '0110110010010100': 1, '0010101010100101': 1, '0001000100111011': 1, '0101011101100100': 4, '0101001010100100': 2, '0001110010101001': 9, '0001011001101011': 1, '0001100011011011': 2, '0010101110010101': 1, '0001010011001010': 1, '0001011001111011': 1, '0001000101010101': 4, '0000101011101011': 1, '0000110101101011': 5, '0101001100010110': 1, '0000101000011000': 5, '0001101010101010': 3, '0000100101110101': 1, '0000011000111001': 1, '0101011001100101': 1, '0000100110011010': 2, '0101011010100101': 2, '0100011011010100': 2, '0001100111010001': 1, '0001010100010010': 1, '0000110000100101': 3, '0001010101011001': 9, '0010011000010101': 1, '0001010101011011': 2, '0001110110111000': 1, '0001101110001000': 2, '0000001001001001': 1, '0100101011101001': 9, '0000000100101000': 16, '0100100010010100': 5, '0000100010011011': 3, '0000100111101010': 1, '0100111111010100': 1, '0001001111101001': 6, '0000110010100001': 1, '0001011011011001': 9, '0000101100010001': 1, '0001000101101000': 46, '0100100010100101': 3, '0101001011100100': 2, '0000110010100011': 1, '0001010000101011': 1, '0000111011010101': 1, '0000100101100110': 2, '0000101100011001': 8, '1011010111100100': 1, '0001111101000100': 1, '0001011000100000': 1, '0001000011100001': 1, '0000100100011011': 1, '0000100111101000': 22, '0001010010101001': 27, '0001000111000100': 1, '0001000001100110': 1, '0000110100101011': 1, '1001010110011000': 2, '0000000010100010': 1, '0000110100111010': 1, '0001001101011001': 8, '0001101111101001': 1, '0001010011011001': 10, '1000100000011011': 1, '0011111010100100': 3, '0000000100011011': 1, '1010000010111001': 2, '1001010010010100': 1, '0101110111010101': 1, '0000110110011001': 14, '0001100111101010': 1, '0000110000010110': 1, '0001010011101001': 13, '0000110101110101': 1, '0000110000100100': 1, '0001000000011000': 6, '0000010000100100': 1, '0000001011011011': 1, '0000111011100010': 1, '0101010110100101': 1, '0001000011100100': 1, '0000001001011000': 2, '1001010011101011': 2, '0000000010101010': 3, '0000110101010101': 4, '0000000101011011': 3, '0001111111101001': 2, '0000111000100110': 1, '1001010011100000': 1, '0000011111100101': 1, '0011111011100100': 1, '0000001110101001': 4, '0000110100001000': 2, '0000100011010100': 3, '0001110101100000': 1, '0101110010100101': 1, '0000010011001001': 1, '0001000001100001': 1, '0001000001010000': 1, '0001011101110011': 1, '0001011101111011': 1, '0000111101011001': 8, '0001011000010000': 1, '0001011011011000': 10, '0110110111100100': 1, '0000010001011001': 1, '0001101100011010': 3, '0001010101011000': 13, '0000101101111000': 2, '0101001001101000': 7, '0000110010111010': 1, '0001110100111001': 4, '0000101111101011': 2, '0001001110010110': 1, '0001000101110110': 1, '1001111100010111': 1, '0000110011101000': 32, '0110001100010101': 1, '1000100010011001': 1, '0000000111101001': 2, '0000110101100111': 1, '1010001010101000': 17, '0001110011001000': 1, '0001001110111000': 1, '0010011010100100': 1, '0101101001101000': 3, '0000110100010100': 2, '0001100010101001': 3, '0000010000101001': 4, '0000010111011010': 1, '0000100100010101': 1, '0000001011100110': 1, '0000000111101000': 4, '0100001001101000': 1, '0000000100010000': 2, '0000001110101000': 5, '1000000011001001': 1, '0000000111011000': 4, '0000110111111000': 3, '1000000011101010': 1, '0001100101100110': 2, '0000010110111000': 2, '0000001011011000': 9, '1001111001100100': 1, '0011011001010101': 2, '0001001100011001': 21, '1011011010100100': 5, '0001011101100111': 3, '0000010001101010': 1, '0001000110111011': 1, '0100111010010100': 3, '0000100111011000': 8, '0001100001101010': 3, '1000101011011000': 10, '0000110001100100': 3, '0001011111101011': 1, '0000110101111011': 1, '0001001101111000': 2, '1000101011001000': 2, '0000110010010100': 1, '0000010100101001': 13, '0101010111100101': 3, '0001000001000111': 1, '0000111101011000': 12, '0000100110111001': 2, '0001100110101011': 2, '0000010111101010': 2, '0000010110101001': 8, '0001111100011011': 2, '0000110000101001': 8, '1000101011010000': 2, '0000111000011001': 2, '0000100101010100': 2, '0000101111010000': 1, '0000010011011001': 6, '0000010110101011': 1, '1001010110011010': 1, '0001011010111000': 2, '0001011110011001': 5, '0001111011011000': 4, '0100111101100101': 1, '0001100111011001': 3, '0000110111011011': 1, '0000100000101001': 1, '0001001011110101': 1, '0001101001011000': 1, '0000000111101010': 3, '0000100000101011': 1, '0001110111101010': 2, '0000110101011010': 4, '0010110010100100': 1, '1100101011010100': 1, '0001110011101000': 12, '0001101111101010': 1, '0001011001100001': 1, '1101010010100101': 6, '0001010101001001': 1, '0001000100001001': 2, '0110111101010110': 1, '0000100100011001': 11, '0000010100010100': 2, '0000111010011010': 1, '0001110000101000': 5, '1001010010111000': 1, '0001000100101000': 42, '0101101100010110': 1, '0001000111100000': 1, '0001010101101010': 4, '0001010011111000': 1, '0000100100100001': 2, '0000001101011010': 2, '0000000000011000': 1, '0001100101101010': 4, '0001001101011000': 24, '0000101100100100': 7, '0001110001100100': 1, '0000101111101001': 10, '0001101010101011': 3, '0001010100101010': 13, '1000101001101001': 1, '0000001010101010': 1, '0101111100100101': 1, '0001000010011010': 5, '0000011101101001': 10, '0001101101101001': 8, '0011000101100111': 1, '0000111000101001': 4, '1011010010100100': 6, '0110101000101011': 1, '0000111110011000': 12, '1000101011100010': 1, '0000010101110101': 1, '0000101010101011': 3, '0001011110100101': 1, '0001000111011010': 3, '0000100110100011': 1, '0000101101101000': 29, '0100010101010100': 1, '0001010010101010': 11, '0001101101100000': 1, '0000100010011001': 7, '0001010111101000': 23, '1000100000101010': 1, '0000110011010100': 1, '0001011000011011': 2, '0000101100101010': 7, '0000100101011000': 19, '0000101101001000': 2, '0001001101011011': 3, '0000101011101010': 5, '0001000001011000': 8, '0001110100011001': 5, '0001001011001001': 1, '0000111000101011': 2, '0000110110011011': 4, '0001010010010101': 4, '0001011010010001': 1, '1100111110010100': 2, '0001001010010100': 3, '0001111100010100': 1, '0001010100011011': 5, '0001100011101011': 3, '0100101101100111': 1, '0000111111010001': 1, '1000000011101011': 1, '0101100011101001': 5, '0000110001100001': 1, '0000110100001010': 1, '0001100100001001': 1, '0001000110111000': 3, '0010000011111001': 1, '0001001100100000': 2, '1000101001000100': 1, '0110001010100111': 1, '0001111110101001': 5, '0001001010001010': 1, '0001000110010101': 1, '0100010010010100': 2, '0000111100101001': 17, '0000100110101001': 8, '0001110110011001': 3, '0001100110011011': 2, '0001100000011000': 1, '0000101010011010': 1, '0001011010100010': 1, '0001010011100001': 1, '0000100000101000': 8, '0000001000010101': 1, '0101011101100101': 3, '0011000110010110': 2, '0001111000011001': 1, '0000010111011000': 3, '0000010101111001': 1, '0000000010011001': 6, '0011100011010000': 1, '0000001100101011': 2, '0100001000101000': 8, '0110001011100100': 2, '0000101110011010': 2, '0000101111001001': 3, '0000101110101000': 14, '0001110000101010': 2, '0001100111100100': 1, '0001110110011010': 2, '0101001011101001': 14, '0000011010110100': 1, '0001100011011010': 1, '0000100101100100': 3, '0001101000100111': 1, '0000011111101000': 1, '0000110000011001': 3, '1001010010010110': 2, '0010010011100100': 2, '0000101110011001': 6, '0000011111100001': 1, '0001000001111001': 1, '0001000100111001': 1, '0000000000111000': 1, '0001000101011010': 8, '0001000001010100': 3, '0001110101011011': 2, '0000110101011001': 8, '0001101111111000': 1, '0000000010100100': 1, '0000010100001000': 1, '0111101000100100': 1, '0101011000100101': 1, '0000011101010111': 1, '0000100011011010': 2, '0001010100011001': 12, '0110101001100100': 1, '0001110001100111': 1, '0000101111100101': 3, '0111001011100100': 2, '0000000010101001': 8, '0001100100111000': 1, '0000100100000100': 1, '0100001010101001': 7, '0001011110101000': 10, '0000010011010000': 1, '0001000101100001': 3, '0000000111011010': 1, '0000110101111000': 3, '0000001000111000': 1, '0001000101010000': 1, '0001100011101001': 5, '0111100011010101': 1, '0111011100100110': 1, '0001100110011000': 5, '0000101111101010': 4, '0000100101011011': 1, '0101101010100100': 1, '0001001010011000': 9, '0001000110001000': 3, '0111010110010100': 1, '0000100010001000': 1, '0000010101101011': 3, '1011001101100111': 1, '0000111110101001': 4, '0001000010001000': 3, '0001011110011010': 2, '0001011011010100': 1, '0000000000101010': 2, '0100100011101001': 11, '0001011010101010': 5, '0000000101010101': 3, '0000011110100100': 1, '0100011100100100': 3, '0001000110101011': 4, '0000000001011011': 1, '0000001011111001': 3, '0001001001001001': 1, '1001010011101010': 1, '0001101100011001': 3, '1000000011100100': 1, '0000111100011000': 9, '0000001110100100': 1, '0000111011011010': 2, '0101101010101001': 4, '0010100101010100': 2, '0001011101101000': 15, '0110011101010101': 1, '0001000100011011': 9, '0000110010011011': 1, '0000010100011001': 8, '0001000011110101': 1, '0001011111111000': 1, '0001111000011011': 1, '0000110110110110': 1, '0001000000101000': 19, '1000101001011000': 5, '0001011101100000': 1, '0000010110101000': 8, '0001011110111011': 1, '0001100010011000': 10, '0000110000011011': 2, '0000011010100111': 2, '0001110101101010': 4, '1001010101101010': 6, '0000001010011000': 6, '0000111000101010': 2, '0000111010011000': 7, '0000110101010001': 2, '0101111011101001': 3, '0000101101101011': 6, '0000111101101001': 14, '0001110100011010': 2, '0000111000011011': 1, '0001001110110100': 1, '1110100001100100': 2, '0001100111101001': 3, '1000100010011011': 1, '0001101001101001': 2, '1000101011100110': 2, '1000000110101010': 1, '0001010100100110': 2, '0001000100101011': 6, '0001001101011010': 3, '0000111011101010': 4, '0001011100111010': 1, '0001010110010100': 1, '0001110101001000': 1, '0000100100000000': 1, '0001011111101001': 12, '0000101101100110': 1, '0000111111100101': 1, '0000001101100000': 2, '0001110001011000': 1, '0001110100000100': 1, '0000000010101011': 2, '1011011011100100': 8, '0000010110010001': 1, '0000111100011010': 5, '0111001010010110': 2, '0001110001011010': 2}
alabio_counts_results = dict(sorted(alabio_counts_results.items(), key=operator.itemgetter(1),reverse=True)) #sorts dictionary by decreasing counts
varlabels = ['Test','Mask','Work1','Work2','Rec1','Rec2','Age','Race1','Race2','Pov1','Pov2','Health1','Health2','Cases1','Cases2','Deaths']
# find first 10 entries where cases are decreasing
deccaseskey = []
deccasesval = []
for key in alabio_counts_results:
cases1 = key[13]
cases2 = key[14]
if (cases1 == '1') & (cases2 == '1'): # 1 = dec/flat cases
deccaseskey.append(key)
prob = np.array(alabio_counts_results[key]) / sum(alabio_counts_results.values())
deccasesval.append(prob)
if len(deccaseskey) >= 10:
break
# find first 10 entries where deaths are decreasing
decdeathskey = []
decdeathsval = []
for key in alabio_counts_results:
deaths = key[15]
if (deaths == '1'): # 1 = dec/flat cases
decdeathskey.append(key)
prob = np.array(alabio_counts_results[key]) / sum(alabio_counts_results.values())
decdeathsval.append(prob)
if len(decdeathskey) >= 10:
break
topprobs_alabio_cases = dict(zip(deccaseskey,deccasesval))
topprobs_alabio_deaths = dict(zip(decdeathskey,decdeathsval))
"""examples"""
var_labels = ['Cases', 'Tests', 'Home']
make_prob_hist(results, var_labels, top_n_probs='all')
make_prob_hist(results, var_labels, top_n_probs=4)
make_prob_hist(results_maxtomin, ['Increasing','Decreasing'], top_n_probs='all', whichvar=[0,2])
make_prob_hist(topprobs_alabio_cases, varlabels, probdict = topprobs_alabio_cases)
make_prob_hist(topprobs_alabio_deaths, varlabels, probdict = topprobs_alabio_deaths)
"""Lesser model before rotation - for presentation"""
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.id(0)
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, backend=simulator).result()
statevector = result.get_statevector()
plot_bloch_multivector(statevector)
"""Lesser model after rotation - for presentation"""
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ry(circ.angle_from_probability(.62,.38), 0)
qc.ry(circ.angle_from_probability(0.645,0.355), 1)
qc.ry(circ.angle_from_probability(0.73,0.27),2)
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, backend=simulator).result()
statevector = result.get_statevector()
plot_bloch_multivector(statevector)
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
# Importando módulos
from qiskit import *
# Uma das formas de se inicializar um circuito quântico é usando "QuantumCircuit(x,y)"
# que é armazenado em uma variável.
# Nele, onde x é o número de qubits
# e y o número de bits clássicos.
# Usamos os bits clássicos para armazenar as medições dos qubits.
nQubits = 2
nBits = 2
circuitoQuantico = QuantumCircuit(nQubits, nBits)
# Nesse caso cada qubit tem o seu bit aonde será armazenado seu valor após a medição
# (o primeiro bit armazena o valor do primeiro qubit, o segundo bit do segundo qubit,...)
# Logo depois de inicializar o circuito e durante todo o processo de adicionar as operações desejadas,
# podemos visualizar o circuito, chamando a função draw(output = 'mpl') pertencente a variável do circuito quântico
circuitoQuantico.draw(output = 'mpl')
# Depois de realizar as operações desejadas nos qubits, medimos chamando a função measure(x,y),
# pertencente a variável de circuito quântico.
# Nele o x e y são os ÍNDICES do qubit e bit respectivamente(lembrar que o índice começa a contar em 0).
circuitoQuantico.measure(0,0)
circuitoQuantico.measure(1,1)
# Chamando o draw() para exibir novamente o circuito, mas agora exibindo a medições
circuitoQuantico.draw(output = 'mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
import random
circ = QuantumCircuit(40, 40)
# Initialize with a Hadamard layer
circ.h(range(40))
# Apply some random CNOT and T gates
qubit_indices = [i for i in range(40)]
for i in range(10):
control, target, t = random.sample(qubit_indices, 3)
circ.cx(control, target)
circ.t(t)
circ.measure(range(40), range(40))
# Create statevector method simulator
statevector_simulator = AerSimulator(method='statevector')
# Transpile circuit for backend
tcirc = transpile(circ, statevector_simulator)
# Try and run circuit
statevector_result = statevector_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(statevector_result.success))
print('Why not? {}'.format(statevector_result.status))
# Create extended stabilizer method simulator
extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer')
# Transpile circuit for backend
tcirc = transpile(circ, extended_stabilizer_simulator)
extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(extended_stabilizer_result.success))
small_circ = QuantumCircuit(2, 2)
small_circ.h(0)
small_circ.cx(0, 1)
small_circ.t(0)
small_circ.measure([0, 1], [0, 1])
# This circuit should give 00 or 11 with equal probability...
expected_results ={'00': 50, '11': 50}
tsmall_circ = transpile(small_circ, extended_stabilizer_simulator)
result = extended_stabilizer_simulator.run(
tsmall_circ, shots=100).result()
counts = result.get_counts(0)
print('100 shots in {}s'.format(result.time_taken))
plot_histogram([expected_results, counts],
legend=['Expected', 'Extended Stabilizer'])
# Add runtime options for extended stabilizer simulator
opts = {'extended_stabilizer_approximation_error': 0.03}
reduced_error = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
reduced_error_counts = reduced_error.get_counts(0)
print('100 shots in {}s'.format(reduced_error.time_taken))
plot_histogram([expected_results, reduced_error_counts],
legend=['Expected', 'Extended Stabilizer'])
print("The circuit above, with 100 shots at precision 0.03 "
"and default mixing time, needed {}s".format(int(reduced_error.time_taken)))
opts = {
'extended_stabilizer_approximation_error': 0.03,
'extended_stabilizer_mixing_time': 100
}
optimized = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken))
# We set these options here only to make the example run more quickly.
opts = {'extended_stabilizer_mixing_time': 100}
multishot = extended_stabilizer_simulator.run(
tcirc, shots=100, **opts).result()
print("100 shots took {} s".format(multishot.time_taken))
opts = {
'extended_stabilizer_measure_sampling': True,
'extended_stabilizer_mixing_time': 100
}
measure_sampling = extended_stabilizer_simulator.run(
circ, shots=100, **opts).result()
print("With the optimization, 100 shots took {} s".format(result.time_taken))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/LSEG-API-Samples/Article.EikonAPI.Python.PortfolioOptimizationUsingQiskitAndEikonDataAPI
|
LSEG-API-Samples
|
# ! pip install qiskit qiskit-finance==0.2.1
import warnings
warnings.filterwarnings("ignore")
import qiskit.tools.jupyter
%qiskit_version_table
# from qiskit import IBMQ
# IBMQ.save_account('MY_API_TOKEN')
# ! pip install eikon
import eikon as ek
print("Eikon version: ", ek.__version__)
eikon_key = open("eikon.txt","r")
ek.set_app_key(str(eikon_key.read()))
eikon_key.close()
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import seaborn as sns
from qiskit import Aer
from qiskit_finance.data_providers._base_data_provider import BaseDataProvider
from qiskit.finance.applications.ising import portfolio
from qiskit.circuit.library import TwoLocal
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.aqua.algorithms import VQE, QAOA, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import COBYLA
class EikonDataProvider(BaseDataProvider):
"""
The abstract base class for Eikon data_provider.
"""
def __init__(self, stocks_list, start_date, end_date):
'''
stocks -> List of interested assets
start -> start date to fetch historical data
end ->
'''
super().__init__()
self._stocks = stocks_list
self._start = start_date
self._end = end_date
self._data = []
self.stock_data = pd.DataFrame()
def run(self):
self._data = []
stocks_notfound = []
stock_data = ek.get_timeseries(self._stocks,
start_date=self._start,
end_date=self._end,
interval='daily',
corax='adjusted')
for ticker in self._stocks:
stock_value = stock_data[ticker]['CLOSE']
self.stock_data[ticker] = stock_data[ticker]['CLOSE']
if stock_value.dropna().empty:
stocks_notfound.append(ticker)
self._data.append(stock_value)
# List of stocks
stock_list = ['FB.O', 'AAPL.O', 'AMZN.O', 'NFLX.O', 'GOOGL.O']
# Start Date
start_date = datetime.datetime(2019,6,10)
# End Date
end_date = datetime.datetime(2021,10,20)
# Set number of equities to the number of stocks
num_assets = len(stock_list)
# Set the risk factor
risk_factor = 0.7
# Set budget
budget = 2
# Scaling of budget penalty term will be dependant on the number of assets
penalty = num_assets
data = EikonDataProvider(stocks_list = stock_list, start_date=start_date, end_date=end_date)
data.run()
# Top 5 rows of data
df = data.stock_data
df.head()
df.describe()
# Closing Price History
fig, ax = plt.subplots(figsize=(15, 8))
ax.plot(df)
plt.title('Close Price History')
plt.xlabel('Date',fontsize =20)
plt.ylabel('Price in USD',fontsize = 20)
ax.legend(df.columns.values)
plt.show()
# # Mean value of each equities
# mean_vector = data.get_mean_vector()
# sns.barplot(y=mean_vector, x = stock_list)
# plt.show()
mu = data.get_period_return_mean_vector()
sns.barplot(y=mu, x = stock_list)
plt.show()
# Covariance Matrix
sigma = data.get_period_return_covariance_matrix()
f, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(sigma, mask=np.zeros_like(sigma, dtype=np.bool), annot=True,
square=True, ax=ax, xticklabels=stock_list, yticklabels=stock_list)
plt.title("Covariance between Equities")
plt.show()
# Correlation Matrix
corr = df.corr()
f, ax = plt.subplots(figsize=(10, 8))
sns.heatmap(corr, mask=np.zeros_like(corr, dtype=np.bool), annot=True,
square=True, ax=ax, xticklabels=stock_list, yticklabels=stock_list)
plt.title("Correlation between Equities")
plt.show()
sns.pairplot(df)
plt.show()
# returns = np.log(df/df.shift(1)).dropna()
# returns.head()
# sns.pairplot(returns)
# plt.show()
# Retrieve Hamiltonian
qubitOp, offset = portfolio.get_operator(mu, sigma, risk_factor, budget, penalty)
def index_to_selection(i, num_assets):
s = "{0:b}".format(i).rjust(num_assets)
x = np.array([1 if s[i]=='1' else 0 for i in reversed(range(num_assets))])
return x
def selection_to_picks(num_assets, selection):
purchase = []
for i in range(num_assets):
if selection[i] == 1:
purchase.append(stock_list[i])
return purchase
# def print_result(result):
# selection = sample_most_likely(result.eigenstate)
# value = portfolio.portfolio_value(selection, mu, sigma, q, budget, penalty)
# print(f"!!! Optimal: portfolio holdings !!!")
# return selection
def print_result(result):
selection = sample_most_likely(result.eigenstate)
value = portfolio.portfolio_value(selection, mu, sigma, risk_factor, budget, penalty)
print('Optimal: selection {}, value {:.4f}'.format(selection, value))
eigenvector = result.eigenstate if isinstance(result.eigenstate, np.ndarray) else result.eigenstate.to_matrix()
probabilities = np.abs(eigenvector)**2
i_sorted = reversed(np.argsort(probabilities))
print('\n----------------- Full result ---------------------')
print('selection\tvalue\t\tprobability')
print('---------------------------------------------------')
states, values, probs = [], [], []
for i in i_sorted:
x = index_to_selection(i, num_assets)
value = portfolio.portfolio_value(x, mu, sigma, risk_factor, budget, penalty)
probability = probabilities[i]
print('%10s\t%.4f\t\t%.4f' %(x, value, probability))
states.append(''.join(str(i) for i in x))
values.append(value)
probs.append(probability)
return selection, states, values, probs
def numpyEigensolver(qubitOp):
selections = []
exact_eigensolver = NumPyMinimumEigensolver(qubitOp)
result = exact_eigensolver.run()
selection, state, values, probabilities = print_result(result)
print(selection_to_picks(num_assets, selection))
return state, values, probabilities
#Classical Benchmark
%time
state, values, probabilities = numpyEigensolver(qubitOp) # ['FB.O', 'AAPL.O', 'AMZN.O', 'NFLX.O', 'GOOGL.O']
# f, ax = plt.subplots(figsize=(20, 8))
# optimized_value = sns.barplot(state, values)
# for item in optimized_value.get_xticklabels():
# item.set_rotation(45)
# plt.title("Optimized Values of Each Possible Combination of Assets", fontsize=25) #Lower the value is, best optimal set of asset it is
# plt.xlabel('Possible Combinations of Assets',fontsize =20)
# plt.ylabel('Optimized Values',fontsize = 20)
# plt.show()
f, ax = plt.subplots(figsize=(20, 8))
optimized_value = sns.barplot(state, probabilities)
for item in optimized_value.get_xticklabels():
item.set_rotation(45)
plt.title("Probabilites of Each Possible Combination of Assets", fontsize=25) # Probability of Max Return at given risk level
plt.xlabel('Possible Combinations of Assets',fontsize =20)
plt.ylabel('Probability',fontsize = 20)
plt.show()
def vqe(qubitOp):
backend = Aer.get_backend('statevector_simulator') # You can switch to different backends by providing the name of backend.
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=1000)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=3, entanglement='full')
vqe = VQE(qubitOp, ry, cobyla)
vqe.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
result = vqe.run(quantum_instance)
selection, state, values, probabilities = print_result(result)
print(selection_to_picks(num_assets, selection))
return state, values, probabilities
# Variational Quantum EigenSolver
%time
state, values, probabilities = vqe(qubitOp) # ['FB.O', 'AAPL.O', 'AMZN.O', 'NFLX.O', 'GOOGL.O']
# f, ax = plt.subplots(figsize=(20, 8))
# optimized_value = sns.barplot(state, values)
# for item in optimized_value.get_xticklabels():
# item.set_rotation(45)
# plt.title("Optimized Values of Each Possible Combination of Assets", fontsize=25) #Lower the value is, best optimal set of asset it is
# plt.xlabel('Possible Combinations of Assets',fontsize =20)
# plt.ylabel('Optimized Values',fontsize = 20)
# plt.show()
f, ax = plt.subplots(figsize=(20, 8))
optimized_value = sns.barplot(state, probabilities)
for item in optimized_value.get_xticklabels():
item.set_rotation(45)
plt.title("Probabilites of Each Possible Combination of Assets", fontsize=25) # Probability of Max Return at given risk level
plt.xlabel('Possible Combinations of Assets',fontsize =20)
plt.ylabel('Probability',fontsize = 20)
plt.show()
def qaoa(qubitOp):
backend = Aer.get_backend('statevector_simulator') # You can switch to different backends by providing the name of backend.
seed = 50
cobyla = COBYLA()
cobyla.set_options(maxiter=1000)
qaoa = QAOA(qubitOp, cobyla, 3)
qaoa.random_seed = seed
quantum_instance = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
results= qaoa.run(quantum_instance)
selection, state, values, probabilities = print_result(results)
print(selection_to_picks(num_assets, selection))
return state, values, probabilities
# QAOA (Quantum Approximate Optimization Algorithm)
%time
state, values, probabilities = qaoa(qubitOp) # ['FB.O', 'AAPL.O', 'AMZN.O', 'NFLX.O', 'GOOGL.O']
# f, ax = plt.subplots(figsize=(20, 8))
# optimized_value = sns.barplot(state, values)
# for item in optimized_value.get_xticklabels():
# item.set_rotation(45)
# plt.title("Optimized Values of Each Possible Combination of Assets", fontsize=25) #Lower the value is, best optimal set of asset it is
# plt.xlabel('Possible Combinations of Assets',fontsize =20)
# plt.ylabel('Optimized Values',fontsize = 20)
# plt.show()
f, ax = plt.subplots(figsize=(20, 8))
optimized_value = sns.barplot(state, probabilities)
for item in optimized_value.get_xticklabels():
item.set_rotation(45)
plt.title("Probabilites of Each Possible Combination of Assets", fontsize=25) # Probability of Max Return at given risk level
plt.xlabel('Possible Combinations of Assets',fontsize =20)
plt.ylabel('Probability',fontsize = 20)
plt.show()
|
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
#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 = 128
#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(qc, backend,shots=shots).result()
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
#------------------------------------------------------------------------------------
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
num_qubits = 2
ansatz = TwoLocal(num_qubits, "ry", "cz")
optimizer = SLSQP(maxiter=1000)
ansatz.decompose().draw("mpl", style="iqx")
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(estimator, ansatz, optimizer)
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list([
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156)
])
result = vqe.compute_minimum_eigenvalue(H2_op)
print(result)
from qiskit.algorithms.optimizers import SPSA
estimator = Estimator(options={"shots": 1000})
vqe.estimator = estimator
vqe.optimizer = SPSA(maxiter=100)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
print("Ch 5: Explore a backend")
print("-----------------------")
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
# Get all available and operational backends.
available_backends = provider.backends(operational=True)
# Fish out criteria to compare
print("{0:20} {1:<10} {2:<10} {3:<10}".format("Name","#Qubits","Max exp.","Pending jobs"))
print("{0:20} {1:<10} {2:<10} {3:<10}".format("----","-------","--------","------------"))
for n in range(0, len(available_backends)):
backend = provider.get_backend(str(available_backends[n]))
print("{0:20} {1:<10} {2:<10} {3:<10}".format(backend.name(),backend.configuration().n_qubits,backend.configuration().max_experiments,backend.status().pending_jobs))
# Select the least busy backend with 5 qubits
least_busy_backend = least_busy(provider.backends(n_qubits=5,operational=True, simulator=False))
# Print out qubit properties for the backend.
print("\nQubit data for backend:",least_busy_backend.status().backend_name)
for q in range (0, least_busy_backend.configuration().n_qubits):
print("\nQubit",q,":")
for n in range (0, len(least_busy_backend.properties().qubits[0])):
print(least_busy_backend.properties().qubits[q][n].name,"=",least_busy_backend.properties().qubits[q][n].value,least_busy_backend.properties().qubits[q][n].unit)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QFT
def create_qpe_circuit(theta, num_qubits):
'''Creates a QPE circuit given theta and num_qubits.'''
# Step 1: Create a circuit with two quantum registers and one classical register.
first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation
second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi>
classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout
qpe_circuit = QuantumCircuit(first, second, classical)
# Step 2: Initialize the qubits.
# All qubits are initialized in |0> by default, no extra code is needed to initialize the first register.
qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example.
# Step 3: Create superposition in the first register.
qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization.
qpe_circuit.h(first)
# Step 4: Apply a controlled-U^(2^j) black box.
qpe_circuit.barrier()
for j in range(num_qubits):
qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor.
# Step 5: Apply an inverse QFT to the first register.
qpe_circuit.barrier()
qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True)
# Step 6: Measure the first register.
qpe_circuit.barrier()
qpe_circuit.measure(first, classical)
return qpe_circuit
num_qubits = 4
qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2.
qpe_circuit_fixed_phase.draw('mpl')
from qiskit.circuit import Parameter
theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later.
qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits)
qpe_circuit_parameterized.draw('mpl')
number_of_phases = 21
phases = np.linspace(0, 2, number_of_phases)
individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists.
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):
results = Sampler().run(
[qpe_circuit_parameterized]*len(individual_phases),
parameter_values=individual_phases
).result()
from qiskit.tools.visualization import plot_histogram
idx = 6
plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}'])
def most_likely_bitstring(results_dict):
'''Finds the most likely outcome bit string from a result dictionary.'''
return max(results_dict, key=results_dict.get)
def find_neighbors(bitstring):
'''Finds the neighbors of a bit string.
Example:
For bit string '1010', this function returns ('1001', '1011')
'''
if bitstring == len(bitstring)*'0':
neighbor_left = len(bitstring)*'1'
else:
neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring))
if bitstring == len(bitstring)*'1':
neighbor_right = len(bitstring)*'0'
else:
neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring))
return (neighbor_left, neighbor_right)
def estimate_phase(results_dict):
'''Estimates the phase from a result dictionary of a QPE circuit.'''
# Find the most likely outcome bit string N1 and its neighbors.
num_1_key = most_likely_bitstring(results_dict)
neighbor_left, neighbor_right = find_neighbors(num_1_key)
# Get probabilities of N1 and its neighbors.
num_1_prob = results_dict.get(num_1_key)
neighbor_left_prob = results_dict.get(neighbor_left)
neighbor_right_prob = results_dict.get(neighbor_right)
# Find the second most likely outcome N2 and its probability P2 among the neighbors.
if neighbor_left_prob is None:
# neighbor_left doesn't exist
if neighbor_right_prob is None:
# both neighbors don't exist, N2 is N1
num_2_key = num_1_key
num_2_prob = num_1_prob
else:
# If only neighbor_left doesn't exist, N2 is neighbor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
elif neighbor_right_prob is None:
# If only neighbor_right doesn't exist, N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
elif neighbor_left_prob > neighbor_right_prob:
# Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
else:
# Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
# Calculate the estimated phases for N1 and N2.
num_qubits = len(num_1_key)
num_1_phase = (int(num_1_key, 2) / 2**num_qubits)
num_2_phase = (int(num_2_key, 2) / 2**num_qubits)
# Calculate the weighted average phase from N1 and N2.
phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob)
return phase_estimated
qpe_solutions = []
for idx, result_dict in enumerate(results.quasi_dists):
qpe_solutions.append(estimate_phase(result_dict.binary_probabilities()))
ideal_solutions = np.append(
phases[:(number_of_phases-1)//2], # first period
np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period
)
ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 6))
plt.plot(phases, ideal_solutions, '--', label='Ideal solutions')
plt.plot(phases, qpe_solutions, 'o', label='QPE solutions')
plt.title('Quantum Phase Estimation Algorithm')
plt.xlabel('Input Phase')
plt.ylabel('Output Phase')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import COBYLA
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE
from qiskit.primitives import Sampler
from qiskit_optimization.converters import LinearEqualityToPenalty
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from qiskit.utils import algorithm_globals
import numpy as np
import matplotlib.pyplot as plt
from docplex.mp.model import Model
algorithm_globals.random_seed = 123456
# prepare problem instance
n = 6 # number of assets
q = 0.5 # risk factor
budget = n // 2 # budget
penalty = 2 * n # scaling of penalty term
# instance from [1]
mu = np.array([0.7313, 0.9893, 0.2725, 0.8750, 0.7667, 0.3622])
sigma = np.array(
[
[0.7312, -0.6233, 0.4689, -0.5452, -0.0082, -0.3809],
[-0.6233, 2.4732, -0.7538, 2.4659, -0.0733, 0.8945],
[0.4689, -0.7538, 1.1543, -1.4095, 0.0007, -0.4301],
[-0.5452, 2.4659, -1.4095, 3.5067, 0.2012, 1.0922],
[-0.0082, -0.0733, 0.0007, 0.2012, 0.6231, 0.1509],
[-0.3809, 0.8945, -0.4301, 1.0922, 0.1509, 0.8992],
]
)
# or create random instance
# mu, sigma = portfolio.random_model(n, seed=123) # expected returns and covariance matrix
# create docplex model
mdl = Model("portfolio_optimization")
x = mdl.binary_var_list(range(n), name="x")
objective = mdl.sum([mu[i] * x[i] for i in range(n)])
objective -= q * mdl.sum([sigma[i, j] * x[i] * x[j] for i in range(n) for j in range(n)])
mdl.maximize(objective)
mdl.add_constraint(mdl.sum(x[i] for i in range(n)) == budget)
# case to
qp = from_docplex_mp(mdl)
# solve classically as reference
opt_result = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp)
print(opt_result.prettyprint())
# we convert the problem to an unconstrained problem for further analysis,
# otherwise this would not be necessary as the MinimumEigenSolver would do this
# translation automatically
linear2penalty = LinearEqualityToPenalty(penalty=penalty)
qp = linear2penalty.convert(qp)
_, offset = qp.to_ising()
# set classical optimizer
maxiter = 100
optimizer = COBYLA(maxiter=maxiter)
# set variational ansatz
ansatz = RealAmplitudes(n, reps=1)
m = ansatz.num_parameters
# set sampler
sampler = Sampler()
# run variational optimization for different values of alpha
alphas = [1.0, 0.50, 0.25] # confidence levels to be evaluated
# dictionaries to store optimization progress and results
objectives = {alpha: [] for alpha in alphas} # set of tested objective functions w.r.t. alpha
results = {} # results of minimum eigensolver w.r.t alpha
# callback to store intermediate results
def callback(i, params, obj, stddev, alpha):
# we translate the objective from the internal Ising representation
# to the original optimization problem
objectives[alpha].append(np.real_if_close(-(obj + offset)))
# loop over all given alpha values
for alpha in alphas:
# initialize SamplingVQE using CVaR
vqe = SamplingVQE(
sampler=sampler,
ansatz=ansatz,
optimizer=optimizer,
aggregation=alpha,
callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha),
)
# initialize optimization algorithm based on CVaR-SamplingVQE
opt_alg = MinimumEigenOptimizer(vqe)
# solve problem
results[alpha] = opt_alg.solve(qp)
# print results
print("alpha = {}:".format(alpha))
print(results[alpha].prettyprint())
print()
# plot resulting history of objective values
plt.figure(figsize=(10, 5))
plt.plot([0, maxiter], [opt_result.fval, opt_result.fval], "r--", linewidth=2, label="optimum")
for alpha in alphas:
plt.plot(objectives[alpha], label="alpha = %.2f" % alpha, linewidth=2)
plt.legend(loc="lower right", fontsize=14)
plt.xlim(0, maxiter)
plt.xticks(fontsize=14)
plt.xlabel("iterations", fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel("objective value", fontsize=14)
plt.show()
# evaluate and sort all objective values
objective_values = np.zeros(2**n)
for i in range(2**n):
x_bin = ("{0:0%sb}" % n).format(i)
x = [0 if x_ == "0" else 1 for x_ in reversed(x_bin)]
objective_values[i] = qp.objective.evaluate(x)
ind = np.argsort(objective_values)
# evaluate final optimal probability for each alpha
for alpha in alphas:
probabilities = np.fromiter(
results[alpha].min_eigen_solver_result.eigenstate.binary_probabilities().values(),
dtype=float,
)
print("optimal probability (alpha = %.2f): %.4f" % (alpha, probabilities[ind][-1:]))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.extensions import HamiltonianGate
from qiskit.circuit.library.standard_gates import CRYGate
def quantum_fourier_transform(t, vis=False):
reg = QuantumRegister(t, name='c')
circ = QuantumCircuit(reg, name='$Q.F.T.$')
for i in range(t // 2):
circ.swap(i, t - 1 - i)
for i in range(t):
circ.h(i)
for j in range(i + 1, t):
circ.cu1(np.pi / (2 ** (j - i)), i, j)
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Quantum Fourier Transform", fontsize=16)
return circ.to_gate()
def quantum_phase_estimation(n, t, unitary, vis=False):
reg_b = QuantumRegister(n, name='b')
reg_c = QuantumRegister(t, name='c')
circ = QuantumCircuit(reg_b, reg_c, name='$Q.P.E.$')
circ.h(range(n, n + t))
for i in range(t):
circ.append(unitary.control(1).power(2**i), [n + i] + list(range(n)))
circ.append(quantum_fourier_transform(t, vis=vis).inverse(), range(n, n + t))
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Quantum Phase Estimation", fontsize=16)
return circ.to_gate()
def subroutine_a(t, m, l, k, t0, vis=False):
reg_c = QuantumRegister(t, name='c')
reg_m = QuantumRegister(m, name='m')
reg_l = QuantumRegister(l, name='l')
circ = QuantumCircuit(reg_c, reg_m, reg_l, name='$Sub_A$')
vis_temp = vis
for i in range(t):
gate = subroutine_c(m, t - i, l - k, t0, vis=vis_temp)
circ.append(gate.control(2), [reg_l[k], reg_c[i]] + [reg_m[j] for j in range(m)])
vis_temp = False
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Subroutine A", fontsize=16)
return circ.to_gate()
def subroutine_b(t, m, l, t0, vis=False):
reg_c = QuantumRegister(t, name='c')
reg_m = QuantumRegister(m, name='m')
reg_l = QuantumRegister(l, name='l')
circ = QuantumCircuit(reg_c, reg_m, reg_l, name='$Sub_B$')
vis_temp = vis
for i in range(l):
gate = subroutine_a(t, m, l, i, t0, vis=vis_temp)
circ.append(gate, range(t + m + l))
vis_temp = False
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Subroutine B", fontsize=16)
return circ.to_gate()
def subroutine_c(m, u, v, t0, vis=False):
reg = QuantumRegister(m, name='m')
circ = QuantumCircuit(reg, name='$Sub_C$')
t = -t0 / (2 ** (u + v - m))
for i in range(m):
circ.rz(t / (2 ** (i + 1)), i)
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle("Subroutine C", fontsize=16)
return circ.to_gate()
def hhl_forward_ckt(n, t, m, l, A, t0, vis=False):
reg_b = QuantumRegister(n, name='b')
reg_c = QuantumRegister(t, name='c')
reg_m = QuantumRegister(m, name='m')
reg_l = QuantumRegister(l, name='l')
temp = QuantumCircuit(reg_b, name='$U$')
temp.append(HamiltonianGate(A, t0 / (2 ** t)), reg_b)
circ = QuantumCircuit(reg_b, reg_c, reg_m, reg_l, name='$Fwd$')
circ.append(quantum_phase_estimation(n, t, temp.to_gate(), vis=vis), range(n + t))
circ.h(reg_m)
circ.h(reg_l)
for i in range(m):
circ.rz(t0 / (2 ** (m - i)), reg_m[i])
circ.append(subroutine_b(t, m, l, t0, vis=vis), range(n, n + t + m + l))
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle('HHL Forward Computation', fontsize=16)
return circ.to_gate()
def hhl_circuit(A, t0, theta, size, vis=False):
n, t, m, l = size
reg_b = QuantumRegister(n, name='b')
reg_c = QuantumRegister(t, name='c')
reg_m = QuantumRegister(m, name='m')
reg_l = QuantumRegister(l, name='l')
ancil = QuantumRegister(1, name='anc')
circ = QuantumCircuit(reg_b, reg_c, reg_m, reg_l, ancil, name='$HHL$')
circ.append(hhl_forward_ckt(n, t, m, l, A, t0, vis=vis), range(sum(size)))
for i in range(l):
circ.append(CRYGate(theta).power(2**i), [reg_l[i], ancil])
circ.append(hhl_forward_ckt(n, t, m, l, A, t0).inverse(), range(sum(size)))
if vis:
circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\
.suptitle('HHL Circuit', fontsize=16)
return circ
def ad_hoc_hhl(A, t0, r):
reg_b = QuantumRegister(2)
reg_c = QuantumRegister(4)
ancil = QuantumRegister(1)
circ = QuantumCircuit(reg_b, reg_c, ancil)
circ.append(quantum_phase_estimation(2, 4, HamiltonianGate(A, t0/16)), range(6))
circ.swap(reg_c[1], reg_c[3])
for i in range(4):
circ.cry(np.pi * (2 ** (4-i-r)), reg_c[i], ancil[0])
circ.barrier()
circ.swap(reg_c[1], reg_c[3])
circ.append(quantum_phase_estimation(2, 4, HamiltonianGate(A, t0 / 16)).inverse(), range(6))
return circ
if __name__ == '__main__':
size = [3, 4, 4, 4]
theta = np.pi/12
t0 = 2 * np.pi
A = [[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0]]
circ = hhl_circuit(A, t0, theta, size, vis=True)
plt.show()
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer.primitives import Estimator as AerEstimator
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0; H 0 0 1.599",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['BeH2']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper() #(num_particles=problem.num_particles) #BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
#estimator = AerEstimator()
#estimator.set_options(approximation=False, shots=None)
#vqe_solver = VQE(estimator, ansatz, SLSQP())
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
import matplotlib.pyplot as plt
points = measurement_range
num_points = len(points)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
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.
# pylint: disable=bad-docstring-quotes,invalid-name
"""Quantum circuit object."""
from __future__ import annotations
import collections.abc
import copy
import itertools
import multiprocessing as mp
import string
import re
import warnings
import typing
from collections import OrderedDict, defaultdict, namedtuple
from typing import (
Union,
Optional,
Tuple,
Type,
TypeVar,
Sequence,
Callable,
Mapping,
Iterable,
Any,
DefaultDict,
Literal,
overload,
)
import numpy as np
from qiskit.exceptions import QiskitError
from qiskit.utils.multiprocessing import is_main_process
from qiskit.circuit.instruction import Instruction
from qiskit.circuit.gate import Gate
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.exceptions import CircuitError
from qiskit.utils import optionals as _optionals
from . import _classical_resource_map
from ._utils import sort_parameters
from .classical import expr
from .parameterexpression import ParameterExpression, ParameterValueType
from .quantumregister import QuantumRegister, Qubit, AncillaRegister, AncillaQubit
from .classicalregister import ClassicalRegister, Clbit
from .parametertable import ParameterReferences, ParameterTable, ParameterView
from .parametervector import ParameterVector
from .instructionset import InstructionSet
from .operation import Operation
from .register import Register
from .bit import Bit
from .quantumcircuitdata import QuantumCircuitData, CircuitInstruction
from .delay import Delay
from .measure import Measure
from .reset import Reset
from .tools import pi_check
if typing.TYPE_CHECKING:
import qiskit # pylint: disable=cyclic-import
from qiskit.transpiler.layout import TranspileLayout # pylint: disable=cyclic-import
BitLocations = namedtuple("BitLocations", ("index", "registers"))
# The following types are not marked private to avoid leaking this "private/public" abstraction out
# into the documentation. They are not imported by circuit.__init__, nor are they meant to be.
# Arbitrary type variables for marking up generics.
S = TypeVar("S")
T = TypeVar("T")
# Types that can be coerced to a valid Qubit specifier in a circuit.
QubitSpecifier = Union[
Qubit,
QuantumRegister,
int,
slice,
Sequence[Union[Qubit, int]],
]
# Types that can be coerced to a valid Clbit specifier in a circuit.
ClbitSpecifier = Union[
Clbit,
ClassicalRegister,
int,
slice,
Sequence[Union[Clbit, int]],
]
# Generic type which is either :obj:`~Qubit` or :obj:`~Clbit`, used to specify types of functions
# which operate on either type of bit, but not both at the same time.
BitType = TypeVar("BitType", Qubit, Clbit)
# Regex pattern to match valid OpenQASM identifiers
VALID_QASM2_IDENTIFIER = re.compile("[a-z][a-zA-Z_0-9]*")
QASM2_RESERVED = {
"OPENQASM",
"qreg",
"creg",
"include",
"gate",
"opaque",
"U",
"CX",
"measure",
"reset",
"if",
"barrier",
}
class QuantumCircuit:
"""Create a new circuit.
A circuit is a list of instructions bound to some registers.
Args:
regs (list(:class:`~.Register`) or list(``int``) or list(list(:class:`~.Bit`))): The
registers to be included in the circuit.
* If a list of :class:`~.Register` objects, represents the :class:`.QuantumRegister`
and/or :class:`.ClassicalRegister` objects to include in the circuit.
For example:
* ``QuantumCircuit(QuantumRegister(4))``
* ``QuantumCircuit(QuantumRegister(4), ClassicalRegister(3))``
* ``QuantumCircuit(QuantumRegister(4, 'qr0'), QuantumRegister(2, 'qr1'))``
* If a list of ``int``, the amount of qubits and/or classical bits to include in
the circuit. It can either be a single int for just the number of quantum bits,
or 2 ints for the number of quantum bits and classical bits, respectively.
For example:
* ``QuantumCircuit(4) # A QuantumCircuit with 4 qubits``
* ``QuantumCircuit(4, 3) # A QuantumCircuit with 4 qubits and 3 classical bits``
* If a list of python lists containing :class:`.Bit` objects, a collection of
:class:`.Bit` s to be added to the circuit.
name (str): the name of the quantum circuit. If not set, an
automatically generated string will be assigned.
global_phase (float or ParameterExpression): The global phase of the circuit in radians.
metadata (dict): Arbitrary key value metadata to associate with the
circuit. This gets stored as free-form data in a dict in the
:attr:`~qiskit.circuit.QuantumCircuit.metadata` attribute. It will
not be directly used in the circuit.
Raises:
CircuitError: if the circuit name, if given, is not valid.
Examples:
Construct a simple Bell state circuit.
.. plot::
:include-source:
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
Construct a 5-qubit GHZ circuit.
.. code-block::
from qiskit import QuantumCircuit
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, range(1, 5))
qc.measure_all()
Construct a 4-qubit Bernstein-Vazirani circuit using registers.
.. plot::
:include-source:
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')
"""
instances = 0
prefix = "circuit"
# Class variable OPENQASM header
header = "OPENQASM 2.0;"
extension_lib = 'include "qelib1.inc";'
def __init__(
self,
*regs: Register | int | Sequence[Bit],
name: str | None = None,
global_phase: ParameterValueType = 0,
metadata: dict | None = None,
):
if any(not isinstance(reg, (list, QuantumRegister, ClassicalRegister)) for reg in regs):
# check if inputs are integers, but also allow e.g. 2.0
try:
valid_reg_size = all(reg == int(reg) for reg in regs)
except (ValueError, TypeError):
valid_reg_size = False
if not valid_reg_size:
raise CircuitError(
"Circuit args must be Registers or integers. (%s '%s' was "
"provided)" % ([type(reg).__name__ for reg in regs], regs)
)
regs = tuple(int(reg) for reg in regs) # cast to int
self._base_name = None
if name is None:
self._base_name = self.cls_prefix()
self._name_update()
elif not isinstance(name, str):
raise CircuitError(
"The circuit name should be a string (or None to auto-generate a name)."
)
else:
self._base_name = name
self.name = name
self._increment_instances()
# Data contains a list of instructions and their contexts,
# in the order they were applied.
self._data: list[CircuitInstruction] = []
self._op_start_times = None
# A stack to hold the instruction sets that are being built up during for-, if- and
# while-block construction. These are stored as a stripped down sequence of instructions,
# and sets of qubits and clbits, rather than a full QuantumCircuit instance because the
# builder interfaces need to wait until they are completed before they can fill in things
# like `break` and `continue`. This is because these instructions need to "operate" on the
# full width of bits, but the builder interface won't know what bits are used until the end.
self._control_flow_scopes: list[
"qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock"
] = []
self.qregs: list[QuantumRegister] = []
self.cregs: list[ClassicalRegister] = []
self._qubits: list[Qubit] = []
self._clbits: list[Clbit] = []
# Dict mapping Qubit or Clbit instances to tuple comprised of 0) the
# corresponding index in circuit.{qubits,clbits} and 1) a list of
# Register-int pairs for each Register containing the Bit and its index
# within that register.
self._qubit_indices: dict[Qubit, BitLocations] = {}
self._clbit_indices: dict[Clbit, BitLocations] = {}
self._ancillas: list[AncillaQubit] = []
self._calibrations: DefaultDict[str, dict[tuple, Any]] = defaultdict(dict)
self.add_register(*regs)
# Parameter table tracks instructions with variable parameters.
self._parameter_table = ParameterTable()
# Cache to avoid re-sorting parameters
self._parameters = None
self._layout = None
self._global_phase: ParameterValueType = 0
self.global_phase = global_phase
self.duration = None
self.unit = "dt"
self.metadata = {} if metadata is None else metadata
@staticmethod
def from_instructions(
instructions: Iterable[
CircuitInstruction
| tuple[qiskit.circuit.Instruction]
| tuple[qiskit.circuit.Instruction, Iterable[Qubit]]
| tuple[qiskit.circuit.Instruction, Iterable[Qubit], Iterable[Clbit]]
],
*,
qubits: Iterable[Qubit] = (),
clbits: Iterable[Clbit] = (),
name: str | None = None,
global_phase: ParameterValueType = 0,
metadata: dict | None = None,
) -> "QuantumCircuit":
"""Construct a circuit from an iterable of CircuitInstructions.
Args:
instructions: The instructions to add to the circuit.
qubits: Any qubits to add to the circuit. This argument can be used,
for example, to enforce a particular ordering of qubits.
clbits: Any classical bits to add to the circuit. This argument can be used,
for example, to enforce a particular ordering of classical bits.
name: The name of the circuit.
global_phase: The global phase of the circuit in radians.
metadata: Arbitrary key value metadata to associate with the circuit.
Returns:
The quantum circuit.
"""
circuit = QuantumCircuit(name=name, global_phase=global_phase, metadata=metadata)
added_qubits = set()
added_clbits = set()
if qubits:
qubits = list(qubits)
circuit.add_bits(qubits)
added_qubits.update(qubits)
if clbits:
clbits = list(clbits)
circuit.add_bits(clbits)
added_clbits.update(clbits)
for instruction in instructions:
if not isinstance(instruction, CircuitInstruction):
instruction = CircuitInstruction(*instruction)
qubits = [qubit for qubit in instruction.qubits if qubit not in added_qubits]
clbits = [clbit for clbit in instruction.clbits if clbit not in added_clbits]
circuit.add_bits(qubits)
circuit.add_bits(clbits)
added_qubits.update(qubits)
added_clbits.update(clbits)
circuit._append(instruction)
return circuit
@property
def layout(self) -> Optional[TranspileLayout]:
r"""Return any associated layout information about the circuit
This attribute contains an optional :class:`~.TranspileLayout`
object. This is typically set on the output from :func:`~.transpile`
or :meth:`.PassManager.run` to retain information about the
permutations caused on the input circuit by transpilation.
There are two types of permutations caused by the :func:`~.transpile`
function, an initial layout which permutes the qubits based on the
selected physical qubits on the :class:`~.Target`, and a final layout
which is an output permutation caused by :class:`~.SwapGate`\s
inserted during routing.
"""
return self._layout
@property
def data(self) -> QuantumCircuitData:
"""Return the circuit data (instructions and context).
Returns:
QuantumCircuitData: a list-like object containing the :class:`.CircuitInstruction`\\ s
for each instruction.
"""
return QuantumCircuitData(self)
@data.setter
def data(self, data_input: Iterable):
"""Sets the circuit data from a list of instructions and context.
Args:
data_input (Iterable): A sequence of instructions with their execution contexts. The
elements must either be instances of :class:`.CircuitInstruction` (preferred), or a
3-tuple of ``(instruction, qargs, cargs)`` (legacy). In the legacy format,
``instruction`` must be an :class:`~.circuit.Instruction`, while ``qargs`` and
``cargs`` must be iterables of :class:`.Qubit` or :class:`.Clbit` specifiers
(similar to the allowed forms in calls to :meth:`append`).
"""
# If data_input is QuantumCircuitData(self), clearing self._data
# below will also empty data_input, so make a shallow copy first.
data_input = list(data_input)
self._data = []
self._parameter_table = ParameterTable()
if not data_input:
return
if isinstance(data_input[0], CircuitInstruction):
for instruction in data_input:
self.append(instruction)
else:
for instruction, qargs, cargs in data_input:
self.append(instruction, qargs, cargs)
@property
def op_start_times(self) -> list[int]:
"""Return a list of operation start times.
This attribute is enabled once one of scheduling analysis passes
runs on the quantum circuit.
Returns:
List of integers representing instruction start times.
The index corresponds to the index of instruction in :attr:`QuantumCircuit.data`.
Raises:
AttributeError: When circuit is not scheduled.
"""
if self._op_start_times is None:
raise AttributeError(
"This circuit is not scheduled. "
"To schedule it run the circuit through one of the transpiler scheduling passes."
)
return self._op_start_times
@property
def calibrations(self) -> dict:
"""Return calibration dictionary.
The custom pulse definition of a given gate is of the form
``{'gate_name': {(qubits, params): schedule}}``
"""
return dict(self._calibrations)
@calibrations.setter
def calibrations(self, calibrations: dict):
"""Set the circuit calibration data from a dictionary of calibration definition.
Args:
calibrations (dict): A dictionary of input in the format
``{'gate_name': {(qubits, gate_params): schedule}}``
"""
self._calibrations = defaultdict(dict, calibrations)
def has_calibration_for(self, instruction: CircuitInstruction | tuple):
"""Return True if the circuit has a calibration defined for the instruction context. In this
case, the operation does not need to be translated to the device basis.
"""
if isinstance(instruction, CircuitInstruction):
operation = instruction.operation
qubits = instruction.qubits
else:
operation, qubits, _ = instruction
if not self.calibrations or operation.name not in self.calibrations:
return False
qubits = tuple(self.qubits.index(qubit) for qubit in qubits)
params = []
for p in operation.params:
if isinstance(p, ParameterExpression) and not p.parameters:
params.append(float(p))
else:
params.append(p)
params = tuple(params)
return (qubits, params) in self.calibrations[operation.name]
@property
def metadata(self) -> dict:
"""The user provided metadata associated with the circuit.
The metadata for the circuit is a user provided ``dict`` of metadata
for the circuit. It will not be used to influence the execution or
operation of the circuit, but it is expected to be passed between
all transforms of the circuit (ie transpilation) and that providers will
associate any circuit metadata with the results it returns from
execution of that circuit.
"""
return self._metadata
@metadata.setter
def metadata(self, metadata: dict | None):
"""Update the circuit metadata"""
if metadata is None:
metadata = {}
warnings.warn(
"Setting metadata to None was deprecated in Terra 0.24.0 and this ability will be "
"removed in a future release. Instead, set metadata to an empty dictionary.",
DeprecationWarning,
stacklevel=2,
)
elif not isinstance(metadata, dict):
raise TypeError("Only a dictionary is accepted for circuit metadata")
self._metadata = metadata
def __str__(self) -> str:
return str(self.draw(output="text"))
def __eq__(self, other) -> bool:
if not isinstance(other, QuantumCircuit):
return False
# TODO: remove the DAG from this function
from qiskit.converters import circuit_to_dag
return circuit_to_dag(self, copy_operations=False) == circuit_to_dag(
other, copy_operations=False
)
@classmethod
def _increment_instances(cls):
cls.instances += 1
@classmethod
def cls_instances(cls) -> int:
"""Return the current number of instances of this class,
useful for auto naming."""
return cls.instances
@classmethod
def cls_prefix(cls) -> str:
"""Return the prefix to use for auto naming."""
return cls.prefix
def _name_update(self) -> None:
"""update name of instance using instance number"""
if not is_main_process():
pid_name = f"-{mp.current_process().pid}"
else:
pid_name = ""
self.name = f"{self._base_name}-{self.cls_instances()}{pid_name}"
def has_register(self, register: Register) -> bool:
"""
Test if this circuit has the register r.
Args:
register (Register): a quantum or classical register.
Returns:
bool: True if the register is contained in this circuit.
"""
has_reg = False
if isinstance(register, QuantumRegister) and register in self.qregs:
has_reg = True
elif isinstance(register, ClassicalRegister) and register in self.cregs:
has_reg = True
return has_reg
def reverse_ops(self) -> "QuantumCircuit":
"""Reverse the circuit by reversing the order of instructions.
This is done by recursively reversing all instructions.
It does not invert (adjoint) any gate.
Returns:
QuantumCircuit: the reversed circuit.
Examples:
input:
.. parsed-literal::
┌───┐
q_0: ┤ H ├─────■──────
└───┘┌────┴─────┐
q_1: ─────┤ RX(1.57) ├
└──────────┘
output:
.. parsed-literal::
┌───┐
q_0: ─────■──────┤ H ├
┌────┴─────┐└───┘
q_1: ┤ RX(1.57) ├─────
└──────────┘
"""
reverse_circ = QuantumCircuit(
self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + "_reverse"
)
for instruction in reversed(self.data):
reverse_circ._append(instruction.replace(operation=instruction.operation.reverse_ops()))
reverse_circ.duration = self.duration
reverse_circ.unit = self.unit
return reverse_circ
def reverse_bits(self) -> "QuantumCircuit":
"""Return a circuit with the opposite order of wires.
The circuit is "vertically" flipped. If a circuit is
defined over multiple registers, the resulting circuit will have
the same registers but with their order flipped.
This method is useful for converting a circuit written in little-endian
convention to the big-endian equivalent, and vice versa.
Returns:
QuantumCircuit: the circuit with reversed bit order.
Examples:
input:
.. parsed-literal::
┌───┐
a_0: ┤ H ├──■─────────────────
└───┘┌─┴─┐
a_1: ─────┤ X ├──■────────────
└───┘┌─┴─┐
a_2: ──────────┤ X ├──■───────
└───┘┌─┴─┐
b_0: ───────────────┤ X ├──■──
└───┘┌─┴─┐
b_1: ────────────────────┤ X ├
└───┘
output:
.. parsed-literal::
┌───┐
b_0: ────────────────────┤ X ├
┌───┐└─┬─┘
b_1: ───────────────┤ X ├──■──
┌───┐└─┬─┘
a_0: ──────────┤ X ├──■───────
┌───┐└─┬─┘
a_1: ─────┤ X ├──■────────────
┌───┐└─┬─┘
a_2: ┤ H ├──■─────────────────
└───┘
"""
circ = QuantumCircuit(
list(reversed(self.qubits)),
list(reversed(self.clbits)),
name=self.name,
global_phase=self.global_phase,
)
new_qubit_map = circ.qubits[::-1]
new_clbit_map = circ.clbits[::-1]
for reg in reversed(self.qregs):
bits = [new_qubit_map[self.find_bit(qubit).index] for qubit in reversed(reg)]
circ.add_register(QuantumRegister(bits=bits, name=reg.name))
for reg in reversed(self.cregs):
bits = [new_clbit_map[self.find_bit(clbit).index] for clbit in reversed(reg)]
circ.add_register(ClassicalRegister(bits=bits, name=reg.name))
for instruction in self.data:
qubits = [new_qubit_map[self.find_bit(qubit).index] for qubit in instruction.qubits]
clbits = [new_clbit_map[self.find_bit(clbit).index] for clbit in instruction.clbits]
circ._append(instruction.replace(qubits=qubits, clbits=clbits))
return circ
def inverse(self) -> "QuantumCircuit":
"""Invert (take adjoint of) this circuit.
This is done by recursively inverting all gates.
Returns:
QuantumCircuit: the inverted circuit
Raises:
CircuitError: if the circuit cannot be inverted.
Examples:
input:
.. parsed-literal::
┌───┐
q_0: ┤ H ├─────■──────
└───┘┌────┴─────┐
q_1: ─────┤ RX(1.57) ├
└──────────┘
output:
.. parsed-literal::
┌───┐
q_0: ──────■──────┤ H ├
┌─────┴─────┐└───┘
q_1: ┤ RX(-1.57) ├─────
└───────────┘
"""
inverse_circ = QuantumCircuit(
self.qubits,
self.clbits,
*self.qregs,
*self.cregs,
name=self.name + "_dg",
global_phase=-self.global_phase,
)
for instruction in reversed(self._data):
inverse_circ._append(instruction.replace(operation=instruction.operation.inverse()))
return inverse_circ
def repeat(self, reps: int) -> "QuantumCircuit":
"""Repeat this circuit ``reps`` times.
Args:
reps (int): How often this circuit should be repeated.
Returns:
QuantumCircuit: A circuit containing ``reps`` repetitions of this circuit.
"""
repeated_circ = QuantumCircuit(
self.qubits, self.clbits, *self.qregs, *self.cregs, name=self.name + f"**{reps}"
)
# benefit of appending instructions: decomposing shows the subparts, i.e. the power
# is actually `reps` times this circuit, and it is currently much faster than `compose`.
if reps > 0:
try: # try to append as gate if possible to not disallow to_gate
inst: Instruction = self.to_gate()
except QiskitError:
inst = self.to_instruction()
for _ in range(reps):
repeated_circ._append(inst, self.qubits, self.clbits)
return repeated_circ
def power(self, power: float, matrix_power: bool = False) -> "QuantumCircuit":
"""Raise this circuit to the power of ``power``.
If ``power`` is a positive integer and ``matrix_power`` is ``False``, this implementation
defaults to calling ``repeat``. Otherwise, if the circuit is unitary, the matrix is
computed to calculate the matrix power.
Args:
power (float): The power to raise this circuit to.
matrix_power (bool): If True, the circuit is converted to a matrix and then the
matrix power is computed. If False, and ``power`` is a positive integer,
the implementation defaults to ``repeat``.
Raises:
CircuitError: If the circuit needs to be converted to a gate but it is not unitary.
Returns:
QuantumCircuit: A circuit implementing this circuit raised to the power of ``power``.
"""
if power >= 0 and isinstance(power, (int, np.integer)) and not matrix_power:
return self.repeat(power)
# attempt conversion to gate
if self.num_parameters > 0:
raise CircuitError(
"Cannot raise a parameterized circuit to a non-positive power "
"or matrix-power, please bind the free parameters: "
"{}".format(self.parameters)
)
try:
gate = self.to_gate()
except QiskitError as ex:
raise CircuitError(
"The circuit contains non-unitary operations and cannot be "
"controlled. Note that no qiskit.circuit.Instruction objects may "
"be in the circuit for this operation."
) from ex
power_circuit = QuantumCircuit(self.qubits, self.clbits, *self.qregs, *self.cregs)
power_circuit.append(gate.power(power), list(range(gate.num_qubits)))
return power_circuit
def control(
self,
num_ctrl_qubits: int = 1,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> "QuantumCircuit":
"""Control this circuit on ``num_ctrl_qubits`` qubits.
Args:
num_ctrl_qubits (int): The number of control qubits.
label (str): An optional label to give the controlled operation for visualization.
ctrl_state (str or int): The control state in decimal or as a bitstring
(e.g. '111'). If None, use ``2**num_ctrl_qubits - 1``.
Returns:
QuantumCircuit: The controlled version of this circuit.
Raises:
CircuitError: If the circuit contains a non-unitary operation and cannot be controlled.
"""
try:
gate = self.to_gate()
except QiskitError as ex:
raise CircuitError(
"The circuit contains non-unitary operations and cannot be "
"controlled. Note that no qiskit.circuit.Instruction objects may "
"be in the circuit for this operation."
) from ex
controlled_gate = gate.control(num_ctrl_qubits, label, ctrl_state)
control_qreg = QuantumRegister(num_ctrl_qubits)
controlled_circ = QuantumCircuit(
control_qreg, self.qubits, *self.qregs, name=f"c_{self.name}"
)
controlled_circ.append(controlled_gate, controlled_circ.qubits)
return controlled_circ
def compose(
self,
other: Union["QuantumCircuit", Instruction],
qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None,
clbits: ClbitSpecifier | Sequence[ClbitSpecifier] | None = None,
front: bool = False,
inplace: bool = False,
wrap: bool = False,
) -> Optional["QuantumCircuit"]:
"""Compose circuit with ``other`` circuit or instruction, optionally permuting wires.
``other`` can be narrower or of equal width to ``self``.
Args:
other (qiskit.circuit.Instruction or QuantumCircuit):
(sub)circuit or instruction to compose onto self. If not a :obj:`.QuantumCircuit`,
this can be anything that :obj:`.append` will accept.
qubits (list[Qubit|int]): qubits of self to compose onto.
clbits (list[Clbit|int]): clbits of self to compose onto.
front (bool): If True, front composition will be performed. This is not possible within
control-flow builder context managers.
inplace (bool): If True, modify the object. Otherwise return composed circuit.
wrap (bool): If True, wraps the other circuit into a gate (or instruction, depending on
whether it contains only unitary instructions) before composing it onto self.
Returns:
QuantumCircuit: the composed circuit (returns None if inplace==True).
Raises:
CircuitError: if no correct wire mapping can be made between the two circuits, such as
if ``other`` is wider than ``self``.
CircuitError: if trying to emit a new circuit while ``self`` has a partially built
control-flow context active, such as the context-manager forms of :meth:`if_test`,
:meth:`for_loop` and :meth:`while_loop`.
CircuitError: if trying to compose to the front of a circuit when a control-flow builder
block is active; there is no clear meaning to this action.
Examples:
.. code-block:: python
>>> lhs.compose(rhs, qubits=[3, 2], inplace=True)
.. parsed-literal::
┌───┐ ┌─────┐ ┌───┐
lqr_1_0: ───┤ H ├─── rqr_0: ──■──┤ Tdg ├ lqr_1_0: ───┤ H ├───────────────
├───┤ ┌─┴─┐└─────┘ ├───┤
lqr_1_1: ───┤ X ├─── rqr_1: ┤ X ├─────── lqr_1_1: ───┤ X ├───────────────
┌──┴───┴──┐ └───┘ ┌──┴───┴──┐┌───┐
lqr_1_2: ┤ U1(0.1) ├ + = lqr_1_2: ┤ U1(0.1) ├┤ X ├───────
└─────────┘ └─────────┘└─┬─┘┌─────┐
lqr_2_0: ─────■───── lqr_2_0: ─────■───────■──┤ Tdg ├
┌─┴─┐ ┌─┴─┐ └─────┘
lqr_2_1: ───┤ X ├─── lqr_2_1: ───┤ X ├───────────────
└───┘ └───┘
lcr_0: 0 ═══════════ lcr_0: 0 ═══════════════════════
lcr_1: 0 ═══════════ lcr_1: 0 ═══════════════════════
"""
# pylint: disable=cyclic-import
from qiskit.circuit.controlflow.switch_case import SwitchCaseOp
if inplace and front and self._control_flow_scopes:
# If we're composing onto ourselves while in a stateful control-flow builder context,
# there's no clear meaning to composition to the "front" of the circuit.
raise CircuitError(
"Cannot compose to the front of a circuit while a control-flow context is active."
)
if not inplace and self._control_flow_scopes:
# If we're inside a stateful control-flow builder scope, even if we successfully cloned
# the partial builder scope (not simple), the scope wouldn't be controlled by an active
# `with` statement, so the output circuit would be permanently broken.
raise CircuitError(
"Cannot emit a new composed circuit while a control-flow context is active."
)
dest = self if inplace else self.copy()
# As a special case, allow composing some clbits onto no clbits - normally the destination
# has to be strictly larger. This allows composing final measurements onto unitary circuits.
if isinstance(other, QuantumCircuit):
if not self.clbits and other.clbits:
dest.add_bits(other.clbits)
for reg in other.cregs:
dest.add_register(reg)
if wrap and isinstance(other, QuantumCircuit):
other = (
other.to_gate()
if all(isinstance(ins.operation, Gate) for ins in other.data)
else other.to_instruction()
)
if not isinstance(other, QuantumCircuit):
if qubits is None:
qubits = self.qubits[: other.num_qubits]
if clbits is None:
clbits = self.clbits[: other.num_clbits]
if front:
# Need to keep a reference to the data for use after we've emptied it.
old_data = list(dest.data)
dest.clear()
dest.append(other, qubits, clbits)
for instruction in old_data:
dest._append(instruction)
else:
dest.append(other, qargs=qubits, cargs=clbits)
if inplace:
return None
return dest
if other.num_qubits > dest.num_qubits or other.num_clbits > dest.num_clbits:
raise CircuitError(
"Trying to compose with another QuantumCircuit which has more 'in' edges."
)
# number of qubits and clbits must match number in circuit or None
edge_map: dict[Qubit | Clbit, Qubit | Clbit] = {}
if qubits is None:
edge_map.update(zip(other.qubits, dest.qubits))
else:
mapped_qubits = dest.qbit_argument_conversion(qubits)
if len(mapped_qubits) != len(other.qubits):
raise CircuitError(
f"Number of items in qubits parameter ({len(mapped_qubits)}) does not"
f" match number of qubits in the circuit ({len(other.qubits)})."
)
edge_map.update(zip(other.qubits, mapped_qubits))
if clbits is None:
edge_map.update(zip(other.clbits, dest.clbits))
else:
mapped_clbits = dest.cbit_argument_conversion(clbits)
if len(mapped_clbits) != len(other.clbits):
raise CircuitError(
f"Number of items in clbits parameter ({len(mapped_clbits)}) does not"
f" match number of clbits in the circuit ({len(other.clbits)})."
)
edge_map.update(zip(other.clbits, dest.cbit_argument_conversion(clbits)))
variable_mapper = _classical_resource_map.VariableMapper(
dest.cregs, edge_map, dest.add_register
)
mapped_instrs: list[CircuitInstruction] = []
for instr in other.data:
n_qargs: list[Qubit] = [edge_map[qarg] for qarg in instr.qubits]
n_cargs: list[Clbit] = [edge_map[carg] for carg in instr.clbits]
n_op = instr.operation.copy()
if (condition := getattr(n_op, "condition", None)) is not None:
n_op.condition = variable_mapper.map_condition(condition)
if isinstance(n_op, SwitchCaseOp):
n_op.target = variable_mapper.map_target(n_op.target)
mapped_instrs.append(CircuitInstruction(n_op, n_qargs, n_cargs))
if front:
# adjust new instrs before original ones and update all parameters
mapped_instrs += dest.data
dest.clear()
append = dest._control_flow_scopes[-1].append if dest._control_flow_scopes else dest._append
for instr in mapped_instrs:
append(instr)
for gate, cals in other.calibrations.items():
dest._calibrations[gate].update(cals)
dest.global_phase += other.global_phase
if inplace:
return None
return dest
def tensor(self, other: "QuantumCircuit", inplace: bool = False) -> Optional["QuantumCircuit"]:
"""Tensor ``self`` with ``other``.
Remember that in the little-endian convention the leftmost operation will be at the bottom
of the circuit. See also
`the docs <qiskit.org/documentation/tutorials/circuits/3_summary_of_quantum_operations.html>`__
for more information.
.. parsed-literal::
┌────────┐ ┌─────┐ ┌─────┐
q_0: ┤ bottom ├ ⊗ q_0: ┤ top ├ = q_0: ─┤ top ├──
└────────┘ └─────┘ ┌┴─────┴─┐
q_1: ┤ bottom ├
└────────┘
Args:
other (QuantumCircuit): The other circuit to tensor this circuit with.
inplace (bool): If True, modify the object. Otherwise return composed circuit.
Examples:
.. plot::
:include-source:
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')
Returns:
QuantumCircuit: The tensored circuit (returns None if inplace==True).
"""
num_qubits = self.num_qubits + other.num_qubits
num_clbits = self.num_clbits + other.num_clbits
# If a user defined both circuits with via register sizes and not with named registers
# (e.g. QuantumCircuit(2, 2)) then we have a naming collision, as the registers are by
# default called "q" resp. "c". To still allow tensoring we define new registers of the
# correct sizes.
if (
len(self.qregs) == len(other.qregs) == 1
and self.qregs[0].name == other.qregs[0].name == "q"
):
# check if classical registers are in the circuit
if num_clbits > 0:
dest = QuantumCircuit(num_qubits, num_clbits)
else:
dest = QuantumCircuit(num_qubits)
# handle case if ``measure_all`` was called on both circuits, in which case the
# registers are both named "meas"
elif (
len(self.cregs) == len(other.cregs) == 1
and self.cregs[0].name == other.cregs[0].name == "meas"
):
cr = ClassicalRegister(self.num_clbits + other.num_clbits, "meas")
dest = QuantumCircuit(*other.qregs, *self.qregs, cr)
# Now we don't have to handle any more cases arising from special implicit naming
else:
dest = QuantumCircuit(
other.qubits,
self.qubits,
other.clbits,
self.clbits,
*other.qregs,
*self.qregs,
*other.cregs,
*self.cregs,
)
# compose self onto the output, and then other
dest.compose(other, range(other.num_qubits), range(other.num_clbits), inplace=True)
dest.compose(
self,
range(other.num_qubits, num_qubits),
range(other.num_clbits, num_clbits),
inplace=True,
)
# Replace information from tensored circuit into self when inplace = True
if inplace:
self.__dict__.update(dest.__dict__)
return None
return dest
@property
def qubits(self) -> list[Qubit]:
"""
Returns a list of quantum bits in the order that the registers were added.
"""
return self._qubits
@property
def clbits(self) -> list[Clbit]:
"""
Returns a list of classical bits in the order that the registers were added.
"""
return self._clbits
@property
def ancillas(self) -> list[AncillaQubit]:
"""
Returns a list of ancilla bits in the order that the registers were added.
"""
return self._ancillas
def __and__(self, rhs: "QuantumCircuit") -> "QuantumCircuit":
"""Overload & to implement self.compose."""
return self.compose(rhs)
def __iand__(self, rhs: "QuantumCircuit") -> "QuantumCircuit":
"""Overload &= to implement self.compose in place."""
self.compose(rhs, inplace=True)
return self
def __xor__(self, top: "QuantumCircuit") -> "QuantumCircuit":
"""Overload ^ to implement self.tensor."""
return self.tensor(top)
def __ixor__(self, top: "QuantumCircuit") -> "QuantumCircuit":
"""Overload ^= to implement self.tensor in place."""
self.tensor(top, inplace=True)
return self
def __len__(self) -> int:
"""Return number of operations in circuit."""
return len(self._data)
@typing.overload
def __getitem__(self, item: int) -> CircuitInstruction:
...
@typing.overload
def __getitem__(self, item: slice) -> list[CircuitInstruction]:
...
def __getitem__(self, item):
"""Return indexed operation."""
return self._data[item]
@staticmethod
def cast(value: S, type_: Callable[..., T]) -> Union[S, T]:
"""Best effort to cast value to type. Otherwise, returns the value."""
try:
return type_(value)
except (ValueError, TypeError):
return value
def qbit_argument_conversion(self, qubit_representation: QubitSpecifier) -> list[Qubit]:
"""
Converts several qubit representations (such as indexes, range, etc.)
into a list of qubits.
Args:
qubit_representation (Object): representation to expand
Returns:
List(Qubit): the resolved instances of the qubits.
"""
return _bit_argument_conversion(
qubit_representation, self.qubits, self._qubit_indices, Qubit
)
def cbit_argument_conversion(self, clbit_representation: ClbitSpecifier) -> list[Clbit]:
"""
Converts several classical bit representations (such as indexes, range, etc.)
into a list of classical bits.
Args:
clbit_representation (Object): representation to expand
Returns:
List(tuple): Where each tuple is a classical bit.
"""
return _bit_argument_conversion(
clbit_representation, self.clbits, self._clbit_indices, Clbit
)
def _resolve_classical_resource(self, specifier):
"""Resolve a single classical resource specifier into a concrete resource, raising an error
if the specifier is invalid.
This is slightly different to :meth:`.cbit_argument_conversion`, because it should not
unwrap :obj:`.ClassicalRegister` instances into lists, and in general it should not allow
iterables or broadcasting. It is expected to be used as a callback for things like
:meth:`.InstructionSet.c_if` to check the validity of their arguments.
Args:
specifier (Union[Clbit, ClassicalRegister, int]): a specifier of a classical resource
present in this circuit. An ``int`` will be resolved into a :obj:`.Clbit` using the
same conventions as measurement operations on this circuit use.
Returns:
Union[Clbit, ClassicalRegister]: the resolved resource.
Raises:
CircuitError: if the resource is not present in this circuit, or if the integer index
passed is out-of-bounds.
"""
if isinstance(specifier, Clbit):
if specifier not in self._clbit_indices:
raise CircuitError(f"Clbit {specifier} is not present in this circuit.")
return specifier
if isinstance(specifier, ClassicalRegister):
# This is linear complexity for something that should be constant, but QuantumCircuit
# does not currently keep a hashmap of registers, and requires non-trivial changes to
# how it exposes its registers publically before such a map can be safely stored so it
# doesn't miss updates. (Jake, 2021-11-10).
if specifier not in self.cregs:
raise CircuitError(f"Register {specifier} is not present in this circuit.")
return specifier
if isinstance(specifier, int):
try:
return self._clbits[specifier]
except IndexError:
raise CircuitError(f"Classical bit index {specifier} is out-of-range.") from None
raise CircuitError(f"Unknown classical resource specifier: '{specifier}'.")
def _validate_expr(self, node: expr.Expr) -> expr.Expr:
for var in expr.iter_vars(node):
if isinstance(var.var, Clbit):
if var.var not in self._clbit_indices:
raise CircuitError(f"Clbit {var.var} is not present in this circuit.")
elif isinstance(var.var, ClassicalRegister):
if var.var not in self.cregs:
raise CircuitError(f"Register {var.var} is not present in this circuit.")
return node
def append(
self,
instruction: Operation | CircuitInstruction,
qargs: Sequence[QubitSpecifier] | None = None,
cargs: Sequence[ClbitSpecifier] | None = None,
) -> InstructionSet:
"""Append one or more instructions to the end of the circuit, modifying the circuit in
place.
The ``qargs`` and ``cargs`` will be expanded and broadcast according to the rules of the
given :class:`~.circuit.Instruction`, and any non-:class:`.Bit` specifiers (such as
integer indices) will be resolved into the relevant instances.
If a :class:`.CircuitInstruction` is given, it will be unwrapped, verified in the context of
this circuit, and a new object will be appended to the circuit. In this case, you may not
pass ``qargs`` or ``cargs`` separately.
Args:
instruction: :class:`~.circuit.Instruction` instance to append, or a
:class:`.CircuitInstruction` with all its context.
qargs: specifiers of the :class:`.Qubit`\\ s to attach instruction to.
cargs: specifiers of the :class:`.Clbit`\\ s to attach instruction to.
Returns:
qiskit.circuit.InstructionSet: a handle to the :class:`.CircuitInstruction`\\ s that
were actually added to the circuit.
Raises:
CircuitError: if the operation passed is not an instance of :class:`~.circuit.Instruction` .
"""
if isinstance(instruction, CircuitInstruction):
operation = instruction.operation
qargs = instruction.qubits
cargs = instruction.clbits
else:
operation = instruction
# Convert input to instruction
if not isinstance(operation, Operation):
if hasattr(operation, "to_instruction"):
operation = operation.to_instruction()
if not isinstance(operation, Operation):
raise CircuitError("operation.to_instruction() is not an Operation.")
else:
if issubclass(operation, Operation):
raise CircuitError(
"Object is a subclass of Operation, please add () to "
"pass an instance of this object."
)
raise CircuitError(
"Object to append must be an Operation or have a to_instruction() method."
)
# Make copy of parameterized gate instances
if hasattr(operation, "params"):
is_parameter = any(isinstance(param, Parameter) for param in operation.params)
if is_parameter:
operation = copy.deepcopy(operation)
expanded_qargs = [self.qbit_argument_conversion(qarg) for qarg in qargs or []]
expanded_cargs = [self.cbit_argument_conversion(carg) for carg in cargs or []]
if self._control_flow_scopes:
appender = self._control_flow_scopes[-1].append
requester = self._control_flow_scopes[-1].request_classical_resource
else:
appender = self._append
requester = self._resolve_classical_resource
instructions = InstructionSet(resource_requester=requester)
if isinstance(operation, Instruction):
for qarg, carg in operation.broadcast_arguments(expanded_qargs, expanded_cargs):
self._check_dups(qarg)
instruction = CircuitInstruction(operation, qarg, carg)
appender(instruction)
instructions.add(instruction)
else:
# For Operations that are non-Instructions, we use the Instruction's default method
for qarg, carg in Instruction.broadcast_arguments(
operation, expanded_qargs, expanded_cargs
):
self._check_dups(qarg)
instruction = CircuitInstruction(operation, qarg, carg)
appender(instruction)
instructions.add(instruction)
return instructions
# Preferred new style.
@typing.overload
def _append(
self, instruction: CircuitInstruction, _qargs: None = None, _cargs: None = None
) -> CircuitInstruction:
...
# To-be-deprecated old style.
@typing.overload
def _append(
self,
operation: Operation,
qargs: Sequence[Qubit],
cargs: Sequence[Clbit],
) -> Operation:
...
def _append(
self,
instruction: CircuitInstruction | Instruction,
qargs: Sequence[Qubit] | None = None,
cargs: Sequence[Clbit] | None = None,
):
"""Append an instruction to the end of the circuit, modifying the circuit in place.
.. warning::
This is an internal fast-path function, and it is the responsibility of the caller to
ensure that all the arguments are valid; there is no error checking here. In
particular, all the qubits and clbits must already exist in the circuit and there can be
no duplicates in the list.
.. note::
This function may be used by callers other than :obj:`.QuantumCircuit` when the caller
is sure that all error-checking, broadcasting and scoping has already been performed,
and the only reference to the circuit the instructions are being appended to is within
that same function. In particular, it is not safe to call
:meth:`QuantumCircuit._append` on a circuit that is received by a function argument.
This is because :meth:`.QuantumCircuit._append` will not recognise the scoping
constructs of the control-flow builder interface.
Args:
instruction: Operation instance to append
qargs: Qubits to attach the instruction to.
cargs: Clbits to attach the instruction to.
Returns:
Operation: a handle to the instruction that was just added
:meta public:
"""
old_style = not isinstance(instruction, CircuitInstruction)
if old_style:
instruction = CircuitInstruction(instruction, qargs, cargs)
self._data.append(instruction)
if isinstance(instruction.operation, Instruction):
self._update_parameter_table(instruction)
# mark as normal circuit if a new instruction is added
self.duration = None
self.unit = "dt"
return instruction.operation if old_style else instruction
def _update_parameter_table(self, instruction: CircuitInstruction):
for param_index, param in enumerate(instruction.operation.params):
if isinstance(param, (ParameterExpression, QuantumCircuit)):
# Scoped constructs like the control-flow ops use QuantumCircuit as a parameter.
atomic_parameters = set(param.parameters)
else:
atomic_parameters = set()
for parameter in atomic_parameters:
if parameter in self._parameter_table:
self._parameter_table[parameter].add((instruction.operation, param_index))
else:
if parameter.name in self._parameter_table.get_names():
raise CircuitError(f"Name conflict on adding parameter: {parameter.name}")
self._parameter_table[parameter] = ParameterReferences(
((instruction.operation, param_index),)
)
# clear cache if new parameter is added
self._parameters = None
def add_register(self, *regs: Register | int | Sequence[Bit]) -> None:
"""Add registers."""
if not regs:
return
if any(isinstance(reg, int) for reg in regs):
# QuantumCircuit defined without registers
if len(regs) == 1 and isinstance(regs[0], int):
# QuantumCircuit with anonymous quantum wires e.g. QuantumCircuit(2)
if regs[0] == 0:
regs = ()
else:
regs = (QuantumRegister(regs[0], "q"),)
elif len(regs) == 2 and all(isinstance(reg, int) for reg in regs):
# QuantumCircuit with anonymous wires e.g. QuantumCircuit(2, 3)
if regs[0] == 0:
qregs: tuple[QuantumRegister, ...] = ()
else:
qregs = (QuantumRegister(regs[0], "q"),)
if regs[1] == 0:
cregs: tuple[ClassicalRegister, ...] = ()
else:
cregs = (ClassicalRegister(regs[1], "c"),)
regs = qregs + cregs
else:
raise CircuitError(
"QuantumCircuit parameters can be Registers or Integers."
" If Integers, up to 2 arguments. QuantumCircuit was called"
" with %s." % (regs,)
)
for register in regs:
if isinstance(register, Register) and any(
register.name == reg.name for reg in self.qregs + self.cregs
):
raise CircuitError('register name "%s" already exists' % register.name)
if isinstance(register, AncillaRegister):
for bit in register:
if bit not in self._qubit_indices:
self._ancillas.append(bit)
if isinstance(register, QuantumRegister):
self.qregs.append(register)
for idx, bit in enumerate(register):
if bit in self._qubit_indices:
self._qubit_indices[bit].registers.append((register, idx))
else:
self._qubits.append(bit)
self._qubit_indices[bit] = BitLocations(
len(self._qubits) - 1, [(register, idx)]
)
elif isinstance(register, ClassicalRegister):
self.cregs.append(register)
for idx, bit in enumerate(register):
if bit in self._clbit_indices:
self._clbit_indices[bit].registers.append((register, idx))
else:
self._clbits.append(bit)
self._clbit_indices[bit] = BitLocations(
len(self._clbits) - 1, [(register, idx)]
)
elif isinstance(register, list):
self.add_bits(register)
else:
raise CircuitError("expected a register")
def add_bits(self, bits: Iterable[Bit]) -> None:
"""Add Bits to the circuit."""
duplicate_bits = set(self._qubit_indices).union(self._clbit_indices).intersection(bits)
if duplicate_bits:
raise CircuitError(f"Attempted to add bits found already in circuit: {duplicate_bits}")
for bit in bits:
if isinstance(bit, AncillaQubit):
self._ancillas.append(bit)
if isinstance(bit, Qubit):
self._qubits.append(bit)
self._qubit_indices[bit] = BitLocations(len(self._qubits) - 1, [])
elif isinstance(bit, Clbit):
self._clbits.append(bit)
self._clbit_indices[bit] = BitLocations(len(self._clbits) - 1, [])
else:
raise CircuitError(
"Expected an instance of Qubit, Clbit, or "
"AncillaQubit, but was passed {}".format(bit)
)
def find_bit(self, bit: Bit) -> BitLocations:
"""Find locations in the circuit which can be used to reference a given :obj:`~Bit`.
Args:
bit (Bit): The bit to locate.
Returns:
namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``)
contains the index at which the ``Bit`` can be found (in either
:obj:`~QuantumCircuit.qubits`, :obj:`~QuantumCircuit.clbits`, depending on its
type). The second element (``registers``) is a list of ``(register, index)``
pairs with an entry for each :obj:`~Register` in the circuit which contains the
:obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found).
Notes:
The circuit index of an :obj:`~AncillaQubit` will be its index in
:obj:`~QuantumCircuit.qubits`, not :obj:`~QuantumCircuit.ancillas`.
Raises:
CircuitError: If the supplied :obj:`~Bit` was of an unknown type.
CircuitError: If the supplied :obj:`~Bit` could not be found on the circuit.
"""
try:
if isinstance(bit, Qubit):
return self._qubit_indices[bit]
elif isinstance(bit, Clbit):
return self._clbit_indices[bit]
else:
raise CircuitError(f"Could not locate bit of unknown type: {type(bit)}")
except KeyError as err:
raise CircuitError(
f"Could not locate provided bit: {bit}. Has it been added to the QuantumCircuit?"
) from err
def _check_dups(self, qubits: Sequence[Qubit]) -> None:
"""Raise exception if list of qubits contains duplicates."""
squbits = set(qubits)
if len(squbits) != len(qubits):
raise CircuitError("duplicate qubit arguments")
def to_instruction(
self,
parameter_map: dict[Parameter, ParameterValueType] | None = None,
label: str | None = None,
) -> Instruction:
"""Create an Instruction out of this circuit.
Args:
parameter_map(dict): For parameterized circuits, a mapping from
parameters in the circuit to parameters to be used in the
instruction. If None, existing circuit parameters will also
parameterize the instruction.
label (str): Optional gate label.
Returns:
qiskit.circuit.Instruction: a composite instruction encapsulating this circuit
(can be decomposed back)
"""
from qiskit.converters.circuit_to_instruction import circuit_to_instruction
return circuit_to_instruction(self, parameter_map, label=label)
def to_gate(
self,
parameter_map: dict[Parameter, ParameterValueType] | None = None,
label: str | None = None,
) -> Gate:
"""Create a Gate out of this circuit.
Args:
parameter_map(dict): For parameterized circuits, a mapping from
parameters in the circuit to parameters to be used in the
gate. If None, existing circuit parameters will also
parameterize the gate.
label (str): Optional gate label.
Returns:
Gate: a composite gate encapsulating this circuit
(can be decomposed back)
"""
from qiskit.converters.circuit_to_gate import circuit_to_gate
return circuit_to_gate(self, parameter_map, label=label)
def decompose(
self,
gates_to_decompose: Type[Gate] | Sequence[Type[Gate]] | Sequence[str] | str | None = None,
reps: int = 1,
) -> "QuantumCircuit":
"""Call a decomposition pass on this circuit,
to decompose one level (shallow decompose).
Args:
gates_to_decompose (type or str or list(type, str)): Optional subset of gates
to decompose. Can be a gate type, such as ``HGate``, or a gate name, such
as 'h', or a gate label, such as 'My H Gate', or a list of any combination
of these. If a gate name is entered, it will decompose all gates with that
name, whether the gates have labels or not. Defaults to all gates in circuit.
reps (int): Optional number of times the circuit should be decomposed.
For instance, ``reps=2`` equals calling ``circuit.decompose().decompose()``.
can decompose specific gates specific time
Returns:
QuantumCircuit: a circuit one level decomposed
"""
# pylint: disable=cyclic-import
from qiskit.transpiler.passes.basis.decompose import Decompose
from qiskit.transpiler.passes.synthesis import HighLevelSynthesis
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.converters.dag_to_circuit import dag_to_circuit
dag = circuit_to_dag(self)
dag = HighLevelSynthesis().run(dag)
pass_ = Decompose(gates_to_decompose)
for _ in range(reps):
dag = pass_.run(dag)
return dag_to_circuit(dag)
def qasm(
self,
formatted: bool = False,
filename: str | None = None,
encoding: str | None = None,
) -> str | None:
"""Return OpenQASM string.
Args:
formatted (bool): Return formatted Qasm string.
filename (str): Save Qasm to file with name 'filename'.
encoding (str): Optionally specify the encoding to use for the
output file if ``filename`` is specified. By default this is
set to the system's default encoding (ie whatever
``locale.getpreferredencoding()`` returns) and can be set to
any valid codec or alias from stdlib's
`codec module <https://docs.python.org/3/library/codecs.html#standard-encodings>`__
Returns:
str: If formatted=False.
Raises:
MissingOptionalLibraryError: If pygments is not installed and ``formatted`` is
``True``.
QASM2ExportError: If circuit has free parameters.
QASM2ExportError: If an operation that has no OpenQASM 2 representation is encountered.
"""
from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import
if self.num_parameters > 0:
raise QASM2ExportError(
"Cannot represent circuits with unbound parameters in OpenQASM 2."
)
existing_gate_names = {
"barrier",
"measure",
"reset",
"u3",
"u2",
"u1",
"cx",
"id",
"u0",
"u",
"p",
"x",
"y",
"z",
"h",
"s",
"sdg",
"t",
"tdg",
"rx",
"ry",
"rz",
"sx",
"sxdg",
"cz",
"cy",
"swap",
"ch",
"ccx",
"cswap",
"crx",
"cry",
"crz",
"cu1",
"cp",
"cu3",
"csx",
"cu",
"rxx",
"rzz",
"rccx",
"rc3x",
"c3x",
"c3sx", # This is the Qiskit gate name, but the qelib1.inc name is 'c3sqrtx'.
"c4x",
}
# Mapping of instruction name to a pair of the source for a definition, and an OQ2 string
# that includes the `gate` or `opaque` statement that defines the gate.
gates_to_define: OrderedDict[str, tuple[Instruction, str]] = OrderedDict()
regless_qubits = [bit for bit in self.qubits if not self.find_bit(bit).registers]
regless_clbits = [bit for bit in self.clbits if not self.find_bit(bit).registers]
dummy_registers: list[QuantumRegister | ClassicalRegister] = []
if regless_qubits:
dummy_registers.append(QuantumRegister(name="qregless", bits=regless_qubits))
if regless_clbits:
dummy_registers.append(ClassicalRegister(name="cregless", bits=regless_clbits))
register_escaped_names: dict[str, QuantumRegister | ClassicalRegister] = {}
for regs in (self.qregs, self.cregs, dummy_registers):
for reg in regs:
register_escaped_names[
_make_unique(_qasm_escape_name(reg.name, "reg_"), register_escaped_names)
] = reg
bit_labels: dict[Qubit | Clbit, str] = {
bit: "%s[%d]" % (name, idx)
for name, register in register_escaped_names.items()
for (idx, bit) in enumerate(register)
}
register_definitions_qasm = "".join(
f"{'qreg' if isinstance(reg, QuantumRegister) else 'creg'} {name}[{reg.size}];\n"
for name, reg in register_escaped_names.items()
)
instruction_calls = []
for instruction in self._data:
operation = instruction.operation
if operation.name == "measure":
qubit = instruction.qubits[0]
clbit = instruction.clbits[0]
instruction_qasm = f"measure {bit_labels[qubit]} -> {bit_labels[clbit]};"
elif operation.name == "reset":
instruction_qasm = f"reset {bit_labels[instruction.qubits[0]]};"
elif operation.name == "barrier":
if not instruction.qubits:
# Barriers with no operands are invalid in (strict) OQ2, and the statement
# would have no meaning anyway.
continue
qargs = ",".join(bit_labels[q] for q in instruction.qubits)
instruction_qasm = "barrier;" if not qargs else f"barrier {qargs};"
else:
instruction_qasm = _qasm2_custom_operation_statement(
instruction, existing_gate_names, gates_to_define, bit_labels
)
instruction_calls.append(instruction_qasm)
instructions_qasm = "".join(f"{call}\n" for call in instruction_calls)
gate_definitions_qasm = "".join(f"{qasm}\n" for _, qasm in gates_to_define.values())
out = "".join(
(
self.header,
"\n",
self.extension_lib,
"\n",
gate_definitions_qasm,
register_definitions_qasm,
instructions_qasm,
)
)
if filename:
with open(filename, "w+", encoding=encoding) as file:
file.write(out)
if formatted:
_optionals.HAS_PYGMENTS.require_now("formatted OpenQASM 2 output")
import pygments
from pygments.formatters import ( # pylint: disable=no-name-in-module
Terminal256Formatter,
)
from qiskit.qasm.pygments import OpenQASMLexer
from qiskit.qasm.pygments import QasmTerminalStyle
code = pygments.highlight(
out, OpenQASMLexer(), Terminal256Formatter(style=QasmTerminalStyle)
)
print(code)
return None
return out
def draw(
self,
output: str | None = None,
scale: float | None = None,
filename: str | None = None,
style: dict | str | None = None,
interactive: bool = False,
plot_barriers: bool = True,
reverse_bits: bool = None,
justify: str | None = None,
vertical_compression: str | None = "medium",
idle_wires: bool = True,
with_layout: bool = True,
fold: int | None = None,
# The type of ax is matplotlib.axes.Axes, but this is not a fixed dependency, so cannot be
# safely forward-referenced.
ax: Any | None = None,
initial_state: bool = False,
cregbundle: bool = None,
wire_order: list = None,
):
"""Draw the quantum circuit. Use the output parameter to choose the drawing format:
**text**: ASCII art TextDrawing that can be printed in the console.
**mpl**: images with color rendered purely in Python using matplotlib.
**latex**: high-quality images compiled via latex.
**latex_source**: raw uncompiled latex output.
.. warning::
Support for :class:`~.expr.Expr` nodes in conditions and :attr:`.SwitchCaseOp.target`
fields is preliminary and incomplete. The ``text`` and ``mpl`` drawers will make a
best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip
these completely.
Args:
output (str): select the output method to use for drawing the circuit.
Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``.
By default the `text` drawer is used unless the user config file
(usually ``~/.qiskit/settings.conf``) has an alternative backend set
as the default. For example, ``circuit_drawer = latex``. If the output
kwarg is set, that backend will always be used over the default in
the user config file.
scale (float): scale of image to draw (shrink if < 1.0). Only used by
the `mpl`, `latex` and `latex_source` outputs. Defaults to 1.0.
filename (str): file path to save image to. Defaults to None.
style (dict or str): dictionary of style or file name of style json file.
This option is only used by the `mpl` or `latex` output type.
If `style` is a str, it is used as the path to a json file
which contains a style dict. The file will be opened, parsed, and
then any style elements in the dict will replace the default values
in the input dict. A file to be loaded must end in ``.json``, but
the name entered here can omit ``.json``. For example,
``style='iqx.json'`` or ``style='iqx'``.
If `style` is a dict and the ``'name'`` key is set, that name
will be used to load a json file, followed by loading the other
items in the style dict. For example, ``style={'name': 'iqx'}``.
If `style` is not a str and `name` is not a key in the style dict,
then the default value from the user config file (usually
``~/.qiskit/settings.conf``) will be used, for example,
``circuit_mpl_style = iqx``.
If none of these are set, the `default` style will be used.
The search path for style json files can be specified in the user
config, for example,
``circuit_mpl_style_path = /home/user/styles:/home/user``.
See: :class:`~qiskit.visualization.qcstyle.DefaultStyle` for more
information on the contents.
interactive (bool): when set to true, show the circuit in a new window
(for `mpl` this depends on the matplotlib backend being used
supporting this). Note when used with either the `text` or the
`latex_source` output type this has no effect and will be silently
ignored. Defaults to False.
reverse_bits (bool): when set to True, reverse the bit order inside
registers for the output visualization. Defaults to False unless the
user config file (usually ``~/.qiskit/settings.conf``) has an
alternative value set. For example, ``circuit_reverse_bits = True``.
plot_barriers (bool): enable/disable drawing barriers in the output
circuit. Defaults to True.
justify (string): options are ``left``, ``right`` or ``none``. If
anything else is supplied, it defaults to left justified. It refers
to where gates should be placed in the output circuit if there is
an option. ``none`` results in each gate being placed in its own
column.
vertical_compression (string): ``high``, ``medium`` or ``low``. It
merges the lines generated by the `text` output so the drawing
will take less vertical room. Default is ``medium``. Only used by
the `text` output, will be silently ignored otherwise.
idle_wires (bool): include idle wires (wires with no circuit elements)
in output visualization. Default is True.
with_layout (bool): include layout information, with labels on the
physical layout. Default is True.
fold (int): sets pagination. It can be disabled using -1. In `text`,
sets the length of the lines. This is useful when the drawing does
not fit in the console. If None (default), it will try to guess the
console width using ``shutil.get_terminal_size()``. However, if
running in jupyter, the default line length is set to 80 characters.
In `mpl`, it is the number of (visual) layers before folding.
Default is 25.
ax (matplotlib.axes.Axes): Only used by the `mpl` backend. An optional
Axes object to be used for the visualization output. If none is
specified, a new matplotlib Figure will be created and used.
Additionally, if specified there will be no returned Figure since
it is redundant.
initial_state (bool): Optional. Adds ``|0>`` in the beginning of the wire.
Default is False.
cregbundle (bool): Optional. If set True, bundle classical registers.
Default is True, except for when ``output`` is set to ``"text"``.
wire_order (list): Optional. A list of integers used to reorder the display
of the bits. The list must have an entry for every bit with the bits
in the range 0 to (``num_qubits`` + ``num_clbits``).
Returns:
:class:`.TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or
:class:`str`:
* `TextDrawing` (output='text')
A drawing that can be printed as ascii art.
* `matplotlib.figure.Figure` (output='mpl')
A matplotlib figure object for the circuit diagram.
* `PIL.Image` (output='latex')
An in-memory representation of the image of the circuit diagram.
* `str` (output='latex_source')
The LaTeX source code for visualizing the circuit diagram.
Raises:
VisualizationError: when an invalid output method is selected
ImportError: when the output methods requires non-installed libraries.
Example:
.. plot::
:include-source:
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
"""
# pylint: disable=cyclic-import
from qiskit.visualization import circuit_drawer
return circuit_drawer(
self,
scale=scale,
filename=filename,
style=style,
output=output,
interactive=interactive,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits,
justify=justify,
vertical_compression=vertical_compression,
idle_wires=idle_wires,
with_layout=with_layout,
fold=fold,
ax=ax,
initial_state=initial_state,
cregbundle=cregbundle,
wire_order=wire_order,
)
def size(
self,
filter_function: Callable[..., int] = lambda x: not getattr(
x.operation, "_directive", False
),
) -> int:
"""Returns total number of instructions in circuit.
Args:
filter_function (callable): a function to filter out some instructions.
Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)).
By default filters out "directives", such as barrier or snapshot.
Returns:
int: Total number of gate operations.
"""
return sum(map(filter_function, self._data))
def depth(
self,
filter_function: Callable[..., int] = lambda x: not getattr(
x.operation, "_directive", False
),
) -> int:
"""Return circuit depth (i.e., length of critical path).
Args:
filter_function (callable): A function to filter instructions.
Should take as input a tuple of (Instruction, list(Qubit), list(Clbit)).
Instructions for which the function returns False are ignored in the
computation of the circuit depth.
By default filters out "directives", such as barrier or snapshot.
Returns:
int: Depth of circuit.
Notes:
The circuit depth and the DAG depth need not be the
same.
"""
# Assign each bit in the circuit a unique integer
# to index into op_stack.
bit_indices: dict[Qubit | Clbit, int] = {
bit: idx for idx, bit in enumerate(self.qubits + self.clbits)
}
# If no bits, return 0
if not bit_indices:
return 0
# A list that holds the height of each qubit
# and classical bit.
op_stack = [0] * len(bit_indices)
# Here we are playing a modified version of
# Tetris where we stack gates, but multi-qubit
# gates, or measurements have a block for each
# qubit or cbit that are connected by a virtual
# line so that they all stacked at the same depth.
# Conditional gates act on all cbits in the register
# they are conditioned on.
# The max stack height is the circuit depth.
for instruction in self._data:
levels = []
reg_ints = []
for ind, reg in enumerate(instruction.qubits + instruction.clbits):
# Add to the stacks of the qubits and
# cbits used in the gate.
reg_ints.append(bit_indices[reg])
if filter_function(instruction):
levels.append(op_stack[reg_ints[ind]] + 1)
else:
levels.append(op_stack[reg_ints[ind]])
# Assuming here that there is no conditional
# snapshots or barriers ever.
if getattr(instruction.operation, "condition", None):
# Controls operate over all bits of a classical register
# or over a single bit
if isinstance(instruction.operation.condition[0], Clbit):
condition_bits = [instruction.operation.condition[0]]
else:
condition_bits = instruction.operation.condition[0]
for cbit in condition_bits:
idx = bit_indices[cbit]
if idx not in reg_ints:
reg_ints.append(idx)
levels.append(op_stack[idx] + 1)
max_level = max(levels)
for ind in reg_ints:
op_stack[ind] = max_level
return max(op_stack)
def width(self) -> int:
"""Return number of qubits plus clbits in circuit.
Returns:
int: Width of circuit.
"""
return len(self.qubits) + len(self.clbits)
@property
def num_qubits(self) -> int:
"""Return number of qubits."""
return len(self.qubits)
@property
def num_ancillas(self) -> int:
"""Return the number of ancilla qubits."""
return len(self.ancillas)
@property
def num_clbits(self) -> int:
"""Return number of classical bits."""
return len(self.clbits)
# The stringified return type is because OrderedDict can't be subscripted before Python 3.9, and
# typing.OrderedDict wasn't added until 3.7.2. It can be turned into a proper type once 3.6
# support is dropped.
def count_ops(self) -> "OrderedDict[Instruction, int]":
"""Count each operation kind in the circuit.
Returns:
OrderedDict: a breakdown of how many operations of each kind, sorted by amount.
"""
count_ops: dict[Instruction, int] = {}
for instruction in self._data:
count_ops[instruction.operation.name] = count_ops.get(instruction.operation.name, 0) + 1
return OrderedDict(sorted(count_ops.items(), key=lambda kv: kv[1], reverse=True))
def num_nonlocal_gates(self) -> int:
"""Return number of non-local gates (i.e. involving 2+ qubits).
Conditional nonlocal gates are also included.
"""
multi_qubit_gates = 0
for instruction in self._data:
if instruction.operation.num_qubits > 1 and not getattr(
instruction.operation, "_directive", False
):
multi_qubit_gates += 1
return multi_qubit_gates
def get_instructions(self, name: str) -> list[CircuitInstruction]:
"""Get instructions matching name.
Args:
name (str): The name of instruction to.
Returns:
list(tuple): list of (instruction, qargs, cargs).
"""
return [match for match in self._data if match.operation.name == name]
def num_connected_components(self, unitary_only: bool = False) -> int:
"""How many non-entangled subcircuits can the circuit be factored to.
Args:
unitary_only (bool): Compute only unitary part of graph.
Returns:
int: Number of connected components in circuit.
"""
# Convert registers to ints (as done in depth).
bits = self.qubits if unitary_only else (self.qubits + self.clbits)
bit_indices: dict[Qubit | Clbit, int] = {bit: idx for idx, bit in enumerate(bits)}
# Start with each qubit or cbit being its own subgraph.
sub_graphs = [[bit] for bit in range(len(bit_indices))]
num_sub_graphs = len(sub_graphs)
# Here we are traversing the gates and looking to see
# which of the sub_graphs the gate joins together.
for instruction in self._data:
if unitary_only:
args = instruction.qubits
num_qargs = len(args)
else:
args = instruction.qubits + instruction.clbits
num_qargs = len(args) + (
1 if getattr(instruction.operation, "condition", None) else 0
)
if num_qargs >= 2 and not getattr(instruction.operation, "_directive", False):
graphs_touched = []
num_touched = 0
# Controls necessarily join all the cbits in the
# register that they use.
if not unitary_only:
for bit in instruction.operation.condition_bits:
idx = bit_indices[bit]
for k in range(num_sub_graphs):
if idx in sub_graphs[k]:
graphs_touched.append(k)
break
for item in args:
reg_int = bit_indices[item]
for k in range(num_sub_graphs):
if reg_int in sub_graphs[k]:
if k not in graphs_touched:
graphs_touched.append(k)
break
graphs_touched = list(set(graphs_touched))
num_touched = len(graphs_touched)
# If the gate touches more than one subgraph
# join those graphs together and return
# reduced number of subgraphs
if num_touched > 1:
connections = []
for idx in graphs_touched:
connections.extend(sub_graphs[idx])
_sub_graphs = []
for idx in range(num_sub_graphs):
if idx not in graphs_touched:
_sub_graphs.append(sub_graphs[idx])
_sub_graphs.append(connections)
sub_graphs = _sub_graphs
num_sub_graphs -= num_touched - 1
# Cannot go lower than one so break
if num_sub_graphs == 1:
break
return num_sub_graphs
def num_unitary_factors(self) -> int:
"""Computes the number of tensor factors in the unitary
(quantum) part of the circuit only.
"""
return self.num_connected_components(unitary_only=True)
def num_tensor_factors(self) -> int:
"""Computes the number of tensor factors in the unitary
(quantum) part of the circuit only.
Notes:
This is here for backwards compatibility, and will be
removed in a future release of Qiskit. You should call
`num_unitary_factors` instead.
"""
return self.num_unitary_factors()
def copy(self, name: str | None = None) -> "QuantumCircuit":
"""Copy the circuit.
Args:
name (str): name to be given to the copied circuit. If None, then the name stays the same.
Returns:
QuantumCircuit: a deepcopy of the current circuit, with the specified name
"""
cpy = self.copy_empty_like(name)
operation_copies = {
id(instruction.operation): instruction.operation.copy() for instruction in self._data
}
cpy._parameter_table = ParameterTable(
{
param: ParameterReferences(
(operation_copies[id(operation)], param_index)
for operation, param_index in self._parameter_table[param]
)
for param in self._parameter_table
}
)
cpy._data = [
instruction.replace(operation=operation_copies[id(instruction.operation)])
for instruction in self._data
]
return cpy
def copy_empty_like(self, name: str | None = None) -> "QuantumCircuit":
"""Return a copy of self with the same structure but empty.
That structure includes:
* name, calibrations and other metadata
* global phase
* all the qubits and clbits, including the registers
Args:
name (str): Name for the copied circuit. If None, then the name stays the same.
Returns:
QuantumCircuit: An empty copy of self.
"""
if not (name is None or isinstance(name, str)):
raise TypeError(
f"invalid name for a circuit: '{name}'. The name must be a string or 'None'."
)
cpy = copy.copy(self)
# copy registers correctly, in copy.copy they are only copied via reference
cpy.qregs = self.qregs.copy()
cpy.cregs = self.cregs.copy()
cpy._qubits = self._qubits.copy()
cpy._ancillas = self._ancillas.copy()
cpy._clbits = self._clbits.copy()
cpy._qubit_indices = self._qubit_indices.copy()
cpy._clbit_indices = self._clbit_indices.copy()
cpy._parameter_table = ParameterTable()
cpy._data = []
cpy._calibrations = copy.deepcopy(self._calibrations)
cpy._metadata = copy.deepcopy(self._metadata)
if name:
cpy.name = name
return cpy
def clear(self) -> None:
"""Clear all instructions in self.
Clearing the circuits will keep the metadata and calibrations.
"""
self._data.clear()
self._parameter_table.clear()
def _create_creg(self, length: int, name: str) -> ClassicalRegister:
"""Creates a creg, checking if ClassicalRegister with same name exists"""
if name in [creg.name for creg in self.cregs]:
save_prefix = ClassicalRegister.prefix
ClassicalRegister.prefix = name
new_creg = ClassicalRegister(length)
ClassicalRegister.prefix = save_prefix
else:
new_creg = ClassicalRegister(length, name)
return new_creg
def _create_qreg(self, length: int, name: str) -> QuantumRegister:
"""Creates a qreg, checking if QuantumRegister with same name exists"""
if name in [qreg.name for qreg in self.qregs]:
save_prefix = QuantumRegister.prefix
QuantumRegister.prefix = name
new_qreg = QuantumRegister(length)
QuantumRegister.prefix = save_prefix
else:
new_qreg = QuantumRegister(length, name)
return new_qreg
def reset(self, qubit: QubitSpecifier) -> InstructionSet:
"""Reset the quantum bit(s) to their default state.
Args:
qubit: qubit(s) to reset.
Returns:
qiskit.circuit.InstructionSet: handle to the added instruction.
"""
return self.append(Reset(), [qubit], [])
def measure(self, qubit: QubitSpecifier, cbit: ClbitSpecifier) -> InstructionSet:
r"""Measure a quantum bit (``qubit``) in the Z basis into a classical bit (``cbit``).
When a quantum state is measured, a qubit is projected in the computational (Pauli Z) basis
to either :math:`\lvert 0 \rangle` or :math:`\lvert 1 \rangle`. The classical bit ``cbit``
indicates the result
of that projection as a ``0`` or a ``1`` respectively. This operation is non-reversible.
Args:
qubit: qubit(s) to measure.
cbit: classical bit(s) to place the measurement result(s) in.
Returns:
qiskit.circuit.InstructionSet: handle to the added instructions.
Raises:
CircuitError: if arguments have bad format.
Examples:
In this example, a qubit is measured and the result of that measurement is stored in the
classical bit (usually expressed in diagrams as a double line):
.. code-block::
from qiskit import QuantumCircuit
circuit = QuantumCircuit(1, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.draw()
.. parsed-literal::
┌───┐┌─┐
q: ┤ H ├┤M├
└───┘└╥┘
c: 1/══════╩═
0
It is possible to call ``measure`` with lists of ``qubits`` and ``cbits`` as a shortcut
for one-to-one measurement. These two forms produce identical results:
.. code-block::
circuit = QuantumCircuit(2, 2)
circuit.measure([0,1], [0,1])
.. code-block::
circuit = QuantumCircuit(2, 2)
circuit.measure(0, 0)
circuit.measure(1, 1)
Instead of lists, you can use :class:`~qiskit.circuit.QuantumRegister` and
:class:`~qiskit.circuit.ClassicalRegister` under the same logic.
.. code-block::
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qreg = QuantumRegister(2, "qreg")
creg = ClassicalRegister(2, "creg")
circuit = QuantumCircuit(qreg, creg)
circuit.measure(qreg, creg)
This is equivalent to:
.. code-block::
circuit = QuantumCircuit(qreg, creg)
circuit.measure(qreg[0], creg[0])
circuit.measure(qreg[1], creg[1])
"""
return self.append(Measure(), [qubit], [cbit])
def measure_active(self, inplace: bool = True) -> Optional["QuantumCircuit"]:
"""Adds measurement to all non-idle qubits. Creates a new ClassicalRegister with
a size equal to the number of non-idle qubits being measured.
Returns a new circuit with measurements if `inplace=False`.
Args:
inplace (bool): All measurements inplace or return new circuit.
Returns:
QuantumCircuit: Returns circuit with measurements when `inplace = False`.
"""
from qiskit.converters.circuit_to_dag import circuit_to_dag
if inplace:
circ = self
else:
circ = self.copy()
dag = circuit_to_dag(circ)
qubits_to_measure = [qubit for qubit in circ.qubits if qubit not in dag.idle_wires()]
new_creg = circ._create_creg(len(qubits_to_measure), "measure")
circ.add_register(new_creg)
circ.barrier()
circ.measure(qubits_to_measure, new_creg)
if not inplace:
return circ
else:
return None
def measure_all(
self, inplace: bool = True, add_bits: bool = True
) -> Optional["QuantumCircuit"]:
"""Adds measurement to all qubits.
By default, adds new classical bits in a :obj:`.ClassicalRegister` to store these
measurements. If ``add_bits=False``, the results of the measurements will instead be stored
in the already existing classical bits, with qubit ``n`` being measured into classical bit
``n``.
Returns a new circuit with measurements if ``inplace=False``.
Args:
inplace (bool): All measurements inplace or return new circuit.
add_bits (bool): Whether to add new bits to store the results.
Returns:
QuantumCircuit: Returns circuit with measurements when ``inplace=False``.
Raises:
CircuitError: if ``add_bits=False`` but there are not enough classical bits.
"""
if inplace:
circ = self
else:
circ = self.copy()
if add_bits:
new_creg = circ._create_creg(len(circ.qubits), "meas")
circ.add_register(new_creg)
circ.barrier()
circ.measure(circ.qubits, new_creg)
else:
if len(circ.clbits) < len(circ.qubits):
raise CircuitError(
"The number of classical bits must be equal or greater than "
"the number of qubits."
)
circ.barrier()
circ.measure(circ.qubits, circ.clbits[0 : len(circ.qubits)])
if not inplace:
return circ
else:
return None
def remove_final_measurements(self, inplace: bool = True) -> Optional["QuantumCircuit"]:
"""Removes final measurements and barriers on all qubits if they are present.
Deletes the classical registers that were used to store the values from these measurements
that become idle as a result of this operation, and deletes classical bits that are
referenced only by removed registers, or that aren't referenced at all but have
become idle as a result of this operation.
Measurements and barriers are considered final if they are
followed by no other operations (aside from other measurements or barriers.)
Args:
inplace (bool): All measurements removed inplace or return new circuit.
Returns:
QuantumCircuit: Returns the resulting circuit when ``inplace=False``, else None.
"""
# pylint: disable=cyclic-import
from qiskit.transpiler.passes import RemoveFinalMeasurements
from qiskit.converters import circuit_to_dag
if inplace:
circ = self
else:
circ = self.copy()
dag = circuit_to_dag(circ)
remove_final_meas = RemoveFinalMeasurements()
new_dag = remove_final_meas.run(dag)
kept_cregs = set(new_dag.cregs.values())
kept_clbits = set(new_dag.clbits)
# Filter only cregs/clbits still in new DAG, preserving original circuit order
cregs_to_add = [creg for creg in circ.cregs if creg in kept_cregs]
clbits_to_add = [clbit for clbit in circ._clbits if clbit in kept_clbits]
# Clear cregs and clbits
circ.cregs = []
circ._clbits = []
circ._clbit_indices = {}
# We must add the clbits first to preserve the original circuit
# order. This way, add_register never adds clbits and just
# creates registers that point to them.
circ.add_bits(clbits_to_add)
for creg in cregs_to_add:
circ.add_register(creg)
# Clear instruction info
circ.data.clear()
circ._parameter_table.clear()
# Set circ instructions to match the new DAG
for node in new_dag.topological_op_nodes():
# Get arguments for classical condition (if any)
inst = node.op.copy()
circ.append(inst, node.qargs, node.cargs)
if not inplace:
return circ
else:
return None
@staticmethod
def from_qasm_file(path: str) -> "QuantumCircuit":
"""Take in a QASM file and generate a QuantumCircuit object.
Args:
path (str): Path to the file for a QASM program
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
See also:
:func:`.qasm2.load`: the complete interface to the OpenQASM 2 importer.
"""
# pylint: disable=cyclic-import
from qiskit import qasm2
return qasm2.load(
path,
include_path=qasm2.LEGACY_INCLUDE_PATH,
custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS,
custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL,
strict=False,
)
@staticmethod
def from_qasm_str(qasm_str: str) -> "QuantumCircuit":
"""Take in a QASM string and generate a QuantumCircuit object.
Args:
qasm_str (str): A QASM program string
Return:
QuantumCircuit: The QuantumCircuit object for the input QASM
See also:
:func:`.qasm2.loads`: the complete interface to the OpenQASM 2 importer.
"""
# pylint: disable=cyclic-import
from qiskit import qasm2
return qasm2.loads(
qasm_str,
include_path=qasm2.LEGACY_INCLUDE_PATH,
custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS,
custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL,
strict=False,
)
@property
def global_phase(self) -> ParameterValueType:
"""Return the global phase of the circuit in radians."""
return self._global_phase
@global_phase.setter
def global_phase(self, angle: ParameterValueType):
"""Set the phase of the circuit.
Args:
angle (float, ParameterExpression): radians
"""
if isinstance(angle, ParameterExpression) and angle.parameters:
self._global_phase = angle
else:
# Set the phase to the [0, 2π) interval
angle = float(angle)
if not angle:
self._global_phase = 0
else:
self._global_phase = angle % (2 * np.pi)
@property
def parameters(self) -> ParameterView:
"""The parameters defined in the circuit.
This attribute returns the :class:`.Parameter` objects in the circuit sorted
alphabetically. Note that parameters instantiated with a :class:`.ParameterVector`
are still sorted numerically.
Examples:
The snippet below shows that insertion order of parameters does not matter.
.. code-block:: python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> a, b, elephant = Parameter("a"), Parameter("b"), Parameter("elephant")
>>> circuit = QuantumCircuit(1)
>>> circuit.rx(b, 0)
>>> circuit.rz(elephant, 0)
>>> circuit.ry(a, 0)
>>> circuit.parameters # sorted alphabetically!
ParameterView([Parameter(a), Parameter(b), Parameter(elephant)])
Bear in mind that alphabetical sorting might be unintuitive when it comes to numbers.
The literal "10" comes before "2" in strict alphabetical sorting.
.. code-block:: python
>>> from qiskit.circuit import QuantumCircuit, Parameter
>>> angles = [Parameter("angle_1"), Parameter("angle_2"), Parameter("angle_10")]
>>> circuit = QuantumCircuit(1)
>>> circuit.u(*angles, 0)
>>> circuit.draw()
┌─────────────────────────────┐
q: ┤ U(angle_1,angle_2,angle_10) ├
└─────────────────────────────┘
>>> circuit.parameters
ParameterView([Parameter(angle_1), Parameter(angle_10), Parameter(angle_2)])
To respect numerical sorting, a :class:`.ParameterVector` can be used.
.. code-block:: python
>>> from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
>>> x = ParameterVector("x", 12)
>>> circuit = QuantumCircuit(1)
>>> for x_i in x:
... circuit.rx(x_i, 0)
>>> circuit.parameters
ParameterView([
ParameterVectorElement(x[0]), ParameterVectorElement(x[1]),
ParameterVectorElement(x[2]), ParameterVectorElement(x[3]),
..., ParameterVectorElement(x[11])
])
Returns:
The sorted :class:`.Parameter` objects in the circuit.
"""
# parameters from gates
if self._parameters is None:
self._parameters = sort_parameters(self._unsorted_parameters())
# return as parameter view, which implements the set and list interface
return ParameterView(self._parameters)
@property
def num_parameters(self) -> int:
"""The number of parameter objects in the circuit."""
return len(self._unsorted_parameters())
def _unsorted_parameters(self) -> set[Parameter]:
"""Efficiently get all parameters in the circuit, without any sorting overhead."""
parameters = set(self._parameter_table)
if isinstance(self.global_phase, ParameterExpression):
parameters.update(self.global_phase.parameters)
return parameters
@overload
def assign_parameters(
self,
parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]],
inplace: Literal[False] = ...,
*,
flat_input: bool = ...,
strict: bool = ...,
) -> "QuantumCircuit":
...
@overload
def assign_parameters(
self,
parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]],
inplace: Literal[True] = ...,
*,
flat_input: bool = ...,
strict: bool = ...,
) -> None:
...
def assign_parameters( # pylint: disable=missing-raises-doc
self,
parameters: Union[Mapping[Parameter, ParameterValueType], Sequence[ParameterValueType]],
inplace: bool = False,
*,
flat_input: bool = False,
strict: bool = True,
) -> Optional["QuantumCircuit"]:
"""Assign parameters to new parameters or values.
If ``parameters`` is passed as a dictionary, the keys must be :class:`.Parameter`
instances in the current circuit. The values of the dictionary can either be numeric values
or new parameter objects.
If ``parameters`` is passed as a list or array, the elements are assigned to the
current parameters in the order of :attr:`parameters` which is sorted
alphabetically (while respecting the ordering in :class:`.ParameterVector` objects).
The values can be assigned to the current circuit object or to a copy of it.
Args:
parameters: Either a dictionary or iterable specifying the new parameter values.
inplace: If False, a copy of the circuit with the bound parameters is returned.
If True the circuit instance itself is modified.
flat_input: If ``True`` and ``parameters`` is a mapping type, it is assumed to be
exactly a mapping of ``{parameter: value}``. By default (``False``), the mapping
may also contain :class:`.ParameterVector` keys that point to a corresponding
sequence of values, and these will be unrolled during the mapping.
strict: If ``False``, any parameters given in the mapping that are not used in the
circuit will be ignored. If ``True`` (the default), an error will be raised
indicating a logic error.
Raises:
CircuitError: If parameters is a dict and contains parameters not present in the
circuit.
ValueError: If parameters is a list/array and the length mismatches the number of free
parameters in the circuit.
Returns:
A copy of the circuit with bound parameters if ``inplace`` is False, otherwise None.
Examples:
Create a parameterized circuit and assign the parameters in-place.
.. plot::
:include-source:
from qiskit.circuit import QuantumCircuit, Parameter
circuit = QuantumCircuit(2)
params = [Parameter('A'), Parameter('B'), Parameter('C')]
circuit.ry(params[0], 0)
circuit.crx(params[1], 0, 1)
circuit.draw('mpl')
circuit.assign_parameters({params[0]: params[2]}, inplace=True)
circuit.draw('mpl')
Bind the values out-of-place by list and get a copy of the original circuit.
.. plot::
:include-source:
from qiskit.circuit import QuantumCircuit, ParameterVector
circuit = QuantumCircuit(2)
params = ParameterVector('P', 2)
circuit.ry(params[0], 0)
circuit.crx(params[1], 0, 1)
bound_circuit = circuit.assign_parameters([1, 2])
bound_circuit.draw('mpl')
circuit.draw('mpl')
"""
if inplace:
target = self
else:
target = self.copy()
target._increment_instances()
target._name_update()
# Normalise the inputs into simple abstract interfaces, so we've dispatched the "iteration"
# logic in one place at the start of the function. This lets us do things like calculate
# and cache expensive properties for (e.g.) the sequence format only if they're used; for
# many large, close-to-hardware circuits, we won't need the extra handling for
# `global_phase` or recursive definition binding.
#
# During normalisation, be sure to reference 'parameters' and related things from 'self' not
# 'target' so we can take advantage of any caching we might be doing.
if isinstance(parameters, dict):
raw_mapping = parameters if flat_input else self._unroll_param_dict(parameters)
our_parameters = self._unsorted_parameters()
if strict and (extras := raw_mapping.keys() - our_parameters):
raise CircuitError(
f"Cannot bind parameters ({', '.join(str(x) for x in extras)}) not present in"
" the circuit."
)
parameter_binds = _ParameterBindsDict(raw_mapping, our_parameters)
else:
our_parameters = self.parameters
if len(parameters) != len(our_parameters):
raise ValueError(
"Mismatching number of values and parameters. For partial binding "
"please pass a dictionary of {parameter: value} pairs."
)
parameter_binds = _ParameterBindsSequence(our_parameters, parameters)
# Clear out the parameter table for the relevant entries, since we'll be binding those.
# Any new references to parameters are reinserted as part of the bind.
target._parameters = None
# This is deliberately eager, because we want the side effect of clearing the table.
all_references = [
(parameter, value, target._parameter_table.pop(parameter, ()))
for parameter, value in parameter_binds.items()
]
seen_operations = {}
# The meat of the actual binding for regular operations.
for to_bind, bound_value, references in all_references:
update_parameters = (
tuple(bound_value.parameters)
if isinstance(bound_value, ParameterExpression)
else ()
)
for operation, index in references:
seen_operations[id(operation)] = operation
assignee = operation.params[index]
if isinstance(assignee, ParameterExpression):
new_parameter = assignee.assign(to_bind, bound_value)
for parameter in update_parameters:
if parameter not in target._parameter_table:
target._parameter_table[parameter] = ParameterReferences(())
target._parameter_table[parameter].add((operation, index))
if not new_parameter.parameters:
if new_parameter.is_real():
new_parameter = (
int(new_parameter)
if new_parameter._symbol_expr.is_integer
else float(new_parameter)
)
else:
new_parameter = complex(new_parameter)
new_parameter = operation.validate_parameter(new_parameter)
elif isinstance(assignee, QuantumCircuit):
new_parameter = assignee.assign_parameters(
{to_bind: bound_value}, inplace=False, flat_input=True
)
else:
raise RuntimeError( # pragma: no cover
f"Saw an unknown type during symbolic binding: {assignee}."
" This may indicate an internal logic error in symbol tracking."
)
operation.params[index] = new_parameter
# After we've been through everything at the top level, make a single visit to each
# operation we've seen, rebinding its definition if necessary.
for operation in seen_operations.values():
if (
definition := getattr(operation, "_definition", None)
) is not None and definition.num_parameters:
definition.assign_parameters(
parameter_binds.mapping, inplace=True, flat_input=True, strict=False
)
if isinstance(target.global_phase, ParameterExpression):
new_phase = target.global_phase
for parameter in new_phase.parameters & parameter_binds.mapping.keys():
new_phase = new_phase.assign(parameter, parameter_binds.mapping[parameter])
target.global_phase = new_phase
# Finally, assign the parameters inside any of the calibrations. We don't track these in
# the `ParameterTable`, so we manually reconstruct things.
def map_calibration(qubits, parameters, schedule):
modified = False
new_parameters = list(parameters)
for i, parameter in enumerate(new_parameters):
if not isinstance(parameter, ParameterExpression):
continue
if not (contained := parameter.parameters & parameter_binds.mapping.keys()):
continue
for to_bind in contained:
parameter = parameter.assign(to_bind, parameter_binds.mapping[to_bind])
if not parameter.parameters:
parameter = (
int(parameter) if parameter._symbol_expr.is_integer else float(parameter)
)
new_parameters[i] = parameter
modified = True
if modified:
schedule.assign_parameters(parameter_binds.mapping)
return (qubits, tuple(new_parameters)), schedule
target._calibrations = defaultdict(
dict,
(
(
gate,
dict(
map_calibration(qubits, parameters, schedule)
for (qubits, parameters), schedule in calibrations.items()
),
)
for gate, calibrations in target._calibrations.items()
),
)
return None if inplace else target
@staticmethod
def _unroll_param_dict(
parameter_binds: Mapping[Parameter, ParameterValueType]
) -> Mapping[Parameter, ParameterValueType]:
out = {}
for parameter, value in parameter_binds.items():
if isinstance(parameter, ParameterVector):
if len(parameter) != len(value):
raise CircuitError(
f"Parameter vector '{parameter.name}' has length {len(parameter)},"
f" but was assigned to {len(value)} values."
)
out.update(zip(parameter, value))
else:
out[parameter] = value
return out
def bind_parameters(
self, values: Union[Mapping[Parameter, float], Sequence[float]]
) -> "QuantumCircuit":
"""Assign numeric parameters to values yielding a new circuit.
If the values are given as list or array they are bound to the circuit in the order
of :attr:`parameters` (see the docstring for more details).
To assign new Parameter objects or bind the values in-place, without yielding a new
circuit, use the :meth:`assign_parameters` method.
Args:
values: ``{parameter: value, ...}`` or ``[value1, value2, ...]``
Raises:
CircuitError: If values is a dict and contains parameters not present in the circuit.
TypeError: If values contains a ParameterExpression.
Returns:
Copy of self with assignment substitution.
"""
if isinstance(values, dict):
if any(isinstance(value, ParameterExpression) for value in values.values()):
raise TypeError(
"Found ParameterExpression in values; use assign_parameters() instead."
)
return self.assign_parameters(values)
else:
if any(isinstance(value, ParameterExpression) for value in values):
raise TypeError(
"Found ParameterExpression in values; use assign_parameters() instead."
)
return self.assign_parameters(values)
def barrier(self, *qargs: QubitSpecifier, label=None) -> InstructionSet:
"""Apply :class:`~.library.Barrier`. If ``qargs`` is empty, applies to all qubits
in the circuit.
Args:
qargs (QubitSpecifier): Specification for one or more qubit arguments.
label (str): The string label of the barrier.
Returns:
qiskit.circuit.InstructionSet: handle to the added instructions.
"""
from .barrier import Barrier
qubits: list[QubitSpecifier] = []
if not qargs: # None
qubits.extend(self.qubits)
for qarg in qargs:
if isinstance(qarg, QuantumRegister):
qubits.extend([qarg[j] for j in range(qarg.size)])
elif isinstance(qarg, list):
qubits.extend(qarg)
elif isinstance(qarg, range):
qubits.extend(list(qarg))
elif isinstance(qarg, slice):
qubits.extend(self.qubits[qarg])
else:
qubits.append(qarg)
return self.append(Barrier(len(qubits), label=label), qubits, [])
def delay(
self,
duration: ParameterValueType,
qarg: QubitSpecifier | None = None,
unit: str = "dt",
) -> InstructionSet:
"""Apply :class:`~.circuit.Delay`. If qarg is ``None``, applies to all qubits.
When applying to multiple qubits, delays with the same duration will be created.
Args:
duration (int or float or ParameterExpression): duration of the delay.
qarg (Object): qubit argument to apply this delay.
unit (str): unit of the duration. Supported units: ``'s'``, ``'ms'``, ``'us'``,
``'ns'``, ``'ps'``, and ``'dt'``. Default is ``'dt'``, i.e. integer time unit
depending on the target backend.
Returns:
qiskit.circuit.InstructionSet: handle to the added instructions.
Raises:
CircuitError: if arguments have bad format.
"""
qubits: list[QubitSpecifier] = []
if qarg is None: # -> apply delays to all qubits
for q in self.qubits:
qubits.append(q)
else:
if isinstance(qarg, QuantumRegister):
qubits.extend([qarg[j] for j in range(qarg.size)])
elif isinstance(qarg, list):
qubits.extend(qarg)
elif isinstance(qarg, (range, tuple)):
qubits.extend(list(qarg))
elif isinstance(qarg, slice):
qubits.extend(self.qubits[qarg])
else:
qubits.append(qarg)
instructions = InstructionSet(resource_requester=self._resolve_classical_resource)
for q in qubits:
inst: tuple[
Instruction, Sequence[QubitSpecifier] | None, Sequence[ClbitSpecifier] | None
] = (Delay(duration, unit), [q], [])
self.append(*inst)
instructions.add(*inst)
return instructions
def h(self, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.HGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.h import HGate
return self.append(HGate(), [qubit], [])
def ch(
self,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CHGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.h import CHGate
return self.append(
CHGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], []
)
def i(self, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.IGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.i import IGate
return self.append(IGate(), [qubit], [])
def id(self, qubit: QubitSpecifier) -> InstructionSet: # pylint: disable=invalid-name
"""Apply :class:`~qiskit.circuit.library.IGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
See Also:
QuantumCircuit.i: the same function.
"""
return self.i(qubit)
def ms(self, theta: ParameterValueType, qubits: Sequence[QubitSpecifier]) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.MSGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The angle of the rotation.
qubits: The qubits to apply the gate to.
Returns:
A handle to the instructions created.
"""
# pylint: disable=cyclic-import
from .library.generalized_gates.gms import MSGate
return self.append(MSGate(len(qubits), theta), qubits)
def p(self, theta: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.PhaseGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: THe angle of the rotation.
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.p import PhaseGate
return self.append(PhaseGate(theta), [qubit], [])
def cp(
self,
theta: ParameterValueType,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CPhaseGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The angle of the rotation.
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.p import CPhaseGate
return self.append(
CPhaseGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], []
)
def mcp(
self,
lam: ParameterValueType,
control_qubits: Sequence[QubitSpecifier],
target_qubit: QubitSpecifier,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.MCPhaseGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
lam: The angle of the rotation.
control_qubits: The qubits used as the controls.
target_qubit: The qubit(s) targeted by the gate.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.p import MCPhaseGate
num_ctrl_qubits = len(control_qubits)
return self.append(
MCPhaseGate(lam, num_ctrl_qubits), control_qubits[:] + [target_qubit], []
)
def r(
self, theta: ParameterValueType, phi: ParameterValueType, qubit: QubitSpecifier
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The angle of the rotation.
phi: The angle of the axis of rotation in the x-y plane.
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.r import RGate
return self.append(RGate(theta, phi), [qubit], [])
def rv(
self,
vx: ParameterValueType,
vy: ParameterValueType,
vz: ParameterValueType,
qubit: QubitSpecifier,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RVGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Rotation around an arbitrary rotation axis :math:`v`, where :math:`|v|` is the angle of
rotation in radians.
Args:
vx: x-component of the rotation axis.
vy: y-component of the rotation axis.
vz: z-component of the rotation axis.
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.generalized_gates.rv import RVGate
return self.append(RVGate(vx, vy, vz), [qubit], [])
def rccx(
self,
control_qubit1: QubitSpecifier,
control_qubit2: QubitSpecifier,
target_qubit: QubitSpecifier,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RCCXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit1: The qubit(s) used as the first control.
control_qubit2: The qubit(s) used as the second control.
target_qubit: The qubit(s) targeted by the gate.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.x import RCCXGate
return self.append(RCCXGate(), [control_qubit1, control_qubit2, target_qubit], [])
def rcccx(
self,
control_qubit1: QubitSpecifier,
control_qubit2: QubitSpecifier,
control_qubit3: QubitSpecifier,
target_qubit: QubitSpecifier,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RC3XGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit1: The qubit(s) used as the first control.
control_qubit2: The qubit(s) used as the second control.
control_qubit3: The qubit(s) used as the third control.
target_qubit: The qubit(s) targeted by the gate.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.x import RC3XGate
return self.append(
RC3XGate(), [control_qubit1, control_qubit2, control_qubit3, target_qubit], []
)
def rx(
self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The rotation angle of the gate.
qubit: The qubit(s) to apply the gate to.
label: The string label of the gate in the circuit.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.rx import RXGate
return self.append(RXGate(theta, label=label), [qubit], [])
def crx(
self,
theta: ParameterValueType,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CRXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The angle of the rotation.
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.rx import CRXGate
return self.append(
CRXGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], []
)
def rxx(
self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RXXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The angle of the rotation.
qubit1: The qubit(s) to apply the gate to.
qubit2: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.rxx import RXXGate
return self.append(RXXGate(theta), [qubit1, qubit2], [])
def ry(
self, theta: ParameterValueType, qubit: QubitSpecifier, label: str | None = None
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RYGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The rotation angle of the gate.
qubit: The qubit(s) to apply the gate to.
label: The string label of the gate in the circuit.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.ry import RYGate
return self.append(RYGate(theta, label=label), [qubit], [])
def cry(
self,
theta: ParameterValueType,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CRYGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The angle of the rotation.
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.ry import CRYGate
return self.append(
CRYGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], []
)
def ryy(
self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RYYGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The rotation angle of the gate.
qubit1: The qubit(s) to apply the gate to.
qubit2: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.ryy import RYYGate
return self.append(RYYGate(theta), [qubit1, qubit2], [])
def rz(self, phi: ParameterValueType, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RZGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
phi: The rotation angle of the gate.
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.rz import RZGate
return self.append(RZGate(phi), [qubit], [])
def crz(
self,
theta: ParameterValueType,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CRZGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The angle of the rotation.
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.rz import CRZGate
return self.append(
CRZGate(theta, label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], []
)
def rzx(
self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RZXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The rotation angle of the gate.
qubit1: The qubit(s) to apply the gate to.
qubit2: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.rzx import RZXGate
return self.append(RZXGate(theta), [qubit1, qubit2], [])
def rzz(
self, theta: ParameterValueType, qubit1: QubitSpecifier, qubit2: QubitSpecifier
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.RZZGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The rotation angle of the gate.
qubit1: The qubit(s) to apply the gate to.
qubit2: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.rzz import RZZGate
return self.append(RZZGate(theta), [qubit1, qubit2], [])
def ecr(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.ECRGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit1, qubit2: The qubits to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.ecr import ECRGate
return self.append(ECRGate(), [qubit1, qubit2], [])
def s(self, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.SGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.s import SGate
return self.append(SGate(), [qubit], [])
def sdg(self, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.SdgGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.s import SdgGate
return self.append(SdgGate(), [qubit], [])
def cs(
self,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CSGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.s import CSGate
return self.append(
CSGate(label=label, ctrl_state=ctrl_state),
[control_qubit, target_qubit],
[],
)
def csdg(
self,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CSdgGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.s import CSdgGate
return self.append(
CSdgGate(label=label, ctrl_state=ctrl_state),
[control_qubit, target_qubit],
[],
)
def swap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.SwapGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit1, qubit2: The qubits to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.swap import SwapGate
return self.append(SwapGate(), [qubit1, qubit2], [])
def iswap(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.iSwapGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit1, qubit2: The qubits to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.iswap import iSwapGate
return self.append(iSwapGate(), [qubit1, qubit2], [])
def cswap(
self,
control_qubit: QubitSpecifier,
target_qubit1: QubitSpecifier,
target_qubit2: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CSwapGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the control.
target_qubit1: The qubit(s) targeted by the gate.
target_qubit2: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. ``'1'``). Defaults to controlling
on the ``'1'`` state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.swap import CSwapGate
return self.append(
CSwapGate(label=label, ctrl_state=ctrl_state),
[control_qubit, target_qubit1, target_qubit2],
[],
)
def fredkin(
self,
control_qubit: QubitSpecifier,
target_qubit1: QubitSpecifier,
target_qubit2: QubitSpecifier,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CSwapGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the control.
target_qubit1: The qubit(s) targeted by the gate.
target_qubit2: The qubit(s) targeted by the gate.
Returns:
A handle to the instructions created.
See Also:
QuantumCircuit.cswap: the same function with a different name.
"""
return self.cswap(control_qubit, target_qubit1, target_qubit2)
def sx(self, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.SXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.sx import SXGate
return self.append(SXGate(), [qubit], [])
def sxdg(self, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.SXdgGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.sx import SXdgGate
return self.append(SXdgGate(), [qubit], [])
def csx(
self,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.CSXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.sx import CSXGate
return self.append(
CSXGate(label=label, ctrl_state=ctrl_state),
[control_qubit, target_qubit],
[],
)
def t(self, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.TGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.t import TGate
return self.append(TGate(), [qubit], [])
def tdg(self, qubit: QubitSpecifier) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.TdgGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.t import TdgGate
return self.append(TdgGate(), [qubit], [])
def u(
self,
theta: ParameterValueType,
phi: ParameterValueType,
lam: ParameterValueType,
qubit: QubitSpecifier,
) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.UGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The :math:`\theta` rotation angle of the gate.
phi: The :math:`\phi` rotation angle of the gate.
lam: The :math:`\lambda` rotation angle of the gate.
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.u import UGate
return self.append(UGate(theta, phi, lam), [qubit], [])
def cu(
self,
theta: ParameterValueType,
phi: ParameterValueType,
lam: ParameterValueType,
gamma: ParameterValueType,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.CUGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
theta: The :math:`\theta` rotation angle of the gate.
phi: The :math:`\phi` rotation angle of the gate.
lam: The :math:`\lambda` rotation angle of the gate.
gamma: The global phase applied of the U gate, if applied.
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.u import CUGate
return self.append(
CUGate(theta, phi, lam, gamma, label=label, ctrl_state=ctrl_state),
[control_qubit, target_qubit],
[],
)
def x(self, qubit: QubitSpecifier, label: str | None = None) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.XGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
label: The string label of the gate in the circuit.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.x import XGate
return self.append(XGate(label=label), [qubit], [])
def cx(
self,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.CXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.x import CXGate
return self.append(
CXGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], []
)
def cnot(
self,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.CXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
See Also:
QuantumCircuit.cx: the same function with a different name.
"""
return self.cx(control_qubit, target_qubit, label, ctrl_state)
def dcx(self, qubit1: QubitSpecifier, qubit2: QubitSpecifier) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.DCXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit1: The qubit(s) to apply the gate to.
qubit2: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.dcx import DCXGate
return self.append(DCXGate(), [qubit1, qubit2], [])
def ccx(
self,
control_qubit1: QubitSpecifier,
control_qubit2: QubitSpecifier,
target_qubit: QubitSpecifier,
ctrl_state: str | int | None = None,
) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.CCXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit1: The qubit(s) used as the first control.
control_qubit2: The qubit(s) used as the second control.
target_qubit: The qubit(s) targeted by the gate.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.x import CCXGate
return self.append(
CCXGate(ctrl_state=ctrl_state),
[control_qubit1, control_qubit2, target_qubit],
[],
)
def toffoli(
self,
control_qubit1: QubitSpecifier,
control_qubit2: QubitSpecifier,
target_qubit: QubitSpecifier,
) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.CCXGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit1: The qubit(s) used as the first control.
control_qubit2: The qubit(s) used as the second control.
target_qubit: The qubit(s) targeted by the gate.
Returns:
A handle to the instructions created.
See Also:
QuantumCircuit.ccx: the same gate with a different name.
"""
return self.ccx(control_qubit1, control_qubit2, target_qubit)
def mcx(
self,
control_qubits: Sequence[QubitSpecifier],
target_qubit: QubitSpecifier,
ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None,
mode: str = "noancilla",
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.MCXGate`.
The multi-cX gate can be implemented using different techniques, which use different numbers
of ancilla qubits and have varying circuit depth. These modes are:
- ``'noancilla'``: Requires 0 ancilla qubits.
- ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0.
- ``'v-chain'``: Requires 2 less ancillas than the number of control qubits.
- ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer).
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubits: The qubits used as the controls.
target_qubit: The qubit(s) targeted by the gate.
ancilla_qubits: The qubits used as the ancillae, if the mode requires them.
mode: The choice of mode, explained further above.
Returns:
A handle to the instructions created.
Raises:
ValueError: if the given mode is not known, or if too few ancilla qubits are passed.
AttributeError: if no ancilla qubits are passed, but some are needed.
"""
from .library.standard_gates.x import MCXGrayCode, MCXRecursive, MCXVChain
num_ctrl_qubits = len(control_qubits)
available_implementations = {
"noancilla": MCXGrayCode(num_ctrl_qubits),
"recursion": MCXRecursive(num_ctrl_qubits),
"v-chain": MCXVChain(num_ctrl_qubits, False),
"v-chain-dirty": MCXVChain(num_ctrl_qubits, dirty_ancillas=True),
# outdated, previous names
"advanced": MCXRecursive(num_ctrl_qubits),
"basic": MCXVChain(num_ctrl_qubits, dirty_ancillas=False),
"basic-dirty-ancilla": MCXVChain(num_ctrl_qubits, dirty_ancillas=True),
}
# check ancilla input
if ancilla_qubits:
_ = self.qbit_argument_conversion(ancilla_qubits)
try:
gate = available_implementations[mode]
except KeyError as ex:
all_modes = list(available_implementations.keys())
raise ValueError(
f"Unsupported mode ({mode}) selected, choose one of {all_modes}"
) from ex
if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0:
required = gate.num_ancilla_qubits
if ancilla_qubits is None:
raise AttributeError(f"No ancillas provided, but {required} are needed!")
# convert ancilla qubits to a list if they were passed as int or qubit
if not hasattr(ancilla_qubits, "__len__"):
ancilla_qubits = [ancilla_qubits]
if len(ancilla_qubits) < required:
actually = len(ancilla_qubits)
raise ValueError(f"At least {required} ancillas required, but {actually} given.")
# size down if too many ancillas were provided
ancilla_qubits = ancilla_qubits[:required]
else:
ancilla_qubits = []
return self.append(gate, control_qubits[:] + [target_qubit] + ancilla_qubits[:], [])
def mct(
self,
control_qubits: Sequence[QubitSpecifier],
target_qubit: QubitSpecifier,
ancilla_qubits: QubitSpecifier | Sequence[QubitSpecifier] | None = None,
mode: str = "noancilla",
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.MCXGate`.
The multi-cX gate can be implemented using different techniques, which use different numbers
of ancilla qubits and have varying circuit depth. These modes are:
- ``'noancilla'``: Requires 0 ancilla qubits.
- ``'recursion'``: Requires 1 ancilla qubit if more than 4 controls are used, otherwise 0.
- ``'v-chain'``: Requires 2 less ancillas than the number of control qubits.
- ``'v-chain-dirty'``: Same as for the clean ancillas (but the circuit will be longer).
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubits: The qubits used as the controls.
target_qubit: The qubit(s) targeted by the gate.
ancilla_qubits: The qubits used as the ancillae, if the mode requires them.
mode: The choice of mode, explained further above.
Returns:
A handle to the instructions created.
Raises:
ValueError: if the given mode is not known, or if too few ancilla qubits are passed.
AttributeError: if no ancilla qubits are passed, but some are needed.
See Also:
QuantumCircuit.mcx: the same gate with a different name.
"""
return self.mcx(control_qubits, target_qubit, ancilla_qubits, mode)
def y(self, qubit: QubitSpecifier) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.YGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.y import YGate
return self.append(YGate(), [qubit], [])
def cy(
self,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.CYGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the controls.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.y import CYGate
return self.append(
CYGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], []
)
def z(self, qubit: QubitSpecifier) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.ZGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
qubit: The qubit(s) to apply the gate to.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.z import ZGate
return self.append(ZGate(), [qubit], [])
def cz(
self,
control_qubit: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.CZGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit: The qubit(s) used as the controls.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '1'). Defaults to controlling
on the '1' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.z import CZGate
return self.append(
CZGate(label=label, ctrl_state=ctrl_state), [control_qubit, target_qubit], []
)
def ccz(
self,
control_qubit1: QubitSpecifier,
control_qubit2: QubitSpecifier,
target_qubit: QubitSpecifier,
label: str | None = None,
ctrl_state: str | int | None = None,
) -> InstructionSet:
r"""Apply :class:`~qiskit.circuit.library.CCZGate`.
For the full matrix form of this gate, see the underlying gate documentation.
Args:
control_qubit1: The qubit(s) used as the first control.
control_qubit2: The qubit(s) used as the second control.
target_qubit: The qubit(s) targeted by the gate.
label: The string label of the gate in the circuit.
ctrl_state:
The control state in decimal, or as a bitstring (e.g. '10'). Defaults to controlling
on the '11' state.
Returns:
A handle to the instructions created.
"""
from .library.standard_gates.z import CCZGate
return self.append(
CCZGate(label=label, ctrl_state=ctrl_state),
[control_qubit1, control_qubit2, target_qubit],
[],
)
def pauli(
self,
pauli_string: str,
qubits: Sequence[QubitSpecifier],
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.library.PauliGate`.
Args:
pauli_string: A string representing the Pauli operator to apply, e.g. 'XX'.
qubits: The qubits to apply this gate to.
Returns:
A handle to the instructions created.
"""
from qiskit.circuit.library.generalized_gates.pauli import PauliGate
return self.append(PauliGate(pauli_string), qubits, [])
def _push_scope(
self,
qubits: Iterable[Qubit] = (),
clbits: Iterable[Clbit] = (),
registers: Iterable[Register] = (),
allow_jumps: bool = True,
forbidden_message: Optional[str] = None,
):
"""Add a scope for collecting instructions into this circuit.
This should only be done by the control-flow context managers, which will handle cleaning up
after themselves at the end as well.
Args:
qubits: Any qubits that this scope should automatically use.
clbits: Any clbits that this scope should automatically use.
allow_jumps: Whether this scope allows jumps to be used within it.
forbidden_message: If given, all attempts to add instructions to this scope will raise a
:exc:`.CircuitError` with this message.
"""
# pylint: disable=cyclic-import
from qiskit.circuit.controlflow.builder import ControlFlowBuilderBlock
# Chain resource requests so things like registers added to inner scopes via conditions are
# requested in the outer scope as well.
if self._control_flow_scopes:
resource_requester = self._control_flow_scopes[-1].request_classical_resource
else:
resource_requester = self._resolve_classical_resource
self._control_flow_scopes.append(
ControlFlowBuilderBlock(
qubits,
clbits,
resource_requester=resource_requester,
registers=registers,
allow_jumps=allow_jumps,
forbidden_message=forbidden_message,
)
)
def _pop_scope(self) -> "qiskit.circuit.controlflow.builder.ControlFlowBuilderBlock":
"""Finish a scope used in the control-flow builder interface, and return it to the caller.
This should only be done by the control-flow context managers, since they naturally
synchronise the creation and deletion of stack elements."""
return self._control_flow_scopes.pop()
def _peek_previous_instruction_in_scope(self) -> CircuitInstruction:
"""Return the instruction 3-tuple of the most recent instruction in the current scope, even
if that scope is currently under construction.
This function is only intended for use by the control-flow ``if``-statement builders, which
may need to modify a previous instruction."""
if self._control_flow_scopes:
return self._control_flow_scopes[-1].peek()
if not self._data:
raise CircuitError("This circuit contains no instructions.")
return self._data[-1]
def _pop_previous_instruction_in_scope(self) -> CircuitInstruction:
"""Return the instruction 3-tuple of the most recent instruction in the current scope, even
if that scope is currently under construction, and remove it from that scope.
This function is only intended for use by the control-flow ``if``-statement builders, which
may need to replace a previous instruction with another.
"""
if self._control_flow_scopes:
return self._control_flow_scopes[-1].pop()
if not self._data:
raise CircuitError("This circuit contains no instructions.")
instruction = self._data.pop()
if isinstance(instruction.operation, Instruction):
self._update_parameter_table_on_instruction_removal(instruction)
return instruction
def _update_parameter_table_on_instruction_removal(self, instruction: CircuitInstruction):
"""Update the :obj:`.ParameterTable` of this circuit given that an instance of the given
``instruction`` has just been removed from the circuit.
.. note::
This does not account for the possibility for the same instruction instance being added
more than once to the circuit. At the time of writing (2021-11-17, main commit 271a82f)
there is a defensive ``deepcopy`` of parameterised instructions inside
:meth:`.QuantumCircuit.append`, so this should be safe. Trying to account for it would
involve adding a potentially quadratic-scaling loop to check each entry in ``data``.
"""
atomic_parameters: list[tuple[Parameter, int]] = []
for index, parameter in enumerate(instruction.operation.params):
if isinstance(parameter, (ParameterExpression, QuantumCircuit)):
atomic_parameters.extend((p, index) for p in parameter.parameters)
for atomic_parameter, index in atomic_parameters:
new_entries = self._parameter_table[atomic_parameter].copy()
new_entries.discard((instruction.operation, index))
if not new_entries:
del self._parameter_table[atomic_parameter]
# Invalidate cache.
self._parameters = None
else:
self._parameter_table[atomic_parameter] = new_entries
@typing.overload
def while_loop(
self,
condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr,
body: None,
qubits: None,
clbits: None,
*,
label: str | None,
) -> "qiskit.circuit.controlflow.while_loop.WhileLoopContext":
...
@typing.overload
def while_loop(
self,
condition: tuple[ClassicalRegister | Clbit, int] | expr.Expr,
body: "QuantumCircuit",
qubits: Sequence[QubitSpecifier],
clbits: Sequence[ClbitSpecifier],
*,
label: str | None,
) -> InstructionSet:
...
def while_loop(self, condition, body=None, qubits=None, clbits=None, *, label=None):
"""Create a ``while`` loop on this circuit.
There are two forms for calling this function. If called with all its arguments (with the
possible exception of ``label``), it will create a
:obj:`~qiskit.circuit.controlflow.WhileLoopOp` with the given ``body``. If ``body`` (and
``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which
will automatically build a :obj:`~qiskit.circuit.controlflow.WhileLoopOp` when the scope
finishes. In this form, you do not need to keep track of the qubits or clbits you are
using, because the scope will handle it for you.
Example usage::
from qiskit.circuit import QuantumCircuit, Clbit, Qubit
bits = [Qubit(), Qubit(), Clbit()]
qc = QuantumCircuit(bits)
with qc.while_loop((bits[2], 0)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
Args:
condition (Tuple[Union[ClassicalRegister, Clbit], int]): An equality condition to be
checked prior to executing ``body``. The left-hand side of the condition must be a
:obj:`~ClassicalRegister` or a :obj:`~Clbit`, and the right-hand side must be an
integer or boolean.
body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to
use the context-manager mode.
qubits (Optional[Sequence[Qubit]]): The circuit qubits over which the loop body should
be run. Omit this to use the context-manager mode.
clbits (Optional[Sequence[Clbit]]): The circuit clbits over which the loop body should
be run. Omit this to use the context-manager mode.
label (Optional[str]): The string label of the instruction in the circuit.
Returns:
InstructionSet or WhileLoopContext: If used in context-manager mode, then this should be
used as a ``with`` resource, which will infer the block content and operands on exit.
If the full form is used, then this returns a handle to the instructions created.
Raises:
CircuitError: if an incorrect calling convention is used.
"""
# pylint: disable=cyclic-import
from qiskit.circuit.controlflow.while_loop import WhileLoopOp, WhileLoopContext
if isinstance(condition, expr.Expr):
condition = self._validate_expr(condition)
else:
condition = (self._resolve_classical_resource(condition[0]), condition[1])
if body is None:
if qubits is not None or clbits is not None:
raise CircuitError(
"When using 'while_loop' as a context manager,"
" you cannot pass qubits or clbits."
)
return WhileLoopContext(self, condition, label=label)
elif qubits is None or clbits is None:
raise CircuitError(
"When using 'while_loop' with a body, you must pass qubits and clbits."
)
return self.append(WhileLoopOp(condition, body, label), qubits, clbits)
@typing.overload
def for_loop(
self,
indexset: Iterable[int],
loop_parameter: Parameter | None,
body: None,
qubits: None,
clbits: None,
*,
label: str | None,
) -> "qiskit.circuit.controlflow.for_loop.ForLoopContext":
...
@typing.overload
def for_loop(
self,
indexset: Iterable[int],
loop_parameter: Union[Parameter, None],
body: "QuantumCircuit",
qubits: Sequence[QubitSpecifier],
clbits: Sequence[ClbitSpecifier],
*,
label: str | None,
) -> InstructionSet:
...
def for_loop(
self, indexset, loop_parameter=None, body=None, qubits=None, clbits=None, *, label=None
):
"""Create a ``for`` loop on this circuit.
There are two forms for calling this function. If called with all its arguments (with the
possible exception of ``label``), it will create a
:class:`~qiskit.circuit.ForLoopOp` with the given ``body``. If ``body`` (and
``qubits`` and ``clbits``) are *not* passed, then this acts as a context manager, which,
when entered, provides a loop variable (unless one is given, in which case it will be
reused) and will automatically build a :class:`~qiskit.circuit.ForLoopOp` when the
scope finishes. In this form, you do not need to keep track of the qubits or clbits you are
using, because the scope will handle it for you.
For example::
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)) as i:
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
Args:
indexset (Iterable[int]): A collection of integers to loop over. Always necessary.
loop_parameter (Optional[Parameter]): The parameter used within ``body`` to which
the values from ``indexset`` will be assigned. In the context-manager form, if this
argument is not supplied, then a loop parameter will be allocated for you and
returned as the value of the ``with`` statement. This will only be bound into the
circuit if it is used within the body.
If this argument is ``None`` in the manual form of this method, ``body`` will be
repeated once for each of the items in ``indexset`` but their values will be
ignored.
body (Optional[QuantumCircuit]): The loop body to be repeatedly executed. Omit this to
use the context-manager mode.
qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the loop body
should be run. Omit this to use the context-manager mode.
clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the loop body
should be run. Omit this to use the context-manager mode.
label (Optional[str]): The string label of the instruction in the circuit.
Returns:
InstructionSet or ForLoopContext: depending on the call signature, either a context
manager for creating the for loop (it will automatically be added to the circuit at the
end of the block), or an :obj:`~InstructionSet` handle to the appended loop operation.
Raises:
CircuitError: if an incorrect calling convention is used.
"""
# pylint: disable=cyclic-import
from qiskit.circuit.controlflow.for_loop import ForLoopOp, ForLoopContext
if body is None:
if qubits is not None or clbits is not None:
raise CircuitError(
"When using 'for_loop' as a context manager, you cannot pass qubits or clbits."
)
return ForLoopContext(self, indexset, loop_parameter, label=label)
elif qubits is None or clbits is None:
raise CircuitError(
"When using 'for_loop' with a body, you must pass qubits and clbits."
)
return self.append(ForLoopOp(indexset, loop_parameter, body, label), qubits, clbits)
@typing.overload
def if_test(
self,
condition: tuple[ClassicalRegister | Clbit, int],
true_body: None,
qubits: None,
clbits: None,
*,
label: str | None,
) -> "qiskit.circuit.controlflow.if_else.IfContext":
...
@typing.overload
def if_test(
self,
condition: tuple[ClassicalRegister | Clbit, int],
true_body: "QuantumCircuit",
qubits: Sequence[QubitSpecifier],
clbits: Sequence[ClbitSpecifier],
*,
label: str | None = None,
) -> InstructionSet:
...
def if_test(
self,
condition,
true_body=None,
qubits=None,
clbits=None,
*,
label=None,
):
"""Create an ``if`` statement on this circuit.
There are two forms for calling this function. If called with all its arguments (with the
possible exception of ``label``), it will create a
:obj:`~qiskit.circuit.IfElseOp` with the given ``true_body``, and there will be
no branch for the ``false`` condition (see also the :meth:`.if_else` method). However, if
``true_body`` (and ``qubits`` and ``clbits``) are *not* passed, then this acts as a context
manager, which can be used to build ``if`` statements. The return value of the ``with``
statement is a chainable context manager, which can be used to create subsequent ``else``
blocks. In this form, you do not need to keep track of the qubits or clbits you are using,
because the scope will handle it for you.
For example::
from qiskit.circuit import QuantumCircuit, Qubit, Clbit
bits = [Qubit(), Qubit(), Qubit(), Clbit(), Clbit()]
qc = QuantumCircuit(bits)
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 1)
with qc.if_test((bits[3], 0)) as else_:
qc.x(2)
with else_:
qc.h(2)
qc.z(2)
Args:
condition (Tuple[Union[ClassicalRegister, Clbit], int]): A condition to be evaluated at
circuit runtime which, if true, will trigger the evaluation of ``true_body``. Can be
specified as either a tuple of a ``ClassicalRegister`` to be tested for equality
with a given ``int``, or as a tuple of a ``Clbit`` to be compared to either a
``bool`` or an ``int``.
true_body (Optional[QuantumCircuit]): The circuit body to be run if ``condition`` is
true.
qubits (Optional[Sequence[QubitSpecifier]]): The circuit qubits over which the if/else
should be run.
clbits (Optional[Sequence[ClbitSpecifier]]): The circuit clbits over which the if/else
should be run.
label (Optional[str]): The string label of the instruction in the circuit.
Returns:
InstructionSet or IfContext: depending on the call signature, either a context
manager for creating the ``if`` block (it will automatically be added to the circuit at
the end of the block), or an :obj:`~InstructionSet` handle to the appended conditional
operation.
Raises:
CircuitError: If the provided condition references Clbits outside the
enclosing circuit.
CircuitError: if an incorrect calling convention is used.
Returns:
A handle to the instruction created.
"""
# pylint: disable=cyclic-import
from qiskit.circuit.controlflow.if_else import IfElseOp, IfContext
if isinstance(condition, expr.Expr):
condition = self._validate_expr(condition)
else:
condition = (self._resolve_classical_resource(condition[0]), condition[1])
if true_body is None:
if qubits is not None or clbits is not None:
raise CircuitError(
"When using 'if_test' as a context manager, you cannot pass qubits or clbits."
)
# We can only allow jumps if we're in a loop block, but the default path (no scopes)
# also allows adding jumps to support the more verbose internal mode.
in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps)
return IfContext(self, condition, in_loop=in_loop, label=label)
elif qubits is None or clbits is None:
raise CircuitError("When using 'if_test' with a body, you must pass qubits and clbits.")
return self.append(IfElseOp(condition, true_body, None, label), qubits, clbits)
def if_else(
self,
condition: tuple[ClassicalRegister, int] | tuple[Clbit, int] | tuple[Clbit, bool],
true_body: "QuantumCircuit",
false_body: "QuantumCircuit",
qubits: Sequence[QubitSpecifier],
clbits: Sequence[ClbitSpecifier],
label: str | None = None,
) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.IfElseOp`.
.. note::
This method does not have an associated context-manager form, because it is already
handled by the :meth:`.if_test` method. You can use the ``else`` part of that with
something such as::
from qiskit.circuit import QuantumCircuit, Qubit, Clbit
bits = [Qubit(), Qubit(), Clbit()]
qc = QuantumCircuit(bits)
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
with qc.if_test((bits[2], 0)) as else_:
qc.h(0)
with else_:
qc.x(0)
Args:
condition: A condition to be evaluated at circuit runtime which,
if true, will trigger the evaluation of ``true_body``. Can be
specified as either a tuple of a ``ClassicalRegister`` to be
tested for equality with a given ``int``, or as a tuple of a
``Clbit`` to be compared to either a ``bool`` or an ``int``.
true_body: The circuit body to be run if ``condition`` is true.
false_body: The circuit to be run if ``condition`` is false.
qubits: The circuit qubits over which the if/else should be run.
clbits: The circuit clbits over which the if/else should be run.
label: The string label of the instruction in the circuit.
Raises:
CircuitError: If the provided condition references Clbits outside the
enclosing circuit.
Returns:
A handle to the instruction created.
"""
# pylint: disable=cyclic-import
from qiskit.circuit.controlflow.if_else import IfElseOp
if isinstance(condition, expr.Expr):
condition = self._validate_expr(condition)
else:
condition = (self._resolve_classical_resource(condition[0]), condition[1])
return self.append(IfElseOp(condition, true_body, false_body, label), qubits, clbits)
@typing.overload
def switch(
self,
target: Union[ClbitSpecifier, ClassicalRegister],
cases: None,
qubits: None,
clbits: None,
*,
label: Optional[str],
) -> "qiskit.circuit.controlflow.switch_case.SwitchContext":
...
@typing.overload
def switch(
self,
target: Union[ClbitSpecifier, ClassicalRegister],
cases: Iterable[Tuple[typing.Any, QuantumCircuit]],
qubits: Sequence[QubitSpecifier],
clbits: Sequence[ClbitSpecifier],
*,
label: Optional[str],
) -> InstructionSet:
...
def switch(self, target, cases=None, qubits=None, clbits=None, *, label=None):
"""Create a ``switch``/``case`` structure on this circuit.
There are two forms for calling this function. If called with all its arguments (with the
possible exception of ``label``), it will create a :class:`.SwitchCaseOp` with the given
case structure. If ``cases`` (and ``qubits`` and ``clbits``) are *not* passed, then this
acts as a context manager, which will automatically build a :class:`.SwitchCaseOp` when the
scope finishes. In this form, you do not need to keep track of the qubits or clbits you are
using, because the scope will handle it for you.
Example usage::
from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister
qreg = QuantumRegister(3)
creg = ClassicalRegister(3)
qc = QuantumCircuit(qreg, creg)
qc.h([0, 1, 2])
qc.measure([0, 1, 2], [0, 1, 2])
with qc.switch(creg) as case:
with case(0):
qc.x(0)
with case(1, 2):
qc.z(1)
with case(case.DEFAULT):
qc.cx(0, 1)
Args:
target (Union[ClassicalRegister, Clbit]): The classical value to switch one. This must
be integer-like.
cases (Iterable[Tuple[typing.Any, QuantumCircuit]]): A sequence of case specifiers.
Each tuple defines one case body (the second item). The first item of the tuple can
be either a single integer value, the special value :data:`.CASE_DEFAULT`, or a
tuple of several integer values. Each of the integer values will be tried in turn;
control will then pass to the body corresponding to the first match.
:data:`.CASE_DEFAULT` matches all possible values. Omit in context-manager form.
qubits (Sequence[Qubit]): The circuit qubits over which all case bodies execute. Omit in
context-manager form.
clbits (Sequence[Clbit]): The circuit clbits over which all case bodies execute. Omit in
context-manager form.
label (Optional[str]): The string label of the instruction in the circuit.
Returns:
InstructionSet or SwitchCaseContext: If used in context-manager mode, then this should
be used as a ``with`` resource, which will return an object that can be repeatedly
entered to produce cases for the switch statement. If the full form is used, then this
returns a handle to the instructions created.
Raises:
CircuitError: if an incorrect calling convention is used.
"""
# pylint: disable=cyclic-import
from qiskit.circuit.controlflow.switch_case import SwitchCaseOp, SwitchContext
if isinstance(target, expr.Expr):
target = self._validate_expr(target)
else:
target = self._resolve_classical_resource(target)
if cases is None:
if qubits is not None or clbits is not None:
raise CircuitError(
"When using 'switch' as a context manager, you cannot pass qubits or clbits."
)
in_loop = bool(self._control_flow_scopes and self._control_flow_scopes[-1].allow_jumps)
return SwitchContext(self, target, in_loop=in_loop, label=label)
if qubits is None or clbits is None:
raise CircuitError("When using 'switch' with cases, you must pass qubits and clbits.")
return self.append(SwitchCaseOp(target, cases, label=label), qubits, clbits)
def break_loop(self) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.BreakLoopOp`.
.. warning::
If you are using the context-manager "builder" forms of :meth:`.if_test`,
:meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are
within a loop context, because otherwise the "resource width" of the operation cannot be
determined. This would quickly lead to invalid circuits, and so if you are trying to
construct a reusable loop body (without the context managers), you must also use the
non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the
:obj:`.BreakLoopOp` instruction must span all the resources of its containing loop, not
just the immediate scope.
Returns:
A handle to the instruction created.
Raises:
CircuitError: if this method was called within a builder context, but not contained
within a loop.
"""
# pylint: disable=cyclic-import
from qiskit.circuit.controlflow.break_loop import BreakLoopOp, BreakLoopPlaceholder
if self._control_flow_scopes:
operation = BreakLoopPlaceholder()
resources = operation.placeholder_resources()
return self.append(operation, resources.qubits, resources.clbits)
return self.append(BreakLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits)
def continue_loop(self) -> InstructionSet:
"""Apply :class:`~qiskit.circuit.ContinueLoopOp`.
.. warning::
If you are using the context-manager "builder" forms of :meth:`.if_test`,
:meth:`.for_loop` or :meth:`.while_loop`, you can only call this method if you are
within a loop context, because otherwise the "resource width" of the operation cannot be
determined. This would quickly lead to invalid circuits, and so if you are trying to
construct a reusable loop body (without the context managers), you must also use the
non-context-manager form of :meth:`.if_test` and :meth:`.if_else`. Take care that the
:class:`~qiskit.circuit.ContinueLoopOp` instruction must span all the resources of its
containing loop, not just the immediate scope.
Returns:
A handle to the instruction created.
Raises:
CircuitError: if this method was called within a builder context, but not contained
within a loop.
"""
# pylint: disable=cyclic-import
from qiskit.circuit.controlflow.continue_loop import ContinueLoopOp, ContinueLoopPlaceholder
if self._control_flow_scopes:
operation = ContinueLoopPlaceholder()
resources = operation.placeholder_resources()
return self.append(operation, resources.qubits, resources.clbits)
return self.append(
ContinueLoopOp(self.num_qubits, self.num_clbits), self.qubits, self.clbits
)
def add_calibration(
self,
gate: Union[Gate, str],
qubits: Sequence[int],
# Schedule has the type `qiskit.pulse.Schedule`, but `qiskit.pulse` cannot be imported
# while this module is, and so Sphinx will not accept a forward reference to it. Sphinx
# needs the types available at runtime, whereas mypy will accept it, because it handles the
# type checking by static analysis.
schedule,
params: Sequence[ParameterValueType] | None = None,
) -> None:
"""Register a low-level, custom pulse definition for the given gate.
Args:
gate (Union[Gate, str]): Gate information.
qubits (Union[int, Tuple[int]]): List of qubits to be measured.
schedule (Schedule): Schedule information.
params (Optional[List[Union[float, Parameter]]]): A list of parameters.
Raises:
Exception: if the gate is of type string and params is None.
"""
def _format(operand):
try:
# Using float/complex value as a dict key is not good idea.
# This makes the mapping quite sensitive to the rounding error.
# However, the mechanism is already tied to the execution model (i.e. pulse gate)
# and we cannot easily update this rule.
# The same logic exists in DAGCircuit.add_calibration.
evaluated = complex(operand)
if np.isreal(evaluated):
evaluated = float(evaluated.real)
if evaluated.is_integer():
evaluated = int(evaluated)
return evaluated
except TypeError:
# Unassigned parameter
return operand
if isinstance(gate, Gate):
params = gate.params
gate = gate.name
if params is not None:
params = tuple(map(_format, params))
else:
params = ()
self._calibrations[gate][(tuple(qubits), params)] = schedule
# Functions only for scheduled circuits
def qubit_duration(self, *qubits: Union[Qubit, int]) -> float:
"""Return the duration between the start and stop time of the first and last instructions,
excluding delays, over the supplied qubits. Its time unit is ``self.unit``.
Args:
*qubits: Qubits within ``self`` to include.
Returns:
Return the duration between the first start and last stop time of non-delay instructions
"""
return self.qubit_stop_time(*qubits) - self.qubit_start_time(*qubits)
def qubit_start_time(self, *qubits: Union[Qubit, int]) -> float:
"""Return the start time of the first instruction, excluding delays,
over the supplied qubits. Its time unit is ``self.unit``.
Return 0 if there are no instructions over qubits
Args:
*qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating
indices of ``self.qubits``.
Returns:
Return the start time of the first instruction, excluding delays, over the qubits
Raises:
CircuitError: if ``self`` is a not-yet scheduled circuit.
"""
if self.duration is None:
# circuit has only delays, this is kind of scheduled
for instruction in self._data:
if not isinstance(instruction.operation, Delay):
raise CircuitError(
"qubit_start_time undefined. Circuit must be scheduled first."
)
return 0
qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits]
starts = {q: 0 for q in qubits}
dones = {q: False for q in qubits}
for instruction in self._data:
for q in qubits:
if q in instruction.qubits:
if isinstance(instruction.operation, Delay):
if not dones[q]:
starts[q] += instruction.operation.duration
else:
dones[q] = True
if len(qubits) == len([done for done in dones.values() if done]): # all done
return min(start for start in starts.values())
return 0 # If there are no instructions over bits
def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> float:
"""Return the stop time of the last instruction, excluding delays, over the supplied qubits.
Its time unit is ``self.unit``.
Return 0 if there are no instructions over qubits
Args:
*qubits: Qubits within ``self`` to include. Integers are allowed for qubits, indicating
indices of ``self.qubits``.
Returns:
Return the stop time of the last instruction, excluding delays, over the qubits
Raises:
CircuitError: if ``self`` is a not-yet scheduled circuit.
"""
if self.duration is None:
# circuit has only delays, this is kind of scheduled
for instruction in self._data:
if not isinstance(instruction.operation, Delay):
raise CircuitError(
"qubit_stop_time undefined. Circuit must be scheduled first."
)
return 0
qubits = [self.qubits[q] if isinstance(q, int) else q for q in qubits]
stops = {q: self.duration for q in qubits}
dones = {q: False for q in qubits}
for instruction in reversed(self._data):
for q in qubits:
if q in instruction.qubits:
if isinstance(instruction.operation, Delay):
if not dones[q]:
stops[q] -= instruction.operation.duration
else:
dones[q] = True
if len(qubits) == len([done for done in dones.values() if done]): # all done
return max(stop for stop in stops.values())
return 0 # If there are no instructions over bits
class _ParameterBindsDict:
__slots__ = ("mapping", "allowed_keys")
def __init__(self, mapping, allowed_keys):
self.mapping = mapping
self.allowed_keys = allowed_keys
def items(self):
"""Iterator through all the keys in the mapping that we care about. Wrapping the main
mapping allows us to avoid reconstructing a new 'dict', but just use the given 'mapping'
without any copy / reconstruction."""
for parameter, value in self.mapping.items():
if parameter in self.allowed_keys:
yield parameter, value
class _ParameterBindsSequence:
__slots__ = ("parameters", "values", "mapping_cache")
def __init__(self, parameters, values):
self.parameters = parameters
self.values = values
self.mapping_cache = None
def items(self):
"""Iterator through all the keys in the mapping that we care about."""
return zip(self.parameters, self.values)
@property
def mapping(self):
"""Cached version of a mapping. This is only generated on demand."""
if self.mapping_cache is None:
self.mapping_cache = dict(zip(self.parameters, self.values))
return self.mapping_cache
# Used by the OQ2 exporter. Just needs to have enough parameters to support the largest standard
# (non-controlled) gate in our standard library. We have to use the same `Parameter` instances each
# time so the equality comparisons will work.
_QASM2_FIXED_PARAMETERS = [Parameter("param0"), Parameter("param1"), Parameter("param2")]
def _qasm2_custom_operation_statement(
instruction, existing_gate_names, gates_to_define, bit_labels
):
operation = _qasm2_define_custom_operation(
instruction.operation, existing_gate_names, gates_to_define
)
# Insert qasm representation of the original instruction
if instruction.clbits:
bits = itertools.chain(instruction.qubits, instruction.clbits)
else:
bits = instruction.qubits
bits_qasm = ",".join(bit_labels[j] for j in bits)
instruction_qasm = f"{_instruction_qasm2(operation)} {bits_qasm};"
return instruction_qasm
def _qasm2_define_custom_operation(operation, existing_gate_names, gates_to_define):
"""Extract a custom definition from the given operation, and append any necessary additional
subcomponents' definitions to the ``gates_to_define`` ordered dictionary.
Returns a potentially new :class:`.Instruction`, which should be used for the
:meth:`~.Instruction.qasm` call (it may have been renamed)."""
# pylint: disable=cyclic-import
from qiskit.circuit import library as lib
from qiskit.qasm2 import QASM2ExportError
if operation.name in existing_gate_names:
return operation
# Check instructions names or label are valid
escaped = _qasm_escape_name(operation.name, "gate_")
if escaped != operation.name:
operation = operation.copy(name=escaped)
# These are built-in gates that are known to be safe to construct by passing the correct number
# of `Parameter` instances positionally, and have no other information. We can't guarantee that
# if they've been subclassed, though. This is a total hack; ideally we'd be able to inspect the
# "calling" signatures of Qiskit `Gate` objects to know whether they're safe to re-parameterise.
known_good_parameterized = {
lib.PhaseGate,
lib.RGate,
lib.RXGate,
lib.RXXGate,
lib.RYGate,
lib.RYYGate,
lib.RZGate,
lib.RZXGate,
lib.RZZGate,
lib.XXMinusYYGate,
lib.XXPlusYYGate,
lib.UGate,
lib.U1Gate,
lib.U2Gate,
lib.U3Gate,
}
# In known-good situations we want to use a manually parametrised object as the source of the
# definition, but still continue to return the given object as the call-site object.
if type(operation) in known_good_parameterized:
parameterized_operation = type(operation)(*_QASM2_FIXED_PARAMETERS[: len(operation.params)])
elif hasattr(operation, "_qasm2_decomposition"):
new_op = operation._qasm2_decomposition()
parameterized_operation = operation = new_op.copy(
name=_qasm_escape_name(new_op.name, "gate_")
)
else:
parameterized_operation = operation
# If there's an _equal_ operation in the existing circuits to be defined, then our job is done.
previous_definition_source, _ = gates_to_define.get(operation.name, (None, None))
if parameterized_operation == previous_definition_source:
return operation
# Otherwise, if there's a naming clash, we need a unique name.
if operation.name in gates_to_define:
operation = _rename_operation(operation)
new_name = operation.name
if parameterized_operation.params:
parameters_qasm = (
"(" + ",".join(f"param{i}" for i in range(len(parameterized_operation.params))) + ")"
)
else:
parameters_qasm = ""
if operation.num_qubits == 0:
raise QASM2ExportError(
f"OpenQASM 2 cannot represent '{operation.name}, which acts on zero qubits."
)
if operation.num_clbits != 0:
raise QASM2ExportError(
f"OpenQASM 2 cannot represent '{operation.name}', which acts on {operation.num_clbits}"
" classical bits."
)
qubits_qasm = ",".join(f"q{i}" for i in range(parameterized_operation.num_qubits))
parameterized_definition = getattr(parameterized_operation, "definition", None)
if parameterized_definition is None:
gates_to_define[new_name] = (
parameterized_operation,
f"opaque {new_name}{parameters_qasm} {qubits_qasm};",
)
else:
qubit_labels = {bit: f"q{i}" for i, bit in enumerate(parameterized_definition.qubits)}
body_qasm = " ".join(
_qasm2_custom_operation_statement(
instruction, existing_gate_names, gates_to_define, qubit_labels
)
for instruction in parameterized_definition.data
)
# if an inner operation has the same name as the actual operation, it needs to be renamed
if operation.name in gates_to_define:
operation = _rename_operation(operation)
new_name = operation.name
definition_qasm = f"gate {new_name}{parameters_qasm} {qubits_qasm} {{ {body_qasm} }}"
gates_to_define[new_name] = (parameterized_operation, definition_qasm)
return operation
def _rename_operation(operation):
"""Returns the operation with a new name following this pattern: {operation name}_{operation id}"""
new_name = f"{operation.name}_{id(operation)}"
updated_operation = operation.copy(name=new_name)
return updated_operation
def _qasm_escape_name(name: str, prefix: str) -> str:
"""Returns a valid OpenQASM identifier, using `prefix` as a prefix if necessary. `prefix` must
itself be a valid identifier."""
# Replace all non-ASCII-word characters (letters, digits, underscore) with the underscore.
escaped_name = re.sub(r"\W", "_", name, flags=re.ASCII)
if (
not escaped_name
or escaped_name[0] not in string.ascii_lowercase
or escaped_name in QASM2_RESERVED
):
escaped_name = prefix + escaped_name
return escaped_name
def _instruction_qasm2(operation):
"""Return an OpenQASM 2 string for the instruction."""
from qiskit.qasm2 import QASM2ExportError # pylint: disable=cyclic-import
if operation.name == "c3sx":
qasm2_call = "c3sqrtx"
else:
qasm2_call = operation.name
if operation.params:
qasm2_call = "{}({})".format(
qasm2_call,
",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params]),
)
if operation.condition is not None:
if not isinstance(operation.condition[0], ClassicalRegister):
raise QASM2ExportError(
"OpenQASM 2 can only condition on registers, but got '{operation.condition[0]}'"
)
qasm2_call = (
"if(%s==%d) " % (operation.condition[0].name, operation.condition[1]) + qasm2_call
)
return qasm2_call
def _make_unique(name: str, already_defined: collections.abc.Set[str]) -> str:
"""Generate a name by suffixing the given stem that is unique within the defined set."""
if name not in already_defined:
return name
used = {in_use[len(name) :] for in_use in already_defined if in_use.startswith(name)}
characters = (string.digits + string.ascii_letters) if name else string.ascii_letters
for parts in itertools.chain.from_iterable(
itertools.product(characters, repeat=n) for n in itertools.count(1)
):
suffix = "".join(parts)
if suffix not in used:
return name + suffix
# This isn't actually reachable because the above loop is infinite.
return name
def _bit_argument_conversion(specifier, bit_sequence, bit_set, type_) -> list[Bit]:
"""Get the list of bits referred to by the specifier ``specifier``.
Valid types for ``specifier`` are integers, bits of the correct type (as given in ``type_``), or
iterables of one of those two scalar types. Integers are interpreted as indices into the
sequence ``bit_sequence``. All allowed bits must be in ``bit_set`` (which should implement
fast lookup), which is assumed to contain the same bits as ``bit_sequence``.
Returns:
List[Bit]: a list of the specified bits from ``bits``.
Raises:
CircuitError: if an incorrect type or index is encountered, if the same bit is specified
more than once, or if the specifier is to a bit not in the ``bit_set``.
"""
# The duplication between this function and `_bit_argument_conversion_scalar` is so that fast
# paths return as quickly as possible, and all valid specifiers will resolve without needing to
# try/catch exceptions (which is too slow for inner-loop code).
if isinstance(specifier, type_):
if specifier in bit_set:
return [specifier]
raise CircuitError(f"Bit '{specifier}' is not in the circuit.")
if isinstance(specifier, (int, np.integer)):
try:
return [bit_sequence[specifier]]
except IndexError as ex:
raise CircuitError(
f"Index {specifier} out of range for size {len(bit_sequence)}."
) from ex
# Slices can't raise IndexError - they just return an empty list.
if isinstance(specifier, slice):
return bit_sequence[specifier]
try:
return [
_bit_argument_conversion_scalar(index, bit_sequence, bit_set, type_)
for index in specifier
]
except TypeError as ex:
message = (
f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'"
if isinstance(specifier, Bit)
else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'"
)
raise CircuitError(message) from ex
def _bit_argument_conversion_scalar(specifier, bit_sequence, bit_set, type_):
if isinstance(specifier, type_):
if specifier in bit_set:
return specifier
raise CircuitError(f"Bit '{specifier}' is not in the circuit.")
if isinstance(specifier, (int, np.integer)):
try:
return bit_sequence[specifier]
except IndexError as ex:
raise CircuitError(
f"Index {specifier} out of range for size {len(bit_sequence)}."
) from ex
message = (
f"Incorrect bit type: expected '{type_.__name__}' but got '{type(specifier).__name__}'"
if isinstance(specifier, Bit)
else f"Invalid bit index: '{specifier}' of type '{type(specifier)}'"
)
raise CircuitError(message)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
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/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = t3_st_qcs
# zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False)
# print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
# with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
# with open(filename, "wb") as f:
# pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
# with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump(backend.properties(), f)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
# mit_results = meas_fitter.filter.apply(job.result())
rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq')
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/QPower-Research/QPowerAlgo
|
QPower-Research
|
#In case you don't have qiskit, install it now
%pip install qiskit --quiet
#Installing/upgrading pylatexenc seems to have fixed my mpl issue
#If you try this and it doesn't work, try also restarting the runtime/kernel
%pip install pylatexenc --quiet
!pip install -Uqq ipdb
!pip install qiskit_optimization
import networkx as nx
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions.hamiltonian_gate import HamiltonianGate
from qiskit.extensions import RXGate, XGate, CXGate
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
import numpy as np
from qiskit.visualization import plot_histogram
import ipdb
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#quadratic optimization
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import QuadraticProgramToQubo
%pdb on
# def ApplyCost(qc, gamma):
# Ix = np.array([[1,0],[0,1]])
# Zx= np.array([[1,0],[0,-1]])
# Xx = np.array([[0,1],[1,0]])
# Temp = (Ix-Zx)/2
# T = Operator(Temp)
# I = Operator(Ix)
# Z = Operator(Zx)
# X = Operator(Xx)
# FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
# ham = HamiltonianGate(FinalOp,gamma)
# qc.append(ham,[0,1,2])
task = QuadraticProgram(name = 'QUBO on QC')
task.binary_var(name = 'x')
task.binary_var(name = 'y')
task.binary_var(name = 'z')
task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1})
qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO
operator, offset = qubo.to_ising()
print(operator)
# ham = HamiltonianGate(operator,0)
# print(ham)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
ham = HamiltonianGate(FinalOp,0)
print(ham)
#define PYBIND11_DETAILED_ERROR_MESSAGES
def compute_expectation(counts):
"""
Computes expectation value based on measurement results
Args:
counts: dict
key as bitstring, val as count
G: networkx graph
Returns:
avg: float
expectation value
"""
avg = 0
sum_count = 0
for bitstring, count in counts.items():
x = int(bitstring[2])
y = int(bitstring[1])
z = int(bitstring[0])
obj = -2*x*z-y*z-x+2*y-3*z
avg += obj * count
sum_count += count
return avg/sum_count
# We will also bring the different circuit components that
# build the qaoa circuit under a single function
def create_qaoa_circ(theta):
"""
Creates a parametrized qaoa circuit
Args:
G: networkx graph
theta: list
unitary parameters
Returns:
qc: qiskit circuit
"""
nqubits = 3
n,m=3,3
p = len(theta)//2 # number of alternating unitaries
qc = QuantumCircuit(nqubits,nqubits)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z)
beta = theta[:p]
gamma = theta[p:]
# initial_state
for i in range(0, nqubits):
qc.h(i)
for irep in range(0, p):
#ipdb.set_trace(context=6)
# problem unitary
# for pair in list(G.edges()):
# qc.rzz(2 * gamma[irep], pair[0], pair[1])
#ApplyCost(qc,2*0)
ham = HamiltonianGate(operator,2 * gamma[irep])
qc.append(ham,[0,1,2])
# mixer unitary
for i in range(0, nqubits):
qc.rx(2 * beta[irep], i)
qc.measure(qc.qubits[:n],qc.clbits[:m])
return qc
# Finally we write a function that executes the circuit on the chosen backend
def get_expectation(shots=512):
"""
Runs parametrized circuit
Args:
G: networkx graph
p: int,
Number of repetitions of unitaries
"""
backend = Aer.get_backend('qasm_simulator')
backend.shots = shots
def execute_circ(theta):
qc = create_qaoa_circ(theta)
# ipdb.set_trace(context=6)
counts = {}
job = execute(qc, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc)
return compute_expectation(counts)
return execute_circ
from scipy.optimize import minimize
expectation = get_expectation()
res = minimize(expectation, [1, 1], method='COBYLA')
expectation = get_expectation()
res = minimize(expectation, res.x, method='COBYLA')
res
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('aer_simulator')
backend.shots = 512
qc_res = create_qaoa_circ(res.x)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc_res, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc_res)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc_basis = transpile(qc, backend)
qc_basis.draw(output='mpl')
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate
import numpy as np
import os
from qiskit.extensions import UnitaryGate
import sys
import matplotlib.pyplot as plt
%matplotlib inline
os.makedirs(name = 'Plots',exist_ok=True)
sys.path.append("..")
from Modules.normal_SPEA import SPEA
# uncomment & RUN to use actual backends
# from qiskit import IBMQ
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='??your_provider??')
# santiago = provider.get_backend('ibmq_santiago')
# casablanca = provider.get_backend('ibmq_casablanca')
sim = Aer.get_backend('qasm_simulator')
U1 = QuantumCircuit(1)
U1.x(0)
U1.draw('mpl')
spe = SPEA(U1,resolution= 10,error = 4,max_iters=12)
result = spe.get_eigen_pair(progress = False,algo = 'alternate',backend = Aer.get_backend('qasm_simulator'))
result
# original theta = 0.2
t = []
for resolution in range(10,50,5):
spe = SPEA(U1,resolution= resolution,max_iters=10)
res = spe.get_eigen_pair(backend = sim,algo = 'alternate',target_cost = 0.9)
theta = res['theta']
t.append(theta)
plt.figure(dpi = 100,figsize=(8,6))
plt.title("Eigenphase estimation for X gate",fontsize = 15)
plt.grid()
plt.plot(list(range(10,50,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7)
plt.plot([10,50],[0.5,0.5],color='black',label = "True")
plt.plot([10,50],[0,0],color='black')
plt.plot([10,50],[1,1],color='black')
plt.legend()
plt.xlabel("Resolution of theta ")
plt.ylabel("Estimates")
plt.savefig("Plots/SPE_PLOT1.jpg",dpi = 200)
u2 = UnitaryGate(data=np.array([[1,0],
[0, np.exp(2*np.pi*1j*(1/5))]]))
# original theta = 0.2
t = []
for resolution in range(20,80,5):
spe = SPEA(u2,resolution= resolution,max_iters=10)
res = spe.get_eigen_pair(backend = sim,algo = 'alternate',target_cost = 0.94)
theta = res['theta']
t.append(theta)
plt.figure(dpi = 100,figsize = (8,6))
plt.title("Eigenphase estimation for theta = 1/5, 0",fontsize = 15)
plt.grid()
plt.plot(list(range(20,80,5)),t,marker = 'o',color='g',label = 'Estimates',alpha=0.7)
plt.plot([10,80],[0.2,0.2],color='black',label = "True")
plt.plot([10,80],[0,0],color='black')
plt.plot([10,80],[1,1],color='black')
plt.legend()
plt.xlabel("Resolution of theta ")
plt.ylabel("Estimates")
plt.savefig("Plots/SPE_PLOT2.jpg",dpi = 200)
|
https://github.com/qiskit-community/qiskit-aqt-provider
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright Alpine Quantum Technologies GmbH 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.
"""Basic example with the Qiskit AQT provider and the noisy offline simulator.
Creates a 2-qubit GHZ state.
"""
import qiskit
from qiskit import QuantumCircuit
from qiskit_aqt_provider.aqt_provider import AQTProvider
if __name__ == "__main__":
# Ways to specify an access token (in precedence order):
# - as argument to the AQTProvider initializer
# - in the AQT_TOKEN environment variable
# - if none of the above exists, default to an empty string, which restricts access
# to the default workspace only.
provider = AQTProvider("token")
# The backends() method lists all available computing backends. Printing it
# renders it as a table that shows each backend's containing workspace.
print(provider.backends())
# Retrieve a backend by providing search criteria. The search must have a single
# match. For example:
backend = provider.get_backend("offline_simulator_noise", workspace="default")
# Define a quantum circuit that produces a 2-qubit GHZ state.
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
# Transpile for the target backend.
qc = qiskit.transpile(qc, backend)
# Execute on the target backend.
result = backend.run(qc, shots=200).result()
if result.success:
# due to the noise, also the states '01' and '10' may be populated!
print(result.get_counts())
else: # pragma: no cover
print(result.to_dict()["error"])
|
https://github.com/COFAlumni-USB/qiskit-fall-2022
|
COFAlumni-USB
|
import numpy as np
import math
import qiskit as qiskit
from numpy import sqrt
from random import randint
from qiskit import *
from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info, transpile
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_histogram
from qiskit.tools import job_monitor
from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeOpenPulse3Q, FakeManila, FakeValencia, FakeHanoi
from qiskit import pulse, transpile
from qiskit.pulse.library import Gaussian
#Compuertas personalizadas
from qiskit.circuit import Gate
from qiskit import QiskitError
#informacion
import qiskit.tools.jupyter
provider = IBMQ.load_account()
belem = provider.get_backend('ibmq_belem')
print('se ha ejecutado correctamente')
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeManila()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=33.33), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration( 'h', [0], h_q0)
circ.add_calibration( 'x', [0], h_q0)
circ.add_calibration( 'cx',[0], h_q0)
circ.add_calibration( 'sx',[0], h_q0)
circ.add_calibration( 'id',[0], h_q0)
circ.add_calibration( 'rz',[0], h_q0)
circ.add_calibration( 'reset',[0], h_q0)
backend = FakeManila()
circ1 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ1.draw('mpl', idle_wires=False)
result = execute(circ1, backend=FakeManila()).result();
job = backend.run(circ1)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q1.draw()
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.3, sigma=33.33), pulse.drive_channel(0))
h_q1.draw()
circ.add_calibration( 'h', [0], h_q1)
circ.add_calibration( 'x', [0], h_q1)
circ.add_calibration( 'cx',[0], h_q1)
circ.add_calibration( 'sx',[0], h_q1)
circ.add_calibration( 'id',[0], h_q1)
circ.add_calibration( 'rz',[0], h_q1)
circ.add_calibration( 'reset',[0], h_q1)
backend = FakeOpenPulse3Q()
circ2 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ2.draw('mpl', idle_wires=False)
result = execute(circ2, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ2)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeManila()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.3, sigma=33.33), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration( 'h', [0], h_q0)
circ.add_calibration( 'x', [0], h_q0)
circ.add_calibration( 'cx',[0], h_q0)
circ.add_calibration( 'sx',[0], h_q0)
circ.add_calibration( 'id',[0], h_q0)
circ.add_calibration( 'rz',[0], h_q0)
circ.add_calibration( 'reset',[0], h_q0)
backend = FakeManila()
circ1 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ1.draw('mpl', idle_wires=False)
result = execute(circ1, backend=FakeManila()).result();
job = backend.run(circ1)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q1.draw()
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.3, sigma=33.33), pulse.drive_channel(0))
h_q1.draw()
circ.add_calibration( 'h', [0], h_q1)
circ.add_calibration( 'x', [0], h_q1)
circ.add_calibration( 'cx',[0], h_q1)
circ.add_calibration( 'sx',[0], h_q1)
circ.add_calibration( 'id',[0], h_q1)
circ.add_calibration( 'rz',[0], h_q1)
circ.add_calibration( 'reset',[0], h_q1)
backend = FakeOpenPulse3Q()
circ2 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ2.draw('mpl', idle_wires=False)
result = execute(circ2, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ2)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeManila()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=1, sigma=33.33), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration( 'h', [0], h_q0)
circ.add_calibration( 'x', [0], h_q0)
circ.add_calibration( 'cx',[0], h_q0)
circ.add_calibration( 'sx',[0], h_q0)
circ.add_calibration( 'id',[0], h_q0)
circ.add_calibration( 'rz',[0], h_q0)
circ.add_calibration( 'reset',[0], h_q0)
backend = FakeManila()
circ1 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ1.draw('mpl', idle_wires=False)
result = execute(circ1, backend=FakeManila()).result();
job = backend.run(circ1)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q1.draw()
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=1, sigma=33.33), pulse.drive_channel(0))
h_q1.draw()
circ.add_calibration( 'h', [0], h_q1)
circ.add_calibration( 'x', [0], h_q1)
circ.add_calibration( 'cx',[0], h_q1)
circ.add_calibration( 'sx',[0], h_q1)
circ.add_calibration( 'id',[0], h_q1)
circ.add_calibration( 'rz',[0], h_q1)
circ.add_calibration( 'reset',[0], h_q1)
backend = FakeOpenPulse3Q()
circ2 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ2.draw('mpl', idle_wires=False)
result = execute(circ2, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ2)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# let's define both vectors
u = [-3,-2,0,-1,4]
v = [-1,-1,2,-3,5]
uv = 0; # summation is initially zero
for i in range(len(u)): # iteratively access every pair with the same indices
print("pairwise multiplication of the entries with index",i,"is",u[i]*v[i])
uv = uv + u[i]*v[i] # i-th entries are multiplied and then added to summation
print() # print an empty line
print("The dot product of",u,'and',v,'is',uv)
#
# your solution is here
#
# let's define the vectors
v=[-3,4,-5,6]
u=[4,3,6,5]
vu = 0
for i in range(len(v)):
vu = vu + v[i]*u[i]
print(v,u,vu)
#
# your solution is here
#
u = [-3,-4]
uu = u[0]*u[0] + u[1]*u[1]
print(u,u,uu)
# let's find the dot product of v and u
v = [-4,0]
u = [0,-5]
result = 0;
for i in range(2):
result = result + v[i]*u[i]
print("the dot product of u and v is",result)
# we can use the same code
v = [-4,3]
u = [-3,-4]
result = 0;
for i in range(2):
result = result + v[i]*u[i]
print("the dot product of u and v is",result)
# you may consider to write a function in Python for dot product
#
# your solution is here
#
u = [-3,-4]
neg_u=[3,4]
v=[-4,3]
neg_v=[4,-3]
# let's define a function for inner product
def dot(v_one,v_two):
summation = 0
for i in range(len(v_one)):
summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications
return summation # return the inner product
print("the dot product of u and -v (",u," and ",neg_v,") is",dot(u,neg_v))
print("the dot product of -u and v (",neg_u," and ",v,") is",dot(neg_u,v))
print("the dot product of -u and -v (",neg_u," and ",neg_v,") is",dot(neg_u,neg_v))
#
# your solution is here
#
# let's define a function for inner product
def dot(v_one,v_two):
summation = 0
for i in range(len(v_one)):
summation = summation + v_one[i]*v_two[i] # adding up pairwise multiplications
return summation # return the inner product
v = [-1,2,-3,4]
v_neg_two=[2,-4,6,-8]
u=[-2,-1,5,2]
u_three=[-6,-3,15,6]
print("the dot product of v and u is",dot(v,u))
print("the dot product of -2v and 3u is",dot(v_neg_two,u_three))
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 1量子ビット回路を定義
q1 = QuantumCircuit(1)
## 回路を描画
q1.draw(output="mpl")
# 量子ゲートで回路を作成
q1.x(0)
q1.x(0)
## 回路を描画
q1.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q1, vector_sim )
result = job.result().get_statevector(q1, decimals=3)
print(result)
# 1量子ビット回路を定義
q2 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q2.h(0)
# 回路を描画
q2.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q2, vector_sim )
result = job.result().get_statevector(q2, decimals=3)
print(result)
# 1量子ビット回路を定義
q3 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q3.h(0)
q3.h(0)
# 回路を描画
q3.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q3, vector_sim )
result = job.result().get_statevector(q3, decimals=3)
print(result)
# 1量子ビット回路を定義
q4 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q4.x(0)
q4.h(0)
# 回路を描画
q4.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q4, vector_sim )
result = job.result().get_statevector(q4, decimals=3)
print(result)
# 1量子ビット回路を定義
q5 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q5.h(0)
q5.z(0)
# 回路を描画
q5.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q5, vector_sim )
result = job.result().get_statevector(q5, decimals=3)
print(result)
# 1量子ビット回路を定義
q6 = QuantumCircuit(1)
# 量子ゲートで回路を作成
q6.x(0)
q6.h(0)
q6.z(0)
# 回路を描画
q6.draw(output="mpl")
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(q6, vector_sim )
result = job.result().get_statevector(q6, decimals=3)
print(result)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, backend=FakeBoeblingen())
|
https://github.com/arian-code/nptel_quantum_assignments
|
arian-code
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
%matplotlib inline
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector.from_instruction(qc)
plot_state_qsphere(state)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/QC-Hub/Examples
|
QC-Hub
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit import BasicAer
'''
APItoken="APItoken"
config = { "url": 'https://quantumexperience.ng.bluemix.net/api'}
'''
n1 = input("Enter a binary number with less than 8 digits:")
n2 = input("Enter another binary number with less than 8 digits:")
l1 = len(n1)
l2 = len(n2)
n = 0
if l1>l2:
n = l1
else:
n = l2
a = QuantumRegister(n) #First number
b = QuantumRegister(n+1) #Second number
c = QuantumRegister(n) #Carry bits
cl = ClassicalRegister(n+1) #Clasical register to store the value of qubits
qc = QuantumCircuit(a,b,c,cl) #Creating a quantum circuit using quantum registers and classical registers
for i in range(l1):
if n1[i] == "1":
qc.x(a[l1-(i+1)]) #Changing all qubits corresponding to 1 in the first number to |1> using CNOT gate
for i in range(l2):
if n2[i] == "1":
qc.x(b[l2-(i+1)]) #Changing all qubits corresponding to 1 in the second number to |1> using CNOT gate
for i in range(n-1):
qc.ccx(a[i],b[i],c[i+1]) #Applying CCNOT gate with current qubits of the two numbers as control and changes the next carry bit
qc.cx(a[i],b[i]) #Applying CNOT gate with the qubits of first number as control and make changes to the qubits of the second number
qc.ccx(c[i],b[i],c[i+1]) #Applying CCNOT gate with the current carry bit and current qubit of the second number as control and make changes to the next carry bit
qc.ccx(a[n-1],b[n-1],b[n]) #Making changes corresponding to the final carry bits
qc.cx(a[n-1],b[n-1])
qc.ccx(c[n-1],b[n-1],b[n])
qc.cx(c[n-1],b[n-1])
for i in range(n-1): #Reversing the qubits
qc.ccx(c[(n-2)-i],b[(n-2)-i],c[(n-1)-i])
qc.cx(a[(n-2)-i],b[(n-2)-i])
qc.ccx(a[(n-2)-i],b[(n-2)-i],c[(n-1)-i])
qc.cx(c[(n-2)-i],b[(n-2)-i])
qc.cx(a[(n-2)-i],b[(n-2)-i])
for i in range(n+1):
qc.measure(b[i],cl[i]) #Measuring thre qubits and storing its values to a classical register
print(qc) #Printing the quantum circuit using ASCII characters
backend = BasicAer.get_backend('qasm_simulator') #Creating a backend using virtual qasm simulator
job = execute(qc, backend, shots=2) #Creating a job
counts = job.result().get_counts(qc) #Calculating the occurances of each output
print(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the LookaheadSwap pass"""
import unittest
from numpy import pi
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler.passes import LookaheadSwap
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import CXGate
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeMelbourne
class TestLookaheadSwap(QiskitTestCase):
"""Tests the LookaheadSwap pass."""
def test_lookahead_swap_doesnt_modify_mapped_circuit(self):
"""Test that lookahead swap is idempotent.
It should not modify a circuit which is already compatible with the
coupling map, and can be applied repeatedly without modifying the circuit.
"""
qr = QuantumRegister(3, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[1])
original_dag = circuit_to_dag(circuit)
# Create coupling map which contains all two-qubit gates in the circuit.
coupling_map = CouplingMap([[0, 1], [0, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(original_dag)
self.assertEqual(original_dag, mapped_dag)
remapped_dag = LookaheadSwap(coupling_map).run(mapped_dag)
self.assertEqual(mapped_dag, remapped_dag)
def test_lookahead_swap_should_add_a_single_swap(self):
"""Test that LookaheadSwap will insert a SWAP to match layout.
For a single cx gate which is not available in the current layout, test
that the mapper inserts a single swap to enable the gate.
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
def test_lookahead_swap_finds_minimal_swap_solution(self):
"""Of many valid SWAPs, test that LookaheadSwap finds the cheapest path.
For a two CNOT circuit: cx q[0],q[2]; cx q[0],q[1]
on the initial layout: qN -> qN
(At least) two solutions exist:
- SWAP q[0],[1], cx q[0],q[2], cx q[0],q[1]
- SWAP q[1],[2], cx q[0],q[2], SWAP q[1],q[2], cx q[0],q[1]
Verify that we find the first solution, as it requires fewer SWAPs.
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[1])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
def test_lookahead_swap_maps_measurements(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs.
Create a circuit with measures on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped measure corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[2], cr[1])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")}
self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_maps_measurements_with_target(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs.
Create a circuit with measures on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped measure corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[2], cr[1])
dag_circuit = circuit_to_dag(circuit)
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None})
mapped_dag = LookaheadSwap(target).run(dag_circuit)
mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")}
self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_maps_barriers(self):
"""Verify barrier nodes are updated to re-mapped qregs.
Create a circuit with a barrier on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped barrier corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.barrier(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
mapped_barrier_qargs = [set(op.qargs) for op in mapped_dag.named_nodes("barrier")][0]
self.assertIn(mapped_barrier_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_higher_depth_width_is_better(self):
"""Test that lookahead swap finds better circuit with increasing search space.
Increasing the tree width and depth is expected to yield a better (or same) quality
circuit, in the form of fewer SWAPs.
"""
# q_0: ──■───────────────────■───────────────────────────────────────────────»
# ┌─┴─┐ │ ┌───┐ »
# q_1: ┤ X ├──■──────────────┼─────────────────┤ X ├─────────────────────────»
# └───┘┌─┴─┐ │ └─┬─┘┌───┐ ┌───┐ »
# q_2: ─────┤ X ├──■─────────┼───────────────────┼──┤ X ├──────────┤ X ├──■──»
# └───┘┌─┴─┐ ┌─┴─┐ │ └─┬─┘ ┌───┐└─┬─┘ │ »
# q_3: ──────────┤ X ├──■──┤ X ├─────────────────┼────┼────■──┤ X ├──┼────┼──»
# └───┘┌─┴─┐└───┘ ┌───┐ │ │ │ └─┬─┘ │ │ »
# q_4: ───────────────┤ X ├──■────────────┤ X ├──┼────■────┼────┼────┼────┼──»
# └───┘┌─┴─┐ └─┬─┘ │ │ │ │ │ »
# q_5: ────────────────────┤ X ├──■─────────┼────┼─────────┼────■────┼────┼──»
# └───┘┌─┴─┐ │ │ │ │ │ »
# q_6: ─────────────────────────┤ X ├──■────■────┼─────────┼─────────■────┼──»
# └───┘┌─┴─┐ │ ┌─┴─┐ ┌─┴─┐»
# q_7: ──────────────────────────────┤ X ├───────■───────┤ X ├──────────┤ X ├»
# └───┘ └───┘ └───┘»
# «q_0: ──■───────
# « │
# «q_1: ──┼───────
# « │
# «q_2: ──┼───────
# « │
# «q_3: ──┼───────
# « │
# «q_4: ──┼───────
# « │
# «q_5: ──┼────■──
# « ┌─┴─┐ │
# «q_6: ┤ X ├──┼──
# « └───┘┌─┴─┐
# «q_7: ─────┤ X ├
# « └───┘
qr = QuantumRegister(8, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[6], qr[4])
circuit.cx(qr[7], qr[1])
circuit.cx(qr[4], qr[2])
circuit.cx(qr[3], qr[7])
circuit.cx(qr[5], qr[3])
circuit.cx(qr[6], qr[2])
circuit.cx(qr[2], qr[7])
circuit.cx(qr[0], qr[6])
circuit.cx(qr[5], qr[7])
original_dag = circuit_to_dag(circuit)
# Create a ring of 8 connected qubits
coupling_map = CouplingMap.from_grid(num_rows=2, num_columns=4)
mapped_dag_1 = LookaheadSwap(coupling_map, search_depth=3, search_width=3).run(original_dag)
mapped_dag_2 = LookaheadSwap(coupling_map, search_depth=5, search_width=5).run(original_dag)
num_swaps_1 = mapped_dag_1.count_ops().get("swap", 0)
num_swaps_2 = mapped_dag_2.count_ops().get("swap", 0)
self.assertLessEqual(num_swaps_2, num_swaps_1)
def test_lookahead_swap_hang_in_min_case(self):
"""Verify LookaheadSwap does not stall in minimal case."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2171
qr = QuantumRegister(14, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
dag = circuit_to_dag(qc)
cmap = CouplingMap(FakeMelbourne().configuration().coupling_map)
out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag)
self.assertIsInstance(out, DAGCircuit)
def test_lookahead_swap_hang_full_case(self):
"""Verify LookaheadSwap does not stall in reported case."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2171
qr = QuantumRegister(14, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
qc.cx(qr[6], qr[7])
qc.cx(qr[8], qr[7])
qc.cx(qr[8], qr[6])
qc.cx(qr[7], qr[8])
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
qc.cx(qr[0], qr[1])
dag = circuit_to_dag(qc)
cmap = CouplingMap(FakeMelbourne().configuration().coupling_map)
out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag)
self.assertIsInstance(out, DAGCircuit)
def test_global_phase_preservation(self):
"""Test that LookaheadSwap preserves global phase"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = pi / 3
circuit.cx(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(mapped_dag.global_phase, circuit.global_phase)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
from qiskit_aqua import Operator, run_algorithm
from qiskit_aqua.input import EnergyInput
from qiskit_aqua.translators.ising import partition
from qiskit import Aer
from qiskit_aqua.algorithms.classical.cplex.cplex_ising import CPLEX_Ising
number_list = partition.read_numbers_from_file('sample.partition')
qubitOp, offset = partition.get_partition_qubitops(number_list)
algo_input = EnergyInput(qubitOp)
print(number_list)
if True:
np.random.seed(8123179)
number_list = partition.random_number_list(5, weight_range=25)
qubitOp, offset = partition.get_partition_qubitops(number_list)
algo_input.qubit_op = qubitOp
print(number_list)
to_be_tested_algos = ['ExactEigensolver', 'CPLEX.Ising', 'VQE']
print(to_be_tested_algos)
algorithm_cfg = {
'name': 'ExactEigensolver',
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params,algo_input)
x = partition.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('partition objective:', result['energy'] + offset)
print('solution:', x)
print('solution objective:', partition.partition_value(x, number_list))
cplex_installed = True
try:
CPLEX_Ising.check_pluggable_valid()
except Exception as e:
cplex_installed = False
if cplex_installed:
algorithm_cfg = {
'name': 'CPLEX.Ising',
'display': 0
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg
}
result = run_algorithm(params, algo_input)
x_dict = result['x_sol']
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('partition objective:', result['energy'] + offset)
x = np.array([x_dict[i] for i in sorted(x_dict.keys())])
print('solution:', x)
print('solution objective:', partition.partition_value(x, number_list))
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'L_BFGS_B',
'maxfun': 6000
}
var_form_cfg = {
'name': 'RYRZ',
'depth': 3,
'entanglement': 'linear'
}
params = {
'problem': {'name': 'ising'},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg
}
backend = Aer.get_backend('statevector_simulator')
result = run_algorithm(params, algo_input, backend=backend)
x = partition.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('partition objective:', result['energy'] + offset)
print('solution:', x)
print('solution objective:', partition.partition_value(x, number_list))
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
import numpy as np
X_train = np.asarray([[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]])
y_train = [0, 1, 0, 1]
X_test = np.asarray([[0.2, 0.4], [0.4, -0.8]])
y_test = [0, 1]
import matplotlib.pyplot as plt
plt.scatter(
X_train[:,0], X_train[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_train],
marker='x', s=200)
plt.scatter(
X_test[:,0], X_test[:,1],
color=['red' if yy == 0 else 'blue' for yy in y_test],
marker='o', s=200)
plt.hlines(0.0, -1.0, 1.0)
plt.vlines(0.0, -1.0, 1.0)
plt.show()
from dc_qiskit_qml.encoding_maps import EncodingMap
import scipy.sparse as sparse
class MyEncodingMap(EncodingMap):
def map(self, input_vector: list) -> sparse.dok_matrix:
result = sparse.dok_matrix((4,1))
index = 0
if input_vector[0] > 0 and input_vector[1] > 0:
index = 0
if input_vector[0] < 0 < input_vector[1]:
index = 1
if input_vector[0] < 0 and input_vector[1] < 0:
index = 2
if input_vector[0] > 0 > input_vector[1]:
index = 3
result[index, 0] = 1.0
return result
encoding_map = MyEncodingMap()
list(zip(X_train, [encoding_map.map(x).keys() for x in X_train]))
list(zip(X_test, [encoding_map.map(x).keys() for x in X_test]))
from qiskit_aer.backends.aerbackend import AerBackend
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlBinaryDataStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXToffoli
initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli(), do_optimizations=True)
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
qml.predict(X_test), y_test
qiskit.IBMQ.load_account()
qiskit.IBMQ.get_provider().backends()
qiskit.Aer.backends()
b16 = qiskit.IBMQ.get_provider().get_backend('ibmq_16_melbourne')
b16.status()
execution_backend = b16
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
async_qml_job = qml.predict_async(X_test)
async_qml_job.job.status(), async_qml_job.job.job_id()
async_qml_job.predict_result(), y_test
qml.last_predict_probability, qml.last_predict_p_acc
qml._last_predict_circuits[0].draw(output='mpl')
from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXMottonen
initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXMottonen())
execution_backend: AerBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
qml.predict(X_test), y_test
qml._last_predict_circuits[0].draw(output='mpl', fold=-1)
execution_backend = b16
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
shots=8192,
encoding_map=encoding_map,
classifier_circuit_factory=initial_state_builder)
qml.fit(X_train, y_train)
async_qml_job.job.status(), async_qml_job.job.job_id()
qml.last_predict_probability, qml.last_predict_p_acc
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a Statevector
state = Statevector(qc)
plot_state_city(state)
|
https://github.com/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/alpine-quantum-technologies/qiskit-aqt-provider-rc
|
alpine-quantum-technologies
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, Alpine Quantum Technologies GmbH 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import uuid
from collections import Counter, defaultdict, namedtuple
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
DefaultDict,
Dict,
List,
NoReturn,
Optional,
Set,
Union,
)
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers import JobV1
from qiskit.providers.jobstatus import JobStatus
from qiskit.result.result import Result
from qiskit.utils.lazy_tester import contextlib
from tqdm import tqdm
from typing_extensions import Self, TypeAlias, assert_never
from qiskit_aqt_provider import api_models_generated
from qiskit_aqt_provider.aqt_options import AQTOptions
if TYPE_CHECKING: # pragma: no cover
from qiskit_aqt_provider.aqt_resource import AQTResource
# Tags for the status of AQT API jobs
@dataclass
class JobFinished:
"""The job finished successfully."""
status: ClassVar = JobStatus.DONE
results: Dict[int, List[List[int]]]
@dataclass
class JobFailed:
"""An error occurred during the job execution."""
status: ClassVar = JobStatus.ERROR
error: str
class JobQueued:
"""The job is queued."""
status: ClassVar = JobStatus.QUEUED
@dataclass
class JobOngoing:
"""The job is running."""
status: ClassVar = JobStatus.RUNNING
finished_count: int
class JobCancelled:
"""The job was cancelled."""
status = ClassVar = JobStatus.CANCELLED
JobStatusPayload: TypeAlias = Union[JobQueued, JobOngoing, JobFinished, JobFailed, JobCancelled]
@dataclass(frozen=True)
class Progress:
"""Progress information of a job."""
finished_count: int
"""Number of completed circuits."""
total_count: int
"""Total number of circuits in the job."""
@dataclass
class _MockProgressBar:
"""Minimal tqdm-compatible progress bar mock."""
total: int
"""Total number of items in the job."""
n: int = 0
"""Number of processed items."""
def update(self, n: int = 1) -> None:
"""Update the number of processed items by `n`."""
self.n += n
def __enter__(self) -> Self:
return self
def __exit__(*args) -> None:
...
class AQTJob(JobV1):
_backend: "AQTResource"
def __init__(
self,
backend: "AQTResource",
circuits: List[QuantumCircuit],
options: AQTOptions,
):
"""Initialize a job instance.
Args:
backend: backend to run the job on
circuits: list of circuits to execute
options: overridden resource options for this job.
"""
super().__init__(backend, "")
self.circuits = circuits
self.options = options
self.status_payload: JobStatusPayload = JobQueued()
def submit(self) -> None:
"""Submit this job for execution.
Raises:
RuntimeError: this job was already submitted.
"""
if self.job_id():
raise RuntimeError(f"Job already submitted (ID: {self.job_id()})")
job_id = self._backend.submit(self.circuits, self.options.shots)
self._job_id = str(job_id)
def status(self) -> JobStatus:
"""Query the job's status.
Returns:
JobStatus: aggregated job status for all the circuits in this job.
"""
payload = self._backend.result(uuid.UUID(self.job_id()))
if isinstance(payload, api_models_generated.JobResponseRRQueued):
self.status_payload = JobQueued()
elif isinstance(payload, api_models_generated.JobResponseRROngoing):
self.status_payload = JobOngoing(finished_count=payload.response.finished_count)
elif isinstance(payload, api_models_generated.JobResponseRRFinished):
self.status_payload = JobFinished(
results={
int(circuit_index): [[sample.__root__ for sample in shot] for shot in shots]
for circuit_index, shots in payload.response.result.items()
}
)
elif isinstance(payload, api_models_generated.JobResponseRRError):
self.status_payload = JobFailed(error=payload.response.message)
elif isinstance(payload, api_models_generated.JobResponseRRCancelled):
self.status_payload = JobCancelled()
else: # pragma: no cover
assert_never(payload)
return self.status_payload.status
def progress(self) -> Progress:
"""Progress information for this job."""
num_circuits = len(self.circuits)
if isinstance(self.status_payload, JobQueued):
return Progress(finished_count=0, total_count=num_circuits)
if isinstance(self.status_payload, JobOngoing):
return Progress(
finished_count=self.status_payload.finished_count, total_count=num_circuits
)
# if the circuit is finished, failed, or cancelled, it is completed
return Progress(finished_count=num_circuits, total_count=num_circuits)
@property
def error_message(self) -> Optional[str]:
"""Error message for this job (if any)."""
if isinstance(self.status_payload, JobFailed):
return self.status_payload.error
return None
def result(self) -> Result:
"""Block until all circuits have been evaluated and return the combined result.
Success or error is signalled by the `success` field in the returned Result instance.
Returns:
The combined result of all circuit evaluations.
"""
if self.options.with_progress_bar:
context: Union[tqdm[NoReturn], _MockProgressBar] = tqdm(total=len(self.circuits))
else:
context = _MockProgressBar(total=len(self.circuits))
with context as progress_bar:
def callback(
job_id: str, # noqa: ARG001
status: JobStatus, # noqa: ARG001
job: AQTJob,
) -> None:
progress = job.progress()
progress_bar.update(progress.finished_count - progress_bar.n)
# one of DONE, CANCELLED, ERROR
self.wait_for_final_state(
timeout=self.options.query_timeout_seconds,
wait=self.options.query_period_seconds,
callback=callback,
)
# make sure the progress bar completes
progress_bar.update(self.progress().finished_count - progress_bar.n)
results = []
if isinstance(self.status_payload, JobFinished):
for circuit_index, circuit in enumerate(self.circuits):
samples = self.status_payload.results[circuit_index]
meas_map = _build_memory_mapping(circuit)
data: Dict[str, Any] = {
"counts": _format_counts(samples, meas_map),
}
if self.options.memory:
data["memory"] = [
"".join(str(x) for x in reversed(states)) for states in samples
]
results.append(
{
"shots": self.options.shots,
"success": True,
"status": JobStatus.DONE,
"data": data,
"header": {
"memory_slots": circuit.num_clbits,
"creg_sizes": [[reg.name, reg.size] for reg in circuit.cregs],
"qreg_sizes": [[reg.name, reg.size] for reg in circuit.qregs],
"name": circuit.name,
"metadata": circuit.metadata or {},
},
}
)
return Result.from_dict(
{
"backend_name": self._backend.name,
"backend_version": self._backend.version,
"qobj_id": id(self.circuits),
"job_id": self.job_id(),
"success": self.status_payload.status is JobStatus.DONE,
"results": results,
# Pass error message as metadata
"error": self.error_message,
}
)
def _build_memory_mapping(circuit: QuantumCircuit) -> Dict[int, Set[int]]:
"""Scan the circuit for measurement instructions and collect qubit to classical bits mappings.
Qubits can be mapped to multiple classical bits, possibly in different classical registers.
The returned map only maps qubits referenced in a `measure` operation in the passed circuit.
Qubits not targeted by a `measure` operation will not appear in the returned result.
Parameters:
circuit: the `QuantumCircuit` to analyze.
Returns:
the translation map for all measurement operations in the circuit.
Examples:
>>> qc = QuantumCircuit(2)
>>> qc.measure_all()
>>> _build_memory_mapping(qc)
{0: {0}, 1: {1}}
>>> qc = QuantumCircuit(2, 2)
>>> _ = qc.measure([0, 1], [1, 0])
>>> _build_memory_mapping(qc)
{0: {1}, 1: {0}}
>>> qc = QuantumCircuit(3, 2)
>>> _ = qc.measure([0, 1], [0, 1])
>>> _build_memory_mapping(qc)
{0: {0}, 1: {1}}
>>> qc = QuantumCircuit(4, 6)
>>> _ = qc.measure([0, 1, 2, 3], [2, 3, 4, 5])
>>> _build_memory_mapping(qc)
{0: {2}, 1: {3}, 2: {4}, 3: {5}}
>>> qc = QuantumCircuit(3, 4)
>>> qc.measure_all(add_bits=False)
>>> _build_memory_mapping(qc)
{0: {0}, 1: {1}, 2: {2}}
>>> qc = QuantumCircuit(3, 3)
>>> _ = qc.x(0)
>>> _ = qc.measure([0], [2])
>>> _ = qc.y(1)
>>> _ = qc.measure([1], [1])
>>> _ = qc.x(2)
>>> _ = qc.measure([2], [0])
>>> _build_memory_mapping(qc)
{0: {2}, 1: {1}, 2: {0}}
5 qubits in two registers:
>>> from qiskit import QuantumRegister, ClassicalRegister
>>> qr0 = QuantumRegister(2)
>>> qr1 = QuantumRegister(3)
>>> cr = ClassicalRegister(2)
>>> qc = QuantumCircuit(qr0, qr1, cr)
>>> _ = qc.measure(qr0, cr)
>>> _build_memory_mapping(qc)
{0: {0}, 1: {1}}
Multiple mapping of a qubit:
>>> qc = QuantumCircuit(3, 3)
>>> _ = qc.measure([0, 1], [0, 1])
>>> _ = qc.measure([0], [2])
>>> _build_memory_mapping(qc)
{0: {0, 2}, 1: {1}}
"""
field = namedtuple("field", "offset,size")
# quantum memory map
qregs = {}
offset = 0
for qreg in circuit.qregs:
qregs[qreg] = field(offset, qreg.size)
offset += qreg.size
# classical memory map
clregs = {}
offset = 0
for creg in circuit.cregs:
clregs[creg] = field(offset, creg.size)
offset += creg.size
qu2cl: DefaultDict[int, Set[int]] = defaultdict(set)
for instruction in circuit.data:
operation = instruction.operation
if operation.name == "measure":
for qubit, clbit in zip(instruction.qubits, instruction.clbits):
qubit_index = qregs[qubit.register].offset + qubit.index
clbit_index = clregs[clbit.register].offset + clbit.index
qu2cl[qubit_index].add(clbit_index)
return dict(qu2cl)
def _shot_to_int(
fluorescence_states: List[int], qubit_to_bit: Optional[Dict[int, Set[int]]] = None
) -> int:
"""Format the detected fluorescence states from a single shot as an integer.
This follows the Qiskit ordering convention, where bit 0 in the classical register is mapped
to bit 0 in the returned integer. The first classical register in the original circuit
represents the least-significant bits in the interger representation.
An optional translation map from the quantum to the classical register can be applied.
If given, only the qubits registered in the translation map are present in the return value,
at the index given by the translation map.
Parameters:
fluorescence_states: detected fluorescence states for this shot
qubit_to_bit: optional translation map from quantum register to classical register positions
Returns:
integral representation of the shot result, with the translation map applied.
Examples:
Without a translation map, the natural mapping is used (n -> n):
>>> _shot_to_int([1])
1
>>> _shot_to_int([0, 0, 1])
4
>>> _shot_to_int([0, 1, 1])
6
Swap qubits 1 and 2 in the classical register:
>>> _shot_to_int([1, 0, 1], {0: {0}, 1: {2}, 2: {1}})
3
If the map is partial, only the mapped qubits are present in the output:
>>> _shot_to_int([1, 0, 1], {1: {2}, 2: {1}})
2
One can translate into a classical register larger than the
qubit register.
Warning: the classical register is always initialized to 0.
>>> _shot_to_int([1], {0: {1}})
2
>>> _shot_to_int([0, 1, 1], {0: {3}, 1: {4}, 2: {5}}) == (0b110 << 3)
True
or with a map larger than the qubit space:
>>> _shot_to_int([1], {0: {0}, 1: {1}})
1
Consider the typical example of two quantum registers (the second one contains
ancilla qubits) and one classical register:
>>> from qiskit import QuantumRegister, ClassicalRegister
>>> qr_meas = QuantumRegister(2)
>>> qr_ancilla = QuantumRegister(3)
>>> cr = ClassicalRegister(2)
>>> qc = QuantumCircuit(qr_meas, qr_ancilla, cr)
>>> _ = qc.measure(qr_meas, cr)
>>> tr_map = _build_memory_mapping(qc)
We assume that a single shot gave the result:
>>> ancillas = [1, 1, 0]
>>> meas = [1, 0]
Then the corresponding output is 0b01 (measurement qubits mapped straight
to the classical register of length 2):
>>> _shot_to_int(meas + ancillas, tr_map) == 0b01
True
One can overwrite qr_meas[1] with qr_ancilla[0]:
>>> _ = qc.measure(qr_ancilla[0], cr[1])
>>> tr_map = _build_memory_mapping(qc)
>>> _shot_to_int(meas + ancillas, tr_map) == 0b11
True
"""
tr_map = qubit_to_bit or {}
if tr_map:
# allocate a zero-initialized classical register
# TODO: support pre-initialized classical registers
clbits = max(max(d) for d in tr_map.values()) + 1
creg = [0] * clbits
for src_index, dest_indices in tr_map.items():
# the translation map could map more than just the measured qubits
with contextlib.suppress(IndexError):
for dest_index in dest_indices:
creg[dest_index] = fluorescence_states[src_index]
else:
creg = fluorescence_states.copy()
return int((np.left_shift(1, np.arange(len(creg))) * creg).sum())
def _format_counts(
samples: List[List[int]], qubit_to_bit: Optional[Dict[int, Set[int]]] = None
) -> Dict[str, int]:
"""Format all shots results from a circuit evaluation.
The returned dictionary is compatible with Qiskit's `ExperimentResultData`
`counts` field.
Keys are hexadecimal string representations of the detected states, with the
optional `QuantumRegister` to `ClassicalRegister` applied. Values are the occurrences
of the keys.
Parameters:
samples: detected qubit fluorescence states for all shots
qubit_to_bit: optional quantum to classical register translation map
Returns:
collected counts, for `ExperimentResultData`.
Examples:
>>> _format_counts([[1, 0, 0], [0, 1, 0], [1, 0, 0]])
{'0x1': 2, '0x2': 1}
>>> _format_counts([[1, 0, 0], [0, 1, 0], [1, 0, 0]], {0: {2}, 1: {1}, 2: {0}})
{'0x4': 2, '0x2': 1}
"""
return dict(Counter(hex(_shot_to_int(shot, qubit_to_bit)) for shot in samples))
|
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/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
import numpy as np
a = np.array([1, 0])
b = np.array([0, 1])
print("Vectors :")
print("a = ", a)
print("\nb = ", b)
print("\nCross product of vectors a and b =")
print(np.cross(a, b))
print("------------------------------------")
x = np.array([[2, 6, 9], [2, 7, 3]])
y = np.array([[7, 5, 6], [3, 12, 3]])
print("\nMatrices :")
print("x =", x)
print("\ny =", y)
print("\nCross product of matrices x and y =")
print(np.cross(x, y))
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister
# If the name is not given, default name is taken
q=QuantumRegister(2)
q
# We can also give the name to the quantum register
q=QuantumRegister(2,'qr')
q
c=ClassicalRegister(2)
c=ClassicalRegister(2,'cr')
q=QuantumRegister(2,'qr')
c=ClassicalRegister(2,'cr')
qc=QuantumCircuit(q,c)
qc=QuantumCircuit(QuantumRegister(2,'qr'),ClassicalRegister(2,'cr'))
qc=QuantumCircuit(QuantumRegister(2,'qr'))
qc=QuantumCircuit(QuantumRegister(2))
qc=QuantumCircuit(QuantumRegister(2),ClassicalRegister(2))
qc=QuantumCircuit(2)
qc=QuantumCircuit(2,2)
qc
# In this example, we have given registers name
qc=QuantumCircuit(QuantumRegister(2,'qr'),ClassicalRegister(2,'cr'))
qc.draw(output="mpl")
print(qc.qubits)
print(qc.clbits)
# In this example, we have NOT given registers name
qc=QuantumCircuit(2,2)
qc.draw(output="mpl")
print(qc.qubits)
print(qc.clbits)
qc.qregs
qc.cregs
qc.num_qubits
qc.num_clbits
qc.clbits
qc.qubits
qc.width() #total number of qubits and classical bits
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, transpile
from qiskit.tools.visualization import plot_histogram, plot_state_city
import qiskit.quantum_info as qi
Aer.backends()
simulator = Aer.get_backend('aer_simulator')
# Create circuit
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
# Run and get memory
result = simulator.run(circ, shots=10, memory=True).result()
memory = result.get_memory(circ)
print(memory)
# Increase shots to reduce sampling variance
shots = 10000
# Stabilizer simulation method
sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer')
job_stabilizer = sim_stabilizer.run(circ, shots=shots)
counts_stabilizer = job_stabilizer.result().get_counts(0)
# Statevector simulation method
sim_statevector = Aer.get_backend('aer_simulator_statevector')
job_statevector = sim_statevector.run(circ, shots=shots)
counts_statevector = job_statevector.result().get_counts(0)
# Density Matrix simulation method
sim_density = Aer.get_backend('aer_simulator_density_matrix')
job_density = sim_density.run(circ, shots=shots)
counts_density = job_density.result().get_counts(0)
# Matrix Product State simulation method
sim_mps = Aer.get_backend('aer_simulator_matrix_product_state')
job_mps = sim_mps.run(circ, shots=shots)
counts_mps = job_mps.result().get_counts(0)
plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps],
title='Counts for different simulation methods',
legend=['stabilizer', 'statevector',
'density_matrix', 'matrix_product_state'])
from qiskit_aer import AerError
# Initialize a GPU backend
# Note that the cloud instance for tutorials does not have a GPU
# so this will raise an exception.
try:
simulator_gpu = Aer.get_backend('aer_simulator')
simulator_gpu.set_options(device='GPU')
except AerError as e:
print(e)
# Configure a single-precision statevector simulator backend
simulator = Aer.get_backend('aer_simulator_statevector')
simulator.set_options(precision='single')
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
print(counts)
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_statevector()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get statevector
result = simulator.run(circ).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state')
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_unitary()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get unitary
result = simulator.run(circ).result()
unitary = result.get_unitary(circ)
print("Circuit unitary:\n", np.asarray(unitary).round(5))
# Construct quantum circuit without measure
steps = 5
circ = QuantumCircuit(1)
for i in range(steps):
circ.save_statevector(label=f'psi_{i}')
circ.rx(i * np.pi / steps, 0)
circ.save_statevector(label=f'psi_{steps}')
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
data = result.data(0)
data
# Generate a random statevector
num_qubits = 2
psi = qi.random_statevector(2 ** num_qubits, seed=100)
# Set initial state to generated statevector
circ = QuantumCircuit(num_qubits)
circ.set_statevector(psi)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Use initilize instruction to set initial state
circ = QuantumCircuit(num_qubits)
circ.initialize(psi, range(num_qubits))
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get result data
result = simulator.run(circ).result()
result.data(0)
num_qubits = 2
rho = qi.random_density_matrix(2 ** num_qubits, seed=100)
circ = QuantumCircuit(num_qubits)
circ.set_density_matrix(rho)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random Clifford C
num_qubits = 2
stab = qi.random_clifford(num_qubits, seed=100)
# Set initial state to stabilizer state C|0>
circ = QuantumCircuit(num_qubits)
circ.set_stabilizer(stab)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random unitary
num_qubits = 2
unitary = qi.random_unitary(2 ** num_qubits, seed=100)
# Set initial state to unitary
circ = QuantumCircuit(num_qubits)
circ.set_unitary(unitary)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
import numpy as np
import pytest
from qiskit import Aer
from qiskit.algorithms.gradients import ReverseEstimatorGradient
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import Estimator
from qiskit.quantum_info import SparsePauliOp
np.random.seed(0)
max_parallel_threads = 12
gpu = False
method = "statevector_gpu"
def generate_circuit(nqubits):
ansatz = TwoLocal(
nqubits,
["rx", "ry", "rz"],
["cx"],
"linear",
reps=3,
flatten=True,
).decompose()
params = np.random.rand(ansatz.num_parameters)
return ansatz, params
def execute_statevector(benchmark, circuit, params):
backend_options = {
"method": method,
"precision": "double",
"max_parallel_threads": max_parallel_threads,
"fusion_enable": True,
"fusion_threshold": 14,
"fusion_max_qubit": 5,
}
circuit = circuit.bind_parameters(params)
backend = Aer.get_backend("statevector_simulator")
backend.set_options(**backend_options)
def evalfunc(backend, circuit):
backend.run(circuit).result()
benchmark(evalfunc, backend, circuit)
def execute_estimator(benchmark, circuit, obs, params):
estimator = Estimator()
def evalfunc(estimator, circuit, obs, params):
estimator.run([circuit], [obs], [params]).result()
benchmark(evalfunc, estimator, circuit, obs, params)
def execute_gradient(benchmark, circuit, obs, params):
estimator_grad = ReverseEstimatorGradient()
def evalfunc(estimator_grad, circuit, obs, params):
estimator_grad.run([circuit], [obs], [params]).result()
benchmark(evalfunc, estimator_grad, circuit, obs, params)
nqubits_list = range(4, 21)
@pytest.mark.parametrize("nqubits", nqubits_list)
def test_statevector(benchmark, nqubits):
benchmark.group = "qiskit_statevector"
circuit, params = generate_circuit(nqubits)
execute_statevector(benchmark, circuit, params)
# @pytest.mark.parametrize("nqubits", nqubits_list)
# def test_estimator(benchmark, nqubits):
# benchmark.group = "qiskit_estimator"
# circuit, params = generate_circuit(nqubits)
# obs = SparsePauliOp.from_list([("Z" * nqubits, 1)])
# execute_estimator(benchmark, circuit, obs, params)
# @pytest.mark.parametrize("nqubits", nqubits_list)
# def test_gradient(benchmark, nqubits):
# benchmark.group = "qiskit_gradient"
# circuit, params = generate_circuit(nqubits)
# obs = SparsePauliOp.from_list([("Z" * nqubits, 1)])
# execute_gradient(benchmark, circuit, obs, params)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
import random
circ = QuantumCircuit(40, 40)
# Initialize with a Hadamard layer
circ.h(range(40))
# Apply some random CNOT and T gates
qubit_indices = [i for i in range(40)]
for i in range(10):
control, target, t = random.sample(qubit_indices, 3)
circ.cx(control, target)
circ.t(t)
circ.measure(range(40), range(40))
# Create statevector method simulator
statevector_simulator = AerSimulator(method='statevector')
# Transpile circuit for backend
tcirc = transpile(circ, statevector_simulator)
# Try and run circuit
statevector_result = statevector_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(statevector_result.success))
print('Why not? {}'.format(statevector_result.status))
# Create extended stabilizer method simulator
extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer')
# Transpile circuit for backend
tcirc = transpile(circ, extended_stabilizer_simulator)
extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(extended_stabilizer_result.success))
small_circ = QuantumCircuit(2, 2)
small_circ.h(0)
small_circ.cx(0, 1)
small_circ.t(0)
small_circ.measure([0, 1], [0, 1])
# This circuit should give 00 or 11 with equal probability...
expected_results ={'00': 50, '11': 50}
tsmall_circ = transpile(small_circ, extended_stabilizer_simulator)
result = extended_stabilizer_simulator.run(
tsmall_circ, shots=100).result()
counts = result.get_counts(0)
print('100 shots in {}s'.format(result.time_taken))
plot_histogram([expected_results, counts],
legend=['Expected', 'Extended Stabilizer'])
# Add runtime options for extended stabilizer simulator
opts = {'extended_stabilizer_approximation_error': 0.03}
reduced_error = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
reduced_error_counts = reduced_error.get_counts(0)
print('100 shots in {}s'.format(reduced_error.time_taken))
plot_histogram([expected_results, reduced_error_counts],
legend=['Expected', 'Extended Stabilizer'])
print("The circuit above, with 100 shots at precision 0.03 "
"and default mixing time, needed {}s".format(int(reduced_error.time_taken)))
opts = {
'extended_stabilizer_approximation_error': 0.03,
'extended_stabilizer_mixing_time': 100
}
optimized = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken))
# We set these options here only to make the example run more quickly.
opts = {'extended_stabilizer_mixing_time': 100}
multishot = extended_stabilizer_simulator.run(
tcirc, shots=100, **opts).result()
print("100 shots took {} s".format(multishot.time_taken))
opts = {
'extended_stabilizer_measure_sampling': True,
'extended_stabilizer_mixing_time': 100
}
measure_sampling = extended_stabilizer_simulator.run(
circ, shots=100, **opts).result()
print("With the optimization, 100 shots took {} s".format(result.time_taken))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
# This cell is added by sphinx-gallery
# It can be customized to whatever you like
%matplotlib inline
!pip install pennylane
import pennylane as qml
from matplotlib import pyplot as plt
import numpy as np
import scipy
import networkx as nx
import copy
qubit_number = 4
qubits = range(qubit_number)
ising_graph = nx.cycle_graph(qubit_number)
print(f"Edges: {ising_graph.edges}")
nx.draw(ising_graph)
target_weights = [0.56, 1.24, 1.67, -0.79]
target_bias = [-1.44, -1.43, 1.18, -0.93]
def create_hamiltonian_matrix(n_qubits, graph, weights, bias):
full_matrix = np.zeros((2 ** n_qubits, 2 ** n_qubits))
# Creates the interaction component of the Hamiltonian
for i, edge in enumerate(graph.edges):
interaction_term = 1
for qubit in range(0, n_qubits):
if qubit in edge:
interaction_term = np.kron(interaction_term, qml.PauliZ.matrix)
else:
interaction_term = np.kron(interaction_term, np.identity(2))
full_matrix += weights[i] * interaction_term
# Creates the bias components of the matrix
for i in range(0, n_qubits):
z_term = x_term = 1
for j in range(0, n_qubits):
if j == i:
z_term = np.kron(z_term, qml.PauliZ.matrix)
x_term = np.kron(x_term, qml.PauliX.matrix)
else:
z_term = np.kron(z_term, np.identity(2))
x_term = np.kron(x_term, np.identity(2))
full_matrix += bias[i] * z_term + x_term
return full_matrix
# Prints a visual representation of the Hamiltonian matrix
ham_matrix = create_hamiltonian_matrix(qubit_number, ising_graph, target_weights, target_bias)
plt.matshow(ham_matrix, cmap="hot")
plt.show()
low_energy_state = [
(-0.054661080280306085 + 0.016713907320174026j),
(0.12290003656489545 - 0.03758500591109822j),
(0.3649337966440005 - 0.11158863596657455j),
(-0.8205175732627094 + 0.25093231967092877j),
(0.010369790825776609 - 0.0031706387262686003j),
(-0.02331544978544721 + 0.007129899300113728j),
(-0.06923183949694546 + 0.0211684344103713j),
(0.15566094863283836 - 0.04760201916285508j),
(0.014520590919500158 - 0.004441887836078486j),
(-0.032648113364535575 + 0.009988590222879195j),
(-0.09694382811137187 + 0.02965579457620536j),
(0.21796861485652747 - 0.06668776658411019j),
(-0.0027547112135013247 + 0.0008426289322652901j),
(0.006193695872468649 - 0.0018948418969390599j),
(0.018391279795405405 - 0.005625722994009138j),
(-0.041350974715649635 + 0.012650711602265649j),
]
res = np.vdot(low_energy_state, (ham_matrix @ low_energy_state))
energy_exp = np.real_if_close(res)
print(f"Energy Expectation: {energy_exp}")
ground_state_energy = np.real_if_close(min(np.linalg.eig(ham_matrix)[0]))
print(f"Ground State Energy: {ground_state_energy}")
def state_evolve(hamiltonian, qubits, time):
U = scipy.linalg.expm(-1j * hamiltonian * time)
qml.QubitUnitary(U, wires=qubits)
def qgrnn_layer(weights, bias, qubits, graph, trotter_step):
# Applies a layer of RZZ gates (based on a graph)
for i, edge in enumerate(graph.edges):
qml.MultiRZ(2 * weights[i] * trotter_step, wires=(edge[0], edge[1]))
# Applies a layer of RZ gates
for i, qubit in enumerate(qubits):
qml.RZ(2 * bias[i] * trotter_step, wires=qubit)
# Applies a layer of RX gates
for qubit in qubits:
qml.RX(2 * trotter_step, wires=qubit)
def swap_test(control, register1, register2):
qml.Hadamard(wires=control)
for reg1_qubit, reg2_qubit in zip(register1, register2):
qml.CSWAP(wires=(control, reg1_qubit, reg2_qubit))
qml.Hadamard(wires=control)
# Defines some fixed values
reg1 = tuple(range(qubit_number)) # First qubit register
reg2 = tuple(range(qubit_number, 2 * qubit_number)) # Second qubit register
control = 2 * qubit_number # Index of control qubit
trotter_step = 0.01 # Trotter step size
# Defines the interaction graph for the new qubit system
new_ising_graph = nx.complete_graph(reg2)
print(f"Edges: {new_ising_graph.edges}")
nx.draw(new_ising_graph)
def qgrnn(weights, bias, time=None):
# Prepares the low energy state in the two registers
qml.QubitStateVector(np.kron(low_energy_state, low_energy_state), wires=reg1 + reg2)
# Evolves the first qubit register with the time-evolution circuit to
# prepare a piece of quantum data
state_evolve(ham_matrix, reg1, time)
# Applies the QGRNN layers to the second qubit register
depth = time / trotter_step # P = t/Delta
for _ in range(0, int(depth)):
qgrnn_layer(weights, bias, reg2, new_ising_graph, trotter_step)
# Applies the SWAP test between the registers
swap_test(control, reg1, reg2)
# Returns the results of the SWAP test
return qml.expval(qml.PauliZ(control))
N = 15 # The number of pieces of quantum data that are used for each step
max_time = 0.1 # The maximum value of time that can be used for quantum data
rng = np.random.default_rng(seed=42)
def cost_function(weight_params, bias_params):
# Randomly samples times at which the QGRNN runs
times_sampled = rng.random(size=N) * max_time
# Cycles through each of the sampled times and calculates the cost
total_cost = 0
for dt in times_sampled:
result = qgrnn_qnode(weight_params, bias_params, time=dt)
total_cost += -1 * result
return total_cost / N
# Defines the new device
qgrnn_dev = qml.device("default.qubit", wires=2 * qubit_number + 1)
# Defines the new QNode
qgrnn_qnode = qml.QNode(qgrnn, qgrnn_dev)
steps = 20
optimizer = qml.AdamOptimizer(stepsize=0.5)
weights = rng.random(size=len(new_ising_graph.edges)) - 0.5
bias = rng.random(size=qubit_number) - 0.5
initial_weights = copy.copy(weights)
initial_bias = copy.copy(bias)
for i in range(0, steps):
(weights, bias), cost = optimizer.step_and_cost(cost_function, weights, bias)
# Prints the value of the cost function
if i % 5 == 0:
print(f"Cost at Step {i}: {cost}")
print(f"Weights at Step {i}: {weights}")
print(f"Bias at Step {i}: {bias}")
print("---------------------------------------------")
new_ham_matrix = create_hamiltonian_matrix(
qubit_number, nx.complete_graph(qubit_number), weights, bias
)
init_ham = create_hamiltonian_matrix(
qubit_number, nx.complete_graph(qubit_number), initial_weights, initial_bias
)
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(6, 6))
axes[0].matshow(ham_matrix, vmin=-7, vmax=7, cmap="hot")
axes[0].set_title("Target", y=1.13)
axes[1].matshow(init_ham, vmin=-7, vmax=7, cmap="hot")
axes[1].set_title("Initial", y=1.13)
axes[2].matshow(new_ham_matrix, vmin=-7, vmax=7, cmap="hot")
axes[2].set_title("Learned", y=1.13)
plt.subplots_adjust(wspace=0.3, hspace=0.3)
plt.show()
# We first pick out the weights of edges (1, 3) and (2, 0)
# and then remove them from the list of target parameters
weights_noedge = []
weights_edge = []
for ii, edge in enumerate(new_ising_graph.edges):
if (edge[0] - qubit_number, edge[1] - qubit_number) in ising_graph.edges:
weights_edge.append(weights[ii])
else:
weights_noedge.append(weights[ii])
print("Target parameters Learned parameters")
print("Weights")
print("-" * 41)
for ii_target, ii_learned in zip(target_weights, weights_edge):
print(f"{ii_target : <20}|{ii_learned : >20}")
print("\nBias")
print("-"*41)
for ii_target, ii_learned in zip(target_bias, bias):
print(f"{ii_target : <20}|{ii_learned : >20}")
print(f"\nNon-Existing Edge Parameters: {[val.unwrap() for val in weights_noedge]}")
|
https://github.com/tula3and/qoupang
|
tula3and
|
from qiskit import *
# from qiskit import IBMQ
# IBMQ.save_account('<API Token>')
# provider = IBMQ.load_account()
# backend = IBMQ.get_provider(hub='ibm-q-kaist', group='internal', project='default').backends.ibmq_manhattan
backend = Aer.get_backend('qasm_simulator')
q = QuantumRegister(48)
c = ClassicalRegister(48)
circuit = QuantumCircuit(q,c)
circuit.h(q)
for i in range(47):
circuit.cx(q[i], q[47])
circuit.measure(q,c)
import string
table = string.ascii_uppercase + string.ascii_lowercase + string.digits
def hash8():
hash_result = ''
result = execute(circuit, backend, shots=1).result()
count = result.get_counts(circuit)
bits = max(count, key=lambda i: count[i])
start = 0
end = 6
while (end <= 48):
rand = int(bits[start:end], 2) % len(table)
start += 6
end += 6
hash_result += table[rand]
return hash_result
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
|
https://github.com/hritiksauw199/Qiskit-textbook-solutions
|
hritiksauw199
|
from qiskit import QuantumCircuit
import qiskit.quantum_info as qi
qc_AB = QuantumCircuit(1)
qc_AB.h(0)
qc_AB.s(0)
qc_AB.z(0)
qc_AB.draw()
psi_AB = qi.Statevector.from_instruction(qc_AB)
psi_AB.draw('latex', prefix='|\\psi_{AB}\\rangle = ')
rho_AB = qi.DensityMatrix.from_instruction(qc_AB)
rho_AB.draw('latex', prefix='\\rho_{AB} = ')
from qiskit.visualization import plot_state_city
plot_state_city(rho_AB.data, title='Density Matrix')
qc_AB = QuantumCircuit(2)
qc_AB.h(0)
qc_AB.h(1)
qc_AB.draw()
psi_AB = qi.Statevector.from_instruction(qc_AB)
psi_AB.draw('latex', prefix='|\\psi_{AB}\\rangle = ')
rho_AB = qi.DensityMatrix.from_instruction(qc_AB)
rho_AB.draw('latex', prefix='\\rho_{AB} = ')
from qiskit.visualization import plot_state_city
plot_state_city(rho_AB.data, title='Density Matrix')
qc_AB = QuantumCircuit(2)
qc_AB.h(0)
qc_AB.h(1)
qc_AB.draw()
psi_AB = qi.Statevector.from_instruction(qc_AB)
psi_AB.draw('latex', prefix='|\\psi_{AB}\\rangle = ')
rho_AB = qi.DensityMatrix.from_instruction(qc_AB)
rho_AB.draw('latex', prefix='\\rho_{AB} = ')
rho_B = qi.partial_trace(rho_AB,[0])
rho_A = qi.partial_trace(rho_AB,[1])
display(rho_B.draw('latex', prefix=" \\rho_{B} = "),
rho_A.draw('latex', prefix=" \\rho_{A} = "))
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/IffTech/UCLA-Qiskit-Intro
|
IffTech
|
# You'll always start off any Quantum circuit with...QuantumCircuit
from qiskit import QuantumCircuit
# Every quantum circuit has some number of quantum registers and classical registers that you get to define in advance
# You can either pass one integer in to denote a fixed number of quantum registers
# OR you can pass in two numbers, the first being the # of quantum registers and the second being the number of classical registers
qc = QuantumCircuit(5) # creates empty circuit with 5 quantum registers
qc = QuantumCircuit(3,1) # creates empty circuit with 3 quantum registers, 1 classical register
# For this part of the workshop, we'll start simple with a one-qubit circuit and gradually work towards
# larger qubit circuits
qc = QuantumCircuit(1,1)
# A blank circuit isn't really useful to us so lets add some gates!
# There are two ways to add gates, the easier way is to do it like so:
## Apply an X gate to qubit 0 (the only qubit in this circuit)
qc.x(0)
## Or to .append() them to the circuit
## The [0] tells qiskit to apply the gate to the 0th qubit (the first).
from qiskit.circuit.library import XGate
qc.append(XGate(), [0])
# to see the circuit, we can just use the .draw() method
qc.draw()
# Notice how despite two different methods for adding gates, we still see the same gate!
# For a "shinier" representation of our circuit, we can tell Qiskit to leverage matplotlib
qc.draw(output='mpl')
# Awesome! Your first quantum circuit!
# Before we actually run this on something, lets perform some "sanity checks"
# We know that applying two pauli operators back to back should return the qubit to its original state (it essentially undoes itself)
# So we expect the unitary matrix to be the identity.
# We can access this information like so
# Credit to Chistopher J. Wood, lead Qiskit Aer developer: https://quantumcomputing.stackexchange.com/a/14283
from qiskit.quantum_info import Operator
op = Operator(qc)
op.data
# We can also see what happens to a qubit initialized to |0> when it goes through the unitary
from qiskit.quantum_info import Statevector
# .from_instruction automatically defaults to |0>
state_vec = Statevector.from_instruction(qc)
state_vec.data
# so we remain in the |0> state
# But a circuit that just ends up being an identity matrix is pretty boring. Why don't we make things more fun with our old friend the
# Hadamard gate?
# Lets create a new circuit and apply it:
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.draw(output='mpl')
# Now lets see what the unitary is
Operator(qc).data
# And lets see what happens when we send in a qubit with |0>
state_vec = Statevector.from_instruction(qc)
state_vec.data
# Sometimes it's nice to visualize the states themselves
# We can always pull out our trusty bloch sphere for one qubit states:
# You'll see in a bit why it's called "plot_bloch_multivector"
# There IS a single plot_bloch_vector but it requires you to convert your state vector into
# cartesian/polar coordinates, which is a lot of unnecessary overhead for what we want to do
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(state_vec)
# This allows you to view the density matrix formulation,
# you can see the real and imaginary components of the density matrix
from qiskit.visualization import plot_state_city
plot_state_city(state_vec)
# now lets actually "run" our circuit
# In real world quantum computation, we know the only way to get useful information out of the quantum algorithm is to perform
# a measurement, which collapses the qubit state to one of two values.
# Let's go ahead and add a measurement to our circuit, telling Qiskit to store the result in the classical register
qc.measure(0,0)
qc.draw(output='mpl')
# You can either run your circuit on an ACTUAL quantum computer
# (which means you'll have to create an IBM Q account) or
# most of the time, you can run in on a simulator (which is what we'll do here).
from qiskit.providers.aer import AerSimulator
# There's a wide variety of simulators you can select, see: https://qiskit.org/documentation/stubs/qiskit.providers.aer.AerSimulator.html#qiskit.providers.aer.AerSimulator
# For the majority of purposes, statevector will do fine
backend = AerSimulator(method='statevector')
# shots defines how many times your circuit should run
job = backend.run(qc, shots=1024)
# Every time you run a circuit on a backend (real or simulated) you'll get a "Job"
# that you can then access results from
result = job.result()
# Here's the counts on each type of measurement
result.get_counts()
# we can also plot the probabilities via histogram
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts())
# You can also save the state of the quantum circuit AFTER running it on the simulators
# Let's add the following to our quantum circuit
qc.save_state() # <- you can save the statevector after running the experiment and view it later
job = backend.run(qc, shots=1024)
result = job.result()
result.get_statevector()
# not really that interesting
qc = QuantumCircuit(1,1)
qc.h(0)
# note that we can place the save state at an intermediate point as well!
qc.save_state()
qc.measure(0,0)
job = backend.run(qc, shots=1024)
result = job.result()
result.get_statevector()
# So far we've always started in |0>
# What if we want to start in some other initial state, like |1> or (|0> + |1>)/sqrt(2)?
# Qiskit lets us do that with ease!
# for a basis state we can do the following
qc = QuantumCircuit(1) # just for demonstration purposes, we don't need to create a classical register here
qc.initialize('1')
qc.draw(output='mpl')
# we can check it's |1> through the following:
Statevector.from_instruction(qc)
# For a non 0/1 basis state, (some kind of superposition perhaps) we can do the following
from numpy import sqrt
qc = QuantumCircuit(1) # just for demonstration purposes, we don't need to create a classical register here
qc.initialize([1j/sqrt(2), 1/sqrt(2)])
qc.draw(output='mpl')
Statevector.from_instruction(qc)
# You may want to build your own gates from matrices at some point
# Qiskit makes this a cinch with UnitaryGate
import numpy as np
custom_gate_matrix = np.eye(2) # 2x2 identity matrix
qc = QuantumCircuit(1)
from qiskit.extensions import UnitaryGate
custom_gate = UnitaryGate(custom_gate_matrix, label="Gate Name Here")
qc.append(custom_gate, [0])
qc.draw(output='mpl')
# The X, Y, and Z gates are all based on the Pauli matrices and are known for making rotations of pi radians around the bloch sphere
# on each respective axis.
# What if I want to rotate some fractional amount instead of pi?
# Each X,Y,Z gate has a version capable of accepting an argument theta that allows you to explicitly define the amount of rotation
# desired on any axis
qc = QuantumCircuit(1)
import numpy as np
qc.rx(np.pi/3, 0)
qc.draw(output='mpl')
state_vec = Statevector.from_instruction(qc)
plot_bloch_multivector(state_vec)
qc = QuantumCircuit(1)
import numpy as np
qc.ry(np.pi/3, 0)
qc.draw(output='mpl')
state_vec = Statevector.from_instruction(qc)
plot_bloch_multivector(state_vec)
qc = QuantumCircuit(1)
import numpy as np
qc.rz(np.pi/3, 0)
qc.draw(output='mpl')
state_vec = Statevector.from_instruction(qc)
plot_bloch_multivector(state_vec)
# We can create a two-qubit circuit
qc = QuantumCircuit(2,2)
# Single qubit gates can be applied as usual
qc.z(0)
qc.x(1)
# You can also apply two-qubit gates like so, with the first integer denoting the "control" qubit
# and the second denoting the target
qc.cx(0,1)
qc.draw(output='mpl')
# lets see what the statevector result looks like
state_vec = Statevector.from_instruction(qc)
state_vec
# The current state is separable and can be visualized with TWO bloch spheres
plot_bloch_multivector(state_vec)
# the statecity plot should also work
plot_state_city(state_vec)
# We can still obtain the unitary
Operator(qc).data
# And the syntax for running simulations does not change as well
## Let's add a measurement to the last operators
## For multiple measurements you can use the "measure_all" method
## If you declared the circuit with no quantum registers, like
## QuantumCircuit(2), measure_all will create classical registers automatically.
## If you declared something like QuantumCircuit(2,2) and classical reigsters ALREADY exist
## then you can invoke it with .measure_all(add_bits=False), otherwise, it'll continue to create
## extra classical registers which you don't need
qc.measure_all(add_bits=False)
qc.draw(output='mpl')
backend = AerSimulator(method='statevector')
job = backend.run(qc, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# You can still save the intermediate statevector as well
qc = QuantumCircuit(2,2)
# Single qubit gates can be applied as usual
qc.z(0)
qc.x(1)
qc.cx(0,1)
qc.save_statevector()
qc.measure_all(add_bits=False)
qc.draw(output='mpl')
backend = AerSimulator(method='statevector')
job = backend.run(qc, shots=1024)
result = job.result()
result.get_statevector()
# You can choose one qubit to initalize to a custom state:
qc = QuantumCircuit(2,2)
# Set qubit 0 to be in equal superposition
qc.initialize([1/sqrt(2), 1/sqrt(2)], 0)
qc.draw(output='mpl')
# You can also set the entire system to be in a certain state
qc = QuantumCircuit(2,2)
# Set the system to be in a Bell State, note that I don't have to state the qubits being targeted
# (Although in Qiskit examples, they'll usually be explicit with which qubits were selected)
qc.initialize([1/sqrt(2), 0, 0, 1/sqrt(2)])
qc.draw(output='mpl')
# For initalizations where you just want to pick between starting with |0> or |1> you can do the following:
qc = QuantumCircuit(2,2)
# Keep in mind this sets the SECOND qubit to 1, and the FIRST qubit to 0
qc.initialize("10")
qc.draw(output='mpl')
Statevector.from_instruction(qc)
# You can also just pass in an integer
qc = QuantumCircuit(2,2)
# Set qubit 0 to be in equal superposition
qc.initialize(3)
qc.draw(output='mpl')
Statevector.from_instruction(qc)
# create a quantum circuit to play around with
qc = QuantumCircuit(2)
# We create a custom gate
custom_gate = UnitaryGate(np.eye(2), label="Identity")
# Then we get the controlled version, with 1 qubit for control and the qubit in question needing to be in the |1> state to turn on
# the gate
controlled_custom_gate = custom_gate.control(num_ctrl_qubits=1, label="Controlled Identity")
# Add the gate
# The [0,1] here tells qiskit we want qubit 0 to be control, qubit 1 to be the target
qc.append(controlled_custom_gate, [0,1])
qc.draw(output='mpl')
# Note we can pass in ctrl_state as an integer OR as a string of 1s and 0s
controlled_custom_gate = custom_gate.control(num_ctrl_qubits=1, ctrl_state=0, label="Controlled Identity")
qc.append(controlled_custom_gate, [0,1])
qc.draw(output='mpl')
## When an entangled state is created, by definition it is NON-SEPERABLE
## (you cannot split the vector that constitutes it into two separate vectors).
## This does put a wrench into visualization but only partly.
## Observe the following Bell state generating circuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.draw(output='mpl')
# We get the statevector
state_vec = Statevector.from_instruction(qc)
# and try to visualize it...
plot_bloch_multivector(state_vec)
# BEHOLD! You don't get anything
# This is generally the case whenever you run into entanglement, Qiskit will fail to properly display seperate bloch spheres (because it's impossible!)
# You may also still get "something" but the vector is shorter or significantly longer than what it should be (visually)
# However, the Density Matrix can give you more information....
# But we still have one way of seeing things, the state city diagram
plot_state_city(state_vec)
## You can actually figure out if a system has some degree of entanglment by using the trace and reducing the degrees of freedom to individual qubits
## Credit to "Quantum Mechanic" on Stack Overflow https://quantumcomputing.stackexchange.com/questions/17580/how-to-calculate-the-amount-of-entanglement-for-each-qubit-in-a-quantum-computer
# We can define even larger circuits...
qc = QuantumCircuit(5,5)
# apply some single qubit gates
qc.rz(np.pi/8, 1)
qc.z(0)
qc.y(3)
qc.x(2)
# apply a CCX or Toffoli gate with 0 and 1 as control qubits, 2 as the target qubit
qc.ccx(0,1,2)
# apply a controlled swap gate
qc.cswap(2,3,4)
qc.draw(output='mpl')
# lets see what the statevector result looks like
state_vec = Statevector.from_instruction(qc)
state_vec
# can still see what the unitary matrix looks like
unitary_mat = Operator(qc)
unitary_mat
# Should be able to visualize all the qubits too!
plot_bloch_multivector(state_vec)
# Should be able to visualize all the qubits too!
plot_state_city(state_vec)
# Rules for simulation remain the same
## Add measurement gets
qc.measure_all(add_bits=False)
job = backend.run(qc, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# We can still initialize our circuits to custom states
qc = QuantumCircuit(5,5)
qc.initialize(4) # initialized to |00100>
qc.draw(output='mpl')
Statevector.from_instruction(qc)
# Now that we have all these extra qubits, we can do some pretty crazy stuff with defining controlled gates.
# For example, lets say we want a controlled X gate that only applies when the control qubits have the state "0011"
# In such a case we can just piggyback off of the fact that Qiskit already has an X gate and build up from it
from qiskit.circuit.library import XGate
# keep in mind that the ordering is flipped for qubits in qiskit!
custom_controlled_X = XGate().control(num_ctrl_qubits=4, ctrl_state="0011", label="Crazy Controlled X")
qc = QuantumCircuit(5)
qc.append(custom_controlled_X, [0,1,2,3,4])
qc.draw(output='mpl')
# Let's test the circuit.
# We expect that for any other initialized state, nothing should happen and the initialied state stays as is
qc = QuantumCircuit(5)
qc.initialize(0)
qc.append(custom_controlled_X, [0,1,2,3,4])
Statevector.from_instruction(qc)
plot_bloch_multivector(Statevector.from_instruction(qc))
# ...and if we set the initial state right then the gate gets applied
qc = QuantumCircuit(5)
qc.initialize("00011")
qc.append(custom_controlled_X, [0,1,2,3,4])
Statevector.from_instruction(qc)
plot_bloch_multivector(Statevector(qc))
# Note that we flipped qubit 4, the one we wanted to target!
# Sometimes you'll find that it's easier when building custom gates to go ahead and build it out in a separate circuit and then treat
# that circuit as a whole gate entirely (kind of like when you write a large computer program and you call multiple functions,
# or when you have a long essay with lots of individual paragraphs you work on)
# We can do that like so (taken from https://qiskit.org/documentation/tutorials/circuits_advanced/01_advanced_circuits.html#Composite-Gates
# slightly modified for this tutorial)
sub_circ = QuantumCircuit(2, name='sub_circ')
sub_circ.h(0)
# theta is set to 1, with control qubit 0 and target 1
sub_circ.crz(1,0,1)
# A barrier is usually used as a way to explicitly split up certain parts of the circuit for visual purposes
# in most tutorials, although it actually has a role in telling the transpiler not to optimize
# "The barrier acts as a directive for circuit compilation to separate pieces of a circuit so that any optimizations or
# This only comes into play when using the transpile or execute functions in Qiskit (execute includes a transpile step)."
# re-writes are constrained to only act between barriers (and if there are no barriers they act on the whole circuit). - Christopher J. Wood, Lead Developer for Qiskit Aer
sub_circ.barrier()
sub_circ.id(1)
# The U gate takes several parameters and is a kind of universal gate capable of performing a rotation in ANY direction
sub_circ.u(1,2,-2,0)
sub_circ.draw(output='mpl')
# Convert to a gate and stick it into an arbitrary place in the bigger circuit
sub_inst = sub_circ.to_instruction()
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.append(sub_inst, [1,2])
qc.draw(output='mpl')
# register naming code obtained from:
# https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
# credits to Ali Javadi for their answer
# label our qubits
# Note that you can also explicitly declare your Quantum and Classical Registers as separate entities and then
# initialize a QuantumCircuit with them, although QuantumCircuit(n,m) will do just fine as well if you don't care much for register labeling
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
n = 3
function_inputs = QuantumRegister(n, "x")
target = QuantumRegister(1, "f(x)")
# store our results here
classical_registers = ClassicalRegister(3)
circuit = QuantumCircuit(function_inputs, target, classical_registers)
# Initialization phase
# apply Hadamards to three qubits
circuit.h(0)
circuit.h(1)
circuit.h(2)
# Get the last hadamard in the kickback position
circuit.x(3)
circuit.h(3)
circuit.draw(output="mpl")
# visualize the current state after execution
plot_bloch_multivector(Statevector.from_instruction(circuit))
circuit.barrier()
circuit.draw(output='mpl')
# Create an Oracle
# In this case, we want to solve for (x0 AND x1 AND x2)
# Note that when the circuit actually gets run on hardware, the gate actually gets
# broken down into smaller gates (so this one may get broken down in CCX gates, and even further
# to CX and other single qubit gates) that are native to the hardware (the hardware
# may only support
# a certain subset of gates, although that subset is capable of generating any other
# gate's operations
# Inspiration for Oracle from: https://cnot.io/quantum_algorithms/grover/grovers_algorithm.html
# as well as Ryan LaRose's QuIC Seminar notes on Grover's Algorithm:
# https://www.ryanlarose.com/uploads/1/1/5/8/115879647/grover.pdf
circuit.mcx([0,1,2],3)
circuit.draw(output="mpl")
# oracle complete, put the barrier down
circuit.barrier()
circuit.draw(output="mpl")
# Oracle implementation taken from Eric Li (https://you.stonybrook.edu/qcomputing/2018/07/18/2-3-qubit-grovers-algorithm/)
# and Martin Vesely (https://quantumcomputing.stackexchange.com/questions/9531/grover-diffusion-operator-for-a-3-qubit-system)
for i in range(3):
circuit.h(i)
# 2|0><0| - I
for i in range(3):
circuit.x(i)
circuit.h(2)
circuit.mcx([0,1],2)
circuit.h(2)
for i in range(3):
circuit.x(i)
for i in range(3):
circuit.h(i)
circuit.barrier()
circuit.draw(output="mpl")
# get results
# .measure_all fails here because there isn't an equal number of classical regsiters, so we have to resort to the next best thing
# circuit.measure_all(add_bits=False)
# Need to explicitly declare which quantum bit gets measured to which classical bit
circuit.measure([0,1,2],[0,1,2])
backend = AerSimulator(method='statevector')
job = backend.run(circuit, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# Create a custom gate representing the oracle
from qiskit.circuit.library import MCXGate
oracle = MCXGate(num_ctrl_qubits=3, label="oracle", ctrl_state="111")
# create a custom gate representing the diffusion operator
grover_op_circ = QuantumCircuit(3, name="Grover's Operator")
for i in range(3):
grover_op_circ.h(i)
# 2|0><0| - I
for i in range(3):
grover_op_circ.x(i)
grover_op_circ.h(2)
grover_op_circ.mcx([0,1],2)
grover_op_circ.h(2)
for i in range(3):
grover_op_circ.x(i)
for i in range(3):
grover_op_circ.h(i)
# Now rebuild the original circuit using our newly defined custom gates
n = 3
function_inputs = QuantumRegister(n, "x")
target = QuantumRegister(1, "f(x)")
# store our results here
classical_registers = ClassicalRegister(3)
qc = QuantumCircuit(function_inputs, target, classical_registers)
# apply Hadamards to three qubits
qc.h(0)
qc.h(1)
qc.h(2)
# Get the last hadamard in the kickback position
qc.x(3)
qc.h(3)
qc.barrier()
qc.append(oracle, [0,1,2,3])
qc.barrier()
qc.append(grover_op_circ.decompose(), [0,1,2])
qc.draw(output='mpl')
# now we apply the same things again
qc.barrier()
qc.append(oracle, [0,1,2,3])
qc.barrier()
qc.append(grover_op_circ.to_instruction(), [0,1,2])
qc.draw(output='mpl')
# Now let's see how the results hold up
qc.measure([0,1,2],[0,1,2])
backend = AerSimulator(method='statevector')
job = backend.run(qc.decompose(), shots=1024)
result = job.result()
plot_histogram(result.get_counts())
qc.draw(output='mpl')
# Create Sqrt iSWAP gate
from qiskit.circuit.library import ZGate
# Obtained from: https://github.com/quantumlib/Cirq/blob/a22269dfe41b0da78243bbd210a915d26cc7d25f/cirq-core/cirq/ops/swap_gates.py#L166
sqrt_iSWAP_circ = QuantumCircuit(2, name="sqrt(iSWAP)")
sqrt_iSWAP_circ.cx(0,1)
sqrt_iSWAP_circ.h(0)
sqrt_iSWAP_circ.cx(1,0)
sqrt_iSWAP_circ.append(ZGate().power(0.25), [0])
sqrt_iSWAP_circ.cx(1,0)
sqrt_iSWAP_circ.append(ZGate().power(-0.25), [0])
sqrt_iSWAP_circ.h(0)
sqrt_iSWAP_circ.cx(0,1)
sqrt_iSWAP_circ.draw(output='mpl')
# Create the full IonQ supported Given's Rotation
from qiskit.circuit import Parameter
import numpy as np
# You can create a Parameter that you later bind values to during execution
theta = Parameter('θ')
givens_circ = QuantumCircuit(2, name="Givens Rotation")
givens_circ.append(sqrt_iSWAP_circ.to_instruction(), [0,1])
givens_circ.rz(-theta, 0)
givens_circ.rz(theta + np.pi, 1)
givens_circ.append(sqrt_iSWAP_circ.to_instruction(), [0,1])
givens_circ.rz(np.pi, 1)
givens_circ.draw(output='mpl')
print(givens_circ.parameters)
# Full simulation
qc = QuantumCircuit(2)
# Initialize the circuit to be a full, even superpositon (equivalent of putting two hadamards)
full_superposition = [1/np.sqrt(4)] * 4
qc.initialize(full_superposition)
qc.append(givens_circ.bind_parameters({theta: np.pi/3}).to_instruction(), [0,1])
qc.draw(output='mpl')
# hmmm, close but not quite right
np.round(Statevector.from_instruction(qc).data.reshape(4,1), 3)
# taken from https://medium.com/mdr-inc/checking-the-unitary-matrix-of-the-quantum-circuit-on-qiskit-5968c6019a45
# All credit to Yuchiro Minato
from qiskit import Aer, execute
# The Unitary simulator only works with circuits that have NO MEASUREMENT GATES
# but allows you to get the unitary representing the matrix.
# Operator() fails to work if your circuit contains a custom initialization value
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
# This unitary comes from the correct implementation from: https://github.com/QC-at-Davis/GroveFold/blob/feature/vectoradditionfrombiomoleculesusingbiopython/src/scripts/IonQ-Givens-Cirq-Simulation.ipynb
# (literally copied and pasted here, then converted back into a matrix)
x =np.array([[-1. -1.34015774e-16j, 0. +0.00000000e+00j,
0. +0.00000000e+00j, 0. -3.72797834e-17j],
[ 0. +0.00000000e+00j, -0.5 -5.88784672e-17j,
0.8660254+1.17756934e-16j, 0. +0.00000000e+00j],
[ 0. +0.00000000e+00j, -0.8660254+5.88784672e-17j,
-0.5 +1.96261557e-16j, 0. +0.00000000e+00j],
[ 0. -2.29934717e-17j, 0. -0.00000000e+00j,
0. -0.00000000e+00j, -1. +3.51298275e-16j]])
# Note certain entries seem to be flipped...
np.round(x, 3)
y = np.array([1/sqrt(4)] * 4).reshape(4, 1)
x @ y
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Test circuits and reference outputs for standard algorithms.
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
# Backwards compatibility for Terra <= 0.13
if not hasattr(QuantumCircuit, 'i'):
QuantumCircuit.i = QuantumCircuit.iden
def grovers_circuit(final_measure=True, allow_sampling=True):
"""Testing a circuit originated in the Grover algorithm"""
circuits = []
# 6-qubit grovers
qr = QuantumRegister(6)
if final_measure:
cr = ClassicalRegister(2)
regs = (qr, cr)
else:
regs = (qr, )
circuit = QuantumCircuit(*regs)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.x(qr[2])
circuit.x(qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.cx(qr[1], qr[3])
circuit.ccx(qr[2], qr[3], qr[4])
circuit.cx(qr[1], qr[3])
circuit.x(qr[0])
circuit.cx(qr[0], qr[2])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[4])
circuit.ccx(qr[0], qr[1], qr[4])
circuit.h(qr[4])
circuit.x(qr[0])
circuit.x(qr[1])
circuit.x(qr[4])
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[4])
if final_measure:
circuit.barrier(qr)
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
if not allow_sampling:
circuit.barrier(qr)
circuit.i(qr)
circuits.append(circuit)
return circuits
def grovers_counts(shots, hex_counts=True):
"""Reference counts for Grovers algorithm"""
targets = []
if hex_counts:
# 6-qubit grovers
targets.append({'0x0': 5 * shots / 8, '0x1': shots / 8,
'0x2': shots / 8, '0x3': shots / 8})
else:
# 6-qubit grovers
targets.append({'00': 5 * shots / 8, '01': shots / 8,
'10': shots / 8, '11': shots / 8})
return targets
def teleport_circuit():
"""Testing a circuit originated in the teleportation algorithm"""
circuits = []
# Classic 3-qubit teleportation
qr = QuantumRegister(3)
c0 = ClassicalRegister(1)
c1 = ClassicalRegister(1)
c2 = ClassicalRegister(1)
# Compiles to creg order [c2, c1, c0]
circuit = QuantumCircuit(qr, c0, c1, c2)
# Teleport the |0> state from qr[0] to qr[2]
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.barrier(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.measure(qr[0], c0[0])
circuit.measure(qr[1], c1[0])
circuit.z(qr[2]).c_if(c0, 1)
circuit.x(qr[2]).c_if(c1, 1)
circuit.measure(qr[2], c2[0])
circuits.append(circuit)
return circuits
def teleport_counts(shots, hex_counts=True):
"""Reference counts for teleport circuits"""
targets = []
if hex_counts:
# Classical 3-qubit teleport
targets.append({'0x0': shots / 4, '0x1': shots / 4,
'0x2': shots / 4, '0x3': shots / 4})
else:
# Classical 3-qubit teleport
targets.append({'0 0 0': shots / 4, '0 0 1': shots / 4,
'0 1 0': shots / 4, '0 1 1': shots / 4})
return targets
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import copy
import itertools
from functools import reduce
import logging
import json
from operator import iadd as op_iadd, isub as op_isub
import sys
import numpy as np
from scipy import sparse as scisparse
from scipy import linalg as scila
from qiskit import ClassicalRegister, QuantumCircuit
from qiskit.quantum_info import Pauli
from qiskit.qasm import pi
from qiskit.assembler.run_config import RunConfig
from qiskit.tools import parallel_map
from qiskit.tools.events import TextProgressBar
from qiskit.aqua import AquaError, aqua_globals
from qiskit.aqua.utils import PauliGraph, compile_and_run_circuits, find_regs_by_name
from qiskit.aqua.utils.backend_utils import is_statevector_backend
logger = logging.getLogger(__name__)
class Operator(object):
"""
Operators relevant for quantum applications
Note:
For grouped paulis representation, all operations will always convert it to paulis and then convert it back.
(It might be a performance issue.)
"""
def __init__(self, paulis=None, grouped_paulis=None, matrix=None, coloring="largest-degree"):
"""
Args:
paulis ([[float, Pauli]]): each list contains a coefficient (real number) and a corresponding Pauli class object.
grouped_paulis ([[[float, Pauli]]]): each list of list contains a grouped paulis.
matrix (numpy.ndarray or scipy.sparse.csr_matrix) : a 2-D sparse matrix represents operator (using CSR format internally)
coloring (bool): method to group paulis.
"""
self._paulis = paulis
self._coloring = coloring
self._grouped_paulis = grouped_paulis
if matrix is not None:
matrix = matrix if scisparse.issparse(matrix) else scisparse.csr_matrix(matrix)
matrix = matrix if scisparse.isspmatrix_csr(matrix) else matrix.to_csr(copy=True)
self._matrix = matrix
self._to_dia_matrix(mode="matrix")
# use for fast lookup whether or not the paulis is existed.
self._simplify_paulis()
self._summarize_circuits = False
def _extend_or_combine(self, rhs, mode, operation=op_iadd):
"""
Add two operators either extend (in-place) or combine (copy) them.
The addition performs optimized combiniation of two operators.
If `rhs` has identical basis, the coefficient are combined rather than
appended.
Args:
rhs (Operator): to-be-combined operator
mode (str): in-place or not.
Returns:
Operator: the operator.
"""
if mode == 'inplace':
lhs = self
elif mode == 'non-inplace':
lhs = copy.deepcopy(self)
if lhs._paulis is not None and rhs._paulis is not None:
for pauli in rhs._paulis:
pauli_label = pauli[1].to_label()
idx = lhs._paulis_table.get(pauli_label, None)
if idx is not None:
lhs._paulis[idx][0] = operation(lhs._paulis[idx][0], pauli[0])
else:
lhs._paulis_table[pauli_label] = len(lhs._paulis)
new_pauli = copy.deepcopy(pauli)
new_pauli[0] = operation(0.0, pauli[0])
lhs._paulis.append(new_pauli)
elif lhs._grouped_paulis is not None and rhs._grouped_paulis is not None:
lhs._grouped_paulis_to_paulis()
rhs._grouped_paulis_to_paulis()
lhs = operation(lhs, rhs)
lhs._paulis_to_grouped_paulis()
elif lhs._matrix is not None and rhs._matrix is not None:
lhs._matrix = operation(lhs._matrix, rhs._matrix)
lhs._to_dia_matrix(mode='matrix')
else:
raise TypeError("the representations of two Operators should be the same. ({}, {})".format(
lhs.representations, rhs.representations))
return lhs
def __add__(self, rhs):
"""Overload + operation"""
return self._extend_or_combine(rhs, 'non-inplace', op_iadd)
def __iadd__(self, rhs):
"""Overload += operation"""
return self._extend_or_combine(rhs, 'inplace', op_iadd)
def __sub__(self, rhs):
"""Overload - operation"""
return self._extend_or_combine(rhs, 'non-inplace', op_isub)
def __isub__(self, rhs):
"""Overload -= operation"""
return self._extend_or_combine(rhs, 'inplace', op_isub)
def __neg__(self):
"""Overload unary - """
ret = copy.deepcopy(self)
ret.scaling_coeff(-1.0)
return ret
def __eq__(self, rhs):
"""Overload == operation"""
if self._matrix is not None and rhs._matrix is not None:
return np.all(self._matrix == rhs._matrix)
if self._paulis is not None and rhs._paulis is not None:
if len(self._paulis) != len(rhs._paulis):
return False
for coeff, pauli in self._paulis:
found_pauli = False
rhs_coeff = 0.0
for coeff2, pauli2 in rhs._paulis:
if pauli == pauli2:
found_pauli = True
rhs_coeff = coeff2
break
if not found_pauli and rhs_coeff != 0.0: # since we might have 0 weights of paulis.
return False
if coeff != rhs_coeff:
return False
return True
if self._grouped_paulis is not None and rhs._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
rhs._grouped_paulis_to_paulis()
return self.__eq__(rhs)
def __ne__(self, rhs):
""" != """
return not self.__eq__(rhs)
def __str__(self):
"""Overload str()"""
curr_repr = ""
length = ""
group = None
if self._paulis is not None:
curr_repr = 'paulis'
length = len(self._paulis)
elif self._grouped_paulis is not None:
curr_repr = 'grouped_paulis'
group = len(self._grouped_paulis)
length = sum([len(gp) - 1 for gp in self._grouped_paulis])
elif self._matrix is not None:
curr_repr = 'matrix'
length = "{}x{}".format(2 ** self.num_qubits, 2 ** self.num_qubits)
ret = "Representation: {}, qubits: {}, size: {}{}".format(
curr_repr, self.num_qubits, length, "" if group is None else " (number of groups: {})".format(group))
return ret
def copy(self):
"""Get a copy of self."""
return copy.deepcopy(self)
def chop(self, threshold=1e-15):
"""
Eliminate the real and imagine part of coeff in each pauli by `threshold`.
If pauli's coeff is less then `threshold` in both real and imagine parts, the pauli is removed.
To align the internal representations, all available representations are chopped.
The chopped result is stored back to original property.
Note: if coeff is real-only, the imag part is skipped.
Args:
threshold (float): threshold chops the paulis
"""
def chop_real_imag(coeff, threshold):
temp_real = coeff.real if np.absolute(coeff.real) >= threshold else 0.0
temp_imag = coeff.imag if np.absolute(coeff.imag) >= threshold else 0.0
if temp_real == 0.0 and temp_imag == 0.0:
return 0.0
else:
new_coeff = temp_real + 1j * temp_imag
return new_coeff
if self._paulis is not None:
for i in range(len(self._paulis)):
self._paulis[i][0] = chop_real_imag(self._paulis[i][0], threshold)
paulis = [x for x in self._paulis if x[0] != 0.0]
self._paulis = paulis
self._paulis_table = {pauli[1].to_label(): i for i, pauli in enumerate(self._paulis)}
if self._dia_matrix is not None:
self._to_dia_matrix('paulis')
elif self._grouped_paulis is not None:
grouped_paulis = []
for group_idx in range(1, len(self._grouped_paulis)):
for pauli_idx in range(len(self._grouped_paulis[group_idx])):
self._grouped_paulis[group_idx][pauli_idx][0] = chop_real_imag(
self._grouped_paulis[group_idx][pauli_idx][0], threshold)
paulis = [x for x in self._grouped_paulis[group_idx] if x[0] != 0.0]
grouped_paulis.append(paulis)
self._grouped_paulis = grouped_paulis
if self._dia_matrix is not None:
self._to_dia_matrix('grouped_paulis')
elif self._matrix is not None:
rows, cols = self._matrix.nonzero()
for row, col in zip(rows, cols):
self._matrix[row, col] = chop_real_imag(self._matrix[row, col], threshold)
self._matrix.eliminate_zeros()
if self._dia_matrix is not None:
self._to_dia_matrix('matrix')
def _simplify_paulis(self):
"""
Merge the paulis (grouped_paulis) whose bases are identical but the pauli with zero coefficient
would not be removed.
Usually used in construction.
"""
if self._paulis is not None:
new_paulis = []
new_paulis_table = {}
for curr_paulis in self._paulis:
pauli_label = curr_paulis[1].to_label()
new_idx = new_paulis_table.get(pauli_label, None)
if new_idx is not None:
new_paulis[new_idx][0] += curr_paulis[0]
else:
new_paulis_table[pauli_label] = len(new_paulis)
new_paulis.append(curr_paulis)
self._paulis = new_paulis
self._paulis_table = new_paulis_table
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self._simplify_paulis()
self._paulis_to_grouped_paulis()
def __mul__(self, rhs):
"""
Overload * operation. Only support two Operators have the same representation mode.
Returns:
Operator: the multipled Operator.
Raises:
TypeError, if two Operators do not have the same representations.
"""
if self._paulis is not None and rhs._paulis is not None:
ret_pauli = Operator(paulis=[])
for existed_pauli in self._paulis:
for pauli in rhs._paulis:
basis, sign = Pauli.sgn_prod(existed_pauli[1], pauli[1])
coeff = existed_pauli[0] * pauli[0] * sign
if abs(coeff) > 1e-15:
pauli_term = [coeff, basis]
ret_pauli += Operator(paulis=[pauli_term])
return ret_pauli
elif self._grouped_paulis is not None and rhs._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
rhs._grouped_paulis_to_paulis()
mul_pauli = self * rhs
mul_pauli._paulis_to_grouped_paulis()
ret_grouped_pauli = Operator(paulis=mul_pauli._paulis, grouped_paulis=mul_pauli._grouped_paulis)
return ret_grouped_pauli
elif self._matrix is not None and rhs._matrix is not None:
ret_matrix = self._matrix.dot(rhs._matrix)
return Operator(matrix=ret_matrix)
else:
raise TypeError("the representations of two Operators should be the same. ({}, {})".format(
self.representations, rhs.representations))
@property
def coloring(self):
"""Getter of method of grouping paulis"""
return self._coloring
@coloring.setter
def coloring(self, new_coloring):
"""Setter of method of grouping paulis"""
self._coloring = new_coloring
@property
def aer_paulis(self):
if getattr(self, '_aer_paulis', None) is None:
self.to_paulis()
aer_paulis = []
for coeff, p in self._paulis:
new_coeff = [coeff.real, coeff.imag]
new_p = p.to_label()
aer_paulis.append([new_coeff, new_p])
self._aer_paulis = aer_paulis
return self._aer_paulis
def _to_dia_matrix(self, mode):
"""
Convert the reprenetations into diagonal matrix if possible and then store it back.
For paulis, if all paulis are Z or I (identity), convert to dia_matrix.
Args:
mode (str): "matrix", "paulis" or "grouped_paulis".
"""
if mode not in ['matrix', 'paulis', 'grouped_paulis']:
raise ValueError(
'Mode should be one of "matrix", "paulis", "grouped_paulis"')
if mode == 'matrix' and self._matrix is not None:
dia_matrix = self._matrix.diagonal()
if not scisparse.csr_matrix(dia_matrix).nnz == self._matrix.nnz:
dia_matrix = None
self._dia_matrix = dia_matrix
elif mode == 'paulis' and self._paulis is not None:
if self._paulis == []:
self._dia_matrix = None
else:
valid_dia_matrix_flag = True
dia_matrix = 0.0
for idx in range(len(self._paulis)):
coeff, pauli = self._paulis[idx][0], self._paulis[idx][1]
if not (np.all(np.logical_not(pauli.x))):
valid_dia_matrix_flag = False
break
dia_matrix += coeff * pauli.to_spmatrix().diagonal()
self._dia_matrix = dia_matrix.copy() if valid_dia_matrix_flag else None
elif mode == 'grouped_paulis' and self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self._to_dia_matrix(mode='paulis')
self._paulis_to_grouped_paulis()
else:
self._dia_matrix = None
@property
def paulis(self):
"""Getter of Pauli list."""
return self._paulis
@property
def grouped_paulis(self):
"""Getter of grouped Pauli list."""
return self._grouped_paulis
@property
def matrix(self):
"""Getter of matrix; if matrix is diagonal, diagonal matrix is returned instead."""
return self._dia_matrix if self._dia_matrix is not None else self._matrix
def enable_summarize_circuits(self):
self._summarize_circuits = True
def disable_summarize_circuits(self):
self._summarize_circuits = False
@property
def representations(self):
"""
Return the available representations in the Operator.
Returns:
list: available representations ([str])
"""
ret = []
if self._paulis is not None:
ret.append("paulis")
if self._grouped_paulis is not None:
ret.append("grouped_paulis")
if self._matrix is not None:
ret.append("matrix")
return ret
@property
def num_qubits(self):
"""
number of qubits required for the operator.
Returns:
int: number of qubits
"""
if self._paulis is not None:
if self._paulis != []:
return len(self._paulis[0][1])
else:
return 0
elif self._grouped_paulis is not None and self._grouped_paulis != []:
return len(self._grouped_paulis[0][0][1])
else:
return int(np.log2(self._matrix.shape[0]))
@staticmethod
def load_from_file(file_name, before_04=False):
"""
Load paulis in a file to construct an Operator.
Args:
file_name (str): path to the file, which contains a list of Paulis and coefficients.
before_04 (bool): support the format < 0.4.
Returns:
Operator class: the loaded operator.
"""
with open(file_name, 'r') as file:
return Operator.load_from_dict(json.load(file), before_04=before_04)
def save_to_file(self, file_name):
"""
Save operator to a file in pauli representation.
Args:
file_name (str): path to the file
"""
with open(file_name, 'w') as f:
json.dump(self.save_to_dict(), f)
@staticmethod
def load_from_dict(dictionary, before_04=False):
"""
Load paulis in a dict to construct an Operator, \
the dict must be represented as follows: label and coeff (real and imag). \
E.g.: \
{'paulis': \
[ \
{'label': 'IIII', \
'coeff': {'real': -0.33562957575267038, 'imag': 0.0}}, \
{'label': 'ZIII', \
'coeff': {'real': 0.28220597164664896, 'imag': 0.0}}, \
... \
] \
} \
Args:
dictionary (dict): dictionary, which contains a list of Paulis and coefficients.
before_04 (bool): support the format < 0.4.
Returns:
Operator: the loaded operator.
"""
if 'paulis' not in dictionary:
raise AquaError('Dictionary missing "paulis" key')
paulis = []
for op in dictionary['paulis']:
if 'label' not in op:
raise AquaError('Dictionary missing "label" key')
pauli_label = op['label']
if 'coeff' not in op:
raise AquaError('Dictionary missing "coeff" key')
pauli_coeff = op['coeff']
if 'real' not in pauli_coeff:
raise AquaError('Dictionary missing "real" key')
coeff = pauli_coeff['real']
if 'imag' in pauli_coeff:
coeff = complex(pauli_coeff['real'], pauli_coeff['imag'])
pauli_label = pauli_label[::-1] if before_04 else pauli_label
paulis.append([coeff, Pauli.from_label(pauli_label)])
return Operator(paulis=paulis)
def save_to_dict(self):
"""
Save operator to a dict in pauli representation.
Returns:
dict: a dictionary contains an operator with pauli representation.
"""
self._check_representation("paulis")
ret_dict = {"paulis": []}
for pauli in self._paulis:
op = {"label": pauli[1].to_label()}
if isinstance(pauli[0], complex):
op["coeff"] = {"real": np.real(pauli[0]),
"imag": np.imag(pauli[0])
}
else:
op["coeff"] = {"real": pauli[0]}
ret_dict["paulis"].append(op)
return ret_dict
def print_operators(self, print_format='paulis'):
"""
Print out the paulis in the selected representation.
Args:
print_format (str): "paulis", "grouped_paulis", "matrix"
Returns:
str: a formated operator.
Raises:
ValueError: if `print_format` is not supported.
"""
ret = ""
if print_format == 'paulis':
self._check_representation("paulis")
for pauli in self._paulis:
ret = ''.join([ret, "{}\t{}\n".format(pauli[1].to_label(), pauli[0])])
if ret == "":
ret = ''.join([ret, "Pauli list is empty."])
elif print_format == 'grouped_paulis':
self._check_representation("grouped_paulis")
for i in range(len(self._grouped_paulis)):
ret = ''.join([ret, 'Post Rotations of TPB set {} '.format(i)])
ret = ''.join([ret, ': {} '.format(self._grouped_paulis[i][0][1].to_label())])
ret = ''.join([ret, '\n'])
for j in range(1, len(self._grouped_paulis[i])):
ret = ''.join([ret, '{} '.format(self._grouped_paulis[i][j][1].to_label())])
ret = ''.join([ret, '{}\n'.format(self._grouped_paulis[i][j][0])])
ret = ''.join([ret, '\n'])
if ret == "":
ret = ''.join([ret, "Grouped pauli list is empty."])
elif print_format == 'matrix':
self._check_representation("matrix")
ret = str(self._matrix.toarray())
else:
raise ValueError('Mode should be one of "matrix", "paulis", "grouped_paulis"')
return ret
def construct_evaluation_circuit(self, operator_mode, input_circuit, backend, use_simulator_operator_mode=False):
"""
Construct the circuits for evaluation.
Args:
operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix
input_circuit (QuantumCircuit): the quantum circuit.
backend (BaseBackend): backend selection for quantum machine.
use_simulator_operator_mode (bool): if aer_provider is used, we can do faster
evaluation for pauli mode on statevector simualtion
Returns:
[QuantumCircuit]: the circuits for evaluation.
"""
if is_statevector_backend(backend):
if operator_mode == 'matrix':
circuits = [input_circuit]
else:
self._check_representation("paulis")
if use_simulator_operator_mode:
circuits = [input_circuit]
else:
n_qubits = self.num_qubits
q = find_regs_by_name(input_circuit, 'q')
circuits = [input_circuit]
for idx, pauli in enumerate(self._paulis):
circuit = QuantumCircuit() + input_circuit
if np.all(np.logical_not(pauli[1].z)) and np.all(np.logical_not(pauli[1].x)): # all I
continue
for qubit_idx in range(n_qubits):
if not pauli[1].z[qubit_idx] and pauli[1].x[qubit_idx]:
circuit.u3(np.pi, 0.0, np.pi, q[qubit_idx]) # x
elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]:
circuit.u1(np.pi, q[qubit_idx]) # z
elif pauli[1].z[qubit_idx] and pauli[1].x[qubit_idx]:
circuit.u3(np.pi, np.pi/2, np.pi/2, q[qubit_idx]) # y
circuits.append(circuit)
else:
if operator_mode == 'matrix':
raise AquaError("matrix mode can not be used with non-statevector simulator.")
n_qubits = self.num_qubits
circuits = []
base_circuit = QuantumCircuit() + input_circuit
c = find_regs_by_name(base_circuit, 'c', qreg=False)
if c is None:
c = ClassicalRegister(n_qubits, name='c')
base_circuit.add_register(c)
if operator_mode == "paulis":
self._check_representation("paulis")
for idx, pauli in enumerate(self._paulis):
circuit = QuantumCircuit() + base_circuit
q = find_regs_by_name(circuit, 'q')
c = find_regs_by_name(circuit, 'c', qreg=False)
for qubit_idx in range(n_qubits):
if pauli[1].x[qubit_idx]:
if pauli[1].z[qubit_idx]:
# Measure Y
circuit.u1(-np.pi/2, q[qubit_idx]) # sdg
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
else:
# Measure X
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
circuit.barrier(q)
circuit.measure(q, c)
circuits.append(circuit)
else:
self._check_representation("grouped_paulis")
for idx, tpb_set in enumerate(self._grouped_paulis):
circuit = QuantumCircuit() + base_circuit
q = find_regs_by_name(circuit, 'q')
c = find_regs_by_name(circuit, 'c', qreg=False)
for qubit_idx in range(n_qubits):
if tpb_set[0][1].x[qubit_idx]:
if tpb_set[0][1].z[qubit_idx]:
# Measure Y
circuit.u1(-np.pi/2, q[qubit_idx]) # sdg
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
else:
# Measure X
circuit.u2(0.0, np.pi, q[qubit_idx]) # h
circuit.barrier(q)
circuit.measure(q, c)
circuits.append(circuit)
return circuits
def evaluate_with_result(self, operator_mode, circuits, backend, result, use_simulator_operator_mode=False):
"""
Use the executed result with operator to get the evaluated value.
Args:
operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix
circuits (list of qiskit.QuantumCircuit): the quantum circuits.
backend (str): backend selection for quantum machine.
result (qiskit.Result): the result from the backend.
use_simulator_operator_mode (bool): if aer_provider is used, we can do faster
evaluation for pauli mode on statevector simualtion
Returns:
float: the mean value
float: the standard deviation
"""
avg, std_dev, variance = 0.0, 0.0, 0.0
if is_statevector_backend(backend):
if operator_mode == "matrix":
self._check_representation("matrix")
if self._dia_matrix is None:
self._to_dia_matrix(mode='matrix')
quantum_state = np.asarray(result.get_statevector(circuits[0]))
if self._dia_matrix is not None:
avg = np.sum(self._dia_matrix * np.absolute(quantum_state) ** 2)
else:
avg = np.vdot(quantum_state, self._matrix.dot(quantum_state))
else:
self._check_representation("paulis")
if use_simulator_operator_mode:
temp = result.data(circuits[0])['snapshots']['expectation_value']['test'][0]['value']
avg = temp[0] + 1j * temp[1]
else:
quantum_state = np.asarray(result.get_statevector(circuits[0]))
circuit_idx = 1
for idx, pauli in enumerate(self._paulis):
if np.all(np.logical_not(pauli[1].z)) and np.all(np.logical_not(pauli[1].x)):
avg += pauli[0]
else:
quantum_state_i = np.asarray(result.get_statevector(circuits[circuit_idx]))
avg += pauli[0] * (np.vdot(quantum_state, quantum_state_i))
circuit_idx += 1
else:
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Computing the expectation from measurement results:")
TextProgressBar(sys.stderr)
num_shots = sum(list(result.get_counts(circuits[0]).values()))
if operator_mode == "paulis":
self._check_representation("paulis")
results = parallel_map(Operator._routine_paulis_with_shots,
[(pauli, result.get_counts(circuits[idx]))
for idx, pauli in enumerate(self._paulis)],
num_processes=aqua_globals.num_processes)
for result in results:
avg += result[0]
variance += result[1]
else:
self._check_representation("grouped_paulis")
results = parallel_map(Operator._routine_grouped_paulis_with_shots,
[(tpb_set, result.get_counts(circuits[tpb_idx]))
for tpb_idx, tpb_set in enumerate(self._grouped_paulis)],
num_processes=aqua_globals.num_processes)
for result in results:
avg += result[0]
variance += result[1]
std_dev = np.sqrt(variance / num_shots)
return avg, std_dev
@staticmethod
def _routine_grouped_paulis_with_shots(args):
tpb_set, measured_results = args
avg_paulis = []
avg = 0.0
variance = 0.0
for pauli_idx, pauli in enumerate(tpb_set):
if pauli_idx == 0:
continue
observable = Operator._measure_pauli_z(measured_results, pauli[1])
avg_paulis.append(observable)
avg += pauli[0] * observable
# Compute the covariance matrix elements of tpb_set
# and add up to the total standard deviation
# tpb_set = grouped_paulis, tensor product basis set
for pauli_1_idx, pauli_1 in enumerate(tpb_set):
for pauli_2_idx, pauli_2 in enumerate(tpb_set):
if pauli_1_idx == 0 or pauli_2_idx == 0:
continue
variance += pauli_1[0] * pauli_2[0] * \
Operator._covariance(measured_results, pauli_1[1], pauli_2[1],
avg_paulis[pauli_1_idx-1], avg_paulis[pauli_2_idx-1])
return avg, variance
@staticmethod
def _routine_paulis_with_shots(args):
pauli, measured_results = args
curr_result = Operator._measure_pauli_z(measured_results, pauli[1])
avg = pauli[0] * curr_result
variance = (pauli[0] ** 2) * Operator._covariance(measured_results, pauli[1], pauli[1],
curr_result, curr_result)
return avg, variance
def _eval_directly(self, quantum_state):
self._check_representation("matrix")
if self._dia_matrix is None:
self._to_dia_matrix(mode='matrix')
if self._dia_matrix is not None:
avg = np.sum(self._dia_matrix * np.absolute(quantum_state) ** 2)
else:
avg = np.vdot(quantum_state, self._matrix.dot(quantum_state))
return avg
def eval(self, operator_mode, input_circuit, backend, backend_config=None, compile_config=None,
run_config=None, qjob_config=None, noise_config=None):
"""
Supporting three ways to evaluate the given circuits with the operator.
1. If `input_circuit` is a numpy.ndarray, it will directly perform inner product with the operator.
2. If `backend` is a statevector simulator, use quantum backend to get statevector \
and then evaluate with the operator.
3. Other cases: it use with quanutm backend (simulator or real quantum machine), \
to obtain the mean and standard deviation of measured results.
Args:
operator_mode (str): representation of operator, including paulis, grouped_paulis and matrix
input_circuit (QuantumCircuit or numpy.ndarray): the quantum circuit.
backend (BaseBackend): backend selection for quantum machine.
backend_config (dict): configuration for backend
compile_config (dict): configuration for compilation
run_config (RunConfig): configuration for running a circuit
qjob_config (dict): the setting to retrieve results from quantum backend, including timeout and wait.
noise_config (dict) the setting of noise model for the qasm simulator in the Aer provider.
Returns:
float, float: mean and standard deviation of avg
"""
backend_config = backend_config or {}
compile_config = compile_config or {}
if run_config is not None:
if isinstance(run_config, dict):
run_config = RunConfig(**run_config)
else:
run_config = RunConfig()
qjob_config = qjob_config or {}
noise_config = noise_config or {}
if isinstance(input_circuit, np.ndarray):
avg = self._eval_directly(input_circuit)
std_dev = 0.0
else:
if is_statevector_backend(backend):
run_config.shots = 1
circuits = self.construct_evaluation_circuit(operator_mode, input_circuit, backend)
result = compile_and_run_circuits(circuits, backend=backend, backend_config=backend_config,
compile_config=compile_config, run_config=run_config,
qjob_config=qjob_config, noise_config=noise_config,
show_circuit_summary=self._summarize_circuits)
avg, std_dev = self.evaluate_with_result(operator_mode, circuits, backend, result)
return avg, std_dev
def to_paulis(self):
self._check_representation('paulis')
def to_grouped_paulis(self):
self._check_representation('grouped_paulis')
def to_matrix(self):
self._check_representation('matrix')
def convert(self, input_format, output_format, force=False):
"""
A wrapper for conversion among all representations.
Note that, if the output target is already there, it will skip the conversion.
The result is stored back into its property directly.
Args:
input_format (str): case-insensitive input format,
should be one of "paulis", "grouped_paulis", "matrix"
output_format (str): case-insensitive output format,
should be one of "paulis", "grouped_paulis", "matrix"
force (bool): convert to targeted format regardless its present.
Raises:
ValueError: if the unsupported output_format is specified.
"""
input_format = input_format.lower()
output_format = output_format.lower()
if input_format not in ["paulis", "grouped_paulis", "matrix"]:
raise ValueError(
"Input format {} is not supported".format(input_format))
if output_format not in ["paulis", "grouped_paulis", "matrix"]:
raise ValueError(
"Output format {} is not supported".format(output_format))
if output_format == "paulis" and (self._paulis is None or force):
if input_format == "matrix":
self._matrix_to_paulis()
elif input_format == "grouped_paulis":
self._grouped_paulis_to_paulis()
elif output_format == "grouped_paulis" and (self._grouped_paulis is None or force):
if self._grouped_paulis == []:
return
if input_format == "paulis":
self._paulis_to_grouped_paulis()
elif input_format == "matrix":
self._matrix_to_grouped_paulis()
elif output_format == "matrix" and (self._matrix is None or force):
if input_format == "paulis":
self._paulis_to_matrix()
elif input_format == "grouped_paulis":
self._grouped_paulis_to_matrix()
def _grouped_paulis_to_paulis(self):
"""
Convert grouped paulis to paulis, and save it in internal property directly.
Note:
Ideally, all paulis in grouped_paulis should be unique.
No need to check whether it is existed.
"""
if self._grouped_paulis == []:
return
paulis = []
for group in self._grouped_paulis:
for idx in range(1, len(group)): # the first one is the header.
paulis.append(group[idx])
self._paulis = paulis
self._matrix = None
self._grouped_paulis = None
def _matrix_to_paulis(self):
"""
Convert matrix to paulis, and save it in internal property directly.
Note:
Conversion from Paulis to matrix: H = sum_i alpha_i * Pauli_i
Conversion from matrix to Paulis: alpha_i = coeff * Trace(H.Pauli_i) (dot product of trace)
where coeff = 2^(- # of qubits), # of qubit = log2(dim of matrix)
"""
if self._matrix.nnz == 0:
return
num_qubits = self.num_qubits
coeff = 2 ** (-num_qubits)
paulis = []
# generate all possible paulis basis
for basis in itertools.product('IXYZ', repeat=num_qubits):
pauli_i = Pauli.from_label(''.join(basis))
trace_value = np.sum(self._matrix.dot(pauli_i.to_spmatrix()).diagonal())
alpha_i = trace_value * coeff
if alpha_i != 0.0:
paulis.append([alpha_i, pauli_i])
self._paulis = paulis
self._matrix = None
self._grouped_paulis = None
def _paulis_to_grouped_paulis(self):
"""
Convert paulis to grouped_paulis, and save it in internal property directly.
Groups a list of [coeff,Pauli] into tensor product basis (tpb) sets
"""
if self._paulis == []:
return
if self._coloring is not None:
self._grouped_paulis = PauliGraph(self._paulis, mode=self._coloring).grouped_paulis
else:
temp_paulis = copy.deepcopy(self._paulis)
n = self.num_qubits
grouped_paulis = []
sorted_paulis = []
def check_pauli_in_list(target, pauli_list):
ret = False
for pauli in pauli_list:
if target[1] == pauli[1]:
ret = True
break
return ret
for i in range(len(temp_paulis)):
p_1 = temp_paulis[i]
if not check_pauli_in_list(p_1, sorted_paulis):
paulis_temp = []
# pauli_list_temp.extend(p_1) # this is going to signal the total
# post-rotations of the set (set master)
paulis_temp.append(p_1)
paulis_temp.append(copy.deepcopy(p_1))
paulis_temp[0][0] = 0.0 # zero coeff for HEADER
for j in range(i+1, len(temp_paulis)):
p_2 = temp_paulis[j]
if not check_pauli_in_list(p_2, sorted_paulis) and p_1[1] != p_2[1]:
j = 0
for i in range(n):
# p_2 is identity, p_1 is identity, p_1 and p_2 has same basis
if not ((not p_2[1].z[i] and not p_2[1].x[i]) or
(not p_1[1].z[i] and not p_1[1].x[i]) or
(p_2[1].z[i] == p_1[1].z[i] and
p_2[1].x[i] == p_1[1].x[i])):
break
else:
# update master, if p_2 is not identity
if p_2[1].z[i] or p_2[1].x[i]:
paulis_temp[0][1].update_z(p_2[1].z[i], i)
paulis_temp[0][1].update_x(p_2[1].x[i], i)
j += 1
if j == n:
paulis_temp.append(p_2)
sorted_paulis.append(p_2)
grouped_paulis.append(paulis_temp)
self._grouped_paulis = grouped_paulis
self._matrix = None
self._paulis = None
def _matrix_to_grouped_paulis(self):
"""
Convert matrix to grouped_paulis, and save it in internal property directly.
"""
if self._matrix.nnz == 0:
return
self._matrix_to_paulis()
self._paulis_to_grouped_paulis()
self._matrix = None
self._paulis = None
def _paulis_to_matrix(self):
"""
Convert paulis to matrix, and save it in internal property directly.
If all paulis are Z or I (identity), convert to dia_matrix.
"""
if self._paulis == []:
return
p = self._paulis[0]
hamiltonian = p[0] * p[1].to_spmatrix()
for idx in range(1, len(self._paulis)):
p = self._paulis[idx]
hamiltonian += p[0] * p[1].to_spmatrix()
self._matrix = hamiltonian
self._to_dia_matrix(mode='matrix')
self._paulis = None
self._grouped_paulis = None
def _grouped_paulis_to_matrix(self):
"""
Convert grouped_paulis to matrix, and save it in internal property directly.
If all paulis are Z or I (identity), convert to dia_matrix.
"""
if self._grouped_paulis == []:
return
p = self._grouped_paulis[0][1]
hamiltonian = p[0] * p[1].to_spmatrix()
for idx in range(2, len(self._grouped_paulis[0])):
p = self._grouped_paulis[0][idx]
hamiltonian += p[0] * p[1].to_spmatrix()
for group_idx in range(1, len(self._grouped_paulis)):
group = self._grouped_paulis[group_idx]
for idx in range(1, len(group)):
p = group[idx]
hamiltonian += p[0] * p[1].to_spmatrix()
self._matrix = hamiltonian
self._to_dia_matrix(mode='matrix')
self._paulis = None
self._grouped_paulis = None
@staticmethod
def _measure_pauli_z(data, pauli):
"""
Appropriate post-rotations on the state are assumed.
Args:
data (dict): a dictionary of the form data = {'00000': 10} ({str: int})
pauli (Pauli): a Pauli object
Returns:
float: Expected value of paulis given data
"""
observable = 0.0
num_shots = sum(data.values())
p_z_or_x = np.logical_or(pauli.z, pauli.x)
for key, value in data.items():
bitstr = np.asarray(list(key))[::-1].astype(np.bool)
sign = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p_z_or_x)) else 1.0
observable += sign * value
observable /= num_shots
return observable
@staticmethod
def _covariance(data, pauli_1, pauli_2, avg_1, avg_2):
"""
Compute the covariance matrix element between two
Paulis, given the measurement outcome.
Appropriate post-rotations on the state are assumed.
Args:
data (dict): a dictionary of the form data = {'00000': 10} ({str:int})
pauli_1 (Pauli): a Pauli class member
pauli_2 (Pauli): a Pauli class member
avg_1 (float): expectation value of pauli_1 on `data`
avg_2 (float): expectation value of pauli_2 on `data`
Returns:
float: the element of the covariance matrix between two Paulis
"""
cov = 0.0
num_shots = sum(data.values())
if num_shots == 1:
return cov
p1_z_or_x = np.logical_or(pauli_1.z, pauli_1.x)
p2_z_or_x = np.logical_or(pauli_2.z, pauli_2.x)
for key, value in data.items():
bitstr = np.asarray(list(key))[::-1].astype(np.bool)
sign_1 = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p1_z_or_x)) else 1.0
sign_2 = -1.0 if np.logical_xor.reduce(np.logical_and(bitstr, p2_z_or_x)) else 1.0
cov += (sign_1 - avg_1) * (sign_2 - avg_2) * value
cov /= (num_shots - 1)
return cov
def two_qubit_reduced_operator(self, m, threshold=10**-13):
"""
Eliminates the central and last qubit in a list of Pauli that has
diagonal operators (Z,I) at those positions
Chemistry specific method:
It can be used to taper two qubits in parity and binary-tree mapped
fermionic Hamiltonians when the spin orbitals are ordered in two spin
sectors, (block spin order) according to the number of particles in the system.
Args:
m (int): number of fermionic particles
threshold (float): threshold for Pauli simplification
Returns:
Operator: a new operator whose qubit number is reduced by 2.
"""
if self._paulis is None or self._paulis == []:
return self
operator_out = Operator(paulis=[])
par_1 = 1 if m % 2 == 0 else -1
par_2 = 1 if m % 4 == 0 else -1
n = self.num_qubits
last_idx = n - 1
mid_idx = n // 2 - 1
for pauli_term in self._paulis: # loop over Pauli terms
coeff_out = pauli_term[0]
# Z operator encountered at qubit n/2-1
if pauli_term[1].z[mid_idx] and not pauli_term[1].x[mid_idx]:
coeff_out = par_2 * coeff_out
# Z operator encountered at qubit n-1
if pauli_term[1].z[last_idx] and not pauli_term[1].x[last_idx]:
coeff_out = par_1 * coeff_out
# TODO: can change to delete
z_temp = []
x_temp = []
for j in range(n - 1):
if j != mid_idx:
z_temp.append(pauli_term[1].z[j])
x_temp.append(pauli_term[1].x[j])
pauli_term_out = [coeff_out, Pauli(np.asarray(z_temp), np.asarray(x_temp))]
if np.absolute(coeff_out) > threshold:
operator_out += Operator(paulis=[pauli_term_out])
operator_out.chop(threshold=threshold)
return operator_out
def get_flat_pauli_list(self):
"""
Get the flat list of paulis
Returns:
list: The list of pauli terms
"""
if self._paulis is not None:
return [] + self._paulis
else:
if self._grouped_paulis is not None:
return [pauli for group in self._grouped_paulis for pauli in group[1:]]
elif self._matrix is not None:
self._check_representation('paulis')
return [] + self._paulis
@staticmethod
def construct_evolution_circuit(slice_pauli_list, evo_time, num_time_slices, state_registers,
ancillary_registers=None, ctl_idx=0, unitary_power=None, use_basis_gates=True,
shallow_slicing=False):
"""
Construct the evolution circuit according to the supplied specification.
Args:
slice_pauli_list (list): The list of pauli terms corresponding to a single time slice to be evolved
evo_time (int): The evolution time
num_time_slices (int): The number of time slices for the expansion
state_registers (QuantumRegister): The Qiskit QuantumRegister corresponding to the qubits of the system
ancillary_registers (QuantumRegister): The optional Qiskit QuantumRegister corresponding to the control
qubits for the state_registers of the system
ctl_idx (int): The index of the qubit of the control ancillary_registers to use
unitary_power (int): The power to which the unitary operator is to be raised
use_basis_gates (bool): boolean flag for indicating only using basis gates when building circuit.
shallow_slicing (bool): boolean flag for indicating using shallow qc.data reference repetition for slicing
Returns:
QuantumCircuit: The Qiskit QuantumCircuit corresponding to specified evolution.
"""
if state_registers is None:
raise ValueError('Quantum state registers are required.')
qc_slice = QuantumCircuit(state_registers)
if ancillary_registers is not None:
qc_slice.add_register(ancillary_registers)
# for each pauli [IXYZ]+, record the list of qubit pairs needing CX's
cnot_qubit_pairs = [None] * len(slice_pauli_list)
# for each pauli [IXYZ]+, record the highest index of the nontrivial pauli gate (X,Y, or Z)
top_XYZ_pauli_indices = [-1] * len(slice_pauli_list)
for pauli_idx, pauli in enumerate(reversed(slice_pauli_list)):
n_qubits = pauli[1].numberofqubits
# changes bases if necessary
nontrivial_pauli_indices = []
for qubit_idx in range(n_qubits):
# pauli I
if not pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]:
continue
if cnot_qubit_pairs[pauli_idx] is None:
nontrivial_pauli_indices.append(qubit_idx)
if pauli[1].x[qubit_idx]:
# pauli X
if not pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u2(0.0, pi, state_registers[qubit_idx])
else:
qc_slice.h(state_registers[qubit_idx])
# pauli Y
elif pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u3(pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx])
else:
qc_slice.rx(pi / 2, state_registers[qubit_idx])
# pauli Z
elif pauli[1].z[qubit_idx] and not pauli[1].x[qubit_idx]:
pass
else:
raise ValueError('Unrecognized pauli: {}'.format(pauli[1]))
if len(nontrivial_pauli_indices) > 0:
top_XYZ_pauli_indices[pauli_idx] = nontrivial_pauli_indices[-1]
# insert lhs cnot gates
if cnot_qubit_pairs[pauli_idx] is None:
cnot_qubit_pairs[pauli_idx] = list(zip(
sorted(nontrivial_pauli_indices)[:-1],
sorted(nontrivial_pauli_indices)[1:]
))
for pair in cnot_qubit_pairs[pauli_idx]:
qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]])
# insert Rz gate
if top_XYZ_pauli_indices[pauli_idx] >= 0:
if ancillary_registers is None:
lam = (2.0 * pauli[0] * evo_time / num_time_slices).real
if use_basis_gates:
qc_slice.u1(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]])
else:
qc_slice.rz(lam, state_registers[top_XYZ_pauli_indices[pauli_idx]])
else:
unitary_power = (2 ** ctl_idx) if unitary_power is None else unitary_power
lam = (2.0 * pauli[0] * evo_time / num_time_slices * unitary_power).real
if use_basis_gates:
qc_slice.u1(lam / 2, state_registers[top_XYZ_pauli_indices[pauli_idx]])
qc_slice.cx(ancillary_registers[ctl_idx], state_registers[top_XYZ_pauli_indices[pauli_idx]])
qc_slice.u1(-lam / 2, state_registers[top_XYZ_pauli_indices[pauli_idx]])
qc_slice.cx(ancillary_registers[ctl_idx], state_registers[top_XYZ_pauli_indices[pauli_idx]])
else:
qc_slice.crz(lam, ancillary_registers[ctl_idx],
state_registers[top_XYZ_pauli_indices[pauli_idx]])
# insert rhs cnot gates
for pair in reversed(cnot_qubit_pairs[pauli_idx]):
qc_slice.cx(state_registers[pair[0]], state_registers[pair[1]])
# revert bases if necessary
for qubit_idx in range(n_qubits):
if pauli[1].x[qubit_idx]:
# pauli X
if not pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u2(0.0, pi, state_registers[qubit_idx])
else:
qc_slice.h(state_registers[qubit_idx])
# pauli Y
elif pauli[1].z[qubit_idx]:
if use_basis_gates:
qc_slice.u3(-pi / 2, -pi / 2, pi / 2, state_registers[qubit_idx])
else:
qc_slice.rx(-pi / 2, state_registers[qubit_idx])
# repeat the slice
if shallow_slicing:
logger.info('Under shallow slicing mode, the qc.data reference is repeated shallowly. '
'Thus, changing gates of one slice of the output circuit might affect other slices.')
qc_slice.data *= num_time_slices
qc = qc_slice
else:
qc = QuantumCircuit()
for _ in range(num_time_slices):
qc += qc_slice
return qc
@staticmethod
def _suzuki_expansion_slice_matrix(pauli_list, lam, expansion_order):
"""
Compute the matrix for a single slice of the suzuki expansion following the paper
https://arxiv.org/pdf/quant-ph/0508139.pdf
Args:
pauli_list (list): The operator's complete list of pauli terms for the suzuki expansion
lam (complex): The parameter lambda as defined in said paper
expansion_order (int): The order for the suzuki expansion
Returns:
numpy array: The matrix representation corresponding to the specified suzuki expansion
"""
if expansion_order == 1:
left = reduce(
lambda x, y: x @ y,
[scila.expm(lam / 2 * c * p.to_spmatrix().tocsc()) for c, p in pauli_list]
)
right = reduce(
lambda x, y: x @ y,
[scila.expm(lam / 2 * c * p.to_spmatrix().tocsc()) for c, p in reversed(pauli_list)]
)
return left @ right
else:
pk = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1
side_base = Operator._suzuki_expansion_slice_matrix(
pauli_list,
lam * pk,
expansion_order - 1
)
side = side_base @ side_base
middle = Operator._suzuki_expansion_slice_matrix(
pauli_list,
lam * (1 - 4 * pk),
expansion_order - 1
)
return side @ middle @ side
@staticmethod
def _suzuki_expansion_slice_pauli_list(pauli_list, lam_coef, expansion_order):
"""
Similar to _suzuki_expansion_slice_matrix, with the difference that this method
computes the list of pauli terms for a single slice of the suzuki expansion,
which can then be fed to construct_evolution_circuit to build the QuantumCircuit.
"""
if expansion_order == 1:
half = [[lam_coef / 2 * c, p] for c, p in pauli_list]
return half + list(reversed(half))
else:
pk = (4 - 4 ** (1 / (2 * expansion_order - 1))) ** -1
side_base = Operator._suzuki_expansion_slice_pauli_list(
pauli_list,
lam_coef * pk,
expansion_order - 1
)
side = side_base * 2
middle = Operator._suzuki_expansion_slice_pauli_list(
pauli_list,
lam_coef * (1 - 4 * pk),
expansion_order - 1
)
return side + middle + side
def evolve(
self,
state_in=None,
evo_time=0,
evo_mode=None,
num_time_slices=0,
quantum_registers=None,
expansion_mode='trotter',
expansion_order=1
):
"""
Carry out the eoh evolution for the operator under supplied specifications.
Args:
state_in: The initial state for the evolution
evo_time (int): The evolution time
evo_mode (str): The mode under which the evolution is carried out.
Currently only support 'matrix' or 'circuit'
num_time_slices (int): The number of time slices for the expansion
quantum_registers (QuantumRegister): The QuantumRegister to build the QuantumCircuit off of
expansion_mode (str): The mode under which the expansion is to be done.
Currently support 'trotter', which follows the expansion as discussed in
http://science.sciencemag.org/content/273/5278/1073,
and 'suzuki', which corresponds to the discussion in
https://arxiv.org/pdf/quant-ph/0508139.pdf
expansion_order (int): The order for suzuki expansion
Returns:
Depending on the evo_mode specified, either return the matrix vector multiplication result
or the constructed QuantumCircuit.
"""
if num_time_slices < 0 or not isinstance(num_time_slices, int):
raise ValueError('Number of time slices should be a non-negative integer.')
if not (expansion_mode == 'trotter' or expansion_mode == 'suzuki'):
raise NotImplementedError('Expansion mode {} not supported.'.format(expansion_mode))
pauli_list = self.get_flat_pauli_list()
if evo_mode == 'matrix':
self._check_representation("matrix")
if num_time_slices == 0:
return scila.expm(-1.j * evo_time * self._matrix.tocsc()) @ state_in
else:
if len(pauli_list) == 1:
approx_matrix_slice = scila.expm(
-1.j * evo_time / num_time_slices * pauli_list[0][0] * pauli_list[0][1].to_spmatrix().tocsc()
)
else:
if expansion_mode == 'trotter':
approx_matrix_slice = reduce(
lambda x, y: x @ y,
[
scila.expm(-1.j * evo_time / num_time_slices * c * p.to_spmatrix().tocsc())
for c, p in pauli_list
]
)
# suzuki expansion
elif expansion_mode == 'suzuki':
approx_matrix_slice = Operator._suzuki_expansion_slice_matrix(
pauli_list,
-1.j * evo_time / num_time_slices,
expansion_order
)
else:
raise ValueError('Unrecognized expansion mode {}.'.format(expansion_mode))
return reduce(lambda x, y: x @ y, [approx_matrix_slice] * num_time_slices) @ state_in
elif evo_mode == 'circuit':
if num_time_slices == 0:
raise ValueError('Number of time slices should be a positive integer for {} mode.'.format(evo_mode))
else:
if quantum_registers is None:
raise ValueError('Quantum registers are needed for circuit construction.')
if len(pauli_list) == 1:
slice_pauli_list = pauli_list
else:
if expansion_mode == 'trotter':
slice_pauli_list = pauli_list
# suzuki expansion
else:
slice_pauli_list = Operator._suzuki_expansion_slice_pauli_list(
pauli_list,
1,
expansion_order
)
return self.construct_evolution_circuit(
slice_pauli_list, evo_time, num_time_slices, quantum_registers
)
else:
raise ValueError('Evolution mode should be either "matrix" or "circuit".')
def is_empty(self):
"""
Check Operator is empty or not.
Returns:
bool: is empty?
"""
if self._matrix is None and self._dia_matrix is None \
and (self._paulis == [] or self._paulis is None) \
and (self._grouped_paulis == [] or self._grouped_paulis is None):
return True
else:
return False
def _check_representation(self, targeted_representation):
"""
Check the targeted representation is existed or not, if not, find available representations
and then convert to the targeted one.
Args:
targeted_representation (str): should be one of paulis, grouped_paulis and matrix
Raises:
ValueError: if the `targeted_representation` is not recognized.
"""
if targeted_representation == 'paulis':
if self._paulis is None:
if self._matrix is not None:
self._matrix_to_paulis()
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
else:
raise AquaError(
"at least having one of the three operator representations.")
elif targeted_representation == 'grouped_paulis':
if self._grouped_paulis is None:
if self._paulis is not None:
self._paulis_to_grouped_paulis()
elif self._matrix is not None:
self._matrix_to_grouped_paulis()
else:
raise AquaError(
"at least having one of the three operator representations.")
elif targeted_representation == 'matrix':
if self._matrix is None:
if self._paulis is not None:
self._paulis_to_matrix()
elif self._grouped_paulis is not None:
self._grouped_paulis_to_matrix()
else:
raise AquaError(
"at least having one of the three operator representations.")
else:
raise ValueError(
'"targeted_representation" should be one of "paulis", "grouped_paulis" and "matrix".'
)
@staticmethod
def row_echelon_F2(matrix_in):
"""
Computes the row Echelon form of a binary matrix on the binary
finite field
Args:
matrix_in (numpy.ndarray): binary matrix
Returns:
numpy.ndarray : matrix_in in Echelon row form
"""
size = matrix_in.shape
for i in range(size[0]):
pivot_index = 0
for j in range(size[1]):
if matrix_in[i, j] == 1:
pivot_index = j
break
for k in range(size[0]):
if k != i and matrix_in[k, pivot_index] == 1:
matrix_in[k, :] = np.mod(matrix_in[k, :] + matrix_in[i, :], 2)
matrix_out_temp = copy.deepcopy(matrix_in)
indices = []
matrix_out = np.zeros(size)
for i in range(size[0] - 1):
if np.array_equal(matrix_out_temp[i, :], np.zeros(size[1])):
indices.append(i)
for row in np.sort(indices)[::-1]:
matrix_out_temp = np.delete(matrix_out_temp, (row), axis=0)
matrix_out[0:size[0] - len(indices), :] = matrix_out_temp
matrix_out = matrix_out.astype(int)
return matrix_out
@staticmethod
def kernel_F2(matrix_in):
"""
Computes the kernel of a binary matrix on the binary finite field
Args:
matrix_in (numpy.ndarray): binary matrix
Returns:
[numpy.ndarray]: the list of kernel vectors
"""
size = matrix_in.shape
kernel = []
matrix_in_id = np.vstack((matrix_in, np.identity(size[1])))
matrix_in_id_ech = (Operator.row_echelon_F2(matrix_in_id.transpose())).transpose()
for col in range(size[1]):
if (np.array_equal(matrix_in_id_ech[0:size[0], col], np.zeros(size[0])) and not
np.array_equal(matrix_in_id_ech[size[0]:, col], np.zeros(size[1]))):
kernel.append(matrix_in_id_ech[size[0]:, col])
return kernel
def find_Z2_symmetries(self):
"""
Finds Z2 Pauli-type symmetries of an Operator
Returns:
[Pauli]: the list of Pauli objects representing the Z2 symmetries
[Pauli]: the list of single - qubit Pauli objects to construct the Cliffors operators
[Operators]: the list of Clifford unitaries to block diagonalize Operator
[int]: the list of support of the single-qubit Pauli objects used to build the clifford operators
"""
Pauli_symmetries = []
sq_paulis = []
cliffords = []
sq_list = []
stacked_paulis = []
if self.is_empty():
logger.info("Operator is empty.")
return [], [], [], []
self._check_representation("paulis")
for pauli in self._paulis:
stacked_paulis.append(np.concatenate((pauli[1].x, pauli[1].z), axis=0).astype(np.int))
stacked_matrix = np.array(np.stack(stacked_paulis))
symmetries = Operator.kernel_F2(stacked_matrix)
if len(symmetries) == 0:
logger.info("No symmetry is found.")
return [], [], [], []
stacked_symmetries = np.stack(symmetries)
symm_shape = stacked_symmetries.shape
for row in range(symm_shape[0]):
Pauli_symmetries.append(Pauli(stacked_symmetries[row, : symm_shape[1] // 2],
stacked_symmetries[row, symm_shape[1] // 2:]))
stacked_symm_del = np.delete(stacked_symmetries, (row), axis=0)
for col in range(symm_shape[1] // 2):
# case symmetries other than one at (row) have Z or I on col qubit
Z_or_I = True
for symm_idx in range(symm_shape[0] - 1):
if not (stacked_symm_del[symm_idx, col] == 0
and stacked_symm_del[symm_idx, col + symm_shape[1] // 2] in (0, 1)):
Z_or_I = False
if Z_or_I:
if ((stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 0) or
(stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1)):
sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2),
np.zeros(symm_shape[1] // 2)))
sq_paulis[row].z[col] = False
sq_paulis[row].x[col] = True
sq_list.append(col)
break
# case symmetries other than one at (row) have X or I on col qubit
X_or_I = True
for symm_idx in range(symm_shape[0] - 1):
if not (stacked_symm_del[symm_idx, col] in (0, 1) and
stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 0):
X_or_I = False
if X_or_I:
if ((stacked_symmetries[row, col] == 0 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1) or
(stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1)):
sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2), np.zeros(symm_shape[1] // 2)))
sq_paulis[row].z[col] = True
sq_paulis[row].x[col] = False
sq_list.append(col)
break
# case symmetries other than one at (row) have Y or I on col qubit
Y_or_I = True
for symm_idx in range(symm_shape[0] - 1):
if not ((stacked_symm_del[symm_idx, col] == 1 and
stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 1)
or (stacked_symm_del[symm_idx, col] == 0 and
stacked_symm_del[symm_idx, col + symm_shape[1] // 2] == 0)):
Y_or_I = False
if Y_or_I:
if ((stacked_symmetries[row, col] == 0 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 1) or
(stacked_symmetries[row, col] == 1 and
stacked_symmetries[row, col + symm_shape[1] // 2] == 0)):
sq_paulis.append(Pauli(np.zeros(symm_shape[1] // 2), np.zeros(symm_shape[1] // 2)))
sq_paulis[row].z[col] = True
sq_paulis[row].x[col] = True
sq_list.append(col)
break
for symm_idx, Pauli_symm in enumerate(Pauli_symmetries):
cliffords.append(Operator([[1 / np.sqrt(2), Pauli_symm], [1 / np.sqrt(2), sq_paulis[symm_idx]]]))
return Pauli_symmetries, sq_paulis, cliffords, sq_list
@staticmethod
def qubit_tapering(operator, cliffords, sq_list, tapering_values):
"""
Builds an Operator which has a number of qubits tapered off,
based on a block-diagonal Operator built using a list of cliffords.
The block-diagonal subspace is an input parameter, set through the list
tapering_values, which takes values +/- 1.
Args:
operator (Operator): the target operator to be tapered
cliffords ([Operator]): list of unitary Clifford transformation
sq_list ([int]): position of the single-qubit operators that anticommute
with the cliffords
tapering_values ([int]): array of +/- 1 used to select the subspace. Length
has to be equal to the length of cliffords and sq_list
Returns:
Operator : the tapered operator, or empty operator if the `operator` is empty.
"""
if len(cliffords) == 0 or len(sq_list) == 0 or len(tapering_values) == 0:
logger.warning("Cliffords, single qubit list and tapering values cannot be empty.\n"
"Return the original operator instead.")
return operator
if len(cliffords) != len(sq_list):
logger.warning("Number of Clifford unitaries has to be the same as length of single"
"qubit list and tapering values.\n"
"Return the original operator instead.")
return operator
if len(sq_list) != len(tapering_values):
logger.warning("Number of Clifford unitaries has to be the same as length of single"
"qubit list and tapering values.\n"
"Return the original operator instead.")
return operator
if operator.is_empty():
logger.warning("The operator is empty, return the empty operator directly.")
return operator
operator.to_paulis()
for clifford in cliffords:
operator = clifford * operator * clifford
operator_out = Operator(paulis=[])
for pauli_term in operator.paulis:
coeff_out = pauli_term[0]
for idx, qubit_idx in enumerate(sq_list):
if not (not pauli_term[1].z[qubit_idx] and not pauli_term[1].x[qubit_idx]):
coeff_out = tapering_values[idx] * coeff_out
z_temp = np.delete(pauli_term[1].z.copy(), np.asarray(sq_list))
x_temp = np.delete(pauli_term[1].x.copy(), np.asarray(sq_list))
pauli_term_out = [coeff_out, Pauli(z_temp, x_temp)]
operator_out += Operator(paulis=[pauli_term_out])
operator_out.zeros_coeff_elimination()
return operator_out
def zeros_coeff_elimination(self):
"""
Elinminate paulis or grouped paulis whose coefficients are zeros.
The difference from `_simplify_paulis` method is that, this method will not remove duplicated
paulis.
"""
if self._paulis is not None:
new_paulis = [pauli for pauli in self._paulis if pauli[0] != 0]
self._paulis = new_paulis
self._paulis_table = {pauli[1].to_label(): i for i, pauli in enumerate(self._paulis)}
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self.zeros_coeff_elimination()
self._paulis_to_grouped_paulis()
self._paulis = None
def scaling_coeff(self, scaling_factor):
"""
Constant scale the coefficient in an operator.
Note that: the behavior of scaling in paulis (grouped_paulis) might be different from matrix
Args:
scaling_factor (float): the sacling factor
"""
if self._paulis is not None:
for idx in range(len(self._paulis)):
self._paulis[idx] = [self._paulis[idx][0] * scaling_factor, self._paulis[idx][1]]
elif self._grouped_paulis is not None:
self._grouped_paulis_to_paulis()
self._scale_paulis(scaling_factor)
self._paulis_to_grouped_paulis()
elif self._matrix is not None:
self._matrix *= scaling_factor
if self._dia_matrix is not None:
self._dia_matrix *= scaling_factor
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
"""Tests for generator of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import generators, types, stylesheet
from qiskit.circuit import library, Delay
class TestGates(QiskitTestCase):
"""Tests for generator.gates."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
self.u1 = types.ScheduledGate(
t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0
)
self.u3 = types.ScheduledGate(
t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0
)
self.delay = types.ScheduledGate(
t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0
)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_sched_gate_with_finite_duration(self):
"""Test test_gen_sched_gate generator with finite duration gate."""
drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 120])
self.assertListEqual(
list(drawing_obj.yvals),
[-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_meta = {
"name": "u3",
"label": "n/a",
"bits": str(self.qubit.register.name),
"t0": 100,
"duration": 20,
"unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]",
"parameters": "0, 0, 0",
}
self.assertDictEqual(ref_meta, drawing_obj.meta)
ref_styles = {
"zorder": self.formatter["layer.gate"],
"facecolor": self.formatter["color.gates"]["u3"],
"alpha": self.formatter["alpha.gate"],
"linewidth": self.formatter["line_width.gate"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_zero_duration(self):
"""Test test_gen_sched_gate generator with zero duration gate."""
drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"])
self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"])
ref_styles = {
"zorder": self.formatter["layer.frame_change"],
"color": self.formatter["color.gates"]["u1"],
"size": self.formatter["text_size.frame_change"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_delay(self):
"""Test test_gen_sched_gate generator with delay."""
drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value))
def test_gen_full_gate_name_with_finite_duration(self):
"""Test gen_full_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]")
ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format(
name=self.formatter["latex_symbol.gates"]["u3"]
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_zero_duration(self):
"""Test gen_full_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1(0.00)")
ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_delay(self):
"""Test gen_full_gate_name generator with delay."""
drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
def test_gen_short_gate_name_with_finite_duration(self):
"""Test gen_short_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_zero_duration(self):
"""Test gen_short_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_delay(self):
"""Test gen_short_gate_name generator with delay."""
drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
class TestTimeslot(QiskitTestCase):
"""Tests for generator.bits."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_timeslot(self):
"""Test gen_timeslot generator."""
drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value))
self.assertListEqual(
list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
)
self.assertListEqual(
list(drawing_obj.yvals),
[
-0.5 * self.formatter["box_height.timeslot"],
0.5 * self.formatter["box_height.timeslot"],
],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_styles = {
"zorder": self.formatter["layer.timeslot"],
"alpha": self.formatter["alpha.timeslot"],
"linewidth": self.formatter["line_width.timeslot"],
"facecolor": self.formatter["color.timeslot"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_bit_name(self):
"""Test gen_bit_name generator."""
drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, str(self.qubit.register.name))
ref_latex = r"{{\rm {register}}}_{{{index}}}".format(
register=self.qubit.register.prefix, index=self.qubit.index
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.bit_name"],
"color": self.formatter["color.bit_name"],
"size": self.formatter["text_size.bit_name"],
"va": "center",
"ha": "right",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestBarrier(QiskitTestCase):
"""Tests for generator.barriers."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(3))
self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_barrier(self):
"""Test gen_barrier generator."""
drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 100])
self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5])
self.assertListEqual(drawing_obj.bits, [self.qubits[1]])
ref_styles = {
"alpha": self.formatter["alpha.barrier"],
"zorder": self.formatter["layer.barrier"],
"linewidth": self.formatter["line_width.barrier"],
"linestyle": self.formatter["line_style.barrier"],
"color": self.formatter["color.barrier"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestGateLink(QiskitTestCase):
"""Tests for generator.gate_links."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(2))
self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def gen_bit_link(self):
"""Test gen_bit_link generator."""
drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, self.qubits)
ref_styles = {
"alpha": self.formatter["alpha.bit_link"],
"zorder": self.formatter["layer.bit_link"],
"linewidth": self.formatter["line_width.bit_link"],
"linestyle": self.formatter["line_style.bit_link"],
"color": self.formatter["color.gates"]["cx"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
|
https://github.com/qiskit-community/prototype-qrao
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Quantum Random Access Optimizer."""
from typing import Union, List, Tuple, Optional
import time
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms.minimum_eigensolvers import (
MinimumEigensolver,
MinimumEigensolverResult,
NumPyMinimumEigensolver,
)
from qiskit.algorithms.minimum_eigen_solvers import (
MinimumEigensolver as LegacyMinimumEigensolver,
MinimumEigensolverResult as LegacyMinimumEigensolverResult,
NumPyMinimumEigensolver as LegacyNumPyMinimumEigensolver,
)
from qiskit_optimization.algorithms import (
OptimizationAlgorithm,
OptimizationResult,
OptimizationResultStatus,
SolutionSample,
)
from qiskit_optimization.problems import QuadraticProgram, Variable
from .encoding import QuantumRandomAccessEncoding
from .rounding_common import RoundingScheme, RoundingContext, RoundingResult
from .semideterministic_rounding import SemideterministicRounding
def _get_aux_operators_evaluated(relaxed_results):
try:
# Must be using the new "minimum_eigensolvers"
# https://github.com/Qiskit/qiskit-terra/blob/main/releasenotes/notes/0.22/add-eigensolvers-with-primitives-8b3a9f55f5fd285f.yaml
return relaxed_results.aux_operators_evaluated
except AttributeError:
# Must be using the old (deprecated) "minimum_eigen_solvers"
return relaxed_results.aux_operator_eigenvalues
class QuantumRandomAccessOptimizationResult(OptimizationResult):
"""Result of Quantum Random Access Optimization procedure."""
def __init__(
self,
*,
x: Optional[Union[List[float], np.ndarray]],
fval: Optional[float],
variables: List[Variable],
status: OptimizationResultStatus,
samples: Optional[List[SolutionSample]],
relaxed_results: Union[
MinimumEigensolverResult, LegacyMinimumEigensolverResult
],
rounding_results: RoundingResult,
relaxed_results_offset: float,
sense: int,
) -> None:
"""
Args:
x: the optimal value found by ``MinimumEigensolver``.
fval: the optimal function value.
variables: the list of variables of the optimization problem.
status: the termination status of the optimization algorithm.
min_eigen_solver_result: the result obtained from the underlying algorithm.
samples: the x values of the QUBO, the objective function value of the QUBO,
and the probability, and the status of sampling.
"""
super().__init__(
x=x,
fval=fval,
variables=variables,
status=status,
raw_results=None,
samples=samples,
)
self._relaxed_results = relaxed_results
self._rounding_results = rounding_results
self._relaxed_results_offset = relaxed_results_offset
assert sense in (-1, 1)
self._sense = sense
@property
def relaxed_results(
self,
) -> Union[MinimumEigensolverResult, LegacyMinimumEigensolverResult]:
"""Variationally obtained ground state of the relaxed Hamiltonian"""
return self._relaxed_results
@property
def rounding_results(self) -> RoundingResult:
"""Rounding results"""
return self._rounding_results
@property
def trace_values(self):
"""List of expectation values, one corresponding to each decision variable"""
trace_values = [
v[0] for v in _get_aux_operators_evaluated(self._relaxed_results)
]
return trace_values
@property
def relaxed_fval(self) -> float:
"""Relaxed function value, in the conventions of the original ``QuadraticProgram``
Restoring convertions may be necessary, for instance, if the provided
``QuadraticProgram`` represents a maximization problem, as it will be
converted to a minimization problem when phrased as a Hamiltonian.
"""
return self._sense * (
self._relaxed_results_offset + self.relaxed_results.eigenvalue.real
)
def __repr__(self) -> str:
lines = (
"QRAO Result",
"-----------",
f"relaxed function value: {self.relaxed_fval}",
super().__repr__(),
)
return "\n".join(lines)
class QuantumRandomAccessOptimizer(OptimizationAlgorithm):
"""Quantum Random Access Optimizer."""
def __init__(
self,
min_eigen_solver: Union[MinimumEigensolver, LegacyMinimumEigensolver],
encoding: QuantumRandomAccessEncoding,
rounding_scheme: Optional[RoundingScheme] = None,
):
"""
Args:
min_eigen_solver: The minimum eigensolver to use for solving the
relaxed problem (typically an instance of ``VQE`` or ``QAOA``).
encoding: The ``QuantumRandomAccessEncoding``, which must have
already been ``encode()``ed with a ``QuadraticProgram``.
rounding_scheme: The rounding scheme. If ``None`` is provided,
``SemideterministicRounding()`` will be used.
"""
self.min_eigen_solver = min_eigen_solver
self.encoding = encoding
if rounding_scheme is None:
rounding_scheme = SemideterministicRounding()
self.rounding_scheme = rounding_scheme
@property
def min_eigen_solver(self) -> Union[MinimumEigensolver, LegacyMinimumEigensolver]:
"""The minimum eigensolver."""
return self._min_eigen_solver
@min_eigen_solver.setter
def min_eigen_solver(
self, min_eigen_solver: Union[MinimumEigensolver, LegacyMinimumEigensolver]
) -> None:
"""Set the minimum eigensolver."""
if not min_eigen_solver.supports_aux_operators():
raise TypeError(
f"The provided MinimumEigensolver ({type(min_eigen_solver)}) "
"does not support auxiliary operators."
)
self._min_eigen_solver = min_eigen_solver
@property
def encoding(self) -> QuantumRandomAccessEncoding:
"""The encoding."""
return self._encoding
@encoding.setter
def encoding(self, encoding: QuantumRandomAccessEncoding) -> None:
"""Set the encoding"""
if encoding.num_qubits == 0:
raise ValueError(
"The passed encoder has no variables associated with it; you probably "
"need to call `encode()` to encode it with a `QuadraticProgram`."
)
# Instead of copying, we "freeze" the encoding to ensure it is not
# modified going forward.
encoding.freeze()
self._encoding = encoding
def get_compatibility_msg(self, problem: QuadraticProgram) -> str:
if problem != self.encoding.problem:
return (
"The problem passed does not match the problem used "
"to construct the QuantumRandomAccessEncoding."
)
return ""
def solve_relaxed(
self,
) -> Tuple[
Union[MinimumEigensolverResult, LegacyMinimumEigensolverResult], RoundingContext
]:
"""Solve the relaxed Hamiltonian given the ``encoding`` provided to the constructor."""
# Get the ordered list of operators that correspond to each decision
# variable. This line assumes the variables are numbered consecutively
# starting with 0. Note that under this assumption, the following
# range is equivalent to `sorted(self.encoding.var2op.keys())`. See
# encoding.py for more commentary on this assumption, which always
# holds when starting from a `QuadraticProgram`.
variable_ops = [self.encoding.term2op(i) for i in range(self.encoding.num_vars)]
# solve relaxed problem
start_time_relaxed = time.time()
relaxed_results = self.min_eigen_solver.compute_minimum_eigenvalue(
self.encoding.qubit_op, aux_operators=variable_ops
)
stop_time_relaxed = time.time()
relaxed_results.time_taken = stop_time_relaxed - start_time_relaxed
trace_values = [v[0] for v in _get_aux_operators_evaluated(relaxed_results)]
# Collect inputs for rounding
# double check later that there's no funny business with the
# parameter ordering.
# If the relaxed solution can be expressed as an explicit circuit
# then always express it that way - even if a statevector simulator
# was used and the actual wavefunction could be used. The only exception
# is the numpy eigensolver. If you wish to round the an explicit statevector,
# you must do so by manually rounding and passing in a QuantumCircuit
# initialized to the desired state.
if hasattr(self.min_eigen_solver, "ansatz"):
circuit = self.min_eigen_solver.ansatz.bind_parameters(
relaxed_results.optimal_point
)
elif isinstance(
self.min_eigen_solver,
(NumPyMinimumEigensolver, LegacyNumPyMinimumEigensolver),
):
statevector = relaxed_results.eigenstate
if isinstance(self.min_eigen_solver, LegacyNumPyMinimumEigensolver):
# statevector is a StateFn in this case, so we must convert it
# to a Statevector
statevector = statevector.primitive
circuit = QuantumCircuit(self.encoding.num_qubits)
circuit.initialize(statevector)
else:
circuit = None
rounding_context = RoundingContext(
encoding=self.encoding,
trace_values=trace_values,
circuit=circuit,
)
return relaxed_results, rounding_context
def solve(self, problem: Optional[QuadraticProgram] = None) -> OptimizationResult:
if problem is None:
problem = self.encoding.problem
else:
if problem != self.encoding.problem:
raise ValueError(
"The problem given must exactly match the problem "
"used to generate the encoded operator. Alternatively, "
"the argument to `solve` can be left blank."
)
# Solve relaxed problem
# ============================
(relaxed_results, rounding_context) = self.solve_relaxed()
# Round relaxed solution
# ============================
rounding_results = self.rounding_scheme.round(rounding_context)
# Process rounding results
# ============================
# The rounding classes don't have enough information to evaluate the
# objective function, so they return a RoundingSolutionSample, which
# contains only part of the information in the SolutionSample. Here we
# fill in the rest.
samples: List[SolutionSample] = []
for sample in rounding_results.samples:
samples.append(
SolutionSample(
x=sample.x,
fval=problem.objective.evaluate(sample.x),
probability=sample.probability,
status=self._get_feasibility_status(problem, sample.x),
)
)
# TODO: rewrite this logic once the converters are integrated.
# we need to be very careful about ensuring that the problem
# sense is taken into account in the relaxed solution and the rounding
# this is likely only a temporary patch while we are sticking to a
# maximization problem.
fsense = {"MINIMIZE": min, "MAXIMIZE": max}[problem.objective.sense.name]
best_sample = fsense(samples, key=lambda x: x.fval)
return QuantumRandomAccessOptimizationResult(
samples=samples,
x=best_sample.x,
fval=best_sample.fval,
variables=problem.variables,
status=OptimizationResultStatus.SUCCESS,
relaxed_results=relaxed_results,
rounding_results=rounding_results,
relaxed_results_offset=self.encoding.offset,
sense=problem.objective.sense.value,
)
|
https://github.com/AbeerVaishnav13/Using-Qiskit
|
AbeerVaishnav13
|
import qiskit as q
%matplotlib inline
circuit = q.QuantumCircuit(3, 2)
# Grover Search algorithm for 2 qubits and 1 control bit
# Preparation using superposition
circuit.h(0)
circuit.h(1)
circuit.x(2)
circuit.h(2)
circuit.barrier()
# Function Uw
circuit.x(0)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.barrier()
# Function Us
circuit.h(0)
circuit.h(1)
circuit.x(0)
circuit.x(1)
circuit.ccx(0, 1, 2)
circuit.x(0)
circuit.x(1)
circuit.h(0)
circuit.h(1)
circuit.barrier()
# Measure
circuit.measure([0, 1], [0, 1])
# Draw the circuit
circuit.draw()
circuit.draw(output='mpl')
from qiskit import IBMQ
# IBM-Q Account credentials initialization
IBMQ.load_account()
# List all backends available with us
provider = IBMQ.get_provider('ibm-q')
for backend in provider.backends():
try:
qubit_count = len(backend.properties().qubits)
except:
qubit_count = 'simulated'
print(f'{backend.name()} ({qubit_count}) : {backend.status().pending_jobs} queued job(s).')
from qiskit.tools.monitor import job_monitor
# Executing a job on the IBM-Q quantum computer
backend = provider.get_backend('ibmq_ourense')
job = q.execute(circuit, backend = backend, shots = 1024)
job_monitor(job)
from qiskit.visualization import plot_histogram
from matplotlib import style
style.use('dark_background')
# Display histogram for results
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts])
# Trying on ibmq-qasm-simulator
sim_backend = provider.get_backend('ibmq_qasm_simulator')
sim_job = q.execute(circuit, backend = sim_backend, shots = 1024)
job_monitor(sim_job)
# Results of the ibmq-qasm-simulator
sim_result = sim_job.result()
sim_counts = sim_result.get_counts(circuit)
plot_histogram([sim_counts])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.