repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
|
Alice-Bob-SW
|
# 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.
"""
StatePreparation test.
"""
import unittest
import math
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Statevector, Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
from qiskit.circuit.library import StatePreparation
@ddt
class TestStatePreparation(QiskitTestCase):
"""Test initialization with StatePreparation class"""
def test_prepare_from_label(self):
"""Prepare state from label."""
desired_sv = Statevector.from_label("01+-lr")
qc = QuantumCircuit(6)
qc.prepare_state("01+-lr", range(6))
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_from_int(self):
"""Prepare state from int."""
desired_sv = Statevector.from_label("110101")
qc = QuantumCircuit(6)
qc.prepare_state(53, range(6))
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_from_list(self):
"""Prepare state from list."""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_single_qubit(self):
"""Prepare state in single qubit."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], qreg[1])
expected = QuantumCircuit(qreg)
expected.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], [qreg[1]])
self.assertEqual(circuit, expected)
def test_nonzero_state_incorrect(self):
"""Test final state incorrect if initial state not zero"""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
qc.x(0)
qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
actual_sv = Statevector(qc)
self.assertFalse(desired_sv == actual_sv)
@data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
def test_inverse(self, state):
"""Test inverse of StatePreparation"""
qc = QuantumCircuit(2)
stateprep = StatePreparation(state)
qc.append(stateprep, [0, 1])
qc.append(stateprep.inverse(), [0, 1])
self.assertTrue(np.allclose(Operator(qc).data, np.identity(2**qc.num_qubits)))
def test_double_inverse(self):
"""Test twice inverse of StatePreparation"""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
stateprep = StatePreparation([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc.append(stateprep.inverse().inverse(), [0, 1])
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_incompatible_state_and_qubit_args(self):
"""Test error raised if number of qubits not compatible with state arg"""
qc = QuantumCircuit(3)
with self.assertRaises(QiskitError):
qc.prepare_state("11")
def test_incompatible_int_state_and_qubit_args(self):
"""Test error raised if number of qubits not compatible with integer state arg"""
# pylint: disable=pointless-statement
with self.assertRaises(QiskitError):
stateprep = StatePreparation(5, num_qubits=2)
stateprep.definition
def test_int_state_and_no_qubit_args(self):
"""Test automatic determination of qubit number"""
stateprep = StatePreparation(5)
self.assertEqual(stateprep.num_qubits, 3)
def test_repeats(self):
"""Test repeat function repeats correctly"""
qc = QuantumCircuit(2)
qc.append(StatePreparation("01").repeat(2), [0, 1])
self.assertEqual(qc.decompose().count_ops()["state_preparation"], 2)
if __name__ == "__main__":
unittest.main()
|
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/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 the converters."""
import math
import unittest
import numpy as np
from qiskit.converters import circuit_to_instruction
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit, Instruction
from qiskit.circuit import Parameter
from qiskit.quantum_info import Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
class TestCircuitToInstruction(QiskitTestCase):
"""Test Circuit to Instruction."""
def test_flatten_circuit_registers(self):
"""Check correct flattening"""
qr1 = QuantumRegister(4, "qr1")
qr2 = QuantumRegister(3, "qr2")
qr3 = QuantumRegister(3, "qr3")
cr1 = ClassicalRegister(4, "cr1")
cr2 = ClassicalRegister(1, "cr2")
circ = QuantumCircuit(qr1, qr2, qr3, cr1, cr2)
circ.cx(qr1[1], qr2[2])
circ.measure(qr3[0], cr2[0])
inst = circuit_to_instruction(circ)
q = QuantumRegister(10, "q")
c = ClassicalRegister(5, "c")
self.assertEqual(inst.definition[0].qubits, (q[1], q[6]))
self.assertEqual(inst.definition[1].qubits, (q[7],))
self.assertEqual(inst.definition[1].clbits, (c[4],))
def test_flatten_registers_of_circuit_single_bit_cond(self):
"""Check correct mapping of registers gates conditioned on single classical bits."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(3, "qr2")
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
circ = QuantumCircuit(qr1, qr2, cr1, cr2)
circ.h(qr1[0]).c_if(cr1[1], True)
circ.h(qr2[1]).c_if(cr2[0], False)
circ.cx(qr1[1], qr2[2]).c_if(cr2[2], True)
circ.measure(qr2[2], cr2[0])
inst = circuit_to_instruction(circ)
q = QuantumRegister(5, "q")
c = ClassicalRegister(6, "c")
self.assertEqual(inst.definition[0].qubits, (q[0],))
self.assertEqual(inst.definition[1].qubits, (q[3],))
self.assertEqual(inst.definition[2].qubits, (q[1], q[4]))
self.assertEqual(inst.definition[0].operation.condition, (c[1], True))
self.assertEqual(inst.definition[1].operation.condition, (c[3], False))
self.assertEqual(inst.definition[2].operation.condition, (c[5], True))
def test_flatten_circuit_registerless(self):
"""Test that the conversion works when the given circuit has bits that are not contained in
any register."""
qr1 = QuantumRegister(2)
qubits = [Qubit(), Qubit(), Qubit()]
qr2 = QuantumRegister(3)
cr1 = ClassicalRegister(2)
clbits = [Clbit(), Clbit(), Clbit()]
cr2 = ClassicalRegister(3)
circ = QuantumCircuit(qr1, qubits, qr2, cr1, clbits, cr2)
circ.cx(3, 5)
circ.measure(4, 4)
inst = circuit_to_instruction(circ)
self.assertEqual(inst.num_qubits, len(qr1) + len(qubits) + len(qr2))
self.assertEqual(inst.num_clbits, len(cr1) + len(clbits) + len(cr2))
inst_definition = inst.definition
cx = inst_definition.data[0]
measure = inst_definition.data[1]
self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
self.assertEqual(measure.clbits, (inst_definition.clbits[4],))
def test_flatten_circuit_overlapping_registers(self):
"""Test that the conversion works when the given circuit has bits that are contained in more
than one register."""
qubits = [Qubit() for _ in [None] * 10]
qr1 = QuantumRegister(bits=qubits[:6])
qr2 = QuantumRegister(bits=qubits[4:])
clbits = [Clbit() for _ in [None] * 10]
cr1 = ClassicalRegister(bits=clbits[:6])
cr2 = ClassicalRegister(bits=clbits[4:])
circ = QuantumCircuit(qubits, clbits, qr1, qr2, cr1, cr2)
circ.cx(3, 5)
circ.measure(4, 4)
inst = circuit_to_instruction(circ)
self.assertEqual(inst.num_qubits, len(qubits))
self.assertEqual(inst.num_clbits, len(clbits))
inst_definition = inst.definition
cx = inst_definition.data[0]
measure = inst_definition.data[1]
self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
self.assertEqual(cx.clbits, ())
self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
self.assertEqual(measure.clbits, (inst_definition.clbits[4],))
def test_flatten_parameters(self):
"""Verify parameters from circuit are moved to instruction.params"""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
inst = circuit_to_instruction(qc)
self.assertEqual(inst.params, [phi, theta])
self.assertEqual(inst.definition[0].operation.params, [theta])
self.assertEqual(inst.definition[1].operation.params, [phi])
self.assertEqual(inst.definition[2].operation.params, [theta, phi, 0])
self.assertEqual(str(inst.definition[3].operation.params[0]), "phi + theta")
def test_underspecified_parameter_map_raises(self):
"""Verify we raise if not all circuit parameters are present in parameter_map."""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
gamma = Parameter("gamma")
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
self.assertRaises(QiskitError, circuit_to_instruction, qc, {theta: gamma})
# Raise if provided more parameters than present in the circuit
delta = Parameter("delta")
self.assertRaises(
QiskitError, circuit_to_instruction, qc, {theta: gamma, phi: phi, delta: delta}
)
def test_parameter_map(self):
"""Verify alternate parameter specification"""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
gamma = Parameter("gamma")
qc.rz(theta, qr[0])
qc.rz(phi, qr[1])
qc.u(theta, phi, 0, qr[2])
qc.rz(sum_, qr[0])
inst = circuit_to_instruction(qc, {theta: gamma, phi: phi})
self.assertEqual(inst.params, [gamma, phi])
self.assertEqual(inst.definition[0].operation.params, [gamma])
self.assertEqual(inst.definition[1].operation.params, [phi])
self.assertEqual(inst.definition[2].operation.params, [gamma, phi, 0])
self.assertEqual(str(inst.definition[3].operation.params[0]), "gamma + phi")
def test_registerless_classical_bits(self):
"""Test that conditions on registerless classical bits can be handled during the conversion.
Regression test of gh-7394."""
expected = QuantumCircuit([Qubit(), Clbit()])
expected.h(0).c_if(expected.clbits[0], 0)
test = circuit_to_instruction(expected)
self.assertIsInstance(test, Instruction)
self.assertIsInstance(test.definition, QuantumCircuit)
self.assertEqual(len(test.definition.data), 1)
test_instruction = test.definition.data[0]
expected_instruction = expected.data[0]
self.assertIs(type(test_instruction.operation), type(expected_instruction.operation))
self.assertEqual(test_instruction.operation.condition, (test.definition.clbits[0], 0))
def test_zero_operands(self):
"""Test that an instruction can be created, even if it has zero operands."""
base = QuantumCircuit(global_phase=math.pi)
instruction = base.to_instruction()
self.assertEqual(instruction.num_qubits, 0)
self.assertEqual(instruction.num_clbits, 0)
self.assertEqual(instruction.definition, base)
compound = QuantumCircuit(1)
compound.append(instruction, [], [])
np.testing.assert_allclose(-np.eye(2), Operator(compound), atol=1e-16)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
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.
"""Test the EnlargeWithAncilla pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import Layout
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestEnlargeWithAncilla(QiskitTestCase):
"""Tests the EnlargeWithAncilla pass."""
def setUp(self):
super().setUp()
self.qr3 = QuantumRegister(3, "qr")
circuit = QuantumCircuit(self.qr3)
circuit.h(self.qr3)
self.dag = circuit_to_dag(circuit)
def test_no_extension(self):
"""There are no virtual qubits to extend."""
layout = Layout({self.qr3[0]: 0, self.qr3[1]: 1, self.qr3[2]: 2})
pass_ = EnlargeWithAncilla()
pass_.property_set["layout"] = layout
after = pass_.run(self.dag)
qregs = list(after.qregs.values())
self.assertEqual(1, len(qregs))
self.assertEqual(self.qr3, qregs[0])
def test_with_extension(self):
"""There are 2 virtual qubit to extend."""
ancilla = QuantumRegister(2, "ancilla")
layout = Layout(
{0: self.qr3[0], 1: ancilla[0], 2: self.qr3[1], 3: ancilla[1], 4: self.qr3[2]}
)
layout.add_register(ancilla)
pass_ = EnlargeWithAncilla()
pass_.property_set["layout"] = layout
after = pass_.run(self.dag)
qregs = list(after.qregs.values())
self.assertEqual(2, len(qregs))
self.assertEqual(self.qr3, qregs[0])
self.assertEqual(ancilla, qregs[1])
if __name__ == "__main__":
unittest.main()
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
# 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
%matplotlib inline
b = '111'
n = len(b)
simon_circuit = QuantumCircuit(n*2, n)
# Apply Hadamard gates before querying the oracle
simon_circuit.h(range(n))
# Apply barrier for visual separation
simon_circuit.barrier()
simon_circuit += simon_oracle(b)
# Apply barrier for visual separation
simon_circuit.barrier()
# Apply Hadamard gates to the input register
simon_circuit.h(range(n))
# Measure qubits
simon_circuit.measure(range(n), range(n))
simon_circuit.draw()
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(simon_circuit, backend=backend, shots=shots).result()
counts = results.get_counts()
plot_histogram(counts)
print(counts)
# Calculate the dot product of the results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
for z in counts:
print( '{}.{} = {} (mod 2)'.format(b, z, bdotz(b,z)) )
b = '10'
n = len(b)
simon_circuit_2 = QuantumCircuit(n*2, n)
# Apply Hadamard gates before querying the oracle
simon_circuit_2.h(range(n))
# Apply barrier for visual separation
simon_circuit_2.barrier()
# Query oracle
simon_circuit_2 += simon_oracle(b)
# Apply barrier for visual separation
simon_circuit_2.barrier()
# Apply Hadamard gates to the input register
simon_circuit_2.h(range(n))
# Measure qubits
simon_circuit_2.measure(range(n), range(n))
simon_circuit_2.draw()
# 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')
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)
# Calculate the dot product of the 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))
|
https://github.com/geduardo/Q-Snake-Qiskitcamp-Europe-2019
|
geduardo
|
import numpy as np
from qiskit import *
def Qand(First_bool,Second_bool):
#input two booleans into the function
a = int(First_bool)
b = int(Second_bool)
#quantum circuit that applies a Toffoli gate
q = QuantumRegister(3)
qc = QuantumCircuit(q)
if a is 1:
qc.x(0)
if b is 1:
qc.x(1)
qc.ccx(q[0], q[1], q[2])
# Code for giving a True if the 3rd qubit is 1 and False if the 3rd qubit is 0
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=8)
Q_and = bool(int(np.real(outputstate[7])))
return Q_and
def Qor(First_bool,Second_bool):
#input two booleans into the function
a = int(First_bool)
b = int(Second_bool)
#quantum circuit that applies a Toffoli gate
q = QuantumRegister(3)
qc = QuantumCircuit(q)
if a is 1:
qc.x(0)
if b is 1:
qc.x(1)
qc.ccx(q[0], q[1], q[2])
# Code for giving a True at least one of the two control qubits are in state 1
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend)
result = job.result()
outputstate = result.get_statevector(qc, decimals=8)
if a is 1 and b is 0:
Q_or = bool(int(np.real(outputstate[1])))
elif a is 0 and b is 1:
Q_or = bool(int(np.real(outputstate[2])))
else:
Q_or = bool(int(np.real(outputstate[7])))
return(Q_or)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
from matplotlib.pyplot import plot, figure, arrow, Circle, gca, text, bar
figure(figsize=(6,6), dpi=60)
#The higher dpi value makes the figure bigger.
plot(1,5,'bo')
arrow(0.5,0.5,0.1,0.1,head_width=0.04,head_length=0.08,color="blue")
arrow(0,0,1.1,0,head_width=0.04,head_length=0.08)
arrow(0,0,-1.1,0,head_width=0.04,head_length=0.08)
arrow(0,0,0,-1.1,head_width=0.04,head_length=0.08)
arrow(0,0,0,1.1,head_width=0.04,head_length=0.08)
gca().add_patch( Circle((0.5,0.5),0.2,color='black',fill=False) )
%run qlatvia.py
import matplotlib
def draw_axes():
# dummy points for zooming out
points = [ [1.3,0], [0,1.3], [-1.3,0], [0,-1.3] ]
# coordinates for the axes
arrows = [ [1.1,0], [0,1.1], [-1.1,0], [0,-1.1] ]
# drawing dummy points
for p in points: matplotlib.pyplot.plot(p[0],p[1]+0.2)
# drawing the axes
for a in arrows: matplotlib.pyplot.arrow(0,0,a[0],a[1],head_width=0.04, head_length=0.08)
draw_axes()
import matplotlib
def draw_unit_circle():
unit_circle= matplotlib.pyplot.Circle((0.2,0.2),0.2,color='black',fill=False)
matplotlib.pyplot.gca().add_patch(unit_circle)
draw_unit_circle()
import matplotlib
def draw_quantum_state(x,y):
# shorten the line length to 0.92
# line_length + head_length should be 1
x1 = 0.92 * x
y1 = 0.92 * y
matplotlib.pyplot.arrow(0,0,x1,y1,head_width=0.04,head_length=0.08,color="blue")
x2 = 1.15 * x
y2 = 1.15 * y
matplotlib.pyplot.text(x2,y2,arrow)
draw_quantum_state(1,1)
import matplotlib
def draw_qubit():
# draw a figure
matplotlib.pyplot.figure(figsize=(6,6), dpi=60)
# draw the origin
matplotlib.pyplot.plot(0,0,'ro') # a point in red color
# drawing the axes by using one of our predefined functions
draw_axes()
# drawing the unit circle by using one of our predefined functions
draw_unit_circle()
# drawing |0>
matplotlib.pyplot.plot(1,0,"o")
matplotlib.pyplot.text(1.05,0.05,"|0>")
# drawing |1>
matplotlib.pyplot.plot(0,1,"o")
matplotlib.pyplot.text(0.05,1.05,"|1>")
# drawing -|0>
matplotlib.pyplot.plot(-1,0,"o")
matplotlib.pyplot.text(-1.2,-0.1,"-|0>")
# drawing -|1>
matplotlib.pyplot.plot(0,-1,"o")
matplotlib.pyplot.text(-0.2,-1.1,"-|1>")
draw_qubit()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
import random
circ = QuantumCircuit(40, 40)
# Initialize with a Hadamard layer
circ.h(range(40))
# Apply some random CNOT and T gates
qubit_indices = [i for i in range(40)]
for i in range(10):
control, target, t = random.sample(qubit_indices, 3)
circ.cx(control, target)
circ.t(t)
circ.measure(range(40), range(40))
# Create statevector method simulator
statevector_simulator = AerSimulator(method='statevector')
# Transpile circuit for backend
tcirc = transpile(circ, statevector_simulator)
# Try and run circuit
statevector_result = statevector_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(statevector_result.success))
print('Why not? {}'.format(statevector_result.status))
# Create extended stabilizer method simulator
extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer')
# Transpile circuit for backend
tcirc = transpile(circ, extended_stabilizer_simulator)
extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(extended_stabilizer_result.success))
small_circ = QuantumCircuit(2, 2)
small_circ.h(0)
small_circ.cx(0, 1)
small_circ.t(0)
small_circ.measure([0, 1], [0, 1])
# This circuit should give 00 or 11 with equal probability...
expected_results ={'00': 50, '11': 50}
tsmall_circ = transpile(small_circ, extended_stabilizer_simulator)
result = extended_stabilizer_simulator.run(
tsmall_circ, shots=100).result()
counts = result.get_counts(0)
print('100 shots in {}s'.format(result.time_taken))
plot_histogram([expected_results, counts],
legend=['Expected', 'Extended Stabilizer'])
# Add runtime options for extended stabilizer simulator
opts = {'extended_stabilizer_approximation_error': 0.03}
reduced_error = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
reduced_error_counts = reduced_error.get_counts(0)
print('100 shots in {}s'.format(reduced_error.time_taken))
plot_histogram([expected_results, reduced_error_counts],
legend=['Expected', 'Extended Stabilizer'])
print("The circuit above, with 100 shots at precision 0.03 "
"and default mixing time, needed {}s".format(int(reduced_error.time_taken)))
opts = {
'extended_stabilizer_approximation_error': 0.03,
'extended_stabilizer_mixing_time': 100
}
optimized = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken))
# We set these options here only to make the example run more quickly.
opts = {'extended_stabilizer_mixing_time': 100}
multishot = extended_stabilizer_simulator.run(
tcirc, shots=100, **opts).result()
print("100 shots took {} s".format(multishot.time_taken))
opts = {
'extended_stabilizer_measure_sampling': True,
'extended_stabilizer_mixing_time': 100
}
measure_sampling = extended_stabilizer_simulator.run(
circ, shots=100, **opts).result()
print("With the optimization, 100 shots took {} s".format(result.time_taken))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import json
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import ZFeatureMap
from qiskit.quantum_info import SparsePauliOp
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
from qiskit_machine_learning.neural_networks import EstimatorQNN
from sklearn.model_selection import train_test_split
algorithm_globals.random_seed = 12345
# We now define a two qubit unitary as defined in [3]
def conv_circuit(params):
target = QuantumCircuit(2)
target.rz(-np.pi / 2, 1)
target.cx(1, 0)
target.rz(params[0], 0)
target.ry(params[1], 1)
target.cx(0, 1)
target.ry(params[2], 1)
target.cx(1, 0)
target.rz(np.pi / 2, 0)
return target
# Let's draw this circuit and see what it looks like
params = ParameterVector("θ", length=3)
circuit = conv_circuit(params)
circuit.draw("mpl")
def conv_layer(num_qubits, param_prefix):
qc = QuantumCircuit(num_qubits, name="Convolutional Layer")
qubits = list(range(num_qubits))
param_index = 0
params = ParameterVector(param_prefix, length=num_qubits * 3)
for q1, q2 in zip(qubits[0::2], qubits[1::2]):
qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2])
qc.barrier()
param_index += 3
for q1, q2 in zip(qubits[1::2], qubits[2::2] + [0]):
qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2])
qc.barrier()
param_index += 3
qc_inst = qc.to_instruction()
qc = QuantumCircuit(num_qubits)
qc.append(qc_inst, qubits)
return qc
circuit = conv_layer(4, "θ")
circuit.decompose().draw("mpl")
def pool_circuit(params):
target = QuantumCircuit(2)
target.rz(-np.pi / 2, 1)
target.cx(1, 0)
target.rz(params[0], 0)
target.ry(params[1], 1)
target.cx(0, 1)
target.ry(params[2], 1)
return target
params = ParameterVector("θ", length=3)
circuit = pool_circuit(params)
circuit.draw("mpl")
def pool_layer(sources, sinks, param_prefix):
num_qubits = len(sources) + len(sinks)
qc = QuantumCircuit(num_qubits, name="Pooling Layer")
param_index = 0
params = ParameterVector(param_prefix, length=num_qubits // 2 * 3)
for source, sink in zip(sources, sinks):
qc = qc.compose(pool_circuit(params[param_index : (param_index + 3)]), [source, sink])
qc.barrier()
param_index += 3
qc_inst = qc.to_instruction()
qc = QuantumCircuit(num_qubits)
qc.append(qc_inst, range(num_qubits))
return qc
sources = [0, 1]
sinks = [2, 3]
circuit = pool_layer(sources, sinks, "θ")
circuit.decompose().draw("mpl")
def generate_dataset(num_images):
images = []
labels = []
hor_array = np.zeros((6, 8))
ver_array = np.zeros((4, 8))
j = 0
for i in range(0, 7):
if i != 3:
hor_array[j][i] = np.pi / 2
hor_array[j][i + 1] = np.pi / 2
j += 1
j = 0
for i in range(0, 4):
ver_array[j][i] = np.pi / 2
ver_array[j][i + 4] = np.pi / 2
j += 1
for n in range(num_images):
rng = algorithm_globals.random.integers(0, 2)
if rng == 0:
labels.append(-1)
random_image = algorithm_globals.random.integers(0, 6)
images.append(np.array(hor_array[random_image]))
elif rng == 1:
labels.append(1)
random_image = algorithm_globals.random.integers(0, 4)
images.append(np.array(ver_array[random_image]))
# Create noise
for i in range(8):
if images[-1][i] == 0:
images[-1][i] = algorithm_globals.random.uniform(0, np.pi / 4)
return images, labels
images, labels = generate_dataset(50)
train_images, test_images, train_labels, test_labels = train_test_split(
images, labels, test_size=0.3
)
fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []})
for i in range(4):
ax[i // 2, i % 2].imshow(
train_images[i].reshape(2, 4), # Change back to 2 by 4
aspect="equal",
)
plt.subplots_adjust(wspace=0.1, hspace=0.025)
feature_map = ZFeatureMap(8)
feature_map.decompose().draw("mpl")
feature_map = ZFeatureMap(8)
ansatz = QuantumCircuit(8, name="Ansatz")
# First Convolutional Layer
ansatz.compose(conv_layer(8, "с1"), list(range(8)), inplace=True)
# First Pooling Layer
ansatz.compose(pool_layer([0, 1, 2, 3], [4, 5, 6, 7], "p1"), list(range(8)), inplace=True)
# Second Convolutional Layer
ansatz.compose(conv_layer(4, "c2"), list(range(4, 8)), inplace=True)
# Second Pooling Layer
ansatz.compose(pool_layer([0, 1], [2, 3], "p2"), list(range(4, 8)), inplace=True)
# Third Convolutional Layer
ansatz.compose(conv_layer(2, "c3"), list(range(6, 8)), inplace=True)
# Third Pooling Layer
ansatz.compose(pool_layer([0], [1], "p3"), list(range(6, 8)), inplace=True)
# Combining the feature map and ansatz
circuit = QuantumCircuit(8)
circuit.compose(feature_map, range(8), inplace=True)
circuit.compose(ansatz, range(8), inplace=True)
observable = SparsePauliOp.from_list([("Z" + "I" * 7, 1)])
# we decompose the circuit for the QNN to avoid additional data copying
qnn = EstimatorQNN(
circuit=circuit.decompose(),
observables=observable,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
)
circuit.draw("mpl")
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()
with open("11_qcnn_initial_point.json", "r") as f:
initial_point = json.load(f)
classifier = NeuralNetworkClassifier(
qnn,
optimizer=COBYLA(maxiter=200), # Set max iterations here
callback=callback_graph,
initial_point=initial_point,
)
x = np.asarray(train_images)
y = np.asarray(train_labels)
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
classifier.fit(x, y)
# score classifier
print(f"Accuracy from the train data : {np.round(100 * classifier.score(x, y), 2)}%")
y_predict = classifier.predict(test_images)
x = np.asarray(test_images)
y = np.asarray(test_labels)
print(f"Accuracy from the test data : {np.round(100 * classifier.score(x, y), 2)}%")
# Let's see some examples in our dataset
fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []})
for i in range(0, 4):
ax[i // 2, i % 2].imshow(test_images[i].reshape(2, 4), aspect="equal")
if y_predict[i] == -1:
ax[i // 2, i % 2].set_title("The QCNN predicts this is a Horizontal Line")
if y_predict[i] == +1:
ax[i // 2, i % 2].set_title("The QCNN predicts this is a Vertical Line")
plt.subplots_adjust(wspace=0.1, hspace=0.5)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
from ibm_quantum_widgets import draw_circuit
circuit = QuantumCircuit(2,2)
circuit
circuit.draw(output='mpl')
circuit.x(0)
circuit.draw(output='mpl')
circuit.h(0)
circuit.draw(output='mpl')
circuit.cx(0,1)
circuit.draw(output='mpl')
circuit.measure([0,1],[1,1])
circuit.draw(output='mpl')
draw_circuit(circuit)
simulator = Aer.get_backend('qasm_simulator')
simulator
job = execute(circuit, backend=simulator, shots=1024)
job
result = job.result()
result
counts = result.get_counts()
counts
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import COBYLA
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE
from qiskit.primitives import Sampler
from qiskit_optimization.converters import LinearEqualityToPenalty
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from qiskit.utils import algorithm_globals
import numpy as np
import matplotlib.pyplot as plt
from docplex.mp.model import Model
algorithm_globals.random_seed = 123456
# prepare problem instance
n = 6 # number of assets
q = 0.5 # risk factor
budget = n // 2 # budget
penalty = 2 * n # scaling of penalty term
# instance from [1]
mu = np.array([0.7313, 0.9893, 0.2725, 0.8750, 0.7667, 0.3622])
sigma = np.array(
[
[0.7312, -0.6233, 0.4689, -0.5452, -0.0082, -0.3809],
[-0.6233, 2.4732, -0.7538, 2.4659, -0.0733, 0.8945],
[0.4689, -0.7538, 1.1543, -1.4095, 0.0007, -0.4301],
[-0.5452, 2.4659, -1.4095, 3.5067, 0.2012, 1.0922],
[-0.0082, -0.0733, 0.0007, 0.2012, 0.6231, 0.1509],
[-0.3809, 0.8945, -0.4301, 1.0922, 0.1509, 0.8992],
]
)
# or create random instance
# mu, sigma = portfolio.random_model(n, seed=123) # expected returns and covariance matrix
# create docplex model
mdl = Model("portfolio_optimization")
x = mdl.binary_var_list(range(n), name="x")
objective = mdl.sum([mu[i] * x[i] for i in range(n)])
objective -= q * mdl.sum([sigma[i, j] * x[i] * x[j] for i in range(n) for j in range(n)])
mdl.maximize(objective)
mdl.add_constraint(mdl.sum(x[i] for i in range(n)) == budget)
# case to
qp = from_docplex_mp(mdl)
# solve classically as reference
opt_result = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp)
print(opt_result.prettyprint())
# we convert the problem to an unconstrained problem for further analysis,
# otherwise this would not be necessary as the MinimumEigenSolver would do this
# translation automatically
linear2penalty = LinearEqualityToPenalty(penalty=penalty)
qp = linear2penalty.convert(qp)
_, offset = qp.to_ising()
# set classical optimizer
maxiter = 100
optimizer = COBYLA(maxiter=maxiter)
# set variational ansatz
ansatz = RealAmplitudes(n, reps=1)
m = ansatz.num_parameters
# set sampler
sampler = Sampler()
# run variational optimization for different values of alpha
alphas = [1.0, 0.50, 0.25] # confidence levels to be evaluated
# dictionaries to store optimization progress and results
objectives = {alpha: [] for alpha in alphas} # set of tested objective functions w.r.t. alpha
results = {} # results of minimum eigensolver w.r.t alpha
# callback to store intermediate results
def callback(i, params, obj, stddev, alpha):
# we translate the objective from the internal Ising representation
# to the original optimization problem
objectives[alpha].append(np.real_if_close(-(obj + offset)))
# loop over all given alpha values
for alpha in alphas:
# initialize SamplingVQE using CVaR
vqe = SamplingVQE(
sampler=sampler,
ansatz=ansatz,
optimizer=optimizer,
aggregation=alpha,
callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha),
)
# initialize optimization algorithm based on CVaR-SamplingVQE
opt_alg = MinimumEigenOptimizer(vqe)
# solve problem
results[alpha] = opt_alg.solve(qp)
# print results
print("alpha = {}:".format(alpha))
print(results[alpha].prettyprint())
print()
# plot resulting history of objective values
plt.figure(figsize=(10, 5))
plt.plot([0, maxiter], [opt_result.fval, opt_result.fval], "r--", linewidth=2, label="optimum")
for alpha in alphas:
plt.plot(objectives[alpha], label="alpha = %.2f" % alpha, linewidth=2)
plt.legend(loc="lower right", fontsize=14)
plt.xlim(0, maxiter)
plt.xticks(fontsize=14)
plt.xlabel("iterations", fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel("objective value", fontsize=14)
plt.show()
# evaluate and sort all objective values
objective_values = np.zeros(2**n)
for i in range(2**n):
x_bin = ("{0:0%sb}" % n).format(i)
x = [0 if x_ == "0" else 1 for x_ in reversed(x_bin)]
objective_values[i] = qp.objective.evaluate(x)
ind = np.argsort(objective_values)
# evaluate final optimal probability for each alpha
for alpha in alphas:
probabilities = np.fromiter(
results[alpha].min_eigen_solver_result.eigenstate.binary_probabilities().values(),
dtype=float,
)
print("optimal probability (alpha = %.2f): %.4f" % (alpha, probabilities[ind][-1:]))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
circuit = QuantumCircuit(3,3)
circuit
# qiskit.__dir__()
circuit.draw(output='mpl')
circuit.x(0)
circuit.barrier()
circuit.draw(output='mpl')
circuit.h(1)
circuit.cx(1,2)
circuit.draw(output='mpl')
circuit.barrier()
circuit.cx(0,1)
circuit.h(0)
circuit.draw(output='mpl')
circuit.barrier()
circuit.measure([0,1],[0,1])
circuit.draw(output='mpl')
circuit.barrier()
circuit.cx(1,2)
circuit.cx(0,2)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator,shots=1024)
result = job.result()
counts=result.get_counts()
print(counts)
plot_histogram(counts)
|
https://github.com/CQCL/pytket-qiskit
|
CQCL
|
# -*- 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/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
from qiskit import *
nshots = 8192
IBMQ.load_account()
provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
device = provider.get_backend('ibmq_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/JavaFXpert/qiskit4devs-workshop-notebooks
|
JavaFXpert
|
#!pip install qiskit
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Create a Quantum Register with 1 qubit (wire).
qr = QuantumRegister(1)
# Create a Classical Register with 1 bit (double wire).
cr = ClassicalRegister(1)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place an X gate on the qubit wire. The registers are zero-indexed.
circ.x(qr[0])
# Measure the qubit into the classical register
circ.measure(qr, cr)
# Draw the circuit
circ.draw(output='mpl')
# Import BasicAer
from qiskit import BasicAer
# Use BasicAer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 100 times.
job_sim = execute(circ, backend_sim, shots=100)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
from qiskit.tools.visualization import plot_histogram
# Plot the results on a bar chart
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 1 qubit (wire).
# Create a Classical Register with 1 bit (double wire).
# Create a Quantum Circuit from the quantum and classical registers
# Place two X gates on the qubit wire. The registers are zero-indexed.
# Measure the qubit into the classical register
# Draw the circuit
# Import BasicAer
# Use BasicAer's qasm_simulator
# Execute the circuit on the qasm simulator, running it 100 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a bar chart
|
https://github.com/apozas/qaoa-color
|
apozas
|
#!/usr/bin/env python
# coding: utf-8
# In[65]:
# useful additional packages
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import numpy as np
import time
from pprint import pprint
# importing Qiskit
from qiskit import Aer, IBMQ
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
# In[72]:
"Choice of the backend"
# using local qasm simulator
backend = Aer.get_backend('qasm_simulator')
# using IBMQ qasm simulator
# backend = IBMQ.get_backend('ibmq_qasm_simulator')
# using real device
# backend = least_busy(IBMQ.backends(simulator=False))
flag_qx2 = True
if backend.name() == 'ibmqx4':
flag_qx2 = False
print("Your choice for the backend is: ", backend, "flag_qx2 is: ", flag_qx2)
# In[73]:
# Here, two useful routine
# Define a F_gate
def G_gate(circ, p, q , i, j) :
theta = np.arctan(np.sqrt(p/(1-p)))
circ.ry(theta,q[j])
circ.cx(q[i],q[j])
circ.ry(-theta,q[j])
#circ.cx(q[i],q[j])
circ.barrier(q[i])
# Define the cxrv gate which uses reverse CNOT instead of CNOT
def cxrv(circ,q,i,j) :
circ.h(q[i])
circ.h(q[j])
circ.cx(q[j],q[i])
circ.h(q[i])
circ.h(q[j])
circ.barrier(q[i],q[j])
# In[78]:
# 3-qubit W state
n = 8
q = QuantumRegister(n)
c = ClassicalRegister(n)
W_states = QuantumCircuit(q,c)
W_states.x(q[n-1]) #start is |100>
# In[79]:
for i in range(1,n) :
p=1/(n+1-i)
print(n-i, n-i-1, p)
print(p/(1-p))
print(np.arctan(np.sqrt(p/(1-p)))*180/3.14)
G_gate(W_states, p, q, n-i, n-i-1)
W_states.cx(q[n-i-1], q[n-i])
# In[80]:
for i in range(n) :
W_states.measure(q[i] , c[i])
shots = 10000
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print('start W state 3-qubit on', backend, "N=", shots,time_exp)
result = execute(W_states, backend=backend, shots=shots)
time_exp = time.strftime('%d/%m/%Y %H:%M:%S')
print('end W state 3-qubit on', backend, "N=", shots,time_exp)
W_states.draw(output="mpl")
plot_histogram(result.result().get_counts(W_states))
# In[81]:
# In[ ]:
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
import qiskit_chemistry
# An example of using a loop to vary inter-atomic distance. A dictionary is
# created outside the loop, but inside the loop the 'atom' value is updated
# with a new molecular configuration. The molecule is H2 and its inter-atomic distance
# i.e the distance between the two atoms, is altered from 0.5 to 1.0. Each atom is
# specified by x, y, z coords and the atoms are set on the z-axis, equidistant from
# the origin, and updated by d inside the loop where the molecule string has this value
# substituted by format(). Note the negative sign preceding the first format
# substitution point i.e. the {} brackets
#
input_dict = {
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': None, 'unit': 'Angstrom', 'charge': 0, 'spin': 0, 'basis': 'sto3g'},
'algorithm': {'name': 'ExactEigensolver'},
}
molecule = 'H .0 .0 -{0}; H .0 .0 {0}'
for i in range(21):
d = (0.5 + i * 0.5 / 20) / 2
input_dict['PYSCF']['atom'] = molecule.format(d)
solver = qiskit_chemistry.QiskitChemistry()
result = solver.run(input_dict)
print('{:.4f} : {}'.format(d * 2, result['energy']))
|
https://github.com/wyqian1027/Qiskit-Fall-Fest-USC-2022
|
wyqian1027
|
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_bloch_multivector, array_to_latex
from grader import *
language(False)
phi_plus = QuantumCircuit(2)
phi_plus.h(0)
phi_plus.cnot(0, 1)
phi_plus.draw('mpl')
# Let's see the result
backend = Aer.get_backend('statevector_simulator')
result = execute(phi_plus, backend).result().get_statevector()
array_to_latex(result)
phi_minus = QuantumCircuit(2)
##### ==================================
# Write your solution in here.
##### ==================================
phi_minus.draw('mpl')
# This cell will tell you if what you did gives the correct result.
# Just take it as an indication, the tests do not take into consideration every possible option
# If you think that your answer is (in)correct and the grader says different, just ask me please
# Don't try to tamper with the code, please :)
ex1_grader(phi_minus)
psi_plus = QuantumCircuit(2)
##### ==================================
# Write your solution in here.
##### ==================================
psi_plus.draw('mpl')
ex2_grader(psi_plus)
psi_minus = QuantumCircuit(2)
##### ==================================
# Write your solution in here.
##### ==================================
psi_minus.draw('mpl')
ex3_grader(psi_minus)
GHZ = QuantumCircuit(3)
##### ==================================
# Write your solution in here.
##### ==================================
GHZ.draw('mpl')
ex4_grader(GHZ)
Even = QuantumCircuit(3)
##### ==================================
# Write your solution in here.
##### ==================================
Even.draw('mpl')
ex5_grader(Even)
Odd = QuantumCircuit(3)
##### ==================================
# Write your solution in here.
##### ==================================
Odd.draw('mpl')
ex6_grader(Odd)
def measure_z_axis(qc, qubit, cbit): #Measurements have to be saved in classical bits
qc.measure(qubit, cbit)
def measure_x_axis(qc, qubit, cbit):
##### ==================================
# Write your solution in here.
##### ==================================
ex7_grader(measure_x_axis)
def expectation_value_single_qubit(qc, nshots=8092):
# Run the given circuit that is already measuring the selected basis
backend_shots = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend_shots, shots=nshots).result().get_counts() #Counts is a dictionary that contains the number of zeros and the number of ones measured
# This is just to make things easier in your solution
if '1' not in counts.keys():
counts['1'] = 0
if '0' not in counts.keys():
counts['0'] = 0
# Get the number of times that 0 and 1 were measured
n_zeros = counts['0']
n_ones = counts['1']
# Compute the probabilities
p_0 = n_zeros/nshots
p_1 = n_ones/nshots #OR 1-p_0
expectation_value = 1*p_0+(-1)*p_1
return expectation_value
# Measure <Z> over a state that you like
qc_z = QuantumCircuit(1,1)
measure_z_axis(qc_z, 0, 0)
print('<Z>=', expectation_value_single_qubit(qc_z))
qc_z.draw('mpl')
# Measure <X> over a state that you like
qc_x = QuantumCircuit(1,1)
measure_x_axis(qc_x, 0, 0)
print('<X>=', expectation_value_single_qubit(qc_x))
qc_x.draw('mpl')
##### ==================================
# Write your solution in here.
# Create bell state circuit
# For each of the operators that we want to measure (ZZ, ZX, XZ and XX) create a new circuit (maybe using qc.copy())
# that measures along that axis.
chsh_circuits = []
##### ==================================
chsh_circuits[0].draw('mpl')
chsh_circuits[1].draw('mpl')
chsh_circuits[2].draw('mpl')
chsh_circuits[3].draw('mpl')
# I couldn't come up with tests that would not give the answer away if you looked at the code so you are on your own here!
# We can run all the circuits at the same time and then post process the data
nshots = 8092 # The more shots, the less error
backend_shots = Aer.get_backend('qasm_simulator')
counts_list = execute(chsh_circuits, backend_shots, shots=nshots).result().get_counts()
counts_list
##### ==================================
# Write your solution in here.
# For each of the circuits, take the counts that you got from that circuit, compute the probability
# of each state and combine them together being very careful of which sign goes with which term
# You might want to take some inspiration from the function expectation_value_single_qubit
# If you are completely lost and don't know how to solve this, just ask
##### ==================================
# If you don't know if your answer is correct you can compute the results by hand
# (it's probably easier than doing this) and check if everything is working
##### ==================================
# Write your solution in here.
exp_AB =
exp_Ab =
exp_aB =
exp_ab =
CHSH =
##### ==================================
print('Your result is <CHSH>=', CHSH)
print('The correct result is <CHSH>=', 2*np.sqrt(2))
##### ==================================
# Write your solution in here.
Can_entanglement_be_teleported = #Write True or False :D
##### ==================================
# There is no grader for this question hehe
##### ==================================
# Write your solution in here.
Where_did_the_bell_pair_go = 'Write where you think they went'
##### ==================================
# There is no grader for this question hehe
##### ==================================
# Write your solution in here.
##### ==================================
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test TrotterQRTE."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import ddt, data, unpack
import numpy as np
from scipy.linalg import expm
from numpy.testing import assert_raises
from qiskit_algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE
from qiskit.primitives import Estimator
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZGate
from qiskit.quantum_info import Statevector, Pauli, SparsePauliOp
from qiskit.utils import algorithm_globals
from qiskit.circuit import Parameter
from qiskit.opflow import PauliSumOp, X, MatrixOp
from qiskit.synthesis import SuzukiTrotter, QDrift
@ddt
class TestTrotterQRTE(QiskitAlgorithmsTestCase):
"""TrotterQRTE tests."""
def setUp(self):
super().setUp()
self.seed = 50
algorithm_globals.random_seed = self.seed
@data(
(
None,
Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j]),
),
(
SuzukiTrotter(),
Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j]),
),
)
@unpack
def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state):
"""Test for default TrotterQRTE on a single qubit."""
with self.assertWarns(DeprecationWarning):
operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")]))
initial_state = QuantumCircuit(1)
time = 1
evolution_problem = TimeEvolutionProblem(operator, time, initial_state)
trotter_qrte = TrotterQRTE(product_formula=product_formula)
evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state
np.testing.assert_array_almost_equal(
Statevector.from_instruction(evolution_result_state_circuit).data, expected_state.data
)
@data((SparsePauliOp(["X", "Z"]), None), (SparsePauliOp(["X", "Z"]), Parameter("t")))
@unpack
def test_trotter_qrte_trotter(self, operator, t_param):
"""Test for default TrotterQRTE on a single qubit with auxiliary operators."""
if not t_param is None:
operator = SparsePauliOp(operator.paulis, np.array([t_param, 1]))
# LieTrotter with 1 rep
aux_ops = [Pauli("X"), Pauli("Y")]
initial_state = QuantumCircuit(1)
time = 3
num_timesteps = 2
evolution_problem = TimeEvolutionProblem(
operator, time, initial_state, aux_ops, t_param=t_param
)
estimator = Estimator()
expected_psi, expected_observables_result = self._get_expected_trotter_qrte(
operator,
time,
num_timesteps,
initial_state,
aux_ops,
t_param,
)
expected_evolved_state = Statevector(expected_psi)
algorithm_globals.random_seed = 0
trotter_qrte = TrotterQRTE(estimator=estimator, num_timesteps=num_timesteps)
evolution_result = trotter_qrte.evolve(evolution_problem)
np.testing.assert_array_almost_equal(
Statevector.from_instruction(evolution_result.evolved_state).data,
expected_evolved_state.data,
)
aux_ops_result = evolution_result.aux_ops_evaluated
expected_aux_ops_result = [
(expected_observables_result[-1][0], {"variance": 0, "shots": 0}),
(expected_observables_result[-1][1], {"variance": 0, "shots": 0}),
]
means = [element[0] for element in aux_ops_result]
expected_means = [element[0] for element in expected_aux_ops_result]
np.testing.assert_array_almost_equal(means, expected_means)
vars_and_shots = [element[1] for element in aux_ops_result]
expected_vars_and_shots = [element[1] for element in expected_aux_ops_result]
observables_result = evolution_result.observables
expected_observables_result = [
[(o, {"variance": 0, "shots": 0}) for o in eor] for eor in expected_observables_result
]
means = [sub_element[0] for element in observables_result for sub_element in element]
expected_means = [
sub_element[0] for element in expected_observables_result for sub_element in element
]
np.testing.assert_array_almost_equal(means, expected_means)
for computed, expected in zip(vars_and_shots, expected_vars_and_shots):
self.assertAlmostEqual(computed.pop("variance", 0), expected["variance"], 2)
self.assertEqual(computed.pop("shots", 0), expected["shots"])
@data(
(
PauliSumOp(SparsePauliOp([Pauli("XY"), Pauli("YX")])),
Statevector([-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j]),
),
(
PauliSumOp(SparsePauliOp([Pauli("ZZ"), Pauli("ZI"), Pauli("IZ")])),
Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]),
),
(
Pauli("YY"),
Statevector([0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j]),
),
)
@unpack
def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state):
"""Test for TrotterQRTE on two qubits with various types of a Hamiltonian."""
# LieTrotter with 1 rep
initial_state = QuantumCircuit(2)
evolution_problem = TimeEvolutionProblem(operator, 1, initial_state)
trotter_qrte = TrotterQRTE()
evolution_result = trotter_qrte.evolve(evolution_problem)
np.testing.assert_array_almost_equal(
Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data
)
@data(
(QuantumCircuit(1), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j])),
(
QuantumCircuit(1).compose(ZGate(), [0]),
Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j]),
),
)
@unpack
def test_trotter_qrte_qdrift(self, initial_state, expected_state):
"""Test for TrotterQRTE with QDrift."""
with self.assertWarns(DeprecationWarning):
operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")]))
time = 1
evolution_problem = TimeEvolutionProblem(operator, time, initial_state)
algorithm_globals.random_seed = 0
trotter_qrte = TrotterQRTE(product_formula=QDrift())
evolution_result = trotter_qrte.evolve(evolution_problem)
np.testing.assert_array_almost_equal(
Statevector.from_instruction(evolution_result.evolved_state).data,
expected_state.data,
)
@data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None))
@unpack
def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict):
"""Test TrotterQRTE with raising errors for parameters."""
with self.assertWarns(DeprecationWarning):
operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(
SparsePauliOp([Pauli("Z")])
)
initial_state = QuantumCircuit(1)
self._run_error_test(initial_state, operator, None, None, t_param, param_value_dict)
@data(([Pauli("X"), Pauli("Y")], None))
@unpack
def test_trotter_qrte_trotter_aux_ops_errors(self, aux_ops, estimator):
"""Test TrotterQRTE with raising errors."""
with self.assertWarns(DeprecationWarning):
operator = PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(
SparsePauliOp([Pauli("Z")])
)
initial_state = QuantumCircuit(1)
self._run_error_test(initial_state, operator, aux_ops, estimator, None, None)
@data(
(X, QuantumCircuit(1)),
(MatrixOp([[1, 1], [0, 1]]), QuantumCircuit(1)),
(PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(SparsePauliOp([Pauli("Z")])), None),
(
SparsePauliOp([Pauli("X"), Pauli("Z")], np.array([Parameter("a"), Parameter("b")])),
QuantumCircuit(1),
),
)
@unpack
def test_trotter_qrte_trotter_hamiltonian_errors(self, operator, initial_state):
"""Test TrotterQRTE with raising errors for evolution problem content."""
self._run_error_test(initial_state, operator, None, None, None, None)
@staticmethod
def _run_error_test(initial_state, operator, aux_ops, estimator, t_param, param_value_dict):
time = 1
algorithm_globals.random_seed = 0
trotter_qrte = TrotterQRTE(estimator=estimator)
with assert_raises(ValueError):
evolution_problem = TimeEvolutionProblem(
operator,
time,
initial_state,
aux_ops,
t_param=t_param,
param_value_map=param_value_dict,
)
_ = trotter_qrte.evolve(evolution_problem)
@staticmethod
def _get_expected_trotter_qrte(operator, time, num_timesteps, init_state, observables, t_param):
"""Compute reference values for Trotter evolution via exact matrix exponentiation."""
dt = time / num_timesteps
observables = [obs.to_matrix() for obs in observables]
psi = Statevector(init_state).data
if t_param is None:
ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in operator.to_list()]
observable_results = []
observable_results.append([np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables])
for n in range(num_timesteps):
if t_param is not None:
time_value = (n + 1) * dt
bound = operator.assign_parameters([time_value])
ops = [Pauli(op).to_matrix() * np.real(coeff) for op, coeff in bound.to_list()]
for op in ops:
psi = expm(-1j * op * dt).dot(psi)
observable_results.append(
[np.real(np.conj(psi).dot(obs).dot(psi)) for obs in observables]
)
return psi, observable_results
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""
StatePreparation test.
"""
import unittest
import math
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Statevector, Operator
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
from qiskit.circuit.library import StatePreparation
@ddt
class TestStatePreparation(QiskitTestCase):
"""Test initialization with StatePreparation class"""
def test_prepare_from_label(self):
"""Prepare state from label."""
desired_sv = Statevector.from_label("01+-lr")
qc = QuantumCircuit(6)
qc.prepare_state("01+-lr", range(6))
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_from_int(self):
"""Prepare state from int."""
desired_sv = Statevector.from_label("110101")
qc = QuantumCircuit(6)
qc.prepare_state(53, range(6))
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_from_list(self):
"""Prepare state from list."""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_prepare_single_qubit(self):
"""Prepare state in single qubit."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], qreg[1])
expected = QuantumCircuit(qreg)
expected.prepare_state([1 / math.sqrt(2), 1 / math.sqrt(2)], [qreg[1]])
self.assertEqual(circuit, expected)
def test_nonzero_state_incorrect(self):
"""Test final state incorrect if initial state not zero"""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
qc.x(0)
qc.prepare_state([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
actual_sv = Statevector(qc)
self.assertFalse(desired_sv == actual_sv)
@data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
def test_inverse(self, state):
"""Test inverse of StatePreparation"""
qc = QuantumCircuit(2)
stateprep = StatePreparation(state)
qc.append(stateprep, [0, 1])
qc.append(stateprep.inverse(), [0, 1])
self.assertTrue(np.allclose(Operator(qc).data, np.identity(2**qc.num_qubits)))
def test_double_inverse(self):
"""Test twice inverse of StatePreparation"""
desired_sv = Statevector([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc = QuantumCircuit(2)
stateprep = StatePreparation([1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
qc.append(stateprep.inverse().inverse(), [0, 1])
actual_sv = Statevector(qc)
self.assertTrue(desired_sv == actual_sv)
def test_incompatible_state_and_qubit_args(self):
"""Test error raised if number of qubits not compatible with state arg"""
qc = QuantumCircuit(3)
with self.assertRaises(QiskitError):
qc.prepare_state("11")
def test_incompatible_int_state_and_qubit_args(self):
"""Test error raised if number of qubits not compatible with integer state arg"""
# pylint: disable=pointless-statement
with self.assertRaises(QiskitError):
stateprep = StatePreparation(5, num_qubits=2)
stateprep.definition
def test_int_state_and_no_qubit_args(self):
"""Test automatic determination of qubit number"""
stateprep = StatePreparation(5)
self.assertEqual(stateprep.num_qubits, 3)
def test_repeats(self):
"""Test repeat function repeats correctly"""
qc = QuantumCircuit(2)
qc.append(StatePreparation("01").repeat(2), [0, 1])
self.assertEqual(qc.decompose().count_ops()["state_preparation"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
A collection of functions that decide the layout of an output image.
See :py:mod:`~qiskit.visualization.timeline.types` for more info on the required data.
There are 2 types of layout functions in this module.
1. layout.bit_arrange
In this stylesheet entry the input data is a list of `types.Bits` and returns a
sorted list of `types.Bits`.
The function signature of the layout is restricted to:
```python
def my_layout(bits: List[types.Bits]) -> List[types.Bits]:
# your code here: sort input bits and return list of bits
```
2. layout.time_axis_map
In this stylesheet entry the input data is `Tuple[int, int]` that represents horizontal
axis limit of the output image. The layout function returns `types.HorizontalAxis` data
which is consumed by the plotter API to make horizontal axis.
The function signature of the layout is restricted to:
```python
def my_layout(time_window: Tuple[int, int]) -> types.HorizontalAxis:
# your code here: create and return axis config
```
Arbitrary layout function satisfying the above format can be accepted.
"""
import warnings
from typing import List, Tuple
import numpy as np
from qiskit import circuit
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.timeline import types
def qreg_creg_ascending(bits: List[types.Bits]) -> List[types.Bits]:
"""Sort bits by ascending order.
Bit order becomes Q0, Q1, ..., Cl0, Cl1, ...
Args:
bits: List of bits to sort.
Returns:
Sorted bits.
"""
qregs = []
cregs = []
for bit in bits:
if isinstance(bit, circuit.Qubit):
qregs.append(bit)
elif isinstance(bit, circuit.Clbit):
cregs.append(bit)
else:
raise VisualizationError(f"Unknown bit {bit} is provided.")
with warnings.catch_warnings():
warnings.simplefilter("ignore")
qregs = sorted(qregs, key=lambda x: x.index, reverse=False)
cregs = sorted(cregs, key=lambda x: x.index, reverse=False)
return qregs + cregs
def qreg_creg_descending(bits: List[types.Bits]) -> List[types.Bits]:
"""Sort bits by descending order.
Bit order becomes Q_N, Q_N-1, ..., Cl_N, Cl_N-1, ...
Args:
bits: List of bits to sort.
Returns:
Sorted bits.
"""
qregs = []
cregs = []
for bit in bits:
if isinstance(bit, circuit.Qubit):
qregs.append(bit)
elif isinstance(bit, circuit.Clbit):
cregs.append(bit)
else:
raise VisualizationError(f"Unknown bit {bit} is provided.")
qregs = sorted(qregs, key=lambda x: x.index, reverse=True)
cregs = sorted(cregs, key=lambda x: x.index, reverse=True)
return qregs + cregs
def time_map_in_dt(time_window: Tuple[int, int]) -> types.HorizontalAxis:
"""Layout function for the horizontal axis formatting.
Generate equispaced 6 horizontal axis ticks.
Args:
time_window: Left and right edge of this graph.
Returns:
Axis formatter object.
"""
# shift time axis
t0, t1 = time_window
# axis label
axis_loc = np.linspace(max(t0, 0), t1, 6)
axis_label = axis_loc.copy()
# consider time resolution
label = "System cycle time (dt)"
formatted_label = [f"{val:.0f}" for val in axis_label]
return types.HorizontalAxis(
window=(t0, t1), axis_map=dict(zip(axis_loc, formatted_label)), label=label
)
|
https://github.com/theochemel/grovers
|
theochemel
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import BasicAer, Aer
from qiskit.tools.visualization import plot_state_city, plot_histogram, plot_state_hinton
# Create a Quantum Register with 3 qubits.
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
# Create a Quantum Circuit acting on the q register
circ = QuantumCircuit(q, c)
# MARK: START OF CIRCUIT
circ.h(q[1])
circ.h(q[2])
# circ.x(q[0])
# circ.h(q[0])
# MARK: Oracle generation. q[0] is oracle qubit. '11' is Sv
circ.ccx(q[2], q[1], q[0])
# circ.x(q[0])
# MARK: Conditional phase rotation
# Omitted for now
circ.cz(q[1], q[0])
circ.cz(q[2], q[0])
# MARK: Grover operator. Diffusion transform D = WRW
# W = Walsh-Hadamard transform (H gate on each qubit)
# R = Rotation matrix (controlled - z wrapped in bit-flips?)
circ.h(q[1])
circ.h(q[2])
circ.x(q[1])
circ.x(q[2])
circ.h(q[1])
circ.cx(q[2], q[1])
circ.h(q[1])
circ.x(q[2])
circ.x(q[1])
circ.h(q[1])
circ.h(q[2])
# MARK: Measure circuit
circ.measure(q[1], c[1])
circ.measure(q[2], c[2])
# MARK: END OF CIRCUIT
print(circ)
backend = BasicAer.get_backend('statevector_simulator')
job = execute(circ, backend)
stateVectorResult = job.result()
outputstate = stateVectorResult.get_statevector(circ, decimals=3)
print(outputstate)
plot_state_city(outputstate)
# plot_state_hinton(outputstate)
simulator = Aer.get_backend('qasm_simulator')
shotsResult = execute(circ, simulator).result()
counts = shotsResult.get_counts(circ)
print(counts)
plot_histogram(counts)
|
https://github.com/scaleway/qiskit-scaleway
|
scaleway
|
import os
import random
from qiskit import QuantumCircuit
from qiskit_scaleway import ScalewayProvider
def test_qsim_simple_circuit():
provider = ScalewayProvider(
project_id=os.environ["QISKIT_SCALEWAY_PROJECT_ID"],
secret_key=os.environ["QISKIT_SCALEWAY_API_TOKEN"],
url=os.environ["QISKIT_SCALEWAY_API_URL"],
)
backend = provider.get_backend("qsim_simulation_pop_c16m128")
assert backend is not None
session_id = backend.start_session(
name="my-qsim-session-autotest",
deduplication_id=f"my-qsim-session-autotest-{random.randint(1, 1000)}",
max_duration="2m",
)
assert session_id is not None
try:
qc = QuantumCircuit(4)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.measure_all()
shots_count = 1000
job = backend.run(qc, shots=shots_count, session_id=session_id)
# cirq_result = job.result(format="cirq")
# assert cirq_result is not None
# assert cirq_result.repetitions == shots_count
qiskit_result = job.result(format="qiskit")
assert qiskit_result is not None
assert qiskit_result.success
assert qiskit_result.results[0].shots == shots_count
finally:
backend.stop_session(session_id)
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import *
from qiskit import transpile
import numpy as np
import matplotlib.pyplot as plt
from qiskit.extensions import UnitaryGate
from qiskit import IBMQ
import sys
sys.path.append("..")
%matplotlib inline
qiskit.__qiskit_version__
from Modules.iterative_qpe import IQPE
U = UnitaryGate(data=np.array([[1, 0],
[0, np.exp(2*np.pi*1j*(1/5))]]))
iqpe = IQPE(precision=4,unitary=U,unknown=True)
q = QuantumCircuit(2, 4)
q.x(1)
phase = iqpe.get_circuit_phase(
QC=q, clbits=[0, 1, 2, 3], qubits=[1],ancilla=0, show=True, save_circ = True)
phase
U = QuantumCircuit(2,name='U')
U.cp(2*np.pi*1/6,0,1)
U.draw('mpl')
#.control(num_ctrl_qcubits= 1, label = 'CCu', ctrl_state = '1')
iqpe = IQPE(precision=4,unitary=U,unknown=True)
q = QuantumCircuit(3, 4)
q.x(1)
q.x(2)
phase = iqpe.get_circuit_phase(
QC=q, clbits=[0, 1, 2, 3], qubits=[1,2],ancilla=0, show=True,save_circ = True,circ_name = "IQPE_circ.JPG")
print("Phase of the circuit in binary:", phase)
u2 = QuantumCircuit(3)
u2.cp(2*np.pi*(1/6),1,2)
u2.draw('mpl')
estimates = []
for prec in range(2, 9):
q = QuantumCircuit(4, prec)
# making eigenvector
q.x(2)
q.x(3)
iqpe = IQPE(precision=prec, unitary=u2,unknown=True)
phase = iqpe.get_circuit_phase(
QC=q, clbits=[i for i in range(prec)], qubits=[1,2,3], ancilla=0)
# print(phase[0])
estimates.append(phase[1])
plt.figure(figsize=(9, 7))
plt.plot(list(range(2, 9)), estimates, marker='o',
label='Estimates', linestyle='dotted',linewidth = 2,color = 'cyan')
plt.plot([0, 10], [0.16667, 0.16667], color='black', label='Actual phase')
plt.title("IQPE estimates for $\\theta = 1/6$", fontsize=16)
plt.xlabel("Number of iterations ", fontsize=14)
plt.ylabel("Estimate of phase", fontsize=14)
plt.legend()
from Modules.iterative_qpe import get_estimate_plot_phase
IBMQ.load_account()
## provider = IBMQ.get_provider('''ENTER YOUR PROVIDER''')
casb = provider.get_backend('ibmq_casablanca')
get_estimate_plot_phase(theta=0.524, iters = 9,unknown= True, save=True, experiments=5,backend=casb)
get_estimate_plot_phase(0.111, iters= 8, unknown=True, save=True,experiments=3)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Choose the drawer you like best:
from qiskit.tools.visualization import matplotlib_circuit_drawer as draw
#from qiskit.tools.visualization import circuit_drawer as draw
from qiskit import IBMQ
IBMQ.load_accounts() # make sure you have setup your token locally to use this
%matplotlib inline
import matplotlib.pyplot as plt
def show_results(D):
# D is a dictionary with classical bits as keys and count as value
# example: D = {'000': 497, '001': 527}
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
from qiskit import Aer
# See a list of available local simulators
print("Aer backends: ", Aer.backends())
# see a list of available remote backends (these are freely given by IBM)
print("IBMQ Backends: ", IBMQ.backends())
# execute circuit and either display a histogram of the results
def execute_locally(qc, draw_circuit=False):
# Compile and run the Quantum circuit on a simulator backend
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
result_counts = result_sim.get_counts(qc)
# Print the results
print("simulation: ", result_sim, result_counts)
if draw_circuit: # draw the circuit
draw(qc)
else: # or show the results
show_results(result_counts)
from qiskit.backends.ibmq import least_busy
import time
# Compile and run on a real device backend
def execute_remotely(qc, draw_circuit=False):
if draw_circuit: # draw the circuit
draw(qc)
try:
# select least busy available device and execute.
least_busy_device = least_busy(IBMQ.backends(simulator=False))
print("Running on current least busy device: ", least_busy_device)
# running the job
job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10)
lapse, interval = 0, 10
while job_exp.status().name != 'DONE':
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status())
time.sleep(interval)
lapse += 1
print(job_exp.status())
exp_result = job_exp.result()
result_counts = exp_result.get_counts(qc)
# Show the results
print("experiment: ", exp_result, result_counts)
if not draw_circuit: # show the results
show_results(result_counts)
except:
print("All devices are currently unavailable.")
def new_circuit(size):
# Create a Quantum Register with size qubits
qr = QuantumRegister(size)
# Create a Classical Register with size bits
cr = ClassicalRegister(size)
# Create a Quantum Circuit acting on the qr and cr register
return qr, cr, QuantumCircuit(qr, cr)
# create the circuit
# H gate on qubit 0
# measure the qubits
# create the circuit
# H gate on qubit 0
# X gate on qubit 1
# measure the qubits
# create the circuit
execute_remotely(circuit)
|
https://github.com/ichen17/Learning-Qiskit
|
ichen17
|
from qiskit import *
import numpy as np
from random import random
from qiskit.extensions import Initialize
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import qiskit.providers.aer.noise as noise
# Protocol uses 3 qubits and 1 classical bit in a register
qr = QuantumRegister(3, name="q") # Protocol uses 4 qubits
cr1 = ClassicalRegister(1, name="cr1") # and 2 classical bit
#cr2 = ClassicalRegister(1, name="cr2")
bit_flip_circuit = QuantumCircuit(qr,cr1)
def encoding(qc, q0, q1, q2):
"""Creates encoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
def measure(qc, q0, cr):
"""Measures qubit q0 """
qc.barrier()
qc.measure(q0,cr)
def decoding(qc, q0, q1, q2):
"""Creates decoding process using qubits q0 & q1 & q2"""
qc.cx(q0,q1) # CNOT with q1 as control and q0 as target
qc.cx(q0,q2) # CNOT with q2 as control and q0 as target
qc.ccx(q2,q1,q0) # Apply a Toffoli gate |011> <-> |111>
prob_1 = 0.25 # 1-qubit gate
#prob_2 = 0.01 # 2-qubit gate
# Depolarizing quantum errors
error_1 = noise.phase_amplitude_damping_error(prob_1, 0.1, 1)
#error_1 = noise.amplitude_damping_error(prob_1, 1)
#error_2 = noise.depolarizing_error(prob_2, 2)
# Add errors to noise model
noise_model = noise.NoiseModel()
noise_model.add_all_qubit_quantum_error(error_1, ['id'])
#noise_model.add_all_qubit_quantum_error(error_2, ['cx'])
# Get basis gates from noise model
basis_gates = noise_model.basis_gates
encoding(bit_flip_circuit, 0, 1, 2)
# step 2. error simulation
#bit_flip_circuit.append(Er,[0,1,2,3])
#error_simulation(bit_flip_circuit, 0, 1, 2, p)
bit_flip_circuit.barrier()
bit_flip_circuit.i(0)
bit_flip_circuit.i(1)
bit_flip_circuit.i(2)
bit_flip_circuit.barrier()
# step 3. decoding
decoding(bit_flip_circuit, 0, 1, 2)
# step 4. measurement
measure(bit_flip_circuit, 0, 0)
# View the circuit:
%matplotlib inline
bit_flip_circuit.draw(output='mpl')
result = execute(bit_flip_circuit, Aer.get_backend('qasm_simulator'),
basis_gates=basis_gates,
noise_model=noise_model).result()
counts = result.get_counts(0)
plot_histogram(counts)
nocor = QuantumCircuit(1,1)
nocor.i(0)
measure(nocor, 0, 0)
nocor.draw(output='mpl')
result = execute(nocor, Aer.get_backend('qasm_simulator'),
basis_gates=basis_gates,
noise_model=noise_model).result()
counts = result.get_counts(0)
plot_histogram(counts)
|
https://github.com/shufan-mct/IBM_quantum_challenge_2020
|
shufan-mct
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
#initialization
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
lightout4=[[1, 1, 1, 0, 0, 0, 1, 0, 0],[1, 0, 1, 0, 0, 0, 1, 1, 0],[1, 0, 1, 1, 1, 1, 0, 0, 1],[1, 0, 0, 0, 0, 0, 1, 0, 0]]
def qRAM(ad,tile):
qc = QuantumCircuit(ad, tile)
##address 00->tile lightsout[0]
qc.x([ad[0],ad[1]])
i=0
for lightout in lightout4[0]:
if lightout==1:
qc.ccx(ad[0],ad[1],tile[i])
i=i+1
qc.x([ad[0],ad[1]])
##address 01->tile lightsout[1]
qc.x(ad[1])
i=0
for lightout in lightout4[1]:
if lightout==1:
qc.ccx(ad[0],ad[1],tile[i])
i=i+1
qc.x(ad[1])
##address 10->tile lightsout[2]
qc.x(ad[0])
i=0
for lightout in lightout4[2]:
if lightout==1:
qc.ccx(ad[0],ad[1],tile[i])
i=i+1
qc.x(ad[0])
##address 11->tile lightsout[3]
i=0
for lightout in lightout4[3]:
if lightout==1:
qc.ccx(ad[0],ad[1],tile[i])
i=i+1
U_s = qc.to_gate()
U_s.name = "$U_qram$"
return U_s
def nine_mct(control_qubits,ancilla_qubits,output_qubit):
qc = QuantumCircuit(control_qubits, ancilla_qubits, output_qubit)
qc.mct([control_qubits[0],control_qubits[1],control_qubits[2]],ancilla_qubits[0],mode='noancilla')
qc.mct([control_qubits[3],control_qubits[4],control_qubits[5]],ancilla_qubits[1],mode='noancilla')
qc.mct([control_qubits[6],control_qubits[7],control_qubits[8]],ancilla_qubits[2],mode='noancilla')
qc.mct([ancilla_qubits[0],ancilla_qubits[1],ancilla_qubits[2]],output_qubit[0],mode='noancilla')
qc.mct([control_qubits[6],control_qubits[7],control_qubits[8]],ancilla_qubits[2],mode='noancilla')
qc.mct([control_qubits[3],control_qubits[4],control_qubits[5]],ancilla_qubits[1],mode='noancilla')
qc.mct([control_qubits[0],control_qubits[1],control_qubits[2]],ancilla_qubits[0],mode='noancilla')
U_s = qc.to_gate()
U_s.name = "$U_9mct$"
return U_s
def oracle_2a(tile,flip,flag_a,ancilla):
qc = QuantumCircuit(tile,flip,flag_a,ancilla)
#build lightsout_oracle
switch_list=[[1,3],[0,2,4],[1,5],[0,4,6],[1,3,5,7],[2,4,8],[3,7],[4,6,8],[5,7]]
i=0
for clights in switch_list:
qc.cx(flip[8-i],tile[i])
for clight in clights:
qc.cx(flip[8-i],tile[clight])
i=i+1
for i in range(9):
qc.x(tile[i])
qc.append(nine_mct(tile,ancilla,flag_a),[*range(9),*range(19,25),18])
for i in range(9):
qc.x(tile[i])
i=0
for clights in switch_list:
qc.cx(flip[8-i],tile[i])
for clight in clights:
qc.cx(flip[8-i],tile[clight])
i=i+1
U_s = qc.to_gate()
U_s.name = "$U_ora2a$"
return U_s
def eight_mct_in(in_qubits,ancilla_qubits):
qc = QuantumCircuit(in_qubits, ancilla_qubits)
qc.mct([in_qubits[0],in_qubits[1],in_qubits[2]],ancilla_qubits[0],mode='noancilla')
qc.mct([in_qubits[3],in_qubits[4],in_qubits[5]],ancilla_qubits[1],mode='noancilla')
qc.ccx(in_qubits[6],in_qubits[7],ancilla_qubits[2])
qc.mct([ancilla_qubits[0],ancilla_qubits[1],ancilla_qubits[2]],in_qubits[8],mode='noancilla')
qc.ccx(in_qubits[6],in_qubits[7],ancilla_qubits[2])
qc.mct([in_qubits[3],in_qubits[4],in_qubits[5]],ancilla_qubits[1],mode='noancilla')
qc.mct([in_qubits[0],in_qubits[1],in_qubits[2]],ancilla_qubits[0],mode='noancilla')
U_s = qc.to_gate()
U_s.name = "$U_8mct$"
return U_s
def nine_diffuser(flip_qubits,ancilla_qubits):
qc = QuantumCircuit(flip_qubits,ancilla_qubits)
# Apply transformation |s> -> |00..0> (H-gates)
for qubit in range(9):
qc.h(qubit)
# Apply transformation |00..0> -> |11..1> (X-gates)
for qubit in range(9):
qc.x(qubit)
# Do multi-controlled-Z gate
qc.h(8)
qc.append(eight_mct_in(flip_qubits,ancilla_qubits),[*range(15)])
qc.h(8)
# Apply transformation |11..1> -> |00..0>
for qubit in range(9):
qc.x(qubit)
# Apply transformation |00..0> -> |s>
for qubit in range(9):
qc.h(qubit)
# We will return the diffuser as a gate
U_s = qc.to_gate()
U_s.name = "$U_9diff$"
return U_s
def u2a(tile,flip,flag_a,ancilla):
qc = QuantumCircuit(tile,flip,flag_a,ancilla)
for i in range(17):
#Oracle
qc.append(oracle_2a(tile,flip,flag_a,ancilla),[*range(25)])
# Diffuser
qc.append(nine_diffuser(flip,ancilla),[*range(9,18),*range(19,25)])
U_s = qc.to_gate()
U_s.name = "$U_2a$"
return U_s
def u2ad(tile,flip,flag_a,ancilla):
qc = QuantumCircuit(tile,flip,flag_a,ancilla)
for i in range(17):
# Diffuser
qc.append(nine_diffuser(flip,ancilla),[*range(9,18),*range(19,25)])
#Oracle
qc.append(oracle_2a(tile,flip,flag_a,ancilla),[*range(25)])
U_s = qc.to_gate()
U_s.name = "$U_2ad$"
return U_s
def counter(flip,flag_b,ancilla):
qc = QuantumCircuit(flip,flag_b,ancilla)
for i in range(9):
qc.mct([flip[i],ancilla[0],ancilla[1],ancilla[2]],ancilla[3],mode='noancilla')
qc.mct([flip[i],ancilla[0],ancilla[1]],ancilla[2],mode='noancilla')
qc.ccx(flip[i],ancilla[0],ancilla[1])
qc.cx(flip[i],ancilla[0])
qc.x([ancilla[2],ancilla[3]])
qc.ccx(ancilla[2],ancilla[3],flag_b[0])
qc.x([ancilla[2],ancilla[3]])
for i in range(9):
qc.cx(flip[8-i],ancilla[0])
qc.ccx(flip[8-i],ancilla[0],ancilla[1])
qc.mct([flip[8-i],ancilla[0],ancilla[1]],ancilla[2],mode='noancilla')
qc.mct([flip[8-i],ancilla[0],ancilla[1],ancilla[2]],ancilla[3],mode='noancilla')
U_s = qc.to_gate()
U_s.name = "$U_counter$"
return U_s
####Circuit Implement
ad = QuantumRegister(2, name='ad')
tile = QuantumRegister(9, name='tile')
flip = QuantumRegister(9, name='flip')
flag_a = QuantumRegister(1, name='f_a')
flag_b = QuantumRegister(1, name='f_b')
ancilla = QuantumRegister(6, name='a')
cbits = ClassicalRegister(2, name='cbits')
qc = QuantumCircuit(ad, tile,flip,flag_a,flag_b,ancilla,cbits)
####Initialize
qc.h(ad)
qc.h(flip)
qc.x(flag_a)
qc.h(flag_a)
qc.x(flag_b)
qc.h(flag_b)
####qRAM
qc.append(qRAM(ad,tile),[*range(11)])
####u2a block
qc.append(u2a(tile,flip,flag_a,ancilla),[*range(2,21),*range(22,28)])
####counter
qc.append(counter(flip,flag_b,ancilla),[*range(11,20),*range(21,28)])
####u2ad block
qc.append(u2ad(tile,flip,flag_a,ancilla),[*range(2,21),*range(22,28)])
####qRAM
qc.append(qRAM(ad,tile),[*range(11)])
####2 qubit diffusion
qc.h(ad)
qc.z(ad)
qc.cz(ad[0],ad[1])
qc.h(ad)
# Measure the variable qubits
qc.measure(ad, cbits)
qc.draw()
####Circuit Implement
ad = QuantumRegister(2, name='ad')
tile = QuantumRegister(9, name='tile')
flip = QuantumRegister(9, name='flip')
flag_a = QuantumRegister(1, name='f_a')
flag_b = QuantumRegister(1, name='f_b')
ancilla = QuantumRegister(6, name='a')
cbits = ClassicalRegister(2, name='cbits')
qc = QuantumCircuit(ad, tile,flip,flag_a,flag_b,ancilla,cbits)
####Initialize
qc.h(ad)
qc.h(flip)
qc.x(flag_a)
qc.h(flag_a)
qc.x(flag_b)
qc.h(flag_b)
####qRAM
qc.append(qRAM(ad,tile),[*range(11)])
####u2a block
qc.append(u2a(tile,flip,flag_a,ancilla),[*range(2,21),*range(22,28)])
####counter
qc.append(counter(flip,flag_b,ancilla),[*range(11,20),*range(21,28)])
####u2ad block
qc.append(u2ad(tile,flip,flag_a,ancilla),[*range(2,21),*range(22,28)])
####qRAM
qc.append(qRAM(ad,tile),[*range(11)])
####2 qubit diffusion
qc.h(ad)
qc.z(ad)
qc.cz(ad[0],ad[1])
qc.h(ad)
# Measure the variable qubits
qc.measure(ad, cbits)
qasm_simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=qasm_simulator, shots=1024).result()
plot_histogram(result.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
ghz.draw(output='mpl')
|
https://github.com/conradhaupt/Qiskit-Bayesian-Inference-Module-QCA19-
|
conradhaupt
|
import qiskit as qk
import qinfer as qf
from qiskit.aqua.algorithms.single_sample import IQPE,QPE
from qiskit.aqua.components import iqfts
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.aqua.algorithms import ExactEigensolver
from qiskit.aqua.components.initial_states import Custom
import numpy as np
from qiskit import Aer,execute
from qiskit.aqua import QuantumInstance
# We need distributions to model priors.
from qinfer import distributions
# The noisy coin model has already been implmented, so let's import it here.
from qinfer.test_models import NoisyCoinModel
# Next, we need to import the sequential Monte Carlo updater class.
from qinfer.smc import SMCUpdater
# We'll be demonstrating approximate likelihood evaluation (ALE) as well.
from qinfer import ale
from qinfer import FiniteOutcomeModel
import matplotlib.pyplot as plt
from scipy.stats import circmean
EPS = 1e-15
def chop(value):
if np.abs(value) <= EPS:
return 0
else:
return value
print(angle)
angle = np.pi / 3
real = chop(np.real(np.exp(1.j * angle)))
imag = chop(np.imag(np.exp(1.j * angle)))
PAULI_DICT_ZZ = {
'paulis': [
{"coeff": {"imag": imag, "real": real}, "label": "ZZ"}
]
}
QUBIT_OP_ZZ = WeightedPauliOperator.from_dict(PAULI_DICT_ZZ)
eigen_results = ExactEigensolver(QUBIT_OP_ZZ,4).run()
eigen_value = eigen_results['eigvals'][0]
eigen_vector = eigen_results['eigvecs'][0]
eigen_results
state_in = Custom(QUBIT_OP_ZZ.num_qubits, state_vector=eigen_vector)
simulator = Aer.get_backend('qasm_simulator')
iqpe_builder = IQPE(
QUBIT_OP_ZZ,
state_in,
num_iterations=6,
num_time_slices=1,
expansion_mode='suzuki',
expansion_order=3,
shallow_circuit_concat=True)
iqpe_results = iqpe_circ = iqpe_builder.run(simulator,shots=2048)
iqpe_results
output_results = iqpe_results['top_measurement_label']
output_results
iqpe_results
class IQPEModel(FiniteOutcomeModel):
def __init__(self):
super(IQPEModel, self).__init__()
## PROPERTIES ##
@property
def n_modelparams(self):
# phi
return 1
@property
def expparams_dtype(self):
# return [('theta','float64'), ('m','int64'),('T2','float64')]
return [('theta','float64'), ('m','int64')]
@property
def is_n_outcomes_constant(self):
return True
## METHODS ##
@staticmethod
def are_models_valid(modelparams):
return np.logical_and(modelparams[:] >= 0, modelparams[:]<=2*np.pi).all(axis=1)
def n_outcomes(self, expparams):
return 2
def likelihood(self, outcomes, modelparams, expparams):
# We first call the superclass method, which basically
# just makes sure that call count diagnostics are properly
# logged.
super(IQPEModel, self).likelihood(outcomes, modelparams, expparams)
# Probability of getting 0 for QPE is
# P(0) = (1 + cos(M(theta - phi)))/2
# pr0 = np.exp(-expparams['m'] / expparams['T2']) * (1 + np.cos(expparams['m'] * (expparams['theta'] - modelparams[:]))) / 2 + (1 - np.exp(-expparams['m'] / expparams['T2']))/2
pr0 = (1 + np.cos(expparams['m'] * (expparams['theta'] - modelparams[:]))) / 2
# Concatenate over outcomes.
return FiniteOutcomeModel.pr0_to_likelihood_array(outcomes, pr0)
N_PARTICLES = 5000
N_EXP = 20
N_TRIALS = 1
prior = distributions.UniformDistribution([0, 2 * np.pi])
# prior = distributions.NormalDistribution(np.pi,0.5)
model = IQPEModel()
performance_dtype = [
('outcome', 'i1'),
('est_mean', 'f8'), ('est_cov_mat', 'f8'),
('true_err', 'f8'), ('resample_count', 'i8'),
('elapsed_time', 'f8'),
('like_count', 'i8'), ('sim_count', 'i8'),
('bme', 'f8'),
('var', 'f8'),
('bme_err', 'f8')
]
performance = np.empty((N_TRIALS, N_EXP), dtype=performance_dtype)
true_params = np.empty((N_TRIALS, model.n_modelparams))
import time
def radiandiff(a,b):
FULL_ROTATION = 2 * np.pi
return np.min(np.abs([a - b, b - a, a - b + FULL_ROTATION, b - a + FULL_ROTATION]))
THETA = np.pi/3
# M = np.linspace(1,5)
# n = 2
# expected_bit = np.float64(output_results[-n])
M = 3
T2 = 100
# expparams = np.array([(M,THETA,T2)], dtype=model.expparams_dtype)
expparams = np.array([(M,THETA)], dtype=model.expparams_dtype)
class PhaseSMCUpdater(SMCUpdater):
@staticmethod
def particle_mean(weights,locations):
weighted_values = np.multiply(weights, locations)
return circmean(weighted_values)
simulator = Aer.get_backend('qasm_simulator')
for idx_trial in range(N_TRIALS):
# First, make new updaters using the constructors
# defined above.
updater = PhaseSMCUpdater(model, N_PARTICLES, prior)
# # Sample true set of modelparams.
# truemp = prior.sample()
# true_params[idx_trial, :] = truemp
# Now loop over experiments, updating each of the
# updaters with the same data, so that we can compare
# their estimation performance.
print(idx_trial)
circuit = iqpe_builder.construct_circuit(k=M,omega=THETA,measurement=True)
results = execute(circuit,simulator,shots=4096,memory=True)
counts = results.result().get_counts()
memory = results.result().get_memory()
print(counts)
for idx_exp in range(N_EXP):
# Make a short hand for indexing the current simulation
# and experiment.
idxs = np.s_[idx_trial, idx_exp]
# Start by simulating and recording the data.
#########################################
#########################################
#########################################
#########################################
#########################################
#########################################
#########################################
#########################################
USE_QISKIT_QASM_SIMULATOR = False
if USE_QISKIT_QASM_SIMULATOR:
outcome = int(memory[idx_exp])
else:
outcome = model.simulate_experiment(np.array([[angle]]),expparams)
#########################################
#########################################
#########################################
#########################################
#########################################
#########################################
#########################################
#########################################
performance['outcome'][idxs] = outcome
# print(outcome)
# Reset the like_count and sim_count
# properties so that we can count how many were used
# by this update. Note that this is a hack;
# an appropriate method should be added to
# Simulatable.
model._sim_count = 0
model._call_count = 0
# Time the actual update.
tic = toc = None
tic = time.time()
updater.update(outcome, expparams)
performance[idxs]['elapsed_time'] = time.time() - tic
# Record the performance of this updater.
# weighted_values = np.multiply(updater.particle_weights, updater.particle_locations)
# est_mean = circmean(weighted_values)
est_mean = updater.est_mean()
performance[idxs]['est_mean'] = est_mean
performance[idxs]['true_err'] = radiandiff(est_mean,angle) ** 2
# performance[idxs]['true_err'] = np.abs(est_mean - truemp) ** 2
performance[idxs]['est_cov_mat'] = updater.est_covariance_mtx()
performance[idxs]['resample_count'] = updater.resample_count
performance[idxs]['like_count'] = model.call_count
performance[idxs]['sim_count'] = model.sim_count
# Finally, record the ideal stats.
# performance[idxs]['bme'], performance[idxs]['var'] = exactBME(
# idx_exp + 1 - np.sum(performance[idxs]['outcome']), idx_exp + 1,
# ALPHA, BETA
# )
# performance[idxs]['bme'],
# performance[idxs]['bme_err'] = np.abs(performance[idxs]['bme'] - truemp) ** 2
print('Done!')
# plt.semilogy(np.mean(performance['true_err'],axis=0))
updater.plot_posterior_marginal()
counts
def averageofcounts(counts):
# print(dir(counts))
sum = 0
count = 0
for k,v in counts.items():
key_val = int(k)
sum += key_val * v
count += v
return sum / count
model = IQPEModel()
n_meas = 25
prior = distributions.UniformDistribution([0, 1])
updater = PhaseSMCUpdater(model, 2000, prior)
heuristic = qf.ExpSparseHeuristic(updater)
true_params = 1
est_hist = []
for m in range(25):
print('Infering for m=%d' % (m))
THETA = np.pi
M = 4
T2 = 100
experiment = np.array([(M,THETA,T2)], dtype=model.expparams_dtype)
# experiment = np.array([(m, n_meas)], dtype=model.expparams_dtype)
# datum = model.simulate_experiment(true_params, experiment)
circuit = iqpe_builder.construct_circuit(k=M,omega=THETA,measurement=True)
n_shots = 4096
results = execute(circuit,simulator,shots=n_shots)
counts = results.result().get_counts()
datum = averageofcounts(counts)
# print(datum)
updater.update(datum, experiment)
est_hist.append(updater.est_mean())
plt.plot(est_hist, label='Est.')
plt.hlines(true_params, 0, 20, label='True')
plt.legend(ncol=2)
plt.xlabel('# of Times Sampled (25 measurements/ea)')
plt.ylabel('Measured value')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc_basis = transpile(qc, backend)
qc_basis.draw(output='mpl')
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
Q_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(3)
c = ClassicalRegister(3)
super0 = QuantumCircuit(q, c)
super0.h(q[0])
super0.id(q[1])
super0.id(q[2])
super0.measure(q[0], c[0])
#print(super0.qasm3())
print(qasm3.dumps(super0))
q = QuantumRegister(1, name='q')
c = ClassicalRegister(1, name='c')
super0 = QuantumCircuit(q, c,name='qc')
super0.h(q[0])
#Inst = super0.qasm()
Inst = qasm2.dumps(super0)
print(Inst[36:len(Inst)])
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
two_q = QuantumCircuit(q, c,name='qc')
two_q.h(q[0])
two_q.h(q[1])
two_q.measure(q[0],c[0])
print('____________QuantumCircuit.qasm()_____________________')
qasm = qasm2.dumps(two_q)
print(qasm[36:len(qasm)])
print('____________QuantumCircuit.data_____________________')
print(two_q.data)
print('____________QuantumCircuit.qregs_____________________')
print(two_q.qregs)
print('____________QuantumCircuit.cregs_____________________')
print(two_q.cregs)
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q, c,name='qc')
qc.h(q[0])
qc.h(q[1])
qc.measure(q[0],c[0])
print('_________Initial___________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
inst = qc.data[1]
del qc.data[1]
print('______________del qc.data[1]_____________________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
qc.data.append(inst)
print('______________qc.data.append(inst)_____________________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
qc.data.insert(0,inst)
print('______________qc.data.insert(0,inst)_____________________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q, c,name='qc')
q2 = QuantumRegister(2, name='q2')
c2 = ClassicalRegister(2, name='c2')
qc2 = QuantumCircuit(q2, c2,name='qc2')
qc.h(q[0])
qc.measure(q[0],c[0])
qc2.h(q2[0])
print('__________qc______________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
print('__________qc2______________')
qasm = qasm2.dumps(qc2)
print(qasm[36:len(qasm)])
q = QuantumRegister(1, name='q')
c = ClassicalRegister(1, name='c')
qc = QuantumCircuit(q, c,name='qc')
q2 = QuantumRegister(1, name='q2')
c2 = ClassicalRegister(1, name='c2')
qc2 = QuantumCircuit(q2, c2,name='qc2')
qc.add_register(c2)
qc2.add_register(q)
qc.h(q[0])
qc2.h(q2[0])
qc.measure(q[0],c2[0])
qc2.h(q[0])
print('__________qc______________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
print('__________qc2______________')
qasm = qasm2.dumps(qc2)
print(qasm[36:len(qasm)])
q1 = QuantumRegister(2, name='q1')
c1 = ClassicalRegister(3, name='c1')
qc1 = QuantumCircuit(q1, c1,name='qc1')
q2 = QuantumRegister(2, name='q2')
c2 = ClassicalRegister(3, name='c2')
qc2 = QuantumCircuit(q2, c2,name='qc2')
qc1.h(q1[0])
qc1.id(q1[1])
qc2.id(q2[0])
qc2.h(q2[1])
qc3 = qc1 & qc2
print('__________qc3 = qc1 & qc2______________')
qasm = qasm2.dumps(qc3)
print(qasm[36:len(qasm)])
qc1 &= qc1
print('__________qc1 &= qc2______________')
qasm = qasm2.dumps(qc1)
print(qasm[36:len(qasm)])
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q, c,name='qc')
qc.h(q[0])
qc.h(q[1])
qc.measure(q,c)
print(qc)
qc.draw(output='mpl')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- 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/jonasmaziero/computacao_quantica_qiskit_sbf_2023
|
jonasmaziero
|
from sympy import Matrix
X = Matrix([[0,1],[1,0]]); X
Y = Matrix([[0,-1j],[1j,0]]); Y
Z = Matrix([[1,0],[0,-1]]); Z
X.eigenvals()
X.eigenvects()
Y.eigenvects()
Z.eigenvects()
from sympy import Matrix
X = Matrix([[0,1],[1,0]])
ket0 = Matrix([[1],[0]]); ket1 = Matrix([[0],[1]]); ket0, ket1
X*ket0, X*ket1
Y*ket0, Y*ket1, Z*ket0, Z*ket1
from sympy.physics.quantum import TensorProduct as tp
ket00 = tp(ket0,ket0); ket01 = tp(ket0,ket1); ket10 = tp(ket1,ket0); ket11 = tp(ket1,ket1); ket00, ket01, ket10, ket11
tp(eye(2),X), tp(eye(2),eye(2))*ket00, tp(eye(2),X)*ket00, tp(X,eye(2))*ket00, tp(X,X)*ket00
from qiskit import QuantumCircuit
import qiskit
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(2) # prepara o estado |00>
qc.draw('mpl')
state = Statevector(qc)
state
qc = QuantumCircuit(2)
qc.x(1) # estado |01>
qc.draw('mpl')
state = Statevector(qc); state
from sympy.physics.quantum.dagger import Dagger
P0 = ket0*Dagger(ket0); P1 = ket1*Dagger(ket1); P0,P1
CNOTab = tp(P0,eye(2)) + tp(P1,X); CNOTba = tp(eye(2),P0) + tp(X,P1); CNOTab,CNOTba
H = Matrix([[1,1],[1,-1]])/sqrt(2); H
Phip = CNOTab*tp(H,eye(2))*ket00; Phim = CNOTab*tp(H,eye(2))*ket10; Phip,Phim
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.draw('mpl')
from qiskit.quantum_info import Statevector
state = Statevector(qc); state # |Phi+>
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.x([0,1])
qc.h(0)
qc.cx(0,1)
qc.draw('mpl')
from qiskit.quantum_info import Statevector
state = Statevector(qc); state # |Psi->
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0); qc.cx(0,1) # prepara |Phi+>
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.draw('mpl')
from qiskit.quantum_info import Statevector
state = Statevector(qc); state # estado |00>
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi->
qc.barrier()
qc.cx(0,1)
qc.h(0)
qc.draw('mpl')
from qiskit.quantum_info import Statevector
state = Statevector(qc); state # estado |11>
from sympy import Matrix
X = Matrix([[0,1],[1,0]]); X
init_printing(use_unicode=True) # pra visualização ficar melhor
X.eigenvects()
from qiskit import QuantumCircuit
qc = QuantumCircuit(1,1)
qc.h(0)
from qiskit.quantum_info import Statevector
state = Statevector(qc)
state
qc.measure(0,0)
qc.draw('mpl')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13 # 8192
job = execute(qc, backend=simulator, shots=nshots)
from qiskit.tools.visualization import plot_histogram
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit
qc = QuantumCircuit(1,1)
qc.h(0)
qc.barrier()
qc.h(0)
qc.measure(0,0)
qc.draw('mpl')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13 # 8192
job = execute(qc, backend=simulator, shots=nshots)
from qiskit.tools.visualization import plot_histogram
plot_histogram(job.result().get_counts())
from qiskit import QuantumCircuit
qc = QuantumCircuit(1,1)
qc.sdg(0)
qc.h(0)
qc.measure(0,0)
qc.draw('mpl')
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
job = execute(qc, backend=simulator, shots=nshots)
from qiskit.tools.visualization import plot_histogram
plot_histogram(job.result().get_counts())
from sympy import symbols
th, ph, lb = symbols('theta phi lambda'); th, ph, lb
sn = Matrix([[cos(th),exp(-1j*ph)*sin(th)],[exp(1j*ph)*sin(th),-cos(th)]]); sn
sn.eigenvects()
import math
math.cos(math.pi/8)**2
from qiskit import QuantumCircuit
qc = QuantumCircuit(1,1)
import math
th = -math.pi/4
ph = 0
lb = math.pi - ph
qc.u(th,ph,lb, 0) # porta parametrizada
qc.measure(0,0)
qc.draw('mpl')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
job = execute(qc, backend = simulator, shots=nshots)
from qiskit.tools.visualization import plot_histogram
plot_histogram(job.result().get_counts())
# Cria o circuito quântico, sem usar medidas
from qiskit import QuantumCircuit
qc = QuantumCircuit(1)
qc.h(0)
qc.s(0)
qc.draw(output='mpl') # estado |o+>=(|0>+i|1>)/sqrt(2)
2**13
from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
import qiskit; from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
qstc = state_tomography_circuits(qc, [0]); job = execute(qstc, backend=simulator, shots=nshots)
qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method='lstsq')
qiskit.visualization.plot_state_city(rho)
rho
from sympy import Matrix, symbols, init_printing, eye
init_printing(use_unicode=True)
X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]])
x,y,z = symbols('x y z')
rho = (1/2)*(eye(2) + x*X + y*Y + z*Z); rho
rho.eigenvals()
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(4) # não faz nada no 1º qubit
qc.x(1)
qc.h(2)
qc.h(3); qc.s(3)
state = Statevector(qc)
plot_bloch_multivector(state)
|
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/bibscore/qiskit_kindergarten
|
bibscore
|
import os
from qiskit import *
import qiskit.tools.visualization as qt
from PIL import Image
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from numpy import pi
import matplotlib.pyplot as plt
%matplotlib inline
qreg_q = QuantumRegister(3, 'q')
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
circuit = QuantumCircuit(qreg_q, crz, crx)
circuit.x(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
initial = circuit.copy()
circuit.barrier()
circuit.h(qreg_q[1])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.barrier()
circuit.cx(qreg_q[0], qreg_q[1])
circuit.h(qreg_q[0])
circuit.barrier()
circuit.measure(qreg_q[0], 0)
circuit.measure(qreg_q[1], 1)
circuit.barrier()
circuit.draw(output='mpl')
simulator_qasm = Aer.get_backend('qasm_simulator')
simulator_aer = Aer.get_backend("aer_simulator")
result = execute(circuit, backend=simulator_qasm, shots=1024).result()
counts = result.get_counts()
qt.plot_histogram(counts, color="#625BF5", title="Qubits outputs for quantum teleportation circuit")
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
bob_gates(circuit, 2, crz, crx)
circuit.draw(output='mpl')
initial.draw(output='mpl')
initial.save_statevector()
statevector = simulator_aer.run(initial).result().get_statevector()
qt.plot_bloch_multivector(statevector)
circuit.save_statevector()
statevector2 = simulator_aer.run(circuit).result().get_statevector()
qt.plot_bloch_multivector(statevector2)
|
https://github.com/qiskit-community/qiskit-dell-runtime
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# Copyright 2021 Dell (www.dell.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from dell_runtime import DellRuntimeProvider
import unittest
from dell_runtime import LocalUserMessengerClient
from dell_runtime import EmulatorRuntimeJob, EmulationExecutor
from qiskit import QuantumCircuit, execute, transpile
from time import sleep
import logging
# RUNTIME_PROGRAM = """
# import random
# from qiskit import transpile
# from qiskit.circuit.random import random_circuit
# def prepare_circuits(backend):
# circuit = random_circuit(num_qubits=5, depth=4, measure=True,
# seed=random.randint(0, 1000))
# return transpile(circuit, backend)
# def main(backend, user_messenger, **kwargs):
# iterations = kwargs['iterations']
# interim_results = kwargs.pop('interim_results', {})
# final_result = kwargs.pop("final_result", {})
# for it in range(iterations):
# qc = prepare_circuits(backend)
# user_messenger.publish({"iteration": it, "interim_results": interim_results})
# backend.run(qc).result()
# user_messenger.publish(final_result, final=True)
# """
RUNTIME_PROGRAM = """
from qiskit.compiler import transpile, schedule
def main(
backend,
user_messenger,
circuits,
**kwargs,
):
user_messenger.publish({'results': 'intermittently'})
circuits = transpile(
circuits,
)
if not isinstance(circuits, list):
circuits = [circuits]
# Compute raw results
result = backend.run(circuits, **kwargs).result()
user_messenger.publish({'results': 'finally'})
user_messenger.publish(result.to_dict(), final=True)
print("job complete successfully")
"""
FAIL_PROGRAM = """
from qiskit.compiler import transpile, schedule
def main(
backend,
user_messenger,
circuits,
**kwargs,
):
raise Exception('test failure')
"""
RUNTIME_PROGRAM_METADATA = {
"max_execution_time": 600,
"description": "Qiskit test program"
}
logger = logging.getLogger(__name__)
class EmulatorRuntimeJobTest(unittest.TestCase):
def test_multiple_runtime_jobs(self):
executor = EmulationExecutor(program=None, program_data=(RUNTIME_PROGRAM, "STRING"), inputs = { "iterations": 2 })
executor2 = EmulationExecutor(program=None, program_data=(RUNTIME_PROGRAM, "STRING"), inputs = { "iterations": 2 })
executor3 = EmulationExecutor(program=None, program_data=(RUNTIME_PROGRAM, "STRING"), inputs = { "iterations": 2 })
self.assertIsNotNone(executor)
job = EmulatorRuntimeJob("1", None, executor=executor)
job2 = EmulatorRuntimeJob("1", None, executor=executor2)
job3 = EmulatorRuntimeJob("1", None, executor=executor3)
sleep(1)
self.assertIsNotNone(job)
job.cancel()
job2.cancel()
job3.cancel()
# pdb.set_trace()
sleep(1)
status = job.status()
self.assertEqual(status, "Canceled")
def test_intermittent_results(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
# runtime_program = provider.runtime.program(program_id)
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
result = job.result(timeout=120)
messages = job.get_unread_messages()
logger.debug(f'unread messages {messages}')
self.assertEqual(len(messages), 2)
self.assertEqual("intermittently", messages[0]['results'])
self.assertEqual("finally", messages[1]['results'])
messages = job.get_unread_messages()
self.assertEqual(0, len(messages))
def test_get_results(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
response = job.result(timeout=120)
results = response['results'][0]
self.assertIsNotNone(results)
self.assertTrue(results['success'])
self.assertTrue(results['success'])
self.assertEqual("DONE", results['status'])
shots = results['shots']
count = results['data']['counts']['0x0']
self.assertGreater(count, (0.45 * shots))
self.assertLess(count, (0.55 * shots))
def test_get_status(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
# runtime_program = provider.runtime.program(program_id)
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
status = job.status()
correct_status = status == "Creating" or status == "Running"
self.assertTrue(correct_status)
job.result(timeout=120)
status = job.status()
max_try = 50
attempt = 0
while (status == "Creating" or status == "Running") and attempt < max_try:
sleep(0.1)
attempt += 1
status = job.status()
self.assertEqual(status, "Completed")
def test_get_failed_status(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(FAIL_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
status = job.status()
self.assertEqual(status, "Creating")
max_try = 500
attempt = 0
while (status == "Creating" or status == "Running") and attempt < max_try:
sleep(0.1)
attempt += 1
status = job.status()
self.assertEqual(status, "Failed")
def test_cancel_job(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
# runtime_program = provider.runtime.program(program_id)
job = provider.runtime.run(program_id, options=None, inputs=program_inputs)
sleep(1)
res = job.cancel()
self.assertTrue(res)
status = job.status()
self.assertEqual(status, "Canceled")
def test_callback_function(self):
provider = DellRuntimeProvider()
program_id = provider.runtime.upload_program(RUNTIME_PROGRAM, metadata=RUNTIME_PROGRAM_METADATA)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
program_inputs = {
'circuits': qc,
}
import sys
import io
old_stdout = sys.stdout
new_stdout = io.StringIO()
sys.stdout = new_stdout
job = provider.runtime.run(program_id, options=None, inputs=program_inputs,callback=print)
result =job.result(timeout=600)
output = new_stdout.getvalue()
sys.stdout = old_stdout
self.assertTrue("{'results': 'intermittently'}"
in output)
|
https://github.com/lancecarter03/QiskitLearning
|
lancecarter03
|
import numpy as np
from qiskit import QuantumCircuit
|
https://github.com/PAYAL980/Four-Algorithms-in-Qiskit
|
PAYAL980
|
# Importing libraries and necessary tools
from qiskit import *
import numpy as np
import math
import random
from qiskit.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeJakarta, FakeNairobi
from qiskit_textbook.tools import simon_oracle
""" Simon oracle has been imported from qiskit textbook to be used in the algorithm"""
oracle = simon_oracle('00')
oracle.draw('mpl')
oracle = simon_oracle('01')
oracle.draw('mpl')
oracle = simon_oracle('10')
oracle.draw('mpl')
oracle = simon_oracle('11')
oracle.draw('mpl')
""" Defining a function for Simon's algorithm
Input: N - Length of the bitstring 'a'
oracle1- black box encoding the function
Output: qc - the quantum circuit to be run on a simulator to get the final output """
def Simon(oracle, N):
# Creating the quantum circuit of '2N' qubits where N is the number of bits in the input bitstring
qc = QuantumCircuit(N*2, N)
# Applying Hadamard gates on all qubits to create superposition
qc.h(range(N))
qc.barrier() # Barrier for better visualization
# Appending the oracle for the funtion to the quantum circuit
qc.append(oracle, range(2*N))
qc.barrier() # Barrier for better visualization
# Applying Hadamard gates to all the input qubits
qc.h(range(N))
qc.barrier() # Barrier for better visualization
# Measuring input qubits to find the linearly independent strings
qc.measure(range(N), range(N))
return qc
# Testing the algorithm for a = '10'
a = '10'
N = len(a)
ora = simon_oracle(a)
q1 = Simon(ora, N)
q1.draw('mpl')
# Running on non-noisy simulator 1
backend = Aer.get_backend('aer_simulator')
job = execute(q1,backend, shots=1024)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
""" Getting the output strings in form of a list to find 'a' classically"""
res = list(counts.keys())
res
# Running on non-noisy simulator 2
backend = Aer.get_backend('qasm_simulator')
job = execute(q1,backend, shots=1024)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Running on noisy simulator 1
backend = FakeJakarta()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Running on noisy simulator 2
backend = FakeNairobi()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
plot_histogram(counts)
# Defining a function that gives the output directly without running many cells
# a - the bitstring(to be encoded as black box)
# sim: simulator on which you want to run the algorithm
#. - 1: non-noisy aer simulator
# 2: non-noisy qasm simulator
# 3: noisy simulator FakeJakarta
# 4: noisy simulator FakeNairobi
# Output: counts, maximum number of counts are obtained for the linearly independent strings
def run(a, sim):
oracle_1 = simon_oracle(a)
N = len(a)
q1 = Simon(oracle_1, N)
count = 0
if sim==1:
backend = Aer.get_backend('aer_simulator')
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
count = counts
elif sim == 2:
backend = Aer.get_backend('qasm_simulator')
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
count = counts
elif sim == 3:
backend = FakeJakarta()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
count = counts
else:
backend = FakeNairobi()
job = execute(q1,backend)
results = job.result()
counts = results.get_counts()
count = counts
return count
# Testing the algorithm for '110' on all 4 simulators
a = '110'
plot_histogram(run(a, 1))
plot_histogram(run(a, 2))
plot_histogram(run(a, 3))
plot_histogram(run(a, 4))
# Testing the algorithm for '1101' on all 4 simulators
a = '1101'
plot_histogram(run(a, 1))
plot_histogram(run(a, 2))
plot_histogram(run(a, 3))
plot_histogram(run(a, 4))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.primitives import Sampler
sampler = Sampler()
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1)
job = sampler.run(circuit)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
circuits = (
random_circuit(2, 2, seed=0, measure=True).decompose(reps=1),
random_circuit(2, 2, seed=1, measure=True).decompose(reps=1),
)
job = sampler.run(circuits)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Quasi-distribution: {result.quasi_dists}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
circuit.measure_all()
parameter_values = [0, 1, 2, 3, 4, 5]
job = sampler.run(circuit, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Parameter values: {parameter_values}")
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Sampler
sampler = Sampler(session=backend)
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Metadata: {result.metadata[0]}")
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
sampler = Sampler()
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the first run: {result.quasi_dists[0]}")
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the second run: {result.quasi_dists[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
estimator_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(estimator_circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(estimator_circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/IceKhan13/purplecaffeine
|
IceKhan13
|
from qiskit_algorithms import QAOA, SamplingVQE
from qiskit_algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.circuit.library import TwoLocal
from qiskit_optimization import QuadraticProgram
from purplecaffeine import Trial, LocalStorage
qubo = QuadraticProgram(name="qubo_trial")
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())
local_storage = LocalStorage("./trials")
with Trial("QAOA trial", storage=local_storage) as trial:
# track some parameters
trial.add_parameter("algo", "qaoa")
trial.add_parameter("sampler", "qiskit.primitives.Sampler")
trial.add_parameter("optimizer", "qiskit.algorithms.optimizers.COBYLA")
# track usefull data
trial.add_text("qubo", qubo.export_as_lp_string())
qaoa_mes = QAOA(
sampler=Sampler(),
optimizer=COBYLA(),
callback=lambda idx, params, mean, std: trial.add_metric("qaoa_history", mean)
)
# run
qaoa = MinimumEigenOptimizer(qaoa_mes)
qaoa_result = qaoa.solve(qubo)
# track results of run
trial.add_text("qaoa_result", qaoa_result.prettyprint())
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
with Trial("VQE trial", storage=local_storage) as trial:
# track some parameters
trial.add_parameter("algo", "vqe")
trial.add_parameter("sampler", "qiskit.primitives.Sampler")
trial.add_parameter("optimizer", "qiskit.algorithms.optimizers.COBYLA")
# track usefull data
trial.add_text("qubo", qubo.export_as_lp_string())
# track some objects
trial.add_circuit("ansatz", ansatz)
vqe_mes = SamplingVQE(
sampler=Sampler(),
ansatz=ansatz,
optimizer=COBYLA(),
callback=lambda idx, params, mean, std: trial.add_metric("vqe_history", mean)
)
# run
vqe = MinimumEigenOptimizer(vqe_mes)
vqe_result = vqe.solve(qubo)
# track results of run
trial.add_text("vqe_result", vqe_result.prettyprint())
local_storage.list()
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
# -*- 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/andre-juan/qiskit_certificate_sample_test
|
andre-juan
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# main classes and functions
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, BasicAer, execute
# visualization stuff
from qiskit.visualization import (plot_histogram, plot_bloch_multivector,
plot_state_city, plot_state_hinton,
plot_state_qsphere,
plot_state_paulivec,
plot_bloch_multivector,
plot_bloch_vector,
plot_gate_map,
plot_error_map)
# gates
from qiskit.circuit.library import CXGate, MCMT, XGate
# quantum info theory stuff
from qiskit.quantum_info import Operator, Statevector, state_fidelity, process_fidelity, average_gate_fidelity
# other tools
from qiskit.tools import job_monitor
from qiskit import IBMQ
def show_figure(fig):
'''
auxiliar function to display plot
even if it's not the last command of the cell
from: https://github.com/Qiskit/qiskit-terra/issues/1682
'''
new_fig = plt.figure()
new_mngr = new_fig.canvas.manager
new_mngr.canvas.figure = fig
fig.set_canvas(new_mngr.canvas)
plt.show(fig)
def test_circuit_qasm(qc):
'''
auxiliar function, used to run a given quantum circuit with the qasm simulator.
measurement is added in this function, so you must pass a circuit
with no classical registers and measurements.
'''
qc.measure_all()
#################################
backend = Aer.get_backend("qasm_simulator")
job = execute(qc, backend, shots=1e5, seed_simulator=42)
results = job.result()
counts = results.get_counts()
return plot_histogram(counts, title="Results", figsize=(12, 4))
def test_circuit_sv(qc, print_stuff=True):
'''
auxiliar function, used to run a given quantum circuit with the statevector simulator.
it optinally prints the state vector components and respective probabilities.
'''
backend = Aer.get_backend("statevector_simulator")
job = execute(qc, backend, seed_simulator=42)
results = job.result()
counts = results.get_counts()
if print_stuff:
sv = results.data(0)['statevector']
probs = sv**2
print(f"Statevector:\t{sv}\n")
print(f"Probabilities:\t{probs}")
return plot_histogram(counts, title="Results", figsize=(12, 4))
# 1 - A)
qc = QuantumCircuit(4, 4)
qc.qregs, qc.cregs
# 2 - C)
qc = QuantumCircuit(1)
qc.ry(3*np.pi/4, 0)
test_circuit_sv(qc)
# 3 - A), B) & D) are possible
inp_reg = QuantumRegister(2, name="inp")
ancilla = QuantumRegister(1, name="anc")
qc = QuantumCircuit(inp_reg, ancilla)
qc.h(inp_reg)
qc.x(ancilla)
qc.barrier()
qc.h(inp_reg[0])
qc.h(inp_reg[1])
qc.x(ancilla)
qc.barrier()
qc.h(inp_reg[0:2])
qc.x(ancilla[0])
qc.draw("mpl")
# 4 - A)
inp = QuantumRegister(3, name="q")
meas = ClassicalRegister(3, name="c")
qc = QuantumCircuit(inp, meas)
# # this would also be possible, but it's not in options
# qc.measure(inp, meas)
qc.measure([0, 1, 2], [0, 1, 2])
qc.draw("mpl")
# 5 - A)
bell = QuantumCircuit(2)
# this makes |01> + |10>
bell.h(0)
bell.x(1)
bell.cx(0, 1)
show_figure(bell.draw("mpl"))
test_circuit_sv(bell)
# 6 - A) & C)
qc = QuantumCircuit(1, 1)
# # both below are equivalent
# qc.h(0)
qc.ry(np.pi/2, 0)
show_figure(qc.draw("mpl"))
simulator = Aer.get_backend("statevector_simulator")
job = execute(qc, simulator)
results = job.result()
outputstate = results.get_statevector(qc)
print(f"\nState:\t{outputstate}\n")
plot_bloch_multivector(outputstate)
# 7 - B)
# S gate induces a pi/2 phase! (is a P gate with \theta = pi/2, i.e., it's a Rz gate with \theta = pi/2)
# tip: S = T^2, hence the "S" stands for "T Squared" (not sure if that's the actual reason for the name, but it's a mnemonic)
qc = QuantumCircuit(1)
qc.h(0)
qc.s(0)
show_figure(qc.draw("mpl"))
simulator = Aer.get_backend("statevector_simulator")
job = execute(qc, simulator)
results = job.result()
outputstate = results.get_statevector(qc)
print(f"\nState:\t{outputstate}\n")
plot_bloch_multivector(outputstate)
# another way to get the statevector, using the Statevector class
qc = QuantumCircuit(1)
qc.h(0)
qc.s(0)
show_figure(qc.draw("mpl"))
outputstate = Statevector.from_label("0").evolve(qc)
print(f"\nState:\t{outputstate}\n")
plot_bloch_multivector(outputstate)
# 8 - A), B)
qc = QuantumCircuit(2)
# # both options below work
# v = [1/np.sqrt(2), 0, 0, 1/np.sqrt(2)]
# qc.initialize(v, [0, 1])
qc.h(0)
qc.cx(0, 1)
show_figure(qc.draw("mpl"))
simulator = Aer.get_backend("statevector_simulator")
result = execute(qc, simulator).result()
statevector = result.get_statevector(qc)
print(f"\nState:\t{statevector}\n")
# 9 - D)
# notice how the first tree are equivalent to cnot
# the last one is the only multi-qubit gate OTHER THAN a cnot ;)
qc = QuantumCircuit(2)
################################
qc.cx(0, 1)
qc.barrier()
################################
qc.cnot(0, 1)
qc.barrier()
################################
# that's nice! multi-controlled x
qc.mct([0], 1)
qc.barrier()
################################
qc.cz(0, 1)
qc.barrier()
################################
qc.draw("mpl")
# 10 - D)
# notice how the first tree are equivalent to the toffoli gate
# the last one is the only multi-qubit gate OTHER THAN a toffoli ;)
qc = QuantumCircuit(3)
################################
qc.ccx(0, 1, 2)
qc.barrier()
################################
qc.mct([0, 1], 2)
qc.barrier()
################################
# very nice construction!
ccx = CXGate().control()
qc.append(ccx, [0, 1, 2])
qc.barrier()
################################
qc.cry(0, 1, 2)
qc.barrier()
################################
qc.draw("mpl")
# another nice way to do toffoli
qc = QuantumCircuit(3)
mct = MCMT(gate='x', num_ctrl_qubits = 2, num_target_qubits = 1)
qc.append(mct, [0,1,2])
qc = qc.decompose()
qc.draw("mpl")
# 11 - B) & C)
qc = QuantumCircuit(3, 3)
qc.barrier()
qc.barrier([0, 1, 2])
qc.draw("mpl")
# 12 - A)
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.t(0)
qc.t(0)
qc.h(0)
qc.measure(0, 0)
show_figure(qc.draw("mpl"))
print("\nSince S = T^2, the circuit above is equivalent to:")
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.s(0)
qc.h(0)
qc.measure(0, 0)
show_figure(qc.draw("mpl"))
# 13 - A)
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.barrier(0)
qc.cx(0, 1)
qc.barrier([0, 1])
# take a look in the docstring!
print(f"\nDepth of the circuit: {qc.depth()}")
qc.draw("mpl")
# 14 - A)
qc = QuantumCircuit(3)
qasm_sim = Aer.get_backend("qasm_simulator")
# coupling map connecting 3 qubits linearly
couple_map = [[0, 1], [1, 2]]
job = execute(qc, qasm_sim, shots=1024, coupling_map=couple_map)
result = job.result()
# 15 - A)
backend = BasicAer.get_backend("qasm_simulator")
qc = QuantumCircuit(3)
execute(qc, backend, shots=1024, coupling_map=[[0, 1], [1, 2]])
# 16 - A), C) & D)
# answer here: https://qiskit.org/documentation/apidoc/providers_basicaer.html#simulators
qasm = BasicAer.get_backend("qasm_simulator")
sv = BasicAer.get_backend("statevector_simulator")
unitary = BasicAer.get_backend("unitary_simulator")
# 17 - B)
backend = BasicAer.get_backend("statevector_simulator")
# 18 - C)
# info: https://qiskit.org/documentation/stubs/qiskit.quantum_info.Operator.html
# # i think the following is possible:
# op = Operator([[0, 1], [1, 0]])
qc = QuantumCircuit(1)
qc.x(0)
op = Operator(qc)
op
# 19 - C)
# info here: https://qiskit.org/documentation/tutorials/circuits_advanced/02_operators_overview.html#Process-Fidelity
# namely:
# "We may also compare operators using the process_fidelity function from the Quantum Information module.
# This is an information theoretic quantity for how close two quantum channels are to each other,
# and in the case of unitary operators it does not depend on global phase."
op_a = Operator(XGate())
op_b = np.exp(1j * 0.5) * Operator(XGate())
pF = process_fidelity(op_a, op_b)
print(f'\nProcess fidelity pF = {pF}')
agF = average_gate_fidelity(op_a, op_b)
print(f'\nAverage gate fidelity agF = {agF}')
# # code below returns an error, because, of course, op_a and op_b are not states,
# # but operators (processes, gates)
# sF = state_fidelity(op_a, op_b)
# print(f'\nState fidelity sF = {sF}')
# 20 - B)
# BE VERY CAREFUL WITH THE ENDIANNESS!!!
qc = QuantumCircuit(2, 2)
qc.x(0)
# better to visualize order of measurements
qc.barrier()
qc.measure([0, 1], [0, 1])
show_figure(qc.draw("mpl"))
simulator = Aer.get_backend("qasm_simulator")
result = execute(qc, simulator, shots=1000).result()
counts = result.get_counts(qc)
print(counts)
# openqasm string
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cnot(0, 1)
qc.barrier()
qc.measure([0, 1], [0, 1])
####################################
show_figure(qc.draw("mpl"))
####################################
print(qc.qasm())
print("\n")
print(qc.qasm(formatted=True))
qasm_str = qc.qasm(filename="qasm_test")
qc_test_str = QuantumCircuit.from_qasm_str(qasm_str)
qc_test_str.draw("mpl")
qc_test_file = QuantumCircuit.from_qasm_file("qasm_test")
qc_test_file.draw("mpl")
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cnot(0, 1)
qc.barrier()
##########################
backend = Aer.get_backend("unitary_simulator")
unitary = execute(qc, backend).result().get_unitary()
unitary
fig, ax = plt.subplots(1, 2, figsize=(8, 3))
sns.heatmap(np.real(unitary), annot=True, ax=ax[0])
ax[0].set_title("Real part")
sns.heatmap(np.imag(unitary), annot=True, ax=ax[1])
ax[1].set_title("Imaginary part")
plt.tight_layout()
plt.show()
qc = QuantumCircuit(3)
qc.h(0)
qc.cnot(0, 1)
qc.cnot(0, 2)
show_figure(qc.draw("mpl"))
####################################
sv = Statevector.from_label("000")
sv = sv.evolve(qc)
print(f'Statevector:\n\n{sv.data}')
show_figure(plot_state_hinton(sv))
####################################
gate = qc.to_gate()
gate.name = "my_gate"
####################################
qc2 = QuantumCircuit(3)
qc2.append(gate, [0, 1, 2])
print("Gate in the circuit:")
show_figure(qc2.draw("mpl"))
print("Decomposed gate in the circuit:")
show_figure(qc2.decompose().draw("mpl"))
# that's more useful when "backend" is a real hardware, of course
job = execute(qc, backend)
job_monitor(job)
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
circ = bell.compose(meas)
show_figure(bell.draw("mpl"))
show_figure(meas.draw("mpl"))
show_figure(circ.draw("mpl"))
backend = Aer.get_backend("qasm_simulator")
job = execute(circ, backend, shots=1e5, seed_simulator=42)
results = job.result()
counts = results.get_counts()
plot_histogram(counts, title="Results", figsize=(6, 4))
simulator = Aer.get_backend("statevector_simulator")
job = execute(bell, simulator)
results = job.result()
psi = results.get_statevector(bell)
print(psi)
# "here we see that there is no information about the quantum state in the single qubit space as all vectors are zero."
# if it was a separable state, it would be shown!
show_figure(plot_bloch_multivector(psi))
show_figure(plot_state_city(psi))
show_figure(plot_state_hinton(psi))
show_figure(plot_state_qsphere(psi))
show_figure(plot_bloch_vector([1,0,0], figsize=(2, 2)))
show_figure(plot_bloch_vector([0,1,0], figsize=(2, 2)))
show_figure(plot_bloch_vector([0,0,1], figsize=(2, 2)))
# already saved my token!
# for more info: https://quantum-computing.ibm.com/lab/docs/iql/manage/account/ibmq
provider = IBMQ.load_account()
accountProvider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
provider.backends(simulator=False)
for bcknd in provider.backends(simulator=False):
print(f"\nBackend: {bcknd.name()}")
backend = provider.get_backend(bcknd.name())
show_figure(plot_gate_map(backend, figsize=(3, 3)))
print(f"Coupling map:\n\n{bcknd._configuration.coupling_map}\n")
print("="*50)
print("="*50)
for bcknd in provider.backends(simulator=False):
print(f"\nBackend: {bcknd.name()}")
backend = provider.get_backend(bcknd.name())
show_figure(plot_error_map(backend))
print("="*50)
print("="*50)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test RemoveFinalMeasurements pass"""
import unittest
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.circuit.classicalregister import Clbit
from qiskit.transpiler.passes import RemoveFinalMeasurements
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestRemoveFinalMeasurements(QiskitTestCase):
"""Test removing final measurements."""
def test_multi_bit_register_removed_with_clbits(self):
"""Remove register when all clbits removed."""
def expected_dag():
q0 = QuantumRegister(2, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(2, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# measure into all clbits of c0
qc.measure(0, 0)
qc.measure(1, 1)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_register_kept_if_measured_clbit_busy(self):
"""
A register is kept if the measure destination bit is still
busy after measure removal.
"""
def expected_dag():
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(1, "c0")
qc = QuantumCircuit(q0, c0)
qc.x(0).c_if(c0[0], 0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(1, "c0")
qc = QuantumCircuit(q0, c0)
# make c0 busy
qc.x(0).c_if(c0[0], 0)
# measure into c0
qc.measure(0, c0[0])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertListEqual(list(dag.cregs.values()), [c0])
self.assertListEqual(dag.clbits, list(c0))
self.assertEqual(dag, expected_dag())
def test_multi_bit_register_kept_if_not_measured_clbit_busy(self):
"""
A multi-bit register is kept if it contains a busy bit even if
the measure destination bit itself is idle.
"""
def expected_dag():
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
qc.x(q0[0]).c_if(c0[0], 0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# make c0[0] busy
qc.x(q0[0]).c_if(c0[0], 0)
# measure into not busy c0[1]
qc.measure(0, c0[1])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
# c0 should not be removed because it has busy bit c0[0]
self.assertListEqual(list(dag.cregs.values()), [c0])
# note: c0[1] should not be removed even though it is now idle
# because it is referenced by creg c0.
self.assertListEqual(dag.clbits, list(c0))
self.assertEqual(dag, expected_dag())
def test_overlapping_register_removal(self):
"""Only registers that become idle directly as a result of
final op removal are removed. In this test, a 5-bit creg
is implicitly created with its own bits, along with cregs
``c0_lower_3`` and ``c0_upper_3`` which reuse those underlying bits.
``c0_lower_3`` and ``c0_upper_3`` reference only 1 bit in common.
A final measure is performed into a bit that exists in ``c0_lower_3``
but not in ``c0_upper_3``, and subsequently is removed. Consequently,
both ``c0_lower_3`` and the 5-bit register are removed, because they
have become unused as a result of the final measure removal.
``c0_upper_3`` remains, because it was idle beforehand, not as a
result of the measure removal, along with all of its bits,
including the bit shared with ``c0_lower_3``."""
def expected_dag():
q0 = QuantumRegister(3, "q0")
c0 = ClassicalRegister(5, "c0")
c0_upper_3 = ClassicalRegister(name="c0_upper_3", bits=c0[2:])
# note c0 is *not* added to circuit!
qc = QuantumCircuit(q0, c0_upper_3)
return circuit_to_dag(qc)
q0 = QuantumRegister(3, "q0")
c0 = ClassicalRegister(5, "c0")
qc = QuantumCircuit(q0, c0)
c0_lower_3 = ClassicalRegister(name="c0_lower_3", bits=c0[:3])
c0_upper_3 = ClassicalRegister(name="c0_upper_3", bits=c0[2:])
# Only qc.clbits[2] is shared between the two.
qc.add_register(c0_lower_3)
qc.add_register(c0_upper_3)
qc.measure(0, c0_lower_3[0])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertListEqual(list(dag.cregs.values()), [c0_upper_3])
self.assertListEqual(dag.clbits, list(c0_upper_3))
self.assertEqual(dag, expected_dag())
def test_multi_bit_register_removed_if_all_bits_idle(self):
"""A multibit register is removed when all bits are idle."""
def expected_dag():
q0 = QuantumRegister(1, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# measure into single bit c0[0] of c0
qc.measure(0, 0)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_multi_reg_shared_bits_removed(self):
"""All registers sharing removed bits should be removed."""
def expected_dag():
q0 = QuantumRegister(2, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(2, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# Create reg with shared bits (same as c0)
c1 = ClassicalRegister(name="c1", bits=qc.clbits)
qc.add_register(c1)
# measure into all clbits of c0
qc.measure(0, c0[0])
qc.measure(1, c0[1])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_final_measures_share_dest(self):
"""Multiple final measurements use the same clbit."""
def expected_dag():
qc = QuantumCircuit(QuantumRegister(2, "q0"))
return circuit_to_dag(qc)
rq = QuantumRegister(2, "q0")
rc = ClassicalRegister(1, "c0")
qc = QuantumCircuit(rq, rc)
qc.measure(0, 0)
qc.measure(1, 0)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertEqual(dag, expected_dag())
def test_remove_chained_final_measurements(self):
"""Remove successive final measurements."""
def expected_dag():
q0 = QuantumRegister(1, "q0")
q1 = QuantumRegister(1, "q1")
c0 = ClassicalRegister(1, "c0")
qc = QuantumCircuit(q0, c0, q1)
qc.measure(q0, c0)
qc.measure(q0, c0)
qc.barrier()
qc.h(q1)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
q1 = QuantumRegister(1, "q1")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(q0, c0, q1, c1)
qc.measure(q0, c0)
qc.measure(q0, c0)
qc.barrier()
qc.h(q1)
qc.measure(q1, c1)
qc.measure(q0, c1)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertEqual(dag, expected_dag())
def test_remove_clbits_without_register(self):
"""clbits of final measurements not in a register are removed."""
def expected_dag():
q0 = QuantumRegister(1, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
qc = QuantumCircuit(q0)
# Add clbit without adding register
qc.add_bits([Clbit()])
self.assertFalse(qc.cregs)
# Measure to regless clbit
qc.measure(0, 0)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_final_barriers_and_measures_complex(self):
"""Test complex final barrier and measure removal."""
def expected_dag():
q0 = QuantumRegister(5, "q0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(q0, c1)
qc.h(q0[0])
return circuit_to_dag(qc)
# ┌───┐┌─┐ ░ ░ ┌─┐
# q0_0: ┤ H ├┤M├─░─────░─┤M├───────────────
# └┬─┬┘└╥┘ ░ ░ └╥┘┌─┐
# q0_1: ─┤M├──╫──░─────░──╫─┤M├────────────
# └╥┘ ║ ░ ░ ░ ║ └╥┘┌─┐
# q0_2: ──╫───╫──░──░──░──╫──╫─┤M├─────────
# ║ ║ ░ ░ ░ ║ ║ └╥┘┌─┐
# q0_3: ──╫───╫──░──░──░──╫──╫──╫─┤M├──────
# ║ ║ ░ ░ ░ ║ ║ ║ └╥┘┌─┐ ░
# q0_4: ──╫───╫──░─────░──╫──╫──╫──╫─┤M├─░─
# ║ ║ ░ ░ ║ ║ ║ ║ └╥┘ ░
# c0: 1/══╩═══╩═══════════╬══╬══╬══╬══╬════
# 0 0 ║ ║ ║ ║ ║
# ║ ║ ║ ║ ║
# c1: 1/══════════════════╬══╬══╬══╬══╬════
# ║ ║ ║ ║ ║
# meas: 5/════════════════╩══╩══╩══╩══╩════
# 0 1 2 3 4
q0 = QuantumRegister(5, "q0")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(q0, c0, c1)
qc.measure(q0[1], c0)
qc.h(q0[0])
qc.measure(q0[0], c0[0])
qc.barrier()
qc.barrier(q0[2], q0[3])
qc.measure_all()
qc.barrier(q0[4])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertEqual(dag, expected_dag())
if __name__ == "__main__":
unittest.main()
|
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.
"""
Tests for the bergholm state preparation
"""
from unittest import TestCase
import random
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Statevector
from qclib.state_preparation import UCGInitialize
from qclib.state_preparation import UCGEInitialize
class TestUCGEInitialize(TestCase):
"""Test UCGEInitialize"""
@staticmethod
def _logical_swap(num_qubits, input_vector, new_order):
qubit_shape = [2] * num_qubits
reshaped_state = input_vector.reshape(qubit_shape)
swapped_vector = np.moveaxis(reshaped_state, new_order, range(len(new_order))).reshape(-1,)
return swapped_vector
def _test_compare_ucg_bipartition(self, num_qubits, input_vector1, input_vector2):
qubit_order = list(range(num_qubits))
random.shuffle(qubit_order)
input_vector = np.kron(input_vector1, input_vector2)
input_vector = self._logical_swap(num_qubits, input_vector, qubit_order)
circuit1 = QuantumCircuit(num_qubits)
UCGInitialize.initialize(circuit1, input_vector)
state1 = Statevector(circuit1)
circuit2 = QuantumCircuit(num_qubits)
UCGEInitialize.initialize(circuit2, input_vector)
state2 = Statevector(circuit2)
circuit1_tranpiled = transpile(circuit1, basis_gates=['u', 'cx'])
circuit2_transpiled = transpile(circuit2, basis_gates=['u', 'cx'])
self.assertTrue(np.allclose(state1, state2))
self.assertTrue(circuit1_tranpiled.depth() >= circuit2_transpiled.depth())
def test_compare_ucg_bipartition_real(self):
num_qubits = 8
input_vector1 = np.random.rand(2 ** (num_qubits//2))
input_vector1 = input_vector1 / np.linalg.norm(input_vector1)
input_vector2 = np.random.rand(2 ** (num_qubits//2))
input_vector2 = input_vector2 / np.linalg.norm(input_vector2)
self._test_compare_ucg_bipartition(num_qubits, input_vector1, input_vector2)
def test_compare_ucg_bipartition_complex(self):
num_qubits = 8
real_part = np.random.rand(2 ** (num_qubits//2))
imag_part = np.random.rand(2 ** (num_qubits//2))
input_vector1 = real_part + 1j * imag_part
input_vector1 = input_vector1 / np.linalg.norm(input_vector1)
real_part = np.random.rand(2 ** (num_qubits//2))
imag_part = np.random.rand(2 ** (num_qubits//2))
input_vector2 = real_part + 1j * imag_part
input_vector2 = input_vector2 / np.linalg.norm(input_vector2)
self._test_compare_ucg_bipartition(num_qubits, input_vector1, input_vector2)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""Tests for qiskit/tools/parallel"""
import os
import time
from unittest.mock import patch
from qiskit.tools.parallel import get_platform_parallel_default, parallel_map
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.pulse import Schedule
from qiskit.test import QiskitTestCase
def _parfunc(x):
"""Function for testing parallel_map"""
time.sleep(1)
return x
def _build_simple_circuit(_):
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
qc = QuantumCircuit(qreg, creg)
return qc
def _build_simple_schedule(_):
return Schedule()
class TestGetPlatformParallelDefault(QiskitTestCase):
"""Tests get_parallel_default_for_platform."""
def test_windows_parallel_default(self):
"""Verifies the parallel default for Windows."""
with patch("sys.platform", "win32"):
parallel_default = get_platform_parallel_default()
self.assertEqual(parallel_default, False)
def test_mac_os_unsupported_version_parallel_default(self):
"""Verifies the parallel default for macOS."""
with patch("sys.platform", "darwin"):
with patch("sys.version_info", (3, 8, 0, "final", 0)):
parallel_default = get_platform_parallel_default()
self.assertEqual(parallel_default, False)
def test_other_os_parallel_default(self):
"""Verifies the parallel default for Linux and other OSes."""
with patch("sys.platform", "linux"):
parallel_default = get_platform_parallel_default()
self.assertEqual(parallel_default, True)
class TestParallel(QiskitTestCase):
"""A class for testing parallel_map functionality."""
def test_parallel_env_flag(self):
"""Verify parallel env flag is set"""
self.assertEqual(os.getenv("QISKIT_IN_PARALLEL", None), "FALSE")
def test_parallel(self):
"""Test parallel_map"""
ans = parallel_map(_parfunc, list(range(10)))
self.assertEqual(ans, list(range(10)))
def test_parallel_circuit_names(self):
"""Verify unique circuit names in parallel"""
out_circs = parallel_map(_build_simple_circuit, list(range(10)))
names = [circ.name for circ in out_circs]
self.assertEqual(len(names), len(set(names)))
def test_parallel_schedule_names(self):
"""Verify unique schedule names in parallel"""
out_schedules = parallel_map(_build_simple_schedule, list(range(10)))
names = [schedule.name for schedule in out_schedules]
self.assertEqual(len(names), len(set(names)))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.visualization import plot_error_map
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
plot_error_map(backend)
|
https://github.com/MahamShafiq/Qiskit
|
MahamShafiq
|
!pip install qiskit
import numpy as np
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute
from qiskit.circuit import Parameter
from qiskit import Aer
from matplotlib import pyplot as plt
from time import time
%matplotlib inline
def preprocess(trainset):
labels = trainset.targets
labels = labels.numpy()
index1 = np.where(labels == 0) # filter 3's
index2 = np.where(labels == 1) # filter on 5's
n=200 # Number of datapoints per class
index = np.concatenate((index1[0][0:n],index2[0][0:n]))
trainset.targets = labels[index]
trainset.data = trainset.data[index]
return trainset
#converts the image into tensors
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()])
trainset = datasets.MNIST(root='./mnistdata', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(preprocess(trainset), batch_size=1, shuffle=True)
dataiter = iter(trainloader)
images, labels = dataiter.next()
print(images.shape)
print(labels.shape)
plt.imshow(images[0].numpy().squeeze(), cmap='gray_r');
def to_numbers(tensor_list):
list = []
for tensor in tensor_list:
list += [tensor.item()]
return list
class QiskitCircuit():
# Specify initial parameters and the quantum circuit
def __init__(self,shots):
self.theta = Parameter('Theta')
self.shots = shots
def create_circuit():
qr = QuantumRegister(1,'q')
cr = ClassicalRegister(1,'c')
ckt = QuantumCircuit(qr,cr)
ckt.h(qr[0])
ckt.barrier()
ckt.ry(self.theta,qr[0])
ckt.barrier()
ckt.measure(qr,cr)
return ckt
self.circuit = create_circuit()
def N_qubit_expectation_Z(self, counts, shots, nr_qubits):
expects = np.zeros(nr_qubits)
for key in counts.keys():
perc = counts[key]/shots
check = np.array([(float(key[i])-1/2)*2*perc for i in range(nr_qubits)])
expects += check
return expects
def bind(self, parameters):
[self.theta] = to_numbers(parameters)
self.circuit.data[2][0]._params = to_numbers(parameters)
def run(self, i):
self.bind(i)
backend = Aer.get_backend('qasm_simulator')
job_sim = execute(self.circuit,backend,shots=self.shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(self.circuit)
return self.N_qubit_expectation_Z(counts,self.shots,1)
class TorchCircuit(Function):
@staticmethod
def forward(ctx, i):
if not hasattr(ctx, 'QiskitCirc'):
ctx.QiskitCirc = QiskitCircuit(shots=100)
exp_value = ctx.QiskitCirc.run(i[0])
result = torch.tensor([exp_value]) # store the result as a torch tensor
ctx.save_for_backward(result, i)
return result
@staticmethod
def backward(ctx, grad_output):
s = np.pi/2
forward_tensor, i = ctx.saved_tensors
# Obtain paramaters
input_numbers = to_numbers(i[0])
gradient = []
for k in range(len(input_numbers)):
input_plus_s = input_numbers
input_plus_s[k] = input_numbers[k] + s # Shift up by s
exp_value_plus = ctx.QiskitCirc.run(torch.tensor(input_plus_s))[0]
result_plus_s = torch.tensor([exp_value_plus])
input_minus_s = input_numbers
input_minus_s[k] = input_numbers[k] - s # Shift down by s
exp_value_minus = ctx.QiskitCirc.run(torch.tensor(input_minus_s))[0]
result_minus_s = torch.tensor([exp_value_minus])
gradient_result = (result_plus_s - result_minus_s)
gradient.append(gradient_result)
result = torch.tensor([gradient])
return result.float() * grad_output.float()
qc = TorchCircuit.apply
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_drop = nn.Dropout2d()
self.h1 = nn.Linear(320, 50)
self.h2 = nn.Linear(50, 1)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 2))
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
x = x.view(-1, 320)
x = F.relu(self.h1(x))
x = F.dropout(x, training=self.training)
x = self.h2(x)
x = qc(x)
x = (x+1)/2 # Normalise the inputs to 1 or 0
x = torch.cat((x, 1-x), -1)
return x
network = Net()
print(network)
optimizer = optim.SGD(network.parameters(), lr=0.003, momentum=0.9)
epochs = 30
time0 = time()
loss_list = []
for epoch in range(epochs):
total_loss = []
target_list = []
for batch_idx, (data, target) in enumerate(trainloader):
target_list.append(target.item())
optimizer.zero_grad()
output = network(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print("Loss = {:.2f} after epoch #{:2d}".format(loss_list[-1],epoch+1))
#print(loss_list[-1])
# Normalise the loss between 0 and 1
print("Training finished, took {:.2f}s after epoch #{:2d}".format(time() - time0,epochs))
for i in range(len(loss_list)):
loss_list[i] += 1
# Plot the loss per epoch
plt.plot(np.arange(epochs),loss_list)
plt.title("Hybrid NN Training Convergence")
plt.xlabel('Training Iterations')
plt.ylabel('Loss')
|
https://github.com/tstopa/Qiskit_for_high_schools
|
tstopa
|
from qiskit import *
from qiskit import QuantumCircuit
circuit = QuantumCircuit(2)
%matplotlib inline
circuit.draw('mpl')
circuit.draw()
circuit.h([0])
circuit.draw()
%matplotlib inline
circuit.draw(output="mpl")
circuit.x([1])
circuit.draw()
circuit.draw(output="mpl")
circuit.cx([1], [0])
circuit.draw()
circuit.draw(output="mpl")
from qiskit import Aer
for backend in Aer.backends():
print(backend.name())
from qiskit import IBMQ
provider = IBMQ.load_account()
provider.backends()
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
!pip install qiskit
!pip install pennylane
import pennylane as qml
from pennylane import numpy as np
#Create a basic default Quantum circuit
#First , create a device to use the qubits
def create_device():
return qml.device("default.qubit",wires=1)
dev=create_device()
#Create an instance of Qnode() class which takes as parameters: the device name
@qml.qnode(dev)
def create_circuit(inputs):
qml.RX(inputs[0],wires=0)
qml.RY(inputs[1],wires=0)
#qml.CNOT(wires=[0,1])
return qml.expval(qml.PauliZ(0))#,qml.expval(qml.PauliZ(1))
d_circuit=qml.grad(create_circuit,argnum=0)
#Create a cost function to optimize
def cost_function(x):
return create_circuit(x)
#Creating an optimizer for gradient descent
def optimize(inputs):
grad_list=[]
opt=qml.AdagradOptimizer(stepsize=0.6,eps=1e-8)
steps=100
for i in range(steps):
inputs=opt.step(cost_function,inputs)
if (i + 1) % 5 == 0:
print("Cost after step {:5d}: {: .7f}".format(i + 1, cost_function(inputs)))
grad_list.append(cost_function(inputs))
print("Optimized rotation angles: {}".format(inputs))
return inputs,grad_list
inp=[0.011,0.012]
print("Cost Function values")
print(create_circuit(inp))
print(cost_function(inp))
print("Computing Adagrad Gradients")
inputs = np.array([0.011, 0.012])
angles,point=optimize(inputs)
print("Finalized gradients")
print(point[-1])
from qiskit.visualization import plot_bloch_vector
%matplotlib inline
rot_x=[0,0,point[-1]]
plot_bloch_vector(rot_x, title="Bloch Sphere")
dev = qml.device('default.qubit.tf', wires=["a","b"])
@qml.qnode(dev)
def dual_circuit(a):
qml.Hadamard("a")
qml.RX(a[0], wires=["a"])
qml.RY(a[1],wires=["b"])
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
def cost_fun(x):
return dual_circuit(x)
def plotter(circuit):
return qml.draw(circuit)
print("Input states to the Circuit")
inputs=[0.011,0.012]
print("Results after convergence")
results=optimize(inputs)
print("Drawing the circuit")
drawer=plotter(dual_circuit)
print(drawer(inputs))
|
https://github.com/dhanton/quantum-chess
|
dhanton
|
import itertools
from qiskit import *
from . import qutils
from qchess.point import Point
from qchess.piece import *
from qchess.pawn import Pawn
from qchess.engines.base_engine import BaseEngine
class QiskitEngine(BaseEngine):
def __init__(self, qchess, width, height):
self.qchess = qchess
self.classical_board = qchess.board
self.width = width
self.height = height
NullPiece.qflag = 0
self.qflag_index = 0
if width * height > qutils.MAX_QUBIT_MEMORY:
print()
print('-----------WARNING-----------')
print('Maximum number of qubits exceeded')
print('You can still play the game, but the program might crash if the system becomes too entangled')
print()
self.generate_circuit()
def generate_circuit(self):
#board main quantum register
self.qregister = QuantumRegister(self.width * self.height)
#ancilla qubits used for some intermediate operations
self.aregister = QuantumRegister(3)
#ancilla qubits used by the mct function in qutils
self.mct_register = QuantumRegister(6)
#classical bits to collapse each square individually
self.cregister = ClassicalRegister(self.width * self.height)
#classical bit for other operations
self.cbit_misc = ClassicalRegister(1)
self.qcircuit = QuantumCircuit(self.qregister, self.aregister, self.mct_register, self.cregister, self.cbit_misc)
#populate the qubits if pieces already exist
for i in range(self.width * self.height):
if self.qchess.get_piece(i) != NullPiece:
self.qcircuit.x(self.qregister[i])
def on_add_piece(self, x, y, piece):
piece.qflag = 1 << self.qflag_index
self.qflag_index += 1
#the value is already |0> (no piece)
#since we want to add the piece with 100% probability, we swap to |1>
q1 = self.get_qubit(x, y)
self.qcircuit.x(q1)
def on_pawn_promotion(self, promoted_pawn, pawn):
promoted_pawn.qflag = pawn.qflag
def get_qubit(self, x, y):
return self.qregister[self.qchess.get_array_index(x, y)]
def get_bit(self, x, y):
return self.cregister[self.qchess.get_array_index(x, y)]
def get_all_entangled_points(self, x, y):
points = []
qflag = self.classical_board[x][y].qflag
if qflag != 0:
for i in range(self.width):
for j in range(self.height):
if self.classical_board[i][j].qflag & qflag != 0:
points.append(Point(i, j))
return points
def entangle_flags(self, qflag1, qflag2):
#nullpiece
if not qflag1 or not qflag2:
return
#already entangled
if qflag1 & qflag2 != 0:
return
for i in range(self.width * self.height):
piece = self.qchess.get_piece(i)
if piece.qflag & qflag1 != 0:
piece.qflag |= qflag2
elif piece.qflag & qflag2 != 0:
piece.qflag |= qflag1
def entangle_path_flags(self, qflag, source, target):
all_qflags = 0
pieces = self.qchess.get_path_pieces(source, target)
for piece in pieces:
all_qflags |= piece.qflag
self.entangle_flags(all_qflags, qflag)
return bool(pieces)
def collapse_by_flag(self, qflag, collapse_all=False):
#nullpiece
if not qflag and not collapse_all:
return
collapsed_indices = []
for i in range(self.width * self.height):
piece = self.qchess.get_piece(i)
if (
not piece.collapsed and
piece != NullPiece and (collapse_all or piece.qflag & qflag != 0)
):
#measure the ith qubit to the ith bit
self.qcircuit.measure(self.qregister[i], self.cregister[i])
collapsed_indices.append(i)
if collapsed_indices:
job = execute(self.qcircuit, backend=qutils.backend, shots=1)
result = job.result()
bitstring = list(result.get_counts().keys())[0].split(' ')[1]
for i, char in enumerate(bitstring[::-1]):
pos = self.qchess.get_board_point(i)
if char == '0' and i in collapsed_indices:
self.classical_board[pos.x][pos.y] = NullPiece
#set to |0> in circuit
self.qcircuit.reset(self.qregister[i])
if char == '1' and i in collapsed_indices:
#set to |1> in circuit
self.qcircuit.reset(self.qregister[i])
self.qcircuit.x(self.qregister[i])
piece = self.qchess.get_piece(i)
assert(piece != NullPiece)
piece.collapsed = True
#since we can't be 100% sure of the original qflag of a piece
#we assign them at random from the qflag used to collapse
#(note: binary qflag has as many '1's as the number of collapsed pieces)
if not collapse_all:
#find the position of the first '1' in binary qflag
binary_qflag = bin(qflag)[2:]
index = len(binary_qflag) - binary_qflag.find('1') - 1
#there should always be enough '1's for every collapsed piece
assert(index < len(bin(qflag)))
#generate a new qflag with all '0's except a '1' in that position
new_qflag = 1 << index
#remove the '1' in that position from binary qflag
qflag ^= new_qflag
#assign new original qflag
piece.qflag = new_qflag
#assign new qflags to all the pieces
if collapse_all:
self.qflag_index = 0
for i in range(self.height * self.width):
piece = self.qchess.get_piece(i)
if piece == NullPiece: continue
piece.qflag = 1 << self.qflag_index
self.qflag_index += 1
all_collapsed = collapse_all
if not all_collapsed:
all_collapsed = True
for i in range(self.width * self.height):
if not self.qchess.get_piece(i).collapsed:
all_collapsed = False
break
#the circuit is reset when all pieces are collapsed, even if
#no new pieces were collapsed in this call
#when all the qubits are |0> or |1>, it's cheaper to just reset
#the circuit than to keep track of all the qubits operations
if all_collapsed:
self.generate_circuit()
def set_piece_uncollapsed(self, point):
if self.classical_board[point.x][point.y] != NullPiece:
self.classical_board[point.x][point.y].collapsed = False
def collapse_path(self, source, target, collapse_target=False, collapse_source=False):
qflag = 0
for piece in self.qchess.get_path_pieces(source, target):
qflag |= piece.qflag
source_piece = self.classical_board[source.x][source.y]
if source_piece != NullPiece and collapse_source:
#force the piece to get collapsed
source_piece.collapsed = False
qflag |= source_piece.qflag
target_piece = self.classical_board[target.x][target.y]
if target_piece != NullPiece and collapse_source:
#force the piece to get collapsed
target_piece.collapsed = False
qflag |= target_piece.qflag
self.collapse_by_flag(qflag)
#return true if path is clear after collapse
return not bool(self.qchess.get_path_pieces(source, target))
def collapse_point(self, x, y):
self.collapse_by_flag(self.classical_board[x][y].qflag)
def collapse_all(self):
self.collapse_by_flag(None, collapse_all=True)
"""
The idea of this function is to calculate all posible permutations
of the pieces entangled with target to see if, in any of the combinations,
target is not empty and the path is blocked at the same time. This
would violate double occupancy so a measurement has to be performed.
"""
def does_slide_violate_double_occupancy(self, source, target):
target_piece = self.classical_board[target.x][target.y]
if target_piece == NullPiece:
#target is always empty
return False
entangled_points = []
path = self.qchess.get_path_points(source, target)
for i in range(self.width * self.height):
point = self.qchess.get_board_point(i)
if self.classical_board[point.x][point.y].qflag & target_piece.qflag != 0:
entangled_points.append(point)
#if a piece is blocking the path independently of the entanglement
#of target, then DO is violated
for point in path:
if self.classical_board[point.x][point.y] != NullPiece and not point in entangled_points:
return True
#the number of pieces is the number of 1s in the target qflag
number_of_pieces = list(bin(target_piece.qflag)).count('1')
assert(len(entangled_points) >= number_of_pieces)
#contains 1 for each piece and the rest are zeroes (empty squares)
permutations = [1] * number_of_pieces + [0] * (len(entangled_points) - number_of_pieces)
#unique permutations of number of pieces in all points
permutations = set(list(itertools.permutations(permutations)))
for perm in permutations:
blocked = False
target_empty = True
#entangled_points and all permutations have the same length
#so they correspond to the same point for the same index
for i, point in enumerate(entangled_points):
if point in path and perm[i] == 1:
blocked = True
if point == target and perm[i] == 1:
target_empty = False
if blocked and not target_empty:
return True
return False
def standard_move(self, source, target, force=False):
piece = self.classical_board[source.x][source.y]
if not force and piece.type == PieceType.PAWN:
return self._standard_pawn_move(source, target)
target_piece = self.classical_board[target.x][target.y]
if target_piece == NullPiece or target_piece == piece:
if piece.is_move_slide():
if self.entangle_path_flags(piece.qflag, source, target):
piece.collapsed = False
#if something may be blocking then the piece might stay in place
#so we don't want to remove it clasically
if target_piece == NullPiece:
target_piece = piece
qutils.perform_standard_slide(self, source, target)
else:
qutils.perform_standard_jump(self, source, target)
self.classical_board[source.x][source.y] = target_piece.copy()
self.classical_board[target.x][target.y] = piece.copy()
else:
if target_piece.color == piece.color:
self.collapse_by_flag(target_piece.qflag)
if (
self.classical_board[source.x][source.y] != NullPiece and
self.classical_board[target.x][target.y] == NullPiece
):
new_source_piece = NullPiece
if piece.is_move_slide():
if self.entangle_path_flags(piece.qflag, source, target):
#if something may be blocking then the piece might stay in place
#so we don't want to remove it clasically
piece.collapsed = False
new_source_piece = piece
qutils.perform_standard_slide(self, source, target)
else:
qutils.perform_standard_jump(self, source, target)
self.classical_board[source.x][source.y] = new_source_piece.copy()
self.classical_board[target.x][target.y] = piece.copy()
else:
self.collapse_by_flag(piece.qflag)
if self.classical_board[source.x][source.y] != NullPiece:
path_empty = self.qchess.is_path_empty(source, target)
#if the path is empty the move is just a jump
if piece.is_move_slide() and not path_empty:
"""
Afer qutils.perform_capture_slide the path is collapsed
already unless does_slide_violate_double_occupancy returns 0,
in which case entanglement occurs.
We call collapse_path to update the classical board.
"""
if qutils.perform_capture_slide(self, source, target):
if self.does_slide_violate_double_occupancy(source, target):
path_clear = self.collapse_path(source, target, collapse_source=True)
if path_clear and self.classical_board[source.x][source.y] == NullPiece:
self.classical_board[target.x][target.y] = piece.copy()
else:
if not self.entangle_path_flags(piece.qflag, source, target):
self.classical_board[source.x][source.y] = NullPiece
else:
piece.collapsed = False
self.classical_board[target.x][target.y] = piece.copy()
else:
path_clear = self.collapse_path(source, target, collapse_source=True)
if path_clear and self.classical_board[source.x][source.y] == NullPiece:
self.classical_board[target.x][target.y] = piece.copy()
else:
qutils.perform_capture_jump(self, source, target)
self.classical_board[source.x][source.y] = NullPiece
self.classical_board[target.x][target.y] = piece.copy()
def _standard_pawn_move(self, source, target):
pawn = self.classical_board[source.x][source.y]
target_piece = self.classical_board[target.x][target.y]
move_type, ep_point = pawn.is_move_valid(source, target, qchess=self.qchess)
#this is checked in QChess class
assert(move_type != Pawn.MoveType.INVALID)
if (
move_type == Pawn.MoveType.SINGLE_STEP or
move_type == Pawn.MoveType.DOUBLE_STEP
):
self.collapse_by_flag(target_piece.qflag)
if (
self.classical_board[source.x][source.y] != NullPiece and
self.classical_board[target.x][target.y] == NullPiece
):
if move_type == Pawn.MoveType.SINGLE_STEP:
qutils.perform_standard_jump(self, source, target)
self.classical_board[source.x][source.y] = NullPiece
else:
if not self.entangle_path_flags(pawn.qflag, source, target):
self.classical_board[source.x][source.y] = NullPiece
else:
pawn.collapsed = False
qutils.perform_standard_slide(self, source, target)
self.classical_board[target.x][target.y] = pawn.copy()
elif move_type == Pawn.MoveType.CAPTURE:
#pawn is the only piece that needs to collapse target when capturing
#because it can't move diagonally unless capturing
self.collapse_by_flag(pawn.qflag | target_piece.qflag)
if (
self.classical_board[source.x][source.y] != NullPiece and
self.classical_board[target.x][target.y] != NullPiece
):
qutils.perform_capture_jump(self, source, target)
self.classical_board[source.x][source.y] = NullPiece
self.classical_board[target.x][target.y] = pawn.copy()
elif move_type == Pawn.MoveType.EN_PASSANT:
if target_piece == NullPiece:
qutils.perform_standard_en_passant(self, source, target, ep_point)
self.classical_board[source.x][source.y] = NullPiece
self.classical_board[target.x][target.y] = pawn
self.classical_board[ep_point.x][ep_point.y] = NullPiece
elif target_piece.color == pawn.color:
self.collapse_by_flag(target_piece.qflag)
if self.classical_board[target.x][target.y] == NullPiece:
qutils.perform_standard_en_passant(self, source, target, ep_point)
self.classical_board[source.x][source.y] = NullPiece
self.classical_board[target.x][target.y] = pawn.copy()
self.classical_board[ep_point.x][ep_point.y] = NullPiece
else:
self.collapse_by_flag(pawn.qflag)
if self.classical_board[source.x][source.y] != NullPiece:
qutils.perform_capture_en_passant(self, source, target, ep_point)
self.classical_board[source.x][source.y] = NullPiece
self.classical_board[target.x][target.y] = pawn.copy()
self.classical_board[ep_point.x][ep_point.y] = NullPiece
def split_move(self, source, target1, target2):
piece = self.classical_board[source.x][source.y]
target_piece1 = self.classical_board[target1.x][target1.y]
target_piece2 = self.classical_board[target2.x][target2.y]
#the source piece is always swapped with the target2
#so unless the path is blocked we know what piece target2 has
new_source_piece = target_piece2
if piece.is_move_slide():
qutils.perform_split_slide(self, source, target1, target2)
path1_blocked = self.entangle_path_flags(piece.qflag, source, target1)
path2_blocked = self.entangle_path_flags(piece.qflag, source, target2)
#set the source piece to null if any of the paths is not blocked,
#since the piece will always slide through that one if the other is blocked
if path1_blocked and path2_blocked and new_source_piece == NullPiece:
new_source_piece = piece
new_source_piece.collapsed = False
else:
qutils.perform_split_jump(self, source, target1, target2)
if not piece.collapsed or not target_piece1.collapsed:
#entangle only the pieces affected by iSwap_sqrt
self.entangle_flags(piece.qflag, target_piece1.qflag)
if target_piece1 == NullPiece:
self.classical_board[target1.x][target1.y] = piece.copy()
self.classical_board[target2.x][target2.y] = piece.copy()
self.classical_board[source.x][source.y] = new_source_piece.copy()
#only uncollapse the pieces if state |t1, t2> is not |00> or |11>
#because iSwap_sqrt leaves these states untouched
if target_piece1 == NullPiece:
self.set_piece_uncollapsed(target1)
self.set_piece_uncollapsed(target2)
def merge_move(self, source1, source2, target):
piece1 = self.classical_board[source1.x][source1.y]
piece2 = self.classical_board[source2.x][source2.y]
target_piece = self.classical_board[target.x][target.y]
#the target piece is always swapped with the source2
#so unless the path is blocked we know what piece source2 has
new_source2_piece = target_piece
if piece1.is_move_slide():
qutils.perform_merge_slide(self, source1, source2, target)
self.entangle_path_flags(piece1.qflag, source1, target)
path2_blocked = self.entangle_path_flags(piece2.qflag, source2, target)
if path2_blocked and new_source2_piece == NullPiece:
new_source2_piece = piece1
new_source2_piece.collapsed = False
else:
qutils.perform_merge_jump(self, source1, source2, target)
if not piece1.collapsed or not piece2.collapsed:
#entangle only the pieces affected by iSwap_sqrt
self.entangle_flags(piece1.qflag, piece2.qflag)
if target_piece == NullPiece:
self.classical_board[target.x][target.y] = piece1.copy()
self.classical_board[source1.x][source1.y] = piece2.copy()
self.classical_board[source2.x][source2.y] = new_source2_piece.copy()
if target_piece == NullPiece:
self.set_piece_uncollapsed(source1)
self.set_piece_uncollapsed(target)
def castling_move(self, king_source, rook_source, king_target, rook_target):
king = self.classical_board[king_source.x][king_source.y]
rook = self.classical_board[rook_source.x][rook_source.y]
king_target_piece = self.classical_board[king_target.x][king_target.y]
rook_target_piece = self.classical_board[rook_target.x][rook_target.y]
#collapse target pieces
self.collapse_by_flag(king_target_piece.qflag | rook_target_piece.qflag)
#if both targets are empty
if (
self.classical_board[king_target.x][king_target.y] == NullPiece and
self.classical_board[rook_target.x][rook_target.y] == NullPiece
):
#the path doesn't neccesarily have to be the shortest straight path
#between king and rook
king_path = self.qchess.get_path_points(king_source, king_target)
rook_path = self.qchess.get_path_points(rook_source, rook_target)
# in general it's the unique combination of their paths
path = []
for point in king_path + rook_path:
if point == king_target or point == rook_target: continue
#we don't need to include empty squares
if self.classical_board[point.x][point.y] == NullPiece: continue
if not point in path:
path.append(point)
#exclude king_target and rook_target just in case
if king_target in path: path.remove(king_target)
if rook_target in path: path.remove(rook_target)
#perform the quantum move
qutils.perform_castle(self, king_source, rook_source, king_target, rook_target, path)
if not path:
#remove from source only if path is empty
self.classical_board[king_source.x][king_source.y] = NullPiece
self.classical_board[rook_source.x][rook_source.y] = NullPiece
else:
#entangle with all the pieces in the path
path_qflags = 0
for point in path:
path_qflags |= self.classical_board[point.x][point.y].qflag
self.entangle_flags(king.qflag, rook.qflag)
self.entangle_flags(path_qflags, king.qflag)
king.collapsed = False
rook.collapsed = False
self.classical_board[king_target.x][king_target.y] = king.copy()
self.classical_board[rook_target.x][rook_target.y] = rook.copy()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test PauliExpectation"""
import itertools
import unittest
from test.python.opflow import QiskitOpflowTestCase
import numpy as np
from qiskit import BasicAer
from qiskit.opflow import (
CX,
CircuitSampler,
H,
I,
ListOp,
Minus,
One,
PauliExpectation,
PauliSumOp,
Plus,
S,
StateFn,
X,
Y,
Z,
Zero,
)
from qiskit.utils import QuantumInstance, algorithm_globals
# pylint: disable=invalid-name
class TestPauliExpectation(QiskitOpflowTestCase):
"""Pauli Change of Basis Expectation tests."""
def setUp(self) -> None:
super().setUp()
self.seed = 97
backend = BasicAer.get_backend("qasm_simulator")
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend, seed_simulator=self.seed, seed_transpiler=self.seed
)
self.sampler = CircuitSampler(q_instance, attach_results=True)
self.expect = PauliExpectation()
def test_pauli_expect_pair(self):
"""pauli expect pair test"""
op = Z ^ Z
# wf = (Pl^Pl) + (Ze^Ze)
wf = CX @ (H ^ I) @ Zero
converted_meas = self.expect.convert(~StateFn(op) @ wf)
self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), 0, delta=0.1)
def test_pauli_expect_single(self):
"""pauli expect single test"""
paulis = [Z, X, Y, I]
states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus]
for pauli, state in itertools.product(paulis, states):
converted_meas = self.expect.convert(~StateFn(pauli) @ state)
matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix()
self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1)
def test_pauli_expect_op_vector(self):
"""pauli expect op vector test"""
paulis_op = ListOp([X, Y, Z, I])
converted_meas = self.expect.convert(~StateFn(paulis_op))
plus_mean = converted_meas @ Plus
np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1)
with self.assertWarns(DeprecationWarning):
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1)
minus_mean = converted_meas @ Minus
np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1)
sampled_minus = self.sampler.convert(minus_mean)
np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1)
zero_mean = converted_meas @ Zero
np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero = self.sampler.convert(zero_mean)
np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1)
sum_zero = (Plus + Minus) * (0.5**0.5)
sum_zero_mean = converted_meas @ sum_zero
np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero_mean = self.sampler.convert(sum_zero_mean)
# !!NOTE!!: Depolarizing channel (Sampling) means interference
# does not happen between circuits in sum, so expectation does
# not equal expectation for Zero!!
np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 1], decimal=1)
for i, op in enumerate(paulis_op.oplist):
mat_op = op.to_matrix()
np.testing.assert_array_almost_equal(
zero_mean.eval()[i],
Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(),
decimal=1,
)
np.testing.assert_array_almost_equal(
plus_mean.eval()[i],
Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(),
decimal=1,
)
np.testing.assert_array_almost_equal(
minus_mean.eval()[i],
Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(),
decimal=1,
)
def test_pauli_expect_state_vector(self):
"""pauli expect state vector test"""
states_op = ListOp([One, Zero, Plus, Minus])
paulis_op = X
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1)
# Small test to see if execution results are accessible
for composed_op in sampled:
self.assertIn("counts", composed_op[1].execution_results)
def test_pauli_expect_op_vector_state_vector(self):
"""pauli expect op vector state vector test"""
paulis_op = ListOp([X, Y, Z, I])
states_op = ListOp([One, Zero, Plus, Minus])
valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]]
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), valids, decimal=1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1)
def test_to_matrix_called(self):
"""test to matrix called in different situations"""
qs = 45
states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)])
paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)])
# 45 qubit calculation - throws exception if to_matrix is called
# massive is False
with self.assertRaises(ValueError):
states_op.to_matrix()
paulis_op.to_matrix()
# now set global variable or argument
try:
algorithm_globals.massive = True
with self.assertRaises(MemoryError):
states_op.to_matrix()
paulis_op.to_matrix()
algorithm_globals.massive = False
with self.assertRaises(MemoryError):
states_op.to_matrix(massive=True)
paulis_op.to_matrix(massive=True)
finally:
algorithm_globals.massive = False
def test_not_to_matrix_called(self):
"""45 qubit calculation - literally will not work if to_matrix is
somehow called (in addition to massive=False throwing an error)"""
qs = 45
states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)])
paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)])
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), [[1, -1, 0], [1, -1, 0]])
def test_grouped_pauli_expectation(self):
"""grouped pauli expectation test"""
two_qubit_H2 = (
(-1.052373245772859 * I ^ I)
+ (0.39793742484318045 * I ^ Z)
+ (-0.39793742484318045 * Z ^ I)
+ (-0.01128010425623538 * Z ^ Z)
+ (0.18093119978423156 * X ^ X)
)
wf = CX @ (H ^ I) @ Zero
expect_op = PauliExpectation(group_paulis=False).convert(~StateFn(two_qubit_H2) @ wf)
self.sampler._extract_circuitstatefns(expect_op)
num_circuits_ungrouped = len(self.sampler._circuit_ops_cache)
self.assertEqual(num_circuits_ungrouped, 5)
expect_op_grouped = PauliExpectation(group_paulis=True).convert(~StateFn(two_qubit_H2) @ wf)
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=self.seed,
seed_transpiler=self.seed,
)
sampler = CircuitSampler(q_instance)
sampler._extract_circuitstatefns(expect_op_grouped)
num_circuits_grouped = len(sampler._circuit_ops_cache)
self.assertEqual(num_circuits_grouped, 2)
@unittest.skip(reason="IBMQ testing not available in general.")
def test_ibmq_grouped_pauli_expectation(self):
"""pauli expect op vector state vector test"""
from qiskit import IBMQ
p = IBMQ.load_account()
backend = p.get_backend("ibmq_qasm_simulator")
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend, seed_simulator=self.seed, seed_transpiler=self.seed
)
paulis_op = ListOp([X, Y, Z, I])
states_op = ListOp([One, Zero, Plus, Minus])
valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]]
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
with self.assertWarns(DeprecationWarning):
sampled = CircuitSampler(q_instance).convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1)
def test_multi_representation_ops(self):
"""Test observables with mixed representations"""
mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X])
converted_meas = self.expect.convert(~StateFn(mixed_ops))
plus_mean = converted_meas @ Plus
with self.assertWarns(DeprecationWarning):
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(
sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1
)
def test_pauli_expectation_non_hermite_op(self):
"""Test PauliExpectation for non hermitian operator"""
exp = ~StateFn(1j * Z) @ One
self.assertEqual(self.expect.convert(exp).eval(), 1j)
def test_list_pauli_sum_op(self):
"""Test PauliExpectation for List[PauliSumOp]"""
test_op = ListOp([~StateFn(PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)]))])
observable = self.expect.convert(test_op)
self.assertIsInstance(observable, ListOp)
self.assertIsInstance(observable[0][0][0].primitive, PauliSumOp)
self.assertIsInstance(observable[0][1][0].primitive, PauliSumOp)
def test_expectation_with_coeff(self):
"""Test PauliExpectation with coefficients."""
with self.subTest("integer coefficients"):
exp = 3 * ~StateFn(X) @ (2 * Minus)
with self.assertWarns(DeprecationWarning):
target = self.sampler.convert(self.expect.convert(exp)).eval()
self.assertEqual(target, -12)
with self.subTest("complex coefficients"):
exp = 3j * ~StateFn(X) @ (2j * Minus)
with self.assertWarns(DeprecationWarning):
target = self.sampler.convert(self.expect.convert(exp)).eval()
self.assertEqual(target, -12j)
if __name__ == "__main__":
unittest.main()
|
https://github.com/arthurfaria/QC_basic_agorithms_qiskit
|
arthurfaria
|
# imports:
import numpy as np
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, assemble, transpile
n=2
dj_circuit = QuantumCircuit(n+1, n)
bits = []
for qubit in range(n+1):
dj_circuit.h(qubit)
# Put the n qubit in state |->
dj_circuit.x(n)
dj_circuit.draw(output = 'mpl')
def oracle(bits):
for i in bits:
return dj_circuit.x(i)
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
# I: Create state |00>x|1>
n=2
dj_circuit = QuantumCircuit(n+1, n)
def full_circuit(bits):
# II: Apply Hadamard to all
for qubit in range(n+1):
dj_circuit.h(qubit)
# Put the n qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw()
# III: Call Oracle
oracle(bits)
# IV: Apply Hadamard to all qubits in the first register
for qubit in range(n):
dj_circuit.h(qubit)
# V: Measure first register
for i in range(n):
measurements = dj_circuit.measure(i, i)
# get results
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(dj_circuit, aer_sim)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
return list(answer)[0]
def oracle_type(bits):
sample = full_circuit(bits)
ans = ''
if sample[0]=='0' and sample[1]=='0':
ans = "constant"
elif sample[0]=='1' and sample[1]=='1':
ans = "constant"
elif sample[0]=='0' and sample[1]=='1':
ans = "balanced"
elif sample[0]=='1' and sample[1]=='0':
ans = "balanced"
else:
ans = "Neither constant nor balanced"
return print(ans)
bits1 = [1,1]
oracle_type(bits1)
|
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/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module to build a Fermi-Hubbard problem."""
from abc import ABC, abstractmethod
from typing import List
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_cold_atom.fermions.fermion_circuit_solver import FermionicBasis
from qiskit_cold_atom.fermions.fermion_gate_library import FermiHubbard
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class FermionicLattice(ABC):
"""Abstract base fermionic lattice."""
@property
@abstractmethod
def size(self) -> int:
"""The number of lattice sites of the system."""
@abstractmethod
def to_fermionic_op(self) -> FermionicOp:
"""Creates the Hamiltonian of the lattice in second quantization.
Returns:
The Hamiltonian as a FermionicOp.
"""
@abstractmethod
def to_circuit(self, time: float = 1.0) -> QuantumCircuit:
"""
Wrap the generator of the system in a QuantumCircuit.
Args:
time: Duration of the time evolution.
Returns:
A quantum circuit which corresponds to the time-evolved Hamiltonian.
"""
class FermiHubbard1D(FermionicLattice):
"""Describes a one-dimensional Fermi-Hubbard model with open boundary conditions."""
def __init__(
self,
num_sites: int,
particles_up: int,
particles_down: int,
hop_strength: float,
int_strength: float,
potential: List[float],
):
r"""
Initialize a one-dimensional fermi-hubbard system. In second quantization this system is
described by the Hamiltonian
:math:`H = \sum_{i=1,\sigma}^{L-1} - J_i (f^\dagger_{i,\sigma} f_{i+1,\sigma} +
f^\dagger_{i+1,\sigma} f_{i,\sigma}) + U \sum_{i=1}^{L} n_{i,\uparrow} n_{i,\downarrow}
+ \sum_{i=1,\sigma}^{L} \mu_i n_{i,\sigma}`
Args:
num_sites: number of lattice sites in the 1D chain.
particles_up: total number of spin-up particles in the lattice
particles_down: total number of spin-down particles in the lattice
hop_strength: strength of hopping between sites
int_strength: strength of the local interaction
potential: list of local phases, must be on length num_wires
Raises:
QiskitColdAtomError: if the length of the potential does not match the system size.
"""
# pylint: disable=invalid-name
self._size = num_sites
self.particles_up = particles_up
self.particles_down = particles_down
self.J = hop_strength
self.U = int_strength
self.basis = FermionicBasis(self.size, n_particles=[self.particles_up, self.particles_down])
if not len(potential) == self.size:
raise QiskitColdAtomError(
f"The length of the potentials {len(potential)} must match system size {self.size}"
)
self.mu = potential
@property
def size(self) -> int:
"""Return the number of sites of the problem."""
return self._size
def to_fermionic_op(self) -> FermionicOp:
"""Construct the hamiltonian of the lattice as a FermionicOp.
Returns:
A FermionicOp defining the systems Hamiltonian
"""
operator_labels = {}
# add hopping terms
for idx in range(self.size - 1):
right_to_left_up = f"+_{idx} -_{idx+1}"
operator_labels[right_to_left_up] = -self.J
left_to_right_up = f"-_{idx} +_{idx+1}"
operator_labels[left_to_right_up] = self.J
right_to_left_down = f"+_{self.size + idx} -_{self.size + idx+1}"
operator_labels[right_to_left_down] = -self.J
left_to_right_down = f"-_{self.size + idx} +_{self.size + idx+1}"
operator_labels[left_to_right_down] = self.J
# add interaction terms
for idx in range(self.size):
opstring = f"+_{idx} -_{idx} +_{self.size + idx} -_{self.size + idx}"
operator_labels[opstring] = self.U
# add potential terms
for idx in range(self.size):
op_up = f"+_{idx} -_{idx}"
operator_labels[op_up] = self.mu[idx]
op_down = f"+_{self.size + idx} -_{self.size + idx}"
operator_labels[op_down] = self.mu[idx]
return FermionicOp(operator_labels, num_spin_orbitals=2 * self.size)
def to_circuit(self, time: float = 1.0) -> QuantumCircuit:
"""
Wrap the generator of the system in a QuantumCircuit.
Args:
time: Duration of the time evolution.
Returns:
A quantum circuit which corresponds to the time-evolved Hamiltonian.
"""
circ = QuantumCircuit(2 * self.size)
circ.append(
FermiHubbard(
num_modes=2 * self.size,
j=[self.J * time] * (self.size - 1),
u=self.U * time,
mu=[mu_i * time for mu_i in self.mu],
),
qargs=range(2 * self.size),
)
return circ
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeAuckland
backend = FakeAuckland()
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
depths = []
gate_counts = []
non_local_gate_counts = []
levels = [str(x) for x in range(4)]
for level in range(4):
circ = transpile(ghz, backend, optimization_level=level)
depths.append(circ.depth())
gate_counts.append(sum(circ.count_ops().values()))
non_local_gate_counts.append(circ.num_nonlocal_gates())
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.bar(levels, depths, label='Depth')
ax1.set_xlabel("Optimization Level")
ax1.set_ylabel("Depth")
ax1.set_title("Output Circuit Depth")
ax2.bar(levels, gate_counts, label='Number of Circuit Operations')
ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates')
ax2.set_xlabel("Optimization Level")
ax2.set_ylabel("Number of gates")
ax2.legend()
ax2.set_title("Number of output circuit gates")
fig.tight_layout()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate
from qiskit.converters import dag_to_circuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
circuit = dag_to_circuit(dag)
circuit.draw('mpl')
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
#setup.py
import numpy as np
from scipy.linalg import expm
from qiskit.extensions import UnitaryGate
from qiskit.circuit.add_control import add_control
from qiskit import Aer
import circuit
import hhl
import tools
#참고 논문 :Low Complexity Quantum Matrix Inversion A기gorithm for non-Hermitian Matrices
def main(A,b,backend,shots,t,n_l,delta):
#Check if Hermitian
if np.allclose(A,A.T) == False:
print("Given A matrice is not Hermitian.")
print("Given Matrices will be transformed into Hermitian formation.")
A = np.vstack((np.hstack((np.zeros_like(A),A)),np.hstack((A.T, np.zeros_like(A))))) # Hermitian의 꼴로 바꿈
b = np.hstack((b,np.zeros_like((np.shape(A)[0]-np.shape(b)[0],1))))
#A의 shape와 동일한 zero array를 생성하고, A의 왼쪽에 배치, horizontal 방향도 마찬가지.
i = complex(0,1) #complex(real part, imaginary part)
U = expm(i*A*t) #여기서 A가 행렬로 주어졌기 때문에, 행렬을 exp에 올리기 위해서는 expm이라는 scipy 패키지가 필요함.
U_gate = UnitaryGate(U) #위에서 구성한 U라는 행렬로써 Unitary gate를 구성할 수 있음. (4*4) 행렬
CU = add_control(U_gate,1,ctrl_state=None, label="CU")
#CU라는 게이트 이름을 label에 저장
#control 되는 경우의 state를 지정 -> 해당사항 없음
#두번째 인자는 컨트롤 큐빗의 개수를 지정함.
n_b = int(np.log2(U.shape[0]))
#Ax =b의 꼴이고, b는 4*1의 shape이므로, A의 행의 개수와 동일함. 따라서, U의 행렬의 행의 개수와 동일함.
#행의 개수에 log2를 취하면 필요한 n_b의 값을 구할 수 있음.
My_HHL_result = hhl.My_HHL(CU,b,n_l,n_b,backend,delta,shots,A,details = True,chevyshev = False)
print("\n")
qiskit_result = hhl.qiskit_HHL(A,b,backend)
print("\n")
classical_result = hhl.classical_HHL(A,b)
print("\n")
#For normalized answer
print("<Un - normalized Case Comparision>")
print('Qiskit Error : {0}'.format(np.linalg.norm(qiskit_result[1]-classical_result[1])))
print('My HHL Error : {0}'.format(np.linalg.norm(My_HHL_result[1]-classical_result[1])))
print("\n")
print("<Normalized Case Comparision>")
print('Qiskit Error : {0}'.format(np.linalg.norm(qiskit_result[0]-classical_result[0])))
print('My HHL Error : {0}'.format(np.linalg.norm(My_HHL_result[0]-classical_result[0])))
if __name__ == "__main__":
#setups
A = np.array([[2,-1],[1,4]]) #non-Hermitian인 경우의 행렬에 대한 저장
b = np.array([1,1])
backend = Aer.get_backend('aer_simulator')
shots = 8192
t = np.pi*2/16
n_l = 3 #QPE 상에서 n_ㅣ는 하다마드로 초기화 되는 부분
delta = 1/16*(2**(n_l-1))
main(A,b,backend,shots,t,n_l,delta)
|
https://github.com/sjana01/QiskitNotebooks
|
sjana01
|
import numpy as np
# importing Qiskit
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_bloch_multivector
# 3 qubit example
qc = QuantumCircuit(3)
qc.h(2)
qc.cp(np.pi/2, 1, 2) # CROT from qubit 1 to qubit 2
qc.cp(np.pi/4, 0, 2) # CROT from qubit 0 to qubit 2
qc.h(1)
qc.cp(np.pi/2, 0, 1) # CROT from qubit 0 to qubit 1
qc.h(0)
qc.swap(0, 2) #swaps qubit 0 and 2
qc.draw('mpl')
# General QFT function
def qft_rot(circuit, n):
'''
circuit: given quantum circuit
n: number of qubit
'''
if n==0:
return circuit
n -= 1 # we want the qubit indexing to go from 0 to n-2
circuit.h(n)
for qubit in range(n):
circuit.cp(np.pi/2**(n-qubit), qubit, n)
qft_rot(circuit, n) # recursively call the function to repeat the process for next n-1 qubits
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-1-qubit)
return circuit
def qft(circuit, n):
''' QFT on the n qubits
'''
qft_rot(circuit, n)
swap_registers(circuit, n)
return circuit
# Draw the circuit with n=4
qc = QuantumCircuit(4)
qft(qc, 4)
qc.draw('mpl')
bin(13)
# Checking the circuit with 13='1101'
#quantum circuit that encodes '1101'
qc = QuantumCircuit(4)
qc.x([0,2,3])
qc.draw('mpl')
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy()
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qft(qc, 4)
qc.draw('mpl')
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
# Inverse QFT
def inv_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
return circuit.decompose() # .decompose() allows us to see the individual gates
# Create the state |13>
state = 13
qc1 = QuantumCircuit(4)
for qubit in range(4):
qc1.h(qubit)
qc1.p(state*np.pi/8, 0)
qc1.p(state*np.pi/4, 1)
qc1.p(state*np.pi/2, 2)
qc1.p(state*np.pi, 3)
qc1.draw('mpl')
# Check this creates the state |13>
qc1_init = qc1.copy()
qc1_init.save_statevector()
sim = Aer.get_backend("aer_simulator")
statevector = sim.run(qc1_init).result().get_statevector()
plot_bloch_multivector(statevector)
# Apply inverse QFT
inv_qc = inv_qft(qc1, 4)
inv_qc.measure_all()
inv_qc.draw('mpl')
# check on simulator
counts = sim.run(qc_init).result().get_counts()
plot_histogram(counts)
# initialize
qpe = QuantumCircuit(4, 3)
qpe.x(3)
# apply the hadamard gates
for qubit in range(3):
qpe.h(qubit)
j = 1
for qubit in range(3):
for i in range(j):
qpe.cp(np.pi/4, qubit, 3)
j *= 2
qpe.barrier()
# apply inverse QFT, we use the in built QFT function
from qiskit.circuit.library import QFT
qpe = qpe.compose(QFT(3, inverse=True), [0,1,2])
# Measure
qpe.barrier()
for n in range(3):
qpe.measure(n,n)
qpe.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator')
shots = 2048
t_qpe = transpile(qpe, aer_sim)
results = aer_sim.run(t_qpe, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Create and set up circuit
qpe2 = QuantumCircuit(4, 3)
# Apply H-Gates to counting qubits:
for qubit in range(3):
qpe2.h(qubit)
# Prepare our eigenstate |psi>:
qpe2.x(3)
# Do the controlled-U operations:
angle = 2*np.pi/3
repetitions = 1
for counting_qubit in range(3):
for i in range(repetitions):
qpe2.cp(angle, counting_qubit, 3);
repetitions *= 2
# Do the inverse QFT:
qpe2 = qpe2.compose(QFT(3, inverse=True), [0,1,2])
# Measure of course!
for n in range(3):
qpe2.measure(n,n)
qpe2.draw('mpl')
# Let's see the results!
shots = 4096
t_qpe2 = transpile(qpe2, aer_sim)
results = aer_sim.run(t_qpe2, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Examples of periods
N = 35
a = 3
import matplotlib.pyplot as plt
# Calculate the plotting data
xvals = np.arange(N)
yvals = [np.mod(a**x, N) for x in xvals]
# Use matplotlib to display it nicely
fig, ax = plt.subplots()
ax.plot(xvals, yvals, linewidth=1, linestyle='dotted', marker='x')
ax.set(xlabel='$x$', ylabel=f'${a}^x$ mod ${N}$',
title="Example of Periodic Function in Shor's Algorithm")
try: # plot r on the graph
r = yvals[1:].index(1) + 1
plt.annotate('', xy=(0,1), xytext=(r,1),
arrowprops=dict(arrowstyle='<->'))
plt.annotate(f'$r={r}$', xy=(r/3,1.5))
except ValueError:
print('Could not find period, check a < N and have no common factors.')
# We solve period finding problem for N=15
# The function c_amod15 returns the controlled-U gate for a, repeated power times.
def c_amod15(a, power):
"""Controlled multiplication by a mod 15"""
if a not in [2,4,7,8,11,13]:
raise ValueError("'a' must be 2,4,7,8,11 or 13")
U = QuantumCircuit(4)
for _iteration in range(power):
if a in [2,13]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a in [7,8]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [4, 11]:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = f"{a}^{power} mod 15"
c_U = U.control()
return c_U
# Specify variables
N_COUNT = 8 # number of counting qubits
a = 8
# Create QuantumCircuit with N_COUNT counting qubits
# plus 4 qubits for U to act on
qc = QuantumCircuit(N_COUNT + 4, N_COUNT)
# Initialize counting qubits
# in state |+>
for qubit in range(N_COUNT):
qc.h(qubit)
# And auxiliary register in state |1>
qc.x(N_COUNT)
# Do controlled-U operations
for qubit in range(N_COUNT):
qc.append(c_amod15(a, 2**qubit), [qubit] + [i+N_COUNT for i in range(4)])
# Do inverse-QFT
qc.append(QFT(N_COUNT, inverse=True), range(N_COUNT))
# Measure circuit
qc.measure(range(N_COUNT), range(N_COUNT))
qc.draw('mpl', fold=-1)
# measurement results
t_qc = transpile(qc, aer_sim)
counts = aer_sim.run(t_qc).result().get_counts()
plot_histogram(counts)
import pandas as pd
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2) # Convert (base 2) string to decimal
phase = decimal/(2**N_COUNT) # Find corresponding eigenvalue
measured_phases.append(phase)
# Add these values to the rows in our table:
rows.append([f"{output}(bin) = {decimal:>3}(dec)",
f"{decimal}/{2**N_COUNT} = {phase:.2f}"])
# Print the rows in a table
headers=["Register Output", "Phase"]
df = pd.DataFrame(rows, columns=headers)
df
from fractions import Fraction
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(15)
rows.append([phase,
f"{frac.numerator}/{frac.denominator}",
frac.denominator])
# Print as a table
headers=["Phase", "Fraction", "Guess for r"]
df = pd.DataFrame(rows, columns=headers)
print(df)
def a_2jmodN(a, j, N):
''' Computes a^{2^j} mod N '''
for _ in range(j):
a = np.mod(a**2 , N)
return a
# Factoring 15 using period finding
def qpe_amod15(a):
"""Performs quantum phase estimation on the operation a*r mod 15.
Args:
a (int): This is 'a' in a*r mod 15
Returns:
float: Estimate of the phase
"""
N_COUNT = 8
qc = QuantumCircuit(4+N_COUNT, N_COUNT)
for q in range(N_COUNT):
qc.h(q) # Initialize counting qubits in state |+>
qc.x(3+N_COUNT) # And auxiliary register in state |1>
for q in range(N_COUNT): # Do controlled-U operations
qc.append(c_amod15(a, 2**q), [q] + [i+N_COUNT for i in range(4)])
qc.append(QFT(N_COUNT, inverse=True), range(N_COUNT)) # Do inverse-QFT
qc.measure(range(N_COUNT), range(N_COUNT))
# Simulate Results
aer_sim = Aer.get_backend('aer_simulator')
# `memory=True` tells the backend to save each measurement in a list
job = aer_sim.run(transpile(qc, aer_sim), shots=1, memory=True)
readings = job.result().get_memory()
print("Register Reading: " + readings[0])
phase = int(readings[0],2)/(2**N_COUNT)
print(f"Corresponding Phase: {phase}")
return phase
phase = qpe_amod15(a) # Phase = s/r
Fraction(phase).limit_denominator(15)
frac = Fraction(phase).limit_denominator(15)
s, r = frac.numerator, frac.denominator
print(r)
from math import gcd
# repeats the algorithm until at least one factor of 15 is found
a = 7
FACTOR_FOUND = False
ATTEMPT = 0
while not FACTOR_FOUND:
ATTEMPT += 1
print(f"\nATTEMPT {ATTEMPT}:")
phase = qpe_amod15(a) # Phase = s/r
frac = Fraction(phase).limit_denominator(N)
r = frac.denominator
print(f"Result: r = {r}")
if phase != 0:
# Guesses for factors are gcd(x^{r/2} ±1 , 15)
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
print(f"Guessed Factors: {guesses[0]} and {guesses[1]}")
for guess in guesses:
if guess not in [1,N] and (N % guess) == 0:
# Guess is a factor!
print("*** Non-trivial factor found: {guess} ***")
FACTOR_FOUND = True
|
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))
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Base classes for an approximate circuit definition."""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Optional, SupportsFloat
import numpy as np
from qiskit import QuantumCircuit
class ApproximateCircuit(QuantumCircuit, ABC):
"""A base class that represents an approximate circuit."""
def __init__(self, num_qubits: int, name: Optional[str] = None) -> None:
"""
Args:
num_qubits: number of qubit this circuit will span.
name: a name of the circuit.
"""
super().__init__(num_qubits, name=name)
@property
@abstractmethod
def thetas(self) -> np.ndarray:
"""
The property is not implemented and raises a ``NotImplementedException`` exception.
Returns:
a vector of parameters of this circuit.
"""
raise NotImplementedError
@abstractmethod
def build(self, thetas: np.ndarray) -> None:
"""
Constructs this circuit out of the parameters(thetas). Parameter values must be set before
constructing the circuit.
Args:
thetas: a vector of parameters to be set in this circuit.
"""
raise NotImplementedError
class ApproximatingObjective(ABC):
"""
A base class for an optimization problem definition. An implementing class must provide at least
an implementation of the ``objective`` method. In such case only gradient free optimizers can
be used. Both method, ``objective`` and ``gradient``, preferable to have in an implementation.
"""
def __init__(self) -> None:
# must be set before optimization
self._target_matrix: np.ndarray | None = None
@abstractmethod
def objective(self, param_values: np.ndarray) -> SupportsFloat:
"""
Computes a value of the objective function given a vector of parameter values.
Args:
param_values: a vector of parameter values for the optimization problem.
Returns:
a float value of the objective function.
"""
raise NotImplementedError
@abstractmethod
def gradient(self, param_values: np.ndarray) -> np.ndarray:
"""
Computes a gradient with respect to parameters given a vector of parameter values.
Args:
param_values: a vector of parameter values for the optimization problem.
Returns:
an array of gradient values.
"""
raise NotImplementedError
@property
def target_matrix(self) -> np.ndarray:
"""
Returns:
a matrix being approximated
"""
return self._target_matrix
@target_matrix.setter
def target_matrix(self, target_matrix: np.ndarray) -> None:
"""
Args:
target_matrix: a matrix to approximate in the optimization procedure.
"""
self._target_matrix = target_matrix
@property
@abstractmethod
def num_thetas(self) -> int:
"""
Returns:
the number of parameters in this optimization problem.
"""
raise NotImplementedError
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Objects to represent the information at a node in the DAGCircuit."""
from __future__ import annotations
import typing
import uuid
import qiskit._accelerate.circuit
from qiskit.circuit import (
Clbit,
ClassicalRegister,
ControlFlowOp,
IfElseOp,
WhileLoopOp,
SwitchCaseOp,
ForLoopOp,
Parameter,
QuantumCircuit,
)
from qiskit.circuit.classical import expr
if typing.TYPE_CHECKING:
from qiskit.dagcircuit import DAGCircuit
DAGNode = qiskit._accelerate.circuit.DAGNode
DAGOpNode = qiskit._accelerate.circuit.DAGOpNode
DAGInNode = qiskit._accelerate.circuit.DAGInNode
DAGOutNode = qiskit._accelerate.circuit.DAGOutNode
def _legacy_condition_eq(cond1, cond2, bit_indices1, bit_indices2) -> bool:
if cond1 is cond2 is None:
return True
elif None in (cond1, cond2):
return False
target1, val1 = cond1
target2, val2 = cond2
if val1 != val2:
return False
if isinstance(target1, Clbit) and isinstance(target2, Clbit):
return bit_indices1[target1] == bit_indices2[target2]
if isinstance(target1, ClassicalRegister) and isinstance(target2, ClassicalRegister):
return target1.size == target2.size and all(
bit_indices1[t1] == bit_indices2[t2] for t1, t2 in zip(target1, target2)
)
return False
def _circuit_to_dag(circuit: QuantumCircuit, node_qargs, node_cargs, bit_indices) -> DAGCircuit:
"""Get a :class:`.DAGCircuit` of the given :class:`.QuantumCircuit`. The bits in the output
will be ordered in a canonical order based on their indices in the outer DAG, as defined by the
``bit_indices`` mapping and the ``node_{q,c}args`` arguments."""
from qiskit.converters import circuit_to_dag # pylint: disable=cyclic-import
def sort_key(bits):
outer, _inner = bits
return bit_indices[outer]
return circuit_to_dag(
circuit,
copy_operations=False,
qubit_order=[
inner for _outer, inner in sorted(zip(node_qargs, circuit.qubits), key=sort_key)
],
clbit_order=[
inner for _outer, inner in sorted(zip(node_cargs, circuit.clbits), key=sort_key)
],
)
def _make_expr_key(bit_indices):
def key(var):
if isinstance(var, Clbit):
return bit_indices.get(var)
if isinstance(var, ClassicalRegister):
return [bit_indices.get(bit) for bit in var]
return None
return key
def _condition_op_eq(node1, node2, bit_indices1, bit_indices2):
cond1 = node1.op.condition
cond2 = node2.op.condition
if isinstance(cond1, expr.Expr) and isinstance(cond2, expr.Expr):
if not expr.structurally_equivalent(
cond1, cond2, _make_expr_key(bit_indices1), _make_expr_key(bit_indices2)
):
return False
elif isinstance(cond1, expr.Expr) or isinstance(cond2, expr.Expr):
return False
elif not _legacy_condition_eq(cond1, cond2, bit_indices1, bit_indices2):
return False
return len(node1.op.blocks) == len(node2.op.blocks) and all(
_circuit_to_dag(block1, node1.qargs, node1.cargs, bit_indices1)
== _circuit_to_dag(block2, node2.qargs, node2.cargs, bit_indices2)
for block1, block2 in zip(node1.op.blocks, node2.op.blocks)
)
def _switch_case_eq(node1, node2, bit_indices1, bit_indices2):
target1 = node1.op.target
target2 = node2.op.target
if isinstance(target1, expr.Expr) and isinstance(target2, expr.Expr):
if not expr.structurally_equivalent(
target1, target2, _make_expr_key(bit_indices1), _make_expr_key(bit_indices2)
):
return False
elif isinstance(target1, Clbit) and isinstance(target2, Clbit):
if bit_indices1[target1] != bit_indices2[target2]:
return False
elif isinstance(target1, ClassicalRegister) and isinstance(target2, ClassicalRegister):
if target1.size != target2.size or any(
bit_indices1[b1] != bit_indices2[b2] for b1, b2 in zip(target1, target2)
):
return False
else:
return False
cases1 = [case for case, _ in node1.op.cases_specifier()]
cases2 = [case for case, _ in node2.op.cases_specifier()]
return (
len(cases1) == len(cases2)
and all(set(labels1) == set(labels2) for labels1, labels2 in zip(cases1, cases2))
and len(node1.op.blocks) == len(node2.op.blocks)
and all(
_circuit_to_dag(block1, node1.qargs, node1.cargs, bit_indices1)
== _circuit_to_dag(block2, node2.qargs, node2.cargs, bit_indices2)
for block1, block2 in zip(node1.op.blocks, node2.op.blocks)
)
)
def _for_loop_eq(node1, node2, bit_indices1, bit_indices2):
indexset1, param1, body1 = node1.op.params
indexset2, param2, body2 = node2.op.params
if indexset1 != indexset2:
return False
if (param1 is None and param2 is not None) or (param1 is not None and param2 is None):
return False
if param1 is not None and param2 is not None:
sentinel = Parameter(str(uuid.uuid4()))
body1 = (
body1.assign_parameters({param1: sentinel}, inplace=False)
if param1 in body1.parameters
else body1
)
body2 = (
body2.assign_parameters({param2: sentinel}, inplace=False)
if param2 in body2.parameters
else body2
)
return _circuit_to_dag(body1, node1.qargs, node1.cargs, bit_indices1) == _circuit_to_dag(
body2, node2.qargs, node2.cargs, bit_indices2
)
_SEMANTIC_EQ_CONTROL_FLOW = {
IfElseOp: _condition_op_eq,
WhileLoopOp: _condition_op_eq,
SwitchCaseOp: _switch_case_eq,
ForLoopOp: _for_loop_eq,
}
_SEMANTIC_EQ_SYMMETRIC = frozenset({"barrier", "swap", "break_loop", "continue_loop"})
# Note: called from dag_node.rs.
def _semantic_eq(node1, node2, bit_indices1, bit_indices2):
"""
Check if DAG nodes are considered equivalent, e.g., as a node_match for
:func:`rustworkx.is_isomorphic_node_match`.
Args:
node1 (DAGOpNode, DAGInNode, DAGOutNode): A node to compare.
node2 (DAGOpNode, DAGInNode, DAGOutNode): The other node to compare.
bit_indices1 (dict): Dictionary mapping Bit instances to their index
within the circuit containing node1
bit_indices2 (dict): Dictionary mapping Bit instances to their index
within the circuit containing node2
Return:
Bool: If node1 == node2
"""
if not isinstance(node1, DAGOpNode) or not isinstance(node1, DAGOpNode):
return type(node1) is type(node2) and bit_indices1.get(node1.wire) == bit_indices2.get(
node2.wire
)
if isinstance(node1.op, ControlFlowOp) and isinstance(node2.op, ControlFlowOp):
# While control-flow operations aren't represented natively in the DAG, we have to do
# some unpleasant dispatching and very manual handling. Once they have more first-class
# support we'll still be dispatching, but it'll look more appropriate (like the dispatch
# based on `DAGOpNode`/`DAGInNode`/`DAGOutNode` that already exists) and less like we're
# duplicating code from the `ControlFlowOp` classes.
if type(node1.op) is not type(node2.op):
return False
comparer = _SEMANTIC_EQ_CONTROL_FLOW.get(type(node1.op))
if comparer is None: # pragma: no cover
raise RuntimeError(f"unhandled control-flow operation: {type(node1.op)}")
return comparer(node1, node2, bit_indices1, bit_indices2)
node1_qargs = [bit_indices1[qarg] for qarg in node1.qargs]
node1_cargs = [bit_indices1[carg] for carg in node1.cargs]
node2_qargs = [bit_indices2[qarg] for qarg in node2.qargs]
node2_cargs = [bit_indices2[carg] for carg in node2.cargs]
# For barriers, qarg order is not significant so compare as sets
if node1.op.name == node2.op.name and node1.name in _SEMANTIC_EQ_SYMMETRIC:
node1_qargs = set(node1_qargs)
node1_cargs = set(node1_cargs)
node2_qargs = set(node2_qargs)
node2_cargs = set(node2_cargs)
return (
node1_qargs == node2_qargs
and node1_cargs == node2_cargs
and _legacy_condition_eq(
getattr(node1.op, "condition", None),
getattr(node2.op, "condition", None),
bit_indices1,
bit_indices2,
)
and node1.op == node2.op
)
# Bind semantic_eq from Python to Rust implementation
DAGNode.semantic_eq = staticmethod(_semantic_eq)
|
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":
### added x gate ###
qc.x(qubit)
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
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.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# 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)
# Number of trotter steps
trotter_steps = 15 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[3], qr[5]])
qc.cx(qr[3], qr[1])
qc.cx(qr[5], qr[3])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time/trotter_steps})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw("mpl") # only view trotter gates
# 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")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1])
print('Job ID', cal_job.job_id())
dt_now = datetime.datetime.now()
print(dt_now)
with open("jobs_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_15step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "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_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_jakarta_15step_20220412_031437_.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')
# set the target state
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
# mit_results = meas_fitter.filter.apply(job.result()) # apply QREM
rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq')
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/Ilan-Bondarevsky/qiskit_algorithm
|
Ilan-Bondarevsky
|
from qiskit import QuantumCircuit, QuantumRegister, AncillaRegister, ClassicalRegister
from bit_functions import full_bitfield, get_qubit_list
from Grover.grover_cirq import grover_circuit
from logic_gate_circuits import xnor_gate
from backend_operation import run_simulator
class sudoko_grover(grover_circuit):
def __init__(self, max_num : int = 4):
super().__init__()
self.max_num = max_num
self.min_num = 1
self.max_num_circuit = None
def same_num_cirq(self):
bit = self.max_num.bit_length()
qubit_A = QuantumRegister(bit, 'A')
qubit_B = QuantumRegister(bit, 'B')
anc = AncillaRegister(bit + 1)
qc = QuantumCircuit(qubit_A, qubit_B, anc)
for i in range(bit):
xnor_qc = xnor_gate()
qc = qc.compose(xnor_qc, [qubit_A[i], qubit_B[i], anc[i]])
inv_qc = qc.inverse()
qc.mcx(anc[:-1], anc[-1])
qc = qc.compose(inv_qc, list(qubit_A) + list(qubit_B) + list(anc))
return qc
def calculation_logic(self):
pass
def build_iteration(self):
pass
if __name__ == "__main__":
x = sudoko_grover()
y=x.same_num_cirq()
print(y.draw())
y.add_register(ClassicalRegister(1))
y.measure(y.qubits[-1],y.clbits[-1])
print(y.draw())
print(run_simulator(y).get_counts())
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
qc = QuantumCircuit(2)
qc.id(0)
qc.x(1)
op_XI = Operator(qc)
print(op_XI.data)
from qiskit.quantum_info import Operator
op_XI = Operator([[0, 0, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 1, 0, 0]])
print(op_XI.data)
from qiskit.quantum_info import Operator, Pauli
op_XI = Operator(Pauli('XI'))
print(op_XI.data)
from qiskit.quantum_info import Operator
from qiskit.circuit.library.standard_gates \
import CPhaseGate
import numpy as np
op_CP = Operator(CPhaseGate(np.pi / 4))
print(op_CP.data)
from qiskit.quantum_info import Pauli
pauli_piXZ = Pauli('-XZ')
print(pauli_piXZ.to_matrix())
from qiskit import QuantumCircuit
from qiskit.quantum_info import Pauli
qc = QuantumCircuit(2)
qc.z(0)
qc.x(1)
pauli_XZ = Pauli(qc)
print(pauli_XZ.equiv(Pauli('-XZ')))
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit import *
circuit = QuantumCircuit(3,3)
# draw ckt
%matplotlib inline
circuit.draw(output='mpl')
# teleport from q0 to q2 (applying x gate)
circuit.x(0)
circuit.barrier()
circuit.draw()
circuit.h(1)
circuit.cx(1,2)
circuit.draw()
circuit.cx(0,1)
circuit.h(0)
circuit.draw()
circuit.barrier()
circuit.measure([0,1],[0,1])
circuit.draw()
circuit.barrier()
circuit.cx(1,2)
circuit.cz(0,2)
circuit.draw()
circuit.draw(output='mpl')
circuit.measure(2,2)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots = 1024).result()
counts = result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
circuit.draw()
print(counts)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# 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/swe-train/qiskit__qiskit
|
swe-train
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_histogram
# Use Aer's qasm_simulator
simulator = QasmSimulator()
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# compile the circuit down to low-level QASM instructions
# supported by the backend (not needed for simple circuits)
compiled_circuit = transpile(circuit, simulator)
# Execute the circuit on the qasm simulator
job = simulator.run(compiled_circuit, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(compiled_circuit)
# print("\nTotal count for 00 and 11 are:",counts)
# Draw the ci
circuit.draw(output="latex", filename="printing.png")
|
https://github.com/fiasqo-io/quantumcircuit_gym
|
fiasqo-io
|
import itertools as it
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, execute, Aer
from qutip import qeye, basis, Qobj, fidelity, hadamard_transform, qubit_states, tracedist
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
class QuantCircuitEnv(gym.Env):
"""
A quantum circuit implementation using the Qiskit library, containing methods to construct
and simulate quantum circuits designed to perform specific operations. Mainly for use in
Reinforcement Learning with an agent choosing and learning actions for a specific goal.
"""
def __init__(self):
pass
def var_init(self,
num_qubits,
unitary=False,
gate_group='pauli',
connectivity='nearest_neighbour',
goal_state=None,
goal_unitary=None,
custom_gates=None,
custom_connectivity=None):
"""
Initialises the Quantum Circuit Environment object with arguments since gym.make can't
do so.
Args:
num_qubits (int): number of qubits in the desired circuit
unitary (bool): if True sets environment to use unitary matrices,
otherwise uses statevectors
gate_group (str): string to define the gate group used,
options include 'pauli','clifford' and 'IQP'
goal_state (list): list of complex values defining goal statevector,
must have 2**num_qubits values
goal_unitary (np.array): goal unitary matrix,
must have shape (2**num_qubits, 2**num_qubits)
custom_gates (list): list of gate functions to use in the circuit
custom_connectivity (np.array): a NxN binary matrix where N is the number of qubits,
with entry [i,j] = 1 when qubit i is physically
connected to qubit j.
Return:
None
"""
# Define whether using unitaries or statevectors
try:
self.is_unitary = bool(unitary)
except ValueError:
print('Please use a boolean value for "unitary".')
# Set number of qubits in circuit, and dimensionality
try:
self.num_qubits = int(num_qubits)
except ValueError:
print('Please use an integer value for number of qubits.')
self.dimension = 2**self.num_qubits
# Initialise qiskit circuit object
self.q_reg = QuantumRegister(self.num_qubits)
self.qcircuit = QuantumCircuit(self.q_reg)
# Initialise current/goal statevectors
self.current_state = [1+0j] + [0+0j]*(self.dimension - 1)
# concatenate real and imaginary parts of statevector into one array
self.comp_state = np.append(np.real(self.current_state), np.imag(self.current_state))
if goal_state is None:
self.goal_state = [1+0j]+[0+0j]*(self.dimension-1)
else:
assert len(goal_state) == self.dimension, 'Goal state is not correct length.'
self.goal_state = goal_state
self.comp_goal = np.append(np.real(self.goal_state), np.imag(self.goal_state))
# Initialise unitaries
if self.is_unitary:
self.current_unitary = qeye(self.dimension).full()
if goal_unitary is None:
self.goal_unitary = qeye(self.dimension).full()
else:
assert np.asarray(goal_unitary).shape == (self.dimension, self.dimension), ('Goal '
'unitary is not correct shape.')
self.goal_unitary = goal_unitary
# Define gate group used
self.gate_group = gate_group
self.set_gate_group(gate_group, custom_gates)
# Initialise qubit connectivity
self.define_connectivity(connectivity, custom_connectivity)
# Initialise gate list
self.gate_list = self._create_gates()
# Initialise other various values
self.basis_state = basis(self.dimension)
self.gate_count = 1
self.action_space_n = len(self.gate_list)
self.num_actions = self.num_qubits*6
self.EPS = 1e-10
self.has_run = False
def step(self, action):
"""
Takes a single step (action) inside the environment
Args:
action (int): index of the action in self.gate_list generated by self._create_gates -
containing all combinations of legal qubit/gate combinations
Return:
diff (np.array): difference between current and goal state
reward (float): reward gained from taking the specified action
done (bool): True if agent has reached the goal, False otherwise
measures (dict): dictionary containing the measure used to determine reward
"""
if not self.has_run:
self.set_gate_group(self.gate_group)
self.gate_list = self._create_gates()
self.has_run = True
assert action in range(self.action_space_n), 'Not a valid action.'
# Initialize done variable
done = False
# Extra reward for using identities instead of other gates - may not be needed?
extra = 0
# Keep track of number of gates used
self.gate_count += 1
# Check if multi-qubit gate - self.gate_list[action][0] is a tuple of the qubits
if len(self.gate_list[action][0]) > 1:
# Apply gate to circuit - the second arg of the tuple is the gate function
self.gate_list[action][1](self.q_reg[self.gate_list[action][0][0]],
self.q_reg[self.gate_list[action][0][1]])
else:
# Do the same but for single qubit gates
self.gate_list[action][1](self.q_reg[self.gate_list[action][0][0]])
# Unitary case
if self.is_unitary:
self.job = execute(self.qcircuit,
backend=qiskit.BasicAer.get_backend('unitary_simulator'))
self.current_unitary = self.job.result().get_unitary(self.qcircuit)
diff = np.asarray(self.goal_unitary-self.current_unitary).flatten()
diff = np.append(np.real(diff), np.imag(diff))
# Statevector case
else:
self.job = execute(self.qcircuit,
backend=qiskit.BasicAer.get_backend('statevector_simulator'))
self.current_state = self.job.result().get_statevector(self.qcircuit)
self.comp_state = np.append(np.real(self.current_state), np.imag(self.current_state))
diff = self.comp_goal - self.comp_state
reward = 0
# Reward inversely proportional to number of gates used if fidelity is hit
if round(self.fidelity(), 3) == 1:
reward = 50*(1/(self.gate_count+1))
done = True
return diff, reward, done, {'fidelity': round(self.fidelity(), 3)}
def reset(self):
"""
Resets the circuit to empty and any relevant variables to their initial state
Return:
diff (list): real and imaginary parts of the current reset quantum state/unitary
"""
self.qcircuit = QuantumCircuit(self.q_reg)
self.current_state = [1+0j]+[0+0j]*(2**self.num_qubits-1)
self.current_unitary = qeye(2**self.num_qubits).full()
self.comp_state = np.append(np.real(self.current_state), np.imag(self.current_state))
self.gate_count = 0
self.has_run = False
if self.is_unitary:
diff = np.asarray(self.goal_unitary-self.current_unitary).flatten()
diff = np.append(np.real(diff), np.imag(diff))
else:
diff = self.comp_goal - self.comp_state
return diff
def render(self):
"""
Return:
text drawing of the current circuit represented by the QuantumCircuit object
"""
return self.qcircuit.draw()
def define_goal(self, goal_state):
"""
Defines goal statevector or unitary matrix for the circuit.
Args:
goal_state (list): flattened statevector or unitary matrix
Return:
None
"""
if self.is_unitary:
self.goal_unitary = goal_state
elif not self.is_unitary:
assert len(goal_state) == len(self.current_state)
self.goal_state = goal_state
self.comp_goal = np.append(np.real(goal_state), np.imag(goal_state))
def sample(self):
"""
Return:
action (int): a specific action in the circuit environment action space
"""
action = np.random.randint(0, self.action_space_n)
return action
def fidelity(self):
"""
Calculates fidelity of current and goal state/unitary.
Return:
fid (float): fidelity measure
"""
if self.is_unitary:
assert self.current_unitary.shape == self.goal_unitary.shape
fid = fidelity(Qobj(self.current_unitary)*self.basis_state,
Qobj(self.goal_unitary)*self.basis_state)
else:
assert len(self.current_state) == len(self.goal_state)
fid = fidelity(Qobj([self.current_state]), Qobj([self.goal_state]))
return fid
def set_gate_group(self, gate_group, custom_gates=None):
"""
Defines the gate group to be used within the enviroment
Args:
gate_group (str): name of the gate group used
custom_gates (dict): A set of custom gates may be defined using a dictionary,
the form looks like{"gate_name":gate_function}
Returns:
None
"""
gate_group = gate_group.lower()
if gate_group == 'clifford':
# Clifford group uses cnot, phase gate and hadamard
self.gate_group_list = [
self.qcircuit.iden,
self.qcircuit.cx,
self.qcircuit.h,
self.qcircuit.s,
self.qcircuit.t
]
elif gate_group == 'pauli':
self.gate_group_list = [
self.qcircuit.iden,
self.qcircuit.h,
self.qcircuit.x,
self.qcircuit.z,
self.qcircuit.cx
]
elif gate_group == 'IQP':
self.gate_group_list = [
self.qcircuit.iden,
self.qcircuit.t,
(2, self.c_s_gate)
]
# Sets up the circuit with initial hadamard gates,
# as is necessary for circuits with the IQP format
temp_state = (hadamard_transform(self.num_qubits)*
qubit_states(self.num_qubits)).full()
self.qcircuit.initialize(temp_state.flatten(),
[self.q_reg[i] for i in range(self.num_qubits)])
elif gate_group == 'custom':
assert custom_gates is not None, 'custom_gates is not defined.'
self.gate_group_list = custom_gates
else:
raise "%s gate_group not defined!"%gate_group
def _create_gates(self):
"""
Create a list of gate/qubit tuples that contains all possible combinations
given a defined qubit connectivity.
Return:
gate_list (list): list of tuples of all qubit/gate combinations
"""
gate_list = []
for gates in self.gate_group_list:
if isinstance(gates, tuple):
gate_qubits = gates[0]
gates = gates[1]
else:
# Qiskit defines the gate function as 'iden',
# but in the descriptions of a circuit object calls the identity 'id'
# changed to make valid key for the dictionary
if gates.__name__ == 'iden':
name = 'id'
else:
name = gates.__name__
gate_qubits = self.qcircuit.definitions[str(name)]['n_bits']
# Check if multi-qubit gate (currently max is 2 qubits)
if gate_qubits > 1:
for qubits_t in range(self.num_qubits):
for qubits_c in range(self.num_qubits):
# Check for connectivity, and don't allow connection with self
if self.connectivity[qubits_t, qubits_c] == 1 and qubits_t != qubits_c:
gate_list.append(((qubits_t, qubits_c), gates))
else:
# Assumption made that these are single-qubit gates
for i in range(self.num_qubits):
gate_list.append(((i, ), gates))
return gate_list
def define_connectivity(self, connectivity, custom_matrix=None):
"""
Creates a binary matrix that describes the connections between qubits
Args:
connectivity (str): string representation of connectivity format
custom_matrix (np.array): binary array with index pairs denoting a connection between
those two qubits i.e. (i,j) = 1 if qubit i is connected to
qubit j. This is a one way mapping, if two way connectivity is
desired the array must be symmetric about the diagonal.
Return:
None
"""
connectivity_matrix = np.identity(self.num_qubits)
connectivity = connectivity.lower()
assert connectivity in ['nearest_neighbour', 'fully_connected', 'custom', 'ibm']
if connectivity == 'nearest_neighbour':
for i in range(self.num_qubits-1):
connectivity_matrix[i, i+1] = 1
connectivity_matrix[i+1, i] = 1
# Connects extremities
connectivity_matrix[0, self.num_qubits-1] == 1
connectivity_matrix[self.num_qubits-1, 0] == 1
elif connectivity == 'fully_connected':
#fully conencted mean every conenction is allowable
connectivity_matrix = np.ones((self.num_qubits, self.num_qubits))
elif connectivity == "custom":
assert np.asarray(custom_matrix).shape == ((self.num_qubits, self.num_qubits),
"Dimension mismatch!")
connectivity_matrix = custom_matrix
elif connectivity == "ibm":
assert self.num_qubits in [5, 14, 20]
# Based on IBMQ 5 Tenerife and IBMQ 5 Yorktown
if self.num_qubits == 5:
connectivity_matrix = np.array([[0, 1, 1, 0, 0],
[1, 0, 1, 0, 0],
[1, 1, 0, 1, 1],
[0, 0, 1, 0, 1],
[0, 0, 1, 1, 0]])
# Based on IBMQ 14 Melbourne
elif self.num_qubits == 14:
connectivity_matrix = np.zeros((14, 14))
for i in range(14):
for j in range(14):
if i + j == 14:
connectivity_matrix[(i, j)] = 1
for i in range(13):
if i != 6:
connectivity_matrix[(i, i+1)] = 1
# Based on IBMQ 20 Tokyo
elif self.num_qubits == 20:
connectivity_matrix = np.zeros((20, 20))
for k in [0, 5, 10, 15]:
for j in range(k, k+4):
connectivity_matrix[(j, j+1)] = 1
for k in range(5):
connectivity_matrix[(k, k+5)] = 1
connectivity_matrix[(k+5, k+10)] = 1
connectivity_matrix[(k+10, k+15)] = 1
for k in [1, 3, 5, 7, 11, 13]:
connectivity_matrix[(k, k+6)] = 1
for k in [2, 4, 6, 8, 12, 14]:
connectivity_matrix[(k, k+4)] = 1
self.connectivity = connectivity_matrix
def plot_connectivity_graph(self):
"""
Draws a graph of nodes and edges that represents the physical connectivity of the qubits.
Graph will not be completely symmetric and will not be an exact replica of the framework,
but will provide an accurate visual representation of the connections between qubits.
Returns:
None
"""
graph = nx.Graph()
graph.add_nodes_from([i for i in range(self.num_qubits)])
for i in range(self.num_qubits):
for j in range(self.num_qubits):
if self.connectivity[(i, j)] == 1:
graph.add_edge(i, j)
nx.draw(graph, with_labels=True, font_weight='bold')
plt.show()
def trace_norm(self):
"""
Calculates trace norms of density state of matrix - to use this as a metric,
take the difference (p_0 - p_1) and return the value of the trace distance
Return:
dist (float): trace distance of difference between density matrices
"""
current = Qobj(self.current_state)
goal = Qobj(self.goal_state)
density_1 = current*current.dag()
density_2 = goal*goal.dag()
dist = tracedist(density_1, density_2)
return dist
def c_s_gate(self, target, control):
"""
Creates custom composite gate from defined qiskit gates that is contained in the IQP group
Args:
target (int): index of the target qubit
control (int): index of the control qubit
Return:
None
"""
# We need to create a controlled-S gate using simple gates from qiskit,
# this can be done using cnots and T gates + T_dag
self.qcircuit.cx(control, target)
self.qcircuit.tdg(target)
self.qcircuit.cx(control, target)
self.qcircuit.t(target)
self.qcircuit.t(control)
def make_curriculum(self, num_gates, loop_list=None):
"""
Designs curriculum for agent which gradually increases goal difficulty.
Args:
num_gates (int): max number of gates for a circuit in the curriculum
loop_list (list): A list of times you want to loop each curriculum stage
Return:
curriculum (list): list of goal unitaries/statevectors for the agent to target
tracker (array): array of how many goals found in each section
"""
if not loop_list is None:
assert len(loop_list) == num_gates, ('List of number of loops for each gate'
'must have length num_gates')
loop_num = 0
gate_group_n = len(self.gate_group_list)
curriculum, state_check, tracker = ([], [], [])
self.gate_list = self._create_gates()
num_moves = len(self.gate_list)
moves = np.linspace(0, num_moves-1, num_moves)
for j in range(0, num_gates):
max_gates = j+1
curriculum_sect = []
if max_gates < 4:
all_moves = [p for p in it.product(moves, repeat=max_gates)]
else:
all_moves = np.zeros(5000)
for k in range(0, len(all_moves)):
self.reset()
self.set_gate_group(self.gate_group)
l = 0
move_set = all_moves[k]
while l != max_gates:
if max_gates >= 4:
#randomly search combinations
i = np.random.randint(0, num_moves)
else:
#move through every combination
i = move_set[l]
self.gate_list = self._create_gates()
tple = self.gate_list[int(i)]
if len(tple[0]) > 1:
tple[1](self.q_reg[tple[0][0]], self.q_reg[tple[0][1]])
else:
tple[1](self.q_reg[tple[0][0]])
l += 1
else:
job2 = execute(self.qcircuit,
backend=qiskit.BasicAer.get_backend('statevector_simulator'))
state_to_check = job2.result().get_statevector(self.qcircuit)
for i in range(len(state_to_check.real)):
state_to_check.real[i] = np.round(state_to_check.real[i], 4)
state_to_check.imag[i] = np.round(state_to_check.imag[i], 4)
if self.is_unitary:
job = execute(self.qcircuit,
backend=qiskit.BasicAer.get_backend('unitary_simulator'))
current_state = job.result().get_unitary(self.qcircuit)
for i in range(len(current_state.real)):
for j in range(len(current_state[0].real)):
current_state.real[i][j] = np.round(current_state.real[i][j], 4)
current_state.imag[i][j] = np.round(current_state.imag[i][j], 4)
else:
current_state = state_to_check
if len(state_check) >= 1:
if (any(np.equal(state_check, state_to_check).all(1)) or
any(np.equal(state_check, -state_to_check).all(1))):
pass
else:
curriculum_sect.append(current_state)
state_check.append(state_to_check)
else:
curriculum_sect.append(current_state)
state_check.append(state_to_check)
tracker.append(len(curriculum_sect))
if loop_list is None:
loop = 1
else:
loop = loop_list[loop_num]
curriculum += curriculum_sect*loop
loop_num += 1
for i in range(len(curriculum)):
curriculum[i] = np.ndarray.tolist(curriculum[i])
return curriculum, tracker
|
https://github.com/AnshDabkara/Qiskit_Algorithm
|
AnshDabkara
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute, assemble, QuantumRegister, ClassicalRegister
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from numpy import pi
marked = ('11') # state which we want to search
n = len(marked)
gs_circuit = QuantumCircuit(n+1,n)
gs_circuit.clear()
gs_circuit.x(n)
gs_circuit.h(range(n+1))
gs_circuit.barrier()
# oracle operator
for i, yes in enumerate(marked):
if yes == '0':
gs_circuit.x(i)
gs_circuit.mcx(list(range(n)),n)
for i, yes in enumerate(marked):
if yes == '0':
gs_circuit.x(i)
gs_circuit.barrier()
# diffuser operator
gs_circuit.h(range(n))
gs_circuit.x(range(n))
gs_circuit.cx(0,1)
gs_circuit.x(range(n))
gs_circuit.h(range(n))
gs_circuit.barrier()
# measure
gs_circuit.measure(range(n),range(n))
gs_circuit.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator') #Local Simulator
shots = 1024 #No. of times the circuit is running
qobj = assemble(gs_circuit, shots = shots)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts) #Plotting the result
# Converting the binary string to decimal
b_str = list(counts.keys())[0]
b = int(b_str,2)
print('ans:',b)
|
https://github.com/DanKim44/CodingWithQiskitS2
|
DanKim44
|
#Coding With Qiskit S2E6 Quantum Machine Learning
import qiskit
from matplotlib import pyplot as plt
import numpy as np
from qiskit.ml.datasets import ad_hoc_data
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.circuit.library import ZZFeatureMap
from qiskit.aqua.algorithms import QSVM
from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
feature_dim = 2
training_data_set_size = 20
testing_data_set_size = 10
random_seed = 10598
shot = 10000
sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=training_data_set_size,
test_size=testing_data_set_size,
gap = 0.3,
n=feature_dim,
plot_data=True)
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
print(class_to_label)
backend = BasicAer.get_backend('qasm_simulator')
feature_map = ZZFeatureMap(feature_dim, reps=2)
svm = QSVM(feature_map, training_input, test_input, None)
svm.random_seed = random_seed
quantum_instance = QuantumInstance(backend, shots=shot, seed_simulator=random_seed, seed_transpiler=random_seed)
result = svm.run(quantum_instance)
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix), interpolation='nearest', origin='upper', cmap='bone_r')
plt.show()
#computed distance from kernel in higher dimensional space
#diagonal black line shows that the distance from each point to itself is 0
predicted_labels = svm.predict(datapoints[0])
predicted_classes = map_label_to_class_name(predicted_labels, svm.label_to_class)
print("ground truth: {}".format(datapoints[1]))
print("prediction: {}".format(predicted_labels))
print("testing success reation: ", result['testing_accuracy'])
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test pulse builder context utilities."""
from math import pi
import numpy as np
from qiskit import circuit, compiler, pulse
from qiskit.pulse import builder, exceptions, macros
from qiskit.pulse.instructions import directives
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeOpenPulse2Q
from qiskit.providers.fake_provider.utils.configurable_backend import (
ConfigurableFakeBackend as ConfigurableBackend,
)
from qiskit.pulse import library, instructions
class TestBuilder(QiskitTestCase):
"""Test the pulse builder context."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.configuration = self.backend.configuration()
self.defaults = self.backend.defaults()
self.inst_map = self.defaults.instruction_schedule_map
def assertScheduleEqual(self, program, target):
"""Assert an error when two pulse programs are not equal.
.. note:: Two programs are converted into standard execution format then compared.
"""
self.assertEqual(target_qobj_transform(program), target_qobj_transform(target))
class TestBuilderBase(TestBuilder):
"""Test builder base."""
def test_schedule_supplied(self):
"""Test that schedule is used if it is supplied to the builder."""
d0 = pulse.DriveChannel(0)
with pulse.build(name="reference") as reference:
with pulse.align_sequential():
pulse.delay(10, d0)
with pulse.build(schedule=reference) as schedule:
pass
self.assertScheduleEqual(schedule, reference)
self.assertEqual(schedule.name, "reference")
def test_default_alignment_left(self):
"""Test default left alignment setting."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(0)
with pulse.build(default_alignment="left") as schedule:
pulse.delay(10, d0)
pulse.delay(20, d1)
with pulse.build(self.backend) as reference:
with pulse.align_left():
pulse.delay(10, d0)
pulse.delay(20, d1)
self.assertScheduleEqual(schedule, reference)
def test_default_alignment_right(self):
"""Test default right alignment setting."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(0)
with pulse.build(default_alignment="right") as schedule:
pulse.delay(10, d0)
pulse.delay(20, d1)
with pulse.build() as reference:
with pulse.align_right():
pulse.delay(10, d0)
pulse.delay(20, d1)
self.assertScheduleEqual(schedule, reference)
def test_default_alignment_sequential(self):
"""Test default sequential alignment setting."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(0)
with pulse.build(default_alignment="sequential") as schedule:
pulse.delay(10, d0)
pulse.delay(20, d1)
with pulse.build() as reference:
with pulse.align_sequential():
pulse.delay(10, d0)
pulse.delay(20, d1)
self.assertScheduleEqual(schedule, reference)
class TestContexts(TestBuilder):
"""Test builder contexts."""
def test_align_sequential(self):
"""Test the sequential alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as schedule:
with pulse.align_sequential():
pulse.delay(3, d0)
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(8, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_align_left(self):
"""Test the left alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_left():
pulse.delay(11, d2)
pulse.delay(3, d0)
with pulse.align_left():
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_align_right(self):
"""Test the right alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_right():
with pulse.align_right():
pulse.delay(11, d2)
pulse.delay(3, d0)
pulse.delay(13, d0)
pulse.delay(5, d1)
reference = pulse.Schedule()
# d0
reference.insert(8, instructions.Delay(3, d0), inplace=True)
reference.insert(11, instructions.Delay(13, d0), inplace=True)
# d1
reference.insert(19, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(0, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_transpiler_settings(self):
"""Test the transpiler settings context.
Tests that two cx gates are optimized away with higher optimization level.
"""
twice_cx_qc = circuit.QuantumCircuit(2)
twice_cx_qc.cx(0, 1)
twice_cx_qc.cx(0, 1)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=0):
builder.call(twice_cx_qc)
self.assertNotEqual(len(schedule.instructions), 0)
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(optimization_level=3):
builder.call(twice_cx_qc)
self.assertEqual(len(schedule.instructions), 0)
def test_scheduler_settings(self):
"""Test the circuit scheduler settings context."""
inst_map = pulse.InstructionScheduleMap()
d0 = pulse.DriveChannel(0)
test_x_sched = pulse.Schedule()
test_x_sched += instructions.Delay(10, d0)
inst_map.add("x", (0,), test_x_sched)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(test_x_sched)
x_qc = circuit.QuantumCircuit(2)
x_qc.x(0)
with pulse.build(backend=self.backend) as schedule:
with pulse.transpiler_settings(basis_gates=["x"]):
with pulse.circuit_scheduler_settings(inst_map=inst_map):
builder.call(x_qc)
self.assertScheduleEqual(schedule, ref_sched)
def test_phase_offset(self):
"""Test the phase offset context."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
with pulse.phase_offset(3.14, d0):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftPhase(3.14, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftPhase(-3.14, d0)
self.assertScheduleEqual(schedule, reference)
def test_frequency_offset(self):
"""Test the frequency offset context."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
with pulse.frequency_offset(1e9, d0):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(1e9, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftFrequency(-1e9, d0)
self.assertScheduleEqual(schedule, reference)
def test_phase_compensated_frequency_offset(self):
"""Test that the phase offset context properly compensates for phase
accumulation."""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as schedule:
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(1e9, d0)
reference += instructions.Delay(10, d0)
reference += instructions.ShiftPhase(
-2 * np.pi * ((1e9 * 10 * self.configuration.dt) % 1), d0
)
reference += instructions.ShiftFrequency(-1e9, d0)
self.assertScheduleEqual(schedule, reference)
class TestChannels(TestBuilder):
"""Test builder channels."""
def test_drive_channel(self):
"""Text context builder drive channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.drive_channel(0), pulse.DriveChannel(0))
def test_measure_channel(self):
"""Text context builder measure channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.measure_channel(0), pulse.MeasureChannel(0))
def test_acquire_channel(self):
"""Text context builder acquire channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.acquire_channel(0), pulse.AcquireChannel(0))
def test_control_channel(self):
"""Text context builder control channel."""
with pulse.build(self.backend):
self.assertEqual(pulse.control_channels(0, 1)[0], pulse.ControlChannel(0))
class TestInstructions(TestBuilder):
"""Test builder instructions."""
def test_delay(self):
"""Test delay instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.delay(10, d0)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_parametric_pulse(self):
"""Test play instruction with parametric pulse."""
d0 = pulse.DriveChannel(0)
test_pulse = library.Constant(10, 1.0)
with pulse.build() as schedule:
pulse.play(test_pulse, d0)
reference = pulse.Schedule()
reference += instructions.Play(test_pulse, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_sample_pulse(self):
"""Test play instruction with sample pulse."""
d0 = pulse.DriveChannel(0)
test_pulse = library.Waveform([0.0, 0.0])
with pulse.build() as schedule:
pulse.play(test_pulse, d0)
reference = pulse.Schedule()
reference += instructions.Play(test_pulse, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_array_pulse(self):
"""Test play instruction on an array directly."""
d0 = pulse.DriveChannel(0)
test_array = np.array([0.0, 0.0], dtype=np.complex_)
with pulse.build() as schedule:
pulse.play(test_array, d0)
reference = pulse.Schedule()
test_pulse = pulse.Waveform(test_array)
reference += instructions.Play(test_pulse, d0)
self.assertScheduleEqual(schedule, reference)
def test_play_name_argument(self):
"""Test name argument for play instruction."""
d0 = pulse.DriveChannel(0)
test_pulse = library.Constant(10, 1.0)
with pulse.build() as schedule:
pulse.play(test_pulse, channel=d0, name="new_name")
self.assertEqual(schedule.instructions[0][1].name, "new_name")
def test_acquire_memory_slot(self):
"""Test acquire instruction into memory slot."""
acquire0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as schedule:
pulse.acquire(10, acquire0, mem0)
reference = pulse.Schedule()
reference += pulse.Acquire(10, acquire0, mem_slot=mem0)
self.assertScheduleEqual(schedule, reference)
def test_acquire_register_slot(self):
"""Test acquire instruction into register slot."""
acquire0 = pulse.AcquireChannel(0)
reg0 = pulse.RegisterSlot(0)
with pulse.build() as schedule:
pulse.acquire(10, acquire0, reg0)
reference = pulse.Schedule()
reference += pulse.Acquire(10, acquire0, reg_slot=reg0)
self.assertScheduleEqual(schedule, reference)
def test_acquire_qubit(self):
"""Test acquire instruction on qubit."""
acquire0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as schedule:
pulse.acquire(10, 0, mem0)
reference = pulse.Schedule()
reference += pulse.Acquire(10, acquire0, mem_slot=mem0)
self.assertScheduleEqual(schedule, reference)
def test_instruction_name_argument(self):
"""Test setting the name of an instruction."""
d0 = pulse.DriveChannel(0)
for instruction_method in [
pulse.delay,
pulse.set_frequency,
pulse.set_phase,
pulse.shift_frequency,
pulse.shift_phase,
]:
with pulse.build() as schedule:
instruction_method(0, d0, name="instruction_name")
self.assertEqual(schedule.instructions[0][1].name, "instruction_name")
def test_set_frequency(self):
"""Test set frequency instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.set_frequency(1e9, d0)
reference = pulse.Schedule()
reference += instructions.SetFrequency(1e9, d0)
self.assertScheduleEqual(schedule, reference)
def test_shift_frequency(self):
"""Test shift frequency instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.shift_frequency(0.1e9, d0)
reference = pulse.Schedule()
reference += instructions.ShiftFrequency(0.1e9, d0)
self.assertScheduleEqual(schedule, reference)
def test_set_phase(self):
"""Test set phase instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.set_phase(3.14, d0)
reference = pulse.Schedule()
reference += instructions.SetPhase(3.14, d0)
self.assertScheduleEqual(schedule, reference)
def test_shift_phase(self):
"""Test shift phase instruction."""
d0 = pulse.DriveChannel(0)
with pulse.build() as schedule:
pulse.shift_phase(3.14, d0)
reference = pulse.Schedule()
reference += instructions.ShiftPhase(3.14, d0)
self.assertScheduleEqual(schedule, reference)
def test_snapshot(self):
"""Test snapshot instruction."""
with pulse.build() as schedule:
pulse.snapshot("test", "state")
reference = pulse.Schedule()
reference += instructions.Snapshot("test", "state")
self.assertScheduleEqual(schedule, reference)
class TestDirectives(TestBuilder):
"""Test builder directives."""
def test_barrier_with_align_right(self):
"""Test barrier directive with right alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_right():
pulse.delay(3, d0)
pulse.barrier(d0, d1, d2)
pulse.delay(11, d2)
with pulse.align_right():
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(7, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(9, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(3, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_barrier_with_align_left(self):
"""Test barrier directive with left alignment context."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
with pulse.build() as schedule:
with pulse.align_left():
pulse.delay(3, d0)
pulse.barrier(d0, d1, d2)
pulse.delay(11, d2)
with pulse.align_left():
pulse.delay(5, d1)
pulse.delay(7, d0)
reference = pulse.Schedule()
# d0
reference.insert(0, instructions.Delay(3, d0), inplace=True)
reference.insert(3, instructions.Delay(7, d0), inplace=True)
# d1
reference.insert(3, instructions.Delay(5, d1), inplace=True)
# d2
reference.insert(3, instructions.Delay(11, d2), inplace=True)
self.assertScheduleEqual(schedule, reference)
def test_barrier_on_qubits(self):
"""Test barrier directive on qubits."""
with pulse.build(self.backend) as schedule:
pulse.barrier(0, 1)
reference = pulse.ScheduleBlock()
reference += directives.RelativeBarrier(
pulse.DriveChannel(0),
pulse.DriveChannel(1),
pulse.MeasureChannel(0),
pulse.MeasureChannel(1),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
pulse.AcquireChannel(0),
pulse.AcquireChannel(1),
)
self.assertEqual(schedule, reference)
def test_trivial_barrier(self):
"""Test that trivial barrier is not added."""
with pulse.build() as schedule:
pulse.barrier(pulse.DriveChannel(0))
self.assertEqual(schedule, pulse.ScheduleBlock())
class TestUtilities(TestBuilder):
"""Test builder utilities."""
def test_active_backend(self):
"""Test getting active builder backend."""
with pulse.build(self.backend):
self.assertEqual(pulse.active_backend(), self.backend)
def test_append_schedule(self):
"""Test appending a schedule to the active builder."""
d0 = pulse.DriveChannel(0)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
with pulse.build() as schedule:
builder.call(reference)
self.assertScheduleEqual(schedule, reference)
def test_append_instruction(self):
"""Test appending an instruction to the active builder."""
d0 = pulse.DriveChannel(0)
instruction = instructions.Delay(10, d0)
with pulse.build() as schedule:
builder.append_instruction(instruction)
self.assertScheduleEqual(schedule, (0, instruction))
def test_qubit_channels(self):
"""Test getting the qubit channels of the active builder's backend."""
with pulse.build(self.backend):
qubit_channels = pulse.qubit_channels(0)
self.assertEqual(
qubit_channels,
{
pulse.DriveChannel(0),
pulse.MeasureChannel(0),
pulse.AcquireChannel(0),
pulse.ControlChannel(0),
pulse.ControlChannel(1),
},
)
def test_active_transpiler_settings(self):
"""Test setting settings of active builder's transpiler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_transpiler_settings())
with pulse.transpiler_settings(test_setting=1):
self.assertEqual(pulse.active_transpiler_settings()["test_setting"], 1)
def test_active_circuit_scheduler_settings(self):
"""Test setting settings of active builder's circuit scheduler."""
with pulse.build(self.backend):
self.assertFalse(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(test_setting=1):
self.assertEqual(pulse.active_circuit_scheduler_settings()["test_setting"], 1)
def test_num_qubits(self):
"""Test builder utility to get number of qubits."""
with pulse.build(self.backend):
self.assertEqual(pulse.num_qubits(), 2)
def test_samples_to_seconds(self):
"""Test samples to time"""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
time = pulse.samples_to_seconds(100)
self.assertTrue(isinstance(time, float))
self.assertEqual(pulse.samples_to_seconds(100), 10)
def test_samples_to_seconds_array(self):
"""Test samples to time (array format)."""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
samples = np.array([100, 200, 300])
times = pulse.samples_to_seconds(samples)
self.assertTrue(np.issubdtype(times.dtype, np.floating))
np.testing.assert_allclose(times, np.array([10, 20, 30]))
def test_seconds_to_samples(self):
"""Test time to samples"""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
samples = pulse.seconds_to_samples(10)
self.assertTrue(isinstance(samples, int))
self.assertEqual(pulse.seconds_to_samples(10), 100)
def test_seconds_to_samples_array(self):
"""Test time to samples (array format)."""
config = self.backend.configuration()
config.dt = 0.1
with pulse.build(self.backend):
times = np.array([10, 20, 30])
samples = pulse.seconds_to_samples(times)
self.assertTrue(np.issubdtype(samples.dtype, np.integer))
np.testing.assert_allclose(pulse.seconds_to_samples(times), np.array([100, 200, 300]))
class TestMacros(TestBuilder):
"""Test builder macros."""
def test_macro(self):
"""Test builder macro decorator."""
@pulse.macro
def nested(a):
pulse.play(pulse.Gaussian(100, a, 20), pulse.drive_channel(0))
return a * 2
@pulse.macro
def test():
pulse.play(pulse.Constant(100, 1.0), pulse.drive_channel(0))
output = nested(0.5)
return output
with pulse.build(self.backend) as schedule:
output = test()
self.assertEqual(output, 0.5 * 2)
reference = pulse.Schedule()
reference += pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
reference += pulse.Play(pulse.Gaussian(100, 0.5, 20), pulse.DriveChannel(0))
self.assertScheduleEqual(schedule, reference)
def test_measure(self):
"""Test utility function - measure."""
with pulse.build(self.backend) as schedule:
reg = pulse.measure(0)
self.assertEqual(reg, pulse.MemorySlot(0))
reference = macros.measure(
qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
self.assertScheduleEqual(schedule, reference)
def test_measure_multi_qubits(self):
"""Test utility function - measure with multi qubits."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure([0, 1])
self.assertListEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)])
reference = macros.measure(
qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
self.assertScheduleEqual(schedule, reference)
def test_measure_all(self):
"""Test utility function - measure."""
with pulse.build(self.backend) as schedule:
regs = pulse.measure_all()
self.assertEqual(regs, [pulse.MemorySlot(0), pulse.MemorySlot(1)])
reference = macros.measure_all(self.backend)
self.assertScheduleEqual(schedule, reference)
backend_100q = ConfigurableBackend("100q", 100)
with pulse.build(backend_100q) as schedule:
regs = pulse.measure_all()
reference = backend_100q.defaults().instruction_schedule_map.get(
"measure", list(range(100))
)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubit(self):
"""Test delaying on a qubit macro."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0)
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
a0 = pulse.AcquireChannel(0)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
self.assertScheduleEqual(schedule, reference)
def test_delay_qubits(self):
"""Test delaying on multiple qubits to make sure we don't insert delays twice."""
with pulse.build(self.backend) as schedule:
pulse.delay_qubits(10, 0, 1)
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
m0 = pulse.MeasureChannel(0)
m1 = pulse.MeasureChannel(1)
a0 = pulse.AcquireChannel(0)
a1 = pulse.AcquireChannel(1)
u0 = pulse.ControlChannel(0)
u1 = pulse.ControlChannel(1)
reference = pulse.Schedule()
reference += instructions.Delay(10, d0)
reference += instructions.Delay(10, d1)
reference += instructions.Delay(10, m0)
reference += instructions.Delay(10, m1)
reference += instructions.Delay(10, a0)
reference += instructions.Delay(10, a1)
reference += instructions.Delay(10, u0)
reference += instructions.Delay(10, u1)
self.assertScheduleEqual(schedule, reference)
class TestGates(TestBuilder):
"""Test builder gates."""
def test_cx(self):
"""Test cx gate."""
with pulse.build(self.backend) as schedule:
pulse.cx(0, 1)
reference_qc = circuit.QuantumCircuit(2)
reference_qc.cx(0, 1)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_u1(self):
"""Test u1 gate."""
with pulse.build(self.backend) as schedule:
with pulse.transpiler_settings(layout_method="trivial"):
pulse.u1(np.pi / 2, 0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.append(circuit.library.U1Gate(np.pi / 2), [0])
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_u2(self):
"""Test u2 gate."""
with pulse.build(self.backend) as schedule:
pulse.u2(np.pi / 2, 0, 0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.append(circuit.library.U2Gate(np.pi / 2, 0), [0])
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_u3(self):
"""Test u3 gate."""
with pulse.build(self.backend) as schedule:
pulse.u3(np.pi / 8, np.pi / 16, np.pi / 4, 0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.append(circuit.library.U3Gate(np.pi / 8, np.pi / 16, np.pi / 4), [0])
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_x(self):
"""Test x gate."""
with pulse.build(self.backend) as schedule:
pulse.x(0)
reference_qc = circuit.QuantumCircuit(1)
reference_qc.x(0)
reference_qc = compiler.transpile(reference_qc, self.backend)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_lazy_evaluation_with_transpiler(self):
"""Test that the two cx gates are optimizied away by the transpiler."""
with pulse.build(self.backend) as schedule:
pulse.cx(0, 1)
pulse.cx(0, 1)
reference_qc = circuit.QuantumCircuit(2)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_measure(self):
"""Test pulse measurement macro against circuit measurement and
ensure agreement."""
with pulse.build(self.backend) as schedule:
with pulse.align_sequential():
pulse.x(0)
pulse.measure(0)
reference_qc = circuit.QuantumCircuit(1, 1)
reference_qc.x(0)
reference_qc.measure(0, 0)
reference_qc = compiler.transpile(reference_qc, self.backend)
reference = compiler.schedule(reference_qc, self.backend)
self.assertScheduleEqual(schedule, reference)
def test_backend_require(self):
"""Test that a backend is required to use a gate."""
with self.assertRaises(exceptions.BackendNotSet):
with pulse.build():
pulse.x(0)
class TestBuilderComposition(TestBuilder):
"""Test more sophisticated composite builder examples."""
def test_complex_build(self):
"""Test a general program build with nested contexts,
circuits and macros."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
d2 = pulse.DriveChannel(2)
delay_dur = 30
short_dur = 20
long_dur = 49
with pulse.build(self.backend) as schedule:
with pulse.align_sequential():
pulse.delay(delay_dur, d0)
pulse.u2(0, pi / 2, 1)
with pulse.align_right():
pulse.play(library.Constant(short_dur, 0.1), d1)
pulse.play(library.Constant(long_dur, 0.1), d2)
pulse.u2(0, pi / 2, 1)
with pulse.align_left():
pulse.u2(0, pi / 2, 0)
pulse.u2(0, pi / 2, 1)
pulse.u2(0, pi / 2, 0)
pulse.measure(0)
# prepare and schedule circuits that will be used.
single_u2_qc = circuit.QuantumCircuit(2)
single_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1])
single_u2_qc = compiler.transpile(single_u2_qc, self.backend)
single_u2_sched = compiler.schedule(single_u2_qc, self.backend)
# sequential context
sequential_reference = pulse.Schedule()
sequential_reference += instructions.Delay(delay_dur, d0)
sequential_reference.insert(delay_dur, single_u2_sched, inplace=True)
# align right
align_right_reference = pulse.Schedule()
align_right_reference += pulse.Play(library.Constant(long_dur, 0.1), d2)
align_right_reference.insert(
long_dur - single_u2_sched.duration, single_u2_sched, inplace=True
)
align_right_reference.insert(
long_dur - single_u2_sched.duration - short_dur,
pulse.Play(library.Constant(short_dur, 0.1), d1),
inplace=True,
)
# align left
triple_u2_qc = circuit.QuantumCircuit(2)
triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0])
triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1])
triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0])
triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend)
align_left_reference = compiler.schedule(triple_u2_qc, self.backend, method="alap")
# measurement
measure_reference = macros.measure(
qubits=[0], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
reference = pulse.Schedule()
reference += sequential_reference
# Insert so that the long pulse on d2 occurs as early as possible
# without an overval on d1.
insert_time = reference.ch_stop_time(d1) - align_right_reference.ch_start_time(d1)
reference.insert(insert_time, align_right_reference, inplace=True)
reference.insert(reference.ch_stop_time(d0, d1), align_left_reference, inplace=True)
reference += measure_reference
self.assertScheduleEqual(schedule, reference)
class TestSubroutineCall(TestBuilder):
"""Test for calling subroutine."""
def test_call(self):
"""Test calling schedule instruction."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
reference = pulse.Schedule()
reference = reference.insert(10, instructions.Delay(10, d0))
reference += instructions.Delay(20, d1)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(reference)
with pulse.build() as schedule:
with pulse.align_right():
builder.call(reference)
self.assertScheduleEqual(schedule, ref_sched)
with pulse.build() as schedule:
with pulse.align_right():
pulse.call(reference)
self.assertScheduleEqual(schedule, ref_sched)
def test_call_circuit(self):
"""Test calling circuit instruction."""
inst_map = self.inst_map
reference = inst_map.get("u1", (0,), 0.0)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(reference)
u1_qc = circuit.QuantumCircuit(2)
u1_qc.append(circuit.library.U1Gate(0.0), [0])
transpiler_settings = {"optimization_level": 0}
with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule:
with pulse.align_right():
builder.call(u1_qc)
self.assertScheduleEqual(schedule, ref_sched)
def test_call_circuit_with_cregs(self):
"""Test calling of circuit wiht classical registers."""
qc = circuit.QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
with pulse.build(self.backend) as schedule:
pulse.call(qc)
reference_qc = compiler.transpile(qc, self.backend)
reference = compiler.schedule(reference_qc, self.backend)
ref_sched = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
ref_sched += pulse.instructions.Call(reference)
self.assertScheduleEqual(schedule, ref_sched)
def test_call_gate_and_circuit(self):
"""Test calling circuit with gates."""
h_control = circuit.QuantumCircuit(2)
h_control.h(0)
with pulse.build(self.backend) as schedule:
with pulse.align_sequential():
# this is circuit, a subroutine stored as Call instruction
pulse.call(h_control)
# this is instruction, not subroutine
pulse.cx(0, 1)
# this is macro, not subroutine
pulse.measure([0, 1])
# subroutine
h_reference = compiler.schedule(compiler.transpile(h_control, self.backend), self.backend)
# gate
cx_circ = circuit.QuantumCircuit(2)
cx_circ.cx(0, 1)
cx_reference = compiler.schedule(compiler.transpile(cx_circ, self.backend), self.backend)
# measurement
measure_reference = macros.measure(
qubits=[0, 1], inst_map=self.inst_map, meas_map=self.configuration.meas_map
)
reference = pulse.Schedule()
with self.assertWarns(DeprecationWarning):
reference += pulse.instructions.Call(h_reference)
reference += cx_reference
reference += measure_reference << reference.duration
self.assertScheduleEqual(schedule, reference)
def test_subroutine_not_transpiled(self):
"""Test called circuit is frozen as a subroutine."""
subprogram = circuit.QuantumCircuit(1)
subprogram.x(0)
transpiler_settings = {"optimization_level": 2}
with pulse.build(self.backend, default_transpiler_settings=transpiler_settings) as schedule:
pulse.call(subprogram)
pulse.call(subprogram)
self.assertNotEqual(len(target_qobj_transform(schedule).instructions), 0)
def test_subroutine_not_transformed(self):
"""Test called schedule is not transformed."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
subprogram = pulse.Schedule()
subprogram.insert(0, pulse.Delay(30, d0), inplace=True)
subprogram.insert(10, pulse.Delay(10, d1), inplace=True)
with pulse.build() as target:
with pulse.align_right():
pulse.delay(10, d1)
pulse.call(subprogram)
reference = pulse.Schedule()
reference.insert(0, pulse.Delay(10, d1), inplace=True)
reference.insert(10, pulse.Delay(30, d0), inplace=True)
reference.insert(20, pulse.Delay(10, d1), inplace=True)
self.assertScheduleEqual(target, reference)
def test_deepcopying_subroutine(self):
"""Test if deepcopying the schedule can copy inline subroutine."""
from copy import deepcopy
with pulse.build() as subroutine:
pulse.delay(10, pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine)
copied_prog = deepcopy(main_prog)
main_call = main_prog.instructions[0]
copy_call = copied_prog.instructions[0]
self.assertNotEqual(id(main_call), id(copy_call))
def test_call_with_parameters(self):
"""Test call subroutine with parameters."""
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine, amp=0.3)
self.assertEqual(main_prog.is_parameterized(), False)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_1.pulse.amp, 0.3)
def test_call_partly_with_parameters(self):
"""Test multiple calls partly with parameters then assign."""
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine)
self.assertEqual(main_prog.is_parameterized(), True)
main_prog.assign_parameters({amp: 0.5})
self.assertEqual(main_prog.is_parameterized(), False)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_1.pulse.amp, 0.5)
def test_call_with_not_existing_parameter(self):
"""Test call subroutine with parameter not defined."""
amp = circuit.Parameter("amp1")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with self.assertRaises(exceptions.PulseError):
with pulse.build():
pulse.call(subroutine, amp=0.1)
def test_call_with_common_parameter(self):
"""Test call subroutine with parameter that is defined multiple times."""
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(320, amp, 80), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, amp=0.1)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_1.pulse.amp, 0.1)
def test_call_with_parameter_name_collision(self):
"""Test call subroutine with duplicated parameter names."""
amp1 = circuit.Parameter("amp")
amp2 = circuit.Parameter("amp")
sigma = circuit.Parameter("sigma")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp1, sigma), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, amp2, sigma), pulse.DriveChannel(0))
with pulse.build() as main_prog:
pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.2}, sigma=40)
assigned_sched = target_qobj_transform(main_prog)
play_0 = assigned_sched.instructions[0][1]
play_1 = assigned_sched.instructions[1][1]
self.assertEqual(play_0.pulse.amp, 0.1)
self.assertEqual(play_0.pulse.sigma, 40)
self.assertEqual(play_1.pulse.amp, 0.2)
self.assertEqual(play_1.pulse.sigma, 40)
def test_call_subroutine_with_parametrized_duration(self):
"""Test call subroutine containing a parametrized duration."""
dur = circuit.Parameter("dur")
with pulse.build() as subroutine:
pulse.play(pulse.Constant(dur, 0.1), pulse.DriveChannel(0))
pulse.play(pulse.Constant(dur, 0.2), pulse.DriveChannel(0))
with pulse.build() as main:
pulse.call(subroutine)
self.assertEqual(len(main.blocks), 1)
|
https://github.com/Glebegor/Quantum-programming-algorithms
|
Glebegor
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/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/swe-bench/Qiskit__qiskit
|
swe-bench
|
import os
import sys
cwd = os.getcwd()
qiskit_dir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(cwd))))
sys.path.append(qiskit_dir)
from qiskit import IBMQ
from qiskit.tools.jupyter import *
IBMQ.load_account()
%qiskit_backend_overview
|
https://github.com/rigetti/qiskit-rigetti
|
rigetti
|
##############################################################################
# Copyright 2021 Rigetti Computing
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
from typing import Any
from qiskit import QuantumCircuit
from qiskit.circuit import InstructionSet
from .gates import (
CanonicalGate,
CPhase00Gate,
CPhase01Gate,
CPhase10Gate,
PSwapGate,
XYGate,
)
class QuilCircuit(QuantumCircuit):
"""
A :class:`qiskit.circuit.QuantumCircuit` extension with added support for standard Quil gates:
https://github.com/rigetti/quilc/blob/master/src/quil/stdgates.quil
"""
def xy(self, theta: float, qubit1: Any, qubit2: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.xy.XYGate`."""
return self.append(XYGate(theta), [qubit1, qubit2], [])
def piswap(self, theta: float, qubit1: Any, qubit2: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.xy.XYGate`."""
return self.xy(theta, qubit1, qubit2)
def pswap(self, theta: float, qubit1: Any, qubit2: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.pswap.PSwapGate`."""
return self.append(PSwapGate(theta), [qubit1, qubit2], [])
def cphase00(self, theta: float, control_qubit: Any, target_qubit: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.cphase.CPhase00`."""
return self.append(CPhase00Gate(theta), [control_qubit, target_qubit], [])
def cphase01(self, theta: float, control_qubit: Any, target_qubit: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.cphase.CPhase01`."""
return self.append(CPhase01Gate(theta), [control_qubit, target_qubit], [])
def cphase10(self, theta: float, control_qubit: Any, target_qubit: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.cphase.CPhase10`."""
return self.append(CPhase10Gate(theta), [control_qubit, target_qubit], [])
def can(self, alpha: float, beta: float, gamma: float, qubit1: Any, qubit2: Any) -> InstructionSet:
"""Apply :class:`qiskit_rigetti.gates.can.CanonicalGate`."""
return self.append(CanonicalGate(alpha, beta, gamma), [qubit1, qubit2], [])
|
https://github.com/martynscn/Masters-Thesis-on-Quantum-Cryptography
|
martynscn
|
# This code has been adapted and modified from IBM Qiskit 2021 and also from https://github.com/ttlion/ShorAlgQiskit.
# It uses the implementation as contained in the work of Stephane Beauregard (https://arxiv.org/abs/quant-ph/0205095)
# Many thanks to IBM Qiskit team, Tiago Miguel (ttlion), Qubit by Qubit, Peter Shor and Stephane Beauregard.
from typing import Optional, Union, Tuple, List
import math
import array
import fractions
import logging
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute, IBMQ, transpile,BasicAer, Aer, assemble
from qiskit.circuit import Gate, Instruction, ParameterVector
from qiskit.circuit.library import QFT
from qiskit.providers import BaseBackend, Backend
from qiskit.quantum_info import partial_trace
from qiskit.utils import summarize_circuits
from qiskit.utils.arithmetic import is_power
from qiskit.utils.validation import validate_min
from qiskit.utils.quantum_instance import QuantumInstance
import qiskit.visualization
from qiskit.providers.aer import QasmSimulator
from datetime import datetime
import csv
# provider = IBMQ.enable_account("PUT TOKEN HERE")
backend = QasmSimulator()
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" #"last_expr" or "all"
def get_angles(a: int, n) -> np.ndarray:
# """Calculates the array of angles to be used in the addition in Fourier Space."""
s = bin(int(a))[2:].zfill(n + 1)
angles = np.zeros([n + 1])
for i in range(0, n + 1):
for j in range(i, n + 1):
if s[j] == '1':
angles[n - i] += math.pow(2, -(j - i))
angles[n - i] *= np.pi
return angles[::-1]
# This returns the angles in the opposite order
def my_create_QFT(qft_num_qubits,approximation_degree: int = 0,do_swaps: bool = False,insert_barriers: bool = True, name: str = 'qft'):
# up_reg = QuantumRegister(size = qft_num_qubits, name="aux")
circuit_qft = QuantumCircuit(qft_num_qubits)
i=qft_num_qubits-1
while i>=0:
# circuit_qft.h(up_reg[i])
circuit_qft.h(i)
j=i-1
while j>=0:
if (np.pi)/(pow(2,(i-j))) > approximation_degree:
# circuit_qft.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] )
circuit_qft.cu1( (np.pi)/(pow(2,(i-j))) , i , j )
j=j-1
if insert_barriers:
circuit_qft.barrier()
i=i-1
""" If specified, apply the Swaps at the end """
if do_swaps:
i=0
while i < ((qft_num_qubits-1)/2):
# circuit_qft.swap(up_reg[i], up_reg[qft_num_qubits-1-i])
circuit_qft.swap(i, qft_num_qubits-1-i)
i=i+1
circuit_qft.name = "QFT"
return circuit_qft
def my_create_inverse_QFT(qft_num_qubits,approximation_degree: int = 0,do_swaps: bool = False,insert_barriers: bool = True, name: str = 'iqft'):
my_create_QFT_circuit = my_create_QFT(qft_num_qubits,approximation_degree,do_swaps,insert_barriers, name)
my_create_inverse_QFT_circuit = my_create_QFT_circuit.inverse()
my_create_inverse_QFT_circuit.name = "QFT†"
return my_create_inverse_QFT_circuit
def phi_add_gate(size: int, angles: Union[np.ndarray, ParameterVector]) -> Gate:
# """Gate that performs addition by a in Fourier Space."""
circuit = QuantumCircuit(size, name="phi_add")
for i, angle in enumerate(angles):
circuit.p(angle, i)
return circuit.to_gate()
def double_controlled_phi_add_mod_N(num_qubits: int, angles: Union[np.ndarray, ParameterVector],reg_size, a, N, n) -> QuantumCircuit:
# """Creates a circuit which implements double-controlled modular addition by a."""
circuit = QuantumCircuit(num_qubits, name="ccphi_add_mod_N")
ctl_up = 0
ctl_down = 1
ctl_aux = 2
# get qubits from aux register, omitting the control qubit
qubits = range(3, num_qubits)
# store the gates representing addition/subtraction by a in Fourier Space
phi_add_a = phi_add_gate(len(qubits), angles)
iphi_add_a = phi_add_a.inverse()
phi_add_N = phi_add_gate(reg_size - 1, get_angles(N, n))
iphi_add_N = phi_add_N.inverse()
circuit.append(phi_add_a.control(2), [ctl_up, ctl_down, *qubits])
circuit.append(iphi_add_N, qubits)
qft = QFT(n + 1).to_instruction()
# qft = my_create_QFT(n + 1).to_instruction()
iqft = QFT(n + 1).inverse().to_instruction()
# iqft = my_create_inverse_QFT(n + 1).to_instruction()
circuit.append(iqft, qubits)
circuit.cx(qubits[0], ctl_aux)
circuit.append(qft, qubits)
circuit.append(phi_add_N, qubits)
circuit.append(iphi_add_a.control(2), [ctl_up, ctl_down, *qubits])
circuit.append(iqft, qubits)
circuit.x(qubits[0])
circuit.cx(qubits[0], ctl_aux)
circuit.x(qubits[0])
circuit.append(qft, qubits)
circuit.append(phi_add_a.control(2), [ctl_up, ctl_down, *qubits])
return circuit
# """Circuit that implements single controlled modular multiplication by a"""
def controlled_multiple_mod_N(num_qubits: int, N: int, a: int, n, aux_reg_size):
# """Implements modular multiplication by a as an instruction."""
circuit = QuantumCircuit(
num_qubits,
# name="multiply_by_{}_mod_{}".format(a % N, N),
name=r"${0}^{{{1}^{{{2}}}}} mod{3}$".format(2,2,int(math.log(math.log(a,2),2)), N)
)
# label = r"${0}^{{{1}^{{{2}}}}} mod{3}$".format("†","y")
down = circuit.qubits[1: n + 1]
aux = circuit.qubits[n + 1:]
qubits = [aux[i] for i in reversed(range(n + 1))]
ctl_up = 0
ctl_aux = aux[-1]
angle_params = ParameterVector("angles", length=len(aux) - 1)
double_controlled_phi_add = double_controlled_phi_add_mod_N(
len(aux) + 2, angle_params, aux_reg_size, a, N, n
)
idouble_controlled_phi_add = double_controlled_phi_add.inverse()
qft_circuit = QFT(n + 1).to_instruction()
# qft_circuit = my_create_QFT(n + 1).to_instruction()
iqft_circuit = QFT(n + 1).inverse().to_instruction()
# iqft_circuit = my_create_inverse_QFT(n + 1).to_instruction()
circuit.append(qft_circuit, qubits)
# perform controlled addition by a on the aux register in Fourier space
for i, ctl_down in enumerate(down):
a_exp = (2 ** i) * a % N
angles = get_angles(a_exp, n)
bound = double_controlled_phi_add.assign_parameters({angle_params: angles})
circuit.append(bound, [ctl_up, ctl_down, ctl_aux, *qubits])
circuit.append(iqft_circuit, qubits)
# perform controlled subtraction by a in Fourier space on both the aux and down register
for j in range(n):
circuit.cswap(ctl_up, down[j], aux[j])
circuit.append(qft_circuit, qubits)
a_inv = modinv(a, N)
for i in reversed(range(len(down))):
a_exp = (2 ** i) * a_inv % N
angles = get_angles(a_exp, n)
bound = idouble_controlled_phi_add.assign_parameters({angle_params: angles})
circuit.append(bound, [ctl_up, down[i], ctl_aux, *qubits])
circuit.append(iqft_circuit, qubits)
return circuit
def modinv(a: int, m: int) -> int:
# """Returns the modular multiplicative inverse of a with respect to the modulus m."""
def egcd(a: int, b: int) -> Tuple[int, int, int]:
if a == 0:
return b, 0, 1
else:
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y
g, x, _ = egcd(a, m)
if g != 1:
raise ValueError("The greatest common divisor of {} and {} is {}, so the "
"modular inverse does not exist.".format(a, m, g))
return x % m
def get_factors(N: int, a: int, measurement: str) -> Optional[List[int]]:
# """Apply the continued fractions to find r and the gcd to find the desired factors."""
x_final = int(measurement, 2)
#print('In decimal, x_final value for this result is: {}.'.format(x_final))
if x_final <= 0:
fail_reason = 'x_final value is <= 0, there are no continued fractions.'
else:
fail_reason = None
#print('Running continued fractions for this case.')
# Calculate T and x/T
T_upper = len(measurement)
T = pow(2, T_upper)
x_over_T = x_final / T ## this is our theta
# Cycle in which each iteration corresponds to putting one more term in the
# calculation of the Continued Fraction (CF) of x/T
# Initialize the first values according to CF rule
i = 0
b = array.array('i')
t = array.array('f')
b.append(math.floor(x_over_T))
t.append(x_over_T - b[i])
exponential = 0.0
while i < N and fail_reason is None:
# From the 2nd iteration onwards, calculate the new terms of the CF based on the previous terms as the rule suggests
if i > 0:
try:
b_temp = math.floor(1 / t[i - 1])
except ZeroDivisionError as err:
b_temp = 0
b.append(b_temp)
try:
t_temp = (1 / t[i - 1]) - b[i]
except ZeroDivisionError as err:
t_temp = 0
t.append(t_temp) # type: ignore
# Calculate the denominator of the CF using the known terms
denominator = calculate_continued_fraction(b)
# Increment i for next iteration
i += 1
if denominator % 2 == 1:
#print('Odd denominator, will try next iteration of continued fractions.')
continue
# Denominator is even, try to get factors of N. Get the exponential a^(r/2)
if denominator < 1000:
try:
exponential = pow(a, denominator / 2)
except OverflowError as err:
exponential = 999999999
# Check if the value is too big or not
if exponential > 1000000:
if exponential == 999999999:
fail_reason = 'OverflowError'
else:
fail_reason = 'denominator of continued fraction is too big (> 10^9).'
else:
# The value is not too big, get the right values and do the proper gcd()
putting_plus = int(exponential + 1)
putting_minus = int(exponential - 1)
one_factor = math.gcd(putting_plus, N)
other_factor = math.gcd(putting_minus, N)
# Check if the factors found are trivial factors or are the desired factors
if any(factor in {1, N} for factor in (one_factor, other_factor)):
#print('Found just trivial factors, not good enough.')
# Check if the number has already been found, (use i - 1 because i was already incremented)
if t[i - 1] == 0:
fail_reason = 'the continued fractions found exactly x_final/(2^(2n)).'
else:
return sorted((one_factor, other_factor))
# Search for factors failed, write the reason for failure to the debug logs
#print('Cannot find factors from measurement {0} because {1}'.format(measurement, fail_reason or 'it took too many attempts.'))
return None
def calculate_continued_fraction(b: array.array) -> int:
# """Calculate the continued fraction of x/T from the current terms of expansion b."""
x_over_T = 0
for i in reversed(range(len(b) - 1)):
x_over_T = 1 / (b[i + 1] + x_over_T)
x_over_T += b[0]
frac = fractions.Fraction(x_over_T).limit_denominator()
#print('Approximation number %s of continued fractions:'.format(len(b)))
#print("Numerator:{0} \t\t Denominator: {1}.".format(frac.numerator, frac.denominator))
return frac.denominator
def process_results(sim_result, circuit, shots, N, a, n):
counts_result = sim_result.get_counts(circuit)
total_counts = len(counts_result)
counts_result_sorted = sorted(counts_result.items(), key=lambda x: x[1], reverse=True)
# """ Print info to user from the simulation results """
# print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(shots))
counts_result_keys = list(counts_result.keys())
counts_result_values = list(counts_result.values())
#i=0
#while i < len(counts_result):
#print('Result \"{0}\" happened {1} times out of {2}\n'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],shots))
#print('Result \"{0}\" happened {1} times out of {2}\n'.format(counts_result_keys[i],counts_result_values[i],shots))
#i=i+1
prob_success=0
prob_failure=0
result_successful_counts = 0
result_failure_counts = 0
# len(counts_result_sorted)
# For each simulation result, print proper info to user and try to calculate the factors of N
#for measurement in counts_result_keys:
for measurement, frequency in counts_result_sorted:
# Get the x_final value from the final state qubits
x_value = int(measurement, 2)
#prob_this_result = 100 * ( int(counts_result[measurement] ) ) / (shots)
prob_this_result = 100 * frequency/shots
# print("------> Analyzing result {0}. This result happened in {1:.4f} % of all cases\nIn decimal, x_final value for this result is: {2}".format(measurement,prob_this_result,x_value))
factors = get_factors(N, a, measurement)
if factors:
prob_success = prob_success + prob_this_result
# print('Found factors {0} from measurement {1} which is {2} in decimal.\n'.format(factors, measurement, x_value))
result_successful_counts = result_successful_counts + 1
if factors not in result_factors:
result_factors.append(factors)
elif not factors:
prob_failure = prob_failure + prob_this_result
result_failure_counts = result_failure_counts + 1
return [result_factors, prob_success, prob_failure, total_counts, result_successful_counts,result_failure_counts]
def my_shor(a,N,shots):
start_time_number = datetime.now()
start_time = start_time_number.strftime("%H:%M:%S")
summary_result = dict()
validate_min('N', N, 3)
validate_min('a', a, 2)
if N < 1 or N % 2 == 0:
raise ValueError('The input needs to be an odd integer greater than 1.')
if a >= N or math.gcd(a, N) != 1:
raise ValueError('The integer a needs to satisfy a < N and gcd(a, N) = 1.')
n = math.ceil(math.log(N,2))
global result_factors
result_factors = []
tf, b, p = is_power(N, return_decomposition=True)
if tf:
print('The input integer is a power: {0}={1}^{2}.'.format(N, b, p))
result_factors.append(b)
# """auxilliary quantum register used in addition and multiplication"""
aux_reg = QuantumRegister(size = n+2, name="aux_reg")
up_reg = QuantumRegister(2*n, name = "up_reg")
# """quantum register where the multiplications are made"""
down_reg = QuantumRegister(n, name = "down_reg")
# """classical register where the measured values of the QFT are stored"""
up_classic = ClassicalRegister(2*n, name="up_classic")
# """ Create Quantum Circuit """
circuit = QuantumCircuit(up_reg ,down_reg ,aux_reg, up_classic, name="Shor circuit(N={}, a={})".format(N, a))
# phi_add_N_gate = phiADD(circuit,q,a,N,inv)
phi_add_N_gate = phi_add_gate(aux_reg.size - 1, get_angles(N,n))
iphi_add_N_gate = phi_add_N_gate.inverse()
# """ Initialize down register to 1 and create maximal superposition in top register """
circuit.h(up_reg)
circuit.x(down_reg[0])
# circuit.draw(filename = "shor_standard_QFT")
# """ Apply the multiplication gates as showed in the report in order to create the exponentiation """
for i, ctl_up in enumerate(up_reg): # type: ignore
a_aux = int(pow(a, pow(2, i)))
controlled_multiple_mod_N_circuit = controlled_multiple_mod_N(
len(down_reg) + len(aux_reg) + 1, N, a_aux,n,aux_reg.size
)
controlled_multiple_mod_N_result = controlled_multiple_mod_N_circuit.to_instruction()
circuit.append(
controlled_multiple_mod_N_result, [ctl_up, *down_reg, *aux_reg]
)
# circuit.draw()
iqft = QFT(len(up_reg)).inverse().to_instruction()
# iqft = my_create_inverse_QFT(len(up_reg)).to_instruction()
# iqft = my_create_inverse_QFT(len(up_reg), insert_barriers = False).to_gate(label = r"$QFT^{{{0}}}$".format("†"))
circuit.append(iqft, up_reg)
circuit.measure(up_reg, up_classic)
# circuit.draw(filename = "shor_standard_QFT_final_circuit",fold = -1 )
# print(summarize_circuits(circuit))
# circuit.draw()
print('Running with N={0} and a={1} with number of qubits n={2}'.format(N, a, 4*n + 2))
qc_compiled = transpile(circuit, backend, optimization_level = 3)
job_sim_1 = backend.run(qc_compiled, shots=shots)
sim_result=job_sim_1.result()
# counts_result = sim_result.get_counts(circuit)
# len(counts_result)
# measurement_plot = qiskit.visualization.plot_histogram(counts_result,figsize=(20, 12) ,number_to_keep = 30,bar_labels=True, title = "Measurement results from shor_standard_QFT circuit variant" )
# measurement_plot.savefig("shor_standard_QFT_measurement")
# measurement_plot
processed_result = process_results(sim_result, circuit, shots, N, a, n)
end_time_number = datetime.now()
end_time = end_time_number.strftime("%H:%M:%S")
duration = end_time_number - start_time_number
print("Current Start Time =", start_time)
print(processed_result)
print("Current End Time =", end_time)
circuit_count_ops = circuit.count_ops()
circuit_decomposed = circuit.decompose()
circuit_decomposed_count_ops = circuit_decomposed.count_ops()
qc_compiled_count_ops = qc_compiled.count_ops()
summary_result["num_qubits"] = n
summary_result["Number(N)"] = N
summary_result["a"] = a
summary_result["start_time"] = start_time
summary_result["end_time"] = end_time
summary_result["duration"] = duration
summary_result["result_factors"] = processed_result[0]
summary_result["prob_success"] = processed_result[1]
summary_result["prob_failure"] = processed_result[2]
summary_result["total_counts"] = processed_result[3]
summary_result["result_successful_counts"] = processed_result[4]
summary_result["result_failure_counts"] = processed_result[5]
summary_result["circuit_width"] = circuit.width()
summary_result["circuit_depth"] = circuit.depth()
summary_result["circuit_size"] = circuit.size()
summary_result["circuit_num_nonlocal_gates"] = circuit.num_nonlocal_gates()
summary_result["circuit_num_ancillas"] = circuit.num_ancillas
summary_result["circuit_num_clbits"] = circuit.num_clbits
summary_result["circuit_num_qubits"] = circuit.num_qubits
summary_result["circuit_num_ancillas"] = circuit.num_ancillas
summary_result["circuit_num_of_count_ops"] = len(circuit_count_ops)
summary_result["circuit_num_of_x"] = circuit_count_ops.get('x')
summary_result["circuit_num_of_measure"] = circuit_count_ops.get('measure')
summary_result["circuit_num_of_h"] = circuit_count_ops.get('h')
summary_result["circuit_num_of_cswap"] = circuit_count_ops.get('cswap')
summary_result["circuit_num_of_swap"] = circuit_count_ops.get('swap')
summary_result["circuit_num_of_cx"] = circuit_count_ops.get('cx')
summary_result["circuit_num_of_toffoli"] = circuit_count_ops.get('toffoli')
summary_result["circuit_num_of_p"] = circuit_count_ops.get('p')
summary_result["circuit_num_of_t"] = circuit_count_ops.get('t')
summary_result["circuit_decomposed_width"] = circuit_decomposed.width()
summary_result["circuit_decomposed_depth"] = circuit_decomposed.depth()
summary_result["circuit_decomposed_size"] = circuit_decomposed.size()
summary_result["circuit_decomposed_num_nonlocal_gates"] = circuit_decomposed.num_nonlocal_gates()
summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas
summary_result["circuit_decomposed_num_clbits"] = circuit_decomposed.num_clbits
summary_result["circuit_decomposed_num_qubits"] = circuit_decomposed.num_qubits
summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas
summary_result["circuit_decomposed_num_of_count_ops"] = len(circuit_decomposed_count_ops)
summary_result["circuit_decomposed_num_of_x"] = circuit_decomposed_count_ops.get('x')
summary_result["circuit_decomposed_num_of_measure"] = circuit_decomposed_count_ops.get('measure')
summary_result["circuit_decomposed_num_of_h"] = circuit_decomposed_count_ops.get('h')
summary_result["circuit_decomposed_num_of_cswap"] = circuit_decomposed_count_ops.get('cswap')
summary_result["circuit_decomposed_num_of_swap"] = circuit_decomposed_count_ops.get('swap')
summary_result["circuit_decomposed_num_of_cx"] = circuit_decomposed_count_ops.get('cx')
summary_result["circuit_decomposed_num_of_toffoli"] = circuit_decomposed_count_ops.get('toffoli')
summary_result["circuit_decomposed_num_of_p"] = circuit_decomposed_count_ops.get('p')
summary_result["circuit_decomposed_num_of_t"] = circuit_decomposed_count_ops.get('t')
summary_result["qc_compiled_width"] = qc_compiled.width()
summary_result["qc_compiled_depth"] = qc_compiled.depth()
summary_result["qc_compiled_size"] = qc_compiled.size()
summary_result["qc_compiled_num_nonlocal_gates"] = qc_compiled.num_nonlocal_gates()
summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas
summary_result["qc_compiled_num_clbits"] = qc_compiled.num_clbits
summary_result["qc_compiled_num_qubits"] = qc_compiled.num_qubits
summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas
summary_result["qc_compiled_num_of_count_ops"] = len(qc_compiled_count_ops)
summary_result["qc_compiled_num_of_x"] = qc_compiled_count_ops.get('x')
summary_result["qc_compiled_num_of_measure"] = qc_compiled_count_ops.get('measure')
summary_result["qc_compiled_num_of_h"] = qc_compiled_count_ops.get('h')
summary_result["qc_compiled_num_of_cswap"] = qc_compiled_count_ops.get('cswap')
summary_result["qc_compiled_num_of_swap"] = qc_compiled_count_ops.get('swap')
summary_result["qc_compiled_num_of_cx"] = qc_compiled_count_ops.get('cx')
summary_result["qc_compiled_num_of_toffoli"] = qc_compiled_count_ops.get('toffoli')
summary_result["qc_compiled_num_of_p"] = qc_compiled_count_ops.get('p')
summary_result["qc_compiled_num_of_t"] = qc_compiled_count_ops.get('t')
return summary_result
# Run for just a single number N
%%time
N = 33
shots = 1024
global result_factors
all_summary_result_temp = []
for random_a in range(16, 17):
if math.gcd(random_a,N) > 1:
continue
a = random_a
summary_result = my_shor(a,N,shots)
print("Finished running for a = {} and N = {}\n".format(a, N))
all_summary_result_temp.append(summary_result)
summary_result_list = []
for key, value in summary_result.items():
summary_result_list.append([key,value])
summary_result_list
with open("a({0})_N({1})_standard.csv".format(a, N), 'a') as myfile:
write = csv.writer(myfile)
#write.writerow(fields)
write.writerows(summary_result_list)
all_summary_result_temp
# Run for many numbers N.
%%time
shots = 1024
global result_factors
all_summary_result = []
for N in [15, 21, 33, 35, 39, 51, 55, 57]:
for a in range(2, N):
if math.gcd(a,N) > 1:
continue
print("Beginning running for a = {} and N = {}".format(a, N))
summary_result = my_shor(a,N,shots)
print("Finished running for a = {} and N = {}\n\n".format(a, N))
all_summary_result.append(summary_result)
all_summary_result
%qiskit_copyright
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
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
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
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)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
t3_st_qcs = transpile(t3_st_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_st_qcs), ")")
t3_st_qcs[-1].draw("mpl") # only view trotter gates
# 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")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(t3_st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=initial_layout)
print('Job ID', cal_job.job_id())
dt_now = datetime.datetime.now()
print(dt_now)
with open("jobs_jakarta_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("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "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_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
filename = "job_ids_jakarta_100step_20220412_171248_.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')
# set the target state
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
# mit_results = meas_fitter.filter.apply(job.result()) # apply QREM
rho = StateTomographyFitter(job.result(), st_qcs).fit(method='lstsq')
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The molecule tested is H2.
The shadow is constructed based on derandomized Hamiltonian.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit.circuit.library import TwoLocal, RealAmplitudes
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def process_hamiltonian(hamiltonian, derandomize = False):
"""
For use in derandomization and as input in the function estimate_exp, the Hamiltonian needs to be
reformatted from SparsePauliOp to a list of the form [[(X/Y/Z, position), (X/Y/Z, position)], [...], ...]
For derandomization, the all-identity Hamiltonian term is removed.
For use in estimating expectation values, the all-identity Hamiltonian term is retained as the empty
list [].
hamiltonian:
the problem's qubit Hamiltonian of type SparsePauliOp
derandomize:
if True: return the Hamiltonian formatted for derandomization as well as for use in calculating
the expectation value
if False: return the Hamiltonian formatted for calculating the expectation value only
"""
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
#print('HAMILTONIAN\n', observables_xyze)
def basis_change_circuit(pauli_op):
"""
Generating circuit with just the basis change operators.
pauli_op:
n-qubit Pauli operator that indicates the change of basis
"""
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
"""
Calculate the ground state energy from a shadow represeantation of performed measurements.
operators:
the derandomized Hamiltonian
params:
set of optimal parameters, obtained from VQE run, to be used in the ansatz for shadow generation
"""
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
ansatz = RealAmplitudes(num_qubits=system_size, reps=8, entanglement='linear')
ansatz.decompose().draw('mpl')
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
estimator.set_options(shots = None)
vqe_solver = VQE(estimator, ansatz, SLSQP(maxiter=2000))
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
'''
EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = modified_derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
'''
ESTIMATE THE HAMILTONIAN ON OPTIMAL PARAMETERS
'''
qc = ansatz.bind_parameters(result.raw_result.optimal_point)
job_ham = estimator.run(qc, bkencoded_hamiltonian)
result_h = job_ham.result()
print(f">>> Expectation value of the Hamiltonian: {result_h.values[0]}")
expectation_values = []
for index, term in enumerate(bkencoded_hamiltonian.paulis):
job = estimator.run(qc, term)
#print(f">>> Job ID: {job.job_id()}")
#print(f">>> Job Status: {job.status()}")
result2 = job.result()
#print(f">>> {result2}")
expval = result2.values[0]
expectation_values.append(expval)
print(" > Expectation value of {} with coeff {}: {}".format(term, bkencoded_hamiltonian.coeffs.real[index], expval))
total_expval = 0.0
for index, expval in enumerate(expectation_values):
total_expval += expval * bkencoded_hamiltonian.coeffs.real[index]
print('>>> Total expectation value from summing up expectation values of all terms', total_expval)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests for qiskit-terra/qiskit/quantum_info/synthesis/xx_decompose/qiskit.py .
"""
from statistics import mean
import unittest
import ddt
import numpy as np
from scipy.stats import unitary_group
import qiskit
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.synthesis.xx_decompose.decomposer import (
XXDecomposer,
TwoQubitWeylDecomposition,
)
from .utilities import canonical_matrix
EPSILON = 1e-8
@ddt.ddt
class TestXXDecomposer(unittest.TestCase):
"""Tests for decomposition of two-qubit unitaries over discrete gates from XX family."""
decomposer = XXDecomposer(euler_basis="PSX")
def __init__(self, *args, seed=42, **kwargs):
super().__init__(*args, **kwargs)
self._random_state = np.random.Generator(np.random.PCG64(seed))
def test_random_compilation(self):
"""Test that compilation gives correct results."""
for _ in range(100):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
# decompose into CX, CX/2, and CX/3
circuit = self.decomposer(unitary, approximate=False)
decomposed_unitary = Operator(circuit).data
self.assertTrue(np.all(unitary - decomposed_unitary < EPSILON))
def test_compilation_determinism(self):
"""Test that compilation is stable under multiple calls."""
for _ in range(10):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
# decompose into CX, CX/2, and CX/3
circuit1 = self.decomposer(unitary, approximate=False)
circuit2 = self.decomposer(unitary, approximate=False)
self.assertEqual(circuit1, circuit2)
@ddt.data(np.pi / 3, np.pi / 5, np.pi / 2)
def test_default_embodiment(self, angle):
"""Test that _default_embodiment actually does yield XX gates."""
embodiment = self.decomposer._default_embodiment(angle)
embodiment_matrix = Operator(embodiment).data
self.assertTrue(np.all(canonical_matrix(angle, 0, 0) - embodiment_matrix < EPSILON))
def test_check_embodiment(self):
"""Test that XXDecomposer._check_embodiments correctly diagnoses il/legal embodiments."""
# build the member of the XX family corresponding to a single CX
good_angle = np.pi / 2
good_embodiment = qiskit.QuantumCircuit(2)
good_embodiment.h(0)
good_embodiment.cx(0, 1)
good_embodiment.h(1)
good_embodiment.rz(np.pi / 2, 0)
good_embodiment.rz(np.pi / 2, 1)
good_embodiment.h(1)
good_embodiment.h(0)
good_embodiment.global_phase += np.pi / 4
# mismatch two members of the XX family
bad_angle = np.pi / 10
bad_embodiment = qiskit.QuantumCircuit(2)
# "self.assertDoesNotRaise"
XXDecomposer(embodiments={good_angle: good_embodiment})
self.assertRaises(
qiskit.exceptions.QiskitError, XXDecomposer, embodiments={bad_angle: bad_embodiment}
)
def test_compilation_improvement(self):
"""Test that compilation to CX, CX/2, CX/3 improves over CX alone."""
slope, offset = (64 * 90) / 1000000, 909 / 1000000 + 1 / 1000
strength_table = self.decomposer._strength_to_infidelity(
basis_fidelity={
strength: 1 - (slope * strength / (np.pi / 2) + offset)
for strength in [np.pi / 2, np.pi / 4, np.pi / 6]
},
approximate=True,
)
limited_strength_table = {np.pi / 2: strength_table[np.pi / 2]}
clever_costs = []
naive_costs = []
for _ in range(200):
unitary = unitary_group.rvs(4, random_state=self._random_state)
unitary /= np.linalg.det(unitary) ** (1 / 4)
weyl_decomposition = TwoQubitWeylDecomposition(unitary)
target = [getattr(weyl_decomposition, x) for x in ("a", "b", "c")]
if target[-1] < -EPSILON:
target = [np.pi / 2 - target[0], target[1], -target[2]]
# decompose into CX, CX/2, and CX/3
clever_costs.append(self.decomposer._best_decomposition(target, strength_table)["cost"])
naive_costs.append(
self.decomposer._best_decomposition(target, limited_strength_table)["cost"]
)
# the following are taken from Fig 14 of the XX synthesis paper
self.assertAlmostEqual(mean(clever_costs), 1.445e-2, delta=5e-3)
self.assertAlmostEqual(mean(naive_costs), 2.058e-2, delta=5e-3)
def test_error_on_empty_basis_fidelity(self):
"""Test synthesizing entangling gate with no entangling basis fails."""
decomposer = XXDecomposer(basis_fidelity={})
qc = QuantumCircuit(2)
qc.cx(0, 1)
mat = Operator(qc).to_matrix()
with self.assertRaisesRegex(
qiskit.exceptions.QiskitError,
"Attempting to synthesize entangling gate with no controlled gates in basis set.",
):
decomposer(mat)
def test_no_error_on_empty_basis_fidelity_trivial_target(self):
"""Test synthesizing non-entangling gate with no entangling basis succeeds."""
decomposer = XXDecomposer(basis_fidelity={})
qc = QuantumCircuit(2)
qc.x(0)
qc.y(1)
mat = Operator(qc).to_matrix()
dqc = decomposer(mat)
self.assertTrue(np.allclose(mat, Operator(dqc).to_matrix()))
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
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
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
# unused for this file
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../../solutions/utils/")
import circuit_utils, zne_utils, tomography_utils
importlib.reload(circuit_utils)
importlib.reload(zne_utils) # unused for this file
importlib.reload(tomography_utils) # unused for this file
from circuit_utils import *
from zne_utils import zne_wrapper, zne_decoder
from tomography_utils import expvals_to_valid_rho
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
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_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100]
print("trotter step list: ", num_steps_list)
scale_factors = [1.0, 2.0, 3.0] # unused for this file
shots = 1 << 13
reps = 8 # unused
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
# 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())
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
raw_fid_list = []
raw_stddev_list = []
qrem_fid_list = []
qrem_stddev_list = []
for num_steps in num_steps_list:
print("trotter steps: ", num_steps)
t1 = time.perf_counter()
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
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(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = t3_st_qcs
# zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False)
# print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
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)
retrieved_jobs = jobs
raw_fids = []
qrem_fids = []
for job in retrieved_jobs:
raw_results = job.result()
mit_results = meas_fitter.filter.apply(raw_results)
raw_rho = StateTomographyFitter(raw_results, t3_zne_qcs).fit(method='lstsq')
qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq')
raw_fids.append(state_fidelity(raw_rho, target_state))
qrem_fids.append(state_fidelity(qrem_rho, target_state))
raw_fid_list.append(np.mean(raw_fids))
raw_stddev_list.append(np.std(raw_fids))
qrem_fid_list.append(np.mean(qrem_fids))
qrem_stddev_list.append(np.std(qrem_fids))
t2 = time.perf_counter()
print('raw state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(raw_fids), np.std(raw_fids)))
print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids)))
print("time:", t2 - t1)
print()
with open("e2d1_raw.pkl", "wb") as f:
pickle.dump({"num_steps_list": num_steps_list, "fid": raw_fid_list, "stddev": raw_stddev_list}, f)
with open("e2d1_qrem.pkl", "wb") as f:
pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f)
import qiskit.tools.jupyter
%qiskit_version_table
plt.plot(num_steps_list, raw_fid_list)
plt.plot(num_steps_list, qrem_fid_list)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram, visualize_transition
quantum_bit = 1
classical_bit = 1
circ = QuantumCircuit(quantum_bit, classical_bit)
circ.x(0)
circ.draw(output='mpl')
visualize_transition(circ)
circ.measure(0, 0)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, backend=simulator, shots=1000).result()
counts = result.get_counts(circ)
plot_histogram(counts)
circ = QuantumCircuit(1, 1)
circ.x(0)
circ.x(0)
circ.draw(output='mpl')
visualize_transition(circ)
circ.measure(0, 0)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, backend=simulator, shots=1000).result()
counts = result.get_counts(circ)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
import click
import time
import random
import statistics
import csv
import os.path
import math
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import QiskitError, execute, Aer
from qiskit_qcgpu_provider import QCGPUProvider
# Implementation of the Quantum Fourier Transform
def construct_circuit(num_qubits):
q = QuantumRegister(num_qubits)
c = ClassicalRegister(num_qubits)
circ = QuantumCircuit(q, c)
# Quantum Fourier Transform
for j in range(num_qubits):
for k in range(j):
circ.cu1(math.pi / float(2**(j - k)), q[j], q[k])
circ.h(q[j])
# circ.measure(q, c)
return circ
# Benchmarking functions
# qiskit_backend = Aer.get_backend('qasm_simulator')
# qcgpu_backend = QCGPUProvider().get_backend('qasm_simulator')
qiskit_backend = Aer.get_backend('statevector_simulator')
qcgpu_backend = QCGPUProvider().get_backend('statevector_simulator')
def bench_qiskit(qc):
start = time.time()
job_sim = execute(qc, qiskit_backend)
sim_result = job_sim.result()
return time.time() - start
def bench_qcgpu(qc):
start = time.time()
job_sim = execute(qc, qcgpu_backend)
sim_result = job_sim.result()
return time.time() - start
# Reporting
def create_csv(filename):
file_exists = os.path.isfile(filename)
csvfile = open(filename, 'a')
headers = ['name', 'num_qubits', 'time']
writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n', fieldnames=headers)
if not file_exists:
writer.writeheader() # file doesn't exist yet, write a header
return writer
def write_csv(writer, data):
writer.writerow(data)
@click.command()
@click.option('--samples', default=5, help='Number of samples to take for each qubit.')
@click.option('--qubits', default=5, help='How many qubits you want to test for')
@click.option('--out', default='benchmark_data.csv',
help='Where to store the CSV output of each test')
@click.option(
'--single',
default=False,
help='Only run the benchmark for a single amount of qubits, and print an analysis')
@click.option('--burn', default=True, help='Burn the first few samples for accuracy')
def benchmark(samples, qubits, out, single, burn):
burn_count = 5 if burn else 0
if single:
functions = bench_qcgpu, bench_qiskit
times = {f.__name__: [] for f in functions}
names = []
means = []
qc = construct_circuit(qubits)
# Run the benchmarks
for i in range(samples + burn_count):
progress = (i) / (samples + burn_count)
if samples > 1:
print("\rProgress: [{0:50s}] {1:.1f}%".format('#' * int(progress * 50), progress * 100), end="", flush=True)
func = random.choice(functions)
t = func(qc)
if i >= burn_count:
times[func.__name__].append(t)
print('')
for name, numbers in times.items():
print('FUNCTION:', name, 'Used', len(numbers), 'times')
print('\tMEDIAN', statistics.median(numbers))
print('\tMEAN ', statistics.mean(numbers))
if len(numbers) > 1:
print('\tSTDEV ', statistics.stdev(numbers))
return
functions = bench_qcgpu, bench_qiskit
writer = create_csv(out)
for n in range(1, qubits):
# Progress counter
progress = (n + 1) / (qubits)
print("\rProgress: [{0:50s}] {1:.1f}%".format('#' * int(progress * 50), progress * 100), end="", flush=True)
# Construct the circuit
qc = construct_circuit(n + 1)
# Run the benchmarks
for i in range(samples):
func = random.choice(functions)
t = func(qc)
# times[func.__name__].append(t)
write_csv(writer, {'name': func.__name__, 'num_qubits': n + 1, 'time': t})
if __name__ == '__main__':
benchmark()
|
https://github.com/psasanka1729/nisq-grover-qiskit-floquet-model
|
psasanka1729
|
import numpy as np
from scipy.sparse import identity
from scipy import sparse
from qiskit import*
L = 4
gates_list = open('gates_list_'+str(L)+'.txt','r')
MCX_transpile = []
for gates in gates_list:
MCX_transpile.append(gates.split(","))
len(MCX_transpile)
number_of_gates = len(MCX_transpile)
Seed = 4000
np.random.seed(Seed)
Noise = np.random.rand(number_of_gates)
def H_fixed(): # Hadamad gate acting on one qubit.
return 1/np.sqrt(2)*np.matrix([[1,1],
[1,-1]])
def Ry(theta):
return np.matrix([[np.cos(theta/2), -np.sin(theta/2)],
[np.sin(theta/2), np.cos(theta/2)]])
def sigma_Z():
return np.matrix([[1,0],
[0,-1]])
def sigma_X():
return np.matrix([[0,1],
[1,0]])
def Rz(theta):
return np.matrix([[np.exp(-1j*theta/2), 0],
[0, np.exp(1j*theta/2)]])
'''
For noise = 0; the following returns the fixed Hadamard gate.
'''
def Hadamard_variable(noise):
return Ry(np.pi/2+noise)*sigma_Z()
def sigma_X_variable(noise):
return Hadamard_variable(noise)*sigma_Z()*Hadamard_variable(noise)
def Cx(noise):
Pi_0 = np.matrix([[1,0],[0,0]])
final_matrix_1 = sparse.kron(Pi_0,np.identity(2))
Pi_1 = np.matrix([[0,0],[0,1]])
final_matrix_2 = sparse.kron(Pi_1,sigma_X_variable(noise))
return final_matrix_1+final_matrix_2
def CU_gate(quantum_gate,control_qubit,target_qubit):
Pi_0 = np.matrix([[1,0],[0,0]])
Pi_1 = np.matrix([[0,0],[0,1]])
'''
List below will hold gates acting on one qubit. For example, for L = 8,
gate U acting on control qubit c and target qubit t is
I x I x ...x (Pi_0)_c x ...x (I)_t x ... x I + I x I x ...x (Pi_1)_c x ...x (U)_t x ... x I
'''
qubits_list_1 = []
for i in range(L):
if i == control_qubit:
qubits_list_1.append(Pi_0)
else: # Other gates are identity operators.
qubits_list_1.append(np.identity(2))
qubits_list_2 = []
for i in range(L):
if i == control_qubit:
qubits_list_2.append(Pi_1)
elif i == target_qubit:
qubits_list_2.append(quantum_gate)
else: # Other gates are identity operators.
qubits_list_2.append(np.identity(2))
#qubits_list_1.reverse()
#qubits_list_2.reverse()
final_matrix_1 = sparse.csr_matrix(qubits_list_1[0]) # Initializes the final matrix.
for g in range(1,len(qubits_list_1)):
final_matrix_1 = sparse.kron(qubits_list_1[g],final_matrix_1) # kronecker product.
final_matrix_2 = sparse.csr_matrix(qubits_list_2[0]) # Initializes the final matrix.
for g in range(1,len(qubits_list_2)):
final_matrix_2 = sparse.kron(qubits_list_2[g],final_matrix_2) # kronecker product.
return final_matrix_1+final_matrix_2
def N_th_qubit_gate(quantum_gate,qubit_number):
'''
List below will hold gates acting on one qubit. For example, for L = 3,
the Hadamard gate acting on the qubit 1 is given by = 1 x H x 1, where
x is the Kronecker product. Then, qubits_list = [1,H,1].
'''
qubits_list = []
for i in range(L):
if i == qubit_number: # qubit_number^th position in the list is the quantum_gate.
qubits_list.append(quantum_gate)
else: # Other gates are identity operators.
qubits_list.append(np.identity(2))
'''
The following loop performs the Kronecker product.
'''
final_matrix = sparse.csr_matrix(qubits_list[0]) # Initializes the final matrix.
for i in range(1,len(qubits_list)):
final_matrix = sparse.kron(final_matrix,qubits_list[i]) # kronecker product.
return final_matrix
U_0 = np.identity(2**L, dtype = complex);
Delta = 0.0
noise_counter = 0
for i in MCX_transpile:
if i[0] == 'h':
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
qubit = int(i[2])
U_0 = U_0*N_th_qubit_gate(Hadamard_variable(epsilon),qubit)
#np.matmul(U_0,N_th_qubit_gate(Hadamard_variable(epsilon),qubit))
elif i[0] == 'cx':
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
control_qubit = int(i[1])
target_qubit = int(i[2])
U_0 = U_0*CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit)
#np.matmul(U_0,CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit))
elif i[0] == 'rz':
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
qubit = int(i[2])
angle = float(i[1])
U_0 = U_0*N_th_qubit_gate(Rz(epsilon+angle),qubit)
m = np.around(U_0,2)
m = m/m[0,0]
m.real
def Grover_operator(Delta):
noise_counter = 0
'''
First the U_x will be created.
'''
U_x = np.identity(2**L, dtype = complex);
for i in range(L):
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
U_x = U_x*N_th_qubit_gate(Hadamard_variable(epsilon),i)
#np.matmul(U_x,N_th_qubit_gate(Hadamard_variable(epsilon),i))
for i in range(L):
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
U_x = U_x*N_th_qubit_gate(sigma_X_variable(epsilon),i)
#np.matmul(U_x,N_th_qubit_gate(sigma_X_variable(epsilon),i))
# mcx gate of U_x
for i in MCX_transpile:
if i[0] == 'h':
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
qubit = int(i[2])
U_x = U_x*N_th_qubit_gate(Hadamard_variable(epsilon),qubit)
#np.matmul(U_x,N_th_qubit_gate(Hadamard_variable(epsilon),qubit))
elif i[0] == 'cx':
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
control_qubit = int(i[1])
target_qubit = int(i[2])
U_x = U_x*CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit)
#np.matmul(U_x,CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit))
elif i[0] == 'rz':
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
qubit = int(i[2])
angle = float(i[1])
U_x = U_x*N_th_qubit_gate(Rz(epsilon+angle),qubit)
#np.matmul(U_x,N_th_qubit_gate(Rz_variable(epsilon+angle),qubit))
for i in range(L):
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
U_x = U_x*N_th_qubit_gate(sigma_X_variable(epsilon),i)
#np.matmul(U_x,N_th_qubit_gate(sigma_X_variable(epsilon),i))
for i in range(L):
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
U_x = U_x*N_th_qubit_gate(Hadamard_variable(epsilon),i)
#np.matmul(U_x,N_th_qubit_gate(Hadamard_variable(epsilon),i))
'''
First the U_0 will be created.
'''
U_0 = np.identity(2**L, dtype = complex);
for i in range(L):
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
U_0 = U_0*N_th_qubit_gate(sigma_X_variable(epsilon),i)
#np.matmul(U_0,N_th_qubit_gate(sigma_X_variable(epsilon),i))
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
U_0 = U_0*N_th_qubit_gate(Hadamard_variable(epsilon),L)
#np.matmul(U_0,N_th_qubit_gate(Hadamard_variable(epsilon),L))
# mcx gate of U_0
for i in MCX_transpile:
if i[0] == 'h':
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
qubit = int(i[2])
U_0 = U_0*N_th_qubit_gate(Hadamard_variable(epsilon),qubit)
#np.matmul(U_0,N_th_qubit_gate(Hadamard_variable(epsilon),qubit))
elif i[0] == 'cx':
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
control_qubit = int(i[1])
target_qubit = int(i[2])
U_0 = U_0*CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit)
#np.matmul(U_0,CU_gate(sigma_X_variable(epsilon),control_qubit,target_qubit))
elif i[0] == 'rz':
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
qubit = int(i[2])
angle = float(i[1])
U_0 = U_0*N_th_qubit_gate(Rz(epsilon+angle),qubit)
#np.matmul(U_0,N_th_qubit_gate(Rz_variable(epsilon+angle),qubit))
for i in range(L):
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
U_0 = U_0*N_th_qubit_gate(sigma_X_variable(epsilon),i)
#np.matmul(U_0,N_th_qubit_gate(sigma_X_variable(epsilon),i))
epsilon = Delta*Noise[noise_counter]
noise_counter += 1
U_0 = U_0*N_th_qubit_gate(Hadamard_variable(epsilon),L)
#np.matmul(U_0,N_th_qubit_gate(Hadamard_variable(epsilon),L))
return U_0
|
https://github.com/dcavar/q
|
dcavar
|
import numpy as np
A = np.array([[1, 3, 2], [0, 2, 6]])
print("Matrix A:\n", A)
B = np.array([[2, 0, 1, 4], [3, 1, 3, 1], [1, 2, 2, 6]])
print("Matrix B:\n", B)
print("Matrix product:")
A @ B
A = np.array([[0, 1], [1, 0]])
print("Matrix A:\n", A)
B = np.array([[1], [0]])
print("Matrix B:\n", B)
A @ B
C = 2 * A
print("Matrix C:\n", C)
from qiskit.quantum_info import Statevector
ASV = Statevector([0, 1])
ASV.draw(output="latex")
ASV.draw(output="qsphere")
BSV = Statevector([1, 0])
BSV.draw(output="latex")
BSV.draw(output="qsphere")
CSV = BSV.tensor(ASV.tensor(BSV))
CSV.draw(output="latex")
A = np.array([ 1, 2 ])
B = np.array([ 1, 2 ])
np.tensordot(A, B, axes=0)
A = np.array([[1,3], [4,2]])
B = np.array([[2,1], [5,4]])
np.tensordot(A, B, axes=0)
x = 2
y = 1
z = complex(x, y)
z
print(np.real(z))
print(np.imag(z))
r = complex(2, 3)
r
r * z
x = complex((z.real * r.real) - (z.imag * r.imag), (z.real * r.imag) + (z.imag * r.real))
x
from qiskit.visualization import plot_bloch_vector
x = plot_bloch_vector([0,1,0], title="New Bloch Sphere")
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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=invalid-name,missing-docstring
# pylint: disable=attribute-defined-outside-init
from qiskit import transpile
from qiskit.circuit.library.standard_gates import XGate
from qiskit.transpiler import CouplingMap
from qiskit.transpiler import InstructionDurations
from qiskit.transpiler.passes import (
TimeUnitConversion,
ASAPSchedule,
ALAPSchedule,
DynamicalDecoupling,
)
from qiskit.converters import circuit_to_dag
from .utils import random_circuit
class SchedulingPassBenchmarks:
params = ([5, 10, 20], [500, 1000])
param_names = ["n_qubits", "depth"]
timeout = 300
def setup(self, n_qubits, depth):
seed = 42
self.circuit = random_circuit(
n_qubits, depth, measure=True, conditional=True, reset=True, seed=seed, max_operands=2
)
self.basis_gates = ["rz", "sx", "x", "cx", "id", "reset"]
self.cmap = [
[0, 1],
[1, 0],
[1, 2],
[1, 6],
[2, 1],
[2, 3],
[3, 2],
[3, 4],
[3, 8],
[4, 3],
[5, 6],
[5, 10],
[6, 1],
[6, 5],
[6, 7],
[7, 6],
[7, 8],
[7, 12],
[8, 3],
[8, 7],
[8, 9],
[9, 8],
[9, 14],
[10, 5],
[10, 11],
[11, 10],
[11, 12],
[11, 16],
[12, 7],
[12, 11],
[12, 13],
[13, 12],
[13, 14],
[13, 18],
[14, 9],
[14, 13],
[15, 16],
[16, 11],
[16, 15],
[16, 17],
[17, 16],
[17, 18],
[18, 13],
[18, 17],
[18, 19],
[19, 18],
]
self.coupling_map = CouplingMap(self.cmap)
self.transpiled_circuit = transpile(
self.circuit,
basis_gates=self.basis_gates,
coupling_map=self.coupling_map,
optimization_level=1,
)
self.dag = circuit_to_dag(self.transpiled_circuit)
self.durations = InstructionDurations(
[
("rz", None, 0),
("id", None, 160),
("sx", None, 160),
("x", None, 160),
("cx", None, 800),
("measure", None, 3200),
("reset", None, 3600),
],
dt=1e-9,
)
self.timed_dag = TimeUnitConversion(self.durations).run(self.dag)
_pass = ALAPSchedule(self.durations)
_pass.property_set["time_unit"] = "dt"
self.scheduled_dag = _pass.run(self.timed_dag)
def time_time_unit_conversion_pass(self, _, __):
TimeUnitConversion(self.durations).run(self.dag)
def time_alap_schedule_pass(self, _, __):
_pass = ALAPSchedule(self.durations)
_pass.property_set["time_unit"] = "dt"
_pass.run(self.timed_dag)
def time_asap_schedule_pass(self, _, __):
_pass = ASAPSchedule(self.durations)
_pass.property_set["time_unit"] = "dt"
_pass.run(self.timed_dag)
def time_dynamical_decoupling_pass(self, _, __):
DynamicalDecoupling(self.durations, dd_sequence=[XGate(), XGate()]).run(self.scheduled_dag)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
!git clone --branch qamp-qiskit-demodays https://github.com/qiskit-community/qiskit-qec.git /Users/ruihaoli/qiskit-qec
%cd ../qiskit-qec
!pip install -r requirements.txt
import numpy as np
from qiskit_qec.operators.xp_pauli import XPPauli
from qiskit_qec.operators.xp_pauli_list import XPPauliList
# XPPauli object
a = XPPauli(
data=np.array([0, 3, 1, 6, 4, 3], dtype=np.int64), phase_exp=11, precision=4
)
unique_a = a.unique_vector_rep()
print(unique_a.matrix)
print(unique_a.x)
print(unique_a.z)
print(unique_a._phase_exp)
# XPPauliList object
b = XPPauliList(
data=np.array([[1, 0, 1, 1, 5, 3, 5, 4], [1, 0, 1, 0, 1, 5, 2, 0]], dtype=np.int64),
phase_exp=np.array([4, 7]),
precision=6,
)
unique_b = b.unique_vector_rep()
print(unique_b.matrix)
print(unique_b._phase_exp)
a = XPPauli(
data=np.array([1, 1, 1, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0]), phase_exp=12, precision=8
)
rescaled_a = a.rescale_precision(new_precision=2, inplace=False)
print(rescaled_a.matrix)
print(rescaled_a._phase_exp)
# Case where it is not possible to rescale
a.rescale_precision(new_precision=3, inplace=False)
a = XPPauli(data=np.array([1, 1, 2, 2, 1, 2, 3, 3]), phase_exp=0, precision=8)
antisym_op = a.antisymmetric_op(int_vec=a.z)
print(antisym_op.matrix)
print(antisym_op._phase_exp)
a = XPPauli(data=np.array([0, 1, 0, 0, 2, 0]), phase_exp=6, precision=4)
b = XPPauli(data=np.array([1, 1, 1, 3, 3, 0]), phase_exp=2, precision=4)
product = a.compose(b, inplace=False)
print(product.matrix)
print(product._phase_exp)
# Multiplying two XPPauliList objects
a = XPPauliList(
data=np.array([[1, 0, 1, 1, 5, 3, 5, 4], [1, 0, 1, 0, 1, 5, 2, 0]]),
phase_exp=np.array([4, 7]),
precision=6,
)
b = XPPauliList(
data=np.array([[1, 0, 0, 1, 4, 1, 0, 1], [0, 1, 1, 0, 1, 3, 0, 5]]),
phase_exp=np.array([11, 2]),
precision=6,
)
product = a.compose(b, inplace=False)
print(product.matrix)
print(product._phase_exp)
a = XPPauliList(
data=np.array([[1, 0, 1, 1, 5, 3, 5, 4], [1, 0, 1, 1, 5, 4, 1, 5]]),
phase_exp=[1, 2],
precision=6,
)
a1 = a.power(n=5)
print(a1.matrix)
print(a1._phase_exp, "\n")
a2 = a.power(n=[3, 4])
print(a2.matrix)
print(a2._phase_exp)
import qiskit_qec.arithmetic.modn as modn
# Quotient of a/b in the ring Z_N
a, b, N = 18, 3, 5
q = modn.quo(a, b, N)
print(q)
print(q == (a % N) // (b % N))
# Divisor of a/b in the ring Z_N
a, b, N = 24, 8, 7
d = modn.div(a, b, N)
print(d)
print((b * d) % N == a % N)
# Annihilator of a in the ring Z/nZ
a, N = 10, 5
ann = modn.ann(a, N)
print(ann)
print((a * ann) % N == 0)
from qiskit_qec.linear.matrix import do_row_op
mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
N = 4
print(mat, "\n")
# Swap rows 0 and 1
mat1 = do_row_op(mat, ("swap", [0, 1], []), N)
print(mat1, "\n")
# Append the product of row 0 by a scalar (3) to the end of matrix
mat2 = do_row_op(mat, ("append", [0], [3]), N)
print(mat2)
from qiskit_qec.linear.matrix import howell, howell_complete
mat = np.array([[8, 5, 5], [0, 9, 8], [0, 0, 10]])
N = 12
howell_mat = howell(mat, N)
print(howell_mat, "\n")
howell_mat, transform_mat, kernel_mat = howell_complete(mat, N)
print(howell_mat, "\n")
print(transform_mat, "\n")
print(kernel_mat)
|
https://github.com/jdellaverson19/qiskit2020
|
jdellaverson19
|
import numpy as np
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit.visualization import plot_histogram
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# 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)
print(counts)
# Draw the circuit
circuit.draw()
print(circuit)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit_nature.problems.sampling.protein_folding.interactions.random_interaction import (
RandomInteraction,
)
from qiskit_nature.problems.sampling.protein_folding.interactions.miyazawa_jernigan_interaction import (
MiyazawaJerniganInteraction,
)
from qiskit_nature.problems.sampling.protein_folding.peptide.peptide import Peptide
from qiskit_nature.problems.sampling.protein_folding.protein_folding_problem import (
ProteinFoldingProblem,
)
from qiskit_nature.problems.sampling.protein_folding.penalty_parameters import PenaltyParameters
from qiskit.utils import algorithm_globals, QuantumInstance
algorithm_globals.random_seed = 23
main_chain = "APRLRFY"
side_chains = [""] * 7
random_interaction = RandomInteraction()
mj_interaction = MiyazawaJerniganInteraction()
penalty_back = 10
penalty_chiral = 10
penalty_1 = 10
penalty_terms = PenaltyParameters(penalty_chiral, penalty_back, penalty_1)
peptide = Peptide(main_chain, side_chains)
protein_folding_problem = ProteinFoldingProblem(peptide, mj_interaction, penalty_terms)
qubit_op = protein_folding_problem.qubit_op()
print(qubit_op)
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import COBYLA
from qiskit.algorithms import NumPyMinimumEigensolver, VQE
from qiskit.opflow import PauliExpectation, CVaRExpectation
from qiskit import execute, Aer
# set classical optimizer
optimizer = COBYLA(maxiter=50)
# set variational ansatz
ansatz = RealAmplitudes(reps=1)
# set the backend
backend_name = "aer_simulator"
backend = QuantumInstance(
Aer.get_backend(backend_name),
shots=8192,
seed_transpiler=algorithm_globals.random_seed,
seed_simulator=algorithm_globals.random_seed,
)
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
# initialize CVaR_alpha objective with alpha = 0.1
cvar_exp = CVaRExpectation(0.1, PauliExpectation())
# initialize VQE using CVaR
vqe = VQE(
expectation=cvar_exp,
optimizer=optimizer,
ansatz=ansatz,
quantum_instance=backend,
callback=store_intermediate_result,
)
raw_result = vqe.compute_minimum_eigenvalue(qubit_op)
print(raw_result)
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(counts, values)
plt.ylabel("Conformation Energy")
plt.xlabel("VQE Iterations")
fig.add_axes([0.44, 0.51, 0.44, 0.32])
plt.plot(counts[40:], values[40:])
plt.ylabel("Conformation Energy")
plt.xlabel("VQE Iterations")
plt.show()
result = protein_folding_problem.interpret(raw_result=raw_result)
print(
"The bitstring representing the shape of the protein during optimization is: ",
result.turns_sequence,
)
print("The expanded expression is:", result.get_result_binary_vector())
print(
f"The folded protein will have a main turns sequence of: {result.protein_shape_decoder.main_turns}"
)
print(f"and the following side turns sequences: {result.protein_shape_decoder.side_turns}")
print(result.protein_shape_file_gen.get_xyz_file())
%matplotlib notebook
fig = result.get_figure(title="Protein Structure", ticks=False, grid=False)
fig.show()
peptide = Peptide("APRLR", ["", "", "F", "Y", ""])
protein_folding_problem = ProteinFoldingProblem(peptide, mj_interaction, penalty_terms)
qubit_op = protein_folding_problem.qubit_op()
raw_result = vqe.compute_minimum_eigenvalue(qubit_op)
result_2 = protein_folding_problem.interpret(raw_result=raw_result)
%matplotlib notebook
fig = result_2.get_figure(title="Protein Structure", ticks=False, grid=False)
fig.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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量子ビット回路を用意
qe = QuantumCircuit(2) # 今回は量子ビットのみ用意します。
# 回路を描画
qe.draw(output="mpl")
#qe # ← 修正して回路を完成させてください。片方の量子ビットに重ね合わせを掛けます。
qe.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(qe, vector_sim )
counts = job.result().get_counts(qe) # 実行結果の詳細を取り出し
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
# qe # ← cxゲートを使って回路を完成させてください。順番に注意してください。
qe.draw(output='mpl')
# 状態ベクトルシミュレーターの実行
vector_sim = Aer.get_backend('statevector_simulator')
job = execute(qe, vector_sim )
# result = job.result().get_statevector(qe, decimals=3)
# print(result)
counts = job.result().get_counts(qe) # 実行結果の詳細を取り出し
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
# 2量子ビット回路を用意
qe2 = QuantumCircuit(2,2) # 量子ビットと古典レジスターを用意します
# 量子回路を設計
qe2.h(0)
qe2.cx(0,1)
# 回路を測定
qe2.measure(0,0)
qe2.measure(1,1)
# 回路を描画
qe2.draw(output="mpl")
# QASMシミュレーターで実験
simulator = Aer.get_backend('qasm_simulator')
job = execute(qe2, backend=simulator, shots=1024)
result = job.result()
# 測定された回数を表示
counts = result.get_counts(qe2)
print(counts)
# ヒストグラムで測定された確率をプロット
from qiskit.visualization import *
plot_histogram( counts )
from qiskit import IBMQ
IBMQ.save_account('MY_API_TOKEN')
# IBM Q アカウントをロードします。
provider = IBMQ.load_account()
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("The best backend is " + real_backend.name())
print('run on real device!')
real_result = execute(qe2,real_backend).result() # 計算を実行します
print(real_result.get_counts(qe2)) # 結果を表示
plot_histogram(real_result.get_counts(qe2)) # ヒストグラムを表示
|
https://github.com/lmarza/QuantumDeskCalculator
|
lmarza
|
from qiskit import *
from operations import addition, subtraction, multiplication, division
from utils import bcolors, selectOperator, checkOperation, printResult, initQubits
import math
if __name__ == "__main__":
print(bcolors.OKGREEN + '##########################################' + bcolors.ENDC)
print(bcolors.OKGREEN + '####### Quantum Desk Calculator ########' + bcolors.ENDC)
print(bcolors.OKGREEN + '##########################################'+ bcolors.ENDC)
# take the operator and check
operator = selectOperator()
input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC))
input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC))
# check the inputs
while (input1 < 0 or input1 > 2047) or (input2 < 0 or input2 > 2047):
if input1 < 0 or input1 > 2047:
print(bcolors.FAIL + "Invalid first input number" + bcolors.ENDC)
input1 = int(input(bcolors.WARNING + "Enter a first positive integer between 0 and 2047:\n" + bcolors.ENDC))
if input2 < 0 or input2 > 2047:
print(bcolors.FAIL + "Invalid second input number" + bcolors.ENDC)
input2 = int(input(bcolors.WARNING + "Enter a second positive integer between 0 and 2047:\n" + bcolors.ENDC))
#check if the operation is valid
checkOperation(input1, input2, operator)
first = '{0:{fill}3b}'.format(input1, fill='0')
second = '{0:{fill}3b}'.format(input2, fill='0')
# for multiplication
firstDec = input1
secondDec = input2
l1 = len(first)
l2 = len(second)
# Making sure that 'first' and 'second' are of the same length
# by padding the smaller string with zeros
if operator == '+' or operator == '-' or operator == '/':
if l2>l1:
first,second = second, first
l2, l1 = l1, l2
second = ("0")*(l1-l2) + second
n = l1
elif operator == '*' :
# Padding 'first' the same lenght of 'result'
# since result can have at max len(first) + len(second) bits when multiplying
first = ("0")*(l2) + first
n = l1+l2
print()
print(bcolors.OKCYAN + '#'*150 + bcolors.ENDC)
print(bcolors.BOLD + bcolors.OKCYAN + 'You want to perform the following operation:'+ bcolors.ENDC)
print(bcolors.BOLD + bcolors.OKCYAN + f'{input1} {operator} {input2} --> {first} {operator} {second} = ...' + bcolors.ENDC)
# create the register based on the operation choosen
# Add a qbit to 'a' and 'b' in case of overflowing results
# (the result is only read on 'a' or 'accumulator', but since 'a' (or 'accumulator') and 'b'
# should have the same lenght, we also add a qbit to 'b')
a = QuantumRegister(n+1, "a")
b = QuantumRegister(n+1, "b")
accumulator = QuantumRegister(n+1, "accumulator")
cl = ClassicalRegister(n+1, "cl")
if operator == '+' or operator == '-' or operator == '*':
qc = QuantumCircuit(a, b, cl, name="qc")
# Flip the corresponding qubit in register a if a bit in the string first is a 1
initQubits(first, qc, a, n)
# Flip the corresponding qubit in register b if b bit in the string second is a 1
if operator != '*':
initQubits(second, qc, b, n)
if operator == '+':
addition.sum(a,b,qc)
printResult(first, second, qc,a, cl, n, operator)
elif operator == '-':
subtraction.sub(a,b,qc)
printResult(first, second, qc,a, cl, n, operator)
elif operator == '*':
multiplication.multiply(a,secondDec,b,qc)
printResult(first, second, qc, b, cl, n,operator)
elif operator == '/':
qc = QuantumCircuit(a, b, accumulator, cl, name="qc")
# Flip the corresponding qubit in register a and b if a,b bit in the string first,second is a 1
initQubits(first, qc, a, n)
initQubits(second, qc, b, n)
division.div(a, b, accumulator, cl, qc, 0)
printResult(first, second, qc, accumulator, cl, n, operator)
print(bcolors.OKCYAN + '#'*150 + bcolors.ENDC)
|
https://github.com/jaykomarraju/Quantum-Optimization-for-Solar-Farm
|
jaykomarraju
|
import numpy as np
import networkx as nx
from qiskit import Aer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
num_time_slots = 24
# Define the QUBO problem
qubo = QuadraticProgram()
# Add binary variables for charging (c) and discharging (d) states
for t in range(num_time_slots):
qubo.binary_var(f'c_{t}')
qubo.binary_var(f'd_{t}')
# Define the objective function
# (In practice, you need to calculate Jij and hi based on the solar farm data)
Jij = np.random.rand(num_time_slots, num_time_slots) * 0.5
hi_c = -1 + np.random.rand(num_time_slots)
hi_d = 1 - np.random.rand(num_time_slots)
# Set linear and quadratic terms of the objective function
linear_terms = {}
quadratic_terms = {}
for t in range(num_time_slots):
linear_terms[f'c_{t}'] = hi_c[t]
linear_terms[f'd_{t}'] = hi_d[t]
for s in range(num_time_slots):
if t != s:
quadratic_terms[(f'c_{t}', f'c_{s}')] = Jij[t, s]
quadratic_terms[(f'd_{t}', f'd_{s}')] = Jij[t, s]
qubo.minimize(linear=linear_terms, quadratic=quadratic_terms)
# Set up the quantum instance
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=42, seed_transpiler=42, shots=10000)
# Set up the QAOA algorithm and optimizer
optimizer = COBYLA(maxiter=500)
qaoa = QAOA(optimizer=optimizer, reps=5, quantum_instance=quantum_instance)
# Set up the minimum eigen optimizer
min_eig_optimizer = MinimumEigenOptimizer(qaoa)
# Solve the problem
result = min_eig_optimizer.solve(qubo)
print("QAOA result:", result)
# Solve the problem using a classical solver (NumPyMinimumEigensolver)
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qubo)
print("Classical result:", exact_result)
|
https://github.com/Dpbm/scientific-research-1-quantum-oracles
|
Dpbm
|
%matplotlib inline
from pprint import pprint
from qiskit.quantum_info import Statevector
from qiskit import QuantumCircuit, QuantumRegister,transpile
from qiskit.visualization import array_to_latex, plot_distribution, plot_histogram
from qiskit.circuit.library import GroverOperator
from qiskit_aer import AerSimulator
from qiskit_algorithms import AmplificationProblem
from qiskit_algorithms import Grover
from qiskit.primitives import Sampler
#from qiskit.providers.fake_provider import FakeWashington
import numpy as np
import pandas as pd
import os
from tqdm.notebook import trange
import seaborn as sns
import matplotlib.pyplot as plt
from dotenv import load_dotenv
from qiskit_ibm_runtime import QiskitRuntimeService, Options, Sampler as IBMSampler
from utils import get_image_path
def hanoi(disc, start, aux, end, steps):
if(disc == 0):
return
hanoi(disc-1, start, end, aux, steps)
steps.append((disc, start, end))
hanoi(disc-1, aux, start, end, steps)
return steps
steps = hanoi(2, 0, 1, 2, [])
pprint(steps, width=20)
steps_for_3 = hanoi(3, 0, 1, 2, [])
pprint(steps_for_3, width=20)
def hanoi_solver(towers, steps):
for _, from_, to_ in steps:
value = towers[from_].pop()
towers[to_].append(value)
print(towers)
towers = [list(range(3, 0, -1)), [], []]
hanoi_solver(towers, steps_for_3)
print('result: ', towers)
def generate_hanoi_u(total_discs=3, n_qubits=3, total_towers=3):
assert total_discs <= 2**n_qubits, "Invalid size"
assert total_towers > 0 and total_towers <= 3, "invalid towers amount"
total_qubits = n_qubits*total_towers
tower = QuantumCircuit(total_qubits, name="hanoi U")
for i in range(1, total_discs+1):
binary = f"{i:0{total_qubits}b}"[::-1]
zeros = [ i for i,v in enumerate(binary) if v=='0']
has_zeros = len(zeros) > 0
if(has_zeros): tower.x(zeros)
tower.mcp(np.pi, list(range(1, total_qubits)), 0)
if(has_zeros): tower.x(zeros)
tower.barrier()
return tower
tower = generate_hanoi_u(n_qubits=1, total_discs=1)
tower.draw('mpl', style="clifford")
def get_unitary(qc, sim=AerSimulator()):
qc_copy = qc.copy()
qc_copy.save_unitary()
result = sim.run(transpile(qc_copy, sim), shots=1000).result().get_unitary()
display(array_to_latex(result, max_size=10000))
get_unitary(tower)
source = QuantumRegister(1, name="source")
auxiliary = QuantumRegister(1, name="aux")
target = QuantumRegister(1, name="target")
hanoi_1 = QuantumCircuit(source, auxiliary, target)
hanoi_1.append(generate_hanoi_u(n_qubits=1, total_discs=1), [*source, *auxiliary, *target])
hanoi_1.swap(source, target)
display(hanoi_1.draw('mpl', style="clifford", filename=get_image_path("hanoi_1_disc.png")))
get_unitary(hanoi_1)
def test_result(oracle, expected, filename=None, sampler=Sampler()):
problem = AmplificationProblem(oracle, is_good_state=expected)
grover = Grover(sampler=sampler)
result = grover.amplify(problem)
print(f"Reached the expected values: {result.oracle_evaluation}")
print(f"Top measurments: {result.top_measurement}")
s = pd.Series(result.circuit_results[0])
df = pd.DataFrame(s)
df = df.reset_index(names="bit_strings")
df = df.rename(columns={0:'distribution'})
plt.figure(figsize=(10, 5))
plt.bar(data=df, x="bit_strings", height='distribution')
plt.xticks(rotation=90)
plt.xlabel("bit_string")
plt.ylabel("dist")
if(filename):
plt.savefig(filename, bbox_inches="tight")
display(plt.show())
test_result(hanoi_1, ['100'], filename=get_image_path("result_hanoi_1_disc.png"))
hanoi(2, 0, 1, 2, [])
source = QuantumRegister(2, name="source")
auxiliary = QuantumRegister(2, name="aux")
target = QuantumRegister(2, name="target")
hanoi_2 = QuantumCircuit(source, auxiliary, target)
hanoi_2.append(generate_hanoi_u(n_qubits=2, total_discs=2), [*source, *auxiliary, *target])
hanoi_2.swap(source[0], auxiliary[0])
hanoi_2.swap(source[1], target[1])
hanoi_2.swap(auxiliary[0], target[0])
display(hanoi_2.draw('mpl', style="clifford", filename=get_image_path("hanoi_2_discs.png")))
get_unitary(hanoi_2)
test_result(hanoi_2, ['010000', '100000'], filename=get_image_path("result_hanoi_2_discs.png"))
hanoi(3, 0, 1, 2, [])
source = QuantumRegister(2, name="source")
auxiliary = QuantumRegister(2, name="aux")
target = QuantumRegister(2, name="target")
hanoi_3 = QuantumCircuit(source, auxiliary, target)
hanoi_3.append(generate_hanoi_u(n_qubits=2), [*source, *auxiliary, *target])
#(1, 0, 2)
hanoi_3.swap(source[0], target[0])
#(2, 0, 1)
hanoi_3.swap(source[1], auxiliary[1])
#(1, 2, 1)
hanoi_3.swap(target[0], auxiliary[0])
#(3, 0, 2)
hanoi_3.swap(source[0], target[0])
hanoi_3.swap(source[1], target[1])
#(1, 1, 0)
hanoi_3.swap(auxiliary[0], source[0])
#(2, 1, 2)
hanoi_3.swap(auxiliary[1], target[1])
#(1, 0, 2)
hanoi_3.swap(source[0], target[0])
display(hanoi_3.draw('mpl',style="clifford", filename=get_image_path("hanoi_3_discs.png")))
get_unitary(hanoi_3)
test_result(hanoi_3, ['010000', '100000', '110000'], filename=get_image_path("result_hanoi_3_discs.png"))
def auto_hanoi(n, enable_display=True, filename=None):
n_qubits = len(str(bin(n))[2:])
source = QuantumRegister(n_qubits, name="source")
auxiliary = QuantumRegister(n_qubits, name="aux")
target = QuantumRegister(n_qubits, name="target")
qc = QuantumCircuit(source, auxiliary, target)
qc.append(generate_hanoi_u(n_qubits=n_qubits, total_discs=n), [*source, *auxiliary, *target])
steps = hanoi(n, 0, 1, 2, [])
encoded_towers = {
0: source,
1: auxiliary,
2: target
}
for value, from_, to in steps:
binary = f"{value:0{n_qubits}b}"
ones_pos = [ i for i, value in enumerate(binary) if value == '1' ]
tower_from = encoded_towers[from_]
tower_to = encoded_towers[to]
for one_pos in ones_pos:
qc.swap(tower_from[one_pos], tower_to[one_pos])
if(enable_display): display(qc.draw('mpl', style="clifford", filename=filename))
return qc
hanoi_4 = auto_hanoi(4, filename=get_image_path("hanoi_4_discs.png"))
test_result(hanoi_4, ['001000000', '010000000', '011000000', '100000000'],filename=get_image_path("result_hanoi_4_discs.png"))
load_dotenv()
QiskitRuntimeService.save_account(channel="ibm_quantum", token=os.getenv("IBM_TOKEN"), overwrite=True)
service = QiskitRuntimeService()
options = Options(optimization_level=3)
options.execution.shots = 1000
ibm_backend = service.least_busy(operational=True, simulator=False)
display(ibm_backend.status())
print(f'num_qubits: {ibm_backend.num_qubits}')
def get_depth(start=1, end=10, backend=AerSimulator()):
depths = pd.Series(dtype=np.int32)
for n in trange(start, end):
circuit = auto_hanoi(n, enable_display=False)
depths[n] = transpile(circuit, backend=backend).depth()
return depths
start = 1
end = 10
depths = get_depth(start=start, end=end)
washington_depths = get_depth(start=start, end=end, backend=FakeWashington())
ibmq_depths = get_depth(start=start, end=end, backend=ibm_backend)
hanoi_steps = lambda n: len(hanoi(n, 1, 2, 3, []))
vec_hanoi = np.vectorize(hanoi_steps)
range_ = np.arange(start, end)
total_steps = pd.Series(vec_hanoi(range_), index=range_, dtype=np.int32)
df = pd.DataFrame({"aer_depth":depths, "depth_fake_washington":washington_depths, "IBMQ_depth":ibmq_depths, "classical_steps":total_steps}, columns=["aer_depth", "depth_fake_washington", "IBMQ_depth", "classical_steps"])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5), sharey=True)
fig.suptitle('Depths x classical steps comparation')
sns.lineplot(ax=ax1, data=df[["classical_steps", "aer_depth"]], palette="flare")
sns.lineplot(ax=ax2, data=df[["aer_depth", "depth_fake_washington", "IBMQ_depth"]], palette="flare")
plt.savefig(get_image_path("hanoi_depths_comparation.png"))
plt.show()
sampler = IBMSampler(backend=ibm_backend, options=options)
oracle = auto_hanoi(3)
grover = GroverOperator(oracle, insert_barriers=True).decompose()
n_qubits = oracle.num_qubits
grover.name = "Grover"
qc = QuantumCircuit(n_qubits)
qc.h(range(n_qubits))
qc.compose(grover, list(range(n_qubits)), inplace=True)
qc.measure_all()
display(qc.draw('mpl', style="clifford", filename=get_image_path("hanoi_3_discs_ibm_q_test.png")))
job = sampler.run(qc.decompose())
sim = AerSimulator()
result = sim.run(qc.decompose(), shots=1000).result().get_counts()
plot_histogram(result)
job_id = ''
job = service.job(job_id)
plot_distribution(job.result().quasi_dists)
sampler = IBMSampler(backend=ibm_backend, options=options)
test_result(auto_hanoi(3), ['010000', '100000', '110000'], filename=get_image_path("result_hanoi_3_discs_ibm_q.png"), sampler=sampler)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureMoleculeDriver, ElectronicStructureDriverType
molecule = Molecule(
# coordinates are given in Angstrom
geometry=[
["O", [0.0, 0.0, 0.0]],
["H", [0.758602, 0.0, 0.504284]],
["H", [0.758602, 0.0, -0.504284]]
],
multiplicity=1, # = 2*spin + 1
charge=0,
)
driver = ElectronicStructureMoleculeDriver(
molecule=molecule,
basis="sto3g",
driver_type=ElectronicStructureDriverType.PYSCF,
)
properties = driver.run()
print(properties)
print(properties.get_property("ParticleNumber"))
#print(properties.get_property("ElectronicEnergy"))
properties.get_property("ElectronicEnergy").nuclear_repulsion_energy
# WRITE YOUR CODE BETWEEN THESE LINES - START
num_alpha_electrons = 5
num_beta_electrons = 5
num_spin_orbitals = 14
nuclear_rep_energy = properties.get_property("ElectronicEnergy").nuclear_repulsion_energy
# WRITE YOUR CODE BETWEEN THESE LINES - END
from qc_grader.challenges.spring_2022 import grade_ex4a
grade_ex4a(
num_alpha_electrons=num_alpha_electrons,
num_beta_electrons=num_beta_electrons,
num_spin_orbitals=num_spin_orbitals,
nuclear_rep_energy=nuclear_rep_energy
)
from qiskit_nature.transformers.second_quantization.electronic import ActiveSpaceTransformer
# Check the occupation of the spin orbitals
PN_property = properties.get_property("ParticleNumber")
print(PN_property)
# Define the active space around the Fermi level
# (selected automatically around the HOMO and LUMO, ordered by energy)
transformer = ActiveSpaceTransformer(
num_electrons=2, #how many electrons we have in our active space
num_molecular_orbitals=2, #how many orbitals we have in our active space
)
# We can hand-pick the MOs to be included in the AS
# (in case they are not exactly around the Fermi level)
# transformer = ActiveSpaceTransformer(
# num_electrons=2, #how many electrons we have in our active space
# num_molecular_orbitals=2, #how many orbitals we have in our active space
# active_orbitals=[4,7], #We are specifically choosing MO number 4 (occupied with two electrons) and 7 (empty)
# )
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
problem = ElectronicStructureProblem(driver, [transformer])
second_q_ops = problem.second_q_ops() # this calls driver.run() internally
hamiltonian = second_q_ops[0]
print(hamiltonian)
from qiskit_nature.operators.second_quantization import FermionicOp
# WRITE YOUR CODE BETWEEN THESE LINES - START
op = (0.5j* FermionicOp('-_0 +_1')) + (2.0* FermionicOp('-_0 +_2'))
# list of valid tuples to initialize the FermionicOp
list_operator = op.to_list('sparse')
# positive integer that represents the length of registers
num_register_length = 3
list_operator
# WRITE YOUR CODE BETWEEN THESE LINES - END
(FermionicOp('+_1 -_0')).to_list() == (FermionicOp('+_1')@FermionicOp('-_0')).to_list()
(0.5j* FermionicOp("+_1 -_0", 4, "dense")).to_list() == (0.5j* FermionicOp("+_1", 4, "dense")@FermionicOp("-_0", 4, "dense")).to_list()
from qc_grader.challenges.spring_2022 import grade_ex4b
grade_ex4b(list_operator, num_register_length)
from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper
from qiskit_nature.converters.second_quantization import QubitConverter
# Setup the mapper and qubit converter
mapper_type = 'JordanWignerMapper'
if mapper_type == 'ParityMapper':
mapper = ParityMapper()
elif mapper_type == 'JordanWignerMapper':
mapper = JordanWignerMapper()
elif mapper_type == 'BravyiKitaevMapper':
mapper = BravyiKitaevMapper()
converter = QubitConverter(mapper)
qubit_op = converter.convert(hamiltonian)
print(qubit_op)
from qiskit_nature.circuit.library import HartreeFock
particle_number = problem.grouped_property_transformed.get_property("ParticleNumber")
num_spin_orbitals = particle_number.num_spin_orbitals
num_particles = particle_number.num_particles
init_state = HartreeFock(num_spin_orbitals, num_particles, converter)
print(init_state)
from qiskit.circuit.library import TwoLocal
from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD
# Choose the ansatz
ansatz_type = "UCCSD"
# Put arguments for twolocal
if ansatz_type == "TwoLocal":
# Single qubit rotations that are placed on all qubits with independent parameters
rotation_blocks = ['ry', 'rz']
# Entangling gates
entanglement_blocks = 'cz'
# How the qubits are entangled
entanglement = 'full'
# Repetitions of rotation_blocks + entanglement_blocks with independent parameters
repetitions = 1
# Skip the final rotation_blocks layer
skip_final_rotation_layer = True
ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions,
entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer)
# Add the initial state
ansatz.compose(init_state, front=True, inplace=True)
elif ansatz_type == "UCCSD":
ansatz = UCCSD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "PUCCD":
ansatz = PUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "SUCCD":
ansatz = SUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "Custom":
# Example of how to write your own circuit
from qiskit.circuit import Parameter, QuantumCircuit, QuantumRegister
# Define the variational parameter
theta = Parameter('a')
n = qubit_op.num_qubits
# Make an empty quantum circuit
qc = QuantumCircuit(qubit_op.num_qubits)
qubit_label = 0
# Place a Hadamard gate
qc.h(qubit_label)
# Place a CNOT ladder
for i in range(n-1):
qc.cx(i, i+1)
# Visual separator
qc.barrier()
# rz rotations on all qubits
qc.rz(theta, range(n))
ansatz = qc
ansatz.compose(init_state, front=True, inplace=True)
print(ansatz.decompose())
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP
optimizer_type = 'L_BFGS_B'
# You may want to tune the parameters
# of each optimizer, here the defaults are used
if optimizer_type == 'COBYLA':
optimizer = COBYLA(maxiter=500)
elif optimizer_type == 'L_BFGS_B':
optimizer = L_BFGS_B(maxfun=500)
elif optimizer_type == 'SPSA':
optimizer = SPSA(maxiter=500)
elif optimizer_type == 'SLSQP':
optimizer = SLSQP(maxiter=500)
from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
import numpy as np
def exact_diagonalizer(problem, converter):
solver = NumPyMinimumEigensolverFactory()
calc = GroundStateEigensolver(converter, solver)
result = calc.solve(problem)
return result
result_exact = exact_diagonalizer(problem, converter)
exact_energy = np.real(result_exact.eigenenergies[0])
print("Exact electronic energy", exact_energy)
print(result_exact)
# The targeted electronic energy for H2 is -1.85336 Ha
# Check with your VQE result.
from qiskit.algorithms import VQE
from IPython.display import display, clear_output
# Print and save the data in lists
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)
counts = []
values = []
params = []
deviation = []
# Set initial parameters of the ansatz
# We choose a fixed small displacement
# So all participants start from similar starting point
try:
initial_point = [0.01] * len(ansatz.ordered_parameters)
except:
initial_point = [0.01] * ansatz.num_parameters
algorithm = VQE(ansatz,
optimizer=optimizer,
quantum_instance=backend,
callback=callback,
initial_point=initial_point)
result = algorithm.compute_minimum_eigenvalue(qubit_op)
print(result)
# Store results in a dictionary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
# Unroller transpile your circuit into CNOTs and U gates
pass_ = Unroller(['u', 'cx'])
pm = PassManager(pass_)
ansatz_tp = pm.run(ansatz)
cnots = ansatz_tp.count_ops()['cx']
energy = result.optimal_value
if ansatz_type == "TwoLocal":
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': rotation_blocks,
'entanglement_blocks': entanglement_blocks,
'entanglement': entanglement,
'repetitions': repetitions,
'skip_final_rotation_layer': skip_final_rotation_layer,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.cost_function_evals,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots}
else:
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': None,
'entanglement_blocks': None,
'entanglement': None,
'repetitions': None,
'skip_final_rotation_layer': None,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.cost_function_evals,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots}
# Plot the results
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.set_xlabel('Iterations')
ax.set_ylabel('Energy')
ax.grid()
fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}')
plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}")
ax.plot(counts, values)
ax.axhline(exact_energy, linestyle='--')
fig_title = f"\
{result_dict['optimizer']}-\
{result_dict['mapping']}-\
{result_dict['ansatz']}-\
Energy({result_dict['energy (Ha)']:.3f}).png"
fig.savefig(fig_title, dpi=300)
# Display and save the data
import pandas as pd
import os.path
filename = 'results_h2o.csv'
if os.path.isfile(filename):
result_df = pd.read_csv(filename)
result_df = result_df.append([result_dict])
else:
result_df = pd.DataFrame.from_dict([result_dict])
result_df.to_csv(filename)
result_df[['optimizer','ansatz', 'rotation blocks', 'entanglement_blocks',
'entanglement', 'repetitions', '# of qubits', '# of parameters', '# of CNOTs', '# of evaluations', 'error (mHa)']]
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import GroundStateEigensolver, QEOM, VQEUCCFactory
# This first part sets the ground state solver
# see more about this part in the ground state calculation tutorial
quantum_instance = QuantumInstance(Aer.get_backend("aer_simulator_statevector"))
solver = VQEUCCFactory(quantum_instance)
gsc = GroundStateEigensolver(converter, solver)
# The qEOM algorithm is simply instantiated with the chosen ground state solver
qeom_excited_states_calculation = QEOM(gsc, "sd")
qeom_results = qeom_excited_states_calculation.solve(problem)
print(qeom_results)
# WRITE YOUR CODE BETWEEN THESE LINES - START
# WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Provider for a single IBM Quantum Experience account."""
import logging
from typing import Dict, List, Optional, Any, Callable, Union
from collections import OrderedDict
import traceback
import copy
from qiskit.providers import ProviderV1 as Provider # type: ignore[attr-defined]
from qiskit.providers.models import (QasmBackendConfiguration,
PulseBackendConfiguration)
from qiskit.circuit import QuantumCircuit
from qiskit.transpiler import Layout
from qiskit.providers.ibmq.runtime import runtime_job # pylint: disable=unused-import
from qiskit.providers.ibmq import ibmqfactory # pylint: disable=unused-import
from .api.clients import AccountClient
from .ibmqbackend import IBMQBackend, IBMQSimulator
from .credentials import Credentials
from .ibmqbackendservice import IBMQBackendService, IBMQDeprecatedBackendService
from .utils.json_decoder import decode_backend_configuration
from .experiment import IBMExperimentService
from .runtime.ibm_runtime_service import IBMRuntimeService
from .exceptions import IBMQNotAuthorizedError, IBMQInputValueError
from .runner_result import RunnerResult
logger = logging.getLogger(__name__)
class AccountProvider(Provider):
"""Provider for a single IBM Quantum Experience account.
The account provider class provides access to the IBM Quantum Experience
services available to this account.
You can access a provider by enabling an account with the
:meth:`IBMQ.enable_account()<IBMQFactory.enable_account>` method, which
returns the default provider you have access to::
from qiskit import IBMQ
provider = IBMQ.enable_account(<INSERT_IBM_QUANTUM_EXPERIENCE_TOKEN>)
To select a different provider, use the
:meth:`IBMQ.get_provider()<IBMQFactory.get_provider>` method and specify the hub,
group, or project name of the desired provider.
Each provider may offer different services. The main service,
:class:`~qiskit.providers.ibmq.ibmqbackendservice.IBMQBackendService`, is
available to all providers and gives access to IBM Quantum Experience
devices and simulators.
You can obtain an instance of a service using the :meth:`service()` method
or as an attribute of this ``AccountProvider`` instance. For example::
backend_service = provider.service('backend')
backend_service = provider.service.backend
Since :class:`~qiskit.providers.ibmq.ibmqbackendservice.IBMQBackendService`
is the main service, some of the backend-related methods are available
through this class for convenience.
The :meth:`backends()` method returns all the backends available to this account::
backends = provider.backends()
The :meth:`get_backend()` method returns a backend that matches the filters
passed as argument. An example of retrieving a backend that matches a
specified name::
simulator_backend = provider.get_backend('ibmq_qasm_simulator')
It is also possible to use the ``backend`` attribute to reference a backend.
As an example, to retrieve the same backend from the example above::
simulator_backend = provider.backend.ibmq_qasm_simulator
Note:
The ``backend`` attribute can be used to autocomplete the names of
backends available to this provider. To autocomplete, press ``tab``
after ``provider.backend.``. This feature may not be available
if an error occurs during backend discovery. Also note that
this feature is only available in interactive sessions, such as
in Jupyter Notebook and the Python interpreter.
"""
def __init__(self, credentials: Credentials, factory: 'ibmqfactory.IBMQFactory') -> None:
"""AccountProvider constructor.
Args:
credentials: IBM Quantum Experience credentials.
factory: IBM Quantum account.
"""
super().__init__()
self.credentials = credentials
self._factory = factory
self._api_client = AccountClient(credentials,
**credentials.connection_parameters())
# Initialize the internal list of backends.
self.__backends: Dict[str, IBMQBackend] = {}
self._backend = IBMQBackendService(self)
self.backends = IBMQDeprecatedBackendService(self.backend) # type: ignore[assignment]
# Initialize other services.
self._experiment = IBMExperimentService(self) if credentials.experiment_url else None
self._runtime = IBMRuntimeService(self) \
if credentials.runtime_url else None
self._services = {'backend': self._backend,
'experiment': self._experiment,
'runtime': self._runtime}
@property
def _backends(self) -> Dict[str, IBMQBackend]:
"""Gets the backends for the provider, if not loaded.
Returns:
Dict[str, IBMQBackend]: the backends
"""
if not self.__backends:
self.__backends = self._discover_remote_backends()
return self.__backends
@_backends.setter
def _backends(self, value: Dict[str, IBMQBackend]) -> None:
"""Sets the value for the account's backends.
Args:
value: the backends
"""
self.__backends = value
def backends(
self,
name: Optional[str] = None,
filters: Optional[Callable[[List[IBMQBackend]], bool]] = None,
**kwargs: Any
) -> List[IBMQBackend]:
"""Return all backends accessible via this provider, subject to optional filtering.
Args:
name: Backend name to filter by.
filters: More complex filters, such as lambda functions.
For example::
AccountProvider.backends(filters=lambda b: b.configuration().n_qubits > 5)
kwargs: Simple filters that specify a ``True``/``False`` criteria in the
backend configuration, backends status, or provider credentials.
An example to get the operational backends with 5 qubits::
AccountProvider.backends(n_qubits=5, operational=True)
Returns:
The list of available backends that match the filter.
"""
# pylint: disable=method-hidden
# pylint: disable=arguments-differ
# This method is only for faking the subclassing of `BaseProvider`, as
# `.backends()` is an abstract method. Upon initialization, it is
# replaced by a `IBMQBackendService` instance.
pass
def _discover_remote_backends(self, timeout: Optional[float] = None) -> Dict[str, IBMQBackend]:
"""Return the remote backends available for this provider.
Args:
timeout: Maximum number of seconds to wait for the discovery of
remote backends.
Returns:
A dict of the remote backend instances, keyed by backend name.
"""
ret = OrderedDict() # type: ignore[var-annotated]
configs_list = self._api_client.list_backends(timeout=timeout)
for raw_config in configs_list:
# Make sure the raw_config is of proper type
if not isinstance(raw_config, dict):
logger.warning("An error occurred when retrieving backend "
"information. Some backends might not be available.")
continue
try:
decode_backend_configuration(raw_config)
try:
config = PulseBackendConfiguration.from_dict(raw_config)
except (KeyError, TypeError):
config = QasmBackendConfiguration.from_dict(raw_config)
backend_cls = IBMQSimulator if config.simulator else IBMQBackend
ret[config.backend_name] = backend_cls(
configuration=config,
provider=self,
credentials=self.credentials,
api_client=self._api_client)
except Exception: # pylint: disable=broad-except
logger.warning(
'Remote backend "%s" for provider %s could not be instantiated due to an '
'invalid config: %s',
raw_config.get('backend_name', raw_config.get('name', 'unknown')),
repr(self), traceback.format_exc())
return ret
def run_circuits(
self,
circuits: Union[QuantumCircuit, List[QuantumCircuit]],
backend_name: str,
shots: Optional[int] = None,
initial_layout: Optional[Union[Layout, Dict, List]] = None,
layout_method: Optional[str] = None,
routing_method: Optional[str] = None,
translation_method: Optional[str] = None,
seed_transpiler: Optional[int] = None,
optimization_level: int = 1,
init_qubits: bool = True,
rep_delay: Optional[float] = None,
transpiler_options: Optional[dict] = None,
measurement_error_mitigation: bool = False,
use_measure_esp: Optional[bool] = None,
**run_config: Dict
) -> 'runtime_job.RuntimeJob':
"""Execute the input circuit(s) on a backend using the runtime service.
Note:
This method uses the IBM Quantum runtime service which is not
available to all accounts.
Args:
circuits: Circuit(s) to execute.
backend_name: Name of the backend to execute circuits on.
Transpiler options are automatically grabbed from backend configuration
and properties unless otherwise specified.
shots: Number of repetitions of each circuit, for sampling. If not specified,
the backend default is used.
initial_layout: Initial position of virtual qubits on physical qubits.
layout_method: Name of layout selection pass ('trivial', 'dense',
'noise_adaptive', 'sabre').
Sometimes a perfect layout can be available in which case the layout_method
may not run.
routing_method: Name of routing pass ('basic', 'lookahead', 'stochastic', 'sabre')
translation_method: Name of translation pass ('unroller', 'translator', 'synthesis')
seed_transpiler: Sets random seed for the stochastic parts of the transpiler.
optimization_level: How much optimization to perform on the circuits.
Higher levels generate more optimized circuits, at the expense of longer
transpilation time.
If None, level 1 will be chosen as default.
init_qubits: Whether to reset the qubits to the ground state for each shot.
rep_delay: Delay between programs in seconds. Only supported on certain
backends (``backend.configuration().dynamic_reprate_enabled`` ). If supported,
``rep_delay`` will be used instead of ``rep_time`` and must be from the
range supplied by the backend (``backend.configuration().rep_delay_range``).
Default is given by ``backend.configuration().default_rep_delay``.
transpiler_options: Additional transpiler options.
measurement_error_mitigation: Whether to apply measurement error mitigation.
use_measure_esp: Whether to use excited state promoted (ESP) readout for measurements
which are the final instruction on a qubit. ESP readout can offer higher fidelity
than standard measurement sequences. See
`here <https://arxiv.org/pdf/2008.08571.pdf>`_.
**run_config: Extra arguments used to configure the circuit execution.
Returns:
Runtime job.
"""
inputs = copy.deepcopy(run_config) # type: Dict[str, Any]
inputs['circuits'] = circuits
inputs['optimization_level'] = optimization_level
inputs['init_qubits'] = init_qubits
inputs['measurement_error_mitigation'] = measurement_error_mitigation
if shots:
inputs['shots'] = shots
if initial_layout:
inputs['initial_layout'] = initial_layout
if layout_method:
inputs['layout_method'] = layout_method
if routing_method:
inputs['routing_method'] = routing_method
if translation_method:
inputs['translation_method'] = translation_method
if seed_transpiler:
inputs['seed_transpiler'] = seed_transpiler
if rep_delay:
inputs['rep_delay'] = rep_delay
if transpiler_options:
inputs['transpiler_options'] = transpiler_options
if use_measure_esp is not None:
inputs['use_measure_esp'] = use_measure_esp
options = {'backend_name': backend_name}
return self.runtime.run('circuit-runner', options=options, inputs=inputs,
result_decoder=RunnerResult)
def service(self, name: str) -> Any:
"""Return the specified service.
Args:
name: Name of the service.
Returns:
The specified service.
Raises:
IBMQInputValueError: If an unknown service name is specified.
IBMQNotAuthorizedError: If the account is not authorized to use
the service.
"""
if name not in self._services:
raise IBMQInputValueError(f"Unknown service {name} specified.")
if self._services[name] is None:
raise IBMQNotAuthorizedError("You are not authorized to use this service.")
return self._services[name]
def services(self) -> Dict:
"""Return all available services.
Returns:
All services available to this provider.
"""
return {key: val for key, val in self._services.items() if val is not None}
def has_service(self, name: str) -> bool:
"""Check if this provider has access to the service.
Args:
name: Name of the service.
Returns:
Whether the provider has access to the service.
Raises:
IBMQInputValueError: If an unknown service name is specified.
"""
if name not in self._services:
raise IBMQInputValueError(f"Unknown service {name} specified.")
if self._services[name] is None:
return False
return True
@property
def backend(self) -> IBMQBackendService:
"""Return the backend service.
Returns:
The backend service instance.
"""
return self._backend
@property
def experiment(self) -> IBMExperimentService:
"""Return the experiment service.
Returns:
The experiment service instance.
Raises:
IBMQNotAuthorizedError: If the account is not authorized to use
the experiment service.
"""
if self._experiment:
return self._experiment
else:
raise IBMQNotAuthorizedError("You are not authorized to use the experiment service.")
@property
def runtime(self) -> IBMRuntimeService:
"""Return the runtime service.
Returns:
The runtime service instance.
Raises:
IBMQNotAuthorizedError: If the account is not authorized to use the service.
"""
if self._runtime:
return self._runtime
else:
raise IBMQNotAuthorizedError("You are not authorized to use the runtime service.")
def __eq__(
self,
other: Any
) -> bool:
if not isinstance(other, AccountProvider):
return False
return self.credentials == other.credentials
def __repr__(self) -> str:
credentials_info = "hub='{}', group='{}', project='{}'".format(
self.credentials.hub, self.credentials.group, self.credentials.project)
return "<{} for IBMQ({})>".format(
self.__class__.__name__, credentials_info)
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import plot, draw, show
import os, shutil
from qiskit import BasicAer, IBMQ, QuantumCircuit, ClassicalRegister,\
QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.transpiler import CouplingMap
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
LaTex_folder_Deutsch_Josza = str(os.getcwd())+'/Latex_quantum_gates/Deutsch_Josza_algorithm/'
if not os.path.exists(LaTex_folder_Deutsch_Josza):
os.makedirs(LaTex_folder_Deutsch_Josza)
else:
shutil.rmtree(LaTex_folder_Deutsch_Josza)
os.makedirs(LaTex_folder_Deutsch_Josza)
n = 4 # number of qubits in state |0>
# Choose a type of oracle at random.
# With probability one-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("Oracle is constant with value = ", oracleValue)
else:
print("Oracle is balanced ")
# this is a hidden parameter for balanced oracles
a = np.random.randint(1,2**n)
# Creating registers
# n qubits for querying the oracle and one qubit forstoring the answer
qr = QuantumRegister(n+1, 'q') #all qubits are initialised to |0>
# for recording the measurement on the first register
cr = ClassicalRegister(n, 'c')
circuitName = "DeutschJosza"
djCircuit = QuantumCircuit(qr, cr)
# Create the superposition of all input queries in the first register
# by applying the Hadamard gate to each qubit.
for qubit in qr[0:-2]:
djCircuit.h(qubit)
# Flip the second register and apply the Hadamard gate
djCircuit.x(qr[n])
djCircuit.h(qr[n])
# Apply the barrier to mark the beginning of the oracle
djCircuit.barrier()
if oracleType == 0:#If the oracleType is "0", the oracle returns oracleValue
#for all inputs
if oracleValue == 1:
djCircuit.x(qr[n])
else:
djCircuit.id(qr[n])
else: #otherwise, it returns the inner product of the input with
#a (non-zero) bitstring
for i, qubit in enumerate(qr[0:-2]):
if(a & (1 << i)):
djCircuit.cx(qubit, qr[n])
# Apply barrier to mark the end of the oracle
djCircuit.barrier()
# Apply Hadamard gates after querying the oracle
for qubit in qr[0:-2]:
djCircuit.h(qubit)
# Measurement
djCircuit.barrier()
for i in range(n):
djCircuit.measure(qr[i], cr[i])
# create a LaTex file for the algorithm
LaTex_code = djCircuit.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'Deutsch_Josza_algorithm.tex'
with open(LaTex_folder_Deutsch_Josza+f_name, 'w') as f:
f.write(LaTex_code)
## execute on a simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
job = execute(djCircuit, backend=backend, shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
draw()
show(block=True)
## execute on a real device
provider = IBMQ.load_account()
for backend in IBMQ.providers()[0].backends():
print(backend.name(),)
backend = provider.backend.ibmq_lima
djCompiled = transpile(djCircuit, backend=backend, optimization_level=1)
djCompiled.draw(output='mpl', scale=0.5)
draw()
show(block=True)
print("This step might take some time!!!")
job = execute(djCompiled, backend=backend, shots=shots)
job_monitor(job)
results = job.result()
answer = results.get_counts()
threshold = int(0.01 *shots) # the threshld of plotting significant measurements
# filter the answer for better view of plots
filteredAnswer = {k: v for k,v in answer.items() if v>= threshold}
# number of counts removed
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold])
# the removed counts are assigned to a new index
filteredAnswer['other_bitstrings'] = removedCounts
plot_histogram(filteredAnswer)
draw()
show(block=True)
# Quantum computers have noise so they would not produce discrete outputs
# like simulators - that only demonstrates the superiority
# of quantum over classical
print(filteredAnswer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(0, 0)
qc.draw(output='mpl')
from qiskit import QuantumRegister, ClassicalRegister
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
qc = QuantumCircuit(q, c)
qc.h([0, 1, 2])
qc.barrier()
qc.measure(q, c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw(output='mpl')
nq = 2
m = 2
q = QuantumRegister(nq, 'q')
c = ClassicalRegister(m, 'c')
qc_S = QuantumCircuit(q,c)
qc_S.h(0)
qc_S.x(1)
qc_S.draw('mpl')
from math import pi
cu_circ = QuantumCircuit(2)
cu_circ.cp(pi/2, 0, 1)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc_S.cp(pi/2, 0, 1)
qc_S.draw('mpl')
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, q[0], c[0])
qc_S.draw('mpl')
qc_S.reset(0)
qc_S.h(0)
qc_S.draw('mpl')
qc_S.p(-pi/2, 0).c_if(c, 1)
qc_S.draw('mpl')
## 2^t c-U operations (with t=m-2)
for _ in range(2 ** (m - 2)):
qc_S.cp(pi/2, 0, 1)
x_measurement(qc_S, q[0], c[1])
qc_S.draw('mpl')
import matplotlib.pyplot as plt
from qiskit.tools.visualization import plot_histogram
from qiskit_aer.primitives import Sampler
sampler = Sampler()
job = sampler.run(qc_S)
result = job.result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
nq = 3 # number of qubits
m = 3 # number of classical bits
q = QuantumRegister(nq,'q')
c = ClassicalRegister(m,'c')
qc = QuantumCircuit(q,c)
qc.h(0)
qc.x([1, 2])
qc.draw('mpl')
cu_circ = QuantumCircuit(nq)
cu_circ.mcp(pi/4, [0, 1], 2)
cu_circ.draw('mpl')
for _ in range(2 ** (m - 1)):
qc.mcp(pi/4, [0, 1], 2)
qc.draw('mpl')
x_measurement(qc, q[0], c[0])
qc.draw('mpl')
qc.reset(0)
qc.h(0)
qc.draw('mpl')
qc.p(-pi/2, 0).c_if(c, 1)
qc.draw('mpl')
for _ in range(2 ** (m - 2)):
qc.mcp(pi/4, [0, 1], 2)
x_measurement(qc, q[0], c[1])
qc.draw('mpl')
# initialization of qubit q0
qc.reset(0)
qc.h(0)
# phase correction
qc.p(-pi/4, 0).c_if(c, 1)
qc.p(-pi/2, 0).c_if(c, 2)
qc.p(-3*pi/2, 0).c_if(c, 3)
# c-U operations
for _ in range(2 ** (m - 3)):
qc.mcp(pi/4, [0, 1], 2)
# X measurement
qc.h(0)
qc.measure(0, 2)
qc.draw('mpl')
result = sampler.run(qc).result()
dist0 = result.quasi_dists[0]
key_new = [str(key/2**m) for key in list(dist0.keys())]
dist1 = dict(zip(key_new, dist0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(dist0, ax=ax[0])
plot_histogram(dist1, ax=ax[1])
plt.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.