repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/Soumyo2121/Basic-Quantum-Algorithms
|
Soumyo2121
|
import qiskit
from qiskit import *
n = int(input("Enter the length of binry string: "))
n_q = n
n_c = n
qc = QuantumCircuit(n_q,n_c)
for i in range(n):
qc.h(i)
qc.measure(i,i)
qc.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
# This code is a Qiskit project.
# (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.
from __future__ import annotations
import pytest
import logging
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library import UnitaryGate
from qiskit.circuit.library.standard_gates import (
RXXGate,
RYYGate,
RZZGate,
RZXGate,
XXPlusYYGate,
XXMinusYYGate,
CHGate,
CXGate,
CYGate,
CZGate,
CSGate,
CSdgGate,
CSXGate,
CRXGate,
CRYGate,
CRZGate,
CPhaseGate,
ECRGate,
SwapGate,
iSwapGate,
DCXGate,
)
from qiskit.quantum_info import PauliList, random_unitary
from qiskit.primitives import Estimator
from qiskit_ibm_runtime import SamplerV2
from qiskit_aer import AerSimulator
from qiskit_aer.primitives import Sampler
from circuit_knitting.utils.simulation import ExactSampler
from circuit_knitting.cutting import (
partition_problem,
generate_cutting_experiments,
reconstruct_expectation_values,
)
from circuit_knitting.cutting.instructions import Move
logger = logging.getLogger(__name__)
def append_random_unitary(circuit: QuantumCircuit, qubits):
circuit.unitary(random_unitary(2 ** len(qubits)), qubits)
@pytest.fixture(
params=[
[SwapGate()],
[iSwapGate()],
[DCXGate()],
[CXGate()],
[CYGate()],
[CZGate()],
[CHGate()],
[ECRGate()],
[CSXGate()],
[CSXGate().inverse()],
[CSGate()],
[CSdgGate()],
[RYYGate(0.0)],
[RZZGate(np.pi)],
[RXXGate(np.pi / 3)],
[RYYGate(np.pi / 7)],
[RZZGate(np.pi / 11)],
[CRXGate(0.0)],
[CRYGate(np.pi)],
[CRZGate(np.pi / 2)],
[CRXGate(np.pi / 3)],
[CRYGate(np.pi / 7)],
[CRZGate(np.pi / 11)],
[RXXGate(np.pi / 3), CRYGate(np.pi / 7)],
[CPhaseGate(np.pi / 3)],
[RXXGate(np.pi / 3), CPhaseGate(np.pi / 7)],
[UnitaryGate(random_unitary(2**2))],
[RZXGate(np.pi / 5)],
# XXPlusYYGate, XXMinusYYGate, with some combinations:
# beta == 0 or not; and
# within |theta| < pi or not
[XXPlusYYGate(7 * np.pi / 11)],
[XXPlusYYGate(17 * np.pi / 11, beta=0.4)],
[XXPlusYYGate(-19 * np.pi / 11, beta=0.3)],
[XXMinusYYGate(11 * np.pi / 17)],
[Move()],
[Move(), Move()],
]
)
def example_circuit(request) -> QuantumCircuit:
"""Fixture for an example circuit.
Except for the parametrized gates, the system can be separated according to
the partition labels "AAB".
"""
qc = QuantumCircuit(3)
cut_indices = []
for instruction in request.param:
if instruction.name == "move" and len(cut_indices) % 2 == 1:
# We should not entangle qubit 1 with the remainder of the system.
# In fact, we're also assuming that the previous operation here was
# a move.
append_random_unitary(qc, [0])
append_random_unitary(qc, [1])
else:
append_random_unitary(qc, [0, 1])
append_random_unitary(qc, [2])
cut_indices.append(len(qc.data))
qubits = [1, 2]
if len(cut_indices) % 2 == 0:
qubits.reverse()
qc.append(instruction, qubits)
qc.barrier()
append_random_unitary(qc, [0, 1])
qc.barrier()
append_random_unitary(qc, [2])
return qc
def test_cutting_exact_reconstruction(example_circuit):
"""Test gate-cut circuit vs original circuit on statevector simulator"""
qc = example_circuit
observables = PauliList(["III", "IIY", "XII", "XYZ", "iZZZ", "-XZI"])
phases = np.array([(-1j) ** obs.phase for obs in observables])
observables_nophase = PauliList(["III", "IIY", "XII", "XYZ", "ZZZ", "XZI"])
estimator = Estimator()
exact_expvals = (
estimator.run([qc] * len(observables), list(observables)).result().values
)
subcircuits, bases, subobservables = partition_problem(
qc, "AAB", observables=observables_nophase
)
subexperiments, coefficients = generate_cutting_experiments(
subcircuits, subobservables, num_samples=np.inf
)
if np.random.randint(2):
# Re-use a single sampler
sampler = ExactSampler()
samplers = {label: sampler for label in subcircuits.keys()}
else:
# One sampler per partition
samplers = {label: ExactSampler() for label in subcircuits.keys()}
results = {
label: sampler.run(subexperiments[label]).result()
for label, sampler in samplers.items()
}
reconstructed_expvals = reconstruct_expectation_values(
results, coefficients, subobservables
)
reconstructed_expvals *= phases
logger.info("Max error: %f", np.max(np.abs(exact_expvals - reconstructed_expvals)))
assert np.allclose(exact_expvals, reconstructed_expvals, atol=1e-8)
@pytest.mark.parametrize(
"sampler,is_exact_sampler",
[(Sampler(), False), (SamplerV2(AerSimulator()), False), (ExactSampler(), True)],
)
def test_sampler_with_identity_subobservable(sampler, is_exact_sampler):
"""This test ensures that the sampler works for a subcircuit with no observable measurements.
Specifically, that
- ``Sampler`` does not blow up (Issue #422); and
- ``ExactSampler`` returns correct results
This is related to https://github.com/Qiskit-Extensions/circuit-knitting-toolbox/issues/422.
"""
# Create a circuit to cut
qc = QuantumCircuit(3)
append_random_unitary(qc, [0, 1])
append_random_unitary(qc, [2])
qc.rxx(np.pi / 3, 1, 2)
append_random_unitary(qc, [0, 1])
append_random_unitary(qc, [2])
# Determine expectation value using cutting
observables = PauliList(
["IIZ"]
) # Without the workaround to Issue #422, this observable causes a Sampler error.
subcircuits, bases, subobservables = partition_problem(
qc, "AAB", observables=observables
)
subexperiments, coefficients = generate_cutting_experiments(
subcircuits, subobservables, num_samples=np.inf
)
samplers = {label: sampler for label in subexperiments.keys()}
results = {
label: sampler.run(subexperiments[label]).result()
for label, sampler in samplers.items()
}
reconstructed_expvals = reconstruct_expectation_values(
results, coefficients, subobservables
)
if is_exact_sampler:
# Determine exact expectation values
estimator = Estimator()
exact_expvals = (
estimator.run([qc] * len(observables), list(observables)).result().values
)
logger.info(
"Max error: %f", np.max(np.abs(exact_expvals - reconstructed_expvals))
)
# Ensure both methods yielded equivalent expectation values
assert np.allclose(exact_expvals, reconstructed_expvals, atol=1e-8)
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for PTM 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.operators.channel import PTM
from .channel_test_case import ChannelTestCase
class TestPTM(ChannelTestCase):
"""Tests for PTM channel representation."""
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = PTM(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat16 = np.eye(16) / 4
chan = PTM(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(chan.num_qubits, 2)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, PTM, mat16, input_dims=2, output_dims=4)
# Non multi-qubit dimensions should raise exception
self.assertRaises(QiskitError, PTM, np.eye(6) / 2, input_dims=3, output_dims=2)
def test_circuit_init(self):
"""Test initialization from a circuit."""
circuit, target = self.simple_circuit_no_measure()
op = PTM(circuit)
target = PTM(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, PTM, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4, real=True)
self.assertEqual(PTM(mat), PTM(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = PTM(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = PTM(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = PTM(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(PTM(self.depol_ptm(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(PTM(1.25 * self.ptmI - 0.25 * self.depol_ptm(1)).is_cptp())
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, PTM(np.eye(4)).compose, PTM(np.eye(16)))
self.assertRaises(QiskitError, PTM(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = PTM(self.ptmX)
chan2 = PTM(self.ptmY)
chan = chan1.compose(chan2)
rho_targ = rho.evolve(PTM(self.ptmZ))
self.assertEqual(rho.evolve(chan), rho_targ)
# 50% depolarizing channel
chan1 = PTM(self.depol_ptm(0.5))
chan = chan1.compose(chan1)
rho_targ = rho.evolve(PTM(self.depol_ptm(0.75)))
self.assertEqual(rho.evolve(chan), rho_targ)
# Compose random
ptm1 = self.rand_matrix(4, 4, real=True)
ptm2 = self.rand_matrix(4, 4, real=True)
chan1 = PTM(ptm1, input_dims=2, output_dims=2)
chan2 = PTM(ptm2, input_dims=2, output_dims=2)
rho_targ = rho.evolve(chan1).evolve(chan2)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho.evolve(chan), rho_targ)
chan = chan1 & chan2
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho.evolve(chan), rho_targ)
def test_dot(self):
"""Test dot method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = PTM(self.ptmX)
chan2 = PTM(self.ptmY)
rho_targ = rho.evolve(PTM(self.ptmZ))
self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ)
# Compose random
ptm1 = self.rand_matrix(4, 4, real=True)
ptm2 = self.rand_matrix(4, 4, real=True)
chan1 = PTM(ptm1, input_dims=2, output_dims=2)
chan2 = PTM(ptm2, input_dims=2, output_dims=2)
rho_targ = rho.evolve(chan1).evolve(chan2)
self.assertEqual(rho.evolve(chan2.dot(chan1)), rho_targ)
self.assertEqual(rho.evolve(chan2 @ chan1), rho_targ)
def test_compose_front(self):
"""Test deprecated front compose method."""
# Random input test state
rho = DensityMatrix(self.rand_rho(2))
# UnitaryChannel evolution
chan1 = PTM(self.ptmX)
chan2 = PTM(self.ptmY)
chan = chan2.compose(chan1, front=True)
rho_targ = rho.evolve(PTM(self.ptmZ))
self.assertEqual(rho.evolve(chan), rho_targ)
# Compose random
ptm1 = self.rand_matrix(4, 4, real=True)
ptm2 = self.rand_matrix(4, 4, real=True)
chan1 = PTM(ptm1, input_dims=2, output_dims=2)
chan2 = PTM(ptm2, input_dims=2, output_dims=2)
rho_targ = rho.evolve(chan1).evolve(chan2)
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(rho.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 = PTM(self.ptmI)
chan2 = PTM(self.ptmX)
# 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 = PTM(self.depol_ptm(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 = PTM(self.ptmI)
chan2 = PTM(self.ptmX)
# 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 = PTM(self.depol_ptm(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
p_id = 0.9
depol = PTM(self.depol_ptm(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = PTM(self.depol_ptm(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.ptmI
mat2 = 0.5 * self.depol_ptm(1)
chan1 = PTM(mat1)
chan2 = PTM(mat2)
targ = PTM(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = PTM(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = PTM(mat)
op0 = PTM(mat0)
op1 = PTM(mat1)
op01 = op1.tensor(op0)
eye = PTM(self.ptmI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = PTM(mat)
op0 = PTM(mat0)
op1 = PTM(mat1)
op01 = op1.tensor(op0)
eye = PTM(self.ptmI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = PTM(self.ptmI)
chan2 = PTM(np.eye(16))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = PTM(self.ptmI)
val = 0.5
targ = PTM(val * self.ptmI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = PTM(self.ptmI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = PTM(self.ptmI)
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"""
chan = PTM(self.ptmI)
targ = PTM(-self.ptmI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Contains functions used by the basic provider simulators.
"""
from __future__ import annotations
from string import ascii_uppercase, ascii_lowercase
import numpy as np
import qiskit.circuit.library.standard_gates as gates
from qiskit.exceptions import QiskitError
# Single qubit gates supported by ``single_gate_params``.
SINGLE_QUBIT_GATES = {
"U": gates.UGate,
"u": gates.UGate,
"u1": gates.U1Gate,
"u2": gates.U2Gate,
"u3": gates.U3Gate,
"h": gates.HGate,
"p": gates.PhaseGate,
"s": gates.SGate,
"sdg": gates.SdgGate,
"sx": gates.SXGate,
"sxdg": gates.SXdgGate,
"t": gates.TGate,
"tdg": gates.TdgGate,
"x": gates.XGate,
"y": gates.YGate,
"z": gates.ZGate,
"id": gates.IGate,
"i": gates.IGate,
"r": gates.RGate,
"rx": gates.RXGate,
"ry": gates.RYGate,
"rz": gates.RZGate,
}
def single_gate_matrix(gate: str, params: list[float] | None = None) -> np.ndarray:
"""Get the matrix for a single qubit.
Args:
gate: the single qubit gate name
params: the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
Raises:
QiskitError: If a gate outside the supported set is passed in for the
``Gate`` argument.
"""
if params is None:
params = []
if gate in SINGLE_QUBIT_GATES:
gc = SINGLE_QUBIT_GATES[gate]
else:
raise QiskitError("Gate is not a valid basis gate for this simulator: %s" % gate)
return gc(*params).to_matrix()
# Two qubit gates WITHOUT parameters: name -> matrix
TWO_QUBIT_GATES = {
"CX": gates.CXGate().to_matrix(),
"cx": gates.CXGate().to_matrix(),
"ecr": gates.ECRGate().to_matrix(),
"cy": gates.CYGate().to_matrix(),
"cz": gates.CZGate().to_matrix(),
"swap": gates.SwapGate().to_matrix(),
"iswap": gates.iSwapGate().to_matrix(),
"ch": gates.CHGate().to_matrix(),
"cs": gates.CSGate().to_matrix(),
"csdg": gates.CSdgGate().to_matrix(),
"csx": gates.CSXGate().to_matrix(),
"dcx": gates.DCXGate().to_matrix(),
}
# Two qubit gates WITH parameters: name -> class
TWO_QUBIT_GATES_WITH_PARAMETERS = {
"cp": gates.CPhaseGate,
"crx": gates.CRXGate,
"cry": gates.CRYGate,
"crz": gates.CRZGate,
"cu": gates.CUGate,
"cu1": gates.CU1Gate,
"cu3": gates.CU3Gate,
"rxx": gates.RXXGate,
"ryy": gates.RYYGate,
"rzz": gates.RZZGate,
"rzx": gates.RZXGate,
"xx_minus_yy": gates.XXMinusYYGate,
"xx_plus_yy": gates.XXPlusYYGate,
}
# Three qubit gates: name -> matrix
THREE_QUBIT_GATES = {
"ccx": gates.CCXGate().to_matrix(),
"ccz": gates.CCZGate().to_matrix(),
"rccx": gates.RCCXGate().to_matrix(),
"cswap": gates.CSwapGate().to_matrix(),
}
def einsum_matmul_index(gate_indices: list[int], number_of_qubits: int) -> str:
"""Return the index string for Numpy.einsum matrix-matrix multiplication.
The returned indices are to perform a matrix multiplication A.B where
the matrix A is an M-qubit matrix, matrix B is an N-qubit matrix, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on B.
Args:
gate_indices (list[int]): the indices of the right matrix subsystems
to contract with the left matrix.
number_of_qubits (int): the total number of qubits for the right matrix.
Returns:
str: An indices string for the Numpy.einsum function.
"""
mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits)
# Right indices for the N-qubit input and output tensor
tens_r = ascii_uppercase[:number_of_qubits]
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return f"{mat_l}{mat_r}, {tens_lin}{tens_r}->{tens_lout}{tens_r}"
def einsum_vecmul_index(gate_indices: list[int], number_of_qubits: int) -> str:
"""Return the index string for Numpy.einsum matrix-vector multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, vector v is an N-qubit vector, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on v.
Args:
gate_indices (list[int]): the indices of the right matrix subsystems
to contract with the left matrix.
number_of_qubits (int): the total number of qubits for the right matrix.
Returns:
str: An indices string for the Numpy.einsum function.
"""
mat_l, mat_r, tens_lin, tens_lout = _einsum_matmul_index_helper(gate_indices, number_of_qubits)
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return f"{mat_l}{mat_r}, {tens_lin}->{tens_lout}"
def _einsum_matmul_index_helper(
gate_indices: list[int], number_of_qubits: int
) -> tuple[str, str, str, str]:
"""Return the index string for Numpy.einsum matrix multiplication.
The returned indices are to perform a matrix multiplication A.v where
the matrix A is an M-qubit matrix, matrix v is an N-qubit vector, and
M <= N, and identity matrices are implied on the subsystems where A has no
support on v.
Args:
gate_indices (list[int]): the indices of the right matrix subsystems
to contract with the left matrix.
number_of_qubits (int): the total number of qubits for the right matrix.
Returns:
tuple: (mat_left, mat_right, tens_in, tens_out) of index strings for
that may be combined into a Numpy.einsum function string.
Raises:
QiskitError: if the total number of qubits plus the number of
contracted indices is greater than 26.
"""
# Since we use ASCII alphabet for einsum index labels we are limited
# to 26 total free left (lowercase) and 26 right (uppercase) indexes.
# The rank of the contracted tensor reduces this as we need to use that
# many characters for the contracted indices
if len(gate_indices) + number_of_qubits > 26:
raise QiskitError("Total number of free indexes limited to 26")
# Indices for N-qubit input tensor
tens_in = ascii_lowercase[:number_of_qubits]
# Indices for the N-qubit output tensor
tens_out = list(tens_in)
# Left and right indices for the M-qubit multiplying tensor
mat_left = ""
mat_right = ""
# Update left indices for mat and output
for pos, idx in enumerate(reversed(gate_indices)):
mat_left += ascii_lowercase[-1 - pos]
mat_right += tens_in[-1 - idx]
tens_out[-1 - idx] = ascii_lowercase[-1 - pos]
tens_out = "".join(tens_out)
# Combine indices into matrix multiplication string format
# for numpy.einsum function
return mat_left, mat_right, tens_in, tens_out
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QFT
def create_qpe_circuit(theta, num_qubits):
'''Creates a QPE circuit given theta and num_qubits.'''
# Step 1: Create a circuit with two quantum registers and one classical register.
first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation
second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi>
classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout
qpe_circuit = QuantumCircuit(first, second, classical)
# Step 2: Initialize the qubits.
# All qubits are initialized in |0> by default, no extra code is needed to initialize the first register.
qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example.
# Step 3: Create superposition in the first register.
qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization.
qpe_circuit.h(first)
# Step 4: Apply a controlled-U^(2^j) black box.
qpe_circuit.barrier()
for j in range(num_qubits):
qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor.
# Step 5: Apply an inverse QFT to the first register.
qpe_circuit.barrier()
qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True)
# Step 6: Measure the first register.
qpe_circuit.barrier()
qpe_circuit.measure(first, classical)
return qpe_circuit
num_qubits = 4
qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2.
qpe_circuit_fixed_phase.draw('mpl')
from qiskit.circuit import Parameter
theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later.
qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits)
qpe_circuit_parameterized.draw('mpl')
number_of_phases = 21
phases = np.linspace(0, 2, number_of_phases)
individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists.
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
results = Sampler().run(
[qpe_circuit_parameterized]*len(individual_phases),
parameter_values=individual_phases
).result()
from qiskit.tools.visualization import plot_histogram
idx = 6
plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}'])
def most_likely_bitstring(results_dict):
'''Finds the most likely outcome bit string from a result dictionary.'''
return max(results_dict, key=results_dict.get)
def find_neighbors(bitstring):
'''Finds the neighbors of a bit string.
Example:
For bit string '1010', this function returns ('1001', '1011')
'''
if bitstring == len(bitstring)*'0':
neighbor_left = len(bitstring)*'1'
else:
neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring))
if bitstring == len(bitstring)*'1':
neighbor_right = len(bitstring)*'0'
else:
neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring))
return (neighbor_left, neighbor_right)
def estimate_phase(results_dict):
'''Estimates the phase from a result dictionary of a QPE circuit.'''
# Find the most likely outcome bit string N1 and its neighbors.
num_1_key = most_likely_bitstring(results_dict)
neighbor_left, neighbor_right = find_neighbors(num_1_key)
# Get probabilities of N1 and its neighbors.
num_1_prob = results_dict.get(num_1_key)
neighbor_left_prob = results_dict.get(neighbor_left)
neighbor_right_prob = results_dict.get(neighbor_right)
# Find the second most likely outcome N2 and its probability P2 among the neighbors.
if neighbor_left_prob is None:
# neighbor_left doesn't exist
if neighbor_right_prob is None:
# both neighbors don't exist, N2 is N1
num_2_key = num_1_key
num_2_prob = num_1_prob
else:
# If only neighbor_left doesn't exist, N2 is neighbor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
elif neighbor_right_prob is None:
# If only neighbor_right doesn't exist, N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
elif neighbor_left_prob > neighbor_right_prob:
# Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
else:
# Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
# Calculate the estimated phases for N1 and N2.
num_qubits = len(num_1_key)
num_1_phase = (int(num_1_key, 2) / 2**num_qubits)
num_2_phase = (int(num_2_key, 2) / 2**num_qubits)
# Calculate the weighted average phase from N1 and N2.
phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob)
return phase_estimated
qpe_solutions = []
for idx, result_dict in enumerate(results.quasi_dists):
qpe_solutions.append(estimate_phase(result_dict.binary_probabilities()))
ideal_solutions = np.append(
phases[:(number_of_phases-1)//2], # first period
np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period
)
ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 6))
plt.plot(phases, ideal_solutions, '--', label='Ideal solutions')
plt.plot(phases, qpe_solutions, 'o', label='QPE solutions')
plt.title('Quantum Phase Estimation Algorithm')
plt.xlabel('Input Phase')
plt.ylabel('Output Phase')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
|
hamburgerguy
|
"""Qiskit code for running Simon's algorithm on quantum hardware for 2 qubits and b = '11' """
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
#set b equal to '11'
b = '11'
#1) initialize qubits
n = 2
simon_circuit_2 = QuantumCircuit(n*2, n)
#2) Apply Hadamard gates before querying the oracle
simon_circuit_2.h(range(n))
#3) Query oracle
simon_circuit_2 += simon_oracle(b)
#5) Apply Hadamard gates to the input register
simon_circuit_2.h(range(n))
#3) and 6) Measure qubits
simon_circuit_2.measure(range(n), range(n))
# Load saved IBMQ accounts and get the least busy backend device
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Execute and monitor the job
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
# Get results and plot counts
device_counts = job.result().get_counts()
plot_histogram(device_counts)
#additionally, function for calculating dot product of results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
print('b = ' + b)
for z in device_counts:
print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots))
#the most significant results are those for which b dot z=0(mod 2).
'''b = 11
11.00 = 0 (mod 2) (45.0%)
11.01 = 1 (mod 2) (6.2%)
11.10 = 1 (mod 2) (6.4%)
11.11 = 0 (mod 2) (42.4%)'''
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/ctuning/ck-qiskit
|
ctuning
|
# 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.
"""
Quantum teleportation example.
Note: if you have only cloned the Qiskit repository but not
used `pip install`, the examples only work from the root directory.
"""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
###############################################################
# Set the backend name and coupling map.
###############################################################
coupling_map = [[0, 1], [0, 2], [1, 2], [3, 2], [3, 4], [4, 2]]
backend = BasicAer.get_backend("qasm_simulator")
###############################################################
# Make a quantum program for quantum teleportation.
###############################################################
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
c2 = ClassicalRegister(1, "c2")
qc = QuantumCircuit(q, c0, c1, c2, name="teleport")
# Prepare an initial state
qc.u(0.3, 0.2, 0.1, q[0])
# Prepare a Bell pair
qc.h(q[1])
qc.cx(q[1], q[2])
# Barrier following state preparation
qc.barrier(q)
# Measure in the Bell basis
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[0], c0[0])
qc.measure(q[1], c1[0])
# Apply a correction
qc.barrier(q)
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.measure(q[2], c2[0])
###############################################################
# Execute.
# Experiment does not support feedback, so we use the simulator
###############################################################
# First version: not mapped
initial_layout = {q[0]: 0, q[1]: 1, q[2]: 2}
job = execute(qc, backend=backend, coupling_map=None, shots=1024, initial_layout=initial_layout)
result = job.result()
print(result.get_counts(qc))
# Second version: mapped to 2x8 array coupling graph
job = execute(
qc, backend=backend, coupling_map=coupling_map, shots=1024, initial_layout=initial_layout
)
result = job.result()
print(result.get_counts(qc))
# Both versions should give the same distribution
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
%load_ext autoreload
%autoreload 2
import nbimporter
from typing import Dict, Tuple, List
import numpy as np
from tqdm import tqdm
QUBITS_NUM = 4
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
NUM_ITERATIONS = 100
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
from qiskit import Aer
from qiskit.utils import QuantumInstance, algorithm_globals
seed = 50
algorithm_globals.random_seed = seed
simulator_backend = Aer.get_backend('qasm_simulator')
from scipy.optimize import minimize
from linear_entangelment_and_full_entangelment_ansatz_circuits import *
def get_ansatz_state(thetas, ansatz_entangelment, input_state):
if ansatz_entangelment=="full":
return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state)
if ansatz_entangelment=="linear":
return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state)
def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List:
pauli_operators = hamiltonian.to_pauli_op().settings['oplist']
pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators))
pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators))
return pauli_coeffs, pauli_strings
from qiskit.circuit.library.standard_gates import HGate, SGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
reducing_to_pauli_z_mapping = {
'I': 'I',
'Z': 'Z',
'X': 'Z',
'Y': 'Z'
}
def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str:
reduced_pauli_string = ""
for matrix_index in range(QUBITS_NUM):
pauli_matrix = str(pauli_string[matrix_index])
reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix]
reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string
return reduced_pauli_string
def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit):
quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit")
additional_circuit_layer = QuantumCircuit(quantum_registers)
for quantum_register_index, pauli_matrix in enumerate(pauli_string):
if pauli_matrix == "X":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
if pauli_string == "Y":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]])
extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer)
return extended_quantum_circuit
def get_probability_distribution(counts: Dict) -> Dict:
proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()}
return proba_distribution
def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict:
quantum_state_circuit.measure_all()
transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend)
Qobj = assemble(transpiled_quantum_state_circuit)
result = simulator_backend.run(Qobj).result()
counts = result.get_counts(quantum_state_circuit)
return get_probability_distribution(counts)
def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict:
return dict(sorted(proba_distribution.items()))
def reset_power_of_minus_1(power_of_minus_1):
power_of_minus_1 = 0
return power_of_minus_1
def convert_pauli_string_into_str(pauli_string) -> str:
return str(pauli_string)
def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit):
pauli_string_expectation_value = 0
power_of_minus_1 = 0
pauli_string_str = convert_pauli_string_into_str(pauli_string)
extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit)
probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit)
reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string)
sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution)
for qubits_string, proba in sorted_probas_distribuition.items():
for string_index in range(QUBITS_NUM):
if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"):
power_of_minus_1 += 1
pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba
power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1)
return pauli_string_expectation_value
def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings):
total_expection_value = 0
for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)):
total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas(
pauli_string, ansatz_circuit)
return total_expection_value
from qiskit import assemble, transpile
def cost_function(thetas, hamiltonian, ansatz_entangelment):
initial_eigenvector = np.identity(N)[0]
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector)
L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings)
insert_approximated_energy_to_list_of_all_approximated_energies(L)
return L
def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment):
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM)
optimizer_result = minimize(cost_function,
x0=initial_thetas,
args=(hamiltonian, ansatz_entangelment),
method="CG",
options={"maxiter":NUM_ITERATIONS,
"disp": True})
optimal_thetas = optimizer_result.x
return optimal_thetas
def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment):
optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment)
print(optimal_thetas)
initial_eigenvector = np.identity(N)[0]
optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector)
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings)
return approximated_eigenvalue
from numpy import linalg as LA
def get_approximation_error(exact_eigenvalue, approximated_eigenvalue):
return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue)
def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian):
eigen_values = LA.eigvals(hamiltonian.to_matrix())
print(sorted(eigen_values))
return min(sorted(eigen_values))
def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue):
exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian)
print("Exact Eigenvalue:")
print(exact_eigenvalue)
print("\nApproximated Eigenvalue:")
print(approximated_eigenvalue)
print("\nApproximation Error")
print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue))
plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3)
approximated_energies = []
def insert_approximated_energy_to_list_of_all_approximated_energies(energy):
approximated_energies.append(energy)
import matplotlib.pyplot as plt
def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin):
plt.title("convergence of optimization process to the exact eigenvalue")
plt.margins(0, margin)
plt.plot(approximated_energies[-NUM_ITERATIONS:])
plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-')
plt.grid()
plt.xlabel("# of iterations")
plt.ylabel("Energy")
def plot_fidelity():
plt.plot(LiH_approximated_energies)
plt.xlabel("# of iterations")
plt.ylabel("Energy")
from qiskit.opflow import X, Z, I, H, Y
LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \
-0.0029329964409502266*(X^X^Y^Y) + \
0.0029329964409502266*(X^Y^Y^X) + \
0.01291078027311749*(X^Z^X^I) + \
-0.0013743761078958677*(X^Z^X^Z) + \
0.011536413200774975*(X^I^X^I) + \
0.0029329964409502266*(Y^X^X^Y) + \
-0.0029329964409502266*(Y^Y^X^X) + \
0.01291078027311749*(Y^Z^Y^I) + \
-0.0013743761078958677*(Y^Z^Y^Z) + \
0.011536413200774975*(Y^I^Y^I) + \
0.16199475388004184*(Z^I^I^I) + \
0.011536413200774975*(Z^X^Z^X) + \
0.011536413200774975*(Z^Y^Z^Y) + \
0.12444770133137588*(Z^Z^I^I) + \
0.054130445793298836*(Z^I^Z^I) + \
0.05706344223424907*(Z^I^I^Z) + \
0.012910780273117487*(I^X^Z^X) + \
-0.0013743761078958677*(I^X^I^X) + \
0.012910780273117487*(I^Y^Z^Y) + \
-0.0013743761078958677*(I^Y^I^Y) + \
0.16199475388004186*(I^Z^I^I) + \
0.05706344223424907*(I^Z^Z^I) + \
0.054130445793298836*(I^Z^I^Z) + \
-0.013243698330265966*(I^I^Z^I) + \
0.08479609543670981*(I^I^Z^Z) + \
-0.013243698330265952*(I^I^I^Z)
%%time
LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear")
compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue)
%%time
LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full")
compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue)
H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \
+ 0.1721839326191554 * (I^I^I^Z) \
- 0.22575349222402372 * (I^I^Z^I) \
+ 0.17218393261915543 * (I^Z^I^I) \
- 0.2257534922240237 * (Z^I^I^I) \
+ 0.12091263261776627 * (I^I^Z^Z) \
+ 0.16892753870087907 * (I^Z^I^Z) \
+ 0.045232799946057826 * (Y^Y^Y^Y) \
+ 0.045232799946057826 * (X^X^Y^Y) \
+ 0.045232799946057826 * (Y^Y^X^X) \
+ 0.045232799946057826 * (X^X^X^X) \
+ 0.1661454325638241 * (Z^I^I^Z) \
+ 0.1661454325638241 * (I^Z^Z^I) \
+ 0.17464343068300453 * (Z^I^Z^I) \
+ 0.12091263261776627 * (Z^Z^I^I)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue)
transverse_ising_4_qubits = 0.0 * (I^I^I^I) \
+ 0.8398088405253477 * (X^I^I^I) \
+ 0.7989496312070936 * (I^X^I^I) \
+ 0.38189710487113193 * (Z^Z^I^I) \
+ 0.057753122422666725 * (I^I^X^I) \
+ 0.5633292636970458 * (Z^I^Z^I) \
+ 0.3152740621483513 * (I^Z^Z^I) \
+ 0.07209487981989715 * (I^I^I^X) \
+ 0.17892334004292654 * (Z^I^I^Z) \
+ 0.2273896497668042 * (I^Z^I^Z) \
+ 0.09762902934216211 * (I^I^Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear")
compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full")
compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue)
QUBITS_NUM = 3
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
NUM_ITERATIONS = 1000
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
from qiskit.opflow import X, Z, I
transverse_ising_3_qubits = 0.0 * (I^I^I) \
+ 0.012764169333459807 * (X^I^I) \
+ 0.7691573729160869 * (I^X^I) \
+ 0.398094746026449 * (Z^Z^I) \
+ 0.15250261906586637 * (I^I^X) \
+ 0.2094051920882264 * (Z^I^Z) \
+ 0.5131291860752999 * (I^Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear")
compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full")
compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue)
QUBITS_NUM = 2
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
NUM_ITERATIONS = 1000
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \
+ 0.43305656297810435 * (X^I) \
+ 0.8538597608997253 * (Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear")
compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full")
compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue)
from qiskit.opflow import X, Z, I
H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \
-0.3277380754984016*(Z^I) + \
0.15567463610622564*(Z^Z) + \
-0.3277380754984016*(I^Z)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full")
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
|
https://github.com/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
|
rubenandrebarreiro
|
# import the quantum circuit and the quantum register
# from the IBM's Qiskit library
from qiskit import QuantumCircuit, QuantumRegister
# import the Sparse Pauli operator from
# the IBM's Qiskit quantum information module
from qiskit.quantum_info import SparsePauliOp
# defome the function to generate a Sparse Pauli operator
# for the Heisenberg's Hamiltonian
def heisenberg_hamiltonian(
length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0
) -> SparsePauliOp:
# create an empty list for the terms
terms = []
# for each index ranged for the number of qubits on
# the Heisenberg's Hamiltonian
for i in range( ( length - 1 ) ):
# if it is pretended to append a XX operator term to
# the Heisenberg's Hamiltonian operator
if jx:
# append a XX operator term to
# the Heisenberg's Hamiltonian operator
terms.append( ( "XX", [i, i + 1], jx ) )
# if it is pretended to append a YY operator term to
# the Heisenberg's Hamiltonian operator
if jy:
# append a YY operator term to
# the Heisenberg's Hamiltonian operator
terms.append( ( "YY", [i, i + 1], jy ) )
# if it is pretended to append a ZZ operator term to
# the Heisenberg's Hamiltonian operator
if jz:
# append a ZZ operator term to
# the Heisenberg's Hamiltonian operator
terms.append( ( "ZZ", [i, i + 1], jz ) )
# return the Sparse Pauli operator
# for the Heisenberg's Hamiltonian
return SparsePauliOp.from_sparse_list(terms, num_qubits=length)
# define a function to generate the quantum circuit for the state preparation
def state_prep_circuit( num_qubits: int, layers: int = 1 ) -> QuantumCircuit:
# create a quantum register with the number of qubits pretended
qubits = QuantumRegister(num_qubits, name="q")
# create a quantum circuit with the quantum register defined before
circuit = QuantumCircuit(qubits)
# apply a Hadamard gate to
# the quantum circuit, on all the qubits
circuit.h(qubits)
# for each layer of the quantum circuit
for _ in range(layers):
# for each 2n-th qubit
for i in range(0, ( num_qubits - 1 ), 2):
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on the current qubit
# and target on the next qubit
circuit.cx( qubits[i], qubits[ ( i + 1 ) ] )
# apply a RY (Rotation-Y) gate to
# the quantum circuit, on the 1st qubit,
# with the theta angle equal to 0.1
# on all the qubits
circuit.ry( 0.1, qubits )
# for each (2n + 1)-th qubit
for i in range(1, ( num_qubits - 1 ), 2):
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on the current qubit
# and target on the next qubit
circuit.cx( qubits[i], qubits[ ( i + 1 ) ] )
# apply a RY (Rotation-Y) gate to
# the quantum circuit, on the 1st qubit,
# with the theta angle equal to 0.1
# on all the qubits
circuit.ry(0.1, qubits)
# return the quantum circuit for the state preparation
return circuit
# define the number of qubits for
# the Heisenberg's Hamiltonian operator and
# for the state preparation quantum circuit
length = 5
# create the Heisenberg's Hamiltonian operator
# for the number of qubits defined before
hamiltonian = heisenberg_hamiltonian( length, 1.0, 1.0 )
# create the state preparation quantum circuit
# for the number of qubits defined before
circuit = state_prep_circuit( length, layers=2 )
# print the Heisenberg's Hamiltonian operator
print(hamiltonian)
# draw the quantum circuit implementing
# a state preparation
circuit.draw("mpl")
# import estimator from IBM's Qiskit
# Aer primitives module
from qiskit_aer.primitives import Estimator
# create an Estimator object with approximation
estimator = Estimator( approximation=True )
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=None )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the exact expectation value (energy)
# from the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
exact_value = result.values[0]
# print the exact expectation value (energy)
# from the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
print( f"Exact energy: {exact_value}" )
# import the IBM's Qiskit Runtime Service
# from the Qiskit IBM's Runtime
from qiskit_ibm_runtime import QiskitRuntimeService
# define the hub for the IBM's Qiskit
# Runtime Service
hub = "ibm-q-internal"
# define the group for the IBM's Qiskit
# Runtime Service
group = "deployed"
# define the project for the IBM's Qiskit
# Runtime Service
project = "default"
# create an IBM's Qiskit Runtime Service
service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}")
# import the estimator, options and session
# for quantum simulations from the Qiskit IBM Runtime module
from qiskit_ibm_runtime import Estimator, Options, Session
# import the coupling map from
# the IBM's Qiskit Transpiler module
from qiskit.transpiler import CouplingMap
# define the backend to run the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime
backend = service.get_backend("simulator_statevector")
# set the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime
simulator = {
"basis_gates": ["id", "rz", "sx", "cx", "reset"],
"coupling_map": list(CouplingMap.from_line(length + 1)),
}
# define the number of shots for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime
shots = 10000
# import the built-in math module
import math
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 0 (zero)
options = Options(
simulator=simulator,
resilience_level=0,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# import the noise model and the readout error
# from the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import NoiseModel, ReadoutError
# create a noise model
noise_model = NoiseModel()
##### your code here #####
# create the measurement miss-assignments and
# correct measurement probabilities
# create the measurement miss-assignment
# probabilities for the 1st qubit,
# for the erroneous measurement outcomes
qubit0_p0_given1 = 0.2
qubit0_p1_given0 = 0.5
# create the correct measurement
# probabilities for the 1st qubit
qubit0_p0_given0 = (1 - qubit0_p0_given1)
qubit0_p1_given1 = (1 - qubit0_p1_given0)
# create the measurement miss-assignment
# probabilities for the remaining qubits k_i,
# for the erroneous measurement outcomes
qubitk_p0_given1 = 0.02
qubitk_p1_given0 = 0.05
# create the correct measurement
# probabilities for the remaining qubits k_i
qubitk_p0_given0 = (1 - qubitk_p0_given1)
qubitk_p1_given1 = (1 - qubitk_p1_given0)
# create the readout error objects
# create a readout error for the 1st qubit
readout_error_qubit0 = ReadoutError( [ [ qubit0_p0_given0, qubit0_p0_given1 ],
[ qubit0_p1_given0, qubit0_p1_given1 ] ] )
# ceeate a readout error for the remaining qubits k_i
readout_error_qubitk = ReadoutError( [ [ qubitk_p0_given0, qubitk_p0_given1 ],
[ qubitk_p1_given0, qubitk_p1_given1 ] ] )
# add a readout error to the noise model for the 1st qubit
noise_model.add_readout_error( readout_error_qubit0, [0] )
# for each of the remaining qubits k_i
# note: recall that even though our circuit acts on 5 qubits,
# we will initialize a simulator with 6 qubits in order to
# later demonstrate the potential effects of qubit choice
for k in range( 1, ( length + 1 ) ):
# add a readout error to the noise model
# for the remaining qubits k_i
noise_model.add_readout_error( readout_error_qubitk, [k] )
# print the noise model created before
print(noise_model)
# submit your answer
# import the grader for the exercise 1 of the lab 5
from qc_grader.challenges.qgss_2023 import grade_lab5_ex1
# grade the exercise 1 of the lab 5
grade_lab5_ex1(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# considering the noise model defined before,
# and a resilience level of 0 (zero)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
transpilation=dict( initial_layout=list( range(length) ) ),
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# considering the noise model defined before,
# and a resilience level of 0 (zero),
# but this time, with a layout where
# the 1st qubit is not considered
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
transpilation=dict( initial_layout=list( range(1, ( length + 1 ) ) ) ),
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# considering the noise model defined before,
# and a resilience level of 1 (one),
# but this time, with a layout where
# the 1st qubit is not considered
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=1,
transpilation=dict( initial_layout=list( range( 1, ( length + 1 ) ) ) ),
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the variable for
# the new number of shots
new_shots: int
##### your code here #####
# define the new number of shots
new_shots = 20000
# submit your answer
# import the grader for the exercise 2 of the lab 5
from qc_grader.challenges.qgss_2023 import grade_lab5_ex2
# grade the exercise 2 of the lab 5
grade_lab5_ex2(new_shots)
# import the noise model and the depolarizing error
# from the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import depolarizing_error
# creata a noise model
noise_model = NoiseModel()
##### your code here #####
# create the depolarizaation probability
depolarization_prob = 0.01
# create the depolarization error objects
# create a two-qubit depolarization error for two qubits
depolarizing_error_two_quits = depolarizing_error( depolarization_prob, 2 )
# add the two-qubit depolarization error after each CNOT/CX gate
noise_model.add_all_qubit_quantum_error( depolarizing_error_two_quits, ['cx'] )
# print the noise model created before
print(noise_model)
# submit your answer
# import the grader for the exercise 3 of the lab 5
from qc_grader.challenges.qgss_2023 import grade_lab5_ex3
# grade the exercise 3 of the lab 5
grade_lab5_ex3(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 1 (one)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=1,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 2 (two)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=2,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variances of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian,
# applying Zero-Noise Extrapolation with Noise Amplification
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
# print the statistics for the estimated energy,
# the energy error, and the variances
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
# import Pauli error from
# the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import pauli_error
# create a noise model
noise_model = NoiseModel()
##### your code here #####
# create the Pauli error probability
pauli_error_prob = 0.1
# create the Pauli error objects
# create a bit flip error for a qubit
bit_flip_error = pauli_error( [ ( "X", pauli_error_prob ),
( "I", ( 1 - pauli_error_prob ) ) ] )
# add a bit flip error for a qubit,
# after each Pauli-X, Pauli-Y, Pauli-Z, and Hadamard gate
noise_model.add_all_qubit_quantum_error( bit_flip_error, ["x", "y", "z", "h"] )
# print the noise model created before
print(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 0 (zero)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 1 (one)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 2 (two)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variances of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian,
# applying Zero-Noise Extrapolation with Noise Amplification
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
# print the statistics for the estimated energy,
# the energy error, and the variances
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
# import Pauli error from
# the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import pauli_error
# create a noise model
noise_model = NoiseModel()
##### your code here #####
# create the Pauli error probability
pauli_error_prob = 0.1
# create the Pauli error objects
# create a phase flip error for a qubit
phase_flip_error = pauli_error( [ ( "Z", pauli_error_prob ),
( "I", ( 1 - pauli_error_prob ) ) ] )
# add a phase flip error for a qubit,
# after each Pauli-X, Pauli-Y, Pauli-Z, and Hadamard gate
noise_model.add_all_qubit_quantum_error( phase_flip_error, ["x", "y", "z", "h"] )
# print the noise model created before
print(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 0 (zero)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 1 (one)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=1,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 2 (two)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variances of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian,
# applying Zero-Noise Extrapolation with Noise Amplification
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
# print the statistics for the estimated energy,
# the energy error, and the variances
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
# import Reset error from
# the IBM's Qiskit Aer Noise module
from qiskit_aer.noise import reset_error
# create a noise model
noise_model = NoiseModel()
##### your code here #####
# create the Reset error probabilities
reset_0_prob = 0.2
reset_1_prob = 0.33
# create the Reset error objects
# create a Reset error for a qubit
reset_0_1_error = reset_error( reset_0_prob, reset_1_prob )
# add a Reset error for a qubit,
# after each Pauli-X, Pauli-Y, Pauli-Z, and Hadamard gate
noise_model.add_all_qubit_quantum_error( reset_0_1_error, ["x", "y", "z", "h"] )
# print the noise model created before
print(noise_model)
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 0 (zero)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=0,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 1 (one)
options = Options(
simulator=dict( noise_model=noise_model, **simulator ),
resilience_level=1,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variance from the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
variance = result.metadata[0]["variance"]
# compute the standard deviation of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
std = math.sqrt( variance / shots )
# print the statistics for the estimated energy,
# the energy error, the variance, and the standard error
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
# define the options for the quantum simulation
# to run in the backend, using the IBM's Qiskit Runtime,
# with a resilience level of 2 (two)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
# within the context of a session of the IBM's Qiskit Runtime
with Session( service=service, backend=backend ):
# create an estimator object with the options defined before
estimator = Estimator(options=options)
# create a job for the quantum circuit implementing
# the Heisenberg's Hamiltonian, running the Estimator
job = estimator.run( circuit, hamiltonian, shots=shots )
# retrieve the results of the job ran by
# the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
result = job.result()
# retrieve the values of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian
experiment_value = result.values[0]
# compute the error as the distance between
# the experiment value and the exact value
error = abs(experiment_value - exact_value)
# retrieve the variances of the results of
# the job ran by the Estimator created before,
# that was ran on the quantum circuit
# implementing the Heisenberg's Hamiltonian,
# applying Zero-Noise Extrapolation with Noise Amplification
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
# print the statistics for the estimated energy,
# the energy error, and the variances
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
# import the IBM's Qiskit Jupyter Tools
import qiskit.tools.jupyter
# show the table of the IBM's Qiskit version
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
https://arxiv.org/abs/quant-ph/0407010
https://arxiv.org/abs/2108.10182
"""
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qclib.gates.initialize import Initialize
from qclib.state_preparation.util.state_tree_preparation import (
Amplitude,
state_decomposition,
)
from qclib.state_preparation.util.angle_tree_preparation import create_angles_tree
from qclib.state_preparation.util.tree_register import add_register
from qclib.state_preparation.util.tree_walk import top_down
class TopDownInitialize(Initialize):
"""
Top-down state preparation
https://arxiv.org/abs/quant-ph/0407010
https://arxiv.org/abs/2108.10182
This class implements a state preparation gate.
"""
def __init__(self, params, label=None, opt_params=None):
"""
Parameters
----------
params: list of complex
A unit vector representing a quantum state.
Values are amplitudes.
opt_params: {'global_phase': global_phase, 'lib': lib}
global_phase: bool
If ``True``, corrects the global phase.
Default value is ``True``.
lib: str
Library to be used.
Default value is ``'qclib'``.
"""
self._name = "top-down"
self._get_num_qubits(params)
if opt_params is None:
self.global_phase = True
self.lib = "qclib"
else:
if opt_params.get("global_phase") is None:
self.global_phase = True
else:
self.global_phase = opt_params.get("global_phase")
if opt_params.get("lib") is None:
self.lib = "qclib"
else:
self.lib = opt_params.get("lib")
if label is None:
label = "TDSP"
super().__init__(self._name, self.num_qubits, params, label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
if self.lib == "qiskit":
reg = QuantumRegister(self.num_qubits)
circuit = QuantumCircuit(reg)
# pylint: disable=maybe-no-member
circuit.initialize(self.params)
return circuit
data = [Amplitude(i, a) for i, a in enumerate(self.params)]
state_tree = state_decomposition(self.num_qubits, data)
angle_tree = create_angles_tree(state_tree)
circuit = QuantumCircuit()
add_register(circuit, angle_tree, 0)
top_down(angle_tree, circuit, 0)
if self.global_phase:
circuit.global_phase += sum(np.angle(self.params)) / len(self.params)
return circuit
@staticmethod
def initialize(q_circuit, state, qubits=None, opt_params=None):
"""
Appends a TopDownInitialize gate into the q_circuit
"""
if qubits is None:
q_circuit.append(
TopDownInitialize(state, opt_params=opt_params), q_circuit.qubits
)
else:
q_circuit.append(TopDownInitialize(state, opt_params=opt_params), qubits)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QFT
def create_qpe_circuit(theta, num_qubits):
'''Creates a QPE circuit given theta and num_qubits.'''
# Step 1: Create a circuit with two quantum registers and one classical register.
first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation
second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi>
classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout
qpe_circuit = QuantumCircuit(first, second, classical)
# Step 2: Initialize the qubits.
# All qubits are initialized in |0> by default, no extra code is needed to initialize the first register.
qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example.
# Step 3: Create superposition in the first register.
qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization.
qpe_circuit.h(first)
# Step 4: Apply a controlled-U^(2^j) black box.
qpe_circuit.barrier()
for j in range(num_qubits):
qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor.
# Step 5: Apply an inverse QFT to the first register.
qpe_circuit.barrier()
qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True)
# Step 6: Measure the first register.
qpe_circuit.barrier()
qpe_circuit.measure(first, classical)
return qpe_circuit
num_qubits = 4
qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2.
qpe_circuit_fixed_phase.draw('mpl')
from qiskit.circuit import Parameter
theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later.
qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits)
qpe_circuit_parameterized.draw('mpl')
number_of_phases = 21
phases = np.linspace(0, 2, number_of_phases)
individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists.
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
results = Sampler().run(
[qpe_circuit_parameterized]*len(individual_phases),
parameter_values=individual_phases
).result()
from qiskit.tools.visualization import plot_histogram
idx = 6
plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}'])
def most_likely_bitstring(results_dict):
'''Finds the most likely outcome bit string from a result dictionary.'''
return max(results_dict, key=results_dict.get)
def find_neighbors(bitstring):
'''Finds the neighbors of a bit string.
Example:
For bit string '1010', this function returns ('1001', '1011')
'''
if bitstring == len(bitstring)*'0':
neighbor_left = len(bitstring)*'1'
else:
neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring))
if bitstring == len(bitstring)*'1':
neighbor_right = len(bitstring)*'0'
else:
neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring))
return (neighbor_left, neighbor_right)
def estimate_phase(results_dict):
'''Estimates the phase from a result dictionary of a QPE circuit.'''
# Find the most likely outcome bit string N1 and its neighbors.
num_1_key = most_likely_bitstring(results_dict)
neighbor_left, neighbor_right = find_neighbors(num_1_key)
# Get probabilities of N1 and its neighbors.
num_1_prob = results_dict.get(num_1_key)
neighbor_left_prob = results_dict.get(neighbor_left)
neighbor_right_prob = results_dict.get(neighbor_right)
# Find the second most likely outcome N2 and its probability P2 among the neighbors.
if neighbor_left_prob is None:
# neighbor_left doesn't exist
if neighbor_right_prob is None:
# both neighbors don't exist, N2 is N1
num_2_key = num_1_key
num_2_prob = num_1_prob
else:
# If only neighbor_left doesn't exist, N2 is neighbor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
elif neighbor_right_prob is None:
# If only neighbor_right doesn't exist, N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
elif neighbor_left_prob > neighbor_right_prob:
# Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
else:
# Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
# Calculate the estimated phases for N1 and N2.
num_qubits = len(num_1_key)
num_1_phase = (int(num_1_key, 2) / 2**num_qubits)
num_2_phase = (int(num_2_key, 2) / 2**num_qubits)
# Calculate the weighted average phase from N1 and N2.
phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob)
return phase_estimated
qpe_solutions = []
for idx, result_dict in enumerate(results.quasi_dists):
qpe_solutions.append(estimate_phase(result_dict.binary_probabilities()))
ideal_solutions = np.append(
phases[:(number_of_phases-1)//2], # first period
np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period
)
ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 6))
plt.plot(phases, ideal_solutions, '--', label='Ideal solutions')
plt.plot(phases, qpe_solutions, 'o', label='QPE solutions')
plt.title('Quantum Phase Estimation Algorithm')
plt.xlabel('Input Phase')
plt.ylabel('Output Phase')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_lima')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
def qc_qft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'QFT')
for l in range(0, n):
qc.h(qr[l])
if l < n-1:
for q in range(l+1, n):
lb = 2*math.pi*2**(-q+l-1)
qc.cp(lb, qr[q], qr[l])
#qc.barrier()
#qc.barrier()
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(0, ul):
qc.swap(p, n-1-p)
return qc
n = 4; qc_qft_ = qc_qft(n); qc_qft_.draw(output='mpl')
def qc_iqft(n):
qr = QuantumRegister(n); qc = QuantumCircuit(qr, name = 'IQFT')
if n%2 == 0:
ul = n//2
else:
ul = (n-1)//2
for p in range(ul-1, -1, -1):
qc.swap(p, n-1-p)
#qc.barrier()
for l in range(n-1, -1, -1):
if l < n-1:
for q in range(n-1, l+1-1, -1):
lb = -2*math.pi*2**(-q+l-1)#; print(lb)
qc.cp(lb, qr[q], qr[l])
qc.h(qr[l])
#qc.barrier()
return qc
n = 4; qc_iqft_ = qc_iqft(n); qc_iqft_.draw(output='mpl')
#x0 = 1 + 0*1j; x1 = 0 + 0*1j # estado |0>
#x0 = 0 + 0*1j; x1 = 1 + 0*1j # estado |1>
x0 = 1/math.sqrt(2) + 0*1j; x1 = 1/math.sqrt(2) + 0*1j # estado |+>
mx0 = math.sqrt(x0.real**2 + x0.imag**2)
if x0.real != 0:
ph0 = math.atan(x0.imag/x0.real)
elif x0.real == 0 and x0.imag != 0:
ph0 = math.pi/2
elif x0.real == 0 and x0.imag == 0:
ph0 = 0
mx1 = math.sqrt(x1.real**2 + x1.imag**2)
if x1.real != 0:
ph1 = math.atan(x1.imag/x1.real)
elif x1.real == 0 and x1.imag != 0:
ph1 = math.pi/2
elif x1.real == 0 and x1.imag == 0:
ph1 = 0
print('|x0|=',mx0,', ph0=', ph0,', |x1|=', mx1,', ph1=', ph1)
th = 2*math.acos(mx1); ph = ph1-ph0+math.pi; lb = ph0-math.pi
print('th=',th,', ph=', ph,', lb=', lb)
n = 1
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
qc.x(qr[0]); qc.u(th, ph, lb, qr[0]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc))
def tfc(x): # classical discrete Fourier transform
d = len(x)
y = np.zeros(d, dtype = complex)
for k in range(0, d):
for j in range(0, d):
y[k] += x[j]*(math.cos(2*math.pi*j*k/d) + 1j*math.sin(2*math.pi*j*k/d))
return y/math.sqrt(d)
d = 4; x = np.zeros(d, dtype = complex);
#x = [1/2, 1/2, 1/2, 1/2]
x = [-1/2, -1/2, 1/2, 1/2]
y = tfc(x); print(y)
n = 2
qr = QuantumRegister(n); qc = QuantumCircuit(qr)
#qc.h([0,1]); qc.barrier() # ok
qc.x([0]); qc.h([0,1]); qc.barrier() # ok a menos de uma fase global de pi
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1])
qc.draw(output='mpl')
svsimulator = Aer.get_backend('statevector_simulator')
job = execute(qc, backend = svsimulator, shots = 1, memory = True)
print(job.result().get_statevector(qc)) # para >1 qubit tem a questao da ordem da bc
d = 4; x = np.zeros(d, dtype = complex);
x = [math.sqrt(1/6), math.sqrt(1/6), math.sqrt(2/3), 0]
y = tfc(x); print(y)
n = 3
qr = QuantumRegister(n); cr = ClassicalRegister(n); qc = QuantumCircuit(qr, cr)
qc.x([0,2]); qc.barrier()
qc_qft_ = qc_qft(n); qft = qc_qft_.to_gate(); qc.append(qft, [0,1,2]); qc.barrier()
qc_iqft_ = qc_iqft(n); iqft = qc_iqft_.to_gate(); qc.append(iqft, [0,1,2]); qc.barrier()
qc.measure([0,1,2],[0,1,2])
qc.draw(output='mpl')
job_sim = execute(qc, backend = simulator, shots = nshots)
job_exp = execute(qc, backend = device, shots = nshots)
job_monitor(job_exp)
plot_histogram([job_sim.result().get_counts(), job_exp.result().get_counts()],
legend = ['sim', 'exp'])
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
my_list = [1,3,6,8,2,7,5,7,9,2,16,4]
def my_oracle(my_input):
winner = 9
response = False
if winner == my_input:
response = True
return response
for index, number in enumerate(my_list):
if (my_oracle(number) == True):
print("Winner winner chicken dinner! at index = %i"%index)
print("%i times the Oracle was called"%(index+1))
break
from qiskit import *
import matplotlib.pyplot as plt
import numpy as np
# create the oracle quantum circuit
oracle = QuantumCircuit(2, name='oracle')
oracle.cz(0,1) # apply the Controlled-Z gate or CZ gate
oracle.to_gate() # make oracle into its own gate
oracle.draw()
backend = Aer.get_backend('statevector_simulator')
grover_circuit = QuantumCircuit(2,2) # 2 qubits, 2 classical registers
grover_circuit.h([0,1]) # apply hadamard gate on both qubits 0 and 1 to prepare superposition state discussed in description.md
grover_circuit.append(oracle, [0,1]) # append oracle to be able to query each state at same time
grover_circuit.draw()
job = execute(grover_circuit, backend)
result = job.result()
sv = result.get_statevector()
np.around(sv, 2)
reflection = QuantumCircuit(2, name='reflection')
reflection.h([0,1]) # apply hadamard gate on all qubits to bring them back to '00' state from the original 's' state
reflection.z([0,1]) # apply Z gate on both qubits
reflection.cz(0,1) # controlled-z gate
reflection.h([0,1]) # transform back with hadamard on both qubits
reflection.to_gate()
reflection.draw()
backend = Aer.get_backend('qasm_simulator')
grover_circuit = QuantumCircuit(2,2)
grover_circuit.h([0,1])
grover_circuit.append(oracle, [0,1])
grover_circuit.append(reflection, [0,1])
grover_circuit.measure([0,1], [0,1])
grover_circuit.draw()
job = execute(grover_circuit, backend, shots=1)
result = job.result()
result.get_counts()
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr,cr)
%matplotlib inline
circuit.draw(output = 'mpl')
circuit.h(qr[0])
circuit.cx(qr[0],qr[1])
circuit.draw(output = 'mpl')
circuit.measure(qr,cr)
circuit.draw(output = 'mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend = simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_16_melbourne')
job = execute(circuit,backend = qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
|
https://github.com/mentesniker/Quantum-Cryptography
|
mentesniker
|
from qiskit import QuantumCircuit
from qiskit import BasicAer
from qiskit import execute
def encryption(qc, initialString, pk):
for bit in range(0,len(initialString)):
if(initialString[bit] == '1'):
qc.x(bit)
if(pk[2*bit] == '1'):
qc.z(bit)
if(pk[2*bit+1] == '1'):
qc.x(bit)
return qc
def decryption(qc, lenCypher, pk):
for bit in range(0,lenCypher):
if(pk[2*bit] == '1'):
qc.z(bit)
if(pk[2*bit+1] == '1'):
qc.x(bit)
return qc
def generate_random_key(length,backend):
pk = ''
for i in range(0,2*length):
qc = QuantumCircuit(1,1)
qc.h(0)
qc.measure(0,0)
counts = execute(qc, backend=backend, shots=1).result().get_counts(qc)
pk += list(counts.keys())[0]
return pk
def run_circuit(qc,backend):
job = execute(qc, backend, shots=100)
result = job.result()
return result.get_counts(qc)
initialString = '0110'
pk = generate_random_key(len(initialString),backend)
encrypt = QuantumCircuit(len(initialString),len(initialString))
backend = BasicAer.get_backend('qasm_simulator')
encryption(encrypt,initialString,pk)
encrypt.barrier()
encrypt.measure([0,1,2,3],[0,1,2,3])
print("the encrypted string is: " + str(run_circuit(encrypt,backend)))
encrypt.barrier()
decryption(encrypt,len(encrypt.qubits),pk)
encrypt.barrier()
encrypt.measure([0,1,2,3],[0,1,2,3])
print("the original string is: " + str(run_circuit(encrypt,backend)))
encrypt.draw()
|
https://github.com/riachakraborty/Algorithms-
|
riachakraborty
|
# useful additional packages
#%%
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline
# importing Qiskit
from qiskit import Aer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, compile
#from qiskit.tools.monitor import job_monitor, backend_monitor, backend_overview
backend = Aer.get_backend('statevector_simulator')
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Load our saved IBMQ accounts
IBMQ.load_accounts()
n = 12 # the length of the first register for querying the oracle
# Choose a type of oracle at random. With probability half it is constant,
# and with the same probability it is balanced
oracleType, oracleValue = np.random.randint(2), np.random.randint(2)
if oracleType == 0:
print("The oracle returns a constant value ", oracleValue)
else:
print("The oracle returns a balanced function")
a = np.random.randint(1,2**n) # this is a hidden parameter for balanced oracle.
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1) #all qubits are initialized to zero
# for recording the measurement on the first register
cr = ClassicalRegister(n)
circuitName = "DeutschJozsa"
djCircuit = QuantumCircuit(qr, cr)
# Create the superposition of all input queries in the first register by applying the Hadamard gate to each qubit.
for i in range(n):
djCircuit.h(qr[i])
# Flip the second register and apply the Hadamard gate.
djCircuit.x(qr[n])
djCircuit.h(qr[n])
# Apply barrier to mark the beginning of the oracle
djCircuit.barrier()
if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue for all input.
if oracleValue == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # Otherwise, it returns the inner product of the input with a (non-zero bitstring)
for i in range(n):
if (a & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier to mark the end of the oracle
djCircuit.barrier()
# Apply Hadamard gates after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measurement
djCircuit.barrier()
for i in range(n):
djCircuit.measure(qr[i], cr[i])
#draw the circuit
#djCircuit.draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
shots = 1000
job = execute(djCircuit, backend=backend, shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/jdanielescanez/quantum-solver
|
jdanielescanez
|
#!/usr/bin/env python3
# Author: Daniel Escanez-Exposito
from abc import ABC, abstractmethod
from qiskit import QuantumCircuit
from qiskit.circuit.library import YGate, ZGate
from qiskit.circuit.gate import Gate
import qiskit.quantum_info as qi
from numpy.random import randint
import numpy as np
from math import ceil
## An abstract class of a participant entity in the Six-State implementation
## @see https://qiskit.org/textbook/ch-algorithms/quantum-key-distribution.html
class Participant(ABC):
## Constructor
@abstractmethod
def __init__(self, name='', original_bits_size=0):
## The name of the participant
self.name = name
## The original size of the message
self.original_bits_size = original_bits_size
## The values of the participant
self.values = None
## The axes of the participant
self.axes = None
## The key of the participant
self.key = None
## If the key is determined safe
self.is_safe_key = False
## The otp of the participant
self.otp = None
## The gate measuring z and y axes
self.set_hy()
## Values setter
def set_values(self, values=None):
if values == None:
self.values = list(randint(2, size=self.original_bits_size))
else:
self.values = values
## Axes setter
def set_axes(self, axes=None):
if axes == None:
self.axes = list(randint(3, size=self.original_bits_size))
else:
self.axes = axes
## Print values
def show_values(self):
print('\n' + self.name, 'Values:')
print(self.values)
## Print axes
def show_axes(self):
print('\n' + self.name, 'Axes:')
print(self.axes)
## Print key
def show_key(self):
print('\n' + self.name, 'Key:')
print(self.key)
## Print otp
def show_otp(self):
print('\n' + self.name, 'OTP:')
print(self.otp)
## Remove the values of the qubits that were measured on the wrong axis
def remove_garbage(self, another_axes):
self.key = []
for i in range(self.original_bits_size):
if self.axes[i] == another_axes[i]:
self.key.append(self.values[i])
## Check if the shared key is equal to the current key
def check_key(self, shared_key):
return shared_key == self.key[:len(shared_key)]
## Use the rest of the key and validate it
def confirm_key(self, shared_size):
self.key = self.key[shared_size:]
self.is_safe_key = True
## Generate an One-Time Pad
def generate_otp(self, n_bits):
self.otp = []
for i in range(ceil(len(self.key) / n_bits)):
bits_string = ''.join(map(str, self.key[i * n_bits: (i + 1) * n_bits]))
self.otp.append(int(bits_string, 2))
## Performs an XOR operation between the message and the One-Time Pad
def xor_otp_message(self, message):
final_message = ''
CHR_LIMIT = 1114112
if len(self.otp) > 0:
for i, char in enumerate(message):
final_message += chr((ord(char) ^ self.otp[i % len(self.otp)]) % CHR_LIMIT)
return final_message
## New gate setter
def set_hy(self):
hy_op = qi.Operator(1/np.sqrt(2)*(YGate().to_matrix() + ZGate().to_matrix()))
hy_gate = QuantumCircuit(1)
hy_gate.unitary(hy_op, [0], label='h_y')
self.hy = hy_gate.to_gate()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/lynnlangit/learning-quantum
|
lynnlangit
|
try:
import cirq
except ImportError:
print("installing cirq...")
%pip install --quiet cirq
print("installed cirq.")
import cirq
# One Qubit
q = cirq.NamedQubit("a")
# Create a Circuit A and NOT the qubit, then measure
circuit = cirq.Circuit(cirq.X(q), cirq.measure(q, key='measured value') )
print("Circuit A:")
print(circuit)
print()
# Simulate the circuit 10 times
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=10)
print("Results of Circuit A:")
print(result)
# Two Qubits
q0,q1 = cirq.LineQubit.range(2)
# Create a Circuit B and NOT the qubit, use a controlled-X gate on the qubits, then measure
ops = cirq.X(q0), cirq.CNOT(q0,q1),cirq.measure(q0, key='m'),cirq.measure(q1, key='n')
circuit1 = cirq.Circuit(ops )
print("Circuit B:")
print(circuit1)
print()
simulator = cirq.Simulator()
result = simulator.run(circuit1, repetitions=10)
print("Results of Circuit B:")
print(result)
qubit = cirq.NamedQubit("a")
# Create a circuit which puts a qubit into superposition using H, then measure
circuit = cirq.Circuit(cirq.H(qubit), cirq.measure(qubit, key='m') )
print("Circuit C:")
print(circuit)
# Simulate the circuit 10 times
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=10)
print("Results:")
print(result)
import matplotlib.pyplot as plt
qubit = cirq.NamedQubit("a")
# Create a circuit which puts a qubit into superposition using H, then measure
ops = [cirq.H(qubit), cirq.measure(qubit, key='m')]
circuit = cirq.Circuit(ops)
print("Circuit C:")
print(circuit)
# Simulate the circuit 100 times, plot results
result = cirq.Simulator().run(circuit, repetitions=100)
_ = cirq.vis.plot_state_histogram(result, plt.subplot())
a = cirq.NamedQubit("a")
b = cirq.NamedQubit("b")
c = cirq.NamedQubit("c")
# Create a circuit which puts qubits into superposition using H,
# Then entangle two qubits, then measure
ops = [cirq.H(a), cirq.H(b), cirq.CNOT(b,c), cirq.H(b),cirq.measure(b)]
circuit = cirq.Circuit(ops)
print("Circuit D:\n")
print(circuit)
# Simulate the circuit 100 times, plot results
result = cirq.Simulator().run(circuit, repetitions=100)
_ = cirq.vis.plot_state_histogram(result, plt.subplot())
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
#!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 3 qubits
qr = QuantumRegister(3)
# Create a Quantum Circuit from the quantum register. Because we're going to use
# the statevector_simulator, we won't measure the circuit or need classical registers.
circ = QuantumCircuit(qr)
# Place an X gate on the 2nd and 3rd wires. The topmost wire is index 0.
circ.x(qr[1])
circ.x(qr[2])
# Draw the circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
# Execute the circuit on the state vector simulator
job_sim = execute(circ, backend_sv_sim)
# Grab the results from the job.
result_sim = job_sim.result()
# Obtain the state vector for the quantum circuit
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector in a manner that contains a comma-delimited string.
quantum_state
# Plot the state vector on a Q-sphere
from qiskit.tools.visualization import plot_state_qsphere
plot_state_qsphere(quantum_state)
# Create a Classical Register with 3 bits
cr = ClassicalRegister(3)
# Create the measurement portion of a quantum circuit
meas_circ = QuantumCircuit(qr, cr)
# Create a barrier that separates the gates from the measurements
meas_circ.barrier(qr)
# Measure the qubits into the classical registers
meas_circ.measure(qr, cr)
# Add the measument circuit to the original circuit
complete_circuit = circ + meas_circ
# Draw the new circuit
complete_circuit.draw(output='mpl')
# Use the BasicAer qasm_simulator backend
from qiskit import BasicAer
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 1000 times.
job_sim = execute(complete_circuit, backend_sim, shots=1000)
# 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(complete_circuit)
print(counts)
# Plot the results on a histogram
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 3 qubits
# Create a Quantum Circuit from the quantum register. Because we're going to use
# the statevector_simulator, we won't measure the circuit or need classical registers.
# Place Hadamard gate on each of the wires.
# Draw the circuit
# Use the BasicAer statevector_simulator backend
# Execute the circuit on the state vector simulator
# Grab the results from the job.
# Obtain the state vector for the quantum circuit
# Output the quantum state vector in a manner that contains a comma-delimited string.
# Plot the state vector on a Q-sphere
# Create a Classical Register with 3 bits
# Create the measurement portion of a quantum circuit
# Create a barrier that separates the gates from the measurements
# Measure the qubits into the classical registers
# Add the measument circuit to the original circuit
# Draw the new circuit
# Use the BasicAer qasm_simulator backend
# Execute the circuit on the qasm simulator, running it 1000 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a histogram
|
https://github.com/usamisaori/quantum-expressibility-entangling-capability
|
usamisaori
|
import sys
sys.path.append('../')
from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\
sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\
sampleCircuitF
from entanglement import Ent
import warnings
warnings.filterwarnings('ignore')
labels = [
'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3',
'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F'
]
samplers = [
sampleCircuitA,
sampleCircuitB1,
sampleCircuitB2,
sampleCircuitB3,
sampleCircuitC,
sampleCircuitD,
sampleCircuitE,
sampleCircuitF
]
q = 4
for layer in range(1, 4):
print(f'qubtis: {q}')
print('-' * 25)
for (label, sampler) in zip(labels, samplers):
expr = Ent(sampler, layer=layer, epoch=3000)
print(f'{label}(layer={layer}): {expr}')
print()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for quantum channel representation transformations."""
import unittest
import numpy as np
from qiskit import QiskitError
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.channel.choi import Choi
from qiskit.quantum_info.operators.channel.superop import SuperOp
from qiskit.quantum_info.operators.channel.kraus import Kraus
from qiskit.quantum_info.operators.channel.stinespring import Stinespring
from qiskit.quantum_info.operators.channel.ptm import PTM
from qiskit.quantum_info.operators.channel.chi import Chi
from .channel_test_case import ChannelTestCase
class TestTransformations(ChannelTestCase):
"""Tests for Operator channel representation."""
unitary_mat = [
ChannelTestCase.UI,
ChannelTestCase.UX,
ChannelTestCase.UY,
ChannelTestCase.UZ,
ChannelTestCase.UH,
]
unitary_choi = [
ChannelTestCase.choiI,
ChannelTestCase.choiX,
ChannelTestCase.choiY,
ChannelTestCase.choiZ,
ChannelTestCase.choiH,
]
unitary_chi = [
ChannelTestCase.chiI,
ChannelTestCase.chiX,
ChannelTestCase.chiY,
ChannelTestCase.chiZ,
ChannelTestCase.chiH,
]
unitary_sop = [
ChannelTestCase.sopI,
ChannelTestCase.sopX,
ChannelTestCase.sopY,
ChannelTestCase.sopZ,
ChannelTestCase.sopH,
]
unitary_ptm = [
ChannelTestCase.ptmI,
ChannelTestCase.ptmX,
ChannelTestCase.ptmY,
ChannelTestCase.ptmZ,
ChannelTestCase.ptmH,
]
def test_operator_to_operator(self):
"""Test Operator to Operator transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Operator(mat)
chan2 = Operator(chan1)
self.assertEqual(chan1, chan2)
def test_operator_to_choi(self):
"""Test Operator to Choi transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_superop(self):
"""Test Operator to SuperOp transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_kraus(self):
"""Test Operator to Kraus transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Kraus(mat)
chan2 = Kraus(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_stinespring(self):
"""Test Operator to Stinespring transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Stinespring(mat)
chan2 = Stinespring(Operator(chan1))
self.assertEqual(chan1, chan2)
def test_operator_to_chi(self):
"""Test Operator to Chi transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Operator(mat))
self.assertEqual(chan1, chan2)
def test_operator_to_ptm(self):
"""Test Operator to PTM transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Operator(mat))
self.assertEqual(chan1, chan2)
def test_choi_to_operator(self):
"""Test Choi to Operator transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Operator(mat)
chan2 = Operator(Choi(choi))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
def test_choi_to_choi(self):
"""Test Choi to Choi transformation."""
# Test unitary channels
for choi in self.unitary_choi:
chan1 = Choi(choi)
chan2 = Choi(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(chan1)
self.assertEqual(chan1, chan2)
def test_choi_to_superop(self):
"""Test Choi to SuperOp transformation."""
# Test unitary channels
for choi, sop in zip(self.unitary_choi, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Choi(choi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Choi(self.depol_choi(p)))
self.assertEqual(chan1, chan2)
def test_choi_to_kraus(self):
"""Test Choi to Kraus transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Kraus(mat)
chan2 = Kraus(Choi(choi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(Choi(self.depol_choi(p))))
self.assertEqual(output, target)
def test_choi_to_stinespring(self):
"""Test Choi to Stinespring transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Kraus(mat)
chan2 = Kraus(Choi(choi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(Choi(self.depol_choi(p))))
self.assertEqual(output, target)
def test_choi_to_chi(self):
"""Test Choi to Chi transformation."""
# Test unitary channels
for choi, chi in zip(self.unitary_choi, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Choi(choi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(Choi(self.depol_choi(p)))
self.assertEqual(chan1, chan2)
def test_choi_to_ptm(self):
"""Test Choi to PTM transformation."""
# Test unitary channels
for choi, ptm in zip(self.unitary_choi, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Choi(choi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Choi(self.depol_choi(p)))
self.assertEqual(chan1, chan2)
def test_superop_to_operator(self):
"""Test SuperOp to Operator transformation."""
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Operator(mat)
chan2 = Operator(SuperOp(sop))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, SuperOp(self.depol_sop(0.5)))
def test_superop_to_choi(self):
"""Test SuperOp to Choi transformation."""
# Test unitary channels
for choi, sop in zip(self.unitary_choi, self.unitary_sop):
chan1 = Choi(choi)
chan2 = Choi(SuperOp(sop))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0, 0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(SuperOp(self.depol_sop(p)))
self.assertEqual(chan1, chan2)
def test_superop_to_superop(self):
"""Test SuperOp to SuperOp transformation."""
# Test unitary channels
for sop in self.unitary_sop:
chan1 = SuperOp(sop)
chan2 = SuperOp(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0, 0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(chan1)
self.assertEqual(chan1, chan2)
def test_superop_to_kraus(self):
"""Test SuperOp to Kraus transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Kraus(mat)
chan2 = Kraus(SuperOp(sop))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(SuperOp(self.depol_sop(p))))
self.assertEqual(output, target)
def test_superop_to_stinespring(self):
"""Test SuperOp to Stinespring transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Stinespring(mat)
chan2 = Stinespring(SuperOp(sop))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(SuperOp(self.depol_sop(p))))
self.assertEqual(output, target)
def test_superop_to_chi(self):
"""Test SuperOp to Chi transformation."""
# Test unitary channels
for sop, ptm in zip(self.unitary_sop, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(SuperOp(sop))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(SuperOp(self.depol_sop(p)))
self.assertEqual(chan1, chan2)
def test_superop_to_ptm(self):
"""Test SuperOp to PTM transformation."""
# Test unitary channels
for sop, ptm in zip(self.unitary_sop, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(SuperOp(sop))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(SuperOp(self.depol_sop(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_operator(self):
"""Test Kraus to Operator transformation."""
for mat in self.unitary_mat:
chan1 = Operator(mat)
chan2 = Operator(Kraus(mat))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, Kraus(self.depol_kraus(0.5)))
def test_kraus_to_choi(self):
"""Test Kraus to Choi transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_superop(self):
"""Test Kraus to SuperOp transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_kraus(self):
"""Test Kraus to Kraus transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Kraus(mat)
chan2 = Kraus(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Kraus(self.depol_kraus(p))
chan2 = Kraus(chan1)
self.assertEqual(chan1, chan2)
def test_kraus_to_stinespring(self):
"""Test Kraus to Stinespring transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Stinespring(mat)
chan2 = Stinespring(Kraus(mat))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(Kraus(self.depol_kraus(p))))
self.assertEqual(output, target)
def test_kraus_to_chi(self):
"""Test Kraus to Chi transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_kraus_to_ptm(self):
"""Test Kraus to PTM transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Kraus(self.depol_kraus(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_operator(self):
"""Test Stinespring to Operator transformation."""
for mat in self.unitary_mat:
chan1 = Operator(mat)
chan2 = Operator(Stinespring(mat))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, Stinespring(self.depol_stine(0.5)))
def test_stinespring_to_choi(self):
"""Test Stinespring to Choi transformation."""
# Test unitary channels
for mat, choi in zip(self.unitary_mat, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_superop(self):
"""Test Stinespring to SuperOp transformation."""
# Test unitary channels
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Kraus(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_kraus(self):
"""Test Stinespring to Kraus transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Kraus(mat)
chan2 = Kraus(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Kraus(self.depol_kraus(p))
chan2 = Kraus(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_stinespring(self):
"""Test Stinespring to Stinespring transformation."""
# Test unitary channels
for mat in self.unitary_mat:
chan1 = Stinespring(mat)
chan2 = Stinespring(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Stinespring(self.depol_stine(p))
chan2 = Stinespring(chan1)
self.assertEqual(chan1, chan2)
def test_stinespring_to_chi(self):
"""Test Stinespring to Chi transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Chi(chi)
chan2 = Chi(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_stinespring_to_ptm(self):
"""Test Stinespring to PTM transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Stinespring(mat))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Stinespring(self.depol_stine(p)))
self.assertEqual(chan1, chan2)
def test_chi_to_operator(self):
"""Test Chi to Operator transformation."""
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Operator(mat)
chan2 = Operator(Chi(chi))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, Chi(self.depol_chi(0.5)))
def test_chi_to_choi(self):
"""Test Chi to Choi transformation."""
# Test unitary channels
for chi, choi in zip(self.unitary_chi, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(Chi(chi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(Chi(self.depol_chi(p)))
self.assertEqual(chan1, chan2)
def test_chi_to_superop(self):
"""Test Chi to SuperOp transformation."""
# Test unitary channels
for chi, sop in zip(self.unitary_chi, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(Chi(chi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(Chi(self.depol_chi(p)))
self.assertEqual(chan1, chan2)
def test_chi_to_kraus(self):
"""Test Chi to Kraus transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Kraus(mat)
chan2 = Kraus(Chi(chi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(Chi(self.depol_chi(p))))
self.assertEqual(output, target)
def test_chi_to_stinespring(self):
"""Test Chi to Stinespring transformation."""
# Test unitary channels
for mat, chi in zip(self.unitary_mat, self.unitary_chi):
chan1 = Kraus(mat)
chan2 = Kraus(Chi(chi))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(Chi(self.depol_chi(p))))
self.assertEqual(output, target)
def test_chi_to_chi(self):
"""Test Chi to Chi transformation."""
# Test unitary channels
for chi in self.unitary_chi:
chan1 = Chi(chi)
chan2 = Chi(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(chan1)
self.assertEqual(chan1, chan2)
def test_chi_to_ptm(self):
"""Test Chi to PTM transformation."""
# Test unitary channels
for chi, ptm in zip(self.unitary_chi, self.unitary_ptm):
chan1 = PTM(ptm)
chan2 = PTM(Chi(chi))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(Chi(self.depol_chi(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_operator(self):
"""Test PTM to Operator transformation."""
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = Operator(mat)
chan2 = Operator(PTM(ptm))
self.assertTrue(matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, PTM(self.depol_ptm(0.5)))
def test_ptm_to_choi(self):
"""Test PTM to Choi transformation."""
# Test unitary channels
for ptm, choi in zip(self.unitary_ptm, self.unitary_choi):
chan1 = Choi(choi)
chan2 = Choi(PTM(ptm))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Choi(self.depol_choi(p))
chan2 = Choi(PTM(self.depol_ptm(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_superop(self):
"""Test PTM to SuperOp transformation."""
# Test unitary channels
for ptm, sop in zip(self.unitary_ptm, self.unitary_sop):
chan1 = SuperOp(sop)
chan2 = SuperOp(PTM(ptm))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = SuperOp(self.depol_sop(p))
chan2 = SuperOp(PTM(self.depol_ptm(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_kraus(self):
"""Test PTM to Kraus transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = Kraus(mat)
chan2 = Kraus(PTM(ptm))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Kraus(self.depol_kraus(p)))
output = rho.evolve(Kraus(PTM(self.depol_ptm(p))))
self.assertEqual(output, target)
def test_ptm_to_stinespring(self):
"""Test PTM to Stinespring transformation."""
# Test unitary channels
for mat, ptm in zip(self.unitary_mat, self.unitary_ptm):
chan1 = Kraus(mat)
chan2 = Kraus(PTM(ptm))
self.assertTrue(matrix_equal(chan2.data[0], chan1.data[0], ignore_phase=True))
# Test depolarizing channels
rho = DensityMatrix(np.diag([1, 0]))
for p in [0.25, 0.5, 0.75, 1]:
target = rho.evolve(Stinespring(self.depol_stine(p)))
output = rho.evolve(Stinespring(PTM(self.depol_ptm(p))))
self.assertEqual(output, target)
def test_ptm_to_chi(self):
"""Test PTM to Chi transformation."""
# Test unitary channels
for chi, ptm in zip(self.unitary_chi, self.unitary_ptm):
chan1 = Chi(chi)
chan2 = Chi(PTM(ptm))
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = Chi(self.depol_chi(p))
chan2 = Chi(PTM(self.depol_ptm(p)))
self.assertEqual(chan1, chan2)
def test_ptm_to_ptm(self):
"""Test PTM to PTM transformation."""
# Test unitary channels
for ptm in self.unitary_ptm:
chan1 = PTM(ptm)
chan2 = PTM(chan1)
self.assertEqual(chan1, chan2)
# Test depolarizing channels
for p in [0.25, 0.5, 0.75, 1]:
chan1 = PTM(self.depol_ptm(p))
chan2 = PTM(chan1)
self.assertEqual(chan1, chan2)
if __name__ == "__main__":
unittest.main()
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
from qiskit.primitives import Estimator
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.observables_evaluator import estimate_observables
from qiskit.algorithms.optimizers import COBYLA, SLSQP
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.utils import algorithm_globals
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_nature.second_q.mappers import JordanWignerMapper
def kronecker_delta_function(n: int, m: int) -> int:
"""An implementation of the Kronecker delta function.
Args:
n (int): The first integer argument.
m (int): The second integer argument.
Returns:
Returns 1 if n = m, else returns 0.
"""
return int(n == m)
def create_deuteron_hamiltonian(
N: int, hbar_omega: float = 7.0, V_0: float = -5.68658111
) -> SparsePauliOp:
"""Creates a version of the Deuteron Hamiltonian as a qubit operator.
Args:
N (int): An integer number that represents the dimension of the
basis.
hbar_omega (float, optional): The value of the product of hbar and omega. Defaults to 7.0.
V_0 (float, optional): The value of the potential energy. Defaults to -5.68658111.
Returns:
SparsePauliOp: The qubit-space Hamiltonian that represents the Deuteron.
"""
hamiltonian_terms = {}
for m in range(N):
for n in range(N):
label = "+_{} -_{}".format(str(n), str(m))
coefficient_kinect = (hbar_omega / 2) * (
(2 * n + 3 / 2) * kronecker_delta_function(n, m)
- np.sqrt(n * (n + (1 / 2))) * kronecker_delta_function(n, m + 1)
- np.sqrt((n + 1) * (n + (3 / 2)) * kronecker_delta_function(n, m - 1))
)
hamiltonian_terms[label] = coefficient_kinect
coefficient_potential = (
V_0 * kronecker_delta_function(n, 0) * kronecker_delta_function(n, m)
)
hamiltonian_terms[label] += coefficient_potential
hamiltonian = FermionicOp(hamiltonian_terms, num_spin_orbitals=N)
mapper = JordanWignerMapper()
qubit_hamiltonian = mapper.map(hamiltonian)
if not isinstance(qubit_hamiltonian, SparsePauliOp):
qubit_hamiltonian = qubit_hamiltonian.primitive
return qubit_hamiltonian
deuteron_hamiltonians = [create_deuteron_hamiltonian(i) for i in range(1, 5)]
for i, hamiltonian in enumerate(deuteron_hamiltonians):
print("Deuteron Hamiltonian: H_{}".format(i + 1))
print(hamiltonian)
print("\n")
theta = Parameter(r"$\theta$")
eta = Parameter(r"$\eta$")
wavefunction = QuantumCircuit(1)
wavefunction.ry(theta, 0)
wavefunction.draw("mpl")
wavefunction2 = QuantumCircuit(2)
wavefunction2.x(0)
wavefunction2.ry(theta, 1)
wavefunction2.cx(1, 0)
wavefunction2.draw("mpl")
wavefunction3 = QuantumCircuit(3)
wavefunction3.x(0)
wavefunction3.ry(eta, 1)
wavefunction3.ry(theta, 2)
wavefunction3.cx(2, 0)
wavefunction3.cx(0, 1)
wavefunction3.ry(-eta, 1)
wavefunction3.cx(0, 1)
wavefunction3.cx(1, 0)
wavefunction3.draw("mpl")
ansatz = [wavefunction, wavefunction2, wavefunction3]
reference_values = []
print("Exact binding energies calculated through numpy.linalg.eigh \n")
for i, hamiltonian in enumerate(deuteron_hamiltonians):
eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix())
reference_values.append(eigenvalues[0])
print("Exact binding energy for H_{}: {}".format(i + 1, eigenvalues[0]))
print(
"Results using Estimator for H_1, H_2 and H_3 with the ansatz given in the reference paper \n"
)
for i in range(3):
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}: {} MeV".format(i + 1, binding_energy))
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=True)
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
plots = []
for i in range(3):
counts = []
values = []
params = []
deviation = []
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=COBYLA(), callback=callback)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots.append([counts, values])
fig, ax = plt.subplots(nrows=3, ncols=1)
fig.set_size_inches((12, 12))
for i, plot in enumerate(plots):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
twolocal_ansatzes = []
for i in range(1, 5):
ansatz = TwoLocal(
deuteron_hamiltonians[i - 1].num_qubits,
["rz", "ry"],
"cx",
entanglement="full",
reps=i,
initial_state=None,
)
twolocal_ansatzes.append(ansatz)
print("Results using Estimator for H_1, H_2, H_3 and H_4 with TwoLocal ansatz \n")
seed = 42
algorithm_globals.random_seed = seed
for i in range(4):
vqe = VQE(Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}:".format(i + 1), binding_energy, "MeV")
seed = 42
algorithm_globals.random_seed = seed
plots_tl = []
for i in range(4):
counts = []
values = []
params = []
deviation = []
vqe = VQE(
Estimator(),
ansatz=twolocal_ansatzes[i],
optimizer=SLSQP(),
callback=callback,
)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots_tl.append([counts, values])
fig, ax = plt.subplots(nrows=4, ncols=1)
fig.set_size_inches((15, 15))
for i, plot in enumerate(plots_tl):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
def calculate_observables_exp_values(
quantum_circuit: QuantumCircuit, observables: list, angles: list
) -> list:
"""Calculate the expectation value of an observable given the quantum
circuit that represents the wavefunction and a list of parameters.
Args:
quantum_circuit (QuantumCircuit): A parameterized quantum circuit
that represents the wavefunction of the system.
observables (list): A list containing the observables that we want
to know the expectation values.
angles (list): A list with the values that will be used in the
'bind_parameters' method.
Returns:
list_exp_values (list): A list containing the expectation values
of the observables given as input.
"""
list_exp_values = []
for observable in observables:
exp_values = []
for angle in angles:
qc = quantum_circuit.bind_parameters({theta: angle})
result = estimate_observables(
Estimator(),
quantum_state=qc,
observables=[observable],
)
exp_values.append(result[0][0])
list_exp_values.append(exp_values)
return list_exp_values
angles = list(np.linspace(-np.pi, np.pi, 100))
observables = [
Pauli("IZ"),
Pauli("ZI"),
Pauli("XX"),
Pauli("YY"),
deuteron_hamiltonians[1],
]
h2_observables_exp_values = calculate_observables_exp_values(wavefunction2, observables, angles)
fig, ax = plt.subplots(nrows=2, ncols=1)
fig.set_size_inches((12, 12))
ax[0].plot(angles, h2_observables_exp_values[0], "o", label=r"$Z_0$")
ax[0].plot(angles, h2_observables_exp_values[1], "o", label=r"$Z_1$")
ax[0].plot(angles, h2_observables_exp_values[2], "o", label=r"$X_0X_1$")
ax[0].plot(angles, h2_observables_exp_values[3], "o", label=r"$Y_0Y_1$")
ax[0].axhline(
y=1,
color="k",
linestyle="--",
)
ax[0].axhline(y=-1, color="k", linestyle="--")
ax[0].legend()
ax[0].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[0].set_ylabel(r"$\langle O \rangle $ - Operator Expectation Value", fontsize=15)
ax[0].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[0].set_title(
r"Expectation value of the observables $Z_0$, $Z_1$, $X_0X_1$ and $Y_0Y_1$ when we vary $\theta$ in the ansatz.",
fontsize=15,
)
ax[1].plot(angles, h2_observables_exp_values[4], "o")
ax[1].axhline(
y=reference_values[1],
color="k",
linestyle="--",
label="Binding Energy: {} MeV".format(np.round(reference_values[1], 3)),
)
ax[1].legend()
ax[1].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[1].set_ylabel(r"$\langle H_2 \rangle $ - Energy (MeV)", fontsize=15)
ax[1].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[1].set_title(
r"Behavior of the expectation value of $H_2$ when we vary $\theta$ in the ansatz.", fontsize=15
)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/yatharth0610/Quantum-Algorithms-qiskit-
|
yatharth0610
|
from qiskit import *
from qiskit.compiler import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import matplotlib.pyplot as plotter
import numpy as np
from IPython.display import display, Math, Latex
%matplotlib inline
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
qc1=QuantumCircuit(2)
qc1.h(0)
qc1.h(1)
qc1.barrier() #The part between the barriers is our oracle
qc1.cz(0,1)
#We are using a controlled-Z gate which flips the sign of the second qubit when both qubits are set to '1'
qc1.barrier()
qc1.draw('mpl')
def final_vector(qc):
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=3)
return outputstate
print(final_vector(qc1)) #We can see that the desired state has been obtained
qc2=QuantumCircuit(3)
qc2.h(0)
qc2.h(1)
qc2.h(2)
qc2.barrier()
#The part between the barriers is our oracle
qc2.x(0)
qc2.h(1)
qc2.x(2)
qc2.ccx(0, 2, 1)
qc2.x(0)
qc2.h(1)
qc2.x(2)
qc2.barrier()
qc2.draw('mpl')
def final_vector(qc):
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=3)
return outputstate
print(final_vector(qc2))
def ccz_gate(qc,a,b,c):
qc.h(c)
qc.ccx(a,b,c)
qc.h(c)
#Let's create an oracle which will mark the states 101 and 110
#(This particular oracle won't be using ancilla qubits)
def phase_oracle(circuit):
circuit.cz(0, 2)
circuit.cz(0, 1)
n=3
qc2=QuantumCircuit(n,n)
for i in range(0,n):
qc2.h(i)
qc2.barrier([0,1,2])
#This creates a superposition of all states
#We will now perform the Grover iteration
phase_oracle(qc2)
qc2.barrier([0,1,2])
for i in range(0,n):
qc2.h(i)
#Performing a conditional phase shift
qc2.x(0)
qc2.x(1)
qc2.x(2)
ccz_gate(qc2,0,1,2)
qc2.x(0)
qc2.x(1)
qc2.x(2)
for i in range(0,n):
qc2.h(i)
#The Grover iteration is now complete
qc2.barrier([0,1,2])
qc2.draw('mpl')
qc2.measure(0,0)
qc2.measure(1,1)
qc2.measure(2,2)
qc2.draw('mpl')
def counts_circ(circ):
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=2000)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
return(counts)
plot_histogram(counts_circ(qc2))
qc_mct=QuantumCircuit(5,5)
for i in range(0,4):
qc_mct.x(i)
qc_mct.mct([0,1,2,3],4)
qc_mct.draw('mpl')
qc_mct.measure(0,0)
qc_mct.measure(1,1)
qc_mct.measure(2,2)
qc_mct.measure(3,3)
qc_mct.measure(4,4)
plot_histogram(counts_circ(qc_mct))
def c3z_gate(qc, a, b, c, d):
qc.h(d)
qc.mct([a, b, c], d)
qc.h(d)
def phase_oracle(qc):
qc.x(1)
qc.x(3)
c3z_gate(qc, 0, 1, 2, 3) # Handles 1010
qc.x(2)
c3z_gate(qc, 0, 1, 2, 3) # Handles 1000
qc.x(3)
c3z_gate(qc, 0, 1, 2, 3) # Handles 1001
qc.x(2)
qc.x(0)
qc.x(3)
c3z_gate(qc, 0, 1, 2, 3) # Handles 0010
qc.x(0)
qc.x(1)
qc.x(3)
n = 4
qc3 = QuantumCircuit(n, n)
for i in range(0,n):
qc3.h(i)
qc3.barrier([0, 1, 2, 3])
phase_oracle(qc3)
qc3.barrier([0, 1, 2, 3])
for i in range(0,n):
qc3.h(i)
qc3.x(0)
qc3.x(1)
qc3.x(2)
qc3.x(3)
c3z_gate(qc3, 0, 1, 2, 3)
qc3.x(0)
qc3.x(1)
qc3.x(2)
qc3.x(3)
for i in range(0,n):
qc3.h(i)
qc3.barrier([0, 1, 2, 3])
qc3.measure(0, 0)
qc3.measure(1, 1)
qc3.measure(2, 2)
qc3.measure(3, 3)
qc3.draw('mpl')
def counts_circ(circ):
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=2000)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
return(counts)
plot_histogram(counts_circ(qc3))
|
https://github.com/joemoorhouse/quantum-mc
|
joemoorhouse
|
from quantum_mc.arithmetic.piecewise_linear_transform import PiecewiseLinearTransform3
import unittest
import numpy as np
from qiskit.test.base import QiskitTestCase
import quantum_mc.calibration.fitting as ft
import quantum_mc.calibration.time_series as ts
from scipy.stats import multivariate_normal, norm
from qiskit.test.base import QiskitTestCase
from qiskit import execute, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, AncillaRegister
from qiskit.circuit.library import NormalDistribution
from qiskit.quantum_info import Statevector
from qiskit.circuit.library import NormalDistribution, LogNormalDistribution, IntegerComparator
from qiskit.utils import QuantumInstance
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
def get_sims(normal_distribution):
import numpy as np
values = normal_distribution._values
probs = normal_distribution._probabilities
# we generate a bunch of realisation of values, based
upper_bounds = [0.0]
stop = 0.0
for val, prob in zip(values, probs):
stop += prob
upper_bounds.append(stop)
r = np.random.uniform(low=0.0, high=1.0, size=10)
indices = np.searchsorted(upper_bounds, r, side='left', sorter=None) - 1
g1, g2 = np.meshgrid(range(2**3), range(2**3), indexing="ij",)
i1 = g1.flatten()[indices]
i2 = g2.flatten()[indices]
#x = list(zip(*(grid.flatten() for grid in meshgrid)))
return i1, i2
class TestMcVar(QiskitTestCase):
def test_no_discretisation(self):
correl = ft.get_correl("AAPL", "MSFT")
coeff_set = []
pl_set = []
for ticker in ["MSFT", "AAPL"]:
((cdf_x, cdf_y), sigma) = ft.get_cdf_data(ticker)
(x, y) = ft.get_fit_data(ticker, norm_to_rel = False)
(pl, coeffs) = ft.fit_piecewise_linear(x, y)
# scale, to apply an arbitrary delta (we happen to use the same value here, but could be different)
coeffs = ft.scaled_coeffs(coeffs, 1.0 if ticker == "MSFT" else 1.0)
coeff_set.append(coeffs)
pl_set.append(lambda z : ft.piecewise_linear(z, *coeff_set[0]))
pl_set.append(lambda z : ft.piecewise_linear(z, *coeff_set[1]))
c = np.linalg.cholesky(correl)
r = np.random.normal(0, 1, size = (2, 10))
v = c@r
v1 = np.vectorize(pl_set[0])(v[0, :])
v2 = np.vectorize(pl_set[1])(v[1, :])
v = v1 + v2
def test_distribution_load(self):
""" Test that calculates a cumulative probability from the P&L distribution."""
correl = ft.get_correl("AAPL", "MSFT")
bounds_std = 3.0
num_qubits = [3, 3]
sigma = correl
bounds = [(-bounds_std, bounds_std), (-bounds_std, bounds_std)]
mu = [0, 0]
# starting point is a multi-variate normal distribution
normal = NormalDistribution(num_qubits, mu=mu, sigma=sigma, bounds=bounds)
pl_set = []
coeff_set = []
for ticker in ["MSFT", "AAPL"]:
((cdf_x, cdf_y), sigma) = ft.get_cdf_data(ticker)
(x, y) = ft.get_fit_data(ticker, norm_to_rel = False)
(pl, coeffs) = ft.fit_piecewise_linear(x, y)
# scale, to apply an arbitrary delta (we happen to use the same value here, but could be different)
coeffs = ft.scaled_coeffs(coeffs, 1.2)
pl_set.append(lambda z : ft.piecewise_linear(z, *coeffs))
coeff_set.append(coeffs)
# calculate the max and min P&Ls
p_max = max(pl_set[0](bounds_std), pl_set[1](bounds_std))
p_min = min(pl_set[0](-bounds_std), pl_set[1](-bounds_std))
# we discretise the transforms and create the circuits
transforms = []
i_to_js = []
for i,ticker in enumerate(["MSFT", "AAPL"]):
(i_0, i_1, a0, a1, a2, b0, b1, b2, i_to_j, i_to_x, j_to_y) = ft.integer_piecewise_linear_coeffs(coeff_set[i], x_min = -bounds_std, x_max = bounds_std, y_min = p_min, y_max = p_max)
transforms.append(PiecewiseLinearTransform3(i_0, i_1, a0, a1, a2, b0, b1, b2))
i_to_js.append(np.vectorize(i_to_j))
i1, i2 = get_sims(normal)
j1 = i_to_js[0](i1)
j2 = i_to_js[1](i2)
j_tot = j1 + j2
num_ancillas = transforms[0].num_ancilla_qubits
qr_input = QuantumRegister(6, 'input') # 2 times 3 registers
qr_objective = QuantumRegister(1, 'objective')
qr_result = QuantumRegister(6, 'result')
qr_ancilla = QuantumRegister(num_ancillas, 'ancilla')
#output = ClassicalRegister(6, 'output')
state_preparation = QuantumCircuit(qr_input, qr_objective, qr_result, qr_ancilla) #, output)
state_preparation.append(normal, qr_input)
for i in range(2):
offset = i * 3
state_preparation.append(transforms[i], qr_input[offset:offset + 3] + qr_result[:] + qr_ancilla[:])
# to calculate the cdf, we use an additional comparator
x_eval = 4
comparator = IntegerComparator(len(qr_result), x_eval + 1, geq=False)
state_preparation.append(comparator, qr_result[:] + qr_objective[:] + qr_ancilla[0:comparator.num_ancillas])
# now check
check = False
if check:
job = execute(state_preparation, backend=Aer.get_backend('statevector_simulator'))
var_prob = 0
for i, a in enumerate(job.result().get_statevector()):
b = ('{0:0%sb}' % (len(qr_input) + 1)).format(i)[-(len(qr_input) + 1):]
prob = np.abs(a)**2
if prob > 1e-6 and b[0] == '1':
var_prob += prob
print('Operator CDF(%s)' % x_eval + ' = %.4f' % var_prob)
# now do AE
problem = EstimationProblem(state_preparation=state_preparation,
objective_qubits=[len(qr_input)])
# target precision and confidence level
epsilon = 0.01
alpha = 0.05
qi = QuantumInstance(Aer.get_backend('aer_simulator'), shots=100)
ae_cdf = IterativeAmplitudeEstimation(epsilon, alpha=alpha, quantum_instance=qi)
result_cdf = ae_cdf.estimate(problem)
conf_int = np.array(result_cdf.confidence_interval)
print('Estimated value:\t%.4f' % result_cdf.estimation)
print('Confidence interval: \t[%.4f, %.4f]' % tuple(conf_int))
state_preparation.draw()
|
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
|
maheshwaripranav
|
# Essentials
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Classical Machine Learning
from sklearn.svm import SVC
from sklearn.datasets import make_blobs, make_circles
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score, accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Quantum Machine Learning
from qiskit import BasicAer
from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.kernels import QuantumKernel
dataset = pd.read_csv(r'iris_data\iris.data')
features_all= dataset.iloc[:, :4].values
features_sepal= dataset.iloc[:, :2].values
features_petal= dataset.iloc[:, 2:4].values
label = dataset.iloc[:, 4].values
for i in range(len(label)):
if label[i] == 'Iris-setosa':
label[i] = 0
elif label[i] == 'Iris-versicolor':
label[i] = 1
elif label[i] == 'Iris-virginica':
label[i] = 2
label = label.astype(str).astype(int)
X_train, X_test, y_train, y_test = train_test_split(features_all, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="linear", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
X_train, X_test, y_train, y_test = train_test_split(features_sepal, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="rbf", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
X_train, X_test, y_train, y_test = train_test_split(features_petal, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="linear", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement='linear')
backend = QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=8000)
kernel = QuantumKernel(feature_map=feature_map, quantum_instance=backend)
X_train, X_test, y_train, y_test = train_test_split(features_all, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel=kernel.evaluate)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
X_train, X_test, y_train, y_test = train_test_split(features_sepal, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="rbf", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
X_train, X_test, y_train, y_test = train_test_split(features_petal, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="linear", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
es_problem = driver.run()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
from qiskit.algorithms.eigensolvers import NumPyEigensolver
numpy_solver = NumPyEigensolver(filter_criterion=es_problem.get_default_filter_criterion())
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.algorithms import GroundStateEigensolver, QEOM
from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD
ansatz = UCCSD(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
initial_state=HartreeFock(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
),
)
estimator = Estimator()
# This first part sets the ground state solver
# see more about this part in the ground state calculation tutorial
solver = VQE(estimator, ansatz, SLSQP())
solver.initial_point = [0.0] * ansatz.num_parameters
gse = GroundStateEigensolver(mapper, solver)
# The qEOM algorithm is simply instantiated with the chosen ground state solver and Estimator primitive
qeom_excited_states_solver = QEOM(gse, estimator, "sd")
from qiskit_nature.second_q.algorithms import ExcitedStatesEigensolver
numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, numpy_solver)
numpy_results = numpy_excited_states_solver.solve(es_problem)
qeom_results = qeom_excited_states_solver.solve(es_problem)
print(numpy_results)
print("\n\n")
print(qeom_results)
import numpy as np
def filter_criterion(eigenstate, eigenvalue, aux_values):
return np.isclose(aux_values["ParticleNumber"][0], 2.0)
new_numpy_solver = NumPyEigensolver(filter_criterion=filter_criterion)
new_numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, new_numpy_solver)
new_numpy_results = new_numpy_excited_states_solver.solve(es_problem)
print(new_numpy_results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""PauliBasisChange Class"""
from functools import partial, reduce
from typing import Callable, List, Optional, Tuple, Union, cast
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow.converters.converter_base import ConverterBase
from qiskit.opflow.list_ops.composed_op import ComposedOp
from qiskit.opflow.list_ops.list_op import ListOp
from qiskit.opflow.list_ops.summed_op import SummedOp
from qiskit.opflow.operator_base import OperatorBase
from qiskit.opflow.operator_globals import H, I, S
from qiskit.opflow.primitive_ops.pauli_op import PauliOp
from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp
from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp
from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn
from qiskit.opflow.state_fns.state_fn import StateFn
from qiskit.quantum_info import Pauli
from qiskit.utils.deprecation import deprecate_func
class PauliBasisChange(ConverterBase):
r"""
Deprecated: Converter for changing Paulis into other bases. By default, the diagonal basis
composed only of Pauli {Z, I}^n is used as the destination basis to which to convert.
Meaning, if a Pauli containing X or Y terms is passed in, which cannot be
sampled or evolved natively on some Quantum hardware, the Pauli can be replaced by a
composition of a change of basis circuit and a Pauli composed of only Z
and I terms (diagonal), which can be evolved or sampled natively on the Quantum
hardware.
The replacement function determines how the ``PauliOps`` should be replaced by their computed
change-of-basis ``CircuitOps`` and destination ``PauliOps``. Several convenient out-of-the-box
replacement functions have been added as static methods, such as ``measurement_replacement_fn``.
This class uses the typical basis change method found in most Quantum Computing textbooks
(such as on page 210 of Nielsen and Chuang's, "Quantum Computation and Quantum Information",
ISBN: 978-1-107-00217-3), which involves diagonalizing the single-qubit Paulis with H and S†
gates, mapping the eigenvectors of the diagonalized origin Pauli to the diagonalized
destination Pauli using CNOTS, and then de-diagonalizing any single qubit Paulis to their
non-diagonal destination values. Many other methods are possible, as well as variations on
this method, such as the placement of the CNOT chains.
"""
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self,
destination_basis: Optional[Union[Pauli, PauliOp]] = None,
traverse: bool = True,
replacement_fn: Optional[Callable] = None,
) -> None:
"""
Args:
destination_basis: The Pauli into the basis of which the operators
will be converted. If None is specified, the destination basis will be the
diagonal ({I, Z}^n) basis requiring only single qubit rotations.
traverse: If true and the operator passed into convert contains sub-Operators,
such as ListOp, traverse the Operator and apply the conversion to every
applicable sub-operator within it.
replacement_fn: A function specifying what to do with the basis-change
``CircuitOp`` and destination ``PauliOp`` when converting an Operator and
replacing converted values. By default, this will be
1) For StateFns (or Measurements): replacing the StateFn with
ComposedOp(StateFn(d), c) where c is the conversion circuit and d is the
destination Pauli, so the overall beginning and ending operators are
equivalent.
2) For non-StateFn Operators: replacing the origin p with c·d·c†, where c
is the conversion circuit and d is the destination, so the overall
beginning and ending operators are equivalent.
"""
super().__init__()
if destination_basis is not None:
self.destination = destination_basis # type: ignore
else:
self._destination = None # type: Optional[PauliOp]
self._traverse = traverse
self._replacement_fn = replacement_fn or PauliBasisChange.operator_replacement_fn
@property
def destination(self) -> Optional[PauliOp]:
r"""
The destination ``PauliOp``, or ``None`` if using the default destination, the diagonal
basis.
"""
return self._destination
@destination.setter
def destination(self, dest: Union[Pauli, PauliOp]) -> None:
r"""
The destination ``PauliOp``, or ``None`` if using the default destination, the diagonal
basis.
"""
if isinstance(dest, Pauli):
dest = PauliOp(dest)
if not isinstance(dest, PauliOp):
raise TypeError(
f"PauliBasisChange can only convert into Pauli bases, not {type(dest)}."
)
self._destination = dest
# TODO see whether we should make this performant by handling ListOps of Paulis later.
# pylint: disable=too-many-return-statements
def convert(self, operator: OperatorBase) -> OperatorBase:
r"""
Given a ``PauliOp``, or an Operator containing ``PauliOps`` if ``_traverse`` is True,
converts each Pauli into the basis specified by self._destination and a
basis-change-circuit, calls ``replacement_fn`` with these two Operators, and replaces
the ``PauliOps`` with the output of ``replacement_fn``. For example, for the built-in
``operator_replacement_fn`` below, each PauliOp p will be replaced by the composition
of the basis-change Clifford ``CircuitOp`` c with the destination PauliOp d and c†,
such that p = c·d·c†, up to global phase.
Args:
operator: The Operator to convert.
Returns:
The converted Operator.
"""
if (
isinstance(operator, OperatorStateFn)
and isinstance(operator.primitive, PauliSumOp)
and operator.primitive.grouping_type == "TPB"
):
primitive = operator.primitive.primitive.copy()
origin_x = reduce(np.logical_or, primitive.paulis.x)
origin_z = reduce(np.logical_or, primitive.paulis.z)
origin_pauli = Pauli((origin_z, origin_x))
cob_instr_op, _ = self.get_cob_circuit(origin_pauli)
primitive.paulis.z = np.logical_or(primitive.paulis.x, primitive.paulis.z)
primitive.paulis.x = False
# The following line is because the deprecated PauliTable did not have a phase
# and did not track it, so phase=0 was always guaranteed.
# But the new PauliList may change phase.
primitive.paulis.phase = 0
dest_pauli_sum_op = PauliSumOp(primitive, coeff=operator.coeff, grouping_type="TPB")
return self._replacement_fn(cob_instr_op, dest_pauli_sum_op)
if (
isinstance(operator, OperatorStateFn)
and isinstance(operator.primitive, SummedOp)
and all(
isinstance(op, PauliSumOp) and op.grouping_type == "TPB"
for op in operator.primitive.oplist
)
):
sf_list: List[OperatorBase] = [
StateFn(op, is_measurement=operator.is_measurement)
for op in operator.primitive.oplist
]
listop_of_statefns = SummedOp(oplist=sf_list, coeff=operator.coeff)
return listop_of_statefns.traverse(self.convert)
if isinstance(operator, OperatorStateFn) and isinstance(operator.primitive, PauliSumOp):
operator = OperatorStateFn(
operator.primitive.to_pauli_op(),
coeff=operator.coeff,
is_measurement=operator.is_measurement,
)
if isinstance(operator, PauliSumOp):
operator = operator.to_pauli_op()
if isinstance(operator, (Pauli, PauliOp)):
cob_instr_op, dest_pauli_op = self.get_cob_circuit(operator)
return self._replacement_fn(cob_instr_op, dest_pauli_op)
if isinstance(operator, StateFn) and "Pauli" in operator.primitive_strings():
# If the StateFn/Meas only contains a Pauli, use it directly.
if isinstance(operator.primitive, PauliOp):
cob_instr_op, dest_pauli_op = self.get_cob_circuit(operator.primitive)
return self._replacement_fn(cob_instr_op, dest_pauli_op * operator.coeff)
# TODO make a canonical "distribute" or graph swap as method in ListOp?
elif operator.primitive.distributive:
if operator.primitive.abelian:
origin_pauli = self.get_tpb_pauli(operator.primitive)
cob_instr_op, _ = self.get_cob_circuit(origin_pauli)
diag_ops: List[OperatorBase] = [
self.get_diagonal_pauli_op(op) for op in operator.primitive.oplist
]
dest_pauli_op = operator.primitive.__class__(
diag_ops, coeff=operator.coeff, abelian=True
)
return self._replacement_fn(cob_instr_op, dest_pauli_op)
else:
sf_list = [
StateFn(op, is_measurement=operator.is_measurement)
for op in operator.primitive.oplist
]
listop_of_statefns = operator.primitive.__class__(
oplist=sf_list, coeff=operator.coeff
)
return listop_of_statefns.traverse(self.convert)
elif (
isinstance(operator, ListOp)
and self._traverse
and "Pauli" in operator.primitive_strings()
):
# If ListOp is abelian we can find a single post-rotation circuit
# for the whole set. For now,
# assume operator can only be abelian if all elements are
# Paulis (enforced in AbelianGrouper).
if operator.abelian:
origin_pauli = self.get_tpb_pauli(operator)
cob_instr_op, _ = self.get_cob_circuit(origin_pauli)
oplist = cast(List[PauliOp], operator.oplist)
diag_ops = [self.get_diagonal_pauli_op(op) for op in oplist]
dest_list_op = operator.__class__(diag_ops, coeff=operator.coeff, abelian=True)
return self._replacement_fn(cob_instr_op, dest_list_op)
else:
return operator.traverse(self.convert)
return operator
@staticmethod
def measurement_replacement_fn(
cob_instr_op: PrimitiveOp, dest_pauli_op: Union[PauliOp, PauliSumOp, ListOp]
) -> OperatorBase:
r"""
A built-in convenience replacement function which produces measurements
isomorphic to an ``OperatorStateFn`` measurement holding the origin ``PauliOp``.
Args:
cob_instr_op: The basis-change ``CircuitOp``.
dest_pauli_op: The destination Pauli type operator.
Returns:
The ``~StateFn @ CircuitOp`` composition equivalent to a measurement by the original
``PauliOp``.
"""
return ComposedOp([StateFn(dest_pauli_op, is_measurement=True), cob_instr_op])
@staticmethod
def statefn_replacement_fn(
cob_instr_op: PrimitiveOp, dest_pauli_op: Union[PauliOp, PauliSumOp, ListOp]
) -> OperatorBase:
r"""
A built-in convenience replacement function which produces state functions
isomorphic to an ``OperatorStateFn`` state function holding the origin ``PauliOp``.
Args:
cob_instr_op: The basis-change ``CircuitOp``.
dest_pauli_op: The destination Pauli type operator.
Returns:
The ``~CircuitOp @ StateFn`` composition equivalent to a state function defined by the
original ``PauliOp``.
"""
return ComposedOp([cob_instr_op.adjoint(), StateFn(dest_pauli_op)])
@staticmethod
def operator_replacement_fn(
cob_instr_op: PrimitiveOp, dest_pauli_op: Union[PauliOp, PauliSumOp, ListOp]
) -> OperatorBase:
r"""
A built-in convenience replacement function which produces Operators
isomorphic to the origin ``PauliOp``.
Args:
cob_instr_op: The basis-change ``CircuitOp``.
dest_pauli_op: The destination ``PauliOp``.
Returns:
The ``~CircuitOp @ PauliOp @ CircuitOp`` composition isomorphic to the
original ``PauliOp``.
"""
return ComposedOp([cob_instr_op.adjoint(), dest_pauli_op, cob_instr_op])
def get_tpb_pauli(self, list_op: ListOp) -> Pauli:
r"""
Gets the Pauli (not ``PauliOp``!) whose diagonalizing single-qubit rotations is a
superset of the diagonalizing single-qubit rotations for each of the Paulis in
``list_op``. TPB stands for `Tensor Product Basis`.
Args:
list_op: the :class:`ListOp` whose TPB Pauli to return.
Returns:
The TBP Pauli.
"""
oplist = cast(List[PauliOp], list_op.oplist)
origin_z = reduce(np.logical_or, [p_op.primitive.z for p_op in oplist])
origin_x = reduce(np.logical_or, [p_op.primitive.x for p_op in oplist])
return Pauli((origin_z, origin_x))
def get_diagonal_pauli_op(self, pauli_op: PauliOp) -> PauliOp:
"""Get the diagonal ``PualiOp`` to which ``pauli_op`` could be rotated with only
single-qubit operations.
Args:
pauli_op: The ``PauliOp`` whose diagonal to compute.
Returns:
The diagonal ``PauliOp``.
"""
return PauliOp(
Pauli(
(
np.logical_or(pauli_op.primitive.z, pauli_op.primitive.x),
[False] * pauli_op.num_qubits,
)
),
coeff=pauli_op.coeff,
)
def get_diagonalizing_clifford(self, pauli: Union[Pauli, PauliOp]) -> OperatorBase:
r"""
Construct a ``CircuitOp`` with only single-qubit gates which takes the eigenvectors
of ``pauli`` to eigenvectors composed only of \|0⟩ and \|1⟩ tensor products. Equivalently,
finds the basis-change circuit to take ``pauli`` to a diagonal ``PauliOp`` composed only
of Z and I tensor products.
Note, underlying Pauli bits are in Qiskit endianness, so we need to reverse before we
begin composing with Operator flow.
Args:
pauli: the ``Pauli`` or ``PauliOp`` to whose diagonalizing circuit to compute.
Returns:
The diagonalizing ``CircuitOp``.
"""
if isinstance(pauli, PauliOp):
pauli = pauli.primitive
tensorall = cast(
Callable[[List[PrimitiveOp]], PrimitiveOp], partial(reduce, lambda x, y: x.tensor(y))
)
y_to_x_origin = tensorall(
[S if has_y else I for has_y in reversed(np.logical_and(pauli.x, pauli.z))]
).adjoint()
x_to_z_origin = tensorall( # pylint: disable=assignment-from-no-return
[H if has_x else I for has_x in reversed(pauli.x)]
)
return x_to_z_origin.compose(y_to_x_origin)
def pad_paulis_to_equal_length(
self, pauli_op1: PauliOp, pauli_op2: PauliOp
) -> Tuple[PauliOp, PauliOp]:
r"""
If ``pauli_op1`` and ``pauli_op2`` do not act over the same number of qubits, pad
identities to the end of the shorter of the two so they are of equal length. Padding is
applied to the end of the Paulis. Note that the Terra represents Paulis in big-endian
order, so this will appear as padding to the beginning of the Pauli x and z bit arrays.
Args:
pauli_op1: A pauli_op to possibly pad.
pauli_op2: A pauli_op to possibly pad.
Returns:
A tuple containing the padded PauliOps.
"""
num_qubits = max(pauli_op1.num_qubits, pauli_op2.num_qubits)
pauli_1, pauli_2 = pauli_op1.primitive, pauli_op2.primitive
# Padding to the end of the Pauli, but remember that Paulis are in reverse endianness.
if not len(pauli_1.z) == num_qubits:
missing_qubits = num_qubits - len(pauli_1.z)
pauli_1 = Pauli(
(
([False] * missing_qubits) + pauli_1.z.tolist(),
([False] * missing_qubits) + pauli_1.x.tolist(),
)
)
if not len(pauli_2.z) == num_qubits:
missing_qubits = num_qubits - len(pauli_2.z)
pauli_2 = Pauli(
(
([False] * missing_qubits) + pauli_2.z.tolist(),
([False] * missing_qubits) + pauli_2.x.tolist(),
)
)
return PauliOp(pauli_1, coeff=pauli_op1.coeff), PauliOp(pauli_2, coeff=pauli_op2.coeff)
def construct_cnot_chain(self, diag_pauli_op1: PauliOp, diag_pauli_op2: PauliOp) -> PrimitiveOp:
r"""
Construct a ``CircuitOp`` (or ``PauliOp`` if equal to the identity) which takes the
eigenvectors of ``diag_pauli_op1`` to the eigenvectors of ``diag_pauli_op2``,
assuming both are diagonal (or performing this operation on their diagonalized Paulis
implicitly if not). This works by the insight that the eigenvalue of a diagonal Pauli's
eigenvector is equal to or -1 if the parity is 1 and 1 if the parity is 0, or
1 - (2 * parity). Therefore, using CNOTs, we can write the parity of diag_pauli_op1's
significant bits onto some qubit, and then write out that parity onto diag_pauli_op2's
significant bits.
Args:
diag_pauli_op1: The origin ``PauliOp``.
diag_pauli_op2: The destination ``PauliOp``.
Return:
The ``PrimitiveOp`` performs the mapping.
"""
# TODO be smarter about connectivity and actual distance between pauli and destination
# TODO be smarter in general
pauli_1 = (
diag_pauli_op1.primitive if isinstance(diag_pauli_op1, PauliOp) else diag_pauli_op1
)
pauli_2 = (
diag_pauli_op2.primitive if isinstance(diag_pauli_op2, PauliOp) else diag_pauli_op2
)
origin_sig_bits = np.logical_or(pauli_1.z, pauli_1.x)
destination_sig_bits = np.logical_or(pauli_2.z, pauli_2.x)
num_qubits = max(len(pauli_1.z), len(pauli_2.z))
sig_equal_sig_bits = np.logical_and(origin_sig_bits, destination_sig_bits)
non_equal_sig_bits = np.logical_not(origin_sig_bits == destination_sig_bits)
# Equivalent to np.logical_xor(origin_sig_bits, destination_sig_bits)
if not any(non_equal_sig_bits):
return I ^ num_qubits
# I am deeply sorry for this code, but I don't know another way to do it.
sig_in_origin_only_indices = np.extract(
np.logical_and(non_equal_sig_bits, origin_sig_bits), np.arange(num_qubits)
)
sig_in_dest_only_indices = np.extract(
np.logical_and(non_equal_sig_bits, destination_sig_bits), np.arange(num_qubits)
)
if len(sig_in_origin_only_indices) > 0 and len(sig_in_dest_only_indices) > 0:
origin_anchor_bit = min(sig_in_origin_only_indices)
dest_anchor_bit = min(sig_in_dest_only_indices)
else:
# Set to lowest equal bit
origin_anchor_bit = min(np.extract(sig_equal_sig_bits, np.arange(num_qubits)))
dest_anchor_bit = origin_anchor_bit
cnots = QuantumCircuit(num_qubits)
# Step 3) Take the indices of bits which are sig_bits in
# pauli but but not in dest, and cnot them to the pauli anchor.
for i in sig_in_origin_only_indices:
if not i == origin_anchor_bit:
cnots.cx(i, origin_anchor_bit)
# Step 4)
if not origin_anchor_bit == dest_anchor_bit:
cnots.swap(origin_anchor_bit, dest_anchor_bit)
# Need to do this or a Terra bug sometimes flips cnots. No time to investigate.
cnots.i(0)
# Step 6)
for i in sig_in_dest_only_indices:
if not i == dest_anchor_bit:
cnots.cx(i, dest_anchor_bit)
return PrimitiveOp(cnots)
def get_cob_circuit(self, origin: Union[Pauli, PauliOp]) -> Tuple[PrimitiveOp, PauliOp]:
r"""
Construct an Operator which maps the +1 and -1 eigenvectors
of the origin Pauli to the +1 and -1 eigenvectors of the destination Pauli. It does so by
1) converting any \|i+⟩ or \|i+⟩ eigenvector bits in the origin to
\|+⟩ and \|-⟩ with S†s, then
2) converting any \|+⟩ or \|+⟩ eigenvector bits in the converted origin to
\|0⟩ and \|1⟩ with Hs, then
3) writing the parity of the significant (Z-measured, rather than I)
bits in the origin to a single
"origin anchor bit," using cnots, which will hold the parity of these bits,
4) swapping the parity of the pauli anchor bit into a destination anchor bit using
a swap gate (only if they are different, if there are any bits which are significant
in both origin and dest, we set both anchors to one of these bits to avoid a swap).
5) writing the parity of the destination anchor bit into the other significant bits
of the destination,
6) converting the \|0⟩ and \|1⟩ significant eigenvector bits to \|+⟩ and \|-⟩ eigenvector
bits in the destination where the destination demands it
(e.g. pauli.x == true for a bit), using Hs 8) converting the \|+⟩ and \|-⟩
significant eigenvector bits to \|i+⟩ and \|i-⟩ eigenvector bits in the
destination where the destination demands it
(e.g. pauli.x == true and pauli.z == true for a bit), using Ss
Args:
origin: The ``Pauli`` or ``PauliOp`` to map.
Returns:
A tuple of a ``PrimitiveOp`` which equals the basis change mapping and a ``PauliOp``
which equals the destination basis.
Raises:
TypeError: Attempting to convert from non-Pauli origin.
ValueError: Attempting to change a non-identity Pauli to an identity Pauli, or vice
versa.
"""
# If pauli is an PrimitiveOp, extract the Pauli
if isinstance(origin, Pauli):
origin = PauliOp(origin)
if not isinstance(origin, PauliOp):
raise TypeError(
f"PauliBasisChange can only convert Pauli-based OpPrimitives, not {type(origin)}"
)
# If no destination specified, assume nearest Pauli in {Z,I}^n basis,
# the standard basis change for expectations.
destination = self.destination or self.get_diagonal_pauli_op(origin)
# Pad origin or destination if either are not as long as the other
origin, destination = self.pad_paulis_to_equal_length(origin, destination)
origin_sig_bits = np.logical_or(origin.primitive.x, origin.primitive.z)
destination_sig_bits = np.logical_or(destination.primitive.x, destination.primitive.z)
if not any(origin_sig_bits) or not any(destination_sig_bits):
if not (any(origin_sig_bits) or any(destination_sig_bits)):
# Both all Identity, just return Identities
return I ^ origin.num_qubits, destination
else:
# One is Identity, one is not
raise ValueError("Cannot change to or from a fully Identity Pauli.")
# Steps 1 and 2
cob_instruction = self.get_diagonalizing_clifford(origin)
# Construct CNOT chain, assuming full connectivity... - Steps 3)-5)
cob_instruction = self.construct_cnot_chain(origin, destination).compose(cob_instruction)
# Step 6 and 7
dest_diagonlizing_clifford = self.get_diagonalizing_clifford(destination).adjoint()
cob_instruction = dest_diagonlizing_clifford.compose(cob_instruction)
return cast(PrimitiveOp, cob_instruction), destination
|
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/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
# our backend is the Pulse Simulator
from resources import helper
from qiskit.providers.aer import PulseSimulator
backend_sim = PulseSimulator()
# sample duration for pulse instructions
dt = 1e-9
# create the model
duffing_model = helper.get_transmon(dt)
# get qubit frequency from Duffing model
qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift()
import numpy as np
# visualization tools
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3 # kilohertz
us = 1.0e-6 # microseconds
ns = 1.0e-9 # nanoseconds
from qiskit import pulse
from qiskit.pulse import Play, Acquire
from qiskit.pulse.pulse_lib import GaussianSquare
# qubit to be used throughout the notebook
qubit = 0
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_samples = 1200
meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150)
measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit))
inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', [qubit], measure_sched)
# save the measurement/acquire pulse for later
measure = inst_map.get('measure', qubits=[qubit])
from qiskit.pulse import pulse_lib
def build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma):
### create a Rabi schedule (already done)
### create a Gaussian Rabi pulse using pulse_lib
### play Rabi pulse on the Rabi schedule and return
rabi_schedule = pulse.Schedule(name='rabi_experiment')
### WRITE YOUR CODE BETWEEN THESE LINES - START
rabi_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma)
rabi_schedule = pulse.Schedule()
rabi_schedule += Play(rabi_pulse, drive_chan)
### WRITE YOUR CODE BETWEEN THESE LINES - END
# add measurement to rabi_schedule
# << indicates time shift the beginning to the start of the schedule
rabi_schedule += measure << rabi_schedule.duration
return rabi_schedule
# Gaussian pulse parameters, with varying amplitude
drive_duration = 128
num_rabi_points = 41
drive_amps = np.linspace(0, 0.9, num_rabi_points)
drive_sigma = 16
# now vary the amplitude for each drive amp
rabi_schedules = []
for drive_amp in drive_amps:
rabi_schedules.append(build_rabi_pulse_schedule(drive_duration, drive_amp, drive_sigma))
rabi_schedules[-1].draw()
# assemble the schedules into a Qobj
from qiskit import assemble
rabi_qobj = assemble(**helper.get_params('rabi', globals()))
answer1a = rabi_qobj
# run the simulation
rabi_result = backend_sim.run(rabi_qobj, duffing_model).result()
# retrieve the data from the experiment
rabi_values = helper.get_values_from_result(rabi_result, qubit)
fit_params, y_fit = helper.fit_sinusoid(drive_amps, rabi_values, [1, 0, 0.5, 0])
plt.scatter(drive_amps, rabi_values, color='white')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(0, color='red', linestyle='--')
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
print("Pi pulse amplitude is %f"%float(drive_period/2))
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_duration,
amp=drive_period/4,
sigma=drive_sigma,
name='x90_pulse')
# Ramsey experiment parameters
time_max_us = 0.4
time_step_us = 0.0035
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
def build_ramsey_pulse_schedule(delay):
### create a Ramsey pulse schedule (already done)
### play an x90 pulse on the drive channel
### play another x90 pulse after delay
### add measurement pulse to schedule
ramsey_schedule = pulse.Schedule(name='ramsey_experiment')
### HINT: include delay by adding it to the duration of the schedule
### round delay to nearest integer with int(delay)
### WRITE YOUR CODE BETWEEN THESE LINES - START
ramsey_schedule = pulse.Schedule()
ramsey_schedule += Play(x90_pulse, drive_chan)
ramsey_schedule += Play(x90_pulse, drive_chan) << ramsey_schedule.duration + int(delay)
ramsey_schedule += measure << ramsey_schedule.duration
### WRITE YOUR CODE BETWEEN THESE LINES - END
return ramsey_schedule
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
ramsey_schedules.append(build_ramsey_pulse_schedule(delay))
ramsey_schedules[-1].draw()
# assemble the schedules into a Qobj
# the helper will drive the pulses off-resonantly by an unknown value
ramsey_qobj = assemble(**helper.get_params('ramsey', globals()))
answer1b = ramsey_qobj
# run the simulation
ramsey_result = backend_sim.run(ramsey_qobj, duffing_model).result()
# retrieve the data from the experiment
ramsey_values = helper.get_values_from_result(ramsey_result, qubit)
# off-resonance component
fit_params, y_fit = helper.fit_sinusoid(times_us, ramsey_values, [1, 0.7, 0.1, 0.25])
_, _, ramsey_period_us, _, = fit_params
del_f_MHz = 1/ramsey_period_us # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='white')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.6f} MHz")
plt.xlim(np.min(times_us), np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend(loc=3)
plt.show()
print("Drive is off-resonant by %f MHz"%float(del_f_MHz))
name = 'Saasha Joshi'
email = 'saashajoshi08@gmail.com'
from grading_tools import grade
grade(answer1a, name, email, 'lab6', 'ex1a')
grade(answer1b, name, email, 'lab6', 'ex1b')
from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();'));
from grading_tools import send_code;send_code('ex1.ipynb')
|
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
|
hamburgerguy
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
https://github.com/Sanjay-995/Qiskit-Developer-Prep-Guide
|
Sanjay-995
|
import qiskit
qiskit.__version__
qiskit.__qiskit_version__
#Import the required packages
from qiskit import QuantumCircuit, QuantumRegister,ClassicalRegister,Aer,execute
from qiskit.visualization import *
qc1=QuantumCircuit(2)
qc1.x(0)
qc1.cx(0,1)
qc1.draw('mpl')
backend=Aer.get_backend('statevector_simulator')
job=execute(qc1,backend)
result=job.result()
sv=result.get_statevector()
sv.draw(output="latex")
qc2=QuantumCircuit(2)
qc2.x(0)
qc2.cnot(0,1)
qc2.draw('mpl')
backend=Aer.get_backend('statevector_simulator')
job=execute(qc2,backend)
result=job.result()
sv=result.get_statevector()
sv.draw(output="latex")
# We create 5-qubit mct gate
# We have a list of control qubits :0,1,2,3 and a target qubit 4.
qc3=QuantumCircuit(5)
qc3.x(range(4))
qc3.mct([0,1,2,3],4)
qc3.draw('mpl')
backend=Aer.get_backend('statevector_simulator')
job=execute(qc3,backend)
result=job.result()
sv=result.get_statevector()
sv.draw(output="latex")
qc4=QuantumCircuit(2)
qc4.cz(0,1)
qc4.draw('mpl')
backend=Aer.get_backend('statevector_simulator')
job=execute(qc4,backend)
result=job.result()
sv=result.get_statevector()
print("statevector:", sv)
sv.draw(output="latex")
backend=Aer.get_backend('unitary_simulator')
job=execute(qc4,backend)
result=job.result()
sv=result.get_unitary()
print(sv)
#Let's apply a X on the control qubit
qc4=QuantumCircuit(2)
qc4.x(0)
qc4.cz(0,1)
qc4.draw('mpl')
backend=Aer.get_backend('statevector_simulator')
job=execute(qc4,backend)
result=job.result()
sv=result.get_statevector()
print("statevector:", sv)
sv.draw(output="latex")
backend=Aer.get_backend('unitary_simulator')
job=execute(qc4,backend)
result=job.result()
sv=result.get_unitary()
print(sv)
plot_state_qsphere(sv,show_state_phases=True)
|
https://github.com/tanmaybisen31/Quantum-Teleportation
|
tanmaybisen31
|
from qiskit import*
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
qc=QuantumCircuit(1,1)
from qiskit.tools.visualization import plot_bloch_multivector
qc.x(0)
sim=Aer.get_backend('statevector_simulator')
result=execute(qc,backend=sim).result()
sv=result.get_statevector()
print(sv)
qc.draw()
plot_bloch_multivector(sv)
qc.measure(range(1),range(1))
backend=Aer.get_backend('qasm_simulator')
result=execute(qc,backend=backend).result()
count=result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(count)
s=Aer.get_backend('unitary_simulator')
result=execute(qc,backend=s).result()
unitary=result.get_unitary()
print(unitary)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for PauliTable class."""
import unittest
from test import combine
import numpy as np
from ddt import ddt
from scipy.sparse import csr_matrix
from qiskit import QiskitError
from qiskit.quantum_info.operators.symplectic import PauliTable
from qiskit.test import QiskitTestCase
def pauli_mat(label):
"""Return Pauli matrix from a Pauli label"""
mat = np.eye(1, dtype=complex)
for i in label:
if i == "I":
mat = np.kron(mat, np.eye(2, dtype=complex))
elif i == "X":
mat = np.kron(mat, np.array([[0, 1], [1, 0]], dtype=complex))
elif i == "Y":
mat = np.kron(mat, np.array([[0, -1j], [1j, 0]], dtype=complex))
elif i == "Z":
mat = np.kron(mat, np.array([[1, 0], [0, -1]], dtype=complex))
else:
raise QiskitError(f"Invalid Pauli string {i}")
return mat
class TestPauliTableInit(QiskitTestCase):
"""Tests for PauliTable initialization."""
def test_array_init(self):
"""Test array initialization."""
# Matrix array initialization
with self.subTest(msg="bool array"):
target = np.array([[False, False], [True, True]])
with self.assertWarns(DeprecationWarning):
value = PauliTable(target)._array
self.assertTrue(np.all(value == target))
with self.subTest(msg="bool array no copy"):
target = np.array([[False, True], [True, True]])
with self.assertWarns(DeprecationWarning):
value = PauliTable(target)._array
value[0, 0] = not value[0, 0]
self.assertTrue(np.all(value == target))
with self.subTest(msg="bool array raises"):
array = np.array([[False, False, False], [True, True, True]])
with self.assertWarns(DeprecationWarning):
self.assertRaises(QiskitError, PauliTable, array)
def test_vector_init(self):
"""Test vector initialization."""
# Vector array initialization
with self.subTest(msg="bool vector"):
target = np.array([False, False, False, False])
with self.assertWarns(DeprecationWarning):
value = PauliTable(target)._array
self.assertTrue(np.all(value == target))
with self.subTest(msg="bool vector no copy"):
target = np.array([False, True, True, False])
with self.assertWarns(DeprecationWarning):
value = PauliTable(target)._array
value[0, 0] = not value[0, 0]
self.assertTrue(np.all(value == target))
def test_string_init(self):
"""Test string initialization."""
# String initialization
with self.subTest(msg='str init "I"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("I")._array
target = np.array([[False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "X"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("X")._array
target = np.array([[True, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "Y"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("Y")._array
target = np.array([[True, True]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "Z"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("Z")._array
target = np.array([[False, True]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "IX"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("IX")._array
target = np.array([[True, False, False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "XI"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("XI")._array
target = np.array([[False, True, False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "YZ"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("YZ")._array
target = np.array([[False, True, True, True]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
with self.subTest(msg='str init "XIZ"'):
with self.assertWarns(DeprecationWarning):
value = PauliTable("XIZ")._array
target = np.array([[False, False, True, True, False, False]], dtype=bool)
self.assertTrue(np.all(np.array(value == target)))
def test_table_init(self):
"""Test table initialization."""
# Pauli Table initialization
with self.subTest(msg="PauliTable"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliTable(target)
self.assertEqual(value, target)
with self.subTest(msg="PauliTable no copy"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XI", "IX", "IZ"])
value = PauliTable(target)
value[0] = "II"
self.assertEqual(value, target)
class TestPauliTableProperties(QiskitTestCase):
"""Tests for PauliTable properties."""
def test_array_propertiy(self):
"""Test array property"""
with self.subTest(msg="array"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable("II")
array = np.zeros([2, 4], dtype=bool)
self.assertTrue(np.all(pauli.array == array))
with self.subTest(msg="set array"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable("XX")
array = np.zeros([1, 4], dtype=bool)
pauli.array = array
self.assertTrue(np.all(pauli.array == array))
with self.subTest(msg="set array raises"):
def set_array_raise():
with self.assertWarns(DeprecationWarning):
pauli = PauliTable("XXX")
pauli.array = np.eye(4)
return pauli
self.assertRaises(ValueError, set_array_raise)
def test_x_propertiy(self):
"""Test X property"""
with self.subTest(msg="X"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ", "YY"])
array = np.array([[False, True], [False, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.X == array))
with self.subTest(msg="set X"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.X = val
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli, PauliTable.from_labels(["II", "XY"]))
with self.subTest(msg="set X raises"):
def set_x():
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.X = val
return pauli
self.assertRaises(Exception, set_x)
def test_z_propertiy(self):
"""Test Z property"""
with self.subTest(msg="Z"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ", "YY"])
array = np.array([[False, False], [True, False], [True, True]], dtype=bool)
self.assertTrue(np.all(pauli.Z == array))
with self.subTest(msg="set Z"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ"])
val = np.array([[False, False], [True, True]], dtype=bool)
pauli.Z = val
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli, PauliTable.from_labels(["XI", "ZZ"]))
with self.subTest(msg="set Z raises"):
def set_z():
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IZ"])
val = np.array([[False, False, False], [True, True, True]], dtype=bool)
pauli.Z = val
return pauli
self.assertRaises(Exception, set_z)
def test_shape_propertiy(self):
"""Test shape property"""
shape = (3, 8)
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(np.zeros(shape))
self.assertEqual(pauli.shape, shape)
def test_size_propertiy(self):
"""Test size property"""
with self.subTest(msg="size"):
for j in range(1, 10):
shape = (j, 8)
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(np.zeros(shape))
self.assertEqual(pauli.size, j)
def test_n_qubit_propertiy(self):
"""Test n_qubit property"""
with self.subTest(msg="num_qubits"):
for j in range(1, 10):
shape = (5, 2 * j)
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(np.zeros(shape))
self.assertEqual(pauli.num_qubits, j)
def test_eq(self):
"""Test __eq__ method."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["II", "XI"])
pauli2 = PauliTable.from_labels(["XI", "II"])
self.assertEqual(pauli1, pauli1)
self.assertNotEqual(pauli1, pauli2)
def test_len_methods(self):
"""Test __len__ method."""
for j in range(1, 10):
labels = j * ["XX"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
self.assertEqual(len(pauli), j)
def test_add_methods(self):
"""Test __add__ method."""
labels1 = ["XXI", "IXX"]
labels2 = ["XXI", "ZZI", "ZYZ"]
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(labels1)
pauli2 = PauliTable.from_labels(labels2)
target = PauliTable.from_labels(labels1 + labels2)
self.assertEqual(target, pauli1 + pauli2)
def test_add_qargs(self):
"""Test add method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["IIII", "YYYY"])
pauli2 = PauliTable.from_labels(["XY", "YZ"])
with self.subTest(msg="qargs=[0, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIII", "YYYY", "IIXY", "IIYZ"])
self.assertEqual(pauli1 + pauli2([0, 1]), target)
with self.subTest(msg="qargs=[0, 3]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIII", "YYYY", "XIIY", "YIIZ"])
self.assertEqual(pauli1 + pauli2([0, 3]), target)
with self.subTest(msg="qargs=[2, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIII", "YYYY", "IYXI", "IZYI"])
self.assertEqual(pauli1 + pauli2([2, 1]), target)
with self.subTest(msg="qargs=[3, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIII", "YYYY", "YIXI", "ZIYI"])
self.assertEqual(pauli1 + pauli2([3, 1]), target)
def test_getitem_methods(self):
"""Test __getitem__ method."""
with self.subTest(msg="__getitem__ single"):
labels = ["XI", "IY"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
self.assertEqual(pauli[0], PauliTable(labels[0]))
self.assertEqual(pauli[1], PauliTable(labels[1]))
with self.subTest(msg="__getitem__ array"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
inds = [0, 3]
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[inds], PauliTable.from_labels(labels[inds]))
inds = np.array([4, 1])
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[inds], PauliTable.from_labels(labels[inds]))
with self.subTest(msg="__getitem__ slice"):
labels = np.array(["XI", "IY", "IZ", "XY", "ZX"])
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
self.assertEqual(pauli[:], pauli)
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[1:3], PauliTable.from_labels(labels[1:3]))
def test_setitem_methods(self):
"""Test __setitem__ method."""
with self.subTest(msg="__setitem__ single"):
labels = ["XI", "IY"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["XI", "IY"])
pauli[0] = "II"
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[0], PauliTable("II"))
pauli[1] = "XX"
with self.assertWarns(DeprecationWarning):
self.assertEqual(pauli[1], PauliTable("XX"))
def raises_single():
# Wrong size Pauli
pauli[0] = "XXX"
self.assertRaises(Exception, raises_single)
with self.subTest(msg="__setitem__ array"):
labels = np.array(["XI", "IY", "IZ"])
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
target = PauliTable.from_labels(["II", "ZZ"])
inds = [2, 0]
pauli[inds] = target
self.assertEqual(pauli[inds], target)
def raises_array():
with self.assertWarns(DeprecationWarning):
pauli[inds] = PauliTable.from_labels(["YY", "ZZ", "XX"])
self.assertRaises(Exception, raises_array)
with self.subTest(msg="__setitem__ slice"):
labels = np.array(5 * ["III"])
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
target = PauliTable.from_labels(5 * ["XXX"])
pauli[:] = target
self.assertEqual(pauli[:], target)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(2 * ["ZZZ"])
pauli[1:3] = target
self.assertEqual(pauli[1:3], target)
class TestPauliTableLabels(QiskitTestCase):
"""Tests PauliTable label representation conversions."""
def test_from_labels_1q(self):
"""Test 1-qubit from_labels method."""
labels = ["I", "Z", "Z", "X", "Y"]
array = np.array(
[[False, False], [False, True], [False, True], [True, False], [True, True]], dtype=bool
)
with self.assertWarns(DeprecationWarning):
target = PauliTable(array)
value = PauliTable.from_labels(labels)
self.assertEqual(target, value)
def test_from_labels_2q(self):
"""Test 2-qubit from_labels method."""
labels = ["II", "YY", "XZ"]
array = np.array(
[[False, False, False, False], [True, True, True, True], [False, True, True, False]],
dtype=bool,
)
with self.assertWarns(DeprecationWarning):
target = PauliTable(array)
value = PauliTable.from_labels(labels)
self.assertEqual(target, value)
def test_from_labels_5q(self):
"""Test 5-qubit from_labels method."""
labels = [5 * "I", 5 * "X", 5 * "Y", 5 * "Z"]
array = np.array(
[10 * [False], 5 * [True] + 5 * [False], 10 * [True], 5 * [False] + 5 * [True]],
dtype=bool,
)
with self.assertWarns(DeprecationWarning):
target = PauliTable(array)
value = PauliTable.from_labels(labels)
self.assertEqual(target, value)
def test_to_labels_1q(self):
"""Test 1-qubit to_labels method."""
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(
np.array(
[[False, False], [False, True], [False, True], [True, False], [True, True]],
dtype=bool,
)
)
target = ["I", "Z", "Z", "X", "Y"]
value = pauli.to_labels()
self.assertEqual(value, target)
def test_to_labels_1q_array(self):
"""Test 1-qubit to_labels method w/ array=True."""
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(
np.array(
[[False, False], [False, True], [False, True], [True, False], [True, True]],
dtype=bool,
)
)
target = np.array(["I", "Z", "Z", "X", "Y"])
value = pauli.to_labels(array=True)
self.assertTrue(np.all(value == target))
def test_labels_round_trip(self):
"""Test from_labels and to_labels round trip."""
target = ["III", "IXZ", "XYI", "ZZZ"]
with self.assertWarns(DeprecationWarning):
value = PauliTable.from_labels(target).to_labels()
self.assertEqual(value, target)
def test_labels_round_trip_array(self):
"""Test from_labels and to_labels round trip w/ array=True."""
labels = ["III", "IXZ", "XYI", "ZZZ"]
target = np.array(labels)
with self.assertWarns(DeprecationWarning):
value = PauliTable.from_labels(labels).to_labels(array=True)
self.assertTrue(np.all(value == target))
class TestPauliTableMatrix(QiskitTestCase):
"""Tests PauliTable matrix representation conversions."""
def test_to_matrix_1q(self):
"""Test 1-qubit to_matrix method."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_array(self):
"""Test 1-qubit to_matrix method w/ array=True."""
labels = ["Z", "I", "Y", "X"]
target = np.array([pauli_mat(i) for i in labels])
with self.assertWarns(DeprecationWarning):
value = PauliTable.from_labels(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_1q_sparse(self):
"""Test 1-qubit to_matrix method w/ sparse=True."""
labels = ["X", "I", "Z", "Y"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_2q(self):
"""Test 2-qubit to_matrix method."""
labels = ["IX", "YI", "II", "ZZ"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_array(self):
"""Test 2-qubit to_matrix method w/ array=True."""
labels = ["ZZ", "XY", "YX", "IZ"]
target = np.array([pauli_mat(i) for i in labels])
with self.assertWarns(DeprecationWarning):
value = PauliTable.from_labels(labels).to_matrix(array=True)
self.assertTrue(isinstance(value, np.ndarray))
self.assertTrue(np.all(value == target))
def test_to_matrix_2q_sparse(self):
"""Test 2-qubit to_matrix method w/ sparse=True."""
labels = ["IX", "II", "ZY", "YZ"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
def test_to_matrix_5q(self):
"""Test 5-qubit to_matrix method."""
labels = ["IXIXI", "YZIXI", "IIXYZ"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix()
self.assertTrue(isinstance(values, list))
for target, value in zip(targets, values):
self.assertTrue(np.all(value == target))
def test_to_matrix_5q_sparse(self):
"""Test 5-qubit to_matrix method w/ sparse=True."""
labels = ["XXXYY", "IXIZY", "ZYXIX"]
targets = [pauli_mat(i) for i in labels]
with self.assertWarns(DeprecationWarning):
values = PauliTable.from_labels(labels).to_matrix(sparse=True)
for mat, targ in zip(values, targets):
self.assertTrue(isinstance(mat, csr_matrix))
self.assertTrue(np.all(targ == mat.toarray()))
class TestPauliTableIteration(QiskitTestCase):
"""Tests for PauliTable iterators class."""
def test_enumerate(self):
"""Test enumerate with PauliTable."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(pauli):
with self.assertWarns(DeprecationWarning):
self.assertEqual(i, PauliTable(labels[idx]))
def test_iter(self):
"""Test iter with PauliTable."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(iter(pauli)):
with self.assertWarns(DeprecationWarning):
self.assertEqual(i, PauliTable(labels[idx]))
def test_zip(self):
"""Test zip with PauliTable."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for label, i in zip(labels, pauli):
with self.assertWarns(DeprecationWarning):
self.assertEqual(i, PauliTable(label))
def test_label_iter(self):
"""Test PauliTable label_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(pauli.label_iter()):
self.assertEqual(i, labels[idx])
def test_matrix_iter(self):
"""Test PauliTable dense matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(pauli.matrix_iter()):
self.assertTrue(np.all(i == pauli_mat(labels[idx])))
def test_matrix_iter_sparse(self):
"""Test PauliTable sparse matrix_iter method."""
labels = ["III", "IXI", "IYY", "YIZ", "XYZ", "III"]
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(labels)
for idx, i in enumerate(pauli.matrix_iter(sparse=True)):
self.assertTrue(isinstance(i, csr_matrix))
self.assertTrue(np.all(i.toarray() == pauli_mat(labels[idx])))
@ddt
class TestPauliTableOperator(QiskitTestCase):
"""Tests for PauliTable base operator methods."""
@combine(j=range(1, 10))
def test_tensor(self, j):
"""Test tensor method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(labels1)
pauli2 = PauliTable.from_labels(labels2)
value = pauli1.tensor(pauli2)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels([i + j for i in labels1 for j in labels2])
self.assertEqual(value, target)
@combine(j=range(1, 10))
def test_expand(self, j):
"""Test expand method j={j}."""
labels1 = ["XX", "YY"]
labels2 = [j * "I", j * "Z"]
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(labels1)
pauli2 = PauliTable.from_labels(labels2)
value = pauli1.expand(pauli2)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels([j + i for j in labels2 for i in labels1])
self.assertEqual(value, target)
def test_compose_1q(self):
"""Test 1-qubit compose methods."""
# Test single qubit Pauli dot products
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="compose single I"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["I", "X", "Y", "Z"])
value = pauli.compose("I")
self.assertEqual(target, value)
with self.subTest(msg="compose single X"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["X", "I", "Z", "Y"])
value = pauli.compose("X")
self.assertEqual(target, value)
with self.subTest(msg="compose single Y"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["Y", "Z", "I", "X"])
value = pauli.compose("Y")
self.assertEqual(target, value)
with self.subTest(msg="compose single Z"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["Z", "Y", "X", "I"])
value = pauli.compose("Z")
self.assertEqual(target, value)
def test_dot_1q(self):
"""Test 1-qubit dot method."""
# Test single qubit Pauli dot products
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="dot single I"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["I", "X", "Y", "Z"])
value = pauli.dot("I")
self.assertEqual(target, value)
with self.subTest(msg="dot single X"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["X", "I", "Z", "Y"])
value = pauli.dot("X")
self.assertEqual(target, value)
with self.subTest(msg="dot single Y"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["Y", "Z", "I", "X"])
value = pauli.dot("Y")
self.assertEqual(target, value)
with self.subTest(msg="dot single Z"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["Z", "Y", "X", "I"])
value = pauli.dot("Z")
self.assertEqual(target, value)
def test_qargs_compose_1q(self):
"""Test 1-qubit compose method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("Z")
with self.subTest(msg="compose 1-qubit qargs=[0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIZ", "XXY"])
value = pauli1.compose(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IZI", "XYX"])
value = pauli1.compose(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="compose 1-qubit qargs=[2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZII", "YXX"])
value = pauli1.compose(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_dot_1q(self):
"""Test 1-qubit dot method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("Z")
with self.subTest(msg="dot 1-qubit qargs=[0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IIZ", "XXY"])
value = pauli1.dot(pauli2, qargs=[0])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IZI", "XYX"])
value = pauli1.dot(pauli2, qargs=[1])
self.assertEqual(value, target)
with self.subTest(msg="dot 1-qubit qargs=[2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZII", "YXX"])
value = pauli1.dot(pauli2, qargs=[2])
self.assertEqual(value, target)
def test_qargs_compose_2q(self):
"""Test 2-qubit compose method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("ZY")
with self.subTest(msg="compose 2-qubit qargs=[0, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IZY", "XYZ"])
value = pauli1.compose(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[1, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IYZ", "XZY"])
value = pauli1.compose(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[0, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZIY", "YXZ"])
value = pauli1.compose(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 2-qubit qargs=[2, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["YIZ", "ZXY"])
value = pauli1.compose(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_dot_2q(self):
"""Test 2-qubit dot method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("ZY")
with self.subTest(msg="dot 2-qubit qargs=[0, 1]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IZY", "XYZ"])
value = pauli1.dot(pauli2, qargs=[0, 1])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[1, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IYZ", "XZY"])
value = pauli1.dot(pauli2, qargs=[1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[0, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZIY", "YXZ"])
value = pauli1.dot(pauli2, qargs=[0, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 2-qubit qargs=[2, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["YIZ", "ZXY"])
value = pauli1.dot(pauli2, qargs=[2, 0])
self.assertEqual(value, target)
def test_qargs_compose_3q(self):
"""Test 3-qubit compose method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("XYZ")
with self.subTest(msg="compose 3-qubit qargs=None"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XYZ", "IZY"])
value = pauli1.compose(pauli2)
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[0, 1, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XYZ", "IZY"])
value = pauli1.compose(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[2, 1, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZYX", "YZI"])
value = pauli1.compose(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="compose 3-qubit qargs=[1, 0, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XZY", "IYZ"])
value = pauli1.compose(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
def test_qargs_dot_3q(self):
"""Test 3-qubit dot method with qargs."""
with self.assertWarns(DeprecationWarning):
pauli1 = PauliTable.from_labels(["III", "XXX"])
pauli2 = PauliTable("XYZ")
with self.subTest(msg="dot 3-qubit qargs=None"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[0, 1, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XYZ", "IZY"])
value = pauli1.dot(pauli2, qargs=[0, 1, 2])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[2, 1, 0]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["ZYX", "YZI"])
value = pauli1.dot(pauli2, qargs=[2, 1, 0])
self.assertEqual(value, target)
with self.subTest(msg="dot 3-qubit qargs=[1, 0, 2]"):
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["XZY", "IYZ"])
value = pauli1.dot(pauli2, qargs=[1, 0, 2])
self.assertEqual(value, target)
class TestPauliTableMethods(QiskitTestCase):
"""Tests for PauliTable utility methods class."""
def test_sort(self):
"""Test sort method."""
with self.subTest(msg="1 qubit standard order"):
unsrt = ["X", "Z", "I", "Y", "X", "Z"]
srt = ["I", "X", "X", "Y", "Z", "Z"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="1 qubit weight order"):
unsrt = ["X", "Z", "I", "Y", "X", "Z"]
srt = ["I", "X", "X", "Y", "Z", "Z"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="2 qubit standard order"):
srt = [
"II",
"IX",
"IY",
"IY",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZI",
"ZX",
"ZY",
"ZZ",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit weight order"):
srt = [
"II",
"IX",
"IX",
"IY",
"IZ",
"XI",
"YI",
"YI",
"ZI",
"XX",
"XX",
"XY",
"XZ",
"YX",
"YY",
"YY",
"YZ",
"ZX",
"ZX",
"ZY",
"ZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort(weight=True)
self.assertEqual(target, value)
with self.subTest(msg="3 qubit standard order"):
srt = [
"III",
"III",
"IIX",
"IIY",
"IIZ",
"IXI",
"IXX",
"IXY",
"IXZ",
"IYI",
"IYX",
"IYY",
"IYZ",
"IZI",
"IZX",
"IZY",
"IZY",
"IZZ",
"XII",
"XII",
"XIX",
"XIY",
"XIZ",
"XXI",
"XXX",
"XXY",
"XXZ",
"XYI",
"XYX",
"XYY",
"XYZ",
"XYZ",
"XZI",
"XZX",
"XZY",
"XZZ",
"YII",
"YIX",
"YIY",
"YIZ",
"YXI",
"YXX",
"YXY",
"YXZ",
"YXZ",
"YYI",
"YYX",
"YYX",
"YYY",
"YYZ",
"YZI",
"YZX",
"YZY",
"YZZ",
"ZII",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZXX",
"ZXX",
"ZXY",
"ZXZ",
"ZYI",
"ZYI",
"ZYX",
"ZYY",
"ZYZ",
"ZZI",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort()
self.assertEqual(target, value)
with self.subTest(msg="3 qubit weight order"):
srt = [
"III",
"IIX",
"IIY",
"IIZ",
"IXI",
"IYI",
"IZI",
"XII",
"YII",
"ZII",
"IXX",
"IXY",
"IXZ",
"IYX",
"IYY",
"IYZ",
"IZX",
"IZY",
"IZZ",
"XIX",
"XIY",
"XIZ",
"XXI",
"XYI",
"XZI",
"XZI",
"YIX",
"YIY",
"YIZ",
"YXI",
"YYI",
"YZI",
"YZI",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZYI",
"ZZI",
"ZZI",
"XXX",
"XXY",
"XXZ",
"XYX",
"XYY",
"XYZ",
"XZX",
"XZY",
"XZZ",
"YXX",
"YXY",
"YXZ",
"YYX",
"YYY",
"YYZ",
"YZX",
"YZY",
"YZZ",
"ZXX",
"ZXY",
"ZXZ",
"ZYX",
"ZYY",
"ZYZ",
"ZZX",
"ZZY",
"ZZZ",
]
unsrt = srt.copy()
np.random.shuffle(unsrt)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(srt)
value = PauliTable.from_labels(unsrt).sort(weight=True)
self.assertEqual(target, value)
def test_unique(self):
"""Test unique method."""
with self.subTest(msg="1 qubit"):
labels = ["X", "Z", "X", "X", "I", "Y", "I", "X", "Z", "Z", "X", "I"]
unique = ["X", "Z", "I", "Y"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(unique)
value = PauliTable.from_labels(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="2 qubit"):
labels = ["XX", "IX", "XX", "II", "IZ", "ZI", "YX", "YX", "ZZ", "IX", "XI"]
unique = ["XX", "IX", "II", "IZ", "ZI", "YX", "ZZ", "XI"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(unique)
value = PauliTable.from_labels(labels).unique()
self.assertEqual(target, value)
with self.subTest(msg="10 qubit"):
labels = [10 * "X", 10 * "I", 10 * "X"]
unique = [10 * "X", 10 * "I"]
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(unique)
value = PauliTable.from_labels(labels).unique()
self.assertEqual(target, value)
def test_delete(self):
"""Test delete method."""
with self.subTest(msg="single row"):
for j in range(1, 6):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels([j * "X", j * "Y"])
self.assertEqual(pauli.delete(0), PauliTable(j * "Y"))
self.assertEqual(pauli.delete(1), PauliTable(j * "X"))
with self.subTest(msg="multiple rows"):
for j in range(1, 6):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels([j * "X", j * "Y", j * "Z"])
self.assertEqual(pauli.delete([0, 2]), PauliTable(j * "Y"))
self.assertEqual(pauli.delete([1, 2]), PauliTable(j * "X"))
self.assertEqual(pauli.delete([0, 1]), PauliTable(j * "Z"))
with self.subTest(msg="single qubit"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["IIX", "IYI", "ZII"])
value = pauli.delete(0, qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["II", "IY", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(1, qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IX", "II", "ZI"])
self.assertEqual(value, target)
value = pauli.delete(2, qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["IX", "YI", "II"])
self.assertEqual(value, target)
with self.subTest(msg="multiple qubits"):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["IIX", "IYI", "ZII"])
value = pauli.delete([0, 1], qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["I", "I", "Z"])
self.assertEqual(value, target)
value = pauli.delete([1, 2], qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["X", "I", "I"])
self.assertEqual(value, target)
value = pauli.delete([0, 2], qubit=True)
with self.assertWarns(DeprecationWarning):
target = PauliTable.from_labels(["I", "Y", "I"])
self.assertEqual(value, target)
def test_insert(self):
"""Test insert method."""
# Insert single row
for j in range(1, 10):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(j * "X")
target0 = PauliTable.from_labels([j * "I", j * "X"])
target1 = PauliTable.from_labels([j * "X", j * "I"])
with self.subTest(msg=f"single row from str ({j})"):
value0 = pauli.insert(0, j * "I")
self.assertEqual(value0, target0)
value1 = pauli.insert(1, j * "I")
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row from PauliTable ({j})"):
with self.assertWarns(DeprecationWarning):
value0 = pauli.insert(0, PauliTable(j * "I"))
self.assertEqual(value0, target0)
with self.assertWarns(DeprecationWarning):
value1 = pauli.insert(1, PauliTable(j * "I"))
self.assertEqual(value1, target1)
with self.subTest(msg=f"single row from array ({j})"):
with self.assertWarns(DeprecationWarning):
value0 = pauli.insert(0, PauliTable(j * "I").array)
self.assertEqual(value0, target0)
with self.assertWarns(DeprecationWarning):
value1 = pauli.insert(1, PauliTable(j * "I").array)
self.assertEqual(value1, target1)
# Insert multiple rows
for j in range(1, 10):
with self.assertWarns(DeprecationWarning):
pauli = PauliTable(j * "X")
insert = PauliTable.from_labels([j * "I", j * "Y", j * "Z"])
target0 = insert + pauli
target1 = pauli + insert
with self.subTest(msg=f"multiple-rows from PauliTable ({j})"):
value0 = pauli.insert(0, insert)
self.assertEqual(value0, target0)
value1 = pauli.insert(1, insert)
self.assertEqual(value1, target1)
with self.subTest(msg=f"multiple-rows from array ({j})"):
value0 = pauli.insert(0, insert.array)
self.assertEqual(value0, target0)
value1 = pauli.insert(1, insert.array)
self.assertEqual(value1, target1)
# Insert single column
pauli = PauliTable.from_labels(["X", "Y", "Z"])
for i in ["I", "X", "Y", "Z"]:
with self.assertWarns(DeprecationWarning):
target0 = PauliTable.from_labels(["X" + i, "Y" + i, "Z" + i])
target1 = PauliTable.from_labels([i + "X", i + "Y", i + "Z"])
with self.subTest(msg="single-column single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column single-val from PauliTable"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable(i), qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column single-val from array"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable(i).array, qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable(i).array, qubit=True)
self.assertEqual(value, target1)
# Insert single column with multiple values
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["X", "Y", "Z"])
for i in [("I", "X", "Y"), ("X", "Y", "Z"), ("Y", "Z", "I")]:
with self.assertWarns(DeprecationWarning):
target0 = PauliTable.from_labels(["X" + i[0], "Y" + i[1], "Z" + i[2]])
target1 = PauliTable.from_labels([i[0] + "X", i[1] + "Y", i[2] + "Z"])
with self.subTest(msg="single-column multiple-vals from PauliTable"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable.from_labels(i), qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable.from_labels(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="single-column multiple-vals from array"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns from single
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["X", "Y", "Z"])
for j in range(1, 5):
for i in [j * "I", j * "X", j * "Y", j * "Z"]:
with self.assertWarns(DeprecationWarning):
target0 = PauliTable.from_labels(["X" + i, "Y" + i, "Z" + i])
target1 = PauliTable.from_labels([i + "X", i + "Y", i + "Z"])
with self.subTest(msg="multiple-columns single-val from str"):
value = pauli.insert(0, i, qubit=True)
self.assertEqual(value, target0)
value = pauli.insert(1, i, qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-columns single-val from PauliTable"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable(i), qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-columns single-val from array"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable(i).array, qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable(i).array, qubit=True)
self.assertEqual(value, target1)
# Insert multiple columns multiple row values
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["X", "Y", "Z"])
for j in range(1, 5):
for i in [
(j * "I", j * "X", j * "Y"),
(j * "X", j * "Z", j * "Y"),
(j * "Y", j * "Z", j * "I"),
]:
with self.assertWarns(DeprecationWarning):
target0 = PauliTable.from_labels(["X" + i[0], "Y" + i[1], "Z" + i[2]])
target1 = PauliTable.from_labels([i[0] + "X", i[1] + "Y", i[2] + "Z"])
with self.subTest(msg="multiple-column multiple-vals from PauliTable"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable.from_labels(i), qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable.from_labels(i), qubit=True)
self.assertEqual(value, target1)
with self.subTest(msg="multiple-column multiple-vals from array"):
with self.assertWarns(DeprecationWarning):
value = pauli.insert(0, PauliTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target0)
with self.assertWarns(DeprecationWarning):
value = pauli.insert(1, PauliTable.from_labels(i).array, qubit=True)
self.assertEqual(value, target1)
def test_commutes(self):
"""Test commutes method."""
# Single qubit Pauli
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="commutes single-Pauli I"):
value = list(pauli.commutes("I"))
target = [True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli X"):
value = list(pauli.commutes("X"))
target = [True, True, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Y"):
value = list(pauli.commutes("Y"))
target = [True, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli Z"):
value = list(pauli.commutes("Z"))
target = [True, False, False, True]
self.assertEqual(value, target)
# 2-qubit Pauli
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["II", "IX", "YI", "XY", "ZZ"])
with self.subTest(msg="commutes single-Pauli II"):
value = list(pauli.commutes("II"))
target = [True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IX"):
value = list(pauli.commutes("IX"))
target = [True, True, True, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XI"):
value = list(pauli.commutes("XI"))
target = [True, True, False, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YI"):
value = list(pauli.commutes("YI"))
target = [True, True, True, False, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli IY"):
value = list(pauli.commutes("IY"))
target = [True, False, True, True, False]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli XY"):
value = list(pauli.commutes("XY"))
target = [True, False, False, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli YX"):
value = list(pauli.commutes("YX"))
target = [True, True, True, True, True]
self.assertEqual(value, target)
with self.subTest(msg="commutes single-Pauli ZZ"):
value = list(pauli.commutes("ZZ"))
target = [True, False, False, True, True]
self.assertEqual(value, target)
def test_commutes_with_all(self):
"""Test commutes_with_all method."""
# 1-qubit
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="commutes_with_all [I]"):
value = list(pauli.commutes_with_all("I"))
target = [0, 1, 2, 3]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [X]"):
value = list(pauli.commutes_with_all("X"))
target = [0, 1]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Y]"):
value = list(pauli.commutes_with_all("Y"))
target = [0, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [Z]"):
value = list(pauli.commutes_with_all("Z"))
target = [0, 3]
self.assertEqual(value, target)
# 2-qubit Pauli
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["II", "IX", "YI", "XY", "ZZ"])
with self.subTest(msg="commutes_with_all [IX, YI]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["IX", "YI"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, ZZ]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, ZZ]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["YX", "ZZ"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, YX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "YX"])
value = list(pauli.commutes_with_all(other))
target = [0, 3, 4]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [XY, IX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0]
self.assertEqual(value, target)
with self.subTest(msg="commutes_with_all [YX, IX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["YX", "IX"])
value = list(pauli.commutes_with_all(other))
target = [0, 1, 2]
self.assertEqual(value, target)
def test_anticommutes_with_all(self):
"""Test anticommutes_with_all method."""
# 1-qubit
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["I", "X", "Y", "Z"])
with self.subTest(msg="anticommutes_with_all [I]"):
value = list(pauli.anticommutes_with_all("I"))
target = []
self.assertEqual(value, target)
with self.subTest(msg="antianticommutes_with_all [X]"):
value = list(pauli.anticommutes_with_all("X"))
target = [2, 3]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Y]"):
value = list(pauli.anticommutes_with_all("Y"))
target = [1, 3]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [Z]"):
value = list(pauli.anticommutes_with_all("Z"))
target = [1, 2]
self.assertEqual(value, target)
# 2-qubit Pauli
with self.assertWarns(DeprecationWarning):
pauli = PauliTable.from_labels(["II", "IX", "YI", "XY", "ZZ"])
with self.subTest(msg="anticommutes_with_all [IX, YI]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["IX", "YI"])
value = list(pauli.anticommutes_with_all(other))
target = [3, 4]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, ZZ]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = [1, 2]
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, ZZ]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["YX", "ZZ"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, YX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "YX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [XY, IX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["XY", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
with self.subTest(msg="anticommutes_with_all [YX, IX]"):
with self.assertWarns(DeprecationWarning):
other = PauliTable.from_labels(["YX", "IX"])
value = list(pauli.anticommutes_with_all(other))
target = []
self.assertEqual(value, target)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, backend=FakeBoeblingen())
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
filename = "job_ids_jakarta_100step_20220412_030333_.pkl"
import pickle
with open(filename, "rb") as f:
print(pickle.load(f))
filename = "job_ids_jakarta_100step_20220413_012425_.pkl"
with open(filename, "rb") as f:
print(pickle.load(f))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub="ibm-q", group="open", project="main")
program_id = "qaoa"
qaoa_program = provider.runtime.program(program_id)
print(f"Program name: {qaoa_program.name}, Program id: {qaoa_program.program_id}")
print(qaoa_program.parameters())
import numpy as np
from qiskit.tools import job_monitor
from qiskit.opflow import PauliSumOp, Z, I
from qiskit.algorithms.optimizers import SPSA
# Define the cost operator to run.
op = (
(Z ^ Z ^ I ^ I ^ I)
- (I ^ I ^ Z ^ Z ^ I)
+ (I ^ I ^ Z ^ I ^ Z)
- (Z ^ I ^ Z ^ I ^ I)
- (I ^ Z ^ Z ^ I ^ I)
+ (I ^ Z ^ I ^ Z ^ I)
+ (I ^ I ^ I ^ Z ^ Z)
)
# SPSA helps deal with noisy environments.
optimizer = SPSA(maxiter=100)
# We will run a depth two QAOA.
reps = 2
# The initial point for the optimization, chosen at random.
initial_point = np.random.random(2 * reps)
# The backend that will run the programm.
options = {"backend_name": "ibmq_qasm_simulator"}
# The inputs of the program as described above.
runtime_inputs = {
"operator": op,
"reps": reps,
"optimizer": optimizer,
"initial_point": initial_point,
"shots": 2**13,
# Set to True when running on real backends to reduce circuit
# depth by leveraging swap strategies. If False the
# given optimization_level (default is 1) will be used.
"use_swap_strategies": False,
# Set to True when optimizing sparse problems.
"use_initial_mapping": False,
# Set to true when using echoed-cross-resonance hardware.
"use_pulse_efficient": False,
}
job = provider.runtime.run(
program_id=program_id,
options=options,
inputs=runtime_inputs,
)
job_monitor(job)
print(f"Job id: {job.job_id()}")
print(f"Job status: {job.status()}")
result = job.result()
from collections import defaultdict
def op_adj_mat(op: PauliSumOp) -> np.array:
"""Extract the adjacency matrix from the op."""
adj_mat = np.zeros((op.num_qubits, op.num_qubits))
for pauli, coeff in op.primitive.to_list():
idx = tuple([i for i, c in enumerate(pauli[::-1]) if c == "Z"]) # index of Z
adj_mat[idx[0], idx[1]], adj_mat[idx[1], idx[0]] = np.real(coeff), np.real(coeff)
return adj_mat
def get_cost(bit_str: str, adj_mat: np.array) -> float:
"""Return the cut value of the bit string."""
n, x = len(bit_str), [int(bit) for bit in bit_str[::-1]]
cost = 0
for i in range(n):
for j in range(n):
cost += adj_mat[i, j] * x[i] * (1 - x[j])
return cost
def get_cut_distribution(result) -> dict:
"""Extract the cut distribution from the result.
Returns:
A dict of cut value: probability.
"""
adj_mat = op_adj_mat(PauliSumOp.from_list(result["inputs"]["operator"]))
state_results = []
for bit_str, amp in result["eigenstate"].items():
state_results.append((bit_str, get_cost(bit_str, adj_mat), amp**2 * 100))
vals = defaultdict(int)
for res in state_results:
vals[res[1]] += res[2]
return dict(vals)
import matplotlib.pyplot as plt
cut_vals = get_cut_distribution(result)
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
axs[0].plot(result["optimizer_history"]["energy"])
axs[1].bar(list(cut_vals.keys()), list(cut_vals.values()))
axs[0].set_xlabel("Energy evaluation number")
axs[0].set_ylabel("Energy")
axs[1].set_xlabel("Cut value")
axs[1].set_ylabel("Probability")
from qiskit_optimization.runtime import QAOAClient
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization import QuadraticProgram
qubo = QuadraticProgram()
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
qaoa_mes = QAOAClient(
provider=provider, backend=provider.get_backend("ibmq_qasm_simulator"), reps=2, alpha=0.75
)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qubo)
print(result.prettyprint())
from qiskit.transpiler import PassManager
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
UnrollCustomDefinitions,
BasisTranslator,
Optimize1qGatesDecomposition,
)
from qiskit.transpiler.passes.calibration.builders import RZXCalibrationBuilderNoEcho
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import (
EchoRZXWeylDecomposition,
)
from qiskit.test.mock import FakeBelem
backend = FakeBelem()
inst_map = backend.defaults().instruction_schedule_map
channel_map = backend.configuration().qubit_channel_mapping
rzx_basis = ["rzx", "rz", "x", "sx"]
pulse_efficient = PassManager(
[
# Consolidate consecutive two-qubit operations.
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=["rz", "sx", "x", "rxx"]),
# Rewrite circuit in terms of Weyl-decomposed echoed RZX gates.
EchoRZXWeylDecomposition(backend.defaults().instruction_schedule_map),
# Attach scaled CR pulse schedules to the RZX gates.
RZXCalibrationBuilderNoEcho(
instruction_schedule_map=inst_map, qubit_channel_mapping=channel_map
),
# Simplify single-qubit gates.
UnrollCustomDefinitions(std_eqlib, rzx_basis),
BasisTranslator(std_eqlib, rzx_basis),
Optimize1qGatesDecomposition(rzx_basis),
]
)
from qiskit import QuantumCircuit
circ = QuantumCircuit(3)
circ.h([0, 1, 2])
circ.rzx(0.5, 0, 1)
circ.swap(0, 1)
circ.cx(2, 1)
circ.rz(0.4, 1)
circ.cx(2, 1)
circ.rx(1.23, 2)
circ.cx(2, 1)
circ.draw("mpl")
pulse_efficient.run(circ).draw("mpl", fold=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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-optimize-20points" # 01.06.2021 experiment
filename = "data/noisy_VQE_maxiter-500_Ising_L5_anti_-1_20" #"data/noisy_VQE_maxiter-100_Ising_L5_anti_-1_20_recycle"
print("filename: ", filename, "notebook name: ", name)
# where to get the simulated thetas values from? needs to contain a thetas_mitigated array
filename_simulated_thetas = 'data/ibmq_antiferro-1D-load_bogota-optimize_thetas-loss-cost_run2.npz'
load = True
recompute = False # whether or not to recompute Magnetization, makes sense on device
# this is noisy simulation data
L = 5
num_trash = 2
anti = -1
VQE_params = np.load(filename + ".npz", allow_pickle=True)
pick = np.arange(0,len(VQE_params['gx_list']))
gx_list = VQE_params['gx_list'][pick]
gz_list = VQE_params['gz_list'][pick]
opt_params = VQE_params['opt_params'][pick]
Qmags = VQE_params["Qmag"][pick]
Qen = VQE_params["Qen"][pick]
Sen = VQE_params["Sen"][pick]
Smags = VQE_params["Smag"][pick]
gx_vals = np.unique(gx_list)
gz_vals = np.unique(gz_list)
# these are the results from using precalculated VQE values from noisy simulation on the real device (ibmq_bogota)
if load:
temp = np.load("data/" + name + "executed_mags-Es.npz",allow_pickle=True)
Qmags_executed = temp["Qmags"]
# these are values actually obtained with VQE on ibmq_rome
VQE_params = np.load("data/rome_VQE_maxiter-30_Ising_L5_anti_-1_20_recycle.npz", allow_pickle=True)
print(VQE_params.files)
pick = np.arange(0,len(VQE_params['gx_list']))
gx_list2 = VQE_params['gx_list'][pick]
gz_list2 = VQE_params['gz_list'][pick]
opt_params2 = VQE_params['opt_params'][pick]
Qmags2 = VQE_params["Qmag"][pick]
Qen2 = VQE_params["Qen"][pick]
Sen2 = VQE_params["Sen"][pick]
Smags2 = VQE_params["Smag"][pick]
gx_vals2 = np.unique(gx_list2)
gz_vals2 = np.unique(gz_list2)
fig, axs = plt.subplots(ncols=2,figsize=(14,4))
ax=axs[0]
ax.plot(gx_list, Qmags_executed,"x--", label="simulated VQE on ibmq_bogota")
ax.plot(gx_list2, Qmags2,".:", label = "full mag on ibmq_rome")
ax.set_xscale("log")
ax.legend()
ax=axs[1]
ax.plot(gx_list, abs(Qmags_executed),"x--", label="simulated VQE on ibmq_bogota")
ax.plot(gx_list2, abs(Qmags2),".:", label = "full mag on ibmq_rome")
ax.set_xscale("log")
ax.legend()
fig, axs = plt.subplots(ncols=2, figsize=(10,5))
ax = axs[0]
ax.plot(gx_list, Smags,"x--", label="ED")
ax.plot(gx_list, Qmags,"x--", label="VQE simu w/ noise")
ax.set_xscale("log")
if recompute or load:
ax.plot(gx_list, Qmags_executed,"x--", label="IBMQ")
ax.legend()
ax.set_title("$M$")
ax = axs[1]
ax.plot(gx_list, Smags,"x--", label="ED")
ax.plot(gx_list, abs(Qmags),"x--", label="VQE simu w/ noise")
ax.set_xscale("log")
if recompute or load:
ax.plot(gx_list, abs(Qmags_executed),"x--", label="ibmq_bogota")
ax.legend()
ax.set_title("$\\mid M \\mid$")
##############################################################################
### II - Training ###########################################################
##############################################################################
cal_matrix = np.array([[0.982, 0.036, 0.032, 0.003],
[0.011, 0.959, 0., 0.036],
[0.007, 0.001, 0.962, 0.023],
[0., 0.004, 0.006, 0.938]]) # this was the one from the experiment
from qiskit.tools.visualization import *
temp = np.load("data/" + 'ibmq_antiferro-1D-load_simu' + "raw-vs-mitigated-counts.npz",allow_pickle=True)
plot_histogram([temp["raw_counts"].item(), temp["mitigated_counts"].item()], legend=['raw', 'mitigated'])
counts0 = temp["raw_counts"].item()
counts1 = temp["mitigated_counts"].item()
sortkeys = list(sorted([_ for _ in counts0]))
fig, ax = plt.subplots(figsize=(5,3))
plt.grid()
sortkeys = list(sorted([_ for _ in counts0]))
vals = np.array([counts0[_] for _ in sortkeys])
vals = vals/np.sum(vals)
ax.bar(sortkeys,vals, width=-0.3, align="edge", label="raw")
sortkeys = list(sorted([_ for _ in counts1]))
vals = np.array([counts1[_] for _ in sortkeys])
vals = vals/np.sum(vals)
ax.bar(sortkeys,vals, width=0.3, align="edge", label="mitigated")
ax.legend()
plt.tick_params(labelsize=14)
ax.set_ylabel("counts/shots", fontsize=20)
plt.tight_layout()
plt.savefig("plots/counts_mitigated-vs-raw.png")
plt.savefig("plots/counts_mitigated-vs-raw.pdf")
phis = opt_params
# translate to Rikes naming
gxs = gx_list
gzs = gz_list
phys_params= [0]
fig, ax = plt.subplots(ncols=1,figsize=(6,5))
ax.set_title("Mitigated results")
cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:", label="loss noisy sim.")
cost = np.load("data/" + name + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:", label="loss ibmq_bogota")
ax.plot(gx_list, Qmags,"x--", label="$\\langle \\sigma_z \\rangle$ noisy sim.")
ax.plot(gx_list, Qmags_executed,"x--", label="$\\langle \\sigma_z \\rangle$ ibmq_bogota")
ax.set_xscale("log")
for p in phys_params:
ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
ax.legend()
phys_params = [-1]
fig, ax = plt.subplots(ncols=1,figsize=(6,5))
ax.set_title("Mitigated results")
cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,"x--", label="loss noisy sim.")
cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:", label="loss ibmq_bogota")
ax.plot(gx_list, abs(Qmags),"x--", label="$\\mid M \\mid$ noisy sim.")
ax.plot(gx_list, abs(Qmags_executed),".:", label="$\\mid M \\mid$ ibmq_bogota")
ax.set_xscale("log")
for p in phys_params:
ax.plot(gx_list[p],cost[p],"o",alpha=0.3,color="magenta")
ax.legend()
name
fig, axs = plt.subplots(nrows=2,figsize=(6,6),sharex=True,gridspec_kw={'height_ratios': [2, 2]})
ax = axs[0]
cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:")#, label="loss noisy sim.")
cost = np.load("data/" + name + "_thetas-loss-cost_run1.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:")#, label="loss ibmq_bogota")
ax.plot(gx_list, Qmags,"x--", label="$\hat{S}$ noisy sim.")
ax.plot(gx_list, Qmags_executed,"x--", label="$\hat{S}$ ibmq_bogota")
ax.set_xscale("log")
ax.plot(gx_list[0],cost[0], "X",markersize=20,alpha=0.4,color="magenta")
ax = axs[1]
cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,"x--", label="cost noisy sim.")
cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:", label="cost ibmq_bogota")
ax.plot(gx_list, abs(Qmags),"x--", label="$\\mid \hat{S} \\mid$ noisy sim.")
ax.plot(gx_list, abs(Qmags_executed),".:", label="$\\mid \hat{S} \\mid$ ibmq_bogota")
ax.set_xscale("log")
ax.plot(gx_list[-1],cost[-1],"X",markersize=20,alpha=0.4,color="magenta")
for ax in axs:
ax.legend()
ax.tick_params(labelsize=14)
axs[-1].set_xlabel("$g_x$", fontsize=14)
plt.tight_layout()
axs[0].text(0.01,0.9,"a", fontweight="bold", size=18, transform = axs[0].transAxes)
axs[1].text(0.01,0.9,"b", fontweight="bold", size=18, transform = axs[1].transAxes)
plt.savefig("plots/" + name + "_mainplot.png", bbox_inches='tight')
plt.savefig("plots/" + name + "_mainplot.pdf", bbox_inches='tight')
fig, ax = plt.subplots(ncols=1,figsize=(6,5))
ax.set_title("Mitigated results")
cost = np.load("data/" + "ibmq_antiferro-1D-load_simu" + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,"x--", label="loss noisy sim.")
cost = np.load("data/" + name + "_thetas-loss-cost_run2.npz", allow_pickle=True)["cost_mitigated"]
ax.plot(gx_list, cost,".:", label="loss ibmq_bogota")
ax.plot(gx_list, abs(Qmags),"x--", label="order parameter")
#ax.plot(gx_list, abs(Qmags_executed),".:", label="$\\mid M \\mid$ ibmq_bogota")
ax.set_xscale("log")
ax.plot(gx_list[-1],cost[-1], "X",markersize=20,alpha=0.4,color="magenta")
ax.legend(fontsize=16)
ax.tick_params(labelsize=14)
ax.set_xlabel("$g_x$", fontsize=14)
plt.savefig("plots/IBMQ_presentation.png", dpi=400, bbox_inches='tight')
cost = np.load("data/ibmq_antiferro-2D_load-AD_10x10_noisy-rome-simu_thetas-loss-cost_run1.npy",allow_pickle=True)
qmag = np.load("data/noisy_rome_simu_VQE_maxiter-500_Ising_L5_anti_-1_10x10.npz", allow_pickle=True)["Qmag"].reshape(10,10)
x,y = np.logspace(-2,2,10), np.logspace(-2,2,10)
x,y = np.meshgrid(x,y)
fig,axs = plt.subplots(ncols=1, nrows=2,figsize=(5,5),sharex=True, sharey=True, squeeze=False)
cmap = plt.get_cmap("plasma") #'viridis'
cbar_labelsize = 14
cbar = np.zeros((2,2), dtype="object")
ax = axs[0,0]
im = ax.pcolormesh(x,y,qmag, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export
cbar[0,0] = fig.colorbar(im, ax=ax)
cbar[0,0].ax.tick_params(labelsize=cbar_labelsize)
ax = axs[1,0]
im = ax.pcolormesh(x,y,cost,vmin=0, cmap=cmap, shading="auto",rasterized=True)
cbar[1,0] = fig.colorbar(im, ax=ax)
cbar[1,0].ax.tick_params(labelsize=cbar_labelsize)
#ax.plot(vs[47],ds[25],"x", color="magenta")
axs[1,0].plot(1e-2,1e-2,"x", markersize=12, color="magenta")
for ax in axs.flatten():
ax.set_xscale("log")
ax.set_yscale("log")
ax.tick_params(labelsize=14)
axs[1,0].set_xlabel(r"$g_x$",fontsize=18)
axs[0,0].set_ylabel(r"$g_z$",fontsize=18)
axs[1,0].set_ylabel(r"$g_z$",fontsize=18)
plt.tight_layout()
# has to happen after tight_layout()
axs[0,0].text(-0.25,0.9,"a", fontweight="bold", size=18, transform = axs[0,0].transAxes)
axs[1,0].text(-0.25,0.9,"b", fontweight="bold", size=18, transform = axs[1,0].transAxes)
axs[0,0].text(0.05,0.9,"Staggered Magnetization", size=14, transform = axs[0,0].transAxes)
axs[1,0].text(0.05,0.9,"cost", size=14, transform = axs[1,0].transAxes)
plt.savefig("plots/antiferro2D.pdf", bbox_inches='tight')
fig,axs = plt.subplots(ncols=2,figsize=(9,4),sharex=True, sharey=True)
cmap = plt.get_cmap("plasma") #'viridis'
cbar_labelsize = 14
cbar = np.zeros((2), dtype="object")
ax = axs[0]
im = ax.pcolormesh(x,y,qmag, cmap=cmap, shading="auto",rasterized=True) #,rasterized=True necessary for pdf export
cbar[0] = fig.colorbar(im, ax=ax)
cbar[0].ax.tick_params(labelsize=cbar_labelsize)
ax = axs[1]
im = ax.pcolormesh(x,y,cost,vmin=0, cmap=cmap, shading="auto",rasterized=True)
cbar[1] = fig.colorbar(im, ax=ax)
cbar[1].ax.tick_params(labelsize=cbar_labelsize)
#ax.plot(vs[47],ds[25],"x", color="magenta")
axs[1].plot(1e-2,1e-2,"x", markersize=12, color="magenta")
for ax in axs:
ax.set_xscale("log")
ax.set_yscale("log")
ax.tick_params(labelsize=14)
axs[1].set_xlabel(r"$g_x$",fontsize=18)
axs[0].set_xlabel(r"$g_x$",fontsize=18)
axs[0].set_ylabel(r"$g_z$",fontsize=18)
plt.tight_layout()
# has to happen after tight_layout()
#axs[0].text(0.05,0.9,"a Staggered Magnetization", fontweight="bold", size=18, transform = axs[0].transAxes)
#axs[1].text(0.05,0.9,"b cost", fontweight="bold", size=18, transform = axs[1].transAxes)
axs[0].set_title("order parameter", fontsize=14)
axs[1].set_title("cost", fontsize=14)
plt.savefig("plots/antiferro2D_bigger.pdf", bbox_inches='tight')
plt.savefig("plots/antiferro2D_bigger.png", bbox_inches='tight')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc.draw(output='mpl')
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../utils/")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
# from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
with open("jobs_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open(filename, "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_ibmq_jakarta_100step_20220413_030821_.pkl" # change here
with open(filename, "rb") as f:
job_ids_dict = pickle.load(f)
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/miamico/Quantum_Generative_Adversarial_Networks
|
miamico
|
"""Simple example on how to log scalars and images to tensorboard without tensor ops.
License: Copyleft
"""
__author__ = "Michael Gygli"
import tensorflow as tf
# from StringIO import StringIO
import matplotlib.pyplot as plt
import numpy as np
class Logger(object):
"""Logging in tensorboard without tensorflow ops."""
def __init__(self, log_dir):
"""Creates a summary writer logging to log_dir."""
self.writer = tf.summary.FileWriter(log_dir)
def log_scalar(self, tag, value, step):
"""Log a scalar variable.
Parameter
----------
tag : basestring
Name of the scalar
value
step : int
training iteration
"""
summary = tf.Summary(value=[tf.Summary.Value(tag=tag,
simple_value=value)])
self.writer.add_summary(summary, step)
def log_images(self, tag, images, step):
"""Logs a list of images."""
im_summaries = []
for nr, img in enumerate(images):
# Write the image to a string
s = StringIO()
plt.imsave(s, img, format='png')
# Create an Image object
img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),
height=img.shape[0],
width=img.shape[1])
# Create a Summary value
im_summaries.append(tf.Summary.Value(tag='%s/%d' % (tag, nr),
image=img_sum))
# Create and write Summary
summary = tf.Summary(value=im_summaries)
self.writer.add_summary(summary, step)
def log_histogram(self, tag, values, step, bins=1000):
"""Logs the histogram of a list/vector of values."""
# Convert to a numpy array
values = np.array(values)
# Create histogram using numpy
counts, bin_edges = np.histogram(values, bins=bins)
# Fill fields of histogram proto
hist = tf.HistogramProto()
hist.min = float(np.min(values))
hist.max = float(np.max(values))
hist.num = int(np.prod(values.shape))
hist.sum = float(np.sum(values))
hist.sum_squares = float(np.sum(values ** 2))
# Requires equal number as bins, where the first goes from -DBL_MAX to bin_edges[1]
# See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/summary.proto#L30
# Thus, we drop the start of the first bin
bin_edges = bin_edges[1:]
# Add bin edges and counts
for edge in bin_edges:
hist.bucket_limit.append(edge)
for c in counts:
hist.bucket.append(c)
# Create and write Summary
summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=hist)])
self.writer.add_summary(summary, step)
self.writer.flush()
|
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/Christophe-pere/Deutsch_Jozsa_qiskit
|
Christophe-pere
|
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
class DeutschJozsa:
'''
Class to generate a DeutschJozsa object containing:
- init functions
- oracle function
- dj function
'''
def __init__(self, case, input_str):
'''
Initialization of the object:
@case: (str) type of oracle balanced or constant
@input_str: (str) string input state values
'''
self.case = case
self.number_qubit = len(input_str)
self.str_input = input_str
def oracle(self):
'''
Will create the oracle needed for the Deutsch-Jozsa algorithm
No input, the function will be used in the dj function
@return the oracle in form of a gate
'''
# Create the QuantumCircuit with n+1 qubits
self.oracle_circuit = QuantumCircuit(self.number_qubit+1)
# Balanced case
if self.case == "balanced":
# apply an X-gate to a qubit when its value is 1
for qubit in range(len(self.str_input)):
if self.str_input[qubit] == '1':
self.oracle_circuit.x(qubit)
# Apply CNOT gates on each qubit
for qubit in range(self.number_qubit):
self.oracle_circuit.cx(qubit, self.number_qubit)
# apply another set of X gates when the input qubit == 1
for qubit in range(len(self.str_input)):
if self.str_input[qubit] == '1':
self.oracle_circuit.x(qubit)
# Constant case
if self.case == "constant":
# Output 0 for a constant oracle
self.output = np.random.randint(2)
if self.output == 1:
self.oracle_circuit.x(self.number_qubit)
# convert the quantum circuit into a gate
self.oracle_gate = self.oracle_circuit.to_gate()
# name of the oracle
self.oracle_gate.name = "Oracle"
return self.oracle_gate
def dj(self):
'''
Create the Deutsch-Jozsa algorithm in the general case with n qubit
No input
@return the quantum circuit of the DJ
'''
self.dj_circuit = QuantumCircuit(self.number_qubit+1, self.number_qubit)
# Set up the output qubit:
self.dj_circuit.x(self.number_qubit)
self.dj_circuit.h(self.number_qubit)
# Psi_0
for qubit in range(self.number_qubit):
self.dj_circuit.h(qubit)
# Psi_1 + oracle
self.dj_circuit.append(self.oracle(), range(self.number_qubit+1))
# Psi_2
for qubit in range(self.number_qubit):
self.dj_circuit.h(qubit)
# Psi_3
# Let's put some measurement
for i in range(self.number_qubit):
self.dj_circuit.measure(i, i)
return self.dj_circuit
test = DeutschJozsa('constant', '0110')
#circuit = test.oracle()
dj_circuit = test.dj()
dj_circuit.draw('mpl')
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
from qiskit import IBMQ
#TOKEN = 'paste your token here'
#IBMQ.save_account(TOKEN)
IBMQ.load_account() # Load account from disk
IBMQ.providers()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True)
backend = provider.get_backend('ibmq_manila')
backend
mapped_circuit = transpile(dj_circuit, backend=backend)
qobj = assemble(mapped_circuit, backend=backend, shots=1024)
job = backend.run(qobj)
job.status() # 9:17 pm
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
plot_histogram(counts,figsize=(10,8), filename='DJ.jpeg')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
qp = QuadraticProgram()
qp.binary_var("x")
qp.binary_var("y")
qp.integer_var(lowerbound=0, upperbound=7, name="z")
qp.maximize(linear={"x": 2, "y": 1, "z": 1})
qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="LE", rhs=5.5, name="xyz_leq")
qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="GE", rhs=2.5, name="xyz_geq")
print(qp.prettyprint())
from qiskit_optimization.converters import InequalityToEquality
ineq2eq = InequalityToEquality()
qp_eq = ineq2eq.convert(qp)
print(qp_eq.prettyprint())
print(qp_eq.prettyprint())
from qiskit_optimization.converters import IntegerToBinary
int2bin = IntegerToBinary()
qp_eq_bin = int2bin.convert(qp_eq)
print(qp_eq_bin.prettyprint())
print(qp_eq_bin.prettyprint())
from qiskit_optimization.converters import LinearEqualityToPenalty
lineq2penalty = LinearEqualityToPenalty()
qubo = lineq2penalty.convert(qp_eq_bin)
print(qubo.prettyprint())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.quantum_info import state_fidelity
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import Aer
print(Aer.backends())
from qiskit import QuantumCircuit,Aer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = Aer.get_backend("aer_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
print(counts)
from qiskit import QuantumCircuit,Aer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
backend = Aer.get_backend("aer_simulator")
qc.save_statevector()
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
statevector = result.get_statevector(tqc, 4)
print(statevector)
from qiskit import QuantumCircuit,Aer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
backend = Aer.get_backend("aer_simulator")
qc.save_unitary()
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
unitary = result.get_unitary(qc, 4)
print(unitary)
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.providers.aer.noise import \
NoiseModel, depolarizing_error
err_1 = depolarizing_error(0.95, 1)
err_2 = depolarizing_error(0.01, 2)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(err_1,
['u1', 'u2', 'u3'])
noise_model.add_all_qubit_quantum_error(err_2,
['cx'])
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = Aer.get_backend("aer_simulator")
backend.set_options(noise_model=noise_model)
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
print(counts)
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import AerSimulator
from qiskit.test.mock import FakeVigo
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
device_backend = FakeVigo()
backend = AerSimulator.from_backend(device_backend)
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
print(counts)
|
https://github.com/QuantumVic/discrete-time-quantum-walks
|
QuantumVic
|
from qiskit import *
import numpy as np
import matplotlib as mpl
from qiskit.tools.visualization import plot_histogram, plot_state_city
from qiskit.tools.monitor import job_monitor
state_sim = Aer.get_backend('statevector_simulator')
qasm_sim = Aer.get_backend('qasm_simulator')
unitary_sim = Aer.get_backend('unitary_simulator')
qiskit.__qiskit_version__ #developed in q0.14.0, q-terra0.11.0
# Definition of c_Increment, c_Decrement gates #
def increment(qc,qr):
"""controlled-increment gate, cf. PhysRevA.72.032329"""
for i in range(num_qubits - 1):
qc.mct(qr[0:num_qubits - 1 - i], qr[num_qubits - 1 - i] , qr_aux)
def decrement(qc,qr):
"""controlled-decrement gate, cf. PhysRevA.72.032329"""
for i in range(num_qubits - 1):
qc.mct(qr[0:i+1], qr[i+1], qr_aux)
# Definition of QW cycle #
def quantum_walk(qc,qr):
"""implement DTQW on a previously defined circuit and register cf. PhysRevA.72.032329"""
# coin operator
qc.h(qr[0])
#conditional shift
increment(qc,qr)
qc.x(qr[0])
decrement(qc,qr)
qc.x(qr[0])
# Definition of circuit analysis functions #
def get_tot_gates(qc):
"""get the total number of basic gates of a circuit"""
tot_gates = 0
for key in qc.decompose().count_ops():
tot_gates = tot_gates + qc.decompose().count_ops()[key]
return tot_gates
def get_cx_gates(qc):
"""get the total number of cx gates of a circuit"""
cx_gates = qc.decompose().count_ops()['cx']
return cx_gates
# Total number of qubits (lattice nodes + coin)
num_qubits = 4
num_steps = 1
# Define qRegister and cRegister
qr = QuantumRegister(num_qubits, 'qr')
cr = ClassicalRegister(num_qubits - 1, 'cr')
# Define qCircuit
# We need (num_qubits - 3) aux qubits for mct-gates
if num_qubits > 3:
qr_aux = QuantumRegister(num_qubits - 3, 'aux')
qc = QuantumCircuit(qr,qr_aux,cr)
else:
qr_aux = None
qc = QuantumCircuit(qr,cr)
# BEGINNING OF QUANTUM CIRCUIT
# Initialization for symmetric state 1/sqrt(2) [|0> + i|1>] of coin
qc.h(qr[0])
qc.s(qr[0])
qc.barrier()
# Initialization for middle state |1000...> of nodes
qc.x(qr[num_qubits - 1])
qc.barrier()
# Running the QW
for i in range(num_steps):
quantum_walk(qc,qr)
qc.barrier()
# Measurement
qc.measure(qr[1:num_qubits],cr)
qc.draw(output='mpl')
# Execute the circuit
job = execute(qc, backend=qasm_sim)
results_dict = job.result().get_counts()
# Convert the results to decimal value of cReg and plot
results_dec = {}
for key, value in results_dict.items():
results_dec[str(int(key,2))] = value
plot_histogram(results_dec)
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import QuantumCircuit
import math
from qiskit.quantum_info import Statevector
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(4,4)
qc.initialize([1,0],0)
qc.initialize([0,1],1)
qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],2)
qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],3)
qc.draw("mpl")
state = Statevector.from_instruction(qc)
plot_bloch_multivector(state)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
from random import randrange
#
# you may use method 'randrange' for this task
# randrange(n) returns a value from {0,1,...,n-1} randomly
#
#
# your solution is here
#
from random import randrange
for experiment in [100,1000,10000,100000]:
heads = tails = 0
for i in range(experiment):
if randrange(2) == 0: heads = heads + 1
else: tails = tails + 1
print("experiment:",experiment)
print("heads =",heads," tails = ",tails)
print("the ratio of #heads/#tails is",(round(heads/tails,4)))
print() # empty line
#
# you may use method 'randrange' for this task
# randrange(n) returns a value from {0,1,...,n-1} randomly
#
#
# your solution is here
#
from random import randrange
# let's pick a random number between {0,1,...,99}
# it is expected to be less than 60 with probability 0.6
# and greater than or equal to 60 with probability 0.4
for experiment in [100,1000,10000,100000]:
heads = tails = 0
for i in range(experiment):
if randrange(100) <60: heads = heads + 1 # with probability 0.6
else: tails = tails + 1 # with probability 0.4
print("experiment:",experiment)
print("heads =",heads," tails = ",tails)
print("the ratio of #heads/#tails is",(round(heads/tails,4)))
print() # empty line
def biased_coin(N,B):
from random import randrange
random_number = randrange(N)
if random_number < B:
return "Heads"
else:
return "Tails"
def biased_coin(N,B):
from random import randrange
random_number = randrange(N)
if random_number < B:
return "Heads"
else:
return "Tails"
from random import randrange
N = 101
B = randrange(100)
total_tosses = 500
the_number_of_heads = 0
for i in range(total_tosses):
if biased_coin(N,B) == "Heads":
the_number_of_heads = the_number_of_heads + 1
my_guess = the_number_of_heads/total_tosses
real_bias = B/N
error = abs(my_guess-real_bias)/real_bias*100
print("my guess is",my_guess)
print("real bias is",real_bias)
print("error (%) is",error)
|
https://github.com/W-Bernau/QiskitAlgorithms
|
W-Bernau
|
from qiskit import *
from math import pi
import numpy as np
from qiskit_aer import Aer
from qiskit.visualization import *
import matplotlib.pyplot as plt
from qutip import *
qc = QuantumCircuit(2)
qc.h(1)
qc.barrier()
qc.cu(np.pi/2, 0, 1, 0, 0 ,1)
qc.barrier()
qc.h(0)
qc.barrier()
qc.swap(0,1)
qc.draw()
backend = Aer.get_backend('statevector_simulator')
out = (backend.run(transpile(qc,backend))).result().get_statevector()
print(out)
def qft3():
n = 3
q = QuantumRegister(n)
c = ClassicalRegister(n)
qc = QuantumCircuit(q,c)
qc.h(q[2])
qc.barrier()
qc.cu(np.pi/2, 0, 0, 0, q[1], q[2])
qc.barrier()
qc.h(q[1])
qc.barrier()
qc.cu(np.pi/4, 0, 0, 0, q[0], q[2])
qc.barrier()
qc.cu(np.pi/2, 0, 0, 0, q[0], q[1])
qc.barrier()
qc.h(q[0])
qc.barrier()
qc.swap(q[0], q[2])
return q,c,qc
q,c,qc = qft3()
qc.barrier()
qc.draw()
|
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/grossiM/Qiskit_workshop1019
|
grossiM
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(2,name='qr')
crsingle = ClassicalRegister(1)
deutsch = QuantumCircuit(qr,crsingle)
deutsch.x(qr[1])
deutsch.h(qr[1])
deutsch.draw(output='latex')
deutsch.h(qr[0])
deutsch.draw(output='mpl')
deutsch.cx(qr[0],qr[1])
deutsch.h(qr[0])
deutsch.measure(qr[0],crsingle[0])
deutsch.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(deutsch, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# set the length of the $n$-bit string.
n = 2
# set the oracle, b for balanced, c for constant
oracle = "b"
# if the oracle is balanced, set the hidden bitstring, b
if oracle == "b":
b = 3 # np.random.randint(1,2**n) uncomment for a random value
# if the oracle is constant, set c = 0 or 1 randomly.
if oracle == "c":
c = np.random.randint(2)
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1)
cr = ClassicalRegister(n)
djCircuit = QuantumCircuit(qr, cr)
barriers = True
# Since all qubits are initialized to |0>, we need to flip the second register qubit to the the |1> state
djCircuit.x(qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to all qubits
djCircuit.h(qr)
# Apply barrier
if barriers:
djCircuit.barrier()
# Query the oracle
if oracle == "c": # if the oracle is constant, return c
if c == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # otherwise, the oracle is balanced and it returns the inner product of the input with b (non-zero bitstring)
for i in range(n):
if (b & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to the first register after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measure the first register
for i in range(n):
djCircuit.measure(qr[i], cr[i])
djCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(djCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
#IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(djCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
N = 4
qrQFT = QuantumRegister(N,'qftr')
QFT = QuantumCircuit(qrQFT)
for i in range(N):
QFT.h(qrQFT[i])
for k in range(i+1,N):
l = k-i+1
QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i])
QFT.draw(output='mpl')
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/qiskit-jku-provider
|
qiskit-community
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=missing-docstring,broad-except
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit import execute
from .common import QiskitTestCase
from qiskit_jku_provider import QasmSimulator
class JKUSnapshotTest(QiskitTestCase):
"""Test JKU's statevector return capatbilities."""
def setUp(self):
super().setUp()
self.backend = QasmSimulator(silent=True)
qr = QuantumRegister(2)
self.q_circuit = QuantumCircuit(qr)
self.q_circuit.h(qr[0])
self.q_circuit.cx(qr[0], qr[1])
def test_statevector_output(self):
"""Test final state vector for single circuit run."""
result = execute(self.q_circuit, backend=self.backend).result()
self.assertEqual(result.success, True)
actual = result.get_statevector(self.q_circuit)
# state is 1/sqrt(2)|00> + 1/sqrt(2)|11>, up to a global phase
self.assertAlmostEqual((abs(actual[0]))**2, 1/2, places=5)
self.assertEqual(actual[1], 0)
self.assertEqual(actual[2], 0)
self.assertAlmostEqual((abs(actual[3]))**2, 1/2, places=5)
if __name__ == '__main__':
unittest.main()
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
# Qiskitライブラリーを導入
from qiskit import *
# 描画のためのライブラリーを導入
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskitバージョンの確認
qiskit.__qiskit_version__
# 2量子ビット回路を用意してください
qc=QuantumCircuit(2,2)
# 回路を描画します
qc.draw(output="mpl")
# EveがEPRペアを作ってAliceとBobに渡します
qc.h(0)
qc.cx(0,1)
qc.barrier()
# 回路を描画します
qc.draw(output="mpl")
# Aliceが送りたい2古典ビットをセットします
msg = "11" # 送りたいメッセージの入力
if msg == "00":
pass
elif msg == "10": #10の場合
qc.x(0)
elif msg == "01": #01の場合
qc.z(0)
elif msg == "11": #01の場合
qc.z(0)
qc.x(0)
# 回路を描画します
qc.draw(output="mpl")
# BobはAliceからEPRビットをもらい、復元のためのゲートを適用します
qc.cx(0,1)
qc.h(0)
qc.barrier()
# 回路を描画します
qc.draw(output="mpl")
# Bobが測定します
qc.measure(0,0)
qc.measure(1,1)
# 回路を描画します
qc.draw(output="mpl")
# qasm_simulator で実行して、AliceからBobに2ビットが転送されたか確認します。
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(qc,backend)
sim_result = job_sim.result()
print(sim_result.get_counts(qc))
from qiskit.visualization import plot_histogram
plot_histogram(sim_result.get_counts(qc))
# 初めて実デバイスで実行する人はこちらを実行
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN') # ご自分のトークンを入れてください
# アカウント情報をロードして、使える量子デバイスを確認します
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
# 最もすいているバックエンドを選びます
from qiskit.providers.ibmq import least_busy
large_enough_devices = IBMQ.get_provider().backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator)
print(large_enough_devices)
real_backend = least_busy(large_enough_devices)
print("ベストなバックエンドは " + real_backend.name())
# 上記のバックエンドで実行します
job = execute(qc,real_backend)
# ジョブの実行状態を確認します
from qiskit.tools.monitor import job_monitor
job_monitor(job)
# 結果を確認します
real_result= job.result()
print(real_result.get_counts(qc))
plot_histogram(real_result.get_counts(qc))
|
https://github.com/Gopal-Dahale/qiskit-qulacs
|
Gopal-Dahale
|
import numpy as np
from qiskit.circuit.library import IQP
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.quantum_info import SparsePauliOp, random_hermitian
n_qubits = 4
mat = np.real(random_hermitian(n_qubits, seed=1234))
circuit = IQP(mat)
observable = SparsePauliOp("Z" * n_qubits)
print(f">>> Observable: {observable.paulis}")
from qiskit_qulacs.qulacs_backend import QulacsBackend
backend = QulacsBackend()
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_circuit = pm.run(circuit)
isa_observable = observable.apply_layout(isa_circuit.layout)
isa_circuit.draw("mpl")
from qiskit_qulacs.qulacs_estimator import QulacsEstimator
qulacs_estimator = QulacsEstimator()
job = qulacs_estimator.run(isa_circuit, isa_observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
import numpy as np
from qiskit.circuit.library import IQP
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.quantum_info import SparsePauliOp, random_hermitian
n_qubits = 4
mat = np.real(random_hermitian(n_qubits, seed=1234))
circuit = IQP(mat)
circuit.measure_all()
pm = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_circuit = pm.run(circuit)
from qiskit_qulacs.qulacs_sampler import QulacsSampler
qulacs_sampler = QulacsSampler()
job = qulacs_sampler.run(isa_circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-probability distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit.visualization import plot_histogram
plot_histogram(result.quasi_dists[0])
import qiskit
qiskit.__version__
|
https://github.com/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/Z-928/Bugs4Q
|
Z-928
|
from qiskit.circuit import Parameter
from qiskit import pulse
from qiskit.test.mock.backends.almaden import *
phase = Parameter('phase')
with pulse.build(FakeAlmaden()) as phase_test_sched:
pulse.shift_phase(phase, pulse.drive_channel(0))
phase_test_sched.instructions # ()
|
https://github.com/TRSasasusu/qiskit-quantum-zoo
|
TRSasasusu
|
"""
Implementing [arXiv:quant-ph/9511018](https://arxiv.org/abs/quant-ph/9511018)
"""
from typing import Optional
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit import Gate
def carry() -> Gate:
"""CARRY. It requires 4 qubits.
Returns:
its gate
"""
qc = QuantumCircuit(4)
qc.ccx(1, 2, 3)
qc.cx(1, 2)
qc.ccx(0, 2, 3)
return qc.to_gate()
def qsum() -> Gate:
"""SUM. It requires 3 qubits.
Returns:
its gate
"""
qc = QuantumCircuit(3)
qc.cx(1, 2)
qc.cx(0, 2)
return qc.to_gate()
def adder(n: int) -> Gate:
r"""ADDER: $a,b\to a,a+b$. It requires $3n+1$ qubits: $a$ uses $n$ qubits, $b$ uses $n+1$ qubits, and $c$ uses $n$ qubits.
Args:
n (int): $n$ bits for representing $a$.
Returns:
its gate
"""
qubits = QuantumRegister(n + (n + 1) + n)
a = qubits[:n]
b = qubits[n:n + (n + 1)]
c = qubits[n + (n + 1):]
qc = QuantumCircuit(qubits)
carry_gate = carry()
carry_gate_dag = carry_gate.inverse()
sum_gate = qsum()
for i in range(n - 1):
qc.append(carry_gate, [c[i]] + [a[i]] + [b[i]] + [c[i + 1]])
qc.append(carry_gate, [c[n - 1]] + [a[-1]] + [b[n - 1]] + [b[n]])
qc.cx(a[-1], b[n - 1])
qc.append(sum_gate, [c[n - 1]] + [a[-1]] + [b[n - 1]])
for i in reversed(range(n - 1)):
qc.append(carry_gate_dag, [c[i]] + [a[i]] + [b[i]] + [c[i + 1]])
qc.append(sum_gate, [c[i]] + [a[i]] + [b[i]])
return qc.to_gate()
def adder_modM(M: int, N_len: int) -> Gate:
r"""ADDER MOD: $a,b\to a,a+b\mod M$. It requires $4N_\mathit{len}+2$ qubits: $a$ uses $N_\mathit{len}$ qubits, $b$ uses $N_\mathit{len}+1$ qubits, $c$ uses $N_\mathit{len}$ qubits, $M$ uses $N_\mathit{len}$ qubits, and $t$ uses 1 qubit.
Args:
M (int): $N$ in the paper, but we uses $M$ instead.
N_len (int): a number of bits for representing $a$.
Returns:
its gate
"""
M_val = M
qubits = QuantumRegister(N_len + (N_len + 1) + N_len + N_len + 1)
a, left_qubits = qubits[:N_len], qubits[N_len:]
b, left_qubits = left_qubits[:N_len + 1], left_qubits[N_len + 1:]
c, left_qubits = left_qubits[:N_len], left_qubits[N_len:]
M, left_qubits = left_qubits[:N_len], left_qubits[N_len:]
t = left_qubits[:1]
qc = QuantumCircuit(qubits)
adder_gate = adder(N_len)
adder_gate_dag = adder_gate.inverse()
for i, char in enumerate(bin(M_val)[2:][::-1]):
if char == '1':
qc.x(M[i])
qc.append(adder_gate, a + b + c)
qc.append(adder_gate_dag, M + b + c)
qc.x(b[-1])
qc.cx(b[-1], t[0])
qc.x(b[-1])
for i, char in enumerate(bin(M_val)[2:][::-1]):
if char == '1':
qc.cx(t[0], M[i])
qc.append(adder_gate, M + b + c)
for i, char in enumerate(bin(M_val)[2:][::-1]):
if char == '1':
qc.cx(t[0], M[i])
qc.append(adder_gate_dag, a + b + c)
qc.cx(b[-1], t[0])
qc.append(adder_gate, a + b + c)
for i, char in enumerate(bin(M_val)[2:][::-1]):
if char == '1':
qc.x(M[i])
return qc.to_gate()
def ctrl_multi_modM(a: int, M: int, N_len: int) -> Gate:
r"""Ctrl MULT MOD: $x,0\to x,ax\mod M$ if $c=1$, otherwise $x,0\to x,x$. It requires $9N_\mathit{len}-1$ qubits: $\mathit{ctrl}$ uses 1 qubit, $x$ uses $N_\mathit{len}$ qubits, $y$ uses $2N_\mathit{len}$ qubits, $\mathit{xx}$ (which is a register in the middle of Fig. 5 in the paper) uses $2N_\mathit{len}-1$ qubits, $c$ (which is $c$ for ADDER MOD) uses $2N_\mathit{len}-1$ qubits, $M$ (which is $M$ for ADDER MOD) uses $2N_\mathit{len}-1$ qubits, and $t$ (which is $t$ for ADDER MOD) uses 1 qubit.
Args:
a (int): $a$
M (int): $M$ (see `adder_modM`)
N_len (int): a number of bits for representing $x$
Returns:
its gate
"""
M_val = M
N_len = N_len
qubits = QuantumRegister(9 * N_len - 1)
ctrl, left_qubits = qubits[:1], qubits[1:]
x, left_qubits = left_qubits[:N_len], left_qubits[N_len:]
y, left_qubits = left_qubits[:2 * N_len], left_qubits[2 * N_len:]
xx, left_qubits = left_qubits[:2 * N_len - 1], left_qubits[2 * N_len - 1:]
c, left_qubits = left_qubits[:2 * N_len - 1], left_qubits[2 * N_len - 1:]
M, left_qubits = left_qubits[:2 * N_len - 1], left_qubits[2 * N_len - 1:]
t, left_qubits = left_qubits[:1], qubits[1:]
qc = QuantumCircuit(qubits)
adder_modM_gate = adder_modM(M=M_val, N_len=2 * N_len - 1)
for i in range(N_len):
for j, char in enumerate(bin(2 ** i * a % M_val)[2:][::-1]):
if char == '1':
qc.ccx(ctrl[0], x[i], xx[j])
qc.append(adder_modM_gate, xx + y + c + M + t)
for j, char in enumerate(bin(2 ** i * a % M_val)[2:][::-1]):
if char == '1':
qc.ccx(ctrl[0], x[i], xx[j])
qc.x(ctrl[0])
for x_bit, y_bit in zip(x, y):
qc.ccx(ctrl[0], x_bit, y_bit)
qc.x(ctrl[0])
return qc.to_gate()
def ax_modM(a: int, M: int, N_len: Optional[int] = None, x_0_at_first: bool = True) -> Gate:
r"""Modular exponentiation, $a^x\mod M$. It requires $10N_\mathit{len}-2$ qubits: $x$ uses $N_\mathit{len}$ qubits, $\mathit{x\ for\ Ctrl\ MULT\ MOD}$ uses $N_\mathit{len}$ qubits, $y$ uses $2N_\mathit{len}$ qubits, $\mathit{xx}$ uses $2N_\mathit{len}-1$ qubits, $c$ (which is $c$ for ADDER MOD) uses $2N_\mathit{len}-1$ qubits, $M$ (which is $M$ for ADDER MOD) uses $2N_\mathit{len}-1$ qubits, and $t$ (which is $t$ for ADDER MOD) uses 1 qubit.
Args:
a (int): $a$
M (int): $M$ (see `adder_modM`)
N_len (int): a number of bits for representing $x$
x_0_at_first (bool): if True, it adds 1 into the target register before calculating modular exponentiation
Returns:
its gate
"""
M_val = M
if N_len is None:
N_len = int(np.ceil(np.log2(M)))
qubits = QuantumRegister(10 * N_len - 2)
x, left_qubits = qubits[:N_len], qubits[N_len:]
x_for_ctrl_multi_modM_gate, left_qubits = left_qubits[:N_len], left_qubits[N_len:]
y, left_qubits = left_qubits[:2 * N_len], left_qubits[2 * N_len:]
xx, left_qubits = left_qubits[:2 * N_len - 1], left_qubits[2 * N_len - 1:]
c, left_qubits = left_qubits[:2 * N_len - 1], left_qubits[2 * N_len - 1:]
M, left_qubits = left_qubits[:2 * N_len - 1], left_qubits[2 * N_len - 1:]
t, left_qubits = left_qubits[:1], qubits[1:]
qc = QuantumCircuit(qubits)
if x_0_at_first:
qc.x(x_for_ctrl_multi_modM_gate[0])
for i in range(N_len):
ctrl_multi_modM_gate = ctrl_multi_modM(pow(a, 2 ** i, M_val), M_val, N_len)
ctrl_multi_modM_gate_dag = ctrl_multi_modM(pow(a, -2 ** i, M_val), M_val, N_len).inverse()
qc.append(ctrl_multi_modM_gate, [x[i]] + x_for_ctrl_multi_modM_gate + y + xx + c + M + t)
for j in range(N_len):
qc.cswap(x[i], x_for_ctrl_multi_modM_gate[j], y[j])
qc.append(ctrl_multi_modM_gate_dag, [x[i]] + x_for_ctrl_multi_modM_gate + y + xx + c + M + t)
return qc.to_gate()
|
https://github.com/0sophy1/Qiskit-Dev-Cert-lectures
|
0sophy1
|
import numpy as np
from math import sqrt
#define 0, 1, +, - state
zero = np.array([[1],[0]])
one = np.array([[0],[1]])
plus = np.array([[1/sqrt(2)],[1/sqrt(2)]])
minus = np.array([[1/sqrt(2)],[ -1/sqrt(2)]])
#define H operation
H = np.array([[1/sqrt(2), 1/sqrt(2)], [1/sqrt(2), -1/sqrt(2)]])
np.matmul(H,zero) #=plus
np.matmul(H, one) #=minus
np.matmul(H, plus) #=zero
np.matmul(H, minus) #=one
|
https://github.com/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
%matplotlib inline
import numpy as np
from qiskit.visualization import plot_histogram
n = 2 #Number of qubits
qr1 = QuantumRegister(size=n)
qr2 = QuantumRegister(size=1)
cr = ClassicalRegister(size=n)
def function(circuit,fn):
if fn == 'const-0':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
elif fn == 'const-1':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.x(qr1)
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
elif fn == 'balanced':
circuit.x(qr2)
circuit.barrier()
circuit.h(qr1)
circuit.h(qr2)
circuit.barrier()
circuit.cx(qr1[0],qr2)
circuit.barrier()
circuit.h(qr1)
circuit.barrier()
circuit.measure(qr1,cr)
return circuit
circuit_1 = QuantumCircuit(qr1,qr2,cr)
circuit_1 = function(circuit_1,'const-1')
circuit_1.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_1,backend=simulator).result()
plot_histogram(result.get_counts())
circuit_0 = QuantumCircuit(qr1,qr2,cr)
circuit_0 = function(circuit_0,'const-0')
circuit_0.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_0,backend=simulator).result()
plot_histogram(result.get_counts())
circuit_b = QuantumCircuit(qr1,qr2,cr)
circuit_b = function(circuit_b,'balanced')
circuit_b.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit_b,backend=simulator).result()
plot_histogram(result.get_counts())
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
import numpy as np
import pylab
from qiskit import Aer
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SPSA
from qiskit.circuit.library import TwoLocal
from qiskit.opflow import I, X, Z
H2_op = (-1.052373245772859 * I ^ I) + \
(0.39793742484318045 * I ^ Z) + \
(-0.39793742484318045 * Z ^ I) + \
(-0.01128010425623538 * Z ^ Z) + \
(0.18093119978423156 * X ^ X)
print(f'Number of qubits: {H2_op.num_qubits}')
# Compute reference using classical method
npme = NumPyMinimumEigensolver()
result = npme.compute_minimum_eigenvalue(operator=H2_op)
ref_value = result.eigenvalue.real
print(f'Reference value: {ref_value:.5f}')
### Performance Without Noise
seed = 170
iterations = 125
algorithm_globals.random_seed = seed
backend = Aer.get_backend('aer_simulator')
qi = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed)
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
ansatz = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz')
spsa = SPSA(maxiter=iterations)
vqe = VQE(ansatz, optimizer=spsa, callback=store_intermediate_result, quantum_instance=qi)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(f"Delta from reference energy value is: {(result.eigenvalue.real-ref_value):.5f}")
# Plot energy values
pylab.rcParams['figure.figsize'] = (12, 4)
pylab.plot(counts,values)
pylab.xlabel('Eval count')
pylab.ylabel('Energy')
pylab.title('Convergence without noise')
pylab.show()
### Performance With Noise
import os
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.test.mock import FakeVigo
device_backend = FakeVigo()
backend = Aer.get_backend('aer_simulator')
counts1 = []
values1 = []
noise_model = None
device = QasmSimulator.from_backend(device_backend)
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device)
basis_gate = noise_model.basis_gates
print(noise_model)
print()
algorithm_globals.random_seed = seed
qi = QuantumInstance(backend=backend, seed_simulator=seed, seed_transpiler=seed,
coupling_map=coupling_map, noise_model=noise_model)
def store_intermediate_result1(eval_count, parameters, mean, std):
counts1.append(eval_count)
values1.append(mean)
var_form = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz')
spsa = SPSA(maxiter=iterations)
vqe = VQE(ansatz, optimizer=spsa, callback=store_intermediate_result1, quantum_instance=qi)
result1 = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
print(f"Delta from reference energy value is: {(result1.eigenvalue.real-ref_value):.5f}")
# Plot energy values
if counts1 or values1:
pylab.rcParams['figure.figsize'] = (12, 4)
pylab.plot(counts1,values1)
pylab.xlabel('Eval count')
pylab.ylabel('Energy')
pylab.title('Convergence with noise')
pylab.show()
### Performance With Noise And Measurement Error Mitigation
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
counts2 = []
values2 = []
if noise_model is not None:
algorithm_globals.random_seed = seed
qi = 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)
def store_intermediate_result2(eval_count, parameters, mean, std):
counts2.append(eval_count)
values2.append(mean)
ansatz = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz')
spsa = SPSA(maxiter=iterations)
vqe = VQE(ansatz, optimizer=spsa, callback=store_intermediate_result2, quantum_instance=qi)
result2 = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"VQE on Aer qasm simulator (with noise and measurement error mitigation): {result2.eigenvalue.real:.5f}")
print(f"Delta from reference energy value is: {(result2.eigenvalue.real - ref_value):.5f}")
# Plot energy values
if counts2 or values2:
pylab.rcParams['figure.figsize'] = (12, 4)
pylab.plot(counts2,values2)
pylab.xlabel('Eval count')
pylab.ylabel('Energy')
pylab.title('Convergence with noise and measurement error mitigation')
pylab.show()
# Summary
print('--------- Summary ---------')
print(f'Reference value: {ref_value:.5f}')
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
print(f"VQE on Aer qasm simulator (with noise and measurement error mitigation): {result2.eigenvalue.real:.5f}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/qclib/qclib
|
qclib
|
# Copyright 2021 qclib project.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
An Efficient Algorithm for Sparse Quantum State Preparation
https://ieeexplore.ieee.org/document/9586240
"""
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library import UGate
from qclib.gates.ldmcu import Ldmcu
from qclib.gates.initialize_sparse import InitializeSparse
class MergeInitialize(InitializeSparse):
"""
An Efficient Algorithm for Sparse Quantum State Preparation
https://ieeexplore.ieee.org/document/9586240
"""
def __init__(self, params, label=None):
"""
Classical algorithm that creates a quantum circuit C that loads
a sparse quantum state, applying a sequence of operations maping
the desired state |sigma> to |0>. And then inverting C to obtain
the mapping of |0> to the desired state |sigma>.
Args:
params: A dictionary with the non-zero amplitudes corresponding to each state in
format { '000': <value>, ... , '111': <value> }
Returns:
Creates a quantum gate that maps |0> to the desired state |params>
"""
self._name = "merge"
if label is None:
label = "MERGESP"
# Parameters need to be validated first by superclass
self._get_num_qubits(params)
super().__init__(self._name, self.num_qubits, params.items(), label=label)
def _define(self):
self.definition = self._define_initialize()
def _define_initialize(self):
state_dict = dict(self.params)
b_strings = list(state_dict.keys())
n_qubits = len(b_strings[0])
quantum_register = QuantumRegister(n_qubits)
quantum_circuit = QuantumCircuit(quantum_register)
while len(b_strings) > 1:
bitstr1, bitstr2, dif, dif_qubits = self._select_strings(state_dict)
bitstr1, bitstr2, state_dict, quantum_circuit = self._preprocess_states(
bitstr1, bitstr2, dif, dif_qubits, state_dict, quantum_circuit
)
state_dict, quantum_circuit = self._merge(
state_dict, quantum_circuit, bitstr1, bitstr2, dif_qubits, dif
)
b_strings = list(state_dict.keys())
b_string = b_strings.pop()
for (bit_idx, bit) in enumerate(b_string):
if bit == "1":
quantum_circuit.x(bit_idx)
return quantum_circuit.reverse_ops()
@staticmethod
def initialize(q_circuit, state, qubits=None):
if qubits is None:
q_circuit.append(MergeInitialize(state), q_circuit.qubits)
else:
q_circuit.append(MergeInitialize(state), qubits)
@staticmethod
def _maximizing_difference_bit_search(b_strings, dif_qubits):
"""
Splits the set of bit strings into two (t_0 and t_1), by setting
t_0 as the set of bit_strings with 0 in the bit_index position, and
t_1 as the set of bit_strings with 1 in the bit_index position.
Searching for the bit_index not in dif_qubits that maximizes the difference
between the size of the nonempty t_0 and t_1.
Args:
b_string: A list of bit strings eg.: ['000', '011', ...,'101']
dif_qubits: A list of previous qubits found to maximize the difference
Returns:
bit_index: The qubit index that maximizes abs(len(t_0)-len(t_1))
t_0: List of binary strings with 0 on the bit_index qubit
t_1: List of binary strings with 1 on the bit_index qubit
"""
t_0 = []
t_1 = []
bit_index = 0
set_difference = -1
bit_search_space = list(set(range(len(b_strings[0]))) - set(dif_qubits))
for bit in bit_search_space:
temp_t0 = [x for x in b_strings if x[bit] == "0"]
temp_t1 = [x for x in b_strings if x[bit] == "1"]
if temp_t0 and temp_t1:
temp_difference = np.abs(len(temp_t0) - len(temp_t1))
if temp_difference > set_difference:
t_0 = temp_t0
t_1 = temp_t1
bit_index = bit
set_difference = temp_difference
return bit_index, t_0, t_1
@staticmethod
def _build_bit_string_set(b_strings, dif_qubits, dif_values):
"""
Creates a new set of bit strings from b_strings, where the bits
in the indexes in dif_qubits match the values in dif_values.
Args:
b_strings: list of bit strings eg.: ['000', '011', ...,'101']
dif_qubits: list of integers with the bit indexes
dif_values: list of integers values containing the values each bit
with index in dif_qubits shoud have
Returns:
A new list of bit_strings, with matching values in dif_values
on indexes dif_qubits
"""
bit_string_set = []
for b_string in b_strings:
if [b_string[i] for i in dif_qubits] == dif_values:
bit_string_set.append(b_string)
return bit_string_set
def _bit_string_search(self, b_strings, dif_qubits, dif_values):
"""
Searches for the bit strings with unique qubit values in `dif_values`
on indexes `dif_qubits`.
Args:
b_strings: List of binary strings where the search is to be performed
e.g.: ['000', '010', '101', '111']
dif_qubits: List of indices on a binary string of size N e.g.: [1, 3, 5]
dif_values: List of values each qubit must have on indexes stored in dif_qubits [0, 1, 1]
Returns:
b_strings: One size list with the string found, to have values dif_values on indexes
dif_qubits
dif_qubits: Updated list with new indexes
dif_values: Updated list with new values
"""
temp_strings = b_strings
while len(temp_strings) > 1:
bit, t_0, t_1 = self._maximizing_difference_bit_search(
temp_strings, dif_qubits
)
dif_qubits.append(bit)
if len(t_0) < len(t_1):
dif_values.append("0")
temp_strings = t_0
else:
dif_values.append("1")
temp_strings = t_1
return temp_strings, dif_qubits, dif_values
def _select_strings(self, state_dict):
"""
Searches for the states described by the bit strings bitstr1 and bitstr2 to be merged
Args:
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
Returns:
bitstr1: First binary string
bitstr2: Second binary string
dif_qubit: Qubit index to be used as target for the merging operation
dif_qubits: List of qubit indexes where bitstr1 and bitstr2 must be equal, because the
correspondig qubits of those indexes are to be used as control for the
merging operation
"""
# Initialization
dif_qubits = []
dif_values = []
b_strings1 = b_strings2 = list(state_dict.keys())
# Searching for bitstr1
(b_strings1, dif_qubits, dif_values) = self._bit_string_search(
b_strings1, dif_qubits, dif_values
)
dif_qubit = dif_qubits.pop()
dif_values.pop()
bitstr1 = b_strings1[0]
# Searching for bitstr2
b_strings2.remove(bitstr1)
b_strings1 = self._build_bit_string_set(b_strings2, dif_qubits, dif_values)
(b_strings1, dif_qubits, dif_values) = self._bit_string_search(
b_strings1, dif_qubits, dif_values
)
bitstr2 = b_strings1[0]
return bitstr1, bitstr2, dif_qubit, dif_qubits
@staticmethod
def _apply_operation_to_bit_string(b_string, operation, qubit_indexes):
"""
Applies changes on binary strings according to the operation
Args:
b_string: Binary string '00110'
operation: Operation to be applied to the string
qubit_indexes: Indexes of the qubits on the binary strings where the operations are to
be applied
Returns:
Updated binary string
"""
assert operation in ["x", "cx"]
if operation == "x":
compute = _compute_op_x
else:
compute = _compute_op_cx
return compute(b_string, qubit_indexes)
@staticmethod
def _update_state_dict_according_to_operation(
state_dict, operation, qubit_indexes, merge_strings=None
):
"""
Updates the keys of the state_dict according to the operation being applied to the circuit
Args:
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
operation: Operation to be applied to the states, it must be ['x', 'cx', 'merge']
qubit_indexes: Indexes of the qubits on the binary strings where the operations are to
be applied
merge_strings: Binary strings associated ot the states on the quantum processor
to be merge e.g.:['01001', '10110']
Returns:
A state_dict with the updated states
"""
assert operation in ["x", "cx", "merge"]
state_list = list(state_dict.items())
new_state_dict = {}
if operation == "merge":
assert merge_strings is not None
# Computes the norm of bitstr1 and bitstr2
new_state_dict = state_dict.copy()
norm = np.linalg.norm(
[new_state_dict[merge_strings[0]], new_state_dict[merge_strings[1]]]
)
new_state_dict.pop(merge_strings[1], None)
new_state_dict[merge_strings[0]] = norm
else:
for (bit_string, value) in state_list:
temp_bstring = MergeInitialize._apply_operation_to_bit_string(
bit_string, operation, qubit_indexes
)
new_state_dict[temp_bstring] = value
return new_state_dict
@staticmethod
def _equalize_bit_string_states(
bitstr1, bitstr2, dif, state_dict, quantum_circuit
):
"""
Applies operations to the states represented by bit strings bitstr1 and bitstr2 equalizing
them at every qubit except the one in the dif index. And alters the bit strings and
state_dict accordingly.
Args:
bitstr1: First bit string
bitstr2: Second bit string
dif: index where both bitstr1 and bitstr2 must be different
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
quantum_circuit: Qiskit's quantum circuit's object with the gates applied to the circuit
Returns:
Updated bitstr1, bitstr2, state_dict and quantum_circuit
"""
b_index_list = list(range(len(bitstr1)))
b_index_list.remove(dif)
for b_index in b_index_list:
if bitstr1[b_index] != bitstr2[b_index]:
quantum_circuit.cx(dif, b_index)
bitstr1 = MergeInitialize._apply_operation_to_bit_string(
bitstr1, "cx", [dif, b_index]
)
bitstr2 = MergeInitialize._apply_operation_to_bit_string(
bitstr2, "cx", [dif, b_index]
)
state_dict = MergeInitialize._update_state_dict_according_to_operation(
state_dict, "cx", [dif, b_index]
)
return bitstr1, bitstr2, state_dict, quantum_circuit
@staticmethod
def _apply_not_gates_to_qubit_index_list(
bitstr1, bitstr2, dif_qubits, state_dict, quantum_circuit
):
"""
Applies quantum not gate at the qubit at a given index, where the state represented by the
bit string bitstr2 is different than '1' at index in diff_qubits.
Args:
bitstr1: First bit string
bitstr2: Second bit string
dif_qubits: indexes where both bitstr1 and bitstr2 are equal
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
quantum_circuit: Qiskit's quantum circuit's object with the gates applied to the circuit
Returns:
Updated bitstr1, bitstr2, state_dict and quantum_circuit
"""
for b_index in dif_qubits:
if bitstr2[b_index] != "1":
quantum_circuit.x(b_index)
bitstr1 = MergeInitialize._apply_operation_to_bit_string(bitstr1, "x", b_index)
bitstr2 = MergeInitialize._apply_operation_to_bit_string(bitstr2, "x", b_index)
state_dict = MergeInitialize._update_state_dict_according_to_operation(
state_dict, "x", b_index
)
return bitstr1, bitstr2, state_dict, quantum_circuit
def _preprocess_states(
self, bitstr1, bitstr2, dif, dif_qubits, state_dict, quantum_circuit
):
"""
Apply the operations on the basis states to prepare for merging bitstr1 and bitstr2.
Args:
state_dict: A dictionary with the non-zero amplitudes associated to their corresponding
binary strings as keys e.g.: {'001': <value>, '101': <value>}
bitstr1: First binary string to be merged
bitstr2: Second binary string to be merged
dif_qubits: List of qubit indexes on the binary strings
dif: Target qubit index where the merge operation is to be applied
quantum_circuit: Qiskit's QuantumCircuit object where the operations are to be called
Returns:
state_dict: Updated state dict
bitstr1: First updated binary string to be merged
bitstr2: Second updated binary string to be merged
quantum_circuit: Qiskit's quantum circuit's object with the gates applied to the circuit
"""
if bitstr1[dif] != "1":
quantum_circuit.x(dif)
bitstr1 = MergeInitialize._apply_operation_to_bit_string(bitstr1, "x", dif)
bitstr2 = MergeInitialize._apply_operation_to_bit_string(bitstr2, "x", dif)
state_dict = self._update_state_dict_according_to_operation(
state_dict, "x", dif
)
(
bitstr1,
bitstr2,
state_dict,
quantum_circuit,
) = self._equalize_bit_string_states(
bitstr1, bitstr2, dif, state_dict, quantum_circuit
)
(
bitstr1,
bitstr2,
state_dict,
quantum_circuit,
) = self._apply_not_gates_to_qubit_index_list(
bitstr1, bitstr2, dif_qubits, state_dict, quantum_circuit
)
return bitstr1, bitstr2, state_dict, quantum_circuit
@staticmethod
def _compute_angles(amplitude_1, amplitude_2):
"""
Computes the angles for the adjoint of the merge matrix M
that is going to map the dif qubit to zero e.g.:
M(a|0> + b|1>) -> |1>
Args:
amplitude_1: A complex/real value, associated with the string with
1 on the dif qubit
amplitude_2: A complex/real value, associated with the string with
0 on the dif qubit
Returns:
The angles theta, lambda and phi for the U operator
"""
norm = np.linalg.norm([amplitude_1, amplitude_2])
phi = 0
lamb = 0
# there is no minus on the theta because the intetion is to compute the inverse
if isinstance(amplitude_1, complex) or isinstance(amplitude_2, complex):
amplitude_1 = (
complex(amplitude_1)
if not isinstance(amplitude_1, complex)
else amplitude_1
)
amplitude_2 = (
complex(amplitude_2)
if not isinstance(amplitude_2, complex)
else amplitude_2
)
theta = -2 * np.arcsin(np.abs(amplitude_2 / norm))
lamb = np.log(amplitude_2 / norm).imag
phi = np.log(amplitude_1 / norm).imag - lamb
else:
theta = -2 * np.arcsin(amplitude_2 / norm)
return theta, phi, lamb
def _merge(self, state_dict, quantum_circuit, bitstr1, bitstr2, dif_qubits, dif):
theta, phi, lamb = self._compute_angles(
state_dict[bitstr1], state_dict[bitstr2]
)
# Applying merge operation
merge_gate = UGate(theta, phi, lamb, label="U")
if not dif_qubits:
quantum_circuit.append(merge_gate, dif_qubits + [dif], [])
else:
gate_definition = UGate(theta, phi, lamb, label="U").to_matrix()
Ldmcu.ldmcu(quantum_circuit, gate_definition, dif_qubits, dif)
state_dict = self._update_state_dict_according_to_operation(
state_dict, "merge", None, merge_strings=[bitstr1, bitstr2]
)
return state_dict, quantum_circuit
def _compute_op_cx(xlist, idx):
return (
f'{xlist[: idx[1]]}{(not int(xlist[idx[1]])) * 1}{xlist[idx[1] + 1:]}'
if xlist[idx[0]] == "1"
else xlist
)
def _compute_op_x(xlist, idx):
return (
xlist[:idx] + "1" + xlist[idx + 1:]
if xlist[idx] == "0"
else xlist[0:idx] + "0" + xlist[idx + 1:]
)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""Diagonal gate tests."""
import unittest
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, BasicAer, execute
from qiskit import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.compiler import transpile
from qiskit.extensions.quantum_initializer import DiagonalGate
from qiskit.quantum_info.operators.predicates import matrix_equal
class TestDiagonalGate(QiskitTestCase):
"""
Diagonal gate tests.
"""
def test_diag_gate(self):
"""Test diagonal gates."""
for phases in [
[0, 0],
[0, 0.8],
[0, 0, 1, 1],
[0, 1, 0.5, 1],
(2 * np.pi * np.random.rand(2**3)).tolist(),
(2 * np.pi * np.random.rand(2**4)).tolist(),
(2 * np.pi * np.random.rand(2**5)).tolist(),
]:
with self.subTest(phases=phases):
diag = [np.exp(1j * ph) for ph in phases]
num_qubits = int(np.log2(len(diag)))
q = QuantumRegister(num_qubits)
qc = QuantumCircuit(q)
qc.diagonal(diag, q[0:num_qubits])
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"], optimization_level=0)
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
unitary_desired = _get_diag_gate_matrix(diag)
self.assertTrue(matrix_equal(unitary, unitary_desired, ignore_phase=False))
def test_mod1_entries(self):
"""Test that diagonal raises if entries do not have modules of 1."""
from qiskit.quantum_info.operators.predicates import ATOL_DEFAULT, RTOL_DEFAULT
with self.assertRaises(QiskitError):
DiagonalGate([1, 1 - 2 * ATOL_DEFAULT - RTOL_DEFAULT])
def _get_diag_gate_matrix(diag):
return np.diagflat(diag)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from sklearn.datasets import load_iris
iris_data = load_iris()
print(iris_data.DESCR)
features = iris_data.data
labels = iris_data.target
from sklearn.preprocessing import MinMaxScaler
features = MinMaxScaler().fit_transform(features)
import pandas as pd
import seaborn as sns
df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names)
df["class"] = pd.Series(iris_data.target)
sns.pairplot(df, hue="class", palette="tab10")
from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=0.8, random_state=algorithm_globals.random_seed
)
from sklearn.svm import SVC
svc = SVC()
_ = svc.fit(train_features, train_labels) # suppress printing the return value
train_score_c4 = svc.score(train_features, train_labels)
test_score_c4 = svc.score(test_features, test_labels)
print(f"Classical SVC on the training dataset: {train_score_c4:.2f}")
print(f"Classical SVC on the test dataset: {test_score_c4:.2f}")
from qiskit.circuit.library import ZZFeatureMap
num_features = features.shape[1]
feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1)
feature_map.decompose().draw(output="mpl", fold=20)
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=num_features, reps=3)
ansatz.decompose().draw(output="mpl", fold=20)
from qiskit.algorithms.optimizers import COBYLA
optimizer = COBYLA(maxiter=100)
from qiskit.primitives import Sampler
sampler = Sampler()
from matplotlib import pyplot as plt
from IPython.display import clear_output
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
import time
from qiskit_machine_learning.algorithms.classifiers import VQC
vqc = VQC(
sampler=sampler,
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q4 = vqc.score(train_features, train_labels)
test_score_q4 = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}")
print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}")
from sklearn.decomposition import PCA
features = PCA(n_components=2).fit_transform(features)
plt.rcParams["figure.figsize"] = (6, 6)
sns.scatterplot(x=features[:, 0], y=features[:, 1], hue=labels, palette="tab10")
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=0.8, random_state=algorithm_globals.random_seed
)
svc.fit(train_features, train_labels)
train_score_c2 = svc.score(train_features, train_labels)
test_score_c2 = svc.score(test_features, test_labels)
print(f"Classical SVC on the training dataset: {train_score_c2:.2f}")
print(f"Classical SVC on the test dataset: {test_score_c2:.2f}")
num_features = features.shape[1]
feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1)
ansatz = RealAmplitudes(num_qubits=num_features, reps=3)
optimizer = COBYLA(maxiter=40)
vqc = VQC(
sampler=sampler,
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
# make the objective function plot look nicer.
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
vqc.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q2_ra = vqc.score(train_features, train_labels)
test_score_q2_ra = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset using RealAmplitudes: {train_score_q2_ra:.2f}")
print(f"Quantum VQC on the test dataset using RealAmplitudes: {test_score_q2_ra:.2f}")
from qiskit.circuit.library import EfficientSU2
ansatz = EfficientSU2(num_qubits=num_features, reps=3)
optimizer = COBYLA(maxiter=40)
vqc = VQC(
sampler=sampler,
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q2_eff = vqc.score(train_features, train_labels)
test_score_q2_eff = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset using EfficientSU2: {train_score_q2_eff:.2f}")
print(f"Quantum VQC on the test dataset using EfficientSU2: {test_score_q2_eff:.2f}")
print(f"Model | Test Score | Train Score")
print(f"SVC, 4 features | {train_score_c4:10.2f} | {test_score_c4:10.2f}")
print(f"VQC, 4 features, RealAmplitudes | {train_score_q4:10.2f} | {test_score_q4:10.2f}")
print(f"----------------------------------------------------------")
print(f"SVC, 2 features | {train_score_c2:10.2f} | {test_score_c2:10.2f}")
print(f"VQC, 2 features, RealAmplitudes | {train_score_q2_ra:10.2f} | {test_score_q2_ra:10.2f}")
print(f"VQC, 2 features, EfficientSU2 | {train_score_q2_eff:10.2f} | {test_score_q2_eff:10.2f}")
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 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/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import *
import numpy as np
from numpy import linalg as la
from qiskit.tools.monitor import job_monitor
import qiskit.tools.jupyter
qc = QuantumCircuit(1)
#### your code goes here
# z measurement of qubit 0
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0)
# x measurement of qubit 0
measure_x = QuantumCircuit(1,1)
# your code goes here
# y measurement of qubit 0
measure_y = QuantumCircuit(1,1)
# your code goes here
shots = 2**14 # number of samples used for statistics
sim = Aer.get_backend('qasm_simulator')
bloch_vector_measure = []
for measure_circuit in [measure_x, measure_y, measure_z]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
counts = execute(qc+measure_circuit, sim, shots=shots).result().get_counts()
# calculate the probabilities for each bit value
probs = {}
for output in ['0','1']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
bloch_vector_measure.append( probs['0'] - probs['1'] )
# normalizing the bloch sphere vector
bloch_vector = bloch_vector_measure/la.norm(bloch_vector_measure)
print('The bloch sphere coordinates are [{0:4.3f}, {1:4.3f}, {2:4.3f}]'
.format(*bloch_vector))
from kaleidoscope.interactive import bloch_sphere
bloch_sphere(bloch_vector, vectors_annotation=True)
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector( bloch_vector )
# circuit for the state Tri1
Tri1 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri2
Tri2 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri3
Tri3 = QuantumCircuit(2)
# your code goes here
# circuit for the state Sing
Sing = QuantumCircuit(2)
# your code goes here
# <ZZ>
measure_ZZ = QuantumCircuit(2)
measure_ZZ.measure_all()
# <XX>
measure_XX = QuantumCircuit(2)
# your code goes here
# <YY>
measure_YY = QuantumCircuit(2)
# your code goes here
shots = 2**14 # number of samples used for statistics
A = 1.47e-6 #unit of A is eV
E_sim = []
for state_init in [Tri1,Tri2,Tri3,Sing]:
Energy_meas = []
for measure_circuit in [measure_XX, measure_YY, measure_ZZ]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
qc = state_init+measure_circuit
counts = execute(qc, sim, shots=shots).result().get_counts()
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E_sim.append(A * np.sum(np.array(Energy_meas)))
# Run this cell to print out your results
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_sim[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_sim[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_sim[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_sim[3]))
# reduced plank constant in (eV) and the speed of light(cgs units)
hbar, c = 4.1357e-15, 3e10
# energy difference between the triplets and singlet
E_del = abs(E_sim[0] - E_sim[3])
# frequency associated with the energy difference
f = E_del/hbar
# convert frequency to wavelength in (cm)
wavelength = c/f
print('The wavelength of the radiation from the transition\
in the hyperfine structure is : {:.1f} cm'.format(wavelength))
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_athens')
# run this cell to get the backend information through the widget
backend
# assign your choice for the initial layout to the list variable `initial_layout`.
initial_layout =
qc_all = [state_init+measure_circuit for state_init in [Tri1,Tri2,Tri3,Sing]
for measure_circuit in [measure_XX, measure_YY, measure_ZZ] ]
shots = 8192
job = execute(qc_all, backend, initial_layout=initial_layout, optimization_level=3, shots=shots)
print(job.job_id())
job_monitor(job)
# getting the results of your job
results = job.result()
## To access the results of the completed job
#results = backend.retrieve_job('job_id').result()
def Energy(results, shots):
"""Compute the energy levels of the hydrogen ground state.
Parameters:
results (obj): results, results from executing the circuits for measuring a hamiltonian.
shots (int): shots, number of shots used for the circuit execution.
Returns:
Energy (list): energy values of the four different hydrogen ground states
"""
E = []
A = 1.47e-6
for ind_state in range(4):
Energy_meas = []
for ind_comp in range(3):
counts = results.get_counts(ind_state*3+ind_comp)
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E.append(A * np.sum(np.array(Energy_meas)))
return E
E = Energy(results, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E[3]))
from qiskit.ignis.mitigation.measurement import *
# your code to create the circuits, meas_calibs, goes here
meas_calibs, state_labels =
# execute meas_calibs on your choice of the backend
job = execute(meas_calibs, backend, shots = shots)
print(job.job_id())
job_monitor(job)
cal_results = job.result()
## To access the results of the completed job
#cal_results = backend.retrieve_job('job_id').result()
# your code to obtain the measurement filter object, 'meas_filter', goes here
results_new = meas_filter.apply(results)
E_new = Energy(results_new, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_new[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_new[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_new[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_new[3]))
# results for the energy estimation from the simulation,
# execution on a quantum system without error mitigation and
# with error mitigation in numpy array format
Energy_exact, Energy_exp_orig, Energy_exp_new = np.array(E_sim), np.array(E), np.array(E_new)
# Calculate the relative errors of the energy values without error mitigation
# and assign to the numpy array variable `Err_rel_orig` of size 4
Err_rel_orig =
# Calculate the relative errors of the energy values with error mitigation
# and assign to the numpy array variable `Err_rel_new` of size 4
Err_rel_new =
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
without measurement error mitigation : {}'.format(Err_rel_orig))
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
with measurement error mitigation : {}'.format(Err_rel_new))
|
https://github.com/hkhetawat/QArithmetic
|
hkhetawat
|
# Import the Qiskit SDK
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, Aer
from QArithmetic import sub_swap
# Input N
N = 4
a = QuantumRegister(N+1)
b = QuantumRegister(N+1)
ca = ClassicalRegister(N+1)
cb = ClassicalRegister(N+1)
qc = QuantumCircuit(a, b, ca, cb)
# Input Superposition
# a = 01110
qc.x(a[1])
qc.x(a[2])
qc.x(a[3])
# b = 01011
qc.x(b[0])
qc.x(b[1])
qc.x(b[3])
sub_swap(qc, a, b, N+1)
qc.measure(a, ca)
qc.measure(b, cb)
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
print(result_sim.get_counts(qc))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver()
problem = driver.run()
fermionic_op = problem.hamiltonian.second_q_op()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
qubit_jw_op = mapper.map(fermionic_op)
print(qubit_jw_op)
from qiskit_nature.second_q.mappers import ParityMapper
mapper = ParityMapper()
qubit_p_op = mapper.map(fermionic_op)
print(qubit_p_op)
mapper = ParityMapper(num_particles=problem.num_particles)
qubit_op = mapper.map(fermionic_op)
print(qubit_op)
tapered_mapper = problem.get_tapered_mapper(mapper)
print(type(tapered_mapper))
qubit_op = tapered_mapper.map(fermionic_op)
print(qubit_op)
from qiskit_nature.second_q.circuit.library import HartreeFock
hf_state = HartreeFock(2, (1, 1), JordanWignerMapper())
hf_state.draw()
from qiskit_nature.second_q.mappers import InterleavedQubitMapper
interleaved_mapper = InterleavedQubitMapper(JordanWignerMapper())
hf_state = HartreeFock(2, (1, 1), interleaved_mapper)
hf_state.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
import pydoc
import re
import pytket.passes as tkps
def get_arguments_from_doc(tket_pass):
arguments = []
_doc = pydoc.getdoc(tket_pass)
if 'Overloaded function.' in _doc:
#Return the first signature
#TODO: We should return all possible signatures. This would requires changes in ToQiskitPass also.
matches = re.findall("[1-9]\. (" + tket_pass.__name__ + '[^\n]+)', _doc)
synopsis_line = matches[0]
else:
synopsis_line = pydoc.splitdoc(_doc)[0]
# To avoid issue caused by callable parentheses:
synopsis_line = re.sub('Callable\[\[[^\[]+\][^\[]+\]', 'Callable', synopsis_line)
match = re.search("\(([^(]+)\)", synopsis_line)
if match is not None:
splitted_args = match.group(1).split(', ')
for arg_str in splitted_args:
if arg_str == '**kwargs':
continue
else:
argument = arg_str.split(': ')
eq_index = argument[1].find('=')
if eq_index > 0:
(_type, _default) = argument[1].split(' = ')
arguments.append((argument[0], _type, _default))
else:
arguments.append(tuple(argument))
return arguments
# This is **temp**. Conversion should be done in a better way
# https://github.com/CQCL/pytket-qiskit/blob/develop/pytket/extensions/qiskit/qiskit_convert.py
from pytket.extensions.qiskit import qiskit_to_tk, tk_to_qiskit
from qiskit.converters import dag_to_circuit, circuit_to_dag
from pytket.circuit import Circuit
from qiskit.dagcircuit import DAGCircuit
def qiskit_dag_to_tk(dag: DAGCircuit):
# Replace any gate that is not known to pyket by its definition
from pytket.extensions.qiskit.qiskit_convert import _known_qiskit_gate
for node in dag.op_nodes():
if not type(node.op) in _known_qiskit_gate:
dag.substitute_node_with_dag(node, circuit_to_dag(node.op.definition))
return qiskit_to_tk(dag_to_circuit(dag))
def tk_to_qiskit_dag(tkcirc: Circuit):
return circuit_to_dag(tk_to_qiskit(tkcirc))
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import pandas as pd
with open('Results/sol9_2.log', 'r') as file:
data = file.read()
rows_list = []
for dline in data.split('\n\n'):
if dline.startswith('n = '):
lines=dline.split('\n')
for line in lines:
if line.startswith('n = '):
words=line.split(', ')
for word in words:
if word.startswith('n = '):
n=int(word.strip('n = '))
if word.startswith('m = '):
k=int(word.strip('m = '))
if word.startswith('instance = '):
instance=word.strip('instance = ')
if line.startswith('Classical cost from best known solution: '):
classical_cost=f"{float(line.strip('Classical cost from best known solution: ')):.5f}"
if line.startswith('RAS: '):
words=line.split(' \t ')
for word in words:
if word.startswith('quantum cost = '):
ras_quantum_cost=f"{float(word.strip('quantum cost = ')):.5f}" if word.strip('quantum cost = ') != 'None' else None
if word.startswith('approximation ratio = '):
ras_approximation_ratio=f"{float(word.strip('approximation ratio = ')):.5f}" if word.strip('approximation ratio = ') != 'None' else None
if word.startswith('number of variables = '):
ras_no_of_variables=int(word.strip('number of variables = '))
if word.startswith('runtime = '):
ras_runtime=f"{float(word.strip('runtime = ')):.5f}"
if line.startswith('FQS: '):
words=line.split(' \t ')
for word in words:
if word.startswith('quantum cost = '):
fqs_quantum_cost=f"{float(word.strip('quantum cost = ')):.5f}" if word.strip('quantum cost = ') != 'None' else None
if word.startswith('approximation ratio = '):
fqs_approximation_ratio=f"{float(word.strip('approximation ratio = ')):.5f}" if word.strip('approximation ratio = ') != 'None' else None
if word.startswith('number of variables = '):
fqs_no_of_variables=int(word.strip('number of variables = '))
if word.startswith('runtime = '):
fqs_runtime=f"{float(word.strip('runtime = ')):.5f}"
if line.startswith('GPS: '):
words=line.split(' \t ')
for word in words:
if word.startswith('quantum cost = '):
gps_quantum_cost=f"{float(word.strip('quantum cost = ')):.5f}" if word.strip('quantum cost = ') != 'None' else None
if word.startswith('approximation ratio = '):
gps_approximation_ratio=f"{float(word.strip('approximation ratio = ')):.5f}" if word.strip('approximation ratio = ') != 'None' else None
if word.startswith('number of variables = '):
gps_no_of_variables=int(word.strip('number of variables = '))
if word.startswith('runtime = '):
gps_runtime=f"{float(word.strip('runtime = ')):.5f}"
rows_list.append({'n': n, 'k': k, 'instance': instance, 'Classical Cost': classical_cost, 'RAS: Quantum Cost': ras_quantum_cost, 'RAS: Approximation Ratio': ras_approximation_ratio, 'RAS: No. of Variables': ras_no_of_variables, 'RAS: Runtime': ras_runtime, 'FQS: Quantum Cost': fqs_quantum_cost, 'FQS: Approximation Ratio': fqs_approximation_ratio, 'FQS: No. of Variables': fqs_no_of_variables, 'FQS: Runtime': fqs_runtime, 'GPS: Quantum Cost': gps_quantum_cost, 'GPS: Approximation Ratio': gps_approximation_ratio, 'GPS: No. of Variables': gps_no_of_variables, 'GPS: Runtime': gps_runtime})
df = pd.DataFrame(rows_list)
df.sort_values(by=['n', 'k', 'instance'], inplace=True)
df.head()
df.to_csv('Results/sol9_2.csv', index=False)
|
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":
### replaced z gate ###
qc.x(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit,Aer,transpile
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = Aer.get_backend("aer_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
plot_histogram(counts)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Isometry tests."""
import unittest
import numpy as np
from ddt import ddt, data
from qiskit.quantum_info.random import random_unitary
from qiskit import BasicAer
from qiskit import QuantumCircuit
from qiskit import QuantumRegister
from qiskit import execute
from qiskit.test import QiskitTestCase
from qiskit.compiler import transpile
from qiskit.quantum_info import Operator
from qiskit.extensions.quantum_initializer.isometry import Isometry
@ddt
class TestIsometry(QiskitTestCase):
"""Qiskit isometry tests."""
@data(
np.eye(2, 2),
random_unitary(2, seed=868540).data,
np.eye(4, 4),
random_unitary(4, seed=16785).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=660477).data,
np.eye(4, 4)[:, np.random.RandomState(seed=719010).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=544326).permutation(8)],
random_unitary(8, seed=247924).data[:, 0:4],
random_unitary(8, seed=765720).data,
random_unitary(16, seed=278663).data,
random_unitary(16, seed=406498).data[:, 0:8],
)
def test_isometry(self, iso):
"""Tests for the decomposition of isometries from m to n qubits"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
num_q_input = int(np.log2(iso.shape[1]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
qc.isometry(iso, q[:num_q_input], q[num_q_input:])
# Verify the circuit can be decomposed
self.assertIsInstance(qc.decompose(), QuantumCircuit)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
iso_from_circuit = unitary[::, 0 : 2**num_q_input]
iso_desired = iso
self.assertTrue(np.allclose(iso_from_circuit, iso_desired))
@data(
np.eye(2, 2),
random_unitary(2, seed=99506).data,
np.eye(4, 4),
random_unitary(4, seed=673459).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=124090).data,
np.eye(4, 4)[:, np.random.RandomState(seed=889848).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=94795).permutation(8)],
random_unitary(8, seed=986292).data[:, 0:4],
random_unitary(8, seed=632121).data,
random_unitary(16, seed=623107).data,
random_unitary(16, seed=889326).data[:, 0:8],
)
def test_isometry_tolerance(self, iso):
"""Tests for the decomposition of isometries from m to n qubits with a custom tolerance"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
num_q_input = int(np.log2(iso.shape[1]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
# Compute isometry with custom tolerance
qc.isometry(iso, q[:num_q_input], q[num_q_input:], epsilon=1e-3)
# Verify the circuit can be decomposed
self.assertIsInstance(qc.decompose(), QuantumCircuit)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
iso_from_circuit = unitary[::, 0 : 2**num_q_input]
self.assertTrue(np.allclose(iso_from_circuit, iso))
@data(
np.eye(2, 2),
random_unitary(2, seed=272225).data,
np.eye(4, 4),
random_unitary(4, seed=592640).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=714210).data,
np.eye(4, 4)[:, np.random.RandomState(seed=719934).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=284469).permutation(8)],
random_unitary(8, seed=656745).data[:, 0:4],
random_unitary(8, seed=583813).data,
random_unitary(16, seed=101363).data,
random_unitary(16, seed=583429).data[:, 0:8],
)
def test_isometry_inverse(self, iso):
"""Tests for the inverse of isometries from m to n qubits"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
qc.append(Isometry(iso, 0, 0), q)
qc.append(Isometry(iso, 0, 0).inverse(), q)
result = Operator(qc)
np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0]))
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
qc.draw('mpl')
|
https://github.com/biswaroopmukherjee/Quantum-Waddle
|
biswaroopmukherjee
|
import numpy as np
import time
import networkx as nx
import matplotlib.pyplot as plt
import random
from qiskit import (QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer)
%matplotlib qt
import os
print(os.environ.get('QT_API'))
n=3
steps = 8
def counts_to_prob_2d(counts):
states = list(counts.keys())
state_counts = list(counts.values())
nshots = sum(state_counts)
n = int(len(states[0])/2)
def sep_xy(states):
# Separate x and y coordinates in state vector
states_x = [s[:n] for s in states]
states_y = [s[n:] for s in states]
states_x = np.array([int(s[::-1],2) for s in states_x])
states_y = np.array([int(s[::-1],2) for s in states_y])
return states_x, states_y
x,y = sep_xy(states)
# Create array of probability values
probabilities = np.zeros((2**n,2**n))
probabilities[x,y] = state_counts
probabilities /= nshots
return probabilities
def increment_gate(circuit, qpos, qcoin):
n = len(qpos)
for i in range(n):
circuit.mct(qcoin[:]+qpos[i+1:], qpos[i], None, mode='noancilla')
def decrement_gate(circuit, qpos, qcoin):
n = len(qpos)
for i in range(n):
if i+1 < n: circuit.x(qpos[i+1:])
circuit.mct(qcoin[:]+qpos[i+1:], qpos[i], None, mode='noancilla')
if i+1 < n: circuit.x(qpos[i+1:])
def step(circuit, qpos, qcoin):
circuit.h(qcoin)
circuit.barrier()
# y operations
increment_gate(circuit, qpos[len(qpos)//2:], qcoin)
circuit.x(qcoin[0])
decrement_gate(circuit, qpos[len(qpos)//2:], qcoin)
# x operations
circuit.x(qcoin)
increment_gate(circuit, qpos[:len(qpos)//2], qcoin)
circuit.x(qcoin[0])
decrement_gate(circuit, qpos[:len(qpos)//2:], qcoin)
circuit.barrier()
def initialize_2D(circuit, n, pos):
# convert position to binary
x = "{:b}".format(pos[0])
y = "{:b}".format(pos[1])
for i in range(len(x)):
if x[i]=='1': circuit.x((n-i)-1)
for j in range(len(y)):
if y[j]=='1': circuit.x((2*n-j)-1)
return circuit
def run(steps):
simulator = Aer.get_backend('qasm_simulator')
qpos = QuantumRegister(2*n,'qc')
qcoin = QuantumRegister(2,'qanc')
cpos = ClassicalRegister(2*n,'cr')
circuit = QuantumCircuit(qpos, qcoin, cpos)
circuit = initialize_2D(circuit, n, (3,3))
for i in range(steps):
step(circuit, qpos, qcoin)
# # Map the quantum measurement to the classical bits
circuit.measure(qpos,cpos)
# # Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# # Grab results from the job
result = job.result()
# # Returns counts
counts = result.get_counts(circuit)
return counts
seed = 12
random.seed(seed)
np.random.seed(seed)
def plotSquareGraph(propMat):
colorarray = []
# generate array of colors
numProp = len(propMat)
for idx in range(numProp):
for jdx in range(numProp):
colorarray.append([1-propMat[idx][jdx],1-propMat[idx][jdx],1])
G = nx.grid_2d_graph(numProp, numProp) # 5x5 grid
# print the adjacency list
for line in nx.generate_adjlist(G):
pass
# write edgelist to grid.edgelist
nx.write_edgelist(G, path="grid.edgelist", delimiter=":")
nx.draw(G,node_color = colorarray,cmap=plt.cm.Blues)
plt.plot()
for i in range(steps+1):
counts = run(i)
prop = counts_to_prob_2d(counts)
plt.close()
plt.imshow(prop)
# plotSquareGraph(prop)
plt.pause(1/steps)
|
https://github.com/noamsgl/IBMAscolaChallenge
|
noamsgl
|
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from ipywidgets import interact, interactive, fixed, interact_manual, FloatSlider
import ipywidgets as widgets
sns.set(style='whitegrid', palette='deep', font_scale=1.1, rc={'figure.figsize': [8, 5]})
filepath = "../datasets/universal_error/AllErrors/U3_5.csv"
df = pd.read_csv(filepath)
# reorder columns
df = df[['theta', 'phi', 'lam', 'E', 'depol_prob', 't1', 't2', 'population', 'p0_0', 'p0_1', 'p1_0', 'p1_1']]
df.info()
df.head()
sns.distplot(df['E'], norm_hist=False, kde=False, bins=20, hist_kws={'alpha': 1}).set(xlabel="'Expected Value", ylabel='Count')
df.hist(bins=50, figsize=(20,15), layout=(3,4));
sns.scatterplot(x=df['theta'], y=df['E']);
sns.scatterplot(x=df['phi'], y=df['E']);
sns.scatterplot(x=df['lam'], y=df['E']);
sns.scatterplot(x=df['theta'], y=df['phi']);
sns.pairplot(data=df.sample(1000));
sns.pairplot(data=df.sample(10000));
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
"""Imports for the notebook."""
_req = """This notebook is written for
qiskit-aqua==0.6.0
Your code may not execute properly.
"""
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import warnings
import qiskit
if "0.6" not in qiskit.__qiskit_version__.get("qiskit-aqua"):
warnings.warn(_req)
"""Optional: Turn off warnings for the notebook."""
warnings.filterwarnings("ignore")
"""Specific imports for QAOA with MaxCut."""
# Import the QAOA object
from qiskit.aqua.algorithms.adaptive import QAOA
# Import tools for the MaxCut problem
from qiskit.aqua.translators.ising.max_cut import (
get_max_cut_qubitops, max_cut_value, random_graph
)
from qiskit.aqua.operators.weighted_pauli_operator import (
Pauli, WeightedPauliOperator
)
# Import optimizers in Qiskit for finding the best parameters in the QAOA circuit
from qiskit.aqua.components.optimizers import ADAM, AQGD, COBYLA, POWELL
"""Helper function for drawing weighted graphs.
You don't need to know how this function works. You will see how to use it below.
"""
def draw_weighted(graph: nx.Graph,
pos_color: str = "blue",
neg_color: str = "red",
scale: float = 2.0,
**kwargs) -> None:
"""Shows a visual of a graph with edges scaled by weight and colored by sign.
Args:
graph: The weighted graph to visualize.
pos_color: Color for edges with a positive weight.
neg_color: Color for edges with a negative weight.
scale: Floating point value to scale edge weights by
in the visualization.
Keyword Args:
cut (List[Int]): A list of 0, 1 values specifying which
nodes are in which class. The number of
values must be equal to the number of
nodes in the graph.
"""
pos = nx.spring_layout(graph)
if "cut" in kwargs.keys():
keys = kwargs["cut"]
if len(keys) != len(graph.nodes):
raise ValueError(
f"ecolor_key has length {len(keys)} but graph has {len(graph.nodes)} nodes."
)
nx.draw_networkx_nodes(graph, pos, node_size=700, node_color=keys, cmap=plt.cm.Greens)
else:
nx.draw_networkx_nodes(graph, pos, node_size=700)
col = lambda sgn: pos_color if sgn > 0 else neg_color
for edge in graph.edges:
weight = graph.get_edge_data(*edge)["weight"]
sgn = np.sign(weight)
size = abs(weight)
nx.draw_networkx_edges(graph,
pos,
edgelist=[edge],
width=scale * size,
edge_color=col(sgn),
alpha=0.5)
nx.draw_networkx_labels(graph, pos, font_size=20)
plt.axis("off")
plt.show()
"""Define the graph for MaxCut via an adjacency matrix."""
nodes = 6 # Vary the number of nodes here
matrix = random_graph(n=nodes, edge_prob=0.5, seed=2)
print("The adjacency matrix is:")
print(matrix)
"""Convert the adjacency matrix to a (weighted) graph and visualize it."""
graph = nx.from_numpy_array(matrix, parallel_edges=False)
draw_weighted(graph)
"""TODO: Put a list of 1s and 0s to assign vertex sets and see
what the value of your cut is.
"""
cut = np.array() ### <-- Your code here!
print("The value of this cut is:", max_cut_value(cut, matrix))
"""Visualize the cut by coloring nodes in distinct vertex sets different colors."""
draw_weighted(graph, cut=[0, 0, 0, 1, 1, 1])
"""Pauli operators from matrix."""
op, shift = get_max_cut_qubitops(matrix)
"""Inspect the Pauli operators."""
print("Edge set of the graph:")
for edge in graph.edges:
print("Weight:", graph.get_edge_data(*edge)["weight"], "Edge:", edge)
print("\nWeighted Pauli operators.")
for pauli in op.paulis:
print(2 * np.real(pauli[0]), "*", pauli[1].to_label()[::-1])
"""Make the QAOA instance."""
qaoa = QAOA(op, POWELL(), p=1)
"""See the settings of the QAOA object."""
print(qaoa.print_settings())
"""Inspect the circuits."""
backend = qiskit.BasicAer.get_backend("qasm_simulator")
circs = qaoa.construct_circuit([1, 2], backend=backend)
print(f"There are {len(circs)} circuits.")
print(circs[0])
"""Set the number of points N to define the grid. Larger N ==> longer runtime."""
N = 10
gammas = np.linspace(-np.pi, np.pi, N)
betas = np.linspace(-np.pi, np.pi, N)
"""Minor hacks for the QAOA instance to make the grid search possible.
Run this cell without too much thought -- this is necessary because the way Aqua is set up.
"""
quantum_instance = qiskit.aqua.QuantumInstance(backend=qiskit.BasicAer.get_backend("qasm_simulator"))
qaoa._quantum_instance = quantum_instance
qaoa._use_simulator_operator_mode = True
"""Do the grid search and display the progress."""
import progressbar
bar = progressbar.ProgressBar(maxval=N**2)
costs = np.zeros((len(gammas), len(betas)), dtype=float)
bar.start()
for (ii, gamma) in enumerate(gammas):
for (jj, beta) in enumerate(betas):
costs[ii][jj] = qaoa._energy_evaluation(np.array([gamma, beta]))
bar.update(N * ii + jj)
bar.finish()
"""Visualize the landscape."""
plt.figure(figsize=(7, 7));
plt.imshow(costs, origin=(0, 0));
plt.xlabel("Gammas")
plt.ylabel("Betas")
plt.colorbar();
"""Your code here!"""
"""Write code to answer the above question here."""
print("Min cost =", np.min(costs)) # Your code here!
"""Get a quantum instance and run the algorithm."""
qaoa._optimizer = POWELL()
result = qaoa.run(quantum_instance)
"""View the optimal cost."""
qaoa.get_optimal_cost()
"""Get the circuit with optimal parameters."""
circ = qaoa.get_optimal_circuit()
qreg = circ.qregs[0]
creg = qiskit.ClassicalRegister(6)
circ.add_register(creg)
circ.measure(qreg, creg)
print(circ)
"""Execute the circuit to sample from it."""
job = qiskit.execute(circ, backend=backend, shots=100000)
res = job.result()
counts = res.get_counts()
"""Visualize the statistics."""
qiskit.visualization.plot_histogram(counts, figsize=(17, 6))
"""Get the top sampled bit strings."""
import operator
ntop = 10
top_cuts = sorted(counts, key=operator.itemgetter(1))
print(f"Top {ntop} sampled cuts.")
for cut in top_cuts[:ntop]:
print(cut[::-1])
"""Select a sampled cut and see its value."""
cut = np.array() ### <-- Your answer here!
print("The value of this cut is:", max_cut_value(cut, matrix))
"""Brute force search for the maximum cut."""
import itertools
high = -np.inf
conf = np.zeros(nodes)
cuts = itertools.product(*[[0, 1]] * nodes)
for cut in cuts:
cur = max_cut_value(np.array(cut), matrix)
if cur > high:
conf = np.array(cut)
high = cur
print("Value of maximum cut:", high)
print("Optimal cut:", conf)
"""Visualize the graph to see the maximum cut."""
draw_weighted(graph, cut=conf)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/qclib/qclib
|
qclib
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-docstring,invalid-name,no-member
# pylint: disable=attribute-defined-outside-init
# pylint: disable=unused-argument
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.compiler import transpile
from qiskit.quantum_info.random import random_unitary
class IsometryTranspileBench:
params = ([0, 1, 2, 3], [3, 4, 5, 6])
param_names = ["number of input qubits", "number of output qubits"]
def setup(self, m, n):
q = QuantumRegister(n)
qc = QuantumCircuit(q)
if not hasattr(qc, "iso"):
raise NotImplementedError
iso = random_unitary(2**n, seed=0).data[:, 0 : 2**m]
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
qc.iso(iso, q[:m], q[m:])
self.circuit = qc
def track_cnot_counts_after_mapping_to_ibmq_16_melbourne(self, *unused):
coupling = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
self.circuit,
basis_gates=["u1", "u3", "u2", "cx"],
coupling_map=coupling,
seed_transpiler=0,
)
counts = circuit.count_ops()
cnot_count = counts.get("cx", 0)
return cnot_count
|
https://github.com/anishrverma/Hybrid-Quantum-Endowment-Portfolio-Optimization
|
anishrverma
|
# %pip install --upgrade pip
# %pip install -r requirements.txt
import seaborn as sn
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram
from datetime import datetime
import numpy as np
from itertools import permutations
from qiskit_finance.data_providers import YahooDataProvider
import json # Necessary for YahooDataProvider
import http.client # Necessary for YahooDataProvider
import pandas as pd
import pandas_datareader as web
import os
from docplex.mp.model import Model
from qiskit_optimization.translators import from_docplex_mp
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_optimization.converters import LinearEqualityToPenalty
from qiskit.circuit.library import TwoLocal # For Ansatz
from qiskit.algorithms.optimizers import COBYLA, ADAM, NELDER_MEAD, POWELL, SPSA, QNSPSA
from qiskit.opflow import CVaRExpectation
from qiskit.opflow import PauliExpectation
from qiskit.algorithms import VQE
from qiskit.algorithms import QAOA
from qiskit import Aer
dfMonthlyReturns = pd.read_csv('data/Equity-Benchmarks-Monthly-Return.csv',parse_dates=["Date"],index_col=0)
dfMonthlyReturnsRiskScaled = pd.read_csv('data/Equity-Benchmarks-Monthly-Risk-Scaled.csv',parse_dates=["Date"],index_col=0)
assets = dfMonthlyReturns.columns.to_list()
numAssets = len(assets)
print("We have " + str(numAssets) + " Assets:\n")
[print(asset + " ") for asset in assets];
q = 0.5 # risk apetite
B = 5 # budget
#Whole Period
startDate=datetime(2001, 1, 31)
endDate=datetime(2021, 12, 31)
# #Pre 2008
# startDate=datetime(2001, 1, 31)
# endDate=datetime(2008, 6, 30)
# #QE Era
# startDate=datetime(2010, 1, 31)
# endDate=datetime(2019, 12, 31)
# #Pandemic
# startDate=datetime(2020, 6, 30)
# endDate=datetime(2021, 12, 31)
startStr = str(startDate.date())
endStr = str(endDate.date())
backend = Aer.get_backend('statevector_simulator') # statevector_simulator, qasm_simulator, aer_simulator_statevector
maxIter = 10000
# fidelity = QNSPSA.get_fidelity(ansatz) # only for QNSPSA
optimizer = SPSA(maxiter=500)
# Classical optimizer – COBYLA(maxiter=maxIter), ADAM(maxiter=maxIter), NELDER_MEAD(maxiter=maxIter),
# POWELL(maxiter=maxIter), SPSA(maxiter=100), QNSPSA(fidelity,maxiter=100)
penalty = numAssets # scaling of penalty term. This can be changed at your discretion.
mu = dfMonthlyReturns[startDate:endDate].mean().to_numpy()
sigma = dfMonthlyReturns[startDate:endDate].cov().to_numpy()
muRisk = dfMonthlyReturnsRiskScaled[startDate:endDate].mean().to_numpy()
sigmaRisk = dfMonthlyReturnsRiskScaled[startDate:endDate].cov().to_numpy()
covHeatmap = sn.heatmap(sigma,cmap="mako")
covHeatmap.set(xticklabels=assets,yticklabels=assets)
plt.yticks(rotation='horizontal')
plt.xticks(rotation='vertical')
plt.title("Covariance of Monthly Returns\n"+startStr+" to " +endStr)
plt.show()
covHeatmapRisk = sn.heatmap(sigmaRisk,cmap="mako")
covHeatmapRisk.set(xticklabels=assets,yticklabels=assets)
plt.yticks(rotation='horizontal')
plt.xticks(rotation='vertical')
plt.title("Covariance of Monthly Returns (Risk Scaled)\n"+startStr+" to " +endStr)
plt.show()
covHeatmap = sn.heatmap(sigma,cmap="mako",vmin=0,vmax=0.004)
covHeatmap.set(xticklabels=assets,yticklabels=assets)
plt.yticks(rotation='horizontal')
plt.xticks(rotation='vertical')
plt.title("Covariance of Monthly Returns\n"+startStr+" to " +endStr)
plt.show()
fig = covHeatmap.get_figure()
fig.savefig("figures/CovarianceMonthlyReturns-" + startStr + "-to-" + endStr + ".pdf",bbox_inches='tight')
covHeatmapRisk = sn.heatmap(sigmaRisk,cmap="mako",vmin=0,vmax=0.00011)
covHeatmapRisk.set(xticklabels=assets,yticklabels=assets)
plt.yticks(rotation='horizontal')
plt.xticks(rotation='vertical')
plt.title("Covariance of Monthly Returns (Risk Scaled)\n"+startStr+" to " +endStr)
plt.show()
figRisk = covHeatmapRisk.get_figure()
figRisk.savefig("figures/CovarianceMonthlyReturnsRisk-" + startStr + "-to-" + endStr + ".pdf",bbox_inches='tight')
mdl = Model("Non-Scaled") # You can input a string into the argument if you want to name the model.
x = mdl.binary_var_list('x{}'.format(i) for i in range(numAssets)) # binary decision variables
# Objective Function to be maximized
objective = mdl.sum([mu[i]*x[i] for i in range(numAssets)])
objective -= q * mdl.sum([sigma[i,j]*x[i]*x[j] for i in range(numAssets) for j in range(numAssets)])
mdl.maximize(objective)
mdl.add_constraint(mdl.sum(x[i] for i in range(numAssets)) == B) # Adding the budget constraint
qp = from_docplex_mp(mdl) # Conversion to a quadratic program
qp
mdlRisk = Model("Risk-Scaled") # You can input a string into the argument if you want to name the model.
y = mdlRisk.binary_var_list('y{}'.format(i) for i in range(numAssets)) # binary decision variables
# Objective Function to be maximized
objectiveRisk = mdlRisk.sum([muRisk[i]*y[i] for i in range(numAssets)])
objectiveRisk -= q * mdlRisk.sum([sigmaRisk[i,j]*y[i]*y[j] for i in range(numAssets) for j in range(numAssets)])
mdlRisk.maximize(objectiveRisk)
mdlRisk.add_constraint(mdlRisk.sum(y[i] for i in range(numAssets)) == B) # Adding the budget constraint
qpRisk = from_docplex_mp(mdlRisk) # Conversion to a quadratic program
qpRisk
classicalResult = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp)
# classicalResultEigenstate = (classicalResult.min_eigen_solver_result.eigenstate._primitive.data.real).tolist()
classicalResultEigenstate = classicalResult.min_eigen_solver_result.eigenstate.to_dict_fn().primitive
classicalResult
# making the labels for plotting
# labels = []
# for i in range(2**numAssets):
# labels.append(format(i,'0'+str(numAssets)+'b'))
# fig = plot_histogram(dict(zip(labels, classicalResultEigenstate)),figsize=(60,10))
fig = plot_histogram(classicalResultEigenstate,figsize=(60,10))
fig.savefig("figures/ClassicalEigensolver-"+startStr+"-"+endStr+".pdf")
# fig
classicalResultRisk = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qpRisk)
#classicalResultRiskEigenstate = (classicalResultRisk.min_eigen_solver_result.eigenstate._primitive.data.real).tolist()
classicalResultRiskEigenstate = classicalResultRisk.min_eigen_solver_result.eigenstate.to_dict_fn().primitive
classicalResultRisk
# making the labels for plotting
# labels = []
# for i in range(2**numAssets):
# labels.append(format(i,'0'+str(numAssets)+'b'))
# fig = plot_histogram(dict(zip(labels, classicalResultRiskEigenstate)),figsize=(60,10))
fig = plot_histogram(classicalResultRiskEigenstate,figsize=(60,10))
fig.savefig("figures/ClassicalEigensolverRisk-"+startStr+"-"+endStr+".pdf")
# fig
linearToPenalty = LinearEqualityToPenalty(penalty=penalty)
qubo = linearToPenalty.convert(qp)
quboRisk = linearToPenalty.convert(qpRisk)
qubo
quboRisk
reps = 2
ansatz = TwoLocal(num_qubits=numAssets, rotation_blocks='rx', entanglement_blocks= 'cz', reps=reps, entanglement='full')
ansatz.decompose().draw()
maxIter = 10000
# fidelity = QNSPSA.get_fidelity(ansatz) # only for QNSPSA
optimizer = SPSA(maxiter=500)
# Classical optimizer – COBYLA(maxiter=maxIter), ADAM(maxiter=maxIter), NELDER_MEAD(maxiter=maxIter),
# POWELL(maxiter=maxIter), SPSA(maxiter=100), QNSPSA(fidelity,maxiter=100)
def pauliDict(H):
tempKey = []
tempVal = []
tempDict = {}
for i in range(len(H)):
tempDict[H.primitive.to_list()[i][0]] = H.primitive.to_list()[i][1]
return tempDict
H, offset = qubo.to_ising()
pauliDict(H)
HRisk, offsetRisk = quboRisk.to_ising()
pauliDict(HRisk)
def getCountDictStateVecSim(vqeResult):
tempState = []
tempProb = []
for sample in vqeResult.samples:
tempProb.append(sample.probability)
tempStr = ''
for stateElement in reversed(sample.x):
tempStr += str(int(stateElement))
tempState.append(tempStr)
return dict(zip(tempState, tempProb))
vqeInit = VQE(ansatz=ansatz,optimizer=optimizer, quantum_instance=backend)
vqe = MinimumEigenOptimizer(vqeInit)
vqeResult = vqe.solve(qubo)
if backend.name() == 'qasm_simulator':
counts = vqeResult.min_eigen_solver_result.eigenstate
elif backend.name() == 'statevector_simulator':
counts = getCountDictStateVecSim(vqeResult)
#endif
vqeResult
vqeFig = plot_histogram(counts,figsize=(60,10))
vqeFig.savefig("figures/VQE"+startStr+"-"+endStr+".pdf")
vqeFig
## ALTERNATIVE PLOT SCHEME
# samples_for_plot = {
# " ".join(f"{vqeResult.variables[i].name}={int(v)}" for i, v in enumerate(sample.x)): sample.probability
# for sample in vqeResult.samples
# }
# plot_histogram(samples_for_plot,figsize=(60,5))
vqeRiskInit = VQE(ansatz=ansatz,optimizer=optimizer, quantum_instance=backend)
vqeRisk = MinimumEigenOptimizer(vqeRiskInit)
vqeRiskResult = vqeRisk.solve(quboRisk)
if backend.name() == 'qasm_simulator':
countsRisk = vqeRiskResult.min_eigen_solver_result.eigenstate
elif backend.name() == 'statevector_simulator':
countsRisk = getCountDictStateVecSim(vqeRiskResult)
#endif
vqeRiskResult
vqeRiskFig = plot_histogram(countsRisk,figsize=(60,10))
vqeRiskFig.savefig("figures/VQERisk"+startStr+"-"+endStr+".pdf")
vqeRiskFig
qaoaInit = QAOA(optimizer=optimizer, reps=reps, quantum_instance=backend)
qaoa = MinimumEigenOptimizer(qaoaInit)
qaoaResult = qaoa.solve(qubo)
if backend.name() == 'qasm_simulator':
counts = qaoaResult.min_eigen_solver_result.eigenstate
elif backend.name() == 'statevector_simulator':
counts = getCountDictStateVecSim(qaoaResult)
#endif
qaoaResult
qaoaFig = plot_histogram(counts,figsize=(60,10))
qaoaFig.savefig("figures/QAOA-"+startStr+"-"+endStr+".pdf")
qaoaFig
qaoaRiskInit = QAOA(optimizer=optimizer, reps=reps, quantum_instance=backend)
qaoaRisk = MinimumEigenOptimizer(qaoaRiskInit)
qaoaRiskResult = qaoaRisk.solve(quboRisk)
if backend.name() == 'qasm_simulator':
countsRisk = qaoaRiskResult.min_eigen_solver_result.eigenstate
elif backend.name() == 'statevector_simulator':
countsRisk = getCountDictStateVecSim(qaoaRiskResult)
#endif
qaoaRiskResult
qaoaRiskFig = plot_histogram(countsRisk,figsize=(60,10))
qaoaRiskFig.savefig("figures/QAOARisk-"+startStr+"-"+endStr+".pdf")
qaoaRiskFig
classicalResult
vqeResult
qaoaResult
classicalResultRisk
vqeRiskResult
qaoaRiskResult
def getCombinations(inputVal):
combinations = []
if type(inputVal) == str:
for perm in set(permutations(inputVal)):
combinations.append(''.join(perm))
#endFor
elif type(inputVal) == list:
for i in range(len(inputVal)):
inputVal[i] = int(inputVal[i])
#endFor
for perm in set(permutations(inputVal)):
combinations.append(list(perm))
#endFor
else:
print("Input a string or list of ones and zeroes")
return combinations
def countNonZeroElemInList(inputList):
numNonZeroElem = 0.
for x in inputList:
if x != 0:
numNonZeroElem += 1
else:
numNonZeroElem += 0
#endIf
#endFor
return numNonZeroElem
def assetTotalPortfolioGrowth(initialPortfolioValue,selectedAssets,testDF):
amountSplit = initialPortfolioValue/countNonZeroElemInList(selectedAssets)
assetGrowth = []
for i in range(len(selectedAssets)):
if selectedAssets[i] == 1:
tempDF = testDF.iloc[:,i]
amountTemp = amountSplit
for pctChg in tempDF:
amountTemp += pctChg*amountTemp
assetGrowth.append(amountTemp)
else:
assetGrowth.append(0.)
#endIf
#endFor
return assetGrowth
def assetGrowthTimeSeries(initialPortfolioValue,selectedAssets,testDF):
amountSplit = initialPortfolioValue/countNonZeroElemInList(selectedAssets)
assetGrowthTS = []
for i in range(len(selectedAssets)):
if selectedAssets[i] == 1:
tempVec = []
tempDF = testDF.iloc[:,i]
amountTemp = amountSplit
for pctChg in tempDF:
amountTemp += pctChg*amountTemp
tempVec.append(amountTemp)
assetGrowthTS.append(tempVec)
else:
tempVec = []
tempDF = testDF.iloc[:,i]
for pctChg in tempDF:
tempVec.append(0.0)
assetGrowthTS.append(tempVec)
#endIf
#endFor
return assetGrowthTS
def assetGrowthTimeSeriesWeighted(initialPortfolioValue,selectedAssets,testDF,weights):
assetGrowthTS = []
for i in range(len(selectedAssets)):
if selectedAssets[i] == 1:
tempVec = []
tempDF = testDF.iloc[:,i]
amountTemp = initialPortfolioValue*weights[i]
for pctChg in tempDF:
amountTemp += pctChg*amountTemp
tempVec.append(amountTemp)
assetGrowthTS.append(tempVec)
else:
tempVec = []
tempDF = testDF.iloc[:,i]
for pctChg in tempDF:
tempVec.append(0.0)
assetGrowthTS.append(tempVec)
#endIf
#endFor
return assetGrowthTS
def portfolioGrowthTimeSeries(portfolioTS):
portfolioValueTS = []
for i in range(len(portfolioTS[0])):
tempVal = 0.0
for j in range(len(portfolioTS)):
tempVal += portfolioTS[j][i]
portfolioValueTS.append(tempVal)
return portfolioValueTS
assetTest = qaoaRiskResult.x.tolist()
amountInit = 1000
allAssetCombinations = getCombinations(assetTest)
dateList = dfMonthlyReturns.index
# # Gives total number of chosen assets, AKA budget. More of a sanity check.
# numAssetsChosen = countNonZeroElemInList(assetTest)
# # Gives each selected asset's total final value in a list
# finalAssetValues = assetTotalPortfolioGrowth(amountInit,assetTest,dfMonthlyReturns)
# # Gives the time series of each portfolio element as a list of lists. In each list,
# # the final element is the final value of the held asset.
# chosenAssetsTimeSeries = assetGrowthTimeSeries(amountInit,assetTest,dfMonthlyReturns)
# # Gives the time series for the total portfolio value. The final element is the final portfolio value.
# portfolioTimeSeries = portfolioGrowthTimeSeries(chosenAssetsTimeSeries)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
for i in range(len(allAssetCombinations)):
chosenAssetsTimeSeries = assetGrowthTimeSeries(amountInit,allAssetCombinations[i],dfMonthlyReturns)
portfolioTimeSeries = portfolioGrowthTimeSeries(chosenAssetsTimeSeries)
label = ''
for element in allAssetCombinations[i]:
label+=str(element)
#endFor
ax.plot(dateList,portfolioTimeSeries,color='blue',linestyle='--',alpha=0.1,linewidth=0.5)
#endFor
winningAssetCombination = assetTest
winningAssetTimeSeries = assetGrowthTimeSeries(amountInit,winningAssetCombination,dfMonthlyReturns)
winningPortfolioTimeSeries = portfolioGrowthTimeSeries(winningAssetTimeSeries)
label = ''
for element in winningAssetCombination:
label+=str(element)
#endFor
ax.plot(dateList,winningPortfolioTimeSeries,label=label,color='red',alpha=1,linewidth=2)
plt.xlim(startDate,endDate)
plt.ylabel('Total Portfolio Value')
plt.xlabel('Date')
plt.legend()#bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)
plt.show()
fig.savefig('figures/portfolio-'+label+'risk-'+str(q)+'-'+startStr+"-"+endStr+'.pdf',bbox_inches='tight')
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
for i in range(len(allAssetCombinations)):
chosenAssetsTimeSeries = assetGrowthTimeSeries(amountInit,allAssetCombinations[i],dfMonthlyReturns)
portfolioTimeSeries = portfolioGrowthTimeSeries(chosenAssetsTimeSeries)
label = ''
for element in allAssetCombinations[i]:
label+=str(element)
#endFor
ax.plot(dateList,portfolioTimeSeries,color='blue',linestyle='--',alpha=0.1,linewidth=0.5)
#endFor
winningAssetCombination = assetTest
winningAssetTimeSeries = assetGrowthTimeSeries(amountInit,winningAssetCombination,dfMonthlyReturns)
winningPortfolioTimeSeries = portfolioGrowthTimeSeries(winningAssetTimeSeries)
label = ''
for element in winningAssetCombination:
label+=str(element)
#endFor
label += ' equally weighted'
ax.plot(dateList,winningPortfolioTimeSeries,label=label,color='red',alpha=1,linewidth=2)
portfolioWeights = [0.223214286,0.233800935,0.2042007,0.0,0.0,0.0,0.172583826,0.165250236]
weightedWinningAssetTimeSeries = assetGrowthTimeSeriesWeighted(amountInit,assetTest,dfMonthlyReturns,portfolioWeights)
weightedWinningPortfolioTimeSeries = portfolioGrowthTimeSeries(weightedWinningAssetTimeSeries)
label = ''
for element in winningAssetCombination:
label+=str(element)
#endFor
label += ' risk-parity weighted'
ax.plot(dateList,weightedWinningPortfolioTimeSeries,label=label,color='purple',alpha=1,linewidth=2)
plt.xlim(startDate,endDate)
plt.ylabel('Total Portfolio Value')
plt.xlabel('Date')
plt.legend()#bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0)
plt.show()
fig.savefig('figures/weighted-comparison-portfolio-'+label+'risk-'+str(q)+'-'+startStr+"-"+endStr+'.pdf',bbox_inches='tight')
from qiskit import QuantumCircuit, assemble, Aer
from math import pi, sqrt
from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_bloch_vector
sim = Aer.get_backend('aer_simulator')
qc = QuantumCircuit(1)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
plot_bloch_multivector(state)
qc = QuantumCircuit(1)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
fig=plot_bloch_multivector(state)
fig.savefig('figures/bloch-no-rotate.pdf', bbox_inches='tight')
qc = QuantumCircuit(1)
qc.rx(theta=pi/2,qubit=0)
qc.draw()
qc.save_statevector()
qobj = assemble(qc)
state = sim.run(qobj).result().get_statevector()
fig=plot_bloch_multivector(state)
fig.savefig('figures/bloch-pi-over-two-x-rotate.pdf', bbox_inches='tight')
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
from sklearn import datasets
import pennylane as qml
import numpy as np
from pennylane.optimize import AdamOptimizer
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
X_train, Y_train = datasets.make_circles(n_samples=200, noise=0.09, factor=0.4)
X_test, Y_test = datasets.make_circles(n_samples=50, noise=0.09, factor=0.4)
print('Training Data:')
print(X_train[:10])
print('\nTraining Label:')
print(Y_train[:10])
plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train)
plt.show()
print(f'Total datas: {len(X_train)}')
print(f'labels: {list(set(Y_train))}')
print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5
temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1))
temp[:, :-1] = X_train
temp[:, -1] = Z_train
X_train2 = temp
Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5
temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1))
temp[:, :-1] = X_test
temp[:, -1] = Z_test
X_test2 = temp
print('Solved Training Data:')
print(X_train2[:10])
def plot3D(X, Y):
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(
X[:, 0], X[:, 1], X[:, 2],
zdir='z', s=30, c=Y, depthshade=True
)
plt.show()
plot3D(X_train2, Y_train)
print(f'Total datas: {len(X_train2)}')
print(f'labels: {list(set(Y_train))}')
print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f'label 1 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
qubits_num = 3
layers_num = 2
dev = qml.device("default.qubit", wires=qubits_num)
class VQC:
def __init__(self):
# 3 => U3(theta, phi, lambda)
self.params = (0.05 * np.random.randn(layers_num, qubits_num, 3))
self.bestparams = self.params
self.bestcost = 10
self.opt = AdamOptimizer(0.08)
self.weights = []
self.costs = []
self.accuracies = []
def fit(self, X_train, Y_train, epoch=300):
batch_size = 20
for turn in range(epoch):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train), (batch_size,))
X_train_batch = X_train[batch_index]
Y_train_batch = Y_train[batch_index]
self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params)
cost_now = cost(self.params, X_train, Y_train)
acc_now = accuracy(self.params, X_train, Y_train)
if cost_now < self.bestcost:
self.bestcost = cost_now
self.bestparams = self.params
self.weights.append(self.params)
self.costs.append(cost_now)
self.accuracies.append(acc_now)
print(
"Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format(
turn + 1, cost_now, acc_now * 100
))
def score(self, X_test, Y_test):
predictions = [ predict(self.bestparams, data) for data in X_test ]
acc = accuracy(self.bestparams, X_test, Y_test)
print("FINAL ACCURACY: {:0.2f}%".format(acc * 100))
@qml.qnode(dev)
def circuit(params, data):
angles = [ i * np.pi for i in data ]
for i in range(qubits_num):
qml.RX(angles[i], wires=i)
qml.Rot( *params[0, i], wires=i )
qml.CZ(wires=[1, 0])
qml.CZ(wires=[1, 2])
qml.CZ(wires=[0, 2])
for i in range(qubits_num):
qml.Rot( *params[1, i], wires=i )
# PauliZ measure => 1 -> |0> while -1 -> |1>
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2))
import qiskit
import numpy as np
from qiskit import QuantumCircuit
from qiskit import Aer, execute
unitary_backend = Aer.get_backend('unitary_simulator')
qasm_backend = Aer.get_backend('qasm_simulator')
def predict(params, data):
qcircuit = QuantumCircuit(3, 3)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[0], qubits[2])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
# the measurement
qcircuit.measure([0, 1, 2], [0, 1, 2])
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110', 0)) / shots
if p1 > 0.5:
return 1
else:
return 0
def cost(weights, datas, labels):
loss = 0
for i, data in enumerate(datas):
# like [-1, 1, 1]
measured = circuit(weights, data)
p = measured[0]
if labels[i] == 0:
loss += (1 - p) ** 2
else:
loss += (-1 - p) ** 2
return loss / len(datas)
def accuracy(weights, datas, labels):
predictions = [ predict(weights, data) for data in datas ]
acc = 0
for i, p in enumerate(predictions):
if p == labels[i]:
acc += 1
return acc / len(predictions)
vqc = VQC()
# vqc.params = np.array([[[-1.18991246e-01, -8.69694713e-01, 1.43722811e-03],
# [ 3.47641545e+00, -4.73632073e-02, 1.97135609e+00],
# [ 1.95775707e+00, -1.12139160e-02, -6.21796144e-03]],
# [[ 2.02460380e-02, -2.25797547e+00, 5.14234265e-03],
# [-1.71552299e-02, 2.46283604e-03, -1.03805722e-02],
# [-2.37244982e-03, -3.35799404e-03, 6.10191152e-03]]])
vqc.fit(X_train2, Y_train, epoch=10)
print(cost(vqc.bestparams, X_train2, Y_train))
print(cost(vqc.bestparams, X_test2, Y_test))
vqc.score(X_test2, Y_test)
def createCircuit(params, data):
qcircuit = QuantumCircuit(3, 3)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[0], qubits[2])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
return qcircuit
qcircuit = createCircuit(vqc.bestparams, X_train2[0])
qcircuit.draw(output='mpl')
def measure(qcircuit, label):
# the measurement
qcircuit.measure([0, 1, 2], [0, 1, 2])
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
print(f'simulation results: \n{counts}')
p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110',0)) / shots
print(f'p1: {p1}')
print(f'Expected label: {label}')
example = [3, 30, 35, 70]
for index in example:
qcircuit = createCircuit(vqc.bestparams, X_train2[index])
measure(qcircuit, Y_train[index])
print()
# origin data
plt.scatter(X_train2[:, 0], X_train2[:, 1], c=Y_train)
plt.show()
predictions = [ predict(vqc.bestparams, data) for data in X_test2 ]
Y_ = [ Y_test[i] if Y_test[i] == predictions[i] else 2 for i in range(len(Y_test)) ]
plt.scatter(X_test2[:, 0], X_test2[:, 1], c=Y_)
plt.show()
train_params(X_train2[10:50], Y_train[10:50])
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from IPython.display import IFrame
IFrame(src="http://www.youtube.com/embed/RrUTwq5jKM4", width=1920/2, height=1080/2)
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit = QuantumCircuit(2,2)
circuit.draw()
%matplotlib inline
circuit.draw(output='mpl')
# the quantum circuit has two qubits. they are indexed as qubits 0 and 1
circuit.h(0)
circuit.cx(0,1) # order is control, target
circuit.measure([0,1], [0,1]) # qubits [0,1] are measured and results are stored in classical bits [0,1] in order
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator).result()
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
IBMQ.load_account()
provider = IBMQ.get_provider(hub = 'ibm-q')
qcomp = provider.get_backend('ibmq_16_melbourne')
num_qubits = 2
from qiskit.providers.ibmq import least_busy
possible_devices = provider.backends(filters=lambda x:
x.configuration().n_qubits >= num_qubits
and
x.configuration().simulator == False)
qcomp = least_busy(possible_devices)
print(qcomp)
import qiskit.tools.jupyter
%qiskit_job_watcher
job = execute(circuit, backend=qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
%qiskit_disable_job_watcher
qiskit.__qiskit_version__
%qiskit_copyright
|
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/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from dwave.system import DWaveCliqueSampler, LeapHybridSampler
from helpers import *
qps = createModelsFromDir('BURKARDT_DATA/INT/')
for qp in qps.values():
print(qp.model.solve())
solvers = [createSolver(LeapHybridSampler()), createSolver(DWaveCliqueSampler(),1000)]
results = {}
for qp_name in qps.keys():
print(qp_name)
qp_name = "testprob"
results[qp_name] = [optimizer.solve(qps[qp_name]) for optimizer in solvers]
# problem ids :
# Leap db6c6b80-8882-4636-9879-a18c3b57c980
# Advantage system 0b80397c-22a2-41e1-9dce-2c6cffca3ff3
for res in results[qp_name]:
print(res)
qp_name = "three_vars_quadratic"
results[qp_name] = [optimizer.solve(qps[qp_name]) for optimizer in solvers]
|
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/ankitkmisra/Quantum-Computing-and-Cryptography
|
ankitkmisra
|
%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 *
import numpy as np
from fractions import Fraction as frac
import qiskit.quantum_info as qi
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
qc=QuantumCircuit(4)
#In this particular oracle, the last qubit is storing the value of the function
qc.cx(0,3)
qc.cx(1,3)
qc.cx(2,3)
#The last qubit is 1 if there are odd no. of 1s in the other 3 qubits
#and 0 otherwise
#Hence it is a balanced function
qc.draw('mpl')
qc1=QuantumCircuit(3)
qc1.x(2)
qc1.h(0)
qc1.h(1)
qc1.h(2)
qc1.barrier(range(3))
qc1.cx(0,2)
qc1.cx(1,2)
qc1.barrier(range(3))
qc1.h(0)
qc1.h(1)
meas = QuantumCircuit(3, 2)
meas.measure(range(2),range(2))
# The Qiskit circuit object supports composition using
# the addition operator.
circ = qc1+meas
circ.draw('mpl')
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=1000)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
plot_histogram(counts)
qc2=QuantumCircuit(5)
qc2.x(4)
qc2.h(0)
qc2.h(1)
qc2.h(2)
qc2.h(3)
qc2.h(4)
qc2.barrier(range(5))
#Your code for the oracle here
#YOU ARE PERMITTED TO USE ONLY SINGLE QUBIT GATES AND CNOT(cx) GATES
qc2.cx(0,4)
qc2.cx(1,4)
qc2.cx(2,4)
qc2.cx(3,4)
qc2.x(4)
qc2.barrier(range(5))
qc2.h(0)
qc2.h(1)
qc2.h(2)
qc2.h(3)
meas2 = QuantumCircuit(5, 4)
meas2.measure(range(4),range(4))
circ2 = qc2+meas2
circ2.draw('mpl')
#verification cell, reinitialising the circuit so that it's easier for you to copy-paste the oracle
qc2=QuantumCircuit(5)
#Add X gates HERE as required to change the input state
qc2.x([0,2])
qc2.barrier(range(5))
qc2.cx(0,4)
qc2.cx(1,4)
qc2.cx(2,4)
qc2.cx(3,4)
qc2.x(4)
qc2.barrier(range(5))
measv = QuantumCircuit(5, 1)
measv.measure(4,0)
circv = qc2+measv
circv.draw('mpl')
#DO NOT RUN THIS CELL WITHOUT EDITING THE ABOVE ONE AS DESIRED
#The following code will give you f(x) for the value of x you chose in the above cell
backend_sim2 = Aer.get_backend('qasm_simulator')
job_sim2 = execute(circv, backend_sim2, shots=1000)
result_sim2 = job_sim2.result()
counts2 = result_sim2.get_counts(circv)
print(counts2)
plot_histogram(counts2)
|
https://github.com/nahumsa/Introduction-to-IBM_Qiskit
|
nahumsa
|
# Let's import all functions
import numpy as np
import scipy as sp
from qiskit import Aer
from qiskit.opflow import PauliTrotterEvolution, StateFn, PauliExpectation
from qiskit.opflow import CircuitSampler, PauliOp
from qiskit.opflow import I, X, Y, Z, Zero, One, Plus, Minus
from qiskit.circuit import Parameter
hamiltonian = (Z^Z)
evo_time = Parameter('t')
evolution_op = (evo_time*hamiltonian).exp_i()
print(evolution_op)
num_time_slices = 1
trotterized_op = PauliTrotterEvolution(
trotter_mode='trotter',
reps=num_time_slices).convert(evolution_op)
trotterized_op.to_circuit().draw()
hamiltonian = (X^X)
evo_time = Parameter('t')
evolution_op = (evo_time*hamiltonian).exp_i()
num_time_slices = 1
trotterized_op = PauliTrotterEvolution(
trotter_mode='trotter',
reps=num_time_slices).convert(evolution_op)
trotterized_op.to_circuit().draw()
hamiltonian = (Y^Y)
evo_time = Parameter('t')
evolution_op = (evo_time*hamiltonian).exp_i()
num_time_slices = 1
trotterized_op = PauliTrotterEvolution(
trotter_mode='trotter',
reps=num_time_slices).convert(evolution_op)
trotterized_op.to_circuit().draw()
hamiltonian = (Z^Z^Z^Z)
evo_time = Parameter('t')
evolution_op = (evo_time*hamiltonian).exp_i()
num_time_slices = 1
trotterized_op = PauliTrotterEvolution(
trotter_mode='trotter',
reps=num_time_slices).convert(evolution_op)
trotterized_op.to_circuit().draw()
hamiltonian = (Z^Z) + (X^X)
observable = (X^X)
evo_time = Parameter('t')
evolution_op = (evo_time*hamiltonian).exp_i()
observable_measurement = StateFn(observable).adjoint()
eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix())
initial_state = StateFn(eigenstates[0])
print(initial_state.to_circuit_op())
evo_and_measure = observable_measurement @ evolution_op @ initial_state
print(evo_and_measure)
num_time_slices = 1
trotterized_op = PauliTrotterEvolution(
trotter_mode='trotter',
reps=num_time_slices).convert(evo_and_measure)
print(trotterized_op)
# Let's calculate expectation values
diagonalized_meas_op = PauliExpectation().convert(trotterized_op)
print(diagonalized_meas_op)
evo_time_points = [0.5, 0.75]
hamiltonian_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: evo_time_points})
print(f"Observable at time {evo_time_points}: {np.round(hamiltonian_trotter_expectations.eval(), 3)}")
sampler = CircuitSampler(backend=Aer.get_backend("qasm_simulator"))
# sampler.quantum_instance.run_config.shots = 1000
sampled_trotter_exp_op = sampler.convert(hamiltonian_trotter_expectations)
sampled_trotter_energies = sampled_trotter_exp_op.eval()
print(f"Energies: {np.round(np.real(sampled_trotter_energies),3)}")
import matplotlib.pyplot as plt
def run_hs(shots):
sampler = CircuitSampler(backend=Aer.get_backend("qasm_simulator"))
sampler.quantum_instance.run_config.shots = shots
hamiltonian_trotter_expectations = diagonalized_meas_op.bind_parameters({evo_time: 0.5})
sampled_trotter_exp_op = sampler.convert(hamiltonian_trotter_expectations)
sampled_trotter_energies = sampled_trotter_exp_op.eval()
return np.real(sampled_trotter_energies)
n_shots = [100, 1000, 2000, 5000, 7000, 10000]
exp = []
for shots in n_shots:
exp.append(run_hs(shots))
plt.plot(n_shots, exp, 'o', label=f"t={0.5}")
plt.hlines(y=0., xmin=min(n_shots), xmax=max(n_shots) + 1, colors='red')
plt.xlabel("# shots", size=16)
plt.ylabel(r"$ \langle O \rangle $", size=16)
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# we can break lines when defining our list
M = [
[8 , 0 , -1 , 0 , 2],
[-2 , -3 , 1 , 1 , 4],
[0 , 0 , 1 , -7 , 1],
[1 , 4 , -2 , 5 , 9]
]
# let's print matrix M
print(M)
# let's print M in matrix form, row by row
for i in range(4): # there are 4 rows
print(M[i])
M = [
[8 , 0 , -1 , 0 , 2],
[-2 , -3 , 1 , 1 , 4],
[0 , 0 , 1 , -7 , 1],
[1 , 4 , -2 , 5 , 9]
]
#let's print the element of M in the 1st row and the 1st column.
print(M[0][0])
#let's print the element of M in the 3rd row and the 4th column.
print(M[2][3])
#let's print the element of M in the 4th row and the 5th column.
print(M[3][4])
# we use double nested for-loops
N =[] # the result matrix
for i in range(4): # for each row
N.append([]) # create an empty sub-list for each row in the result matrix
for j in range(5): # in row (i+1), for each column
N[i].append(M[i][j]*-2) # we add new elements into the i-th sub-list
# let's print M and N, and see the results
print("I am M:")
for i in range(4):
print(M[i])
print()
print("I am N:")
for i in range(4):
print(N[i])
# create an empty list for the result matrix
K=[]
for i in range(len(M)): # len(M) return the number of rows in M
K.append([]) # we create a new row for K
for j in range(len(M[0])): # len(M[0]) returns the number of columns in M
K[i].append(M[i][j]+N[i][j]) # we add new elements into the i-th sublist/rows
# print each matrix in a single line
print("M=",M)
print("N=",N)
print("K=",K)
from random import randrange
#
# your solution is here
#
M = [
[-2,3,0,4],
[-1,1,5,9]
]
N =[
[1,2,3],
[4,5,6],
[7,8,9]
]
#
# your solution is here
#
# matrix M
M = [
[-1,0,1],
[-2,-3,4],
[1,5,6]
]
# vector v
v = [1,-3,2]
# the result vector u
u = []
# for each row, we do an inner product
for i in range(3):
# inner product for one row is initiated
inner_result = 0 # this variable keeps the summation of the pairwise multiplications
for j in range(3): # the elements in the i-th row
inner_result = inner_result + M[i][j] * v[j]
# inner product for one row is completed
u.append(inner_result)
print("M is")
for i in range(len(M)):
print(M[i])
print()
print("v=",v)
print()
print("u=",u)
#
# your solution is here
#
# matrix M
M = [
[-1,0,1],
[-2,-1,2],
[1,2,-2]
]
# matrix N
M = [
[0,2,1],
[3,-1,-2],
[-1,1,0]
]
# matrix K
K = []
#
# your solution is here
#
#
# your solution is here
#
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- 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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import torch
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123456
_ = torch.manual_seed(123456) # suppress output
import numpy as np
num_dim = 2
num_discrete_values = 8
num_qubits = num_dim * int(np.log2(num_discrete_values))
from scipy.stats import multivariate_normal
coords = np.linspace(-2, 2, num_discrete_values)
rv = multivariate_normal(mean=[0.0, 0.0], cov=[[1, 0], [0, 1]], seed=algorithm_globals.random_seed)
grid_elements = np.transpose([np.tile(coords, len(coords)), np.repeat(coords, len(coords))])
prob_data = rv.pdf(grid_elements)
prob_data = prob_data / np.sum(prob_data)
import matplotlib.pyplot as plt
from matplotlib import cm
mesh_x, mesh_y = np.meshgrid(coords, coords)
grid_shape = (num_discrete_values, num_discrete_values)
fig, ax = plt.subplots(figsize=(9, 9), subplot_kw={"projection": "3d"})
prob_grid = np.reshape(prob_data, grid_shape)
surf = ax.plot_surface(mesh_x, mesh_y, prob_grid, cmap=cm.coolwarm, linewidth=0, antialiased=False)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
from qiskit import QuantumCircuit
from qiskit.circuit.library import EfficientSU2
qc = QuantumCircuit(num_qubits)
qc.h(qc.qubits)
ansatz = EfficientSU2(num_qubits, reps=6)
qc.compose(ansatz, inplace=True)
qc.decompose().draw("mpl")
qc.num_parameters
from qiskit.primitives import Sampler
shots = 10000
sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed})
from qiskit_machine_learning.connectors import TorchConnector
from qiskit_machine_learning.neural_networks import SamplerQNN
def create_generator() -> TorchConnector:
qnn = SamplerQNN(
circuit=qc,
sampler=sampler,
input_params=[],
weight_params=qc.parameters,
sparse=False,
)
initial_weights = algorithm_globals.random.random(qc.num_parameters)
return TorchConnector(qnn, initial_weights)
from torch import nn
class Discriminator(nn.Module):
def __init__(self, input_size):
super(Discriminator, self).__init__()
self.linear_input = nn.Linear(input_size, 20)
self.leaky_relu = nn.LeakyReLU(0.2)
self.linear20 = nn.Linear(20, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, input: torch.Tensor) -> torch.Tensor:
x = self.linear_input(input)
x = self.leaky_relu(x)
x = self.linear20(x)
x = self.sigmoid(x)
return x
generator = create_generator()
discriminator = Discriminator(num_dim)
def adversarial_loss(input, target, w):
bce_loss = target * torch.log(input) + (1 - target) * torch.log(1 - input)
weighted_loss = w * bce_loss
total_loss = -torch.sum(weighted_loss)
return total_loss
from torch.optim import Adam
lr = 0.01 # learning rate
b1 = 0.7 # first momentum parameter
b2 = 0.999 # second momentum parameter
generator_optimizer = Adam(generator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005)
discriminator_optimizer = Adam(
discriminator.parameters(), lr=lr, betas=(b1, b2), weight_decay=0.005
)
from IPython.display import clear_output
def plot_training_progress():
# we don't plot if we don't have enough data
if len(generator_loss_values) < 2:
return
clear_output(wait=True)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 9))
# Generator Loss
ax1.set_title("Loss")
ax1.plot(generator_loss_values, label="generator loss", color="royalblue")
ax1.plot(discriminator_loss_values, label="discriminator loss", color="magenta")
ax1.legend(loc="best")
ax1.set_xlabel("Iteration")
ax1.set_ylabel("Loss")
ax1.grid()
# Relative Entropy
ax2.set_title("Relative entropy")
ax2.plot(entropy_values)
ax2.set_xlabel("Iteration")
ax2.set_ylabel("Relative entropy")
ax2.grid()
plt.show()
import time
from scipy.stats import multivariate_normal, entropy
n_epochs = 50
num_qnn_outputs = num_discrete_values**num_dim
generator_loss_values = []
discriminator_loss_values = []
entropy_values = []
start = time.time()
for epoch in range(n_epochs):
valid = torch.ones(num_qnn_outputs, 1, dtype=torch.float)
fake = torch.zeros(num_qnn_outputs, 1, dtype=torch.float)
# Configure input
real_dist = torch.tensor(prob_data, dtype=torch.float).reshape(-1, 1)
# Configure samples
samples = torch.tensor(grid_elements, dtype=torch.float)
disc_value = discriminator(samples)
# Generate data
gen_dist = generator(torch.tensor([])).reshape(-1, 1)
# Train generator
generator_optimizer.zero_grad()
generator_loss = adversarial_loss(disc_value, valid, gen_dist)
# store for plotting
generator_loss_values.append(generator_loss.detach().item())
generator_loss.backward(retain_graph=True)
generator_optimizer.step()
# Train Discriminator
discriminator_optimizer.zero_grad()
real_loss = adversarial_loss(disc_value, valid, real_dist)
fake_loss = adversarial_loss(disc_value, fake, gen_dist.detach())
discriminator_loss = (real_loss + fake_loss) / 2
# Store for plotting
discriminator_loss_values.append(discriminator_loss.detach().item())
discriminator_loss.backward()
discriminator_optimizer.step()
entropy_value = entropy(gen_dist.detach().squeeze().numpy(), prob_data)
entropy_values.append(entropy_value)
plot_training_progress()
elapsed = time.time() - start
print(f"Fit in {elapsed:0.2f} sec")
with torch.no_grad():
generated_probabilities = generator().numpy()
fig = plt.figure(figsize=(18, 9))
# Generated CDF
gen_prob_grid = np.reshape(np.cumsum(generated_probabilities), grid_shape)
ax1 = fig.add_subplot(1, 3, 1, projection="3d")
ax1.set_title("Generated CDF")
ax1.plot_surface(mesh_x, mesh_y, gen_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax1.set_zlim(-0.05, 1.05)
# Real CDF
real_prob_grid = np.reshape(np.cumsum(prob_data), grid_shape)
ax2 = fig.add_subplot(1, 3, 2, projection="3d")
ax2.set_title("True CDF")
ax2.plot_surface(mesh_x, mesh_y, real_prob_grid, linewidth=0, antialiased=False, cmap=cm.coolwarm)
ax2.set_zlim(-0.05, 1.05)
# Difference
ax3 = fig.add_subplot(1, 3, 3, projection="3d")
ax3.set_title("Difference between CDFs")
ax3.plot_surface(
mesh_x, mesh_y, real_prob_grid - gen_prob_grid, linewidth=2, antialiased=False, cmap=cm.coolwarm
)
ax3.set_zlim(-0.05, 0.1)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# result = Sampler("ibmq_qasm_simulator").run(circuits).result()
# Built-in modules
import math
# Imports from Qiskit
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, MCMT, ZGate
from qiskit.visualization import plot_distribution
# Imports from Qiskit Runtime
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
# Add your token below
service = QiskitRuntimeService(channel="ibm_quantum")
from qiskit import IBMQ
IBMQ.save_account('33b329939cf6fe545c64afb41b84e0993a774c578c2d3e3a07b2ed8644261511d4712974c684ae3050ca82dd8f4ca161930bb344995de7934be32214bdb17079')
|
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)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.