repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
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.
"""Quickstart example on transpiling and executing circuits."""
import qiskit
from qiskit.circuit.library import QuantumVolume
from qiskit_aqt_provider import AQTProvider
# Define a circuit
circuit = QuantumVolume(5)
circuit.measure_all()
# Select an execution backend
provider = AQTProvider("ACCESS_TOKEN")
backend = provider.get_backend("offline_simulator_no_noise")
# Transpile the circuit to target the selected AQT backend
transpiled_circuit = qiskit.transpile(circuit, backend, optimization_level=2)
print(transpiled_circuit)
# Execute the circuit on the selected AQT backend
result = backend.run(transpiled_circuit, shots=50).result()
if result.success:
print(result.get_counts())
else: # pragma: no cover
raise RuntimeError
|
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_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
header = ['instance', 'iteration', 'distance']
length_instances = 40
with open('qaoa_multiple_distance.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
for instance in range(length_instances):
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
index = -1
for sample in UNIFORM_CONVERGENCE_SAMPLE:
mean = sample["mean"]
index += 1
distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"]))
UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state
iteration = 0
for sample in UNIFORM_CONVERGENCE_SAMPLE:
iteration += 1
mean = sample["mean"]
distance = sample["distance_pgs"]
writer.writerow([instance,iteration, distance])
|
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 Stinespring quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info import Stinespring
from .channel_test_case import ChannelTestCase
class TestStinespring(ChannelTestCase):
"""Tests for Stinespring channel representation."""
def test_init(self):
"""Test initialization"""
# Initialize from unitary
chan = Stinespring(self.UI)
assert_allclose(chan.data, self.UI)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Stinespring
chan = Stinespring(self.depol_stine(0.5))
assert_allclose(chan.data, self.depol_stine(0.5))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize from Non-CPTP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
chan = Stinespring((stine_l, stine_r))
assert_allclose(chan.data, (stine_l, stine_r))
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Initialize with redundant second op
chan = Stinespring((stine_l, stine_l))
assert_allclose(chan.data, stine_l)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, Stinespring, stine_l, input_dims=4, output_dims=4)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = Stinespring(circuit)
target = Stinespring(target)
self.assertEqual(op, target)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, Stinespring, circuit)
def test_equal(self):
"""Test __eq__ method"""
stine = tuple(self.rand_matrix(4, 2) for _ in range(2))
self.assertEqual(Stinespring(stine), Stinespring(stine))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = Stinespring(mat)
cpy = orig.copy()
cpy._data[0][0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = Stinespring(mat)
clone = copy.copy(orig)
clone._data[0][0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(Stinespring(self.depol_stine(0.5)).is_cptp())
self.assertTrue(Stinespring(self.UX).is_cptp())
# Non-CP
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
self.assertFalse(Stinespring((stine_l, stine_r)).is_cptp())
self.assertFalse(Stinespring(self.UI + self.UX).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
stine_l, stine_r = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring list
targ = Stinespring(stine_l.conj(), output_dims=4)
chan1 = Stinespring(stine_l, output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
# Double Stinespring list
targ = Stinespring((stine_l.conj(), stine_r.conj()), output_dims=4)
chan1 = Stinespring((stine_l, stine_r), output_dims=4)
chan = chan1.conjugate()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (2, 4))
def test_transpose(self):
"""Test transpose method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T, 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T, stine_r.T), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.transpose()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_adjoint(self):
"""Test adjoint method."""
stine_l, stine_r = self.rand_matrix(4, 2), self.rand_matrix(4, 2)
# Single square Stinespring list
targ = Stinespring(stine_l.T.conj(), 4, 2)
chan1 = Stinespring(stine_l, 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
# Double square Stinespring list
targ = Stinespring((stine_l.T.conj(), stine_r.T.conj()), 4, 2)
chan1 = Stinespring((stine_l, stine_r), 2, 4)
chan = chan1.adjoint()
self.assertEqual(chan, targ)
self.assertEqual(chan.dim, (4, 2))
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, Stinespring(np.eye(4)))
self.assertRaises(QiskitError, Stinespring(np.eye(2)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_dot(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
rho_targ = rho_init.evolve(Stinespring(self.UZ))
self.assertEqual(rho_init.evolve(chan1.dot(chan2)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan2), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan1.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan1 @ chan1), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
self.assertEqual(rho_init.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho_init.evolve(chan2 @ chan1), rho_targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = Stinespring(self.UX)
chan2 = Stinespring(self.UY)
chan = chan1.compose(chan2, front=True)
rho_targ = rho_init & Stinespring(self.UZ)
self.assertEqual(rho_init.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = Stinespring(self.depol_stine(0.5))
chan = chan1.compose(chan1, front=True)
rho_targ = rho_init & Stinespring(self.depol_stine(0.75))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Compose different dimensions
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(8, 4)
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=4, output_dims=2)
rho_targ = rho_init & chan1 & chan2
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.expand(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = Stinespring(self.UI)
chan2 = Stinespring(self.UX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Completely depolarizing
chan_dep = Stinespring(self.depol_stine(1))
chan = chan_dep.tensor(chan_dep)
rho_targ = DensityMatrix(np.diag([1, 1, 1, 1]) / 4)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
rho_init = DensityMatrix(np.diag([1, 0]))
p_id = 0.9
chan1 = Stinespring(self.depol_stine(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan = chan1.power(3)
rho_targ = rho_init & chan1 & chan1 & chan1
self.assertEqual(rho_init & chan, rho_targ)
rho_targ = rho_init & Stinespring(self.depol_stine(1 - p_id3))
self.assertEqual(rho_init & chan, rho_targ)
def test_add(self):
"""Test add method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) + (rho_init & chan2)
chan = chan1._add(chan2)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 + chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 2 * (rho_init & chan)
chan = chan._add(chan)
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_subtract(self):
"""Test subtract method."""
# Random input test state
rho_init = DensityMatrix(self.rand_rho(2))
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Random Single-Stinespring maps
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
chan2 = Stinespring(stine2, input_dims=2, output_dims=4)
rho_targ = (rho_init & chan1) - (rho_init & chan2)
chan = chan1 - chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Random Single-Stinespring maps
chan = Stinespring((stine1, stine2))
rho_targ = 0 * (rho_init & chan)
chan = chan - chan
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_add_qargs(self):
"""Test add method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_sub_qargs(self):
"""Test sub method with qargs."""
rho = DensityMatrix(self.rand_rho(8))
stine = self.rand_matrix(32, 8)
stine0 = self.rand_matrix(8, 2)
op = Stinespring(stine)
op0 = Stinespring(stine0)
eye = Stinespring(self.UI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(rho & value, rho & target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(rho & value, rho & target)
def test_multiply(self):
"""Test multiply method."""
# Random initial state and Stinespring ops
rho_init = DensityMatrix(self.rand_rho(2))
val = 0.5
stine1, stine2 = self.rand_matrix(16, 2), self.rand_matrix(16, 2)
# Single Stinespring set
chan1 = Stinespring(stine1, input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan1)
chan = chan1._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan1
self.assertEqual(rho_init.evolve(chan), rho_targ)
rho_targ = (rho_init & chan1) * val
chan = chan1 * val
self.assertEqual(rho_init.evolve(chan), rho_targ)
# Double Stinespring set
chan2 = Stinespring((stine1, stine2), input_dims=2, output_dims=4)
rho_targ = val * (rho_init & chan2)
chan = chan2._multiply(val)
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = val * chan2
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = Stinespring(self.depol_stine(1))
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
rho_init = DensityMatrix(np.diag([1, 0]))
rho_targ = DensityMatrix(np.diag([-0.5, -0.5]))
chan = -Stinespring(self.depol_stine(1))
self.assertEqual(rho_init.evolve(chan), rho_targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("ggplot")
from pprint import pprint
import pickle
import time
import datetime
%matplotlib inline
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, X, Y, Z, I
from qiskit.opflow.state_fns.dict_state_fn import DictStateFn
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, 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
# unused for this file
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../../solutions/utils/")
import circuit_utils, zne_utils, tomography_utils
importlib.reload(circuit_utils)
importlib.reload(zne_utils) # unused for this file
importlib.reload(tomography_utils) # unused for this file
from circuit_utils import *
from zne_utils import zne_wrapper, zne_decoder
from tomography_utils import expvals_to_valid_rho
from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
backend = Aer.get_backend("qasm_simulator")
# Returns the matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line
def H_heis3():
# Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product)
XXs = (I^X^X) + (X^X^I)
YYs = (I^Y^Y) + (Y^Y^I)
ZZs = (I^Z^Z) + (Z^Z^I)
# Sum interactions
H = XXs + YYs + ZZs
# Return Hamiltonian
return H
# Returns the matrix representation of U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line
def U_heis3(t):
# Compute XXX Hamiltonian for 3 spins in a line
H = H_heis3()
# Return the exponential of -i multipled by time t multipled by the 3 spin XXX Heisenberg Hamilonian
return (t * H).exp_i()
# Define array of time points
ts = np.linspace(0, np.pi, 100)
target_state = DictStateFn({"000": 0,
"001": 0,
"010": 1,
"011": 0,
"100": 0,
"101": 0,
"110": 1,
"111": 0}, 1 / np.sqrt(2))
print(DensityMatrix(target_state.to_density_matrix()).is_valid())
# Compute probability of remaining in |110> state over the array of time points
# ~target_state gives the bra of the initial state (<110|)
# @ is short hand for matrix multiplication
# U_heis3(t) is the unitary time evolution at time t
# t needs to be wrapped with float(t) to avoid a bug
# (...).eval() returns the inner product <110|U_heis3(t)|110>
# np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110>
probs_010_110 = [np.abs((~target_state @ U_heis3(float(t)) @ target_state).eval())**2 for t in ts]
# Plot evolution of |110>
plt.figure(dpi=200)
plt.plot(ts, probs_010_110)
plt.xlabel('time')
plt.ylabel(r'probability of state $|010\rangle + |110\rangle$')
plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$')
# plt.grid()
plt.show()
num_qubits = 3
# The final time of the state evolution
target_times = [i * np.pi / 20 for i in range(0, 20 + 1)]
pprint(target_times)
# 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] # unused for this file
shots = 1 << 13
reps = 8 # unused
target_state = np.zeros((1 << num_qubits, 1 << num_qubits))
target_state[2, 2] = target_state[6, 6] = target_state[2, 6] = target_state[6, 2] = 0.5
target_state = DensityMatrix(target_state)
target_state.draw("latex")
prob_list = []
for target_time in target_times:
print("target_time: ", target_time)
t1 = time.perf_counter()
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
cr = ClassicalRegister(num_qubits, name="c")
qc = QuantumCircuit(qr, cr)
# 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>)
qc.h(0)
qc.x(1)
general_subspace_encoder(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
general_subspace_decoder(qc, targets=[0, 1, 2]) # decode
qc.x(1)
qc.h(0)
qc.measure(qr, cr[::-1])
# 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")
# optimize circuit
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_qc (depth:", t3_qc.depth(), ")")
t3_qc = transpile(t3_qc, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_qc (depth:", t3_qc.depth(), ")")
job = execute(t3_qc, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
prob = job.result().get_counts().get("0" * num_qubits, 0) / shots
prob_list.append(prob)
t2 = time.perf_counter()
print(r'probability of state |010> + |110> = {:.4f}'.format(prob))
print("time:", t2 - t1)
print()
plt.figure(dpi=200)
plt.plot(ts, probs_010_110, label="theoretical prediction")
plt.scatter(target_times, prob_list, c="green", zorder=4)
plt.legend(("theoretical prediction", "proposed method"))
plt.xlabel('time')
plt.ylabel(r'probability of state $|010\rangle + |110\rangle$')
plt.title(r'Evolution of state $|010\rangle + |110\rangle$ under $H_{Heis3}$')
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
fid_list = []
for target_time in target_times:
print("target_time: ", target_time)
t1 = time.perf_counter()
# 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>)
qc.h(0)
qc.x(1)
general_subspace_encoder(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
general_subspace_decoder(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
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), ")")
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
rho = StateTomographyFitter(job.result(), t3_zne_qcs).fit(method='lstsq')
fid = state_fidelity(rho, target_state)
fid_list.append(fid)
t2 = time.perf_counter()
print('state tomography fidelity = {:.4f}'.format(fid))
print("time:", t2 - t1)
print()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for circuit MPL drawer"""
import unittest
import os
import math
from test.visual import VisualTestUtilities
from pathlib import Path
import numpy as np
from numpy import pi
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.providers.fake_provider import FakeTenerife
from qiskit.visualization.circuit.circuit_visualization import _matplotlib_circuit_drawer
from qiskit.circuit.library import (
XGate,
MCXGate,
HGate,
RZZGate,
SwapGate,
DCXGate,
ZGate,
SGate,
U1Gate,
CPhaseGate,
)
from qiskit.circuit.library import MCXVChain
from qiskit.extensions import HamiltonianGate
from qiskit.circuit import Parameter, Qubit, Clbit
from qiskit.circuit.library import IQP
from qiskit.quantum_info.random import random_unitary
from qiskit.utils import optionals
if optionals.HAS_MATPLOTLIB:
from matplotlib.pyplot import close as mpl_close
else:
raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".')
BASE_DIR = Path(__file__).parent
RESULT_DIR = Path(BASE_DIR) / "circuit_results"
TEST_REFERENCE_DIR = Path(BASE_DIR) / "references"
FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures"
FAILURE_PREFIX = "circuit_failure_"
class TestCircuitMatplotlibDrawer(QiskitTestCase):
"""Circuit MPL visualization"""
def setUp(self):
super().setUp()
self.circuit_drawer = VisualTestUtilities.save_data_wrap(
_matplotlib_circuit_drawer, str(self), RESULT_DIR
)
if not os.path.exists(FAILURE_DIFF_DIR):
os.makedirs(FAILURE_DIFF_DIR)
if not os.path.exists(RESULT_DIR):
os.makedirs(RESULT_DIR)
def tearDown(self):
super().tearDown()
mpl_close("all")
@staticmethod
def _image_path(image_name):
return os.path.join(RESULT_DIR, image_name)
@staticmethod
def _reference_path(image_name):
return os.path.join(TEST_REFERENCE_DIR, image_name)
def test_empty_circuit(self):
"""Test empty circuit"""
circuit = QuantumCircuit()
fname = "empty_circut.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.h(0)
from qiskit import pulse
with pulse.build(name="hadamard") as h_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(0)
)
circuit.add_calibration("h", [0], h_q0)
fname = "calibrations.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_control_gates(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.cx(0, 1)
circuit.ch(0, 1)
from qiskit import pulse
with pulse.build(name="cnot") as cx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("cx", [0, 1], cx_q01)
with pulse.build(name="ch") as ch_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("ch", [0, 1], ch_q01)
fname = "calibrations_with_control_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_swap_and_reset(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.swap(0, 1)
circuit.reset(0)
from qiskit import pulse
with pulse.build(name="swap") as swap_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("swap", [0, 1], swap_q01)
with pulse.build(name="reset") as reset_q0:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("reset", [0], reset_q0)
fname = "calibrations_with_swap_and_reset.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_calibrations_with_rzz_and_rxx(self):
"""Test calibrations annotations
See https://github.com/Qiskit/qiskit-terra/issues/5920
"""
circuit = QuantumCircuit(2, 2)
circuit.rzz(pi, 0, 1)
circuit.rxx(pi, 0, 1)
from qiskit import pulse
with pulse.build(name="rzz") as rzz_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rzz", [0, 1], rzz_q01)
with pulse.build(name="rxx") as rxx_q01:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1)
)
circuit.add_calibration("rxx", [0, 1], rxx_q01)
fname = "calibrations_with_rzz_and_rxx.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_no_ops(self):
"""Test circuit with no ops.
See https://github.com/Qiskit/qiskit-terra/issues/5393"""
circuit = QuantumCircuit(2, 3)
fname = "no_op_circut.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_long_name(self):
"""Test to see that long register names can be seen completely
As reported in #2605
"""
# add a register with a very long name
qr = QuantumRegister(4, "veryLongQuantumRegisterName")
# add another to make sure adjustments are made based on longest
qrr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr, qrr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
fname = "long_name.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_multi_underscore_reg_names(self):
"""Test that multi-underscores in register names display properly"""
q_reg1 = QuantumRegister(1, "q1_re__g__g")
q_reg3 = QuantumRegister(3, "q3_re_g__g")
c_reg1 = ClassicalRegister(1, "c1_re_g__g")
c_reg3 = ClassicalRegister(3, "c3_re_g__g")
circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3)
fname = "multi_underscore_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "multi_underscore_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditional(self):
"""Test that circuits with conditionals draw correctly"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr, 2)
fname = "reg_conditional.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bit_conditional_with_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=True."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_bundle.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bit_conditional_no_cregbundle(self):
"""Test that circuits with single bit conditionals draw correctly
with cregbundle=False."""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.x(qr[1]).c_if(cr[1], 0)
fname = "bit_conditional_no_bundle.png"
self.circuit_drawer(circuit, filename=fname, cregbundle=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_plot_partial_barrier(self):
"""Test plotting of partial barriers."""
# generate a circuit with barrier and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier(0)
circuit.h(q[0])
fname = "plot_partial_barrier.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_plot_barriers(self):
"""Test to see that plotting barriers works.
If it is set to False, no blank columns are introduced"""
# generate a circuit with barriers and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier()
# check for other barrier like commands
circuit.h(q[1])
# this import appears to be unused, but is actually needed to get snapshot instruction
import qiskit.extensions.simulator # pylint: disable=unused-import
circuit.snapshot("1")
# check the barriers plot properly when plot_barriers= True
fname = "plot_barriers_true.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "plot_barriers_false.png"
self.circuit_drawer(circuit, filename=fname2, plot_barriers=False)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_no_barriers_false(self):
"""Generate the same circuit as test_plot_barriers but without the barrier commands
as this is what the circuit should look like when displayed with plot barriers false"""
q1 = QuantumRegister(2, "q")
c1 = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q1, c1)
circuit.h(q1[0])
circuit.h(q1[1])
fname = "no_barriers.png"
self.circuit_drawer(circuit, filename=fname, plot_barriers=False)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_minus1(self):
"""Test to see that fold=-1 is no folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_minus1.png"
self.circuit_drawer(circuit, fold=-1, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_4(self):
"""Test to see that fold=4 is folding"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
for _ in range(3):
circuit.h(0)
circuit.x(0)
fname = "fold_4.png"
self.circuit_drawer(circuit, fold=4, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_big_gates(self):
"""Test large gates with params"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])
circuit.unitary([[1, 0], [0, 1]], [qr[0]])
matrix = np.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])
circuit = circuit.bind_parameters({theta: 1})
circuit.isometry(np.eye(4, 4), list(range(3, 5)), [])
fname = "big_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cnot(self):
"""Test different cnot gates (ccnot, mcx, etc)"""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]])
circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]])
circuit.append(MCXVChain(3, dirty_ancillas=True), [qr[0], qr[1], qr[2], qr[3], qr[5]])
fname = "cnot.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cz(self):
"""Test Z and Controlled-Z Gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.z(0)
circuit.cz(0, 1)
circuit.append(ZGate().control(3, ctrl_state="101"), [0, 1, 2, 3])
circuit.append(ZGate().control(2), [1, 2, 3])
circuit.append(ZGate().control(1, ctrl_state="0", label="CZ Gate"), [2, 3])
fname = "cz.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_pauli_clifford(self):
"""Test Pauli(green) and Clifford(blue) gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(0)
circuit.z(0)
circuit.id(0)
circuit.h(1)
circuit.cx(1, 2)
circuit.cy(1, 2)
circuit.cz(1, 2)
circuit.swap(3, 4)
circuit.s(3)
circuit.sdg(3)
circuit.iswap(3, 4)
circuit.dcx(3, 4)
fname = "pauli_clifford.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_creg_initial(self):
"""Test cregbundle and initial state options"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
circuit.h(0)
circuit.x(1)
fname = "creg_initial_true.png"
self.circuit_drawer(circuit, filename=fname, cregbundle=True, initial_state=True)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "creg_initial_false.png"
self.circuit_drawer(circuit, filename=fname2, cregbundle=False, initial_state=False)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_r_gates(self):
"""Test all R gates"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.r(3 * pi / 4, 3 * pi / 8, 0)
circuit.rx(pi / 2, 1)
circuit.ry(-pi / 2, 2)
circuit.rz(3 * pi / 4, 3)
circuit.rxx(pi / 2, 0, 1)
circuit.ryy(3 * pi / 4, 2, 3)
circuit.rzx(-pi / 2, 0, 1)
circuit.rzz(pi / 2, 2, 3)
fname = "r_gates.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_ctrl_labels(self):
"""Test control labels"""
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cy(1, 0, label="Bottom Y label")
circuit.cu(pi / 2, pi / 2, pi / 2, 0, 2, 3, label="Top U label")
circuit.ch(0, 1, label="Top H label")
circuit.append(
HGate(label="H gate label").control(3, label="H control label", ctrl_state="010"),
[qr[1], qr[2], qr[3], qr[0]],
)
fname = "ctrl_labels.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_cswap_rzz(self):
"""Test controlled swap and rzz gates"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(0, 1, 2)
circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0])
fname = "cswap_rzz.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_ghz_to_gate(self):
"""Test controlled GHZ to_gate circuit"""
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
ghz_circuit = QuantumCircuit(3, name="this is a WWWWWWWWWWWide name Ctrl-GHZ Circuit")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="10")
circuit.append(ccghz, [4, 0, 1, 3, 2])
fname = "ghz_to_gate.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_scale(self):
"""Tests scale
See: https://github.com/Qiskit/qiskit-terra/issues/4179"""
circuit = QuantumCircuit(5)
circuit.unitary(random_unitary(2**5), circuit.qubits)
fname = "scale_default.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "scale_half.png"
self.circuit_drawer(circuit, filename=fname2, scale=0.5)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname3 = "scale_double.png"
self.circuit_drawer(circuit, filename=fname3, scale=2)
ratio3 = VisualTestUtilities._save_diff(
self._image_path(fname3),
self._reference_path(fname3),
fname3,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
self.assertGreaterEqual(ratio3, 0.9999)
def test_pi_param_expr(self):
"""Test pi in circuit with parameter expression."""
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
fname = "pi_in_param_expr.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_partial_layout(self):
"""Tests partial_layout
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
circuit = QuantumCircuit(3)
circuit.h(1)
transpiled = transpile(
circuit,
backend=FakeTenerife(),
basis_gates=["id", "cx", "rz", "sx", "x"],
optimization_level=0,
initial_layout=[1, 2, 0],
seed_transpiler=0,
)
fname = "partial_layout.png"
self.circuit_drawer(transpiled, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_init_reset(self):
"""Test reset and initialize with 1 and 2 qubits"""
circuit = QuantumCircuit(2)
circuit.initialize([0, 1], 0)
circuit.reset(1)
circuit.initialize([0, 1, 0, 0], [0, 1])
fname = "init_reset.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_with_global_phase(self):
"""Tests with global phase"""
circuit = QuantumCircuit(3, global_phase=1.57079632679)
circuit.h(range(3))
fname = "global_phase.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_alternative_colors(self):
"""Tests alternative color schemes"""
ratios = []
for style in ["iqx", "iqx-dark", "textbook"]:
with self.subTest(style=style):
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.s(4)
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
fname = f"{style}_color.png"
self.circuit_drawer(circuit, style={"name": style}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
ratios.append(ratio)
for ratio in ratios:
self.assertGreaterEqual(ratio, 0.9999)
def test_reverse_bits(self):
"""Tests reverse_bits parameter"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
fname = "reverse_bits.png"
self.circuit_drawer(circuit, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_bw(self):
"""Tests black and white style parameter"""
circuit = QuantumCircuit(3, 3)
circuit.h(0)
circuit.x(1)
circuit.sdg(2)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
circuit.swap(1, 2)
circuit.measure_all()
fname = "bw.png"
self.circuit_drawer(circuit, style={"name": "bw"}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_user_style(self):
"""Tests loading a user style"""
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.append(HGate(label="H2"), [1])
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.append(SGate(label="S1"), [4])
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
fname = "user_style.png"
self.circuit_drawer(
circuit,
style={
"name": "user_style",
"displaytext": {"H2": "H_2"},
"displaycolor": {"H2": ("#EEDD00", "#FF0000")},
},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_subfont_change(self):
"""Tests changing the subfont size"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(0)
circuit.u(pi / 2, pi / 2, pi / 2, 1)
circuit.p(pi / 2, 2)
style = {"name": "iqx", "subfontsize": 11}
fname = "subfont.png"
self.circuit_drawer(circuit, style=style, filename=fname)
self.assertEqual(style, {"name": "iqx", "subfontsize": 11}) # check does not change style
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_meas_condition(self):
"""Tests measure with a condition"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
fname = "meas_condition.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_reverse_bits_condition(self):
"""Tests reverse_bits with a condition and gate above"""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
fname = "reverse_bits_cond_true.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "reverse_bits_cond_false.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=False, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_style_custom_gates(self):
"""Tests style for custom gates"""
def cnotnot(gate_label):
gate_circuit = QuantumCircuit(3, name=gate_label)
gate_circuit.cnot(0, 1)
gate_circuit.cnot(0, 2)
gate = gate_circuit.to_gate()
return gate
q = QuantumRegister(3, name="q")
circuit = QuantumCircuit(q)
circuit.append(cnotnot("CNOTNOT"), [q[0], q[1], q[2]])
circuit.append(cnotnot("CNOTNOT_PRIME"), [q[0], q[1], q[2]])
circuit.h(q[0])
fname = "style_custom_gates.png"
self.circuit_drawer(
circuit,
style={
"displaycolor": {"CNOTNOT": ("#000000", "#FFFFFF"), "h": ("#A1A1A1", "#043812")},
"displaytext": {"CNOTNOT_PRIME": "$\\mathrm{CNOTNOT}'$"},
},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_6095(self):
"""Tests controlled-phase gate style
See https://github.com/Qiskit/qiskit-terra/issues/6095"""
circuit = QuantumCircuit(2)
circuit.cp(1.0, 0, 1)
circuit.h(1)
fname = "6095.png"
self.circuit_drawer(
circuit,
style={"displaycolor": {"cp": ("#A27486", "#000000"), "h": ("#A27486", "#000000")}},
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_1q_1c(self):
"""Tests q0-cr0 instruction on a circuit"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(1, 1, name="Inst").to_instruction()
circuit.append(inst, [qr[0]], [cr[0]])
fname = "instruction_1q_1c.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ1(self):
"""Tests q0-q1-q2-cr_20-cr0-cr1 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1], qr[2]], [cr2[0], cr[0], cr[1]])
fname = "instruction_3q_3c_circ1.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ2(self):
"""Tests q3-q0-q2-cr0-cr1-cr_20 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr, cr2)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[0], qr[2]], [cr[0], cr[1], cr2[0]])
fname = "instruction_3q_3c_circ2.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_instruction_3q_3c_circ3(self):
"""Tests q3-q1-q2-cr_31-cr1-cr_30 instruction on a circuit"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
cr3 = ClassicalRegister(2, "cr3")
circuit = QuantumCircuit(qr, cr, cr2, cr3)
inst = QuantumCircuit(3, 3, name="Inst").to_instruction()
circuit.append(inst, [qr[3], qr[1], qr[2]], [cr3[1], cr[1], cr3[0]])
fname = "instruction_3q_3c_circ3.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_overwide_gates(self):
"""Test gates don't exceed width of default fold"""
circuit = QuantumCircuit(5)
initial_state = np.zeros(2**5)
initial_state[5] = 1
circuit.initialize(initial_state)
fname = "wide_params.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_one_bit_regs(self):
"""Test registers with only one bit display without number"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr1 = ClassicalRegister(1, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.h(0)
circuit.measure(0, 0)
fname = "one_bit_regs.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_user_ax_subplot(self):
"""Test for when user supplies ax for a subplot"""
import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(6, 4))
fig.patch.set_facecolor("white")
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
ax1.plot([1, 2, 3])
circuit = QuantumCircuit(4)
circuit.h(0)
circuit.cx(0, 1)
circuit.h(1)
circuit.cx(1, 2)
plt.close(fig)
fname = "user_ax.png"
self.circuit_drawer(circuit, ax=ax2, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_figwidth(self):
"""Test style dict 'figwidth'"""
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.x(1)
circuit.cx(1, 2)
circuit.x(2)
fname = "figwidth.png"
self.circuit_drawer(circuit, style={"figwidth": 5}, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_registerless_one_bit(self):
"""Test circuit with one-bit registers and registerless bits."""
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
fname = "registerless_one_bit.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_measures_with_conditions(self):
"""Test that a measure containing a condition displays"""
qr = QuantumRegister(2, "qr")
cr1 = ClassicalRegister(2, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr1, cr2)
circuit.h(0)
circuit.h(1)
circuit.measure(0, cr1[1])
circuit.measure(1, cr2[0]).c_if(cr1, 1)
circuit.h(0).c_if(cr2, 3)
fname = "measure_cond_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditions_measures_with_bits(self):
"""Test that gates with conditions and measures work with bits"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
fname = "measure_cond_bits_false.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
fname2 = "measure_cond_bits_true.png"
self.circuit_drawer(circuit, cregbundle=True, filename=fname2)
ratio2 = VisualTestUtilities._save_diff(
self._image_path(fname2),
self._reference_path(fname2),
fname2,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
self.assertGreaterEqual(ratio2, 0.9999)
def test_conditional_gates_right_of_measures_with_bits(self):
"""Test that gates with conditions draw to right of measures when same bit"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[1])
circuit.h(qr[1]).c_if(cr[1], 0)
circuit.h(qr[2]).c_if(cr[0], 0)
fname = "measure_cond_bits_right.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_conditions_with_bits_reverse(self):
"""Test that gates with conditions work with bits reversed"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(2, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
fname = "cond_bits_reverse.png"
self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_sidetext_with_condition(self):
"""Test that sidetext gates align properly with conditions"""
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
fname = "sidetext_condition.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_fold_with_conditions(self):
"""Test that gates with conditions draw correctly when folding"""
qr = QuantumRegister(3)
cr = ClassicalRegister(5)
circuit = QuantumCircuit(qr, cr)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 1)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 3)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 5)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 7)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 9)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 11)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 13)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 15)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 17)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 19)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 21)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 23)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 25)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 27)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 29)
circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 31)
fname = "fold_with_conditions.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_idle_wires_barrier(self):
"""Test that idle_wires False works with barrier"""
circuit = QuantumCircuit(4, 4)
circuit.x(2)
circuit.barrier()
fname = "idle_wires_barrier.png"
self.circuit_drawer(circuit, cregbundle=False, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_wire_order(self):
"""Test the wire_order option"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "cx")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
fname = "wire_order.png"
self.circuit_drawer(
circuit,
cregbundle=False,
wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7],
filename=fname,
)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_barrier_label(self):
"""Test the barrier label"""
circuit = QuantumCircuit(2)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
fname = "barrier_label.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_op(self):
"""Test the IfElseOp with if only"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.cx(0, 1)
fname = "if_op.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op(self):
"""Test the IfElseOp with else"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_textbook_style(self):
"""Test the IfElseOp with else in textbook style"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
with circuit.if_test((cr[1], 1)) as _else:
circuit.h(0)
circuit.cx(0, 1)
with _else:
circuit.cx(0, 1)
fname = "if_else_op_textbook.png"
self.circuit_drawer(circuit, style="textbook", filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_with_body(self):
"""Test the IfElseOp with adding a body manually"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.h(1)
circuit.measure(0, 1)
circuit.measure(1, 2)
circuit.x(2)
circuit.x(2, label="XLabel").c_if(cr, 2)
qr2 = QuantumRegister(3, "qr2")
qc2 = QuantumCircuit(qr2, cr)
qc2.x(1)
qc2.y(1)
qc2.z(0)
qc2.x(0, label="X1i").c_if(cr, 4)
circuit.if_else((cr[1], 1), qc2, None, [0, 1, 2], [0, 1, 2])
circuit.x(0, label="X1i")
fname = "if_else_body.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_nested(self):
"""Test the IfElseOp with complex nested if/else"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_nested.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_wire_order(self):
"""Test the IfElseOp with complex nested if/else and wire_order"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_wire_order.png"
self.circuit_drawer(circuit, wire_order=[2, 0, 3, 1, 4, 5, 6], filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_if_else_op_fold(self):
"""Test the IfElseOp with complex nested if/else and fold"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
with circuit.if_test((cr[1], 1)) as _else:
circuit.x(0, label="X c_if").c_if(cr, 4)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
circuit.y(1)
with circuit.if_test((cr[1], 1)):
circuit.y(1)
circuit.z(2)
with circuit.if_test((cr[2], 1)):
circuit.cx(0, 1)
with circuit.if_test((cr[1], 1)):
circuit.h(0)
circuit.x(1)
with _else:
circuit.y(1)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
circuit.x(1)
inst = QuantumCircuit(2, 2, name="Inst").to_instruction()
circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]])
circuit.x(0)
fname = "if_else_op_fold.png"
self.circuit_drawer(circuit, fold=7, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_while_loop_op(self):
"""Test the WhileLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(0)
circuit.measure(0, 2)
with circuit.while_loop((cr[0], 0)):
circuit.h(0)
circuit.cx(0, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.x(0)
fname = "while_loop.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_for_loop_op(self):
"""Test the ForLoopOp"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
a = Parameter("a")
circuit.h(0)
circuit.measure(0, 2)
with circuit.for_loop((2, 4, 8, 16), loop_parameter=a):
circuit.h(0)
circuit.cx(0, 1)
circuit.rx(pi / a, 1)
circuit.measure(0, 0)
with circuit.if_test((cr[2], 1)):
circuit.z(0)
fname = "for_loop.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
def test_switch_case_op(self):
"""Test the SwitchCaseOp"""
qreg = QuantumRegister(3, "q")
creg = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qreg, creg)
circuit.h([0, 1, 2])
circuit.measure([0, 1, 2], [0, 1, 2])
with circuit.switch(creg) as case:
with case(0, 1, 2):
circuit.x(0)
with case(3, 4, 5):
circuit.y(1)
circuit.y(0)
circuit.y(0)
with case(case.DEFAULT):
circuit.cx(0, 1)
circuit.h(0)
fname = "switch_case.png"
self.circuit_drawer(circuit, filename=fname)
ratio = VisualTestUtilities._save_diff(
self._image_path(fname),
self._reference_path(fname),
fname,
FAILURE_DIFF_DIR,
FAILURE_PREFIX,
)
self.assertGreaterEqual(ratio, 0.9999)
if __name__ == "__main__":
unittest.main(verbosity=1)
|
https://github.com/nahumsa/volta
|
nahumsa
|
import sys
sys.path.append('../../')
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import I, X, Y, Z
import matplotlib.pyplot as plt
from volta.observables import sample_hamiltonian
from volta.hamiltonians import BCS_hamiltonian
EPSILONS = [3, 3, 3, 3]
V = -2
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z) #BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix())
print(f"Eigenvalues: {eigenvalues}")
def create_circuit(n: int) -> list:
return [QuantumCircuit(n) for _ in range(2)]
n = hamiltonian.num_qubits
init_states = create_circuit(n)
def copy_unitary(list_states: list) -> list:
out_states = []
for state in list_states:
out_states.append(state.copy())
return out_states
import textwrap
def apply_initialization(list_states: list) -> None:
for ind, state in enumerate(list_states):
b = bin(ind)[2:]
if len(b) != n:
b = '0'*(n - len(b)) + b
spl = textwrap.wrap(b, 1)
for qubit, val in enumerate(spl):
if val == '1':
state.x(qubit)
apply_initialization(init_states)
initialization = copy_unitary(init_states)
from qiskit.circuit.library import TwoLocal
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2)
def apply_ansatz(ansatz: QuantumCircuit, list_states: list) -> None:
for states in list_states:
states.append(ansatz, range(n))
apply_ansatz(ansatz, init_states)
init_states[-1].draw('mpl')
def _apply_varform_params(ansatz, params: list):
"""Get an hardware-efficient ansatz for n_qubits
given parameters.
"""
# Define variational Form
var_form = ansatz
# Get Parameters from the variational form
var_form_params = sorted(var_form.parameters, key=lambda p: p.name)
# Check if the number of parameters is compatible
assert len(var_form_params) == len(params), "The number of parameters don't match"
# Create a dictionary with the parameters and values
param_dict = dict(zip(var_form_params, params))
# Assing those values for the ansatz
wave_function = var_form.assign_parameters(param_dict)
return wave_function
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
def cost_function(params:list) -> float:
backend = BasicAer.get_backend('qasm_simulator')
backend = QuantumInstance(backend, shots=10000)
cost = 0
w = np.arange(len(init_states), 0, -1)
for i, state in enumerate(init_states):
qc = _apply_varform_params(state, params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian,
ansatz=qc,
backend=backend)
cost += w[i] * hamiltonian_eval
return cost
from qiskit.aqua.components.optimizers import COBYLA
optimizer = COBYLA()
n_parameters = len(init_states[0].parameters)
params = np.random.rand(n_parameters)
optimal_params, mean_energy, n_iters = optimizer.optimize(num_vars=n_parameters,
objective_function=cost_function,
initial_point=params)
mean_energy, sum(eigenvalues[:2])
# Optimized first ansatz
ansatz_1 = _apply_varform_params(ansatz, optimal_params)
ansatz_1.name = 'U(θ)'
def cost_function_ind(ind: int, params:list) -> float:
backend = BasicAer.get_backend('qasm_simulator')
backend = QuantumInstance(backend, shots=10000)
cost = 0
# Define Ansatz
qc = _apply_varform_params(init_states[ind], params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian,
ansatz=qc,
backend=backend)
cost += hamiltonian_eval
return cost
energies = []
for i in range(len(init_states)):
energies.append(cost_function_ind(ind=i, params=optimal_params))
energies = np.array(energies)
for i in range(len(init_states)):
print(f"Value for the {i} state: {energies[i]}\t expected energy {eigenvalues[i]}")
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
# set up circuit (no measurements required)
qc = QuantumCircuit(2)
qc.x(0) # qubits numbered from the right, so qubit 0 is the qubit on the right
qc.z(1) # and qubit 1 is on the left
# set up simulator that returns unitary matrix
backend = Aer.get_backend('unitary_simulator')
# run the circuit to get the matrix
gate = execute(qc,backend).result().get_unitary()
# now we use some fanciness to display it in latex
from IPython.display import display, Markdown, Latex
gate_latex = '\\begin{pmatrix}'
for line in gate:
for element in line:
gate_latex += str(element) + '&'
gate_latex = gate_latex[0:-1]
gate_latex += '\\\\'
gate_latex = gate_latex[0:-2]
gate_latex += '\end{pmatrix}'
display(Markdown(gate_latex))
|
https://github.com/sam-pf/pf-qiskit
|
sam-pf
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
Modified Aug 2021s
@author: hassi
"""
print("Ch 7: IBM Q simulators and how they are used")
print("--------------------------------------------")
# Import Qiskit and load account
from qiskit import Aer, IBMQ
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
# Load backends
backends=Aer.backends()
print("\nAer backends:\n\n",backends)
# Collect Aer simulators
simulators=[]
for sim in range(0,len(backends)):
backend = Aer.get_backend(str(backends[sim]))
simulators.append(backend.configuration())
# Add IBM Q simulator
ibmq_simulator=provider.backends(simulator=True)
#simulators.append(provider.get_backend(str(ibmq_simulator[0])).configuration())
for qsim in range(0,len(ibmq_simulator)):
backend = provider.get_backend(str(ibmq_simulator[qsim]))
simulators.append(backend.configuration())
# Display the raw simulator configuration details
print("\nSimulator configuration details:")
for sim in range(0,len(simulators)):
print("\n")
print(simulators[sim].backend_name)
print(simulators[sim].to_dict())
# Fish out criteria to compare
print("\n")
print("{0:25} {1:<10} {2:<10} {3:<10}".format("Name","#Qubits","Max shots.","Description"))
print("{0:25} {1:<10} {2:<10} {3:<10}".format("----","-------","--------","------------"))
description=[]
for sim in range(0,len(simulators)):
if simulators[sim].local==True:
description.append(simulators[sim].description)
elif simulators[sim].local==False:
description.append("Non-local IBM Q simulator")
print("{0:25} {1:<10} {2:<10} {3:<10}".format(simulators[sim].backend_name,
simulators[sim].n_qubits,
simulators[sim].max_shots,
description[sim]))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from sklearn.datasets import make_blobs
# example dataset
features, labels = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True)
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
features = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(features)
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=15, shuffle=False
)
# number of qubits is equal to the number of features
num_qubits = 2
# number of steps performed during the training procedure
tau = 100
# regularization parameter
C = 1000
from qiskit import BasicAer
from qiskit.circuit.library import ZFeatureMap
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.kernels import FidelityQuantumKernel
algorithm_globals.random_seed = 12345
feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1)
qkernel = FidelityQuantumKernel(feature_map=feature_map)
from qiskit_machine_learning.algorithms import PegasosQSVC
pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau)
# training
pegasos_qsvc.fit(train_features, train_labels)
# testing
pegasos_score = pegasos_qsvc.score(test_features, test_labels)
print(f"PegasosQSVC classification test score: {pegasos_score}")
grid_step = 0.2
margin = 0.2
grid_x, grid_y = np.meshgrid(
np.arange(-margin, np.pi + margin, grid_step), np.arange(-margin, np.pi + margin, grid_step)
)
meshgrid_features = np.column_stack((grid_x.ravel(), grid_y.ravel()))
meshgrid_colors = pegasos_qsvc.predict(meshgrid_features)
import matplotlib.pyplot as plt
plt.figure(figsize=(5, 5))
meshgrid_colors = meshgrid_colors.reshape(grid_x.shape)
plt.pcolormesh(grid_x, grid_y, meshgrid_colors, cmap="RdBu", shading="auto")
plt.scatter(
train_features[:, 0][train_labels == 0],
train_features[:, 1][train_labels == 0],
marker="s",
facecolors="w",
edgecolors="r",
label="A train",
)
plt.scatter(
train_features[:, 0][train_labels == 1],
train_features[:, 1][train_labels == 1],
marker="o",
facecolors="w",
edgecolors="b",
label="B train",
)
plt.scatter(
test_features[:, 0][test_labels == 0],
test_features[:, 1][test_labels == 0],
marker="s",
facecolors="r",
edgecolors="r",
label="A test",
)
plt.scatter(
test_features[:, 0][test_labels == 1],
test_features[:, 1][test_labels == 1],
marker="o",
facecolors="b",
edgecolors="b",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Pegasos Classification")
plt.show()
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_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
|
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
|
martynscn
|
# This code has been adapted and modified from IBM Qiskit 2021 and also from https://github.com/ttlion/ShorAlgQiskit.
# It uses the implementation as contained in the work of Stephane Beauregard (https://arxiv.org/abs/quant-ph/0205095)
# Many thanks to IBM Qiskit team, Tiago Miguel (ttlion), Qubit by Qubit, Peter Shor and Stephane Beauregard.
from typing import Optional, Union, Tuple, List
import math
import array
import fractions
import logging
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute, IBMQ, transpile,BasicAer, Aer, assemble
from qiskit.circuit import Gate, Instruction, ParameterVector
from qiskit.circuit.library import QFT
from qiskit.providers import BaseBackend, Backend
from qiskit.quantum_info import partial_trace
from qiskit.utils import summarize_circuits
from qiskit.utils.arithmetic import is_power
from qiskit.utils.validation import validate_min
from qiskit.utils.quantum_instance import QuantumInstance
import qiskit.visualization
from qiskit.providers.aer import QasmSimulator
from datetime import datetime
import csv
# provider = IBMQ.enable_account("PUT TOKEN HERE")
backend = QasmSimulator()
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" #"last_expr" or "all"
# """ Function to check if N is of type q^p"""
def check_if_power(N):
# """ Check if N is a perfect power in O(n^3) time, n=ceil(logN) """
b=2
while (2**b) <= N:
a = 1
c = N
while (c-a) >= 2:
m = int( (a+c)/2 )
if (m**b) < (N+1):
p = int( (m**b) )
else:
p = int(N+1)
if int(p) == int(N):
print('N is {0}^{1}'.format(int(m),int(b)) )
return True
if p<N:
a = int(m)
else:
c = int(m)
b=b+1
return False
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def create_QFT(circuit,up_reg,n,with_swaps):
i=n-1
while i>=0:
circuit.h(up_reg[i])
j=i-1
while j>=0:
if (np.pi)/(pow(2,(i-j))) > 0:
circuit.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] )
j=j-1
i=i-1
if with_swaps==1:
i=0
while i < ((n-1)/2):
circuit.swap(up_reg[i], up_reg[n-1-i])
i=i+1
def create_inverse_QFT(circuit,up_reg,n,with_swaps):
if with_swaps==1:
i=0
while i < ((n-1)/2):
circuit.swap(up_reg[i], up_reg[n-1-i])
i=i+1
i=0
while i<n:
circuit.h(up_reg[i])
if i != n-1:
j=i+1
y=i
while y>=0:
if (np.pi)/(pow(2,(j-y))) > 0:
circuit.cu1( - (np.pi)/(pow(2,(j-y))) , up_reg[j] , up_reg[y] )
y=y-1
i=i+1
def getAngle(a, N):
s=bin(int(a))[2:].zfill(N)
angle = 0
for i in range(0, N):
if s[N-1-i] == '1':
angle += math.pow(2, -(N-i))
angle *= np.pi
return angle
def getAngles(a,N):
s=bin(int(a))[2:].zfill(N)
angles=np.zeros([N])
for i in range(0, N):
for j in range(i,N):
if s[j]=='1':
angles[N-i-1]+=math.pow(2, -(j-i))
angles[N-i-1]*=np.pi
return angles
def ccphase(circuit, angle, ctl1, ctl2, tgt):
circuit.cu1(angle/2,ctl1,tgt)
circuit.cx(ctl2,ctl1)
circuit.cu1(-angle/2,ctl1,tgt)
circuit.cx(ctl2,ctl1)
circuit.cu1(angle/2,ctl2,tgt)
def phiADD(circuit, q, a, N, inv):
angle=getAngles(a,N)
for i in range(0,N):
if inv==0:
circuit.u1(angle[i],q[i])
else:
circuit.u1(-angle[i],q[i])
def cphiADD(circuit, q, ctl, a, n, inv):
angle=getAngles(a,n)
for i in range(0,n):
if inv==0:
circuit.cu1(angle[i],ctl,q[i])
else:
circuit.cu1(-angle[i],ctl,q[i])
def ccphiADD(circuit,q,ctl1,ctl2,a,n,inv):
angle=getAngles(a,n)
for i in range(0,n):
if inv==0:
ccphase(circuit,angle[i],ctl1,ctl2,q[i])
else:
ccphase(circuit,-angle[i],ctl1,ctl2,q[i])
def ccphiADDmodN(circuit, q, ctl1, ctl2, aux, a, N, n):
ccphiADD(circuit, q, ctl1, ctl2, a, n, 0)
phiADD(circuit, q, N, n, 1)
# phiADD(circuit, q, a,N, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.cx(q[n-1],aux)
create_QFT(circuit,q,n,0)
cphiADD(circuit, q, aux, N, n, 0)
# cphiADD(circuit, q, aux, a, n, 0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.x(q[n-1])
circuit.cx(q[n-1], aux)
circuit.x(q[n-1])
create_QFT(circuit,q,n,0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 0)
def ccphiADDmodN_inv(circuit, q, ctl1, ctl2, aux, a, N, n):
ccphiADD(circuit, q, ctl1, ctl2, a, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.x(q[n-1])
circuit.cx(q[n-1],aux)
circuit.x(q[n-1])
create_QFT(circuit, q, n, 0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 0)
cphiADD(circuit, q, aux, N, n, 1)
# cphiADD(circuit, q, aux, a, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.cx(q[n-1], aux)
create_QFT(circuit, q, n, 0)
phiADD(circuit, q, N, n, 0)
# phiADD(circuit, q, a, N, 0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 1)
def cMULTmodN(circuit, ctl, q, aux, a, N, n):
# up_reg = QuantumRegister(1, name = "up_reg")
# down_reg = QuantumRegister(n, name = "down_reg")
# up_classic = ClassicalRegister(2*n, name="up_classic")
# c_aux = ClassicalRegister(1, name = "aux_classic")
# cMULTmodN_circuit = QuantumCircuit(
# up_reg ,down_reg , aux,up_classic, c_aux,
# name=r"${0}^{{{1}^{{{2}}}}} mod{3}$".format(2,2,int(math.log(math.log(a,2),2)), N)
# )
# create_QFT(cMULTmodN_circuit,aux,n+1,0)
# for i in range(0, n):
# ccphiADDmodN(cMULTmodN_circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1)
# create_inverse_QFT(cMULTmodN_circuit, aux, n+1, 0)
# for i in range(0, n):
# circuit.cswap(ctl,q[i],aux[i])
# cMULTmodN_circuit.cswap(ctl,q[i],aux[i])
# create_QFT(cMULTmodN_circuit, aux, n+1, 0)
# ccphiADDmodN_inv(cMULTmodN_circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1)
# create_inverse_QFT(cMULTmodN_circuit, aux, n+1, 0)
# cMULTmodN_circuit_instruction = cMULTmodN_circuit.to_instruction()
# circuit.append(cMULTmodN_circuit_instruction, [ctl, *down_reg, *aux])
create_QFT(circuit,aux,n+1,0)
for i in range(0, n):
ccphiADDmodN(circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1)
create_inverse_QFT(circuit, aux, n+1, 0)
for i in range(0, n):
circuit.cswap(ctl,q[i],aux[i])
a_inv = modinv(a, N)
create_QFT(circuit, aux, n+1, 0)
i = n-1
while i >= 0:
ccphiADDmodN_inv(circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1)
i -= 1
create_inverse_QFT(circuit, aux, n+1, 0)
def calculate_continued_fraction(b: array.array) -> int:
# """Calculate the continued fraction of x/T from the current terms of expansion b."""
x_over_T = 0
for i in reversed(range(len(b) - 1)):
x_over_T = 1 / (b[i + 1] + x_over_T)
x_over_T += b[0]
frac = fractions.Fraction(x_over_T).limit_denominator()
return frac.denominator
def get_factors(N: int, a: int, measurement: str) -> Optional[List[int]]:
# """Apply the continued fractions to find r and the gcd to find the desired factors."""
x_final = int(measurement, 2)
#print('In decimal, x_final value for this result is: {}.'.format(x_final))
if x_final <= 0:
fail_reason = 'x_final value is <= 0, there are no continued fractions.'
else:
fail_reason = None
#print('Running continued fractions for this case.')
# Calculate T and x/T
T_upper = len(measurement)
T = pow(2, T_upper)
x_over_T = x_final / T ## this is our theta
# Cycle in which each iteration corresponds to putting one more term in the
# calculation of the Continued Fraction (CF) of x/T
# Initialize the first values according to CF rule
i = 0
b = array.array('i')
t = array.array('f')
b.append(math.floor(x_over_T))
t.append(x_over_T - b[i])
exponential = 0.0
while i < N and fail_reason is None:
# From the 2nd iteration onwards, calculate the new terms of the CF based on the previous terms as the rule suggests
if i > 0:
try:
b_temp = math.floor(1 / t[i - 1])
except ZeroDivisionError as err:
b_temp = 0
b.append(b_temp)
try:
t_temp = (1 / t[i - 1]) - b[i]
except ZeroDivisionError as err:
t_temp = 0
t.append(t_temp) # type: ignore
# Calculate the denominator of the CF using the known terms
denominator = calculate_continued_fraction(b)
# Increment i for next iteration
i += 1
if denominator % 2 == 1:
#print('Odd denominator, will try next iteration of continued fractions.')
continue
# Denominator is even, try to get factors of N. Get the exponential a^(r/2)
if denominator < 1000:
try:
exponential = pow(a, denominator / 2)
except OverflowError as err:
exponential = 999999999
# Check if the value is too big or not
if exponential > 1000000:
if exponential == 999999999:
fail_reason = 'OverflowError'
else:
fail_reason = 'denominator of continued fraction is too big (> 10^3).'
else:
# The value is not too big, get the right values and do the proper gcd()
putting_plus = int(exponential + 1)
putting_minus = int(exponential - 1)
one_factor = math.gcd(putting_plus, N)
other_factor = math.gcd(putting_minus, N)
# Check if the factors found are trivial factors or are the desired factors
if any(factor in {1, N} for factor in (one_factor, other_factor)):
#print('Found just trivial factors, not good enough.')
# Check if the number has already been found, (use i - 1 because i was already incremented)
if t[i - 1] == 0:
fail_reason = 'the continued fractions found exactly x_final/(2^(2n)).'
else:
return sorted((one_factor, other_factor))
return None
def process_results(sim_result, circuit, shots, N, a, n):
counts_result = sim_result.get_counts(circuit)
total_counts = len(counts_result)
counts_result_sorted = sorted(counts_result.items(), key=lambda x: x[1], reverse=True)
counts_result_keys = list(counts_result.keys())
counts_result_values = list(counts_result.values())
prob_success=0
prob_failure=0
result_successful_counts = 0
result_failure_counts = 0
for initial_undesired_measurement, frequency in counts_result_sorted:
measurement = initial_undesired_measurement.split(" ")[1]
x_value = int(measurement, 2)
prob_this_result = 100 * frequency/shots
factors = get_factors(N, a, measurement)
if factors:
prob_success = prob_success + prob_this_result
result_successful_counts = result_successful_counts + 1
if factors not in result_factors:
result_factors.append(factors)
elif not factors:
prob_failure = prob_failure + prob_this_result
result_failure_counts = result_failure_counts + 1
return [result_factors, prob_success, prob_failure, total_counts, result_successful_counts,result_failure_counts]
def my_shor(a,N,shots):
start_time_number = datetime.now()
start_time = start_time_number.strftime("%H:%M:%S")
summary_result = dict()
validate_min('N', N, 3)
validate_min('a', a, 2)
if N < 1 or N % 2 == 0:
raise ValueError('The input needs to be an odd integer greater than 1.')
if a >= N or math.gcd(a, N) != 1:
raise ValueError('The integer a needs to satisfy a < N and gcd(a, N) = 1.')
n = math.ceil(math.log(N,2))
global result_factors
result_factors = []
tf, b, p = is_power(N, return_decomposition=True)
if tf:
print('The input integer is a power: {0}={1}^{2}.'.format(N, b, p))
result_factors.append(b)
# """auxilliary quantum register used in addition and multiplication"""
aux = QuantumRegister(size = n+2, name="aux_reg")
# """single qubit where the sequential QFT is performed"""
up_reg = QuantumRegister(1, name = "up_reg")
down_reg = QuantumRegister(n, name = "down_reg")
# """classical register where the measured values of the sequential QFT are stored"""
up_classic = ClassicalRegister(2*n, name="up_classic")
# """classical bit used to reset the state of the top qubit to 0 if the previous measurement was 1"""
c_aux = ClassicalRegister(1, name = "aux_classic")
# """ Create Quantum Circuit """
circuit = QuantumCircuit(up_reg ,down_reg , aux,up_classic, c_aux)
circuit.x(down_reg[0])
# circuit.draw(filename = "shor_semiclassical_QFT_initialization")
for i in range(0, 2*n):
circuit.x(up_reg).c_if(c_aux, 1)
circuit.h(up_reg)
cMULTmodN(circuit, up_reg[0], down_reg, aux, a**(2**(2*n-1-i)), N, n)
# later confirm if this should be up_reg[i] instead of up_reg[0]
for j in range(0, 2**i):
circuit.u1(getAngle(j, i), up_reg[0]).c_if(up_classic, j)
circuit.h(up_reg)
circuit.measure(up_reg[0], up_classic[i])
circuit.measure(up_reg[0], c_aux[0])
# circuit.draw(filename = "shor_semiclassical_QFT_final_circuit")
circuit.draw()
qc_compiled = transpile(circuit, backend, optimization_level = 3)
job_sim_1 = backend.run(qc_compiled, shots=shots)
sim_result=job_sim_1.result()
# counts_result = sim_result.get_counts(circuit)
# len(counts_result)
# measurement_plot = qiskit.visualization.plot_histogram(counts_result,figsize=(20, 12) ,number_to_keep = 30,bar_labels=True, title = "Measurement results from shor_standard_QFT circuit variant" )
# measurement_plot.savefig("shor_semiclassical_QFT_measurement_result")
# measurement_plot
processed_result = process_results(sim_result, circuit, shots, N, a, n)
end_time_number = datetime.now()
end_time = end_time_number.strftime("%H:%M:%S")
duration = end_time_number - start_time_number
print("Current Start Time =", start_time)
print(processed_result)
print("Current End Time =", end_time)
circuit_count_ops = circuit.count_ops()
circuit_decomposed = circuit.decompose()
circuit_decomposed_count_ops = circuit_decomposed.count_ops()
qc_compiled_count_ops = qc_compiled.count_ops()
summary_result["num_qubits"] = n
summary_result["Number(N)"] = N
summary_result["a"] = a
summary_result["start_time"] = start_time
summary_result["end_time"] = end_time
summary_result["duration"] = duration
summary_result["result_factors"] = processed_result[0]
summary_result["prob_success"] = processed_result[1]
summary_result["prob_failure"] = processed_result[2]
summary_result["total_counts"] = processed_result[3]
summary_result["result_successful_counts"] = processed_result[4]
summary_result["result_failure_counts"] = processed_result[5]
summary_result["circuit_width"] = circuit.width()
summary_result["circuit_depth"] = circuit.depth()
summary_result["circuit_size"] = circuit.size()
summary_result["circuit_num_nonlocal_gates"] = circuit.num_nonlocal_gates()
summary_result["circuit_num_ancillas"] = circuit.num_ancillas
summary_result["circuit_num_clbits"] = circuit.num_clbits
summary_result["circuit_num_qubits"] = circuit.num_qubits
summary_result["circuit_num_ancillas"] = circuit.num_ancillas
summary_result["circuit_num_of_count_ops"] = len(circuit_count_ops)
summary_result["circuit_num_of_x"] = circuit_count_ops.get('x')
summary_result["circuit_num_of_measure"] = circuit_count_ops.get('measure')
summary_result["circuit_num_of_h"] = circuit_count_ops.get('h')
summary_result["circuit_num_of_cswap"] = circuit_count_ops.get('cswap')
summary_result["circuit_num_of_swap"] = circuit_count_ops.get('swap')
summary_result["circuit_num_of_cx"] = circuit_count_ops.get('cx')
summary_result["circuit_num_of_toffoli"] = circuit_count_ops.get('toffoli')
summary_result["circuit_num_of_p"] = circuit_count_ops.get('p')
summary_result["circuit_num_of_t"] = circuit_count_ops.get('t')
summary_result["circuit_decomposed_width"] = circuit_decomposed.width()
summary_result["circuit_decomposed_depth"] = circuit_decomposed.depth()
summary_result["circuit_decomposed_size"] = circuit_decomposed.size()
summary_result["circuit_decomposed_num_nonlocal_gates"] = circuit_decomposed.num_nonlocal_gates()
summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas
summary_result["circuit_decomposed_num_clbits"] = circuit_decomposed.num_clbits
summary_result["circuit_decomposed_num_qubits"] = circuit_decomposed.num_qubits
summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas
summary_result["circuit_decomposed_num_of_count_ops"] = len(circuit_decomposed_count_ops)
summary_result["circuit_decomposed_num_of_x"] = circuit_decomposed_count_ops.get('x')
summary_result["circuit_decomposed_num_of_measure"] = circuit_decomposed_count_ops.get('measure')
summary_result["circuit_decomposed_num_of_h"] = circuit_decomposed_count_ops.get('h')
summary_result["circuit_decomposed_num_of_cswap"] = circuit_decomposed_count_ops.get('cswap')
summary_result["circuit_decomposed_num_of_swap"] = circuit_decomposed_count_ops.get('swap')
summary_result["circuit_decomposed_num_of_cx"] = circuit_decomposed_count_ops.get('cx')
summary_result["circuit_decomposed_num_of_toffoli"] = circuit_decomposed_count_ops.get('toffoli')
summary_result["circuit_decomposed_num_of_p"] = circuit_decomposed_count_ops.get('p')
summary_result["circuit_decomposed_num_of_t"] = circuit_decomposed_count_ops.get('t')
summary_result["qc_compiled_width"] = qc_compiled.width()
summary_result["qc_compiled_depth"] = qc_compiled.depth()
summary_result["qc_compiled_size"] = qc_compiled.size()
summary_result["qc_compiled_num_nonlocal_gates"] = qc_compiled.num_nonlocal_gates()
summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas
summary_result["qc_compiled_num_clbits"] = qc_compiled.num_clbits
summary_result["qc_compiled_num_qubits"] = qc_compiled.num_qubits
summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas
summary_result["qc_compiled_num_of_count_ops"] = len(qc_compiled_count_ops)
summary_result["qc_compiled_num_of_x"] = qc_compiled_count_ops.get('x')
summary_result["qc_compiled_num_of_measure"] = qc_compiled_count_ops.get('measure')
summary_result["qc_compiled_num_of_h"] = qc_compiled_count_ops.get('h')
summary_result["qc_compiled_num_of_cswap"] = qc_compiled_count_ops.get('cswap')
summary_result["qc_compiled_num_of_swap"] = qc_compiled_count_ops.get('swap')
summary_result["qc_compiled_num_of_cx"] = qc_compiled_count_ops.get('cx')
summary_result["qc_compiled_num_of_toffoli"] = qc_compiled_count_ops.get('toffoli')
summary_result["qc_compiled_num_of_p"] = qc_compiled_count_ops.get('p')
summary_result["qc_compiled_num_of_t"] = qc_compiled_count_ops.get('t')
return summary_result
# Run for just a single number N
%%time
N = 21
shots = 1024
global result_factors
all_summary_result_temp = []
for random_a in range(2, N):
if math.gcd(random_a,N) > 1:
continue
a = random_a
summary_result = my_shor(a,N,shots)
print("Finished running for a = {} and N = {}\n".format(a, N))
all_summary_result_temp.append(summary_result)
summary_result_list = []
for key, value in summary_result.items():
summary_result_list.append([key,value])
summary_result_list
with open("a({0})_N({1})_semiclassical.csv".format(a, N), 'a') as myfile:
write = csv.writer(myfile)
#write.writerow(fields)
write.writerows(summary_result_list)
all_summary_result_temp
# Run for many numbers N.
%%time
shots = 1024
global result_factors
all_summary_result = []
for N in [15, 21, 33, 35, 39, 51, 55, 57]:
for a in range(2, N):
if math.gcd(a,N) > 1:
continue
print("Beginning running for a = {} and N = {}".format(a, N))
summary_result = my_shor(a,N,shots)
print("Finished running for a = {} and N = {}\n\n".format(a, N))
all_summary_result.append(summary_result)
all_summary_result
%qiskit_copyright
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
# Qubits are subject to noise orginating from:
# temperature varations, stray magnetic fields, or operations
# on other qubits.
# Finding a way to mitigate this noise through
# the encoding of our in a way that protects them from noise.
# for some roation R(theta), about some axis it is impossible
# to impent an angle theta with perfect accuracy,such thta you are
# sure that you are not accidentally implement something like
# theta + 0.000000001. That is to say there will always be
# a limit to the accuracy we can achieve.
# As this error adds up through operations the noise will always
# be larger than is tolerable.
# Therefore implementing rotations in a fault tolerant
# Quantum Computer, uses mutiple operations made of T and H
# Gates.
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# The T-GATE:
# Is a rotation around the z-axis by theta = pi/4.
# and is expressed mathematically as Rz(pi/4) = e^(ipi/8Z)
#Ex:
# the default T gate rotating about the z-axis:
qc = QuantumCircuit(1)
qc.t(0)
qc.draw()
# the T-Gate rotating about the x-axis:
qc = QuantumCircuit(1)
qc.h(0)
qc.t(0)
qc.h(0)
qc.draw()
# Putting the two circuits above together we can make the gate:
# Rz(pi/4)Rx(pi/4).
# Bc this is a single-qubit gate,we can think of it as a
# rotation around the Bloch Sphere. That is as a rotaion
# About some axis. It is important to note that this angle
# will always be irrational. Due to its irrationality,
# the angles that result from different repetitions will never
# be the same. Each angle will be somewhere between 0 & 2pi.
# Splitting this interval up into n slices of width 2pi/n.
# For eacg repetition, the resulting angle will fall in one
# of these slices. looking at the angle for the first n+1
# repitioins, it must be true that at least one slicce contains
# two of these angles. Using n1 to denote the number of repetitions
# required for the first and n2 for the second.
# The angle for n2-n1 repetitions stisfies
# theta(n2-n1) != 0, -2pi/n <= theta(n2-n1) <= 2pi/n
# We therefore have he ability to do rotations around small angles.
# We can use this to rotate around angles that are as small as we
# like, just by increasing the number of times we repeat this gate.
# By using small-angle rotations, we can also rotate by any angle
# we like. This won't always be exact, but it is guaranteed to be
# accurate up to 2pi/n, which we can be made as small as we like.
# Using the RzRx rotations allows us to have arbitrary rotaions
# around the Bloch Sphere, through the use of numerous T-Gate operations.
# Therefore the complexity of algorithms in quantum computations is
# often time given in terms of how many T-Gates they require.
qc = QuantumCircuit(1)
# Rx gate rotation about the x-axis:
qc.h(0)
qc.t(0)
qc.h(0)
# Rz gate rotation about the z-axis:
qc.t(0)
qc.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.72" # Two Hydrogen atoms, 0.72 Angstrom apart
)
molecule = driver.run()
from qiskit_nature.second_q.mappers import QubitConverter, ParityMapper
qubit_converter = QubitConverter(ParityMapper())
hamiltonian = qubit_converter.convert(molecule.second_q_ops()[0])
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
sol = NumPyMinimumEigensolver().compute_minimum_eigenvalue(hamiltonian)
real_solution = molecule.interpret(sol)
real_solution.groundenergy
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator"
from qiskit.algorithms.minimum_eigensolvers import VQE
# Use RealAmplitudes circuit to create trial states
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=2)
# Search for better states using SPSA algorithm
from qiskit.algorithms.optimizers import SPSA
optimizer = SPSA(150)
# Set a starting point for reproduceability
import numpy as np
np.random.seed(6)
initial_point = np.random.uniform(-np.pi, np.pi, 12)
# Create an object to store intermediate results
from dataclasses import dataclass
@dataclass
class VQELog:
values: list
parameters: list
def update(self, count, parameters, mean, _metadata):
self.values.append(mean)
self.parameters.append(parameters)
print(f"Running circuit {count} of ~350", end="\r", flush=True)
log = VQELog([],[])
# Main calculation
with Session(service=service, backend=backend) as session:
options = Options()
options.optimization_level = 3
vqe = VQE(Estimator(session=session, options=options),
ansatz, optimizer, callback=log.update, initial_point=initial_point)
result = vqe.compute_minimum_eigenvalue(hamiltonian)
print("Experiment complete.".ljust(30))
print(f"Raw result: {result.optimal_value}")
if 'simulator' not in backend:
# Run once with ZNE error mitigation
options.resilience_level = 2
vqe = VQE(Estimator(session=session, options=options),
ansatz, SPSA(1), initial_point=result.optimal_point)
result = vqe.compute_minimum_eigenvalue(hamiltonian)
print(f"Mitigated result: {result.optimal_value}")
import matplotlib.pyplot as plt
plt.rcParams["font.size"] = 14
# Plot energy and reference value
plt.figure(figsize=(12, 6))
plt.plot(log.values, label="Estimator VQE")
plt.axhline(y=real_solution.groundenergy, color="tab:red", ls="--", label="Target")
plt.legend(loc="best")
plt.xlabel("Iteration")
plt.ylabel("Energy [H]")
plt.title("VQE energy")
plt.show()
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 import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
# Virtual -> physical
# 0 -> 3
# 1 -> 4
# 2 -> 2
my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2])
plot_circuit_layout(my_ghz, backend)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the NormalizeRXAngle pass"""
import unittest
import numpy as np
from ddt import ddt, named_data
from qiskit import QuantumCircuit
from qiskit.transpiler.passes.optimization.normalize_rx_angle import (
NormalizeRXAngle,
)
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.transpiler import Target
from qiskit.circuit.library.standard_gates import SXGate
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestNormalizeRXAngle(QiskitTestCase):
"""Tests the NormalizeRXAngle pass."""
def test_not_convert_to_x_if_no_calib_in_target(self):
"""Check that RX(pi) is NOT converted to X,
if X calibration is not present in the target"""
empty_target = Target()
tp = NormalizeRXAngle(target=empty_target)
qc = QuantumCircuit(1)
qc.rx(90, 0)
transpiled_circ = tp(qc)
self.assertEqual(transpiled_circ.count_ops().get("x", 0), 0)
def test_sx_conversion_works(self):
"""Check that RX(pi/2) is converted to SX,
if SX calibration is present in the target"""
target = Target()
target.add_instruction(SXGate(), properties={(0,): None})
tp = NormalizeRXAngle(target=target)
qc = QuantumCircuit(1)
qc.rx(np.pi / 2, 0)
transpiled_circ = tp(qc)
self.assertEqual(transpiled_circ.count_ops().get("sx", 0), 1)
def test_rz_added_for_negative_rotation_angles(self):
"""Check that RZ is added before and after RX,
if RX rotation angle is negative"""
backend = GenericBackendV2(num_qubits=5)
tp = NormalizeRXAngle(target=backend.target)
# circuit to transpile and test
qc = QuantumCircuit(1)
qc.rx((-1 / 3) * np.pi, 0)
transpiled_circ = tp(qc)
# circuit to show the correct answer
qc_ref = QuantumCircuit(1)
qc_ref.rz(np.pi, 0)
qc_ref.rx(np.pi / 3, 0)
qc_ref.rz(-np.pi, 0)
self.assertQuantumCircuitEqual(transpiled_circ, qc_ref)
@named_data(
{"name": "-0.3pi", "raw_theta": -0.3 * np.pi, "correct_wrapped_theta": 0.3 * np.pi},
{"name": "1.7pi", "raw_theta": 1.7 * np.pi, "correct_wrapped_theta": 0.3 * np.pi},
{"name": "2.2pi", "raw_theta": 2.2 * np.pi, "correct_wrapped_theta": 0.2 * np.pi},
)
def test_angle_wrapping_works(self, raw_theta, correct_wrapped_theta):
"""Check that RX rotation angles are correctly wrapped to [0, pi]"""
backend = GenericBackendV2(num_qubits=5)
tp = NormalizeRXAngle(target=backend.target)
# circuit to transpile and test
qc = QuantumCircuit(1)
qc.rx(raw_theta, 0)
transpiled_circuit = tp(qc)
wrapped_theta = transpiled_circuit.get_instructions("rx")[0].operation.params[0]
self.assertAlmostEqual(wrapped_theta, correct_wrapped_theta)
@named_data(
{
"name": "angles are within resolution",
"resolution": 0.1,
"rx_angles": [0.3, 0.303],
"correct_num_of_cals": 1,
},
{
"name": "angles are not within resolution",
"resolution": 0.1,
"rx_angles": [0.2, 0.4],
"correct_num_of_cals": 2,
},
{
"name": "same angle three times",
"resolution": 0.1,
"rx_angles": [0.2, 0.2, 0.2],
"correct_num_of_cals": 1,
},
)
def test_quantize_angles(self, resolution, rx_angles, correct_num_of_cals):
"""Test that quantize_angles() adds a new calibration only if
the requested angle is not in the vicinity of the already generated angles.
"""
backend = GenericBackendV2(num_qubits=5)
tp = NormalizeRXAngle(backend.target, resolution_in_radian=resolution)
qc = QuantumCircuit(1)
for rx_angle in rx_angles:
qc.rx(rx_angle, 0)
transpiled_circuit = tp(qc)
angles = [
inst.operation.params[0]
for inst in transpiled_circuit.data
if inst.operation.name == "rx"
]
angles_without_duplicate = list(dict.fromkeys(angles))
self.assertEqual(len(angles_without_duplicate), correct_num_of_cals)
if __name__ == "__main__":
unittest.main()
|
https://github.com/sintefmath/QuantumPoker
|
sintefmath
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile
from termcolor import colored
class Board:
def __init__(self, size=3, simulator=None):
# Initialize the quantum circuit with one qubit and classical bit for each cell
self.size = size
self.simulator = simulator
self.superposition_count = 0
self.cells = [[' ' for _ in range(size)] for _ in range(size)] # Initialize the board representation
self.qubits = QuantumRegister(size**2, 'q')
self.bits = ClassicalRegister(size**2, 'c')
self.circuit = QuantumCircuit(self.qubits, self.bits)
''' For a 3x3 board, the winning lines are:
- Horizontal lines: (0, 1, 2), (3, 4, 5), (6, 7, 8)
- Vertical lines: (0, 3, 6), (1, 4, 7), (2, 5, 8)
- Diagonal lines: (0, 4, 8), (2, 4, 6)
'''
self.winning_lines = [tuple(range(i, size**2, size)) for i in range(size)] + \
[tuple(range(i * size, (i + 1) * size)) for i in range(size)] + \
[tuple(range(0, size**2, size + 1)), tuple(range(size - 1, size**2 - 1, size - 1))]
def __str__(self):
# Create a colorful string representation of the board
board_str = ''
for i, row in enumerate(self.cells):
for cell in row:
if '?' in cell: cell_color = 'cyan' # Quantum move
elif cell == 'X': cell_color = 'red'
elif cell == 'O': cell_color = 'green'
else: cell_color = 'yellow'
board_str += f' {colored(cell, cell_color)} '
board_str += '|' if '?' in cell else ' |'
board_str = board_str[:-1] + '\n' # Remove last separator
if i < self.size - 1: # Add horizontal separator
board_str += '-' * (5 * self.size - 1) + '\n'
return board_str
def make_classical_move(self, row, col, player_mark, is_collapsed=False):
if self.cells[row][col] == ' ' or is_collapsed: # Check if the cell is occupied
self.cells[row][col] = player_mark
index = row * self.size + col
if player_mark == 'X': self.circuit.x(self.qubits[index])
else: self.circuit.id(self.qubits[index])
return True
return False
def make_swap_move(self, row1, col1, row2, col2, **kwargs):
if self.cells[row1][col1] != ' ' and self.cells[row2][col2] != ' ':
indices = [row1 * self.size + col1, row2 * self.size + col2]
self.circuit.swap(self.qubits[indices[0]], self.qubits[indices[1]])
self.cells[row1][col1], self.cells[row2][col2] = self.cells[row2][col2], self.cells[row1][col1]
return True
return False
def make_superposition_move(self, row, col, player_mark, **kwargs):
if self.cells[row][col] == ' ':
index = row * self.size + col
self.circuit.h(self.qubits[index])
self.cells[row][col] = player_mark + '?'
self.superposition_count += 1
return True
return False
def make_entangled_move(self, *positions, risk_level, player_mark, **kwargs):
# Entangle the quantum states of 2 or 3 cells based on the risk level
pos_count = len(positions)
if pos_count not in [2, 3] or risk_level not in [1, 2, 3, 4] or len(set(positions)) != pos_count or \
(pos_count == 2 and risk_level not in [1, 3]) or (pos_count == 3 and risk_level not in [2, 4]) or \
any(self.cells[row][col] != ' ' for row, col in positions): return False
indices = [row * self.size + col for row, col in positions]
self.circuit.h(self.qubits[indices[0]])
if pos_count == 2:
# Pairwise Entanglement with Bell state for 2 qubits:
# Lv1. |Ψ+⟩ = (∣01⟩ + ∣10⟩)/√2 | Lv3. |Φ+⟩ = (∣00⟩ + ∣11⟩)/√2
if risk_level == 1: self.circuit.x(self.qubits[indices[1]])
self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]])
else:
# Triple Entanglement with GHZ state for 3 qubits:
# Lv2. (∣010⟩ + ∣101⟩)/√2 | Lv4. (∣000⟩ + ∣111⟩)/√2
if risk_level == 2:
self.circuit.x(self.qubits[indices[1]])
self.circuit.x(self.qubits[indices[2]])
# Apply CNOT chain to entangle all 3 qubits
self.circuit.cx(self.qubits[indices[0]], self.qubits[indices[1]])
self.circuit.cx(self.qubits[indices[1]], self.qubits[indices[2]])
for row, col in positions: self.cells[row][col] = player_mark + '?'
self.superposition_count += pos_count
return True
def can_be_collapsed(self):
# If superpositions/entanglement cells form a potential winning line => collapse
for line in self.winning_lines:
if all(self.cells[i // self.size][i % self.size].endswith('?') for i in line):
return True
return False
def collapse_board(self):
# Update the board based on the measurement results and apply the corresponding classical moves
self.circuit.barrier()
self.circuit.measure(self.qubits, self.bits) # Measure all qubits to collapse them to classical states
transpiled_circuit = transpile(self.circuit, self.simulator)
job = self.simulator.run(transpiled_circuit, memory=True)
counts = job.result().get_counts()
max_state = max(counts, key=counts.get)[::-1] # Get the state with the highest probability
for i in range(self.size ** 2):
row, col = divmod(i, self.size)
if self.cells[row][col].endswith('?'):
self.circuit.reset(self.qubits[i])
self.make_classical_move(row, col, 'X' if max_state[i] == '1' else 'O', is_collapsed=True)
self.superposition_count = 0
return counts
def check_win(self):
# Dynamic implementation for above logic with dynamic winning lines
for line in self.winning_lines:
# Check if all cells in the line are the same and not empty
first_cell = self.cells[line[0] // self.size][line[0] % self.size]
if first_cell not in [' ', 'X?', 'O?']:
is_same = all(self.cells[i // self.size][i % self.size] == first_cell for i in line)
if is_same: return line
# If no spaces and no superpositions left => 'Draw'
# If all cells are filled but some are still in superpositions => collapse_board
if all(self.cells[i // self.size][i % self.size] not in [' '] for i in range(self.size**2)):
if self.superposition_count <= 0: return 'Draw'
return self.superposition_count
return None
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import time
import datetime
import numpy as np
from matplotlib import pyplot as plt
import qiskit
from qiskit import *
from qiskit.opflow import X,Z,I
from qiskit.opflow.state_fns import StateFn, CircuitStateFn
from qiskit.providers.aer import StatevectorSimulator, AerSimulator
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA, SLSQP, SPSA
from qiskit.opflow import CircuitSampler
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis
from qiskit.ignis.mitigation.measurement import complete_meas_cal
from scipy import sparse
import scipy.sparse.linalg.eigen.arpack as arp
from modules.utils import *
anti = -1
L = 5
num_trash = 2
name = "ibmq_antiferro-1D-load_bogota-test"
filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle"
filename_simualted_thetas = 'data/ibmq_antiferro-1D-load_simu_thetas-loss-cost_run2.npz' # where to get the simulated thetas values from?
print("filename: ", filename, "notebook name: ", name)
load = False
recompute = False # whether or not to recompute Magnetization, makes sense on device
IBMQ.load_account() # this then automatically loads your saved account
provider = IBMQ.get_provider(hub='ibm-q-research')
device = provider.backend.ibmq_bogota
print(device)
#backend = device
backend = qiskit.providers.aer.AerSimulator.from_backend(device)
coupling_map = device.configuration().coupling_map
noise_model = qiskit.providers.aer.noise.NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
#aqua_globals.random_seed = seed
qi = qiskit.utils.QuantumInstance(backend=backend, # , seed_simulator=seed, seed_transpiler=seed
coupling_map=coupling_map, noise_model=noise_model,
measurement_error_mitigation_cls= CompleteMeasFitter,
cals_matrix_refresh_period=30 #How often to refresh the calibration matrix in measurement mitigation. in minutes
)
backend._cached_basis_gates
# Very important, at the moment poorly coded so it needs to come back to this instance all the time
ansatz = qiskit.circuit.library.TwoLocal(L,rotation_blocks="ry", entanglement_blocks='cz', entanglement="sca", reps=1)
ansatz.draw("mpl")
ansatz = qiskit.transpile(ansatz, backend)
ansatz.draw("mpl")
L = 5
num_trash = 2
anti = -1
VQE_params = np.load(filename + ".npz", allow_pickle=True)
gx_list = VQE_params['gx_list']
gz_list = VQE_params['gz_list']
opt_params = VQE_params['opt_params']
Qmags = VQE_params["Qmag"]
Qen = VQE_params["Qen"]
Sen = VQE_params["Sen"]
Smags = VQE_params["Smag"]
gx_vals = np.unique(gx_list)
gz_vals = np.unique(gz_list)
if load:
temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True)
Qmags = temp["Qmags"]
Qen = temp["Qen"]
Sen = temp["Sen"]
Smags = temp["Smags"]
verbose=1
if recompute:
mag = QMag(L,anti) #magnetization operator (Qiskit)
Smag = Mag(L,anti) #magnetization operator (numpy)
Qen_executed=np.zeros(len(opt_params), dtype="complex")
Qmags_executed=np.zeros(len(opt_params), dtype="complex")
for j in range(len(opt_params)):
t0 = datetime.datetime.now()
gx = gx_list[j]
gz = gz_list[j]
H = QHIsing(L, anti, np.float32(gx), np.float32(gz)) # build Hamiltonian Op
state = ansatz.assign_parameters(opt_params[j])
meas_outcome = ~StateFn(mag) @ StateFn(state)
Qmags_executed[j] = CircuitSampler(qi).convert(meas_outcome).eval() #https://quantumcomputing.stackexchange.com/questions/12080/evaluating-expectation-values-of-operators-in-qiskit
#e_outcome = ~StateFn(H) @ StateFn(state)
#Qen_executed[j] = CircuitSampler(qi).convert(e_outcome).eval()
init_state, E, ham = ising_groundstate(L, anti, np.float64(gx), np.float64(gz))
Sen[j] = E
Smags[j] = init_state.T.conj()@Smag@init_state #Magnetization with Numpy results
print(f"{j+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {(datetime.datetime.now() - t0)}")
np.savez("data/" + name + "executed_mags-Es.npz",Qmags=Qmags_executed, Qen=Qen_executed, Sen=Sen, Smags=Smags) # for large parameter space takes quite a while because of the exact diagonalization
fig, axs = plt.subplots(ncols=2, figsize=(10,5))
ax = axs[0]
ax.plot(gx_list, Qmags,"x--", label="noisy VQE simu")
ax.plot(gx_list, Smags,"x--", label="ED")
ax.set_xscale("log")
if recompute:
ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ")
ax.legend()
##############################################################################
### II - Training ###########################################################
##############################################################################
# linear entangler (as in scales linearly with trash qubits)
def get_entangler_map(L, num_trash, i_permut=1, nums_trash=[1,2]):
result = []
nums_compressed = list(range(L))
for trashqubit in nums_trash:
nums_compressed.remove(trashqubit)
if nums_trash == None: #old way
nums_compressed = list(range(L))[:L-num_trash]
nums_trash = list(range(L))[-num_trash:]
#print(nums, nums_compressed, nums_trash)
# combine all trash qubits with themselves
for trash_q in nums_trash[:-1]:
result.append((trash_q+1,trash_q))
# combine each of the trash qubits with every n-th
repeated = list(nums_trash) * (L-num_trash) # repeat the list of trash indices cyclicly
for i in range(L-num_trash):
result.append((repeated[i_permut + i], nums_compressed[i]))
return result
def QAE_Ansatz(thetas, L, num_trash, insert_barriers=False, parametrized_gate = "ry", entangling_gate = "cz", nums_trash = [1,2]):
entanglement = [get_entangler_map(L,num_trash,i_permut) for i_permut in range(num_trash)]
if nums_trash == None:
nums_trash = list(range(L))[-num_trash:]
circ = qiskit.circuit.library.TwoLocal(L,
parametrized_gate,
entangling_gate,
entanglement,
reps=num_trash,
insert_barriers=insert_barriers,
skip_final_rotation_layer=True
).assign_parameters(thetas[:-num_trash])
if insert_barriers: circ.barrier()
for i in nums_trash:
circ.ry(thetas[i], i)
#circ.ry(circuit.Parameter(f'θ{i}'), L-i-1)
return circ
def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True, vqe=True):
qreg = QuantumRegister(L, 'q')
creg = ClassicalRegister(num_trash, 'c')
circ = QuantumCircuit(qreg, creg)
circ += QAE_Ansatz(thetas, L, num_trash, insert_barriers=False)#.assign_parameters(thetas) # difference to bind?
if measurement:
for i in range(num_trash):
circ.measure(qreg[L-i-1], creg[i])
if init_state is not None:
if vqe:
circ = ansatz.assign_parameters(init_state) + circ # needs to have ansatz defined somewhere in the script
else:
circ.initialize(init_state, qreg)
return circ
def feature_encoding(thetas, x):
""" thetas: parameters to be optimized, x: Ising model parameter (eg. field) """
new_thetas = []
thetas = thetas.reshape((-1,2))
for theta in thetas:
new_thetas.append(theta[0] * x + theta[1])
return new_thetas
def calibrate_circuit(L, num_trash,shots=1000):
qreg = QuantumRegister(L, 'q')
# obtain calibration matrix
qubit_list = [L-i-1 for i in range(num_trash)] # only need to calibrate the trash qubits
circlabel = f'mcal_{datetime.datetime.now()}'
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qreg, circlabel=circlabel)
cal_job = backend.run(meas_calibs, shots=shots, noise_model=noise_model)
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel=circlabel)
print(circlabel, meas_fitter.cal_matrix)
return meas_fitter
def run_circuit(thetas, L, num_trash, init_state, vqe=True, shots=100, meas_fitter = None):
circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe)
tcirc = qiskit.transpile(circ, backend)
# Execute the circuit
job_sim = backend.run(tcirc, shots=shots) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible
result = job_sim.result()
# Results without mitigation
counts = result.get_counts()
if meas_fitter != None:
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(result)
counts = mitigated_results.get_counts(0)
return counts
meas_fitter = calibrate_circuit(L, num_trash)
phis = opt_params
# translate to Rikes naming
gxs = gx_list
gzs = gz_list
def cost_function_single(thetas, L, num_trash, p, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None):
""" Optimizes circuit """
if vqe:
init_state = phis[p]
else:
J, gx, gz = p
init_state, _ = ising_groundstate(L, J, gx, gz)
if param_encoding: thetas = feature_encoding(thetas, x)
out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter)
cost = out.get('11', 0)*2 + out.get('01', 0) + out.get('10', 0)
return cost/shots
def cost_function(thetas, L, num_trash, ising_params, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None):
""" Optimizes circuit """
cost = 0.
n_samples = len(ising_params)
for i, p in enumerate(ising_params):
if param_encoding:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, x[i], meas_fitter=meas_fitter)
else:
cost += cost_function_single(thetas, L, num_trash, p, shots, vqe, param_encoding, meas_fitter=meas_fitter)
return cost/n_samples
def optimize(ising_params, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None,
meas_fitter=None):
if thetas is None:
n_params = (2*L+2)*2 if param_encoding else (2*L+2)
thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding
print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x)))
counts, values, accepted = [], [], []
def store_intermediate_result(eval_count, parameters, mean, std, ac):
# counts.append(eval_count)
values.append(mean)
accepted.append(ac)
# Initialize optimizer
if pick_optimizer == "cobyla":
optimizer = COBYLA(maxiter=max_iter, tol=0.0001)
if pick_optimizer == "adam" or pick_optimizer == "ADAM":
optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter)
# optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08)
if pick_optimizer == "spsa" or pick_optimizer == None:
optimizer = SPSA(maxiter=max_iter,
#blocking=True,
callback=store_intermediate_result,
learning_rate=0.3,
perturbation=0.1
) # recommended from qiskit (first iteraction takes quite long)
# to reduce time figure out optimal learning rate and perturbation in advance
start_time = time.time()
ret = optimizer.optimize(
num_vars=len(thetas),
objective_function=(lambda thetas: cost_function(thetas, L, num_trash, ising_params, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)),
initial_point=thetas
)
print("Time: {:.5f} sec".format(time.time()-start_time))
print(ret)
return ret[0], values, accepted
def run_inference(thetas, shots=1000, L=5, meas_fitter=None):
points = 50
J = -1.0
x,y = np.meshgrid(gx_vals, gz_vals)
cost = np.zeros((len(gx_vals) * len(gz_vals)))
Smags = np.zeros((len(gx_vals) * len(gz_vals)))
shots = 1000
for i,p in enumerate(list(zip(gxs, gzs))):
t0 = datetime.datetime.now()
cost[i] = cost_function_single(thetas, L, num_trash, i, shots=shots, meas_fitter=meas_fitter)
if not i%verbose:
print(f"{i+1} / {len(opt_params)}, gx = {gx:.2f}, gz = {gz:.2f}, time : {verbose*(datetime.datetime.now() - t0)}")
cost = cost.reshape((len(gx_vals), len(gz_vals)))
return cost
thetas_guess = np.load(filename_simualted_thetas, allow_pickle=True)["thetas_mitigated"]
# Training
phys_params = [-1]
thetas_opt_mitigated, loss, accepted = optimize(phys_params, thetas = thetas_guess, max_iter=30, L=5,meas_fitter=meas_fitter) #, pick_optimizer="adam")
plt.plot(loss)
# Inference
cost_mitigated = np.zeros((len(gx_vals)))
shots = 1000
for i,p in enumerate(list(zip(gxs, gzs))):
t0 = datetime.datetime.now()
cost_mitigated[i] = cost_function_single(thetas_opt_mitigated, L, num_trash, i, shots=shots, meas_fitter=meas_fitter) # np.random.uniform(0, 2*np.pi, 2*L+2) random parameters to check if training "does" something - result was: with random paremters just get noise, so yes, it "does" something
if not i%verbose:
print(f"{i+1} / {len(opt_params)}, gx = {p[0]:.2f}, gz = {p[1]:.2f}, time : {verbose*(datetime.datetime.now() - t0)}")
np.savez("data/" + name + "_thetas-loss-cost_run2",
cost_mitigated=cost_mitigated, thetas_mitigated=thetas_opt_mitigated,
)
fig, ax = plt.subplots(ncols=1,figsize=(6,5))
ax.set_title("Mitigated results")
cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:", label="raw output")
ax.plot(gx_list, Qmags,"x--", color="tab:orange", label="Qmag")
ax.set_xscale("log")
for p in phys_params:
ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from docplex.mp.model import Model
model = Model()
x0 = model.binary_var(name="x0")
x1 = model.binary_var(name="x1")
x2 = model.binary_var(name="x2")
model.minimize(-x0 + 2 * x1 - 3 * x2 - 2 * x0 * x2 - 1 * x1 * x2)
qp = from_docplex_mp(model)
print(qp.prettyprint())
grover_optimizer = GroverOptimizer(6, num_iterations=10, sampler=Sampler())
results = grover_optimizer.solve(qp)
print(results.prettyprint())
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qp)
print(exact_result.prettyprint())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
from qiskit.quantum_info import *
Density_Matrix = DensityMatrix.from_instruction(qc)
plot_state_hinton(Density_Matrix) #Hinton plot tells the imaginary and real part of the circuit
|
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/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""Meta tests for mappers.
The test checks the output of the swapper to a ground truth DAG (one for each
test/swapper) saved in as a QASM (in `test/python/qasm/`). If they need
to be regenerated, the DAG candidate is compiled and run in a simulator and
the count is checked before being saved. This happens with (in the root
directory):
> python -m test.python.transpiler.test_mappers regenerate
To make a new swapper pass throw all the common tests, create a new class inside the file
`path/to/test_mappers.py` that:
* the class name should start with `Tests...`.
* inheriting from ``SwapperCommonTestCases, QiskitTestCase``
* overwrite the required attribute ``pass_class``
For example::
class TestsSomeSwap(SwapperCommonTestCases, QiskitTestCase):
pass_class = SomeSwap # The pass class
additional_args = {'seed_transpiler': 42} # In case SomeSwap.__init__ requires
# additional arguments
To **add a test for all the swappers**, add a new method ``test_foo``to the
``SwapperCommonTestCases`` class:
* defining the following required ``self`` attributes: ``self.count``,
``self.shots``, ``self.delta``. They are required for the regeneration of the
ground truth.
* use the ``self.assertResult`` assertion for comparing for regeneration of the
ground truth.
* explicitly set a unique ``name`` of the ``QuantumCircuit``, as it it used
for the name of the QASM file of the ground truth.
For example::
def test_a_common_test(self):
self.count = {'000': 512, '110': 512} # The expected count for this circuit
self.shots = 1024 # Shots to run in the backend.
self.delta = 5 # This is delta for the AlmostEqual during
# the count check
coupling_map = [[0, 1], [0, 2]] # The coupling map for this specific test
qr = QuantumRegister(3, 'q') #
cr = ClassicalRegister(3, 'c') # Set the circuit to test
circuit = QuantumCircuit(qr, cr, # and don't forget to put a name
name='some_name') # (it will be used to save the QASM
circuit.h(qr[1]) #
circuit.cx(qr[1], qr[2]) #
circuit.measure(qr, cr) #
result = transpile(circuit, self.create_backend(), coupling_map=coupling_map,
pass_manager=self.create_passmanager(coupling_map))
self.assertResult(result, circuit)
```
"""
# pylint: disable=attribute-defined-outside-init
import unittest
import os
import sys
from qiskit import execute
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, BasicAer
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap, SabreSwap
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler import CouplingMap, Layout
from qiskit.test import QiskitTestCase
class CommonUtilitiesMixin:
"""Utilities for meta testing.
Subclasses should redefine the ``pass_class`` argument, with a Swap Mapper
class.
Note: This class assumes that the subclass is also inheriting from
``QiskitTestCase``, and it uses ``QiskitTestCase`` methods directly.
"""
regenerate_expected = False
seed_simulator = 42
seed_transpiler = 42
additional_args = {}
pass_class = None
def create_passmanager(self, coupling_map, initial_layout=None):
"""Returns a PassManager using self.pass_class(coupling_map, initial_layout)"""
passmanager = PassManager()
if initial_layout:
passmanager.append(SetLayout(Layout(initial_layout)))
# pylint: disable=not-callable
passmanager.append(self.pass_class(CouplingMap(coupling_map), **self.additional_args))
return passmanager
def create_backend(self):
"""Returns a Backend."""
return BasicAer.get_backend("qasm_simulator")
def generate_ground_truth(self, transpiled_result, filename):
"""Generates the expected result into a file.
Checks if transpiled_result matches self.counts by running in a backend
(self.create_backend()). That's saved in a QASM in filename.
Args:
transpiled_result (DAGCircuit): The DAGCircuit to execute.
filename (string): Where the QASM is saved.
"""
sim_backend = self.create_backend()
job = execute(
transpiled_result,
sim_backend,
seed_simulator=self.seed_simulator,
seed_transpiler=self.seed_transpiler,
shots=self.shots,
)
self.assertDictAlmostEqual(self.counts, job.result().get_counts(), delta=self.delta)
transpiled_result.qasm(formatted=False, filename=filename)
def assertResult(self, result, circuit):
"""Fetches the QASM in circuit.name file and compares it with result."""
qasm_name = f"{type(self).__name__}_{circuit.name}.qasm"
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
filename = os.path.join(qasm_dir, qasm_name)
if self.regenerate_expected:
# Run result in backend to test that is valid.
self.generate_ground_truth(result, filename)
expected = QuantumCircuit.from_qasm_file(filename)
self.assertEqual(result, expected)
class SwapperCommonTestCases(CommonUtilitiesMixin):
"""Tests that are run in several mappers.
The tests here will be run in several mappers. When adding a test, please
ensure that the test:
* defines ``self.count``, ``self.shots``, ``self.delta``.
* uses the ``self.assertResult`` assertion for comparing for regeneration of
the ground truth.
* explicitly sets a unique ``name`` of the ``QuantumCircuit``.
See also ``CommonUtilitiesMixin`` and the module docstring.
"""
def test_a_cx_to_map(self):
"""A single CX needs to be remapped.
q0:----------m-----
|
q1:-[H]-(+)--|-m---
| | |
q2:------.---|-|-m-
| | |
c0:----------.-|-|-
c1:------------.-|-
c2:--------------.-
CouplingMap map: [1]<-[0]->[2]
expected count: '000': 50%
'110': 50%
"""
self.counts = {"000": 512, "110": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [0, 2]]
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr, name="a_cx_to_map")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.measure(qr, cr)
result = self.create_passmanager(coupling_map).run(circuit)
self.assertResult(result, circuit)
def test_initial_layout(self):
"""Using a non-trivial initial_layout.
q3:----------------m--
q0:----------m-----|--
| |
q1:-[H]-(+)--|-m---|--
| | | |
q2:------.---|-|-m-|--
| | | |
c0:----------.-|-|-|--
c1:------------.-|-|--
c2:--------------.-|--
c3:----------------.--
CouplingMap map: [1]<-[0]->[2]->[3]
expected count: '000': 50%
'110': 50%
"""
self.counts = {"0000": 512, "0110": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [0, 2], [2, 3]]
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr, name="initial_layout")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.measure(qr, cr)
layout = {qr[3]: 0, qr[0]: 1, qr[1]: 2, qr[2]: 3}
result = self.create_passmanager(coupling_map, layout).run(circuit)
self.assertResult(result, circuit)
def test_handle_measurement(self):
"""Handle measurement correctly.
q0:--.-----(+)-m-------
| | |
q1:-(+)-(+)-|--|-m-----
| | | |
q2:------|--|--|-|-m---
| | | | |
q3:-[H]--.--.--|-|-|-m-
| | | |
c0:------------.-|-|-|-
c1:--------------.-|-|-
c2:----------------.-|-
c3:------------------.-
CouplingMap map: [0]->[1]->[2]->[3]
expected count: '0000': 50%
'1011': 50%
"""
self.counts = {"1011": 512, "0000": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [1, 2], [2, 3]]
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr, name="handle_measurement")
circuit.h(qr[3])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[3], qr[0])
circuit.measure(qr, cr)
result = self.create_passmanager(coupling_map).run(circuit)
self.assertResult(result, circuit)
class TestsBasicSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using BasicSwap."""
pass_class = BasicSwap
class TestsLookaheadSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using LookaheadSwap."""
pass_class = LookaheadSwap
class TestsStochasticSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using StochasticSwap."""
pass_class = StochasticSwap
additional_args = {"seed": 0}
class TestsSabreSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using SabreSwap."""
pass_class = SabreSwap
additional_args = {"seed": 1242}
if __name__ == "__main__":
if len(sys.argv) >= 2 and sys.argv[1] == "regenerate":
CommonUtilitiesMixin.regenerate_expected = True
del sys.argv[1]
unittest.main()
|
https://github.com/calebclothier/GoogleDTC
|
calebclothier
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from qiskit import IBMQ, assemble, transpile
from qiskit import QuantumCircuit
N_QUBITS = 20 # Number of qubits used in Google paper
# Link to IBMQ account with API token
#IBMQ.save_account(API_TOKEN)
# Load IBMQ cloud-based QASM simulator
provider = IBMQ.load_account()
backend = provider.backend.ibmq_qasm_simulator
def random_bitstring_circuit(n_qubits: int) -> QuantumCircuit:
"""
Args:
n_qubits: desired number of qubits in the bitstring
Returns:
QuantumCircuit: creates a random bitstring from the ground state
"""
qc = QuantumCircuit(n_qubits)
# Generate random bitstring
random_bitstring = np.random.randint(2, size=n_qubits)
# Apply X gate to nonzero qubits in bitstring
for i in range(n_qubits):
if random_bitstring[i]:
qc.x(i)
return qc
def floquet_circuit(n_qubits: int, g: float) -> QuantumCircuit:
"""
Args:
n_qubits: number of qubits
g: parameter controlling amount of x-rotation
Returns:
QuantumCircuit: circuit implementation of the unitary operator U_f as
detailed in https://arxiv.org/pdf/2107.13571.pdf
"""
qc = QuantumCircuit(n_qubits)
# X rotation by g*pi on all qubits (simulates the periodic driving pulse)
for i in range(n_qubits):
qc.rx(g*np.pi, i)
qc.barrier()
# Ising interaction (only couples adjacent spins with random coupling strengths)
for i in range(0, n_qubits-1, 2):
phi = np.random.uniform(low=0.5, high=1.5)
theta = -phi * np.pi / 2
qc.rzz(theta, i, i+1)
for i in range(1, n_qubits-1, 2):
phi = np.random.uniform(low=0.5, high=1.5)
theta = -phi * np.pi / 2
qc.rzz(theta, i, i+1)
qc.barrier()
# Longitudinal fields for disorder
for i in range(n_qubits):
h = np.random.uniform(low=-1, high=1)
qc.rz(h * np.pi, i)
return qc
def calculate_mean_polarization(n_qubits: int, counts: dict, q_index: int) -> float:
"""
Args:
n_qubits: total number of qubits
counts: dictionary of bitstring measurement outcomes and their respective total counts
q_index: index of qubit whose expected polarization we want to calculate
Returns:
float: the mean Z-polarization <Z>, in [-1, 1], of the qubit at q_index
"""
run, num_shots = 0, 0
for bitstring in counts.keys():
val = 1 if (int(bitstring[n_qubits-q_index-1]) == 0) else -1
run += val * counts[bitstring]
num_shots += counts[bitstring]
return run / num_shots
def calculate_two_point_correlations(series: list) -> list:
"""
Args:
series: time-ordered list of expectation values for some random variable
Returns:
list: two point correlations <f(0)f(t)> of the random variable evaluated at all t>0
"""
n = len(series)
data = np.asarray(series)
mean = np.mean(data)
c0 = np.sum((data - mean) ** 2) / float(n)
def r(h):
acf_lag = ((data[:n - h] - mean) * (data[h:] - mean)).sum() / float(n) / c0
return round(acf_lag, 3)
x = np.arange(n) # Avoiding lag 0 calculation
acf_coeffs = list(map(r, x))
return acf_coeffs
def simulate(n_qubits: int, initial_state: QuantumCircuit, max_time_steps: int, g: float) -> None:
mean_polarizations = np.zeros((n_qubits, max_time_steps+1))
floq_qc = floquet_circuit(n_qubits, g)
for t in range(0, max_time_steps+1):
if ((t % 5) == 0):
print('Time t=%d' % t)
qc = QuantumCircuit(n_qubits)
qc = qc.compose(initial_state)
for i in range(t):
qc = qc.compose(floq_qc)
qc.measure_all()
transpiled = transpile(qc, backend)
job = backend.run(transpiled)
retrieved_job = backend.retrieve_job(job.job_id())
counts = retrieved_job.result().get_counts()
for qubit in range(n_qubits):
mean_polarizations[qubit,t] = calculate_mean_polarization(n_qubits, counts, q_index=qubit)
return mean_polarizations
polarized_state = QuantumCircuit(N_QUBITS) # All qubits in |0> state
thermal_z = simulate(n_qubits=N_QUBITS,
initial_state=polarized_state,
max_time_steps=50,
g=0.6)
fig, ax = plt.subplots(figsize=(10,10))
im = ax.matshow(thermal_z, cmap='viridis')
plt.rcParams.update({'font.size': 15})
plt.rcParams['text.usetex'] = True
ax.set_xlabel('Floquet cycles (t)')
ax.xaxis.labelpad = 10
ax.set_ylabel('Qubit')
ax.set_xticks(np.arange(0, 51, 10))
ax.set_yticks(np.arange(0, N_QUBITS, 5))
ax.xaxis.set_label_position('top')
im.set_clim(-1, 1)
cbar = plt.colorbar(im, fraction=0.018, pad=0.04)
cbar.set_label(r'$\langle Z(t) \rangle$')
plt.show()
plt.plot(thermal_z[10,:], 'bs-')
plt.xlabel('Floquet cycles (t)')
plt.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False)
plt.ylabel(r'$\langle Z(t) \rangle$')
dtc_z = simulate(n_qubits=N_QUBITS,
initial_state=polarized_state,
max_time_steps=50,
g=0.97)
fig, ax = plt.subplots(figsize=(10,10))
im = ax.matshow(dtc_z, cmap='viridis')
plt.rcParams.update({'font.size': 15})
plt.rcParams['text.usetex'] = True
ax.set_xlabel('Floquet cycles (t)')
ax.xaxis.labelpad = 10
ax.set_ylabel('Qubit')
ax.set_xticks(np.arange(0, 51, 10))
ax.set_yticks(np.arange(0, N_QUBITS, 5))
ax.xaxis.set_label_position('top')
im.set_clim(-1, 1)
cbar = plt.colorbar(im, fraction=0.018, pad=0.04)
cbar.set_label(r'$\langle Z(t) \rangle$')
plt.show()
plt.plot(dtc_z[10,:], 'bs-')
plt.xlabel('Floquet cycles (t)')
plt.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False)
plt.ylabel(r'$\langle Z(t) \rangle$')
|
https://github.com/sayana25/IQCQ-UPES-2023
|
sayana25
|
pip install qiskit
pip install qiskit-ibm-runtime
!pip install pylatexenc
!pip install matplotlib
!pip install matplotlib-venn
import qiskit
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,IBMQ, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_vector
from math import sqrt, pi
#qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
initial_state = [0,1] # Define initial_state as |1>
qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit
qc.draw() # Let's view our circuit
qc = QuantumCircuit(3,3) # Create a quantum circuit with 3 qubits, like in python
qc.h(0) #hadamard gate
qc.x(1) #Pauli-X gate
qc.y(2) #Pauli-Y gate
qc.draw() # Let's view our circuit
qc = QuantumCircuit(3,3) # Create a quantum circuit with 3 qubits, like in python
qc.h(0) #hadamard gate
qc.x(1) #Pauli-X gate
qc.y(2) #Pauli-Y gate
qc.measure_all()
# Let's view our circuit
qc.draw('mpl')
import qiskit
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,IBMQ, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_vector
from math import sqrt, pi
X = QuantumRegister(1, "Alice") #naming the qubit
#naming the qubit
circuit = QuantumCircuit(X)
circuit.h(X)
circuit.s(X)
circuit.h(X)
circuit.t(X)
circuit.draw('mpl')
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
X = QuantumRegister(1, "x")
Y = QuantumRegister(1, "y")
A = ClassicalRegister(1, "a")
B = ClassicalRegister(1, "b")
circuit = QuantumCircuit(Y, X, B, A)
circuit.h(Y)
circuit.cx(Y, X)
circuit.measure(Y, B)
circuit.measure(X, A)
display(circuit.draw('mpl'))
qc = QuantumCircuit(4)
qc.x(0)
qc.y(1) # Qubit number inside the bracket, as in python the counting starts from 0
qc.z(2)
qc.barrier
qc.y(0)
qc.z(0)
qc.draw('mpl')
bell = QuantumCircuit(2)
bell.h(0) # apply an H gate to the circuit
bell.cx(0,1) # apply a CNOT gate to the circuit
bell.draw(output="mpl")
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
def bitflip():
qc = QuantumCircuit(1)
qc.x(0)
return qc
state = Statevector.from_instruction(bitflip())
plot_bloch_multivector(state)
def superposition():
qc = QuantumCircuit(1)
qc.h(0)
return qc
state = Statevector.from_instruction(superposition())
plot_bloch_multivector(state)
def antisuperposition():
qc = QuantumCircuit(1)
qc.h(0)
qc.z(0) #phase flip
return qc
state = Statevector.from_instruction(antisuperposition())
plot_bloch_multivector(state)
def complex():
qc = QuantumCircuit(1)
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(complex())
plot_bloch_multivector(state)
|
https://github.com/ncitron/qiskit-hack
|
ncitron
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram as ph
%matplotlib inline
import math
#0 1 2
#3 4 5
#6 7 8
mat = [0,1,0,0,0,0,1,0,0]
circuit = QuantumCircuit(len(mat))
circuit.h(range(len(mat)))
circuit.barrier()
for i in range(len(mat)):
if mat[i] == 1:
circuit.y(i)
circuit.barrier()
circuit.h(range(len(mat)))
circuit.measure_all()
circuit.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend = simulator, shots = 100).result()
counts = result.get_counts()
print(counts)
def oracle(circuit):
circuit.cz(0,2)
circuit.cz(1,2)
def diffuser(circuit):
"""Apply inversion about the average step of Grover's algorithm."""
qbits = circuit.qubits
nqbits = len(qbits)
for q in range(nqbits):
circuit.h(q)
circuit.x(q)
#Do controlled-Z
circuit.h(2)
circuit.ccx(0,1,2)
circuit.h(2)
for q in range(nqbits):
circuit.x(q)
circuit.h(q)
n=3
barriers = True
grover = QuantumCircuit(n)
for qb in range(n):
grover.h(qb)
if barriers:
grover.barrier()
oracle(grover)
if barriers:
grover.barrier()
diffuser(grover)
grover.measure_all()
grover.draw('mpl')
be = Aer.get_backend('qasm_simulator')
sh = 1024
ph(execute(grover,backend=be,shots=sh).result().get_counts())
from qiskit.quantum_info.operators import Operator
controls = QuantumRegister(2)
circuit = QuantumCircuit(controls)
dd = Operator([
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 1, 0, 0],
[1, 0, 0, 0]
])
circuit.unitary(dd, [0, 1], label='dd')
circuit.h(0)
circuit.draw('mpl')
# 4-qubit grover's algorithm
pi = math.pi
qc = QuantumCircuit(4)
shots = 2048
qc.h([0,1,2,3])
## Oracle for 0010 AND 1100 ##
qc.barrier()
qc.x([0,2,3])
qc.cu1(pi/4, 0, 3)
qc.cx(0, 1)
qc.cu1(-pi/4, 1, 3)
qc.cx(0, 1)
qc.cu1(pi/4, 1, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.x([0,2,3])
qc.x([0,1])
qc.cu1(pi/4, 0, 3)
qc.cx(0, 1)
qc.cu1(-pi/4, 1, 3)
qc.cx(0, 1)
qc.cu1(pi/4, 1, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.x([0,1])
qc.barrier()
## Amplification ##
qc.h([0,1,2,3])
qc.x([0,1,2,3])
#Start cccz
qc.cu1(pi/4, 0, 3)
qc.cx(0, 1)
qc.cu1(-pi/4, 1, 3)
qc.cx(0, 1)
qc.cu1(pi/4, 1, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
#end cccz
qc.x([0,1,2,3])
qc.h([0,1,2,3])
qc.barrier()
#### Repeat 1
## Oracle for 0010 AND 1100 ##
qc.x([0,2,3])
qc.cu1(pi/4, 0, 3)
qc.cx(0, 1)
qc.cu1(-pi/4, 1, 3)
qc.cx(0, 1)
qc.cu1(pi/4, 1, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.x([0,2,3])
qc.x([0,1])
qc.cu1(pi/4, 0, 3)
qc.cx(0, 1)
qc.cu1(-pi/4, 1, 3)
qc.cx(0, 1)
qc.cu1(pi/4, 1, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.x([0,1])
qc.barrier()
## Amplification ##
qc.h([0,1,2,3])
qc.x([0,1,2,3])
#Start cccz
qc.cu1(pi/4, 0, 3)
qc.cx(0, 1)
qc.cu1(-pi/4, 1, 3)
qc.cx(0, 1)
qc.cu1(pi/4, 1, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
qc.cx(1, 2)
qc.cu1(-pi/4, 2, 3)
qc.cx(0, 2)
qc.cu1(pi/4, 2, 3)
#end cccz
qc.x([0,1,2,3])
qc.h([0,1,2,3])
qc.measure_all()
qc.draw('mpl')
bcn = Aer.get_backend('qasm_simulator')
ph(execute(qc,backend=bcn,shots=shots).result().get_counts())
# one acceptable answer (0010)
circ = QuantumCircuit(4)
circ.h([0,1,2,3])
circ.barrier()
circ.x([0,2,3])
circ.h(3)
circ.mct([0,1,2], 3)
circ.h(3)
circ.x([0,2,3])
circ.barrier()
circ.h([0,1,2,3])
circ.x([0,1,2,3])
circ.h(3)
circ.mct([0,1,2], 3)
circ.h(3)
circ.x([0,1,2,3])
circ.h([0,1,2,3])
circ.barrier()
circ.x([0,2,3])
circ.h(3)
circ.mct([0,1,2], 3)
circ.h(3)
circ.x([0,2,3])
circ.barrier()
circ.h([0,1,2,3])
circ.x([0,1,2,3])
circ.h(3)
circ.mct([0,1,2], 3)
circ.h(3)
circ.x([0,1,2,3])
circ.h([0,1,2,3])
circ.barrier()
circ.x([0,2,3])
circ.h(3)
circ.mct([0,1,2], 3)
circ.h(3)
circ.x([0,2,3])
circ.barrier()
circ.h([0,1,2,3])
circ.x([0,1,2,3])
circ.h(3)
circ.mct([0,1,2], 3)
circ.h(3)
circ.x([0,1,2,3])
circ.h([0,1,2,3])
circ.measure_all()
circ.draw('mpl')
bcnd = Aer.get_backend('qasm_simulator')
ph(execute(circ,backend=bcnd,shots=1024).result().get_counts())
# three acceptable answers (0101, 1111, 1000)
n = 7
s = []
for i in range(n-1):
s.append(i)
qcqc = QuantumCircuit(n)
qcqc.h(range(n))
qcqc.barrier()
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.barrier()
qcqc.h(range(n))
qcqc.x(range(n))
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x(range(n))
qcqc.h(range(n))
qcqc.barrier()
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.barrier()
qcqc.h(range(n))
qcqc.x(range(n))
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x(range(n))
qcqc.h(range(n))
qcqc.barrier()
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.barrier()
qcqc.h(range(n))
qcqc.x(range(n))
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x(range(n))
qcqc.h(range(n))
qcqc.barrier()
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.barrier()
qcqc.h(range(n))
qcqc.x(range(n))
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x(range(n))
qcqc.h(range(n))
qcqc.barrier()
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([1,3])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x([0,1,2])
qcqc.barrier()
qcqc.h(range(n))
qcqc.x(range(n))
qcqc.h(n-1)
qcqc.mct(s, n-1)
qcqc.h(n-1)
qcqc.x(range(n))
qcqc.h(range(n))
qcqc.measure_all()
qcqc.draw('mpl')
bknd = Aer.get_backend('qasm_simulator')
ph(execute(qcqc,backend=bknd,shots=1024).result().get_counts())
|
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
# initialize two qubits in the zero state and
# two classical bits in the zero state in the quantum circuit
circuit = QuantumCircuit(3,3)
# C gate
# (2) => q2
circuit.x(2)
circuit.draw(output='mpl')
draw_circuit(circuit)
# Hadamard (H) gate
# (0) => (q0)
circuit.h(0)
circuit.draw(output='mpl')
draw_circuit(circuit)
# A controlled-NOT (CX NOT) gate, on control qubit 0
# and target qubit 1, putting the qubits in an entangled state.
# (2,1) = > q2(control bit)(quantum bit)(origin) --> q1(target bit)(quantum bit)(destination)
circuit.cx(2,1)
# (0,2) = > q0(control bit)(quantum bit)(origin) --> q2(target bit)(quantum bit)(destination)
circuit.cx(0,2)
circuit.draw(output='mpl')
draw_circuit(circuit)
# measurement between quantum state and classical state
# [1,1] => [q1,q1](quantum bit) and [2,0] => [c2,c0](classical bit)
circuit.measure([1,1],[2,0])
circuit.draw(output='mpl')
draw_circuit(circuit)
# The n qubit’s measurement result will be stored in the n classical bit
circuit.measure([1,1,2],[2,0,0])
circuit.draw(output='mpl')
draw_circuit(circuit)
simulator = Aer.get_backend("qasm_simulator")
job = execute(circuit, simulator, shots=2024)
result = job.result()
counts = result.get_counts(circuit)
print("Total count for 100 and 101 are: ", counts)
# 1.
plot_histogram(counts)
# 2.
from ibm_quantum_widgets import draw_circuit
draw_circuit(circuit)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Expectation value: {result.values[0]}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job = estimator.run(circuits, observables)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Observables: {[obs.paulis for obs in observables]}")
print(f">>> Expectation values: {result.values.tolist()}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
observable = SparsePauliOp("ZI")
parameter_values = [0, 1, 2, 3, 4, 5]
job = estimator.run(circuit, observable, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Parameter values: {parameter_values}")
print(f">>> Expectation value: {result.values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Estimator
estimator = Estimator(session=backend)
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Metadata: {result.metadata[0]}")
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value: {result.values[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
estimator = Estimator()
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the first run: {result.values[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the second run: {result.values[0]}")
from qiskit.circuit.random import random_circuit
sampler_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
sampler_circuit.measure_all()
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(sampler_circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/arian-code/nptel_quantum_assignments
|
arian-code
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#from ibm_quantum_widgets import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
from qiskit import assemble
import numpy as np
import matplotlib.pyplot as plt
n=4
grover_ckt = QuantumCircuit(n+1, n)
marked = [1,0,1,1] # 1101 element is marked (lsb to msb)=>13
def apply_oracle(n,marked,ckt):
control0 = [i for i in range(n) if not marked[i]]
ckt.x(control0)
ckt.mct(list(range(n)),n)
ckt.x(control0)
ckt.draw()
def reflect_uniform(ckt,n):
ckt.h(list(range(n)))
ckt.x(list(range(n)))
ckt.mct(list(range(n)),n)
ckt.x(list(range(n)))
ckt.h(list(range(n)))
ckt.x(n)
grover_ckt.x(n)
grover_ckt.barrier()
grover_ckt.h(list(range(n+1)))
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
marked = [1,0,1,1] # Corresponds to integer 1101 in binary => 13
ket_a = np.zeros(2**n)
ket_a[13] =1
ket_e = (np.ones(2**n) - ket_a)/np.sqrt(2**n -1)
print (ket_a)
print (ket_e)
def get_projection(psi,e,a ):
proj = [np.real(np.vdot(e,psi)), np.real(np.vdot(a,psi))]
return proj
def plt_vector(proj, axes =[0.0,1.0,0.0,1.0]):
x_pos = 0
y_pos = 0
x_direct = proj[0]
y_direct = proj[1]
# Creating plot
fig, ax = plt.subplots()
ax.quiver(x_pos, y_pos, x_direct, y_direct,scale=1.0)
ax.axis(axes)
# show plot
plt.show()
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj)
print (proj)
#grover_ckt.append(oracle, list(range(n+1)))
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
grover_ckt.draw()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj)
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj)
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
grover_ckt.draw()
svsim = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = svsim.run(qobj).result() # Do the simulation and return the result
statevector = result.data()['statevector']
statevector = statevector[:2**n]
proj = get_projection(statevector, ket_e, ket_a)
plt_vector(proj, axes = [-1.0,1.0,-1.0,1.0])
theta0 = 0.252
theta0
T = 0.5*((np.pi/(2*theta0))-1)
T
n=4
grover_ckt = QuantumCircuit(n+1, n)
marked = [1,0,1,1] # 1101 element is marked (lsb to msb)=>13
grover_ckt.x(n)
grover_ckt.barrier()
grover_ckt.h(list(range(n+1)))
grover_ckt.barrier()
for _ in range(int(np.floor(T))):
apply_oracle(4,marked,grover_ckt)
grover_ckt.barrier()
reflect_uniform(grover_ckt,n)
grover_ckt.barrier()
for j in range(n):
grover_ckt.measure(j,j)
grover_ckt.draw()
sim = Aer.get_backend('qasm_simulator') # Tell Qiskit how to simulate our circuit
qobj = assemble(grover_ckt) # Create a Qobj from the circuit for the simulator to run
result = sim.run(qobj).result() # Do the simulation and return the result
result
counts = result.get_counts(grover_ckt)
plot_histogram(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Stabilizerstate quantum state class."""
import unittest
from test import combine
import logging
from ddt import ddt, data, unpack
import numpy as np
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit
from qiskit.quantum_info.random import random_clifford, random_pauli
from qiskit.quantum_info.states import StabilizerState, Statevector
from qiskit.circuit.library import IGate, XGate, HGate
from qiskit.quantum_info.operators import Clifford, Pauli, Operator
logger = logging.getLogger(__name__)
@ddt
class TestStabilizerState(QiskitTestCase):
"""Tests for StabilizerState class."""
rng = np.random.default_rng(12345)
samples = 10
shots = 1000
threshold = 0.1 * shots
@combine(num_qubits=[2, 3, 4, 5])
def test_init_clifford(self, num_qubits):
"""Test initialization from Clifford."""
stab1 = StabilizerState(random_clifford(num_qubits, seed=self.rng))
stab2 = StabilizerState(stab1)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_init_circuit(self, num_qubits):
"""Test initialization from a Clifford circuit."""
cliff = random_clifford(num_qubits, seed=self.rng)
stab1 = StabilizerState(cliff.to_circuit())
stab2 = StabilizerState(cliff)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_init_instruction(self, num_qubits):
"""Test initialization from a Clifford instruction."""
cliff = random_clifford(num_qubits, seed=self.rng)
stab1 = StabilizerState(cliff.to_instruction())
stab2 = StabilizerState(cliff)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_init_pauli(self, num_qubits):
"""Test initialization from pauli."""
pauli = random_pauli(num_qubits, seed=self.rng)
stab1 = StabilizerState(pauli)
stab2 = StabilizerState(stab1)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_to_operator(self, num_qubits):
"""Test to_operator method for returning projector."""
for _ in range(self.samples):
stab = StabilizerState(random_clifford(num_qubits, seed=self.rng))
target = Operator(stab)
op = StabilizerState(stab).to_operator()
self.assertEqual(op, target)
@combine(num_qubits=[2, 3, 4])
def test_trace(self, num_qubits):
"""Test trace methods"""
stab = StabilizerState(random_clifford(num_qubits, seed=self.rng))
trace = stab.trace()
self.assertEqual(trace, 1.0)
@combine(num_qubits=[2, 3, 4])
def test_purity(self, num_qubits):
"""Test purity methods"""
stab = StabilizerState(random_clifford(num_qubits, seed=self.rng))
purity = stab.purity()
self.assertEqual(purity, 1.0)
@combine(num_qubits=[2, 3])
def test_conjugate(self, num_qubits):
"""Test conjugate method."""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
target = StabilizerState(cliff.conjugate())
state = StabilizerState(cliff).conjugate()
self.assertEqual(state, target)
def test_tensor(self):
"""Test tensor method."""
for _ in range(self.samples):
cliff1 = random_clifford(2, seed=self.rng)
cliff2 = random_clifford(3, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
target = StabilizerState(cliff1.tensor(cliff2))
state = stab1.tensor(stab2)
self.assertEqual(state, target)
def test_expand(self):
"""Test expand method."""
for _ in range(self.samples):
cliff1 = random_clifford(2, seed=self.rng)
cliff2 = random_clifford(3, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
target = StabilizerState(cliff1.expand(cliff2))
state = stab1.expand(stab2)
self.assertEqual(state, target)
@combine(num_qubits=[2, 3, 4])
def test_evolve(self, num_qubits):
"""Test evolve method."""
for _ in range(self.samples):
cliff1 = random_clifford(num_qubits, seed=self.rng)
cliff2 = random_clifford(num_qubits, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
target = StabilizerState(cliff1.compose(cliff2))
state = stab1.evolve(stab2)
self.assertEqual(state, target)
@combine(num_qubits_1=[4, 5, 6], num_qubits_2=[1, 2, 3])
def test_evolve_subsystem(self, num_qubits_1, num_qubits_2):
"""Test subsystem evolve method."""
for _ in range(self.samples):
cliff1 = random_clifford(num_qubits_1, seed=self.rng)
cliff2 = random_clifford(num_qubits_2, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
qargs = sorted(np.random.choice(range(num_qubits_1), num_qubits_2, replace=False))
target = StabilizerState(cliff1.compose(cliff2, qargs))
state = stab1.evolve(stab2, qargs)
self.assertEqual(state, target)
def test_measure_single_qubit(self):
"""Test a measurement of a single qubit"""
for _ in range(self.samples):
cliff = Clifford(XGate())
stab = StabilizerState(cliff)
value = stab.measure()[0]
self.assertEqual(value, "1")
cliff = Clifford(IGate())
stab = StabilizerState(cliff)
value = stab.measure()[0]
self.assertEqual(value, "0")
cliff = Clifford(HGate())
stab = StabilizerState(cliff)
value = stab.measure()[0]
self.assertIn(value, ["0", "1"])
def test_measure_qubits(self):
"""Test a measurement of a subsystem of qubits"""
for _ in range(self.samples):
num_qubits = 4
qc = QuantumCircuit(num_qubits)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertEqual(value, "0000")
value = stab.measure([0, 2])[0]
self.assertEqual(value, "00")
value = stab.measure([1])[0]
self.assertEqual(value, "0")
for i in range(num_qubits):
qc.x(i)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertEqual(value, "1111")
value = stab.measure([2, 0])[0]
self.assertEqual(value, "11")
value = stab.measure([1])[0]
self.assertEqual(value, "1")
qc = QuantumCircuit(num_qubits)
qc.h(0)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertIn(value, ["0000", "0001"])
value = stab.measure([0, 1])[0]
self.assertIn(value, ["00", "01"])
value = stab.measure([2])[0]
self.assertEqual(value, "0")
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertIn(value, ["0000", "1111"])
value = stab.measure([3, 1])[0]
self.assertIn(value, ["00", "11"])
value = stab.measure([2])[0]
self.assertIn(value, ["0", "1"])
def test_reset_single_qubit(self):
"""Test reset method of a single qubit"""
empty_qc = QuantumCircuit(1)
for _ in range(self.samples):
cliff = Clifford(XGate())
stab = StabilizerState(cliff)
value = stab.reset([0])
target = StabilizerState(empty_qc)
self.assertEqual(value, target)
cliff = Clifford(HGate())
stab = StabilizerState(cliff)
value = stab.reset([0])
target = StabilizerState(empty_qc)
self.assertEqual(value, target)
def test_reset_qubits(self):
"""Test reset method of a subsystem of qubits"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
for _ in range(self.samples):
with self.subTest(msg="reset (None)"):
stab = StabilizerState(qc)
res = stab.reset()
value = res.measure()[0]
self.assertEqual(value, "000")
for _ in range(self.samples):
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertEqual(value, "000")
for _ in range(self.samples):
with self.subTest(msg="reset ([0])"):
stab = StabilizerState(qc)
res = stab.reset([0])
value = res.measure()[0]
self.assertIn(value, ["000", "110"])
for _ in range(self.samples):
with self.subTest(msg="reset ([1])"):
stab = StabilizerState(qc)
res = stab.reset([1])
value = res.measure()[0]
self.assertIn(value, ["000", "101"])
for _ in range(self.samples):
with self.subTest(msg="reset ([2])"):
stab = StabilizerState(qc)
res = stab.reset([2])
value = res.measure()[0]
self.assertIn(value, ["000", "011"])
for _ in range(self.samples):
for qargs in [[0, 1], [1, 0]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertIn(value, ["000", "100"])
for _ in range(self.samples):
for qargs in [[0, 2], [2, 0]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertIn(value, ["000", "010"])
for _ in range(self.samples):
for qargs in [[1, 2], [2, 1]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertIn(value, ["000", "001"])
def test_probablities_dict_single_qubit(self):
"""Test probabilities and probabilities_dict methods of a single qubit"""
num_qubits = 1
qc = QuantumCircuit(num_qubits)
for _ in range(self.samples):
with self.subTest(msg="P(id(0))"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"0": 1}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
qc.x(0)
for _ in range(self.samples):
with self.subTest(msg="P(x(0))"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"1": 1}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0, 1])
self.assertTrue(np.allclose(probs, target))
qc = QuantumCircuit(num_qubits)
qc.h(0)
for _ in range(self.samples):
with self.subTest(msg="P(h(0))"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"0": 0.5, "1": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
def test_probablities_dict_two_qubits(self):
"""Test probabilities and probabilities_dict methods of two qubits"""
num_qubits = 2
qc = QuantumCircuit(num_qubits)
qc.h(0)
stab = StabilizerState(qc)
for _ in range(self.samples):
with self.subTest(msg="P(None)"):
value = stab.probabilities_dict()
target = {"00": 0.5, "01": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P([0, 1])"):
value = stab.probabilities_dict([0, 1])
target = {"00": 0.5, "01": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities([0, 1])
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P([1, 0])"):
value = stab.probabilities_dict([1, 0])
target = {"00": 0.5, "10": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities([1, 0])
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P[0]"):
value = stab.probabilities_dict([0])
target = {"0": 0.5, "1": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities([0])
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P([1])"):
value = stab.probabilities_dict([1])
target = {"0": 1.0}
self.assertEqual(value, target)
probs = stab.probabilities([1])
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
def test_probablities_dict_qubits(self):
"""Test probabilities and probabilities_dict methods of a subsystem of qubits"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.h(1)
qc.h(2)
stab = StabilizerState(qc)
for _ in range(self.samples):
with self.subTest(msg="P(None), decimals=1"):
value = stab.probabilities_dict(decimals=1)
target = {
"000": 0.1,
"001": 0.1,
"010": 0.1,
"011": 0.1,
"100": 0.1,
"101": 0.1,
"110": 0.1,
"111": 0.1,
}
self.assertEqual(value, target)
probs = stab.probabilities(decimals=1)
target = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P(None), decimals=2"):
value = stab.probabilities_dict(decimals=2)
target = {
"000": 0.12,
"001": 0.12,
"010": 0.12,
"011": 0.12,
"100": 0.12,
"101": 0.12,
"110": 0.12,
"111": 0.12,
}
self.assertEqual(value, target)
probs = stab.probabilities(decimals=2)
target = np.array([0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P(None), decimals=3"):
value = stab.probabilities_dict(decimals=3)
target = {
"000": 0.125,
"001": 0.125,
"010": 0.125,
"011": 0.125,
"100": 0.125,
"101": 0.125,
"110": 0.125,
"111": 0.125,
}
self.assertEqual(value, target)
probs = stab.probabilities(decimals=3)
target = np.array([0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125])
self.assertTrue(np.allclose(probs, target))
def test_probablities_dict_ghz(self):
"""Test probabilities and probabilities_dict method of a subsystem of qubits"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
with self.subTest(msg="P(None)"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"000": 0.5, "111": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
self.assertTrue(np.allclose(probs, target))
# 3-qubit qargs
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = stab.probabilities_dict(qargs)
target = {"000": 0.5, "111": 0.5}
self.assertDictAlmostEqual(probs, target)
probs = stab.probabilities(qargs)
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
for qargs in [[0, 1], [2, 1], [1, 0], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = stab.probabilities_dict(qargs)
target = {"00": 0.5, "11": 0.5}
self.assertDictAlmostEqual(probs, target)
probs = stab.probabilities(qargs)
target = np.array([0.5, 0, 0, 0.5])
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = stab.probabilities_dict(qargs)
target = {"0": 0.5, "1": 0.5}
self.assertDictAlmostEqual(probs, target)
probs = stab.probabilities(qargs)
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
@combine(num_qubits=[2, 3, 4])
def test_probs_random_subsystem(self, num_qubits):
"""Test probabilities and probabilities_dict methods
of random cliffords for a subsystem of qubits"""
for _ in range(self.samples):
for subsystem_size in range(1, num_qubits):
cliff = random_clifford(num_qubits, seed=self.rng)
qargs = np.random.choice(num_qubits, size=subsystem_size, replace=False)
qc = cliff.to_circuit()
stab = StabilizerState(cliff)
probs = stab.probabilities(qargs)
probs_dict = stab.probabilities_dict(qargs)
target = Statevector(qc).probabilities(qargs)
target_dict = Statevector(qc).probabilities_dict(qargs)
self.assertTrue(np.allclose(probs, target))
self.assertDictAlmostEqual(probs_dict, target_dict)
@combine(num_qubits=[2, 3, 4, 5])
def test_expval_from_random_clifford(self, num_qubits):
"""Test that the expectation values for a random Clifford,
where the Pauli operators are all its stabilizers,
are equal to 1."""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
qc = cliff.to_circuit()
stab = StabilizerState(qc)
stab_gen = stab.clifford.to_dict()["stabilizer"]
for i in range(num_qubits):
op = Pauli(stab_gen[i])
exp_val = stab.expectation_value(op)
self.assertEqual(exp_val, 1)
def test_sample_counts_reset_bell(self):
"""Test sample_counts after reset for Bell state"""
num_qubits = 2
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
stab = StabilizerState(qc)
target = {"00": self.shots / 2, "10": self.shots / 2}
counts = {"00": 0, "10": 0}
for _ in range(self.shots):
res = stab.reset([0])
value = res.measure()[0]
counts[value] += 1
self.assertDictAlmostEqual(counts, target, self.threshold)
target = {"00": self.shots / 2, "01": self.shots / 2}
counts = {"00": 0, "01": 0}
for _ in range(self.shots):
res = stab.reset([1])
value = res.measure()[0]
counts[value] += 1
self.assertDictAlmostEqual(counts, target, self.threshold)
def test_sample_counts_memory_ghz(self):
"""Test sample_counts and sample_memory method for GHZ state"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
stab = StabilizerState(qc)
# 3-qubit qargs
target = {"000": self.shots / 2, "111": self.shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": self.shots / 2, "11": self.shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": self.shots / 2, "1": self.shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
def test_sample_counts_memory_superposition(self):
"""Test sample_counts and sample_memory method of a 3-qubit superposition"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.h(1)
qc.h(2)
stab = StabilizerState(qc)
# 3-qubit qargs
target = {
"000": self.shots / 8,
"001": self.shots / 8,
"010": self.shots / 8,
"011": self.shots / 8,
"100": self.shots / 8,
"101": self.shots / 8,
"110": self.shots / 8,
"111": self.shots / 8,
}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {
"00": self.shots / 4,
"01": self.shots / 4,
"10": self.shots / 4,
"11": self.shots / 4,
}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": self.shots / 2, "1": self.shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
@ddt
class TestStabilizerStateExpectationValue(QiskitTestCase):
"""Tests for StabilizerState.expectation_value method."""
rng = np.random.default_rng(12345)
samples = 10
shots = 1000
threshold = 0.1 * shots
@data(("Z", 1), ("X", 0), ("Y", 0), ("I", 1), ("Z", 1), ("-Z", -1), ("iZ", 1j), ("-iZ", -1j))
@unpack
def test_expval_single_qubit_0(self, label, target):
"""Test expectation_value method of a single qubit on |0>"""
qc = QuantumCircuit(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(("Z", -1), ("X", 0), ("Y", 0), ("I", 1))
@unpack
def test_expval_single_qubit_1(self, label, target):
"""Test expectation_value method of a single qubit on |1>"""
qc = QuantumCircuit(1)
qc.x(0)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(("Z", 0), ("X", 1), ("Y", 0), ("I", 1), ("X", 1), ("-X", -1), ("iX", 1j), ("-iX", -1j))
@unpack
def test_expval_single_qubit_plus(self, label, target):
"""Test expectation_value method of a single qubit on |+>"""
qc = QuantumCircuit(1)
qc.h(0)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 0),
("YY", 0),
("ZZ", 1),
("IX", 0),
("IY", 0),
("IZ", 1),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-ZZ", -1),
("iZZ", 1j),
("-iZZ", -1j),
)
@unpack
def test_expval_two_qubits_00(self, label, target):
"""Test expectation_value method of two qubits in |00>"""
num_qubits = 2
qc = QuantumCircuit(num_qubits)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 0),
("YY", 0),
("ZZ", 1),
("IX", 0),
("IY", 0),
("IZ", -1),
("XY", 0),
("XZ", 0),
("YZ", 0),
)
@unpack
def test_expval_two_qubits_11(self, label, target):
"""Test expectation_value method of two qubits in |11>"""
qc = QuantumCircuit(2)
qc.x(0)
qc.x(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", 0),
("ZZ", 0),
("IX", 1),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-XX", -1),
("iXX", 1j),
("-iXX", -1j),
)
@unpack
def test_expval_two_qubits_plusplus(self, label, target):
"""Test expectation_value method of two qubits in |++>"""
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 0),
("YY", 0),
("ZZ", 0),
("IX", 0),
("IY", 0),
("IZ", -1),
("XY", 0),
("XZ", -1),
("YZ", 0),
)
@unpack
def test_expval_two_qubits_plus1(self, label, target):
"""Test expectation_value method of two qubits in |+1>"""
qc = QuantumCircuit(2)
qc.x(0)
qc.h(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", -1),
("ZZ", 1),
("IX", 0),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-YY", 1),
("iYY", -1j),
("-iYY", 1j),
)
@unpack
def test_expval_two_qubits_bell_phi_plus(self, label, target):
"""Test expectation_value method of two qubits in bell phi plus"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", 1),
("ZZ", -1),
("IX", 0),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-XX", -1),
("-YY", -1),
("iXX", 1j),
("iYY", 1j),
("-iXX", -1j),
("-iYY", -1j),
)
@unpack
def test_expval_two_qubits_bell_phi_minus(self, label, target):
"""Test expectation_value method of two qubits in bell phi minus"""
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.cx(0, 1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", 1),
("ZZ", -1),
("IX", 0),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-XX", -1),
("-YY", -1),
("iXX", 1j),
("iYY", 1j),
("-iXX", -1j),
("-iYY", -1j),
)
@unpack
def test_expval_two_qubits_bell_sdg_h(self, label, target):
"""Test expectation_value method of two qubits in bell followed by sdg and h"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.sdg(0)
qc.sdg(1)
qc.h(0)
qc.h(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@combine(num_qubits=[2, 3, 4, 5])
def test_expval_random(self, num_qubits):
"""Test expectation_value method of random Cliffords"""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
op = random_pauli(num_qubits, group_phase=True, seed=self.rng)
qc = cliff.to_circuit()
stab = StabilizerState(cliff)
exp_val = stab.expectation_value(op)
target = Statevector(qc).expectation_value(op)
self.assertAlmostEqual(exp_val, target)
@combine(num_qubits=[2, 3, 4, 5])
def test_expval_random_subsystem(self, num_qubits):
"""Test expectation_value method of random Cliffords and a subsystem"""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
op = random_pauli(2, group_phase=True, seed=self.rng)
qargs = np.random.choice(num_qubits, size=2, replace=False)
qc = cliff.to_circuit()
stab = StabilizerState(cliff)
exp_val = stab.expectation_value(op, qargs)
target = Statevector(qc).expectation_value(op, qargs)
self.assertAlmostEqual(exp_val, target)
def test_stabilizer_bell_equiv(self):
"""Test that two circuits produce the same stabilizer group."""
qc1 = QuantumCircuit(2)
qc1.h(0)
qc1.x(1)
qc1.cx(0, 1)
qc2 = QuantumCircuit(2)
qc2.h(0)
qc2.cx(0, 1)
qc2.sdg(0)
qc2.sdg(1)
qc2.h(0)
qc2.h(1)
qc3 = QuantumCircuit(2)
qc3.h(0)
qc3.cx(0, 1)
qc4 = QuantumCircuit(2)
qc4.h(0)
qc4.cx(0, 1)
qc4.s(0)
qc4.sdg(1)
qc4.h(0)
qc4.h(1)
cliff1 = StabilizerState(qc1) # ['+XX', '-ZZ']
cliff2 = StabilizerState(qc2) # ['+YY', '+XX']
cliff3 = StabilizerState(qc3) # ['+XX', '+ZZ']
cliff4 = StabilizerState(qc4) # ['-YY', '+XX']
# [XX, -ZZ] and [XX, YY] both generate the stabilizer group {II, XX, YY, -ZZ}
self.assertTrue(cliff1.equiv(cliff2))
self.assertEqual(cliff1.probabilities_dict(), cliff2.probabilities_dict())
# [XX, ZZ] and [XX, -YY] both generate the stabilizer group {II, XX, -YY, ZZ}
self.assertTrue(cliff3.equiv(cliff4))
self.assertEqual(cliff3.probabilities_dict(), cliff4.probabilities_dict())
self.assertFalse(cliff1.equiv(cliff3))
self.assertFalse(cliff2.equiv(cliff4))
if __name__ == "__main__":
unittest.main()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import numpy as np
from copy import deepcopy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.aqua import aqua_globals
from qiskit.aqua.components.optimizers import ADAM
from qiskit.aqua.components.uncertainty_models import UniformDistribution, MultivariateUniformDistribution
from qiskit.aqua.components.uncertainty_models import UnivariateVariationalDistribution, \
MultivariateVariationalDistribution
from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua import AquaError, Pluggable
from qiskit.aqua.components.neural_networks.generative_network import GenerativeNetwork
from qiskit.aqua.components.initial_states import Custom
class QuantumGenerator(GenerativeNetwork):
"""
Generator
"""
CONFIGURATION = {
'name': 'QuantumGenerator',
'description': 'qGAN Generator Network',
'input_schema': {
'$schema': 'http://json-schema.org/schema#',
'id': 'generator_schema',
'type': 'object',
'properties': {
'bounds': {
'type': 'array'
},
'num_qubits': {
'type': 'array'
},
'init_params': {
'type': ['array', 'null'],
'default': None
},
'snapshot_dir': {
'type': ['string', 'null'],
'default': None
}
},
'additionalProperties': False
}
}
def __init__(self, bounds, num_qubits, generator_circuit=None, init_params=None, snapshot_dir=None):
"""
Initialize the generator network.
Args:
bounds: array, k min/max data values [[min_1,max_1],...,[min_k,max_k]], given input data dim k
num_qubits: array, k numbers of qubits to determine representation resolution,
i.e. n qubits enable the representation of 2**n values [n_1,..., n_k]
generator_circuit: UnivariateVariationalDistribution for univariate data/
MultivariateVariationalDistribution for multivariate data, Quantum circuit to implement the generator.
init_params: 1D numpy array or list, Initialization for the generator's parameters.
snapshot_dir: str or None, if not None save the optimizer's parameter after every update step to the given
directory
"""
self._bounds = bounds
self._num_qubits = num_qubits
self.generator_circuit = generator_circuit
if self.generator_circuit is None:
entangler_map = []
if np.sum(num_qubits) > 2:
for i in range(int(np.sum(num_qubits))):
entangler_map.append([i, int(np.mod(i + 1, np.sum(num_qubits)))])
else:
if np.sum(num_qubits) > 1:
entangler_map.append([0, 1])
if len(num_qubits)>1:
num_qubits = list(map(int, num_qubits))
low = bounds[:, 0].tolist()
high = bounds[:, 1].tolist()
init_dist = MultivariateUniformDistribution(num_qubits, low=low, high=high)
q = QuantumRegister(sum(num_qubits))
qc = QuantumCircuit(q)
init_dist.build(qc, q)
init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc)
# Set variational form
var_form = RY(sum(num_qubits), depth=1, initial_state=init_distribution, entangler_map=entangler_map,
entanglement_gate='cz')
if init_params is None:
init_params = aqua_globals.random.rand(var_form.num_parameters) * 2 * 1e-2
# Set generator circuit
self.generator_circuit = MultivariateVariationalDistribution(num_qubits, var_form, init_params,
low=low, high=high)
else:
init_dist = UniformDistribution(sum(num_qubits), low=bounds[0], high=bounds[1])
q = QuantumRegister(sum(num_qubits), name='q')
qc = QuantumCircuit(q)
init_dist.build(qc, q)
init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc)
var_form = RY(sum(num_qubits), depth=1, initial_state=init_distribution, entangler_map=entangler_map,
entanglement_gate='cz')
if init_params is None:
init_params = aqua_globals.random.rand(var_form.num_parameters) * 2 * 1e-2
# Set generator circuit
self.generator_circuit = UnivariateVariationalDistribution(int(np.sum(num_qubits)), var_form,
init_params, low=bounds[0], high=bounds[1])
if len(num_qubits) > 1:
if isinstance(self.generator_circuit, MultivariateVariationalDistribution):
pass
else:
raise AquaError('Set multivariate variational distribution to represent multivariate data')
else:
if isinstance(self.generator_circuit, UnivariateVariationalDistribution):
pass
else:
raise AquaError('Set univariate variational distribution to represent univariate data')
# Set optimizer for updating the generator network
self._optimizer = ADAM(maxiter=1, tol=1e-6, lr=1e-5, beta_1=0.9, beta_2=0.99, noise_factor=1e-8,
eps=1e-10, amsgrad=True, snapshot_dir=snapshot_dir)
if np.ndim(self._bounds) == 1:
bounds = np.reshape(self._bounds, (1, len(self._bounds)))
else:
bounds = self._bounds
for j, prec in enumerate(self._num_qubits):
grid = np.linspace(bounds[j, 0], bounds[j, 1], (2 ** prec)) # prepare data grid for dim j
if j == 0:
if len(self._num_qubits) > 1:
self._data_grid = [grid]
else:
self._data_grid = grid
self._grid_elements = grid
elif j == 1:
self._data_grid.append(grid)
temp = []
for g_e in self._grid_elements:
for g in grid:
temp0 = [g_e]
temp0.append(g)
temp.append(temp0)
self._grid_elements = temp
else:
self._data_grid.append(grid)
temp = []
for g_e in self._grid_elements:
for g in grid:
temp0 = deepcopy(g_e)
temp0.append(g)
temp.append(temp0)
self._grid_elements = deepcopy(temp)
self._data_grid = np.array(self._data_grid)
self._shots = None
self._discriminator = None
self._ret = {}
@classmethod
def init_params(cls, params):
"""
Initialize via parameters dictionary and algorithm input instance.
Args:
params (dict): parameters dictionary
Returns:
QuantumGenerator: vqe object
"""
generator_params = params.get(Pluggable.SECTION_KEY_GENERATIVE_NETWORK)
bounds = generator_params.get('bounds')
if bounds is None:
raise AquaError("Data value bounds are required.")
num_qubits = generator_params.get('num_qubits')
if num_qubits is None:
raise AquaError("Numbers of qubits per dimension required.")
init_params = generator_params.get('init_params')
snapshot_dir = generator_params.get('snapshot_dir')
return cls(bounds, num_qubits, generator_circuit=None, init_params=init_params, snapshot_dir=snapshot_dir)
@classmethod
def get_section_key_name(cls):
return Pluggable.SECTION_KEY_GENERATIVE_NETWORK
def set_seed(self, seed):
"""
Set seed.
Args:
seed: int, seed
Returns:
"""
aqua_globals.random_seed = seed
def set_discriminator(self, discriminator):
"""
Set discriminator
Args:
discriminator: Discriminator, Discriminator used to compute the loss function.
"""
self._discriminator = discriminator
return
def construct_circuit(self, quantum_instance, params=None):
"""
Construct generator circuit.
Args:
quantum_instance: QuantumInstance, used for running the generator circuit
params: array or None, parameters which should be used to run the generator, if None use self._params
Returns: QuantumCircuit, constructed quantum circuit
"""
q = QuantumRegister(sum(self._num_qubits), name='q')
qc = QuantumCircuit(q)
if params is None:
self.generator_circuit.build(qc=qc, q=q)
else:
generator_circuit_copy = deepcopy(self.generator_circuit)
generator_circuit_copy.params = params
generator_circuit_copy.build(qc=qc, q=q)
c = ClassicalRegister(q.size, name='c')
qc.add_register(c)
if quantum_instance.is_statevector:
return qc.copy(name='qc')
else:
qc.measure(q, c)
return qc.copy(name='qc')
def get_output(self, quantum_instance, params=None, shots=None):
"""
Get data samples from the generator.
Args:
quantum_instance: QuantumInstance, used to run the generator circuit.
params: array or None, parameters which should be used to run the generator, if None use self._params
shots: int, if not None use a number of shots that is different from the number set in quantum_instance
Returns: array: generated samples, array: sample occurence in percentage
"""
qc = self.construct_circuit(quantum_instance, params)
if shots is not None:
quantum_instance.set_config(shots=shots)
else:
quantum_instance.set_config(shots=self._shots)
result = quantum_instance.execute(qc)
generated_samples = []
if quantum_instance.is_statevector:
result = result.get_statevector(qc)
values = np.multiply(result, np.conj(result))
values = list(values.real)
keys = []
for j in range(len(values)):
keys.append(np.binary_repr(j, int(sum(self._num_qubits))))
else:
result = result.get_counts(qc)
keys = list(result)
values = list(result.values())
values = [float(v) / np.sum(values) for v in values]
generated_samples_weights = values
for i in range(len(keys)):
index = 0
temp = []
for k, p in enumerate(self._num_qubits):
bin_rep = 0
j = 0
while j < p:
bin_rep += int(keys[i][index]) * 2 ** (int(p) - j - 1)
j += 1
index += 1
if len(self._num_qubits) > 1:
temp.append(self._data_grid[k][int(bin_rep)])
else:
temp.append(self._data_grid[int(bin_rep)])
generated_samples.append(temp)
self.generator_circuit._probabilities = generated_samples_weights
return generated_samples, generated_samples_weights
def loss(self, x, weights):
"""
Loss function
Args:
x: array, sample label (equivalent to discriminator output)
weights: array, probability for measuring the sample
Returns: float, loss function
"""
return (-1)*np.dot(weights, np.log(x))
def _get_objective_function(self, quantum_instance, discriminator):
"""
Get objective function
Args:
quantum_instance: QuantumInstance, used to run the quantum circuit.
discriminator: torch.nn.Module, discriminator network to compute the sample labels.
Returns: objective function for quantum generator optimization
"""
def objective_function(params):
"""
Objective function
Args:
params: array, generator parameters
Returns: loss function
"""
generated_data, generated_prob = self.get_output(quantum_instance, params=params, shots=self._shots)
prediction_generated = discriminator.get_label(generated_data).detach().numpy()
return self.loss(prediction_generated, generated_prob)
return objective_function
def train(self, quantum_instance, shots=None):
"""
Perform one training step w.r.t to the generator's parameters
Args:
quantum_instance: QuantumInstance, used to run the generator circuit.
shots: int, Number of shots for hardware or qasm execution.
Returns: dict, generator loss(float) and updated parameters (array).
"""
self._shots = shots
# Force single optimization iteration
self._optimizer._maxiter = 1
self._optimizer._t = 0
objective = self._get_objective_function(quantum_instance, self._discriminator)
self.generator_circuit.params, loss, nfev = \
self._optimizer.optimize(num_vars=len(self.generator_circuit.params), objective_function=objective,
initial_point=self.generator_circuit.params)
self._ret['loss'] = loss[0]
self._ret['params'] = self.generator_circuit.params
return self._ret
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import qiskit
qiskit.__qiskit_version__
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import BasicAer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.visualization import plot_histogram
q = QuantumRegister(6)
qc = QuantumCircuit(q)
qc.x(q[2])
qc.cx(q[1], q[5])
qc.cx(q[2], q[5])
qc.cx(q[3], q[5])
qc.ccx(q[1], q[2], q[4])
qc.ccx(q[3], q[4], q[5])
qc.ccx(q[1], q[2], q[4])
qc.x(q[2])
qc.draw(output='mpl')
def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula):
"""Circuit that computes the black-box function from f_in to f_out.
Create a circuit that verifies whether a given exactly-1 3-SAT
formula is satisfied by the input. The exactly-1 version
requires exactly one literal out of every clause to be satisfied.
"""
num_clauses = len(exactly_1_3_sat_formula)
for (k, clause) in enumerate(exactly_1_3_sat_formula):
# This loop ensures aux[k] is 1 if an odd number of literals
# are true
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
# Flip aux[k] if all literals are true, using auxiliary qubit
# (ancilla) aux[num_clauses]
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
# Flip back to reverse state of negative literals and ancilla
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
# The formula is satisfied if and only if all auxiliary qubits
# except aux[num_clauses] are 1
if (num_clauses == 1):
circuit.cx(aux[0], f_out[0])
elif (num_clauses == 2):
circuit.ccx(aux[0], aux[1], f_out[0])
elif (num_clauses == 3):
circuit.ccx(aux[0], aux[1], aux[num_clauses])
circuit.ccx(aux[2], aux[num_clauses], f_out[0])
circuit.ccx(aux[0], aux[1], aux[num_clauses])
else:
raise ValueError('We only allow at most 3 clauses')
# Flip back any auxiliary qubits to make sure state is consistent
# for future executions of this routine; same loop as above.
for (k, clause) in enumerate(exactly_1_3_sat_formula):
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
# -- end function
def n_controlled_Z(circuit, controls, target):
"""Implement a Z gate with multiple controls"""
if (len(controls) > 2):
raise ValueError('The controlled Z with more than 2 ' +
'controls is not implemented')
elif (len(controls) == 1):
circuit.h(target)
circuit.cx(controls[0], target)
circuit.h(target)
elif (len(controls) == 2):
circuit.h(target)
circuit.ccx(controls[0], controls[1], target)
circuit.h(target)
# -- end function
def inversion_about_average(circuit, f_in, n):
"""Apply inversion about the average step of Grover's algorithm."""
# Hadamards everywhere
for j in range(n):
circuit.h(f_in[j])
# D matrix: flips the sign of the state |000> only
for j in range(n):
circuit.x(f_in[j])
n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1])
for j in range(n):
circuit.x(f_in[j])
# Hadamards everywhere again
for j in range(n):
circuit.h(f_in[j])
# -- end function
qr = QuantumRegister(3)
qInvAvg = QuantumCircuit(qr)
inversion_about_average(qInvAvg, qr, 3)
qInvAvg.draw(output='mpl')
"""
Grover search implemented in Qiskit.
This module contains the code necessary to run Grover search on 3
qubits, both with a simulator and with a real quantum computing
device. This code is the companion for the paper
"An introduction to quantum computing, without the physics",
Giacomo Nannicini, https://arxiv.org/abs/1708.03684.
"""
def input_state(circuit, f_in, f_out, n):
"""(n+1)-qubit input state for Grover search."""
for j in range(n):
circuit.h(f_in[j])
circuit.x(f_out)
circuit.h(f_out)
# -- end function
# Make a quantum program for the n-bit Grover search.
n = 3
# Exactly-1 3-SAT formula to be satisfied, in conjunctive
# normal form. We represent literals with integers, positive or
# negative, to indicate a Boolean variable or its negation.
exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]]
# Define three quantum registers: 'f_in' is the search space (input
# to the function f), 'f_out' is bit used for the output of function
# f, aux are the auxiliary bits used by f to perform its
# computation.
f_in = QuantumRegister(n)
f_out = QuantumRegister(1)
aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1)
# Define classical register for algorithm result
ans = ClassicalRegister(n)
# Define quantum circuit with above registers
grover = QuantumCircuit()
grover.add_register(f_in)
grover.add_register(f_out)
grover.add_register(aux)
grover.add_register(ans)
input_state(grover, f_in, f_out, n)
T = 2
for t in range(T):
# Apply T full iterations
black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula)
inversion_about_average(grover, f_in, n)
# Measure the output register in the computational basis
for j in range(n):
grover.measure(f_in[j], ans[j])
# Execute circuit
backend = BasicAer.get_backend('qasm_simulator')
job = execute([grover], backend=backend, shots=1000)
result = job.result()
# Get counts and plot histogram
counts = result.get_counts(grover)
plot_histogram(counts)
IBMQ.load_account()
# get ibmq_16_melbourne configuration and coupling map
backend = IBMQ.get_backend('ibmq_16_melbourne')
# compile the circuit for ibmq_16_rueschlikon
grover_compiled = transpile(grover, backend=backend, seed_transpiler=1, optimization_level=3)
print('gates = ', grover_compiled.count_ops())
print('depth = ', grover_compiled.depth())
grover.draw(output='mpl', scale=0.5)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A container class for counts from a circuit execution."""
import re
from qiskit.result import postprocess
from qiskit import exceptions
# NOTE: A dict subclass should not overload any dunder methods like __getitem__
# this can cause unexpected behavior and issues as the cPython dict
# implementation has many standard methods in C for performance and the dunder
# methods are not always used as expected. For example, update() doesn't call
# __setitem__ so overloading __setitem__ would not always provide the expected
# result
class Counts(dict):
"""A class to store a counts result from a circuit execution."""
bitstring_regex = re.compile(r"^[01\s]+$")
def __init__(self, data, time_taken=None, creg_sizes=None, memory_slots=None):
"""Build a counts object
Args:
data (dict): The dictionary input for the counts. Where the keys
represent a measured classical value and the value is an
integer the number of shots with that result.
The keys can be one of several formats:
* A hexadecimal string of the form ``'0x4a'``
* A bit string prefixed with ``0b`` for example ``'0b1011'``
* A bit string formatted across register and memory slots.
For example, ``'00 10'``.
* A dit string, for example ``'02'``. Note for objects created
with dit strings the ``creg_sizes`` and ``memory_slots``
kwargs don't work and :meth:`hex_outcomes` and
:meth:`int_outcomes` also do not work.
time_taken (float): The duration of the experiment that generated
the counts in seconds.
creg_sizes (list): a nested list where the inner element is a list
of tuples containing both the classical register name and
classical register size. For example,
``[('c_reg', 2), ('my_creg', 4)]``.
memory_slots (int): The number of total ``memory_slots`` in the
experiment.
Raises:
TypeError: If the input key type is not an ``int`` or ``str``.
QiskitError: If a dit string key is input with ``creg_sizes`` and/or
``memory_slots``.
"""
bin_data = None
data = dict(data)
if not data:
self.int_raw = {}
self.hex_raw = {}
bin_data = {}
else:
first_key = next(iter(data.keys()))
if isinstance(first_key, int):
self.int_raw = data
self.hex_raw = {hex(key): value for key, value in self.int_raw.items()}
elif isinstance(first_key, str):
if first_key.startswith("0x"):
self.hex_raw = data
self.int_raw = {int(key, 0): value for key, value in self.hex_raw.items()}
elif first_key.startswith("0b"):
self.int_raw = {int(key, 0): value for key, value in data.items()}
self.hex_raw = {hex(key): value for key, value in self.int_raw.items()}
else:
if not creg_sizes and not memory_slots:
self.hex_raw = None
self.int_raw = None
bin_data = data
else:
hex_dict = {}
int_dict = {}
for bitstring, value in data.items():
if not self.bitstring_regex.search(bitstring):
raise exceptions.QiskitError(
"Counts objects with dit strings do not "
"currently support dit string formatting parameters "
"creg_sizes or memory_slots"
)
int_key = self._remove_space_underscore(bitstring)
int_dict[int_key] = value
hex_dict[hex(int_key)] = value
self.hex_raw = hex_dict
self.int_raw = int_dict
else:
raise TypeError(
"Invalid input key type %s, must be either an int "
"key or string key with hexademical value or bit string"
)
header = {}
self.creg_sizes = creg_sizes
if self.creg_sizes:
header["creg_sizes"] = self.creg_sizes
self.memory_slots = memory_slots
if self.memory_slots:
header["memory_slots"] = self.memory_slots
if not bin_data:
bin_data = postprocess.format_counts(self.hex_raw, header=header)
super().__init__(bin_data)
self.time_taken = time_taken
def most_frequent(self):
"""Return the most frequent count
Returns:
str: The bit string for the most frequent result
Raises:
QiskitError: when there is >1 count with the same max counts, or
an empty object.
"""
if not self:
raise exceptions.QiskitError("Can not return a most frequent count on an empty object")
max_value = max(self.values())
max_values_counts = [x[0] for x in self.items() if x[1] == max_value]
if len(max_values_counts) != 1:
raise exceptions.QiskitError(
"Multiple values have the same maximum counts: %s" % ",".join(max_values_counts)
)
return max_values_counts[0]
def hex_outcomes(self):
"""Return a counts dictionary with hexadecimal string keys
Returns:
dict: A dictionary with the keys as hexadecimal strings instead of
bitstrings
Raises:
QiskitError: If the Counts object contains counts for dit strings
"""
if self.hex_raw:
return {key.lower(): value for key, value in self.hex_raw.items()}
else:
out_dict = {}
for bitstring, value in self.items():
if not self.bitstring_regex.search(bitstring):
raise exceptions.QiskitError(
"Counts objects with dit strings do not "
"currently support conversion to hexadecimal"
)
int_key = self._remove_space_underscore(bitstring)
out_dict[hex(int_key)] = value
return out_dict
def int_outcomes(self):
"""Build a counts dictionary with integer keys instead of count strings
Returns:
dict: A dictionary with the keys as integers instead of bitstrings
Raises:
QiskitError: If the Counts object contains counts for dit strings
"""
if self.int_raw:
return self.int_raw
else:
out_dict = {}
for bitstring, value in self.items():
if not self.bitstring_regex.search(bitstring):
raise exceptions.QiskitError(
"Counts objects with dit strings do not "
"currently support conversion to integer"
)
int_key = self._remove_space_underscore(bitstring)
out_dict[int_key] = value
return out_dict
@staticmethod
def _remove_space_underscore(bitstring):
"""Removes all spaces and underscores from bitstring"""
return int(bitstring.replace(" ", "").replace("_", ""), 2)
def shots(self):
"""Return the number of shots"""
return sum(self.values())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from numpy import pi
from qiskit import QuantumRegister, QuantumCircuit, execute, BasicAer
from qiskit.visualization import plot_histogram
qreg_q = QuantumRegister(3, 'q')
circuit = QuantumCircuit(qreg_q)
circuit.h(qreg_q[0])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.cx(qreg_q[0], qreg_q[2])
circuit.measure_all()
circuit.draw(output='latex')
result_meas = execute(circuit, BasicAer.get_backend('qasm_simulator'))
counts = result_meas.result().get_counts()
plot_histogram(counts, figsize=(5,6), bar_labels=False, title="Probabilities")
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/tushdon2/Qiskit_Hackathon_IITR_2021
|
tushdon2
|
# importing required libraries
from tensorflow import keras
import os
from pathlib import Path
modelPath = os.path.join(Path(os.path.realpath("__file__")).parent.parent, "assets/model/hand_gesture_classify_model.h5")
model = keras.models.load_model(modelPath)
model.summary()
# TESTING the model
# Augment the Data
datagen = keras.preprocessing.image.ImageDataGenerator(
samplewise_center = True, # set each sample mean to 0
rotation_range = 10, # randomly rotate images in the range (degrees, 0 to 180)
zoom_range = 0.1, # Randomly zoom image
width_shift_range = 0.1, # randomly shift images horizontally (fraction of total width)
height_shift_range = 0.1, # randomly shift images vertically (fraction of total height)
horizontal_flip = True, # randomly flip images
vertical_flip = True)
# load and iterate testing dataset
dirPath = os.path.join(Path(os.path.realpath("__file__")).parent.parent, "assets/data")
test_it = datagen.flow_from_directory(dirPath + "/test",
target_size = (224, 224),
color_mode = 'rgb',
class_mode = "categorical",
batch_size = 1)
model.evaluate(test_it, steps = test_it.samples/test_it.batch_size)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_jakarta')
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor, backend_overview, backend_monitor
def bernstein_vazirani(s):
ls = len(s)
qc = QuantumCircuit(ls+1,ls)
qc.h(range(ls))
qc.x(ls)
qc.h(ls)
qc.barrier();
for ii, yesno in enumerate(reversed(s)): # the black box
if yesno == '1':
qc.cx(ii, ls);
qc.barrier();
qc.h(range(ls));
qc.barrier();
qc.measure(range(ls),range(ls))
return qc
s = '011' # secretnumber
qc = bernstein_vazirani(s)
qc.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
jobE = execute(qc, backend = device, shots = nshots)
job_monitor(jobE)
jobS = execute(qc, backend = simulator, shots = nshots)
plot_histogram([jobS.result().get_counts(0), jobE.result().get_counts(0)],
bar_labels = False, legend = ['sim', 'exp'])
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# Install the plugin
# !pip install -e .
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import random_clifford
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.synthesis import AICliffordSynthesis
from qiskit_transpiler_service.ai.collection import CollectCliffords
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
coupling_map = QiskitRuntimeService().backend("ibm_cairo").coupling_map
circuit = QuantumCircuit(27)
for c in range(3):
nq = 8
qs = np.random.choice(range(circuit.num_qubits), size=nq, replace=False)
circuit.compose(random_clifford(nq).to_circuit(), qubits=qs.tolist(), inplace=True)
for q in qs:
circuit.t(q)
print(
f"Original circuit -> Depth: {circuit.decompose(reps=3).depth()}, Gates(2q): {circuit.decompose(reps=3).num_nonlocal_gates()}"
)
circuit.draw(output="mpl", fold=-1, scale=0.3, style="iqp")
qiskit_lvl3_transpiler = generate_preset_pass_manager(
optimization_level=3, coupling_map=coupling_map
)
lvl3_transpiled_circuit = qiskit_lvl3_transpiler.run(circuit)
print(
f"Qiskit lvl3 Transpiler -> Depth: {lvl3_transpiled_circuit.decompose(reps=3).depth()}, Gates(2q): {lvl3_transpiled_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
lvl3_transpiled_circuit.draw(output="mpl", fold=-1, scale=0.2, style="iqp")
ai_optimize_cliffords = PassManager(
[
CollectCliffords(),
AICliffordSynthesis(backend_name="ibm_canberra"),
]
)
# AI Synthesis passes respect the coupling map and should run after transpiling
ai_optimized_circuit = ai_optimize_cliffords.run(lvl3_transpiled_circuit)
print(
f"AI-Optimized circuit -> Depth: {ai_optimized_circuit.decompose(reps=3).depth()}, Gates(2q): {ai_optimized_circuit.decompose(reps=3).num_nonlocal_gates()}"
)
ai_optimized_circuit.draw(output="mpl", fold=-1, scale=0.25, style="iqp")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.visualization import plot_error_map
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
plot_error_map(backend)
|
https://github.com/BoxiLi/qiskit-CR-calibration
|
BoxiLi
|
"""
Generation and calibration of CR pulse.
"""
import os
import warnings
import multiprocessing as mpl
from multiprocessing import Pool
from functools import partial
from copy import deepcopy
import numpy as np
from numpy import pi
try:
import jax
import jax.numpy as jnp
except:
warnings("JAX not install, multi-derivative pulse doesn't work.")
os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
os.environ["JAX_PLATFORM_NAME"] = "cpu"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
import scipy
from scipy.signal import find_peaks
from scipy.optimize import curve_fit
import symengine as sym
import matplotlib.pyplot as plt
from qiskit import pulse, circuit, schedule, transpile
from qiskit.circuit import QuantumCircuit
from qiskit.pulse.library import (
Gaussian,
GaussianSquare,
GaussianSquareDrag,
SymbolicPulse,
Waveform,
)
from qiskit.pulse import Play, ShiftPhase, DriveChannel, ScheduleBlock
from ._custom_jax import _value_and_jacfwd
from .job_util import (
amp_to_omega_GHz,
omega_GHz_to_amp,
load_job_data,
save_job_data,
async_execute,
read_calibration_data,
save_calibration_data,
)
# Logger setup after importing logging
import logging
logger = logging.getLogger(__name__)
# %% Compute the DRAG pulse shape using JAX
def _complex_square_root(x):
"""
Calculate the complex square root of a given complex number.
Parameters:
- x (complex): The input complex number.
Returns:
- complex: The complex square root of the input.
"""
a = jnp.real(x)
b = jnp.imag(x)
result = jnp.sign(a) * (
jnp.sqrt((jnp.abs(x) + a) / 2)
+ 1.0j * jnp.sign(b) * jnp.sqrt((jnp.abs(x) - a) / 2)
)
result = jnp.where(
jnp.abs(b / a) < 1.0e-3,
# Taylor expansion
jnp.sign(a)
* jnp.sqrt(jnp.abs(a))
* (1 + (1.0j * b / a) / 2 - (1.0j * b / a) ** 2 / 8),
result,
)
result = jnp.where(a == 0.0, 1.0j * b, result)
return result
def perturbative_pulse_transform_single_photon(pulse_fun, gap, scale=1.0):
"""
Add perturbative DRAG correction to a pulse based on the pulse function and energy gap.
Parameters:
- pulse_fun (callable): The original pulse function.
- gap (float): The gap parameter for the transformation.
- scale (float, optional): Scaling factor for the transformation. Default is 1.
Returns:
- callable: Transformed pulse function.
"""
def new_pulse_fun(t, params):
pulse, dt_pulse = _value_and_jacfwd(pulse_fun)(t, params)
return pulse - 1.0j * dt_pulse / gap * scale
return new_pulse_fun
def perturbative_pulse_transform_two_photon(pulse_fun, gap, gaps):
"""
Add perturbative DRAG correction to a two-photon transition based on the pulse function and energy gaps.
Parameters:
- pulse_fun (callable): The original pulse function.
- gap (float): The common gap parameter for the transformation.
- gaps (tuple): Tuple containing two gap parameters (gap01, gap12).
Returns:
- callable: Transformed pulse function.
"""
def new_pulse_fun(t, params):
pulse, dt_pulse = _value_and_jacfwd(pulse_fun)(t, params)
return _complex_square_root(pulse**2 - 2 * 1.0j * pulse * dt_pulse / gap)
return new_pulse_fun
def exact_pulse_transform_single_photon(pulse_fun, gap, ratio=1, scale=1.0):
"""
Apply an exact DRAG correction using Givens rotation to a pulse. It only works for single-photon transitions.
Parameters:
- pulse_fun (callable): The original pulse function.
- gap (float): The gap parameter for the transformation.
- ratio (float, optional): Ratio parameter. Default is 1.
- scale (float, optional): Scaling factor for the transformation. Default is 1.
Returns:
- callable: Transformed pulse function.
"""
def new_pulse_fun(t, params):
pulse = pulse_fun(t, params)
phase = jnp.where(pulse != 0.0, jnp.exp(1.0j * jnp.angle(pulse)), 0.0)
def renorm_pulse_fun(t, params):
pulse = pulse_fun(t, params)
angle = jnp.angle(pulse)
theta2 = jnp.arctan(
-ratio * (params["omega"] / 2) * jnp.abs(pulse) / (gap / 2)
)
return theta2, angle
(theta2, angle), (dt_theta2, dt_angle) = _value_and_jacfwd(renorm_pulse_fun)(
t, params
)
dt_angle = jnp.where(pulse != 0.0, dt_angle, 0.0)
angle = jnp.where(pulse != 0.0, angle, 0.0)
new_g = phase * (-(gap + dt_angle) * jnp.tan(theta2) + scale * 1.0j * dt_theta2)
return jnp.where(
params["omega"] == 0.0,
0.0,
new_g / (ratio * (params["omega"])),
)
return new_pulse_fun
def pulse_shape(t, params):
"""
Define a pulse shape function based on the specified parameters.
Parameters:
- t (float): Time parameter.
- params (dict): Dictionary containing pulse parameters.
Returns:
- float: Value of the pulse function at the given time.
"""
def pulse_fun(t, params):
order = params["order"]
if order == "2":
fun = (
lambda t, params: t / params["t_r"]
- (jnp.cos(t * pi / params["t_r"]) * jnp.sin(t * pi / params["t_r"]))
/ pi
)
elif order == "1":
fun = lambda t, params: jnp.sin(jnp.pi / 2 / params["t_r"] * t) ** 2
elif order == "3":
t_r = params["t_r"]
fun = (
lambda t, params: (jnp.cos(3 * pi * t / t_r)) / 16
- (9 / 16) * jnp.cos(pi * t / t_r)
+ 1 / 2
)
else:
raise ValueError("Pulse shape order not defined.")
if "t_r" in params:
t_r = params["t_r"]
t_tol = params["t_tol"]
max_value = fun(params["t_r"], params)
pulse = max_value
pulse = jnp.where(t < t_r, fun(t, params), pulse)
pulse = jnp.where(t > t_tol - t_r, fun(t_tol - t, params), pulse)
return pulse
else:
raise NotImplementedError
if "drag_scale" not in params or params["drag_scale"] is None:
drag_scale = jnp.ones(3)
else:
drag_scale = jnp.array(params["drag_scale"])
if "no_drag" in params:
return pulse_fun(t, params)
detuning = params["Delta"]
gap02 = 2 * detuning + params["a1"]
gap12 = detuning + params["a1"]
gap01 = detuning
if "01" in params:
# Only single-derivative DRAG with gap for level 0 and 1. Use beta from the input parameters as a scaling factor for the DRAG coefficient.
pulse_fun = perturbative_pulse_transform_single_photon(
pulse_fun, gap01, scale=params.get("beta", 0.0)
)
elif "01_scale" in params:
# Only single-derivative DRAG with gap for level 0 and 1.
pulse_fun = perturbative_pulse_transform_single_photon(
pulse_fun, gap01, scale=drag_scale[0]
)
elif "12" in params:
# Only single-derivative DRAG with gap for level 1 and 2.
pulse_fun = perturbative_pulse_transform_single_photon(pulse_fun, gap12)
elif "02" in params:
# Only single-derivative DRAG with gap for level 0 and 2.
pulse_fun = perturbative_pulse_transform_two_photon(
pulse_fun, gap02, (gap01, gap12)
)
elif "exact" in params:
# Full correction with Givens rotatino for the two single-photon transitions and the perturbative DRAG correction for the two-photon process.
pulse_fun = perturbative_pulse_transform_two_photon(
pulse_fun, gap02 / params["drag_scale"][2], (gap01, gap12)
)
pulse_fun = exact_pulse_transform_single_photon(
pulse_fun, gap01 / params["drag_scale"][0], ratio=1
)
pulse_fun = exact_pulse_transform_single_photon(
pulse_fun,
gap12 / params["drag_scale"][1],
ratio=jnp.sqrt(2),
# *(1 - gap12/gap01)
)
elif "sw" in params:
# Full correction for all the three transitions, only use perturabtive DRAG correction.
pulse_fun = perturbative_pulse_transform_two_photon(
pulse_fun, gap02 / drag_scale[2], (gap01, gap12)
)
pulse_fun = perturbative_pulse_transform_single_photon(
pulse_fun, gap01 / drag_scale[0]
)
pulse_fun = perturbative_pulse_transform_single_photon(
pulse_fun,
gap12 / drag_scale[1],
)
else:
raise ValueError("Unknown DRAG type.")
final_pulse = pulse_fun(t, params)
return final_pulse
# %% Build CR tomography circuit and send jobs
def get_default_cr_params(backend, qc, qt):
"""
Get the default parameters for the echoed CNOT gate from Qiskit.
Parameters:
- backend (qiskit.providers.backend.Backend): The Qiskit backend.
- qc (int): Control qubit index.
- qt (int): Target qubit index.
Returns:
Tuple[Dict, Dict]: Tuple containing dictionaries of parameters for the echoed CNOT gate for control and target qubits.
"""
inst_sched_map = backend.instruction_schedule_map
def _filter_fun(instruction, pulse="ZX"):
if pulse == "ZX" and "CR90p_u" in instruction[1].pulse.name:
return True
elif pulse == "ZX" and "CX_u" in instruction[1].pulse.name:
return True
elif pulse == "IX" and "CR90p_d" in instruction[1].pulse.name:
return True
elif pulse == "IX" and "CX_d" in instruction[1].pulse.name:
return True
return False
def get_cx_gate_schedule(qc, qt):
from qiskit.pulse import PulseError
try:
return inst_sched_map.get("ecr", (qc, qt))
except PulseError:
return inst_sched_map.get("cx", (qc, qt))
gate_schedule = get_cx_gate_schedule(qc, qt)
cr_sched_default = gate_schedule.filter(instruction_types=[Play]).filter(
_filter_fun
)
cr_instruction = cr_sched_default.instructions[0][1]
cr_pulse = cr_instruction.pulse
ix_sched_default = gate_schedule.filter(instruction_types=[Play]).filter(
partial(_filter_fun, pulse="IX")
)
ix_instruction = ix_sched_default.instructions[0][1]
ix_channel = ix_instruction.channel
ix_pulse = ix_instruction.pulse
return cr_pulse.parameters, ix_pulse.parameters
def _get_modulated_symbolic_pulse(pulse_class, backend, params, frequency_offset):
"""
Add a detuning to the pulse by pulse shape modulation with exp(2*pi*I*delta*t).
Parameters:
- pulse_class (type): The class of the pulse.
- backend (qiskit.providers.backend.Backend): The Qiskit backend.
- params (dict): Pulse parameters.
- frequency_offset (float): Frequency offset for detuning.
Returns:
SymbolicPulse: Modulated symbolic pulse.
"""
default_pulse = pulse_class(**params)
pulse_parameters = default_pulse.parameters
pulse_parameters["delta"] = frequency_offset * backend.dt
_t, _delta = sym.symbols("t, delta")
my_pulse = SymbolicPulse(
pulse_type="GaussianModulated",
duration=default_pulse.duration,
parameters=pulse_parameters,
envelope=default_pulse.envelope * sym.exp(2 * sym.pi * sym.I * _delta * _t),
name="modulated Gaussian",
)
return my_pulse
def _add_symbolic_gaussian_pulse(pulse1, pulse2):
"""
Add two symbolic GaussianSquare pulses.
It is used in the target drive for the direct CNOT gate calibration to separate the parameter from the echoed CNOT gate.
Parameters:
- pulse1 (SymbolicPulse): First symbolic GaussianSquare pulse.
- pulse2 (SymbolicPulse): Second symbolic GaussianSquare pulse.
Returns:
SymbolicPulse: Resulting pulse after adding the two pulses.
"""
edited_params2 = {key + "_": value for key, value in pulse2.parameters.items()}
edited_pulse2_envelop = pulse2.envelope
for p_str in pulse2.parameters.keys():
old_p = sym.symbols(p_str)
new_p = sym.symbols(p_str + "_")
edited_pulse2_envelop = edited_pulse2_envelop.xreplace(old_p, new_p)
pulse_parameters = pulse1.parameters.copy()
pulse_parameters.update(edited_params2)
if pulse1.duration != pulse2.duration:
raise RuntimeError("Pulse duration must be the same.")
my_pulse = SymbolicPulse(
pulse_type="SumGaussian",
duration=pulse1.duration,
parameters=pulse_parameters,
envelope=pulse1.envelope + edited_pulse2_envelop,
name="added_pulse",
)
return my_pulse
def _add_waveform(waveform1, waveform2):
"""Add two qiskit waveform samplings.
Parameters:
- waveform1 (Waveform): First qiskit waveform.
- waveform2 (Waveform): Second qiskit waveform.
Returns:
Waveform: Resulting waveform after adding the two waveforms.
"""
if len(waveform1.samples) != len(waveform2.samples):
raise ValueError("The two waveforms do not have the same length.")
return Waveform(
samples=waveform1.samples + waveform2.samples,
name=waveform1.name,
)
def get_custom_pulse_shape(params, backend, control_qubit, frequency_offset=0.0):
"""Compute the custom sine-shaped pulse with DRAG correction for the custom CR gate. It is only possible to get the array sampling of the waveform, no symbolic expressions.
Parameters:
- params (dict): Dictionary containing parameters for pulse shape computation.
- backend: Qiskit backend.
- control_qubit: Index of the control qubit.
- frequency_offset (float, optional): Frequency offset. Default is 0.0.
Returns:
Waveform: Computed pulse shape with DRAG correction.
"""
def regulate_array_length(array):
result_array = np.zeros((len(array) // 16 + 1) * 16)
result_array[: len(array)] = array
return result_array
params = params.copy()
# Computation of the DRAG pulse needs the final time in ns, transfer "duration" to the final time "t_tol".
if "duration" in params:
params["t_tol"] = params["duration"] * backend.dt * 1.0e9
elif "t_tol" in params:
pass
else:
ValueError(
"The total time of the CR pulse t_tol is not defined in the parameter dictionary."
)
# If amp is given, comute the the drive strength in 2*pi*GHz
params["omega"] = 2 * pi * amp_to_omega_GHz(backend, control_qubit, params["amp"])
# Choose the DRAG type
if "drag_type" in params and params["drag_type"]:
params[params["drag_type"]] = True
else:
params["no_drag"] = True
del params["drag_type"]
# Generate time array
tlist = np.arange(0, params["t_tol"], backend.dt * 1.0e9)
tlist = regulate_array_length(tlist)
# Compute pulse shape with DRAG correction using JAX
pulse_shape_sample = params["amp"] * jax.vmap(pulse_shape, (0, None))(
tlist,
params,
)
del params["amp"]
# Conjugate the pulse shape array (because of the qiskit convention) and apply frequency offset
pulse_shape_sample = np.array(pulse_shape_sample).conjugate()
pulse_shape_sample = pulse_shape_sample * np.exp(
2
* np.pi
* 1.0j
* frequency_offset
* backend.dt
* np.arange(len(pulse_shape_sample))
)
pulse_shape_sample = pulse_shape_sample * np.exp(1.0j * params["angle"])
# Return the computed waveform
return Waveform(
samples=pulse_shape_sample,
name="CR drive",
)
def get_cr_schedule(qubits, backend, **kwargs):
"""
Generate the qiskit Schedule for CR pulse, including both the CR drive and the target.
Args:
qubits (Tuple): Tuple of control and target qubits.
backend (Backend): Qiskit backend.
**kwargs: Additional keyword arguments:
- cr_params (dict): Parameters for the CR pulse.
- ix_params (dict): Parameters for the IX pulse.
- x_gate_ix_params (dict, optional): Additional parameters for the X-gate on the target IX pulse. Default is None.
- frequency_offset (float, optional): Frequency offset in . Default is 0.0.
Returns:
Schedule: Qiskit Schedule for the CR pulse.
"""
cr_params = kwargs["cr_params"].copy()
ix_params = kwargs["ix_params"].copy()
frequency_offset = kwargs.get("frequency_offset", 0.0)
x_gate_ix_params = kwargs.get("x_gate_ix_params", None)
cr_params["risefall_sigma_ratio"] = 2.0
ix_params["risefall_sigma_ratio"] = 2.0
if x_gate_ix_params is not None:
x_gate_ix_params["risefall_sigma_ratio"] = 2.0
if "width" in cr_params:
del cr_params["width"]
if "width" in ix_params:
del ix_params["width"]
qc, qt = qubits
cr_schedule = pulse.Schedule()
control_channel = pulse.ControlChannel(qc)
target_channel = pulse.DriveChannel(qt)
if "beta" not in ix_params:
ix_params["beta"] = 0.0
# Generate CR pulse waveform
if "drag_type" in cr_params:
cr_pulse = get_custom_pulse_shape(
cr_params, backend, qc, frequency_offset=frequency_offset
)
else:
cr_pulse = _get_modulated_symbolic_pulse(
GaussianSquare, backend, cr_params, frequency_offset
)
if "drag_type" in ix_params:
ix_pulse = get_custom_pulse_shape(
ix_params, backend, qc, frequency_offset=frequency_offset
)
if x_gate_ix_params is not None:
x_gate_pulse = get_custom_pulse_shape(
x_gate_ix_params, backend, qc, frequency_offset
)
ix_pulse = _add_waveform(ix_pulse, x_gate_pulse)
else:
ix_pulse = _get_modulated_symbolic_pulse(
GaussianSquareDrag, backend, ix_params, frequency_offset
)
if x_gate_ix_params is not None:
x_gate_pulse = _get_modulated_symbolic_pulse(
GaussianSquare, backend, x_gate_ix_params, frequency_offset
)
ix_pulse = _add_symbolic_gaussian_pulse(ix_pulse, x_gate_pulse)
# Check if CR and IX pulse durations are equal
if cr_pulse.duration != ix_pulse.duration:
raise RuntimeError(
f"CR and IX pulse duration are not equal {cr_pulse.duration} and {ix_pulse.duration}."
)
cr_schedule.append(pulse.Play(cr_pulse, control_channel), inplace=True)
cr_schedule.append(pulse.Play(ix_pulse, target_channel), inplace=True)
tmp_circ = QuantumCircuit(backend.num_qubits)
if backend.name == "DynamicsBackend":
# pass
tmp_circ.rz(
+2 * pi * frequency_offset * backend.dt * ix_pulse.duration,
qt,
)
else:
tmp_circ.rz(
-2 * pi * frequency_offset * backend.dt * ix_pulse.duration,
qt,
)
cr_schedule.append(schedule(tmp_circ, backend=backend), inplace=True)
return cr_schedule
def _generate_indiviual_circuit(
duration,
qubits,
backend,
cr_params,
ix_params,
x_gate_ix_params,
frequency_offset,
control_states,
):
"""
Generate tomography circuits for a given CR pulse duration.
Args:
duration (float): Duration of the CR pulse.
qubits (Tuple): Tuple of control and target qubits.
backend (Backend): Qiskit backend.
cr_params (dict): Parameters for the CR pulse.
ix_params (dict): Parameters for the IX pulse.
x_gate_ix_params (dict): Parameters for the X-gate on the IX pulse.
frequency_offset (float): Frequency offset.
control_states (Tuple): Control states for the tomography circuits.
Returns:
List[QuantumCircuit]: List of generated tomography circuits.
"""
cr_gate = circuit.Gate("cr", num_qubits=2, params=[])
(qc, qt) = qubits
circ_list = []
cr_params["duration"] = int(duration)
ix_params["duration"] = int(duration)
if x_gate_ix_params is not None:
x_gate_ix_params["duration"] = int(duration)
# Get CR pulse schedule
cr_sched = get_cr_schedule(
(qc, qt),
backend,
cr_params=cr_params,
ix_params=ix_params,
x_gate_ix_params=x_gate_ix_params,
frequency_offset=frequency_offset,
)
for basis in ["X", "Y", "Z"]:
for control in control_states:
tomo_circ = circuit.QuantumCircuit(
backend.num_qubits, 2
) # use all qubits to avoid error
if control in (1, "1"):
tomo_circ.x(qc) # flip control from |0> to |1>
tomo_circ.append(cr_gate, [qc, qt])
tomo_circ.barrier(qc, qt)
if basis == "X":
tomo_circ.h(qt)
elif basis == "Y":
tomo_circ.sdg(qt)
tomo_circ.h(qt)
tomo_circ.measure(qc, 0)
tomo_circ.measure(qt, 1)
tomo_circ.add_calibration(gate=cr_gate, qubits=[qc, qt], schedule=cr_sched)
circ_list.append(tomo_circ)
return circ_list
def get_cr_tomo_circuits(
qubits,
backend,
cr_times,
cr_params,
ix_params,
x_gate_ix_params=None,
frequency_offset=0.0,
control_states=(0, 1),
):
"""
Build an array of cross resonance schedules for the Hamiltonian tomography experiment.
Args:
qubits (Tuple): Tuple of control and target qubits.
backend (Backend): Qiskit backend.
cr_times (List[int]): List of CR pulse durations.
cr_params (dict): Parameters for the CR pulse
ix_params (dict): Parameters for the IX pulse.
x_gate_ix_params (dict, optional): Parameters for the X-gate on the IX pulse. Default is None.
frequency_offset (float, optional): Frequency offset. Default is 0.0.
control_states (Tuple, optional): Control states for the tomography circuits. Default is (0, 1).
Returns:
List[QuantumCircuit]: List of generated tomography circuits.
"""
tomo_circs = []
cr_params = cr_params.copy()
ix_params = ix_params.copy()
if x_gate_ix_params is not None:
x_gate_ix_params = x_gate_ix_params.copy()
tomo_circs = []
tmp_fun = partial(
_generate_indiviual_circuit,
qubits=qubits,
backend=backend,
cr_params=cr_params,
ix_params=ix_params,
x_gate_ix_params=x_gate_ix_params,
frequency_offset=frequency_offset,
control_states=control_states,
)
# with mpl.Pool(10) as p:
# tomo_circs = p.map(tmp_fun, cr_times)
tomo_circs = map(tmp_fun, cr_times)
tomo_circs = sum(tomo_circs, [])
logger.info("Tomography circuits have been generated.")
return tomo_circs
def _send_decoy_cicuit(backend, session):
"""
Send a very simple decoy circuit to the backend to prevent idling.
Parameters:
- backend (Backend): Qiskit backend.
- session (Session): Qiskit session.
"""
qc = QuantumCircuit(1)
qc.x(0)
qc = transpile(
qc,
backend,
scheduling_method="asap",
optimization_level=1,
)
job = session.run(
"circuit-runner",
inputs={
"circuits": qc,
"skip_transpilation": True,
"shots": 10,
},
)
return job.job_id()
def send_cr_tomography_job(
qubits,
backend,
cr_params,
ix_params,
cr_times,
x_gate_ix_params=None,
blocking=False,
frequency_offset=0.0,
session=None,
shots=1024,
control_states=(0, 1),
decoy=False,
):
"""
Send the tomography job for CR pulse.
Parameters:
- qubits (Tuple): Tuple of control and target qubits.
- backend (Backend): Qiskit backend.
- cr_params (dict): Parameters for the CR pulse.
- ix_params (dict): Parameters for the IX pulse.
- cr_times (List[float]): List of widths of the CR pulses.
- x_gate_ix_params (dict, optional): Parameters for the X-gate IX pulse. Default is None.
- blocking (bool, optional): If True, block until the job is completed. Default is False.
- frequency_offset (float, optional): Frequency offset. Default is 0.0.
- ZI_correction (float, optional): ZI interaction rate correction. Default is 0.0.
- session (Session, optional): Qiskit session. Default is None.
- shots (int, optional): Number of shots. Default is 1024.
- control_states (Tuple, optional): Tuple of control states. Default is (0, 1).
- decoy (bool, optional): If True, send a decoy circuit to prevent idling. Default is True.
Returns:
str: Job ID.
"""
# Create circuits
cr_tomo_circ_list = get_cr_tomo_circuits(
qubits,
backend,
cr_times,
cr_params=cr_params,
ix_params=ix_params,
x_gate_ix_params=x_gate_ix_params,
frequency_offset=frequency_offset,
control_states=control_states,
)
if decoy:
_send_decoy_cicuit(backend, session)
transpiled_tomo_circ_list = transpile(
cr_tomo_circ_list,
backend,
# scheduling_method="asap",
optimization_level=1,
)
# Send jobs
if session is not None:
job = session.run(
"circuit-runner",
inputs={
"circuits": transpiled_tomo_circ_list,
"skip_transpilation": True,
"shots": shots,
},
)
else:
job = backend.run(transpiled_tomo_circ_list, shots=shots)
tag = "CR tomography"
# job.update_tags([tag]) # qiskit-ibm-runtime does not support yet update_tags, will support soon.
parameters = {
"backend": backend.name,
"qubits": qubits,
"cr_times": cr_times,
"shots": shots,
"cr_params": cr_params,
"ix_params": ix_params,
"x_gate_ix_params": x_gate_ix_params,
"frequency_offset": frequency_offset,
"dt": backend.dt,
}
logger.info(
tag
+ ": "
+ job.job_id()
+ "\n"
+ "\n".join([f"{key}: {val}" for key, val in parameters.items()])
+ "\n"
)
if blocking:
save_job_data(job, backend=backend, parameters=parameters)
else:
async_execute(save_job_data, job, backend=backend, parameters=parameters)
return job.job_id()
def shifted_parameter_cr_job(
qubits,
backend,
cr_params,
ix_params,
cr_times,
prob_ix_strength,
x_gate_ix_params=None,
frequency_offset=0.0,
shots=1024,
blocking=False,
session=None,
control_states=(0, 1),
mode="CR",
):
"""
Send the tomography job for CR pulse with a shifted amplitude on the target drive.
Parameters:
- qubits (Tuple): Tuple of control and target qubits.
- backend (Backend): Qiskit backend.
- cr_params (dict): Parameters for the CR pulse.
- ix_params (dict): Parameters for the IX pulse.
- cr_times (List[float]): List of widths of the CR pulses.
- prob_ix_strength (float): Strength of the probability amplitude shift.
- x_gate_ix_params (dict, optional): Parameters for the X-gate IX pulse. Default is None.
- frequency_offset (float, optional): Frequency offset. Default is 0.0.
- shots (int, optional): Number of shots. Default is 1024.
- blocking (bool, optional): If True, block until the job is completed. Default is False.
- session (Session, optional): Qiskit session. Default is None.
- control_states (Tuple, optional): Tuple of control states. Default is (0, 1).
- mode (str, optional): Operation mode ("CR" or "IX"). Default is "CR".
Returns:
str: Job ID.
"""
if mode == "CR":
ix_params = ix_params.copy()
ix_params["amp"] += prob_ix_strength
else:
x_gate_ix_params = x_gate_ix_params.copy()
x_gate_ix_params["amp"] += prob_ix_strength
tomo_id = send_cr_tomography_job(
qubits,
backend,
cr_params,
ix_params,
cr_times,
x_gate_ix_params,
blocking=blocking,
session=session,
frequency_offset=frequency_offset,
shots=shots,
control_states=control_states,
)
return tomo_id
# %% Analyze CR tomography data
# Part of the following code is from https://github.com/Qiskit/textbook/blob/main/notebooks/quantum-hardware-pulses/hamiltonian-tomography.ipynb
def _get_omega(eDelta, eOmega_x, eOmega_y):
r"""Return \Omega from parameter arguments."""
eOmega = np.sqrt(eDelta**2 + eOmega_x**2 + eOmega_y**2)
return eOmega
def _avg_X(t, eDelta, eOmega_x, eOmega_y, eOmega, t0, normalize=True):
"""Return average X Pauli measurement vs time t"""
if normalize:
eOmega = _get_omega(eDelta, eOmega_x, eOmega_y)
eXt = (
-eDelta * eOmega_x
+ eDelta * eOmega_x * np.cos(eOmega * t + t0)
+ eOmega * eOmega_y * np.sin(eOmega * t + t0)
) / eOmega**2
return eXt
def _avg_Y(t, eDelta, eOmega_x, eOmega_y, eOmega, t0, normalize=True):
"""Return average Y Pauli measurement vs time t"""
if normalize:
eOmega = _get_omega(eDelta, eOmega_x, eOmega_y)
eYt = (
eDelta * eOmega_y
- eDelta * eOmega_y * np.cos(eOmega * t + t0)
- eOmega * eOmega_x * np.sin(eOmega * t + t0)
) / eOmega**2
return eYt
def _avg_Z(t, eDelta, eOmega_x, eOmega_y, eOmega, t0, normalize=True):
"""Return average Z Pauli measurement vs time t"""
if normalize:
eOmega = _get_omega(eDelta, eOmega_x, eOmega_y)
eZt = (
eDelta**2 + (eOmega_x**2 + eOmega_y**2) * np.cos(eOmega * t + t0)
) / eOmega**2
return eZt
def fit_evolution(tlist, eXt, eYt, eZt, p0, include, normalize):
"""
Use curve_fit to determine fit parameters of X,Y,Z Pauli measurements together.
Parameters:
- tlist (array-like): Time values for the measurements.
- eXt (array-like): X Pauli measurements.
- eYt (array-like): Y Pauli measurements.
- eZt (array-like): Z Pauli measurements.
- p0 (array-like): Initial guess for fit parameters.
- include (array-like): Boolean array specifying which Pauli measurements to include in the fit.
- normalize (bool): Whether to normalize the measurements.
Returns:
Tuple[array-like, array-like]: Fit parameters and covariance matrix.
"""
def fun(tlist, eDelta, eOmega_x, eOmega_y, eOmega, t0):
"""Stack average X,Y,Z Pauli measurements vertically."""
result = np.vstack(
[
_avg_X(
tlist, eDelta, eOmega_x, eOmega_y, eOmega, t0, normalize=normalize
),
_avg_Y(
tlist, eDelta, eOmega_x, eOmega_y, eOmega, t0, normalize=normalize
),
_avg_Z(
tlist, eDelta, eOmega_x, eOmega_y, eOmega, t0, normalize=normalize
),
]
)[include].flatten()
return result
data = np.asarray(
[
eXt,
eYt,
eZt,
]
)[include].flatten()
params, cov = curve_fit(fun, tlist, data, p0=p0, method="trf")
return params, cov
def fit_rt_evol(tlist, eXt, eYt, eZt, p0, include, normalize):
"""
Use curve_fit to determine fit parameters of X,Y,Z Pauli measurements together.
Parameters:
- tlist (array-like): Time values for the measurements.
- eXt (array-like): X Pauli measurements.
- eYt (array-like): Y Pauli measurements.
- eZt (array-like): Z Pauli measurements.
- p0 (array-like): Initial guess for fit parameters.
- include (array-like): Boolean array specifying which Pauli measurements to include in the fit.
- normalize (bool): Whether to normalize the measurements.
Returns:
Tuple[array-like, array-like]: Fit parameters and covariance matrix.
"""
def fun(tlist, eDelta, eOmega_x, eOmega_y, eOmega, t0):
"""
Stack average X,Y,Z Pauli measurements vertically.
"""
result = np.vstack(
[
_avg_X(
tlist, eDelta, eOmega_x, eOmega_y, eOmega, t0, normalize=normalize
),
_avg_Y(
tlist, eDelta, eOmega_x, eOmega_y, eOmega, t0, normalize=normalize
),
_avg_Z(
tlist, eDelta, eOmega_x, eOmega_y, eOmega, t0, normalize=normalize
),
]
)[include].flatten()
return result
data = np.asarray(
[
eXt,
eYt,
eZt,
]
)[include].flatten()
params, cov = curve_fit(fun, tlist, data, p0=p0, method="trf")
return params, cov
def recursive_fit(tlist, eXt, eYt, eZt, p0):
"""
Perform recursive fitting of X, Y, Z Pauli expectation values.
Parameters:
- tlist (array-like): Time values for the measurements.
- eXt (array-like): X Pauli expectation values.
- eYt (array-like): Y Pauli expectation values.
- eZt (array-like): Z Pauli expectation values.
- p0 (array-like): Initial guess for fit parameters.
Returns:
Tuple[array-like, array-like]: Fit parameters and covariance matrix.
"""
params = p0.copy()
# First fit with Z measurement only, no normalization
include = np.array([False, False, True])
params, cov = fit_evolution(tlist, eXt, eYt, eZt, params, include, normalize=False)
# Second fit with Z measurement only, normalization applied
include = np.array([False, False, True])
params, cov = fit_evolution(tlist, eXt, eYt, eZt, params, include, normalize=True)
# Third fit with Y and Z measurements, no normalization
include = np.array([False, True, True])
params, cov = fit_evolution(tlist, eXt, eYt, eZt, params, include, normalize=False)
# Fourth fit with X, Y, and Z measurements, no normalization
include = np.array([True, True, True])
params, cov = fit_evolution(tlist, eXt, eYt, eZt, params, include, normalize=False)
# Fifth fit with X, Y, and Z measurements, normalization applied
include = np.array([True, True, True])
params, cov = fit_evolution(tlist, eXt, eYt, eZt, params, include, normalize=True)
return params, cov
def get_interation_rates_MHz(ground_params, excited_params, ground_cov, excited_cov):
"""
Determine two-qubits interaction rates from fits to ground and excited control qubit data.
Parameters:
- ground_params (array-like): Fit parameters for the ground state.
- excited_params (array-like): Fit parameters for the excited state.
- ground_cov (array-like): Covariance matrix for the ground state fit.
- excited_cov (array-like): Covariance matrix for the excited state fit.
Returns:
Tuple[array-like, array-like]: Interaction rates and their standard deviations.
"""
Delta0, Omega0_x, Omega0_y = ground_params[:3]
Delta1, Omega1_x, Omega1_y = excited_params[:3]
Delta0_var, Omega0_x_var, Omega0_y_var = np.diag(ground_cov)[:3]
Delta1_var, Omega1_x_var, Omega1_y_var = np.diag(excited_cov)[:3]
# Interaction rates
IX = 0.5 * (Omega0_x + Omega1_x) / 2 / pi
IY = 0.5 * (Omega0_y + Omega1_y) / 2 / pi
IZ = 0.5 * (Delta0 + Delta1) / 2 / pi
ZX = 0.5 * (Omega0_x - Omega1_x) / 2 / pi
ZY = 0.5 * (Omega0_y - Omega1_y) / 2 / pi
ZZ = 0.5 * (Delta0 - Delta1) / 2 / pi
# Standard deviations
IX_std = 0.5 * (Omega0_x_var + Omega1_x_var) ** 0.5 / 2 / pi
IY_std = 0.5 * (Omega0_y_var + Omega1_y_var) ** 0.5 / 2 / pi
IZ_std = 0.5 * (Delta0_var + Delta1_var) ** 0.5 / 2 / pi
ZX_std = 0.5 * (Omega0_x_var + Omega1_x_var) ** 0.5 / 2 / pi
ZY_std = 0.5 * (Omega0_y_var + Omega1_y_var) ** 0.5 / 2 / pi
ZZ_std = 0.5 * (Delta0_var + Delta1_var) ** 0.5 / 2 / pi
return [[IX, IY, IZ], [ZX, ZY, ZZ]], [
[IX_std, IY_std, IZ_std],
[ZX_std, ZY_std, ZZ_std],
]
def _estimate_period(data, cr_times):
"""
Estimate the period of the oscillatory data using peak finding.
Parameters:
- data (array-like): Oscillatory data.
- cr_times (array-like): Corresponding time values.
Returns:
float: Estimated period of the oscillatory data.
"""
peaks_high, properties = scipy.signal.find_peaks(data, prominence=0.5)
peaks_low, properties = scipy.signal.find_peaks(-data, prominence=0.5)
peaks = sorted(np.concatenate([peaks_low, peaks_high]))
if len(peaks) <= 2:
return cr_times[-1] - cr_times[0]
return 2 * np.mean(np.diff(cr_times[peaks]))
def _get_normalized_cr_tomography_data(job_id):
"""Retrieve and normalize CR tomography data from a job. Renormalize the data to (-1, 1).
Args:
job_id (str): The ID of the job containing CR tomography data.
Returns:
Tuple[array-like, array-like]: A tuple containing the CR times and normalized tomography data.
"""
data = load_job_data(job_id)
result = data["result"]
dt = data["parameters"]["dt"]
cr_times = data["parameters"]["cr_times"]
shots = data["parameters"]["shots"]
# IBM classified data
# Trace out the control, notice that IBM uses reverse qubit indices labeling.
target_data = (
np.array(
[
(result.get_counts(i).get("00", 0) + result.get_counts(i).get("01", 0))
for i in range(len(result.results))
]
)
/ shots
)
if 6 * len(cr_times) == len(target_data):
# two-qubit tomography, with control on 0 and 1
splitted_data = target_data.reshape((len(cr_times), 6)).transpose()
elif 3 * len(cr_times) == len(target_data):
# single tomography
splitted_data = target_data.reshape((len(cr_times), 3)).transpose()
else:
ValueError(
"The number of data points does not match the number of tomography settings."
)
splitted_data = splitted_data * 2 - 1
scale = np.max(splitted_data) - np.min(splitted_data)
average = (np.max(splitted_data) + np.min(splitted_data)) / 2
splitted_data = 2 * (splitted_data - average) / scale
return cr_times, splitted_data, dt
def process_single_qubit_tomo_data(job_id, show_plot=False):
"""Process and analyze single qubit tomography data from a job.
Args:
job_id (str): The ID of the job containing single qubit tomography data.
show_plot (bool, optional): Whether to generate and display plots. Default is False.
Returns:
dict: Dictionary containing the processed results including <X>, <Y>, and <Z>.
Note:
Noticed that the measured value is not the IX, IY, IZ in the sense of CR, but the single qubit dynamics when the control qubit is in |0> or |1>.
"""
cr_times, splitted_data, dt = _get_normalized_cr_tomography_data(job_id)
signal_x, signal_y, signal_z = splitted_data
period = _estimate_period(signal_z, cr_times)
cutoff = -1
params, cov = recursive_fit(
cr_times[:cutoff] * dt * 1.0e6,
signal_x[:cutoff],
signal_y[:cutoff],
signal_z[:cutoff],
p0=np.array([1, 1, 1, 1 / (period * dt * 1.0e6) * 2 * pi, 0.0]),
)
if show_plot:
plot_cr_ham_tomo(
cr_times * dt * 1.0e6,
splitted_data,
ground_params=params,
ground_cov=cov,
)
plt.show()
return {
"IX": params[1] / 2 / pi,
"IY": params[2] / 2 / pi,
"IZ": params[0] / 2 / pi,
}
## TODO remove dt in the signiture.
def process_zx_tomo_data(job_id, show_plot=False):
"""Process and analyze ZX tomography data from a job.
Args:
job_id (str): The ID of the job containing ZX tomography data.
show_plot (bool, optional): Whether to generate and display plots. Default is False.
Returns:
dict: Dictionary containing the processed results including IX, IY, IZ, ZX, ZY, and ZZ.
Note:
The effective coupling strength is in the unit of MHz.
"""
cr_times, splitted_data, dt = _get_normalized_cr_tomography_data(job_id)
signal_x = splitted_data[:2]
signal_y = splitted_data[2:4]
signal_z = splitted_data[4:6]
period0 = _estimate_period(signal_z[0], cr_times)
period1 = _estimate_period(signal_z[1], cr_times)
cutoff = -1
_i = 0
while True:
try:
ground_params, ground_cov = recursive_fit(
cr_times[:cutoff] * dt * 1.0e6,
signal_x[0][:cutoff],
signal_y[0][:cutoff],
signal_z[0][:cutoff],
p0=np.array([1, 1, 1, 1 / (period0 * dt * 1.0e6) * 2 * pi, 0.0]),
)
break
except RuntimeError as e:
_i += 1
period0 *= 2
if _i > 16:
raise e
excited_params, excited_cov = recursive_fit(
cr_times[:cutoff] * dt * 1.0e6,
signal_x[1][:cutoff],
signal_y[1][:cutoff],
signal_z[1][:cutoff],
p0=np.array([1, 1, 1, 1 / (period1 * dt * 1.0e6) * 2 * pi, 0.0]),
)
# ground_params, ground_cov = excited_params, excited_cov
if show_plot:
plot_cr_ham_tomo(
cr_times * dt * 1.0e6,
splitted_data,
ground_params,
excited_params,
ground_cov,
excited_cov,
)
plt.show()
[[IX, IY, IZ], [ZX, ZY, ZZ]] = get_interation_rates_MHz(
ground_params, excited_params, ground_cov, excited_cov
)[0]
return {"IX": IX, "IY": IY, "IZ": IZ, "ZX": ZX, "ZY": ZY, "ZZ": ZZ}
def plot_cr_ham_tomo(
cr_times,
tomography_data,
ground_params,
excited_params=None,
ground_cov=None,
excited_cov=None,
):
"""Plot Hamiltonian tomography data and curve fits with interaction rates.
Args:
cr_times (np.ndarray): Array of CR times.
tomography_data (np.ndarray): Averaged tomography data.
ground_params (np.ndarray): Parameters of the ground fit.
excited_params (np.ndarray, optional): Parameters of the excited fit. Default is None.
ground_cov (np.ndarray, optional): Covariance matrix of the ground fit. Default is None.
excited_cov (np.ndarray, optional): Covariance matrix of the excited fit. Default is None.
"""
colors = ["tab:blue", "tab:red"]
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(4, 4), sharey=True)
is_single_qubit_tomo = excited_params is None
if not is_single_qubit_tomo:
ground_avg = tomography_data[0::2, :]
excited_avg = tomography_data[1::2, :]
else:
ground_avg = tomography_data
# Scatter plot and curve for X(t)
ax1.scatter(
cr_times,
ground_avg[0, :],
lw=0.3,
color=colors[0],
label=r"control in $|0\rangle$" if not is_single_qubit_tomo else None,
)
ax1.plot(cr_times, _avg_X(cr_times, *ground_params), lw=2.0, color=colors[0])
ax1.set_ylabel(r"$\langle X(t) \rangle$", fontsize="small")
ax1.set_xticklabels([])
ax1.set_yticks([])
# Scatter plot and curve for Y(t)
ax2.scatter(
cr_times, ground_avg[1, :], lw=0.3, color=colors[0], label="control in |0>"
)
ax2.plot(cr_times, _avg_Y(cr_times, *ground_params), lw=2.0, color=colors[0])
ax2.set_ylabel(r"$\langle Y(t) \rangle$", fontsize="small")
ax2.set_xticklabels([])
# Scatter plot and curve for Z(t)
ax3.scatter(
cr_times,
ground_avg[2, :],
lw=0.3,
color=colors[0],
label=r"control in $|0\rangle$",
)
ax3.plot(cr_times, _avg_Z(cr_times, *ground_params), lw=2.0, color=colors[0])
ax3.set_ylabel(r"$\langle Z(t) \rangle$", fontsize="small")
ax3.set_yticklabels([])
ax3.set_xlabel(r"Time $(\mu s)$", fontsize="small")
if not is_single_qubit_tomo:
ax1.scatter(
cr_times,
excited_avg[0, :],
lw=0.3,
color=colors[1],
label=r"control in $|1\rangle$",
)
ax1.plot(cr_times, _avg_X(cr_times, *excited_params), lw=2.0, color=colors[1])
ax1.legend(loc=4, fontsize="x-small")
ax2.scatter(
cr_times,
excited_avg[1, :],
lw=0.3,
color=colors[1],
label=r"control in $|1\rangle$",
)
ax2.plot(cr_times, _avg_Y(cr_times, *excited_params), lw=2.0, color=colors[1])
ax3.scatter(
cr_times,
excited_avg[2, :],
lw=0.3,
color=colors[1],
label=r"control in $|1\rangle$",
)
ax3.plot(cr_times, _avg_Z(cr_times, *excited_params), lw=2.0, color=colors[1])
if not is_single_qubit_tomo:
coeffs, errors = get_interation_rates_MHz(
ground_params, excited_params, ground_cov, excited_cov
)
ax3.text(
cr_times[-1] / 2,
-2.55,
"ZX = %.3f (%2.f) MHz ZY = %.3f (%2.f) MHz ZZ = %.3f (%2.f) MHz"
% (
coeffs[1][0],
errors[1][0] * 1000,
coeffs[1][1],
errors[1][1] * 1000,
coeffs[1][2],
errors[1][2] * 1000,
),
fontsize="x-small",
horizontalalignment="center",
)
ax3.text(
cr_times[-1] / 2,
-2.9,
"IX = %.3f (%2.f) MHz IY = %.3f (%2.f) MHz IZ = %.3f (%2.f) MHz"
% (
coeffs[0][0],
errors[0][0] * 1000,
coeffs[0][1],
errors[0][1] * 1000,
coeffs[0][2],
errors[0][2] * 1000,
),
fontsize="x-small",
horizontalalignment="center",
)
else:
coeffs = ground_params / 2 / pi
errors = np.diagonal(ground_cov) ** 0.5 / 2 / pi
ax3.text(
cr_times[-1] / 2,
-2.55,
"X = %.3f (%2.f) MHz Y = %.3f (%2.f) MHz Z = %.3f (%2.f) MHz"
% (
coeffs[1],
errors[1] * 1000,
coeffs[2],
errors[2] * 1000,
coeffs[0],
errors[0] * 1000,
),
fontsize="x-small",
horizontalalignment="center",
)
# %% Iterative calibration
def _compute_drive_scale(
coeff_dict_1, coeff_dict_2, ix_params, prob_ix_strength, conjugate_pulse
):
vau1 = coeff_dict_1["IX"] + 1.0j * coeff_dict_1["IY"]
vau2 = coeff_dict_2["IX"] + 1.0j * coeff_dict_2["IY"]
A1 = ix_params["amp"] * np.exp(1.0j * ix_params["angle"])
A2 = (ix_params["amp"] + prob_ix_strength) * np.exp(1.0j * ix_params["angle"])
if conjugate_pulse:
return (vau2 - vau1) / np.conjugate(A2 - A1)
else:
return (vau2 - vau1) / (A2 - A1)
def _angle(c):
"""
User arctan to calculate the angle such that -1 won't be transfered to the angle parameters, in this way, a negative ZX will remains the same, not transfered to a positive ZX.
The output range is (-pi/2, pi/2)
"""
if c.real == 0.0:
return np.pi / 2
return np.arctan(c.imag / c.real)
def update_pulse_params(
coeff_dict_1,
coeff_dict_2,
cr_params,
ix_params,
prob_ix_strength,
target_IX_strength=None,
backend_name=None,
real_only=False,
):
"""
Update pulse parameters for CR and IX gates based on tomography results. Refer to arxiv 2303.01427 for the derivation.
Args:
coeff_dict_1 (dict): Coefficients from the first tomography job.
coeff_dict_2 (dict): Coefficients from the second tomography job.
cr_params (dict): Parameters for the CR gate pulse.
ix_params (dict): Parameters for the IX gate pulse.
prob_ix_strength (float): The strength of the IX gate pulse.
target_IX_strength (float, optional): Target angle for IX gate. Default is 0.
backend_name (str):
real_only: Update only the real part of the drive.
Returns:
tuple: Updated CR parameters, Updated IX parameters, None (for compatibility with CR-only calibration).
"""
cr_params = cr_params.copy()
ix_params = ix_params.copy()
if backend_name == "DynamicsBackend":
sign = -1 # dynamics end has a different convension
else:
sign = 1
if "ZX" in coeff_dict_1:
phi0 = _angle(coeff_dict_1["ZX"] + 1.0j * coeff_dict_1["ZY"])
else:
# No CR tomography, only single target qubit tomography.
phi0 = 0.0
cr_params["angle"] -= sign * phi0
drive_scale = _compute_drive_scale(
coeff_dict_1, coeff_dict_2, ix_params, prob_ix_strength, backend_name
)
logger.info(
"Estimated drive scale: \n"
f"{drive_scale/1000}" + "\n"
f"{drive_scale/np.exp(1.j*_angle(drive_scale))/1000}" + "\n"
f"{_angle(drive_scale)}"
)
# Update the IX drive strength and phase
vau1 = coeff_dict_1["IX"] + 1.0j * coeff_dict_1["IY"]
A1 = ix_params["amp"] * np.exp(sign * 1.0j * ix_params["angle"])
new_drive = (target_IX_strength - vau1) / drive_scale + A1
if real_only:
ix_params["amp"] = np.real(new_drive)
else:
new_angle = _angle(new_drive)
ix_params["amp"] = np.real(new_drive / np.exp(1.0j * new_angle))
ix_params["angle"] = sign * (new_angle - phi0)
if "ZX" in coeff_dict_1:
return (
cr_params,
ix_params,
None,
np.real(drive_scale / np.exp(1.0j * _angle(drive_scale)) / 1000),
)
else:
return (
cr_params,
None,
ix_params,
np.real(drive_scale / np.exp(1.0j * _angle(drive_scale)) / 1000),
)
def _update_frequency_offset(old_calibration_data, mode, backend_name):
"""
This should not be used separatly because applying more than once will lead to the wrong offset.
"""
new_calibration_data = deepcopy(old_calibration_data)
if mode == "CR":
coeffs_dict = old_calibration_data["coeffs"]
frequency_offset_key = "frequency_offset"
else:
coeffs_dict = old_calibration_data["x_gate_coeffs"]
frequency_offset_key = "x_gate_frequency_offset"
if backend_name == "DynamicsBackend":
correction = coeffs_dict["IZ"] * 1.0e6
else:
correction = -0.5 * coeffs_dict["IZ"] * 1.0e6
new_calibration_data[frequency_offset_key] = (
old_calibration_data.get(frequency_offset_key, 0.0) + correction
)
if np.abs(coeffs_dict["IZ"]) > 2.0:
logger.warning(
"Frequency offset larger than 2MHz, update is not applied. Please check if the fit is accurate."
)
return old_calibration_data
logger.info(
f"Frequency offset is updated to {new_calibration_data[frequency_offset_key]} Hz"
)
return new_calibration_data
def iterative_cr_pulse_calibration(
qubits,
backend,
cr_times,
session,
gate_name,
initial_calibration_data=None,
verbose=False,
threshold_MHz=0.015,
restart=False,
rerun_last_calibration=True,
max_repeat=4,
shots=None,
mode="CR",
IX_ZX_ratio=None,
save_result=True,
control_states=None,
):
"""
Iteratively calibrates CR pulses on the given qubits to remove the IX, ZY, IY terms. The result is saved in the carlibtaion data file and can be accessed via `read_calibration_data`.
Args:
qubits (list): Qubits involved in the calibration.
backend: Quantum backend.
cr_times (list): CR gate times for tomography.
session: Qiskit runtime session.
gate_name (str): Name of the CR gate. This will be used to identify the calibration data when retrieving the information.
initial_calibration_data (dict, optional): Initial parameters for calibration.
verbose (bool, optional): Whether to display detailed logging information. Default is False.
threshold_MHz (float, optional): Error threshold for calibration. Default is 0.015 GHz.
restart (bool, optional): Whether to restart calibration from scratch. Default is False.
rerun_last_calibration (bool, optional): Whether to rerun the last calibration. Default is True.
max_repeat (int, optional): Maximum number of calibration repetitions. Default is 4.
shots (int, optional): Number of shots for each tomography job. Default is 1024.
mode (str, optional): Calibration mode, "CR" or "IX-pi". Default is "CR". The CR mode is used to measure the ZX and ZZ strength. It only updates the phase of CR drive and the IX drive but not IY. The "IX-pi" mode updates the target drive for a CNOT gate.
"""
if control_states is None:
if mode == "CR":
control_states = (0, 1)
elif mode == "IX-pi":
control_states = (1,)
else:
ValueError("Mode must be either 'CR' or 'IX-pi/2'.")
if not restart:
try: # Load existing calibration
logger.info("Loading existing calibration data...")
qubit_calibration_data = read_calibration_data(backend, gate_name, (qubits))
qubit_calibration_data = deepcopy(qubit_calibration_data)
if mode == "IX-pi":
qubit_calibration_data["x_gate_ix_params"]
except KeyError: #
restart = True # we need to overwrite rerun_last_calibration=True
logger.warning(
f"Failed to find the calibration data for the gate{backend.name, gate_name, (qubits)}. Restarting from scratch."
)
if restart:
if not rerun_last_calibration:
logger.warning(
f"Last calibration job for {gate_name} not found or not used. Starting from scratch."
)
rerun_last_calibration = True
if mode == "CR":
if initial_calibration_data is None:
raise ValueError(
"Starting calibration from scratch, but initial parameters are not provided."
)
if (
"cr_params" not in initial_calibration_data
or "ix_params" not in initial_calibration_data
):
raise ValueError(
"The initial pulse parameters for the CR and target drive must be provided."
)
qubit_calibration_data = initial_calibration_data
else:
logger.info("Loading existing calibration data...")
qubit_calibration_data = read_calibration_data(backend, gate_name, (qubits))
qubit_calibration_data = deepcopy(qubit_calibration_data)
qubit_calibration_data["x_gate_ix_params"] = qubit_calibration_data[
"ix_params"
].copy()
qubit_calibration_data["x_gate_ix_params"]["amp"] = 0.0
qubit_calibration_data["x_gate_ix_params"]["angle"] = 0.0
if "beta" in qubit_calibration_data["x_gate_ix_params"]:
del qubit_calibration_data["x_gate_ix_params"]["beta"]
qubit_calibration_data["x_gate_frequency_offset"] = qubit_calibration_data[
"frequency_offset"
]
shots = 512 if shots is None else shots
if mode == "CR" and IX_ZX_ratio is None:
IX_ZX_ratio = 0.0
elif mode == "IX-pi" and IX_ZX_ratio is None:
IX_ZX_ratio = -2
try:
target_IX_strength = qubit_calibration_data["coeffs"]["ZX"] * IX_ZX_ratio
except:
target_IX_strength = 0.0
logger.info(f"Target IX / ZX ratio: {IX_ZX_ratio}")
def _get_error(coeff_dict, mode, target_IX):
if mode == "CR":
error = np.array(
(coeff_dict["IX"] - target_IX, coeff_dict["IY"], coeff_dict["ZY"])
)
elif mode == "IX-pi":
error = np.array((coeff_dict["IX"] - target_IX, coeff_dict["IY"]))
error = np.abs(error)
max_error = np.max(error)
return max_error
def _error_smaller_than(coeff_dict, threshold_MHz, mode, target_IX=None):
"""
Compare the measured coupling strength and check if the error terms are smaller than the threshold.
Args:
coeff_dict (dict): Coefficients from tomography job.
threshold_MHz (float): Error threshold for calibration.
mode (str): Calibration mode, "CR" or "IX-pi/2".
target_IX (float, optional): Target IX angle. Default is None.
Returns:
bool: True if error is smaller than threshold, False otherwise.
"""
if mode == "CR":
error = np.array(
(coeff_dict["IX"] - target_IX, coeff_dict["IY"], coeff_dict["ZY"])
)
elif mode == "IX-pi":
error = np.array((coeff_dict["IX"] - target_IX, coeff_dict["IY"]))
error = np.abs(error)
max_error = np.max(error)
error_type = ["IX", "IY", "ZY"][np.argmax(np.abs(error))]
logger.info(f"Remaining dominant error: {error_type}: {max_error} MHz" + "\n")
return max_error < threshold_MHz
def _step_cr(qubit_calibration_data, n):
"""
Submit two jobs, one with the given pulse parameter. If the calibration is not finished, submit another one with a shifted amplitude for the target drive. This will be used to calculate a new set of pulse parameters and returned.
Args:
qubit_calibration_data (dict): Calibration data.
prob_ix_strength (float): Strength of the IX gate pulse.
n (int): Calibration iteration number.
Returns:
tuple: Updated qubit_calibration_data, Calibration success flag.
"""
cr_params = qubit_calibration_data["cr_params"]
ix_params = qubit_calibration_data["ix_params"]
x_gate_ix_params = None
frequency_offset = qubit_calibration_data.get("frequency_offset", 0.0)
if not rerun_last_calibration and n == 1:
# If the last calibration was ran very recently, we can skip the first experiment that just rerun the tomography for the same pulse parameters.
tomo_id1 = qubit_calibration_data["calibration_job_id"]
else:
# Run tomography experiment for the given parameters.
tomo_id1 = send_cr_tomography_job(
(qubits),
backend,
cr_params,
ix_params,
cr_times,
x_gate_ix_params=x_gate_ix_params,
frequency_offset=frequency_offset,
blocking=True,
session=session,
shots=shots,
control_states=control_states,
)
coeff_dict_1 = process_zx_tomo_data(tomo_id1, show_plot=verbose)
target_IX_strength = (
IX_ZX_ratio
* np.sign(coeff_dict_1["ZX"])
* np.sqrt(coeff_dict_1["ZX"] ** 2 + coeff_dict_1["ZY"] ** 2)
)
if verbose:
logger.info("Tomography results:\n" + str(coeff_dict_1) + "\n")
qubit_calibration_data.update(
{
"calibration_job_id": tomo_id1,
"coeffs": coeff_dict_1,
}
)
# Interrupt the process if the calibration is successful or maximal repeat number is reached.
if np.abs(qubit_calibration_data["coeffs"]["IZ"]) > threshold_MHz:
if not (not rerun_last_calibration and n == 1):
qubit_calibration_data = _update_frequency_offset(
qubit_calibration_data, mode, backend.name
)
if _error_smaller_than(coeff_dict_1, threshold_MHz, mode, target_IX_strength):
logger.info("Successfully calibrated.")
return qubit_calibration_data, True
if n > max_repeat:
logger.info(
f"Maximum repeat number {max_repeat} reached, calibration terminates."
)
return qubit_calibration_data, True
# If not completed, send another job with shifted IX drive amplitude.
# Remark: There is a strange observation that the Omega_GHz_amp_ratio measured here is not the same as the one estimated from single-qubit gate duration. There is a
Omega_GHz_amp_ratio = qubit_calibration_data.get(
"_omega_amp_ratio", amp_to_omega_GHz(backend, qubits[1], 1)
)
logger.info(f"Omega[GHz]/amp: {Omega_GHz_amp_ratio}")
Omega_GHz_amp_ratio = np.real(Omega_GHz_amp_ratio)
prob_ix_strength_MHz = target_IX_strength - coeff_dict_1["IX"]
if np.abs(prob_ix_strength_MHz) > 0.1: # Minimum 0.1 MHz
prob_ix_strength = prob_ix_strength_MHz * 1.0e-3 / Omega_GHz_amp_ratio
logger.info(f"Probe amp shift [MHz]: {prob_ix_strength_MHz} MHz")
else:
prob_ix_strength = (
np.sign(prob_ix_strength_MHz) * 0.1e-3 / Omega_GHz_amp_ratio
)
logger.info("Probe amp shift [MHz]: 0.1 MHz")
logger.info(f"Probe amp shift (amp): {prob_ix_strength}")
tomo_id2 = shifted_parameter_cr_job(
qubits,
backend,
cr_params,
ix_params,
cr_times,
prob_ix_strength,
x_gate_ix_params=x_gate_ix_params,
frequency_offset=frequency_offset,
blocking=True,
session=session,
shots=shots,
control_states=control_states,
)
coeff_dict_2 = process_zx_tomo_data(tomo_id2, show_plot=verbose)
if verbose:
logger.info(coeff_dict_2)
# Compute the new parameters.
(
cr_params,
updated_ix_params,
updated_x_gate_ix_params,
omega_amp_ratio,
) = update_pulse_params(
coeff_dict_1,
coeff_dict_2,
cr_params,
ix_params,
prob_ix_strength,
target_IX_strength=target_IX_strength,
backend_name=backend.name,
# only update the real part, imaginary part can be
# unstable for small pulse ampliutude.
real_only=True,
)
# This should not be added before the second experiment because it should only have a different IX drive amplitude.
qubit_calibration_data.update(
{
"cr_params": cr_params,
"ix_params": updated_ix_params,
"_omega_amp_ratio": np.real(omega_amp_ratio),
}
)
return qubit_calibration_data, False
def _step_ix(qubit_calibration_data, n):
"""
Submit two jobs, one with the given pulse parameter. If the calibration is not finished, submit another one with a shifted amplitude for the target drive. This will be used to calculate a new set of pulse parameters and returned.
Args:
qubit_calibration_data (dict): Calibration data.
prob_ix_strength (float): Strength of the IX gate pulse.
n (int): Calibration iteration number.
Returns:
tuple: Updated qubit_calibration_data, Calibration success flag.
"""
if len(control_states) == 2:
process_data_fun = process_zx_tomo_data
else:
process_data_fun = process_single_qubit_tomo_data
cr_params = qubit_calibration_data["cr_params"]
ix_params = qubit_calibration_data["ix_params"]
x_gate_ix_params = qubit_calibration_data["x_gate_ix_params"]
frequency_offset = qubit_calibration_data.get("x_gate_frequency_offset", 0.0)
if not rerun_last_calibration and n == 1:
# If the last calibration was ran very recently, we can skip the first experiment that just rerun the tomography for the same pulse parameters.
tomo_id1 = qubit_calibration_data["x_gate_calibration_job_id"]
else:
# Run tomography experiment for the given parameters.
tomo_id1 = send_cr_tomography_job(
(qubits),
backend,
cr_params,
ix_params,
cr_times,
x_gate_ix_params=x_gate_ix_params,
frequency_offset=frequency_offset,
blocking=True,
session=session,
shots=shots,
control_states=control_states,
)
coeff_dict_1 = process_data_fun(tomo_id1, show_plot=verbose)
if verbose:
logger.info("Tomography results:\n" + str(coeff_dict_1) + "\n")
qubit_calibration_data.update(
{
"x_gate_calibration_job_id": tomo_id1,
"x_gate_coeffs": coeff_dict_1,
}
)
# Interrupt the process if the calibration is successful or maximal repeat number is reached.
if np.abs(qubit_calibration_data["coeffs"]["IZ"]) > threshold_MHz:
if not (not rerun_last_calibration and n == 1):
qubit_calibration_data = _update_frequency_offset(
qubit_calibration_data, mode, backend.name
)
if _error_smaller_than(coeff_dict_1, threshold_MHz, mode, target_IX_strength):
logger.info("Successfully calibrated.")
return qubit_calibration_data, True
if n > max_repeat:
logger.info(
f"Maximum repeat number {max_repeat} reached, calibration terminates."
)
return qubit_calibration_data, True
# If not completed, send another job with shifted IX drive amplitude.
Omega_GHz_amp_ratio = qubit_calibration_data.get(
"_omega_amp_ratio", amp_to_omega_GHz(backend, qubits[1], 1)
)
Omega_GHz_amp_ratio = np.real(Omega_GHz_amp_ratio)
logger.info(f"Omega[GHz]/amp: {Omega_GHz_amp_ratio}")
prob_ix_strength_MHz = target_IX_strength - coeff_dict_1["IX"]
if np.abs(prob_ix_strength_MHz) > 0.1: # Minimum 0.1 MHz
prob_ix_strength = prob_ix_strength_MHz * 1.0e-3 / Omega_GHz_amp_ratio
logger.info(f"Probe amp shift [MHz]: {prob_ix_strength_MHz} MHz")
else:
prob_ix_strength = (
np.sign(prob_ix_strength_MHz) * 0.1e-3 / Omega_GHz_amp_ratio
)
logger.info("Probe amp shift [MHz]: 0.1 MHz")
logger.info(f"Probe amp shift (amp): {prob_ix_strength}")
tomo_id2 = shifted_parameter_cr_job(
qubits,
backend,
cr_params,
ix_params,
cr_times,
prob_ix_strength,
x_gate_ix_params=x_gate_ix_params,
frequency_offset=frequency_offset,
blocking=True,
session=session,
shots=shots,
control_states=control_states,
mode=mode,
)
coeff_dict_2 = process_data_fun(tomo_id2, show_plot=verbose)
if verbose:
logger.info(coeff_dict_2)
# Compute the new parameters.
cr_params, _, updated_x_gate_ix_params, omega_amp_ratio = update_pulse_params(
coeff_dict_1,
coeff_dict_2,
cr_params,
x_gate_ix_params,
prob_ix_strength,
target_IX_strength=target_IX_strength,
backend_name=backend.name,
)
qubit_calibration_data.update(
{
"x_gate_ix_params": updated_x_gate_ix_params,
"_omega_amp_ratio": np.real(omega_amp_ratio),
}
)
return qubit_calibration_data, False
succeed = False
n = 1
error = np.inf
while (
not succeed and n <= max_repeat + 1
): # +1 because we need one last run for the calibration data.
logger.info(f"\n\nCR calibration round {n}: ")
if mode == "CR":
qubit_calibration_data, succeed = _step_cr(qubit_calibration_data, n)
else:
qubit_calibration_data, succeed = _step_ix(qubit_calibration_data, n)
target_IX_strength = qubit_calibration_data["coeffs"]["ZX"] * IX_ZX_ratio
new_error = _get_error(
qubit_calibration_data["coeffs"], mode, target_IX_strength
)
if save_result and new_error < error:
save_calibration_data(backend, gate_name, qubits, qubit_calibration_data)
logger.info("CR calibration data saved.")
n += 1
shots = 2 * shots if shots < 2048 else shots
if not succeed:
logger.warn(f"CR calibration failed after {n} round.")
def iy_drag_calibration(
qubits,
backend,
gate_name,
cr_times,
session,
verbose=False,
threshold_MHz=0.015,
delta_beta=None,
shots=1024,
):
"""Calibrate the IY-DRAG pulse for the qubits and a precalibrated CR pulse. It samples 3 "beta" value in the "ix_params" and perform an linear fit to obtain the correct IY-DRAG coefficient "beta" that zeros the ZZ interaction.
Args:
qubits (Tuple): Tuple containing the qubits involved in the gate.
backend: The quantum backend.
gate_name (str): Name of the gate for calibration. The pre calibrated CR pulse will be read from the database.
cr_times (List): List of control pulse durations for CR experiments.
session: Qiskit runtime session.
verbose (bool, optional): Whether to display additional information. Defaults to False.
threshold_MHz (float, optional): The error threshold for calibration in MHz. Defaults to 0.015.
delta_beta (float, optional): The step size for beta parameter calibration. Defaults to None.
"""
logger.info("\n" + f"Calibrating the IY-DRAG pulse for {qubits}-{gate_name}.")
qubit_calibration_data = read_calibration_data(backend, gate_name, qubits)
cr_params = qubit_calibration_data["cr_params"]
ix_params = qubit_calibration_data["ix_params"]
frequency_offset = qubit_calibration_data.get("frequency_offset", 0.0)
# Sample three different IY strength.
old_beta = ix_params.get("beta", 0.0)
if "drag_type" in ix_params:
ix_params["drag_type"] = "01"
default_delta_beta = 2.0
elif "drag_type" not in ix_params:
default_delta_beta = 100.0
else:
raise ValueError("Unknown drag type.")
delta_beta = (
old_beta
if (old_beta > default_delta_beta and delta_beta is None)
else delta_beta
)
delta_beta = default_delta_beta if delta_beta is None else delta_beta
beta_list = np.array([0.0, -delta_beta, delta_beta]) + old_beta
ZZ_coeff_list = []
for _, beta in enumerate(beta_list):
if np.abs(beta - old_beta) < 1.0e-6:
_shots = shots * 2
else:
_shots = shots
ix_params["beta"] = beta
job_id = send_cr_tomography_job(
qubits,
backend,
cr_params,
ix_params,
cr_times,
frequency_offset=frequency_offset,
blocking=True,
session=session,
shots=_shots,
)
coeff_dict = process_zx_tomo_data(job_id, show_plot=verbose)
ZZ_coeff_list.append(coeff_dict["ZZ"])
if abs(beta - old_beta) < 1.0e-5 and abs(coeff_dict["ZZ"]) < threshold_MHz:
logger.info(
f"ZZ error {round(coeff_dict['ZZ'], 3)} MHz, no need for further calibration."
)
qubit_calibration_data.update(
{
"calibration_job_id": job_id,
"coeffs": coeff_dict,
}
)
save_calibration_data(backend, gate_name, qubits, qubit_calibration_data)
if np.abs(qubit_calibration_data["coeffs"]["IZ"]) > threshold_MHz:
qubit_calibration_data = _update_frequency_offset(
qubit_calibration_data, "CR", backend.name
)
return
logger.info(f"ZZ sampling measurements complete : {ZZ_coeff_list}." + "\n")
# Fit a linear curve.
fun = lambda x, a, b: a * x + b
par, _ = curve_fit(fun, beta_list, ZZ_coeff_list)
calibrated_beta = -par[1] / par[0]
logger.info(f"Calibrated IY beta: {calibrated_beta}" + "\n")
if verbose:
fig, ax = plt.subplots(figsize=(4, 2), dpi=100)
plt.scatter(beta_list, ZZ_coeff_list)
x_line = np.linspace(min(beta_list), max(beta_list))
y_line = fun(x_line, *par)
plt.plot(x_line, y_line)
plt.xlabel("beta")
plt.ylabel("ZZ [MHz]")
plt.show()
# Perform a final tomography measurement.
ix_params["beta"] = calibrated_beta
job_id = send_cr_tomography_job(
qubits,
backend,
cr_params,
ix_params,
cr_times,
frequency_offset=frequency_offset,
blocking=True,
session=session,
shots=shots * 2,
)
# Compute the interaction strength and save the calibration data.
coeff_dict = process_zx_tomo_data(job_id, show_plot=verbose)
logger.info(f"Updated coupling strength: {coeff_dict}")
qubit_calibration_data.update(
{
"calibration_job_id": job_id,
"coeffs": coeff_dict,
"ix_params": ix_params,
}
)
if np.abs(qubit_calibration_data["coeffs"]["IZ"]) > threshold_MHz:
qubit_calibration_data = _update_frequency_offset(
qubit_calibration_data, "CR", backend.name
)
save_calibration_data(backend, gate_name, qubits, qubit_calibration_data)
logger.info(f"IY-DRAG calibration complete, new calibration data saved.")
|
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.circuit.library.standard_gates import CHGate, U2Gate, CXGate
from qiskit.converters import dag_to_circuit
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)
circuit = dag_to_circuit(dag)
circuit.draw('mpl')
|
https://github.com/Dirac231/BCHamming
|
Dirac231
|
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
def num_to_binary(n, N):
"""Returns the binary representation of n
Args:
n (int): The number to be represented in binary
N (int): The number of digits of the rapresentation
Returns:
bool: The binary representation of n
es: num_to_binary(5,4) = 0101
"""
Nbits=2**N
if n>=Nbits: return 0
return bin(n+2*Nbits)[4:]
def is_power_2(n):
"""Returns True if the number is a power of two"""
return n & (n-1) == 0
def HammingCircuit(N, classical_registers=False, name=None, ancillas=None):
"""It gives you a circuit with 2^N qbits of (message + redundancy)
Args:
N (int): Order of the Hamming cirucit
classical_registers (Bool, int): If True if gives an amount of classical registers equal to the number of qbits, if you want a specific number of classical registers just write the number you want. Defaults to False.
name (str): Name of the circuit. Defaults to None.
ancillas (int): Is the number of ancillas of the circuit. Defaults to zero.
Returns:
circuit: Returns a circuit with just the qbits labeled as the parity and signal
"""
if ancillas is None: ancillas = 2*N-1
registers=[]
for i in range(2**N):
prefix='s' #s stands for signal
if is_power_2(i): prefix='p' #c stands for parity
registers.append(QuantumRegister(1,prefix+num_to_binary(i, N)))
if classical_registers!=False:
if classical_registers==True: registers.append(ClassicalRegister(2**N + ancillas))
else: registers.append(ClassicalRegister(classical_registers))
if ancillas > 0: registers.append(QuantumRegister(ancillas))
circuit=QuantumCircuit(*registers) #circuit already with ancillas
circuit.N=N
if name is not None: circuit.name = name
return circuit
def Swapper(N):
"""Circuit that shifts the every qubit right by the number of
power-of-two qubits before it
Args:
N (int): Order of Hamming code
Returns:
gate: swapper
"""
qc = HammingCircuit(N, name="Swapper", ancillas=0)
source = 2**N - N - 2
target = 2**N - 1
while source >= 0:
if is_power_2(target):
target -= 1
qc.swap(source, target)
source -= 1
target -= 1
return qc.to_gate(label="Swapper")
def ReverseSwapper(N):
"""
Circuit that shifts the every qubit left by the number of
power-of-two qubits before it
"""
qc = HammingCircuit(N, ancillas=0)
source = 0
target = 0
while target < 2**N:
if is_power_2(target):
target += 1
continue
qc.swap(source, target)
source += 1
target += 1
return qc.to_gate(label="Reverse Swapper")
def Encoder(N):
"""Encoder for the quantum hamming code"""
qc = HammingCircuit(N, name="Encoder", ancillas=0)
for p in range(N):
p = 2**p
[qc.cx(i, p) for i in range(2**N) if (i & p) == p and i != p]
return qc.to_gate(label="Encoder")
def Hamming_bit_encoder(N, kind="bit", name="bit encoder"):
"""Creates quantum Hamming bit encoder circuit of order N
Args:
N (int): Order of the circuit
name (str, optional): Name of the circuit. Defaults to "bit encoder".
kind (str, optional): Set to "bit" for correcting bit flip errors,
"phase" for correcting phase flip errors.
Returns:
Gates: Quantum Hamming bit encoder circuit of order N
"""
qc = HammingCircuit(N, ancillas=0)
qc.append(Swapper(N), [*range(2**N)])
qc.append(Encoder(N), [*range(2**N)])
if kind=="phase":
qc.h([*range(2**N)])
return qc.to_gate(label=name)
def is_valid_input(kind):
"""Helper function that checks if kind="bit", "phase" or "both" and raises
an exeption if it isn't
"""
if kind not in ["bit", "phase", "both"]:
message = f"The kind argument must be one of bit, phase or both, received {kind} instead"
raise Exception(message)
return True
def HammingOrder(n):
"""Gives you the order of the Hamming gate as a function of n
Args:
n (int): lenght of the input message
Returns:
N (int): order of the Hamming gate
"""
for i in range(0,15):
N=2**i
if N-i-1>=n: return i
def syndrome(N):
"""This gate calculates the syndrome, this gives the position of the faulty qbit"""
circ=HammingCircuit(N, ancillas=N)
nqubits=2**N
for i in range(1,nqubits):
for j in range(0,N):
if i & 2**j == 2**j: circ.cx(i,nqubits+j)
return circ.to_gate(label='syndrome')
def apply_syndrome(N):
"""This gate that corrects the faulty qbit identified in the syndrome"""
circ=HammingCircuit(N, ancillas=N)
nqubits=2**N
count=np.zeros(N)
for i in range(1,nqubits):
count=count+1
for j in range(N):
count[j]=count[j]%(2**j)
if count[j]==0 and i!=1: circ.x(nqubits+j)
if i==1 and j!=0: circ.x(nqubits+j)
circ.mct([*range(nqubits,nqubits+N)],i)
return circ.to_gate(label='Correction')
def Hamming_bit_decoder(N,kind='bit',read=True,name='decoder'):
"""Hamming Gate resistant to bit-fips"""
circ=HammingCircuit(N, ancillas=N)
if kind=='phase':
circ.h([*range(2**N)])
circ.append(syndrome(N),[*range(2**N+N)])
circ.append(apply_syndrome(N),[*range(2**N+N)])
if read==True: circ.append(ReverseSwapper(N), [*range(2**N)])
return circ.to_gate(label=name)
def HammingSize(n, gate='decoder', kind='both'):
"""Gives you the number of qubits that must be present in the circuit
Args:
n (int): lenght of the input message
gate (str): It's either 'encoder' or 'decoder'
kind (str): The kind argument must be one of bit, phase or both
Returns:
n (int): Number of qubits required for the circuit
"""
is_valid_input(kind)
N=HammingOrder(n)
if gate=='encoder':
if kind=='both': return 2**(N+1)
return 2**N
if gate=='decoder':
if kind=='both': return 2**(N+1) + 2*N + 1
return 2**N + N
raise Exception('Gate not valid, the input must be either \'encoder\' or \'decoder\'')
# I don't know if these functions are still useful
def HammingRedundant(n):
"""Takes a integer "n" and makes the binary representation of that integer hamming redundant"""
bits=int(np.log2(n))+1
parity=int(np.log2(bits))+2
total=2**(parity-1)
N,j=0,0
#shift the digits in the correct positions for the hamming code
for i in range(total):
if i!=0 and int(np.log2(i))!=np.log2(i):
N=N+(n&(2**j)==2**j)*(2**i)
j=j+1
#puts the parity bit in place except for the global parity bit
for i in range(parity):
i=2**i
for j in range(i,total):
N=N^((2**i)*((j&i==i)&((N&2**j)!=0)))
#Global parity bit (yet to be tested)
#for i in range(1,total):N=N^((N&2**i)==1)
return N
def classic_input(n,N=None):
#n is the number in integer format, N is the size of the gate
#doesn't work and i
if N==None: N=int(np.log2(n))+1
if (n>=2**N): raise 'ma sei trimò'
registers=QuantumRegister(N)
circuit=QuantumCircuit(registers)
for i in range(N):
j=2**i
if (n&j)==j: circuit.x(i)
return circuit.to_gate(num_to_binary(n,N))
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import Aer
from qiskit.aqua.utils import split_dataset_to_data_and_labels
from qiskit.tools.visualization import plot_bloch_multivector
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import QSVM
from qiskit.circuit.library import ZZFeatureMap
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.svm import SVC
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
Titanic_DF = pd.read_csv('titanic.csv')
Titanic_DF = Titanic_DF.drop(['PassengerId','Name','Cabin','Ticket'],axis=1)
lb_make = preprocessing.LabelEncoder()
Titanic_DF['Sex'] = lb_make.fit_transform(Titanic_DF['Sex'])
Titanic_DF['Embarked'] = lb_make.fit_transform(Titanic_DF['Embarked'])
le_name_mapping = dict(zip(lb_make.classes_, lb_make.transform(lb_make.classes_)))
pd.DataFrame(Titanic_DF).fillna(inplace=True, method='backfill')
FeatureNames = [x for x in list(Titanic_DF.columns) if x not in ['Name','Survived']]
Data = Titanic_DF[FeatureNames].values
Labels = Titanic_DF['Survived'].values
Titanic_DF.info()
Titanic_DF
feature_dim=2
class_labels = [r'0', r'1']
sample_train, sample_test, label_train, label_test = train_test_split(Data, Labels, test_size=0.3, random_state=12)
std_scale = StandardScaler().fit(sample_train, label_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
pca = PCA(n_components=feature_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
sample_test
def QuantumFormat(sample_train, sample_test, label_train, label_test, training_size, test_size, class_labels):
training_input = {key: (sample_train[label_train == k, :])[:training_size] for k, key in enumerate(class_labels)}
test_input = {key: (sample_test[label_test == k, :])[:test_size] for k, key in enumerate(class_labels)}
return training_input, test_input
training_input, test_input = QuantumFormat(sample_train, sample_test, label_train, label_test, 10, 10, class_labels)
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
training_input, test_input
# QSVM
feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear')
qsvm = QSVM(feature_map, training_input, test_input, None)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = qsvm.run(quantum_instance)
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
# Classical SVM
svc = SVC(probability=True, gamma='auto')
svc.fit(sample_train, label_train)
kernel_matrix2=sklearn.metrics.pairwise.rbf_kernel(sample_train, sample_train)
img = plt.imshow(np.asmatrix(kernel_matrix2[0:10,0:10]),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
# Error Rate
label_predict=svc.predict(sample_test)
print('Error rate: ' + str(sum(label_predict==label_test)/len(label_predict)))
|
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/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":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
### added x gate ###
qc.x(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### added z gate ###
qc.z(1)
qc.h(1)
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/omarcostahamido/Qu-Beats
|
omarcostahamido
|
#!/usr/bin/env python
# coding: utf-8
from typing import List, Callable
import numpy as np
from mido import Message, MidiFile, MidiTrack
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
from qiskit.tools.visualization import plot_histogram
#~~~~~~~ Circuit Transformations ~~~~~~~#
def add_bell_state(qc: QuantumCircuit) -> None:
"""This transformation modifies the input circuit by preparing a Bell State."""
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
def add_teleportation(qc: QuantumCircuit) -> None:
"""This transformation modifies the input circuit by implementing the teleportation
protocol.
"""
qc.z(0)
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.cx(0,1)
qc.measure(1, 1)
qc.cx(1,2)
qc.h(0)
qc.measure(0, 0)
qc.cz(0,2)
qc.h(2)
qc.z(2)
qc.measure([0, 1, 2], [0, 1, 2])
def add_grover(qc: QuantumCircuit) -> None:
"""This transformation modifies the input circuit by implementing Grover's algorithm."""
qc.h(0)
qc.h(1)
qc.x(0)
qc.x(1)
qc.cz(0, 1)
qc.x(0)
qc.x(1)
qc.h(0)
qc.h(1)
qc.cz(0, 1)
qc.h(0)
qc.h(1)
qc.measure([0, 1], [0, 1])
def bertstein_vazirani(qc: QuantumCircuit) -> None:
"""This transformation modifies the input circuit by implementing Bertstein-Vazirani."""
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.z(0)
qc.z(1)
qc.z(2)
qc.z(3)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.measure([0, 1, 2, 3], [0, 1, 2, 3])
#~~~~~~~ Input arrays, representing beats over time ~~~~~~~#
beat1 = [0, 1, 0, 0, 1, 0, 1, 0, 1, 0]
beat2 = [1, 1, 0, 1, 1, 0, 1, 1, 1, 1]
beat3 = [0, 0, 0, 1, 1, 1, 1, 0, 0, 1]
beat4 = [1, 0, 0, 0, 1, 1, 0, 0, 0, 1]
#~~~~~~~ Conversion to MIDI ~~~~~~~#
def save_to_midi(beat_array: List[int],
filename: str,
note: int = 32,
time: int = 100) -> None:
"""Save the input to a new midi file."""
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
for bt in beat_array:
message = 'note_{}'.format('on' if bt == 1 else 'off')
track.append(Message(message, note=note, time=time))
mid.save(filename)
save_to_midi(beat1, '/Users/lauren@ibm.com/Documents/pBeat1.mid')
save_to_midi(beat2, '/Users/lauren@ibm.com/Documents/pBeat2.mid')
save_to_midi(beat3, '/Users/lauren@ibm.com/Documents/pBeat3.mid')
save_to_midi(beat4, '/Users/lauren@ibm.com/Documents/pBeat4.mid')
#~~~~~~~ Build QuantumCircuits ~~~~~~~#
def build_circuits(transformation: Callable,
beat1: List[int], *beats: List[List[int]]) -> List[QuantumCircuit]:
circuits = []
for i in range(len(beats[0])):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
for j, beat in enumerate(beats):
if beat[i] == 1:
qc.x(j)
qc.barrier()
# Add transformation (and measurement)
transformation(qc)
circuits.append(qc)
return circuits
#~~~~~~~ BELL STATE ~~~~~~~#
circuits = build_circuits(add_bell_state, beat1, beat2)
circuits[0].draw(output='mpl')
## Executing code
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuits, backend=simulator, shots=1).result()
cir_array = []
for c in circuits:
cir_array.append([k for k in result.get_counts(c).keys()][0])
new_track1 = []
new_track2 = []
for b in cir_array:
new_track1.append(int(b[0]))
new_track2.append(int(b[1]))
## New Midi Rhythms
save_to_midi(new_track1, '/Users/lauren@ibm.com/Documents/Bell_Circ.mid')
save_to_midi(new_track2, '/Users/lauren@ibm.com/Documents/Bell_Circ2.mid')
#~~~~~~~ TELEPORTATION ~~~~~~~#
circuits = build_circuits(add_teleportation, beat1, beat2, beat3)
circuits[0].draw(output='mpl')
# Executing code
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuits, backend = simulator, shots=1).result()
cir_array = []
for c in circuits:
cir_array.append([k for k in result.get_counts(c).keys()][0])
new_track1 = []
new_track2 = []
new_track3 = []
for b in cir_array:
new_track1.append(int(b[0]))
new_track2.append(int(b[1]))
new_track3.append(int(b[2]))
#~~~~~~~ BERNSTEIN VAZIRANI ~~~~~~~#
circuits = build_circuits(bertstein_vazirani, beat1, beat2, beat2, beat2)
circuits[0].draw(output='mpl')
## Executing code
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuits, backend = simulator, shots=1024).result()
plot_histogram(result.get_counts(circuits[4]))
cir_array = []
for c in circuits:
cir_array.append([k for k in result.get_counts(c).keys()][0])
new_track1 = []
new_track2 = []
new_track3 = []
for b in cir_array:
new_track1.append(int(b[0]))
new_track2.append(int(b[1]))
new_track3.append(int(b[2]))
save_to_midi(new_track1, '/Users/lauren@ibm.com/Documents/new_teleport1.mid')
save_to_midi(new_track2, '/Users/lauren@ibm.com/Documents/new_teleport2.mid')
save_to_midi(new_track3, '/Users/lauren@ibm.com/Documents/new_teleport3.mid')
|
https://github.com/sathayen/qiskit-docker
|
sathayen
|
# Creating quantum circuits
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import execute, Aer
from qiskit.tools.visualization import circuit_drawer, plot_histogram
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.x(qr[0])
qc.measure(qr, cr)
circuit_drawer(qc)
# Run the circuit
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
print("Counts dictionary:", counts )
print("Probability = ", counts['01']/1024)
|
https://github.com/MetalKyubit/Quantum-Algorithms-in-Qiskit
|
MetalKyubit
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import *
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeJakarta
from qiskit.providers.fake_provider import FakeNairobi
#defining a function to create the DJ Algorithm circuit. Function takes in the oracle and number or qubits and
# ouputs the circuit
def DJ_algo(oracle,n):
# n input qubits and 1 helper qubit
qc = QuantumCircuit(n+1,n)
# helper qubit initialised to state ket_1
qc.x(n)
# creating superposition of all the inputs. and making the state of the helper qubit as ket_minus.
for i in range(n+1):
qc.h(i)
qc.barrier()
# applying the oracle that has the funciton encoded in it to the circuit
qc.append(oracle, range(n+1))
qc.barrier()
#applying the hadamard gates again to collapse the superposition to one state that has the final result
#encoded in it.
for i in range(n):
qc.h(i)
# measuring the input qubits to find the final result.
qc.measure(range(n),range(n))
return (qc)
# The oracle is defined below
def dj_oracle(n:int, type:str):
#define a quantum circuit with n input qubits and 1 helper qubits
qc = QuantumCircuit(n+1)
#create an oracle based on whether balanced or constant function
if(type == 'balanced'):
#balanced oracle flips helper when the 0th qubit is 1 half the inputs will have 0th qubit 1 rest
# half will have 0th qubit 0.
qc.cx(0,n)
else:
#apply identity on the n+1 bit
qc.i(n)
#convert to gate
_gate_oracle = qc.to_gate()
if (type == 'balanced'):
_gate_oracle.name = "oracle_balanced"
else:
_gate_oracle.name = "oracle_constant"
# return the gate
return _gate_oracle
# Testing the algorithm for n=3 and constant function
n = 2
oracle = dj_oracle(n, 'constant')
q1 = DJ_algo(oracle, n)
q1.draw('mpl')
backend = Aer.get_backend('aer_simulator')
transpiled =transpile(q1, backend)
job= execute(transpiled, backend)
results= job.result()
counts = results.get_counts()
plot_histogram(counts)
# Running on noisy simulator
backend = FakeJakarta()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Running on noisy simulator
backend = FakeNairobi()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Testing the algorithm for n=3 and constant function
n = 6
oracle = dj_oracle(n, 'balanced')
q1 = DJ_algo(oracle, n)
q1.draw('mpl')
backend = Aer.get_backend('aer_simulator')
transpiled =transpile(q1, backend)
job= execute(transpiled, backend)
results= job.result()
counts = results.get_counts()
plot_histogram(counts)
# Running on noisy simulator
backend = FakeJakarta()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Running on noisy simulator
backend = FakeNairobi()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for core modules of pulse drawer."""
from qiskit import pulse, circuit
from qiskit.test import QiskitTestCase
from qiskit.visualization.pulse_v2 import events
class TestChannelEvents(QiskitTestCase):
"""Tests for ChannelEvents."""
def test_parse_program(self):
"""Test typical pulse program."""
test_pulse = pulse.Gaussian(10, 0.1, 3)
sched = pulse.Schedule()
sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0)))
sched = sched.insert(0, pulse.Play(test_pulse, pulse.DriveChannel(0)))
sched = sched.insert(10, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0)))
sched = sched.insert(10, pulse.Play(test_pulse, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
# check waveform data
waveforms = list(ch_events.get_waveforms())
inst_data0 = waveforms[0]
self.assertEqual(inst_data0.t0, 0)
self.assertEqual(inst_data0.frame.phase, 3.14)
self.assertEqual(inst_data0.frame.freq, 0)
self.assertEqual(inst_data0.inst, pulse.Play(test_pulse, pulse.DriveChannel(0)))
inst_data1 = waveforms[1]
self.assertEqual(inst_data1.t0, 10)
self.assertEqual(inst_data1.frame.phase, 1.57)
self.assertEqual(inst_data1.frame.freq, 0)
self.assertEqual(inst_data1.inst, pulse.Play(test_pulse, pulse.DriveChannel(0)))
# check frame data
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertEqual(inst_data0.t0, 0)
self.assertEqual(inst_data0.frame.phase, 3.14)
self.assertEqual(inst_data0.frame.freq, 0)
self.assertListEqual(inst_data0.inst, [pulse.SetPhase(3.14, pulse.DriveChannel(0))])
inst_data1 = frames[1]
self.assertEqual(inst_data1.t0, 10)
self.assertEqual(inst_data1.frame.phase, -1.57)
self.assertEqual(inst_data1.frame.freq, 0)
self.assertListEqual(inst_data1.inst, [pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))])
def test_multiple_frames_at_the_same_time(self):
"""Test multiple frame instruction at the same time."""
# shift phase followed by set phase
sched = pulse.Schedule()
sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0)))
sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertAlmostEqual(inst_data0.frame.phase, 3.14)
# set phase followed by shift phase
sched = pulse.Schedule()
sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0)))
sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertAlmostEqual(inst_data0.frame.phase, 1.57)
def test_frequency(self):
"""Test parse frequency."""
sched = pulse.Schedule()
sched = sched.insert(0, pulse.ShiftFrequency(1.0, pulse.DriveChannel(0)))
sched = sched.insert(5, pulse.SetFrequency(5.0, pulse.DriveChannel(0)))
ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0))
ch_events.set_config(dt=0.1, init_frequency=3.0, init_phase=0)
frames = list(ch_events.get_frame_changes())
inst_data0 = frames[0]
self.assertAlmostEqual(inst_data0.frame.freq, 1.0)
inst_data1 = frames[1]
self.assertAlmostEqual(inst_data1.frame.freq, 1.0)
def test_parameterized_parametric_pulse(self):
"""Test generating waveforms that are parameterized."""
param = circuit.Parameter("amp")
test_waveform = pulse.Play(pulse.Constant(10, param), pulse.DriveChannel(0))
ch_events = events.ChannelEvents(
waveforms={0: test_waveform}, frames={}, channel=pulse.DriveChannel(0)
)
pulse_inst = list(ch_events.get_waveforms())[0]
self.assertTrue(pulse_inst.is_opaque)
self.assertEqual(pulse_inst.inst, test_waveform)
def test_parameterized_frame_change(self):
"""Test generating waveforms that are parameterized.
Parameterized phase should be ignored when calculating waveform frame.
This is due to phase modulated representation of waveforms,
i.e. we cannot calculate the phase factor of waveform if the phase is unbound.
"""
param = circuit.Parameter("phase")
test_fc1 = pulse.ShiftPhase(param, pulse.DriveChannel(0))
test_fc2 = pulse.ShiftPhase(1.57, pulse.DriveChannel(0))
test_waveform = pulse.Play(pulse.Constant(10, 0.1), pulse.DriveChannel(0))
ch_events = events.ChannelEvents(
waveforms={0: test_waveform},
frames={0: [test_fc1, test_fc2]},
channel=pulse.DriveChannel(0),
)
# waveform frame
pulse_inst = list(ch_events.get_waveforms())[0]
self.assertFalse(pulse_inst.is_opaque)
self.assertEqual(pulse_inst.frame.phase, 1.57)
# framechange
pulse_inst = list(ch_events.get_frame_changes())[0]
self.assertTrue(pulse_inst.is_opaque)
self.assertEqual(pulse_inst.frame.phase, param + 1.57)
def test_zero_duration_delay(self):
"""Test generating waveforms that contains zero duration delay.
Zero duration delay should be ignored.
"""
ch = pulse.DriveChannel(0)
test_sched = pulse.Schedule()
test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch)
test_sched += pulse.Delay(0, ch)
test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch)
test_sched += pulse.Delay(1, ch)
test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch)
ch_events = events.ChannelEvents.load_program(test_sched, ch)
self.assertEqual(len(list(ch_events.get_waveforms())), 4)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from math import pi
import numpy as np
import rustworkx as rx
from qiskit_nature.second_q.hamiltonians.lattices import (
BoundaryCondition,
HyperCubicLattice,
Lattice,
LatticeDrawStyle,
LineLattice,
SquareLattice,
TriangularLattice,
)
from qiskit_nature.second_q.hamiltonians import FermiHubbardModel
num_nodes = 11
boundary_condition = BoundaryCondition.OPEN
line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition)
line_lattice.draw()
num_nodes = 11
boundary_condition = BoundaryCondition.PERIODIC
line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition)
line_lattice.draw()
line_lattice.draw_without_boundary()
num_nodes = 11
boundary_condition = BoundaryCondition.PERIODIC
edge_parameter = 1.0 + 1.0j
onsite_parameter = 1.0
line_lattice = LineLattice(
num_nodes=num_nodes,
edge_parameter=edge_parameter,
onsite_parameter=onsite_parameter,
boundary_condition=boundary_condition,
)
set(line_lattice.graph.weighted_edge_list())
line_lattice.to_adjacency_matrix()
line_lattice.to_adjacency_matrix(weighted=True)
rows = 5
cols = 4
boundary_condition = BoundaryCondition.OPEN
square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
square_lattice.draw()
rows = 5
cols = 4
boundary_condition = (
BoundaryCondition.OPEN,
BoundaryCondition.PERIODIC,
) # open in the x-direction, periodic in the y-direction
square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
square_lattice.draw()
rows = 5
cols = 4
edge_parameter = (1.0, 1.0 + 1.0j)
boundary_condition = (
BoundaryCondition.OPEN,
BoundaryCondition.PERIODIC,
) # open in the x-direction, periodic in the y-direction
onsite_parameter = 1.0
square_lattice = SquareLattice(
rows=rows,
cols=cols,
edge_parameter=edge_parameter,
onsite_parameter=onsite_parameter,
boundary_condition=boundary_condition,
)
set(square_lattice.graph.weighted_edge_list())
size = (3, 4, 5)
boundary_condition = (
BoundaryCondition.OPEN,
BoundaryCondition.OPEN,
BoundaryCondition.OPEN,
)
cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition)
# function for setting the positions
def indextocoord_3d(index: int, size: tuple, angle) -> list:
z = index // (size[0] * size[1])
a = index % (size[0] * size[1])
y = a // size[0]
x = a % size[0]
vec_x = np.array([1, 0])
vec_y = np.array([np.cos(angle), np.sin(angle)])
vec_z = np.array([0, 1])
return_coord = x * vec_x + y * vec_y + z * vec_z
return return_coord.tolist()
pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))])
cubic_lattice.draw(style=LatticeDrawStyle(pos=pos))
rows = 4
cols = 3
boundary_condition = BoundaryCondition.OPEN
triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
triangular_lattice.draw()
rows = 4
cols = 3
boundary_condition = BoundaryCondition.PERIODIC
triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition)
triangular_lattice.draw()
graph = rx.PyGraph(multigraph=False) # multigraph shoud be False
graph.add_nodes_from(range(6))
weighted_edge_list = [
(0, 1, 1.0 + 1.0j),
(0, 2, -1.0),
(2, 3, 2.0),
(4, 2, -1.0 + 2.0j),
(4, 4, 3.0),
(2, 5, -1.0),
]
graph.add_edges_from(weighted_edge_list)
# make a lattice
general_lattice = Lattice(graph)
set(general_lattice.graph.weighted_edge_list())
general_lattice.draw()
general_lattice.draw(self_loop=True)
general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True))
square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC)
t = -1.0 # the interaction parameter
v = 0.0 # the onsite potential
u = 5.0 # the interaction parameter U
fhm = FermiHubbardModel(
square_lattice.uniform_parameters(
uniform_interaction=t,
uniform_onsite_potential=v,
),
onsite_interaction=u,
)
ham = fhm.second_q_op().simplify()
print(ham)
graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False
graph.add_nodes_from(range(6))
weighted_edge_list = [
(0, 1, 1.0 + 1.0j),
(0, 2, -1.0),
(2, 3, 2.0),
(4, 2, -1.0 + 2.0j),
(4, 4, 3.0),
(2, 5, -1.0),
]
graph.add_edges_from(weighted_edge_list)
general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix.
u = 5.0 # the interaction parameter U
fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u)
ham = fhm.second_q_op().simplify()
print(ham)
from qiskit_nature.second_q.problems import LatticeModelProblem
num_nodes = 4
boundary_condition = BoundaryCondition.OPEN
line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition)
fhm = FermiHubbardModel(
line_lattice.uniform_parameters(
uniform_interaction=t,
uniform_onsite_potential=v,
),
onsite_interaction=u,
)
lmp = LatticeModelProblem(fhm)
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import JordanWignerMapper
numpy_solver = NumPyMinimumEigensolver()
qubit_mapper = JordanWignerMapper()
calc = GroundStateEigensolver(qubit_mapper, numpy_solver)
res = calc.solve(lmp)
print(res)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-scheduling-extension
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the CompactScheduling pass"""
from qiskit import QuantumCircuit, transpile
from qiskit.test import QiskitTestCase
from qiskit.transpiler.preset_passmanagers.plugin import list_stage_plugins
class TestCompactScheduling(QiskitTestCase):
"""Tests the CompactScheduling plugin"""
def test_plugin_in_list(self):
"""Test compact scheduling plugin is installed."""
self.assertIn("compact", list_stage_plugins("scheduling"))
def test_compact(self):
"""Test if Compact scheduling yields expected schedule.
(input)
┌───┐ ┌───┐ ░ ┌─┐
q_0: ┤ H ├──■─────────■──┤ H ├─░─┤M├──────
└───┘┌─┴─┐ ┌─┴─┐└───┘ ░ └╥┘┌─┐
q_1: ─────┤ X ├──■──┤ X ├──────░──╫─┤M├───
┌───┐└───┘┌─┴─┐├───┤ ░ ║ └╥┘┌─┐
q_2: ┤ H ├─────┤ X ├┤ H ├──────░──╫──╫─┤M├
└───┘ └───┘└───┘ ░ ║ ║ └╥┘
meas: 3/═════════════════════════════╩══╩══╩═
0 1 2
(Compact scheduled)
┌───┐ ┌────────────────┐ ┌───┐ ░ ┌─┐
q_0: ──────┤ H ├─────────■──┤ Delay(900[dt]) ├──■────────┤ H ├────────░─┤M├──────
┌─────┴───┴──────┐┌─┴─┐└────────────────┘┌─┴─┐┌─────┴───┴──────┐ ░ └╥┘┌─┐
q_1: ┤ Delay(200[dt]) ├┤ X ├────────■─────────┤ X ├┤ Delay(200[dt]) ├─░──╫─┤M├───
├────────────────┤├───┤ ┌─┴─┐ ├───┤├────────────────┤ ░ ║ └╥┘┌─┐
q_2: ┤ Delay(700[dt]) ├┤ H ├──────┤ X ├───────┤ H ├┤ Delay(700[dt]) ├─░──╫──╫─┤M├
└────────────────┘└───┘ └───┘ └───┘└────────────────┘ ░ ║ ║ └╥┘
meas: 3/════════════════════════════════════════════════════════════════════╩══╩══╩═
0 1 2
"""
qc = QuantumCircuit(3)
qc.h([0, 2])
qc.cx(0, 1)
qc.cx(1, 2)
qc.cx(0, 1)
qc.h([0, 2])
qc.measure_all()
durations = [
("h", None, 200),
("cx", [0, 1], 700),
("cx", [1, 2], 900),
("measure", None, 1000)
]
actual = transpile(
qc, instruction_durations=durations, scheduling_method="compact", optimization_level=0
)
expected = QuantumCircuit(3)
expected.delay(200, 1)
expected.delay(700, 2)
expected.h([0, 2])
expected.cx(0, 1)
expected.cx(1, 2)
expected.delay(900, 0)
expected.cx(0, 1)
expected.h([0, 2])
expected.delay(200, 1)
expected.delay(700, 2)
expected.measure_all()
self.assertEqual(expected, actual)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.circuit.random import random_circuit
from qiskit.visualization import plot_state_qsphere
from qiskit.quantum_info.operators import Operator
def pretty_print(x):
with np.printoptions(precision=3, suppress=True):
print(x)
n = 3
circ = random_circuit(n,n)
circ.draw(output='mpl')
circ.draw(output='latex')
result_statevec_sim = execute(circ, Aer.get_backend('statevector_simulator')).result()
psi = result_statevec_sim.get_statevector(circ, decimals=3)
pretty_print(psi)
plot_state_qsphere(psi)
result_unitary_sim = execute(circ, Aer.get_backend('unitary_simulator')).result()
U = result_unitary_sim.get_unitary(circ, decimals=3)
pretty_print(U)
op = Operator(circ) # implicitly uses unitary simulator
op.dim
x = np.zeros(2**n)
x[0] = 1
pretty_print(op.data.dot(x))
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
# Installation of the requirements
#!python -m pip install -r requirements.txt
'''
(C) Renata Wong 2023
Qiskit code for testing fidelity of derandomised classical shadow on the ground state energy of molecules.
This notebook implements an optimization: since the derandomized Hamiltonian may contan very few terms,
instead of generating a quantum circuit for each and measuring once, we generate a single circuit and specify
a shot number that matches the number of occurrences of a derandomized operator. This speeds up the computation
significantly.
Procedure:
1. Derandomize the molecule-in-question's Hamiltonian.
2. Choose a variational ansatz with initial parameters selected at random.
3. Apply the derandomized Hamiltonian as basis change operators to the ansatz.
4. Measure the ansatz in the Pauli Z basis and store the results as a shadow.
5. Obtain the expectation value of the molecular Hamiltonian from the shadow.
6. Optimize for minimum Hamiltonian expectation value.
7. Feed the calculated angles/parameters back to the ansatz.
8. Repeat steps 3-7 till the optimization is completed.
9. Output the minimized expectation value of the molecular Hamiltonian and the mean-square-root-error.
Note: Below we perform calculations on the molecular Hamiltonian of H_2.
To perform calculations on other molecules, you will need to specify their geometry, charge and spin
to replace the values in the driver.
'''
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit.circuit.library import EfficientSU2
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
import time
import numpy as np
from functools import partial
import matplotlib.pyplot as plt
from collections import Counter
from predicting_quantum_properties.prediction_shadow import estimate_exp
from modified_derandomization import modified_derandomized_classical_shadow
# handle deprecation issues
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
# classically obtained ground state energy
EXPECTED_EIGENVALUE = -1.86
# specifying the geometry of the molecule in question
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
# electronic Hamiltonian of the system
second_q_op = hamiltonian.second_q_op()
# The Bravyi-Kitaev repserentation of the Fermionic Hamiltonian
mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = mapper.map(second_q_op)
print(bkencoded_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
# 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
#print('HAMILTONIAN\n', observables_xyze)
'''
VARIATIONAL ANSATZ
Note that for molecules other than H_2 you may need to specify a different number of reps.
'''
reps = 1
ansatz = EfficientSU2(system_size, su2_gates=['rx', 'ry'], entanglement='circular', reps=reps, skip_final_rotation_layer=False)
ansatz.decompose().draw('mpl')
'''
COST FUNCTION
'''
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)
elif op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def min_cost():
return min(cost_history)
def log_cost(cost):
global cost_history
cost_history.append(cost)
def objective_function(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()
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)
cost = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
exp_val = sum_product / match_count
cost += weight * exp_val
log_cost(cost)
return cost
'''
RUNNING EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 100, 200, 600, 1000, 1600]
for num_operators in measurement_range:
derandomized_hamiltonian = modified_derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
optimizer = SPSA(maxiter=2000)
cost_function = partial(objective_function, derandomized_hamiltonian)
expectation_values = []
num_experiments = 3
for iteration in range(num_experiments):
cost_history = []
params = np.random.rand(ansatz.num_parameters)
result = optimizer.minimize(fun=cost_function, x0=params)
minimal_cost = min_cost()
expectation_values.append(minimal_cost)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, minimal_cost))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - EXPECTED_EIGENVALUE)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='SPSA(maxiter=2000)')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/esquivelgor/Quantum-Route-Minimizer
|
esquivelgor
|
from qiskit import *
from qiskit.visualization import plot_histogram
import numpy as np
def NOT(inp):
"""An NOT gate.
Parameters:
inp (str): Input, encoded in qubit 0.
Returns:
QuantumCircuit: Output NOT circuit.
str: Output value measured from qubit 0.
"""
qc = QuantumCircuit(1, 1) # A quantum circuit with a single qubit and a single classical bit
qc.reset(0)
# We encode '0' as the qubit state |0⟩, and '1' as |1⟩
# Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'
# For an input of '1', we do an x to rotate the |0⟩ to |1⟩
if inp=='1':
qc.x(0)
# barrier between input state and gate operation
qc.barrier()
# Now we've encoded the input, we can do a NOT on it using x
qc.x(0)
#barrier between gate operation and measurement
qc.barrier()
# Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]
qc.measure(0,0)
qc.draw()
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp in ['0', '1']:
qc, out = NOT(inp)
print('NOT with input',inp,'gives output',out)
display(qc.draw())
print('\n')
def XOR(inp1,inp2):
"""An XOR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 1.
"""
qc = QuantumCircuit(2, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
# barrier between input state and gate operation
qc.barrier()
# this is where your program for quantum XOR gate goes
qc.cx(0, 1)
# barrier between input state and gate operation
qc.barrier()
qc.measure(1,0) # output from qubit 1 is measured
#We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
#Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = XOR(inp1, inp2)
print('XOR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def AND(inp1,inp2):
"""An AND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum AND gate goes
qc.ccx(0,1,2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = AND(inp1, inp2)
print('AND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def NAND(inp1,inp2):
"""An NAND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output NAND circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum NAND gate goes
qc.ccx(0,1,2)
if inp=='1':
qc.x(2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = NAND(inp1, inp2)
print('NAND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def OR(inp1,inp2):
"""An OR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum OR gate goes
qc.cx(0, 2)
qc.cx(1, 2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = OR(inp1, inp2)
print('OR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
from qiskit import IBMQ
#IBMQ.save_account("a68a35747d4eccd1d58f275e637909987c789ce5c0edd8a4f43014672bf0301b54b28b1b5f44ba8ff87500777429e1e4ceb79621a6ba248d6cca6bca0e233d23", overwrite=True)
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider('ibm-q')
provider.backends()
import qiskit.tools.jupyter
# run this cell
backend = provider.get_backend('ibmq_quito')
qc_and = QuantumCircuit(3)
qc_and.ccx(0,1,2)
print('AND gate')
display(qc_and.draw())
print('\n\nTranspiled AND gate with all the required connectivity')
qc_and.decompose().draw()
from qiskit.tools.monitor import job_monitor
# run the cell to define AND gate for real quantum system
def AND(inp1, inp2, backend, layout):
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
qc.ccx(0, 1, 2)
qc.barrier()
qc.measure(2, 0)
qc_trans = transpile(qc, backend, initial_layout=layout, optimization_level=3)
job = backend.run(qc_trans, shots=8192)
print(job.job_id())
job_monitor(job)
output = job.result().get_counts()
return qc_trans, output
backend
layout = [0, 1, 2]
output_all = []
qc_trans_all = []
prob_all = []
worst = 1
best = 0
for input1 in ['0','1']:
for input2 in ['0','1']:
qc_trans, output = AND(input1, input2, backend, layout)
output_all.append(output)
qc_trans_all.append(qc_trans)
prob = output[str(int( input1=='1' and input2=='1' ))]/8192
prob_all.append(prob)
print('\nProbability of correct answer for inputs',input1,input2)
print('{:.2f}'.format(prob) )
print('---------------------------------')
worst = min(worst,prob)
best = max(best, prob)
print('')
print('\nThe highest of these probabilities was {:.2f}'.format(best))
print('The lowest of these probabilities was {:.2f}'.format(worst))
print('Transpiled AND gate circuit for ibmq_vigo with input 0 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[0].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[0].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[0]) )
qc_trans_all[0].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 0 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[1].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[1].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[1]) )
qc_trans_all[1].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[2].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[2].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[2]) )
qc_trans_all[2].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[3].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[3].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[3]) )
qc_trans_all[3].draw()
|
https://github.com/qiskit-community/qgss-2023
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import SparsePauliOp
def heisenberg_hamiltonian(
length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0
) -> SparsePauliOp:
terms = []
for i in range(length - 1):
if jx:
terms.append(("XX", [i, i + 1], jx))
if jy:
terms.append(("YY", [i, i + 1], jy))
if jz:
terms.append(("ZZ", [i, i + 1], jz))
return SparsePauliOp.from_sparse_list(terms, num_qubits=length)
def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit:
qubits = QuantumRegister(num_qubits, name="q")
circuit = QuantumCircuit(qubits)
circuit.h(qubits)
for _ in range(layers):
for i in range(0, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
for i in range(1, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
return circuit
length = 5
hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0)
circuit = state_prep_circuit(length, layers=2)
print(hamiltonian)
circuit.draw("mpl")
from qiskit_aer.primitives import Estimator
estimator = Estimator(approximation=True)
job = estimator.run(circuit, hamiltonian, shots=None)
result = job.result()
exact_value = result.values[0]
print(f"Exact energy: {exact_value}")
from qiskit_ibm_runtime import QiskitRuntimeService
hub = "ibm-q-internal"
group = "deployed"
project = "default"
service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}")
from qiskit_ibm_runtime import Estimator, Options, Session
from qiskit.transpiler import CouplingMap
backend = service.get_backend("simulator_statevector")
# set simulation options
simulator = {
"basis_gates": ["id", "rz", "sx", "cx", "reset"],
"coupling_map": list(CouplingMap.from_line(length + 1)),
}
shots = 10000
import math
options = Options(
simulator=simulator,
resilience_level=0,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
from qiskit_aer.noise import NoiseModel, ReadoutError
noise_model = NoiseModel()
##### your code here #####
print(noise_model)
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex1
grade_lab5_ex1(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(length))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
new_shots: int
##### your code here #####
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex2
grade_lab5_ex2(new_shots)
from qiskit_aer.noise import depolarizing_error
noise_model = NoiseModel()
##### your code here #####
print(noise_model)
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex3
grade_lab5_ex3(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
|
https://github.com/tuf65651/quantum-research
|
tuf65651
|
# %matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from datetime import datetime
# import math
# Loading your IBM Q account(s)
# IBMQ.load_account()
backend = Aer.get_backend("qasm_simulator")
# global n_reg
# global m_reg
# global scratch_a
# global class_reg
# global backend
# global qc
# global test_timestamp
# def before_tests():
global n_reg # = QuantumRegister(6, 'n')
global scratch_a
global class_reg # = ClassicalRegister(6, 'y')
global qc # = QuantumCircuit(n_reg, m_reg, scratch_a, class_reg)
test_timestamp = datetime.now()
from ArithmaticFunctions import *
def setup_each_addition():
n_reg = QuantumRegister(6, 'n')
m_reg = QuantumRegister(6, 'm')
scratch_a = QuantumRegister(6, 'sca')
class_reg = ClassicalRegister(6, 'y')
qc = QuantumCircuit(n_reg, m_reg, scratch_a, class_reg)
return {'n_reg': n_reg, 'm_reg': m_reg, 'scratch_a': scratch_a, 'class_reg': class_reg, 'qc': qc }
def get_results_of_last_test():
# for bit in range(len(n_reg)):
# qc.measure(n_reg[bit], class_reg[bit])
simulate = execute(qc, backend=backend, shots=1024).result()
return simulate.get_counts()
def verify_results(expected):
if [expected] == list(results.keys()):
print("PASSING - ", test_timestamp)
else:
print("FAILING - ", test_timestamp)
print(f'Got - {results}')
tc = setup_each_addition()
qc = tc['qc']
twos_complement(tc['qc'], tc['n_reg'], tc['scratch_a'])
qc.measure(tc['n_reg'], tc['class_reg'])
results = get_results_of_last_test()
verify_results('000000')
tc = setup_each_addition()
qc = tc['qc']
qc.x(tc['n_reg'][0])
twos_complement(tc['qc'], tc['n_reg'], tc['scratch_a'])
qc.measure(tc['n_reg'], tc['class_reg'])
results = get_results_of_last_test()
verify_results('111111')
tc = setup_each_addition()
qc = tc['qc']
qc.x(tc['n_reg'][2])
twos_complement(tc['qc'], tc['n_reg'], tc['scratch_a'])
qc.measure(tc['n_reg'], tc['class_reg'])
results = get_results_of_last_test()
verify_results('111100')
tc = setup_each_addition()
qc = tc['qc']
qc.x(tc['n_reg'][2])
qc.x(tc['n_reg'][3])
qc.x(tc['n_reg'][4])
qc.x(tc['n_reg'][5])
twos_complement(tc['qc'], tc['n_reg'], tc['scratch_a'])
qc.measure(tc['n_reg'], tc['class_reg'])
results = get_results_of_last_test()
verify_results('000100')
tc = setup_each_addition()
qc = tc['qc']
twos_complement(tc['qc'], tc['n_reg'], tc['scratch_a'])
qc.measure(tc['n_reg'], tc['class_reg'])
results = get_results_of_last_test()
verify_results('000000')
tc = setup_each_addition()
qc = tc['qc']
qc.x(tc['n_reg'][0])
qc.x(tc['n_reg'][1])
qc.x(tc['n_reg'][2])
qc.x(tc['n_reg'][3])
qc.x(tc['n_reg'][4])
twos_complement(tc['qc'], tc['n_reg'], tc['scratch_a'])
qc.measure(tc['n_reg'], tc['class_reg'])
results = get_results_of_last_test()
verify_results('100001')
tc = setup_each_addition()
qc = tc['qc']
twos_complement(tc['qc'], tc['n_reg'], tc['scratch_a'])
qc.measure(tc['n_reg'], tc['class_reg'])
results = get_results_of_last_test()
verify_results('100001')
tc = setup_each_addition()
qc = tc['qc']
qc.x(tc['m_reg'][0])
qc.barrier()
twos_complement(qc, tc['n_reg'], tc['scratch_a'])
add_to_b_in_place(qc, tc['m_reg'], tc['n_reg'], tc['scratch_a'])
twos_complement(qc, tc['n_reg'], tc['scratch_a'])
qc.measure(tc['n_reg'], tc['class_reg'])
results = get_results_of_last_test()
verify_results('111111')
tc = setup_each_addition()
qc = tc['qc']
qc.x(tc['m_reg'][0])
qc.x(tc['m_reg'][1])
qc.x(tc['m_reg'][2])
qc.x(tc['m_reg'][3])
qc.x(tc['m_reg'][4])
qc.x(tc['m_reg'][5])
qc.barrier()
twos_complement(qc, tc['n_reg'], tc['scratch_a'])
add_to_b_in_place(qc, tc['m_reg'], tc['n_reg'], tc['scratch_a'])
twos_complement(qc, tc['n_reg'], tc['scratch_a'])
qc.measure(tc['n_reg'], tc['class_reg'])
results = get_results_of_last_test()
verify_results('111111')
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear')
ansatz.draw('mpl', style='iqx')
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
from qiskit import Aer
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718)
from qiskit.circuit import QuantumCircuit
from qiskit.opflow import Z, X
H = X ^ X
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
# YOUR CODE HERE
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
matmult_result =expectation.eval()
from qc_grader import grade_lab4_ex1
# Note that the grading function is expecting a complex number
grade_lab4_ex1(matmult_result)
from qiskit.opflow import CircuitSampler, PauliExpectation
sampler = CircuitSampler(q_instance)
# YOUR CODE HERE
sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
in_pauli_basis = PauliExpectation().convert(expectation)
shots_result = sampler.convert(in_pauli_basis).eval()
from qc_grader import grade_lab4_ex2
# Note that the grading function is expecting a complex number
grade_lab4_ex2(shots_result)
from qiskit.opflow import PauliExpectation, CircuitSampler
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
in_pauli_basis = PauliExpectation().convert(expectation)
sampler = CircuitSampler(q_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(in_pauli_basis, params=value_dict).eval()
return np.real(result)
eps = 0.2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('lin_comb') # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341])
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(q_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here!
return np.real(result)
# Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import GradientDescent
from qc_grader.gradient_descent import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate the gradient
initial_point=initial_point) # initial point
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='tab:red', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend();
from qiskit.opflow import NaturalGradient
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
natural_gradient = NaturalGradient(regularization='ridge').convert(expectation)
natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient)
sampler = CircuitSampler(q_instance, caching="all")
def evaluate_natural_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(natural_gradient, params=value_dict).eval()
return np.real(result)
print('Vanilla gradient:', evaluate_gradient(initial_point))
print('Natural gradient:', evaluate_natural_gradient(initial_point))
qng_loss = []
def qng_callback(nfevs, x, fx, stepsize):
qng_loss.append(fx)
qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback)
x_opt, fx_opt, nfevs = qng.optimize(initial_point.size,
evaluate_expectation,
gradient_function=evaluate_natural_gradient,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
from qc_grader.spsa import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback)
x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
# Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import QNSPSA
from qc_grader.qnspsa import QNSPSA
qnspsa_loss = []
def qnspsa_callback(nfev, x, fx, stepsize, accepted):
qnspsa_loss.append(fx)
fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation())
qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback)
x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
autospsa_loss = []
def autospsa_callback(nfev, x, fx, stepsize, accepted):
autospsa_loss.append(fx)
autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback)
x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X)
from qc_grader import grade_lab4_ex3
# Note that the grading function is expecting a Hamiltonian
grade_lab4_ex3(H_tfi)
from qiskit.circuit.library import EfficientSU2
efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2)
tfi_sampler = CircuitSampler(q_instance)
def evaluate_tfi(parameters):
exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2))
value_dict = dict(zip(efficient_su2.parameters, parameters))
result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval()
return np.real(result)
# target energy
tfi_target = -3.4939592074349326
# initial point for reproducibility
tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282,
0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126,
0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325,
0.48311132, 0.43623886, 0.6371297 ])
tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None)
tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init)
tfi_minimum = tfi_result[1]
print("Error:", np.abs(tfi_result[1] - tfi_target))
from qc_grader import grade_lab4_ex4
# Note that the grading function is expecting a floating point number
grade_lab4_ex4(tfi_minimum)
from qiskit_machine_learning.datasets import ad_hoc_data
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=20, test_size=10, n=2, one_hot=False, gap=0.5
)
# the training labels are in {0, 1} but we'll use {-1, 1} as class labels!
training_labels = 2 * training_labels - 1
test_labels = 2 * test_labels - 1
def plot_sampled_data():
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label in zip(test_features, test_labels):
marker = 's'
plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k')
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_sampled_data()
from qiskit.circuit.library import ZZFeatureMap
dim = 2
feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple!
feature_map.draw('mpl', style='iqx')
ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here!
ansatz.draw('mpl', style='iqx')
circuit = feature_map.compose(ansatz)
circuit.draw('mpl', style='iqx')
hamiltonian = Z ^ Z # global Z operators
gd_qnn_loss = []
def gd_qnn_callback(*args):
gd_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback)
from qiskit_machine_learning.neural_networks import OpflowQNN
qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
exp_val=PauliExpectation(),
gradient=Gradient(), # <-- Parameter-Shift gradients
quantum_instance=q_instance)
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
#initial_point = np.array([0.2, 0.1, 0.3, 0.4])
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)
classifier.fit(training_features, training_labels);
predicted = classifier.predict(test_features)
def plot_predicted():
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label, pred in zip(test_features, test_labels, predicted):
marker = 's'
color = 'tab:green' if pred == -1 else 'tab:blue'
if label != pred: # mark wrongly classified
plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5,
facecolor='none', edgecolor='tab:red')
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10),
Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10),
Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_predicted()
qng_qnn_loss = []
def qng_qnn_callback(*args):
qng_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients!
quantum_instance=q_instance)
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point)
classifier.fit(training_features, training_labels);
def plot_losses():
plt.figure(figsize=(12, 6))
plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients')
plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients')
plt.xlabel('iterations')
plt.ylabel('loss')
plt.legend(loc='best')
plot_losses()
from qiskit.opflow import I
def sample_gradients(num_qubits, reps, local=False):
"""Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions.
We sample 100 times for random parameters and compute the gradient of the first RY rotation gate.
"""
index = num_qubits - 1
# you can also exchange this for a local operator and observe the same!
if local:
operator = Z ^ Z ^ (I ^ (num_qubits - 2))
else:
operator = Z ^ num_qubits
# real amplitudes ansatz
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
# construct Gradient we want to evaluate for different values
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = Gradient().convert(expectation, params=ansatz.parameters[index])
# evaluate for 100 different, random parameter values
num_points = 100
grads = []
for _ in range(num_points):
# points are uniformly chosen from [0, pi]
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
from qiskit.opflow import NaturalGradient
def sample_natural_gradients(num_qubits, reps):
index = num_qubits - 1
operator = Z ^ num_qubits
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``.
# Hint: Check the ``sample_gradients`` function, this one is almost the same.
grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index])
num_points = 100
grads = []
for _ in range(num_points):
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients')
plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = 6
operator = Z ^ Z ^ (I ^ (num_qubits - 4))
def minimize(circuit, optimizer):
initial_point = np.random.random(circuit.num_parameters)
exp = StateFn(operator, is_measurement=True) @ StateFn(circuit)
grad = Gradient().convert(exp)
# pauli basis
exp = PauliExpectation().convert(exp)
grad = PauliExpectation().convert(grad)
sampler = CircuitSampler(q_instance, caching="all")
def loss(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(exp, values_dict).eval())
def gradient(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(grad, values_dict).eval())
return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point)
circuit = RealAmplitudes(4, reps=1, entanglement='linear')
circuit.draw('mpl', style='iqx')
circuit.reps = 5
circuit.draw('mpl', style='iqx')
def layerwise_training(ansatz, max_num_layers, optimizer):
optimal_parameters = []
fopt = None
for reps in range(1, max_num_layers):
ansatz.reps = reps
# bind already optimized parameters
values_dict = dict(zip(ansatz.parameters, optimal_parameters))
partially_bound = ansatz.bind_parameters(values_dict)
xopt, fopt, _ = minimize(partially_bound, optimizer)
print('Circuit depth:', ansatz.depth(), 'best value:', fopt)
optimal_parameters += list(xopt)
return fopt, optimal_parameters
ansatz = RealAmplitudes(4, entanglement='linear')
optimizer = GradientDescent(maxiter=50)
np.random.seed(12)
fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
4312/8192, 8155/8192
a,b,c,d = symbols('a b c d')
a, b, c, d
X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]); I = Matrix([[1,0],[0,1]])
X, Y, Z, I
rho = a*X+b*Y+c*Z+d*I; rho
tr(X*rho), simplify(tr(Y*rho)), tr(Z*rho), tr(I*rho),
pp=4260/8192; pop=4470/8192; p0=8158/8192; pp, pop, p0
Xav = 2*pp-1; Yav = 2*pop-1; Zav = 2*p0-1; Xav, Yav, Zav
def rho_1qb_tomo(Xav,Yav,Zav):
return (1/2)*(Xav*X+Yav*Y+Zav*Z+I)
rho = rho_1qb_tomo(Xav,Yav,Zav); rho, rho.eigenvects()
c00, a1, a2, a3, b1, b2, b3 = symbols('c_{00} a_1 a_2 a_3 b_1 b_2 b_3')
c11, c12, c13, c21,c22,c23,c31,c32,c33 = symbols('c_{11} c_{12} c_{13} c_{21} c_{22} c_{23} c_{31} c_{32} c_{33}')
c00, a1, a2, a3, b1, b2, b3, c11, c12, c13, c21,c22,c23,c31,c32,c33
rho = c00*tp(I,I) + a1*tp(X,I) + a2*tp(Y,I) + a3*tp(Z,I) + b1*tp(I,X) + b2*tp(I,Y) + b3*tp(I,Z)
rho += c11*tp(X,X) + c12*tp(X,Y) + c13*tp(X,Z) + c21*tp(Y,X) + c22*tp(Y,Y) + c23*tp(Y,Z)
rho += c31*tp(Z,X) + c32*tp(Z,Y) + c33*tp(Z,Z)
rho
tr(rho), tr(rho*tp(X,I)), simplify(tr(rho*tp(Y,I))), simplify(tr(rho*tp(Z,I))), \
simplify(tr(rho*tp(I,X))), simplify(tr(rho*tp(I,Y))), simplify(tr(rho*tp(I,Z))), \
tr(rho*tp(X,X)), simplify(tr(rho*tp(X,Y))), simplify(tr(rho*tp(X,Z))), \
simplify(tr(rho*tp(Y,X))), simplify(tr(rho*tp(Y,Y))), simplify(tr(rho*tp(Y,Z))), \
tr(rho*tp(Z,X)), simplify(tr(rho*tp(Z,Y))), simplify(tr(rho*tp(Z,Z)))
n = 137; N = 4**n-1; N-10**82
p00 = 3906/8192; p01 = 257/8192; p10 = 253/8192; p11 = 3776/8192; p00,p01,p10,p11
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.qi.qi import qft
import numpy as np
import copy
# Setting up a Hadamard QPE circuit for demonstrations below.
def h_qpe(circ, q, n):
for i in range(n-1):
circ.h(q[i])
for j in range(0, n-1, 2): # Only place a CH^n on every other qubit, because CX^n = I for n even
circ.ch(q[j], q[n-1])
circ.barrier()
qft(circ, q, n-1)
n = 5
qr = QuantumRegister(n)
cr = ClassicalRegister(n)
circuit = QuantumCircuit(qr, cr)
circuit.rx(np.pi/4, qr[n-1])
circuit.barrier()
h_qpe(circuit, qr, n)
unt_circ = copy.deepcopy(circuit)
circuit.barrier()
circuit.measure(qr, cr)
%%capture --no-display
from qiskit import BasicAer, LegacySimulators, Aer
qasm_backend = BasicAer.get_backend('qasm_simulator')
sv_backend = BasicAer.get_backend('statevector_simulator')
unt_backend = BasicAer.get_backend('unitary_simulator')
# Setup
from qiskit import execute
qasm_job = execute(circuit, qasm_backend)
sv_job = execute(unt_circ, sv_backend)
unt_job = execute(unt_circ, unt_backend)
qasm_result = qasm_job.result()
sv_result = sv_job.result()
unt_result = unt_job.result()
qasm_result.data()
sv_result.data()
unt_result.data()
# Not displayed because results are too large for github.
qasm_result.get_counts()
sv_result.get_statevector()
unt_result.get_unitary()
len(sv_result.get_statevector())
from qiskit import LegacySimulators
from qiskit.extensions.simulator.snapshot import snapshot
snap_backend = LegacySimulators.get_backend('statevector_simulator')
snap_unt_circ = copy.deepcopy(unt_circ)
snap_unt_circ.snapshot(10)
sv_job = execute(snap_unt_circ, snap_backend)
sv_result = sv_job.result()
sv_result.data()['snapshots']
from qiskit.quantum_info.analyzation.average import average_data
counts = qasm_result.get_counts()
iden = np.eye(len(counts))
oper = {}
for i, key in enumerate(counts.keys()):
oper[key] = iden[i]
average_data(counts, oper)
#!pip install qiskit-terra[visualization]
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.visualization.dag_visualization import dag_drawer
lin_len = 98
# Change to wider in Jupyter, this is only to render nicely in github
circuit.draw(line_length=lin_len)
style = {'cregbundle': True, 'usepiformat': True, 'subfontsize': 12, 'fold': 100, 'showindex': True,
'backgroundcolor': '#fffaff',
"displaycolor": { # Taken from qx_color_scheme() in _circuit_visualization.py
"id": "#ffca64",
"u0": "#f69458",
"u1": "#f69458",
"u2": "#f69458",
"u3": "#f69458",
"x": "#a6ce38",
"y": "#a6ce38",
"z": "#a6ce38",
"h": "#00bff2",
"s": "#00bff2",
"sdg": "#00bff2",
"t": "#ff6666",
"tdg": "#ff6666",
"rx": "#ffca64",
"ry": "#ffca64",
"rz": "#ffca64",
"reset": "#d7ddda",
"target": "#00bff2",
"meas": "#f070aa"}}
circuit.draw(output='mpl', style=style)
circuit.draw(output='latex_source', plot_barriers=False)
circuit.draw(output='latex', plot_barriers=False)
from qiskit import transpiler
draw_circ = transpiler.transpile(circuit, qasm_backend, basis_gates='U,CX')
draw_circ.draw(line_length=2000)
# Not shown in github for rendering reasons, load in Jupyter
from qiskit.tools.qi.qi import outer
from qiskit.tools.visualization import plot_histogram, plot_state_city, plot_bloch_multivector, plot_state_paulivec, plot_state_hinton, plot_state_qsphere
from qiskit.tools.visualization import iplot_histogram, iplot_state_city, iplot_bloch_multivector, iplot_state_paulivec, iplot_state_hinton, iplot_state_qsphere
counts = qasm_result.get_counts()
phi = sv_result.get_statevector()
rho = outer(phi)
plot_histogram(counts)
plot_state_city(rho)
plot_state_hinton(rho)
hist_fig = plot_histogram(counts)
state_fig = plot_state_city(rho)
hist_fig.savefig('histogram.png')
state_fig.savefig('state_plot.png')
iplot_bloch_multivector(rho)
# Not displayed in github, download and run loacally.
from qiskit.converters.circuit_to_dag import circuit_to_dag
my_dag = circuit_to_dag(circuit)
dag_drawer(my_dag)
job = execute(circuit, qasm_backend, shots=50, memory=True)
result = job.result()
result.get_memory(circuit)
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import BasicSwap, CXCancellation, LookaheadSwap, StochasticSwap
from qiskit.transpiler import transpile
from qiskit.mapper import CouplingMap
qr = QuantumRegister(7, 'q')
qr = QuantumRegister(7, 'q')
tpl_circuit = QuantumCircuit(qr)
tpl_circuit.h(qr[3])
tpl_circuit.cx(qr[0], qr[6])
tpl_circuit.cx(qr[6], qr[0])
tpl_circuit.cx(qr[0], qr[1])
tpl_circuit.cx(qr[3], qr[1])
tpl_circuit.cx(qr[3], qr[0])
tpl_circuit.draw()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
simulator = BasicAer.get_backend('qasm_simulator')
coupling_map = CouplingMap(couplinglist=coupling)
pass_manager = PassManager()
pass_manager.append([BasicSwap(coupling_map=coupling_map)])
basic_circ = transpile(tpl_circuit, simulator, pass_manager=pass_manager)
basic_circ.draw()
pass_manager = PassManager()
pass_manager.append([LookaheadSwap(coupling_map=coupling_map)])
lookahead_circ = transpile(tpl_circuit, simulator, pass_manager=pass_manager)
lookahead_circ.draw()
pass_manager = PassManager()
pass_manager.append([StochasticSwap(coupling_map=coupling_map)])
stoch_circ = transpile(tpl_circuit, simulator, pass_manager=pass_manager)
stoch_circ.draw()
qasm_job = execute(circuit, qasm_backend, pass_manager=PassManager())
from qiskit.converters.dag_to_circuit import dag_to_circuit
new_circ_from_dag = dag_to_circuit(my_dag)
new_circ_from_dag.draw(line_length = lin_len)
from qiskit import QuantumCircuit
qasm_str = circuit.qasm()
new_circ = QuantumCircuit.from_qasm_str(qasm_str)
new_circ.draw(line_length = lin_len)
filepath = 'my_qasm_file.txt'
qasm_file = open(filepath, "w")
qasm_file.write(unt_circ.qasm())
qasm_file.close()
new_unt_circ = QuantumCircuit.from_qasm_file(filepath)
new_unt_circ.draw(line_length = lin_len)
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Skip Qobj Validation"""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
from qiskit.exceptions import QiskitError
def _compare_dict(dict1, dict2):
equal = True
for key1, value1 in dict1.items():
if key1 not in dict2:
equal = False
break
if value1 != dict2[key1]:
equal = False
break
return equal
class TestSkipQobjValidation(QiskitAlgorithmsTestCase):
"""Test Skip Qobj Validation"""
def setUp(self):
super().setUp()
self.random_seed = 10598
# ┌───┐ ░ ┌─┐ ░
# q0_0: ┤ H ├──■───░─┤M├─░────
# └───┘┌─┴─┐ ░ └╥┘ ░ ┌─┐
# q0_1: ─────┤ X ├─░──╫──░─┤M├
# └───┘ ░ ║ ░ └╥┘
# c0: 2/══════════════╩═════╩═
# 0 1
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
# Ensure qubit 0 is measured before qubit 1
qc.barrier(qr)
qc.measure(qr[0], cr[0])
qc.barrier(qr)
qc.measure(qr[1], cr[1])
self.qc = qc
self.backend = BasicAer.get_backend("qasm_simulator")
def test_wo_backend_options(self):
"""without backend options test"""
with self.assertWarns(DeprecationWarning):
quantum_instance = QuantumInstance(
self.backend,
seed_transpiler=self.random_seed,
seed_simulator=self.random_seed,
shots=1024,
)
# run without backend_options and without noise
res_wo_bo = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertGreaterEqual(quantum_instance.time_taken, 0.0)
quantum_instance.reset_execution_results()
quantum_instance.skip_qobj_validation = True
res_wo_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertGreaterEqual(quantum_instance.time_taken, 0.0)
quantum_instance.reset_execution_results()
self.assertTrue(_compare_dict(res_wo_bo, res_wo_bo_skip_validation))
def test_w_backend_options(self):
"""with backend options test"""
# run with backend_options
with self.assertWarns(DeprecationWarning):
quantum_instance = QuantumInstance(
self.backend,
seed_transpiler=self.random_seed,
seed_simulator=self.random_seed,
shots=1024,
backend_options={"initial_statevector": [0.5, 0.5, 0.5, 0.5]},
)
res_w_bo = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertGreaterEqual(quantum_instance.time_taken, 0.0)
quantum_instance.reset_execution_results()
quantum_instance.skip_qobj_validation = True
res_w_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertGreaterEqual(quantum_instance.time_taken, 0.0)
quantum_instance.reset_execution_results()
self.assertTrue(_compare_dict(res_w_bo, res_w_bo_skip_validation))
def test_w_noise(self):
"""with noise test"""
# build noise model
# Asymmetric readout error on qubit-0 only
try:
from qiskit.providers.aer.noise import NoiseModel
from qiskit import Aer
self.backend = Aer.get_backend("qasm_simulator")
except ImportError as ex:
self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'")
return
probs_given0 = [0.9, 0.1]
probs_given1 = [0.3, 0.7]
noise_model = NoiseModel()
noise_model.add_readout_error([probs_given0, probs_given1], [0])
with self.assertWarns(DeprecationWarning):
quantum_instance = QuantumInstance(
self.backend,
seed_transpiler=self.random_seed,
seed_simulator=self.random_seed,
shots=1024,
noise_model=noise_model,
)
res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc)
quantum_instance.skip_qobj_validation = True
res_w_noise_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc)
self.assertTrue(_compare_dict(res_w_noise, res_w_noise_skip_validation))
with self.assertWarns(DeprecationWarning):
# BasicAer should fail:
with self.assertRaises(QiskitError):
_ = QuantumInstance(BasicAer.get_backend("qasm_simulator"), noise_model=noise_model)
with self.assertRaises(QiskitError):
quantum_instance = QuantumInstance(BasicAer.get_backend("qasm_simulator"))
quantum_instance.set_config(noise_model=noise_model)
if __name__ == "__main__":
unittest.main()
|
https://github.com/JouziP/MQITE
|
JouziP
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 6 12:26:49 2022
@author: pejmanjouzdani
"""
from qiskit import QuantumCircuit
def getUQUCirc(circ_U, circ_Q):
circ_UQU = QuantumCircuit.copy(circ_Q) ## QU|0>
circ_UQU = circ_UQU.compose(QuantumCircuit.copy(circ_U.inverse()) )## U^QU|0>
return circ_UQU ## U^QU|0>
|
https://github.com/mentesniker/Quantum-Cryptography
|
mentesniker
|
%matplotlib inline
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from random import randint
import hashlib
#These two functions were taken from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa
def tobits(s):
result = []
for c in s:
bits = bin(ord(c))[2:]
bits = '00000000'[len(bits):] + bits
result.extend([int(b) for b in bits])
return ''.join([str(x) for x in result])
def frombits(bits):
chars = []
for b in range(int(len(bits) / 8)):
byte = bits[b*8:(b+1)*8]
chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
return ''.join(chars)
#Alice cell, Bob can't see what's going in on here
m0 = tobits("I like dogs")
m1 = tobits("I like cats")
messageMerge = m0+m1
Alice_bases = [randint(0,1) for x in range(len(messageMerge))]
qubits = list()
for i in range(len(Alice_bases)):
mycircuit = QuantumCircuit(1,1)
if(Alice_bases[i] == 0):
if(messageMerge[i] == "1"):
mycircuit.x(0)
else:
if(messageMerge[i] == "0"):
mycircuit.h(0)
else:
mycircuit.x(0)
mycircuit.h(0)
qubits.append(mycircuit)
#Bob cell, Alice can't see what's going in on here
Bob_bases = [randint(0,1) for x in range(176)]
backend = Aer.get_backend('qasm_simulator')
measurements = list()
choice = 0
for i in range(len(Bob_bases)):
qubit = qubits[i]
if(Bob_bases[i] == 0):
qubit.measure(0,0)
else:
qubit.h(0)
qubit.measure(0,0)
result = execute(qubit, backend, shots=1, memory=True).result()
measurements.append(int(result.get_memory()[0]))
#Bob cell, Alice can't see what's going in on here
I0 = list()
I1 = list()
if(choice == 0):
for i in range(len(Alice_bases)):
if(Alice_bases[i] == Bob_bases[i]):
I0.append(i)
else:
I1.append(i)
else:
for i in range(len(Alice_bases)):
if(Alice_bases[i] == Bob_bases[i]):
I1.append(i)
else:
I0.append(i)
#Alice cell, Bob can't see what's going in on here
x0 = list()
for x in I0:
x0.append(messageMerge[x])
x1 = list()
for x in I1:
x1.append(messageMerge[x])
fx0 = ''.join(format(ord(i), 'b') for i in hashlib.sha224(''.join(x0).encode('utf-8')).hexdigest())
fx1 = ''.join(format(ord(i), 'b') for i in hashlib.sha224(''.join(x1).encode('utf-8')).hexdigest())
s0 = ''
s1 = ''
for bit in range(len(m0)):
s0 += str(int(fx0[bit]) ^ int(m0[bit]))
for bit in range(len(m1)):
s1 += str(int(fx1[bit]) ^ int(m1[bit]))
xB0 = list()
if(choice == 0):
for x in I0:
xB0.append(measurements[x])
else:
for x in I1:
xB0.append(measurements[x])
fxB0 = ''.join(format(ord(i), 'b') for i in hashlib.sha224(''.join([str(x) for x in xB0]).encode('utf-8')).hexdigest())
mB0 = bytearray()
if(choice == 0):
for bit in range(len(s0)):
mB0.append(int(fxB0[bit]) ^ int(s0[bit]))
print("Alice message was: " + frombits(mB0))
else:
for bit in range(len(s1)):
mB0.append(int(fxB0[bit]) ^ int(s1[bit]))
print("Alice message was: " + frombits(mB0))
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
!pip install pennylane
!pip install qiskit
import pennylane as qml
from pennylane.templates import AmplitudeEmbedding,BasisEmbedding,AngleEmbedding
import tensorflow as tf
from tensorflow import keras
device = qml.device('default.qubit', wires=2)
@qml.qnode(device)
def amplitude_circuit(inputs=None):
AmplitudeEmbedding(features=inputs, wires=range(2),normalize=True,pad_with=0.)
return qml.expval(qml.PauliZ(0))
@qml.qnode(device)
def basis_circuit(inputs=None):
BasisEmbedding(features=inputs, wires=range(2))
return qml.expval(qml.PauliZ(0))
@qml.qnode(device)
def angle_circuit(inputs=None):
AngleEmbedding(features=inputs, wires=range(2))
return qml.expval(qml.PauliZ(0))
inputs=[0.05,0.43]
z_a=amplitude_circuit(inputs)
z_an=angle_circuit(inputs)
print(f"Amplitude Embeddings: {z_a}")
print(f"Amplitude Embeddings: {z_an}")
from qiskit.visualization import plot_bloch_vector
%matplotlib inline
rot_1=[0,0,z_a]
rot_2=[0,0,z_an]
print("Bloch sphere for Amplitude Embedding")
plot_bloch_vector([rot_1], title="Bloch Sphere")
print("Bloch sphere for Angle Embedding")
plot_bloch_vector([rot_2], title="Bloch Sphere")
print("For Basis Embeddings, we need to encode n binary features to a basis state of n qubits.")
input_basis=[1,0]
z_b=basis_circuit(input_basis)
print(z_b)
print("Bloch sphere for Basis Embedding")
plot_bloch_vector([0,0,z_b], title="Bloch Sphere")
import tensorflow as tf
from tensorflow import keras
import os
from datetime import datetime
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
assert x_train.shape == (60000, 28, 28)
assert x_test.shape == (10000, 28, 28)
assert y_train.shape == (60000,)
assert y_test.shape == (10000,)
%load_ext tensorboard
%tensorboard --logdir logs/scalars/
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S"),
histogram_freq=0,
write_graph=True,
write_grads=True
)
'''Cerate 2 qubit node circuit with angle embedding and entangled layers'''
n_qubits = 2
@qml.qnode(device)
def qnode(inputs, weights):
qml.templates.AngleEmbedding(inputs, wires=range(n_qubits))
qml.templates.BasicEntanglerLayers(weights, wires=range(n_qubits))
return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]
def create_CQC_model(x_train,y_train,x_test,y_test):
'''Convert the q node circuit into a keras layer with a weight mapping'''
n_layers = 6
weight_shapes = {"weights": (n_layers, n_qubits)}
qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=n_qubits)
'''Initial layers for flattening the Image inputs and compress the features to pass it through the 2-bit node '''
clayer_0 = tf.keras.layers.Flatten(input_shape=(28,28))
clayer_1=tf.keras.layers.Dense(2)
'''Terminal layer with softmax activation for classification'''
clayer_2 = tf.keras.layers.Dense(10, activation="softmax")
model = tf.keras.models.Sequential([clayer_0,clayer_1,qlayer, clayer_2])
opt = tf.keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss="mae", metrics=["accuracy"])
model.fit(x_train,y_train,batch_size=128,epochs=10,verbose=2,validation_data=(x_test,y_test),callbacks=[tensorboard_callback])
model.summary()
'''Testing circuit on a small batch '''
x_train_n,y_train_n,x_test_n,y_test_n=x_train[:1000],y_train[:1000],x_test[:1000],y_test[:1000]
create_CQC_model(x_train_n,y_train_n,x_test_n,y_test_n)
import random
%load_ext tensorboard
%tensorboard --logdir logs/scalars/
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S"),
histogram_freq=0,
write_graph=True,
write_grads=True
)
n_qubits = 9
n_layer_steps = 3
n_layers_to_add = 2
batch_size = 128
epochs = 5
device = qml.device("default.qubit", wires=n_qubits)
def random_gates(n_qubits):
gates = [qml.RX, qml.RY, qml.RZ]
chosen_gates = []
for i in range(n_qubits):
chosen_gate = random.choice(gates)
chosen_gates.append(chosen_gate)
return chosen_gates
def apply_layer(gates, weights):
for i in range(n_qubits):
gates[i](weights[i], wires = i)
for i in range(n_qubits-1):
qml.CZ(wires=[i, i+1])
def apply_frozen_layers(frozen_layer_gates, frozen_layer_weights):
for i in range(len(frozen_layer_gates)):
apply_layer(frozen_layer_gates[i], frozen_layer_weights[i])
@qml.qnode(device,interface='tf')
def qnode(inputs,weights):
layer_gates = []
layer_weights = []
AngleEmbedding(inputs, wires=range(n_qubits))
# Apply frozen layers
new_gates = [random_gates(n_qubits) for i in range(n_layers_to_add)]
apply_frozen_layers(layer_gates, layer_weights)
# Apply layers with trainable parameters
for i in range(n_layers_to_add):
apply_layer(new_gates[i], weights[i])
# Expectation value of the last qubit
return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]
def create_CQC_frozen_model(x_train,y_train):
'''Convert the q node circuit into a keras layer with a weight mapping'''
# n_layers_to_add = 10
# Define shape of the weights
weight_shapes = {"weights": (n_layers_to_add, n_qubits)}
qlayer = qml.qnn.KerasLayer(qnode, weight_shapes,output_dim=n_qubits)
'''Initial layers for flattening the Image inputs and compress the features to pass it through the 2-bit node '''
clayer_0 = tf.keras.layers.Flatten(input_shape=(28,28))
clayer_1=tf.keras.layers.Dense(2)
'''Terminal layer with softmax activation for classification'''
clayer_2 = tf.keras.layers.Dense(2, activation="sigmoid")
model = tf.keras.models.Sequential([clayer_0,clayer_1,qlayer, clayer_2])
opt = tf.keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss="mae", metrics=["accuracy"])
print(model.summary())
model.fit(x_train,y_train,batch_size=128,epochs=10,verbose=2,callbacks=[tensorboard_callback])
model.summary()
'''Testing circuit on a small batch '''
#x_train_n,y_train_n,x_test_n,y_test_n=x_train[:1000],y_train[:1000],x_test[:1000],y_test[:1000]
create_CQC_frozen_model(modif_x_train,modif_y_train)
import numpy as np
import tensorflow as tf
from tensorflow import keras
import os
from datetime import datetime
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
assert x_train.shape == (60000, 28, 28)
assert x_test.shape == (10000, 28, 28)
assert y_train.shape == (60000,)
assert y_test.shape == (10000,)
modif_x_train=[]
modif_y_train=[]
for i in range(len(y_train)):
if y_train[i]==4:
modif_y_train.append(0)
modif_x_train.append(x_train[i])
elif y_train[i]==8:
modif_y_train.append(0)
modif_x_train.append(x_train[i])
modif_x_train,modif_y_train=np.asarray(modif_x_train),np.asarray(modif_y_train)
modif_x_train.shape,modif_y_train.shape,y_train.shape,x_train.shape
|
https://github.com/Cryoris/surfer
|
Cryoris
|
import numpy as np
from time import time
from qiskit import IBMQ, Aer
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.circuit.library import EfficientSU2, RealAmplitudes
from qiskit.opflow import QFI, StateFn, PauliExpectation, CircuitSampler
from surfer.qfi import OverlapQFI, ReverseQFI
# num_qubits = 27
# coupling_map = [
# (0, 1), (4, 7), (10, 12), (15, 18), (21, 23), (24, 25),
# (22, 19), (16, 14), (11, 8), (5, 3),
# ] + [
# (1, 4), (7, 6), (12, 13), (18, 17), (23, 24), (25, 26),
# (19, 20), (14, 11), (8, 9), (3, 2)
# ] + [
# (7, 10), (12, 15), (18, 21), (25, 22), (19, 16),
# (13, 14), (8, 5), (2, 1)
# ]
num_qubits = 20
reps = 1
circuit = EfficientSU2(num_qubits, reps=reps, entanglement="pairwise").decompose()
# circuit = RealAmplitudes(num_qubits, reps=reps, entanglement=coupling_map).decompose()
parameters = circuit.parameters
values = np.zeros(circuit.num_parameters)
# for i in range(circuit.num_qubits):
# values[~i] = np.pi / 2
# start = time()
# qfi = ReverseQFI(do_checks=False).compute(circuit, values)
# time_taken = time() - start
# print(time_taken)
# print(qfi)
start = time()
qgt = OverlapQFI(clifford=True).compute(circuit, values) / 4
time_taken = time() - start
print(time_taken)
print(qgt)
# np.save("qfi_cliff_realamp_plus_kolkata.npy", qfi)
# np.save("qfi_cliff_realamp_+_kolkata.npy", qfi)
np.save("qgt_line20_esu2_pairwise_0.npy", qgt)
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
G
labels = nx.get_edge_attributes(G,'weight')
labels
import json
# Array of JSON Objects
products = [{"name": "HDD", "brand": "Samsung", "price": "$100"},
{"name": "Monitor", "brand": "Dell", "price": "$120"},
{"name": "Mouse", "brand": "Logitech", "price": "$10"}]
# Print the original data
print("The original JSON data:\n{0}".format(products))
# Sort the JSON data based on the value of the brand key
products.sort(key=lambda x: x["price"])
# Print the sorted JSON data
print("The sorted JSON data based on the value of the brand:\n{0}".format(products))
_LAMBDA
UNIFORM_CONVERGENCE_SAMPLE
import json
# Array of JSON Objects
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
# Print the sorted JSON data
UNIFORM_CONVERGENCE_SAMPLE
np.max(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - UNIFORM_CONVERGENCE_SAMPLE[220]["probabilities"])
# generamos las distancias entre para la convergencia uniforme
index = -1
for sample in UNIFORM_CONVERGENCE_SAMPLE:
mean = sample["mean"]
index += 1
distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"]))
UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state
UNIFORM_CONVERGENCE_SAMPLE
import csv
header = ['iteration', 'state', 'probability', 'mean']
header_q = ['iteration', 'distance']
with open('qaoa_cu.csv', 'w', encoding='UTF8') as f:
with open('qaoa_distance.csv', 'w', encoding='UTF8') as q:
writer = csv.writer(f)
writer_q = csv.writer(q)
# write the header
writer.writerow(header)
writer_q.writerow(header_q)
iteration = 0
for sample in UNIFORM_CONVERGENCE_SAMPLE:
iteration += 1
mean = sample["mean"]
distance = sample["distance_pgs"]
state = 0
for probability in sample["probabilities"]:
state += 1
# write the data
data = [iteration, state, probability, mean]
writer.writerow(data)
writer_q.writerow([iteration, distance])
#plot_histogram(job_2, color='midnightblue', title=str(mean), figsize=(30, 5)).savefig(str(contador) + "_2.png")
#print(sample["mean"])
plot_histogram(job_2, color='midnightblue', title="New Histogram", figsize=(30, 5)).savefig('out.png')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
|
https://github.com/0tt3r/QuaC-qiskit
|
0tt3r
|
# -*- coding: utf-8 -*-
"""Demonstrates plugin noise model optimization abilities by recovering T1 noise from an ideal
user-defined noise model.
"""
from qiskit import IBMQ
from quac_qiskit import Quac
from qiskit.test.mock import FakeBurlington
from qiskit.ignis.characterization.coherence import t1_circuits, t2_circuits
from quac_qiskit.optimization import *
from quac_qiskit.models import QuacNoiseModel
def main():
# Get backends
IBMQ.load_account()
provider = IBMQ.get_provider(hub="ibm-q-ornl", group="anl", project="chm168")
backend = provider.get_backend("ibmq_burlington")
plugin_backend = Quac.get_backend("fake_burlington_density_simulator", t1=True, t2=True, meas=False, zz=False)
# Get calibration circuits
hardware_properties = FakeBurlington().properties()
num_gates = np.linspace(10, 500, 30, dtype='int')
qubits = list(range(len(backend.properties().qubits)))
t1_circs, t1_delay = t1_circuits(num_gates,
hardware_properties.gate_length('id', [0]) * 1e9,
qubits)
t2_circs, t2_delay = t2_circuits((num_gates / 2).astype('int'),
hardware_properties.gate_length('id', [0]) * 1e9,
qubits)
# Formulate real noise model
real_noise_model = QuacNoiseModel(
t1_times=[1234, 2431, 2323, 2222, 3454],
t2_times=[12000, 14000, 14353, 20323, 30232]
)
# Formulate initial guess noise model (only same order of magnitude)
guess_noise_model = QuacNoiseModel(
t1_times=[1000, 1000, 1000, 1000, 1000],
t2_times=[10000, 10000, 10000, 10000, 10000]
)
# Calculate calibration circuit reference results
reference_job = execute(t1_circs + t2_circs, plugin_backend,
quac_noise_model=real_noise_model,
optimization_level=0)
reference_result = reference_job.result()
# Calculate optimized noise model
new_noise_model = optimize_noise_model_ng(
guess_noise_model=guess_noise_model,
circuits=t1_circs + t2_circs,
backend=plugin_backend,
reference_result=reference_result,
loss_function=angle_objective_function
)
# Show original noise model and optimized noise model
print(f"Original noise model: {real_noise_model}")
print(f"New noise model: {new_noise_model}")
if __name__ == '__main__':
main()
|
https://github.com/PavanCyborg/Quantum-Algorithms-Benchmarking
|
PavanCyborg
|
#Assign these values as per your requirements.
global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion
min_qubits=2
max_qubits=18
skip_qubits=1
max_circuits=3
num_shots=1000
Noise_Inclusion = False
saveplots = False
Memory_utilization_plot = True
gate_counts_plots = True
ype_of_Simulator = "FAKEV2" #Inputs are "built_in" or "FAKE" or "FAKEV2"
backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends
#Change your Specification of Simulator in Declaring Backend Section
#By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2()
import numpy as np
import copy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute
import time
import matplotlib.pyplot as plt
# Import from Qiskit Aer noise module
from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error)
# Benchmark Name
benchmark_name = "Phase Estimation"
# Selection of basis gate set for transpilation
# Note: selector 1 is a hardware agnostic gate set
basis_selector = 1
basis_gates_array = [
[],
['rx', 'ry', 'rz', 'cx'], # a common basis set, default
['cx', 'rz', 'sx', 'x'], # IBM default basis set
['rx', 'ry', 'rxx'], # IonQ default basis set
['h', 'p', 'cx'], # another common basis set
['u', 'cx'] # general unitaries basis gates
]
np.random.seed(0)
num_gates = 0
depth = 0
def get_QV(backend):
import json
# Assuming backend.conf_filename is the filename and backend.dirname is the directory path
conf_filename = backend.dirname + "/" + backend.conf_filename
# Open the JSON file
with open(conf_filename, 'r') as file:
# Load the JSON data
data = json.load(file)
# Extract the quantum_volume parameter
QV = data.get('quantum_volume', None)
return QV
def checkbackend(backend_name,Type_of_Simulator):
if Type_of_Simulator == "built_in":
available_backends = []
for i in Aer.backends():
available_backends.append(i.name)
if backend_name in available_backends:
platform = backend_name
return platform
else:
print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!")
print(f"available backends are : {available_backends}")
platform = "qasm_simulator"
return platform
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2":
import qiskit.providers.fake_provider as fake_backends
if hasattr(fake_backends,backend_name) is True:
print(f"Backend {backend_name} is available for type {Type_of_Simulator}.")
backend_class = getattr(fake_backends,backend_name)
backend_instance = backend_class()
return backend_instance
else:
print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!")
if Type_of_Simulator == "FAKEV2":
backend_class = getattr(fake_backends,"FakeSantiagoV2")
else:
backend_class = getattr(fake_backends,"FakeSantiago")
backend_instance = backend_class()
return backend_instance
if Type_of_Simulator == "built_in":
platform = checkbackend(backend_name,Type_of_Simulator)
#By default using "Qasm Simulator"
backend = Aer.get_backend(platform)
QV_=None
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"backend version is {backend.backend_version}")
elif Type_of_Simulator == "FAKE":
basis_selector = 0
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting.
max_qubits=backend.configuration().n_qubits
print(f"{platform} device is capable of running {backend.configuration().n_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
elif Type_of_Simulator == "FAKEV2":
basis_selector = 0
if "V2" not in backend_name:
backend_name = backend_name+"V2"
backend = checkbackend(backend_name,Type_of_Simulator)
QV_ = get_QV(backend)
platform = backend.name +"-" +backend.backend_version
max_qubits=backend.num_qubits
print(f"{platform} device is capable of running {backend.num_qubits}")
print(f"{platform} has QV={QV_}")
if max_qubits > 30:
print(f"Device is capable with max_qubits = {max_qubits}")
max_qubit = 30
print(f"Using fake backend {platform} with max_qubits {max_qubits}")
else:
print("Enter valid Simulator.....")
# saved subcircuits circuits for printing
QC_ = None
QFTI_ = None
U_ = None
############### Circuit Definition
def PhaseEstimation(num_qubits, theta):
qr = QuantumRegister(num_qubits)
num_counting_qubits = num_qubits - 1 # only 1 state qubit
cr = ClassicalRegister(num_counting_qubits)
qc = QuantumCircuit(qr, cr, name=f"qpe-{num_qubits}-{theta}")
# initialize counting qubits in superposition
for i in range(num_counting_qubits):
qc.h(qr[i])
# change to |1> in state qubit, so phase will be applied by cphase gate
qc.x(num_counting_qubits)
qc.barrier()
repeat = 1
for j in reversed(range(num_counting_qubits)):
# controlled operation: adds phase exp(i*2*pi*theta*repeat) to the state |1>
# does nothing to state |0>
cp, _ = CPhase(2*np.pi*theta, repeat)
qc.append(cp, [j, num_counting_qubits])
repeat *= 2
#Define global U operator as the phase operator
_, U = CPhase(2*np.pi*theta, 1)
qc.barrier()
# inverse quantum Fourier transform only on counting qubits
qc.append(inv_qft_gate(num_counting_qubits), qr[:num_counting_qubits])
qc.barrier()
# measure counting qubits
qc.measure([qr[m] for m in range(num_counting_qubits)], list(range(num_counting_qubits)))
# save smaller circuit example for display
global QC_, U_, QFTI_
if QC_ == None or num_qubits <= 5:
if num_qubits < 9: QC_ = qc
if U_ == None or num_qubits <= 5:
if num_qubits < 9: U_ = U
if QFTI_ == None or num_qubits <= 5:
if num_qubits < 9: QFTI_ = inv_qft_gate(num_counting_qubits)
return qc
#Construct the phase gates and include matching gate representation as readme circuit
def CPhase(angle, exponent):
qc = QuantumCircuit(1, name=f"U^{exponent}")
qc.p(angle*exponent, 0)
phase_gate = qc.to_gate().control(1)
return phase_gate, qc
############### Inverse QFT Circuit
def inv_qft_gate(input_size):
global QFTI_, num_gates, depth
qr = QuantumRegister(input_size); qc = QuantumCircuit(qr, name="inv_qft")
# Generate multiple groups of diminishing angle CRZs and H gate
for i_qubit in reversed(range(0, input_size)):
# start laying out gates from highest order qubit (the hidx)
hidx = input_size - i_qubit - 1
# precede with an H gate (applied to all qubits)
qc.h(qr[hidx])
num_gates += 1
depth += 1
# if not the highest order qubit, add multiple controlled RZs of decreasing angle
if hidx < input_size - 1:
num_crzs = i_qubit
for j in reversed(range(0, num_crzs)):
divisor = 2 ** (num_crzs - j)
qc.crz( -math.pi / divisor , qr[hidx], qr[input_size - j - 1])
num_gates += 1
depth += 1
qc.barrier()
if QFTI_ == None or input_size <= 5:
if input_size < 9: QFTI_= qc
return qc
# Create an empty noise model
noise_parameters = NoiseModel()
if Type_of_Simulator == "built_in":
# Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5%
depol_one_qb_error = 0.05
depol_two_qb_error = 0.005
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx'])
# Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0%
amp_damp_one_qb_error = 0.0
amp_damp_two_qb_error = 0.0
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz'])
noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx'])
# Add reset noise to all single qubit resets
reset_to_zero_error = 0.005
reset_to_one_error = 0.005
noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"])
# Add readout error
p0given1_error = 0.000
p1given0_error = 0.000
error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]])
noise_parameters.add_all_qubit_readout_error(error_meas)
#print(noise_parameters)
elif Type_of_Simulator == "FAKE"or"FAKEV2":
noise_parameters = NoiseModel.from_backend(backend)
#print(noise_parameters)
### Analysis methods to be expanded and eventually compiled into a separate analysis.py file
import math, functools
def hellinger_fidelity_with_expected(p, q):
""" p: result distribution, may be passed as a counts distribution
q: the expected distribution to be compared against
References:
`Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_
Qiskit Hellinger Fidelity Function
"""
p_sum = sum(p.values())
q_sum = sum(q.values())
if q_sum == 0:
print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0")
return 0
p_normed = {}
for key, val in p.items():
p_normed[key] = val/p_sum
# if p_sum != 0:
# p_normed[key] = val/p_sum
# else:
# p_normed[key] = 0
q_normed = {}
for key, val in q.items():
q_normed[key] = val/q_sum
total = 0
for key, val in p_normed.items():
if key in q_normed.keys():
total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2
del q_normed[key]
else:
total += val
total += sum(q_normed.values())
# in some situations (error mitigation) this can go negative, use abs value
if total < 0:
print(f"WARNING: using absolute value in fidelity calculation")
total = abs(total)
dist = np.sqrt(total)/np.sqrt(2)
fidelity = (1-dist**2)**2
return fidelity
def polarization_fidelity(counts, correct_dist, thermal_dist=None):
"""
Combines Hellinger fidelity and polarization rescaling into fidelity calculation
used in every benchmark
counts: the measurement outcomes after `num_shots` algorithm runs
correct_dist: the distribution we expect to get for the algorithm running perfectly
thermal_dist: optional distribution to pass in distribution from a uniform
superposition over all states. If `None`: generated as
`uniform_dist` with the same qubits as in `counts`
returns both polarization fidelity and the hellinger fidelity
Polarization from: `https://arxiv.org/abs/2008.11294v1`
"""
num_measured_qubits = len(list(correct_dist.keys())[0])
#print(num_measured_qubits)
counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()}
# calculate hellinger fidelity between measured expectation values and correct distribution
hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist)
# to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits
if num_measured_qubits > 16:
return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity }
# if not provided, generate thermal dist based on number of qubits
if thermal_dist == None:
thermal_dist = uniform_dist(num_measured_qubits)
# set our fidelity rescaling value as the hellinger fidelity for a depolarized state
floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist)
# rescale fidelity result so uniform superposition (random guessing) returns fidelity
# rescaled to 0 to provide a better measure of success of the algorithm (polarization)
new_floor_fidelity = 0
fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity)
return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity }
## Uniform distribution function commonly used
def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity):
"""
Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks
fidelity: raw fidelity to rescale
floor_fidelity: threshold fidelity which is equivalent to random guessing
new_floor_fidelity: what we rescale the floor_fidelity to
Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0:
1 -> 1;
0.25 -> 0;
0.5 -> 0.3333;
"""
rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1
# ensure fidelity is within bounds (0, 1)
if rescaled_fidelity < 0:
rescaled_fidelity = 0.0
if rescaled_fidelity > 1:
rescaled_fidelity = 1.0
return rescaled_fidelity
def uniform_dist(num_state_qubits):
dist = {}
for i in range(2**num_state_qubits):
key = bin(i)[2:].zfill(num_state_qubits)
dist[key] = 1/(2**num_state_qubits)
return dist
from matplotlib.patches import Rectangle
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize
from matplotlib.patches import Circle
############### Color Map functions
# Create a selection of colormaps from which to choose; default to custom_spectral
cmap_spectral = plt.get_cmap('Spectral')
cmap_greys = plt.get_cmap('Greys')
cmap_blues = plt.get_cmap('Blues')
cmap_custom_spectral = None
# the default colormap is the spectral map
cmap = cmap_spectral
cmap_orig = cmap_spectral
# current cmap normalization function (default None)
cmap_norm = None
default_fade_low_fidelity_level = 0.16
default_fade_rate = 0.7
# Specify a normalization function here (default None)
def set_custom_cmap_norm(vmin, vmax):
global cmap_norm
if vmin == vmax or (vmin == 0.0 and vmax == 1.0):
print("... setting cmap norm to None")
cmap_norm = None
else:
print(f"... setting cmap norm to [{vmin}, {vmax}]")
cmap_norm = Normalize(vmin=vmin, vmax=vmax)
# Remake the custom spectral colormap with user settings
def set_custom_cmap_style(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
#print("... set custom map style")
global cmap, cmap_custom_spectral, cmap_orig
cmap_custom_spectral = create_custom_spectral_cmap(
fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate)
cmap = cmap_custom_spectral
cmap_orig = cmap_custom_spectral
# Create the custom spectral colormap from the base spectral
def create_custom_spectral_cmap(
fade_low_fidelity_level=default_fade_low_fidelity_level,
fade_rate=default_fade_rate):
# determine the breakpoint from the fade level
num_colors = 100
breakpoint = round(fade_low_fidelity_level * num_colors)
# get color list for spectral map
spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)]
#print(fade_rate)
# create a list of colors to replace those below the breakpoint
# and fill with "faded" color entries (in reverse)
low_colors = [0] * breakpoint
#for i in reversed(range(breakpoint)):
for i in range(breakpoint):
# x is index of low colors, normalized 0 -> 1
x = i / breakpoint
# get color at this index
bc = spectral_colors[i]
r0 = bc[0]
g0 = bc[1]
b0 = bc[2]
z0 = bc[3]
r_delta = 0.92 - r0
#print(f"{x} {bc} {r_delta}")
# compute saturation and greyness ratio
sat_ratio = 1 - x
#grey_ratio = 1 - x
''' attempt at a reflective gradient
if i >= breakpoint/2:
xf = 2*(x - 0.5)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (yf + 0.5)
else:
xf = 2*(0.5 - x)
yf = pow(xf, 1/fade_rate)/2
grey_ratio = 1 - (0.5 - yf)
'''
grey_ratio = 1 - math.pow(x, 1/fade_rate)
#print(f" {xf} {yf} ")
#print(f" {sat_ratio} {grey_ratio}")
r = r0 + r_delta * sat_ratio
g_delta = r - g0
b_delta = r - b0
g = g0 + g_delta * grey_ratio
b = b0 + b_delta * grey_ratio
#print(f"{r} {g} {b}\n")
low_colors[i] = (r,g,b,z0)
#print(low_colors)
# combine the faded low colors with the regular spectral cmap to make a custom version
cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:])
#spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)]
#for i in range(10): print(spectral_colors[i])
#print("")
return cmap_custom_spectral
# Make the custom spectral color map the default on module init
set_custom_cmap_style()
# Arrange the stored annotations optimally and add to plot
def anno_volumetric_data(ax, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True):
# sort all arrays by the x point of the text (anno_offs)
global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos
all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos))
x_anno_offs = [a for a,b,c,d,e in all_annos]
y_anno_offs = [b for a,b,c,d,e in all_annos]
anno_labels = [c for a,b,c,d,e in all_annos]
x_annos = [d for a,b,c,d,e in all_annos]
y_annos = [e for a,b,c,d,e in all_annos]
#print(f"{x_anno_offs}")
#print(f"{y_anno_offs}")
#print(f"{anno_labels}")
for i in range(len(anno_labels)):
x_anno = x_annos[i]
y_anno = y_annos[i]
x_anno_off = x_anno_offs[i]
y_anno_off = y_anno_offs[i]
label = anno_labels[i]
if i > 0:
x_delta = abs(x_anno_off - x_anno_offs[i - 1])
y_delta = abs(y_anno_off - y_anno_offs[i - 1])
if y_delta < 0.7 and x_delta < 2:
y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6
#x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1
ax.annotate(label,
xy=(x_anno+0.0, y_anno+0.1),
arrowprops=dict(facecolor='black', shrink=0.0,
width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)),
xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]),
rotation=labelrot,
horizontalalignment='left', verticalalignment='baseline',
color=(0.2,0.2,0.2),
clip_on=True)
if saveplots == True:
plt.savefig("VolumetricPlotSample.jpg")
# Plot one group of data for volumetric presentation
def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth',
labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True,
x_size=1.0, y_size=1.0, zorder=1, offset_flag=False,
max_depth=0, suppress_low_fidelity=False):
# since data may come back out of order, save point at max y for annotation
i_anno = 0
x_anno = 0
y_anno = 0
# plot data rectangles
low_fidelity_count = True
last_y = -1
k = 0
# determine y-axis dimension for one pixel to use for offset of bars that start at 0
(_, dy) = get_pixel_dims(ax)
# do this loop in reverse to handle the case where earlier cells are overlapped by later cells
for i in reversed(range(len(d_data))):
x = depth_index(d_data[i], depth_base)
y = float(w_data[i])
f = f_data[i]
# each time we star a new row, reset the offset counter
# DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars
# that represent time starting from 0 secs. We offset by one pixel each and center the group
if y != last_y:
last_y = y;
k = 3 # hardcoded for 8 cells, offset by 3
#print(f"{i = } {x = } {y = }")
if max_depth > 0 and d_data[i] > max_depth:
#print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}")
break;
# reject cells with low fidelity
if suppress_low_fidelity and f < suppress_low_fidelity_level:
if low_fidelity_count: break
else: low_fidelity_count = True
# the only time this is False is when doing merged gradation plots
if do_border == True:
# this case is for an array of x_sizes, i.e. each box has different width
if isinstance(x_size, list):
# draw each of the cells, with no offset
if not offset_flag:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder))
# use an offset for y value, AND account for x and width to draw starting at 0
else:
ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder))
# this case is for only a single cell
else:
ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size))
# save the annotation point with the largest y value
if y >= y_anno:
x_anno = x
y_anno = y
i_anno = i
# move the next bar down (if using offset)
k -= 1
# if no data rectangles plotted, no need for a label
if x_anno == 0 or y_anno == 0:
return
x_annos.append(x_anno)
y_annos.append(y_anno)
anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 )
# adjust radius of annotation circle based on maximum width of apps
anno_max = 10
if w_max > 10:
anno_max = 14
if w_max > 14:
anno_max = 18
scale = anno_max / anno_dist
# offset of text from end of arrow
if scale > 1:
x_anno_off = scale * x_anno - x_anno - 0.5
y_anno_off = scale * y_anno - y_anno
else:
x_anno_off = 0.7
y_anno_off = 0.5
x_anno_off += x_anno
y_anno_off += y_anno
# print(f"... {xx} {yy} {anno_dist}")
x_anno_offs.append(x_anno_off)
y_anno_offs.append(y_anno_off)
anno_labels.append(label)
if do_label:
ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot,
horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2))
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# init arrays to hold annotation points for label spreading
def vplot_anno_init ():
global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels
x_annos = []
y_annos = []
x_anno_offs = []
y_anno_offs = []
anno_labels = []
# Number of ticks on volumetric depth axis
max_depth_log = 22
# average transpile factor between base QV depth and our depth based on results from QV notebook
QV_transpile_factor = 12.7
# format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1
# (sign handling may be incorrect)
def format_number(num, digits=0):
if isinstance(num, str): num = float(num)
num = float('{:.3g}'.format(abs(num)))
sign = ''
metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1}
for index in metric:
num_check = num / metric[index]
if num_check >= 1:
num = round(num_check, digits)
sign = index
break
numstr = f"{str(num)}"
if '.' in numstr:
numstr = numstr.rstrip('0').rstrip('.')
return f"{numstr}{sign}"
# Return the color associated with the spcific value, using color map norm
def get_color(value):
# if there is a normalize function installed, scale the data
if cmap_norm:
value = float(cmap_norm(value))
if cmap == cmap_spectral:
value = 0.05 + value*0.9
elif cmap == cmap_blues:
value = 0.00 + value*1.0
else:
value = 0.0 + value*0.95
return cmap(value)
# Return the x and y equivalent to a single pixel for the given plot axis
def get_pixel_dims(ax):
# transform 0 -> 1 to pixel dimensions
pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0))
xpix = pixdims[1][0]
ypix = pixdims[0][1]
#determine x- and y-axis dimension for one pixel
dx = (1 / xpix)
dy = (1 / ypix)
return (dx, dy)
############### Helper functions
# return the base index for a circuit depth value
# take the log in the depth base, and add 1
def depth_index(d, depth_base):
if depth_base <= 1:
return d
if d == 0:
return 0
return math.log(d, depth_base) + 1
# draw a box at x,y with various attributes
def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1):
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5*y_size,
zorder=zorder)
# draw a circle at x,y with various attributes
def circle_at(x, y, value, type=1, fill=True):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.5,0.5,0.5)
return Circle((x, y), size/2,
alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.5)
def box4_at(x, y, value, type=1, fill=True, alpha=1.0):
size = 1.0
value = min(value, 1.0)
value = max(value, 0.0)
fc = get_color(value)
ec = (0.3,0.3,0.3)
ec = fc
return Rectangle((x - size/8, y - size/2), size/4, size,
alpha=alpha,
edgecolor = ec,
facecolor = fc,
fill=fill,
lw=0.1)
# Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value
def qv_box_at(x, y, qv_width, qv_depth, value, depth_base):
#print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}")
return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width,
edgecolor = (value,value,value),
facecolor = (value,value,value),
fill=True,
lw=1)
def bkg_box_at(x, y, value=0.9):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (value,value,value),
fill=True,
lw=0.5)
def bkg_empty_box_at(x, y):
size = 0.6
return Rectangle((x - size/2, y - size/2), size, size,
edgecolor = (.75,.75,.75),
facecolor = (1.0,1.0,1.0),
fill=True,
lw=0.5)
# Plot the background for the volumetric analysis
def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"):
if suptitle == None:
suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}"
QV0 = QV
qv_estimate = False
est_str = ""
if QV == 0: # QV = 0 indicates "do not draw QV background or label"
QV = 2048
elif QV < 0: # QV < 0 indicates "add est. to label"
QV = -QV
qv_estimate = True
est_str = " (est.)"
if avail_qubits > 0 and max_qubits > avail_qubits:
max_qubits = avail_qubits
max_width = 13
if max_qubits > 11: max_width = 18
if max_qubits > 14: max_width = 20
if max_qubits > 16: max_width = 24
if max_qubits > 24: max_width = 33
#print(f"... {avail_qubits} {max_qubits} {max_width}")
plot_width = 6.8
plot_height = 0.5 + plot_width * (max_width / max_depth_log)
#print(f"... {plot_width} {plot_height}")
# define matplotlib figure and axis; use constrained layout to fit colorbar to right
fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True)
plt.suptitle(suptitle)
plt.xlim(0, max_depth_log)
plt.ylim(0, max_width)
# circuit depth axis (x axis)
xbasis = [x for x in range(1,max_depth_log)]
xround = [depth_base**(x-1) for x in xbasis]
xlabels = [format_number(x) for x in xround]
ax.set_xlabel('Circuit Depth')
ax.set_xticks(xbasis)
plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor")
# other label options
#plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left')
#plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor")
# circuit width axis (y axis)
ybasis = [y for y in range(1,max_width)]
yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now
ylabels = [str(y) for y in yround] # not used now
#ax.set_ylabel('Circuit Width (Number of Qubits)')
ax.set_ylabel('Circuit Width')
ax.set_yticks(ybasis)
#create simple line plot (not used right now)
#ax.plot([0, 10],[0, 10])
log2QV = math.log2(QV)
QV_width = log2QV
QV_depth = log2QV * QV_transpile_factor
# show a quantum volume rectangle of QV = 64 e.g. (6 x 6)
if QV0 != 0:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base))
else:
ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base))
# the untranspiled version is commented out - we do not show this by default
# also show a quantum volume rectangle un-transpiled
# ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base))
# show 2D array of volumetric cells based on this QV_transpiled
# DEVNOTE: we use +1 only to make the visuals work; s/b without
# Also, the second arg of the min( below seems incorrect, needs correction
maxprod = (QV_width + 1) * (QV_depth + 1)
for w in range(1, min(max_width, round(QV) + 1)):
# don't show VB squares if width greater than known available qubits
if avail_qubits != 0 and w > avail_qubits:
continue
i_success = 0
for d in xround:
# polarization factor for low circuit widths
maxtest = maxprod / ( 1 - 1 / (2**w) )
# if circuit would fail here, don't draw box
if d > maxtest: continue
if w * d > maxtest: continue
# guess for how to capture how hardware decays with width, not entirely correct
# # reduce maxtext by a factor of number of qubits > QV_width
# # just an approximation to account for qubit distances
# if w > QV_width:
# over = w - QV_width
# maxtest = maxtest / (1 + (over/QV_width))
# draw a box at this width and depth
id = depth_index(d, depth_base)
# show vb rectangles; if not showing QV, make all hollow (or less dark)
if QV0 == 0:
#ax.add_patch(bkg_empty_box_at(id, w))
ax.add_patch(bkg_box_at(id, w, 0.95))
else:
ax.add_patch(bkg_box_at(id, w, 0.9))
# save index of last successful depth
i_success += 1
# plot empty rectangle after others
d = xround[i_success]
id = depth_index(d, depth_base)
ax.add_patch(bkg_empty_box_at(id, w))
# Add annotation showing quantum volume
if QV0 != 0:
t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12,
horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2),
bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1))
# add colorbar to right of plot
plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax,
shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7))
return ax
# Function to calculate circuit depth
def calculate_circuit_depth(qc):
# Calculate the depth of the circuit
depth = qc.depth()
return depth
def calculate_transpiled_depth(qc,basis_selector):
# use either the backend or one of the basis gate sets
if basis_selector == 0:
qc = transpile(qc, backend)
else:
basis_gates = basis_gates_array[basis_selector]
qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0)
transpiled_depth = qc.depth()
return transpiled_depth,qc
def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title):
avg_fidelity_means = []
avg_Hf_fidelity_means = []
avg_num_qubits_values = list(fidelity_data.keys())
# Calculate the average fidelity and Hamming fidelity for each unique number of qubits
for num_qubits in avg_num_qubits_values:
avg_fidelity = np.average(fidelity_data[num_qubits])
avg_fidelity_means.append(avg_fidelity)
avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits])
avg_Hf_fidelity_means.append(avg_Hf_fidelity)
return avg_fidelity_means,avg_Hf_fidelity_means
list_of_gates = []
def list_of_standardgates():
import qiskit.circuit.library as lib
from qiskit.circuit import Gate
import inspect
# List all the attributes of the library module
gate_list = dir(lib)
# Filter out non-gate classes (like functions, variables, etc.)
gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)]
# Get method names from QuantumCircuit
circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction)
method_names = [name for name, _ in circuit_methods]
# Map gate class names to method names
gate_to_method = {}
for gate in gates:
gate_class = getattr(lib, gate)
class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name
for method in method_names:
if method == class_name or method == class_name.replace('cr', 'c-r'):
gate_to_method[gate] = method
break
# Add common operations that are not strictly gates
additional_operations = {
'Measure': 'measure',
'Barrier': 'barrier',
}
gate_to_method.update(additional_operations)
for k,v in gate_to_method.items():
list_of_gates.append(v)
def update_counts(gates,custom_gates):
operations = {}
for key, value in gates.items():
operations[key] = value
for key, value in custom_gates.items():
if key in operations:
operations[key] += value
else:
operations[key] = value
return operations
def get_gate_counts(gates,custom_gate_defs):
result = gates.copy()
# Iterate over the gate counts in the quantum circuit
for gate, count in gates.items():
if gate in custom_gate_defs:
custom_gate_ops = custom_gate_defs[gate]
# Multiply custom gate operations by the count of the custom gate in the circuit
for _ in range(count):
result = update_counts(result, custom_gate_ops)
# Remove the custom gate entry as we have expanded it
del result[gate]
return result
dict_of_qc = dict()
custom_gates_defs = dict()
# Function to count operations recursively
def count_operations(qc):
dict_of_qc.clear()
circuit_traverser(qc)
operations = dict()
operations = dict_of_qc[qc.name]
del dict_of_qc[qc.name]
# print("operations :",operations)
# print("dict_of_qc :",dict_of_qc)
for keys in operations.keys():
if keys not in list_of_gates:
for k,v in dict_of_qc.items():
if k in operations.keys():
custom_gates_defs[k] = v
operations=get_gate_counts(operations,custom_gates_defs)
custom_gates_defs.clear()
return operations
def circuit_traverser(qc):
dict_of_qc[qc.name]=dict(qc.count_ops())
for i in qc.data:
if str(i.operation.name) not in list_of_gates:
qc_1 = i.operation.definition
circuit_traverser(qc_1)
def get_memory():
import resource
usage = resource.getrusage(resource.RUSAGE_SELF)
max_mem = usage.ru_maxrss/1024 #in MB
return max_mem
# Convert theta to a bitstring distribution
def theta_to_bitstring(theta, num_counting_qubits):
counts = {format( int(theta * (2**num_counting_qubits)), "0"+str(num_counting_qubits)+"b"): 1.0}
return counts
# Convert bitstring to theta representation, useful for debugging
def bitstring_to_theta(counts, num_counting_qubits):
theta_counts = {}
for key in counts.keys():
r = counts[key]
theta = int(key,2) / (2**num_counting_qubits)
if theta not in theta_counts.keys():
theta_counts[theta] = 0
theta_counts[theta] += r
return theta_counts
def analyzer(theta,num_qubits, num_counting_qubits,counts):
num_counting_qubits_1 = num_qubits -1
# calculate expected output histogram
correct_dist = theta_to_bitstring(theta, num_counting_qubits_1)
# generate thermal_dist for polarization calculation
thermal_dist = uniform_dist(num_counting_qubits)
#print("thermal_dist=",thermal_dist)
# convert counts, expectation, and thermal_dist to app form for visibility
# app form of correct distribution is measuring amplitude a 100% of the time
# app_counts = bitstring_to_a(counts, num_counting_qubits)
# app_correct_dist = correct_dist#{a: 1.0}
# app_thermal_dist = bitstring_to_a(thermal_dist, num_counting_qubits)
return correct_dist,thermal_dist
num_state_qubits=1 #(default) not exposed to users
def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits,
max_circuits=max_circuits, num_shots=num_shots, num_state_qubits=num_state_qubits):
creation_times = []
elapsed_times = []
quantum_times = []
circuit_depths = []
transpiled_depths = []
fidelity_data = {}
Hf_fidelity_data = {}
numckts = []
mem_usage = []
algorithmic_1Q_gate_counts = []
algorithmic_2Q_gate_counts = []
transpiled_1Q_gate_counts = []
transpiled_2Q_gate_counts = []
print(f"{benchmark_name} Benchmark Program - {platform}")
# validate parameters (smallest circuit is 3 qubits)
num_state_qubits = max(1, num_state_qubits)
if max_qubits < num_state_qubits + 2:
print(f"ERROR: AE Benchmark needs at least {num_state_qubits + 2} qubits to run")
return
min_qubits = max(max(3, min_qubits), num_state_qubits + 2)
skip_qubits = max(1, skip_qubits)
global max_ckts
max_ckts = max_circuits
global min_qbits,max_qbits,skp_qubits
min_qbits = min_qubits
max_qbits = max_qubits
skp_qubits = skip_qubits
print(f"min, max qubits = {min_qubits} {max_qubits}")
#defining all the standard gates supported by qiskit in a list
if gate_counts_plots == True:
list_of_standardgates()
# Execute Benchmark Program N times for multiple circuit sizes
for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits):
fidelity_data[num_qubits] = []
Hf_fidelity_data[num_qubits] = []
# reset random seed
np.random.seed(0)
# as circuit width grows, the number of counting qubits is increased
num_counting_qubits = num_qubits - num_state_qubits - 1
# determine number of circuits to execute for this group
num_circuits = min(2 ** (num_counting_qubits), max_circuits)
print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}")
numckts.append(num_circuits)
# determine range of secret strings to loop over
if 2**(num_counting_qubits) <= max_circuits:
theta_range = [i/(2**(num_counting_qubits)) for i in list(range(num_circuits))]
else:
theta_range = [i/(2**(num_counting_qubits)) for i in np.random.choice(2**(num_counting_qubits), num_circuits, False)]
for theta in theta_range:
print("*********************************************")
print(f"qc of {num_qubits} qubits for theta {theta}")
#creation of Quantum Circuit.
ts = time.time()
qc = PhaseEstimation(num_qubits, theta)
#creation time
creation_time = time.time() - ts
creation_times.append(creation_time)
#print(qc)
print(f"creation time = {creation_time*1000} ms")
# Calculate gate count for the algorithmic circuit (excluding barriers and measurements)
if gate_counts_plots == True:
operations = count_operations(qc)
n1q = 0; n2q = 0
if operations != None:
for key, value in operations.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c") or key.startswith("mc"):
n2q += value
else:
n1q += value
algorithmic_1Q_gate_counts.append(n1q)
algorithmic_2Q_gate_counts.append(n2q)
# collapse the sub-circuit levels used in this benchmark (for qiskit)
qc=qc.decompose().decompose().decompose()
#print(qc)
# Calculate circuit depth
depth = calculate_circuit_depth(qc)
circuit_depths.append(depth)
# Calculate transpiled circuit depth
transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector)
transpiled_depths.append(transpiled_depth)
#print(qc)
print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}")
if gate_counts_plots == True:
# Calculate gate count for the transpiled circuit (excluding barriers and measurements)
tr_ops = qc.count_ops()
#print("tr_ops = ",tr_ops)
tr_n1q = 0; tr_n2q = 0
if tr_ops != None:
for key, value in tr_ops.items():
if key == "measure": continue
if key == "barrier": continue
if key.startswith("c"): tr_n2q += value
else: tr_n1q += value
transpiled_1Q_gate_counts.append(tr_n1q)
transpiled_2Q_gate_counts.append(tr_n2q)
print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}")
print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}")
#execution
if Type_of_Simulator == "built_in":
#To check if Noise is required
if Noise_Inclusion == True:
noise_model = noise_parameters
else:
noise_model = None
ts = time.time()
job = execute(qc, backend, shots=num_shots, noise_model=noise_model)
elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" :
ts = time.time()
job = backend.run(qc,shots=num_shots, noise_model=noise_parameters)
#retrieving the result
result = job.result()
#print(result)
#calculating elapsed time
elapsed_time = time.time() - ts
elapsed_times.append(elapsed_time)
# Calculate quantum processing time
quantum_time = result.time_taken
quantum_times.append(quantum_time)
print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms")
#counts in result object
counts = result.get_counts()
#Correct distribution to compare with counts
correct_dist,thermal_dist = analyzer(theta,num_qubits, num_counting_qubits,counts)
#fidelity calculation comparision of counts and correct_dist
fidelity_dict = polarization_fidelity(counts, correct_dist,thermal_dist)
fidelity_data[num_qubits].append(fidelity_dict['fidelity'])
Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity'])
#maximum memory utilization (if required)
if Memory_utilization_plot == True:
max_mem = get_memory()
print(f"Maximum Memory Utilized: {max_mem} MB")
mem_usage.append(max_mem)
print("*********************************************")
##########
# print a sample circuit
print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!")
print("\nPhase Operator 'U' = "); print(U_ if U_ != None else " ... too large!")
print("\nInverse QFT Circuit ="); print(QFTI_ if QFTI_ != None else " ... too large!")
return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths,
fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts,
transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage)
# Execute the benchmark program, accumulate metrics, and calculate circuit depths
(creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts,
algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run()
# Define the range of qubits for the x-axis
num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits)
print("num_qubits_range =",num_qubits_range)
# Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits
avg_creation_times = []
avg_elapsed_times = []
avg_quantum_times = []
avg_circuit_depths = []
avg_transpiled_depths = []
avg_1Q_algorithmic_gate_counts = []
avg_2Q_algorithmic_gate_counts = []
avg_1Q_Transpiled_gate_counts = []
avg_2Q_Transpiled_gate_counts = []
max_memory = []
start = 0
for num in numckts:
avg_creation_times.append(np.mean(creation_times[start:start+num]))
avg_elapsed_times.append(np.mean(elapsed_times[start:start+num]))
avg_quantum_times.append(np.mean(quantum_times[start:start+num]))
avg_circuit_depths.append(np.mean(circuit_depths[start:start+num]))
avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num]))
if gate_counts_plots == True:
avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num])))
avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num])))
avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num])))
avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num])))
if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num]))
start += num
# Calculate the fidelity data
avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison")
# Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits
# Add labels to the bars
def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"):
for rect in rects:
height = rect.get_height()
ax.annotate(str.format(height), # Formatting to two decimal places
xy=(rect.get_x() + rect.get_width() / 2, height / 2),
xytext=(0, 0),
textcoords="offset points",
ha='center', va=va,color=text_color,rotation=90)
bar_width = 0.3
# Determine the number of subplots and their arrangement
if Memory_utilization_plot and gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30))
# Plotting for both memory utilization and gate counts
# ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available
elif Memory_utilization_plot:
fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30))
# Plotting for memory utilization only
# ax1, ax2, ax3, ax6, ax7 are available
elif gate_counts_plots:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30))
# Plotting for gate counts only
# ax1, ax2, ax3, ax4, ax5, ax6 are available
else:
fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30))
# Default plotting
# ax1, ax2, ax3, ax6 are available
fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16)
for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000
avg_creation_times[i] *= 1000
ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue')
autolabel(ax1.patches, ax1)
ax1.set_xlabel('Number of Qubits')
ax1.set_ylabel('Average Creation Time (ms)')
ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14)
ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000
avg_elapsed_times[i] *= 1000
for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000
avg_quantum_times[i] *= 1000
Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time')
Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time')
autolabel(Elapsed,ax2,str='{:.1f}')
autolabel(Quantum,ax2,str='{:.1f}')
ax2.set_xlabel('Number of Qubits')
ax2.set_ylabel('Average Time (ms)')
ax2.set_title('Average Time vs Number of Qubits')
ax2.legend()
ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here
Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here
autolabel(Normalized,ax3,str='{:.2f}')
autolabel(Algorithmic,ax3,str='{:.2f}')
ax3.set_xlabel('Number of Qubits')
ax3.set_ylabel('Average Circuit Depth')
ax3.set_title('Average Circuit Depth vs Number of Qubits')
ax3.legend()
if gate_counts_plots == True:
ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_1Q_counts,ax4,str='{}')
autolabel(Algorithmic_1Q_counts,ax4,str='{}')
ax4.set_xlabel('Number of Qubits')
ax4.set_ylabel('Average 1-Qubit Gate Counts')
ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits')
ax4.legend()
ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here
Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here
autolabel(Normalized_2Q_counts,ax5,str='{}')
autolabel(Algorithmic_2Q_counts,ax5,str='{}')
ax5.set_xlabel('Number of Qubits')
ax5.set_ylabel('Average 2-Qubit Gate Counts')
ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits')
ax5.legend()
ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here
Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here
autolabel(Hellinger,ax6,str='{:.2f}')
autolabel(Normalized,ax6,str='{:.2f}')
ax6.set_xlabel('Number of Qubits')
ax6.set_ylabel('Average Value')
ax6.set_title("Fidelity Comparison")
ax6.legend()
if Memory_utilization_plot == True:
ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits))
x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations")
autolabel(ax7.patches, ax7)
ax7.set_xlabel('Number of Qubits')
ax7.set_ylabel('Maximum Memory Utilized (MB)')
ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14)
plt.tight_layout(rect=[0, 0, 1, 0.96])
if saveplots == True:
plt.savefig("ParameterPlotsSample.jpg")
plt.show()
# Quantum Volume Plot
Suptitle = f"Volumetric Positioning - {platform}"
appname=benchmark_name
if QV_ == None:
QV=2048
else:
QV=QV_
depth_base =2
ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity")
w_data = num_qubits_range
# determine width for circuit
w_max = 0
for i in range(len(w_data)):
y = float(w_data[i])
w_max = max(w_max, y)
d_tr_data = avg_transpiled_depths
f_data = avg_f
plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max)
anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
|
https://github.com/hugoecarl/TSP-Problem-Study
|
hugoecarl
|
import math
import matplotlib.pyplot as plt
%matplotlib inline
class TSP:
def __init__(self):
self.flat_mat = flat_mat
self.n = 0
self.melhor_dist = 1e11
self.pontos = []
self.melhores_pontos = []
def busca_exaustiva(self, flat_mat, n, ite):
if ite == n:
dist = 0
for j in range(1, n):
dist += flat_mat[self.pontos[j-1] * n + self.pontos[j]]
dist += flat_mat[self.pontos[n-1] * n + self.pontos[0]]
if dist < self.melhor_dist:
self.melhor_dist = dist
self.melhores_pontos = self.pontos[:]
return
for i in range(n):
if self.pontos[i] == -1:
self.pontos[i] = ite
self.busca_exaustiva(flat_mat, n, ite + 1)
self.pontos[i] = -1
def dist_mat(self):
x = []
y = []
flat_mat = [] #matriz 1 dimensao contendo todas as distancias possiveis entre os pontos para facilitar cálculo.
while True:
try:
temp = input("Digite a coordenada x y: ").split()
x.append(float(temp[0]))
y.append(float(temp[1]))
except:
break
for i in range(len(x)):
for j in range(len(y)):
flat_mat.append(math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2))
return flat_mat, x, y
def get_results(self):
self.flat_mat, x, _ = self.dist_mat()
self.n = len(x)
self.pontos = [-1]*self.n
self.pontos[0] = 0
self.busca_exaustiva(self.flat_mat, self.n, 1)
return self.melhor_dist, self.melhores_pontos
Tsp = TSP()
distancia, pontos = Tsp.get_results()
print("Melhor distancia encontrada: ", distancia)
print("Melhor caminho encontrado: ", pontos)
#plota gráfico
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'ro-')
for i in range(1, len(pontos)):
connectpoints(x,y,pontos[i-1],pontos[i])
connectpoints(x,y,pontos[len(x)-1],pontos[0])
plt.title("Percurso")
plt.show()
%%time
%%cmd
python TSP.py < in-1.txt
type out-1.txt
python TSP.py < in-2.txt
type out-2.txt
python TSP.py < in-3.txt
type out-3.txt
python TSP.py < in-4.txt
type out-4.txt
from qiskit import IBMQ
import numpy as np
#IBMQ.save_account('seu-tokenIBMQ-para-rodar-localmente')
IBMQ.load_account()
from qiskit import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit.optimization.applications.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua import aqua_globals
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.optimization.algorithms import MinimumEigenOptimizer
from qiskit.optimization.problems import QuadraticProgram
import logging
from qiskit.aqua import set_qiskit_aqua_logging
#Preparando os dados segundo os imputs do usuario para serem resolvidos pelo qiskit max 4 pontos por limitação de qubits
coord = []
flat_mat, x, y = TSP().dist_mat()
dist_mat = np.array(flat_mat).reshape(len(x),len(x))
for i, j in zip(x, y):
coord.append([i,j])
ins = tsp.TspData('TSP_Q', dim=len(x), coord=np.array(coord), w=dist_mat)
qubitOp, offset = tsp.get_operator(ins)
print('Offset:', offset)
print('Ising Hamiltonian:')
print(qubitOp.print_details())
#Usando o numpyMinimumEigensolver como o solver do problema para resolver de forma quantica
ee = NumPyMinimumEigensolver(qubitOp)
result = ee.run()
print('energy:', result.eigenvalue.real)
print('tsp objective:', result.eigenvalue.real + offset)
x_Q = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
for i in range(1, len(z)):
connectpoints(x,y,z[i-1],z[i])
connectpoints(x,y,z[len(x)-1],z[0])
plt.title("Percurso")
plt.show()
#instanciando o simulador ou o computador real importante lembrar que nao ira funcionar para mais de 4 pontos pelo numero de qubits disponibilizados pela IBM que sao apenas 16 para o simulador qasm e 15 para a maquina quantica
provider = IBMQ.get_provider(hub = 'ibm-q')
device = provider.get_backend('ibmq_16_melbourne')
aqua_globals.random_seed = np.random.default_rng(123)
seed = 10598
backend = Aer.get_backend('qasm_simulator')
#descomentar essa linha caso queira rodar na maquina real
#backend = device
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
#rodando no simulador quantico
spsa = SPSA(maxiter=10)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, quantum_instance=quantum_instance)
result = vqe.run(quantum_instance)
print('energy:', result.eigenvalue.real)
print('time:', result.optimizer_time)
x = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
'''
Code taken from Warren Alphonso's Website discussing the
VQE implementation of the FermiHubbard model
https://warrenalphonso.github.io/qc/hubbard#VQE
'''
from openfermion.hamiltonians import FermiHubbardModel
from openfermion.utils import SpinPairs
from openfermion.utils import HubbardSquareLattice
from openfermioncirq import SwapNetworkTrotterAnsatz
#==== Create 2x2 Hubbard Square Lattice ========
# HubbardSquareLattice parameters
x_n = 2
y_n = 2
n_dofs = 1 # 1 degree of freedom for spin
periodic = 0 # Don't want tunneling terms to loop back around
spinless = 0 # Has spin
lattice = HubbardSquareLattice(x_n, y_n, n_dofs=n_dofs, periodic=periodic, spinless=spinless)
#====== Create FermiHubbardModel Instance from Defined Lattice =========
tunneling = [('neighbor', (0, 0), 1.)]
interaction = [('onsite', (0, 0), 2., SpinPairs.DIFF)]
potential = [(0, 1.)] # Must be U/2 for half-filling
mag_field = 0.
particle_hole_sym = False
hubbard = FermiHubbardModel(lattice , tunneling_parameters=tunneling, interaction_parameters=interaction,
potential_parameters=potential, magnetic_field=mag_field,
particle_hole_symmetry=particle_hole_sym)
#print(hubbard.hamiltonian())
#Example Adiabatic Evolution for 2x2 Hamiltonian
import numpy as np
import scipy.linalg as sp
import matplotlib.pyplot as plt
H_A = np.array( [[1, 0], [0, -1]] )
H_B = np.array( [[0, 1], [1, 0]] )
H = lambda s: (1-s)*H_A + s*H_B
psi_A = np.array([0, 1]) # The ground state of H_A
# If n=5, then we do 5 steps: H(0), H(0.25), H(0.5), H(0.75), H(1)
n = 50
t = 1
res = psi_A
s_vals = []
up_eigs = []
dwn_eigs = []
for i in range(n):
s = i / (n-1)
s_vals.append(s)
res = np.dot(sp.expm(-1j * H(s) * t), res)
up_eigs.append(sp.eig(H(s))[0][0])
dwn_eigs.append((sp.eig(H(s))[0][1]))
plt.plot(s_vals, up_eigs)
plt.plot(s_vals, dwn_eigs)
plt.ylabel('Eigenvalues')
plt.xlabel('s')
import sys
sys.path.append('./src')
import CustomSwapNetworkTrotterAnsatz
#from openfermioncirq import SwapNetworkTrotterAnsatz
#from CustomSwapNetworkTrotterAnsatz import *
steps = 2
#ansatz = CustomSwapNetworkTrotterAnsatz(hubbard, iterations=steps)
|
https://github.com/kosakhro/QAOA-for-exact-cover
|
kosakhro
| |
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module for generating random Qiskit circuits
"""
from qiskit import QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.random import random_circuit
from qbraid.exceptions import QbraidError
def _qiskit_random(num_qubits: int, depth: int, **kwargs) -> QuantumCircuit:
"""Generate random circuit qiskit circuit.
Args:
num_qubits (int): number of quantum wires
depth (int): layers of operations (i.e. critical path length)
Raises:
QbraidError: When invalid qiskit random circuit options given
Returns:
Qiskit random circuit
"""
if "measure" not in kwargs:
kwargs["measure"] = False
try:
return random_circuit(num_qubits, depth, **kwargs)
except CircuitError as err:
raise QbraidError("Failed to create Qiskit random circuit") from err
|
https://github.com/Pahamanx/QETCI-Hackathon-2022
|
Pahamanx
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
from qiskit.circuit.library import MCXGate
import qiskit.tools.jupyter
%qiskit_job_watcher
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
backend = provider.get_backend('simulator_statevector')
#階乘函式
def factorial(num):
if num == 0:
return 1
else:
a = 1
for i in range(1,num+1):
a = a*i
return a
#定義complete graph大小
graphSize = 5
edgeNumbers = (graphSize)*(graphSize-1)//2
answerNumber = factorial(graphSize-1)//2
groverTimes = int(( 3.14/4*(2**edgeNumbers/answerNumber)**(1/2) )//1)
print(answerNumber, edgeNumbers)
#choosing state
def choose(a):
oracle = QuantumCircuit(edgeNumbers, name = 'choose state')
zGate = MCXGate(edgeNumbers-1)
oracle.x(a)
oracle.h([edgeNumbers-1])
oracle.append(zGate, [i for i in range(edgeNumbers)])
oracle.h([edgeNumbers-1])
oracle.x(a)
oracle.draw(output='mpl')
return oracle
#define Hamiltonian Cycles
hamiltonianCycles = [[0,6,7,8,9], [1,2,3,4,5], [1,3,4,6,8], [1,4,6,7,9],
[0,1,2,4,7], [1,3,5,7,9], [0,1,3,7,8], [0,2,5,7,9],
[2,4,5,6,9], [0,2,3,5,8], [0,2,4,6,8], [3,5,6,8,9]]
#oracle
oracle = QuantumCircuit(edgeNumbers, name = 'oracle')
for i in range(len(hamiltonianCycles)):
oracle.append(choose(hamiltonianCycles[i]), [j for j in range(edgeNumbers)])
oracle.draw(output='mpl')
# diffuser
def diffuser(nqubits):
qc = QuantumCircuit(nqubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(nqubits):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(nqubits):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(nqubits-1)
qc.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc.h(nqubits-1)
# Apply transformation |11..1> -> |00..0>
for qubit in range(nqubits):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(nqubits):
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "U$_s$"
return U_s
#quantum circuit
qc = QuantumCircuit(edgeNumbers)
for i in range(edgeNumbers):
qc.h(i)
for j in range(groverTimes):
qc.append(oracle, [i for i in range(edgeNumbers)])
qc.append(diffuser(edgeNumbers), [i for i in range(edgeNumbers)])
qc.measure_all()
qc.draw(output='mpl')
job = backend.run(transpile(qc, backend=backend), shots=90)
print(job.job_id())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import *
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit $q_{0}$, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{1}$, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit $q_{0}$ and target qubit $q_{2}$, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = backend.run(circ)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = Aer.get_backend('unitary_simulator')
job = backend.run(circ)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition using
# the compose method.
circ.add_register(meas.cregs[0])
qc = circ.compose(meas)
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend_sim.run(transpile(qc, backend_sim), shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for core modules of timeline drawer."""
from qiskit import QuantumCircuit, transpile
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import core, stylesheet, generators, layouts
class TestCanvas(QiskitTestCase):
"""Test for canvas."""
def setUp(self):
super().setUp()
self.style = stylesheet.QiskitTimelineStyle()
circ = QuantumCircuit(4)
circ.h(0)
circ.barrier()
circ.cx(0, 2)
circ.cx(1, 3)
self.circ = transpile(
circ,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)],
optimization_level=0,
)
def test_time_range(self):
"""Test calculating time range."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1}
canvas.time_range = (0, 100)
ref_range = [-10.0, 110.0]
self.assertListEqual(list(canvas.time_range), ref_range)
def test_load_program(self):
"""Test loading program."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 8)
ref_coord = {
self.circ.qregs[0][0]: -1.0,
self.circ.qregs[0][1]: -2.0,
self.circ.qregs[0][2]: -3.0,
self.circ.qregs[0][3]: -4.0,
}
self.assertDictEqual(canvas.assigned_coordinates, ref_coord)
def test_gate_link_overlap(self):
"""Test shifting gate link overlap."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update(
{
"margin.link_interval_percent": 0.01,
"margin.left_percent": 0,
"margin.right_percent": 0,
}
)
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 2)
self.assertListEqual(drawings_tested[0][1].xvals, [706.0])
self.assertListEqual(drawings_tested[1][1].xvals, [694.0])
ref_keys = list(canvas._collections.keys())
self.assertEqual(drawings_tested[0][0], ref_keys[0])
self.assertEqual(drawings_tested[1][0], ref_keys[1])
def test_object_outside_xlimit(self):
"""Test eliminating drawings outside the horizontal limit."""
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [generators.gen_bit_name, generators.gen_timeslot],
"barriers": [],
"gate_links": [],
}
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.load_program(self.circ)
canvas.set_time_range(t_start=400, t_end=600)
canvas.update()
drawings_tested = list(canvas.collections)
self.assertEqual(len(drawings_tested), 12)
def test_non_transpiled_delay_circuit(self):
"""Test non-transpiled circuit containing instruction which is trivial on duration."""
circ = QuantumCircuit(1)
circ.delay(10, 0)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.generator = {
"gates": [generators.gen_sched_gate],
"bits": [],
"barriers": [],
"gate_links": [],
}
with self.assertWarns(DeprecationWarning):
canvas.load_program(circ)
self.assertEqual(len(canvas._collections), 1)
def test_multi_measurement_with_clbit_not_shown(self):
"""Test generating bit link drawings of measurements when clbits is disabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": False})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 0)
def test_multi_measurement_with_clbit_shown(self):
"""Test generating bit link drawings of measurements when clbits is enabled."""
circ = QuantumCircuit(2, 2)
circ.measure(0, 0)
circ.measure(1, 1)
circ = transpile(
circ,
scheduling_method="alap",
basis_gates=[],
instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)],
optimization_level=0,
)
canvas = core.DrawerCanvas(stylesheet=self.style)
canvas.formatter.update({"control.show_clbits": True})
canvas.layout = {
"bit_arrange": layouts.qreg_creg_ascending,
"time_axis_map": layouts.time_map_in_dt,
}
canvas.generator = {
"gates": [],
"bits": [],
"barriers": [],
"gate_links": [generators.gen_gate_link],
}
canvas.load_program(circ)
canvas.update()
self.assertEqual(len(canvas._output_dataset), 2)
|
https://github.com/GIRISHBELANI/QC_Benchmarks_using_dm-simulator
|
GIRISHBELANI
|
import numpy as np
def grovers_dist(num_qubits, marked_item, n_iterations):
dist = {}
for i in range(2**num_qubits):
key = bin(i)[2:].zfill(num_qubits)
theta = np.arcsin(1/np.sqrt(2 ** num_qubits))
if i == marked_item:
dist[key] = np.sin((2*n_iterations+1)*theta)**2
else:
dist[key] = (np.cos((2*n_iterations+1)*theta)/(np.sqrt(2 ** num_qubits - 1)))**2
return dist
num_qubits = 4
marked_item = 6
n_iterations = int(np.pi * np.sqrt(2 ** num_qubits) / 4)
grovers_dist(num_qubits, marked_item, n_iterations)
|
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
|
Keerthiraj-Nagaraj
|
from IPython.display import Image, display
Image('lights_out_rule.png')
Image('lights_out_prob.png')
# The starting pattern is represented by this list of numbers.
# Please use it as an input for your solution.
lights = [0, 1, 1, 1, 0, 0, 1, 1, 1]
def week2a_ans_func(lights):
##### build your quantum circuit here
#### In addition, please make it a function that can solve the problem even with different inputs (lights). We do validation with different inputs.
return qc
# Submission code
from qc_grader import prepare_ex2a, grade_ex2a, submit_ex2a
# Execute your circuit with following prepare_ex2a() function.
# The prepare_ex2a () function works like the execute() function with only QuantumCircuit as an argument.
job = prepare_ex2a(week2a_ans_func)
result = job.result()
count = result.get_counts()
original_problem_set_counts = count[0]
original_problem_set_counts
# The bit string with the highest number of observations is treated as the solution.
# Check your answer by executing following code.
# The quantum cost of the QuantumCircuit is obtained as the score. The quantum cost is related to rank only in the third week.
grade_ex2a(job)
# Submit your results by executing following code. You can submit as many times as you like during the period.
submit_ex2a(job)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Test of GenericBackendV2 backend"""
import math
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, transpile
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.transpiler import CouplingMap
from qiskit.exceptions import QiskitError
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestGenericBackendV2(QiskitTestCase):
"""Test class for GenericBackendV2 backend"""
def setUp(self):
super().setUp()
self.cmap = CouplingMap(
[(0, 2), (0, 1), (1, 3), (2, 4), (2, 3), (3, 5), (4, 6), (4, 5), (5, 7), (6, 7)]
)
def test_supported_basis_gates(self):
"""Test that target raises error if basis_gate not in ``supported_names``."""
with self.assertRaises(QiskitError):
GenericBackendV2(num_qubits=8, basis_gates=["cx", "id", "rz", "sx", "zz"])
def test_operation_names(self):
"""Test that target basis gates include "delay", "measure" and "reset" even
if not provided by user."""
target = GenericBackendV2(num_qubits=8)
op_names = list(target.operation_names)
op_names.sort()
self.assertEqual(op_names, ["cx", "delay", "id", "measure", "reset", "rz", "sx", "x"])
target = GenericBackendV2(num_qubits=8, basis_gates=["ecr", "id", "rz", "sx", "x"])
op_names = list(target.operation_names)
op_names.sort()
self.assertEqual(op_names, ["delay", "ecr", "id", "measure", "reset", "rz", "sx", "x"])
def test_incompatible_coupling_map(self):
"""Test that the size of the coupling map must match num_qubits."""
with self.assertRaises(QiskitError):
GenericBackendV2(num_qubits=5, coupling_map=self.cmap)
def test_control_flow_operation_names(self):
"""Test that control flow instructions are added to the target if control_flow is True."""
target = GenericBackendV2(
num_qubits=8,
basis_gates=["ecr", "id", "rz", "sx", "x"],
coupling_map=self.cmap,
control_flow=True,
).target
op_names = list(target.operation_names)
op_names.sort()
reference = [
"break",
"continue",
"delay",
"ecr",
"for_loop",
"id",
"if_else",
"measure",
"reset",
"rz",
"switch_case",
"sx",
"while_loop",
"x",
]
self.assertEqual(op_names, reference)
def test_default_coupling_map(self):
"""Test that fully-connected coupling map is generated correctly."""
# fmt: off
reference_cmap = [(0, 1), (1, 0), (0, 2), (2, 0), (0, 3), (3, 0), (0, 4), (4, 0), (1, 2), (2, 1),
(1, 3), (3, 1), (1, 4), (4, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3)]
# fmt: on
self.assertEqual(
list(GenericBackendV2(num_qubits=5).coupling_map.get_edges()),
reference_cmap,
)
def test_run(self):
"""Test run method, confirm correct noisy simulation if Aer is installed."""
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 4):
qc.cx(qr[0], qr[k])
qc.measure(qr, cr)
backend = GenericBackendV2(num_qubits=5, basis_gates=["cx", "id", "rz", "sx", "x"])
tqc = transpile(qc, backend=backend, optimization_level=3, seed_transpiler=42)
result = backend.run(tqc, seed_simulator=42, shots=1000).result()
counts = result.get_counts()
self.assertTrue(math.isclose(counts["00000"], 500, rel_tol=0.1))
self.assertTrue(math.isclose(counts["01111"], 500, rel_tol=0.1))
def test_duration_defaults(self):
"""Test that the basis gates are assigned duration defaults within expected ranges."""
basis_gates = ["cx", "id", "rz", "sx", "x", "sdg", "rxx"]
expected_durations = {
"cx": (7.992e-08, 8.99988e-07),
"id": (2.997e-08, 5.994e-08),
"rz": (0.0, 0.0),
"sx": (2.997e-08, 5.994e-08),
"x": (2.997e-08, 5.994e-08),
"measure": (6.99966e-07, 1.500054e-06),
"sdg": (2.997e-08, 5.994e-08),
"rxx": (7.992e-08, 8.99988e-07),
}
for _ in range(20):
target = GenericBackendV2(num_qubits=2, basis_gates=basis_gates).target
for inst in target:
for qargs in target.qargs_for_operation_name(inst):
duration = target[inst][qargs].duration
if inst not in ["delay", "reset"]:
self.assertGreaterEqual(duration, expected_durations[inst][0])
self.assertLessEqual(duration, expected_durations[inst][1])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
%matplotlib inline
circuit.draw()
circuit.h(qr[0])
circuit.draw(output = 'mpl')
circuit.cx(qr[0], qr[1])
circuit.draw(output='mpl')
circuit.measure(qr, cr)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
execute(circuit, backend=simulator)
result = execute(circuit, backend=simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
# plot_histogram
provider = IBMQ.get_provider('ibm-q')
backend = provider.get_backend('ibmq_16_melbourne')
job =execute(circuit, backend= backend)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
|
https://github.com/liudingshan/QiskitGrovers
|
liudingshan
|
import qiskit as qis
from qiskit.tools.visualization import plot_bloch_multivector
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
import math as math
# Define Registers
qr = qis.QuantumRegister(1)
cr = qis.ClassicalRegister(1)
# Make Circuit
circuit = qis.QuantumCircuit(qr, cr)
# Make Gates and Circuit Additions
#circuit.cz(qr[0], qr[1])
circuit.x(qr[0])
#circuit.x(qr[1])
#circuit.cswap(qr[0], qr[1], qr[2])
#circuit.ccx(qr[0], qr[1], qr[2])
#circuit.h(qr[0])
#circuit.cx(qr[0], qr[1])
#circuit.rx(math.pi/2, qr[0])
#circuit.swap(qr[0], qr[1])
# Choose Unitary Simulator
simulator = qis.Aer.get_backend('unitary_simulator')
# Get Unitary Results (Multiplication of all Gates/Additions)
result = qis.execute(circuit, backend=simulator).result()
unitary = result.get_unitary()
# Plot Unitary Results
print(unitary)
# Choose Statevector Simulator
simulator = qis.Aer.get_backend('statevector_simulator')
# Get Statevector Results
result = qis.execute(circuit, backend=simulator).result()
statevector = result.get_statevector()
# Plot Statevector Results
plot_bloch_multivector(statevector)
# Measure Qubits to Classical
circuit.measure(qr, cr)
# Print Circuit (Along w/ Measurements)
print(circuit)
#circuit.draw(output='mpl')
# Choose Qasm Simulator
simulator = qis.Aer.get_backend('qasm_simulator')
# Get Qasm Results
result = qis.execute(circuit, backend=simulator).result()
# Plot Qasm Measurements
plot_histogram(result.get_counts(circuit))
plt.show()
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from qiskit import IBMQ, execute
from qiskit.providers.ibmq.managed import IBMQJobManager
from qiskit.providers.ibmq.job import job_monitor
from qiskit.circuit.random import random_circuit
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('simulator_statevector')
# list all jobs which have been executed from our provider in the past
for job in backend.jobs():
print(job.job_id())
job_monitor(job)
qc = random_circuit(num_qubits=5, depth=4, measure=True)
qc.draw(output='mpl')
job = execute(qc, backend, shots=4096, job_name="test_job_name", job_tags=["test", "job"])
job_monitor(job)
counts = job.result().get_counts(0)
counts
|
https://github.com/nahumsa/volta
|
nahumsa
|
# 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 numpy as np
import textwrap
from typing import Union
from functools import partial
from qiskit import QuantumCircuit
from qiskit.opflow import OperatorBase, ListOp, PrimitiveOp, PauliOp
from qiskit.opflow import I, Z
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.optimizers import Optimizer
from qiskit.utils import QuantumInstance
from qiskit.providers import BaseBackend
from volta.observables import sample_hamiltonian
class SSVQE(object):
"""Subspace-search variational quantum eigensolver for excited states
algorithm class.
Based on https://arxiv.org/abs/1810.09434
"""
def __init__(
self,
hamiltonian: Union[OperatorBase, ListOp, PrimitiveOp, PauliOp],
ansatz: QuantumCircuit,
backend: Union[BaseBackend, QuantumInstance],
optimizer: Optimizer,
n_excited: int,
debug: bool = False,
) -> None:
"""Initialize the class.
Args:
hamiltonian (Union[OperatorBase, ListOp, PrimitiveOp, PauliOp]): Hamiltonian
constructed using qiskit's aqua operators.
ansatz (QuantumCircuit): Anstaz that you want to run VQD.
optimizer (qiskit.aqua.components.optimizers.Optimizer): Classical Optimizers
from aqua components.
backend (Union[BaseBackend, QuantumInstance]): Backend for running the algorithm.
"""
# Input parameters
self.hamiltonian = hamiltonian
self.n_qubits = hamiltonian.num_qubits
self.optimizer = optimizer
self.backend = backend
# Helper Parameters
self.ansatz = ansatz
self.n_parameters = self._get_num_parameters
self._debug = debug
self._ansatz_1_params = None
self._first_optimization = False
self._n_excited = n_excited
# Running inate functions
self._inate_optimizer_run()
def _create_blank_circuit(self) -> list:
return [QuantumCircuit(self.n_qubits) for _ in range(self._n_excited)]
def _copy_unitary(self, list_states: list) -> list:
out_states = []
for state in list_states:
out_states.append(state.copy())
return out_states
def _apply_initialization(self, list_states: list) -> None:
for ind, state in enumerate(list_states):
b = bin(ind)[2:]
if len(b) != self.n_qubits:
b = "0" * (self.n_qubits - len(b)) + b
spl = textwrap.wrap(b, 1)
for qubit, val in enumerate(spl):
if val == "1":
state.x(qubit)
@property
def _get_num_parameters(self) -> int:
"""Get the number of parameters in a given ansatz.
Returns:
int: Number of parameters of the given ansatz.
"""
return len(self.ansatz.parameters)
def _apply_varform_params(self, ansatz, params: list):
"""Get an hardware-efficient ansatz for n_qubits
given parameters.
"""
# Define variational Form
var_form = ansatz
# Get Parameters from the variational form
var_form_params = sorted(var_form.parameters, key=lambda p: p.name)
# Check if the number of parameters is compatible
assert len(var_form_params) == len(
params
), "The number of parameters don't match"
# Create a dictionary with the parameters and values
param_dict = dict(zip(var_form_params, params))
# Assing those values for the ansatz
wave_function = var_form.assign_parameters(param_dict)
return wave_function
def _apply_ansatz(self, list_states: list, name: str = None) -> None:
for states in list_states:
if name:
self.ansatz.name = name
states.append(self.ansatz, range(self.n_qubits))
def _construct_states(self):
circuit = self._create_blank_circuit()
self._apply_initialization(circuit)
self._apply_ansatz(circuit)
return circuit
def _cost_function_1(self, params: list) -> float:
"""Evaluate the first cost function of SSVQE.
Args:
params (list): Parameter values for the ansatz.
Returns:
float: Cost function value.
"""
# Construct states
states = self._construct_states()
cost = 0
w = np.arange(len(states), 0, -1)
for i, state in enumerate(states):
qc = self._apply_varform_params(state, params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(
hamiltonian=self.hamiltonian, ansatz=qc, backend=self.backend
)
cost += w[i] * hamiltonian_eval
return cost
def _inate_optimizer_run(self):
# Random initialization
params = np.random.rand(self.n_parameters)
optimal_params, energy, n_iters = self.optimizer.optimize(
num_vars=self.n_parameters,
objective_function=self._cost_function_1,
initial_point=params,
)
self._ansatz_1_params = optimal_params
self._first_optimization = True
def _cost_excited_state(self, ind: int, params: list):
cost = 0
# Construct states
states = self._construct_states()
# Define Ansatz
qc = self._apply_varform_params(states[ind], params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(
hamiltonian=self.hamiltonian, ansatz=qc, backend=self.backend
)
cost += hamiltonian_eval
return cost, qc
def run(self, index: int) -> (float, QuantumCircuit):
"""Run SSVQE for a given index.
Args:
index(int): Index of the given excited state.
Returns:
Energy: Energy of such excited state.
State: State for such energy.
"""
energy, state = self._cost_excited_state(index, self._ansatz_1_params)
return energy, state
if __name__ == "__main__":
import qiskit
from qiskit import BasicAer
optimizer = qiskit.algorithms.optimizers.COBYLA(maxiter=100)
backend = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"), shots=10000
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=1)
algo = SSVQE(hamiltonian, ansatz, backend, optimizer)
energy, state = algo.run(1)
print(energy)
print(state)
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from crypto.six_state.participant import Participant
from qiskit import QuantumCircuit
## The Sender entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Sender(Participant):
## Constructor
def __init__(self, name='', original_bits_size=0):
super().__init__(name, original_bits_size)
## Encode the message (values) using a quantum circuit
def encode_quantum_message(self):
encoded_message = []
for i in range(len(self.axes)):
qc = QuantumCircuit(1, 1)
if self.values[i] == 1:
qc.x(0)
if self.axes[i] == 1:
qc.h(0)
elif self.axes[i] == 2:
qc.append(self.hy, [0])
encoded_message.append(qc)
return encoded_message
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit_chemistry import FermionicOperator
from qiskit_chemistry.aqua_extensions.components.initial_states import HartreeFock
from qiskit.quantum_info import Pauli
from qiskit_aqua import Operator
from qiskit_aqua.algorithms import IQPE, ExactEigensolver
from qiskit import Aer,QuantumRegister
from qiskit import execute
import yaml as yml
from yaml import SafeLoader as Loader
import numpy as np
import Load_Hamiltonians as lh
from scipy import linalg as las
def construct_twoqubit_pauliham(hI,h0,h1,h2,h3,h4):
return [[hI,Pauli(label='II')],[h0,Pauli(label='IZ')],[h1,Pauli(label='ZI')],[h2,Pauli(label='XX')],[h3,Pauli(label='YY')],[h4,Pauli(label='ZZ')]]
map_type = 'jordan_wigner'
backend = Aer.get_backend('qasm_simulator')
# backend = Aer.get_backend('unitary_simulator')
NW_data_file = str('/Users/mmetcalf/Dropbox/Quantum Embedding/Codes/Lithium_Downfolding/Qiskit Chem/HamiltonianDownfolding_w_IBM/H2.yaml')
print('First File', NW_data_file)
try:
doc = open(NW_data_file, 'r')
data = yml.load(doc, Loader)
finally:
doc.close()
# Import all the data from a yaml file
print('Getting data')
n_spatial_orbitals = data['integral_sets'][0]['n_orbitals']
print('{} spatial orbitals'.format(n_spatial_orbitals))
nuclear_repulsion_energy = data['integral_sets'][0]['coulomb_repulsion']['value']
print('{} Coloumb repulsion'.format(nuclear_repulsion_energy))
n_orbitals = 2 * n_spatial_orbitals
n_particles = data['integral_sets'][0]['n_electrons']
print('{} particles'.format(n_particles))
dist = 2 * data['integral_sets'][0]['geometry']['atoms'][1]['coords'][2]
print('Bond distance is {}'.format(dist))
if map_type == 'parity':
# For two-qubit reduction
n_qubits = n_orbitals - 2
else:
n_qubits = n_orbitals
# Importing the integrals
one_electron_import = data['integral_sets'][0]['hamiltonian']['one_electron_integrals']['values']
two_electron_import = data['integral_sets'][0]['hamiltonian']['two_electron_integrals']['values']
# Getting spatial integrals and spin integrals to construct Hamiltonian
one_electron_spatial_integrals, two_electron_spatial_integrals = lh.get_spatial_integrals(one_electron_import,
two_electron_import,
n_spatial_orbitals)
h1, h2 = lh.convert_to_spin_index(one_electron_spatial_integrals,two_electron_spatial_integrals,n_spatial_orbitals, .01)
fop = FermionicOperator(h1, h2)
qop_paulis = fop.mapping(map_type)
# #print(qop_paulis._paulis)
# qop1 = Operator(paulis=qop_paulis.paulis)
# qop2 = Operator(paulis=qop_paulis.paulis)
#print(id(qop1),' and ', id(qop2))
init_state = HartreeFock(n_qubits, n_orbitals, n_particles, map_type, two_qubit_reduction=False)
#Hamiltonian from Google Paper
hI = -0.2265
h0 = 0.1843
h1 = -0.0549
h2 = 0.1165
h3 = 0.1165
h4 = 0.4386
t_0 = 9.830
#this function returns a list of pauli operators
google_pauliham = construct_twoqubit_pauliham(hI,h0,h1,h2,h3,h4)
google_op = Operator(paulis=google_pauliham)
google_init_state = HartreeFock(num_qubits=2, num_orbitals=2, num_particles=1, qubit_mapping=map_type, two_qubit_reduction=False)
# a = QuantumRegister(1, name='a')
# q = QuantumRegister(2, name='q')
# Circuit = google_op.construct_evolution_circuit(google_pauliham,t_0 , 1, q,
# ancillary_registers=a, ctl_idx=0, unitary_power=None, use_basis_gates=False,
# shallow_slicing=False)
# print(Circuit)
# result = execute(Circuit, backend).result()
# unitary = result.get_unitary(Circuit)
# print("Circuit unitary:\n", unitary)
# eval, evec = las.eigh(unitary)
# print(eval[0])
k = 7
#print('{} are the Paulis before'.format(qop2.paulis))
algorithm = IQPE(operator=google_op, state_in=google_init_state, num_time_slices=1, num_iterations=k, paulis_grouping='random', expansion_mode='trotter')
#print('New location of other op:', id(qop2))
#manually
# algorithm.identity_phase()
# qc_pea = algorithm.construct_circuit(k=1,omega=0)
# alg = execute(qc_pea, backend)
# result = alg.result()
# count = result.get_counts(qc_pea)
# print(qc_pea)
# print('{} are the state populations'.format(count))
result = algorithm.run(backend)
iqpe_energy = result['energy']
print('{} is the energy i got for {} iterations'.format(iqpe_energy,k))
# exact_eigensolver = ExactEigensolver(operator=google_op, k=2)
# ret = exact_eigensolver.run()
# print('The total FCI energy is: {:.12f}'.format(ret['eigvals'][0].real ))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
from qiskit.transpiler.passes import UnitarySynthesis
circuit = QuantumCircuit(1)
circuit.rx(0.8, 0)
unitary = Operator(circuit).data
unitary_circ = QuantumCircuit(1)
unitary_circ.unitary(unitary, [0])
synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk")
out = synth(unitary_circ)
out.draw('mpl')
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### replaced cx gate ###
qc.cy(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/e-eight/vqe
|
e-eight
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
import qiskit
from qiskit_aer import Aer, QasmSimulator
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Decompose
from dc_qiskit_qml import QiskitOptions
from dc_qiskit_qml.encoding_maps import NormedAmplitudeEncoding
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MottonenStatePreparation
from dc_qiskit_algorithms.MottonenStatePreparation import MottonenStatePreparationGate
initial_state_builder = QmlGenericStateCircuitBuilder(MottonenStatePreparation())
execution_backend: QasmSimulator = Aer.get_backend('qasm_simulator')
options = QiskitOptions(shots=8192,optimization_level=3)
qml = QmlHadamardNeighborClassifier(
backend=execution_backend,
classifier_circuit_factory=initial_state_builder,
encoding_map=NormedAmplitudeEncoding(),
options=options
)
import numpy as np
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.pipeline import Pipeline
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
X = np.asarray([x[0:2] for x, y in zip(X, y) if y != 2])
y = np.asarray([y for x, y in zip(X, y) if y != 2])
X_train = X[[33, 85]]
y_train = y[[33, 85]]
X_test = X[[28, 36]]
y_test = y[[28, 36]]
pipeline = Pipeline([
('scaler', StandardScaler()),
('l2norm', Normalizer(norm='l2', copy=True)),
('qml', qml)
])
import matplotlib.pyplot as plt
_X = pipeline.fit_transform(X, y)
_X_train = pipeline.transform(X_train)
_X_test = pipeline.transform(X_test)
plt.scatter(
_X[:,0], _X[:,1],
color=['red' if yy == 0 else 'blue' for yy in y],
s=20)
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.xlim([-1.2,1.2])
plt.ylim([-1.2,1.2])
plt.show()
pipeline.fit(X_train, y_train)
pipeline.predict(X_test), y_test
qml._last_predict_circuits[0].draw(output="mpl", fold=-1)
PassManager([Decompose(MottonenStatePreparationGate)]).run(qml._last_predict_circuits[0]).draw(fold=-1, output="mpl")
qiskit.transpile(
circuits=qml._last_predict_circuits[0],
basis_gates=['cx', 'u1', 'u2', 'u3'],
optimization_level=0
).draw(fold=-1, output="mpl")
qiskit.transpile(
circuits=qml._last_predict_circuits[0],
basis_gates=['cx', 'u1', 'u2', 'u3'],
optimization_level=3
).draw(fold=-1, output="mpl")
X_train = X[45:61]
y_train = y[45:61]
X_test = X[[33, 63]]
y_test = y[[33, 63]]
_X = pipeline.fit_transform(X, y)
_X_train = pipeline.transform(X_train)
_X_test = pipeline.transform(X_test)
plt.scatter(
_X[:,0], _X[:,1],
color=['red' if yy == 0 else 'blue' for yy in y], s=10)
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.show()
pipeline.fit(X_train, y_train)
pipeline.predict(X_test), y_test
qml._last_predict_circuits[0].draw(fold=-1, output="mpl")
PassManager([Decompose(MottonenStatePreparationGate)]).run(qml._last_predict_circuits[0]).draw(fold=-1, output="mpl")
qiskit.transpile(circuits=qml._last_predict_circuits[0], optimization_level=0, backend=execution_backend).draw(fold=120, output="mpl")
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import json
from typing import Any, Callable, Optional, Tuple, Union
from urllib.parse import urljoin
from qiskit import QuantumCircuit, execute
from qiskit.providers import JobStatus
from qiskit.providers.ibmq.job import IBMQJob
from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint
from .exercises import get_question_id
from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate
def _circuit_criteria(
circuit: QuantumCircuit,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[int], Optional[int]]:
if max_qubits is not None and circuit.num_qubits > max_qubits:
print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.')
print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.')
return None, None
try:
if check_gates and not uses_multiqubit_gate(circuit):
print('Your circuit appears to not use any multi-quibit gates.')
print('Please review your circuit and try again.')
return None, None
cost = compute_cost(circuit)
if min_cost is not None and cost < min_cost:
print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n'
'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.')
return None, None
return circuit.num_qubits, cost
except Exception as err:
print(f'Unable to compute cost: {err}')
return None, None
def _circuit_grading(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
payload = None
server = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or '
'the grading servers are down right now.')
return None, None
else:
server = None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
payload = {
'answer': circuit_to_json(circuit)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _job_grading(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str):
print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}')
print(f'Please submit a job as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading '
'servers are down right now.')
return None, None
else:
server = None
job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id
if not job:
print('An invalid or non-existent job was specified.')
return None, None
job_status = job.status()
if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]:
print(f'Job did not successfully complete: {job_status.value}.')
return None, None
elif job_status is not JobStatus.DONE:
print(f'Job has not yet completed: {job_status.value}.')
print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.')
return None, None
header = job.result().header.to_dict()
if 'qc_cost' not in header:
if is_submit:
print('An unprepared answer was specified. '
'Please prepare() and grade() answer before submitting.')
else:
print('An unprepared answer was specified. Please prepare() answer before grading.')
return None, None
download_url, result_url = get_job_urls(job)
if not download_url or not result_url:
print('Unable to obtain job URLs')
return None, None
payload = {
'answer': json.dumps({
'download_url': download_url,
'result_url': result_url
})
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _number_grading(
answer: int,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(answer, int):
print(f'Expected a integer, but was given {type(answer)}')
print(f'Please provide a number as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server '
'or the grading servers are down right now.')
return None, None
else:
server = None
payload = {
'answer': str(answer)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def prepare_circuit(
circuit: QuantumCircuit,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit.')
return None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiment. Please wait...')
job = execute(
circuit,
qobj_header={
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def prepare_solver(
solver_func: Callable,
lab_id: str,
ex_id: str,
problem_set: Optional[Any] = None,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not callable(solver_func):
print(f'Expected a function, but was given {type(solver_func)}')
print(f'Please provide a function that returns a QuantumCircuit.')
return None
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading servers are down right now.')
return
endpoint = server + 'problem-set'
index, value = get_problem_set(lab_id, ex_id, endpoint)
print(f'Running {solver_func.__name__}...')
qc_1 = solver_func(problem_set)
_, cost = _circuit_criteria(
qc_1,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if value and index is not None and index >= 0 and cost is not None:
qc_2 = solver_func(value)
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiments. Please wait...')
job = execute(
[qc_1, qc_2],
qobj_header={
'qc_index': [None, index],
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def grade_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, server = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=False,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_job(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str
) -> bool:
payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def submit_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, _ = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=True,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_job(
job_or_id: IBMQJob,
lab_id: str,
ex_id: str,
) -> bool:
payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def get_problem_set(
lab_id: str, ex_id: str, endpoint: str
) -> Tuple[Optional[int], Optional[Any]]:
problem_set_response = None
try:
payload = {'question_id': get_question_id(lab_id, ex_id)}
problem_set_response = send_request(endpoint, query=payload, method='GET')
except Exception as err:
print('Unable to obtain the problem set')
if problem_set_response:
status = problem_set_response.get('status')
if status == 'valid':
try:
index = problem_set_response.get('index')
value = json.loads(problem_set_response.get('value'))
return index, value
except Exception as err:
print(f'Problem set could not be processed: {err}')
else:
cause = problem_set_response.get('cause')
print(f'Problem set failed: {cause}')
return None, None
def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool:
try:
answer_response = send_request(endpoint, body=payload)
status = answer_response.get('status', None)
cause = answer_response.get('cause', None)
score = cost if cost else answer_response.get('score', None)
handle_grade_response(status, score=score, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def submit_answer(payload: dict) -> bool:
try:
access_token = get_access_token()
baseurl = get_submission_endpoint()
endpoint = urljoin(baseurl, './challenges/answers')
submit_response = send_request(
endpoint,
body=payload,
query={'access_token': access_token}
)
status = submit_response.get('status', None)
if status is None:
status = submit_response.get('valid', None)
cause = submit_response.get('cause', None)
handle_submit_response(status, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def handle_grade_response(
status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None
) -> None:
if status == 'valid':
print('\nCongratulations 🎉! Your answer is correct.')
if score is not None:
print(f'Your score is {score}.')
elif status == 'invalid':
print(f'\nOops 😕! {cause}')
print('Please review your answer and try again.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete then try again.')
else:
print(f'Failed: {cause}')
print('Unable to grade your answer.')
def handle_submit_response(
status: Union[str, bool], cause: Optional[str] = None
) -> None:
if status == 'valid' or status is True:
print('\nSuccess 🎉! Your answer has been submitted.')
elif status == 'invalid' or status is False:
print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}')
print('Make sure your answer is correct and successfully graded before submitting.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete, grade it, and then try to submit again.')
else:
print(f'Failed: {cause}')
print('Unable to submit your answer at this time.')
|
https://github.com/JavaFXpert/qiskit4devs-workshop-notebooks
|
JavaFXpert
|
#!pip install qiskit
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 1 qubit (wire).
qr = QuantumRegister(1)
# Create a Classical Register with 1 bit (double wire).
cr = ClassicalRegister(1)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place an Hadamard gate on the qubit wire
circ.h(qr[0])
# Measure the qubit into the classical register
circ.measure(qr, cr)
# Draw the circuit
circ.draw(output='mpl')
# Import BasicAer
from qiskit import BasicAer
# Use BasicAer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 100 times.
job_sim = execute(circ, backend_sim, shots=100)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
from qiskit.tools.visualization import plot_histogram
# Plot the results on a bar chart
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 1 qubit (wire).
# Create a Classical Register with 1 bit (double wire).
# Create a Quantum Circuit from the quantum and classical registers
# Place an X gate followed by a Hadamard gate on the qubit wire. The registers are zero-indexed.
# Measure the qubit into the classical register
# Draw the circuit
# Import BasicAer
# Use BasicAer's qasm_simulator
# Execute the circuit on the qasm simulator, running it 100 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a bar chart
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Sampler Pub class
"""
from __future__ import annotations
from collections.abc import Mapping
from numbers import Integral
from typing import Tuple, Union
from qiskit import QuantumCircuit
from qiskit.circuit import CircuitInstruction
from .bindings_array import BindingsArray, BindingsArrayLike
from .shape import ShapedMixin
# Public API classes
__all__ = ["SamplerPubLike"]
class SamplerPub(ShapedMixin):
"""Pub (Primitive Unified Bloc) for a Sampler.
Pub is composed of tuple (circuit, parameter_values, shots).
If shots are provided this number of shots will be run with the sampler,
if ``shots=None`` the number of run shots is determined by the sampler.
"""
def __init__(
self,
circuit: QuantumCircuit,
parameter_values: BindingsArray | None = None,
shots: int | None = None,
validate: bool = True,
):
"""Initialize a sampler pub.
Args:
circuit: A quantum circuit.
parameter_values: A bindings array.
shots: A specific number of shots to run with. This value takes
precedence over any value owed by or supplied to a sampler.
validate: If ``True``, the input data is validated during initialization.
"""
super().__init__()
self._circuit = circuit
self._parameter_values = parameter_values or BindingsArray()
self._shots = shots
self._shape = self._parameter_values.shape
if validate:
self.validate()
@property
def circuit(self) -> QuantumCircuit:
"""A quantum circuit."""
return self._circuit
@property
def parameter_values(self) -> BindingsArray:
"""A bindings array."""
return self._parameter_values
@property
def shots(self) -> int | None:
"""An specific number of shots to run with (optional).
This value takes precedence over any value owed by or supplied to a sampler.
"""
return self._shots
@classmethod
def coerce(cls, pub: SamplerPubLike, shots: int | None = None) -> SamplerPub:
"""Coerce a :class:`~.SamplerPubLike` object into a :class:`~.SamplerPub` instance.
Args:
pub: An object to coerce.
shots: An optional default number of shots to use if not
already specified by the pub-like object.
Returns:
A coerced sampler pub.
"""
# Validate shots kwarg if provided
if shots is not None:
if not isinstance(shots, Integral) or isinstance(shots, bool):
raise TypeError("shots must be an integer")
if shots <= 0:
raise ValueError("shots must be positive")
if isinstance(pub, SamplerPub):
if pub.shots is None and shots is not None:
return cls(
circuit=pub.circuit,
parameter_values=pub.parameter_values,
shots=shots,
validate=False, # Assume Pub is already validated
)
return pub
if isinstance(pub, QuantumCircuit):
return cls(circuit=pub, shots=shots, validate=True)
if isinstance(pub, CircuitInstruction):
raise ValueError(
f"An invalid Sampler pub-like was given ({type(pub)}). "
"If you want to run a single circuit, "
"you need to wrap it with `[]` like `sampler.run([circuit])` "
"instead of `sampler.run(circuit)`."
)
if len(pub) not in [1, 2, 3]:
raise ValueError(
f"The length of pub must be 1, 2 or 3, but length {len(pub)} is given."
)
circuit = pub[0]
if len(pub) > 1 and pub[1] is not None:
values = pub[1]
if not isinstance(values, (BindingsArray, Mapping)):
values = {tuple(circuit.parameters): values}
parameter_values = BindingsArray.coerce(values)
else:
parameter_values = None
if len(pub) > 2 and pub[2] is not None:
shots = pub[2]
return cls(circuit=circuit, parameter_values=parameter_values, shots=shots, validate=True)
def validate(self):
"""Validate the pub."""
if not isinstance(self.circuit, QuantumCircuit):
raise TypeError("circuit must be QuantumCircuit.")
self.parameter_values.validate()
if self.shots is not None:
if not isinstance(self.shots, Integral) or isinstance(self.shots, bool):
raise TypeError("shots must be an integer")
if self.shots <= 0:
raise ValueError("shots must be positive")
# Cross validate circuits and parameter values
num_parameters = self.parameter_values.num_parameters
if num_parameters != self.circuit.num_parameters:
message = (
f"The number of values ({num_parameters}) does not match "
f"the number of parameters ({self.circuit.num_parameters}) for the circuit."
)
if num_parameters == 0:
message += (
" Note that if you want to run a single pub, you need to wrap it with `[]` like "
"`sampler.run([(circuit, param_values)])` instead of "
"`sampler.run((circuit, param_values))`."
)
raise ValueError(message)
SamplerPubLike = Union[
QuantumCircuit,
Tuple[QuantumCircuit],
Tuple[QuantumCircuit, BindingsArrayLike],
Tuple[QuantumCircuit, BindingsArrayLike, Union[Integral, None]],
]
"""A Pub (Primitive Unified Bloc) for a Sampler.
A fully specified sample Pub is a tuple ``(circuit, parameter_values, shots)``.
If shots are provided this number of shots will be run with the sampler,
if ``shots=None`` the number of run shots is determined by the sampler.
.. note::
A Sampler Pub can also be initialized in the following formats which
will be converted to the full Pub tuple:
* ``circuit``
* ``(circuit,)``
* ``(circuit, parameter_values)``
"""
|
https://github.com/CodeJP97/QHT-2022-WoQ
|
CodeJP97
|
import networkx as nx
from qiskit import QuantumCircuit, Aer
from qiskit.circuit import Parameter
import numpy as np
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_nodes_from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
G.add_weighted_edges_from([(1, 2, 0.1), (2, 0, 0.5), (0, 3, 0.3), (0, 4, 0.4), (0, 5, 1.0), (3, 5, 0.2), (3, 4, 0.5), (1, 6, 1.0), (1, 7, 0.7), (1, 8, 0.4), (6, 7, 0.3), (7, 8, 0.6), (2, 9, 0.1), (2, 10, 0.4), (9, 10, 1.0), (3, 6, 0.9), (2, 9, 0.3)])
colors = [0,0,0,0,0,0,0,0,0,0,0]
def draw_graph(G,colors):
default_axes = plt.axes(frameon=False)
pos=nx.spring_layout(G, seed= 5)
nx.draw_networkx(G, node_size=300, alpha=0.6, ax=default_axes, pos=pos, node_color=colors)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
draw_graph(G,colors)
def create_qaoa_circuit(G,theta):
p = len(theta)//2
gamma = theta[p:]
beta = theta[:p]
##your code goes here
qaoa_circuit = QuantumCircuit(len(G.nodes()))
for i in range(qaoa_circuit.num_qubits):
qaoa_circuit.h(i)
for i in range(p):
for edge in list(G.edges()):
qaoa_circuit.rzz(2*gamma[i],edge[0],edge[1])
for j in range(qaoa_circuit.num_qubits):
qaoa_circuit.rx(2*beta[i],j)
qaoa_circuit.measure_all()
##
return qaoa_circuit #qaoa_circuit should be of type QuantumCircuit
def get_weights(graph):
w = np.zeros([len(graph.nodes()), len(graph.nodes())])
for i in range(len(graph.nodes())):
for j in range(len(graph.nodes())):
x = graph.get_edge_data(i, j, default = 0)
if x != 0:
w[i, j] = x["weight"]
return w
w
def get_cost(graph, state):
##your code goes here
cost = 0
weights = get_weights(graph)
for i,j in graph.edges():
if state[i] != state[j]:
cost -= 1*weights[i, j]
##
return cost
def expectation_value(graph, counts):
## your code goes here
avg = 0
sum_count = 0
for state, count in counts.items():
cost = get_cost(graph, state)
avg += cost*count
sum_count += count
##
return avg/sum_count
def run_qpu(graph, shots=512):
backend = Aer.get_backend('aer_simulator')
backend.shots = shots
def run_circuit(theta):
qc = create_qaoa_circuit(graph, theta)
counts = backend.run(qc, seed_simulator = 5, nshots= shots).result().get_counts()
return expectation_value(graph,counts)
return run_circuit
from scipy.optimize import minimize
p=1
theta = [1.0 for i in range(2*p)]
exp_value = run_qpu(G)
res = minimize(exp_value, theta , method = 'COBYLA')
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('aer_simulator')
backend.shots = 512
qc_res = create_qaoa_circuit(G, res.x)
counts = backend.run(qc_res, seed_simulator = 5).result().get_counts()
strings = list(counts.keys())
probs = list(counts.values())
max_prob = max(probs)
max_string = strings[probs.index(max_prob)]
print('The optimal Bitstring is {} with probabilty {}'.format(max_string, max_prob/512) )
rescale = [i/512 for i in probs]
plt.plot(strings,rescale)
plt.xlabel('bit-strings')
plt.ylabel('Probabilities')
colors = [int(max_string[i]) for i in range(len(max_string))]
draw_graph(G,colors)
|
https://github.com/ctuning/ck-qiskit
|
ctuning
|
#!/usr/bin/env python3
import qiskit.tools.apps.optimization
num_of_qubits = 2
circuit_depth = 6
num_params = 2 * num_of_qubits * circuit_depth # make sure you set this correctly to the number of parameters used by the ansatz
## Previously used for Hydrogen VQE in QISKit implementation
#
def universal_ansatz(current_params, entangler_map=None):
if entangler_map==None:
# Which qubits to use (0 to 1 best to avoid qiskit bugs)
entangler_map = {1: [0]}
return qiskit.tools.apps.optimization.trial_circuit_ryrz(num_of_qubits, circuit_depth, current_params, entangler_map, None, False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.