repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """A test for visualizing device coupling maps""" import unittest from io import BytesIO from ddt import ddt, data from qiskit.providers.fake_provider import ( FakeProvider, FakeKolkata, FakeWashington, FakeKolkataV2, FakeWashingtonV2, ) from qiskit.visualization import ( plot_gate_map, plot_coupling_map, plot_circuit_layout, plot_error_map, ) from qiskit.utils import optionals from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler.layout import Layout, TranspileLayout from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase if optionals.HAS_MATPLOTLIB: import matplotlib.pyplot as plt if optionals.HAS_PIL: from PIL import Image @ddt @unittest.skipUnless(optionals.HAS_MATPLOTLIB, "matplotlib not available.") @unittest.skipUnless(optionals.HAS_PIL, "PIL not available") @unittest.skipUnless(optionals.HAS_SEABORN, "seaborn not available") class TestGateMap(QiskitVisualizationTestCase): """visual tests for plot_gate_map""" backends = list( filter( lambda x: not x.configuration().simulator and x.configuration().num_qubits in range(5, 21), FakeProvider().backends(), ) ) @data(*backends) def test_plot_gate_map(self, backend): """tests plotting of gate map of a device (20 qubit, 16 qubit, 14 qubit and 5 qubit)""" n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png") fig = plot_gate_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) @data(*backends) def test_plot_circuit_layout(self, backend): """tests plot_circuit_layout for each device""" layout_length = int(backend._configuration.n_qubits / 2) qr = QuantumRegister(layout_length, "qr") circuit = QuantumCircuit(qr) circuit._layout = TranspileLayout( Layout({qr[i]: i * 2 for i in range(layout_length)}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) circuit._layout.initial_layout.add_register(qr) n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "_plot_circuit_layout.png") fig = plot_circuit_layout(circuit, backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.1) plt.close(fig) def test_plot_gate_map_no_backend(self): """tests plotting of gate map without a device""" n_qubits = 8 coupling_map = [[0, 1], [1, 2], [2, 3], [3, 5], [4, 5], [5, 6], [2, 4], [6, 7]] qubit_coordinates = [[0, 1], [1, 1], [1, 0], [1, 2], [2, 0], [2, 2], [2, 1], [3, 1]] img_ref = path_to_diagram_reference(str(n_qubits) + "qubits.png") fig = plot_coupling_map( num_qubits=n_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map ) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_backend_v1(self): """Test plotting error map with fake backend v1.""" backend = FakeKolkata() img_ref = path_to_diagram_reference("kolkata_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_backend_v2(self): """Test plotting error map with fake backend v2.""" backend = FakeKolkataV2() img_ref = path_to_diagram_reference("kolkata_v2_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_over_100_qubit(self): """Test plotting error map with large fake backend.""" backend = FakeWashington() img_ref = path_to_diagram_reference("washington_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) def test_plot_error_map_over_100_qubit_backend_v2(self): """Test plotting error map with large fake backendv2.""" backend = FakeWashingtonV2() img_ref = path_to_diagram_reference("washington_v2_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) self.assertImagesAreEqual(Image.open(img_buffer), img_ref, 0.2) plt.close(fig) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for pass manager visualization tool.""" import unittest import os from qiskit.transpiler import CouplingMap, Layout from qiskit.transpiler.passmanager import PassManager from qiskit import QuantumRegister from qiskit.transpiler.passes import GateDirection, Unroller from qiskit.transpiler.passes import CheckMap from qiskit.transpiler.passes import SetLayout from qiskit.transpiler.passes import TrivialLayout from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import RemoveResetInZeroState from qiskit.utils import optionals from .visualization import QiskitVisualizationTestCase, path_to_diagram_reference @unittest.skipUnless(optionals.HAS_GRAPHVIZ, "Graphviz not installed.") @unittest.skipUnless(optionals.HAS_PYDOT, "pydot not installed") @unittest.skipUnless(optionals.HAS_PIL, "Pillow not installed") class TestPassManagerDrawer(QiskitVisualizationTestCase): """Qiskit pass manager drawer tests.""" def setUp(self): super().setUp() coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] coupling_map = CouplingMap(couplinglist=coupling) basis_gates = ["u1", "u3", "u2", "cx"] qr = QuantumRegister(7, "q") layout = Layout({qr[i]: i for i in range(coupling_map.size())}) # Create a pass manager with a variety of passes and flow control structures self.pass_manager = PassManager() self.pass_manager.append(SetLayout(layout)) self.pass_manager.append(TrivialLayout(coupling_map), condition=lambda x: True) self.pass_manager.append(FullAncillaAllocation(coupling_map)) self.pass_manager.append(EnlargeWithAncilla()) self.pass_manager.append(Unroller(basis_gates)) self.pass_manager.append(CheckMap(coupling_map)) self.pass_manager.append(BarrierBeforeFinalMeasurements(), do_while=lambda x: False) self.pass_manager.append(GateDirection(coupling_map)) self.pass_manager.append(RemoveResetInZeroState()) def test_pass_manager_drawer_basic(self): """Test to see if the drawer draws a normal pass manager correctly""" filename = "current_standard.dot" self.pass_manager.draw(filename=filename, raw=True) try: self.assertFilesAreEqual( filename, path_to_diagram_reference("pass_manager_standard.dot") ) finally: os.remove(filename) def test_pass_manager_drawer_style(self): """Test to see if the colours are updated when provided by the user""" # set colours for some passes, but leave others to take the default values style = { SetLayout: "cyan", CheckMap: "green", EnlargeWithAncilla: "pink", RemoveResetInZeroState: "grey", } filename = "current_style.dot" self.pass_manager.draw(filename=filename, style=style, raw=True) try: self.assertFilesAreEqual(filename, path_to_diagram_reference("pass_manager_style.dot")) finally: os.remove(filename) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for visualization tools.""" import unittest import numpy as np from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.circuit import Qubit, Clbit from qiskit.visualization.circuit import _utils from qiskit.visualization import array_to_latex from qiskit.test import QiskitTestCase from qiskit.utils import optionals class TestVisualizationUtils(QiskitTestCase): """Tests for circuit drawer utilities.""" def setUp(self): super().setUp() self.qr1 = QuantumRegister(2, "qr1") self.qr2 = QuantumRegister(2, "qr2") self.cr1 = ClassicalRegister(2, "cr1") self.cr2 = ClassicalRegister(2, "cr2") self.circuit = QuantumCircuit(self.qr1, self.qr2, self.cr1, self.cr2) self.circuit.cx(self.qr2[0], self.qr2[1]) self.circuit.measure(self.qr2[0], self.cr2[0]) self.circuit.cx(self.qr2[1], self.qr2[0]) self.circuit.measure(self.qr2[1], self.cr2[1]) self.circuit.cx(self.qr1[0], self.qr1[1]) self.circuit.measure(self.qr1[0], self.cr1[0]) self.circuit.cx(self.qr1[1], self.qr1[0]) self.circuit.measure(self.qr1[1], self.cr1[1]) def test_get_layered_instructions(self): """_get_layered_instructions without reverse_bits""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions(self.circuit) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],))], [("cx", (self.qr2[1], self.qr2[0]), ()), ("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr1[0], self.qr1[1], self.qr2[0], self.qr2[1]], qregs) self.assertEqual([self.cr1[0], self.cr1[1], self.cr2[0], self.cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_reverse_bits(self): """_get_layered_instructions with reverse_bits=True""" (qregs, cregs, layered_ops) = _utils._get_layered_instructions( self.circuit, reverse_bits=True ) exp = [ [("cx", (self.qr2[0], self.qr2[1]), ()), ("cx", (self.qr1[0], self.qr1[1]), ())], [("measure", (self.qr2[0],), (self.cr2[0],))], [("measure", (self.qr1[0],), (self.cr1[0],)), ("cx", (self.qr2[1], self.qr2[0]), ())], [("cx", (self.qr1[1], self.qr1[0]), ())], [("measure", (self.qr2[1],), (self.cr2[1],))], [("measure", (self.qr1[1],), (self.cr1[1],))], ] self.assertEqual([self.qr2[1], self.qr2[0], self.qr1[1], self.qr1[0]], qregs) self.assertEqual([self.cr2[1], self.cr2[0], self.cr1[1], self.cr1[0]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_remove_idle_wires(self): """_get_layered_instructions with idle_wires=False""" qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(3, "qr2") cr1 = ClassicalRegister(3, "cr1") cr2 = ClassicalRegister(3, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.cx(qr2[0], qr2[1]) circuit.measure(qr2[0], cr2[0]) circuit.cx(qr2[1], qr2[0]) circuit.measure(qr2[1], cr2[1]) circuit.cx(qr1[0], qr1[1]) circuit.measure(qr1[0], cr1[0]) circuit.cx(qr1[1], qr1[0]) circuit.measure(qr1[1], cr1[1]) (qregs, cregs, layered_ops) = _utils._get_layered_instructions(circuit, idle_wires=False) exp = [ [("cx", (qr2[0], qr2[1]), ()), ("cx", (qr1[0], qr1[1]), ())], [("measure", (qr2[0],), (cr2[0],))], [("measure", (qr1[0],), (cr1[0],))], [("cx", (qr2[1], qr2[0]), ()), ("cx", (qr1[1], qr1[0]), ())], [("measure", (qr2[1],), (cr2[1],))], [("measure", (qr1[1],), (cr1[1],))], ] self.assertEqual([qr1[0], qr1[1], qr2[0], qr2[1]], qregs) self.assertEqual([cr1[0], cr1[1], cr2[0], cr2[1]], cregs) self.assertEqual( exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_simple(self): """Test _get_layered_instructions left justification simple since #2802 q_0: |0>───────■── ┌───┐ │ q_1: |0>┤ H ├──┼── ├───┤ │ q_2: |0>┤ H ├──┼── └───┘┌─┴─┐ q_3: |0>─────┤ X ├ └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_simple(self): """Test _get_layered_instructions right justification simple since #2802 q_0: |0>──■─────── │ ┌───┐ q_1: |0>──┼──┤ H ├ │ ├───┤ q_2: |0>──┼──┤ H ├ ┌─┴─┐└───┘ q_3: |0>┤ X ├───── └───┘ """ qc = QuantumCircuit(4) qc.h(1) qc.h(2) qc.cx(0, 3) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [("cx", (Qubit(QuantumRegister(4, "q"), 0), Qubit(QuantumRegister(4, "q"), 3)), ())], [ ("h", (Qubit(QuantumRegister(4, "q"), 1),), ()), ("h", (Qubit(QuantumRegister(4, "q"), 2),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_left_justification_less_simple(self): """Test _get_layered_instructions left justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐ ┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘└────────────┘ ║ └────────────┘ q_2: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_3: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ q_4: |0>────────────────────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="left") l_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("u2", (Qubit(QuantumRegister(5, "q"), 1),), ())], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [("u2", (Qubit(QuantumRegister(5, "q"), 0),), ())], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( l_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_right_justification_less_simple(self): """Test _get_layered_instructions right justification less simple example since #2802 ┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐ q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├ ├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤ q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├ └────────────┘ └────────────┘ ║ └────────────┘ └────────────┘ q_2: |0>──────────────────────────────────╫────────────────────────────────── ║ q_3: |0>──────────────────────────────────╫────────────────────────────────── ║ q_4: |0>──────────────────────────────────╫────────────────────────────────── ║ c1_0: 0 ══════════════════════════════════╩══════════════════════════════════ """ qasm = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[5]; creg c1[1]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; u2(0,3.14159265358979) q[1]; measure q[0] -> c1[0]; u2(0,3.14159265358979) q[0]; cx q[1],q[0]; u2(0,3.14159265358979) q[0]; u2(0,3.14159265358979) q[1]; """ qc = QuantumCircuit.from_qasm_str(qasm) (_, _, layered_ops) = _utils._get_layered_instructions(qc, justify="right") r_exp = [ [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [ ( "measure", (Qubit(QuantumRegister(5, "q"), 0),), (Clbit(ClassicalRegister(1, "c1"), 0),), ) ], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], [("cx", (Qubit(QuantumRegister(5, "q"), 1), Qubit(QuantumRegister(5, "q"), 0)), ())], [ ("u2", (Qubit(QuantumRegister(5, "q"), 0),), ()), ("u2", (Qubit(QuantumRegister(5, "q"), 1),), ()), ], ] self.assertEqual( r_exp, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) def test_get_layered_instructions_op_with_cargs(self): """Test _get_layered_instructions op with cargs right of measure ┌───┐┌─┐ q_0: |0>┤ H ├┤M├───────────── └───┘└╥┘┌───────────┐ q_1: |0>──────╫─┤0 ├ ║ │ add_circ │ c_0: 0 ══════╩═╡0 ╞ └───────────┘ c_1: 0 ═════════════════════ """ qc = QuantumCircuit(2, 2) qc.h(0) qc.measure(0, 0) qc_2 = QuantumCircuit(1, 1, name="add_circ") qc_2.h(0).c_if(qc_2.cregs[0], 1) qc_2.measure(0, 0) qc.append(qc_2, [1], [0]) (_, _, layered_ops) = _utils._get_layered_instructions(qc) expected = [ [("h", (Qubit(QuantumRegister(2, "q"), 0),), ())], [ ( "measure", (Qubit(QuantumRegister(2, "q"), 0),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], [ ( "add_circ", (Qubit(QuantumRegister(2, "q"), 1),), (Clbit(ClassicalRegister(2, "c"), 0),), ) ], ] self.assertEqual( expected, [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops] ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode(self): """Test generate latex label default.""" self.assertEqual("abc", _utils.generate_latex_label("abc")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_nomathmode_utf8char(self): """Test generate latex label utf8 characters.""" self.assertEqual( "{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_utf8char(self): """Test generate latex label mathtext with utf8.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc_$∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_mathmode_underscore_outside(self): """Test generate latex label with underscore outside mathmode.""" self.assertEqual( "abc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label("$abc$_∭X∀Y"), ) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_signs(self): """Test generate latex label with escaped dollarsign.""" self.assertEqual("${\\ensuremath{\\forall}}$", _utils.generate_latex_label(r"\$∀\$")) @unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc") def test_generate_latex_label_escaped_dollar_sign_in_mathmode(self): """Test generate latex label with escaped dollar sign in mathmode.""" self.assertEqual( "a$bc_{\\ensuremath{\\iiint}}X{\\ensuremath{\\forall}}Y", _utils.generate_latex_label(r"$a$bc$_∭X∀Y"), ) def test_array_to_latex(self): """Test array_to_latex produces correct latex string""" matrix = [ [np.sqrt(1 / 2), 1 / 16, 1 / np.sqrt(8) + 3j, -0.5 + 0.5j], [1 / 3 - 1 / 3j, np.sqrt(1 / 2) * 1j, 34.3210, -9 / 2], ] matrix = np.array(matrix) exp_str = ( "\\begin{bmatrix}\\frac{\\sqrt{2}}{2}&\\frac{1}{16}&" "\\frac{\\sqrt{2}}{4}+3i&-\\frac{1}{2}+\\frac{i}{2}\\\\" "\\frac{1}{3}+\\frac{i}{3}&\\frac{\\sqrt{2}i}{2}&34.321&-" "\\frac{9}{2}\\\\\\end{bmatrix}" ) result = array_to_latex(matrix, source=True).replace(" ", "").replace("\n", "") self.assertEqual(exp_str, result) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for core modules of timeline drawer.""" from qiskit import QuantumCircuit, transpile from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import core, stylesheet, generators, layouts class TestCanvas(QiskitTestCase): """Test for canvas.""" def setUp(self): super().setUp() self.style = stylesheet.QiskitTimelineStyle() circ = QuantumCircuit(4) circ.h(0) circ.barrier() circ.cx(0, 2) circ.cx(1, 3) self.circ = transpile( circ, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)], optimization_level=0, ) def test_time_range(self): """Test calculating time range.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1} canvas.time_range = (0, 100) ref_range = [-10.0, 110.0] self.assertListEqual(list(canvas.time_range), ref_range) def test_load_program(self): """Test loading program.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 8) ref_coord = { self.circ.qregs[0][0]: -1.0, self.circ.qregs[0][1]: -2.0, self.circ.qregs[0][2]: -3.0, self.circ.qregs[0][3]: -4.0, } self.assertDictEqual(canvas.assigned_coordinates, ref_coord) def test_gate_link_overlap(self): """Test shifting gate link overlap.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update( { "margin.link_interval_percent": 0.01, "margin.left_percent": 0, "margin.right_percent": 0, } ) canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 2) self.assertListEqual(drawings_tested[0][1].xvals, [706.0]) self.assertListEqual(drawings_tested[1][1].xvals, [694.0]) ref_keys = list(canvas._collections.keys()) self.assertEqual(drawings_tested[0][0], ref_keys[0]) self.assertEqual(drawings_tested[1][0], ref_keys[1]) def test_object_outside_xlimit(self): """Test eliminating drawings outside the horizontal limit.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [generators.gen_bit_name, generators.gen_timeslot], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.set_time_range(t_start=400, t_end=600) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 12) def test_non_transpiled_delay_circuit(self): """Test non-transpiled circuit containing instruction which is trivial on duration.""" circ = QuantumCircuit(1) circ.delay(10, 0) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } with self.assertWarns(DeprecationWarning): canvas.load_program(circ) self.assertEqual(len(canvas._collections), 1) def test_multi_measurement_with_clbit_not_shown(self): """Test generating bit link drawings of measurements when clbits is disabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": False}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 0) def test_multi_measurement_with_clbit_shown(self): """Test generating bit link drawings of measurements when clbits is enabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": True}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 2)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for drawing of timeline drawer.""" import numpy as np import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import drawings, types class TestDrawingObjects(QiskitTestCase): """Tests for drawings.""" def setUp(self) -> None: """Setup.""" super().setUp() # bits self.qubits = list(qiskit.QuantumRegister(2)) # metadata self.meta1 = {"val1": 0, "val2": 1} self.meta2 = {"val1": 2, "val2": 3} # style data self.style1 = {"property1": 0, "property2": 1} self.style2 = {"property1": 2, "property2": 3} def test_line_data_equivalent(self): """Test LineData equivalent check.""" xs = list(np.arange(10)) ys = list(np.ones(10)) obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_line_data_equivalent_abstract_coord(self): """Test LineData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent(self): """Test BoxData equivalent check.""" xs = [0, 1] ys = [0, 1] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent_abstract_coord(self): """Test BoxData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent(self): """Test TextData equivalent check.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent_abstract_coord(self): """Test TextData equivalent check with abstract coordinate.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent(self): """Test BitLinkData equivalent check.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1 ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2 ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent_abstract_coord(self): """Test BitLinkData equivalent check with abstract coordinate.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style1, ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style2, ) self.assertEqual(obj1, obj2)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for core modules of pulse drawer.""" from qiskit import pulse, circuit from qiskit.test import QiskitTestCase from qiskit.visualization.pulse_v2 import events class TestChannelEvents(QiskitTestCase): """Tests for ChannelEvents.""" def test_parse_program(self): """Test typical pulse program.""" test_pulse = pulse.Gaussian(10, 0.1, 3) sched = pulse.Schedule() sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0))) sched = sched.insert(0, pulse.Play(test_pulse, pulse.DriveChannel(0))) sched = sched.insert(10, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))) sched = sched.insert(10, pulse.Play(test_pulse, pulse.DriveChannel(0))) ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0)) # check waveform data waveforms = list(ch_events.get_waveforms()) inst_data0 = waveforms[0] self.assertEqual(inst_data0.t0, 0) self.assertEqual(inst_data0.frame.phase, 3.14) self.assertEqual(inst_data0.frame.freq, 0) self.assertEqual(inst_data0.inst, pulse.Play(test_pulse, pulse.DriveChannel(0))) inst_data1 = waveforms[1] self.assertEqual(inst_data1.t0, 10) self.assertEqual(inst_data1.frame.phase, 1.57) self.assertEqual(inst_data1.frame.freq, 0) self.assertEqual(inst_data1.inst, pulse.Play(test_pulse, pulse.DriveChannel(0))) # check frame data frames = list(ch_events.get_frame_changes()) inst_data0 = frames[0] self.assertEqual(inst_data0.t0, 0) self.assertEqual(inst_data0.frame.phase, 3.14) self.assertEqual(inst_data0.frame.freq, 0) self.assertListEqual(inst_data0.inst, [pulse.SetPhase(3.14, pulse.DriveChannel(0))]) inst_data1 = frames[1] self.assertEqual(inst_data1.t0, 10) self.assertEqual(inst_data1.frame.phase, -1.57) self.assertEqual(inst_data1.frame.freq, 0) self.assertListEqual(inst_data1.inst, [pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))]) def test_multiple_frames_at_the_same_time(self): """Test multiple frame instruction at the same time.""" # shift phase followed by set phase sched = pulse.Schedule() sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))) sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0))) ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0)) frames = list(ch_events.get_frame_changes()) inst_data0 = frames[0] self.assertAlmostEqual(inst_data0.frame.phase, 3.14) # set phase followed by shift phase sched = pulse.Schedule() sched = sched.insert(0, pulse.SetPhase(3.14, pulse.DriveChannel(0))) sched = sched.insert(0, pulse.ShiftPhase(-1.57, pulse.DriveChannel(0))) ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0)) frames = list(ch_events.get_frame_changes()) inst_data0 = frames[0] self.assertAlmostEqual(inst_data0.frame.phase, 1.57) def test_frequency(self): """Test parse frequency.""" sched = pulse.Schedule() sched = sched.insert(0, pulse.ShiftFrequency(1.0, pulse.DriveChannel(0))) sched = sched.insert(5, pulse.SetFrequency(5.0, pulse.DriveChannel(0))) ch_events = events.ChannelEvents.load_program(sched, pulse.DriveChannel(0)) ch_events.set_config(dt=0.1, init_frequency=3.0, init_phase=0) frames = list(ch_events.get_frame_changes()) inst_data0 = frames[0] self.assertAlmostEqual(inst_data0.frame.freq, 1.0) inst_data1 = frames[1] self.assertAlmostEqual(inst_data1.frame.freq, 1.0) def test_parameterized_parametric_pulse(self): """Test generating waveforms that are parameterized.""" param = circuit.Parameter("amp") test_waveform = pulse.Play(pulse.Constant(10, param), pulse.DriveChannel(0)) ch_events = events.ChannelEvents( waveforms={0: test_waveform}, frames={}, channel=pulse.DriveChannel(0) ) pulse_inst = list(ch_events.get_waveforms())[0] self.assertTrue(pulse_inst.is_opaque) self.assertEqual(pulse_inst.inst, test_waveform) def test_parameterized_frame_change(self): """Test generating waveforms that are parameterized. Parameterized phase should be ignored when calculating waveform frame. This is due to phase modulated representation of waveforms, i.e. we cannot calculate the phase factor of waveform if the phase is unbound. """ param = circuit.Parameter("phase") test_fc1 = pulse.ShiftPhase(param, pulse.DriveChannel(0)) test_fc2 = pulse.ShiftPhase(1.57, pulse.DriveChannel(0)) test_waveform = pulse.Play(pulse.Constant(10, 0.1), pulse.DriveChannel(0)) ch_events = events.ChannelEvents( waveforms={0: test_waveform}, frames={0: [test_fc1, test_fc2]}, channel=pulse.DriveChannel(0), ) # waveform frame pulse_inst = list(ch_events.get_waveforms())[0] self.assertFalse(pulse_inst.is_opaque) self.assertEqual(pulse_inst.frame.phase, 1.57) # framechange pulse_inst = list(ch_events.get_frame_changes())[0] self.assertTrue(pulse_inst.is_opaque) self.assertEqual(pulse_inst.frame.phase, param + 1.57) def test_zero_duration_delay(self): """Test generating waveforms that contains zero duration delay. Zero duration delay should be ignored. """ ch = pulse.DriveChannel(0) test_sched = pulse.Schedule() test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch) test_sched += pulse.Delay(0, ch) test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch) test_sched += pulse.Delay(1, ch) test_sched += pulse.Play(pulse.Gaussian(160, 0.1, 40), ch) ch_events = events.ChannelEvents.load_program(test_sched, ch) self.assertEqual(len(list(ch_events.get_waveforms())), 4)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Tests for generator of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import generators, types, stylesheet from qiskit.circuit import library, Delay class TestGates(QiskitTestCase): """Tests for generator.gates.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] self.u1 = types.ScheduledGate( t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0 ) self.u3 = types.ScheduledGate( t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0 ) self.delay = types.ScheduledGate( t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0 ) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_sched_gate_with_finite_duration(self): """Test test_gen_sched_gate generator with finite duration gate.""" drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 120]) self.assertListEqual( list(drawing_obj.yvals), [-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_meta = { "name": "u3", "label": "n/a", "bits": str(self.qubit.register.name), "t0": 100, "duration": 20, "unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]", "parameters": "0, 0, 0", } self.assertDictEqual(ref_meta, drawing_obj.meta) ref_styles = { "zorder": self.formatter["layer.gate"], "facecolor": self.formatter["color.gates"]["u3"], "alpha": self.formatter["alpha.gate"], "linewidth": self.formatter["line_width.gate"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_zero_duration(self): """Test test_gen_sched_gate generator with zero duration gate.""" drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"]) self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"]) ref_styles = { "zorder": self.formatter["layer.frame_change"], "color": self.formatter["color.gates"]["u1"], "size": self.formatter["text_size.frame_change"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_delay(self): """Test test_gen_sched_gate generator with delay.""" drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value)) def test_gen_full_gate_name_with_finite_duration(self): """Test gen_full_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]") ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format( name=self.formatter["latex_symbol.gates"]["u3"] ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_zero_duration(self): """Test gen_full_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1(0.00)") ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_delay(self): """Test gen_full_gate_name generator with delay.""" drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) def test_gen_short_gate_name_with_finite_duration(self): """Test gen_short_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_zero_duration(self): """Test gen_short_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_delay(self): """Test gen_short_gate_name generator with delay.""" drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) class TestTimeslot(QiskitTestCase): """Tests for generator.bits.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_timeslot(self): """Test gen_timeslot generator.""" drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value)) self.assertListEqual( list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ) self.assertListEqual( list(drawing_obj.yvals), [ -0.5 * self.formatter["box_height.timeslot"], 0.5 * self.formatter["box_height.timeslot"], ], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_styles = { "zorder": self.formatter["layer.timeslot"], "alpha": self.formatter["alpha.timeslot"], "linewidth": self.formatter["line_width.timeslot"], "facecolor": self.formatter["color.timeslot"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_bit_name(self): """Test gen_bit_name generator.""" drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, str(self.qubit.register.name)) ref_latex = r"{{\rm {register}}}_{{{index}}}".format( register=self.qubit.register.prefix, index=self.qubit.index ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.bit_name"], "color": self.formatter["color.bit_name"], "size": self.formatter["text_size.bit_name"], "va": "center", "ha": "right", } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestBarrier(QiskitTestCase): """Tests for generator.barriers.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(3)) self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_barrier(self): """Test gen_barrier generator.""" drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 100]) self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5]) self.assertListEqual(drawing_obj.bits, [self.qubits[1]]) ref_styles = { "alpha": self.formatter["alpha.barrier"], "zorder": self.formatter["layer.barrier"], "linewidth": self.formatter["line_width.barrier"], "linestyle": self.formatter["line_style.barrier"], "color": self.formatter["color.barrier"], } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestGateLink(QiskitTestCase): """Tests for generator.gate_links.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(2)) self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def gen_bit_link(self): """Test gen_bit_link generator.""" drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, self.qubits) ref_styles = { "alpha": self.formatter["alpha.bit_link"], "zorder": self.formatter["layer.bit_link"], "linewidth": self.formatter["line_width.bit_link"], "linestyle": self.formatter["line_style.bit_link"], "color": self.formatter["color.gates"]["cx"], } self.assertDictEqual(ref_styles, drawing_obj.styles)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for layouts of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import layouts class TestBitArrange(QiskitTestCase): """Tests for layout.bit_arrange.""" def setUp(self) -> None: """Setup.""" super().setUp() qregs = qiskit.QuantumRegister(3) cregs = qiskit.ClassicalRegister(3) self.regs = list(qregs) + list(cregs) def test_qreg_creg_ascending(self): """Test qreg_creg_ascending layout function.""" sorted_regs = layouts.qreg_creg_ascending(self.regs) ref_regs = [ self.regs[0], self.regs[1], self.regs[2], self.regs[3], self.regs[4], self.regs[5], ] self.assertListEqual(sorted_regs, ref_regs) def test_qreg_creg_descending(self): """Test qreg_creg_descending layout function.""" sorted_regs = layouts.qreg_creg_descending(self.regs) ref_regs = [ self.regs[2], self.regs[1], self.regs[0], self.regs[5], self.regs[4], self.regs[3], ] self.assertListEqual(sorted_regs, ref_regs) class TestAxisMap(QiskitTestCase): """Tests for layout.time_axis_map.""" def test_time_map_in_dt(self): """Test time_map_in_dt layout function.""" axis_config = layouts.time_map_in_dt(time_window=(-100, 500)) self.assertEqual(axis_config.window, (-100, 500)) self.assertEqual(axis_config.label, "System cycle time (dt)") ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"} self.assertDictEqual(axis_config.axis_map, ref_map)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for core modules of timeline drawer.""" from qiskit import QuantumCircuit, transpile from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import core, stylesheet, generators, layouts class TestCanvas(QiskitTestCase): """Test for canvas.""" def setUp(self): super().setUp() self.style = stylesheet.QiskitTimelineStyle() circ = QuantumCircuit(4) circ.h(0) circ.barrier() circ.cx(0, 2) circ.cx(1, 3) self.circ = transpile( circ, scheduling_method="alap", basis_gates=["h", "cx"], instruction_durations=[("h", 0, 200), ("cx", [0, 2], 1000), ("cx", [1, 3], 1000)], optimization_level=0, ) def test_time_range(self): """Test calculating time range.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter = {"margin.left_percent": 0.1, "margin.right_percent": 0.1} canvas.time_range = (0, 100) ref_range = [-10.0, 110.0] self.assertListEqual(list(canvas.time_range), ref_range) def test_load_program(self): """Test loading program.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 8) ref_coord = { self.circ.qregs[0][0]: -1.0, self.circ.qregs[0][1]: -2.0, self.circ.qregs[0][2]: -3.0, self.circ.qregs[0][3]: -4.0, } self.assertDictEqual(canvas.assigned_coordinates, ref_coord) def test_gate_link_overlap(self): """Test shifting gate link overlap.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update( { "margin.link_interval_percent": 0.01, "margin.left_percent": 0, "margin.right_percent": 0, } ) canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 2) self.assertListEqual(drawings_tested[0][1].xvals, [706.0]) self.assertListEqual(drawings_tested[1][1].xvals, [694.0]) ref_keys = list(canvas._collections.keys()) self.assertEqual(drawings_tested[0][0], ref_keys[0]) self.assertEqual(drawings_tested[1][0], ref_keys[1]) def test_object_outside_xlimit(self): """Test eliminating drawings outside the horizontal limit.""" canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [generators.gen_bit_name, generators.gen_timeslot], "barriers": [], "gate_links": [], } canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.load_program(self.circ) canvas.set_time_range(t_start=400, t_end=600) canvas.update() drawings_tested = list(canvas.collections) self.assertEqual(len(drawings_tested), 12) def test_non_transpiled_delay_circuit(self): """Test non-transpiled circuit containing instruction which is trivial on duration.""" circ = QuantumCircuit(1) circ.delay(10, 0) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.generator = { "gates": [generators.gen_sched_gate], "bits": [], "barriers": [], "gate_links": [], } with self.assertWarns(DeprecationWarning): canvas.load_program(circ) self.assertEqual(len(canvas._collections), 1) def test_multi_measurement_with_clbit_not_shown(self): """Test generating bit link drawings of measurements when clbits is disabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": False}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 0) def test_multi_measurement_with_clbit_shown(self): """Test generating bit link drawings of measurements when clbits is enabled.""" circ = QuantumCircuit(2, 2) circ.measure(0, 0) circ.measure(1, 1) circ = transpile( circ, scheduling_method="alap", basis_gates=[], instruction_durations=[("measure", 0, 2000), ("measure", 1, 2000)], optimization_level=0, ) canvas = core.DrawerCanvas(stylesheet=self.style) canvas.formatter.update({"control.show_clbits": True}) canvas.layout = { "bit_arrange": layouts.qreg_creg_ascending, "time_axis_map": layouts.time_map_in_dt, } canvas.generator = { "gates": [], "bits": [], "barriers": [], "gate_links": [generators.gen_gate_link], } canvas.load_program(circ) canvas.update() self.assertEqual(len(canvas._output_dataset), 2)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for drawing of timeline drawer.""" import numpy as np import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import drawings, types class TestDrawingObjects(QiskitTestCase): """Tests for drawings.""" def setUp(self) -> None: """Setup.""" super().setUp() # bits self.qubits = list(qiskit.QuantumRegister(2)) # metadata self.meta1 = {"val1": 0, "val2": 1} self.meta2 = {"val1": 2, "val2": 3} # style data self.style1 = {"property1": 0, "property2": 1} self.style2 = {"property1": 2, "property2": 3} def test_line_data_equivalent(self): """Test LineData equivalent check.""" xs = list(np.arange(10)) ys = list(np.ones(10)) obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_line_data_equivalent_abstract_coord(self): """Test LineData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.LineData( data_type=types.LineType.BARRIER, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent(self): """Test BoxData equivalent check.""" xs = [0, 1] ys = [0, 1] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_box_data_equivalent_abstract_coord(self): """Test BoxData equivalent check with abstract coordinate.""" xs = [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ys = [types.AbstractCoordinate.BOTTOM, types.AbstractCoordinate.TOP] obj1 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta1, styles=self.style1, ) obj2 = drawings.BoxData( data_type=types.BoxType.SCHED_GATE, bit=self.qubits[0], xvals=xs, yvals=ys, meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent(self): """Test TextData equivalent check.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=0, yval=0, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_text_data_equivalent_abstract_coord(self): """Test TextData equivalent check with abstract coordinate.""" obj1 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta1, styles=self.style1, ) obj2 = drawings.TextData( data_type=types.LabelType.GATE_NAME, bit=self.qubits[0], xval=types.AbstractCoordinate.LEFT, yval=types.AbstractCoordinate.BOTTOM, text="test", latex="test", meta=self.meta2, styles=self.style2, ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent(self): """Test BitLinkData equivalent check.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style1 ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=0, styles=self.style2 ) self.assertEqual(obj1, obj2) def test_bit_link_data_equivalent_abstract_coord(self): """Test BitLinkData equivalent check with abstract coordinate.""" obj1 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style1, ) obj2 = drawings.GateLinkData( bits=[self.qubits[0], self.qubits[1]], xval=types.AbstractCoordinate.LEFT, styles=self.style2, ) self.assertEqual(obj1, obj2)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Tests for generator of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import generators, types, stylesheet from qiskit.circuit import library, Delay class TestGates(QiskitTestCase): """Tests for generator.gates.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] self.u1 = types.ScheduledGate( t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0 ) self.u3 = types.ScheduledGate( t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0 ) self.delay = types.ScheduledGate( t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0 ) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_sched_gate_with_finite_duration(self): """Test test_gen_sched_gate generator with finite duration gate.""" drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 120]) self.assertListEqual( list(drawing_obj.yvals), [-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_meta = { "name": "u3", "label": "n/a", "bits": str(self.qubit.register.name), "t0": 100, "duration": 20, "unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]", "parameters": "0, 0, 0", } self.assertDictEqual(ref_meta, drawing_obj.meta) ref_styles = { "zorder": self.formatter["layer.gate"], "facecolor": self.formatter["color.gates"]["u3"], "alpha": self.formatter["alpha.gate"], "linewidth": self.formatter["line_width.gate"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_zero_duration(self): """Test test_gen_sched_gate generator with zero duration gate.""" drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"]) self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"]) ref_styles = { "zorder": self.formatter["layer.frame_change"], "color": self.formatter["color.gates"]["u1"], "size": self.formatter["text_size.frame_change"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_sched_gate_with_delay(self): """Test test_gen_sched_gate generator with delay.""" drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value)) def test_gen_full_gate_name_with_finite_duration(self): """Test gen_full_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]") ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format( name=self.formatter["latex_symbol.gates"]["u3"] ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_zero_duration(self): """Test gen_full_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1(0.00)") ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_full_gate_name_with_delay(self): """Test gen_full_gate_name generator with delay.""" drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) def test_gen_short_gate_name_with_finite_duration(self): """Test gen_short_gate_name generator with finite duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [110.0]) self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "center", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_zero_duration(self): """Test gen_short_gate_name generator with zero duration gate.""" drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [100.0]) self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1") ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"]) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.gate_name"], "color": self.formatter["color.gate_name"], "size": self.formatter["text_size.gate_name"], "va": "bottom", "ha": "center", } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_short_gate_name_with_delay(self): """Test gen_short_gate_name generator with delay.""" drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value)) class TestTimeslot(QiskitTestCase): """Tests for generator.bits.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubit = list(qiskit.QuantumRegister(1))[0] style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_timeslot(self): """Test gen_timeslot generator.""" drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value)) self.assertListEqual( list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT] ) self.assertListEqual( list(drawing_obj.yvals), [ -0.5 * self.formatter["box_height.timeslot"], 0.5 * self.formatter["box_height.timeslot"], ], ) self.assertListEqual(drawing_obj.bits, [self.qubit]) ref_styles = { "zorder": self.formatter["layer.timeslot"], "alpha": self.formatter["alpha.timeslot"], "linewidth": self.formatter["line_width.timeslot"], "facecolor": self.formatter["color.timeslot"], } self.assertDictEqual(ref_styles, drawing_obj.styles) def test_gen_bit_name(self): """Test gen_bit_name generator.""" drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value)) self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, str(self.qubit.register.name)) ref_latex = r"{{\rm {register}}}_{{{index}}}".format( register=self.qubit.register.prefix, index=self.qubit.index ) self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { "zorder": self.formatter["layer.bit_name"], "color": self.formatter["color.bit_name"], "size": self.formatter["text_size.bit_name"], "va": "center", "ha": "right", } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestBarrier(QiskitTestCase): """Tests for generator.barriers.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(3)) self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def test_gen_barrier(self): """Test gen_barrier generator.""" drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value)) self.assertListEqual(list(drawing_obj.xvals), [100, 100]) self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5]) self.assertListEqual(drawing_obj.bits, [self.qubits[1]]) ref_styles = { "alpha": self.formatter["alpha.barrier"], "zorder": self.formatter["layer.barrier"], "linewidth": self.formatter["line_width.barrier"], "linestyle": self.formatter["line_style.barrier"], "color": self.formatter["color.barrier"], } self.assertDictEqual(ref_styles, drawing_obj.styles) class TestGateLink(QiskitTestCase): """Tests for generator.gate_links.""" def setUp(self) -> None: """Setup.""" super().setUp() self.qubits = list(qiskit.QuantumRegister(2)) self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits) style = stylesheet.QiskitTimelineStyle() self.formatter = style.formatter def gen_bit_link(self): """Test gen_bit_link generator.""" drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0] self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value)) self.assertListEqual(list(drawing_obj.xvals), [100]) self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, self.qubits) ref_styles = { "alpha": self.formatter["alpha.bit_link"], "zorder": self.formatter["layer.bit_link"], "linewidth": self.formatter["line_width.bit_link"], "linestyle": self.formatter["line_style.bit_link"], "color": self.formatter["color.gates"]["cx"], } self.assertDictEqual(ref_styles, drawing_obj.styles)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for layouts of timeline drawer.""" import qiskit from qiskit.test import QiskitTestCase from qiskit.visualization.timeline import layouts class TestBitArrange(QiskitTestCase): """Tests for layout.bit_arrange.""" def setUp(self) -> None: """Setup.""" super().setUp() qregs = qiskit.QuantumRegister(3) cregs = qiskit.ClassicalRegister(3) self.regs = list(qregs) + list(cregs) def test_qreg_creg_ascending(self): """Test qreg_creg_ascending layout function.""" sorted_regs = layouts.qreg_creg_ascending(self.regs) ref_regs = [ self.regs[0], self.regs[1], self.regs[2], self.regs[3], self.regs[4], self.regs[5], ] self.assertListEqual(sorted_regs, ref_regs) def test_qreg_creg_descending(self): """Test qreg_creg_descending layout function.""" sorted_regs = layouts.qreg_creg_descending(self.regs) ref_regs = [ self.regs[2], self.regs[1], self.regs[0], self.regs[5], self.regs[4], self.regs[3], ] self.assertListEqual(sorted_regs, ref_regs) class TestAxisMap(QiskitTestCase): """Tests for layout.time_axis_map.""" def test_time_map_in_dt(self): """Test time_map_in_dt layout function.""" axis_config = layouts.time_map_in_dt(time_window=(-100, 500)) self.assertEqual(axis_config.window, (-100, 500)) self.assertEqual(axis_config.label, "System cycle time (dt)") ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"} self.assertDictEqual(axis_config.axis_map, ref_map)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
#!/usr/bin/env python3 # 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 cases to verify qpy backwards compatibility.""" import argparse import itertools import random import re import sys import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.classicalregister import Clbit from qiskit.circuit.quantumregister import Qubit from qiskit.circuit.parameter import Parameter from qiskit.circuit.parametervector import ParameterVector from qiskit.quantum_info.random import random_unitary from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, QFT, DCXGate, PauliGate from qiskit.circuit.gate import Gate try: from qiskit.qpy import dump, load except ModuleNotFoundError: from qiskit.circuit.qpy_serialization import dump, load # This version pattern is taken from the pypa packaging project: # https://github.com/pypa/packaging/blob/21.3/packaging/version.py#L223-L254 # which is dual licensed Apache 2.0 and BSD see the source for the original # authors and other details VERSION_PATTERN = ( "^" + r""" v? (?: (?:(?P<epoch>[0-9]+)!)? # epoch (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment (?P<pre> # pre-release [-_\.]? (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) [-_\.]? (?P<pre_n>[0-9]+)? )? (?P<post> # post release (?:-(?P<post_n1>[0-9]+)) | (?: [-_\.]? (?P<post_l>post|rev|r) [-_\.]? (?P<post_n2>[0-9]+)? ) )? (?P<dev> # dev release [-_\.]? (?P<dev_l>dev) [-_\.]? (?P<dev_n>[0-9]+)? )? ) (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version """ + "$" ) def generate_full_circuit(): """Generate a multiregister circuit with name, metadata, phase.""" qr_a = QuantumRegister(4, "a") qr_b = QuantumRegister(4, "b") cr_c = ClassicalRegister(4, "c") cr_d = ClassicalRegister(4, "d") full_circuit = QuantumCircuit( qr_a, qr_b, cr_c, cr_d, name="MyCircuit", metadata={"test": 1, "a": 2}, global_phase=3.14159, ) full_circuit.h(qr_a) full_circuit.cx(qr_a, qr_b) full_circuit.barrier(qr_a) full_circuit.barrier(qr_b) full_circuit.measure(qr_a, cr_c) full_circuit.measure(qr_b, cr_d) return full_circuit def generate_unitary_gate_circuit(): """Generate a circuit with a unitary gate.""" unitary_circuit = QuantumCircuit(5, name="unitary_circuit") unitary_circuit.unitary(random_unitary(32, seed=100), [0, 1, 2, 3, 4]) unitary_circuit.measure_all() return unitary_circuit def generate_random_circuits(): """Generate multiple random circuits.""" random_circuits = [] for i in range(1, 15): qc = QuantumCircuit(i, name=f"random_circuit-{i}") qc.h(0) if i > 1: for j in range(i - 1): qc.cx(0, j + 1) qc.measure_all() for j in range(i): qc.reset(j) qc.x(0).c_if(qc.cregs[0], i) for j in range(i): qc.measure(j, j) random_circuits.append(qc) return random_circuits def generate_string_parameters(): """Generate a circuit for the XYZ pauli string.""" op_circuit = QuantumCircuit(3, name="X^Y^Z") op_circuit.append(PauliGate("XYZ"), op_circuit.qubits, []) return op_circuit def generate_register_edge_cases(): """Generate register edge case circuits.""" register_edge_cases = [] # Circuit with shared bits in a register qubits = [Qubit() for _ in range(5)] shared_qc = QuantumCircuit(name="shared_bits") shared_qc.add_bits(qubits) shared_qr = QuantumRegister(bits=qubits) shared_qc.add_register(shared_qr) shared_qc.h(shared_qr) shared_qc.cx(0, 1) shared_qc.cx(0, 2) shared_qc.cx(0, 3) shared_qc.cx(0, 4) shared_qc.measure_all() register_edge_cases.append(shared_qc) # Circuit with registers that have a mix of standalone and shared register # bits qr = QuantumRegister(5, "foo") qr = QuantumRegister(name="bar", bits=qr[:3] + [Qubit(), Qubit()]) cr = ClassicalRegister(5, "foo") cr = ClassicalRegister(name="classical_bar", bits=cr[:3] + [Clbit(), Clbit()]) hybrid_qc = QuantumCircuit(qr, cr, name="mix_standalone_bits_registers") hybrid_qc.h(0) hybrid_qc.cx(0, 1) hybrid_qc.cx(0, 2) hybrid_qc.cx(0, 3) hybrid_qc.cx(0, 4) hybrid_qc.measure(qr, cr) register_edge_cases.append(hybrid_qc) # Circuit with mixed standalone and shared registers qubits = [Qubit() for _ in range(5)] clbits = [Clbit() for _ in range(5)] mixed_qc = QuantumCircuit(name="mix_standalone_bits_with_registers") mixed_qc.add_bits(qubits) mixed_qc.add_bits(clbits) qr = QuantumRegister(bits=qubits) cr = ClassicalRegister(bits=clbits) mixed_qc.add_register(qr) mixed_qc.add_register(cr) qr_standalone = QuantumRegister(2, "standalone") mixed_qc.add_register(qr_standalone) cr_standalone = ClassicalRegister(2, "classical_standalone") mixed_qc.add_register(cr_standalone) mixed_qc.unitary(random_unitary(32, seed=42), qr) mixed_qc.unitary(random_unitary(4, seed=100), qr_standalone) mixed_qc.measure(qr, cr) mixed_qc.measure(qr_standalone, cr_standalone) register_edge_cases.append(mixed_qc) # Circuit with out of order register bits qr_standalone = QuantumRegister(2, "standalone") qubits = [Qubit() for _ in range(5)] clbits = [Clbit() for _ in range(5)] ooo_qc = QuantumCircuit(name="out_of_order_bits") ooo_qc.add_bits(qubits) ooo_qc.add_bits(clbits) random.seed(42) random.shuffle(qubits) random.shuffle(clbits) qr = QuantumRegister(bits=qubits) cr = ClassicalRegister(bits=clbits) ooo_qc.add_register(qr) ooo_qc.add_register(cr) qr_standalone = QuantumRegister(2, "standalone") cr_standalone = ClassicalRegister(2, "classical_standalone") ooo_qc.add_bits([qr_standalone[1], qr_standalone[0]]) ooo_qc.add_bits([cr_standalone[1], cr_standalone[0]]) ooo_qc.add_register(qr_standalone) ooo_qc.add_register(cr_standalone) ooo_qc.unitary(random_unitary(32, seed=42), qr) ooo_qc.unitary(random_unitary(4, seed=100), qr_standalone) ooo_qc.measure(qr, cr) ooo_qc.measure(qr_standalone, cr_standalone) register_edge_cases.append(ooo_qc) return register_edge_cases def generate_parameterized_circuit(): """Generate a circuit with parameters and parameter expressions.""" param_circuit = QuantumCircuit(1, name="parameterized") theta = Parameter("theta") lam = Parameter("λ") theta_pi = 3.14159 * theta pe = theta_pi / lam param_circuit.append(U3Gate(theta, theta_pi, lam), [0]) param_circuit.append(U1Gate(pe), [0]) param_circuit.append(U2Gate(theta_pi, lam), [0]) return param_circuit def generate_qft_circuit(): """Generate a QFT circuit with initialization.""" k = 5 state = (1 / np.sqrt(8)) * np.array( [ np.exp(-1j * 2 * np.pi * k * (0) / 8), np.exp(-1j * 2 * np.pi * k * (1) / 8), np.exp(-1j * 2 * np.pi * k * (2) / 8), np.exp(-1j * 2 * np.pi * k * 3 / 8), np.exp(-1j * 2 * np.pi * k * 4 / 8), np.exp(-1j * 2 * np.pi * k * 5 / 8), np.exp(-1j * 2 * np.pi * k * 6 / 8), np.exp(-1j * 2 * np.pi * k * 7 / 8), ] ) qubits = 3 qft_circ = QuantumCircuit(qubits, qubits, name="QFT") qft_circ.initialize(state) qft_circ.append(QFT(qubits), range(qubits)) qft_circ.measure(range(qubits), range(qubits)) return qft_circ def generate_param_phase(): """Generate circuits with parameterize global phase.""" output_circuits = [] # Generate circuit with ParameterExpression global phase theta = Parameter("theta") phi = Parameter("phi") sum_param = theta + phi qc = QuantumCircuit(5, 1, global_phase=sum_param, name="parameter_phase") qc.h(0) for i in range(4): qc.cx(i, i + 1) qc.barrier() qc.rz(sum_param, range(3)) qc.rz(phi, 3) qc.rz(theta, 4) qc.barrier() for i in reversed(range(4)): qc.cx(i, i + 1) qc.h(0) qc.measure(0, 0) output_circuits.append(qc) # Generate circuit with Parameter global phase theta = Parameter("theta") bell_qc = QuantumCircuit(2, global_phase=theta, name="bell_param_global_phase") bell_qc.h(0) bell_qc.cx(0, 1) bell_qc.measure_all() output_circuits.append(bell_qc) return output_circuits def generate_single_clbit_condition_teleportation(): # pylint: disable=invalid-name """Generate single clbit condition teleportation circuit.""" qr = QuantumRegister(1) cr = ClassicalRegister(2, name="name") teleport_qc = QuantumCircuit(qr, cr, name="Reset Test") teleport_qc.x(0) teleport_qc.measure(0, cr[0]) teleport_qc.x(0).c_if(cr[0], 1) teleport_qc.measure(0, cr[1]) return teleport_qc def generate_parameter_vector(): """Generate tests for parameter vector element ordering.""" qc = QuantumCircuit(11, name="parameter_vector") input_params = ParameterVector("x_par", 11) user_params = ParameterVector("θ_par", 11) for i, param in enumerate(user_params): qc.ry(param, i) for i, param in enumerate(input_params): qc.rz(param, i) return qc def generate_parameter_vector_expression(): # pylint: disable=invalid-name """Generate tests for parameter vector element ordering.""" qc = QuantumCircuit(7, name="vector_expansion") entanglement = [[i, i + 1] for i in range(7 - 1)] input_params = ParameterVector("x_par", 14) user_params = ParameterVector("\u03B8_par", 1) for i in range(qc.num_qubits): qc.ry(user_params[0], qc.qubits[i]) for source, target in entanglement: qc.cz(qc.qubits[source], qc.qubits[target]) for i in range(qc.num_qubits): qc.rz(-2 * input_params[2 * i + 1], qc.qubits[i]) qc.rx(-2 * input_params[2 * i], qc.qubits[i]) return qc def generate_evolution_gate(): """Generate a circuit with a pauli evolution gate.""" # Runtime import since this only exists in terra 0.19.0 from qiskit.circuit.library import PauliEvolutionGate from qiskit.synthesis import SuzukiTrotter from qiskit.quantum_info import SparsePauliOp synthesis = SuzukiTrotter() op = SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]) evo = PauliEvolutionGate([op] * 5, time=2.0, synthesis=synthesis) qc = QuantumCircuit(2, name="pauli_evolution_circuit") qc.append(evo, range(2)) return qc def generate_control_flow_circuits(): """Test qpy serialization with control flow instructions.""" from qiskit.circuit.controlflow import WhileLoopOp, IfElseOp, ForLoopOp # If instruction circuits = [] qc = QuantumCircuit(2, 2, name="control_flow") qc.h(0) qc.measure(0, 0) true_body = QuantumCircuit(1) true_body.x(0) if_op = IfElseOp((qc.clbits[0], True), true_body=true_body) qc.append(if_op, [1]) qc.measure(1, 1) circuits.append(qc) # If else instruction qc = QuantumCircuit(2, 2, name="if_else") qc.h(0) qc.measure(0, 0) false_body = QuantumCircuit(1) false_body.y(0) if_else_op = IfElseOp((qc.clbits[0], True), true_body, false_body) qc.append(if_else_op, [1]) qc.measure(1, 1) circuits.append(qc) # While loop qc = QuantumCircuit(2, 1, name="while_loop") block = QuantumCircuit(2, 1) block.h(0) block.cx(0, 1) block.measure(0, 0) while_loop = WhileLoopOp((qc.clbits[0], 0), block) qc.append(while_loop, [0, 1], [0]) circuits.append(qc) # for loop range qc = QuantumCircuit(2, 1, name="for_loop") body = QuantumCircuit(2, 1) body.h(0) body.cx(0, 1) body.measure(0, 0) body.break_loop().c_if(0, True) for_loop_op = ForLoopOp(range(5), None, body=body) qc.append(for_loop_op, [0, 1], [0]) circuits.append(qc) # For loop iterator qc = QuantumCircuit(2, 1, name="for_loop_iterator") for_loop_op = ForLoopOp(iter(range(5)), None, body=body) qc.append(for_loop_op, [0, 1], [0]) circuits.append(qc) return circuits def generate_control_flow_switch_circuits(): """Generate circuits with switch-statement instructions.""" from qiskit.circuit.controlflow import CASE_DEFAULT circuits = [] qc = QuantumCircuit(2, 1, name="switch_clbit") case_t = qc.copy_empty_like() case_t.x(0) case_f = qc.copy_empty_like() case_f.z(1) qc.switch(qc.clbits[0], [(True, case_t), (False, case_f)], qc.qubits, qc.clbits) circuits.append(qc) qreg = QuantumRegister(2, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg, name="switch_creg") case_0 = QuantumCircuit(qreg, creg) case_0.x(0) case_1 = QuantumCircuit(qreg, creg) case_1.z(1) case_2 = QuantumCircuit(qreg, creg) case_2.x(1) qc.switch( creg, [(0, case_0), ((1, 2), case_1), ((3, 4, CASE_DEFAULT), case_2)], qc.qubits, qc.clbits ) circuits.append(qc) return circuits def generate_schedule_blocks(): """Standard QPY testcase for schedule blocks.""" from qiskit.pulse import builder, channels, library from qiskit.utils import optionals # Parameterized schedule test is avoided. # Generated reference and loaded QPY object may induce parameter uuid mismatch. # As workaround, we need test with bounded parameters, however, schedule.parameters # are returned as Set and thus its order is random. # Since schedule parameters are validated, we cannot assign random numbers. # We need to upgrade testing framework. schedule_blocks = [] # Instructions without parameters with builder.build() as block: with builder.align_sequential(): builder.set_frequency(5e9, channels.DriveChannel(0)) builder.shift_frequency(10e6, channels.DriveChannel(1)) builder.set_phase(1.57, channels.DriveChannel(0)) builder.shift_phase(0.1, channels.DriveChannel(1)) builder.barrier(channels.DriveChannel(0), channels.DriveChannel(1)) builder.play(library.Gaussian(160, 0.1j, 40), channels.DriveChannel(0)) builder.play(library.GaussianSquare(800, 0.1, 64, 544), channels.ControlChannel(0)) builder.play(library.Drag(160, 0.1, 40, 1.5), channels.DriveChannel(1)) builder.play(library.Constant(800, 0.1), channels.MeasureChannel(0)) builder.acquire(1000, channels.AcquireChannel(0), channels.MemorySlot(0)) schedule_blocks.append(block) # Raw symbolic pulse if optionals.HAS_SYMENGINE: import symengine as sym else: import sympy as sym duration, amp, t = sym.symbols("duration amp t") # pylint: disable=invalid-name expr = amp * sym.sin(2 * sym.pi * t / duration) my_pulse = library.SymbolicPulse( pulse_type="Sinusoidal", duration=100, parameters={"amp": 0.1}, envelope=expr, valid_amp_conditions=sym.Abs(amp) <= 1.0, ) with builder.build() as block: builder.play(my_pulse, channels.DriveChannel(0)) schedule_blocks.append(block) # Raw waveform my_waveform = 0.1 * np.sin(2 * np.pi * np.linspace(0, 1, 100)) with builder.build() as block: builder.play(my_waveform, channels.DriveChannel(0)) schedule_blocks.append(block) return schedule_blocks def generate_referenced_schedule(): """Test for QPY serialization of unassigned reference schedules.""" from qiskit.pulse import builder, channels, library schedule_blocks = [] # Completely unassigned schedule with builder.build() as block: builder.reference("cr45p", "q0", "q1") builder.reference("x", "q0") builder.reference("cr45m", "q0", "q1") schedule_blocks.append(block) # Partly assigned schedule with builder.build() as x_q0: builder.play(library.Constant(100, 0.1), channels.DriveChannel(0)) with builder.build() as block: builder.reference("cr45p", "q0", "q1") builder.call(x_q0) builder.reference("cr45m", "q0", "q1") schedule_blocks.append(block) return schedule_blocks def generate_calibrated_circuits(): """Test for QPY serialization with calibrations.""" from qiskit.pulse import builder, Constant, DriveChannel circuits = [] # custom gate mygate = Gate("mygate", 1, []) qc = QuantumCircuit(1, name="calibrated_circuit_1") qc.append(mygate, [0]) with builder.build() as caldef: builder.play(Constant(100, 0.1), DriveChannel(0)) qc.add_calibration(mygate, (0,), caldef) circuits.append(qc) # override instruction qc = QuantumCircuit(1, name="calibrated_circuit_2") qc.x(0) with builder.build() as caldef: builder.play(Constant(100, 0.1), DriveChannel(0)) qc.add_calibration("x", (0,), caldef) circuits.append(qc) return circuits def generate_controlled_gates(): """Test QPY serialization with custom ControlledGates.""" circuits = [] qc = QuantumCircuit(3, name="custom_controlled_gates") controlled_gate = DCXGate().control(1) qc.append(controlled_gate, [0, 1, 2]) circuits.append(qc) custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition nested_qc = QuantumCircuit(3, name="nested_qc") qc.append(custom_gate, [0]) controlled_gate = custom_gate.control(2) nested_qc.append(controlled_gate, [0, 1, 2]) nested_qc.measure_all() circuits.append(nested_qc) qc_open = QuantumCircuit(2, name="open_cx") qc_open.cx(0, 1, ctrl_state=0) circuits.append(qc_open) return circuits def generate_open_controlled_gates(): """Test QPY serialization with custom ControlledGates with open controls.""" circuits = [] qc = QuantumCircuit(3, name="open_controls_simple") controlled_gate = DCXGate().control(1, ctrl_state=0) qc.append(controlled_gate, [0, 1, 2]) circuits.append(qc) custom_gate = Gate("black_box", 1, []) custom_definition = QuantumCircuit(1) custom_definition.h(0) custom_definition.rz(1.5, 0) custom_definition.sdg(0) custom_gate.definition = custom_definition nested_qc = QuantumCircuit(3, name="open_controls_nested") nested_qc.append(custom_gate, [0]) controlled_gate = custom_gate.control(2, ctrl_state=1) nested_qc.append(controlled_gate, [0, 1, 2]) nested_qc.measure_all() circuits.append(nested_qc) return circuits def generate_acquire_instruction_with_kernel_and_discriminator(): """Test QPY serialization with Acquire instruction with kernel and discriminator.""" from qiskit.pulse import builder, AcquireChannel, MemorySlot, Discriminator, Kernel schedule_blocks = [] with builder.build() as block: builder.acquire( 100, AcquireChannel(0), MemorySlot(0), kernel=Kernel( name="my_kernel", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1] ), ) schedule_blocks.append(block) with builder.build() as block: builder.acquire( 100, AcquireChannel(0), MemorySlot(0), discriminator=Discriminator( name="my_disc", my_params_1={"param1": 0.1, "param2": 0.2}, my_params_2=[0, 1] ), ) schedule_blocks.append(block) return schedule_blocks def generate_layout_circuits(): """Test qpy circuits with layout set.""" from qiskit.transpiler.layout import TranspileLayout, Layout qr = QuantumRegister(3, "foo") qc = QuantumCircuit(qr, name="GHZ with layout") qc.h(0) qc.cx(0, 1) qc.swap(0, 1) qc.cx(0, 2) input_layout = {qr[index]: index for index in range(len(qc.qubits))} qc._layout = TranspileLayout( Layout(input_layout), input_qubit_mapping=input_layout, final_layout=Layout.from_qubit_list([qc.qubits[1], qc.qubits[0], qc.qubits[2]]), ) return [qc] def generate_control_flow_expr(): """`IfElseOp`, `WhileLoopOp` and `SwitchCaseOp` with `Expr` nodes in their discriminators.""" from qiskit.circuit.classical import expr, types body1 = QuantumCircuit(1) body1.x(0) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") qc1 = QuantumCircuit(qr1, cr1) qc1.if_test(expr.equal(cr1, 3), body1.copy(), [0], []) qc1.while_loop(expr.logic_not(cr1[1]), body1.copy(), [0], []) inner2 = QuantumCircuit(1) inner2.x(0) outer2 = QuantumCircuit(1, 1) outer2.if_test(expr.logic_not(outer2.clbits[0]), inner2, [0], []) qr2 = QuantumRegister(2, "q2") cr1_2 = ClassicalRegister(3, "c1") cr2_2 = ClassicalRegister(3, "c2") qc2 = QuantumCircuit(qr2, cr1_2, cr2_2) qc2.if_test(expr.logic_or(expr.less(cr1_2, cr2_2), cr1_2[1]), outer2, [1], [1]) inner3 = QuantumCircuit(1) inner3.x(0) outer3 = QuantumCircuit(1, 1) outer3.switch(expr.logic_not(outer2.clbits[0]), [(False, inner2)], [0], []) qr3 = QuantumRegister(2, "q2") cr1_3 = ClassicalRegister(3, "c1") cr2_3 = ClassicalRegister(3, "c2") qc3 = QuantumCircuit(qr3, cr1_3, cr2_3) qc3.switch(expr.bit_xor(cr1_3, cr2_3), [(0, outer2)], [1], [1]) cr1_4 = ClassicalRegister(256, "c1") cr2_4 = ClassicalRegister(4, "c2") cr3_4 = ClassicalRegister(4, "c3") inner4 = QuantumCircuit(1) inner4.x(0) outer_loose = Clbit() outer4 = QuantumCircuit(QuantumRegister(2, "q_outer"), cr2_4, [outer_loose], cr1_4) outer4.if_test( expr.logic_and( expr.logic_or( expr.greater(expr.bit_or(cr2_4, 7), 10), expr.equal(expr.bit_and(cr1_4, cr1_4), expr.bit_not(cr1_4)), ), expr.logic_or( outer_loose, expr.cast(cr1_4, types.Bool()), ), ), inner4, [0], [], ) qc4_loose = Clbit() qc4 = QuantumCircuit(QuantumRegister(2, "qr4"), cr1_4, cr2_4, cr3_4, [qc4_loose]) qc4.rz(np.pi, 0) qc4.switch( expr.logic_and( expr.logic_or( expr.logic_or( expr.less(cr2_4, cr3_4), expr.logic_not(expr.greater_equal(cr3_4, cr2_4)), ), expr.logic_or( expr.logic_not(expr.less_equal(cr3_4, cr2_4)), expr.greater(cr2_4, cr3_4), ), ), expr.logic_and( expr.equal(cr3_4, 2), expr.not_equal(expr.bit_xor(cr1_4, 0x0F), 0x0F), ), ), [(False, outer4)], [1, 0], list(cr2_4) + [qc4_loose] + list(cr1_4), ) qc4.rz(np.pi, 0) return [qc1, qc2, qc3, qc4] def generate_circuits(version_parts): """Generate reference circuits.""" output_circuits = { "full.qpy": [generate_full_circuit()], "unitary.qpy": [generate_unitary_gate_circuit()], "multiple.qpy": generate_random_circuits(), "string_parameters.qpy": [generate_string_parameters()], "register_edge_cases.qpy": generate_register_edge_cases(), "parameterized.qpy": [generate_parameterized_circuit()], } if version_parts is None: return output_circuits if version_parts >= (0, 18, 1): output_circuits["qft_circuit.qpy"] = [generate_qft_circuit()] output_circuits["teleport.qpy"] = [generate_single_clbit_condition_teleportation()] if version_parts >= (0, 19, 0): output_circuits["param_phase.qpy"] = generate_param_phase() if version_parts >= (0, 19, 1): output_circuits["parameter_vector.qpy"] = [generate_parameter_vector()] output_circuits["pauli_evo.qpy"] = [generate_evolution_gate()] output_circuits["parameter_vector_expression.qpy"] = [ generate_parameter_vector_expression() ] if version_parts >= (0, 19, 2): output_circuits["control_flow.qpy"] = generate_control_flow_circuits() if version_parts >= (0, 21, 0): output_circuits["schedule_blocks.qpy"] = generate_schedule_blocks() output_circuits["pulse_gates.qpy"] = generate_calibrated_circuits() if version_parts >= (0, 24, 0): output_circuits["referenced_schedule_blocks.qpy"] = generate_referenced_schedule() output_circuits["control_flow_switch.qpy"] = generate_control_flow_switch_circuits() if version_parts >= (0, 24, 1): output_circuits["open_controlled_gates.qpy"] = generate_open_controlled_gates() output_circuits["controlled_gates.qpy"] = generate_controlled_gates() if version_parts >= (0, 24, 2): output_circuits["layout.qpy"] = generate_layout_circuits() if version_parts >= (0, 25, 0): output_circuits[ "acquire_inst_with_kernel_and_disc.qpy" ] = generate_acquire_instruction_with_kernel_and_discriminator() output_circuits["control_flow_expr.qpy"] = generate_control_flow_expr() return output_circuits def assert_equal(reference, qpy, count, version_parts, bind=None): """Compare two circuits.""" if bind is not None: reference_parameter_names = [x.name for x in reference.parameters] qpy_parameter_names = [x.name for x in qpy.parameters] if reference_parameter_names != qpy_parameter_names: msg = ( f"Circuit {count} parameter mismatch:" f" {reference_parameter_names} != {qpy_parameter_names}" ) sys.stderr.write(msg) sys.exit(4) reference = reference.bind_parameters(bind) qpy = qpy.bind_parameters(bind) if reference != qpy: msg = ( f"Reference Circuit {count}:\n{reference}\nis not equivalent to " f"qpy loaded circuit {count}:\n{qpy}\n" ) sys.stderr.write(msg) sys.exit(1) # Check deprecated bit properties, if set. The QPY dumping code before Terra 0.23.2 didn't # include enough information for us to fully reconstruct this, so we only test if newer. if version_parts >= (0, 23, 2) and isinstance(reference, QuantumCircuit): for ref_bit, qpy_bit in itertools.chain( zip(reference.qubits, qpy.qubits), zip(reference.clbits, qpy.clbits) ): if ref_bit._register is not None and ref_bit != qpy_bit: msg = ( f"Reference Circuit {count}:\n" "deprecated bit-level register information mismatch\n" f"reference bit: {ref_bit}\n" f"loaded bit: {qpy_bit}\n" ) sys.stderr.write(msg) sys.exit(1) if ( version_parts >= (0, 24, 2) and isinstance(reference, QuantumCircuit) and reference.layout != qpy.layout ): msg = f"Circuit {count} layout mismatch {reference.layout} != {qpy.layout}\n" sys.stderr.write(msg) sys.exit(4) # Don't compare name on bound circuits if bind is None and reference.name != qpy.name: msg = f"Circuit {count} name mismatch {reference.name} != {qpy.name}\n{reference}\n{qpy}" sys.stderr.write(msg) sys.exit(2) if reference.metadata != qpy.metadata: msg = f"Circuit {count} metadata mismatch: {reference.metadata} != {qpy.metadata}" sys.stderr.write(msg) sys.exit(3) def generate_qpy(qpy_files): """Generate qpy files from reference circuits.""" for path, circuits in qpy_files.items(): with open(path, "wb") as fd: dump(circuits, fd) def load_qpy(qpy_files, version_parts): """Load qpy circuits from files and compare to reference circuits.""" for path, circuits in qpy_files.items(): print(f"Loading qpy file: {path}") with open(path, "rb") as fd: qpy_circuits = load(fd) for i, circuit in enumerate(circuits): bind = None if path == "parameterized.qpy": bind = [1, 2] elif path == "param_phase.qpy": if i == 0: bind = [1, 2] else: bind = [1] elif path == "parameter_vector.qpy": bind = np.linspace(1.0, 2.0, 22) elif path == "parameter_vector_expression.qpy": bind = np.linspace(1.0, 2.0, 15) assert_equal(circuit, qpy_circuits[i], i, version_parts, bind=bind) def _main(): parser = argparse.ArgumentParser(description="Test QPY backwards compatibilty") parser.add_argument("command", choices=["generate", "load"]) parser.add_argument( "--version", "-v", help=( "Optionally specify the version being tested. " "This will enable additional circuit features " "to test generating and loading QPY." ), ) args = parser.parse_args() # Terra 0.18.0 was the first release with QPY, so that's the default. version_parts = (0, 18, 0) if args.version: version_match = re.search(VERSION_PATTERN, args.version, re.VERBOSE | re.IGNORECASE) version_parts = tuple(int(x) for x in version_match.group("release").split(".")) qpy_files = generate_circuits(version_parts) if args.command == "generate": generate_qpy(qpy_files) else: load_qpy(qpy_files, version_parts) if __name__ == "__main__": _main()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=invalid-name """Randomized tests of transpiler circuit equivalence. This test can be optionally configured (e.g. by CI) via the following env vars: QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS A space-delimited list of layout method names from which the randomizer should pick the layout method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_ROUTING_METHODS A space-delimited list of routing method names from which the randomizer should pick the routing method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS A space-delimited list of scheduling method names from which the randomizer should pick the scheduling method. Defaults to all available built-in methods if unspecified. QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS A boolean value (e.g. "true", "Y", etc.) which, when true, forces the randomizer to pick a backend which fully supports scheduling (i.e. has fully specified duration info). Defaults to False. QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS A boolean value (e.g. "true", "Y", etc.) which, when false, prevents the randomizer from emitting barrier instructions. Defaults to True. """ import os from math import pi from hypothesis import assume, settings, HealthCheck from hypothesis.stateful import multiple, rule, precondition, invariant from hypothesis.stateful import Bundle, RuleBasedStateMachine import hypothesis.strategies as st from qiskit import transpile, Aer from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit import Measure, Reset, Gate, Barrier from qiskit.providers.fake_provider import ( FakeProvider, FakeOpenPulse2Q, FakeOpenPulse3Q, FakeYorktown, FakeTenerife, FakeOurense, FakeVigo, FakeMelbourne, FakeRueschlikon, FakeTokyo, FakePoughkeepsie, FakeAlmaden, FakeSingapore, FakeJohannesburg, FakeBoeblingen, FakeRochester, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeLondon, FakeQasmSimulator, FakeArmonk, FakeRome, FakeSantiago, FakeSydney, FakeToronto, FakeValencia, ) from qiskit.test.base import dicts_almost_equal # pylint: disable=wildcard-import,unused-wildcard-import from qiskit.circuit.library.standard_gates import * default_profile = "transpiler_equivalence" settings.register_profile( default_profile, report_multiple_bugs=False, max_examples=200, deadline=None, suppress_health_check=[HealthCheck.filter_too_much], ) settings.load_profile(os.getenv("HYPOTHESIS_PROFILE", default_profile)) BASE_INSTRUCTIONS = { # Key is (n_qubits, n_clbits, n_params). All gates here should be directly known by Aer so they # can be simulated without an initial transpile (whether that's via `execute` or not). (1, 0, 0): [HGate, IGate, SGate, SdgGate, TGate, TdgGate, XGate, YGate, ZGate, Reset], (2, 0, 0): [CXGate, CYGate, CZGate, SwapGate], (3, 0, 0): [CCXGate, CSwapGate], (1, 0, 1): [PhaseGate, RXGate, RYGate, RZGate], (1, 0, 3): [UGate], (2, 0, 1): [RZZGate, CPhaseGate], (2, 0, 4): [CUGate], (1, 1, 0): [Measure], } variadic_gates = [Barrier] def _strtobool(s): return s.lower() in ("y", "yes", "t", "true", "on", "1") if not _strtobool(os.getenv("QISKIT_RANDOMIZED_TEST_ALLOW_BARRIERS", "True")): variadic_gates.remove(Barrier) def _getenv_list(var_name): value = os.getenv(var_name) return None if value is None else value.split() # Note: a value of `None` for any of the following methods means that # the selected pass manager gets to choose. However, to avoid complexity, # its not possible to specify `None` when overriding these with environment # variables. Really, `None` is useful only for testing Terra's pass managers, # and if you're overriding these, your goal is probably to test a specific # pass or set of passes instead. layout_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_LAYOUT_METHODS") or [ None, "trivial", "dense", "noise_adaptive", "sabre", ] routing_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_ROUTING_METHODS") or [ None, "basic", "stochastic", "lookahead", "sabre", ] scheduling_methods = _getenv_list("QISKIT_RANDOMIZED_TEST_SCHEDULING_METHODS") or [ None, "alap", "asap", ] backend_needs_durations = _strtobool( os.getenv("QISKIT_RANDOMIZED_TEST_BACKEND_NEEDS_DURATIONS", "False") ) def _fully_supports_scheduling(backend): """Checks if backend is not in the set of backends known not to have specified gate durations.""" return not isinstance( backend, ( # no coupling map FakeArmonk, # no measure durations FakeAlmaden, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeJohannesburg, FakeLondon, FakeOpenPulse2Q, FakeOpenPulse3Q, FakePoughkeepsie, FakeQasmSimulator, FakeRochester, FakeRueschlikon, FakeSingapore, FakeTenerife, FakeTokyo, # No reset duration FakeAlmaden, FakeArmonk, FakeBoeblingen, FakeBurlington, FakeCambridge, FakeCambridgeAlternativeBasis, FakeEssex, FakeJohannesburg, FakeLondon, FakeMelbourne, FakeOpenPulse2Q, FakeOpenPulse3Q, FakeOurense, FakePoughkeepsie, FakeQasmSimulator, FakeRochester, FakeRome, FakeRueschlikon, FakeSantiago, FakeSingapore, FakeSydney, FakeTenerife, FakeTokyo, FakeToronto, FakeValencia, FakeVigo, FakeYorktown, ), ) fake_provider = FakeProvider() mock_backends = fake_provider.backends() mock_backends_with_scheduling = [b for b in mock_backends if _fully_supports_scheduling(b)] @st.composite def transpiler_conf(draw): """Composite search strategy to pick a valid transpiler config.""" all_backends = st.one_of(st.none(), st.sampled_from(mock_backends)) scheduling_backends = st.sampled_from(mock_backends_with_scheduling) scheduling_method = draw(st.sampled_from(scheduling_methods)) backend = ( draw(scheduling_backends) if scheduling_method or backend_needs_durations else draw(all_backends) ) return { "backend": backend, "optimization_level": draw(st.integers(min_value=0, max_value=3)), "layout_method": draw(st.sampled_from(layout_methods)), "routing_method": draw(st.sampled_from(routing_methods)), "scheduling_method": scheduling_method, "seed_transpiler": draw(st.integers(min_value=0, max_value=1_000_000)), } class QCircuitMachine(RuleBasedStateMachine): """Build a Hypothesis rule based state machine for constructing, transpiling and simulating a series of random QuantumCircuits. Build circuits with up to QISKIT_RANDOM_QUBITS qubits, apply a random selection of gates from qiskit.circuit.library with randomly selected qargs, cargs, and parameters. At random intervals, transpile the circuit for a random backend with a random optimization level and simulate both the initial and the transpiled circuits to verify that their counts are the same. """ qubits = Bundle("qubits") clbits = Bundle("clbits") backend = Aer.get_backend("aer_simulator") max_qubits = int(backend.configuration().n_qubits / 2) # Limit reg generation for more interesting circuits max_qregs = 3 max_cregs = 3 def __init__(self): super().__init__() self.qc = QuantumCircuit() self.enable_variadic = bool(variadic_gates) @precondition(lambda self: len(self.qc.qubits) < self.max_qubits) @precondition(lambda self: len(self.qc.qregs) < self.max_qregs) @rule(target=qubits, n=st.integers(min_value=1, max_value=max_qubits)) def add_qreg(self, n): """Adds a new variable sized qreg to the circuit, up to max_qubits.""" n = min(n, self.max_qubits - len(self.qc.qubits)) qreg = QuantumRegister(n) self.qc.add_register(qreg) return multiple(*list(qreg)) @precondition(lambda self: len(self.qc.cregs) < self.max_cregs) @rule(target=clbits, n=st.integers(1, 5)) def add_creg(self, n): """Add a new variable sized creg to the circuit.""" creg = ClassicalRegister(n) self.qc.add_register(creg) return multiple(*list(creg)) # Gates of various shapes @precondition(lambda self: self.qc.num_qubits > 0 and self.qc.num_clbits > 0) @rule(n_arguments=st.sampled_from(sorted(BASE_INSTRUCTIONS.keys())), data=st.data()) def add_gate(self, n_arguments, data): """Append a random fixed gate to the circuit.""" n_qubits, n_clbits, n_params = n_arguments gate_class = data.draw(st.sampled_from(BASE_INSTRUCTIONS[n_qubits, n_clbits, n_params])) qubits = data.draw(st.lists(self.qubits, min_size=n_qubits, max_size=n_qubits, unique=True)) clbits = data.draw(st.lists(self.clbits, min_size=n_clbits, max_size=n_clbits, unique=True)) params = data.draw( st.lists( st.floats( allow_nan=False, allow_infinity=False, min_value=-10 * pi, max_value=10 * pi ), min_size=n_params, max_size=n_params, ) ) self.qc.append(gate_class(*params), qubits, clbits) @precondition(lambda self: self.enable_variadic) @rule(gate=st.sampled_from(variadic_gates), qargs=st.lists(qubits, min_size=1, unique=True)) def add_variQ_gate(self, gate, qargs): """Append a gate with a variable number of qargs.""" self.qc.append(gate(len(qargs)), qargs) @precondition(lambda self: len(self.qc.data) > 0) @rule(carg=clbits, data=st.data()) def add_c_if_last_gate(self, carg, data): """Modify the last gate to be conditional on a classical register.""" creg = self.qc.find_bit(carg).registers[0][0] val = data.draw(st.integers(min_value=0, max_value=2 ** len(creg) - 1)) last_gate = self.qc.data[-1] # Conditional instructions are not supported assume(isinstance(last_gate[0], Gate)) last_gate[0].c_if(creg, val) # Properties to check @invariant() def qasm(self): """After each circuit operation, it should be possible to build QASM.""" self.qc.qasm() @precondition(lambda self: any(isinstance(d[0], Measure) for d in self.qc.data)) @rule(kwargs=transpiler_conf()) def equivalent_transpile(self, kwargs): """Simulate, transpile and simulate the present circuit. Verify that the counts are not significantly different before and after transpilation. """ assume( kwargs["backend"] is None or kwargs["backend"].configuration().n_qubits >= len(self.qc.qubits) ) call = ( "transpile(qc, " + ", ".join(f"{key:s}={value!r}" for key, value in kwargs.items() if value is not None) + ")" ) print(f"Evaluating {call} for:\n{self.qc.qasm()}") shots = 4096 # Note that there's no transpilation here, which is why the gates are limited to only ones # that Aer supports natively. aer_counts = self.backend.run(self.qc, shots=shots).result().get_counts() try: xpiled_qc = transpile(self.qc, **kwargs) except Exception as e: failed_qasm = f"Exception caught during transpilation of circuit: \n{self.qc.qasm()}" raise RuntimeError(failed_qasm) from e xpiled_aer_counts = self.backend.run(xpiled_qc, shots=shots).result().get_counts() count_differences = dicts_almost_equal(aer_counts, xpiled_aer_counts, 0.05 * shots) assert ( count_differences == "" ), "Counts not equivalent: {}\nFailing QASM Input:\n{}\n\nFailing QASM Output:\n{}".format( count_differences, self.qc.qasm(), xpiled_qc.qasm() ) TestQuantumCircuit = QCircuitMachine.TestCase
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# Testing Circuits import warnings warnings.simplefilter("ignore") %run "mpl/circuit/test_circuit_matplotlib_drawer.py" # Testing Graphs %run "mpl/graph/test_graph_matplotlib_drawer.py" %run -i "results.py" RESULTS_CIRCUIT RESULTS_GRAPH
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for circuit MPL drawer""" import unittest import os import math from test.visual import VisualTestUtilities from pathlib import Path import numpy as np from numpy import pi from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.providers.fake_provider import FakeTenerife from qiskit.visualization.circuit.circuit_visualization import _matplotlib_circuit_drawer from qiskit.circuit.library import ( XGate, MCXGate, HGate, RZZGate, SwapGate, DCXGate, ZGate, SGate, U1Gate, CPhaseGate, ) from qiskit.circuit.library import MCXVChain from qiskit.extensions import HamiltonianGate from qiskit.circuit import Parameter, Qubit, Clbit from qiskit.circuit.library import IQP from qiskit.quantum_info.random import random_unitary from qiskit.utils import optionals if optionals.HAS_MATPLOTLIB: from matplotlib.pyplot import close as mpl_close else: raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".') BASE_DIR = Path(__file__).parent RESULT_DIR = Path(BASE_DIR) / "circuit_results" TEST_REFERENCE_DIR = Path(BASE_DIR) / "references" FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures" FAILURE_PREFIX = "circuit_failure_" class TestCircuitMatplotlibDrawer(QiskitTestCase): """Circuit MPL visualization""" def setUp(self): super().setUp() self.circuit_drawer = VisualTestUtilities.save_data_wrap( _matplotlib_circuit_drawer, str(self), RESULT_DIR ) if not os.path.exists(FAILURE_DIFF_DIR): os.makedirs(FAILURE_DIFF_DIR) if not os.path.exists(RESULT_DIR): os.makedirs(RESULT_DIR) def tearDown(self): super().tearDown() mpl_close("all") @staticmethod def _image_path(image_name): return os.path.join(RESULT_DIR, image_name) @staticmethod def _reference_path(image_name): return os.path.join(TEST_REFERENCE_DIR, image_name) def test_empty_circuit(self): """Test empty circuit""" circuit = QuantumCircuit() fname = "empty_circut.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.h(0) from qiskit import pulse with pulse.build(name="hadamard") as h_q0: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(0) ) circuit.add_calibration("h", [0], h_q0) fname = "calibrations.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations_with_control_gates(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.cx(0, 1) circuit.ch(0, 1) from qiskit import pulse with pulse.build(name="cnot") as cx_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("cx", [0, 1], cx_q01) with pulse.build(name="ch") as ch_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("ch", [0, 1], ch_q01) fname = "calibrations_with_control_gates.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations_with_swap_and_reset(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.swap(0, 1) circuit.reset(0) from qiskit import pulse with pulse.build(name="swap") as swap_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("swap", [0, 1], swap_q01) with pulse.build(name="reset") as reset_q0: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("reset", [0], reset_q0) fname = "calibrations_with_swap_and_reset.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_calibrations_with_rzz_and_rxx(self): """Test calibrations annotations See https://github.com/Qiskit/qiskit-terra/issues/5920 """ circuit = QuantumCircuit(2, 2) circuit.rzz(pi, 0, 1) circuit.rxx(pi, 0, 1) from qiskit import pulse with pulse.build(name="rzz") as rzz_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("rzz", [0, 1], rzz_q01) with pulse.build(name="rxx") as rxx_q01: pulse.play( pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.DriveChannel(1) ) circuit.add_calibration("rxx", [0, 1], rxx_q01) fname = "calibrations_with_rzz_and_rxx.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_no_ops(self): """Test circuit with no ops. See https://github.com/Qiskit/qiskit-terra/issues/5393""" circuit = QuantumCircuit(2, 3) fname = "no_op_circut.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_long_name(self): """Test to see that long register names can be seen completely As reported in #2605 """ # add a register with a very long name qr = QuantumRegister(4, "veryLongQuantumRegisterName") # add another to make sure adjustments are made based on longest qrr = QuantumRegister(1, "q0") circuit = QuantumCircuit(qr, qrr) # check gates are shifted over accordingly circuit.h(qr) circuit.h(qr) circuit.h(qr) fname = "long_name.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_multi_underscore_reg_names(self): """Test that multi-underscores in register names display properly""" q_reg1 = QuantumRegister(1, "q1_re__g__g") q_reg3 = QuantumRegister(3, "q3_re_g__g") c_reg1 = ClassicalRegister(1, "c1_re_g__g") c_reg3 = ClassicalRegister(3, "c3_re_g__g") circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3) fname = "multi_underscore_true.png" self.circuit_drawer(circuit, cregbundle=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "multi_underscore_false.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_conditional(self): """Test that circuits with conditionals draw correctly""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) # check gates are shifted over accordingly circuit.h(qr) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr, 2) fname = "reg_conditional.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_bit_conditional_with_cregbundle(self): """Test that circuits with single bit conditionals draw correctly with cregbundle=True.""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.x(qr[1]).c_if(cr[1], 0) fname = "bit_conditional_bundle.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_bit_conditional_no_cregbundle(self): """Test that circuits with single bit conditionals draw correctly with cregbundle=False.""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.measure(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.x(qr[1]).c_if(cr[1], 0) fname = "bit_conditional_no_bundle.png" self.circuit_drawer(circuit, filename=fname, cregbundle=False) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_plot_partial_barrier(self): """Test plotting of partial barriers.""" # generate a circuit with barrier and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier(0) circuit.h(q[0]) fname = "plot_partial_barrier.png" self.circuit_drawer(circuit, filename=fname, plot_barriers=True) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_plot_barriers(self): """Test to see that plotting barriers works. If it is set to False, no blank columns are introduced""" # generate a circuit with barriers and other barrier like instructions in q = QuantumRegister(2, "q") c = ClassicalRegister(2, "c") circuit = QuantumCircuit(q, c) # check for barriers circuit.h(q[0]) circuit.barrier() # check for other barrier like commands circuit.h(q[1]) # this import appears to be unused, but is actually needed to get snapshot instruction import qiskit.extensions.simulator # pylint: disable=unused-import circuit.snapshot("1") # check the barriers plot properly when plot_barriers= True fname = "plot_barriers_true.png" self.circuit_drawer(circuit, filename=fname, plot_barriers=True) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "plot_barriers_false.png" self.circuit_drawer(circuit, filename=fname2, plot_barriers=False) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_no_barriers_false(self): """Generate the same circuit as test_plot_barriers but without the barrier commands as this is what the circuit should look like when displayed with plot barriers false""" q1 = QuantumRegister(2, "q") c1 = ClassicalRegister(2, "c") circuit = QuantumCircuit(q1, c1) circuit.h(q1[0]) circuit.h(q1[1]) fname = "no_barriers.png" self.circuit_drawer(circuit, filename=fname, plot_barriers=False) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_fold_minus1(self): """Test to see that fold=-1 is no folding""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) for _ in range(3): circuit.h(0) circuit.x(0) fname = "fold_minus1.png" self.circuit_drawer(circuit, fold=-1, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_fold_4(self): """Test to see that fold=4 is folding""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) for _ in range(3): circuit.h(0) circuit.x(0) fname = "fold_4.png" self.circuit_drawer(circuit, fold=4, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_big_gates(self): """Test large gates with params""" qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2]) desired_vector = [ 1 / math.sqrt(16) * complex(0, 1), 1 / math.sqrt(8) * complex(1, 0), 1 / math.sqrt(16) * complex(1, 1), 0, 0, 1 / math.sqrt(8) * complex(1, 2), 1 / math.sqrt(16) * complex(1, 0), 0, ] circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]]) circuit.unitary([[1, 0], [0, 1]], [qr[0]]) matrix = np.zeros((4, 4)) theta = Parameter("theta") circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]]) circuit = circuit.bind_parameters({theta: 1}) circuit.isometry(np.eye(4, 4), list(range(3, 5)), []) fname = "big_gates.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_cnot(self): """Test different cnot gates (ccnot, mcx, etc)""" qr = QuantumRegister(6, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]]) circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]]) circuit.append(MCXVChain(3, dirty_ancillas=True), [qr[0], qr[1], qr[2], qr[3], qr[5]]) fname = "cnot.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_cz(self): """Test Z and Controlled-Z Gates""" qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.z(0) circuit.cz(0, 1) circuit.append(ZGate().control(3, ctrl_state="101"), [0, 1, 2, 3]) circuit.append(ZGate().control(2), [1, 2, 3]) circuit.append(ZGate().control(1, ctrl_state="0", label="CZ Gate"), [2, 3]) fname = "cz.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_pauli_clifford(self): """Test Pauli(green) and Clifford(blue) gates""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.y(0) circuit.z(0) circuit.id(0) circuit.h(1) circuit.cx(1, 2) circuit.cy(1, 2) circuit.cz(1, 2) circuit.swap(3, 4) circuit.s(3) circuit.sdg(3) circuit.iswap(3, 4) circuit.dcx(3, 4) fname = "pauli_clifford.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_creg_initial(self): """Test cregbundle and initial state options""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.x(0) circuit.h(0) circuit.x(1) fname = "creg_initial_true.png" self.circuit_drawer(circuit, filename=fname, cregbundle=True, initial_state=True) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "creg_initial_false.png" self.circuit_drawer(circuit, filename=fname2, cregbundle=False, initial_state=False) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_r_gates(self): """Test all R gates""" qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.r(3 * pi / 4, 3 * pi / 8, 0) circuit.rx(pi / 2, 1) circuit.ry(-pi / 2, 2) circuit.rz(3 * pi / 4, 3) circuit.rxx(pi / 2, 0, 1) circuit.ryy(3 * pi / 4, 2, 3) circuit.rzx(-pi / 2, 0, 1) circuit.rzz(pi / 2, 2, 3) fname = "r_gates.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_ctrl_labels(self): """Test control labels""" qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cy(1, 0, label="Bottom Y label") circuit.cu(pi / 2, pi / 2, pi / 2, 0, 2, 3, label="Top U label") circuit.ch(0, 1, label="Top H label") circuit.append( HGate(label="H gate label").control(3, label="H control label", ctrl_state="010"), [qr[1], qr[2], qr[3], qr[0]], ) fname = "ctrl_labels.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_cswap_rzz(self): """Test controlled swap and rzz gates""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.cswap(0, 1, 2) circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0]) fname = "cswap_rzz.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_ghz_to_gate(self): """Test controlled GHZ to_gate circuit""" qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) ghz_circuit = QuantumCircuit(3, name="this is a WWWWWWWWWWWide name Ctrl-GHZ Circuit") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2, ctrl_state="10") circuit.append(ccghz, [4, 0, 1, 3, 2]) fname = "ghz_to_gate.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_scale(self): """Tests scale See: https://github.com/Qiskit/qiskit-terra/issues/4179""" circuit = QuantumCircuit(5) circuit.unitary(random_unitary(2**5), circuit.qubits) fname = "scale_default.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "scale_half.png" self.circuit_drawer(circuit, filename=fname2, scale=0.5) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname3 = "scale_double.png" self.circuit_drawer(circuit, filename=fname3, scale=2) ratio3 = VisualTestUtilities._save_diff( self._image_path(fname3), self._reference_path(fname3), fname3, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) self.assertGreaterEqual(ratio3, 0.9999) def test_pi_param_expr(self): """Test pi in circuit with parameter expression.""" x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(1) circuit.rx((pi - x) * (pi - y), 0) fname = "pi_in_param_expr.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_partial_layout(self): """Tests partial_layout See: https://github.com/Qiskit/qiskit-terra/issues/4757""" circuit = QuantumCircuit(3) circuit.h(1) transpiled = transpile( circuit, backend=FakeTenerife(), basis_gates=["id", "cx", "rz", "sx", "x"], optimization_level=0, initial_layout=[1, 2, 0], seed_transpiler=0, ) fname = "partial_layout.png" self.circuit_drawer(transpiled, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_init_reset(self): """Test reset and initialize with 1 and 2 qubits""" circuit = QuantumCircuit(2) circuit.initialize([0, 1], 0) circuit.reset(1) circuit.initialize([0, 1, 0, 0], [0, 1]) fname = "init_reset.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_with_global_phase(self): """Tests with global phase""" circuit = QuantumCircuit(3, global_phase=1.57079632679) circuit.h(range(3)) fname = "global_phase.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_alternative_colors(self): """Tests alternative color schemes""" ratios = [] for style in ["iqx", "iqx-dark", "textbook"]: with self.subTest(style=style): circuit = QuantumCircuit(7) circuit.h(0) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.swap(0, 1) circuit.cswap(0, 1, 2) circuit.append(SwapGate().control(2), [0, 1, 2, 3]) circuit.dcx(0, 1) circuit.append(DCXGate().control(1), [0, 1, 2]) circuit.append(DCXGate().control(2), [0, 1, 2, 3]) circuit.z(4) circuit.s(4) circuit.sdg(4) circuit.t(4) circuit.tdg(4) circuit.p(pi / 2, 4) circuit.cz(5, 6) circuit.cp(pi / 2, 5, 6) circuit.y(5) circuit.rx(pi / 3, 5) circuit.rzx(pi / 2, 5, 6) circuit.u(pi / 2, pi / 2, pi / 2, 5) circuit.barrier(5, 6) circuit.reset(5) fname = f"{style}_color.png" self.circuit_drawer(circuit, style={"name": style}, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) ratios.append(ratio) for ratio in ratios: self.assertGreaterEqual(ratio, 0.9999) def test_reverse_bits(self): """Tests reverse_bits parameter""" circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) circuit.ccx(2, 1, 0) fname = "reverse_bits.png" self.circuit_drawer(circuit, reverse_bits=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_bw(self): """Tests black and white style parameter""" circuit = QuantumCircuit(3, 3) circuit.h(0) circuit.x(1) circuit.sdg(2) circuit.cx(0, 1) circuit.ccx(2, 1, 0) circuit.swap(1, 2) circuit.measure_all() fname = "bw.png" self.circuit_drawer(circuit, style={"name": "bw"}, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_user_style(self): """Tests loading a user style""" circuit = QuantumCircuit(7) circuit.h(0) circuit.append(HGate(label="H2"), [1]) circuit.x(0) circuit.cx(0, 1) circuit.ccx(0, 1, 2) circuit.swap(0, 1) circuit.cswap(0, 1, 2) circuit.append(SwapGate().control(2), [0, 1, 2, 3]) circuit.dcx(0, 1) circuit.append(DCXGate().control(1), [0, 1, 2]) circuit.append(DCXGate().control(2), [0, 1, 2, 3]) circuit.z(4) circuit.append(SGate(label="S1"), [4]) circuit.sdg(4) circuit.t(4) circuit.tdg(4) circuit.p(pi / 2, 4) circuit.cz(5, 6) circuit.cp(pi / 2, 5, 6) circuit.y(5) circuit.rx(pi / 3, 5) circuit.rzx(pi / 2, 5, 6) circuit.u(pi / 2, pi / 2, pi / 2, 5) circuit.barrier(5, 6) circuit.reset(5) fname = "user_style.png" self.circuit_drawer( circuit, style={ "name": "user_style", "displaytext": {"H2": "H_2"}, "displaycolor": {"H2": ("#EEDD00", "#FF0000")}, }, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_subfont_change(self): """Tests changing the subfont size""" circuit = QuantumCircuit(3) circuit.h(0) circuit.x(0) circuit.u(pi / 2, pi / 2, pi / 2, 1) circuit.p(pi / 2, 2) style = {"name": "iqx", "subfontsize": 11} fname = "subfont.png" self.circuit_drawer(circuit, style=style, filename=fname) self.assertEqual(style, {"name": "iqx", "subfontsize": 11}) # check does not change style ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_meas_condition(self): """Tests measure with a condition""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[0]) circuit.h(qr[1]).c_if(cr, 1) fname = "meas_condition.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_reverse_bits_condition(self): """Tests reverse_bits with a condition and gate above""" cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(1, "cr2") qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(1) circuit.h(2) circuit.x(0) circuit.x(0) circuit.measure(2, 1) circuit.x(2).c_if(cr, 2) fname = "reverse_bits_cond_true.png" self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "reverse_bits_cond_false.png" self.circuit_drawer(circuit, cregbundle=False, reverse_bits=False, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_style_custom_gates(self): """Tests style for custom gates""" def cnotnot(gate_label): gate_circuit = QuantumCircuit(3, name=gate_label) gate_circuit.cnot(0, 1) gate_circuit.cnot(0, 2) gate = gate_circuit.to_gate() return gate q = QuantumRegister(3, name="q") circuit = QuantumCircuit(q) circuit.append(cnotnot("CNOTNOT"), [q[0], q[1], q[2]]) circuit.append(cnotnot("CNOTNOT_PRIME"), [q[0], q[1], q[2]]) circuit.h(q[0]) fname = "style_custom_gates.png" self.circuit_drawer( circuit, style={ "displaycolor": {"CNOTNOT": ("#000000", "#FFFFFF"), "h": ("#A1A1A1", "#043812")}, "displaytext": {"CNOTNOT_PRIME": "$\\mathrm{CNOTNOT}'$"}, }, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_6095(self): """Tests controlled-phase gate style See https://github.com/Qiskit/qiskit-terra/issues/6095""" circuit = QuantumCircuit(2) circuit.cp(1.0, 0, 1) circuit.h(1) fname = "6095.png" self.circuit_drawer( circuit, style={"displaycolor": {"cp": ("#A27486", "#000000"), "h": ("#A27486", "#000000")}}, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_1q_1c(self): """Tests q0-cr0 instruction on a circuit""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) inst = QuantumCircuit(1, 1, name="Inst").to_instruction() circuit.append(inst, [qr[0]], [cr[0]]) fname = "instruction_1q_1c.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_3q_3c_circ1(self): """Tests q0-q1-q2-cr_20-cr0-cr1 instruction on a circuit""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr, cr2) inst = QuantumCircuit(3, 3, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1], qr[2]], [cr2[0], cr[0], cr[1]]) fname = "instruction_3q_3c_circ1.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_3q_3c_circ2(self): """Tests q3-q0-q2-cr0-cr1-cr_20 instruction on a circuit""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr, cr2) inst = QuantumCircuit(3, 3, name="Inst").to_instruction() circuit.append(inst, [qr[3], qr[0], qr[2]], [cr[0], cr[1], cr2[0]]) fname = "instruction_3q_3c_circ2.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_instruction_3q_3c_circ3(self): """Tests q3-q1-q2-cr_31-cr1-cr_30 instruction on a circuit""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(2, "cr") cr2 = ClassicalRegister(1, "cr2") cr3 = ClassicalRegister(2, "cr3") circuit = QuantumCircuit(qr, cr, cr2, cr3) inst = QuantumCircuit(3, 3, name="Inst").to_instruction() circuit.append(inst, [qr[3], qr[1], qr[2]], [cr3[1], cr[1], cr3[0]]) fname = "instruction_3q_3c_circ3.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_overwide_gates(self): """Test gates don't exceed width of default fold""" circuit = QuantumCircuit(5) initial_state = np.zeros(2**5) initial_state[5] = 1 circuit.initialize(initial_state) fname = "wide_params.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_one_bit_regs(self): """Test registers with only one bit display without number""" qr1 = QuantumRegister(1, "qr1") qr2 = QuantumRegister(2, "qr2") cr1 = ClassicalRegister(1, "cr1") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.h(0) circuit.measure(0, 0) fname = "one_bit_regs.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_user_ax_subplot(self): """Test for when user supplies ax for a subplot""" import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(6, 4)) fig.patch.set_facecolor("white") ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) ax1.plot([1, 2, 3]) circuit = QuantumCircuit(4) circuit.h(0) circuit.cx(0, 1) circuit.h(1) circuit.cx(1, 2) plt.close(fig) fname = "user_ax.png" self.circuit_drawer(circuit, ax=ax2, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_figwidth(self): """Test style dict 'figwidth'""" circuit = QuantumCircuit(3) circuit.h(0) circuit.cx(0, 1) circuit.x(1) circuit.cx(1, 2) circuit.x(2) fname = "figwidth.png" self.circuit_drawer(circuit, style={"figwidth": 5}, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_registerless_one_bit(self): """Test circuit with one-bit registers and registerless bits.""" qrx = QuantumRegister(2, "qrx") qry = QuantumRegister(1, "qry") crx = ClassicalRegister(2, "crx") circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx) fname = "registerless_one_bit.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_measures_with_conditions(self): """Test that a measure containing a condition displays""" qr = QuantumRegister(2, "qr") cr1 = ClassicalRegister(2, "cr1") cr2 = ClassicalRegister(2, "cr2") circuit = QuantumCircuit(qr, cr1, cr2) circuit.h(0) circuit.h(1) circuit.measure(0, cr1[1]) circuit.measure(1, cr2[0]).c_if(cr1, 1) circuit.h(0).c_if(cr2, 3) fname = "measure_cond_false.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "measure_cond_true.png" self.circuit_drawer(circuit, cregbundle=True, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_conditions_measures_with_bits(self): """Test that gates with conditions and measures work with bits""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(crx[1], 0) circuit.measure(0, bits[3]) fname = "measure_cond_bits_false.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) fname2 = "measure_cond_bits_true.png" self.circuit_drawer(circuit, cregbundle=True, filename=fname2) ratio2 = VisualTestUtilities._save_diff( self._image_path(fname2), self._reference_path(fname2), fname2, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) self.assertGreaterEqual(ratio2, 0.9999) def test_conditional_gates_right_of_measures_with_bits(self): """Test that gates with conditions draw to right of measures when same bit""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.measure(qr[0], cr[1]) circuit.h(qr[1]).c_if(cr[1], 0) circuit.h(qr[2]).c_if(cr[0], 0) fname = "measure_cond_bits_right.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_conditions_with_bits_reverse(self): """Test that gates with conditions work with bits reversed""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(2, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(bits[3], 0) fname = "cond_bits_reverse.png" self.circuit_drawer(circuit, cregbundle=False, reverse_bits=True, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_sidetext_with_condition(self): """Test that sidetext gates align properly with conditions""" qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") circuit = QuantumCircuit(qr, cr) circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) fname = "sidetext_condition.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_fold_with_conditions(self): """Test that gates with conditions draw correctly when folding""" qr = QuantumRegister(3) cr = ClassicalRegister(5) circuit = QuantumCircuit(qr, cr) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 1) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 3) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 5) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 7) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 9) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 11) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 13) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 15) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 17) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 19) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 21) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 23) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 25) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 27) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 29) circuit.append(U1Gate(0).control(1), [1, 0]).c_if(cr, 31) fname = "fold_with_conditions.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_idle_wires_barrier(self): """Test that idle_wires False works with barrier""" circuit = QuantumCircuit(4, 4) circuit.x(2) circuit.barrier() fname = "idle_wires_barrier.png" self.circuit_drawer(circuit, cregbundle=False, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_wire_order(self): """Test the wire_order option""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "cx") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 10) fname = "wire_order.png" self.circuit_drawer( circuit, cregbundle=False, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7], filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_barrier_label(self): """Test the barrier label""" circuit = QuantumCircuit(2) circuit.x(0) circuit.y(1) circuit.barrier() circuit.y(0) circuit.x(1) circuit.barrier(label="End Y/X") fname = "barrier_label.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_op(self): """Test the IfElseOp with if only""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.cx(0, 1) fname = "if_op.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op(self): """Test the IfElseOp with else""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) with circuit.if_test((cr[1], 1)) as _else: circuit.h(0) circuit.cx(0, 1) with _else: circuit.cx(0, 1) fname = "if_else_op.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_textbook_style(self): """Test the IfElseOp with else in textbook style""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) with circuit.if_test((cr[1], 1)) as _else: circuit.h(0) circuit.cx(0, 1) with _else: circuit.cx(0, 1) fname = "if_else_op_textbook.png" self.circuit_drawer(circuit, style="textbook", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_with_body(self): """Test the IfElseOp with adding a body manually""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) circuit.h(1) circuit.measure(0, 1) circuit.measure(1, 2) circuit.x(2) circuit.x(2, label="XLabel").c_if(cr, 2) qr2 = QuantumRegister(3, "qr2") qc2 = QuantumCircuit(qr2, cr) qc2.x(1) qc2.y(1) qc2.z(0) qc2.x(0, label="X1i").c_if(cr, 4) circuit.if_else((cr[1], 1), qc2, None, [0, 1, 2], [0, 1, 2]) circuit.x(0, label="X1i") fname = "if_else_body.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_nested(self): """Test the IfElseOp with complex nested if/else""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) with circuit.if_test((cr[1], 1)) as _else: circuit.x(0, label="X c_if").c_if(cr, 4) with circuit.if_test((cr[2], 1)): circuit.z(0) circuit.y(1) with circuit.if_test((cr[1], 1)): circuit.y(1) circuit.z(2) with circuit.if_test((cr[2], 1)): circuit.cx(0, 1) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.x(1) with _else: circuit.y(1) with circuit.if_test((cr[2], 1)): circuit.x(0) circuit.x(1) inst = QuantumCircuit(2, 2, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]]) circuit.x(0) fname = "if_else_op_nested.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_wire_order(self): """Test the IfElseOp with complex nested if/else and wire_order""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) with circuit.if_test((cr[1], 1)) as _else: circuit.x(0, label="X c_if").c_if(cr, 4) with circuit.if_test((cr[2], 1)): circuit.z(0) circuit.y(1) with circuit.if_test((cr[1], 1)): circuit.y(1) circuit.z(2) with circuit.if_test((cr[2], 1)): circuit.cx(0, 1) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.x(1) with _else: circuit.y(1) with circuit.if_test((cr[2], 1)): circuit.x(0) circuit.x(1) inst = QuantumCircuit(2, 2, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]]) circuit.x(0) fname = "if_else_op_wire_order.png" self.circuit_drawer(circuit, wire_order=[2, 0, 3, 1, 4, 5, 6], filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_if_else_op_fold(self): """Test the IfElseOp with complex nested if/else and fold""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) with circuit.if_test((cr[1], 1)) as _else: circuit.x(0, label="X c_if").c_if(cr, 4) with circuit.if_test((cr[2], 1)): circuit.z(0) circuit.y(1) with circuit.if_test((cr[1], 1)): circuit.y(1) circuit.z(2) with circuit.if_test((cr[2], 1)): circuit.cx(0, 1) with circuit.if_test((cr[1], 1)): circuit.h(0) circuit.x(1) with _else: circuit.y(1) with circuit.if_test((cr[2], 1)): circuit.x(0) circuit.x(1) inst = QuantumCircuit(2, 2, name="Inst").to_instruction() circuit.append(inst, [qr[0], qr[1]], [cr[0], cr[1]]) circuit.x(0) fname = "if_else_op_fold.png" self.circuit_drawer(circuit, fold=7, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_while_loop_op(self): """Test the WhileLoopOp""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(0) circuit.measure(0, 2) with circuit.while_loop((cr[0], 0)): circuit.h(0) circuit.cx(0, 1) circuit.measure(0, 0) with circuit.if_test((cr[2], 1)): circuit.x(0) fname = "while_loop.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_for_loop_op(self): """Test the ForLoopOp""" qr = QuantumRegister(4, "q") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) a = Parameter("a") circuit.h(0) circuit.measure(0, 2) with circuit.for_loop((2, 4, 8, 16), loop_parameter=a): circuit.h(0) circuit.cx(0, 1) circuit.rx(pi / a, 1) circuit.measure(0, 0) with circuit.if_test((cr[2], 1)): circuit.z(0) fname = "for_loop.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) def test_switch_case_op(self): """Test the SwitchCaseOp""" qreg = QuantumRegister(3, "q") creg = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qreg, creg) circuit.h([0, 1, 2]) circuit.measure([0, 1, 2], [0, 1, 2]) with circuit.switch(creg) as case: with case(0, 1, 2): circuit.x(0) with case(3, 4, 5): circuit.y(1) circuit.y(0) circuit.y(0) with case(case.DEFAULT): circuit.cx(0, 1) circuit.h(0) fname = "switch_case.png" self.circuit_drawer(circuit, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.9999) if __name__ == "__main__": unittest.main(verbosity=1)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for graph MPL drawer""" import unittest import os from test.visual import VisualTestUtilities from contextlib import contextmanager from pathlib import Path from qiskit import BasicAer, execute from qiskit.test import QiskitTestCase from qiskit import QuantumCircuit from qiskit.utils import optionals from qiskit.visualization.state_visualization import state_drawer from qiskit.visualization.counts_visualization import plot_histogram from qiskit.visualization.gate_map import plot_gate_map, plot_coupling_map from qiskit.providers.fake_provider import ( FakeArmonk, FakeBelem, FakeCasablanca, FakeRueschlikon, FakeMumbai, FakeManhattan, ) if optionals.HAS_MATPLOTLIB: from matplotlib.pyplot import close as mpl_close else: raise ImportError('Must have Matplotlib installed. To install, run "pip install matplotlib".') BASE_DIR = Path(__file__).parent RESULT_DIR = Path(BASE_DIR) / "graph_results" TEST_REFERENCE_DIR = Path(BASE_DIR) / "references" FAILURE_DIFF_DIR = Path(BASE_DIR).parent / "visual_test_failures" FAILURE_PREFIX = "graph_failure_" @contextmanager def cwd(path): """A context manager to run in a particular path""" oldpwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(oldpwd) class TestGraphMatplotlibDrawer(QiskitTestCase): """Graph MPL visualization""" def setUp(self): super().setUp() self.graph_state_drawer = VisualTestUtilities.save_data_wrap( state_drawer, str(self), RESULT_DIR ) self.graph_count_drawer = VisualTestUtilities.save_data_wrap( plot_histogram, str(self), RESULT_DIR ) self.graph_plot_gate_map = VisualTestUtilities.save_data_wrap( plot_gate_map, str(self), RESULT_DIR ) self.graph_plot_coupling_map = VisualTestUtilities.save_data_wrap( plot_coupling_map, str(self), RESULT_DIR ) if not os.path.exists(FAILURE_DIFF_DIR): os.makedirs(FAILURE_DIFF_DIR) if not os.path.exists(RESULT_DIR): os.makedirs(RESULT_DIR) def tearDown(self): super().tearDown() mpl_close("all") @staticmethod def _image_path(image_name): return os.path.join(RESULT_DIR, image_name) @staticmethod def _reference_path(image_name): return os.path.join(TEST_REFERENCE_DIR, image_name) def test_plot_bloch_multivector(self): """test bloch sphere See https://github.com/Qiskit/qiskit-terra/issues/6397. """ circuit = QuantumCircuit(1) circuit.h(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "bloch_multivector.png" self.graph_state_drawer(state=state, output="bloch", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_hinton(self): """test plot_state_hinton""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "hinton.png" self.graph_state_drawer(state=state, output="hinton", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_qsphere(self): """test for plot_state_qsphere""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "qsphere.png" self.graph_state_drawer(state=state, output="qsphere", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_city(self): """test for plot_state_city""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "state_city.png" self.graph_state_drawer(state=state, output="city", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_state_paulivec(self): """test for plot_state_paulivec""" circuit = QuantumCircuit(1) circuit.x(0) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "paulivec.png" self.graph_state_drawer(state=state, output="paulivec", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram(self): """for testing the plot_histogram""" # specifing counts because we do not want oscillation of # result until a changes is made to plot_histogram counts = {"11": 500, "00": 500} fname = "histogram.png" self.graph_count_drawer(counts, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_with_rest(self): """test plot_histogram with 2 datasets and number_to_keep""" data = [{"00": 3, "01": 5, "10": 6, "11": 12}] fname = "histogram_with_rest.png" self.graph_count_drawer(data, number_to_keep=2, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_2_sets_with_rest(self): """test plot_histogram with 2 datasets and number_to_keep""" data = [ {"00": 3, "01": 5, "10": 6, "11": 12}, {"00": 5, "01": 7, "10": 6, "11": 12}, ] fname = "histogram_2_sets_with_rest.png" self.graph_count_drawer(data, number_to_keep=2, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_color(self): """Test histogram with single color""" counts = {"00": 500, "11": 500} fname = "histogram_color.png" self.graph_count_drawer(data=counts, color="#204940", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_multiple_colors(self): """Test histogram with multiple custom colors""" counts = [ {"00": 10, "01": 15, "10": 20, "11": 25}, {"00": 25, "01": 20, "10": 15, "11": 10}, ] fname = "histogram_multiple_colors.png" self.graph_count_drawer( data=counts, color=["#204940", "#c26219"], filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_hamming(self): """Test histogram with hamming distance""" counts = {"101": 500, "010": 500, "001": 500, "100": 500} fname = "histogram_hamming.png" self.graph_count_drawer(data=counts, sort="hamming", target_string="101", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_value_sort(self): """Test histogram with sorting by value""" counts = {"101": 300, "010": 240, "001": 80, "100": 150, "110": 160, "000": 280, "111": 60} fname = "histogram_value_sort.png" self.graph_count_drawer(data=counts, sort="value", target_string="000", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_desc_value_sort(self): """Test histogram with sorting by descending value""" counts = {"101": 150, "010": 50, "001": 180, "100": 10, "110": 190, "000": 80, "111": 260} fname = "histogram_desc_value_sort.png" self.graph_count_drawer( data=counts, sort="value_desc", target_string="000", filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_legend(self): """Test histogram with legend""" counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}] fname = "histogram_legend.png" self.graph_count_drawer( data=counts, legend=["first", "second"], filename=fname, figsize=(15, 5), ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_histogram_title(self): """Test histogram with title""" counts = [{"0": 50, "1": 30}, {"0": 30, "1": 40}] fname = "histogram_title.png" self.graph_count_drawer(data=counts, title="My Histogram", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_1_qubit_gate_map(self): """Test plot_gate_map using 1 qubit backend""" # getting the mock backend from FakeProvider backend = FakeArmonk() fname = "1_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_5_qubit_gate_map(self): """Test plot_gate_map using 5 qubit backend""" # getting the mock backend from FakeProvider backend = FakeBelem() fname = "5_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_7_qubit_gate_map(self): """Test plot_gate_map using 7 qubit backend""" # getting the mock backend from FakeProvider backend = FakeCasablanca() fname = "7_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_16_qubit_gate_map(self): """Test plot_gate_map using 16 qubit backend""" # getting the mock backend from FakeProvider backend = FakeRueschlikon() fname = "16_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_27_qubit_gate_map(self): """Test plot_gate_map using 27 qubit backend""" # getting the mock backend from FakeProvider backend = FakeMumbai() fname = "27_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_65_qubit_gate_map(self): """test for plot_gate_map using 65 qubit backend""" # getting the mock backend from FakeProvider backend = FakeManhattan() fname = "65_qubit_gate_map.png" self.graph_plot_gate_map(backend=backend, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_figsize(self): """Test figsize parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeBelem() fname = "figsize.png" self.graph_plot_gate_map(backend=backend, figsize=(10, 10), filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_qubit_size(self): """Test qubit_size parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeBelem() fname = "qubit_size.png" self.graph_plot_gate_map(backend=backend, qubit_size=38, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_qubit_color(self): """Test qubit_color parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeCasablanca() fname = "qubit_color.png" self.graph_plot_gate_map(backend=backend, qubit_color=["#ff0000"] * 7, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_qubit_labels(self): """Test qubit_labels parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeCasablanca() fname = "qubit_labels.png" self.graph_plot_gate_map( backend=backend, qubit_labels=list(range(10, 17, 1)), filename=fname ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_line_color(self): """Test line_color parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeManhattan() fname = "line_color.png" self.graph_plot_gate_map(backend=backend, line_color=["#00ff00"] * 144, filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_font_color(self): """Test font_color parameter of plot_gate_map""" # getting the mock backend from FakeProvider backend = FakeManhattan() fname = "font_color.png" self.graph_plot_gate_map(backend=backend, font_color="#ff00ff", filename=fname) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_coupling_map(self): """Test plot_coupling_map""" num_qubits = 5 qubit_coordinates = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] coupling_map = [[1, 0], [1, 2], [1, 3], [3, 4]] fname = "coupling_map.png" self.graph_plot_coupling_map( num_qubits=num_qubits, qubit_coordinates=qubit_coordinates, coupling_map=coupling_map, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) def test_plot_bloch_multivector_figsize_improvements(self): """test bloch sphere figsize, font_size, title_font_size and title_pad See https://github.com/Qiskit/qiskit-terra/issues/7263 and https://github.com/Qiskit/qiskit-terra/pull/7264. """ circuit = QuantumCircuit(3) circuit.h(1) circuit.sxdg(2) # getting the state using backend backend = BasicAer.get_backend("statevector_simulator") result = execute(circuit, backend).result() state = result.get_statevector(circuit) fname = "bloch_multivector_figsize_improvements.png" self.graph_state_drawer( state=state, output="bloch", figsize=(3, 2), font_size=10, title="|0+R> state", title_font_size=14, title_pad=8, filename=fname, ) ratio = VisualTestUtilities._save_diff( self._image_path(fname), self._reference_path(fname), fname, FAILURE_DIFF_DIR, FAILURE_PREFIX, ) self.assertGreaterEqual(ratio, 0.99) if __name__ == "__main__": unittest.main(verbosity=1)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2023. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Determines a commutation library over the unparameterizable standard gates, i.e. a dictionary for each pair of parameterizable standard gates and all qubit overlaps that maps to either True or False, depending on the present commutation relation. """ import itertools from functools import lru_cache from typing import List from qiskit.circuit.commutation_checker import _get_relative_placement, _order_operations from qiskit.circuit import Gate, CommutationChecker import qiskit.circuit.library.standard_gates as stdg from qiskit.dagcircuit import DAGOpNode @lru_cache(None) def _get_unparameterizable_gates() -> List[Gate]: """Retrieve a list of non-parmaterized gates with up to 3 qubits, using the python inspection module Return: A list of non-parameterized gates to be considered in the commutation library """ # These two gates may require a large runtime in later processing steps # blocked_types = [C3SXGate, C4XGate] gates = list(stdg.get_standard_gate_name_mapping().values()) return [g for g in gates if len(g.params) == 0] def _generate_commutation_dict(considered_gates: List[Gate] = None) -> dict: """Compute the commutation relation of considered gates Args: considered_gates List[Gate]: a list of gates between which the commutation should be determined Return: A dictionary that includes the commutation relation for each considered pair of operations and each relative placement """ commutations = {} cc = CommutationChecker() for gate0 in considered_gates: node0 = DAGOpNode(op=gate0, qargs=list(range(gate0.num_qubits)), cargs=[]) for gate1 in considered_gates: # only consider canonical entries ( ( first_gate, _, _, ), (second_gate, _, _), ) = _order_operations(gate0, None, None, gate1, None, None) if (first_gate, second_gate) != (gate0, gate1) and gate0.name != gate1.name: continue # enumerate all relative gate placements with overlap between gate qubits gate_placements = itertools.permutations( range(gate0.num_qubits + gate1.num_qubits - 1), gate0.num_qubits ) gate_pair_commutation = {} for permutation in gate_placements: permutation_list = list(permutation) gate1_qargs = [] # use idx_non_overlapping qubits to represent qubits on g1 that are not connected to g0 next_non_overlapping_qubit_idx = gate0.num_qubits for i in range(gate1.num_qubits): if i in permutation_list: gate1_qargs.append(permutation_list.index(i)) else: gate1_qargs.append(next_non_overlapping_qubit_idx) next_non_overlapping_qubit_idx += 1 node1 = DAGOpNode(op=gate1, qargs=gate1_qargs, cargs=[]) # replace non-overlapping qubits with None to act as a key in the commutation library relative_placement = _get_relative_placement(node0.qargs, node1.qargs) if not gate0.is_parameterized() and not gate1.is_parameterized(): # if no gate includes parameters, compute commutation relation using # matrix multiplication op1 = node0.op qargs1 = node0.qargs cargs1 = node0.cargs op2 = node1.op qargs2 = node1.qargs cargs2 = node1.cargs commutation_relation = cc.commute( op1, qargs1, cargs1, op2, qargs2, cargs2, max_num_qubits=4 ) else: pass # TODO gate_pair_commutation[relative_placement] = commutation_relation commutations[gate0.name, gate1.name] = gate_pair_commutation return commutations def _simplify_commuting_dict(commuting_dict: dict) -> dict: """Compress some of the commutation library entries Args: commuting_dict (dict): A commutation dictionary Return: commuting_dict (dict): A commutation dictionary with simplified entries """ # Remove relative placement key if commutation is independent of relative placement for ops in commuting_dict.keys(): gates_commutations = set(commuting_dict[ops].values()) if len(gates_commutations) == 1: commuting_dict[ops] = next(iter(gates_commutations)) return commuting_dict def _dump_commuting_dict_as_python( commutations: dict, file_name: str = "../_standard_gates_commutations.py" ): """Write commutation dictionary as python object to ./qiskit/circuit/_standard_gates_commutations.py. Args: commutations (dict): a dictionary that includes the commutation relation for each considered pair of operations """ with open(file_name, "w") as fp: dir_str = "standard_gates_commutations = {\n" for k, v in commutations.items(): if not isinstance(v, dict): dir_str += ' ("{}", "{}"): {},\n'.format(*k, v) else: dir_str += ' ("{}", "{}"): {{\n'.format(*k) for entry_key, entry_val in v.items(): dir_str += " {}: {},\n".format(entry_key, entry_val) dir_str += " },\n" dir_str += "}\n" fp.write(dir_str.replace("'", "")) if __name__ == "__main__": cgates = [ g for g in _get_unparameterizable_gates() if g.name not in ["reset", "measure", "delay"] ] commutation_dict = _generate_commutation_dict(considered_gates=cgates) commutation_dict = _simplify_commuting_dict(commutation_dict) _dump_commuting_dict_as_python(commutation_dict)
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
#!/usr/bin/env python3 # 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. """Utility to check that slow imports are not used in the default path.""" import subprocess import sys # This is not unused: importing it sets up sys.modules import qiskit # pylint: disable=unused-import def _main(): optional_imports = [ "networkx", "sympy", "pydot", "pygments", "ipywidgets", "scipy.stats", "matplotlib", "qiskit.providers.aer", "qiskit.providers.ibmq", "qiskit.ignis", "qiskit.aqua", "docplex", ] modules_imported = [] for mod in optional_imports: if mod in sys.modules: modules_imported.append(mod) if not modules_imported: sys.exit(0) res = subprocess.run( [sys.executable, "-X", "importtime", "-c", "import qiskit"], capture_output=True, encoding="utf8", check=True, ) import_tree = [ x.split("|")[-1] for x in res.stderr.split("\n") if "RuntimeWarning" not in x or "warnings.warn" not in x ] indent = -1 matched_module = None for module in import_tree: line_indent = len(module) - len(module.lstrip()) module_name = module.strip() if module_name in modules_imported: if indent > 0: continue indent = line_indent matched_module = module_name if indent > 0: if line_indent < indent: print(f"ERROR: {matched_module} is imported via {module_name}") indent = -1 matched_module = None sys.exit(len(modules_imported)) if __name__ == "__main__": _main()
https://github.com/miamico/Quantum_Generative_Adversarial_Networks
miamico
"""Simple example on how to log scalars and images to tensorboard without tensor ops. License: Copyleft """ __author__ = "Michael Gygli" import tensorflow as tf # from StringIO import StringIO import matplotlib.pyplot as plt import numpy as np class Logger(object): """Logging in tensorboard without tensorflow ops.""" def __init__(self, log_dir): """Creates a summary writer logging to log_dir.""" self.writer = tf.summary.FileWriter(log_dir) def log_scalar(self, tag, value, step): """Log a scalar variable. Parameter ---------- tag : basestring Name of the scalar value step : int training iteration """ summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)]) self.writer.add_summary(summary, step) def log_images(self, tag, images, step): """Logs a list of images.""" im_summaries = [] for nr, img in enumerate(images): # Write the image to a string s = StringIO() plt.imsave(s, img, format='png') # Create an Image object img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=img.shape[0], width=img.shape[1]) # Create a Summary value im_summaries.append(tf.Summary.Value(tag='%s/%d' % (tag, nr), image=img_sum)) # Create and write Summary summary = tf.Summary(value=im_summaries) self.writer.add_summary(summary, step) def log_histogram(self, tag, values, step, bins=1000): """Logs the histogram of a list/vector of values.""" # Convert to a numpy array values = np.array(values) # Create histogram using numpy counts, bin_edges = np.histogram(values, bins=bins) # Fill fields of histogram proto hist = tf.HistogramProto() hist.min = float(np.min(values)) hist.max = float(np.max(values)) hist.num = int(np.prod(values.shape)) hist.sum = float(np.sum(values)) hist.sum_squares = float(np.sum(values ** 2)) # Requires equal number as bins, where the first goes from -DBL_MAX to bin_edges[1] # See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/summary.proto#L30 # Thus, we drop the start of the first bin bin_edges = bin_edges[1:] # Add bin edges and counts for edge in bin_edges: hist.bucket_limit.append(edge) for c in counts: hist.bucket.append(c) # Create and write Summary summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=hist)]) self.writer.add_summary(summary, step) self.writer.flush()
https://github.com/miamico/Quantum_Generative_Adversarial_Networks
miamico
%%capture %pip install qiskit %pip install qiskit_ibm_provider %pip install qiskit-aer # Importing standard Qiskit libraries from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer from qiskit_ibm_provider import IBMProvider from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit.circuit.library import C3XGate # Importing matplotlib import matplotlib.pyplot as plt # Importing Numpy, Cmath and math import numpy as np import os, math, cmath from numpy import pi # Other imports from IPython.display import display, Math, Latex # Specify the path to your env file env_file_path = 'config.env' # Load environment variables from the file os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#')) # Load IBM Provider API KEY IBMP_API_KEY = os.environ.get('IBMP_API_KEY') # Loading your IBM Quantum account(s) IBMProvider.save_account(IBMP_API_KEY, overwrite=True) # Run the quantum circuit on a statevector simulator backend backend = Aer.get_backend('statevector_simulator') qc_b1 = QuantumCircuit(2, 2) qc_b1.h(0) qc_b1.cx(0, 1) qc_b1.draw(output='mpl', style="iqp") sv = backend.run(qc_b1).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.x(0) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b2 = QuantumCircuit(2, 2) qc_b2.h(0) qc_b2.cx(0, 1) qc_b2.z(0) qc_b2.draw(output='mpl', style="iqp") sv = backend.run(qc_b2).result().get_statevector() sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.x(1) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b3 = QuantumCircuit(2, 2) qc_b3.h(0) qc_b3.cx(0, 1) qc_b3.x(0) qc_b3.draw(output='mpl', style="iqp") sv = backend.run(qc_b3).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.x(0) qc_b4.h(0) qc_b4.x(1) qc_b4.cx(0, 1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") qc_b4 = QuantumCircuit(2, 2) qc_b4.h(0) qc_b4.cx(0, 1) qc_b4.x(0) qc_b4.z(1) qc_b4.draw(output='mpl', style="iqp") sv = backend.run(qc_b4).result().get_statevector() sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ") def sv_latex_from_qc(qc, backend): sv = backend.run(qc).result().get_statevector() return sv.draw(output='latex') qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(0) qc_ej2.x(1) qc_ej2.x(2) sv_latex_from_qc(qc_ej2, backend) qc_ej2 = QuantumCircuit(4, 4) qc_ej2.x(3) sv_latex_from_qc(qc_ej2, backend) def circuit_adder (num): if num<1 or num>8: raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricción sería directo. # Definición del circuito base que vamos a construir qreg_q = QuantumRegister(4, 'q') creg_c = ClassicalRegister(1, 'c') circuit = QuantumCircuit(qreg_q, creg_c) qbit_position = 0 for element in reversed(np.binary_repr(num)): if (element=='1'): circuit.barrier() match qbit_position: case 0: # +1 circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]]) circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) circuit.x(qreg_q[0]) case 1: # +2 circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3]) circuit.cx(qreg_q[1], qreg_q[2]) circuit.x(qreg_q[1]) case 2: # +4 circuit.cx(qreg_q[2], qreg_q[3]) circuit.x(qreg_q[2]) case 3: # +8 circuit.x(qreg_q[3]) qbit_position+=1 return circuit add_3 = circuit_adder(3) add_3.draw(output='mpl', style="iqp") qc_test_2 = QuantumCircuit(4, 4) qc_test_2.x(1) qc_test_2_plus_3 = qc_test_2.compose(add_3) qc_test_2_plus_3.draw(output='mpl', style="iqp") sv_latex_from_qc(qc_test_2_plus_3, backend) qc_test_7 = QuantumCircuit(4, 4) qc_test_7.x(0) qc_test_7.x(1) qc_test_7.x(2) qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8)) sv_latex_from_qc(qc_test_7_plus_8, backend) #qc_test_7_plus_8.draw() theta = 6.544985 phi = 2.338741 lmbda = 0 alice_1 = 0 alice_2 = 1 bob_1 = 2 qr_alice = QuantumRegister(2, 'Alice') qr_bob = QuantumRegister(1, 'Bob') cr = ClassicalRegister(3, 'c') qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr) qc_ej3.barrier(label='1') qc_ej3.u(theta, phi, lmbda, alice_1); qc_ej3.barrier(label='2') qc_ej3.h(alice_2) qc_ej3.cx(alice_2, bob_1); qc_ej3.barrier(label='3') qc_ej3.cx(alice_1, alice_2) qc_ej3.h(alice_1); qc_ej3.barrier(label='4') qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]); qc_ej3.barrier(label='5') qc_ej3.x(bob_1).c_if(alice_2, 1) qc_ej3.z(bob_1).c_if(alice_1, 1) qc_ej3.measure(bob_1, bob_1); qc_ej3.draw(output='mpl', style="iqp") result = backend.run(qc_ej3, shots=1024).result() counts = result.get_counts() plot_histogram(counts) sv_0 = np.array([1, 0]) sv_1 = np.array([0, 1]) def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/√2'}, tolerance=1e-10): """ Check if the given numerical value corresponds to a symbolic constant within a specified tolerance. Parameters: - value (float): The numerical value to check. - symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations. Defaults to {1/np.sqrt(2): '1/√2'}. - tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10. Returns: str or float: If a match is found, returns the symbolic representation as a string (prefixed with '-' if the value is negative); otherwise, returns the original value. """ for constant, symbol in symbolic_constants.items(): if np.isclose(abs(value), constant, atol=tolerance): return symbol if value >= 0 else '-' + symbol return value def array_to_dirac_notation(array, tolerance=1e-10): """ Convert a complex-valued array representing a quantum state in superposition to Dirac notation. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state in superposition. - tolerance (float): Tolerance for considering amplitudes as negligible. Returns: str: The Dirac notation representation of the quantum state. """ # Ensure the statevector is normalized array = array / np.linalg.norm(array) # Get the number of qubits num_qubits = int(np.log2(len(array))) # Find indices where amplitude is not negligible non_zero_indices = np.where(np.abs(array) > tolerance)[0] # Generate Dirac notation terms terms = [ (find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b")) for i in non_zero_indices ] # Format Dirac notation dirac_notation = " + ".join([f"{amplitude}|{binary_rep}⟩" for amplitude, binary_rep in terms]) return dirac_notation def array_to_matrix_representation(array): """ Convert a one-dimensional array to a column matrix representation. Parameters: - array (numpy.ndarray): The one-dimensional array to be converted. Returns: numpy.ndarray: The column matrix representation of the input array. """ # Replace symbolic constants with their representations matrix_representation = np.array([find_symbolic_representation(value) or value for value in array]) # Return the column matrix representation return matrix_representation.reshape((len(matrix_representation), 1)) def array_to_dirac_and_matrix_latex(array): """ Generate LaTeX code for displaying both the matrix representation and Dirac notation of a quantum state. Parameters: - array (numpy.ndarray): The complex-valued array representing the quantum state. Returns: Latex: A Latex object containing LaTeX code for displaying both representations. """ matrix_representation = array_to_matrix_representation(array) latex = "Matrix representation\n\\begin{bmatrix}\n" + \ "\\\\\n".join(map(str, matrix_representation.flatten())) + \ "\n\\end{bmatrix}\n" latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}' return Latex(latex) sv_b1 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b1) sv_b2 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b2) sv_b3 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b3) sv_b4 = np.kron(sv_0, sv_0) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = np.kron(sv_0, sv_1) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4) sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2) array_to_dirac_and_matrix_latex(sv_b4)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, QuantumRegister from qiskit.extensions import HamiltonianGate from qiskit.circuit.library.standard_gates import CRYGate def quantum_fourier_transform(t, vis=False): reg = QuantumRegister(t, name='c') circ = QuantumCircuit(reg, name='$Q.F.T.$') for i in range(t // 2): circ.swap(i, t - 1 - i) for i in range(t): circ.h(i) for j in range(i + 1, t): circ.cu1(np.pi / (2 ** (j - i)), i, j) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Quantum Fourier Transform", fontsize=16) return circ.to_gate() def quantum_phase_estimation(n, t, unitary, vis=False): reg_b = QuantumRegister(n, name='b') reg_c = QuantumRegister(t, name='c') circ = QuantumCircuit(reg_b, reg_c, name='$Q.P.E.$') circ.h(range(n, n + t)) for i in range(t): circ.append(unitary.control(1).power(2**i), [n + i] + list(range(n))) circ.append(quantum_fourier_transform(t, vis=vis).inverse(), range(n, n + t)) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Quantum Phase Estimation", fontsize=16) return circ.to_gate() def subroutine_a(t, m, l, k, t0, vis=False): reg_c = QuantumRegister(t, name='c') reg_m = QuantumRegister(m, name='m') reg_l = QuantumRegister(l, name='l') circ = QuantumCircuit(reg_c, reg_m, reg_l, name='$Sub_A$') vis_temp = vis for i in range(t): gate = subroutine_c(m, t - i, l - k, t0, vis=vis_temp) circ.append(gate.control(2), [reg_l[k], reg_c[i]] + [reg_m[j] for j in range(m)]) vis_temp = False if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Subroutine A", fontsize=16) return circ.to_gate() def subroutine_b(t, m, l, t0, vis=False): reg_c = QuantumRegister(t, name='c') reg_m = QuantumRegister(m, name='m') reg_l = QuantumRegister(l, name='l') circ = QuantumCircuit(reg_c, reg_m, reg_l, name='$Sub_B$') vis_temp = vis for i in range(l): gate = subroutine_a(t, m, l, i, t0, vis=vis_temp) circ.append(gate, range(t + m + l)) vis_temp = False if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Subroutine B", fontsize=16) return circ.to_gate() def subroutine_c(m, u, v, t0, vis=False): reg = QuantumRegister(m, name='m') circ = QuantumCircuit(reg, name='$Sub_C$') t = -t0 / (2 ** (u + v - m)) for i in range(m): circ.rz(t / (2 ** (i + 1)), i) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle("Subroutine C", fontsize=16) return circ.to_gate() def hhl_forward_ckt(n, t, m, l, A, t0, vis=False): reg_b = QuantumRegister(n, name='b') reg_c = QuantumRegister(t, name='c') reg_m = QuantumRegister(m, name='m') reg_l = QuantumRegister(l, name='l') temp = QuantumCircuit(reg_b, name='$U$') temp.append(HamiltonianGate(A, t0 / (2 ** t)), reg_b) circ = QuantumCircuit(reg_b, reg_c, reg_m, reg_l, name='$Fwd$') circ.append(quantum_phase_estimation(n, t, temp.to_gate(), vis=vis), range(n + t)) circ.h(reg_m) circ.h(reg_l) for i in range(m): circ.rz(t0 / (2 ** (m - i)), reg_m[i]) circ.append(subroutine_b(t, m, l, t0, vis=vis), range(n, n + t + m + l)) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle('HHL Forward Computation', fontsize=16) return circ.to_gate() def hhl_circuit(A, t0, theta, size, vis=False): n, t, m, l = size reg_b = QuantumRegister(n, name='b') reg_c = QuantumRegister(t, name='c') reg_m = QuantumRegister(m, name='m') reg_l = QuantumRegister(l, name='l') ancil = QuantumRegister(1, name='anc') circ = QuantumCircuit(reg_b, reg_c, reg_m, reg_l, ancil, name='$HHL$') circ.append(hhl_forward_ckt(n, t, m, l, A, t0, vis=vis), range(sum(size))) for i in range(l): circ.append(CRYGate(theta).power(2**i), [reg_l[i], ancil]) circ.append(hhl_forward_ckt(n, t, m, l, A, t0).inverse(), range(sum(size))) if vis: circ.draw('mpl', reverse_bits=True, style={'fontsize': 6, 'subfontsize': 3})\ .suptitle('HHL Circuit', fontsize=16) return circ def ad_hoc_hhl(A, t0, r): reg_b = QuantumRegister(2) reg_c = QuantumRegister(4) ancil = QuantumRegister(1) circ = QuantumCircuit(reg_b, reg_c, ancil) circ.append(quantum_phase_estimation(2, 4, HamiltonianGate(A, t0/16)), range(6)) circ.swap(reg_c[1], reg_c[3]) for i in range(4): circ.cry(np.pi * (2 ** (4-i-r)), reg_c[i], ancil[0]) circ.barrier() circ.swap(reg_c[1], reg_c[3]) circ.append(quantum_phase_estimation(2, 4, HamiltonianGate(A, t0 / 16)).inverse(), range(6)) return circ if __name__ == '__main__': size = [3, 4, 4, 4] theta = np.pi/12 t0 = 2 * np.pi A = [[0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0]] circ = hhl_circuit(A, t0, theta, size, vis=True) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import hhl_components as cmp import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit import Aer, execute from qiskit.visualization import plot_histogram # Initialize parameters t0 = 2 * np.pi r = 6 A = [[3.75, 2.25, 1.25, -0.75], [2.25, 3.75, 0.75, -1.25], [1.25, 0.75, 3.75, -2.25], [-0.75, -1.25, -2.25, 3.75]] b = [0.5, 0.5, 0.5, 0.5] x = [-0.0312, 0.2188, 0.3437, 0.4062] p = [i ** 2 for i in x] basis = ['00', '01', '10', '11'] # Build circuit circ = QuantumCircuit(7, 3) circ.initialize(b, range(2)) circ.append(cmp.ad_hoc_hhl(A, t0, r), range(7)) circ.measure(6, 2) circ.measure([0, 1], [0, 1]) # Get simulators qasm = Aer.get_backend('qasm_simulator') svsm = Aer.get_backend('statevector_simulator') # QASM simulation job = execute(circ, qasm, shots=1024) counts = job.result().get_counts() measured_data = {} expected_data = {basis[i]: np.floor(p[i] * 1024) for i in range(4)} for key in counts.keys(): if key[0] == '1': measured_data[key[1::]] = counts[key] plot_histogram([expected_data, measured_data], title='HHL QASM Simulation', legend=['expected', 'measured']) plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.15) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, Aer, execute from qiskit.circuit import ParameterVector from qiskit.extensions import HamiltonianGate from qiskit.visualization import plot_histogram from qiskit.aqua.components.optimizers import COBYLA class QAOA: def __init__(self, clauses, p, num_shots=1024): # Assign weights and clauses if isinstance(clauses, dict): self.clauses = list(clauses.values()) self.weights = list(clauses.keys()) else: self.clauses = clauses self.weights = [1] * len(clauses) # Assign size parameters self.m = len(self.clauses) self.n = len(self.clauses[0]) self.p = p # Assign auxiliary parameters self.num_shots = num_shots self.error = -1 # Create variational parameters self.gamma = ParameterVector('gamma', length=p) self.beta = ParameterVector('beta', length=p) self.gamma_val = list(np.random.rand(p)) self.beta_val = list(np.random.rand(p)) # Create hamiltonians and variational circuit self.C = np.diag([self.cost(z) for z in range(2 ** self.n)]) self.varckt = self.build_varckt() self.optimize() def cost(self, z): # Convert to bitstr if not isinstance(z, str): z = format(z, '0' + str(self.n) + 'b') z: str # Evaluate C(z) cost = 0 for i in range(self.m): s = True for j in range(self.n): if self.clauses[i][j] != 'X' and self.clauses[i][j] != z[j]: s = False break if s: cost += self.weights[i] # Return output return cost def expectation(self, beta=None, gamma=None): # Resolve default values if beta is None: beta = self.beta_val if gamma is None: gamma = self.gamma_val # Evaluate expectation value circ = self.varckt.bind_parameters({self.beta: beta, self.gamma: gamma}) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=self.num_shots).result() counts = result.get_counts() expval = sum([self.cost(z) * counts[z] / self.num_shots for z in counts.keys()]) return expval def optimize(self): # Define objective function def objfunc(params): return -self.expectation(beta=params[0:self.p], gamma=params[self.p:2*self.p]) # Optimize parameters optimizer = COBYLA(maxiter=1000, tol=0.0001) params = self.beta_val + self.gamma_val ret = optimizer.optimize(num_vars=2*self.p, objective_function=objfunc, initial_point=params) self.beta_val = ret[0][0:self.p] self.gamma_val = ret[0][self.p:2*self.p] self.error = ret[1] return def build_varckt(self): # Build variational circuit circ = QuantumCircuit(self.n) circ.h(range(self.n)) for i in range(self.p): eC = QuantumCircuit(self.n, name='$U(C,\\gamma_' + str(i + 1) + ')$') eC.append(HamiltonianGate(self.C, self.gamma[i]), range(self.n)) eB = QuantumCircuit(self.n, name='$U(B,\\beta_' + str(i + 1) + ')$') eB.rx(2*self.beta[i], range(self.n)) circ.append(eC.to_gate(), range(self.n)) circ.append(eB.to_gate(), range(self.n)) circ.measure_all() return circ def sample(self, shots=None, vis=False): # Resolve defaults if shots is None: shots = self.num_shots # Sample maximum cost value circ = self.varckt.bind_parameters({self.beta: self.beta_val, self.gamma: self.gamma_val}) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=shots).result() counts = result.get_counts() if vis: plot_histogram(counts, title='Sample Output', bar_labels=False) plt.subplots_adjust(left=0.15, right=0.85, top=0.9, bottom=0.15) return max(counts, key=counts.get) if __name__ == '__main__': qaoa = QAOA(['10XX0', '11XXX'], 3) print('Maximized Expectation Value: ' + str(qaoa.expectation())) print('Sampled Output: ' + qaoa.sample()) qaoa.varckt.draw('mpl').suptitle('Variational Circuit', fontsize=16) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit.quantum_info import Operator from qiskit.circuit.library.standard_gates import XGate, YGate, ZGate class FiveQubitCode: def __init__(self): # Initialize Registers self.code = QuantumRegister(5, name="code") self.syndrm = QuantumRegister(4, name="syndrome") # Build Circuit Components self.encoder_ckt = self.build_encoder() self.syndrome_ckt = self.build_syndrome() self.correction_ckt = self.build_correction() self.decoder_ckt = self.encoder_ckt.mirror() # Build Noisy Channel self.noise_ckt = QuantumCircuit(self.code, self.syndrm) for i in range(5): self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[i]], label='noise') # Compose Full Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.barrier() self.circuit = self.encoder_ckt + circ + self.noise_ckt + circ + self.syndrome_ckt self.circuit = self.circuit + circ + self.correction_ckt + circ + self.decoder_ckt def build_encoder(self): # Build Encoder Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Encoder Circuit") circ.z(self.code[4]) circ.h(self.code[4]) circ.z(self.code[4]) circ.cx(self.code[4], self.code[3]) circ.h(self.code[4]) circ.h(self.code[3]) circ.cx(self.code[4], self.code[2]) circ.cx(self.code[3], self.code[2]) circ.h(self.code[2]) circ.cx(self.code[4], self.code[1]) circ.cx(self.code[2], self.code[1]) circ.h(self.code[1]) circ.h(self.code[4]) circ.cx(self.code[4], self.code[0]) circ.cx(self.code[3], self.code[0]) circ.cx(self.code[2], self.code[0]) circ.h(self.code[3]) circ.h(self.code[4]) return circ def build_syndrome(self): # Build Syndrome Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Syndrome Circuit") circ.h(self.syndrm) circ.barrier() circ.cz(self.syndrm[0], self.code[4]) circ.cx(self.syndrm[0], self.code[3]) circ.cx(self.syndrm[0], self.code[2]) circ.cz(self.syndrm[0], self.code[1]) circ.cx(self.syndrm[1], self.code[4]) circ.cx(self.syndrm[1], self.code[3]) circ.cz(self.syndrm[1], self.code[2]) circ.cz(self.syndrm[1], self.code[0]) circ.cx(self.syndrm[2], self.code[4]) circ.cz(self.syndrm[2], self.code[3]) circ.cz(self.syndrm[2], self.code[1]) circ.cx(self.syndrm[2], self.code[0]) circ.cz(self.syndrm[3], self.code[4]) circ.cz(self.syndrm[3], self.code[2]) circ.cx(self.syndrm[3], self.code[1]) circ.cx(self.syndrm[3], self.code[0]) circ.barrier() circ.h(self.syndrm) return circ def build_correction(self): # Build Correction Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.append(XGate().control(4, ctrl_state='0010'), [self.syndrm[i] for i in range(4)] + [self.code[0]]) circ.append(YGate().control(4, ctrl_state='1110'), [self.syndrm[i] for i in range(4)] + [self.code[0]]) circ.append(ZGate().control(4, ctrl_state='1100'), [self.syndrm[i] for i in range(4)] + [self.code[0]]) circ.append(XGate().control(4, ctrl_state='0101'), [self.syndrm[i] for i in range(4)] + [self.code[1]]) circ.append(YGate().control(4, ctrl_state='1101'), [self.syndrm[i] for i in range(4)] + [self.code[1]]) circ.append(ZGate().control(4, ctrl_state='1000'), [self.syndrm[i] for i in range(4)] + [self.code[1]]) circ.append(XGate().control(4, ctrl_state='1010'), [self.syndrm[i] for i in range(4)] + [self.code[2]]) circ.append(YGate().control(4, ctrl_state='1011'), [self.syndrm[i] for i in range(4)] + [self.code[2]]) circ.append(ZGate().control(4, ctrl_state='0001'), [self.syndrm[i] for i in range(4)] + [self.code[2]]) circ.append(XGate().control(4, ctrl_state='0100'), [self.syndrm[i] for i in range(4)] + [self.code[3]]) circ.append(YGate().control(4, ctrl_state='0111'), [self.syndrm[i] for i in range(4)] + [self.code[3]]) circ.append(ZGate().control(4, ctrl_state='0011'), [self.syndrm[i] for i in range(4)] + [self.code[3]]) circ.append(XGate().control(4, ctrl_state='1001'), [self.syndrm[i] for i in range(4)] + [self.code[4]]) circ.append(YGate().control(4, ctrl_state='1111'), [self.syndrm[i] for i in range(4)] + [self.code[4]]) circ.append(ZGate().control(4, ctrl_state='0110'), [self.syndrm[i] for i in range(4)] + [self.code[4]]) return circ def visualize(self): # Draw Circuits self.encoder_ckt.draw('mpl', reverse_bits=True).suptitle('Encoder Circuit', fontsize=16) self.syndrome_ckt.draw('mpl', reverse_bits=True).suptitle('Syndrome Circuit', fontsize=16) self.correction_ckt.draw('mpl', reverse_bits=True).suptitle('Error Correction', fontsize=16) self.decoder_ckt.draw('mpl', reverse_bits=True).suptitle('Decoder Circuit', fontsize=16) self.circuit.draw('mpl', reverse_bits=True, style={'fontsize': 4}) \ .suptitle('Five Qubit Error Correction', fontsize=16) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
"""Performance Analysis of 5 Qubit Code under Depolarizing Error""" import noise import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.visualization import plot_histogram, plot_bloch_vector from five_qubit_code import FiveQubitCode # Parameters error_prob = 0.05 theta = np.pi / 3 phi = np.pi / 4 # Initialize error correcting circuit, backend and noise model qasm = Aer.get_backend('qasm_simulator') noise_depol = noise.depolarizing_noise(error_prob) qecc = FiveQubitCode() # Visualize parameters print(noise_depol) qecc.visualize() # Define test circuit and input state output = ClassicalRegister(5) circ = QuantumCircuit(qecc.code, qecc.syndrm, output) circ.ry(theta, qecc.code[4]) circ.rz(phi, qecc.code[4]) plot_bloch_vector([np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)], title="Input State") plt.show() # Define final measurement circuit meas = QuantumCircuit(qecc.code, qecc.syndrm, output) meas.measure(qecc.code, output) # QASM simulation w/o error correction job = execute(circ + qecc.encoder_ckt + qecc.noise_ckt + qecc.decoder_ckt + meas, backend=qasm, noise_model=noise_depol, basis_gates=noise_depol.basis_gates) counts_noisy = job.result().get_counts() # QASM simulation with error correction job = execute(circ + qecc.circuit + meas, backend=qasm, noise_model=noise_depol, basis_gates=noise_depol.basis_gates) counts_corrected = job.result().get_counts() # Plot QASM simulation data plot_histogram([counts_noisy, counts_corrected], title='5-Qubit Error Correction - Depolarizing Noise $(P_{error} = ' + str(error_prob) + ')$', legend=['w/o code', 'with code'], figsize=(12, 9), bar_labels=False) plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.20) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit.quantum_info import Operator from qiskit.circuit.library.standard_gates import XGate class ThreeQubitCode: def __init__(self): # Initialize Registers self.code = QuantumRegister(3, name="code") self.syndrm = QuantumRegister(2, name="syndrome") # Build Circuit Components self.encoder_ckt = self.build_encoder() self.syndrome_ckt = self.build_syndrome() self.correction_ckt = self.build_correction() # Build Noisy Channel self.noise_ckt = QuantumCircuit(self.code, self.syndrm) self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[0]], label='noise') self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[1]], label='noise') self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[2]], label='noise') # Compose Full Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.barrier() self.circuit = self.encoder_ckt + circ + self.noise_ckt + circ + self.syndrome_ckt + circ + self.correction_ckt def build_encoder(self): # Build Encoder Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Encoder Circuit") circ.cx(self.code[0], self.code[1]) circ.cx(self.code[0], self.code[2]) return circ def build_syndrome(self): # Build Syndrome Circuit circ = QuantumCircuit(self.code, self.syndrm, name="Syndrome Circuit") circ.h(self.syndrm) circ.barrier() circ.cz(self.syndrm[1], self.code[2]) circ.cz(self.syndrm[1], self.code[1]) circ.cz(self.syndrm[0], self.code[1]) circ.cz(self.syndrm[0], self.code[0]) circ.barrier() circ.h(self.syndrm) return circ def build_correction(self): # Build Correction Circuit circ = QuantumCircuit(self.code, self.syndrm) circ.append(XGate().control(2, ctrl_state=2), [self.syndrm[0], self.syndrm[1], self.code[2]]) circ.append(XGate().control(2, ctrl_state=3), [self.syndrm[0], self.syndrm[1], self.code[1]]) circ.append(XGate().control(2, ctrl_state=1), [self.syndrm[0], self.syndrm[1], self.code[0]]) return circ def visualize(self): # Draw Circuits self.encoder_ckt.draw('mpl', reverse_bits=True).suptitle('Encoder Circuit', fontsize=16) self.syndrome_ckt.draw('mpl', reverse_bits=True).suptitle('Syndrome Circuit', fontsize=16) self.correction_ckt.draw('mpl', reverse_bits=True).suptitle('Error Correction', fontsize=16) self.circuit.draw('mpl', reverse_bits=True).suptitle('Three Qubit Error Correction', fontsize=16) plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
"""Performance Analysis of 3 Qubit Code under Bit Flip Error""" import noise import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.quantum_info import partial_trace, state_fidelity from qiskit.quantum_info import DensityMatrix, Kraus from qiskit.visualization import plot_histogram, plot_bloch_vector from three_qubit_code import ThreeQubitCode # Parameters error_prob = 0.05 theta = np.pi/3 phi = np.pi/4 # Initialize error correcting circuit, backend and noise model qasm = Aer.get_backend('qasm_simulator') svsm = Aer.get_backend('statevector_simulator') unit = Aer.get_backend('unitary_simulator') noise_model = noise.bit_flip_noise(error_prob) qecc = ThreeQubitCode() # Visualize parameters print(noise_model) qecc.visualize() # Define test circuit and input state output = ClassicalRegister(3) circ = QuantumCircuit(qecc.code, qecc.syndrm, output) circ.ry(theta, qecc.code[0]) circ.rz(phi, qecc.code[0]) plot_bloch_vector([np.sin(theta)*np.cos(phi), np.sin(theta)*np.sin(phi), np.cos(theta)], title="Input State") plt.show() # Define final measurement circuit meas = QuantumCircuit(qecc.code, qecc.syndrm, output) meas.measure(qecc.code, output) # QASM simulation w/o error correction job = execute(circ + qecc.encoder_ckt + qecc.noise_ckt + meas, backend=qasm, noise_model=noise_model, basis_gates=noise_model.basis_gates) counts_noisy = job.result().get_counts() # QASM simulation with error correction job = execute(circ + qecc.circuit + meas, backend=qasm, noise_model=noise_model, basis_gates=noise_model.basis_gates) counts_corrected = job.result().get_counts() # Plot QASM simulation data plot_histogram([counts_noisy, counts_corrected], title='3-Qubit Error Correction $(P_{error} = ' + str(error_prob) + ')$', legend=['w/o code', 'with code'], figsize=(12, 9), bar_labels=False) plt.subplots_adjust(left=0.15, right=0.72, top=0.9, bottom=0.15) plt.show() # Initialize fidelity simulation objects job = execute(circ + qecc.encoder_ckt, backend=svsm) init_state = DensityMatrix(job.result().get_statevector()) job = execute(qecc.syndrome_ckt, backend=unit) syndrome_op = Kraus(job.result().get_unitary()) # Initialize fidelity simulation parameters p_error = [0.05 * i for i in range(11)] f1 = [] f2 = [] # Evolve initial state for p in p_error: # Build noise channel bit_flip_channel = Kraus([[[0, np.sqrt(p)], [np.sqrt(p), 0]], [[np.sqrt(1-p), 0], [0, np.sqrt(1-p)]]]) bit_flip_channel = bit_flip_channel.tensor(bit_flip_channel).tensor(bit_flip_channel) bit_flip_channel = bit_flip_channel.expand(Kraus(np.eye(2))).expand(Kraus(np.eye(2))) # Apply channels corrupted_state = DensityMatrix(init_state.evolve(bit_flip_channel)) corrected_state = DensityMatrix(corrupted_state.evolve(syndrome_op)) corrected_state = DensityMatrix(corrected_state.evolve(qecc.correction_ckt)) # Trace out syndrome ini = DensityMatrix(partial_trace(init_state, [3, 4])) corrupted_state = DensityMatrix(partial_trace(corrupted_state, [3, 4])) corrected_state = DensityMatrix(partial_trace(corrected_state, [3, 4])) # Record results f1.append(state_fidelity(ini, corrupted_state)) f2.append(state_fidelity(ini, corrected_state)) # Plot fidelity fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(111) ax.plot(p_error, f1, label='w/o code') ax.plot(p_error, f2, label='with code') ax.set_title("$Fidelity$ vs $P_{error}$") ax.set_xlabel('$P_{error}$') ax.set_ylabel('$Fidelity$') ax.set_ylabel('$Fidelity$') ax.legend() plt.xlim(0, 0.5) plt.ylim(0, 1) plt.grid() plt.show()
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import random import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit, Aer, execute from qiskit.circuit import ParameterVector from qiskit.quantum_info import state_fidelity from qiskit.quantum_info import Statevector, DensityMatrix, Operator class Compressor: def __init__(self, ensemble, block_size): # Initialize parameters self.ensemble = ensemble self.n = block_size self.m = block_size self.theta = ParameterVector('theta', length=block_size) self.phi = ParameterVector('phi', length=block_size) # Initialize density matrix properties self.rho = np.zeros((2, 2)) self.s0 = np.array([0, 0]) self.s1 = np.array([0, 0]) self.entropy = 1 self.initialize_density_matrix() self.noise = ParameterVector('noise', length=self.m) # Build subcircuits self.ns_ckt = QuantumCircuit(self.n, name='$Noise$') self.source = QuantumCircuit(self.n, name='$Src$') self.tx_ckt = QuantumCircuit(self.n, name='$Tx$') self.rx_ckt = QuantumCircuit(self.n, name='$Rx$') self.initialize_subcircuits() def initialize_density_matrix(self): # Evaluate density matrix and list of states for key in self.ensemble.keys(): theta = key[0] phi = key[1] state = np.array([np.cos(theta/2), np.sin(theta/2) * np.exp(phi*complex(1, 0))]) self.rho = self.rho + self.ensemble[key] * np.outer(state, state) # Evaluate spectrum self.rho: np.ndarray v, w = np.linalg.eig(self.rho) s0 = Statevector(w[:, 0]) s1 = Statevector(w[:, 1]) self.rho = DensityMatrix(self.rho) # Evaluate entropy and typical basis if state_fidelity(s0, self.rho) > state_fidelity(s1, self.rho): self.s0 = s0 self.s1 = s1 else: self.s0 = s1 self.s1 = s0 self.entropy = -np.real(sum([p * np.log2(p) for p in v])) self.m = int(np.ceil(self.entropy * self.n)) def initialize_subcircuits(self): # Build source self.source.reset(range(self.n)) for i in range(self.n): self.source.ry(self.theta[i], i) self.source.rz(self.phi[i], i) # Build typical basis change operator U = Operator(np.column_stack((self.s0.data, self.s1.data))).adjoint() for i in range(self.n): self.tx_ckt.unitary(U, [i], label='$Basis$') # Build permutation operator data = list(range(2 ** self.n)) data = [("{0:0" + str(self.n) + "b}").format(i) for i in data] data = sorted(data, key=lambda x: x.count('1')) data = [int(x, 2) for x in data] V = np.zeros((2 ** self.n, 2 ** self.n)) for i in range(2 ** self.n): V[i, data[i]] = 1 self.tx_ckt.unitary(V, list(range(self.n)), label='$Perm$') # Build bit flip noisy channel for i in range(self.m): self.ns_ckt.u3(self.noise[i], 0, self.noise[i], i) # Build receiver self.rx_ckt.reset(range(self.m, self.n)) self.rx_ckt.append(self.tx_ckt.to_gate().inverse(), list(range(self.n))) def simulate(self, num_shots=1, bit_flip_prob=0.0): # Get backend and circuit simulator = Aer.get_backend('statevector_simulator') circ = self.source + self.tx_ckt + self.ns_ckt + self.rx_ckt fid_list = [] for i in range(num_shots): # Acquire parameters states = random.choices(list(self.ensemble.keys()), self.ensemble.values(), k=self.n) noise = random.choices([0, np.pi], [1-bit_flip_prob, bit_flip_prob], k=self.m) theta = [p[0] for p in states] phi = [p[1] for p in states] circ1 = self.source.bind_parameters({self.theta: theta, self.phi: phi}) circ2 = circ.bind_parameters({self.theta: theta, self.phi: phi, self.noise: noise}) # Simulate ini_state = execute(circ1, simulator).result().get_statevector() fin_state = execute(circ2, simulator).result().get_statevector() fid_list.append(state_fidelity(ini_state, fin_state)) # Return results return fid_list def visualize(self): # Draw components self.source.draw('mpl', reverse_bits=True).suptitle('Source Circuit') self.tx_ckt.draw('mpl', reverse_bits=True).suptitle('Tx Circuit') self.rx_ckt.draw('mpl', reverse_bits=True).suptitle('Rx Circuit') (self.source + self.tx_ckt + self.ns_ckt + self.rx_ckt).draw('mpl', reverse_bits=True).suptitle('Full Circuit') plt.show() if __name__ == '__main__': ensemble = {(0, 0): 0.5, (np.pi/2, 0): 0.5} com = Compressor(ensemble, 3) com.visualize() fid1 = com.simulate(num_shots=100) fid2 = com.simulate(num_shots=100, bit_flip_prob=0.1) print('Noiseless System Fidelity: ', np.mean(fid1)) print('Noisy (p = 0.1) System Fidelity: ', np.mean(fid2))
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate # Define no. of message qubits n = 10 # Alice's end alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ = QuantumCircuit(n, n) # Preparation circ.reset(range(n)) for i in range(n): if alice_prepare[i] == 1: circ.x(i) circ.barrier() # Hadamard Transform for i in range(n): if alice_hadamard[i] == 1: circ.h(i) circ.barrier() # Eavesdropper circ.append(Gate(name="$Eve$", num_qubits=n, params=[]), range(n)) # Bob's end bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ.barrier() # Hadamard Transform for i in range(n): if bob_hadamard[i] == 1: circ.h(i) circ.barrier() # Measurement circ.measure(range(n), range(n)) circ.draw('mpl', reverse_bits=True, scale=0.45) # Alice's end alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ = QuantumCircuit(n, n) # Preparation circ.reset(range(n)) for i in range(n): if alice_prepare[i] == 1: circ.x(i) circ.barrier() # Hadamard Transform for i in range(n): if alice_hadamard[i] == 1: circ.h(i) circ.barrier() # Bob's end bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) # Hadamard Transform for i in range(n): if bob_hadamard[i] == 1: circ.h(i) circ.barrier() # Measurement circ.measure(range(n), range(n)) circ.draw('mpl', reverse_bits=True, scale=0.45) # Execute Circuit backend = Aer.get_backend('qasm_simulator') job = execute(circ, backend, shots=1) counts = job.result().get_counts(circ) bob_measure = list(counts.keys())[0][::-1] # Print Data print("".join(["Alice Prepared: ","".join([str(i) for i in alice_prepare])])) print("".join(["Alice H Transforms: ","".join([str(i) for i in alice_hadamard])])) print("".join(["Bob H Transforms: ","".join([str(i) for i in bob_hadamard])])) print("".join(["Bob Measurements: ", bob_measure])) # Extract Key alice_key = [] bob_key = [] for i in range(n): if alice_hadamard[i]==bob_hadamard[i]: alice_key.append(int(alice_prepare[i])) bob_key.append(int(bob_measure[i])) # Print Keys print("".join(["Alice extracts key as: ","".join([str(i) for i in alice_key])])) print("".join(["Bob extracts key as: ","".join([str(i) for i in bob_key])])) # Alice's end alice_prepare = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) alice_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ = QuantumCircuit(n, 2*n) # Preparation circ.reset(range(n)) for i in range(n): if alice_prepare[i] == 1: circ.x(i) circ.barrier() # Hadamard Transform for i in range(n): if alice_hadamard[i] == 1: circ.h(i) circ.barrier() # Eavesdropper circ.measure(range(n), range(n)) # Bob's end bob_hadamard = np.random.choice([0,1], size=(n,), p=[0.5, 0.5]) circ.barrier() # Hadamard Transform for i in range(n): if bob_hadamard[i] == 1: circ.h(i) circ.barrier() # Measurement circ.measure(range(n), range(n,2*n)) circ.draw('mpl', reverse_bits=True, scale=0.45) # Execute Circuit backend = Aer.get_backend('qasm_simulator') job = execute(circ, backend, shots=1) counts = job.result().get_counts(circ) measure_data = list(counts.keys())[0][::-1] eve_measure = measure_data[0:n] bob_measure = measure_data[n:2*n] # Print Data print("".join(["Alice Prepared: ","".join([str(i) for i in alice_prepare])])) print("".join(["Alice H Transforms: ","".join([str(i) for i in alice_hadamard])])) print("".join(["Eve Measurements: ", eve_measure])) print("".join(["Bob H Transforms: ","".join([str(i) for i in bob_hadamard])])) print("".join(["Bob Measurements: ", bob_measure])) # Extract Key alice_key = [] bob_key = [] for i in range(n): if alice_hadamard[i]==bob_hadamard[i]: alice_key.append(int(alice_prepare[i])) bob_key.append(int(bob_measure[i])) # Print Keys print("".join(["Alice extracts key as: ","".join([str(i) for i in alice_key])])) print("".join(["Bob extracts key as: ","".join([str(i) for i in bob_key])]))
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
from qiskit import * from qiskit.tools.visualization import plot_histogram %matplotlib inline secretnumber = '11100011' circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber)) circuit.h(range(len(secretnumber))) circuit.x(len(secretnumber)) circuit.h(len(secretnumber)) circuit.barrier() for ii, yesno in enumerate(reversed(secretnumber)): if yesno == '1': circuit.cx(ii,len(secretnumber)) circuit.barrier() circuit.h(range(len(secretnumber))) circuit.barrier() circuit.measure(range(len(secretnumber)),range(len(secretnumber))) circuit.draw(output = 'mpl')
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_histogram, plot_bloch_multivector circ = QuantumCircuit(2, 1) circ.reset([0, 1]) circ.x(0) circ.barrier() circ.h([0, 1]) circ.barrier() circ.append(Gate(name="$U_f$", num_qubits=2, params=[]), [0, 1]) circ.barrier() circ.h(1) circ.barrier() circ.measure(1, 0) circ.draw('mpl', reverse_bits=True) # Implementation of f1(x) f1 = QuantumCircuit(2, name='f1') f1.id(0) f1.draw('mpl', reverse_bits=True) # Implementation of f2(x) f2 = QuantumCircuit(2, name='f2') f2.cx(1, 0) f2.id(0) f2.draw('mpl', reverse_bits=True) # Implementation of f3(x) f3 = QuantumCircuit(2, name='f3') f3.cx(1, 0) f3.x(0) f3.draw('mpl', reverse_bits=True) # Implementation of f4(x) f4 = QuantumCircuit(2, name='f4') f4.x(0) f4.draw('mpl', reverse_bits=True) circ = QuantumCircuit(2) circ.x(0) circ.barrier() circ.h([0, 1]) circ.append(f4.to_instruction(), [0, 1]) circ.h(1) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(2) circ.x(0) circ.barrier() circ.h([0, 1]) circ.append(f2.to_instruction(), [0, 1]) circ.h(1) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(2, 1) circ.x(0) circ.barrier() circ.h([0, 1]) circ.append(f2.to_instruction(), [0, 1]) circ.h(1) circ.measure(1, 0) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=1000).result() counts = result.get_counts(circ) plot_histogram(counts)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_histogram, plot_bloch_multivector # Define no. of input qubits n = 4 circ = QuantumCircuit(n+1, n) circ.reset(range(n+1)) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.barrier() circ.append(Gate(name="$U_f$", num_qubits=n+1, params=[]), range(n+1)) circ.barrier() circ.h(range(1, n+1)) circ.barrier() circ.measure(range(1, n+1), range(n)) circ.draw('mpl', reverse_bits=True) # Constant Function constant = QuantumCircuit(n+1, name='Constant') constant.x(0) constant.draw('mpl', reverse_bits=True) # Balanced Function balanced = QuantumCircuit(n+1, name='Balanced') for i in range(1, n+1): balanced.cx(i, 0) balanced.draw('mpl', reverse_bits=True) circ = QuantumCircuit(n+1) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.append(constant.to_instruction(), range(n+1)) circ.h(range(1, n+1)) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(n+1) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.append(balanced.to_instruction(), range(n+1)) circ.h(range(1, n+1)) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('statevector_simulator') result = execute(circ, simulator).result() state = result.get_statevector(circ) plot_bloch_multivector(state) circ = QuantumCircuit(n+1, n) circ.x(0) circ.barrier() circ.h(range(n+1)) circ.append(constant.to_instruction(), range(n+1)) circ.h(range(1, n+1)) circ.measure(range(1, n+1), range(n)) circ.draw(reverse_bits=True, plot_barriers=False) simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=1000).result() counts = result.get_counts(circ) plot_histogram(counts)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
my_list = [1,3,5,2,4,2,5,8,0,7,6] #classical computation method def oracle(my_input): winner =7 if my_input is winner: response = True else: response = False return response for index, trial_number in enumerate(my_list): if oracle(trial_number) is True: print("Winner is found at index %i" %index) print("%i calls to the oracle used " %(index +1)) break #quantum implemenation from qiskit import * import matplotlib.pyplot as plt import numpy as np from qiskit.tools import job_monitor # oracle circuit oracle = QuantumCircuit(2, name='oracle') oracle.cz(0,1) oracle.to_gate() oracle.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit, backend=backend) result= job.result() sv= result.get_statevector() np.around(sv,2) #amplitude amplification reflection = QuantumCircuit(2, name='reflection') reflection.h([0,1]) reflection.z([0,1]) reflection.cz(0,1) reflection.h([0,1]) reflection.to_gate() reflection.draw(output='mpl') #testing circuit on simulator simulator = Aer.get_backend('qasm_simulator') grover_circuit = QuantumCircuit(2,2) grover_circuit.h([0,1]) grover_circuit.append(oracle,[0,1]) grover_circuit.append(reflection, [0,1]) grover_circuit.barrier() grover_circuit.measure([0,1],[0,1]) grover_circuit.draw(output='mpl') job= execute(grover_circuit,backend=simulator,shots=1) result=job.result() result.get_counts() #testing on real backend system IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp= provider.get_backend('ibmq_manila') job = execute(grover_circuit,backend=qcomp) job_monitor(job) result=job.result() counts=result.get_counts(grover_circuit) from qiskit.visualization import plot_histogram plot_histogram(counts) counts['11']
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from math import pi from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_histogram from qiskit.circuit.library.standard_gates import ZGate, XGate # Define circuit parameters a = '10x01xx' n = len(a) k = 7 circ = QuantumCircuit(k+n, k) circ.reset(range(k+n)) circ.h(range(k+n)) circ.barrier() for i in range(k): name = '$G_' + str(i) + '$' circ.append(QuantumCircuit(n, name=name).to_gate().control(1), [n+i]+list(range(n))) circ.barrier() circ.append(Gate(name="$QFT^{-1}$", num_qubits=k, params=[]), range(n, k+n)) circ.barrier() circ.measure(range(n, k+n), range(k)) circ.draw('mpl', reverse_bits=True, scale=0.5) def Gop(j): p = 2 ** j ctrl_bits = [] ctrl_state = '' for i in range(n): if a[n-i-1] != 'x': ctrl_bits.append(i+1) ctrl_state += a[n-i-1] G = QuantumCircuit(n+1, name='G'+str(j)) for i in range(p): G.append(XGate().control(len(ctrl_bits), ctrl_state=ctrl_state[::-1]), ctrl_bits + [0]) G.h(range(1, n+1)) G.x(range(1, n+1)) G.append(ZGate().control(n-1), reversed(range(1, n+1))) G.x(range(1, n+1)) G.h(range(1, n+1)) return G Gop(3).draw('mpl', reverse_bits=True, scale=0.5) QFT_inv = QuantumCircuit(k, name='QFT^{-1}') for i in reversed(range(k)): if i != k-1: QFT_inv.barrier() for j in reversed(range(i+1,k)): QFT_inv.cu1(-pi/(2 ** (j-i)), i, j) QFT_inv.h(i) QFT_inv.draw('mpl', reverse_bits=True) circ = QuantumCircuit(k+n+1, k) circ.reset(range(k+n+1)) circ.x(0) circ.h(range(k+n+1)) circ.z(n+1) circ.barrier() for i in range(k): circ.append(Gop(i).to_gate().control(1), [n+i+1]+list(range(n+1))) circ.barrier() circ.append(QFT_inv, range(n+1, k+n+1)) circ.barrier() circ.measure(range(n+1, k+n+1), range(k)) circ.draw(reverse_bits=True, scale=0.5) delta = 64 simulator = Aer.get_backend('qasm_simulator') result = execute(circ, simulator, shots=delta).result() counts = result.get_counts(circ) plot_histogram(counts) x = list(counts.keys()) x = [pi*int(i[::-1], 2)/(2 ** k) for i in x] p = list(counts.values()) p = p.index(max(p)) theta = min(x[p], pi-x[p]) m_estimate = (2 ** n) * (theta ** 2) m = 2 ** a.count('x') print('Estimated Count:') print(m_estimate) print('Actual Count:') print(m)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
from qiskit import * from qiskit.visualization import plot_bloch_multivector, plot_bloch_vector, plot_histogram from qiskit.compiler import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.providers.ibmq import least_busy import matplotlib import numpy as np %pylab inline qc = QuantumCircuit(4,3) qc.x(3) qc.h(range(3)) reps = 1 for count in range(3): for i in range (reps): qc.cp(pi/4, count, 3) reps *= 2 qc.barrier() qc.draw('mpl') def inv_qft(qc, n): for qubit in range (n//2): qc.swap(qubit, n-qubit-1) for j in range(n): for m in range(j): qc.cp(-pi/(2*(j-m)), m, j) qc.h(j) inv_qft(qc, 3) qc.barrier() qc.measure(range(3), range(3)) qc.draw('mpl') qasm_sim = Aer.get_backend('qasm_simulator') shots = 1 qobj = assemble(qc, qasm_sim) results = qasm_sim.run(qobj).result() counts = results.get_counts() plot_histogram(counts) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q') provider.backends() backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 4 and not x.configuration().simulator and x.status().operational==True)) print("least busy backend: ", backend) # Run our circuit on the least busy backend. Monitor the execution of the job in the queue from qiskit.tools.monitor import job_monitor shots = 1024 transpiled_circuit = transpile(qc, backend) qobj = assemble(transpiled_circuit, shots=shots) job = backend.run(qobj) job_monitor(job, interval=2) results = job.result() answer = results.get_counts() plot_histogram(answer)
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
# initialization import numpy as np # importing Qiskit from qiskit import IBMQ, BasicAer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute, Aer from qiskit.tools.jupyter import * provider = IBMQ.load_account() # import basic plot tools from qiskit.visualization import plot_histogram def initialize(circuit, n, m): circuit.h(range(n)) # Hadamard transform on measurment register circuit.x(n+m-1) # X gate on last qubit def c_amod15(a, x): if a not in [2,7,8,11,13]: raise ValueError("'a' must be 2,7,8,11 or 13") # remember that a needs to be co-prime with N unitary = QuantumCircuit(4) for iteration in range(x): # bitwise arithmetic to represent modular exponentiation function if a in [2,13]: unitary.swap(0,1) unitary.swap(1,2) unitary.swap(2,3) if a in [7,8]: unitary.swap(2,3) unitary.swap(1,2) unitary.swap(0,1) if a == 11: unitary.swap(1,3) unitary.swap(0,2) if a in [7,11,13]: for q in range(4): unitary.x(q) unitary = unitary.to_gate() unitary.name = "%i^%i mod 15" % (a, x) # But we need to make it a controlled operation for phase kickback c_unitary = unitary.control() return c_unitary def modular_exponentiation(circuit, n, m, a): for exp in range(n): exponent = 2**exp circuit.append(a_x_mod15(a, exponent), [exp] + list(range(n, n+m))) from qiskit.circuit.library import QFT def apply_iqft(circuit, measurement_qubits): circuit.append(QFT( len(measurement_qubits), do_swaps=False).inverse(), measurement_qubits) def shor_algo(n, m, a): # set up the circuit circ = QuantumCircuit(n+m, n) # initialize the registers initialize(circ, n, m) circ.barrier() # map modular exponentiation problem onto qubits modular_exponentiation(circ, n, m, a) circ.barrier() # apply inverse QFT -- expose period apply_iqft(circ, range(n)) # measure the measurement register circ.measure(range(n), range(n)) return circ n = 4; m = 4; a = 11 mycircuit = shor_algo(n, m, a) mycircuit.draw('mpl') simulator = Aer.get_backend('qasm_simulator') counts = execute(mycircuit, backend=simulator, shots=1024).result().get_counts(mycircuit) plot_histogram(counts) for measured_value in counts: print(f"Measured {int(measured_value[::-1], 2)}") from math import gcd from math import sqrt from itertools import count, islice for measured_value in counts: measured_value_decimal = int(measured_value[::-1], 2) print(f"Measured {measured_value_decimal}") if measured_value_decimal % 2 != 0: print("Failed. Measured value is not an even number") continue x = int((a ** (measured_value_decimal/2)) % 15) if (x + 1) % 15 == 0: print("Failed. x + 1 = 0 (mod N) where x = a^(r/2) (mod N)") continue guesses = gcd(x + 1, 15), gcd(x - 1, 15) print(guesses) def is_prime(n): return n > 1 and all(n % i for i in islice(count(2), int(sqrt(n)-1))) if is_prime(guesses[0]) and is_prime(guesses[1]): print(f"**The prime factors are {guesses[0]} and {guesses[1]}**")
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
# Importing Packages from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble, QuantumRegister, ClassicalRegister from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle bb = input("Enter the input string:\n") ### Using in-built "simon_oracle" from QISKIT # importing Qiskit from qiskit import IBMQ, Aer from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, transpile, assemble # import basic plot tools from qiskit.visualization import plot_histogram from qiskit_textbook.tools import simon_oracle n = len(bb) 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(bb) # 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(output="mpl") # use local simulator aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(simon_circuit, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(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 = input("Enter a binary string:\n") # Actual b = 011 b_rev = b[::-1] flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() qc.measure(q1,c1) qc.draw("mpl") aer_sim = Aer.get_backend('aer_simulator') shots = 500 qobj = assemble(qc, shots=shots) results = aer_sim.run(qobj).result() counts = results.get_counts() print(counts) plot_histogram(counts) # Actual b = 011 b="1" b_rev = "1" flagbit = b_rev.find('1') n=len(b) q1=QuantumRegister(n,'q1') q2=QuantumRegister(n,'q2') c1=ClassicalRegister(n) qc = QuantumCircuit(q1,q2,c1) qc.barrier() qc.h(q1) qc.barrier() for i in range(n): qc.cx(q1[i],q2[i]) qc.barrier() if flagbit != -1: # print("test1") for ind, bit in enumerate(b_rev): # print("test2") if bit == "1": # print("test3") qc.cx(flagbit, q2[ind]) qc.barrier() qc.h(q1) qc.barrier() # qc.measure(q1,c1) # qc.draw("mpl") # Simulate the unitary usim = Aer.get_backend('aer_simulator') qc.save_unitary() qobj = assemble(qc) unitary = usim.run(qobj).result().get_unitary() # Display the results: array_to_latex(unitary, prefix="\\text{Circuit = } ")
https://github.com/shantomborah/Quantum-Algorithms
shantomborah
import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import Aer, execute from qiskit.circuit import Gate from qiskit.visualization import plot_bloch_multivector from math import pi q = QuantumRegister(3, name='q') c = ClassicalRegister(2, name='c') circ = QuantumCircuit(q, c) circ.reset(q) circ.u3(pi/2,pi/2,pi/2,q[2]) circ.h(q[1]) circ.cx(q[1],q[0]) circ.barrier() circ.cx(q[2],q[1]) circ.h(q[2]) circ.barrier() circ.measure([q[2],q[1]],[c[1],c[0]]) circ.barrier() circ.x(0).c_if(c,1) circ.z(0).c_if(c,2) circ.x(0).c_if(c,3) circ.z(0).c_if(c,3) circ.draw('mpl', reverse_bits=True) theta = pi/3 phi = pi/2 q = QuantumRegister(3, name='q') c = ClassicalRegister(2, name='c') circ = QuantumCircuit(q, c) circ.reset(q) circ.u3(theta,phi,pi,q[2]) circ.h(q[1]) circ.cx(q[1],q[0]) circ.barrier() circ.draw('mpl', reverse_bits=True) backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) state = job.result().get_statevector(circ) plot_bloch_multivector(state) circ.cx(q[2],q[1]) circ.h(q[2]) circ.barrier() circ.measure([q[2],q[1]],[c[1],c[0]]) circ.barrier() circ.x(0).c_if(c,1) circ.z(0).c_if(c,2) circ.x(0).c_if(c,3) circ.z(0).c_if(c,3) circ.draw('mpl', reverse_bits=True) backend = Aer.get_backend('statevector_simulator') job = execute(circ, backend) state = job.result().get_statevector(circ) plot_bloch_multivector(state)
https://github.com/LohitPotnuru/TransverseIsingModelQiskit
LohitPotnuru
from qiskit import * from scipy.optimize import minimize import numpy as np from pylab import * #2^4 possible states of four qubits stored in dic bit = ['0','1'] dic = [] for i in bit: for j in bit: for k in bit: for l in bit: dic.append(i+j+l+k) def calcEJ(theta): #make quantum circuit with 2 qubits q = QuantumRegister(4) c = ClassicalRegister(4) circuit = QuantumCircuit(q,c) # entangled quantum state preparation q = circuit.qregs[0] circuit.u(theta[0], theta[1], 0, q[0]) circuit.cx(q[0],q[1]) circuit.cx(q[0],q[2]) circuit.cx(q[0],q[3]) for i in range(0,4): circuit.u(theta[i+2],0,0,q[i]) circuit.measure(range(4),range(4)) # Executing the circuit by qasm_simulation to caculate energy from result.get(counts) shots=18192 backend = BasicAer.get_backend('qasm_simulator') result = execute(circuit, backend, shots = shots).result() counts = result.get_counts() #make sure that all possible values accounted for to avoid errors for i in dic: if i not in counts: counts[i] = 0 #calculate expectation value in terms of sigma z of qubit i and qubit i+1 def prob(i): t1=0 t2=0 for j in counts.keys(): if j[i]=='0': t1+=counts[j] else: t1-=counts[j] t1=t1/shots for j in counts.keys(): if j[i+1]=='0': t2+=counts[j] else: t2-=counts[j] t2=t2/shots E=-1*t1*t2 return E E_J=0 for i in range(0,3): E_J+=prob(i) return E_J def calcEZ(theta): #make quantum circuit with 2 qubits q = QuantumRegister(4) c = ClassicalRegister(4) circuit = QuantumCircuit(q,c) # entangled quantum state preparation q = circuit.qregs[0] circuit.u(theta[0], theta[1], 0, q[0]) circuit.cx(q[0],q[1]) circuit.cx(q[0],q[2]) circuit.cx(q[0],q[3]) for i in range(0,4): circuit.u(theta[i+2],0,0,q[i]) circuit.h(range(4)) circuit.measure(range(4),range(4)) # Executing the circuit by qasm_simulation to caculate energy from result.get(counts) shots=18192 backend = BasicAer.get_backend('qasm_simulator') result = execute(circuit, backend, shots = shots).result() counts = result.get_counts() #make sure that all possible values accounted for to avoid errors for i in dic: if i not in counts: counts[i] = 0 #calculate expectation value in terms of sigma x of qubit i def prob(i): E=0 for j in counts.keys(): if j[i]=='0': E+=counts[j] else: E-=counts[j] E=E/shots return E E_Z=0 for i in range(0,3): E_Z+=prob(i) return E_Z # expectation value total def calcE(theta): # Summing the measurement results classical_adder = calcEJ(theta) + h * calcEZ(theta) return classical_adder h=2 calcE(theta=[1.5708,0,1.10715,0,2.03444,0]) theta0=[1.5708,0,1.10715,0,2.03444,0] tol = 1e-3 # tolerance for optimization precision. # Get expectation energy by optimization with corresponding h = 0.1, 0.2,..., 2.9, 3. y_vqe = [] for k in range(0,31): h=k/10 vqe_result = minimize(calcE, theta0 , method="COBYLA", tol=tol) y_vqe.append(vqe_result.fun) print(y_vqe) y_mean = np.array(y_vqe)/4 x2 = [] for k in range(0,31): x2.append(k/10) plot(x2,y_mean,'bs', label='VQE') plt.xlabel('h') plt.ylabel('E/N with N = 4')
https://github.com/sebasmos/QuantumVE
sebasmos
import numpy as np import matplotlib.pyplot as plt def initial_state(num_positions): return np.ones(num_positions) / num_positions def predict_state(prior_prob, velocity): num_positions = len(prior_prob) predicted_prob = np.zeros(num_positions) for i in range(num_positions): predicted_prob[i] = prior_prob[(i - velocity) % num_positions] return predicted_prob def update_state(predicted_prob, observation, observation_noise): likelihood = np.exp(-0.5 * ((np.arange(len(predicted_prob)) - observation) / observation_noise)**2) posterior_prob = likelihood * predicted_prob posterior_prob /= np.sum(posterior_prob) # Normalize return posterior_prob # Simulation parameters num_positions = 100 velocity = 1 observation_noise = 10 num_steps = 50 # Initialize true_positions = np.zeros(num_steps) observations = np.zeros(num_steps) prior_prob = initial_state(num_positions) # Test initial state init_state_2 = np.zeros(num_positions) init_state_2[int(num_positions/2)] = 1 print(init_state_2) p_plus = predict_state(init_state_2, 1) print(p_plus) # Initialize true_positions = np.zeros(num_steps) observations = np.zeros(num_steps) estimated_positions = np.zeros(num_steps) # Store estimated positions # Run the Bayesian update cycle for step in range(num_steps): # True target position update (constant velocity) true_positions[step] = step * velocity # Generate noisy observation observations[step] = true_positions[step] + np.random.normal(0, observation_noise) # Bayesian prediction predicted_prob = predict_state(prior_prob, velocity) # Bayesian update prior_prob = update_state(predicted_prob, observations[step], observation_noise) # Calculate Metrics mse = np.mean((true_positions - estimated_positions) ** 2) # Symmetric Mean Absolute Percentage Error (SMAPE) smape_numerator = 2 * np.abs(estimated_positions - true_positions) smape_denominator = np.abs(estimated_positions) + np.abs(true_positions) smape = np.mean(np.nan_to_num(smape_numerator / smape_denominator)) # Mean Absolute Percentage Error (MAPE) mape_numerator = np.abs(estimated_positions - true_positions) mape_denominator = np.abs(true_positions) mape = np.mean(np.nan_to_num(mape_numerator / mape_denominator)) * 100 r2 = 1 - np.sum((true_positions - estimated_positions) ** 2) / np.sum((true_positions - np.mean(true_positions)) ** 2) mae = np.mean(np.abs(true_positions - estimated_positions)) # Print Metrics print("Mean Squared Error (MSE):", mse) print("Symmetric Mean Absolute Percentage Error (SMAPE):", smape) print("Mean Absolute Percentage Error (MAPE):", mape) print("R-squared (R2):", r2) print("Mean Absolute Error (MAE):", mae) # Plot the results plt.figure(figsize=(12, 6)) plt.plot(np.arange(num_positions), prior_prob, label='Posterior Distribution') plt.scatter(true_positions, np.ones_like(true_positions) * 0.01, color='r', marker='x', label='True Positions') plt.scatter(observations, np.ones_like(observations) * 0.01, color='g', marker='o', label='Noisy Observations') plt.title('Bayesian Multi-Target Tracking') plt.xlabel('Position') plt.ylabel('Probability') plt.legend() plt.show()
https://github.com/sebasmos/QuantumVE
sebasmos
%reset -f %matplotlib inline import numpy as np import matplotlib.pyplot as plt import numpy as np import pickle import datetime import os name_data = "sample_trajectories.pkl" os.makedirs("data") Fn = os.path.join(os.getcwd(),"data",name_data) # initialize random number generator rng = np.random.default_rng() # Set simulation parameters dt = 1e-5 # timestep for simulation dt_out = 1e-4 # timestep of saved trajectories stride_out = int(np.round(dt_out/dt)) N_sim = 4000 # number of trajectories to be generated # For each trajectory, we use a random number of timesteps. This is to # show that the parameter inference works with trajectory samples of # various lengths. # The number of timesteps for each trajectory is sampled from a uniform # distribution on the interes from N_steps_min to N_steps_max, which are # defined here: N_steps_mean = int(np.round(0.05/dt)) N_steps_min = N_steps_mean*0.5 N_steps_max = N_steps_mean*1.5 # generate an array that contains the number of steps of all trajectories: N_steps = rng.integers(low=N_steps_min, high=N_steps_max, size=N_sim) # For each simulation, the initial condition is drawn from a uniform # distribution on [x_L, x_R], using the following values: x_L = -1.5 x_R = 1.5 # Definition of the parameters of the Langevin equation. # # We simulate the Ito-Langevin equation # dX_t = a(X_t) * dt + sqrt(2*D) * dW_t, # where dX_t is the increment of the reaction coordinate at time t, # a(x) is the drift, D is the diffusivity (which we assume to be a constant # number, meaning we consider additive noise), and dW_t is the increment # of the Wiener process. # # We consider a constant diffusivity D = 1. # and a gradient drift a(x) = -dU/dx that originates from a double-well potential # U(x) = U0 * ( x**2 - 1 )**2, so that a(x) = -4 * U0 * ( x**2 - 1 ) * x. U0 = 2. a = lambda x: -4*U0*(x**2 - 1)*x trajectories = [] print("{time}\tStarting simulation of {total} trajectories...".format( total =N_sim, time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) for i in range(N_sim): print("{time}\tRunning simulation {cur_int} of {total}...".format(cur_int=i+1, total =N_sim, time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), end='\r') # # generate array containing current trajectory current_trajectory = np.zeros(N_steps[i]+1,dtype=float) # generate initial condition for current trajectory current_trajectory[0] = rng.random()*(x_R-x_L) + x_L # # generate all random numbers for the current simulation random_numbers_for_current_simulation = rng.normal(size=N_steps[i]) random_numbers_for_current_simulation *= np.sqrt(2*D*dt) # # run simulation using Euler-Maruyama algorithm for j,current_x in enumerate(current_trajectory[:-1]): current_trajectory[j+1] = dt*a(current_x) \ + random_numbers_for_current_simulation[j] \ + current_x # # append current trajectory to list of trajectories trajectories.append(current_trajectory[::stride_out]) print("{time}\tFinished simulation {total} trajectories. ".format( total =N_sim, time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), end='\n') # save resulting trajectories pickle.dump(trajectories,open(Fn,'wb')) import numpy as np import pickle class inference: ''' This is the base class that contains the shared codebase for both the linear and nonlinear integrators ''' def __init__(self,parameters={}): ''' Set simulation parameters, which are provided as dictionary in the argument parameters ''' # self.trajectories_loaded = False self.index_loaded = False # self.verbose = True # default value for verbose self.index_directory = './' # default value for index directory # # the following parameters need to be set by the user self.trajectories_filename = 'not set' self.xl = -np.inf self.xr = +np.inf self.N_bins = 100 self.dt = 'not set' # the following two parameters are calculated by the program # and cannot be set manually self.dx = 'not set' self.x = 'not set' # self.set_parameters(parameters) def set_parameters(self,parameters={}): ''' Change parameters of an existing instance of this class ''' # try: self.verbose = parameters['verbose'] except KeyError: pass # try: self.trajectories_filename = parameters['trajectories_filename'] except KeyError: pass # try: self.index_directory = parameters['index_directory'] except KeyError: pass # try: self.xl = parameters['xl'] except KeyError: pass # try: self.xr = parameters['xr'] except KeyError: pass # try: self.N_bins = parameters['N_bins'] except KeyError: pass # try: self.dt = parameters['dt'] except KeyError: pass # # update arrays # if self.xl > -np.inf and self.xr < np.inf: self.dx = (self.xr - self.xl)/self.N_bins if self.N_bins != 'not set': self.x = self.xl + (np.arange(self.N_bins) + 0.5)*self.dx def get_parameters(self,print_parameters=False): ''' Return current parameters ''' self.index_parameters = { 'trajectories_filename':self.trajectories_filename, 'index_directory':self.index_directory, 'xl':self.xl, 'xr':self.xr, 'dx':self.dx, 'dt':self.dt, 'N_bins':self.N_bins, 'x':self.x } if print_parameters: print("Parameters set for this instance:") print("trajectories_filename = {0}".format( self.trajectories_filename)) print("index_directory = {0}".format( self.index_directory)) print("xl = {0}".format(self.xl)) print("xr = {0}".format(self.xr)) print("dx = {0}".format(self.dx)) print("dt = {0}".format(self.dt)) print("N_bins = {0}".format(self.N_bins)) return self.index_parameters def save_parameters(self): ''' Save current parameters ''' # pickle.dump( self.get_parameters(print_parameters=False), open( self.index_directory + "/index_parameters.pkl", "wb" ) ) def load_parameters(self): ''' Load saved parameters ''' # index_parameters = pickle.load( open( self.index_directory + "/index_parameters.pkl", "rb" ) ) self.set_parameters(index_parameters) def check_if_all_parameters_are_set(self): ''' Check if all the parameters necessary for inference are set ''' # if self.trajectories_filename == 'not set': raise RuntimeError("Filename for input trajectories not set.") # if self.dt == 'not set': raise RuntimeError("Timestep not set.") def load_trajectories(self): # self.trajectory_lengths = [] # if self.trajectories_filename == 'not set': raise RuntimeError("No filename for trajectories to load "\ + "provided.") # self.trajectories = pickle.load(open(f"./data/{self.trajectories_filename}", "rb")) # for i, current_trajectory in enumerate(self.trajectories): self.trajectory_lengths.append(len(current_trajectory)) if self.verbose: print("Loaded {0} trajectories.".format(len(self.trajectories))) # self.trajectories_loaded = True # self.get_range_of_time_series() self.check_bounds_of_spatial_domain() def import_trajectories(self,trajectories): # self.trajectories = [] self.trajectory_lengths = [] # for i, current_trajectory in enumerate(trajectories): self.trajectories.append(current_trajectory) self.trajectory_lengths.append(len(current_trajectory)) # if self.verbose: print("Imported {0} trajectories.".format(len(self.trajectories))) # self.trajectories_loaded = True # self.get_range_of_time_series() self.check_bounds_of_spatial_domain() def get_range_of_time_series(self): # if self.trajectories_loaded == False: raise RuntimeError("Please load trajectories first.") # max_pos = -np.inf min_pos = np.inf for i, current_trajectory in enumerate(self.trajectories): cur_max = np.max(current_trajectory) cur_min = np.min(current_trajectory) if cur_max > max_pos: max_pos = cur_max if cur_min < min_pos: min_pos = cur_min ''' if self.verbose: print("For currently loaded trajectories, minimal and maximal "\ + "positions are {0:3.5f} and {1:3.5f}".format(min_pos,max_pos)) '''; self.min_pos = min_pos self.max_pos = max_pos def check_bounds_of_spatial_domain(self): # if self.xl < self.min_pos: if self.xl != -np.inf: print("Warning: l0 < (minimal position in dataset), i.e." \ + " {0:3.5f} < {1:3.5f}.".format(self.xl,self.min_pos) \ + "\n\tUsing l0 = {0:3.5f}".format(self.min_pos)) self.xl = self.min_pos # if self.xr > self.max_pos: if self.xr != np.inf: print("Warning: r0 > (maximal position in dataset), i.e." \ + " {0:3.5f} > {1:3.5f}.".format(self.xr,self.max_pos) \ + "\n\tUsing r0 = {0:3.5f}".format(self.max_pos)) self.xr = self.max_pos # update parameters so that dx gets calculated again if # self.xl or self.xr have changed self.set_parameters() def get_histogram(self,N_hist=100): # bin_edges = np.linspace(self.xl,self.xr, endpoint=True, num=N_hist+1, dtype=float) bin_centers = (bin_edges[1:] + bin_edges[:-1])/2. dx_bins = bin_edges[1] - bin_edges[0] hist = np.zeros(N_hist,dtype=float) # for i, current_trajectory in enumerate(self.trajectories): # bin_numbers = (current_trajectory - bin_edges[0]) // dx_bins for j in range(N_hist): hist[j] += np.sum( bin_numbers == j ) # return hist, bin_edges def create_index(self): # # check that trajectories are loaded if self.trajectories_loaded == False: raise RuntimeError("Please load trajectories first.") # # # traj_number: enumerates the trajectories we consider # traj_index: enumerates the timestep within each trajectory # traj_bin_index: contains the bin index of the current position of the current trajectory # self.traj_number = np.array([],dtype=int) self.traj_index = np.array([],dtype=int) self.traj_bin_index = np.array([],dtype=int) # update_frequency = np.max([len(self.trajectories) // 100,1]) # for i,current_trajectory in enumerate(self.trajectories): if self.verbose: if i % update_frequency == 0: print('Creating index. '\ + 'Processing trajectory {0} of {1}..'.format( i+1,len(self.trajectories) ),end='\r') current_indices = np.array((current_trajectory-self.xl)//self.dx, dtype=int) # # number of current trajectory self.traj_number = np.append(self.traj_number, np.ones(len(current_indices))*i) # positions within current trajectory self.traj_index = np.append(self.traj_index, np.arange(len(current_indices))) # index of bins self.traj_bin_index = np.append(self.traj_bin_index, current_indices) # self.traj_bin_indices = [] for i in range(self.N_bins): self.traj_bin_indices.append( np.array(np.where(self.traj_bin_index == i)[0],dtype=int) ) # self.traj_number = self.traj_number.astype(int) self.traj_index = self.traj_index.astype(int) # self.index_loaded = True # if self.verbose: print('Finished creating index. Processed {0} trajectories. '.format( len(self.trajectories) ),end='\n') # #return traj_number ,traj_index, traj_bin_indices def save_index(self): # if self.index_loaded == False: raise RuntimeError("No index loaded, so no index can be saved.") # self.save_parameters() # pickle.dump( self.traj_number, open( self.index_directory + "/index_traj_number.pkl", "wb" ) ) pickle.dump( self.traj_index, open( self.index_directory + "/index.pkl", "wb" ) ) pickle.dump( self.traj_bin_indices, open( self.index_directory + "/index_bin_indices.pkl", "wb" ) ) # def load_index(self): # self.load_parameters() # self.traj_number = pickle.load( open( self.index_directory + "/index_traj_number.pkl", "rb" ) ) self.traj_index = pickle.load( open( self.index_directory + "/index.pkl", "rb" ) ) self.traj_bin_indices = pickle.load( open( self.index_directory + "/index_bin_indices.pkl", "rb" ) ) # def run_inference(self,N_shift=1): # D_array = np.zeros(self.N_bins,dtype=float) a_array = np.zeros(self.N_bins,dtype=float) # for i in range(self.N_bins): if self.verbose: print('Running inference. Processing bin {0} of {1}..'.format( i+1,self.N_bins),end='\r') D_array[i], a_array[i] = self.kramers_moyal_single_bin( bin_index=i, N_shift=N_shift) if self.verbose: print('Finished inference with {0} bins. '.format( self.N_bins),end='\n') # output_dictionary = {'x':self.x, 'D':D_array, 'a':a_array} return output_dictionary def kramers_moyal_single_bin(self, bin_index,N_shift): # get list of trajectories starting in given bin list_of_trajectories_starting_in_bin = self.traj_bin_indices[bin_index] N = len(list_of_trajectories_starting_in_bin) # set up variables for <x>, <x^2>, which we want to estimate from data delta_x = 0. delta_x_squared = 0. # iterate through all trajectories that start in bin for i,cur_index in enumerate(list_of_trajectories_starting_in_bin): # note that traj_index[cur_index] labels the time at which the trajectory # with number traj_number[cur_index] is in the bin of interest. # if (self.traj_index[cur_index]+N_shift) >= \ self.trajectory_lengths[self.traj_number[cur_index]]: # this means that the length of the current trajectory segment # is less than the lagtime we want to use. In that case we # skip the current trajectory segment, but since we now have # one datapoint less we need to subtract 1 from N N -= 1 continue # cur_diff = self.trajectories[self.traj_number[cur_index]] \ [self.traj_index[cur_index]+N_shift] \ - self.trajectories[self.traj_number[cur_index]] \ [self.traj_index[cur_index]] # delta_x += cur_diff delta_x_squared += cur_diff**2 # if N == 0: print('Warning: Encountered a bin with N = 0 datapoints. To avoid '\ + 'this issue, please i) change the interval size [xl,xr], '\ + 'ii) decrease N_shift, or iii) use longer '\ + 'trajectories.') return np.nan, np.nan # D = delta_x_squared /(2*N*self.dt*N_shift) drift = delta_x / (N*self.dt*N_shift) # return D, drift # the pickle file should contain a list of 1D arrays, i.e. trajectories = pickle.load(open(f"./data/{name_data}", "rb")) # must lead to an object "trajectories" such that # trajectories[i] = 1D array # for i = 0, ..., len(trajectories) print("number of elements: ", len(trajectories)) print("one element: ", trajectories[0].shape, "first column:", trajectories[0][0]) # directory where the index we create will be saved: index_directory = './' # timestep of the trajectories dt = 1e-4 # create a dictionary with the parameters parameters = {'index_directory':index_directory, 'trajectories_filename':name_data, 'dt':dt} # create an instance of the kramers_moyal class inference = inference(parameters) # parameters of an existing class can be changed by creating a dictionary # with the new parameters, and by passing that dictionary to the class: N_bins = 120 updated_parameters = {'N_bins':N_bins} inference.set_parameters(updated_parameters) inference.get_parameters() inference inference.get_parameters() # parameters of an existing class can be changed by creating a dictionary # with the new parameters, and by passing that dictionary to the class: N_bins = 120 updated_parameters = {'N_bins':N_bins} inference.set_parameters(updated_parameters) inference.get_parameters() # the trajectories are loaded from the pickle file stored in the class variable "trajectories_filename" inference.load_trajectories() # instead of loading a pickle file, already loaded trajectories can alternatively be imported, via: # # preloaded_trajectories = [ list of 1D arrays with trajectories ] # inference.import_trajectories(preloaded_trajectories) # Note that only one list of trajectories can be loaded at one time. If several datasets are to be used, # they should be merged before passing them to the inference class. # after loading trajectories, the class variables # xl, xr, dx, x # are automatically updated: inference.get_parameters() # to see how many datapoints are available within each bin, we create # a histogram of the loaded data: N_hist = N_bins # we use the same number of bins as for the inference hist, bin_edges = inference.get_histogram(N_hist=N_hist) bin_centers = (bin_edges[1:] + bin_edges[:-1])/2. bar_width = bin_centers[1] - bin_centers[0] fig,ax = plt.subplots(1,1,figsize=(10,6)) ax.bar(bin_centers,hist,width=bar_width, alpha=0.5) ax.set_yscale('log') plt.show() plt.close(fig) inference.create_index() inference.save_index() # delete instance of class del inference # create new instance of the class, which needs to know where we store the index files, # and where we store the trajectories parameters = {'index_directory':index_directory, 'trajectories_filename':name_data} inference = inference(parameters=parameters) inference.load_trajectories() inference.load_index() # upon loading the index, all parameters from the previous instance are recovered: inference.get_parameters() # if the inference is run without an argument, the value N_shift = 1 is used inference_result = inference.run_inference() # = inference.run_inference(N_shift=1) # the call returns a dictionary with the bin centers x, as well as the # inferred diffusivity and drift at those bin centers: x = inference_result['x'] D = inference_result['D'] a = inference_result['a'] # we plot the results, and compare them to the input D and a(x) used for # generating the sample data: fig,axes = plt.subplots(1,2,figsize=(15,6)) fig.subplots_adjust(wspace=0.3) ax = axes[0] ax.set_title('Diffusivity') ax.plot(x,D, label=r'inferred $D(x)$') ax.axhline(1., dashes=[4,4], label='$D$ used to generate sample data', color='black') ax.set_ylim(0.8,1.2) ax.set_xlim(np.min(x),np.max(x)) ax.legend(loc='best') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$D(x)$') ax = axes[1] ax.set_title('Drift') ax.plot(x,a, label=r'inferred $a(x)$') ax.plot(x,-4*2*(x**2-1)*x, dashes=[4,4], label=r'$a(x)$ used to generate sample data', color='black') ax.set_xlim(np.min(x),np.max(x)) ax.legend(loc='best') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$a(x)$') plt.show() plt.close(fig) N_shifts = [1,10,50,100] inference_results = [] for i,N_shift in enumerate(N_shifts): print("Running inference for N_shift = {0}".format(N_shift)) inference_result = inference.run_inference(N_shift=N_shift) inference_results.append(inference_result) fig,axes = plt.subplots(1,2,figsize=(15,6)) fig.subplots_adjust(wspace=0.3) for i, inference_result in enumerate(inference_results): x = inference_result['x'] D = inference_result['D'] a = inference_result['a'] # axes[0].plot(x,D, label=r'inferred $D(x)$, $N_{\mathrm{shift}} = $' + '{0}'.format(N_shifts[i])) axes[1].plot(x,a, label=r'inferred $a(x)$, $N_{\mathrm{shift}} = $' + '{0}'.format(N_shifts[i])) ax = axes[0] ax.set_title('Diffusivity') ax.axhline(1., dashes=[4,4], label='$D$ used to generate sample data', color='black') ax.set_ylim(0.5,1.5) ax.set_xlim(np.min(x),np.max(x)) ax.legend(loc='best') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$D(x)$') ax = axes[1] ax.set_title('Drift') ax.plot(x,-4*2*(x**2-1)*x, dashes=[4,4], label=r'$a(x)$ used to generate sample data', color='black') ax.set_ylim(-30,30) ax.set_xlim(np.min(x),np.max(x)) ax.legend(loc='best') ax.set_xlabel(r'$x$') ax.set_ylabel(r'$a(x)$') plt.show() plt.close(fig)
https://github.com/sebasmos/QuantumVE
sebasmos
#Assign these values as per your requirements. global min_qubits,max_qubits,skip_qubits,max_circuits,num_shots,Noise_Inclusion min_qubits=1 max_qubits=3 skip_qubits=1 max_circuits=3 num_shots=1000 use_XX_YY_ZZ_gates = True Noise_Inclusion = False saveplots = False Memory_utilization_plot = True Type_of_Simulator = "built_in" #Inputs are "built_in" or "FAKE" or "FAKEV2" backend_name = "FakeGuadalupeV2" #Can refer to the README files for the available backends gate_counts_plots = True #Change your Specification of Simulator in Declaring Backend Section #By Default : built_in -> qasm_simulator and FAKE -> FakeSantiago() and FAKEV2 -> FakeSantiagoV2() import numpy as np import os,json from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, execute import time import matplotlib.pyplot as plt # Import from Qiskit Aer noise module from qiskit_aer.noise import (NoiseModel, QuantumError, ReadoutError,pauli_error, depolarizing_error, thermal_relaxation_error,reset_error) # Benchmark Name benchmark_name = "Hamiltonian Simulation" # Selection of basis gate set for transpilation # Note: selector 1 is a hardware agnostic gate set basis_selector = 1 basis_gates_array = [ [], ['rx', 'ry', 'rz', 'cx'], # a common basis set, default ['cx', 'rz', 'sx', 'x'], # IBM default basis set ['rx', 'ry', 'rxx'], # IonQ default basis set ['h', 'p', 'cx'], # another common basis set ['u', 'cx'] # general unitaries basis gates ] np.random.seed(0) num_gates = 0 depth = 0 def get_QV(backend): import json # Assuming backend.conf_filename is the filename and backend.dirname is the directory path conf_filename = backend.dirname + "/" + backend.conf_filename # Open the JSON file with open(conf_filename, 'r') as file: # Load the JSON data data = json.load(file) # Extract the quantum_volume parameter QV = data.get('quantum_volume', None) return QV def checkbackend(backend_name,Type_of_Simulator): if Type_of_Simulator == "built_in": available_backends = [] for i in Aer.backends(): available_backends.append(i.name) if backend_name in available_backends: platform = backend_name return platform else: print(f"incorrect backend name or backend not available. Using qasm_simulator by default !!!!") print(f"available backends are : {available_backends}") platform = "qasm_simulator" return platform elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2": import qiskit.providers.fake_provider as fake_backends if hasattr(fake_backends,backend_name) is True: print(f"Backend {backend_name} is available for type {Type_of_Simulator}.") backend_class = getattr(fake_backends,backend_name) backend_instance = backend_class() return backend_instance else: print(f"Backend {backend_name} is not available or incorrect for type {Type_of_Simulator}. Executing with FakeSantiago!!!") if Type_of_Simulator == "FAKEV2": backend_class = getattr(fake_backends,"FakeSantiagoV2") else: backend_class = getattr(fake_backends,"FakeSantiago") backend_instance = backend_class() return backend_instance if Type_of_Simulator == "built_in": platform = checkbackend(backend_name,Type_of_Simulator) #By default using "Qasm Simulator" backend = Aer.get_backend(platform) QV_=None print(f"{platform} device is capable of running {backend.num_qubits}") print(f"backend version is {backend.backend_version}") elif Type_of_Simulator == "FAKE": basis_selector = 0 backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.properties().backend_name +"-"+ backend.properties().backend_version #Replace this string with the backend Provider's name as this is used for Plotting. max_qubits=backend.configuration().n_qubits print(f"{platform} device is capable of running {backend.configuration().n_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") elif Type_of_Simulator == "FAKEV2": basis_selector = 0 if "V2" not in backend_name: backend_name = backend_name+"V2" backend = checkbackend(backend_name,Type_of_Simulator) QV_ = get_QV(backend) platform = backend.name +"-" +backend.backend_version max_qubits=backend.num_qubits print(f"{platform} device is capable of running {backend.num_qubits}") print(f"{platform} has QV={QV_}") if max_qubits > 30: print(f"Device is capable with max_qubits = {max_qubits}") max_qubit = 30 print(f"Using fake backend {platform} with max_qubits {max_qubits}") else: print("Enter valid Simulator.....") # saved circuits and subcircuits for display QC_ = None XX_ = None YY_ = None ZZ_ = None XXYYZZ_ = None # import precalculated data to compare against filename = os.path.join("precalculated_data.json") with open(filename, 'r') as file: data = file.read() precalculated_data = json.loads(data) ############### Circuit Definition def HamiltonianSimulation(n_spins, K, t, w, h_x, h_z): ''' Construct a Qiskit circuit for Hamiltonian Simulation :param n_spins:The number of spins to simulate :param K: The Trotterization order :param t: duration of simulation :return: return a Qiskit circuit for this Hamiltonian ''' num_qubits = n_spins secret_int = f"{K}-{t}" # allocate qubits qr = QuantumRegister(n_spins); cr = ClassicalRegister(n_spins); qc = QuantumCircuit(qr, cr, name=f"hamsim-{num_qubits}-{secret_int}") tau = t / K # start with initial state of 1010101... for k in range(0, n_spins, 2): qc.x(qr[k]) qc.barrier() # loop over each trotter step, adding gates to the circuit defining the hamiltonian for k in range(K): # the Pauli spin vector product [qc.rx(2 * tau * w * h_x[i], qr[i]) for i in range(n_spins)] [qc.rz(2 * tau * w * h_z[i], qr[i]) for i in range(n_spins)] qc.barrier() # Basic implementation of exp(i * t * (XX + YY + ZZ)) if _use_XX_YY_ZZ_gates: # XX operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(xx_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # YY operator on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(yy_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # ZZ operation on each pair of qubits in linear chain for j in range(2): for i in range(j%2, n_spins - 1, 2): qc.append(zz_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) # Use an optimal XXYYZZ combined operator # See equation 1 and Figure 6 in https://arxiv.org/pdf/quant-ph/0308006.pdf else: # optimized XX + YY + ZZ operator on each pair of qubits in linear chain for j in range(2): for i in range(j % 2, n_spins - 1, 2): qc.append(xxyyzz_opt_gate(tau).to_instruction(), [qr[i], qr[(i + 1) % n_spins]]) qc.barrier() # measure all the qubits used in the circuit for i_qubit in range(n_spins): qc.measure(qr[i_qubit], cr[i_qubit]) # save smaller circuit example for display global QC_ if QC_ == None or n_spins <= 6: if n_spins < 9: QC_ = qc return qc ############### XX, YY, ZZ Gate Implementations # Simple XX gate on q0 and q1 with angle 'tau' def xx_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xx_gate") qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) # save circuit example for display global XX_ XX_ = qc return qc # Simple YY gate on q0 and q1 with angle 'tau' def yy_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="yy_gate") qc.s(qr[0]) qc.s(qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) qc.h(qr[0]) qc.h(qr[1]) qc.sdg(qr[0]) qc.sdg(qr[1]) # save circuit example for display global YY_ YY_ = qc return qc # Simple ZZ gate on q0 and q1 with angle 'tau' def zz_gate(tau): qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="zz_gate") qc.cx(qr[0], qr[1]) qc.rz(3.1416*tau, qr[1]) qc.cx(qr[0], qr[1]) # save circuit example for display global ZZ_ ZZ_ = qc return qc # Optimal combined XXYYZZ gate (with double coupling) on q0 and q1 with angle 'tau' def xxyyzz_opt_gate(tau): alpha = tau; beta = tau; gamma = tau qr = QuantumRegister(2); qc = QuantumCircuit(qr, name="xxyyzz_opt") qc.rz(3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(3.1416*gamma - 3.1416/2, qr[0]) qc.ry(3.1416/2 - 3.1416*alpha, qr[1]) qc.cx(qr[0], qr[1]) qc.ry(3.1416*beta - 3.1416/2, qr[1]) qc.cx(qr[1], qr[0]) qc.rz(-3.1416/2, qr[0]) # save circuit example for display global XXYYZZ_ XXYYZZ_ = qc return qc # Create an empty noise model noise_parameters = NoiseModel() if Type_of_Simulator == "built_in": # Add depolarizing error to all single qubit gates with error rate 0.05% and to all two qubit gates with error rate 0.5% depol_one_qb_error = 0.05 depol_two_qb_error = 0.005 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(depol_two_qb_error, 2), ['cx']) # Add amplitude damping error to all single qubit gates with error rate 0.0% and to all two qubit gates with error rate 0.0% amp_damp_one_qb_error = 0.0 amp_damp_two_qb_error = 0.0 noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_one_qb_error, 1), ['rx', 'ry', 'rz']) noise_parameters.add_all_qubit_quantum_error(depolarizing_error(amp_damp_two_qb_error, 2), ['cx']) # Add reset noise to all single qubit resets reset_to_zero_error = 0.005 reset_to_one_error = 0.005 noise_parameters.add_all_qubit_quantum_error(reset_error(reset_to_zero_error, reset_to_one_error),["reset"]) # Add readout error p0given1_error = 0.000 p1given0_error = 0.000 error_meas = ReadoutError([[1 - p1given0_error, p1given0_error], [p0given1_error, 1 - p0given1_error]]) noise_parameters.add_all_qubit_readout_error(error_meas) #print(noise_parameters) elif Type_of_Simulator == "FAKE"or"FAKEV2": noise_parameters = NoiseModel.from_backend(backend) #print(noise_parameters) ### Analysis methods to be expanded and eventually compiled into a separate analysis.py file import math, functools def hellinger_fidelity_with_expected(p, q): """ p: result distribution, may be passed as a counts distribution q: the expected distribution to be compared against References: `Hellinger Distance @ wikipedia <https://en.wikipedia.org/wiki/Hellinger_distance>`_ Qiskit Hellinger Fidelity Function """ p_sum = sum(p.values()) q_sum = sum(q.values()) if q_sum == 0: print("ERROR: polarization_fidelity(), expected distribution is invalid, all counts equal to 0") return 0 p_normed = {} for key, val in p.items(): p_normed[key] = val/p_sum # if p_sum != 0: # p_normed[key] = val/p_sum # else: # p_normed[key] = 0 q_normed = {} for key, val in q.items(): q_normed[key] = val/q_sum total = 0 for key, val in p_normed.items(): if key in q_normed.keys(): total += (np.sqrt(val) - np.sqrt(q_normed[key]))**2 del q_normed[key] else: total += val total += sum(q_normed.values()) # in some situations (error mitigation) this can go negative, use abs value if total < 0: print(f"WARNING: using absolute value in fidelity calculation") total = abs(total) dist = np.sqrt(total)/np.sqrt(2) fidelity = (1-dist**2)**2 return fidelity def polarization_fidelity(counts, correct_dist, thermal_dist=None): """ Combines Hellinger fidelity and polarization rescaling into fidelity calculation used in every benchmark counts: the measurement outcomes after `num_shots` algorithm runs correct_dist: the distribution we expect to get for the algorithm running perfectly thermal_dist: optional distribution to pass in distribution from a uniform superposition over all states. If `None`: generated as `uniform_dist` with the same qubits as in `counts` returns both polarization fidelity and the hellinger fidelity Polarization from: `https://arxiv.org/abs/2008.11294v1` """ num_measured_qubits = len(list(correct_dist.keys())[0]) #print(num_measured_qubits) counts = {k.zfill(num_measured_qubits): v for k, v in counts.items()} # calculate hellinger fidelity between measured expectation values and correct distribution hf_fidelity = hellinger_fidelity_with_expected(counts,correct_dist) # to limit cpu and memory utilization, skip noise correction if more than 16 measured qubits if num_measured_qubits > 16: return { 'fidelity':hf_fidelity, 'hf_fidelity':hf_fidelity } # if not provided, generate thermal dist based on number of qubits if thermal_dist == None: thermal_dist = uniform_dist(num_measured_qubits) # set our fidelity rescaling value as the hellinger fidelity for a depolarized state floor_fidelity = hellinger_fidelity_with_expected(thermal_dist, correct_dist) # rescale fidelity result so uniform superposition (random guessing) returns fidelity # rescaled to 0 to provide a better measure of success of the algorithm (polarization) new_floor_fidelity = 0 fidelity = rescale_fidelity(hf_fidelity, floor_fidelity, new_floor_fidelity) return { 'fidelity':fidelity, 'hf_fidelity':hf_fidelity } ## Uniform distribution function commonly used def rescale_fidelity(fidelity, floor_fidelity, new_floor_fidelity): """ Linearly rescales our fidelities to allow comparisons of fidelities across benchmarks fidelity: raw fidelity to rescale floor_fidelity: threshold fidelity which is equivalent to random guessing new_floor_fidelity: what we rescale the floor_fidelity to Ex, with floor_fidelity = 0.25, new_floor_fidelity = 0.0: 1 -> 1; 0.25 -> 0; 0.5 -> 0.3333; """ rescaled_fidelity = (1-new_floor_fidelity)/(1-floor_fidelity) * (fidelity - 1) + 1 # ensure fidelity is within bounds (0, 1) if rescaled_fidelity < 0: rescaled_fidelity = 0.0 if rescaled_fidelity > 1: rescaled_fidelity = 1.0 return rescaled_fidelity def uniform_dist(num_state_qubits): dist = {} for i in range(2**num_state_qubits): key = bin(i)[2:].zfill(num_state_qubits) dist[key] = 1/(2**num_state_qubits) return dist from matplotlib.patches import Rectangle import matplotlib.cm as cm from matplotlib.colors import ListedColormap, LinearSegmentedColormap, Normalize from matplotlib.patches import Circle ############### Color Map functions # Create a selection of colormaps from which to choose; default to custom_spectral cmap_spectral = plt.get_cmap('Spectral') cmap_greys = plt.get_cmap('Greys') cmap_blues = plt.get_cmap('Blues') cmap_custom_spectral = None # the default colormap is the spectral map cmap = cmap_spectral cmap_orig = cmap_spectral # current cmap normalization function (default None) cmap_norm = None default_fade_low_fidelity_level = 0.16 default_fade_rate = 0.7 # Specify a normalization function here (default None) def set_custom_cmap_norm(vmin, vmax): global cmap_norm if vmin == vmax or (vmin == 0.0 and vmax == 1.0): print("... setting cmap norm to None") cmap_norm = None else: print(f"... setting cmap norm to [{vmin}, {vmax}]") cmap_norm = Normalize(vmin=vmin, vmax=vmax) # Remake the custom spectral colormap with user settings def set_custom_cmap_style( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): #print("... set custom map style") global cmap, cmap_custom_spectral, cmap_orig cmap_custom_spectral = create_custom_spectral_cmap( fade_low_fidelity_level=fade_low_fidelity_level, fade_rate=fade_rate) cmap = cmap_custom_spectral cmap_orig = cmap_custom_spectral # Create the custom spectral colormap from the base spectral def create_custom_spectral_cmap( fade_low_fidelity_level=default_fade_low_fidelity_level, fade_rate=default_fade_rate): # determine the breakpoint from the fade level num_colors = 100 breakpoint = round(fade_low_fidelity_level * num_colors) # get color list for spectral map spectral_colors = [cmap_spectral(v/num_colors) for v in range(num_colors)] #print(fade_rate) # create a list of colors to replace those below the breakpoint # and fill with "faded" color entries (in reverse) low_colors = [0] * breakpoint #for i in reversed(range(breakpoint)): for i in range(breakpoint): # x is index of low colors, normalized 0 -> 1 x = i / breakpoint # get color at this index bc = spectral_colors[i] r0 = bc[0] g0 = bc[1] b0 = bc[2] z0 = bc[3] r_delta = 0.92 - r0 #print(f"{x} {bc} {r_delta}") # compute saturation and greyness ratio sat_ratio = 1 - x #grey_ratio = 1 - x ''' attempt at a reflective gradient if i >= breakpoint/2: xf = 2*(x - 0.5) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (yf + 0.5) else: xf = 2*(0.5 - x) yf = pow(xf, 1/fade_rate)/2 grey_ratio = 1 - (0.5 - yf) ''' grey_ratio = 1 - math.pow(x, 1/fade_rate) #print(f" {xf} {yf} ") #print(f" {sat_ratio} {grey_ratio}") r = r0 + r_delta * sat_ratio g_delta = r - g0 b_delta = r - b0 g = g0 + g_delta * grey_ratio b = b0 + b_delta * grey_ratio #print(f"{r} {g} {b}\n") low_colors[i] = (r,g,b,z0) #print(low_colors) # combine the faded low colors with the regular spectral cmap to make a custom version cmap_custom_spectral = ListedColormap(low_colors + spectral_colors[breakpoint:]) #spectral_colors = [cmap_custom_spectral(v/10) for v in range(10)] #for i in range(10): print(spectral_colors[i]) #print("") return cmap_custom_spectral # Make the custom spectral color map the default on module init set_custom_cmap_style() # Arrange the stored annotations optimally and add to plot def anno_volumetric_data(ax, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True): # sort all arrays by the x point of the text (anno_offs) global x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos all_annos = sorted(zip(x_anno_offs, y_anno_offs, anno_labels, x_annos, y_annos)) x_anno_offs = [a for a,b,c,d,e in all_annos] y_anno_offs = [b for a,b,c,d,e in all_annos] anno_labels = [c for a,b,c,d,e in all_annos] x_annos = [d for a,b,c,d,e in all_annos] y_annos = [e for a,b,c,d,e in all_annos] #print(f"{x_anno_offs}") #print(f"{y_anno_offs}") #print(f"{anno_labels}") for i in range(len(anno_labels)): x_anno = x_annos[i] y_anno = y_annos[i] x_anno_off = x_anno_offs[i] y_anno_off = y_anno_offs[i] label = anno_labels[i] if i > 0: x_delta = abs(x_anno_off - x_anno_offs[i - 1]) y_delta = abs(y_anno_off - y_anno_offs[i - 1]) if y_delta < 0.7 and x_delta < 2: y_anno_off = y_anno_offs[i] = y_anno_offs[i - 1] - 0.6 #x_anno_off = x_anno_offs[i] = x_anno_offs[i - 1] + 0.1 ax.annotate(label, xy=(x_anno+0.0, y_anno+0.1), arrowprops=dict(facecolor='black', shrink=0.0, width=0.5, headwidth=4, headlength=5, edgecolor=(0.8,0.8,0.8)), xytext=(x_anno_off + labelpos[0], y_anno_off + labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='baseline', color=(0.2,0.2,0.2), clip_on=True) if saveplots == True: plt.savefig("VolumetricPlotSample.jpg") # Plot one group of data for volumetric presentation def plot_volumetric_data(ax, w_data, d_data, f_data, depth_base=2, label='Depth', labelpos=(0.2, 0.7), labelrot=0, type=1, fill=True, w_max=18, do_label=False, do_border=True, x_size=1.0, y_size=1.0, zorder=1, offset_flag=False, max_depth=0, suppress_low_fidelity=False): # since data may come back out of order, save point at max y for annotation i_anno = 0 x_anno = 0 y_anno = 0 # plot data rectangles low_fidelity_count = True last_y = -1 k = 0 # determine y-axis dimension for one pixel to use for offset of bars that start at 0 (_, dy) = get_pixel_dims(ax) # do this loop in reverse to handle the case where earlier cells are overlapped by later cells for i in reversed(range(len(d_data))): x = depth_index(d_data[i], depth_base) y = float(w_data[i]) f = f_data[i] # each time we star a new row, reset the offset counter # DEVNOTE: this is highly specialized for the QA area plots, where there are 8 bars # that represent time starting from 0 secs. We offset by one pixel each and center the group if y != last_y: last_y = y; k = 3 # hardcoded for 8 cells, offset by 3 #print(f"{i = } {x = } {y = }") if max_depth > 0 and d_data[i] > max_depth: #print(f"... excessive depth (2), skipped; w={y} d={d_data[i]}") break; # reject cells with low fidelity if suppress_low_fidelity and f < suppress_low_fidelity_level: if low_fidelity_count: break else: low_fidelity_count = True # the only time this is False is when doing merged gradation plots if do_border == True: # this case is for an array of x_sizes, i.e. each box has different width if isinstance(x_size, list): # draw each of the cells, with no offset if not offset_flag: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size[i], y_size=y_size, zorder=zorder)) # use an offset for y value, AND account for x and width to draw starting at 0 else: ax.add_patch(box_at((x/2 + x_size[i]/4), y + k*dy, f, type=type, fill=fill, x_size=x+ x_size[i]/2, y_size=y_size, zorder=zorder)) # this case is for only a single cell else: ax.add_patch(box_at(x, y, f, type=type, fill=fill, x_size=x_size, y_size=y_size)) # save the annotation point with the largest y value if y >= y_anno: x_anno = x y_anno = y i_anno = i # move the next bar down (if using offset) k -= 1 # if no data rectangles plotted, no need for a label if x_anno == 0 or y_anno == 0: return x_annos.append(x_anno) y_annos.append(y_anno) anno_dist = math.sqrt( (y_anno - 1)**2 + (x_anno - 1)**2 ) # adjust radius of annotation circle based on maximum width of apps anno_max = 10 if w_max > 10: anno_max = 14 if w_max > 14: anno_max = 18 scale = anno_max / anno_dist # offset of text from end of arrow if scale > 1: x_anno_off = scale * x_anno - x_anno - 0.5 y_anno_off = scale * y_anno - y_anno else: x_anno_off = 0.7 y_anno_off = 0.5 x_anno_off += x_anno y_anno_off += y_anno # print(f"... {xx} {yy} {anno_dist}") x_anno_offs.append(x_anno_off) y_anno_offs.append(y_anno_off) anno_labels.append(label) if do_label: ax.annotate(label, xy=(x_anno+labelpos[0], y_anno+labelpos[1]), rotation=labelrot, horizontalalignment='left', verticalalignment='bottom', color=(0.2,0.2,0.2)) x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # init arrays to hold annotation points for label spreading def vplot_anno_init (): global x_annos, y_annos, x_anno_offs, y_anno_offs, anno_labels x_annos = [] y_annos = [] x_anno_offs = [] y_anno_offs = [] anno_labels = [] # Number of ticks on volumetric depth axis max_depth_log = 22 # average transpile factor between base QV depth and our depth based on results from QV notebook QV_transpile_factor = 12.7 # format a number using K,M,B,T for large numbers, optionally rounding to 'digits' decimal places if num > 1 # (sign handling may be incorrect) def format_number(num, digits=0): if isinstance(num, str): num = float(num) num = float('{:.3g}'.format(abs(num))) sign = '' metric = {'T': 1000000000000, 'B': 1000000000, 'M': 1000000, 'K': 1000, '': 1} for index in metric: num_check = num / metric[index] if num_check >= 1: num = round(num_check, digits) sign = index break numstr = f"{str(num)}" if '.' in numstr: numstr = numstr.rstrip('0').rstrip('.') return f"{numstr}{sign}" # Return the color associated with the spcific value, using color map norm def get_color(value): # if there is a normalize function installed, scale the data if cmap_norm: value = float(cmap_norm(value)) if cmap == cmap_spectral: value = 0.05 + value*0.9 elif cmap == cmap_blues: value = 0.00 + value*1.0 else: value = 0.0 + value*0.95 return cmap(value) # Return the x and y equivalent to a single pixel for the given plot axis def get_pixel_dims(ax): # transform 0 -> 1 to pixel dimensions pixdims = ax.transData.transform([(0,1),(1,0)])-ax.transData.transform((0,0)) xpix = pixdims[1][0] ypix = pixdims[0][1] #determine x- and y-axis dimension for one pixel dx = (1 / xpix) dy = (1 / ypix) return (dx, dy) ############### Helper functions # return the base index for a circuit depth value # take the log in the depth base, and add 1 def depth_index(d, depth_base): if depth_base <= 1: return d if d == 0: return 0 return math.log(d, depth_base) + 1 # draw a box at x,y with various attributes def box_at(x, y, value, type=1, fill=True, x_size=1.0, y_size=1.0, alpha=1.0, zorder=1): value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Rectangle((x - (x_size/2), y - (y_size/2)), x_size, y_size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.5*y_size, zorder=zorder) # draw a circle at x,y with various attributes def circle_at(x, y, value, type=1, fill=True): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.5,0.5,0.5) return Circle((x, y), size/2, alpha = 0.7, # DEVNOTE: changed to 0.7 from 0.5, to handle only one cell edgecolor = ec, facecolor = fc, fill=fill, lw=0.5) def box4_at(x, y, value, type=1, fill=True, alpha=1.0): size = 1.0 value = min(value, 1.0) value = max(value, 0.0) fc = get_color(value) ec = (0.3,0.3,0.3) ec = fc return Rectangle((x - size/8, y - size/2), size/4, size, alpha=alpha, edgecolor = ec, facecolor = fc, fill=fill, lw=0.1) # Draw a Quantum Volume rectangle with specified width and depth, and grey-scale value def qv_box_at(x, y, qv_width, qv_depth, value, depth_base): #print(f"{qv_width} {qv_depth} {depth_index(qv_depth, depth_base)}") return Rectangle((x - 0.5, y - 0.5), depth_index(qv_depth, depth_base), qv_width, edgecolor = (value,value,value), facecolor = (value,value,value), fill=True, lw=1) def bkg_box_at(x, y, value=0.9): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (value,value,value), fill=True, lw=0.5) def bkg_empty_box_at(x, y): size = 0.6 return Rectangle((x - size/2, y - size/2), size, size, edgecolor = (.75,.75,.75), facecolor = (1.0,1.0,1.0), fill=True, lw=0.5) # Plot the background for the volumetric analysis def plot_volumetric_background(max_qubits=11, QV=32, depth_base=2, suptitle=None, avail_qubits=0, colorbar_label="Avg Result Fidelity"): if suptitle == None: suptitle = f"Volumetric Positioning\nCircuit Dimensions and Fidelity Overlaid on Quantum Volume = {QV}" QV0 = QV qv_estimate = False est_str = "" if QV == 0: # QV = 0 indicates "do not draw QV background or label" QV = 2048 elif QV < 0: # QV < 0 indicates "add est. to label" QV = -QV qv_estimate = True est_str = " (est.)" if avail_qubits > 0 and max_qubits > avail_qubits: max_qubits = avail_qubits max_width = 13 if max_qubits > 11: max_width = 18 if max_qubits > 14: max_width = 20 if max_qubits > 16: max_width = 24 if max_qubits > 24: max_width = 33 #print(f"... {avail_qubits} {max_qubits} {max_width}") plot_width = 6.8 plot_height = 0.5 + plot_width * (max_width / max_depth_log) #print(f"... {plot_width} {plot_height}") # define matplotlib figure and axis; use constrained layout to fit colorbar to right fig, ax = plt.subplots(figsize=(plot_width, plot_height), constrained_layout=True) plt.suptitle(suptitle) plt.xlim(0, max_depth_log) plt.ylim(0, max_width) # circuit depth axis (x axis) xbasis = [x for x in range(1,max_depth_log)] xround = [depth_base**(x-1) for x in xbasis] xlabels = [format_number(x) for x in xround] ax.set_xlabel('Circuit Depth') ax.set_xticks(xbasis) plt.xticks(xbasis, xlabels, color='black', rotation=45, ha='right', va='top', rotation_mode="anchor") # other label options #plt.xticks(xbasis, xlabels, color='black', rotation=-60, ha='left') #plt.xticks(xbasis, xlabels, color='black', rotation=-45, ha='left', va='center', rotation_mode="anchor") # circuit width axis (y axis) ybasis = [y for y in range(1,max_width)] yround = [1,2,3,4,5,6,7,8,10,12,15] # not used now ylabels = [str(y) for y in yround] # not used now #ax.set_ylabel('Circuit Width (Number of Qubits)') ax.set_ylabel('Circuit Width') ax.set_yticks(ybasis) #create simple line plot (not used right now) #ax.plot([0, 10],[0, 10]) log2QV = math.log2(QV) QV_width = log2QV QV_depth = log2QV * QV_transpile_factor # show a quantum volume rectangle of QV = 64 e.g. (6 x 6) if QV0 != 0: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.87, depth_base)) else: ax.add_patch(qv_box_at(1, 1, QV_width, QV_depth, 0.91, depth_base)) # the untranspiled version is commented out - we do not show this by default # also show a quantum volume rectangle un-transpiled # ax.add_patch(qv_box_at(1, 1, QV_width, QV_width, 0.80, depth_base)) # show 2D array of volumetric cells based on this QV_transpiled # DEVNOTE: we use +1 only to make the visuals work; s/b without # Also, the second arg of the min( below seems incorrect, needs correction maxprod = (QV_width + 1) * (QV_depth + 1) for w in range(1, min(max_width, round(QV) + 1)): # don't show VB squares if width greater than known available qubits if avail_qubits != 0 and w > avail_qubits: continue i_success = 0 for d in xround: # polarization factor for low circuit widths maxtest = maxprod / ( 1 - 1 / (2**w) ) # if circuit would fail here, don't draw box if d > maxtest: continue if w * d > maxtest: continue # guess for how to capture how hardware decays with width, not entirely correct # # reduce maxtext by a factor of number of qubits > QV_width # # just an approximation to account for qubit distances # if w > QV_width: # over = w - QV_width # maxtest = maxtest / (1 + (over/QV_width)) # draw a box at this width and depth id = depth_index(d, depth_base) # show vb rectangles; if not showing QV, make all hollow (or less dark) if QV0 == 0: #ax.add_patch(bkg_empty_box_at(id, w)) ax.add_patch(bkg_box_at(id, w, 0.95)) else: ax.add_patch(bkg_box_at(id, w, 0.9)) # save index of last successful depth i_success += 1 # plot empty rectangle after others d = xround[i_success] id = depth_index(d, depth_base) ax.add_patch(bkg_empty_box_at(id, w)) # Add annotation showing quantum volume if QV0 != 0: t = ax.text(max_depth_log - 2.0, 1.5, f"QV{est_str}={QV}", size=12, horizontalalignment='right', verticalalignment='center', color=(0.2,0.2,0.2), bbox=dict(boxstyle="square,pad=0.3", fc=(.9,.9,.9), ec="grey", lw=1)) # add colorbar to right of plot plt.colorbar(cm.ScalarMappable(cmap=cmap), cax=None, ax=ax, shrink=0.6, label=colorbar_label, panchor=(0.0, 0.7)) return ax # Function to calculate circuit depth def calculate_circuit_depth(qc): # Calculate the depth of the circuit depth = qc.depth() return depth def calculate_transpiled_depth(qc,basis_selector): # use either the backend or one of the basis gate sets if basis_selector == 0: qc = transpile(qc, backend) else: basis_gates = basis_gates_array[basis_selector] qc = transpile(qc, basis_gates=basis_gates, seed_transpiler=0) transpiled_depth = qc.depth() return transpiled_depth,qc def plot_fidelity_data(fidelity_data, Hf_fidelity_data, title): avg_fidelity_means = [] avg_Hf_fidelity_means = [] avg_num_qubits_values = list(fidelity_data.keys()) # Calculate the average fidelity and Hamming fidelity for each unique number of qubits for num_qubits in avg_num_qubits_values: avg_fidelity = np.average(fidelity_data[num_qubits]) avg_fidelity_means.append(avg_fidelity) avg_Hf_fidelity = np.mean(Hf_fidelity_data[num_qubits]) avg_Hf_fidelity_means.append(avg_Hf_fidelity) return avg_fidelity_means,avg_Hf_fidelity_means list_of_gates = [] def list_of_standardgates(): import qiskit.circuit.library as lib from qiskit.circuit import Gate import inspect # List all the attributes of the library module gate_list = dir(lib) # Filter out non-gate classes (like functions, variables, etc.) gates = [gate for gate in gate_list if isinstance(getattr(lib, gate), type) and issubclass(getattr(lib, gate), Gate)] # Get method names from QuantumCircuit circuit_methods = inspect.getmembers(QuantumCircuit, inspect.isfunction) method_names = [name for name, _ in circuit_methods] # Map gate class names to method names gate_to_method = {} for gate in gates: gate_class = getattr(lib, gate) class_name = gate_class.__name__.replace('Gate', '').lower() # Normalize class name for method in method_names: if method == class_name or method == class_name.replace('cr', 'c-r'): gate_to_method[gate] = method break # Add common operations that are not strictly gates additional_operations = { 'Measure': 'measure', 'Barrier': 'barrier', } gate_to_method.update(additional_operations) for k,v in gate_to_method.items(): list_of_gates.append(v) def update_counts(gates,custom_gates): operations = {} for key, value in gates.items(): operations[key] = value for key, value in custom_gates.items(): if key in operations: operations[key] += value else: operations[key] = value return operations def get_gate_counts(gates,custom_gate_defs): result = gates.copy() # Iterate over the gate counts in the quantum circuit for gate, count in gates.items(): if gate in custom_gate_defs: custom_gate_ops = custom_gate_defs[gate] # Multiply custom gate operations by the count of the custom gate in the circuit for _ in range(count): result = update_counts(result, custom_gate_ops) # Remove the custom gate entry as we have expanded it del result[gate] return result dict_of_qc = dict() custom_gates_defs = dict() # Function to count operations recursively def count_operations(qc): dict_of_qc.clear() circuit_traverser(qc) operations = dict() operations = dict_of_qc[qc.name] del dict_of_qc[qc.name] # print("operations :",operations) # print("dict_of_qc :",dict_of_qc) for keys in operations.keys(): if keys not in list_of_gates: for k,v in dict_of_qc.items(): if k in operations.keys(): custom_gates_defs[k] = v operations=get_gate_counts(operations,custom_gates_defs) custom_gates_defs.clear() return operations def circuit_traverser(qc): dict_of_qc[qc.name]=dict(qc.count_ops()) for i in qc.data: if str(i.operation.name) not in list_of_gates: qc_1 = i.operation.definition circuit_traverser(qc_1) def get_memory(): import resource usage = resource.getrusage(resource.RUSAGE_SELF) max_mem = usage.ru_maxrss/1024 #in MB return max_mem def analyzer(num_qubits): # we have precalculated the correct distribution that a perfect quantum computer will return # it is stored in the json file we import at the top of the code correct_dist = precalculated_data[f"Qubits - {num_qubits}"] return correct_dist num_state_qubits=1 #(default) not exposed to users def run (min_qubits=min_qubits, max_qubits=max_qubits, skip_qubits=skip_qubits, max_circuits=max_circuits, num_shots=num_shots, use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates): creation_times = [] elapsed_times = [] quantum_times = [] circuit_depths = [] transpiled_depths = [] fidelity_data = {} Hf_fidelity_data = {} numckts = [] mem_usage = [] algorithmic_1Q_gate_counts = [] algorithmic_2Q_gate_counts = [] transpiled_1Q_gate_counts = [] transpiled_2Q_gate_counts = [] print(f"{benchmark_name} Benchmark Program - {platform}") #defining all the standard gates supported by qiskit in a list if gate_counts_plots == True: list_of_standardgates() # validate parameters (smallest circuit is 2 qubits) max_qubits = max(2, max_qubits) min_qubits = min(max(2, min_qubits), max_qubits) if min_qubits % 2 == 1: min_qubits += 1 # min_qubits must be even skip_qubits = max(1, skip_qubits) #print(f"min, max qubits = {min_qubits} {max_qubits}") global _use_XX_YY_ZZ_gates _use_XX_YY_ZZ_gates = use_XX_YY_ZZ_gates if _use_XX_YY_ZZ_gates: print("... using unoptimized XX YY ZZ gates") global max_ckts max_ckts = max_circuits global min_qbits,max_qbits,skp_qubits min_qbits = min_qubits max_qbits = max_qubits skp_qubits = skip_qubits print(f"min, max qubits = {min_qubits} {max_qubits}") # Execute Benchmark Program N times for multiple circuit sizes for num_qubits in range(min_qubits, max_qubits + 1, skip_qubits): fidelity_data[num_qubits] = [] Hf_fidelity_data[num_qubits] = [] # reset random seed np.random.seed(0) # determine number of circuits to execute for this group num_circuits = max(1, max_circuits) print(f"Executing [{num_circuits}] circuits with num_qubits = {num_qubits}") numckts.append(num_circuits) # parameters of simulation #### CANNOT BE MODIFIED W/O ALSO MODIFYING PRECALCULATED DATA ######### w = precalculated_data['w'] # strength of disorder k = precalculated_data['k'] # Trotter error. # A large Trotter order approximates the Hamiltonian evolution better. # But a large Trotter order also means the circuit is deeper. # For ideal or noise-less quantum circuits, k >> 1 gives perfect hamiltonian simulation. t = precalculated_data['t'] # time of simulation ####################################################################### for circuit_id in range(num_circuits): print("*********************************************") print(f"qc of {num_qubits} qubits for circuit_id: {circuit_id}") #creation of Quantum Circuit. ts = time.time() h_x = precalculated_data['h_x'][:num_qubits] # precalculated random numbers between [-1, 1] h_z = precalculated_data['h_z'][:num_qubits] qc = HamiltonianSimulation(num_qubits, K=k, t=t, w=w, h_x= h_x, h_z=h_z) #creation time creation_time = time.time() - ts creation_times.append(creation_time) print(f"creation time = {creation_time*1000} ms") # Calculate gate count for the algorithmic circuit (excluding barriers and measurements) if gate_counts_plots == True: operations = count_operations(qc) n1q = 0; n2q = 0 if operations != None: for key, value in operations.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c") or key.startswith("mc"): n2q += value else: n1q += value algorithmic_1Q_gate_counts.append(n1q) algorithmic_2Q_gate_counts.append(n2q) # collapse the sub-circuit levels used in this benchmark (for qiskit) qc=qc.decompose() #print(qc) # Calculate circuit depth depth = calculate_circuit_depth(qc) circuit_depths.append(depth) # Calculate transpiled circuit depth transpiled_depth,qc = calculate_transpiled_depth(qc,basis_selector) transpiled_depths.append(transpiled_depth) #print(qc) print(f"Algorithmic Depth = {depth} and Normalized Depth = {transpiled_depth}") if gate_counts_plots == True: # Calculate gate count for the transpiled circuit (excluding barriers and measurements) tr_ops = qc.count_ops() #print("tr_ops = ",tr_ops) tr_n1q = 0; tr_n2q = 0 if tr_ops != None: for key, value in tr_ops.items(): if key == "measure": continue if key == "barrier": continue if key.startswith("c"): tr_n2q += value else: tr_n1q += value transpiled_1Q_gate_counts.append(tr_n1q) transpiled_2Q_gate_counts.append(tr_n2q) print(f"Algorithmic 1Q gates = {n1q} ,Algorithmic 2Q gates = {n2q}") print(f"Normalized 1Q gates = {tr_n1q} ,Normalized 2Q gates = {tr_n2q}") #execution if Type_of_Simulator == "built_in": #To check if Noise is required if Noise_Inclusion == True: noise_model = noise_parameters else: noise_model = None ts = time.time() job = execute(qc, backend, shots=num_shots, noise_model=noise_model) elif Type_of_Simulator == "FAKE" or Type_of_Simulator == "FAKEV2" : ts = time.time() job = backend.run(qc,shots=num_shots, noise_model=noise_parameters) #retrieving the result result = job.result() #print(result) #calculating elapsed time elapsed_time = time.time() - ts elapsed_times.append(elapsed_time) # Calculate quantum processing time quantum_time = result.time_taken quantum_times.append(quantum_time) print(f"Elapsed time = {elapsed_time*1000} ms and Quantum Time = {quantum_time*1000} ms") #counts in result object counts = result.get_counts() #Correct distribution to compare with counts correct_dist = analyzer(num_qubits) #fidelity calculation comparision of counts and correct_dist fidelity_dict = polarization_fidelity(counts, correct_dist) fidelity_data[num_qubits].append(fidelity_dict['fidelity']) Hf_fidelity_data[num_qubits].append(fidelity_dict['hf_fidelity']) #maximum memory utilization (if required) if Memory_utilization_plot == True: max_mem = get_memory() print(f"Maximum Memory Utilized: {max_mem} MB") mem_usage.append(max_mem) print("*********************************************") ########## # print a sample circuit print("Sample Circuit:"); print(QC_ if QC_ != None else " ... too large!") if _use_XX_YY_ZZ_gates: print("\nXX, YY, ZZ =") print(XX_); print(YY_); print(ZZ_) else: print("\nXXYYZZ_opt =") print(XXYYZZ_) return (creation_times, elapsed_times, quantum_times, circuit_depths, transpiled_depths, fidelity_data, Hf_fidelity_data, numckts , algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) # Execute the benchmark program, accumulate metrics, and calculate circuit depths (creation_times, elapsed_times, quantum_times, circuit_depths,transpiled_depths, fidelity_data, Hf_fidelity_data, numckts, algorithmic_1Q_gate_counts, algorithmic_2Q_gate_counts, transpiled_1Q_gate_counts, transpiled_2Q_gate_counts,mem_usage) = run() # Define the range of qubits for the x-axis num_qubits_range = range(min_qbits, max_qbits+1,skp_qubits) print("num_qubits_range =",num_qubits_range) # Calculate average creation time, elapsed time, quantum processing time, and circuit depth for each number of qubits avg_creation_times = [] avg_elapsed_times = [] avg_quantum_times = [] avg_circuit_depths = [] avg_transpiled_depths = [] avg_1Q_algorithmic_gate_counts = [] avg_2Q_algorithmic_gate_counts = [] avg_1Q_Transpiled_gate_counts = [] avg_2Q_Transpiled_gate_counts = [] max_memory = [] start = 0 for num in numckts: avg_creation_times.append(np.mean(creation_times[start:start+num])) avg_elapsed_times.append(np.mean(elapsed_times[start:start+num])) avg_quantum_times.append(np.mean(quantum_times[start:start+num])) avg_circuit_depths.append(np.mean(circuit_depths[start:start+num])) avg_transpiled_depths.append(np.mean(transpiled_depths[start:start+num])) if gate_counts_plots == True: avg_1Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_1Q_gate_counts[start:start+num]))) avg_2Q_algorithmic_gate_counts.append(int(np.mean(algorithmic_2Q_gate_counts[start:start+num]))) avg_1Q_Transpiled_gate_counts.append(int(np.mean(transpiled_1Q_gate_counts[start:start+num]))) avg_2Q_Transpiled_gate_counts.append(int(np.mean(transpiled_2Q_gate_counts[start:start+num]))) if Memory_utilization_plot == True:max_memory.append(np.max(mem_usage[start:start+num])) start += num # Calculate the fidelity data avg_f, avg_Hf = plot_fidelity_data(fidelity_data, Hf_fidelity_data, "Fidelity Comparison") # Plot histograms for average creation time, average elapsed time, average quantum processing time, and average circuit depth versus the number of qubits # Add labels to the bars def autolabel(rects,ax,str='{:.3f}',va='top',text_color="black"): for rect in rects: height = rect.get_height() ax.annotate(str.format(height), # Formatting to two decimal places xy=(rect.get_x() + rect.get_width() / 2, height / 2), xytext=(0, 0), textcoords="offset points", ha='center', va=va,color=text_color,rotation=90) bar_width = 0.3 # Determine the number of subplots and their arrangement if Memory_utilization_plot and gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(7, 1, figsize=(18, 30)) # Plotting for both memory utilization and gate counts # ax1, ax2, ax3, ax4, ax5, ax6, ax7 are available elif Memory_utilization_plot: fig, (ax1, ax2, ax3, ax6, ax7) = plt.subplots(5, 1, figsize=(18, 30)) # Plotting for memory utilization only # ax1, ax2, ax3, ax6, ax7 are available elif gate_counts_plots: fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, 1, figsize=(18, 30)) # Plotting for gate counts only # ax1, ax2, ax3, ax4, ax5, ax6 are available else: fig, (ax1, ax2, ax3, ax6) = plt.subplots(4, 1, figsize=(18, 30)) # Default plotting # ax1, ax2, ax3, ax6 are available fig.suptitle(f"General Benchmarks : {platform} - {benchmark_name}", fontsize=16) for i in range(len(avg_creation_times)): #converting seconds to milli seconds by multiplying 1000 avg_creation_times[i] *= 1000 ax1.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax1.bar(num_qubits_range, avg_creation_times, color='deepskyblue') autolabel(ax1.patches, ax1) ax1.set_xlabel('Number of Qubits') ax1.set_ylabel('Average Creation Time (ms)') ax1.set_title('Average Creation Time vs Number of Qubits',fontsize=14) ax2.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) for i in range(len(avg_elapsed_times)): #converting seconds to milli seconds by multiplying 1000 avg_elapsed_times[i] *= 1000 for i in range(len(avg_quantum_times)): #converting seconds to milli seconds by multiplying 1000 avg_quantum_times[i] *= 1000 Elapsed= ax2.bar(np.array(num_qubits_range) - bar_width / 2, avg_elapsed_times, width=bar_width, color='cyan', label='Elapsed Time') Quantum= ax2.bar(np.array(num_qubits_range) + bar_width / 2, avg_quantum_times,width=bar_width, color='deepskyblue',label ='Quantum Time') autolabel(Elapsed,ax2,str='{:.1f}') autolabel(Quantum,ax2,str='{:.1f}') ax2.set_xlabel('Number of Qubits') ax2.set_ylabel('Average Time (ms)') ax2.set_title('Average Time vs Number of Qubits') ax2.legend() ax3.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized = ax3.bar(np.array(num_qubits_range) - bar_width / 2, avg_transpiled_depths, color='cyan', label='Normalized Depth', width=bar_width) # Adjust width here Algorithmic = ax3.bar(np.array(num_qubits_range) + bar_width / 2,avg_circuit_depths, color='deepskyblue', label='Algorithmic Depth', width=bar_width) # Adjust width here autolabel(Normalized,ax3,str='{:.2f}') autolabel(Algorithmic,ax3,str='{:.2f}') ax3.set_xlabel('Number of Qubits') ax3.set_ylabel('Average Circuit Depth') ax3.set_title('Average Circuit Depth vs Number of Qubits') ax3.legend() if gate_counts_plots == True: ax4.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_1Q_counts = ax4.bar(np.array(num_qubits_range) - bar_width / 2, avg_1Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_1Q_counts = ax4.bar(np.array(num_qubits_range) + bar_width / 2, avg_1Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_1Q_counts,ax4,str='{}') autolabel(Algorithmic_1Q_counts,ax4,str='{}') ax4.set_xlabel('Number of Qubits') ax4.set_ylabel('Average 1-Qubit Gate Counts') ax4.set_title('Average 1-Qubit Gate Counts vs Number of Qubits') ax4.legend() ax5.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Normalized_2Q_counts = ax5.bar(np.array(num_qubits_range) - bar_width / 2, avg_2Q_Transpiled_gate_counts, color='cyan', label='Normalized Gate Counts', width=bar_width) # Adjust width here Algorithmic_2Q_counts = ax5.bar(np.array(num_qubits_range) + bar_width / 2, avg_2Q_algorithmic_gate_counts, color='deepskyblue', label='Algorithmic Gate Counts', width=bar_width) # Adjust width here autolabel(Normalized_2Q_counts,ax5,str='{}') autolabel(Algorithmic_2Q_counts,ax5,str='{}') ax5.set_xlabel('Number of Qubits') ax5.set_ylabel('Average 2-Qubit Gate Counts') ax5.set_title('Average 2-Qubit Gate Counts vs Number of Qubits') ax5.legend() ax6.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) Hellinger = ax6.bar(np.array(num_qubits_range) - bar_width / 2, avg_Hf, width=bar_width, label='Hellinger Fidelity',color='cyan') # Adjust width here Normalized = ax6.bar(np.array(num_qubits_range) + bar_width / 2, avg_f, width=bar_width, label='Normalized Fidelity', color='deepskyblue') # Adjust width here autolabel(Hellinger,ax6,str='{:.2f}') autolabel(Normalized,ax6,str='{:.2f}') ax6.set_xlabel('Number of Qubits') ax6.set_ylabel('Average Value') ax6.set_title("Fidelity Comparison") ax6.legend() if Memory_utilization_plot == True: ax7.set_xticks(range(min(num_qubits_range), max(num_qubits_range)+1, skp_qubits)) x = ax7.bar(num_qubits_range, max_memory, color='turquoise', width=bar_width, label="Memory Utilizations") autolabel(ax7.patches, ax7) ax7.set_xlabel('Number of Qubits') ax7.set_ylabel('Maximum Memory Utilized (MB)') ax7.set_title('Memory Utilized vs Number of Qubits',fontsize=14) plt.tight_layout(rect=[0, 0, 1, 0.96]) if saveplots == True: plt.savefig("ParameterPlotsSample.jpg") plt.show() # Quantum Volume Plot Suptitle = f"Volumetric Positioning - {platform}" appname=benchmark_name if QV_ == None: QV=2048 else: QV=QV_ depth_base =2 ax = plot_volumetric_background(max_qubits=max_qbits, QV=QV,depth_base=depth_base, suptitle=Suptitle, colorbar_label="Avg Result Fidelity") w_data = num_qubits_range # determine width for circuit w_max = 0 for i in range(len(w_data)): y = float(w_data[i]) w_max = max(w_max, y) d_tr_data = avg_transpiled_depths f_data = avg_f plot_volumetric_data(ax, w_data, d_tr_data, f_data, depth_base, fill=True,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, w_max=w_max) anno_volumetric_data(ax, depth_base,label=appname, labelpos=(0.4, 0.6), labelrot=15, type=1, fill=False)
https://github.com/sebasmos/QuantumVE
sebasmos
import numpy as np import qiskit.pulse as pulse from qiskit.circuit import Parameter from qiskit_experiments.calibration_management.backend_calibrations import BackendCalibrations from qiskit import IBMQ, schedule API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3" import qiskit as q from qiskit import IBMQ,schedule import numpy as np import qiskit.pulse as pulse from qiskit.circuit import Parameter from qiskit_experiments.calibration_management.backend_calibrations import BackendCalibrations %matplotlib inline import sys sys.path.insert(0, '..') # Add qiskit_runtime directory to the path IBMQ.save_account(API_KEY) # Details in: https://qiskit.org/documentation/install.html IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider("ibm-q") for backend in provider.backends(): try: qubit_count = len(backend.properties().quibits) except: qubit_count = "simulated" print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits") qubit = 0 # The qubit we will work with def setup_cals(backend) -> BackendCalibrations: """A function to instantiate calibrations and add a couple of template schedules.""" cals = BackendCalibrations(backend) dur = Parameter("dur") amp = Parameter("amp") sigma = Parameter("σ") beta = Parameter("β") drive = pulse.DriveChannel(Parameter("ch0")) # Define and add template schedules. with pulse.build(name="xp") as xp: pulse.play(pulse.Drag(dur, amp, sigma, beta), drive) with pulse.build(name="xm") as xm: pulse.play(pulse.Drag(dur, -amp, sigma, beta), drive) with pulse.build(name="x90p") as x90p: pulse.play(pulse.Drag(dur, Parameter("amp"), sigma, Parameter("β")), drive) cals.add_schedule(xp) cals.add_schedule(xm) cals.add_schedule(x90p) return cals def add_parameter_guesses(cals: BackendCalibrations): """Add guesses for the parameter values to the calibrations.""" for sched in ["xp", "x90p"]: cals.add_parameter_value(80, "σ", schedule=sched) cals.add_parameter_value(0.5, "β", schedule=sched) cals.add_parameter_value(320, "dur", schedule=sched) cals.add_parameter_value(0.5, "amp", schedule=sched) cals = setup_cals(backend) add_parameter_guesses(cals) from qiskit_experiments.calibration_management.basis_gate_library import FixedFrequencyTransmon library = FixedFrequencyTransmon(default_values={"duration": 320}) cals = BackendCalibrations(backend, library) from qiskit_experiments.library.characterization.qubit_spectroscopy import QubitSpectroscopy import pandas as pd pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()])) freq01_estimate = backend.defaults().qubit_freq_est[qubit] frequencies = np.linspace(freq01_estimate -15e6, freq01_estimate + 15e6, 51) spec = QubitSpectroscopy(qubit, frequencies) spec.set_experiment_options(amp=0.1) circuit = spec.circuits(backend)[0] circuit.draw(output="mpl") schedule(circuit, backend).draw() spec_data = spec.run(backend) spec_data.block_for_results() spec_data.figure(0) print(spec_data.analysis_results("f01")) from qiskit_experiments.calibration_management.update_library import Frequency Frequency.update(cals, spec_data) pd.DataFrame(cals.parameters_table(qubit_list=[qubit])) from qiskit_experiments.library.calibration import Rabi from qiskit_experiments.calibration_management.update_library import Amplitude rabi = Rabi(qubit) rabi.set_experiment_options( amplitudes=np.linspace(-0.95, 0.95, 51), schedule=cals.get_schedule("x", (qubit,), assign_params={"amp": Parameter("amp")}), ) rabi_data = rabi.run(backend) rabi_data.block_for_results() rabi_data.figure(0) print(rabi_data.analysis_results("rabi_rate")) Amplitude.update(cals, rabi_data, angles_schedules=[(np.pi, "amp", "x"), (np.pi/2, "amp", "sx")]) pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) cals.get_schedule("sx", qubit) cals.get_schedule("x", qubit) cals.get_schedule("y", qubit) cals.save(file_type="csv", overwrite=True, file_prefix="Armonk") cals = BackendCalibrations(backend, library) cals.load_parameter_values(file_name="Armonkparameter_values.csv") pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) from qiskit_experiments.library.calibration.drag import DragCal from qiskit_experiments.calibration_management.update_library import Drag cal_drag = DragCal(qubit) cal_drag.set_experiment_options( rp=cals.get_schedule("x", qubit, assign_params={"β": Parameter("β")}), betas=np.linspace(-20, 20, 25), reps=[3, 5, 7] ) cal_drag.circuits(backend)[1].draw(output='mpl') drag_data = cal_drag.run(backend) drag_data.block_for_results() drag_data.figure(0) print(drag_data.analysis_results("beta")) Drag.update(cals, drag_data, parameter="β", schedule="x") pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="β")) from qiskit_experiments.library.calibration.fine_amplitude import FineXAmplitude from qiskit_experiments.calibration_management.update_library import Amplitude amp_x_cal = FineXAmplitude(qubit) amp_x_cal.set_experiment_options(schedule=cals.get_schedule("x", qubit)) amp_x_cal.circuits(backend)[5].draw(output="mpl") data_fine = amp_x_cal.run(backend) data_fine.block_for_results() data_fine.figure(0) print(data_fine.analysis_results("d_theta")) dtheta = data_fine.analysis_results("d_theta").value.value target_angle = np.pi scale = target_angle / (target_angle + dtheta) pulse_amp = cals.get_parameter_value("amp", qubit, "x") print(f"The ideal angle is {target_angle:.2f} rad. We measured a deviation of {dtheta:.3f} rad.") print(f"Thus, scale the {pulse_amp:.4f} pulse amplitude by {scale:.3f} to obtain {pulse_amp*scale:.5f}.") Amplitude.update(cals, data_fine, angles_schedules=[(target_angle, "amp", "x")]) pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) amp_x_cal.set_experiment_options(schedule=cals.get_schedule("x", qubit)) data_fine2 = amp_x_cal.run(backend) data_fine2.block_for_results() data_fine2.figure(0) print(data_fine2.analysis_results("d_theta")) from qiskit_experiments.library.calibration.fine_amplitude import FineSXAmplitude amp_sx_cal = FineSXAmplitude(qubit) amp_sx_cal.set_experiment_options(schedule=cals.get_schedule("sx", qubit)) amp_sx_cal.circuits(backend)[5].draw(output="mpl") data_fine_sx = amp_sx_cal.run(backend) data_fine_sx.block_for_results() data_fine_sx.figure(0) print(data_fine_sx.analysis_results("d_theta")) Amplitude.update(cals, data_fine_sx, angles_schedules=[(np.pi/2, "amp", "sx")]) pd.DataFrame(cals.parameters_table(qubit_list=[qubit, ()], parameters="amp")) cals.get_schedule("sx", qubit) cals.get_schedule("x", qubit) cals.get_schedule("y", qubit) import qiskit.tools.jupyter %qiskit_copyright
https://github.com/sebasmos/QuantumVE
sebasmos
API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3" import qiskit as q from qiskit import IBMQ,schedule import numpy as np import qiskit.pulse as pulse from qiskit.circuit import Parameter %matplotlib inline import sys sys.path.insert(0, '..') # Add qiskit_runtime directory to the path IBMQ.save_account(API_KEY) # Details in: https://qiskit.org/documentation/install.html IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider("ibm-q") for backend in provider.backends(): try: qubit_count = len(backend.properties().quibits) except: qubit_count = "simulated" print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits") from qiskit.tools.monitor import job_monitor backend = provider.get_backend("ibmq_lima") # Checking for backend support # https://github.com/delapuente/qiskit-runtime/#test-server from qiskit import IBMQ provider = IBMQ.load_account() print(f"Do I have access to Qiskit Runtime? {provider.has_service('runtime')}") backend = provider.backend.ibmq_lima support_runtime = 'runtime' in backend.configuration().input_allowed print(f"Does {backend.name()} support Qiskit Runtime? {support_runtime}") # Get a list of all backends that support runtime. runtime_backends = provider.backends(input_allowed='runtime') print(f"Backends that support Qiskit Runtime: {runtime_backends}")
https://github.com/sebasmos/QuantumVE
sebasmos
import qiskit as q from qiskit import IBMQ %matplotlib inline IBMQ.save_account("5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3") # Details in: https://qiskit.org/documentation/install.html # https://quantumcomputing.stackexchange.com/questions/7098/loading-qiskit-account-in-the-jupyter-notebook-gives-requestsapierror-error ''' IBMQ.delete_account() IBMQ.active_account() ''' API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3" IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() circuit = q.QuantumCircuit(2,2) # 2 qubits, 2 classical bits # Currently: 0,0 circuit.x(0) # Creates quantum bit of 0,1 or any combination of both #1,0 circuit.cx(0,1) #cnot, controlled not, Flibs 2nd qubit value if first quibit is 1 #1,1 circuit.measure([0,1],[0,1]) # Observer performs measurements between the qubit and classical bit circuit.draw() # pip install pylatexenc circuit.draw(output = "mpl") provider = IBMQ.get_provider("ibm-q") for backend in provider.backends(): try: qubit_count = len(backend.properties().quibits) except: qubit_count = "simulated" print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits") from qiskit.tools.monitor import job_monitor backend = provider.get_backend("ibmq_bogota") job = q.execute(circuit, backend, shots = 500) job_monitor(job) from qiskit.visualization import plot_histogram from matplotlib import style style.use("dark_background") result = job.result() counts = result.get_counts(circuit) plot_histogram([counts]) # Currently: 0,0 circuit.h(0) # Creates quantum bit of 0,1 or any combination of both #1,0 circuit.cx(0,1) #cnot, controlled not, Flibs 2nd qubit value if first quibit is 1 #1,1 circuit.measure([0,1],[0,1]) # Observer performs measurements between the qubit and classical bit circuit.draw() job = q.execute(circuit, backend, shots = 500) job_monitor(job) result = job.result() counts = result.get_counts(circuit) plot_histogram([counts])
https://github.com/sebasmos/QuantumVE
sebasmos
API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3" import qiskit as q from qiskit import IBMQ,schedule import numpy as np import qiskit.pulse as pulse from qiskit.circuit import Parameter %matplotlib inline import sys sys.path.insert(0, '..') # Add qiskit_runtime directory to the path IBMQ.save_account(API_KEY) # Details in: https://qiskit.org/documentation/install.html IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() provider = IBMQ.get_provider("ibm-q") for backend in provider.backends(): try: qubit_count = len(backend.properties().quibits) except: qubit_count = "simulated" print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits") from qiskit.tools.monitor import job_monitor backend = provider.get_backend("ibmq_lima") provider = IBMQ.get_provider( hub='ibm-q', group='open', project='main' ) options = { 'backend_name': 'ibmq_qasm_simulator' } runtime_inputs = { # An instance of FeatureMap in # dictionary format used to map # classical data into a quantum # state space. 'feature_map': None, # dict (required) # NxD array of training data, # where N is the number # of samples and D is # the feature dimension. 'data': None, # numpy.ndarray (required) # Nx1 array of +/-1 labels # of the N training samples. 'labels': None, # numpy.ndarray (required) # Initial parameters of the quantum # kernel. If not specified, an # array of randomly generated numbers # is used. 'initial_kernel_parameters': None, # numpy.ndarray # Number of SPSA optimization steps. # Default is 1. 'maxiters': None, # int # Penalty parameter for the soft-margin # support vector machine. Default is # 1. 'C': None, # float # Initial position of virtual qubits # on the physical qubits of # the quantum device. Default is # None. 'initial_layout': None # list or dict } job = provider.runtime.run( program_id='quantum-kernel-alignment', options=options, inputs=runtime_inputs ) # Job id print(job.job_id()) # See job status print(job.status()) # Get results result = job.result()
https://github.com/sebasmos/QuantumVE
sebasmos
# Quantum Kernel Alighment [Reference](https://quantumcomputing.com/Havry/projects/qiskit-runtime-quantum-kernel-alignment/files/main.py) API_KEY = "5bd4ecfdc74e6680da7c79998259781431661e5326ae2f88eea95dee8f74b87530ba63fbca8105404de4ffd36e4b484631907acff73c805580928218a5ccf0b3" import qiskit as q from qiskit import IBMQ,schedule import qiskit.pulse as pulse from qiskit.circuit import Parameter import numpy as np import pandas as pd from qka_files.qka import FeatureMap %matplotlib inline import sys sys.path.insert(0, '..') # Add qiskit_runtime directory to the path IBMQ.save_account(API_KEY, overwrite=True) IBMQ.load_account() # Details in: https://qiskit.org/documentation/install.html # -------------------------------- # ✅ SETUP YOUR PROVIDER # # Assuming you've enabled Runtime, this should automatically work. # If not, 👉 https://app.quantumcomputing.com/runtime/enable provider = IBMQ.get_provider("ibm-q", group="open", project="main") for backend in provider.backends(): try: qubit_count = len(backend.properties().quibits) except: qubit_count = "simulated" print(f"{backend.name()} has {backend.status().pending_jobs} queued and { qubit_count} qubits") # -------------------------------- # ✅ SELECT A BACKEND # You can run on the simulator 💻 (🐇) from qiskit.tools.monitor import job_monitor #backend = provider.get_backend("ibmq_lima") options = {'backend_name': "ibmq_lima"} # -------------------------------- # ✅ READ IN SOME DATA df = pd.read_csv('qka_files/dataset_graph7.csv',sep=',', header=None) # this date is the one that will be used for the classification problem data = df.values # choose number of training and test samples per class 👩‍🏫: num_train = 5 num_test = 5 # extract training and test sets and sort them by class label train = data[:2*num_train, :] test = data[2*num_train:2*(num_train+num_test), :] ind=np.argsort(train[:,-1]) x_train = train[ind][:,:-1] y_train = train[ind][:,-1] ind=np.argsort(test[:,-1]) x_test = test[ind][:,:-1] y_test = test[ind][:,-1] # feature dimension is twice the qubit number d = np.shape(data)[1]-1 # we'll match this to the 7-qubit graph em = [[0,2],[3,4],[2,5],[1,4],[2,3],[4,6]] # define the feature map fm = FeatureMap(feature_dimension=d, entangler_map=em) # set the initial parameter for the feature map initial_point = [0.1] # SVM soft-margin penalty C = 1 maxiters = 10 initial_layout = [0, 1, 2, 3, 4, 5, 6] # Setup a callback for our interim result def interim_result_callback(job_id, interim_result): print(f"interim result: {interim_result}\n") # Set our inputs program_inputs = { 'feature_map': fm, 'data': x_train, 'labels': y_train, 'initial_kernel_parameters': initial_point, 'maxiters': maxiters, 'C': C, 'initial_layout': initial_layout } # -------------------------------- # ✅ RUN THE PROGRAM job = provider.runtime.run(program_id="quantum-kernel-alignment", options=options, inputs=program_inputs, callback=interim_result_callback, ) print("🖼 Circuit for the feature map:") strangeworks.qiskit.extract_diagram(fm.construct_circuit(x=x_train[0], parameters=initial_point)) # -------------------------------- # ✅ GET THE FINAL RESULT # Execution will pause here until the result returns result = job.result() # And finally, we'll display the output strangeworks.print(result, type="log", label="Final Result") # 🎉 Yay, Runtime success! # # ⏭ Try other programs here: # https://app.quantumcomputing.com/runtime/
https://github.com/sebasmos/QuantumVE
sebasmos
# This code is part of qiskit-runtime. # # (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. """The FeatureMap class.""" import json import numpy as np from qiskit import QuantumCircuit, QuantumRegister class FeatureMap: """Mapping data with the feature map.""" def __init__(self, feature_dimension, entangler_map=None): """ Args: feature_dimension (int): number of features (twice the number of qubits for this encoding) entangler_map (list[list]): connectivity of qubits with a list of [source, target], or None for full entanglement. Note that the order in the list is the order of applying the two-qubit gate. Raises: ValueError: If the value of ``feature_dimension`` is odd. """ if isinstance(feature_dimension, int): if feature_dimension % 2 == 0: self._feature_dimension = feature_dimension else: raise ValueError("Feature dimension must be an even integer.") else: raise ValueError("Feature dimension must be an even integer.") self._num_qubits = int(feature_dimension / 2) if entangler_map is None: self._entangler_map = [ [i, j] for i in range(self._num_qubits) for j in range(i + 1, self._num_qubits) ] else: self._entangler_map = entangler_map self._num_parameters = self._num_qubits def construct_circuit(self, x=None, parameters=None, q=None, inverse=False, name=None): """Construct the feature map circuit. Args: x (numpy.ndarray): data vector of size feature_dimension parameters (numpy.ndarray): optional parameters in feature map q (QauntumRegister): the QuantumRegister object for the circuit inverse (bool): whether or not to invert the circuit name (str): The name to use for the constructed ``QuantumCircuit`` object Returns: QuantumCircuit: a quantum circuit transforming data x Raises: ValueError: If the input parameters or vector are invalid """ if parameters is not None: if isinstance(parameters, (int, float)): raise ValueError("Parameters must be a list.") if len(parameters) == 1: parameters = parameters * np.ones(self._num_qubits) else: if len(parameters) != self._num_parameters: raise ValueError( "The number of feature map parameters must be {}.".format( self._num_parameters ) ) if len(x) != self._feature_dimension: raise ValueError( "The input vector must be of length {}.".format(self._feature_dimension) ) if q is None: q = QuantumRegister(self._num_qubits, name="q") circuit = QuantumCircuit(q, name=name) for i in range(self._num_qubits): circuit.ry(-parameters[i], q[i]) for source, target in self._entangler_map: circuit.cz(q[source], q[target]) for i in range(self._num_qubits): circuit.rz(-2 * x[2 * i + 1], q[i]) circuit.rx(-2 * x[2 * i], q[i]) if inverse: return circuit.inverse() else: return circuit def to_json(self): """Return JSON representation of this object. Returns: str: JSON string representing this object. """ return json.dumps( {"feature_dimension": self._feature_dimension, "entangler_map": self._entangler_map} ) @classmethod def from_json(cls, data): """Return an instance of this class from the JSON representation. Args: data (str): JSON string representing an object. Returns: FeatureMap: An instance of this class. """ return cls(**json.loads(data))
https://github.com/sebasmos/QuantumVE
sebasmos
# This code is part of qiskit-runtime. # # (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. """Source code for the QKA Qiskit Runtime program.""" # pylint: disable=invalid-name import itertools import json import numpy as np from numpy.random import RandomState from qiskit import QuantumCircuit, QuantumRegister from qiskit.compiler import transpile from cvxopt import matrix, solvers # pylint: disable=import-error class FeatureMap: """Mapping data with the feature map.""" def __init__(self, feature_dimension, entangler_map=None): """ Args: feature_dimension (int): number of features, twice the number of qubits for this encoding entangler_map (list[list]): connectivity of qubits with a list of [source, target], or None for full entanglement. Note that the order in the list is the order of applying the two-qubit gate. Raises: ValueError: If the value of ``feature_dimension`` is not an even integer. """ if isinstance(feature_dimension, int): if feature_dimension % 2 == 0: self._feature_dimension = feature_dimension else: raise ValueError("Feature dimension must be an even integer.") else: raise ValueError("Feature dimension must be an even integer.") self._num_qubits = int(feature_dimension / 2) if entangler_map is None: self._entangler_map = [ [i, j] for i in range(self._feature_dimension) for j in range(i + 1, self._feature_dimension) ] else: self._entangler_map = entangler_map self._num_parameters = self._num_qubits def construct_circuit(self, x=None, parameters=None, q=None, inverse=False, name=None): """Construct the feature map circuit. Args: x (numpy.ndarray): data vector of size feature_dimension parameters (numpy.ndarray): optional parameters in feature map q (QauntumRegister): the QuantumRegister object for the circuit inverse (bool): whether or not to invert the circuit name (str): name of circuit Returns: QuantumCircuit: a quantum circuit transforming data x Raises: ValueError: If the input parameters or vector are invalid """ if parameters is not None: if isinstance(parameters, (int, float)): raise ValueError("Parameters must be a list.") if len(parameters) == 1: parameters = parameters * np.ones(self._num_qubits) else: if len(parameters) != self._num_parameters: raise ValueError( "The number of feature map parameters must be {}.".format( self._num_parameters ) ) if len(x) != self._feature_dimension: raise ValueError( "The input vector must be of length {}.".format(self._feature_dimension) ) if q is None: q = QuantumRegister(self._num_qubits, name="q") circuit = QuantumCircuit(q, name=name) for i in range(self._num_qubits): circuit.ry(-parameters[i], q[i]) for source, target in self._entangler_map: circuit.cz(q[source], q[target]) for i in range(self._num_qubits): circuit.rz(-2 * x[2 * i + 1], q[i]) circuit.rx(-2 * x[2 * i], q[i]) if inverse: return circuit.inverse() else: return circuit def to_json(self): """Return JSON representation of this object. Returns: str: JSON string representing this object. """ return json.dumps( {"feature_dimension": self._feature_dimension, "entangler_map": self._entangler_map} ) @classmethod def from_json(cls, data): """Return an instance of this class from the JSON representation. Args: data (str): JSON string representing an object. Returns: cls: An instance of this class. """ return cls(**json.loads(data)) class KernelMatrix: """Build the kernel matrix from a quantum feature map.""" def __init__(self, feature_map, backend, initial_layout=None): """ Args: feature_map: the feature map object backend (Backend): the backend instance initial_layout (list or dict): initial position of virtual qubits on the physical qubits of the quantum device """ self._feature_map = feature_map self._feature_map_circuit = self._feature_map.construct_circuit self._backend = backend self._initial_layout = initial_layout self.results = {} def construct_kernel_matrix(self, x1_vec, x2_vec, parameters=None): """Create the kernel matrix for a given feature map and input data. With the qasm simulator or real backends, compute order 'n^2' states Phi^dag(y)Phi(x)|0> for input vectors x and y. Args: x1_vec (numpy.ndarray): NxD array of training data or test data, where N is the number of samples and D is the feature dimension x2_vec (numpy.ndarray): MxD array of training data or support vectors, where M is the number of samples and D is the feature dimension parameters (numpy.ndarray): optional parameters in feature map Returns: numpy.ndarray: the kernel matrix """ is_identical = False if np.array_equal(x1_vec, x2_vec): is_identical = True experiments = [] measurement_basis = "0" * self._feature_map._num_qubits if is_identical: my_product_list = list( itertools.combinations(range(len(x1_vec)), 2) ) # all pairwise combos of datapoint indices for index_1, index_2 in my_product_list: circuit_1 = self._feature_map_circuit( x=x1_vec[index_1], parameters=parameters, name="{}_{}".format(index_1, index_2) ) circuit_2 = self._feature_map_circuit( x=x1_vec[index_2], parameters=parameters, inverse=True ) circuit = circuit_1.compose(circuit_2) circuit.measure_all() experiments.append(circuit) experiments = transpile( experiments, backend=self._backend, initial_layout=self._initial_layout ) program_data = self._backend.run(experiments, shots=8192).result() self.results["program_data"] = program_data mat = np.eye( len(x1_vec), len(x1_vec) ) # kernel matrix element on the diagonal is always 1 for experiment, [index_1, index_2] in enumerate(my_product_list): counts = program_data.get_counts(experiment=experiment) shots = sum(counts.values()) mat[index_1][index_2] = ( counts.get(measurement_basis, 0) / shots ) # kernel matrix element is the probability of measuring all 0s mat[index_2][index_1] = mat[index_1][index_2] # kernel matrix is symmetric return mat else: for index_1, point_1 in enumerate(x1_vec): for index_2, point_2 in enumerate(x2_vec): circuit_1 = self._feature_map_circuit( x=point_1, parameters=parameters, name="{}_{}".format(index_1, index_2) ) circuit_2 = self._feature_map_circuit( x=point_2, parameters=parameters, inverse=True ) circuit = circuit_1.compose(circuit_2) circuit.measure_all() experiments.append(circuit) experiments = transpile( experiments, backend=self._backend, initial_layout=self._initial_layout ) program_data = self._backend.run(experiments, shots=8192).result() self.results["program_data"] = program_data mat = np.zeros((len(x1_vec), len(x2_vec))) i = 0 for index_1, _ in enumerate(x1_vec): for index_2, _ in enumerate(x2_vec): counts = program_data.get_counts(experiment=i) shots = sum(counts.values()) mat[index_1][index_2] = counts.get(measurement_basis, 0) / shots i += 1 return mat class QKA: """The quantum kernel alignment algorithm.""" def __init__(self, feature_map, backend, initial_layout=None, user_messenger=None): """Constructor. Args: feature_map (partial obj): the quantum feature map object backend (Backend): the backend instance initial_layout (list or dict): initial position of virtual qubits on the physical qubits of the quantum device user_messenger (UserMessenger): used to publish interim results. """ self.feature_map = feature_map self.feature_map_circuit = self.feature_map.construct_circuit self.backend = backend self.initial_layout = initial_layout self.num_parameters = self.feature_map._num_parameters self._user_messenger = user_messenger self.result = {} self.kernel_matrix = KernelMatrix( feature_map=self.feature_map, backend=self.backend, initial_layout=self.initial_layout ) def spsa_parameters(self): """Return array of precomputed SPSA parameters. The i-th optimization step, i>=0, the parameters evolve as a_i = a / (i + 1 + A) ** alpha, c_i = c / (i + 1) ** gamma, for fixed coefficents a, c, alpha, gamma, A. Returns: numpy.ndarray: spsa parameters """ spsa_params = np.zeros((5)) spsa_params[0] = 0.05 # a spsa_params[1] = 0.1 # c spsa_params[2] = 0.602 # alpha spsa_params[3] = 0.101 # gamma spsa_params[4] = 0 # A return spsa_params def cvxopt_solver(self, K, y, C, max_iters=10000, show_progress=False): """Convex optimization of SVM objective using cvxopt. Args: K (numpy.ndarray): nxn kernel (Gram) matrix y (numpy.ndarray): nx1 vector of labels +/-1 C (float): soft-margin penalty max_iters (int): maximum iterations for the solver show_progress (bool): print progress of solver Returns: dict: results from the solver """ if y.ndim == 1: y = y[:, np.newaxis] H = np.outer(y, y) * K f = -np.ones(y.shape) n = K.shape[1] # number of training points y = y.astype("float") P = matrix(H) q = matrix(f) G = matrix(np.vstack((-np.eye((n)), np.eye((n))))) h = matrix(np.vstack((np.zeros((n, 1)), np.ones((n, 1)) * C))) A = matrix(y, y.T.shape) b = matrix(np.zeros(1), (1, 1)) solvers.options["maxiters"] = max_iters solvers.options["show_progress"] = show_progress ret = solvers.qp(P, q, G, h, A, b, kktsolver="ldl") return ret def spsa_step_one(self, lambdas, spsa_params, count): """Evaluate +/- perturbations of kernel parameters (lambdas). Args: lambdas (numpy.ndarray): kernel parameters at step 'count' in SPSA optimization loop spsa_params (numpy.ndarray): SPSA parameters count (int): the current step in the SPSA optimization loop Returns: numpy.ndarray: kernel parameters in + direction numpy.ndarray: kernel parameters in - direction numpy.ndarray: random vector with elements {-1,1} """ prng = RandomState(count) c_spsa = float(spsa_params[1]) / np.power(count + 1, spsa_params[3]) delta = 2 * prng.randint(0, 2, size=np.shape(lambdas)[0]) - 1 lambda_plus = lambdas + c_spsa * delta lambda_minus = lambdas - c_spsa * delta return lambda_plus, lambda_minus, delta def spsa_step_two(self, cost_plus, cost_minus, lambdas, spsa_params, delta, count): """Evaluate one iteration of SPSA on SVM objective function F and return updated kernel parameters. F(alpha, lambda) = 1^T * alpha - (1/2) * alpha^T * Y * K * Y * alpha Args: cost_plus (float): objective function F(alpha_+, lambda_+) cost_minus (float): objective function F(alpha_-, lambda_-) lambdas (numpy.ndarray): kernel parameters at step 'count' in SPSA optimization loop spsa_params (numpy.ndarray): SPSA parameters delta (numpy.ndarray): random vector with elements {-1,1} count(int): the current step in the SPSA optimization loop Returns: float: estimate of updated SVM objective function F using average of F(alpha_+, lambda_+) and F(alpha_-, lambda_-) numpy.ndarray: updated values of the kernel parameters after one SPSA optimization step """ a_spsa = float(spsa_params[0]) / np.power(count + 1 + spsa_params[4], spsa_params[2]) c_spsa = float(spsa_params[1]) / np.power(count + 1, spsa_params[3]) g_spsa = (cost_plus - cost_minus) * delta / (2.0 * c_spsa) lambdas_new = lambdas - a_spsa * g_spsa lambdas_new = lambdas_new.flatten() cost_final = (cost_plus + cost_minus) / 2 return cost_final, lambdas_new def align_kernel(self, data, labels, initial_kernel_parameters=None, maxiters=1, C=1): """Align the quantum kernel. Uses SPSA for minimization over kernel parameters (lambdas) and convex optimization for maximization over lagrange multipliers (alpha): min_lambda max_alpha 1^T * alpha - (1/2) * alpha^T * Y * K_lambda * Y * alpha Args: data (numpy.ndarray): NxD array of training data, where N is the number of samples and D is the feature dimension labels (numpy.ndarray): Nx1 array of +/-1 labels of the N training samples initial_kernel_parameters (numpy.ndarray): Initial parameters of the quantum kernel maxiters (int): number of SPSA optimization steps C (float): penalty parameter for the soft-margin support vector machine Returns: dict: the results of kernel alignment """ if initial_kernel_parameters is not None: lambdas = initial_kernel_parameters else: lambdas = np.random.uniform(-1.0, 1.0, size=(self.num_parameters)) spsa_params = self.spsa_parameters() lambda_save = [] cost_final_save = [] for count in range(maxiters): lambda_plus, lambda_minus, delta = self.spsa_step_one( lambdas=lambdas, spsa_params=spsa_params, count=count ) kernel_plus = self.kernel_matrix.construct_kernel_matrix( x1_vec=data, x2_vec=data, parameters=lambda_plus ) kernel_minus = self.kernel_matrix.construct_kernel_matrix( x1_vec=data, x2_vec=data, parameters=lambda_minus ) ret_plus = self.cvxopt_solver(K=kernel_plus, y=labels, C=C) cost_plus = -1 * ret_plus["primal objective"] ret_minus = self.cvxopt_solver(K=kernel_minus, y=labels, C=C) cost_minus = -1 * ret_minus["primal objective"] cost_final, lambda_best = self.spsa_step_two( cost_plus=cost_plus, cost_minus=cost_minus, lambdas=lambdas, spsa_params=spsa_params, delta=delta, count=count, ) lambdas = lambda_best interim_result = {"cost": cost_final, "kernel_parameters": lambdas} self._user_messenger.publish(interim_result) lambda_save.append(lambdas) cost_final_save.append(cost_final) # Evaluate aligned kernel matrix with optimized set of # parameters averaged over last 10% of SPSA steps: num_last_lambdas = int(len(lambda_save) * 0.10) if num_last_lambdas > 0: last_lambdas = np.array(lambda_save)[-num_last_lambdas:, :] lambdas = np.sum(last_lambdas, axis=0) / num_last_lambdas else: lambdas = np.array(lambda_save)[-1, :] kernel_best = self.kernel_matrix.construct_kernel_matrix( x1_vec=data, x2_vec=data, parameters=lambdas ) self.result["aligned_kernel_parameters"] = lambdas self.result["aligned_kernel_matrix"] = kernel_best return self.result def main(backend, user_messenger, **kwargs): """Entry function.""" # Reconstruct the feature map object. feature_map = kwargs.get("feature_map") fm = FeatureMap.from_json(feature_map) data = kwargs.get("data") labels = kwargs.get("labels") initial_kernel_parameters = kwargs.get("initial_kernel_parameters", None) maxiters = kwargs.get("maxiters", 1) C = kwargs.get("C", 1) initial_layout = kwargs.get("initial_layout", None) qka = QKA( feature_map=fm, backend=backend, initial_layout=initial_layout, user_messenger=user_messenger, ) qka_results = qka.align_kernel( data=data, labels=labels, initial_kernel_parameters=initial_kernel_parameters, maxiters=maxiters, C=C, ) user_messenger.publish(qka_results, final=True)
https://github.com/sebasmos/QuantumVE
sebasmos
import sys sys.path.insert(0,'../') from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import os import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def run_one_image(img, model): x = torch.tensor(img) # make it a batch-like x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) # run MAE loss, y, mask = model(x.float(), mask_ratio=0.75) y = model.unpatchify(y) y = torch.einsum('nchw->nhwc', y).detach().cpu() # visualize the mask mask = mask.detach() mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3) mask = model.unpatchify(mask) # 1 is removing, 0 is keeping mask = torch.einsum('nchw->nhwc', mask).detach().cpu() x = torch.einsum('nchw->nhwc', x) # masked image im_masked = x * (1 - mask) # MAE reconstruction pasted with visible patches im_paste = x * (1 - mask) + y * mask # make the plt figure larger plt.rcParams['figure.figsize'] = [24, 24] plt.subplot(1, 4, 1) show_image(x[0], "original") plt.subplot(1, 4, 2) show_image(im_masked[0], "masked") plt.subplot(1, 4, 3) show_image(y[0], "reconstruction") plt.subplot(1, 4, 4) show_image(im_paste[0], "reconstruction + visible") plt.show() # Set the seed for PyTorch torch.manual_seed(42) parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=256, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=50, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='mobilenet_v3', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/ABGQI_mel_spectrograms', type=str, help='dataset path') parser.add_argument('--nb_classes', default=5, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='quinn_5_classes', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='/media/enc/vera1/sebastian/codes/classifiers/mae/MobileNet/output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default="/media/enc/vera1/sebastian/codes/classifiers/mae/MobileNet/quinn_5_classes/checkpoint-49.pth", help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) os.makedirs(args.output_dir, exist_ok=True) device = torch.device(args.device) import torchvision.models as models import torch.nn as nn import torch def count_parameters(model, message=""): trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) total_params = sum(p.numel() for p in model.parameters()) print(f"{message} Trainable params: {trainable_params} of {total_params}") # Load pre-trained MobileNetV3 model frozen_model = models.mobilenet_v3_large(pretrained=True, progress=True) # Freeze all layers except the classifier for param in frozen_model.parameters(): param.requires_grad = False count_parameters(frozen_model, "BEFORE") # Modify the classifier to fit the new number of classes num_classes = args.nb_classes in_features = frozen_model.classifier[-1].in_features frozen_model.classifier[-1] = nn.Linear(in_features, num_classes) num_layers_unfreeze = 50 # Unfreeze the last layer for fine-tuning for param in frozen_model.classifier[-num_layers_unfreeze:].parameters(): # if not isinstance(param, nn.BatchNorm2d):# not working anyway.. param.requires_grad = True import copy stage_1_model = copy.deepcopy(frozen_model) count_parameters(stage_1_model, "AFTER") # # Create random input data # batch_size = 1 # channels = 3 # height = 224 # width = 224 # random_input = torch.randn(batch_size, channels, height, width) # # Forward pass through the model # output = stage_1_model(random_input) # print("Output shape:", output.shape) misc.init_distributed_mode(args) # print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train = build_dataset(is_train=True, args=args) dataset_val = build_dataset(is_train=False, args=args) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) # model = models_vit.__dict__[args.model]( # num_classes=args.nb_classes, # drop_path_rate=args.drop_path, # global_pool=args.global_pool, # ) model = stage_1_model if args.finetune and not args.eval: print("args.finetune and not args.eval") checkpoint = torch.load(args.finetune, map_location='cpu') print("Load pre-trained checkpoint from: %s" % args.finetune) checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding interpolate_pos_embed(model, checkpoint_model) # load pre-trained model msg = model.load_state_dict(checkpoint_model, strict=False) print(msg) if args.global_pool: assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'} else: assert set(msg.missing_keys) == {'head.weight', 'head.bias'} # manually initialize fc layer trunc_normal_(model.head.weight, std=2e-5) model.to(device) model_without_ddp = model n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print("Model = %s" % str(model_without_ddp)) print('number of params (M): %.2f' % (n_parameters / 1.e6)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size / 256 print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module optimizer = optim.Adam(model.parameters(), lr=args.lr)#SEB # optimizer = torch.optim.AdamW(param_groups, lr=args.lr) loss_scaler = NativeScaler() if mixup_fn is not None: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() print("criterion = %s" % str(criterion)) misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") # exit(0) train = False if train: print(f"Start training for {args.epochs} epochs with batch size of {args.batch_size}") start_time = time.time() max_accuracy = 0.0 for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, args.clip_grad, mixup_fn, log_writer=log_writer, args=args ) if args.output_dir: misc.save_model( args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch) test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") max_accuracy = max(max_accuracy, test_stats["acc1"]) print(f'Max accuracy: {max_accuracy:.2f}%') if log_writer is not None: log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch) log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch) log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) EXPERIMENT_NAME = "mobileNet" saving_model = f"{EXPERIMENT_NAME}/models" os.makedirs(saving_model, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok=True) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") @torch.no_grad() def evaluate_test(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = misc.MetricLogger(delimiter=" ") header = 'Test:' # switch to evaluation mode model.eval() all_predictions = [] all_labels = [] for batch in metric_logger.log_every(data_loader, 10, header): images = batch[0] target = batch[-1] images = images.to(device, non_blocking=True) target = target.to(device, non_blocking=True) # compute output with torch.cuda.amp.autocast(): output = model(images) loss = criterion(output, target)# pred = output.argmax(dim=1) all_predictions.append(pred.cpu().numpy())# ADDED all_labels.append(target.cpu().numpy())# ADDED acc1, acc5 = accuracy(output, target, topk=(1, 5)) batch_size = images.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # import pdb;pdb.set_trace() all_predictions = np.array(all_predictions)#.squeeze(0) all_labels = np.array(all_labels)#.squeeze(0) # gather the stats from all processes metric_logger.synchronize_between_processes() print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) # return return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, np.concatenate(all_predictions, axis=0), np.concatenate(all_labels, axis=0) metrics, all_predictions, all_labels = evaluate_test(data_loader_val, model, device) # print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") all_predictions metrics all_predictions unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) unique_classes confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) conf_matrix unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Example usage: plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME) # def visualize_predictions(model, val_loader, device, type_label=None, dataset_type=1, unique_classes=np.array([0, 1, 2, 3, 4, 5, 6])): # criterion = torch.nn.CrossEntropyLoss() # metric_logger = misc.MetricLogger(delimiter=" ") # header = 'Test:' # # switch to evaluation mode # model.eval() # all_predictions = [] # all_labels = [] # for batch in metric_logger.log_every(val_loader, 10, header): # images = batch[0] # target = batch[-1] # images = images.to(device, non_blocking=True) # target = target.to(device, non_blocking=True) # # compute output # with torch.cuda.amp.autocast(): # output = model(images) # loss = criterion(output, target)# # pred = output.argmax(dim=1) # all_predictions.append(pred.cpu().numpy())# ADDED # all_labels.append(target.cpu().numpy())# ADDED # acc1, acc5 = accuracy(output, target, topk=(1, 5)) # batch_size = images.shape[0] # metric_logger.update(loss=loss.item()) # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # all_predictions = np.array(all_predictions)#.squeeze(0) # all_labels = np.array(all_labels)#.squeeze(0) # if type_label is None: # type_label = unique_classes # # Create a 4x4 grid for visualization # num_rows = 4 # num_cols = 4 # plt.figure(figsize=(12, 12)) # for i in range(num_rows * num_cols): # plt.subplot(num_rows, num_cols, i + 1) # idx = np.random.randint(len(all_labels)) # import pdb;pdb.set_trace() # plt.imshow(images[idx].cpu().numpy().squeeze(), cmap='gray') # # Use the class names instead of numeric labels for Fashion MNIST # if dataset_type == 1: # class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # predicted_class = class_names[all_predictions[idx]] # actual_class = class_names[all_labels[idx]] # else: # predicted_class = all_predictions[idx] # actual_class = all_labels[idx] # plt.title(f'Pred: {predicted_class}\nActual: {actual_class}') # plt.axis('off') # plt.tight_layout() # plt.show() # visualize_predictions(model, data_loader_val, device, dataset_type=2, unique_classes=unique_classes) unique_classes report = classification_report(all_labels, all_predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(EXPERIMENT_NAME, "confusion_matrix.csv")) print(df) df # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(all_labels, all_predictions, average='micro') recall = recall_score(all_labels, all_predictions, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((all_labels != 1) & (all_predictions != 1)) fp = np.sum((all_labels != 1) & (all_predictions == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(all_labels, all_predictions, average='weighted') evaluation_metrics = { "Acc1": metrics['acc1'], # Add acc1 metric "Acc5": metrics['acc5'], # Add acc5 metric "loss": metrics['loss'], # Add acc5 metric "F1 Score": [f1], "Precision": [precision], "Recall": [recall], "Specificity": [specificity] } evaluation_metrics # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics) # Save the DataFrame to a CSV file df.to_csv(f'{EXPERIMENT_NAME}/evaluation_metrics_for_table.csv', index=False) df
https://github.com/sebasmos/QuantumVE
sebasmos
import sys sys.path.insert(0,'../') from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import os import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def run_one_image(img, model): x = torch.tensor(img) # make it a batch-like x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) # run MAE loss, y, mask = model(x.float(), mask_ratio=0.75) y = model.unpatchify(y) y = torch.einsum('nchw->nhwc', y).detach().cpu() # visualize the mask mask = mask.detach() mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3) mask = model.unpatchify(mask) # 1 is removing, 0 is keeping mask = torch.einsum('nchw->nhwc', mask).detach().cpu() x = torch.einsum('nchw->nhwc', x) # masked image im_masked = x * (1 - mask) # MAE reconstruction pasted with visible patches im_paste = x * (1 - mask) + y * mask # make the plt figure larger plt.rcParams['figure.figsize'] = [24, 24] plt.subplot(1, 4, 1) show_image(x[0], "original") plt.subplot(1, 4, 2) show_image(im_masked[0], "masked") plt.subplot(1, 4, 3) show_image(y[0], "reconstruction") plt.subplot(1, 4, 4) show_image(im_paste[0], "reconstruction + visible") plt.show() # Set the seed for PyTorch torch.manual_seed(42) # !pip install qiskit_machine_learning # !pip install qiskit torch torchvision matplotlib # !pip install qiskit-machine-learning # !pip install torchviz # !pip install qiskit[all] # !pip install qiskit == 0.45.2 # !pip install qiskit_algorithms == 0.7.1 # !pip install qiskit-ibm-runtime == 0.17.0 # !pip install qiskit-aer == 0.13.2 # #Quentum net draw # !pip install pylatexenc from qiskit_machine_learning.connectors import TorchConnector from qiskit_machine_learning.neural_networks.estimator_qnn import EstimatorQNN from qiskit_machine_learning.circuit.library import QNNCircuit parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=256, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=10, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='mobilenet_v3', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/ABGQI_mel_spectrograms', type=str, help='dataset path') parser.add_argument('--nb_classes', default=5, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='quinn_5_classes', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='./output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default="/media/enc/vera1/sebastian_hdd/codes/classifiers/mae/MobileNet/quinn_5_classes/checkpoint-49.pth", help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) os.makedirs(args.output_dir, exist_ok=True) device = torch.device(args.device) # from torchvision.models import mobilenet_v3_large # model_ft = mobilenet_v3_large(pretrained=True, progress=True) # model_ft.classifier[-1] = nn.Linear(1280, args.nb_classes) # base_model = torch.hub.load('pytorch/vision:v0.10.0', 'mobilenet_v2', pretrained=True) # Remove FC and Global pooling layers to allow for ABGQI fine-tuning # base_model_output = nn.Sequential(*list(base_model.children())[:-3]) # Remove the last 3 layers # print(base_model_output) from torch.nn import Module, Linear from qiskit_machine_learning.connectors.torch_connector import TorchConnector from torch import Tensor from torch.nn import Linear, CrossEntropyLoss, MSELoss from torch.optim import LBFGS # from qiskit_machine_learning.neural_networks import CircuitQNN from qiskit_machine_learning.circuit.library import QNNCircuit from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap from qiskit_algorithms.utils import algorithm_globals from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit_machine_learning.circuit.library import QNNCircuit def create_qnn(): feature_map = ZZFeatureMap(5) ansatz = RealAmplitudes(5, reps=1) qc = QNNCircuit(5) qc.compose(feature_map, inplace=True) qc.compose(ansatz, inplace=True) # Create a Quantum Neural Network (QNN) with 5 output neurons qnn = QNNCircuit(circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters, output_shape=(5,), output_params=[Parameter(f"theta_{i}") for i in range(5)], measurement_error_mitigation=True) return qnn qnn = create_qnn() class qNet(Module): def __init__(self, qnn): super(qNet, self).__init__() # Load the pre-trained MobileNetV3 model self.mobilenet = models.mobilenet_v3_large(pretrained=True, progress=True) # Freeze all layers except the classifier for param in self.mobilenet.parameters(): param.requires_grad = False num_classes = args.nb_classes in_features = self.mobilenet.classifier[-1].in_features self.mobilenet.classifier[-1] = nn.Linear(in_features, num_classes) num_layers_unfreeze = 50 # Unfreeze the last layer for fine-tuning for param in self.mobilenet.classifier[-num_layers_unfreeze:].parameters(): param.requires_grad = True # Ensure that qnn is a PyTorch neural network object self.qnn = TorchConnector(qnn) self.fc1 = nn.Linear(num_classes, num_classes) def forward(self, x): # Pass the input through the MobileNetV3 model x = self.mobilenet(x) # Apply the quantum network in the forward section x = self.qnn(x) x = x.view(x.size(0), -1) # Flatten the output return self.fc1(x) # # # Create random input data batch_size = 1 channels = 3 height = 224 width = 224 random_input = torch.randn(batch_size, channels, height, width) model = qNet(qnn) output = model(random_input) print("Output shape:", output.shape) model model model(random_input) misc.init_distributed_mode(args) # print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train = build_dataset(is_train=True, args=args) dataset_val = build_dataset(is_train=False, args=args) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) # model = models_vit.__dict__[args.model]( # num_classes=args.nb_classes, # drop_path_rate=args.drop_path, # global_pool=args.global_pool, # ) model = stage_1_model if args.finetune and not args.eval: print("args.finetune and not args.eval") checkpoint = torch.load(args.finetune, map_location='cpu') print("Load pre-trained checkpoint from: %s" % args.finetune) checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding interpolate_pos_embed(model, checkpoint_model) # load pre-trained model msg = model.load_state_dict(checkpoint_model, strict=False) print(msg) if args.global_pool: assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'} else: assert set(msg.missing_keys) == {'head.weight', 'head.bias'} # manually initialize fc layer trunc_normal_(model.head.weight, std=2e-5) model.to(device) model_without_ddp = model n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print("Model = %s" % str(model_without_ddp)) print('number of params (M): %.2f' % (n_parameters / 1.e6)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size / 256 print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module optimizer = optim.Adam(model.parameters(), lr=args.lr)#SEB # optimizer = torch.optim.AdamW(param_groups, lr=args.lr) loss_scaler = NativeScaler() if mixup_fn is not None: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() print("criterion = %s" % str(criterion)) misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") # exit(0) train = True if train: print(f"Start training for {args.epochs} epochs with batch size of {args.batch_size}") start_time = time.time() max_accuracy = 0.0 for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, args.clip_grad, mixup_fn, log_writer=log_writer, args=args ) if args.output_dir: misc.save_model( args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch) test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") max_accuracy = max(max_accuracy, test_stats["acc1"]) print(f'Max accuracy: {max_accuracy:.2f}%') if log_writer is not None: log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch) log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch) log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) EXPERIMENT_NAME = "mobileNet" saving_model = f"{EXPERIMENT_NAME}/models" os.makedirs(saving_model, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok=True) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") @torch.no_grad() def evaluate_test(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = misc.MetricLogger(delimiter=" ") header = 'Test:' # switch to evaluation mode model.eval() all_predictions = [] all_labels = [] for batch in metric_logger.log_every(data_loader, 10, header): images = batch[0] target = batch[-1] images = images.to(device, non_blocking=True) target = target.to(device, non_blocking=True) # compute output with torch.cuda.amp.autocast(): output = model(images) loss = criterion(output, target)# pred = output.argmax(dim=1) all_predictions.append(pred.cpu().numpy())# ADDED all_labels.append(target.cpu().numpy())# ADDED acc1, acc5 = accuracy(output, target, topk=(1, 5)) batch_size = images.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) all_predictions = np.array(all_predictions)#.squeeze(0) all_labels = np.array(all_labels)#.squeeze(0) # gather the stats from all processes metric_logger.synchronize_between_processes() print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) # return return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, np.concatenate(all_predictions, axis=0), np.concatenate(all_labels, axis=0) metrics, all_predictions, all_labels = evaluate_test(data_loader_val, model, device) # print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") metrics all_predictions unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) unique_classes confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) conf_matrix unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Example usage: plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME) # def visualize_predictions(model, val_loader, device, type_label=None, dataset_type=1, unique_classes=np.array([0, 1, 2, 3, 4, 5, 6])): # criterion = torch.nn.CrossEntropyLoss() # metric_logger = misc.MetricLogger(delimiter=" ") # header = 'Test:' # # switch to evaluation mode # model.eval() # all_predictions = [] # all_labels = [] # for batch in metric_logger.log_every(val_loader, 10, header): # images = batch[0] # target = batch[-1] # images = images.to(device, non_blocking=True) # target = target.to(device, non_blocking=True) # # compute output # with torch.cuda.amp.autocast(): # output = model(images) # loss = criterion(output, target)# # pred = output.argmax(dim=1) # all_predictions.append(pred.cpu().numpy())# ADDED # all_labels.append(target.cpu().numpy())# ADDED # acc1, acc5 = accuracy(output, target, topk=(1, 5)) # batch_size = images.shape[0] # metric_logger.update(loss=loss.item()) # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # all_predictions = np.array(all_predictions)#.squeeze(0) # all_labels = np.array(all_labels)#.squeeze(0) # if type_label is None: # type_label = unique_classes # # Create a 4x4 grid for visualization # num_rows = 4 # num_cols = 4 # plt.figure(figsize=(12, 12)) # for i in range(num_rows * num_cols): # plt.subplot(num_rows, num_cols, i + 1) # idx = np.random.randint(len(all_labels)) # import pdb;pdb.set_trace() # plt.imshow(images[idx].cpu().numpy().squeeze(), cmap='gray') # # Use the class names instead of numeric labels for Fashion MNIST # if dataset_type == 1: # class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # predicted_class = class_names[all_predictions[idx]] # actual_class = class_names[all_labels[idx]] # else: # predicted_class = all_predictions[idx] # actual_class = all_labels[idx] # plt.title(f'Pred: {predicted_class}\nActual: {actual_class}') # plt.axis('off') # plt.tight_layout() # plt.show() # visualize_predictions(model, data_loader_val, device, dataset_type=2, unique_classes=unique_classes) unique_classes report = classification_report(all_labels, all_predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(EXPERIMENT_NAME, "confusion_matrix.csv")) print(df) df # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(all_labels, all_predictions, average='micro') recall = recall_score(all_labels, all_predictions, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((all_labels != 1) & (all_predictions != 1)) fp = np.sum((all_labels != 1) & (all_predictions == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(all_labels, all_predictions, average='weighted') evaluation_metrics = { "Acc1": metrics['acc1'], # Add acc1 metric "Acc5": metrics['acc5'], # Add acc5 metric "loss": metrics['loss'], # Add acc5 metric "F1 Score": [f1], "Precision": [precision], "Recall": [recall], "Specificity": [specificity] } evaluation_metrics # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics) # Save the DataFrame to a CSV file df.to_csv(f'{EXPERIMENT_NAME}/evaluation_metrics_for_table.csv', index=False) df
https://github.com/sebasmos/QuantumVE
sebasmos
!pwd from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import os import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def run_one_image(img, model): x = torch.tensor(img) # make it a batch-like x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) # run MAE loss, y, mask = model(x.float(), mask_ratio=0.75) y = model.unpatchify(y) y = torch.einsum('nchw->nhwc', y).detach().cpu() # visualize the mask mask = mask.detach() mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3) mask = model.unpatchify(mask) # 1 is removing, 0 is keeping mask = torch.einsum('nchw->nhwc', mask).detach().cpu() x = torch.einsum('nchw->nhwc', x) # masked image im_masked = x * (1 - mask) # MAE reconstruction pasted with visible patches im_paste = x * (1 - mask) + y * mask # make the plt figure larger plt.rcParams['figure.figsize'] = [24, 24] plt.subplot(1, 4, 1) show_image(x[0], "original") plt.subplot(1, 4, 2) show_image(im_masked[0], "masked") plt.subplot(1, 4, 3) show_image(y[0], "reconstruction") plt.subplot(1, 4, 4) show_image(im_paste[0], "reconstruction + visible") plt.show() # Set the seed for PyTorch torch.manual_seed(42) parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=1, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=2, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='vit_base_patch16', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/Datos_Entrenamiento/', type=str, help='dataset path') parser.add_argument('--nb_classes', default=7, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='EXP_base_biggest_dataset', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='./output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default='', help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # -------------------------------------------------------- # References: # DeiT: https://github.com/facebookresearch/deit # -------------------------------------------------------- import os import PIL from torchvision import datasets, transforms from sklearn.model_selection import KFold from torch.utils.data import Subset from timm.data import create_transform from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD def build_transform(is_train, args): mean = IMAGENET_DEFAULT_MEAN std = IMAGENET_DEFAULT_STD # train transform if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation='bicubic', re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, mean=mean, std=std, ) return transform # eval transform t = [] if args.input_size <= 224: crop_pct = 224 / 256 else: crop_pct = 1.0 size = int(args.input_size / crop_pct) t.append( transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(mean, std)) return transforms.Compose(t) def build_dataset_full_dataset(is_train, args): transform = build_transform(is_train, args) # root = os.path.join(args.data_path, 'train' if is_train else 'val') root = args.data_path dataset = datasets.ImageFolder(root, transform=transform) print(dataset) return dataset misc.init_distributed_mode(args) # print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True # create dataset with all folders possible withoput splits training = False# false because we will resplit this dataset = build_dataset_full_dataset(training,args=args) num_splits = 2 train = True kf = KFold(n_splits=num_splits, shuffle=True, random_state=42) # Iterate over each fold for fold, (train_index, val_index) in enumerate(kf.split(dataset)): print(f"\nTraining on Fold {fold + 1}/{num_splits}:".center(60,"-")) # Create train and validation sets for this fold train_dataset_fold = Subset(dataset, train_index) val_dataset_fold = Subset(dataset, val_index) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) model = models_vit.__dict__[args.model]( num_classes=args.nb_classes, drop_path_rate=args.drop_path, global_pool=args.global_pool, ) if args.finetune and not args.eval: checkpoint = torch.load(args.finetune, map_location='cpu') print("Load pre-trained checkpoint from: %s" % args.finetune) checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding interpolate_pos_embed(model, checkpoint_model) # load pre-trained model msg = model.load_state_dict(checkpoint_model, strict=False) print(msg) if args.global_pool: assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'} else: assert set(msg.missing_keys) == {'head.weight', 'head.bias'} # manually initialize fc layer trunc_normal_(model.head.weight, std=2e-5) model.to(device) model_without_ddp = model n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print("Model = %s" % str(model_without_ddp)) print('number of params (M): %.2f' % (n_parameters / 1.e6)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size / 256 print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module # build optimizer with layer-wise lr decay (lrd) param_groups = lrd.param_groups_lrd(model_without_ddp, args.weight_decay, no_weight_decay_list=model_without_ddp.no_weight_decay(), layer_decay=args.layer_decay ) optimizer = torch.optim.AdamW(param_groups, lr=args.lr) loss_scaler = NativeScaler() if mixup_fn is not None: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() print("criterion = %s" % str(criterion)) misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") if train: print(f"Start training for {args.epochs} epochs") start_time = time.time() max_accuracy = 0.0 for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, args.clip_grad, mixup_fn, log_writer=log_writer, args=args ) if args.output_dir: misc.save_model( args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch) test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") max_accuracy = max(max_accuracy, test_stats["acc1"]) print(f'Max accuracy: {max_accuracy:.2f}%') if log_writer is not None: log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch) log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch) log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) evaluation_metrics = { "Acc1": test_stats['acc1'], # Add acc1 metric "Acc5": test_stats['acc5'], # Add acc5 metric "loss": test_stats['loss'], # Add acc5 metric } print(evaluation_metrics) break # if True: # args.distributed: # num_tasks = misc.get_world_size() # global_rank = misc.get_rank() # sampler_train = torch.utils.data.DistributedSampler( # dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True # ) # print("Sampler_train = %s" % str(sampler_train)) # if args.dist_eval: # if len(dataset_val) % num_tasks != 0: # print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' # 'This will slightly alter validation results as extra duplicate entries are added to achieve ' # 'equal num of samples per-process.') # sampler_val = torch.utils.data.DistributedSampler( # dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias # else: # sampler_val = torch.utils.data.SequentialSampler(dataset_val) # else: # sampler_train = torch.utils.data.RandomSampler(dataset_train) # sampler_val = torch.utils.data.SequentialSampler(dataset_val) # if global_rank == 0 and args.log_dir is not None and not args.eval: # os.makedirs(args.log_dir, exist_ok=True) # log_writer = SummaryWriter(log_dir=args.log_dir) # else: # log_writer = None # data_loader_train = torch.utils.data.DataLoader( # dataset_train, sampler=sampler_train, # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=True, # ) # data_loader_val = torch.utils.data.DataLoader( # dataset_val, sampler=sampler_val, # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=False # ) # #Liberia Validacion cruzada # from sklearn.model_selection import KFold # # K-fold cross-validation # num_splits = 5 # ajusta el número de splits según tus necesidades # kf = KFold(n_splits=num_splits, shuffle=True, random_state=42) # for fold, (train_index, val_index) in enumerate(kf.split(dataset_train)): # print(f"\nTraining on Fold {fold + 1}/{num_splits}:") # # create train and validation sets for this fold # train_dataset_fold = Subset(dataset_train, train_index) # val_dataset_fold = Subset(dataset_train, val_index) # data_loader_train = torch.utils.data.DataLoader( # train_dataset_fold, sampler=torch.utils.data.RandomSampler(train_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=True, # ) # data_loader_val = torch.utils.data.DataLoader( # val_dataset_fold, sampler=torch.utils.data.SequentialSampler(val_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=False # ) # mixup_fn = None # mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None # if mixup_active: # print("Mixup is activated!") # mixup_fn = Mixup( # mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, # prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, # label_smoothing=args.smoothing, num_classes=args.nb_classes) # model = models_vit.__dict__[args.model]( # num_classes=args.nb_classes, # drop_path_rate=args.drop_path, # global_pool=args.global_pool, # ) # if args.finetune and not args.eval: # checkpoint = torch.load(args.finetune, map_location='cpu') # print("Load pre-trained checkpoint from: %s" % args.finetune) # checkpoint_model = checkpoint['model'] # state_dict = model.state_dict() # for k in ['head.weight', 'head.bias']: # if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: # print(f"Removing key {k} from pretrained checkpoint") # del checkpoint_model[k] # # interpolate position embedding # interpolate_pos_embed(model, checkpoint_model) # # load pre-trained model # msg = model.load_state_dict(checkpoint_model, strict=False) # print(msg) # if args.global_pool: # assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'} # else: # assert set(msg.missing_keys) == {'head.weight', 'head.bias'} # # manually initialize fc layer # trunc_normal_(model.head.weight, std=2e-5) # model.to(device) # model_without_ddp = model # n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) # print("Model = %s" % str(model_without_ddp)) # print('number of params (M): %.2f' % (n_parameters / 1.e6)) # eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() # if args.lr is None: # only base_lr is specified # args.lr = args.blr * eff_batch_size / 256 # print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) # print("actual lr: %.2e" % args.lr) # print("accumulate grad iterations: %d" % args.accum_iter) # print("effective batch size: %d" % eff_batch_size) # if args.distributed: # model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) # model_without_ddp = model.module # # build optimizer with layer-wise lr decay (lrd) # param_groups = lrd.param_groups_lrd(model_without_ddp, args.weight_decay, # no_weight_decay_list=model_without_ddp.no_weight_decay(), # layer_decay=args.layer_decay # ) # optimizer = torch.optim.AdamW(param_groups, lr=args.lr) # loss_scaler = NativeScaler() # if mixup_fn is not None: # # smoothing is handled with mixup label transform # criterion = SoftTargetCrossEntropy() # elif args.smoothing > 0.: # criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) # else: # criterion = torch.nn.CrossEntropyLoss() # print("criterion = %s" % str(criterion)) # misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) # if args.eval: # test_stats = evaluate(data_loader_val, model, device) # print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") # # exit(0) train = True if train: print(f"Start training for {args.epochs} epochs") start_time = time.time() max_accuracy = 0.0 for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, args.clip_grad, mixup_fn, log_writer=log_writer, args=args ) if args.output_dir: misc.save_model( args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch) test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") max_accuracy = max(max_accuracy, test_stats["acc1"]) print(f'Max accuracy: {max_accuracy:.2f}%') if log_writer is not None: log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch) log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch) log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) EXPERIMENT_NAME = "eval_vit_base" saving_model = f"{EXPERIMENT_NAME}/models" os.makedirs(saving_model, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok=True) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") @torch.no_grad() def evaluate_test(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = misc.MetricLogger(delimiter=" ") header = 'Test:' # switch to evaluation mode model.eval() all_predictions = [] all_labels = [] for batch in metric_logger.log_every(data_loader, 10, header): images = batch[0] target = batch[-1] images = images.to(device, non_blocking=True) target = target.to(device, non_blocking=True) # compute output with torch.cuda.amp.autocast(): output = model(images) loss = criterion(output, target)# pred = output.argmax(dim=1) all_predictions.append(pred.cpu().numpy())# ADDED all_labels.append(target.cpu().numpy())# ADDED acc1, acc5 = accuracy(output, target, topk=(1, 5)) batch_size = images.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) all_predictions = np.array(all_predictions)#.squeeze(0) all_labels = np.array(all_labels)#.squeeze(0) # gather the stats from all processes metric_logger.synchronize_between_processes() print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) # return return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, np.concatenate(all_predictions, axis=0), np.concatenate(all_labels, axis=0) metrics, all_predictions, all_labels = evaluate_test(data_loader_val, model, device) # print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") metrics all_predictions unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) unique_classes confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) conf_matrix unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Example usage: plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME) # def visualize_predictions(model, val_loader, device, type_label=None, dataset_type=1, unique_classes=np.array([0, 1, 2, 3, 4, 5, 6])): # criterion = torch.nn.CrossEntropyLoss() # metric_logger = misc.MetricLogger(delimiter=" ") # header = 'Test:' # # switch to evaluation mode # model.eval() # all_predictions = [] # all_labels = [] # for batch in metric_logger.log_every(val_loader, 10, header): # images = batch[0] # target = batch[-1] # images = images.to(device, non_blocking=True) # target = target.to(device, non_blocking=True) # # compute output # with torch.cuda.amp.autocast(): # output = model(images) # loss = criterion(output, target)# # pred = output.argmax(dim=1) # all_predictions.append(pred.cpu().numpy())# ADDED # all_labels.append(target.cpu().numpy())# ADDED # acc1, acc5 = accuracy(output, target, topk=(1, 5)) # batch_size = images.shape[0] # metric_logger.update(loss=loss.item()) # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # all_predictions = np.array(all_predictions)#.squeeze(0) # all_labels = np.array(all_labels)#.squeeze(0) # if type_label is None: # type_label = unique_classes # # Create a 4x4 grid for visualization # num_rows = 4 # num_cols = 4 # plt.figure(figsize=(12, 12)) # for i in range(num_rows * num_cols): # plt.subplot(num_rows, num_cols, i + 1) # idx = np.random.randint(len(all_labels)) # import pdb;pdb.set_trace() # plt.imshow(images[idx].cpu().numpy().squeeze(), cmap='gray') # # Use the class names instead of numeric labels for Fashion MNIST # if dataset_type == 1: # class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # predicted_class = class_names[all_predictions[idx]] # actual_class = class_names[all_labels[idx]] # else: # predicted_class = all_predictions[idx] # actual_class = all_labels[idx] # plt.title(f'Pred: {predicted_class}\nActual: {actual_class}') # plt.axis('off') # plt.tight_layout() # plt.show() # visualize_predictions(model, data_loader_val, device, dataset_type=2, unique_classes=unique_classes) unique_classes report = classification_report(all_labels, all_predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(EXPERIMENT_NAME, "confusion_matrix.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(all_labels, all_predictions, average='micro') recall = recall_score(all_labels, all_predictions, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((all_labels != 1) & (all_predictions != 1)) fp = np.sum((all_labels != 1) & (all_predictions == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(all_labels, all_predictions, average='weighted') evaluation_metrics = { "Acc1": metrics['acc1'], # Add acc1 metric "Acc5": metrics['acc5'], # Add acc5 metric "loss": metrics['loss'], # Add acc5 metric "F1 Score": [f1], "Precision": [precision], "Recall": [recall], "Specificity": [specificity] } evaluation_metrics # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics) # Save the DataFrame to a CSV file df.to_csv(f'{EXPERIMENT_NAME}/evaluation_metrics_for_table.csv', index=False)
https://github.com/sebasmos/QuantumVE
sebasmos
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import os import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def run_one_image(img, model): x = torch.tensor(img) # make it a batch-like x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) # run MAE loss, y, mask = model(x.float(), mask_ratio=0.75) y = model.unpatchify(y) y = torch.einsum('nchw->nhwc', y).detach().cpu() # visualize the mask mask = mask.detach() mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3) mask = model.unpatchify(mask) # 1 is removing, 0 is keeping mask = torch.einsum('nchw->nhwc', mask).detach().cpu() x = torch.einsum('nchw->nhwc', x) # masked image im_masked = x * (1 - mask) # MAE reconstruction pasted with visible patches im_paste = x * (1 - mask) + y * mask # make the plt figure larger plt.rcParams['figure.figsize'] = [24, 24] plt.subplot(1, 4, 1) show_image(x[0], "original") plt.subplot(1, 4, 2) show_image(im_masked[0], "masked") plt.subplot(1, 4, 3) show_image(y[0], "reconstruction") plt.subplot(1, 4, 4) show_image(im_paste[0], "reconstruction + visible") plt.show() # Set the seed for PyTorch torch.manual_seed(42) parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=32, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=100, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='vit_base_patch16', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/ABGQI_mel_spectrograms', type=str, help='dataset path') parser.add_argument('--nb_classes', default=5, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='quinn_5_classes', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='./output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default='./quinn_5_classes/checkpoint-999.pth', help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) misc.init_distributed_mode(args) # print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train = build_dataset(is_train=True, args=args) dataset_val = build_dataset(is_train=False, args=args) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) # #Liberia Validacion cruzada # from sklearn.model_selection import KFold # # K-fold cross-validation # num_splits = 5 # ajusta el número de splits según tus necesidades # kf = KFold(n_splits=num_splits, shuffle=True, random_state=42) # for fold, (train_index, val_index) in enumerate(kf.split(dataset_train)): # print(f"\nTraining on Fold {fold + 1}/{num_splits}:") # # create train and validation sets for this fold # train_dataset_fold = Subset(dataset_train, train_index) # val_dataset_fold = Subset(dataset_train, val_index) # data_loader_train = torch.utils.data.DataLoader( # train_dataset_fold, sampler=torch.utils.data.RandomSampler(train_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=True, # ) # data_loader_val = torch.utils.data.DataLoader( # val_dataset_fold, sampler=torch.utils.data.SequentialSampler(val_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=False # ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) model = models_vit.__dict__[args.model]( num_classes=args.nb_classes, drop_path_rate=args.drop_path, global_pool=args.global_pool, ) if args.finetune and not args.eval: checkpoint = torch.load(args.finetune, map_location='cpu') print("Load pre-trained checkpoint from: %s" % args.finetune) checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding interpolate_pos_embed(model, checkpoint_model) # load pre-trained model msg = model.load_state_dict(checkpoint_model, strict=False) print(msg) if args.global_pool: assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'} else: assert set(msg.missing_keys) == {'head.weight', 'head.bias'} # manually initialize fc layer trunc_normal_(model.head.weight, std=2e-5) model.to(device) model_without_ddp = model n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print("Model = %s" % str(model_without_ddp)) print('number of params (M): %.2f' % (n_parameters / 1.e6)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size / 256 print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module # build optimizer with layer-wise lr decay (lrd) param_groups = lrd.param_groups_lrd(model_without_ddp, args.weight_decay, no_weight_decay_list=model_without_ddp.no_weight_decay(), layer_decay=args.layer_decay ) optimizer = torch.optim.AdamW(param_groups, lr=args.lr) loss_scaler = NativeScaler() if mixup_fn is not None: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() print("criterion = %s" % str(criterion)) misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") # exit(0) train = False if train: print(f"Start training for {args.epochs} epochs") start_time = time.time() max_accuracy = 0.0 for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, args.clip_grad, mixup_fn, log_writer=log_writer, args=args ) if args.output_dir: misc.save_model( args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch) test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") max_accuracy = max(max_accuracy, test_stats["acc1"]) print(f'Max accuracy: {max_accuracy:.2f}%') if log_writer is not None: log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch) log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch) log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) EXPERIMENT_NAME = "quinn_5_classes" saving_model = f"{EXPERIMENT_NAME}/models" os.makedirs(saving_model, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok=True) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") @torch.no_grad() def evaluate_test(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = misc.MetricLogger(delimiter=" ") header = 'Test:' # switch to evaluation mode model.eval() all_predictions = [] all_labels = [] for batch in metric_logger.log_every(data_loader, 10, header): images = batch[0] target = batch[-1] images = images.to(device, non_blocking=True) target = target.to(device, non_blocking=True) # compute output with torch.cuda.amp.autocast(): output = model(images) loss = criterion(output, target)# pred = output.argmax(dim=1) all_predictions.append(pred.cpu().numpy())# ADDED all_labels.append(target.cpu().numpy())# ADDED acc1, acc5 = accuracy(output, target, topk=(1, 5)) batch_size = images.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) all_predictions = np.array(all_predictions)#.squeeze(0) all_labels = np.array(all_labels)#.squeeze(0) # gather the stats from all processes metric_logger.synchronize_between_processes() print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) # return return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, np.concatenate(all_predictions, axis=0), np.concatenate(all_labels, axis=0) metrics, all_predictions, all_labels = evaluate_test(data_loader_val, model, device) # print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") metrics all_predictions unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) unique_classes confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) conf_matrix unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Example usage: plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME) # def visualize_predictions(model, val_loader, device, type_label=None, dataset_type=1, unique_classes=np.array([0, 1, 2, 3, 4, 5, 6])): # criterion = torch.nn.CrossEntropyLoss() # metric_logger = misc.MetricLogger(delimiter=" ") # header = 'Test:' # # switch to evaluation mode # model.eval() # all_predictions = [] # all_labels = [] # for batch in metric_logger.log_every(val_loader, 10, header): # images = batch[0] # target = batch[-1] # images = images.to(device, non_blocking=True) # target = target.to(device, non_blocking=True) # # compute output # with torch.cuda.amp.autocast(): # output = model(images) # loss = criterion(output, target)# # pred = output.argmax(dim=1) # all_predictions.append(pred.cpu().numpy())# ADDED # all_labels.append(target.cpu().numpy())# ADDED # acc1, acc5 = accuracy(output, target, topk=(1, 5)) # batch_size = images.shape[0] # metric_logger.update(loss=loss.item()) # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # all_predictions = np.array(all_predictions)#.squeeze(0) # all_labels = np.array(all_labels)#.squeeze(0) # if type_label is None: # type_label = unique_classes # # Create a 4x4 grid for visualization # num_rows = 4 # num_cols = 4 # plt.figure(figsize=(12, 12)) # for i in range(num_rows * num_cols): # plt.subplot(num_rows, num_cols, i + 1) # idx = np.random.randint(len(all_labels)) # import pdb;pdb.set_trace() # plt.imshow(images[idx].cpu().numpy().squeeze(), cmap='gray') # # Use the class names instead of numeric labels for Fashion MNIST # if dataset_type == 1: # class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # predicted_class = class_names[all_predictions[idx]] # actual_class = class_names[all_labels[idx]] # else: # predicted_class = all_predictions[idx] # actual_class = all_labels[idx] # plt.title(f'Pred: {predicted_class}\nActual: {actual_class}') # plt.axis('off') # plt.tight_layout() # plt.show() # visualize_predictions(model, data_loader_val, device, dataset_type=2, unique_classes=unique_classes) unique_classes report = classification_report(all_labels, all_predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(EXPERIMENT_NAME, "confusion_matrix.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(all_labels, all_predictions, average='micro') recall = recall_score(all_labels, all_predictions, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((all_labels != 1) & (all_predictions != 1)) fp = np.sum((all_labels != 1) & (all_predictions == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(all_labels, all_predictions, average='weighted') evaluation_metrics = { "Acc1": metrics['acc1'], # Add acc1 metric "Acc5": metrics['acc5'], # Add acc5 metric "loss": metrics['loss'], # Add acc5 metric "F1 Score": [f1], "Precision": [precision], "Recall": [recall], "Specificity": [specificity] } evaluation_metrics # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics) # Save the DataFrame to a CSV file df.to_csv(f'{EXPERIMENT_NAME}/evaluation_metrics_for_table.csv', index=False) df
https://github.com/sebasmos/QuantumVE
sebasmos
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import os import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def run_one_image(img, model): x = torch.tensor(img) # make it a batch-like x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) # run MAE loss, y, mask = model(x.float(), mask_ratio=0.75) y = model.unpatchify(y) y = torch.einsum('nchw->nhwc', y).detach().cpu() # visualize the mask mask = mask.detach() mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3) mask = model.unpatchify(mask) # 1 is removing, 0 is keeping mask = torch.einsum('nchw->nhwc', mask).detach().cpu() x = torch.einsum('nchw->nhwc', x) # masked image im_masked = x * (1 - mask) # MAE reconstruction pasted with visible patches im_paste = x * (1 - mask) + y * mask # make the plt figure larger plt.rcParams['figure.figsize'] = [24, 24] plt.subplot(1, 4, 1) show_image(x[0], "original") plt.subplot(1, 4, 2) show_image(im_masked[0], "masked") plt.subplot(1, 4, 3) show_image(y[0], "reconstruction") plt.subplot(1, 4, 4) show_image(im_paste[0], "reconstruction + visible") plt.show() # Set the seed for PyTorch torch.manual_seed(42) parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=32, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=100, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='vit_base_patch16', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/Datos_Entrenamiento/', type=str, help='dataset path') parser.add_argument('--nb_classes', default=7, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='EXP_base_biggest_dataset', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='./output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default='./EXP_base_biggest_dataset/checkpoint-99.pth', help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) misc.init_distributed_mode(args) # print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train = build_dataset(is_train=True, args=args) dataset_val = build_dataset(is_train=False, args=args) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) # #Liberia Validacion cruzada # from sklearn.model_selection import KFold # # K-fold cross-validation # num_splits = 5 # ajusta el número de splits según tus necesidades # kf = KFold(n_splits=num_splits, shuffle=True, random_state=42) # for fold, (train_index, val_index) in enumerate(kf.split(dataset_train)): # print(f"\nTraining on Fold {fold + 1}/{num_splits}:") # # create train and validation sets for this fold # train_dataset_fold = Subset(dataset_train, train_index) # val_dataset_fold = Subset(dataset_train, val_index) # data_loader_train = torch.utils.data.DataLoader( # train_dataset_fold, sampler=torch.utils.data.RandomSampler(train_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=True, # ) # data_loader_val = torch.utils.data.DataLoader( # val_dataset_fold, sampler=torch.utils.data.SequentialSampler(val_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=False # ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) model = models_vit.__dict__[args.model]( num_classes=args.nb_classes, drop_path_rate=args.drop_path, global_pool=args.global_pool, ) if args.finetune and not args.eval: checkpoint = torch.load(args.finetune, map_location='cpu') print("Load pre-trained checkpoint from: %s" % args.finetune) checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding interpolate_pos_embed(model, checkpoint_model) # load pre-trained model msg = model.load_state_dict(checkpoint_model, strict=False) print(msg) if args.global_pool: assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'} else: assert set(msg.missing_keys) == {'head.weight', 'head.bias'} # manually initialize fc layer trunc_normal_(model.head.weight, std=2e-5) model.to(device) model_without_ddp = model n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print("Model = %s" % str(model_without_ddp)) print('number of params (M): %.2f' % (n_parameters / 1.e6)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size / 256 print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module # build optimizer with layer-wise lr decay (lrd) param_groups = lrd.param_groups_lrd(model_without_ddp, args.weight_decay, no_weight_decay_list=model_without_ddp.no_weight_decay(), layer_decay=args.layer_decay ) optimizer = torch.optim.AdamW(param_groups, lr=args.lr) loss_scaler = NativeScaler() if mixup_fn is not None: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() print("criterion = %s" % str(criterion)) misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") # exit(0) train = False if train: print(f"Start training for {args.epochs} epochs") start_time = time.time() max_accuracy = 0.0 for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, args.clip_grad, mixup_fn, log_writer=log_writer, args=args ) if args.output_dir: misc.save_model( args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch) test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") max_accuracy = max(max_accuracy, test_stats["acc1"]) print(f'Max accuracy: {max_accuracy:.2f}%') if log_writer is not None: log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch) log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch) log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) EXPERIMENT_NAME = "eval_vit_base_large_dataset" saving_model = f"{EXPERIMENT_NAME}/models" os.makedirs(saving_model, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok=True) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") @torch.no_grad() def evaluate_test(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = misc.MetricLogger(delimiter=" ") header = 'Test:' # switch to evaluation mode model.eval() all_predictions = [] all_labels = [] for batch in metric_logger.log_every(data_loader, 10, header): images = batch[0] target = batch[-1] images = images.to(device, non_blocking=True) target = target.to(device, non_blocking=True) # compute output with torch.cuda.amp.autocast(): output = model(images) loss = criterion(output, target)# pred = output.argmax(dim=1) all_predictions.append(pred.cpu().numpy())# ADDED all_labels.append(target.cpu().numpy())# ADDED acc1, acc5 = accuracy(output, target, topk=(1, 5)) batch_size = images.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) all_predictions = np.array(all_predictions)#.squeeze(0) all_labels = np.array(all_labels)#.squeeze(0) # gather the stats from all processes metric_logger.synchronize_between_processes() print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) # return return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, np.concatenate(all_predictions, axis=0), np.concatenate(all_labels, axis=0) metrics, all_predictions, all_labels = evaluate_test(data_loader_val, model, device) # print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") metrics all_predictions unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) unique_classes confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) conf_matrix unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Example usage: plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME) # def visualize_predictions(model, val_loader, device, type_label=None, dataset_type=1, unique_classes=np.array([0, 1, 2, 3, 4, 5, 6])): # criterion = torch.nn.CrossEntropyLoss() # metric_logger = misc.MetricLogger(delimiter=" ") # header = 'Test:' # # switch to evaluation mode # model.eval() # all_predictions = [] # all_labels = [] # for batch in metric_logger.log_every(val_loader, 10, header): # images = batch[0] # target = batch[-1] # images = images.to(device, non_blocking=True) # target = target.to(device, non_blocking=True) # # compute output # with torch.cuda.amp.autocast(): # output = model(images) # loss = criterion(output, target)# # pred = output.argmax(dim=1) # all_predictions.append(pred.cpu().numpy())# ADDED # all_labels.append(target.cpu().numpy())# ADDED # acc1, acc5 = accuracy(output, target, topk=(1, 5)) # batch_size = images.shape[0] # metric_logger.update(loss=loss.item()) # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # all_predictions = np.array(all_predictions)#.squeeze(0) # all_labels = np.array(all_labels)#.squeeze(0) # if type_label is None: # type_label = unique_classes # # Create a 4x4 grid for visualization # num_rows = 4 # num_cols = 4 # plt.figure(figsize=(12, 12)) # for i in range(num_rows * num_cols): # plt.subplot(num_rows, num_cols, i + 1) # idx = np.random.randint(len(all_labels)) # import pdb;pdb.set_trace() # plt.imshow(images[idx].cpu().numpy().squeeze(), cmap='gray') # # Use the class names instead of numeric labels for Fashion MNIST # if dataset_type == 1: # class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # predicted_class = class_names[all_predictions[idx]] # actual_class = class_names[all_labels[idx]] # else: # predicted_class = all_predictions[idx] # actual_class = all_labels[idx] # plt.title(f'Pred: {predicted_class}\nActual: {actual_class}') # plt.axis('off') # plt.tight_layout() # plt.show() # visualize_predictions(model, data_loader_val, device, dataset_type=2, unique_classes=unique_classes) unique_classes report = classification_report(all_labels, all_predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(EXPERIMENT_NAME, "confusion_matrix.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(all_labels, all_predictions, average='micro') recall = recall_score(all_labels, all_predictions, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((all_labels != 1) & (all_predictions != 1)) fp = np.sum((all_labels != 1) & (all_predictions == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(all_labels, all_predictions, average='weighted') evaluation_metrics = { "Acc1": metrics['acc1'], # Add acc1 metric "Acc5": metrics['acc5'], # Add acc5 metric "loss": metrics['loss'], # Add acc5 metric "F1 Score": [f1], "Precision": [precision], "Recall": [recall], "Specificity": [specificity] } evaluation_metrics # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics) # Save the DataFrame to a CSV file df.to_csv(f'{EXPERIMENT_NAME}/evaluation_metrics_for_table.csv', index=False)
https://github.com/sebasmos/QuantumVE
sebasmos
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import os import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def run_one_image(img, model): x = torch.tensor(img) # make it a batch-like x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) # run MAE loss, y, mask = model(x.float(), mask_ratio=0.75) y = model.unpatchify(y) y = torch.einsum('nchw->nhwc', y).detach().cpu() # visualize the mask mask = mask.detach() mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3) mask = model.unpatchify(mask) # 1 is removing, 0 is keeping mask = torch.einsum('nchw->nhwc', mask).detach().cpu() x = torch.einsum('nchw->nhwc', x) # masked image im_masked = x * (1 - mask) # MAE reconstruction pasted with visible patches im_paste = x * (1 - mask) + y * mask # make the plt figure larger plt.rcParams['figure.figsize'] = [24, 24] plt.subplot(1, 4, 1) show_image(x[0], "original") plt.subplot(1, 4, 2) show_image(im_masked[0], "masked") plt.subplot(1, 4, 3) show_image(y[0], "reconstruction") plt.subplot(1, 4, 4) show_image(im_paste[0], "reconstruction + visible") plt.show() # Set the seed for PyTorch torch.manual_seed(42) parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=32, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=100, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='vit_base_patch16', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/Datos_Entrenamiento/', type=str, help='dataset path') parser.add_argument('--nb_classes', default=7, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='EXP_base_biggest_dataset', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='./output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default='', help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) misc.init_distributed_mode(args) # print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__)))) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) # fix the seed for reproducibility seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train = build_dataset(is_train=True, args=args) dataset_val = build_dataset(is_train=False, args=args) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) # #Liberia Validacion cruzada # from sklearn.model_selection import KFold # # K-fold cross-validation # num_splits = 5 # ajusta el número de splits según tus necesidades # kf = KFold(n_splits=num_splits, shuffle=True, random_state=42) # for fold, (train_index, val_index) in enumerate(kf.split(dataset_train)): # print(f"\nTraining on Fold {fold + 1}/{num_splits}:") # # create train and validation sets for this fold # train_dataset_fold = Subset(dataset_train, train_index) # val_dataset_fold = Subset(dataset_train, val_index) # data_loader_train = torch.utils.data.DataLoader( # train_dataset_fold, sampler=torch.utils.data.RandomSampler(train_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=True, # ) # data_loader_val = torch.utils.data.DataLoader( # val_dataset_fold, sampler=torch.utils.data.SequentialSampler(val_dataset_fold), # batch_size=args.batch_size, # num_workers=args.num_workers, # pin_memory=args.pin_mem, # drop_last=False # ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: print("Mixup is activated!") mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) model = models_vit.__dict__[args.model]( num_classes=args.nb_classes, drop_path_rate=args.drop_path, global_pool=args.global_pool, ) if args.finetune and not args.eval: checkpoint = torch.load(args.finetune, map_location='cpu') print("Load pre-trained checkpoint from: %s" % args.finetune) checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding interpolate_pos_embed(model, checkpoint_model) # load pre-trained model msg = model.load_state_dict(checkpoint_model, strict=False) print(msg) if args.global_pool: assert set(msg.missing_keys) == {'head.weight', 'head.bias', 'fc_norm.weight', 'fc_norm.bias'} else: assert set(msg.missing_keys) == {'head.weight', 'head.bias'} # manually initialize fc layer trunc_normal_(model.head.weight, std=2e-5) model.to(device) model_without_ddp = model n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print("Model = %s" % str(model_without_ddp)) print('number of params (M): %.2f' % (n_parameters / 1.e6)) eff_batch_size = args.batch_size * args.accum_iter * misc.get_world_size() if args.lr is None: # only base_lr is specified args.lr = args.blr * eff_batch_size / 256 print("base lr: %.2e" % (args.lr * 256 / eff_batch_size)) print("actual lr: %.2e" % args.lr) print("accumulate grad iterations: %d" % args.accum_iter) print("effective batch size: %d" % eff_batch_size) if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) model_without_ddp = model.module # build optimizer with layer-wise lr decay (lrd) param_groups = lrd.param_groups_lrd(model_without_ddp, args.weight_decay, no_weight_decay_list=model_without_ddp.no_weight_decay(), layer_decay=args.layer_decay ) optimizer = torch.optim.AdamW(param_groups, lr=args.lr) loss_scaler = NativeScaler() if mixup_fn is not None: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing > 0.: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() print("criterion = %s" % str(criterion)) misc.load_model(args=args, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") # exit(0) train = False if train: print(f"Start training for {args.epochs} epochs") start_time = time.time() max_accuracy = 0.0 for epoch in range(args.start_epoch, args.epochs): if args.distributed: data_loader_train.sampler.set_epoch(epoch) train_stats = train_one_epoch( model, criterion, data_loader_train, optimizer, device, epoch, loss_scaler, args.clip_grad, mixup_fn, log_writer=log_writer, args=args ) if args.output_dir: misc.save_model( args=args, model=model, model_without_ddp=model_without_ddp, optimizer=optimizer, loss_scaler=loss_scaler, epoch=epoch) test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") max_accuracy = max(max_accuracy, test_stats["acc1"]) print(f'Max accuracy: {max_accuracy:.2f}%') if log_writer is not None: log_writer.add_scalar('perf/test_acc1', test_stats['acc1'], epoch) log_writer.add_scalar('perf/test_acc5', test_stats['acc5'], epoch) log_writer.add_scalar('perf/test_loss', test_stats['loss'], epoch) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in test_stats.items()}, 'epoch': epoch, 'n_parameters': n_parameters} if args.output_dir and misc.is_main_process(): if log_writer is not None: log_writer.flush() with open(os.path.join(args.output_dir, "log.txt"), mode="a", encoding="utf-8") as f: f.write(json.dumps(log_stats) + "\n") total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) print('Training time {}'.format(total_time_str)) EXPERIMENT_NAME = "eval_vit_base" saving_model = f"{EXPERIMENT_NAME}/models" os.makedirs(saving_model, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok=True) if args.eval: test_stats = evaluate(data_loader_val, model, device) print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") @torch.no_grad() def evaluate_test(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = misc.MetricLogger(delimiter=" ") header = 'Test:' # switch to evaluation mode model.eval() all_predictions = [] all_labels = [] for batch in metric_logger.log_every(data_loader, 10, header): images = batch[0] target = batch[-1] images = images.to(device, non_blocking=True) target = target.to(device, non_blocking=True) # compute output with torch.cuda.amp.autocast(): output = model(images) loss = criterion(output, target)# pred = output.argmax(dim=1) all_predictions.append(pred.cpu().numpy())# ADDED all_labels.append(target.cpu().numpy())# ADDED acc1, acc5 = accuracy(output, target, topk=(1, 5)) batch_size = images.shape[0] metric_logger.update(loss=loss.item()) metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) all_predictions = np.array(all_predictions)#.squeeze(0) all_labels = np.array(all_labels)#.squeeze(0) # gather the stats from all processes metric_logger.synchronize_between_processes() print('* Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f} loss {losses.global_avg:.3f}' .format(top1=metric_logger.acc1, top5=metric_logger.acc5, losses=metric_logger.loss)) # return return {k: meter.global_avg for k, meter in metric_logger.meters.items()}, np.concatenate(all_predictions, axis=0), np.concatenate(all_labels, axis=0) metrics, all_predictions, all_labels = evaluate_test(data_loader_val, model, device) # print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%") metrics all_predictions unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) unique_classes confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) conf_matrix unique_classes = np.unique(np.concatenate((all_labels, all_predictions))) confusion_mat = confusion_matrix(all_labels, all_predictions, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Example usage: plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME) # def visualize_predictions(model, val_loader, device, type_label=None, dataset_type=1, unique_classes=np.array([0, 1, 2, 3, 4, 5, 6])): # criterion = torch.nn.CrossEntropyLoss() # metric_logger = misc.MetricLogger(delimiter=" ") # header = 'Test:' # # switch to evaluation mode # model.eval() # all_predictions = [] # all_labels = [] # for batch in metric_logger.log_every(val_loader, 10, header): # images = batch[0] # target = batch[-1] # images = images.to(device, non_blocking=True) # target = target.to(device, non_blocking=True) # # compute output # with torch.cuda.amp.autocast(): # output = model(images) # loss = criterion(output, target)# # pred = output.argmax(dim=1) # all_predictions.append(pred.cpu().numpy())# ADDED # all_labels.append(target.cpu().numpy())# ADDED # acc1, acc5 = accuracy(output, target, topk=(1, 5)) # batch_size = images.shape[0] # metric_logger.update(loss=loss.item()) # metric_logger.meters['acc1'].update(acc1.item(), n=batch_size) # metric_logger.meters['acc5'].update(acc5.item(), n=batch_size) # all_predictions = np.array(all_predictions)#.squeeze(0) # all_labels = np.array(all_labels)#.squeeze(0) # if type_label is None: # type_label = unique_classes # # Create a 4x4 grid for visualization # num_rows = 4 # num_cols = 4 # plt.figure(figsize=(12, 12)) # for i in range(num_rows * num_cols): # plt.subplot(num_rows, num_cols, i + 1) # idx = np.random.randint(len(all_labels)) # import pdb;pdb.set_trace() # plt.imshow(images[idx].cpu().numpy().squeeze(), cmap='gray') # # Use the class names instead of numeric labels for Fashion MNIST # if dataset_type == 1: # class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # predicted_class = class_names[all_predictions[idx]] # actual_class = class_names[all_labels[idx]] # else: # predicted_class = all_predictions[idx] # actual_class = all_labels[idx] # plt.title(f'Pred: {predicted_class}\nActual: {actual_class}') # plt.axis('off') # plt.tight_layout() # plt.show() # visualize_predictions(model, data_loader_val, device, dataset_type=2, unique_classes=unique_classes) unique_classes report = classification_report(all_labels, all_predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(EXPERIMENT_NAME, "confusion_matrix.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(all_labels, all_predictions, average='micro') recall = recall_score(all_labels, all_predictions, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((all_labels != 1) & (all_predictions != 1)) fp = np.sum((all_labels != 1) & (all_predictions == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(all_labels, all_predictions, average='weighted') evaluation_metrics = { "Acc1": metrics['acc1'], # Add acc1 metric "Acc5": metrics['acc5'], # Add acc5 metric "loss": metrics['loss'], # Add acc5 metric "F1 Score": [f1], "Precision": [precision], "Recall": [recall], "Specificity": [specificity] } evaluation_metrics # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics) # Save the DataFrame to a CSV file df.to_csv(f'{EXPERIMENT_NAME}/evaluation_metrics_for_table.csv', index=False)
https://github.com/sebasmos/QuantumVE
sebasmos
import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') # define the utils imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def run_one_image(img, model): x = torch.tensor(img) # make it a batch-like x = x.unsqueeze(dim=0) x = torch.einsum('nhwc->nchw', x) # run MAE loss, y, mask = model(x.float(), mask_ratio=0.75) y = model.unpatchify(y) y = torch.einsum('nchw->nhwc', y).detach().cpu() # visualize the mask mask = mask.detach() mask = mask.unsqueeze(-1).repeat(1, 1, model.patch_embed.patch_size[0]**2 *3) # (N, H*W, p*p*3) mask = model.unpatchify(mask) # 1 is removing, 0 is keeping mask = torch.einsum('nchw->nhwc', mask).detach().cpu() x = torch.einsum('nchw->nhwc', x) # masked image im_masked = x * (1 - mask) # MAE reconstruction pasted with visible patches im_paste = x * (1 - mask) + y * mask # make the plt figure larger plt.rcParams['figure.figsize'] = [24, 24] plt.subplot(1, 4, 1) show_image(x[0], "original") plt.subplot(1, 4, 2) show_image(im_masked[0], "masked") plt.subplot(1, 4, 3) show_image(y[0], "reconstruction") plt.subplot(1, 4, 4) show_image(im_paste[0], "reconstruction + visible") plt.show() # load an image # img_url = 'https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg' # fox, from ILSVRC2012_val_00046145 # img_url = 'https://user-images.githubusercontent.com/11435359/147743081-0428eecf-89e5-4e07-8da5-a30fd73cc0ba.jpg' # cucumber, from ILSVRC2012_val_00047851 img_path = "/media/enc/vera1/sebastian/data/Data-set-Urban_Esc/test/BI/4-172143-A-13.png" # img = Image.open(requests.get(img_url, stream=True).raw) img = Image.open(img_path) print(img.mode) # If the image has an alpha channel, you can convert it to RGB if img.mode == 'RGBA': # Convert the image to RGB mode (remove alpha channel) img = img.convert('RGB') img = img.resize((224, 224)) img = np.array(img) / 255. assert img.shape == (224, 224, 3) # normalize by ImageNet mean and std img = img - imagenet_mean img = img / imagenet_std plt.rcParams['figure.figsize'] = [5, 5] show_image(torch.tensor(img)) # This is an MAE model trained with pixels as targets for visualization (ViT-Large, training mask ratio=0.75) # download checkpoint if not exist #!wget -nc https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_large.pth # !pip install numpy --upgrade chkpt_dir = 'mae_visualize_vit_large.pth' model_mae = prepare_model(chkpt_dir, 'mae_vit_large_patch16') print('Model loaded.') # make random mask reproducible (comment out to make it change) torch.manual_seed(2) print('MAE with pixel reconstruction:') run_one_image(img, model_mae) # This is an MAE model trained with an extra GAN loss for more realistic generation (ViT-Large, training mask ratio=0.75) # download checkpoint if not exist !wget -nc https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_large_ganloss.pth chkpt_dir = 'mae_visualize_vit_large_ganloss.pth' model_mae_gan = prepare_model('mae_visualize_vit_large_ganloss.pth', 'mae_vit_large_patch16') print('Model loaded.') # make random mask reproducible (comment out to make it change) torch.manual_seed(2) print('MAE with extra GAN loss:') run_one_image(img, model_mae_gan) chkpt_dir = './EXP_mae_vit_base_patch16/checkpoint-99.pth' model_mae_gan = prepare_model(chkpt_dir, 'mae_vit_base_patch16') print('Model loaded.') # make random mask reproducible (comment out to make it change) torch.manual_seed(2) print('MAE with extra GAN loss:') run_one_image(img, model_mae_gan) # mae_base = models_mae.mae_vit_base_patch16() mae_base = prepare_model(chkpt_dir, 'mae_vit_base_patch16') print('MAE with extra GAN loss:') run_one_image(img, model_mae_gan) # t = np.transpose(img, (2,1,0)).astype(np.uint8) t.shape, t.dtype img_with_extra_dim = np.expand_dims(img, axis=0) img_with_extra_dim.shape
https://github.com/sebasmos/QuantumVE
sebasmos
import os MODEL_METADATA = "SVM" model_name = "efficientnet_b3_embeddings_finetuning" EXPERIMENT_NAME = "efficientnet_b3_embeddings_"#"efficientnet_v2_m"#"convnext_base"#"efficientnet_b3"#"mobileNet" results_path = f"{model_name}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) train_path = f"{model_name}/train" val_path = f"{model_name}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) import sys sys.path.insert(0,'../') # from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd import argparse import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter # import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image # import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim import torch.nn as nn import torch import PIL import pandas as pd import torch import numpy as np import pandas as pd from tqdm import tqdm import os import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score import numpy as np from torchvision import datasets, transforms from timm.data import create_transform # from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD IMAGENET_DEFAULT_MEAN = np.array([0.485, 0.456, 0.406]) IMAGENET_DEFAULT_STD = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * IMAGENET_DEFAULT_STD + IMAGENET_DEFAULT_MEAN) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def plot_multiclass_roc_curve(all_labels, all_predictions, results_path="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{results_path}/roc_curve.png') plt.show() def build_dataset(is_train, args): transform = build_transform(is_train, args) root = os.path.join(args.data_path, 'train' if is_train else 'val') dataset = datasets.ImageFolder(root, transform=transform) print(dataset) return dataset def build_transform(is_train, args): mean = IMAGENET_DEFAULT_MEAN std = IMAGENET_DEFAULT_STD # train transform if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation='bicubic', re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, mean=mean, std=std, ) return transform # eval transform t = [] if args.input_size <= 224: crop_pct = 224 / 256 else: crop_pct = 1.0 size = int(args.input_size / crop_pct) t.append( transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(mean, std)) return transforms.Compose(t) # Set the seed for PyTorch torch.manual_seed(42) from sklearn.svm import SVC # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training X_train = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels X_val = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels # Use los mejores parámetros encontrados best_params = {'C': 4, 'gamma': 'scale', 'kernel': 'rbf'}#{'C': 10, 'gamma': 'scale', 'kernel': 'rbf'} # Inicializa el clasificador SVM con los mejores parámetros svm_classifier = SVC(**best_params, random_state=42) svm_classifier.fit(X_train, y_train) # Predict on validation data y_pred = svm_classifier.predict(X_val) # Calculate accuracy accuracy = accuracy_score(y_val, y_pred) # Calculate precision precision = precision_score(y_val, y_pred, average='weighted') # Calculate recall recall = recall_score(y_val, y_pred, average='weighted') # Calculate F1 score f1 = f1_score(y_val, y_pred, average='weighted') # Calculate F0.75 score fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') print("Validation Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("F0.75 Score:", fbeta_75) X_train.shape unique_classes = np.unique(np.concatenate(((y_pred, y_val)))) confusion_mat = confusion_matrix(y_pred, y_val, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() plot_multiclass_roc_curve(y_pred, y_val, results_path) report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(y_val, y_pred, average='micro') recall = recall_score(y_val, y_pred, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((y_val != 1) & (y_pred != 1)) fp = np.sum((y_val != 1) & (y_pred == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') evaluation_metrics = { "Accuracy": accuracy, "F1 Score": f1, "F0.75 Score": fbeta_75, "Precision": precision, "Recall": recall, "Specificity": specificity } print("Evaluation Metrics:") # for metric, value in evaluation_metrics.items(): # print(f"{metric}: {value}") # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics, index=[0]) # # Save the DataFrame to a CSV file df.to_csv(f'{results_path}/evaluation_metrics_for_table_{MODEL_METADATA}.csv', index=False) df from sklearn.svm import SVC # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training X_train = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels X_val = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels start = 0.1 end = 100.0 step = 0.1 # Initialize variables to track best F0.75 score and its corresponding C value best_fbeta_75 = -1 best_c_val = None for c_val in np.arange(start, end + step, step): # Use los mejores parámetros encontrados best_params = {'C': c_val, 'gamma': 'scale', 'kernel': 'rbf'}#{'C': 10, 'gamma': 'scale', 'kernel': 'rbf'} # Inicializa el clasificador SVM con los mejores parámetros svm_classifier = SVC(**best_params, random_state=42) svm_classifier.fit(X_train, y_train) # Predict on validation data y_pred = svm_classifier.predict(X_val) # Calculate accuracy accuracy = accuracy_score(y_val, y_pred) # Calculate precision precision = precision_score(y_val, y_pred, average='weighted') # Calculate recall recall = recall_score(y_val, y_pred, average='weighted') # Calculate F1 score f1 = f1_score(y_val, y_pred, average='weighted') # Calculate F0.75 score fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') # Update best F0.75 score and corresponding C value if a higher score is found if fbeta_75 > best_fbeta_75: best_fbeta_75 = fbeta_75 best_c_val = c_val print(f"value of c: {c_val} ".center(60,"-")) print("Validation Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("F0.75 Score:", fbeta_75) # Print the parameter C that obtains the highest F0.75 score print("Best C value:", best_c_val) print("Best F0.75 Score:", best_fbeta_75) from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC # Define el rango de parámetros que deseas buscar param_grid = { 'C': [0.1,1,10,100], 'gamma': [0.1, 0.01, 0.001, 0.0001], 'kernel': ['rbf'] } # Crea un clasificador SVM svm_classifier = SVC(random_state=42) # Crea un objeto GridSearchCV grid_search = GridSearchCV(estimator=svm_classifier, param_grid=param_grid, cv=10, scoring='accuracy') # Ajusta el modelo GridSearchCV a los datos de entrenamiento grid_search.fit(X_train, y_train) # Obtiene los mejores parámetros y el mejor puntaje best_params = grid_search.best_params_ best_score = grid_search.best_score_ print("Mejores parámetros:", best_params) print("Mejor puntaje:", best_score) # Usa el mejor estimador encontrado por GridSearchCV best_svm_classifier = grid_search.best_estimator_ # Predice sobre los datos de validación usando el mejor modelo y_pred = best_svm_classifier.predict(X_val) # Calcula las métricas de evaluación accuracy = accuracy_score(y_val, y_pred) precision = precision_score(y_val, y_pred, average='weighted') recall = recall_score(y_val, y_pred, average='weighted') f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') print("Exactitud de la validación:", accuracy) print("Precisión:", precision) print("Recall:", recall) print("Puntuación F1:", f1) print("Puntuación F0.75:", fbeta_75)
https://github.com/sebasmos/QuantumVE
sebasmos
# Define the model name model_name = "efficientnet_b3" #EfficientNet_B7_Weights.IMAGENET1K_V1 feat_space = 8 !pwd %cd qubico !pwd import torchvision.models as models import torch MODEL_CONSTRUCTORS = { 'alexnet': models.alexnet, 'convnext_base': models.convnext_base, 'convnext_large': models.convnext_large, 'convnext_small': models.convnext_small, 'convnext_tiny': models.convnext_tiny, 'densenet121': models.densenet121, 'densenet161': models.densenet161, 'densenet169': models.densenet169, 'densenet201': models.densenet201, 'efficientnet_b0': models.efficientnet_b0, 'efficientnet_b1': models.efficientnet_b1, 'efficientnet_b2': models.efficientnet_b2, 'efficientnet_b3': models.efficientnet_b3, 'efficientnet_b4': models.efficientnet_b4, 'efficientnet_b5': models.efficientnet_b5, 'efficientnet_b6': models.efficientnet_b6, 'efficientnet_b7': models.efficientnet_b7, 'efficientnet_v2_l': models.efficientnet_v2_l, 'efficientnet_v2_m': models.efficientnet_v2_m, 'efficientnet_v2_s': models.efficientnet_v2_s, 'googlenet': models.googlenet, 'inception_v3': models.inception_v3, 'maxvit_t': models.maxvit_t, 'mnasnet0_5': models.mnasnet0_5, 'mnasnet0_75': models.mnasnet0_75, 'mnasnet1_0': models.mnasnet1_0, 'mnasnet1_3': models.mnasnet1_3, 'mobilenet_v2': models.mobilenet_v2, 'mobilenet_v3_large': models.mobilenet_v3_large, 'mobilenet_v3_small': models.mobilenet_v3_small, 'regnet_x_16gf': models.regnet_x_16gf, 'regnet_x_1_6gf': models.regnet_x_1_6gf, 'regnet_x_32gf': models.regnet_x_32gf, 'regnet_x_3_2gf': models.regnet_x_3_2gf, 'regnet_x_400mf': models.regnet_x_400mf, 'regnet_x_800mf': models.regnet_x_800mf, 'regnet_x_8gf': models.regnet_x_8gf, 'regnet_y_128gf': models.regnet_y_128gf,# check this regnet_y_128gf: no weigthts avaialble 'regnet_y_16gf': models.regnet_y_16gf, 'regnet_y_1_6gf': models.regnet_y_1_6gf, 'regnet_y_32gf': models.regnet_y_32gf, 'regnet_y_3_2gf': models.regnet_y_3_2gf, 'regnet_y_400mf': models.regnet_y_400mf, 'regnet_y_800mf': models.regnet_y_800mf, 'regnet_y_8gf': models.regnet_y_8gf, 'resnet101': models.resnet101, 'resnet152': models.resnet152, 'resnet18': models.resnet18, 'resnet34': models.resnet34, 'resnet50': models.resnet50, 'resnext101_32x8d': models.resnext101_32x8d, 'resnext101_64x4d': models.resnext101_64x4d, 'resnext50_32x4d': models.resnext50_32x4d, 'shufflenet_v2_x0_5': models.shufflenet_v2_x0_5, 'shufflenet_v2_x1_0': models.shufflenet_v2_x1_0, 'shufflenet_v2_x1_5': models.shufflenet_v2_x1_5, 'shufflenet_v2_x2_0': models.shufflenet_v2_x2_0, 'squeezenet1_0': models.squeezenet1_0, 'squeezenet1_1': models.squeezenet1_1, 'swin_b': models.swin_b, 'swin_s': models.swin_s, 'swin_t': models.swin_t, 'swin_v2_b': models.swin_v2_b, 'swin_v2_s': models.swin_v2_s, 'swin_v2_t': models.swin_v2_t, 'vgg11': models.vgg11, 'vgg11_bn': models.vgg11_bn, 'vgg13': models.vgg13, 'vgg13_bn': models.vgg13_bn, 'vgg16': models.vgg16, 'vgg16_bn': models.vgg16_bn, 'vgg19': models.vgg19, 'vgg19_bn': models.vgg19_bn, 'vit_b_16': models.vit_b_16, 'vit_b_32': models.vit_b_32, 'vit_h_14': models.vit_h_14,# and this..no weigthts avaialble 'vit_l_16': models.vit_l_16, 'vit_l_32': models.vit_l_32, 'wide_resnet101_2': models.wide_resnet101_2, 'wide_resnet50_2': models.wide_resnet50_2 } # Create experiment directory EXPERIMENT_NAME = f"{model_name}_embeddings" import os os.makedirs(EXPERIMENT_NAME, exist_ok=True) train_path = f"{EXPERIMENT_NAME}/train" val_path = f"{EXPERIMENT_NAME}/val" os.makedirs(train_path, exist_ok=True) os.makedirs(val_path, exist_ok=True) import sys sys.path.insert(0,'../') from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim import torchvision.models as models import torch.nn as nn import torch import pandas as pd import torch import numpy as np import pandas as pd from tqdm import tqdm import os import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score import numpy as np imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Set the seed for PyTorch torch.manual_seed(42) parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=64, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=50, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='mobilenet_v3', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/ABGQI_mel_spectrograms', type=str, help='dataset path') parser.add_argument('--nb_classes', default=5, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='quinn_5_classes', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='/media/enc/vera1/sebastian/codes/classifiers/mae/MobileNet/output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default="/media/enc/vera1/sebastian/codes/classifiers/mae/MobileNet/quinn_5_classes/checkpoint-49.pth", help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) os.makedirs(args.output_dir, exist_ok=True) device = torch.device(args.device) misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train = build_dataset(is_train=True, args=args) dataset_val = build_dataset(is_train=False, args=args) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) def count_parameters(model, message=""): trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) total_params = sum(p.numel() for p in model.parameters()) print(f"{message} Trainable params: {trainable_params} of {total_params}") def extract_embeddings(model, data_loader, save_path, device, preprocess=None): embeddings_list = [] targets_list = [] total_batches = len(data_loader) with torch.no_grad(), tqdm(total=total_batches) as pbar: model.eval() # Set the model to evaluation mode for images, targets in data_loader: if preprocess: print("required processing") images = preprocess(images).squeeze() images = images.to(device) # print("image shape is: ", images.shape) embeddings = model(images) embeddings_list.append(embeddings.cpu().detach().numpy()) # Move to CPU and convert to NumPy targets_list.append(targets.numpy()) # Convert targets to NumPy pbar.update(1) # Concatenate embeddings and targets from all batches embeddings = np.concatenate(embeddings_list).squeeze() targets = np.concatenate(targets_list) num_embeddings = embeddings.shape[1] column_names = [f"feat_{i}" for i in range(num_embeddings)] column_names.append("label") embeddings_with_targets = np.hstack((embeddings, np.expand_dims(targets, axis=1))) # Create a DataFrame with column names df = pd.DataFrame(embeddings_with_targets, columns=column_names) df.to_csv(save_path, index=False) model_names = sorted(name for name in models.__dict__ if name.islower() and not name.startswith("__") and not name.startswith('get_') and not name.startswith('list_') and callable(models.__dict__[name])) model_names # Load the model if model_name in MODEL_CONSTRUCTORS: model_constructor = MODEL_CONSTRUCTORS[model_name] if model_name == "vit_h_14": from torchvision.io import read_image from torchvision.models import vit_h_14, ViT_H_14_Weights # Step 1: Initialize model with the best available weights weights = ViT_H_14_Weights.IMAGENET1K_SWAG_E2E_V1.DEFAULT model = vit_h_14(weights=weights) model = torch.nn.Sequential(*(list(model.children())[:-1])) # Step 2: Initialize the inference transforms preprocess = weights.transforms() if model_name =="regnet_y_128gf": from torchvision.io import read_image from torchvision.models import regnet_y_128gf, RegNet_Y_128GF_Weights # Step 1: Initialize model with the best available weights weights = RegNet_Y_128GF_Weights.IMAGENET1K_SWAG_E2E_V1 model = regnet_y_128gf(weights=weights) model = torch.nn.Sequential(*(list(model.children())[:-1])) # Step 2: Initialize the inference transforms preprocess = weights.transforms() if model_name =="mobilenet_v3_large": from torchvision.io import read_image from torchvision.models import mobilenet_v3_large, MobileNet_V3_Large_Weights # Step 1: Initialize model with the best available weights weights = MobileNet_V3_Large_Weights.IMAGENET1K_V2 model = mobilenet_v3_large(weights=weights) model = torch.nn.Sequential(*(list(model.children())[:-1])) # Step 2: Initialize the inference transforms preprocess = weights.transforms() else: model = model_constructor(pretrained=True, progress=True) model.classifier[1].in_features = model.classifier[1].in_features model.classifier[1] = nn.Linear(model.classifier[1].in_features, out_features=feat_space) preprocess=None else: raise ValueError("Invalid model type specified.") model model.eval() model.to(device) # Extract embeddings for training data extract_embeddings(model, data_loader_train, f'{train_path}/train_embeddings.csv', device, preprocess) # Extract embeddings for validation data extract_embeddings(model, data_loader_val, f'{val_path}/val_embeddings.csv', device, preprocess)
https://github.com/sebasmos/QuantumVE
sebasmos
# !pip install qiskit torch torchvision matplotlib # !pip install qiskit-machine-learning # !pip install torchviz # !pip install qiskit[all] # !pip install qiskit == 0.45.2 # !pip install qiskit_algorithms == 0.7.1 # !pip install qiskit-ibm-runtime == 0.17.0 # !pip install qiskit-aer == 0.13.2 # #Quentum net draw # !pip install pylatexenc import os MODEL_METADATA = "SVM" model_name = "efficientnet_b3_embeddings_feat_space_16"#"efficientnet_v2_m"#"convnext_base"#"efficientnet_b3"#"mobileNet" results_path = f"{model_name}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) train_path = f"{model_name}/train" val_path = f"{model_name}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) from qiskit_algorithms.utils import algorithm_globals import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from qiskit.circuit.library import ZZFeatureMap from qiskit.primitives import Sampler from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit_machine_learning.kernels import FidelityQuantumKernel from sklearn.metrics import confusion_matrix, classification_report algorithm_globals.random_seed = 12345 train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training train_features = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels test_features = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels plt.figure(figsize=(18, 5)) ax = sns.countplot(x=y_train, palette='tab10') total = len(y_train) for p in ax.patches: percentage = f'{100 * p.get_height() / total:.1f}%\n' x = p.get_x() + p.get_width() / 2 y = p.get_height() ax.annotate(percentage, (x, y), ha='center', va='center') plt.show() adhoc_dimension = 16 """ class 0 : {0,2} class 1 : {1,3} """ label_map = {0: 0, 1: 1, 2: 0, 3: 1, 4: 0} # Merge labels using the dictionary Y_train = np.array([label_map[label] for label in y_train]) y_test = np.array([label_map[label] for label in y_val]) print("labels_train:", np.unique(Y_train)) print("test_labels:", np.unique(y_test)) plt.figure(figsize=(18, 5)) ax = sns.countplot(x=Y_train, palette='tab10') total = len(Y_train) for p in ax.patches: percentage = f'{100 * p.get_height() / total:.1f}%\n' x = p.get_x() + p.get_width() / 2 y = p.get_height() ax.annotate(percentage, (x, y), ha='center', va='center') plt.show() print(train_features.shape, Y_train.shape) print(test_features.shape, y_test.shape) adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear") sampler = Sampler() fidelity = ComputeUncompute(sampler=sampler) adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map) train_features.shape print(train_features.shape, Y_train.shape) print(test_features.shape, y_test.shape) # train_features = train_features[:100] # test_features = test_features[:20] # Y_train = Y_train[:100] # y_test = y_test[:20] train_features.shape, test_features.shape, Y_train.shape, y_test.shape import time from sklearn.metrics import accuracy_score, precision_score, f1_score, recall_score, fbeta_score from sklearn.svm import SVC # Start timer for training start_train = time.time() adhoc_svc = SVC(kernel=adhoc_kernel.evaluate) adhoc_svc.fit(train_features, Y_train) # End timer for training end_train = time.time() # Start timer for inference start_inference = time.time() predictions = adhoc_svc.predict(test_features) # End timer for inference end_inference = time.time() accuracy = accuracy_score(y_test, predictions) precision = precision_score(y_test, predictions, average='weighted') f1 = f1_score(y_test, predictions, average='weighted') recall = recall_score(y_test, predictions, average='weighted') fbeta_75 = fbeta_score(y_test, predictions, beta=0.75, average='weighted') # Print metrics and time print(f"Accuracy: {accuracy} Precision: {precision} F1 Score: {f1} Recall: {recall} F0.75 Score: {fbeta_75}") print(f"Training time: {end_train - start_train} seconds") print(f"Inference time: {end_inference - start_inference} seconds") unique_classes = np.unique(np.concatenate(((predictions, y_test)))) confusion_mat = confusion_matrix(predictions, y_test, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() report = classification_report(y_test,predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df)
https://github.com/sebasmos/QuantumVE
sebasmos
# !pip install qiskit torch torchvision matplotlib # !pip install qiskit-machine-learning # !pip install torchviz # !pip install qiskit[all] # !pip install qiskit == 0.45.2 # !pip install qiskit_algorithms == 0.7.1 # !pip install qiskit-ibm-runtime == 0.17.0 # !pip install qiskit-aer == 0.13.2 # #Quentum net draw # !pip install pylatexenc import os MODEL_METADATA = "SVM" model_name = "efficientnet_b3_embeddings_feat_space_16"#"efficientnet_v2_m"#"convnext_base"#"efficientnet_b3"#"mobileNet" results_path = f"{model_name}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) train_path = f"{model_name}/train" val_path = f"{model_name}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) from qiskit_algorithms.utils import algorithm_globals import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from qiskit.circuit.library import ZZFeatureMap from qiskit.primitives import Sampler from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit_machine_learning.kernels import FidelityQuantumKernel from sklearn.metrics import confusion_matrix, classification_report algorithm_globals.random_seed = 12345 train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training train_features = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels test_features = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels plt.figure(figsize=(18, 5)) ax = sns.countplot(x=y_train, palette='tab10') total = len(y_train) for p in ax.patches: percentage = f'{100 * p.get_height() / total:.1f}%\n' x = p.get_x() + p.get_width() / 2 y = p.get_height() ax.annotate(percentage, (x, y), ha='center', va='center') plt.show() adhoc_dimension = 16 """ class 0 : {0,2} class 1 : {1,3} """ label_map = {0: 0, 1: 1, 2: 0, 3: 1, 4: 0} # Merge labels using the dictionary Y_train = np.array([label_map[label] for label in y_train]) y_test = np.array([label_map[label] for label in y_val]) print("labels_train:", np.unique(Y_train)) print("test_labels:", np.unique(y_test)) plt.figure(figsize=(18, 5)) ax = sns.countplot(x=Y_train, palette='tab10') total = len(Y_train) for p in ax.patches: percentage = f'{100 * p.get_height() / total:.1f}%\n' x = p.get_x() + p.get_width() / 2 y = p.get_height() ax.annotate(percentage, (x, y), ha='center', va='center') plt.show() print(train_features.shape, Y_train.shape) print(test_features.shape, y_test.shape) adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear") sampler = Sampler() fidelity = ComputeUncompute(sampler=sampler) adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map) train_features.shape print(train_features.shape, Y_train.shape) print(test_features.shape, y_test.shape) train_features = train_features[:100] test_features = test_features[:20] Y_train = Y_train[:100] y_test = y_test[:20] train_features.shape, test_features.shape, Y_train.shape, y_test.shape import time from sklearn.metrics import accuracy_score, precision_score, f1_score, recall_score, fbeta_score from sklearn.svm import SVC # Start timer for training start_train = time.time() adhoc_svc = SVC(kernel=adhoc_kernel.evaluate) adhoc_svc.fit(train_features, Y_train) # End timer for training end_train = time.time() # Start timer for inference start_inference = time.time() predictions = adhoc_svc.predict(test_features) # End timer for inference end_inference = time.time() accuracy = accuracy_score(y_test, predictions) precision = precision_score(y_test, predictions, average='weighted') f1 = f1_score(y_test, predictions, average='weighted') recall = recall_score(y_test, predictions, average='weighted') fbeta_75 = fbeta_score(y_test, predictions, beta=0.75, average='weighted') # Print metrics and time print(f"Accuracy: {accuracy} Precision: {precision} F1 Score: {f1} Recall: {recall} F0.75 Score: {fbeta_75}") print(f"Training time: {end_train - start_train} seconds") print(f"Inference time: {end_inference - start_inference} seconds") unique_classes = np.unique(np.concatenate(((predictions, y_test)))) confusion_mat = confusion_matrix(predictions, y_test, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() report = classification_report(y_test,predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df)
https://github.com/sebasmos/QuantumVE
sebasmos
# !pip install qiskit torch torchvision matplotlib # !pip install qiskit-machine-learning # !pip install torchviz # !pip install qiskit[all] # !pip install qiskit == 0.45.2 # !pip install qiskit_algorithms == 0.7.1 # !pip install qiskit-ibm-runtime == 0.17.0 # !pip install qiskit-aer == 0.13.2 # #Quentum net draw # !pip install pylatexenc import os MODEL_METADATA = "SVM" model_name = "efficientnet_b3_embeddings_feat_space_2"#"efficientnet_v2_m"#"convnext_base"#"efficientnet_b3"#"mobileNet" results_path = f"{model_name}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) train_path = f"{model_name}/train" val_path = f"{model_name}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) from qiskit_algorithms.utils import algorithm_globals import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from qiskit.circuit.library import ZZFeatureMap from qiskit.primitives import Sampler from qiskit_algorithms.state_fidelities import ComputeUncompute from qiskit_machine_learning.kernels import FidelityQuantumKernel from sklearn.metrics import confusion_matrix, classification_report algorithm_globals.random_seed = 12345 train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training train_features = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels test_features = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels plt.figure(figsize=(18, 5)) ax = sns.countplot(x=y_train, palette='tab10') total = len(y_train) for p in ax.patches: percentage = f'{100 * p.get_height() / total:.1f}%\n' x = p.get_x() + p.get_width() / 2 y = p.get_height() ax.annotate(percentage, (x, y), ha='center', va='center') plt.show() train_labels adhoc_dimension = 2 """ class 0 : {0,2} class 1 : {1,3} """ label_map = {0: 0, 1: 1, 2: 0, 3: 1, 4: 0} # Merge labels using the dictionary labels_train = np.array([label_map[label] for label in y_train]) test_labels = np.array([label_map[label] for label in y_val]) print(f"training".center(60,"-")) print("Original labels:", np.unique(y_train)) print("Merged labels:", np.unique(merged_labels)) print(f"testing".center(60,"-")) print("Original labels:", np.unique(train_labels)) print("Merged labels:", np.unique(y_val)) plt.figure(figsize=(18, 5)) ax = sns.countplot(x=labels_train, palette='tab10') total = len(labels_train) for p in ax.patches: percentage = f'{100 * p.get_height() / total:.1f}%\n' x = p.get_x() + p.get_width() / 2 y = p.get_height() ax.annotate(percentage, (x, y), ha='center', va='center') plt.show() train_labels print(train_features.shape, labels_train.shape) print(test_features.shape, test_labels.shape) adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear") sampler = Sampler() fidelity = ComputeUncompute(sampler=sampler) adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map) train_features.shape # feat_2_train = train_features[:,:2] # feat_2_test = test_features[:,:2] feat_2_train.shape, feat_2_test.shape, labels_train.shape, test_labels.shape train_labels # feat_2_train = feat_2_train[:500] # feat_2_test = feat_2_test[:50] # labels_train = labels_train[:500] # test_labels = test_labels[:50] feat_2_train.shape, feat_2_test.shape, labels_train.shape, test_labels.shape import time from sklearn.metrics import accuracy_score, precision_score, f1_score, recall_score, fbeta_score from sklearn.svm import SVC # Start timer for training start_train = time.time() adhoc_svc = SVC(kernel=adhoc_kernel.evaluate) adhoc_svc.fit(feat_2_train, labels_train) # End timer for training end_train = time.time() # Start timer for inference start_inference = time.time() predictions = adhoc_svc.predict(feat_2_test) # End timer for inference end_inference = time.time() accuracy = accuracy_score(test_labels, predictions) precision = precision_score(test_labels, predictions, average='weighted') f1 = f1_score(test_labels, predictions, average='weighted') recall = recall_score(test_labels, predictions, average='weighted') fbeta_75 = fbeta_score(test_labels, predictions, beta=0.75, average='weighted') # Print metrics and time print(f"Accuracy: {accuracy} Precision: {precision} F1 Score: {f1} Recall: {recall} F0.75 Score: {fbeta_75}") print(f"Training time: {end_train - start_train} seconds") print(f"Inference time: {end_inference - start_inference} seconds") y_pred = predictions y_val = test_labels unique_classes = np.unique(np.concatenate(((y_pred, y_val)))) confusion_mat = confusion_matrix(y_pred, y_val, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df)
https://github.com/sebasmos/QuantumVE
sebasmos
import sys sys.path.insert(0,'../') # from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd import argparse import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter # import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image # import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim import torch.nn as nn import torch import PIL import pandas as pd import torch import numpy as np import pandas as pd from tqdm import tqdm import os import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score import numpy as np from torchvision import datasets, transforms from timm.data import create_transform # from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD IMAGENET_DEFAULT_MEAN = np.array([0.485, 0.456, 0.406]) IMAGENET_DEFAULT_STD = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * IMAGENET_DEFAULT_STD + IMAGENET_DEFAULT_MEAN) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() def build_dataset(is_train, args): transform = build_transform(is_train, args) root = os.path.join(args.data_path, 'train' if is_train else 'val') dataset = datasets.ImageFolder(root, transform=transform) print(dataset) return dataset def build_transform(is_train, args): mean = IMAGENET_DEFAULT_MEAN std = IMAGENET_DEFAULT_STD # train transform if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation='bicubic', re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, mean=mean, std=std, ) return transform # eval transform t = [] if args.input_size <= 224: crop_pct = 224 / 256 else: crop_pct = 1.0 size = int(args.input_size / crop_pct) t.append( transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(mean, std)) return transforms.Compose(t) # Set the seed for PyTorch torch.manual_seed(42) # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') # Split the data into training and validation sets (80/20 split) X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.15, random_state=42) X_test = val_embeddings.iloc[:, :-1].values # Features y_test = val_embeddings.iloc[:, -1].values # Labels print(X_train.shape, y_train.shape) print(X_val.shape, y_val.shape) print(X_test.shape, y_test.shape) print("GridSearch over a list of neighbors: {0}".format(l_k)) _ = knn_gscv.fit(x, y) from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import GridSearchCV, cross_val_score, StratifiedKFold # we use stratified folds from sklearn.pipeline import Pipeline n_folds = 10 skf = StratifiedKFold(n_folds, shuffle=True) mlp_classifier = Pipeline(steps=[('std_sc', StandardScaler()), ('mlpc', MLPClassifier(solver='adam', activation='relu', tol=1.e-4, max_iter=1000, warm_start=False, shuffle=True))]) l_hidden_layer_sizes = [(20,), (20, 20)] l_alpha = [10.**k for k in range(-6, 4)] param_grid = {'mlpc__alpha': l_alpha, 'mlpc__hidden_layer_sizes': l_hidden_layer_sizes} mlpc_gscv = GridSearchCV(mlp_classifier, param_grid=param_grid, cv=skf, scoring='accuracy', return_train_score=True, n_jobs=-1, verbose=1) t_0 = time.time() _ = mlpc_gscv.fit(X_train, y_train) t_1 = time.time() print("\nmlp_grid_search_time: {0:.2}f".format((t_1 - t_0)/60.)) import joblib # saving alpha_search in a pickle joblib.dump(mlpc_gscv, 'mlp_classifier_gscv.joblib') df_cv_estimator = pd.DataFrame.from_dict(mlpc_gscv.cv_results_) display(df_cv_estimator[["param_mlpc__alpha", "param_mlpc__hidden_layer_sizes", "mean_test_score"]].sort_values(by="mean_test_score", ascending=False).head()) mlpc_gscv = joblib.load('mlp_classifier_gscv.joblib') best_alpha = mlpc_gscv.best_params_['mlpc__alpha'] print("best alpha: %.6f\t" % best_alpha) print("alpha_min: %f\talpha_max: %f" % (np.array(l_alpha).min(), np.array(l_alpha).max())) best_hidden_layer_sizes = mlpc_gscv.best_params_['mlpc__hidden_layer_sizes'] print("best_hidden_layer_sizes", best_hidden_layer_sizes, "\nacc: %.3f" % mlpc_gscv.best_score_) idx_best_hidden_layer_sizes = [tup == best_hidden_layer_sizes for tup in df_cv_estimator['param_mlpc__hidden_layer_sizes'].values] idx_best_hidden_layer_sizes = np.array(idx_best_hidden_layer_sizes) plt.title("CV alpha vs accuracy") plt.xscale('log') plt.xlabel("alpha") plt.ylabel("cv_accuracy") _ = plt.plot( df_cv_estimator[idx_best_hidden_layer_sizes]['param_mlpc__alpha'], df_cv_estimator[idx_best_hidden_layer_sizes]['mean_test_score']) from sklearn.model_selection import cross_val_score, cross_val_predict, KFold, GridSearchCV ### CV accuracy, recall and precision of best model y_pred = cross_val_predict(mlpc_gscv.best_estimator_, X_train, y_train, cv=skf, n_jobs=2) acc = accuracy_score(y, y_pred) recall = recall_score(y, y_pred) prec = precision_score(y, y_pred) print("acc: %.3f\trecall: %.3f\tprecision: %.3f" % (acc, recall, prec)) print("\nconfusion matrix:\n", confusion_matrix(y, y_pred)) import pandas as pd from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier mlp_classifier = MLPClassifier(hidden_layer_sizes=(100,), activation='relu', solver='adam', alpha=0.0001, batch_size='auto', learning_rate='constant', learning_rate_init=0.001, max_iter=200, shuffle=True, random_state=42, verbose=True, early_stopping=True, validation_fraction=0.1, n_iter_no_change=20) # Increased dropout rate # mlp_classifier = MLPClassifier(random_state=1, max_iter=300) # Train the classifier mlp_classifier.fit(X_train, y_train) # Evaluate the classifier train_accuracy = accuracy_score(y_train, mlp_classifier.predict(X_train)) val_accuracy = accuracy_score(y_val, mlp_classifier.predict(X_val)) test_accuracy = accuracy_score(y_test, mlp_classifier.predict(X_test)) print(f"Training Accuracy: {train_accuracy}") print(f"Validation Accuracy: {val_accuracy}") print(f"Test Accuracy: {test_accuracy}") # Full predictions on test data y_pred = mlp_classifier.predict(X_test) import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from sklearn.metrics import accuracy_score epochs=1000 # Convert data to PyTorch tensors X_train_tensor = torch.tensor(X_train, dtype=torch.float32).cuda() y_train_tensor = torch.tensor(y_train, dtype=torch.long).cuda() X_val_tensor = torch.tensor(X_val, dtype=torch.float32).cuda() y_val_tensor = torch.tensor(y_val, dtype=torch.long).cuda() X_test_tensor = torch.tensor(X_test, dtype=torch.float32).cuda() # Create DataLoader for training and validation data train_dataset = TensorDataset(X_train_tensor, y_train_tensor) train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True) val_dataset = TensorDataset(X_val_tensor, y_val_tensor) val_loader = DataLoader(val_dataset, batch_size=64) class MLP(nn.Module): def __init__(self, dropout_rate=0.5): super(MLP, self).__init__() self.fc1 = nn.Linear(X_train.shape[1], 200) self.fc2 = nn.Linear(200, 100) self.fc3 = nn.Linear(100, len(np.unique(y_train))) self.dropout = nn.Dropout(dropout_rate) def forward(self, x): x = F.relu(self.fc1(x)) x = self.dropout(x) x = F.relu(self.fc2(x)) x = self.dropout(x) x = self.fc3(x) return x # Initialize MLP model and move to CUDA model = MLP(dropout_rate=0.5).cuda() # Define loss function and optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.001) # Adding L2 regularization # Training loop with early stopping best_val_accuracy = 0.0 best_model_state_dict = None patience = 10 for epoch in range(epochs): model.train() for inputs, labels in train_loader: optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # Evaluate on validation set model.eval() with torch.no_grad(): val_accuracy = 0.0 for inputs, labels in val_loader: outputs = model(inputs) val_accuracy += accuracy_score(labels.cpu(), torch.argmax(outputs, dim=1).cpu().numpy()) val_accuracy /= len(val_loader) if val_accuracy > best_val_accuracy: best_val_accuracy = val_accuracy best_model_state_dict = model.state_dict() patience = 10 # Reset patience if a new best validation accuracy is achieved else: patience -= 1 if patience == 0: break # Load the best model state dict if best_model_state_dict is not None: model.load_state_dict(best_model_state_dict) # Evaluate the best model on test set model.eval() with torch.no_grad(): y_test_pred = torch.argmax(model(X_test_tensor), dim=1).cpu().numpy() test_accuracy = accuracy_score(y_test, y_test_pred) print(f"Test Accuracy: {test_accuracy}") output_size = 5 # Example output size hidden_images = [64] # Example hidden layer sizes import torch import torch.nn as nn class SimpleClassifier(nn.Module): def __init__(self, input_size, output_size, hidden_sizes=[64], dropout_prob=0.2): super(SimpleClassifier, self).__init__() self.fc_layers = self._create_fc_layers(input_size, hidden_sizes, dropout_prob) self.output_layer = nn.Linear(hidden_sizes[-1], output_size) def _create_fc_layers(self, input_size, hidden_sizes, dropout_prob): layers = [] prev_size = input_size for hidden_size in hidden_sizes: layers.append(nn.Linear(prev_size, hidden_size)) layers.append(nn.ReLU()) layers.append(nn.Dropout(p=dropout_prob)) prev_size = hidden_size return nn.Sequential(*layers) def forward(self, x): x = self.fc_layers(x) x = self.output_layer(x) return x X_train_shape = X_train.shape input_size = X_train_shape[1] # Input size based on the feature dimension output_size = 5 # Example output size hidden_sizes = [64] # Example hidden layer sizes # Instantiate the model classifier_model = SimpleClassifier(input_size, output_size, hidden_sizes) # Forward pass output = classifier_model(X_train_tensor) print("Output shape:", output.shape) # Should be (7680, 5) classifier_model X_train_tensor = torch.tensor(X_train, dtype=torch.float32) y_train_tensor = torch.tensor(y_train, dtype=torch.long) y_train_np = y_train.astype(int) # Count occurrences of each class label class_counts = np.bincount(y_train_np, minlength=5) # Calculate class weights total_samples = len(y_train_np) num_classes = 5 class_weights = total_samples / (num_classes * class_counts) class_weights = torch.tensor(class_weights, dtype=torch.float32) class_weights # Move data and model to CUDA if available device = torch.device("cuda" if torch.cuda.is_available() else "cpu") X_train_tensor = X_train_tensor.to(device) y_train_tensor = y_train_tensor.to(device) class_weights = class_weights.to(device) classifier_model = SimpleClassifier(input_size, output_size, hidden_sizes) classifier_model = classifier_model.to(device) import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader, TensorDataset from sklearn.metrics import f1_score, precision_score, accuracy_score, recall_score, fbeta_score import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split # Define your SimpleClassifier class here (same as before) # Assuming you have X_train and y_train as your training data # Preprocess the data (scaling) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_val_scaled = scaler.transform(X_val) # Convert them to PyTorch tensors X_train_tensor = torch.tensor(X_train_scaled, dtype=torch.float32) y_train_tensor = torch.tensor(y_train, dtype=torch.long) X_val_tensor = torch.tensor(X_val_scaled, dtype=torch.float32) y_val_tensor = torch.tensor(y_val, dtype=torch.long) # Define batch size and create DataLoader batch_size = 64 train_dataset = TensorDataset(X_train_tensor, y_train_tensor) train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) # Instantiate the model classifier_model = SimpleClassifier(input_size=X_train.shape[1], output_size=output_size, hidden_sizes=hidden_sizes) classifier_model = classifier_model.to(device) # Define loss function criterion = nn.CrossEntropyLoss() # Define optimizer optimizer = optim.Adam(classifier_model.parameters(), lr=0.001) # Lists to store metrics for plotting train_loss_history = [] val_loss_history = [] f1_score_history = [] precision_history = [] accuracy_history = [] # Initialize patience counter patience = 50 # Adjust this value as needed # Initialize variable to track epochs since last improvement epochs_since_last_improvement = 0 # Training loop num_epochs = 10 best_val_loss = float('inf') for epoch in range(num_epochs): classifier_model.train() # Set the model to training mode total_train_loss = 0.0 for inputs, labels in train_loader: inputs, labels = inputs.to(device), labels.to(device) optimizer.zero_grad() # Zero the gradients outputs = classifier_model(inputs) # Forward pass loss = criterion(outputs, labels) # Calculate the loss total_train_loss += loss.item() * inputs.size(0) loss.backward() # Backward pass optimizer.step() # Update weights # Calculate average training loss for the epoch average_train_loss = total_train_loss / len(train_loader.dataset) train_loss_history.append(average_train_loss) # Evaluate on validation set classifier_model.eval() # Set the model to evaluation mode with torch.no_grad(): val_outputs = classifier_model(X_val_tensor.to(device)) val_loss = criterion(val_outputs, y_val_tensor.to(device)) val_loss_history.append(val_loss.item()) # Get predictions for validation data val_predictions = val_outputs.argmax(dim=1) y_val_np = y_val_tensor.cpu().numpy() val_predictions_np = val_predictions.cpu().numpy() # Calculate evaluation metrics f1 = f1_score(y_val_np, val_predictions_np, average='weighted') precision = precision_score(y_val_np, val_predictions_np, average='weighted') accuracy = accuracy_score(y_val_np, val_predictions_np) f1_score_history.append(f1) precision_history.append(precision) accuracy_history.append(accuracy) # Print average loss and evaluation metrics for the epoch print(f"Epoch [{epoch+1}/{num_epochs}], Train Loss: {average_train_loss:.4f}, " f"Val Loss: {val_loss.item():.4f}, F1 Score: {f1:.4f}, Precision: {precision:.4f}, " f"Accuracy: {accuracy:.4f}") # Check for early stopping if val_loss.item() < best_val_loss: best_val_loss = val_loss.item() epochs_since_last_improvement = 0 # Reset counter else: epochs_since_last_improvement += 1 if epochs_since_last_improvement >= patience: print("Early stopping at epoch:", epoch) break # Plot training and validation loss plt.plot(train_loss_history, label='Training Loss') plt.plot(val_loss_history, label='Validation Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.title('Training and Validation Loss') plt.legend() plt.show() # Plot evaluation metrics plt.plot(f1_score_history, label='F1 Score') plt.plot(precision_history, label='Precision') plt.plot(accuracy_history, label='Accuracy') plt.xlabel('Epoch') plt.ylabel('Score') plt.title('Evaluation Metrics') plt.legend() plt.show()
https://github.com/sebasmos/QuantumVE
sebasmos
import os MODEL_METADATA = "RF" model_name = "efficientnet_v2_m"#"efficientnet_b7"## "mobilenet_v3_large"#"convnext_base" EXPERIMENT_NAME = f"{model_name}_embeddings" results_path = f"{EXPERIMENT_NAME}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok = True) train_path = f"{EXPERIMENT_NAME}/train" val_path = f"{EXPERIMENT_NAME}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) import sys sys.path.insert(0,'../') # from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd import argparse import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter # import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image # import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim import torch.nn as nn import torch import PIL import pandas as pd import torch import numpy as np import pandas as pd from tqdm import tqdm import os import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score import numpy as np from torchvision import datasets, transforms from timm.data import create_transform # from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD IMAGENET_DEFAULT_MEAN = np.array([0.485, 0.456, 0.406]) IMAGENET_DEFAULT_STD = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * IMAGENET_DEFAULT_STD + IMAGENET_DEFAULT_MEAN) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def plot_multiclass_roc_curve(all_labels, all_predictions, results_path="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{results_path}/roc_curve.png') plt.show() def build_dataset(is_train, args): transform = build_transform(is_train, args) root = os.path.join(args.data_path, 'train' if is_train else 'val') dataset = datasets.ImageFolder(root, transform=transform) print(dataset) return dataset def build_transform(is_train, args): mean = IMAGENET_DEFAULT_MEAN std = IMAGENET_DEFAULT_STD # train transform if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation='bicubic', re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, mean=mean, std=std, ) return transform # eval transform t = [] if args.input_size <= 224: crop_pct = 224 / 256 else: crop_pct = 1.0 size = int(args.input_size / crop_pct) t.append( transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(mean, std)) return transforms.Compose(t) # Set the seed for PyTorch torch.manual_seed(42) # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training X_train = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels X_val = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels # Train a Random Forest Classifier # Use los mejores parámetros encontrados # best_params = {'max_depth': 80, 'min_samples_leaf': 4, 'min_samples_split': 10, 'n_estimators': 150} # Inicializa el clasificador SVM con los mejores parámetros rf_classifier = RandomForestClassifier(random_state=42) rf_classifier.fit(X_train, y_train) # Predict on validation data y_pred = rf_classifier.predict(X_val) # Calculate accuracy accuracy = accuracy_score(y_val, y_pred) # Calculate precision precision = precision_score(y_val, y_pred, average='weighted') # Calculate recall recall = recall_score(y_val, y_pred, average='weighted') # Calculate F1 score f1 = f1_score(y_val, y_pred, average='weighted') # Calculate F0.75 score fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') print("Validation Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("F0.75 Score:", fbeta_75) unique_classes = np.unique(np.concatenate(((y_pred, y_val)))) confusion_mat = confusion_matrix(y_pred, y_val, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() plot_multiclass_roc_curve(y_pred, y_val, results_path) report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(y_val, y_pred, average='micro') recall = recall_score(y_val, y_pred, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((y_val != 1) & (y_pred != 1)) fp = np.sum((y_val != 1) & (y_pred == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') evaluation_metrics = { "Accuracy": accuracy, "F1 Score": f1, "F0.75 Score": fbeta_75, "Precision": precision, "Recall": recall, "Specificity": specificity } print("Evaluation Metrics:") # for metric, value in evaluation_metrics.items(): # print(f"{metric}: {value}") # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics, index=[0]) # # Save the DataFrame to a CSV file df.to_csv(f'{results_path}/evaluation_metrics_for_table_{MODEL_METADATA}.csv', index=False) df results_path # from sklearn.model_selection import GridSearchCV # from sklearn.ensemble import RandomForestClassifier # from sklearn.preprocessing import StandardScaler # from sklearn.pipeline import Pipeline # from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score # # Define the parameter grid to search # param_grid = { # 'classifier__n_estimators': [50, 100, 150], # 'classifier__max_depth': [None, 10, 20], # 'classifier__min_samples_split': [2, 5, 10], # 'classifier__min_samples_leaf': [1, 2, 4] # } # # Create a pipeline with normalization and RandomForestClassifier # rf_pipeline = Pipeline([ # ('scaler', StandardScaler()), # ('classifier', RandomForestClassifier(random_state=42)) # ]) # # Create GridSearchCV # grid_search = GridSearchCV(estimator=rf_pipeline, param_grid=param_grid, cv=3, scoring='accuracy') # # Fit the grid search to the data # grid_search.fit(X_train, y_train) # # Get the best parameters and best score # best_params = grid_search.best_params_ # best_score = grid_search.best_score_ # print("Best Parameters:", best_params) # print("Best Score:", best_score) # # Use the best estimator found by GridSearchCV # best_rf_classifier = grid_search.best_estimator_ # # Predict on validation data using the best model # y_pred = best_rf_classifier.predict(X_val) # # Calculate metrics # accuracy = accuracy_score(y_val, y_pred) # precision = precision_score(y_val, y_pred, average='weighted') # recall = recall_score(y_val, y_pred, average='weighted') # f1 = f1_score(y_val, y_pred, average='weighted') # fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') # print("Validation Accuracy:", accuracy) # print("Precision:", precision) # print("Recall:", recall) # print("F1 Score:", f1) # print("F0.75 Score:", fbeta_75)
https://github.com/sebasmos/QuantumVE
sebasmos
import os MODEL_METADATA = "SVM" model_name = "efficientnet_b3_embeddings_finetuning" EXPERIMENT_NAME = "efficientnet_b3_embeddings_"#"efficientnet_v2_m"#"convnext_base"#"efficientnet_b3"#"mobileNet" results_path = f"{model_name}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) train_path = f"{model_name}/train" val_path = f"{model_name}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) import sys sys.path.insert(0,'../') # from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd import argparse import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter # import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image # import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim import torch.nn as nn import torch import PIL import pandas as pd import torch import numpy as np import pandas as pd from tqdm import tqdm import os import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score import numpy as np from torchvision import datasets, transforms from timm.data import create_transform # from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD IMAGENET_DEFAULT_MEAN = np.array([0.485, 0.456, 0.406]) IMAGENET_DEFAULT_STD = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * IMAGENET_DEFAULT_STD + IMAGENET_DEFAULT_MEAN) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def plot_multiclass_roc_curve(all_labels, all_predictions, results_path="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{results_path}/roc_curve.png') plt.show() def build_dataset(is_train, args): transform = build_transform(is_train, args) root = os.path.join(args.data_path, 'train' if is_train else 'val') dataset = datasets.ImageFolder(root, transform=transform) print(dataset) return dataset def build_transform(is_train, args): mean = IMAGENET_DEFAULT_MEAN std = IMAGENET_DEFAULT_STD # train transform if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation='bicubic', re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, mean=mean, std=std, ) return transform # eval transform t = [] if args.input_size <= 224: crop_pct = 224 / 256 else: crop_pct = 1.0 size = int(args.input_size / crop_pct) t.append( transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(mean, std)) return transforms.Compose(t) # Set the seed for PyTorch torch.manual_seed(42) from sklearn.svm import SVC # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training X_train = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels X_val = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels # Use los mejores parámetros encontrados best_params = {'C': 4, 'gamma': 'scale', 'kernel': 'rbf'}#{'C': 10, 'gamma': 'scale', 'kernel': 'rbf'} # Inicializa el clasificador SVM con los mejores parámetros svm_classifier = SVC(**best_params, random_state=42) svm_classifier.fit(X_train, y_train) # Predict on validation data y_pred = svm_classifier.predict(X_val) # Calculate accuracy accuracy = accuracy_score(y_val, y_pred) # Calculate precision precision = precision_score(y_val, y_pred, average='weighted') # Calculate recall recall = recall_score(y_val, y_pred, average='weighted') # Calculate F1 score f1 = f1_score(y_val, y_pred, average='weighted') # Calculate F0.75 score fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') print("Validation Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("F0.75 Score:", fbeta_75) X_train.shape unique_classes = np.unique(np.concatenate(((y_pred, y_val)))) confusion_mat = confusion_matrix(y_pred, y_val, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() plot_multiclass_roc_curve(y_pred, y_val, results_path) report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(y_val, y_pred, average='micro') recall = recall_score(y_val, y_pred, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((y_val != 1) & (y_pred != 1)) fp = np.sum((y_val != 1) & (y_pred == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') evaluation_metrics = { "Accuracy": accuracy, "F1 Score": f1, "F0.75 Score": fbeta_75, "Precision": precision, "Recall": recall, "Specificity": specificity } print("Evaluation Metrics:") # for metric, value in evaluation_metrics.items(): # print(f"{metric}: {value}") # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics, index=[0]) # # Save the DataFrame to a CSV file df.to_csv(f'{results_path}/evaluation_metrics_for_table_{MODEL_METADATA}.csv', index=False) df from sklearn.svm import SVC # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print(f"Reading embeddings from: ", train_path) # Prepare data for training X_train = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels X_val = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels start = 0.1 end = 100.0 step = 0.1 # Initialize variables to track best F0.75 score and its corresponding C value best_fbeta_75 = -1 best_c_val = None for c_val in np.arange(start, end + step, step): # Use los mejores parámetros encontrados best_params = {'C': c_val, 'gamma': 'scale', 'kernel': 'rbf'}#{'C': 10, 'gamma': 'scale', 'kernel': 'rbf'} # Inicializa el clasificador SVM con los mejores parámetros svm_classifier = SVC(**best_params, random_state=42) svm_classifier.fit(X_train, y_train) # Predict on validation data y_pred = svm_classifier.predict(X_val) # Calculate accuracy accuracy = accuracy_score(y_val, y_pred) # Calculate precision precision = precision_score(y_val, y_pred, average='weighted') # Calculate recall recall = recall_score(y_val, y_pred, average='weighted') # Calculate F1 score f1 = f1_score(y_val, y_pred, average='weighted') # Calculate F0.75 score fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') # Update best F0.75 score and corresponding C value if a higher score is found if fbeta_75 > best_fbeta_75: best_fbeta_75 = fbeta_75 best_c_val = c_val print(f"value of c: {c_val} ".center(60,"-")) print("Validation Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("F0.75 Score:", fbeta_75) # Print the parameter C that obtains the highest F0.75 score print("Best C value:", best_c_val) print("Best F0.75 Score:", best_fbeta_75) from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC # Define el rango de parámetros que deseas buscar param_grid = { 'C': [0.1,1,10,100], 'gamma': [0.1, 0.01, 0.001, 0.0001], 'kernel': ['rbf'] } # Crea un clasificador SVM svm_classifier = SVC(random_state=42) # Crea un objeto GridSearchCV grid_search = GridSearchCV(estimator=svm_classifier, param_grid=param_grid, cv=10, scoring='accuracy') # Ajusta el modelo GridSearchCV a los datos de entrenamiento grid_search.fit(X_train, y_train) # Obtiene los mejores parámetros y el mejor puntaje best_params = grid_search.best_params_ best_score = grid_search.best_score_ print("Mejores parámetros:", best_params) print("Mejor puntaje:", best_score) # Usa el mejor estimador encontrado por GridSearchCV best_svm_classifier = grid_search.best_estimator_ # Predice sobre los datos de validación usando el mejor modelo y_pred = best_svm_classifier.predict(X_val) # Calcula las métricas de evaluación accuracy = accuracy_score(y_val, y_pred) precision = precision_score(y_val, y_pred, average='weighted') recall = recall_score(y_val, y_pred, average='weighted') f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') print("Exactitud de la validación:", accuracy) print("Precisión:", precision) print("Recall:", recall) print("Puntuación F1:", f1) print("Puntuación F0.75:", fbeta_75)
https://github.com/sebasmos/QuantumVE
sebasmos
import os MODEL_METADATA = "XGBoost" model_name = "convnext_base" EXPERIMENT_NAME = f"{model_name}_embeddings" results_path = f"{EXPERIMENT_NAME}/{MODEL_METADATA}" os.makedirs(results_path, exist_ok = True) os.makedirs(EXPERIMENT_NAME, exist_ok = True) train_path = f"{EXPERIMENT_NAME}/train" val_path = f"{EXPERIMENT_NAME}/val" os.makedirs(train_path, exist_ok = True) os.makedirs(val_path, exist_ok=True) import sys sys.path.insert(0,'../') # from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd import argparse import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter # import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image # import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim import torch.nn as nn import torch import PIL import pandas as pd import torch import numpy as np import pandas as pd from tqdm import tqdm import os import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score import numpy as np from torchvision import datasets, transforms from timm.data import create_transform # from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD IMAGENET_DEFAULT_MEAN = np.array([0.485, 0.456, 0.406]) IMAGENET_DEFAULT_STD = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * IMAGENET_DEFAULT_STD + IMAGENET_DEFAULT_MEAN) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def plot_multiclass_roc_curve(all_labels, all_predictions, results_path="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{results_path}/roc_curve.png') plt.show() def build_dataset(is_train, args): transform = build_transform(is_train, args) root = os.path.join(args.data_path, 'train' if is_train else 'val') dataset = datasets.ImageFolder(root, transform=transform) print(dataset) return dataset def build_transform(is_train, args): mean = IMAGENET_DEFAULT_MEAN std = IMAGENET_DEFAULT_STD # train transform if is_train: # this should always dispatch to transforms_imagenet_train transform = create_transform( input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation='bicubic', re_prob=args.reprob, re_mode=args.remode, re_count=args.recount, mean=mean, std=std, ) return transform # eval transform t = [] if args.input_size <= 224: crop_pct = 224 / 256 else: crop_pct = 1.0 size = int(args.input_size / crop_pct) t.append( transforms.Resize(size, interpolation=PIL.Image.BICUBIC), # to maintain same ratio w.r.t. 224 images ) t.append(transforms.CenterCrop(args.input_size)) t.append(transforms.ToTensor()) t.append(transforms.Normalize(mean, std)) return transforms.Compose(t) # Set the seed for PyTorch torch.manual_seed(42) import pandas as pd import xgboost as xgb from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.model_selection import train_test_split # Read embeddings CSV files train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv') val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv') print("Reading embeddings from:", train_path) # Prepare data for training X_train = train_embeddings.iloc[:, :-1].values # Features y_train = train_embeddings.iloc[:, -1].values # Labels X_val = val_embeddings.iloc[:, :-1].values # Features y_val = val_embeddings.iloc[:, -1].values # Labels # # Split train data for validation # X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42) # Train XGBoost Classifier xgb_classifier = xgb.XGBClassifier(objective='multi:softmax', num_class=len(set(y_train)), random_state=42) xgb_classifier.fit(X_train, y_train) # Predict on validation data y_pred = xgb_classifier.predict(X_val) # Calculate evaluation metrics accuracy = accuracy_score(y_val, y_pred) precision = precision_score(y_val, y_pred, average='weighted') recall = recall_score(y_val, y_pred, average='weighted') f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') print("Validation Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("F0.75 Score:", fbeta_75) unique_classes = np.unique(np.concatenate(((y_pred, y_val)))) confusion_mat = confusion_matrix(y_pred, y_val, labels=unique_classes) conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes) # Plot the confusion matrix using seaborn plt.figure(figsize=(5, 4)) ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True) # Set labels and ticks ax.set_xlabel('Predicted Labels') ax.set_ylabel('True Labels') # Set x and y ticks using the unique classes ax.set_xticks(range(len(unique_classes))) ax.set_yticks(range(len(unique_classes))) # Set x and y ticks at the center of the cells ax.set_xticks([i + 0.5 for i in range(len(unique_classes))]) ax.set_yticks([i + 0.5 for i in range(len(unique_classes))]) plt.show() plot_multiclass_roc_curve(y_pred, y_val, results_path) report = classification_report(y_val,y_pred, target_names=unique_classes,output_dict=True)# Mostrar el informe de df = pd.DataFrame(report).transpose() df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv")) print(df) # Calculate precision, recall, and specificity (micro-averaged) precision = precision_score(y_val, y_pred, average='micro') recall = recall_score(y_val, y_pred, average='micro') # Calculate true negatives, false positives, and specificity (micro-averaged) tn = np.sum((y_val != 1) & (y_pred != 1)) fp = np.sum((y_val != 1) & (y_pred == 1)) specificity = tn / (tn + fp) # Calculate F1 score (weighted average) f1 = f1_score(y_val, y_pred, average='weighted') fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') evaluation_metrics = { "Accuracy": accuracy, "F1 Score": f1, "F0.75 Score": fbeta_75, "Precision": precision, "Recall": recall, "Specificity": specificity } print("Evaluation Metrics:") # for metric, value in evaluation_metrics.items(): # print(f"{metric}: {value}") # Create a DataFrame from the dictionary df = pd.DataFrame(evaluation_metrics, index=[0]) # # Save the DataFrame to a CSV file df.to_csv(f'{results_path}/evaluation_metrics_for_table_{MODEL_METADATA}.csv', index=False) df # from sklearn.model_selection import GridSearchCV # from sklearn.ensemble import RandomForestClassifier # from sklearn.preprocessing import StandardScaler # from sklearn.pipeline import Pipeline # from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score # # Define the parameter grid to search # param_grid = { # 'classifier__n_estimators': [50, 100, 150], # 'classifier__max_depth': [None, 10, 20], # 'classifier__min_samples_split': [2, 5, 10], # 'classifier__min_samples_leaf': [1, 2, 4] # } # # Create a pipeline with normalization and RandomForestClassifier # rf_pipeline = Pipeline([ # ('scaler', StandardScaler()), # ('classifier', RandomForestClassifier(random_state=42)) # ]) # # Create GridSearchCV # grid_search = GridSearchCV(estimator=rf_pipeline, param_grid=param_grid, cv=3, scoring='accuracy') # # Fit the grid search to the data # grid_search.fit(X_train, y_train) # # Get the best parameters and best score # best_params = grid_search.best_params_ # best_score = grid_search.best_score_ # print("Best Parameters:", best_params) # print("Best Score:", best_score) # # Use the best estimator found by GridSearchCV # best_rf_classifier = grid_search.best_estimator_ # # Predict on validation data using the best model # y_pred = best_rf_classifier.predict(X_val) # # Calculate metrics # accuracy = accuracy_score(y_val, y_pred) # precision = precision_score(y_val, y_pred, average='weighted') # recall = recall_score(y_val, y_pred, average='weighted') # f1 = f1_score(y_val, y_pred, average='weighted') # fbeta_75 = fbeta_score(y_val, y_pred, beta=0.75, average='weighted') # print("Validation Accuracy:", accuracy) # print("Precision:", precision) # print("Recall:", recall) # print("F1 Score:", f1) # print("F0.75 Score:", fbeta_75)
https://github.com/sebasmos/QuantumVE
sebasmos
# Define the model name model_name = "efficientnet_v2_m" #EfficientNet_B7_Weights.IMAGENET1K_V1 !pwd %cd Vector_Embeddings !pwd import torchvision.models as models import torch MODEL_CONSTRUCTORS = { 'alexnet': models.alexnet, 'convnext_base': models.convnext_base, 'convnext_large': models.convnext_large, 'convnext_small': models.convnext_small, 'convnext_tiny': models.convnext_tiny, 'densenet121': models.densenet121, 'densenet161': models.densenet161, 'densenet169': models.densenet169, 'densenet201': models.densenet201, 'efficientnet_b0': models.efficientnet_b0, 'efficientnet_b1': models.efficientnet_b1, 'efficientnet_b2': models.efficientnet_b2, 'efficientnet_b3': models.efficientnet_b3, 'efficientnet_b4': models.efficientnet_b4, 'efficientnet_b5': models.efficientnet_b5, 'efficientnet_b6': models.efficientnet_b6, 'efficientnet_b7': models.efficientnet_b7, 'efficientnet_v2_l': models.efficientnet_v2_l, 'efficientnet_v2_m': models.efficientnet_v2_m, 'efficientnet_v2_s': models.efficientnet_v2_s, 'googlenet': models.googlenet, 'inception_v3': models.inception_v3, 'maxvit_t': models.maxvit_t, 'mnasnet0_5': models.mnasnet0_5, 'mnasnet0_75': models.mnasnet0_75, 'mnasnet1_0': models.mnasnet1_0, 'mnasnet1_3': models.mnasnet1_3, 'mobilenet_v2': models.mobilenet_v2, 'mobilenet_v3_large': models.mobilenet_v3_large, 'mobilenet_v3_small': models.mobilenet_v3_small, 'regnet_x_16gf': models.regnet_x_16gf, 'regnet_x_1_6gf': models.regnet_x_1_6gf, 'regnet_x_32gf': models.regnet_x_32gf, 'regnet_x_3_2gf': models.regnet_x_3_2gf, 'regnet_x_400mf': models.regnet_x_400mf, 'regnet_x_800mf': models.regnet_x_800mf, 'regnet_x_8gf': models.regnet_x_8gf, 'regnet_y_128gf': models.regnet_y_128gf,# check this regnet_y_128gf: no weigthts avaialble 'regnet_y_16gf': models.regnet_y_16gf, 'regnet_y_1_6gf': models.regnet_y_1_6gf, 'regnet_y_32gf': models.regnet_y_32gf, 'regnet_y_3_2gf': models.regnet_y_3_2gf, 'regnet_y_400mf': models.regnet_y_400mf, 'regnet_y_800mf': models.regnet_y_800mf, 'regnet_y_8gf': models.regnet_y_8gf, 'resnet101': models.resnet101, 'resnet152': models.resnet152, 'resnet18': models.resnet18, 'resnet34': models.resnet34, 'resnet50': models.resnet50, 'resnext101_32x8d': models.resnext101_32x8d, 'resnext101_64x4d': models.resnext101_64x4d, 'resnext50_32x4d': models.resnext50_32x4d, 'shufflenet_v2_x0_5': models.shufflenet_v2_x0_5, 'shufflenet_v2_x1_0': models.shufflenet_v2_x1_0, 'shufflenet_v2_x1_5': models.shufflenet_v2_x1_5, 'shufflenet_v2_x2_0': models.shufflenet_v2_x2_0, 'squeezenet1_0': models.squeezenet1_0, 'squeezenet1_1': models.squeezenet1_1, 'swin_b': models.swin_b, 'swin_s': models.swin_s, 'swin_t': models.swin_t, 'swin_v2_b': models.swin_v2_b, 'swin_v2_s': models.swin_v2_s, 'swin_v2_t': models.swin_v2_t, 'vgg11': models.vgg11, 'vgg11_bn': models.vgg11_bn, 'vgg13': models.vgg13, 'vgg13_bn': models.vgg13_bn, 'vgg16': models.vgg16, 'vgg16_bn': models.vgg16_bn, 'vgg19': models.vgg19, 'vgg19_bn': models.vgg19_bn, 'vit_b_16': models.vit_b_16, 'vit_b_32': models.vit_b_32, 'vit_h_14': models.vit_h_14,# and this..no weigthts avaialble 'vit_l_16': models.vit_l_16, 'vit_l_32': models.vit_l_32, 'wide_resnet101_2': models.wide_resnet101_2, 'wide_resnet50_2': models.wide_resnet50_2 } # Create experiment directory EXPERIMENT_NAME = f"{model_name}_embeddings" import os os.makedirs(EXPERIMENT_NAME, exist_ok=True) train_path = f"{EXPERIMENT_NAME}/train" val_path = f"{EXPERIMENT_NAME}/val" os.makedirs(train_path, exist_ok=True) os.makedirs(val_path, exist_ok=True) import sys sys.path.insert(0,'../') from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR from torch.utils.data import random_split from torch.utils.data import Subset, DataLoader, random_split from torchvision import datasets, transforms import torch.optim as optim from torch.optim.lr_scheduler import StepLR import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix, classification_report import pandas as pd # from MAE code from util.datasets import build_dataset import argparse import util.misc as misc import argparse import datetime import json import numpy as np import os import time from pathlib import Path import torch import torch.backends.cudnn as cudnn from torch.utils.tensorboard import SummaryWriter import timm assert timm.__version__ == "0.3.2" # version check from timm.models.layers import trunc_normal_ from timm.data.mixup import Mixup from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy import util.lr_decay as lrd import util.misc as misc from util.datasets import build_dataset from util.pos_embed import interpolate_pos_embed from util.misc import NativeScalerWithGradNormCount as NativeScaler import models_vit import sys import os import torch import numpy as np import matplotlib.pyplot as plt from PIL import Image import models_mae import torch; print(f'numpy version: {np.__version__}\nCUDA version: {torch.version.cuda} - Torch versteion: {torch.__version__} - device count: {torch.cuda.device_count()}') from engine_finetune import train_one_epoch, evaluate from timm.data import Mixup from timm.utils import accuracy from sklearn.metrics import confusion_matrix, classification_report import seaborn as sns from sklearn.preprocessing import LabelBinarizer from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt from itertools import cycle import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score import torch.optim as optim import torchvision.models as models import torch.nn as nn import torch import pandas as pd import torch import numpy as np import pandas as pd from tqdm import tqdm import os import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, fbeta_score from sklearn.metrics import precision_score, recall_score, f1_score, fbeta_score import numpy as np imagenet_mean = np.array([0.485, 0.456, 0.406]) imagenet_std = np.array([0.229, 0.224, 0.225]) def show_image(image, title=''): # image is [H, W, 3] assert image.shape[2] == 3 plt.imshow(torch.clip((image * imagenet_std + imagenet_mean) * 255, 0, 255).int()) plt.title(title, fontsize=16) plt.axis('off') return def prepare_model(chkpt_dir, arch='mae_vit_large_patch16'): # build model model = getattr(models_mae, arch)() # load model checkpoint = torch.load(chkpt_dir, map_location='cpu') msg = model.load_state_dict(checkpoint['model'], strict=False) print(msg) return model def plot_multiclass_roc_curve(all_labels, all_predictions, EXPERIMENT_NAME="."): # Step 1: Label Binarization label_binarizer = LabelBinarizer() y_onehot = label_binarizer.fit_transform(all_labels) all_predictions_hot = label_binarizer.transform(all_predictions) # Step 2: Calculate ROC curves fpr = dict() tpr = dict() roc_auc = dict() unique_classes = range(y_onehot.shape[1]) for i in unique_classes: fpr[i], tpr[i], _ = roc_curve(y_onehot[:, i], all_predictions_hot[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) # Step 3: Plot ROC curves fig, ax = plt.subplots(figsize=(8, 8)) # Micro-average ROC curve fpr_micro, tpr_micro, _ = roc_curve(y_onehot.ravel(), all_predictions_hot.ravel()) roc_auc_micro = auc(fpr_micro, tpr_micro) plt.plot( fpr_micro, tpr_micro, label=f"micro-average ROC curve (AUC = {roc_auc_micro:.2f})", color="deeppink", linestyle=":", linewidth=4, ) # Macro-average ROC curve all_fpr = np.unique(np.concatenate([fpr[i] for i in unique_classes])) mean_tpr = np.zeros_like(all_fpr) for i in unique_classes: mean_tpr += np.interp(all_fpr, fpr[i], tpr[i]) mean_tpr /= len(unique_classes) fpr_macro = all_fpr tpr_macro = mean_tpr roc_auc_macro = auc(fpr_macro, tpr_macro) plt.plot( fpr_macro, tpr_macro, label=f"macro-average ROC curve (AUC = {roc_auc_macro:.2f})", color="navy", linestyle=":", linewidth=4, ) # Individual class ROC curves with unique colors colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_classes))) for class_id, color in zip(unique_classes, colors): plt.plot( fpr[class_id], tpr[class_id], color=color, label=f"ROC curve for Class {class_id} (AUC = {roc_auc[class_id]:.2f})", linewidth=2, ) plt.plot([0, 1], [0, 1], color='gray', linestyle='--', linewidth=2) # Add diagonal line for reference plt.axis("equal") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\n to One-vs-Rest multiclass") plt.legend() plt.savefig(f'{EXPERIMENT_NAME}/roc_curve.png') plt.show() # Set the seed for PyTorch torch.manual_seed(42) parser = argparse.ArgumentParser('MAE fine-tuning for image classification', add_help=False) parser.add_argument('--batch_size', default=64, type=int, help='Batch size per GPU (effective batch size is batch_size * accum_iter * # gpus') parser.add_argument('--epochs', default=50, type=int) parser.add_argument('--accum_iter', default=4, type=int, help='Accumulate gradient iterations (for increasing the effective batch size under memory constraints)') # Model parameters parser.add_argument('--model', default='mobilenet_v3', type=str, metavar='MODEL', help='Name of model to train') parser.add_argument('--input_size', default=224, type=int, help='images input size') parser.add_argument('--drop_path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') # Optimizer parameters parser.add_argument('--clip_grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--weight_decay', type=float, default=0.05, help='weight decay (default: 0.05)') parser.add_argument('--lr', type=float, default=None, metavar='LR', help='learning rate (absolute lr)') parser.add_argument('--blr', type=float, default=5e-4, metavar='LR', help='base learning rate: absolute_lr = base_lr * total_batch_size / 256') parser.add_argument('--layer_decay', type=float, default=0.65, help='layer-wise lr decay from ELECTRA/BEiT') parser.add_argument('--min_lr', type=float, default=1e-6, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0') parser.add_argument('--warmup_epochs', type=int, default=5, metavar='N', help='epochs to warmup LR') # Augmentation parameters parser.add_argument('--color_jitter', type=float, default=None, metavar='PCT', help='Color jitter factor (enabled only when not using Auto/RandAug)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0.') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0.') parser.add_argument('--cutmix_minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup_prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup_switch_prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup_mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # * Finetuning params parser.add_argument('--finetune', default='mae_pretrain_vit_base.pth', help='finetune from checkpoint') parser.add_argument('--global_pool', action='store_true') parser.set_defaults(global_pool=True) parser.add_argument('--cls_token', action='store_false', dest='global_pool', help='Use class token instead of global pool for classification') # Dataset parameters parser.add_argument('--data_path', default='/media/enc/vera1/sebastian/data/ABGQI_mel_spectrograms', type=str, help='dataset path') parser.add_argument('--nb_classes', default=5, type=int, help='number of the classification types') parser.add_argument('--output_dir', default='quinn_5_classes', help='path where to save, empty for no saving') parser.add_argument('--log_dir', default='/media/enc/vera1/sebastian/codes/classifiers/mae/MobileNet/output_dir', help='path where to tensorboard log') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default="/media/enc/vera1/sebastian/codes/classifiers/mae/MobileNet/quinn_5_classes/checkpoint-49.pth", help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval',default=True, action='store_true', help='Perform evaluation only') parser.add_argument('--dist_eval', action='store_true', default=False, help='Enabling distributed evaluation (recommended during training for faster monitor') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin_mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no_pin_mem', action='store_false', dest='pin_mem') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--local_rank', default=-1, type=int) parser.add_argument('--dist_on_itp', action='store_true') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') args, unknown = parser.parse_known_args() misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) os.makedirs(args.output_dir, exist_ok=True) device = torch.device(args.device) misc.init_distributed_mode(args) print("{}".format(args).replace(', ', ',\n')) device = torch.device(args.device) seed = args.seed + misc.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train = build_dataset(is_train=True, args=args) dataset_val = build_dataset(is_train=False, args=args) if True: # args.distributed: num_tasks = misc.get_world_size() global_rank = misc.get_rank() sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) print("Sampler_train = %s" % str(sampler_train)) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=True) # shuffle=True to reduce monitor bias else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) if global_rank == 0 and args.log_dir is not None and not args.eval: os.makedirs(args.log_dir, exist_ok=True) log_writer = SummaryWriter(log_dir=args.log_dir) else: log_writer = None data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) def count_parameters(model, message=""): trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) total_params = sum(p.numel() for p in model.parameters()) print(f"{message} Trainable params: {trainable_params} of {total_params}") def extract_embeddings(model, data_loader, save_path, device, preprocess=None): embeddings_list = [] targets_list = [] total_batches = len(data_loader) with torch.no_grad(), tqdm(total=total_batches) as pbar: model.eval() # Set the model to evaluation mode for images, targets in data_loader: if preprocess: print("required processing") images = preprocess(images).squeeze() images = images.to(device) # print("image shape is: ", images.shape) embeddings = model(images) embeddings_list.append(embeddings.cpu().detach().numpy()) # Move to CPU and convert to NumPy targets_list.append(targets.numpy()) # Convert targets to NumPy pbar.update(1) # Concatenate embeddings and targets from all batches embeddings = np.concatenate(embeddings_list).squeeze() targets = np.concatenate(targets_list) num_embeddings = embeddings.shape[1] column_names = [f"feat_{i}" for i in range(num_embeddings)] column_names.append("label") embeddings_with_targets = np.hstack((embeddings, np.expand_dims(targets, axis=1))) # Create a DataFrame with column names df = pd.DataFrame(embeddings_with_targets, columns=column_names) df.to_csv(save_path, index=False) model_names = sorted(name for name in models.__dict__ if name.islower() and not name.startswith("__") and not name.startswith('get_') and not name.startswith('list_') and callable(models.__dict__[name])) model_names # Load the model if model_name in MODEL_CONSTRUCTORS: model_constructor = MODEL_CONSTRUCTORS[model_name] if model_name == "vit_h_14": from torchvision.io import read_image from torchvision.models import vit_h_14, ViT_H_14_Weights # Step 1: Initialize model with the best available weights weights = ViT_H_14_Weights.IMAGENET1K_SWAG_E2E_V1.DEFAULT model = vit_h_14(weights=weights) model = torch.nn.Sequential(*(list(model.children())[:-1])) # Step 2: Initialize the inference transforms preprocess = weights.transforms() if model_name =="regnet_y_128gf": from torchvision.io import read_image from torchvision.models import regnet_y_128gf, RegNet_Y_128GF_Weights # Step 1: Initialize model with the best available weights weights = RegNet_Y_128GF_Weights.IMAGENET1K_SWAG_E2E_V1 model = regnet_y_128gf(weights=weights) model = torch.nn.Sequential(*(list(model.children())[:-1])) # Step 2: Initialize the inference transforms preprocess = weights.transforms() if model_name =="mobilenet_v3_large": from torchvision.io import read_image from torchvision.models import mobilenet_v3_large, MobileNet_V3_Large_Weights # Step 1: Initialize model with the best available weights weights = MobileNet_V3_Large_Weights.IMAGENET1K_V2 model = mobilenet_v3_large(weights=weights) model = torch.nn.Sequential(*(list(model.children())[:-1])) # Step 2: Initialize the inference transforms preprocess = weights.transforms() else: model = model_constructor(pretrained=True, progress=True) model = torch.nn.Sequential(*(list(model.children())[:-1])) preprocess=None else: raise ValueError("Invalid model type specified.") # Set to evaluation model. model.eval() model.to(device) # Extract embeddings for training data extract_embeddings(model, data_loader_train, f'{train_path}/train_embeddings.csv', device, preprocess) # Extract embeddings for validation data extract_embeddings(model, data_loader_val, f'{val_path}/val_embeddings.csv', device, preprocess)
https://github.com/sebasmos/QuantumVE
sebasmos
!pip install tensorflow==2.4.1 !pip install tensorflow-quantum import tensorflow as tf import tensorflow_quantum as tfq import cirq import sympy import numpy as np # visualization tools %matplotlib inline import matplotlib.pyplot as plt from cirq.contrib.svg import SVGCircuit a, b = sympy.symbols('a b') # Create two qubits q0, q1 = cirq.GridQubit.rect(1, 2) # Create a circuit on these qubits using the parameters you created above. circuit = cirq.Circuit( cirq.rx(a).on(q0), cirq.ry(b).on(q1), cirq.CNOT(control=q0, target=q1)) SVGCircuit(circuit) # Calculate a state vector with a=0.5 and b=-0.5. resolver = cirq.ParamResolver({a: 0.5, b: -0.5}) output_state_vector = cirq.Simulator().simulate(circuit, resolver).final_state_vector output_state_vector z0 = cirq.Z(q0) qubit_map={q0: 0, q1: 1} z0.expectation_from_state_vector(output_state_vector, qubit_map).real z0x1 = 0.5 * z0 + cirq.X(q1) z0x1.expectation_from_state_vector(output_state_vector, qubit_map).real # Rank 1 tensor containing 1 circuit. circuit_tensor = tfq.convert_to_tensor([circuit]) print(circuit_tensor.shape) print(circuit_tensor.dtype) # Rank 1 tensor containing 2 Pauli operators. pauli_tensor = tfq.convert_to_tensor([z0, z0x1]) pauli_tensor.shape batch_vals = np.array(np.random.uniform(0, 2 * np.pi, (5, 2)), dtype=np.float32) cirq_results = [] cirq_simulator = cirq.Simulator() for vals in batch_vals: resolver = cirq.ParamResolver({a: vals[0], b: vals[1]}) final_state_vector = cirq_simulator.simulate(circuit, resolver).final_state_vector cirq_results.append( [z0.expectation_from_state_vector(final_state_vector, { q0: 0, q1: 1 }).real]) print('cirq batch results: \n {}'.format(np.array(cirq_results))) tfq.layers.Expectation()(circuit, symbol_names=[a, b], symbol_values=batch_vals, operators=z0) # Parameters that the classical NN will feed values into. control_params = sympy.symbols('theta_1 theta_2 theta_3') # Create the parameterized circuit. qubit = cirq.GridQubit(0, 0) model_circuit = cirq.Circuit( cirq.rz(control_params[0])(qubit), cirq.ry(control_params[1])(qubit), cirq.rx(control_params[2])(qubit)) SVGCircuit(model_circuit) # The classical neural network layers. controller = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='elu'), tf.keras.layers.Dense(3) ]) controller(tf.constant([[0.0],[1.0]])).numpy() # This input is the simulated miscalibration that the model will learn to correct. circuits_input = tf.keras.Input(shape=(), # The circuit-tensor has dtype `tf.string` dtype=tf.string, name='circuits_input') # Commands will be either `0` or `1`, specifying the state to set the qubit to. commands_input = tf.keras.Input(shape=(1,), dtype=tf.dtypes.float32, name='commands_input') dense_2 = controller(commands_input) # TFQ layer for classically controlled circuits. expectation_layer = tfq.layers.ControlledPQC(model_circuit, # Observe Z operators = cirq.Z(qubit)) expectation = expectation_layer([circuits_input, dense_2]) # The full Keras model is built from our layers. model = tf.keras.Model(inputs=[circuits_input, commands_input], outputs=expectation) #https://stackoverflow.com/questions/47605558/importerror-failed-to-import-pydot-you-must-install-pydot-and-graphviz-for-py !pip install pydot !pip install pydotplus !pip install graphviz tf.keras.utils.plot_model(model, show_shapes=True, dpi=70) # The command input values to the classical NN. commands = np.array([[0], [1]], dtype=np.float32) # The desired Z expectation value at output of quantum circuit. expected_outputs = np.array([[1], [-1]], dtype=np.float32) random_rotations = np.random.uniform(0, 2 * np.pi, 3) noisy_preparation = cirq.Circuit( cirq.rx(random_rotations[0])(qubit), cirq.ry(random_rotations[1])(qubit), cirq.rz(random_rotations[2])(qubit) ) datapoint_circuits = tfq.convert_to_tensor([ noisy_preparation ] * 2) # Make two copied of this circuit datapoint_circuits.shape model([datapoint_circuits, commands]).numpy() optimizer = tf.keras.optimizers.Adam(learning_rate=0.05) loss = tf.keras.losses.MeanSquaredError() model.compile(optimizer=optimizer, loss=loss) history = model.fit(x=[datapoint_circuits, commands], y=expected_outputs, epochs=30, verbose=0) plt.plot(history.history['loss']) plt.title("Learning to Control a Qubit") plt.xlabel("Iterations") plt.ylabel("Error in Control") plt.show() def check_error(command_values, desired_values): """Based on the value in `command_value` see how well you could prepare the full circuit to have `desired_value` when taking expectation w.r.t. Z.""" params_to_prepare_output = controller(command_values).numpy() full_circuit = noisy_preparation + model_circuit # Test how well you can prepare a state to get expectation the expectation # value in `desired_values` for index in [0, 1]: state = cirq_simulator.simulate( full_circuit, {s:v for (s,v) in zip(control_params, params_to_prepare_output[index])} ).final_state_vector expt = cirq.Z(qubit).expectation_from_state_vector(state, {qubit: 0}).real print(f'For a desired output (expectation) of {desired_values[index]} with' f' noisy preparation, the controller\nnetwork found the following ' f'values for theta: {params_to_prepare_output[index]}\nWhich gives an' f' actual expectation of: {expt}\n') check_error(commands, expected_outputs) model([datapoint_circuits, commands]) # Define inputs. commands_input = tf.keras.layers.Input(shape=(1), dtype=tf.dtypes.float32, name='commands_input') circuits_input = tf.keras.Input(shape=(), # The circuit-tensor has dtype `tf.string` dtype=tf.dtypes.string, name='circuits_input') operators_input = tf.keras.Input(shape=(1,), dtype=tf.dtypes.string, name='operators_input') # Define classical NN. controller = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='elu'), tf.keras.layers.Dense(3) ]) dense_2 = controller(commands_input) # Since you aren't using a PQC or ControlledPQC you must append # your model circuit onto the datapoint circuit tensor manually. full_circuit = tfq.layers.AddCircuit()(circuits_input, append=model_circuit) expectation_output = tfq.layers.Expectation()(full_circuit, symbol_names=control_params, symbol_values=dense_2, operators=operators_input) # Contruct your Keras model. two_axis_control_model = tf.keras.Model( inputs=[circuits_input, commands_input, operators_input], outputs=[expectation_output]) # The operators to measure, for each command. operator_data = tfq.convert_to_tensor([[cirq.X(qubit)], [cirq.Z(qubit)]]) # The command input values to the classical NN. commands = np.array([[0], [1]], dtype=np.float32) # The desired expectation value at output of quantum circuit. expected_outputs = np.array([[1], [-1]], dtype=np.float32) optimizer = tf.keras.optimizers.Adam(learning_rate=0.05) loss = tf.keras.losses.MeanSquaredError() two_axis_control_model.compile(optimizer=optimizer, loss=loss) history = two_axis_control_model.fit( x=[datapoint_circuits, commands, operator_data], y=expected_outputs, epochs=30, validation_split=0.2, verbose=2) plt.plot(history.history['loss']) plt.title("Learning to Control a Qubit") plt.xlabel("Iterations") plt.ylabel("Error in Control") plt.show() controller.predict(np.array([0,1])) # Define inputs. commands_input = tf.keras.layers.Input(shape=(1), dtype=tf.dtypes.float32, name='commands_input') circuits_input = tf.keras.Input(shape=(), # The circuit-tensor has dtype `tf.string` dtype=tf.dtypes.string, name='circuits_input') operators_input = tf.keras.Input(shape=(1,), dtype=tf.dtypes.string, name='operators_input') # Define classical NN. controller = tf.keras.Sequential([ tf.keras.layers.Dense(100, activation='relu'), tf.keras.layers.Dense(200, activation='relu'), tf.keras.layers.Dense(2000, activation='relu'), tf.keras.layers.Dense(3) ]) dense_2 = controller(commands_input) # Since you aren't using a PQC or ControlledPQC you must append # your model circuit onto the datapoint circuit tensor manually. full_circuit = tfq.layers.AddCircuit()(circuits_input, append=model_circuit) expectation_output = tfq.layers.Expectation()(full_circuit, symbol_names=control_params, symbol_values=dense_2, operators=operators_input) # Contruct your Keras model. two_axis_control_model = tf.keras.Model( inputs=[circuits_input, commands_input, operators_input], outputs=[expectation_output]) # The operators to measure, for each command. operator_data = tfq.convert_to_tensor([[cirq.X(qubit)], [cirq.Z(qubit)]]) # The command input values to the classical NN. commands = np.array([[0], [1]], dtype=np.float32) # The desired expectation value at output of quantum circuit. expected_outputs = np.array([[1], [-1]], dtype=np.float32) optimizer = tf.keras.optimizers.Adam(learning_rate=0.05) loss = tf.keras.losses.MeanSquaredError() two_axis_control_model.compile(optimizer=optimizer, loss=loss) history = two_axis_control_model.fit( x=[datapoint_circuits, commands, operator_data], y=expected_outputs, epochs=30, validation_split=0.2, verbose=2) plt.plot(history.history['loss']) plt.title("Learning to Control a Qubit") plt.xlabel("Iterations") plt.ylabel("Error in Control") plt.show() controller.predict(np.array([0,1]))
https://github.com/derivation/ThinkQuantum
derivation
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer from qiskit.tools.visualization import circuit_drawer, plot_histogram import numpy as np from numpy import pi num_measurements = 5 q = QuantumRegister(1) c = ClassicalRegister(num_measurements) circ = QuantumCircuit(q,c) for m in range(num_measurements): circ.measure(q[0],c[m]) circuit_drawer(circ, output='mpl') backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(circ, backend_sim, shots=1) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) num_measurements = 5 q = QuantumRegister(1) c = ClassicalRegister(num_measurements) circ = QuantumCircuit(q,c) for m in range(num_measurements): circ.measure(q[0],c[m]) circ.rx(pi, q[0]) circuit_drawer(circ, output='mpl') job_sim = execute(circ, backend_sim, shots=1) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) num_measurements = 1 q = QuantumRegister(1) c = ClassicalRegister(num_measurements) circ = QuantumCircuit(q,c) circ.rx(pi/2, q) circ.measure(q, c) circuit_drawer(circ, output='mpl') job_sim = execute(circ, backend_sim, shots=1) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) repetitions = 1024 job_sim = execute(circ, backend_sim, shots=repetitions) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) plot_histogram(counts)
https://github.com/derivation/ThinkQuantum
derivation
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer from qiskit.tools.visualization import circuit_drawer, plot_histogram import numpy as np from numpy import pi num_measurements = 5 q = QuantumRegister(1) c = ClassicalRegister(num_measurements) circ = QuantumCircuit(q,c) for m in range(num_measurements): circ.measure(q[0],c[m]) circuit_drawer(circ, output='mpl') backend_sim = Aer.get_backend('qasm_simulator') job_sim = execute(circ, backend_sim, shots=1) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) num_measurements = 5 q = QuantumRegister(1) c = ClassicalRegister(num_measurements) circ = QuantumCircuit(q,c) for m in range(num_measurements): circ.measure(q[0],c[m]) circ.rx(pi, q[0]) circuit_drawer(circ, output='mpl') job_sim = execute(circ, backend_sim, shots=1) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) num_measurements = 1 q = QuantumRegister(1) c = ClassicalRegister(num_measurements) circ = QuantumCircuit(q,c) circ.rx(pi/2, q) circ.measure(q, c) circuit_drawer(circ, output='mpl') job_sim = execute(circ, backend_sim, shots=1) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) repetitions = 1024 job_sim = execute(circ, backend_sim, shots=repetitions) result_sim = job_sim.result() counts = result_sim.get_counts(circ) print(counts) plot_histogram(counts)
https://github.com/derivation/ThinkQuantum
derivation
import numpy as np from numpy import pi import matplotlib.pyplot as plt import matplotlib.image as mpimg filename = './schrodin_yang.png' im = mpimg.imread(filename) fig, ax = plt.subplots() ax.imshow(im) from skimage.transform import resize n_pixels = 2**5 im = resize(im, (n_pixels, n_pixels)) fig, ax = plt.subplots() ax.imshow(im) data = im[:,:,0].ravel() from qiskit_aqua.components.initial_states import Custom n_qubits = np.int_(np.log2(len(data))) init_state = Custom(n_qubits, state_vector=data) circ = init_state.construct_circuit('circuit') qr = circ.qregs from copy import deepcopy circ_init = deepcopy(circ) circ.h(qr[0][0]) from qiskit import BasicAer, execute simulator = BasicAer.get_backend('statevector_simulator') result = execute(circ, simulator).result() final_state_vector = result.get_statevector(circ) edge_even = np.real(final_state_vector) n_rows = int(np.sqrt(len(edge_even))) edge_even = edge_even.reshape(n_rows, -1) edge_even[:,::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge_even) ax[1].imshow(im) def qft(c, q, n): """n-qubit QFT on q in c.""" for j in range(n): for k in range(j): c.cu1(pi/float(2**(j-k)), q[j], q[k]) c.h(q[j]) def iqft(c, q, n): """n-qubit IQFT on q in c.""" for j in range(n): for k in range(j): c.cu1(-pi/float(2**(j-k)), q[int(n-j-1)], q[int(n-k-1)]) c.h(q[int(n-j-1)]) def shiftBases(c, q, n, p): """Shift the register q by p positions""" iqft(c,q,n) for k in range(n): c.u1(-p*2*pi/float(2**(n-k)), q[int(n-k-1)]) qft(c,q,n) from qiskit import QuantumRegister, QuantumCircuit n = 2 q = QuantumRegister(n,'q') c = QuantumCircuit(q) iqft(c,q,n) shiftBases(c,q,n,1) qft(c,q,n) c.draw(output='mpl') circ = deepcopy(circ_init) qr = circ.qregs shiftBases(circ,qr[0],n_qubits,1) circ.h(qr[0][0]) shiftBases(circ,qr[0],n_qubits,-1) simulator = BasicAer.get_backend('statevector_simulator') result = execute(circ, simulator).result() final_state_vector = result.get_statevector(circ) edge_odd = np.real(final_state_vector) n_rows = np.int_(np.sqrt(len(edge_odd))) edge_odd = edge_odd.reshape(n_rows, -1) edge_odd[:,1::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge_odd) ax[1].imshow(im) edge = edge_even + edge_odd fig, ax = plt.subplots(1,2) ax[0].imshow(edge) ax[1].imshow(im)
https://github.com/derivation/ThinkQuantum
derivation
import numpy as np from numpy import pi import matplotlib.pyplot as plt import matplotlib.image as mpimg from skimage.transform import resize filename = './schrodin_yang.png' im = mpimg.imread(filename) n_pixels = 2**5 im = resize(im, (n_pixels, n_pixels)) data = im[:,:,0].ravel() fig, ax = plt.subplots() ax.imshow(im) n_qubits = int(np.log2(len(data))) from qiskit_aqua.components.initial_states import Custom init_state = Custom(n_qubits, state_vector=data) circ = init_state.construct_circuit('circuit') qr = circ.qregs # circ.draw() circ.h(qr[0][0]) from qiskit import BasicAer, execute simulator = BasicAer.get_backend('statevector_simulator') sim_result = execute(circ, simulator).result() final_state = sim_result.get_statevector(circ) edge = np.real(final_state) n_rows = int(np.sqrt(len(edge))) n_cols = n_rows edge = edge.reshape(n_rows, n_cols) edge[:,::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge) ax[1].imshow(im)
https://github.com/derivation/ThinkQuantum
derivation
import numpy as np from numpy import pi import matplotlib.pyplot as plt import matplotlib.image as mpimg filename = './schrodin_yang.png' im = mpimg.imread(filename) fig, ax = plt.subplots() ax.imshow(im) from skimage.transform import resize n_pixels = 2**5 im = resize(im, (n_pixels, n_pixels)) fig, ax = plt.subplots() ax.imshow(im) data = im[:,:,0].ravel() from qiskit_aqua.components.initial_states import Custom n_qubits = np.int_(np.log2(len(data))) init_state = Custom(n_qubits, state_vector=data) circ = init_state.construct_circuit('circuit') qr = circ.qregs from copy import deepcopy circ_init = deepcopy(circ) circ.h(qr[0][0]) from qiskit import BasicAer, execute simulator = BasicAer.get_backend('statevector_simulator') result = execute(circ, simulator).result() final_state_vector = result.get_statevector(circ) edge_even = np.real(final_state_vector) n_rows = int(np.sqrt(len(edge_even))) edge_even = edge_even.reshape(n_rows, -1) edge_even[:,::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge_even) ax[1].imshow(im) def qft(c, q, n): """n-qubit QFT on q in c.""" for j in range(n): for k in range(j): c.cu1(pi/float(2**(j-k)), q[j], q[k]) c.h(q[j]) def iqft(c, q, n): """n-qubit IQFT on q in c.""" for j in range(n): for k in range(j): c.cu1(-pi/float(2**(j-k)), q[int(n-j-1)], q[int(n-k-1)]) c.h(q[int(n-j-1)]) def shiftBases(c, q, n, p): """Shift the register q by p positions""" iqft(c,q,n) for k in range(n): c.u1(-p*2*pi/float(2**(n-k)), q[int(n-k-1)]) qft(c,q,n) from qiskit import QuantumRegister, QuantumCircuit n = 2 q = QuantumRegister(n,'q') c = QuantumCircuit(q) iqft(c,q,n) shiftBases(c,q,n,1) qft(c,q,n) c.draw(output='mpl') circ = deepcopy(circ_init) qr = circ.qregs shiftBases(circ,qr[0],n_qubits,1) circ.h(qr[0][0]) shiftBases(circ,qr[0],n_qubits,-1) simulator = BasicAer.get_backend('statevector_simulator') result = execute(circ, simulator).result() final_state_vector = result.get_statevector(circ) edge_odd = np.real(final_state_vector) n_rows = np.int_(np.sqrt(len(edge_odd))) edge_odd = edge_odd.reshape(n_rows, -1) edge_odd[:,1::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge_odd) ax[1].imshow(im) edge = edge_even + edge_odd fig, ax = plt.subplots(1,2) ax[0].imshow(edge) ax[1].imshow(im)
https://github.com/derivation/ThinkQuantum
derivation
import numpy as np from numpy import pi import matplotlib.pyplot as plt import matplotlib.image as mpimg from skimage.transform import resize filename = './schrodin_yang.png' im = mpimg.imread(filename) n_pixels = 2**5 im = resize(im, (n_pixels, n_pixels)) data = im[:,:,0].ravel() fig, ax = plt.subplots() ax.imshow(im) n_qubits = int(np.log2(len(data))) from qiskit_aqua.components.initial_states import Custom init_state = Custom(n_qubits, state_vector=data) circ = init_state.construct_circuit('circuit') qr = circ.qregs # circ.draw() circ.h(qr[0][0]) from qiskit import BasicAer, execute simulator = BasicAer.get_backend('statevector_simulator') sim_result = execute(circ, simulator).result() final_state = sim_result.get_statevector(circ) edge = np.real(final_state) n_rows = int(np.sqrt(len(edge))) n_cols = n_rows edge = edge.reshape(n_rows, n_cols) edge[:,::2] = 0 fig, ax = plt.subplots(1,2) ax[0].imshow(edge) ax[1].imshow(im)
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
%pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git --upgrade # qc-grader should be 0.18.12 (or higher) import qc_grader qc_grader.__version__ ### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are on 3.10 > python < 3.12 %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U import qisit ### INSTALL QISKIT: Locally on a Mac or Linux ### %pip install 'qiskit[visualization]'==1.0.2 ### Install the other required packages as well %pip install qiskit_aer %pip install qiskit_ibm_runtime %pip install matplotlib %pip install pylatexenc %pip install qiskit-transpiler-service %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git ### CHECK OTHER DEPENDENCIES %pip show pylatexenc matplotlib qc_grader #qc-grader should be 0.18.8 (or higher) ### Install Qiskit, if needed %pip install qiskit[visualization]==1.0.2 %pip install qiskit_aer %pip install qiskit_ibm_runtime %pip install matplotlib %pip install pylatexenc %pip install qiskit-transpiler-service %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git ### Install Qiskit and relevant packages, if needed %pip install qiskit[visualization]==1.0.2 %pip install qiskit_ibm_runtime %pip install qiskit_aer %pip install qiskit-transpiler-service %pip install graphviz %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U %pip install circuit-knitting-toolbox -U ### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are using python 3.10 or 3.11 for compatibility of the required packages %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-transpiler-service %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U import qc_grader qc_grader.__version__ %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U import qc_grader qc_grader.__version__ %pip install -r git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
from qiskit import QuantumCircuit # Create a new circuit with a single qubit qc = QuantumCircuit(1) # Add a Not gate to qubit 0 qc.x(0) # Return a drawing of the circuit using MatPlotLib ("mpl"). This is the # last line of the cell, so the drawing appears in the cell output. qc.draw("mpl") ### CHECK QISKIT VERSION import qiskit qiskit.__version__ ### CHECK OTHER DEPENDENCIES %pip show pylatexenc matplotlib qc_grader #qc-grader should be 0.18.8 (or higher) ### Imports from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import EstimatorV2 as Estimator from qiskit_aer import AerSimulator import matplotlib.pyplot as plt from qc_grader.challenges.iqc_2024 import grade_lab0_ex1 # Create a new circuit with two qubits qc = QuantumCircuit(2) # Add a Hadamard gate to qubit 0 qc.h(0) # Perform a CNOT gate on qubit 1, controlled by qubit 0 qc.cx(0, 1) # Return a drawing of the circuit using MatPlotLib ("mpl"). This is the # last line of the cell, so the drawing appears in the cell output. qc.draw("mpl") # The ZZ applies a Z operator on qubit 0, and a Z operator on qubit 1 ZZ = SparsePauliOp('ZZ') # The ZI applies a Z operator on qubit 0, and an Identity operator on qubit 1 ZI = SparsePauliOp('ZI') # The IX applies an Identity operator on qubit 0, and an X operator on qubit 1 IX = SparsePauliOp('IX') ### Write your code below here ### IZ = SparsePauliOp('IZ') XX = SparsePauliOp('XX') XI = SparsePauliOp('XI') ### Follow the same naming convention we used above ## Don't change any code past this line, but remember to run the cell. observables = [IZ, IX, ZI, XI, ZZ, XX] # Submit your answer using following code grade_lab0_ex1(observables) # Set up the Estimator estimator = Estimator(backend=AerSimulator()) # Submit the circuit to Estimator pub = (qc, observables) job = estimator.run(pubs=[pub]) # Collect the data data = ['IZ', 'IX', 'ZI', 'XI', 'ZZ', 'XX'] values = job.result()[0].data.evs # Set up our graph container = plt.plot(data, values, '-o') # Label each axis plt.xlabel('Observables') plt.ylabel('Values') # Draw the final graph plt.show() container = plt.bar(data, values, width=0.8) plt.xlabel('Observables') plt.ylabel('Values') plt.show()
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit_textbook.problems import dj_problem_oracle def lab1_ex1(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) return qc state = Statevector.from_instruction(lab1_ex1()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex1 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex1(lab1_ex1()) def lab1_ex2(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) return qc state = Statevector.from_instruction(lab1_ex2()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex2 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex2(lab1_ex2()) def lab1_ex3(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) qc.h(0) return qc state = Statevector.from_instruction(lab1_ex3()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex3 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex3(lab1_ex3()) def lab1_ex4(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.sdg(0) return qc state = Statevector.from_instruction(lab1_ex4()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex4 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex4(lab1_ex4()) def lab1_ex5(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.cx(0,1) qc.x(0) return qc qc = lab1_ex5() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex5 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex5(lab1_ex5()) qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0 qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1 backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def lab1_ex6(): # # # FILL YOUR CODE IN HERE # # qc = QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cx(1,2) qc.y(1) return qc qc = lab1_ex6() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex6 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex6(lab1_ex6()) oraclenr = 4 # determines the oracle (can range from 1 to 5) oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles oracle.name = "DJ-Oracle" def dj_classical(n, input_str): # build a quantum circuit with n qubits and 1 classical readout bit dj_circuit = QuantumCircuit(n+1,1) # Prepare the initial state corresponding to your input bit string for i in range(n): if input_str[i] == '1': dj_circuit.x(i) # append oracle dj_circuit.append(oracle, range(n+1)) # measure the fourth qubit dj_circuit.measure(n,0) return dj_circuit n = 4 # number of qubits input_str = '1111' dj_circuit = dj_classical(n, input_str) dj_circuit.draw() # draw the circuit input_str = '1111' dj_circuit = dj_classical(n, input_str) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit, qasm_sim) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) def lab1_ex7(): min_nr_inputs = 2 max_nr_inputs = 9 return [min_nr_inputs, max_nr_inputs] from qc_grader import grade_lab1_ex7 # Note that the grading function is expecting a list of two integers grade_lab1_ex7(lab1_ex7()) n=4 def psi_0(n): qc = QuantumCircuit(n+1,n) # Build the state (|00000> - |10000>)/sqrt(2) # # # FILL YOUR CODE IN HERE # # qc.x(4) qc.h(4) return qc dj_circuit = psi_0(n) dj_circuit.draw() def psi_1(n): # obtain the |psi_0> = |00001> state qc = psi_0(n) # create the superposition state |psi_1> # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # # qc.barrier() return qc dj_circuit = psi_1(n) dj_circuit.draw() def psi_2(oracle,n): # circuit to obtain psi_1 qc = psi_1(n) # append the oracle qc.append(oracle, range(n+1)) return qc dj_circuit = psi_2(oracle, n) dj_circuit.draw() def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25]) qc = psi_2(oracle, n) # apply n-fold hadamard gate # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # add the measurement by connecting qubits to classical bits # # qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) # # return qc dj_circuit = lab1_ex8(oracle, n) dj_circuit.draw() from qc_grader import grade_lab1_ex8 # Note that the grading function is expecting a quantum circuit with measurements grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n)) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
import networkx as nx import numpy as np import plotly.graph_objects as go import matplotlib as mpl import pandas as pd from IPython.display import clear_output from plotly.subplots import make_subplots from matplotlib import pyplot as plt from qiskit import Aer from qiskit import QuantumCircuit from qiskit.visualization import plot_state_city from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM from time import time from copy import copy from typing import List from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs mpl.rcParams['figure.dpi'] = 300 from qiskit.circuit import Parameter, ParameterVector #Parameters are initialized with a simple string identifier parameter_0 = Parameter('θ[0]') parameter_1 = Parameter('θ[1]') circuit = QuantumCircuit(1) #We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates circuit.ry(theta = parameter_0, qubit = 0) circuit.rx(theta = parameter_1, qubit = 0) circuit.draw('mpl') parameter = Parameter('θ') circuit = QuantumCircuit(1) circuit.ry(theta = parameter, qubit = 0) circuit.rx(theta = parameter, qubit = 0) circuit.draw('mpl') #Set the number of layers and qubits n=3 num_layers = 2 #ParameterVectors are initialized with a string identifier and an integer specifying the vector length parameters = ParameterVector('θ', n*(num_layers+1)) circuit = QuantumCircuit(n, n) for layer in range(num_layers): #Appending the parameterized Ry gates using parameters from the vector constructed above for i in range(n): circuit.ry(parameters[n*layer+i], i) circuit.barrier() #Appending the entangling CNOT gates for i in range(n): for j in range(i): circuit.cx(j,i) circuit.barrier() #Appending one additional layer of parameterized Ry gates for i in range(n): circuit.ry(parameters[n*num_layers+i], i) circuit.barrier() circuit.draw('mpl') print(circuit.parameters) #Create parameter dictionary with random values to bind param_dict = {parameter: np.random.random() for parameter in parameters} print(param_dict) #Assign parameters using the assign_parameters method bound_circuit = circuit.assign_parameters(parameters = param_dict) bound_circuit.draw('mpl') new_parameters = ParameterVector('Ψ',9) new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)]) new_circuit.draw('mpl') #Run the circuit with assigned parameters on Aer's statevector simulator simulator = Aer.get_backend('statevector_simulator') result = simulator.run(bound_circuit).result() statevector = result.get_statevector(bound_circuit) plot_state_city(statevector) #The following line produces an error when run because 'circuit' still contains non-assigned parameters #result = simulator.run(circuit).result() for key in graphs.keys(): print(key) graph = nx.Graph() #Add nodes and edges graph.add_nodes_from(np.arange(0,6,1)) edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)] graph.add_weighted_edges_from(edges) graphs['custom'] = graph #Display widget display_maxcut_widget(graphs['custom']) def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float: """ Computes the maxcut cost function value for a given graph and cut represented by some bitstring Args: graph: The graph to compute cut values for bitstring: A list of integer values '0' or '1' specifying a cut of the graph Returns: The value of the cut """ #Get the weight matrix of the graph weight_matrix = nx.adjacency_matrix(graph).toarray() size = weight_matrix.shape[0] value = 0. #INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE for i in range(size): for j in range(size): value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j]) return value def plot_maxcut_histogram(graph: nx.Graph) -> None: """ Plots a bar diagram with the values for all possible cuts of a given graph. Args: graph: The graph to compute cut values for """ num_vars = graph.number_of_nodes() #Create list of bitstrings and corresponding cut values bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)] values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings] #Sort both lists by largest cut value values, bitstrings = zip(*sorted(zip(values, bitstrings))) #Plot bar diagram bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value'))) fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600)) fig.show() plot_maxcut_histogram(graph = graphs['custom']) from qc_grader import grade_lab2_ex1 bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE # Note that the grading function is expecting a list of integers '0' and '1' grade_lab2_ex1(bitstring) from qiskit_optimization import QuadraticProgram quadratic_program = QuadraticProgram('sample_problem') print(quadratic_program.export_as_lp_string()) quadratic_program.binary_var(name = 'x_0') quadratic_program.integer_var(name = 'x_1') quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8) quadratic = [[0,1,2],[3,4,5],[0,1,2]] linear = [10,20,30] quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5) print(quadratic_program.export_as_lp_string()) def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram: """Constructs a quadratic program from a given graph for a MaxCut problem instance. Args: graph: Underlying graph of the problem. Returns: QuadraticProgram """ #Get weight matrix of graph weight_matrix = nx.adjacency_matrix(graph) shape = weight_matrix.shape size = shape[0] #Build qubo matrix Q from weight matrix W qubo_matrix = np.zeros((size, size)) qubo_vector = np.zeros(size) for i in range(size): for j in range(size): qubo_matrix[i, j] -= weight_matrix[i, j] for i in range(size): for j in range(size): qubo_vector[i] += weight_matrix[i,j] #INSERT YOUR CODE HERE quadratic_program=QuadraticProgram('sample_problem') for i in range(size): quadratic_program.binary_var(name='x_{}'.format(i)) quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector) return quadratic_program quadratic_program = quadratic_program_from_graph(graphs['custom']) print(quadratic_program.export_as_lp_string()) from qc_grader import grade_lab2_ex2 # Note that the grading function is expecting a quadratic program grade_lab2_ex2(quadratic_program) def qaoa_circuit(qubo: QuadraticProgram, p: int = 1): """ Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers. Args: qubo: The quadratic program instance p: The number of layers in the QAOA circuit Returns: The parameterized QAOA circuit """ size = len(qubo.variables) qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True) qubo_linearity = qubo.objective.linear.to_array() #Prepare the quantum and classical registers qaoa_circuit = QuantumCircuit(size,size) #Apply the initial layer of Hadamard gates to all qubits qaoa_circuit.h(range(size)) #Create the parameters to be used in the circuit gammas = ParameterVector('gamma', p) betas = ParameterVector('beta', p) #Outer loop to create each layer for i in range(p): #Apply R_Z rotational gates from cost layer #INSERT YOUR CODE HERE for j in range(size): qubo_matrix_sum_of_col = 0 for k in range(size): qubo_matrix_sum_of_col+= qubo_matrix[j][k] qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j) #Apply R_ZZ rotational gates for entangled qubit rotations from cost layer #INSERT YOUR CODE HERE for j in range(size): for k in range(size): if j!=k: qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k) # Apply single qubit X - rotations with angle 2*beta_i to all qubits #INSERT YOUR CODE HERE for j in range(size): qaoa_circuit.rx(2*betas[i],j) return qaoa_circuit quadratic_program = quadratic_program_from_graph(graphs['custom']) custom_circuit = qaoa_circuit(qubo = quadratic_program) test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters)) from qc_grader import grade_lab2_ex3 # Note that the grading function is expecting a quantum circuit grade_lab2_ex3(test) from qiskit.algorithms import QAOA from qiskit_optimization.algorithms import MinimumEigenOptimizer backend = Aer.get_backend('statevector_simulator') qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1]) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) quadratic_program = quadratic_program_from_graph(graphs['custom']) result = eigen_optimizer.solve(quadratic_program) print(result) def plot_samples(samples): """ Plots a bar diagram for the samples of a quantum algorithm Args: samples """ #Sort samples by probability samples = sorted(samples, key = lambda x: x.probability) #Get list of probabilities, function values and bitstrings probabilities = [sample.probability for sample in samples] values = [sample.fval for sample in samples] bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples] #Plot bar diagram sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value'))) fig = go.Figure( data=sample_plot, layout = dict( xaxis=dict( type = 'category' ) ) ) fig.show() plot_samples(result.samples) graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name]) trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]} offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum() def callback(eval_count, params, mean, std_dev): trajectory['beta_0'].append(params[1]) trajectory['gamma_0'].append(params[0]) trajectory['energy'].append(-mean + offset) optimizers = { 'cobyla': COBYLA(), 'slsqp': SLSQP(), 'adam': ADAM() } qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) result = eigen_optimizer.solve(quadratic_program) fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples) fig.show() graph_name = 'custom' quadratic_program = quadratic_program_from_graph(graphs[graph_name]) #Create callback to record total number of evaluations max_evals = 0 def callback(eval_count, params, mean, std_dev): global max_evals max_evals = eval_count #Create empty lists to track values energies = [] runtimes = [] num_evals=[] #Run QAOA for different values of p for p in range(1,10): print(f'Evaluating for p = {p}...') qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback) eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa) start = time() result = eigen_optimizer.solve(quadratic_program) runtimes.append(time()-start) num_evals.append(max_evals) #Calculate energy of final state from samples avg_value = 0. for sample in result.samples: avg_value += sample.probability*sample.fval energies.append(avg_value) #Create and display plots energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma')) runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma')) num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma')) fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations']) fig.update_layout(width=1800,height=600, showlegend=False) fig.add_trace(energy_plot, row=1, col=1) fig.add_trace(runtime_plot, row=1, col=2) fig.add_trace(num_evals_plot, row=1, col=3) clear_output() fig.show() def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None): num_shots = 1000 seed = 42 simulator = Aer.get_backend('qasm_simulator') simulator.set_options(seed_simulator = 42) #Generate circuit circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1) circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes())) #Create dictionary with precomputed cut values for all bitstrings cut_values = {} size = graph.number_of_nodes() for i in range(2**size): bitstr = '{:b}'.format(i).rjust(size, '0')[::-1] x = [int(bit) for bit in bitstr] cut_values[bitstr] = maxcut_cost_fn(graph, x) #Perform grid search over all parameters data_points = [] max_energy = None for beta in np.linspace(0,np.pi, 50): for gamma in np.linspace(0, 4*np.pi, 50): bound_circuit = circuit.assign_parameters([beta, gamma]) result = simulator.run(bound_circuit, shots = num_shots).result() statevector = result.get_counts(bound_circuit) energy = 0 measured_cuts = [] for bitstring, count in statevector.items(): measured_cuts = measured_cuts + [cut_values[bitstring]]*count if cvar is None: #Calculate the mean of all cut values energy = sum(measured_cuts)/num_shots else: #raise NotImplementedError() #INSERT YOUR CODE HERE measured_cuts = sorted(measured_cuts, reverse = True) for w in range(int(cvar*num_shots)): energy += measured_cuts[w]/int((cvar*num_shots)) #Update optimal parameters if max_energy is None or energy > max_energy: max_energy = energy optimum = {'beta': beta, 'gamma': gamma, 'energy': energy} #Update data data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy}) #Create and display surface plot from data_points df = pd.DataFrame(data_points) df = df.pivot(index='beta', columns='gamma', values='energy') matrix = df.to_numpy() beta_values = df.index.tolist() gamma_values = df.columns.tolist() surface_plot = go.Surface( x=gamma_values, y=beta_values, z=matrix, coloraxis = 'coloraxis' ) fig = go.Figure(data = surface_plot) fig.show() #Return optimum return optimum graph = graphs['custom'] optimal_parameters = plot_qaoa_energy_landscape(graph = graph) print('Optimal parameters:') print(optimal_parameters) optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2) print(optimal_parameters) from qc_grader import grade_lab2_ex4 # Note that the grading function is expecting a python dictionary # with the entries 'beta', 'gamma' and 'energy' grade_lab2_ex4(optimal_parameters)
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# qc-grader should be 0.18.10 (or higher) import qc_grader qc_grader.__version__ # Imports import numpy as np import matplotlib.pyplot as plt from qiskit.circuit.library import EfficientSU2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import QiskitRuntimeService from qiskit_transpiler_service.transpiler_service import TranspilerService # Import for grader from qc_grader.challenges.iqc_2024 import grade_lab3_ait_ex1, grade_lab3_ait_ex2 NUM_QUBITS = 61 circuit = EfficientSU2(NUM_QUBITS, entanglement="circular", reps=1).decompose() print(f"Original circuit -> Depth: {circuit.depth()}, CNOTs: {circuit.num_nonlocal_gates()}") circuit.draw(fold=-1, output="mpl", style="iqp", scale=0.2) # Load saved credentials service = QiskitRuntimeService() transpiler_ai_false = TranspilerService( # Add your code here backend_name="ibm_brisbane", ai="false", optimization_level=3, ) # Submit your answer using following code grade_lab3_ait_ex1(transpiler_ai_false) # Expected result type: TranspilerService circuit_ai_false = transpiler_ai_false.run(circuit) print(f"Transpiled without AI -> Depth: {circuit_ai_false.depth()}, CNOTs: {circuit_ai_false.num_nonlocal_gates()}") circuit_ai_false.draw(fold=-1, output="mpl", scale=0.2) transpiler_ai_true = TranspilerService( # Add your code here backend_name="ibm_brisbane", ai="true", optimization_level=3, ) # Submit your answer using following code grade_lab3_ait_ex2(transpiler_ai_true) # Expected result type: TranspilerService circuit_ai_true = transpiler_ai_true.run(circuit) print(f"Transpiled with AI -> Depth: {circuit_ai_true.depth()}, CNOTs: {circuit_ai_true.num_nonlocal_gates()}") circuit_ai_true.draw(fold=-1, output="mpl", scale=0.2) # Transpiling locally using Qiskit SDK service = QiskitRuntimeService() backend = service.backend("ibm_sherbrooke") pm = generate_preset_pass_manager(backend=backend, optimization_level=3) # Run and compile results num_qubits = [11, 21, 41, 61, 81] num_cnots_local = [] num_cnots_with_ai = [] num_cnots_without_ai = [] for nq in num_qubits: circuit = EfficientSU2(nq, entanglement="circular", reps=1).decompose() # Using the Transpiler locally on Qiskit circuit_local = pm.run(circuit) # Using the transpiler service without AI circuit_without_ai = transpiler_ai_false.run(circuit) # Using the transpiler service with AI circuit_with_ai = transpiler_ai_true.run(circuit) num_cnots_local.append(circuit_local.num_nonlocal_gates()) num_cnots_without_ai.append(circuit_without_ai.num_nonlocal_gates()) num_cnots_with_ai.append(circuit_with_ai.num_nonlocal_gates()) plt.plot(num_qubits, num_cnots_with_ai, '.-') plt.plot(num_qubits, num_cnots_without_ai, '.-') plt.plot(num_qubits, num_cnots_local, '--') plt.xlabel("Number of qubits") plt.ylabel("CNOT count") plt.legend(["Qiskit Transpiler Service with AI", "Qiskit Transpiler Service without AI", "Qiskit SDK"])
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# please create a 3 qubit GHZ circuit # please create a 2 qubit ch gate with only cx and ry gate # Enter your prompt here - Delete this line
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
from qiskit.circuit.library import RealAmplitudes ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear') ansatz.draw('mpl', style='iqx') from qiskit.opflow import Z, I hamiltonian = Z ^ Z from qiskit.opflow import StateFn expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) import numpy as np point = np.random.random(ansatz.num_parameters) index = 2 from qiskit import Aer from qiskit.utils import QuantumInstance backend = Aer.get_backend('qasm_simulator') q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718) from qiskit.circuit import QuantumCircuit from qiskit.opflow import Z, X H = X ^ X U = QuantumCircuit(2) U.h(0) U.cx(0, 1) # YOUR CODE HERE expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U) matmult_result =expectation.eval() from qc_grader import grade_lab4_ex1 # Note that the grading function is expecting a complex number grade_lab4_ex1(matmult_result) from qiskit.opflow import CircuitSampler, PauliExpectation sampler = CircuitSampler(q_instance) # YOUR CODE HERE sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U) in_pauli_basis = PauliExpectation().convert(expectation) shots_result = sampler.convert(in_pauli_basis).eval() from qc_grader import grade_lab4_ex2 # Note that the grading function is expecting a complex number grade_lab4_ex2(shots_result) from qiskit.opflow import PauliExpectation, CircuitSampler expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) in_pauli_basis = PauliExpectation().convert(expectation) sampler = CircuitSampler(q_instance) def evaluate_expectation(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(in_pauli_basis, params=value_dict).eval() return np.real(result) eps = 0.2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps) print(finite_difference) from qiskit.opflow import Gradient expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('fin_diff', analytic=False, epsilon=eps) grad = shifter.convert(expectation, params=ansatz.parameters[index]) print(grad) value_dict = dict(zip(ansatz.parameters, point)) sampler.convert(grad, value_dict).eval().real eps = np.pi / 2 e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0 plus = point + eps * e_i minus = point - eps * e_i finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2 print(finite_difference) expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient() # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz) shifter = Gradient('lin_comb') # parameter-shift rule is the default grad = shifter.convert(expectation, params=ansatz.parameters[index]) sampler.convert(grad, value_dict).eval().real # initial_point = np.random.random(ansatz.num_parameters) initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341]) expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) gradient = Gradient().convert(expectation) gradient_in_pauli_basis = PauliExpectation().convert(gradient) sampler = CircuitSampler(q_instance) def evaluate_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here! return np.real(result) # Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import GradientDescent from qc_grader.gradient_descent import GradientDescent gd_loss = [] def gd_callback(nfevs, x, fx, stepsize): gd_loss.append(fx) gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback) x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters evaluate_expectation, # function to minimize gradient_function=evaluate_gradient, # function to evaluate the gradient initial_point=initial_point) # initial point import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['font.size'] = 14 plt.figure(figsize=(12, 6)) plt.plot(gd_loss, label='vanilla gradient descent') plt.axhline(-1, ls='--', c='tab:red', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend(); from qiskit.opflow import NaturalGradient expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz)) natural_gradient = NaturalGradient(regularization='ridge').convert(expectation) natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient) sampler = CircuitSampler(q_instance, caching="all") def evaluate_natural_gradient(x): value_dict = dict(zip(ansatz.parameters, x)) result = sampler.convert(natural_gradient, params=value_dict).eval() return np.real(result) print('Vanilla gradient:', evaluate_gradient(initial_point)) print('Natural gradient:', evaluate_natural_gradient(initial_point)) qng_loss = [] def qng_callback(nfevs, x, fx, stepsize): qng_loss.append(fx) qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback) x_opt, fx_opt, nfevs = qng.optimize(initial_point.size, evaluate_expectation, gradient_function=evaluate_natural_gradient, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() from qc_grader.spsa import SPSA spsa_loss = [] def spsa_callback(nfev, x, fx, stepsize, accepted): spsa_loss.append(fx) spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback) x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() # Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as: # from qiskit.algorithms.optimizers import QNSPSA from qc_grader.qnspsa import QNSPSA qnspsa_loss = [] def qnspsa_callback(nfev, x, fx, stepsize, accepted): qnspsa_loss.append(fx) fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation()) qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback) x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() autospsa_loss = [] def autospsa_callback(nfev, x, fx, stepsize, accepted): autospsa_loss.append(fx) autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback) x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size, evaluate_expectation, initial_point=initial_point) def plot_loss(): plt.figure(figsize=(12, 6)) plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent') plt.plot(qng_loss, 'tab:green', label='quantum natural gradient') plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA') plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA') plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA') plt.axhline(-1, c='tab:red', ls='--', label='target') plt.ylabel('loss') plt.xlabel('iterations') plt.legend() plot_loss() H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X) from qc_grader import grade_lab4_ex3 # Note that the grading function is expecting a Hamiltonian grade_lab4_ex3(H_tfi) from qiskit.circuit.library import EfficientSU2 efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2) tfi_sampler = CircuitSampler(q_instance) def evaluate_tfi(parameters): exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2)) value_dict = dict(zip(efficient_su2.parameters, parameters)) result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval() return np.real(result) # target energy tfi_target = -3.4939592074349326 # initial point for reproducibility tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282, 0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126, 0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325, 0.48311132, 0.43623886, 0.6371297 ]) tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None) tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init) tfi_minimum = tfi_result[1] print("Error:", np.abs(tfi_result[1] - tfi_target)) from qc_grader import grade_lab4_ex4 # Note that the grading function is expecting a floating point number grade_lab4_ex4(tfi_minimum) from qiskit_machine_learning.datasets import ad_hoc_data training_features, training_labels, test_features, test_labels = ad_hoc_data( training_size=20, test_size=10, n=2, one_hot=False, gap=0.5 ) # the training labels are in {0, 1} but we'll use {-1, 1} as class labels! training_labels = 2 * training_labels - 1 test_labels = 2 * test_labels - 1 def plot_sampled_data(): from matplotlib.patches import Patch from matplotlib.lines import Line2D import matplotlib.pyplot as plt plt.figure(figsize=(12,6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label in zip(test_features, test_labels): marker = 's' plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k') legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_sampled_data() from qiskit.circuit.library import ZZFeatureMap dim = 2 feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple! feature_map.draw('mpl', style='iqx') ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here! ansatz.draw('mpl', style='iqx') circuit = feature_map.compose(ansatz) circuit.draw('mpl', style='iqx') hamiltonian = Z ^ Z # global Z operators gd_qnn_loss = [] def gd_qnn_callback(*args): gd_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback) from qiskit_machine_learning.neural_networks import OpflowQNN qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), exp_val=PauliExpectation(), gradient=Gradient(), # <-- Parameter-Shift gradients quantum_instance=q_instance) from qiskit_machine_learning.algorithms import NeuralNetworkClassifier #initial_point = np.array([0.2, 0.1, 0.3, 0.4]) classifier = NeuralNetworkClassifier(qnn, optimizer=gd) classifier.fit(training_features, training_labels); predicted = classifier.predict(test_features) def plot_predicted(): from matplotlib.lines import Line2D plt.figure(figsize=(12, 6)) for feature, label in zip(training_features, training_labels): marker = 'o' color = 'tab:green' if label == -1 else 'tab:blue' plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) for feature, label, pred in zip(test_features, test_labels, predicted): marker = 's' color = 'tab:green' if pred == -1 else 'tab:blue' if label != pred: # mark wrongly classified plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5, facecolor='none', edgecolor='tab:red') plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color) legend_elements = [ Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15), Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15), Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10), Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10), Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15) ] plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7)) plt.title('Training & test data') plt.xlabel('$x$') plt.ylabel('$y$') plot_predicted() qng_qnn_loss = [] def qng_qnn_callback(*args): qng_qnn_loss.append(args[2]) gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback) qnn = OpflowQNN(qnn_expectation, input_params=list(feature_map.parameters), weight_params=list(ansatz.parameters), gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients! quantum_instance=q_instance) classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point) classifier.fit(training_features, training_labels); def plot_losses(): plt.figure(figsize=(12, 6)) plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients') plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients') plt.xlabel('iterations') plt.ylabel('loss') plt.legend(loc='best') plot_losses() from qiskit.opflow import I def sample_gradients(num_qubits, reps, local=False): """Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions. We sample 100 times for random parameters and compute the gradient of the first RY rotation gate. """ index = num_qubits - 1 # you can also exchange this for a local operator and observe the same! if local: operator = Z ^ Z ^ (I ^ (num_qubits - 2)) else: operator = Z ^ num_qubits # real amplitudes ansatz ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) # construct Gradient we want to evaluate for different values expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = Gradient().convert(expectation, params=ansatz.parameters[index]) # evaluate for 100 different, random parameter values num_points = 100 grads = [] for _ in range(num_points): # points are uniformly chosen from [0, pi] point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); from qiskit.opflow import NaturalGradient def sample_natural_gradients(num_qubits, reps): index = num_qubits - 1 operator = Z ^ num_qubits ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps) expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz)) grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``. # Hint: Check the ``sample_gradients`` function, this one is almost the same. grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index]) num_points = 100 grads = [] for _ in range(num_points): point = np.random.uniform(0, np.pi, ansatz.num_parameters) value_dict = dict(zip(ansatz.parameters, point)) grads.append(sampler.convert(grad, value_dict).eval()) return grads num_qubits = list(range(2, 13)) reps = num_qubits # number of layers = numbers of qubits natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)] fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients') plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = list(range(2, 13)) fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits] fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1) x = np.linspace(num_qubits[0], num_qubits[-1], 200) plt.figure(figsize=(12, 6)) plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth') plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth') plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth') plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}') plt.xlabel('number of qubits') plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$') plt.legend(loc='best'); num_qubits = 6 operator = Z ^ Z ^ (I ^ (num_qubits - 4)) def minimize(circuit, optimizer): initial_point = np.random.random(circuit.num_parameters) exp = StateFn(operator, is_measurement=True) @ StateFn(circuit) grad = Gradient().convert(exp) # pauli basis exp = PauliExpectation().convert(exp) grad = PauliExpectation().convert(grad) sampler = CircuitSampler(q_instance, caching="all") def loss(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(exp, values_dict).eval()) def gradient(x): values_dict = dict(zip(circuit.parameters, x)) return np.real(sampler.convert(grad, values_dict).eval()) return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point) circuit = RealAmplitudes(4, reps=1, entanglement='linear') circuit.draw('mpl', style='iqx') circuit.reps = 5 circuit.draw('mpl', style='iqx') def layerwise_training(ansatz, max_num_layers, optimizer): optimal_parameters = [] fopt = None for reps in range(1, max_num_layers): ansatz.reps = reps # bind already optimized parameters values_dict = dict(zip(ansatz.parameters, optimal_parameters)) partially_bound = ansatz.bind_parameters(values_dict) xopt, fopt, _ = minimize(partially_bound, optimizer) print('Circuit depth:', ansatz.depth(), 'best value:', fopt) optimal_parameters += list(xopt) return fopt, optimal_parameters ansatz = RealAmplitudes(4, entanglement='linear') optimizer = GradientDescent(maxiter=50) np.random.seed(12) fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are on 3.10 > python < 3.12 ''' %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U ''' %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U # Import all in one cell import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import RealAmplitudes from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.visualization import plot_gate_map, plot_circuit_layout, plot_distribution from qiskit.circuit import ParameterVector from qiskit_aer import AerSimulator from qiskit_ibm_runtime import ( QiskitRuntimeService, EstimatorV2 as Estimator, SamplerV2 as Sampler, EstimatorOptions ) import warnings warnings.filterwarnings('ignore') # qc-grader should be 0.18.13 (or higher) import qc_grader qc_grader.__version__ from qc_grader.challenges.iqc_2024 import grade_lab_bonus_ex1, grade_lab_bonus_ex2, grade_lab_bonus_ex3 def old_amplitude_embedding(num_qubits, bird_index): """Create amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ def generate_GHZ(qc): qc.h(0) for i, j in zip(range(num_qubits-1), range(1,num_qubits)): qc.cx(i, j) ### Write your code below here ### qc = QuantumCircuit(num_qubits) if bird_index < 5: generate_GHZ(qc) bin_string = format(bird_index, '0{0}b'.format(num_qubits)) for i in reversed(range(len(bin_string))): if bin_string[i] == '1': qc.x(num_qubits-i-1) ### Don't change any code past this line ### return qc num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_osaka") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 # You can check different birds by changing the index qc = old_amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) def new_amplitude_embedding(num_qubits, bird_index): """Create efficient amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ ### Write your code below here ### ### Don't change any code past this line ### return qc num_qubits = 50 index = 0 # Change to different values for testing qc = new_amplitude_embedding(num_qubits, index) qc.measure_all() # Define the backend and the pass manager aer_sim = AerSimulator(method='matrix_product_state') pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(qc) # Define the sampler with the number of shots sampler = Sampler(backend=aer_sim) result = sampler.run([isa_circuit]).result() samp_dist = result[0].data.meas.get_counts() plot_distribution(samp_dist, figsize=(10, 3)) num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_kyoto") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 #You can check different birds by changing the index qc = new_amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab_bonus_ex1(new_amplitude_embedding(50,3)) # Expected answer type: QuantumCircuit def generate_old_ansatz(qubits): qc = RealAmplitudes(qubits, reps=1, entanglement='pairwise') return qc num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_kyoto") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 # You can check different birds by changing the index qc = new_amplitude_embedding(num_qubits, index_bird) ansatz = generate_old_ansatz(num_qubits) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) transpiled_qc = pm.run(qc.compose(ansatz)) print('Depth new mapping + old ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) # transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) def generate_ansatz(num_qubits): """Generate a `RealAmplitudes` ansatz where all qubits are entangled with each other Parameters: num_qubits (int): Number of qubits for the ansatz Returns: qc (QuantumCircuit): Quantum circuit with the generated ansatz """ ### Write your code below here ### ### Don't change any code past this line ### return qc index_bird = 0 # You can check different birds by changing the index new_mapping_qc = new_amplitude_embedding(num_qubits, index_bird) ansatz = generate_ansatz(num_qubits) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) transpiled_qc = pm.run(new_mapping_qc.compose(ansatz)) print('Depth new mapping + new ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) # transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab_bonus_ex2(transpiled_qc) # Expected answer type: QuantumCircuit # Generate this to match your ansatz source_list = # Add your code here def generalize_optimal_params(num_qubits, ansatz, source_list): """Generate a `list of optimal parameters for N qubits Parameters: num_qubits (int): Number of qubits for the ansatz ansatz (QuantumCircuit): Ansatz for our VQC source_list (list): List of qubits used as source to entangle other qubits Returns: opt_params (list): List of optimal parameters generated for N qubits """ opt_params = np.zeros(ansatz.num_parameters) for i in range(ansatz.num_parameters//2): if i in source_list: opt_params[i] = np.pi return opt_params def test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend): """Tests the shallow VQC on a QPU Parameters: num_qubits (int): Number of qubits for the ansatz list_labels (list): List of labels obs: (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Options for Estimator primitive backend (Backend): Real backend from IBM Quantum to run the job Returns: job_id (str): Job ID for Quantum job """ ### Write your code below here ### ### Don't change any code past this line ### return job_id def retrieve_job(job_id): """Retrieve test results from job id Parameters: job_id (str): Job ID Returns: results_test (list): List of test results errors_test (list): List of test errors """ job = service.job(job_id) results_test = [] errors_test = [] for result in job.result(): results_test.append(abs(abs(result.data.evs)-1)) #COST FUNCTION HAS A -1 NOW!!! errors_test.append(abs(result.data.stds)) return results_test, errors_test def test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, backend): """Tests the shallow VQC on a QPU Parameters: num_qubits (int): Number of qubits for the ansatz list_labels (list): List of labels obs: (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Options for Estimator primitive backend (Backend): AerSimulator backend to run the job Returns: results_test (list): List of test results """ results_test = [] ### Write your code below here ### ### Don't change any code past this line ### result = job.result()[0].data.evs results_test.append(abs(abs(result)-1)) # COST FUNCTION NOW HAS A -1!!! return results_test def compute_performance(result_list, list_labels): """Return the performance of the classifier Parameters: result_list (list): List of results list_labels (list): List of labels Returns: performance (float): Performance of the classifier """ ### Write your code below here ### ### Don't change any code past this line ### return performance num_qubits = 50 aer_sim = AerSimulator(method='matrix_product_state') pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(new_mapping_qc) list_labels = np.append(np.ones(5), np.zeros(5)) obs = SparsePauliOp("Z"*num_qubits) opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list) options = EstimatorOptions() results_test_aer_sim = test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, aer_sim) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data MPS') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for resilience 0: {compute_performance(results_test_aer_sim, list_labels)}") ax.plot(results_test_aer_sim, 'o-', color='tab:red', label='MPS Num qubits = ' + str(num_qubits)) ax.plot(list_labels, 'k-', label='Labels') ax.legend() # Submit your answer using following code grade_lab_bonus_ex3(results_test_aer_sim) # Expected variable types: List service = QiskitRuntimeService() backend = service.backend("select_your_device") # RUN JOBS num_qubits = 50 obs = SparsePauliOp("Z"*num_qubits) opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list) for resilience in [0,1]: DD = True options = EstimatorOptions(default_shots = 5_000, optimization_level=0, resilience_level=resilience) options.dynamical_decoupling.enable = DD options.dynamical_decoupling.sequence_type = 'XpXm' # OPTIONAL # options.resilience.zne_mitigation = True # options.resilience.zne.noise_factors = (1, 1.2, 1.5) # options.resilience.zne.extrapolator = ('exponential', 'linear', 'polynomial_degree_2') #order matters job_id = test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend) results_test_0_DD, errors_test_0_DD = retrieve_job('Enter your JobID for resilience level 0') results_test_1_DD, errors_test_1_DD = retrieve_job('Enter your JobID for resilience level 1') fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title(f'Test of a {num_qubits} qubit VQC on {backend.name}') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for no DD + no TREX: {compute_performance(results_test_0_DD, list_labels):.3f}") print(f"Performance for DD + TREX: {compute_performance(results_test_1_DD, list_labels):.3f}") ax.errorbar(range(10), results_test_0_DD, fmt='--o', yerr=errors_test_0_DD, color='tab:orange', label=f'{backend.name} RL=0 shots={options.default_shots} DD={options.dynamical_decoupling.enable}') ax.errorbar(range(10), results_test_1_DD, fmt='--o', yerr=errors_test_1_DD, color='tab:blue', label=f'{backend.name} RL=1 shots={options.default_shots} DD={options.dynamical_decoupling.enable}') ax.plot(list_labels, 'k-', label='Labels') ax.legend()
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# transpile_parallel.py from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_transpiler_service.transpiler_service import TranspilerService from qiskit_serverless import get_arguments, save_result, distribute_task, get from qiskit_ibm_runtime import QiskitRuntimeService from timeit import default_timer as timer @distribute_task(target={"cpu": 2}) def transpile_parallel(circuit: QuantumCircuit, config): """Distributed transpilation for an abstract circuit into an ISA circuit for a given backend.""" transpiled_circuit = config.run(circuit) return transpiled_circuit # Get program arguments arguments = get_arguments() circuits = arguments.get("circuits") backend_name = arguments.get("backend_name") # Get backend service = QiskitRuntimeService(channel="ibm_quantum") backend = service.get_backend(backend_name) # Define Configs optimization_levels = [1,2,3] pass_managers = [generate_preset_pass_manager(optimization_level=level, backend=backend) for level in optimization_levels] transpiler_services = [ {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': False, 'optimization_level': 3}, {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': True, 'optimization_level': 3} ] configs = pass_managers + transpiler_services # Start process print("Starting timer") start = timer() # run distributed tasks as async function # we get task references as a return type sample_task_references = [] for circuit in circuits: sample_task_references.append([transpile_parallel(circuit, config) for config in configs]) # now we need to collect results from task references results = get([task for subtasks in sample_task_references for task in subtasks]) end = timer() # Record execution time execution_time_serverless = end-start print("Execution time: ", execution_time_serverless) save_result({ "transpiled_circuits": results, "execution_time" : execution_time_serverless })
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
import json import logging import numpy as np import warnings from functools import wraps from typing import Any, Callable, Optional, Tuple, Union from qiskit import IBMQ, QuantumCircuit, assemble from qiskit.circuit import Barrier, Gate, Instruction, Measure from qiskit.circuit.library import UGate, U3Gate, CXGate from qiskit.providers.ibmq import AccountProvider, IBMQProviderError from qiskit.providers.ibmq.job import IBMQJob def get_provider() -> AccountProvider: with warnings.catch_warnings(): warnings.simplefilter('ignore') ibmq_logger = logging.getLogger('qiskit.providers.ibmq') current_level = ibmq_logger.level ibmq_logger.setLevel(logging.ERROR) # get provider try: provider = IBMQ.get_provider() except IBMQProviderError: provider = IBMQ.load_account() ibmq_logger.setLevel(current_level) return provider def get_job(job_id: str) -> Optional[IBMQJob]: try: job = get_provider().backends.retrieve_job(job_id) return job except Exception: pass return None def circuit_to_json(qc: QuantumCircuit) -> str: class _QobjEncoder(json.encoder.JSONEncoder): def default(self, obj: Any) -> Any: if isinstance(obj, np.ndarray): return obj.tolist() if isinstance(obj, complex): return (obj.real, obj.imag) return json.JSONEncoder.default(self, obj) return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder) def circuit_to_dict(qc: QuantumCircuit) -> dict: qobj = assemble(qc) return qobj.to_dict() def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]: try: job_id = job.job_id() if isinstance(job, IBMQJob) else job download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url'] result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url'] return download_url, result_url except Exception: return None, None def cached(key_function: Callable) -> Callable: def _decorator(f: Any) -> Callable: f.__cache = {} @wraps(f) def _decorated(*args: Any, **kwargs: Any) -> int: key = key_function(*args, **kwargs) if key not in f.__cache: f.__cache[key] = f(*args, **kwargs) return f.__cache[key] return _decorated return _decorator def gate_key(gate: Gate) -> Tuple[str, int]: return gate.name, gate.num_qubits @cached(gate_key) def gate_cost(gate: Gate) -> int: if isinstance(gate, (UGate, U3Gate)): return 1 elif isinstance(gate, CXGate): return 10 elif isinstance(gate, (Measure, Barrier)): return 0 return sum(map(gate_cost, (g for g, _, _ in gate.definition.data))) def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int: print('Computing cost...') circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction): circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') return sum(map(gate_cost, (g for g, _, _ in circuit_data))) def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool: circuit_data = None if isinstance(circuit, QuantumCircuit): circuit_data = circuit.data elif isinstance(circuit, Instruction) and circuit.definition is not None: circuit_data = circuit.definition.data else: raise Exception(f'Unable to obtain circuit data from {type(circuit)}') for g, _, _ in circuit_data: if isinstance(g, (Barrier, Measure)): continue elif isinstance(g, Gate): if g.num_qubits > 1: return True elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g): return True return False
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ import logging import functools import numpy as np from qiskit import ClassicalRegister, QuantumCircuit from qiskit.aqua.algorithms.adaptive.vq_algorithm import VQAlgorithm from qiskit.aqua import AquaError, Pluggable, PluggableType, get_pluggable_class from qiskit.aqua.utils.backend_utils import is_aer_statevector_backend from qiskit.aqua.utils import find_regs_by_name logger = logging.getLogger(__name__) class VQE(VQAlgorithm): """ The Variational Quantum Eigensolver algorithm. See https://arxiv.org/abs/1304.3061 """ CONFIGURATION = { 'name': 'VQE', 'description': 'VQE Algorithm', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'vqe_schema', 'type': 'object', 'properties': { 'operator_mode': { 'type': 'string', 'default': 'matrix', 'oneOf': [ {'enum': ['matrix', 'paulis', 'grouped_paulis']} ] }, 'initial_point': { 'type': ['array', 'null'], "items": { "type": "number" }, 'default': None }, 'max_evals_grouped': { 'type': 'integer', 'default': 1 } }, 'additionalProperties': False }, 'problems': ['energy', 'ising'], 'depends': [ {'pluggable_type': 'optimizer', 'default': { 'name': 'L_BFGS_B' } }, {'pluggable_type': 'variational_form', 'default': { 'name': 'RYRZ' } }, ], } def __init__(self, operator, var_form, optimizer, operator_mode='matrix', initial_point=None, max_evals_grouped=1, aux_operators=None, callback=None): """Constructor. Args: operator (Operator): Qubit operator operator_mode (str): operator mode, used for eval of operator var_form (VariationalForm): parametrized variational form. optimizer (Optimizer): the classical optimization algorithm. initial_point (numpy.ndarray): optimizer initial point. max_evals_grouped (int): max number of evaluations performed simultaneously aux_operators (list of Operator): Auxiliary operators to be evaluated at each eigenvalue callback (Callable): a callback that can access the intermediate data during the optimization. Internally, four arguments are provided as follows the index of evaluation, parameters of variational form, evaluated mean, evaluated standard devation. """ self.validate(locals()) super().__init__(var_form=var_form, optimizer=optimizer, cost_fn=self._energy_evaluation, initial_point=initial_point) self._optimizer.set_max_evals_grouped(max_evals_grouped) self._callback = callback if initial_point is None: self._initial_point = var_form.preferred_init_points self._operator = operator self._operator_mode = operator_mode self._eval_count = 0 if aux_operators is None: self._aux_operators = [] else: self._aux_operators = [aux_operators] if not isinstance(aux_operators, list) else aux_operators logger.info(self.print_settings()) @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params (dict): parameters dictionary algo_input (EnergyInput): EnergyInput instance Returns: VQE: vqe object """ if algo_input is None: raise AquaError("EnergyInput instance is required.") operator = algo_input.qubit_op vqe_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) operator_mode = vqe_params.get('operator_mode') initial_point = vqe_params.get('initial_point') max_evals_grouped = vqe_params.get('max_evals_grouped') # Set up variational form, we need to add computed num qubits # Pass all parameters so that Variational Form can create its dependents var_form_params = params.get(Pluggable.SECTION_KEY_VAR_FORM) var_form_params['num_qubits'] = operator.num_qubits var_form = get_pluggable_class(PluggableType.VARIATIONAL_FORM, var_form_params['name']).init_params(params) # Set up optimizer opt_params = params.get(Pluggable.SECTION_KEY_OPTIMIZER) optimizer = get_pluggable_class(PluggableType.OPTIMIZER, opt_params['name']).init_params(params) return cls(operator, var_form, optimizer, operator_mode=operator_mode, initial_point=initial_point, max_evals_grouped=max_evals_grouped, aux_operators=algo_input.aux_ops) @property def setting(self): """Prepare the setting of VQE as a string.""" ret = "Algorithm: {}\n".format(self._configuration['name']) params = "" for key, value in self.__dict__.items(): if key != "_configuration" and key[0] == "_": if "initial_point" in key and value is None: params += "-- {}: {}\n".format(key[1:], "Random seed") else: params += "-- {}: {}\n".format(key[1:], value) ret += "{}".format(params) return ret def print_settings(self): """ Preparing the setting of VQE into a string. Returns: str: the formatted setting of VQE """ ret = "\n" ret += "==================== Setting of {} ============================\n".format(self.configuration['name']) ret += "{}".format(self.setting) ret += "===============================================================\n" ret += "{}".format(self._var_form.setting) ret += "===============================================================\n" ret += "{}".format(self._optimizer.setting) ret += "===============================================================\n" return ret def construct_circuit(self, parameter, backend=None, use_simulator_operator_mode=False): """Generate the circuits. Args: parameters (numpy.ndarray): parameters for variational form. backend (qiskit.BaseBackend): backend object. use_simulator_operator_mode (bool): is backend from AerProvider, if True and mode is paulis, single circuit is generated. Returns: [QuantumCircuit]: the generated circuits with Hamiltonian. """ input_circuit = self._var_form.construct_circuit(parameter) if backend is None: warning_msg = "Circuits used in VQE depends on the backend type, " from qiskit import BasicAer if self._operator_mode == 'matrix': temp_backend_name = 'statevector_simulator' else: temp_backend_name = 'qasm_simulator' backend = BasicAer.get_backend(temp_backend_name) warning_msg += "since operator_mode is '{}', '{}' backend is used.".format( self._operator_mode, temp_backend_name) logger.warning(warning_msg) circuit = self._operator.construct_evaluation_circuit(self._operator_mode, input_circuit, backend, use_simulator_operator_mode) return circuit def _eval_aux_ops(self, threshold=1e-12, params=None): if params is None: params = self.optimal_params wavefn_circuit = self._var_form.construct_circuit(params) circuits = [] values = [] params = [] for operator in self._aux_operators: if not operator.is_empty(): temp_circuit = QuantumCircuit() + wavefn_circuit circuit = operator.construct_evaluation_circuit(self._operator_mode, temp_circuit, self._quantum_instance.backend, self._use_simulator_operator_mode) params.append(operator.aer_paulis) else: circuit = None circuits.append(circuit) if len(circuits) > 0: to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, [c for c in circuits if c is not None]) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': params, 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for operator, circuit in zip(self._aux_operators, circuits): if circuit is None: mean, std = 0.0, 0.0 else: mean, std = operator.evaluate_with_result(self._operator_mode, circuit, self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean = mean.real if abs(mean.real) > threshold else 0.0 std = std.real if abs(std.real) > threshold else 0.0 values.append((mean, std)) if len(values) > 0: aux_op_vals = np.empty([1, len(self._aux_operators), 2]) aux_op_vals[0, :] = np.asarray(values) self._ret['aux_ops'] = aux_op_vals def _run(self): """ Run the algorithm to compute the minimum eigenvalue. Returns: Dictionary of results """ if not self._quantum_instance.is_statevector and self._operator_mode == 'matrix': logger.warning('Qasm simulation does not work on {} mode, changing ' 'the operator_mode to "paulis"'.format(self._operator_mode)) self._operator_mode = 'paulis' self._use_simulator_operator_mode = \ is_aer_statevector_backend(self._quantum_instance.backend) \ and self._operator_mode != 'matrix' self._quantum_instance.circuit_summary = True self._eval_count = 0 self._ret = self.find_minimum(initial_point=self.initial_point, var_form=self.var_form, cost_fn=self._energy_evaluation, optimizer=self.optimizer) if self._ret['num_optimizer_evals'] is not None and self._eval_count >= self._ret['num_optimizer_evals']: self._eval_count = self._ret['num_optimizer_evals'] self._eval_time = self._ret['eval_time'] logger.info('Optimization complete in {} seconds.\nFound opt_params {} in {} evals'.format( self._eval_time, self._ret['opt_params'], self._eval_count)) self._ret['eval_count'] = self._eval_count self._ret['energy'] = self.get_optimal_cost() self._ret['eigvals'] = np.asarray([self.get_optimal_cost()]) self._ret['eigvecs'] = np.asarray([self.get_optimal_vector()]) self._eval_aux_ops() return self._ret # This is the objective function to be passed to the optimizer that is uses for evaluation def _energy_evaluation(self, parameters): """ Evaluate energy at given parameters for the variational form. Args: parameters (numpy.ndarray): parameters for variational form. Returns: float or list of float: energy of the hamiltonian of each parameter. """ num_parameter_sets = len(parameters) // self._var_form.num_parameters circuits = [] parameter_sets = np.split(parameters, num_parameter_sets) mean_energy = [] std_energy = [] for idx in range(len(parameter_sets)): parameter = parameter_sets[idx] circuit = self.construct_circuit(parameter, self._quantum_instance.backend, self._use_simulator_operator_mode) circuits.append(circuit) to_be_simulated_circuits = functools.reduce(lambda x, y: x + y, circuits) if self._use_simulator_operator_mode: extra_args = {'expectation': { 'params': [self._operator.aer_paulis], 'num_qubits': self._operator.num_qubits} } else: extra_args = {} result = self._quantum_instance.execute(to_be_simulated_circuits, **extra_args) for idx in range(len(parameter_sets)): mean, std = self._operator.evaluate_with_result( self._operator_mode, circuits[idx], self._quantum_instance.backend, result, self._use_simulator_operator_mode) mean_energy.append(np.real(mean)) std_energy.append(np.real(std)) self._eval_count += 1 if self._callback is not None: self._callback(self._eval_count, parameter_sets[idx], np.real(mean), np.real(std)) logger.info('Energy evaluation {} returned {}'.format(self._eval_count, np.real(mean))) return mean_energy if len(mean_energy) > 1 else mean_energy[0] def get_optimal_cost(self): if 'opt_params' not in self._ret: raise AquaError("Cannot return optimal cost before running the algorithm to find optimal params.") return self._ret['min_val'] def get_optimal_circuit(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal circuit before running the algorithm to find optimal params.") return self._var_form.construct_circuit(self._ret['opt_params']) def get_optimal_vector(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal vector before running the algorithm to find optimal params.") qc = self.get_optimal_circuit() if self._quantum_instance.is_statevector: ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_statevector(qc, decimals=16) else: c = ClassicalRegister(qc.width(), name='c') q = find_regs_by_name(qc, 'q') qc.add_register(c) qc.barrier(q) qc.measure(q, c) ret = self._quantum_instance.execute(qc) self._ret['min_vector'] = ret.get_counts(qc) return self._ret['min_vector'] @property def optimal_params(self): if 'opt_params' not in self._ret: raise AquaError("Cannot find optimal params before running the algorithm.") return self._ret['opt_params']
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
from qiskit import QuantumCircuit # Create a new circuit with a single qubit qc = QuantumCircuit(1) # Add a Not gate to qubit 0 qc.x(0) # Return a drawing of the circuit using MatPlotLib ("mpl"). This is the # last line of the cell, so the drawing appears in the cell output. qc.draw("mpl") ### CHECK QISKIT VERSION import qiskit qiskit.__version__ ### CHECK OTHER DEPENDENCIES %pip show pylatexenc matplotlib qc_grader #qc-grader should be 0.18.8 (or higher) ### Imports from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import EstimatorV2 as Estimator from qiskit_aer import AerSimulator import matplotlib.pyplot as plt from qc_grader.challenges.iqc_2024 import grade_lab0_ex1 # Create a new circuit with two qubits qc = QuantumCircuit(2) # Add a Hadamard gate to qubit 0 qc.h(0) # Perform a CNOT gate on qubit 1, controlled by qubit 0 qc.cx(0, 1) # Return a drawing of the circuit using MatPlotLib ("mpl"). This is the # last line of the cell, so the drawing appears in the cell output. qc.draw("mpl") # The ZZ applies a Z operator on qubit 0, and a Z operator on qubit 1 ZZ = SparsePauliOp('ZZ') # The ZI applies a Z operator on qubit 0, and an Identity operator on qubit 1 ZI = SparsePauliOp('ZI') # The IX applies an Identity operator on qubit 0, and an X operator on qubit 1 IX = SparsePauliOp('IX') ### Write your code below here ### IZ = SparsePauliOp('IZ') XX = SparsePauliOp('XX') XI = SparsePauliOp('XI') ### Follow the same naming convention we used above ## Don't change any code past this line, but remember to run the cell. observables = [IZ, IX, ZI, XI, ZZ, XX] # Submit your answer using following code grade_lab0_ex1(observables) # Set up the Estimator estimator = Estimator(backend=AerSimulator()) # Submit the circuit to Estimator pub = (qc, observables) job = estimator.run(pubs=[pub]) # Collect the data data = ['IZ', 'IX', 'ZI', 'XI', 'ZZ', 'XX'] values = job.result()[0].data.evs # Set up our graph container = plt.plot(data, values, '-o') # Label each axis plt.xlabel('Observables') plt.ylabel('Values') # Draw the final graph plt.show() container = plt.bar(data, values, width=0.8) plt.xlabel('Observables') plt.ylabel('Values') plt.show()
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# imports import numpy as np from typing import List, Callable from scipy.optimize import minimize from scipy.optimize._optimize import OptimizeResult import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector, Operator, SparsePauliOp from qiskit.primitives import StatevectorSampler, PrimitiveJob from qiskit.circuit.library import TwoLocal from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.visualization import plot_histogram from qiskit_ibm_runtime.fake_provider import FakeSherbrooke from qiskit_ibm_runtime import Session, EstimatorV2 as Estimator from qiskit_aer import AerSimulator # Setup the grader from qc_grader.challenges.iqc_2024 import ( grade_lab1_ex1, grade_lab1_ex2, grade_lab1_ex3, grade_lab1_ex4, grade_lab1_ex5, grade_lab1_ex6, grade_lab1_ex7, ) # Build a circuit to form a psi-minus Bell state # Apply gates to the provided QuantumCircuit, qc qc = QuantumCircuit(2) ### Write your code below here ### qc.h(0) qc.cx(0,1) qc.z(1) qc.x(1) ### Don't change any code past this line ### qc.measure_all() qc.draw('mpl') # Submit your answer using following code grade_lab1_ex1(qc) # Expected result type: QuantumCircuit qc.measure_all() ### Write your code below here ### sampler = StatevectorSampler() #Add your code here pub = (qc)#Add your code here job_sampler = sampler.run([pub])#Add your code here ### Don't change any code past this line ### result_sampler = job_sampler.result() counts_sampler = result_sampler[0].data.meas.get_counts() print(counts_sampler) # Submit your answer using following code grade_lab1_ex2(job_sampler) # Expected result type: PrimitiveJob plot_histogram(counts_sampler) # Step 1 qc = QuantumCircuit(3) #your_code_here # Step 2 (provided) qc.ry(1.91063324, 0) # Add steps 3-6 below qc.ch(0,1) qc.cx(1,2) qc.cx(0,1) qc.x(0) ### Don't change any code past this line ### qc.measure_all() qc.draw('mpl') # Submit your answer using following code grade_lab1_ex3(qc) # Expected result type: # Expected result type: QuantumCircuit sampler = StatevectorSampler() pub = (qc) job_sampler = sampler.run([pub], shots=10000) result_sampler = job_sampler.result() counts_sampler = result_sampler[0].data.meas.get_counts() print(counts_sampler) plot_histogram(counts_sampler) pauli_op = SparsePauliOp(['ZII', 'IZI', 'IIZ']) print(pauli_op.to_matrix()) num_qubits = 3#Add your code here rotation_blocks = ['ry','rz'] #Add your code here entanglement_blocks = 'cz' #Add your code here entanglement = 'full' #Add your code here reps= 1 insert_barriers=True ansatz = TwoLocal(num_qubits= num_qubits, rotation_blocks= rotation_blocks, entanglement_blocks= entanglement_blocks, entanglement= entanglement, reps=reps , insert_barriers= insert_barriers) #Add your code here ### Don't change any code past this line ### ansatz.decompose().draw('mpl') # Submit your answer using following code grade_lab1_ex4(num_qubits, rotation_blocks, entanglement_blocks, entanglement) # Expected result type: int, List[str], str, str num_params = ansatz.num_parameters num_params backend_answer = FakeSherbrooke() #Add your code optimization_level_answer = 0 #Add your code pm = generate_preset_pass_manager(backend=backend_answer,optimization_level=optimization_level_answer) isa_circuit = pm.run(ansatz) # Add your code # Submit your answer using following code grade_lab1_ex5(isa_circuit) # Expected result type: QuantumCircuit isa_circuit.draw('mpl', idle_wires=False,) # Define our Hamiltonian hamiltonian_isa = pauli_op.apply_layout(layout=isa_circuit.layout) def cost_func(params, ansatz, hamiltonian, estimator, callback_dict): """Return estimate of energy from estimator Parameters: params (ndarray): Array of ansatz parameters ansatz (QuantumCircuit): Parameterized ansatz circuit hamiltonian (SparsePauliOp): Operator representation of Hamiltonian estimator (EstimatorV2): Estimator primitive instance Returns: float: Energy estimate """ pub = (ansatz, [hamiltonian], [params]) #Add your code result = estimator.run(pubs=[pub]).result() #Add your code energy = result[0].data.evs[0] #Add your code callback_dict["iters"] += 1 #Add your code callback_dict["prev_vector"] = params #Add your code callback_dict["cost_history"].append(energy) #Add your code ### Don't change any code past this line ### print(energy) return energy, result # Submit your answer using following code grade_lab1_ex6(cost_func) # Expected result type: Callable callback_dict = { "prev_vector": None, "iters": 0, "cost_history": [], } x0 = 2 * np.pi * np.random.random(num_params) x0 ### Select a Backend ## Use FakeSherbrooke to simulate with noise that matches closer to the real experiment. This will run slower. ## Use AerSimulator to simulate without noise to quickly iterate. This will run faster. backend = FakeSherbrooke() # backend = AerSimulator() # ### Don't change any code past this line ### # Here we have updated the cost function to return only the energy to be compatible with recent scipy versions (>=1.10) def cost_func_2(*args, **kwargs): energy, result = cost_func(*args, **kwargs) return energy with Session(backend=backend) as session: estimator = Estimator(session=session) res = minimize( cost_func_2, x0, args=(isa_circuit, hamiltonian_isa, estimator, callback_dict), method="cobyla", options={'maxiter': 30}) # Submit your answer using following code grade_lab1_ex7(res) # Expected result type: OptimizeResult fig, ax = plt.subplots() plt.plot(range(callback_dict["iters"]), callback_dict["cost_history"],'--',color = 'k') plt.xlabel("Energy") plt.ylabel("Cost") plt.draw()
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# Imports from qiskit.circuit.random import random_circuit from qiskit.circuit.library import XGate, YGate from qiskit_ibm_runtime.fake_provider import FakeTorino, FakeOsaka from qiskit.transpiler import InstructionProperties, PassManager from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler.preset_passmanagers.plugin import list_stage_plugins from qiskit.transpiler.timing_constraints import TimingConstraints from qiskit.transpiler.passes.scheduling import ASAPScheduleAnalysis,PadDynamicalDecoupling from qiskit.visualization.timeline import draw, IQXStandard from qiskit.transpiler import StagedPassManager from qiskit.visualization import plot_circuit_layout import matplotlib.pyplot as plt import numpy as np # Setup the grader from qc_grader.challenges.iqc_2024 import ( grade_lab2_ex1, grade_lab2_ex2, grade_lab2_ex3, grade_lab2_ex4, grade_lab2_ex5 ) from util import version_check version_check() ans = {} # Place the correct letter next to the corresponding stage, inside a parenthesis # example: ans["test"] = "M" ans["init"] = "C" ans["layout"] = "D" ans["routing"] = "B" ans["translation"] = "F" ans["optimization"] = "A" ans["scheduling"] = "E" # Submit your answer using following code grade_lab2_ex1(ans) ### Create the scoring function def scoring( qc, backend): from util import transpile_scoring layout = qc.layout ##your code here fidelity = transpile_scoring(qc, layout, backend) score = 1 - fidelity ##your code here return score # Submit your answer using following code grade_lab2_ex2(scoring) ### Create a random circuit ## DO NOT CHANGE THE SEED NUMBER seed = 10000 ## Create circuit num_qubits = 6 depth = 4 qc = random_circuit(num_qubits,depth,measure=False, seed=seed) qc.draw('mpl') ## Save FakeTorino as backend backend = FakeTorino() circuit_depths = { 'opt_lv_0': None, 'opt_lv_1': None, 'opt_lv_2': None, 'opt_lv_3': None, } gate_counts = { 'opt_lv_0': None, 'opt_lv_1': None, 'opt_lv_2': None, 'opt_lv_3': None, } scores = { 'opt_lv_0': None, 'opt_lv_1': None, 'opt_lv_2': None, 'opt_lv_3': None, } # Make a pass manager with our desired optimization level and backend pm_lv0 = generate_preset_pass_manager(backend=backend, optimization_level=0, seed_transpiler=seed) # Run for our random circuit tr_lv0 = pm_lv0.run(qc) # uncomment the next line to draw circuit tr_lv0.draw('mpl', idle_wires=False, fold=60) ### Your code here ### circuit_depths['opt_lv_0'] = qc.depth() gate_counts['opt_lv_0'] = qc.size() scores['opt_lv_0'] = scoring(qc, backend) ### Don't change code after this line ### print("Optimization level 0 results") print("====================") print("Circuit depth:", circuit_depths['opt_lv_0']) print("Gate count:", gate_counts['opt_lv_0']) print("Score:", scores['opt_lv_0']) # Make a pass manager with our desired optimization level and backend pm_lv1 = generate_preset_pass_manager(optimization_level=1, backend = backend, seed_transpiler = seed) ### your code here ### # Run for our random circuit tr_lv1 = pm_lv1.run(qc) # uncomment the next line to draw circuit tr_lv1.draw('mpl', idle_wires=False, fold=60) ### Your code here ### circuit_depths['opt_lv_1'] = tr_lv1.depth() gate_counts['opt_lv_1'] = tr_lv1.size() scores['opt_lv_1'] = scoring(tr_lv1, backend) ### Don't change code after this line ### print("Optimization level 1 results") print("====================") print("Circuit depth:", circuit_depths['opt_lv_1']) print("Gate count:", gate_counts['opt_lv_1']) print("Score:", scores['opt_lv_1']) # Make a pass manager with our desired optimization level and backend pm_lv2 = generate_preset_pass_manager(optimization_level=2, backend = backend, seed_transpiler = seed)### your code here ### # Run for our random circuit tr_lv2 = pm_lv2.run(qc) # uncomment the next line to draw circuit tr_lv2.draw('mpl', idle_wires=False, fold=60) ### Your code here ### circuit_depths['opt_lv_2'] = tr_lv2.depth() gate_counts['opt_lv_2'] = tr_lv2.size() scores['opt_lv_2'] = scoring(tr_lv2, backend) ### Don't change code after this line ### print("Optimization level 2 results") print("====================") print("Circuit depth:", circuit_depths['opt_lv_2']) print("Gate count:", gate_counts['opt_lv_2']) print("Score:", scores['opt_lv_2']) pm_lv3 = generate_preset_pass_manager(optimization_level=3, backend = backend, seed_transpiler = seed) ### your code here ### tr_lv3 = pm_lv3.run(qc) ### your code here ### # uncomment to draw circuit tr_lv3.draw('mpl', idle_wires=False, fold=60) ### Your code here ### circuit_depths['opt_lv_3'] = tr_lv3.depth() gate_counts['opt_lv_3'] = tr_lv3.size() scores['opt_lv_3'] = scoring(tr_lv3, backend) ### Don't change code after this line ### print("Optimization level 3 results") print("====================") print("Circuit depth:", circuit_depths['opt_lv_3']) print("Gate count:", gate_counts['opt_lv_3']) print("Score:", scores['opt_lv_3']) colors = ['#FF6666', '#66B2FF'] ax = ["opt_lv_0", "opt_lv_1", "opt_lv_2", "opt_lv_3"] fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12)) # Plot 1: Circuit Depth ax1.semilogy(ax, [circuit_depths[key] for key in ax],'o-',markersize=9, color='#FF6666', label="Depth") ax1.set_xlabel("Optimization Level", fontsize=12) ax1.set_ylabel("Depth", fontsize=12) ax1.set_title("Circuit Depth", fontsize=14) ax1.legend(fontsize=10) # Plot 2: Total Number of Gates ax2.semilogy(ax, [gate_counts[key] for key in ax],'^-',markersize=9, color='#66B2FF', label="Counts") ax2.set_xlabel("Optimization Level", fontsize=12) ax2.set_ylabel("Gate Count", fontsize=12) ax2.set_title("Gate Count", fontsize=14) ax2.legend(fontsize=10) # Plot 3: Score of Transpiled Circuit ax3.semilogy(ax, [scores[key] for key in ax],'*-',markersize=9, label="Score") ax3.set_xlabel("Optimization Level", fontsize=12) ax3.set_ylabel("Score", fontsize=12) ax3.set_title("Score", fontsize=14) ax3.legend(fontsize=10) fig.tight_layout() plt.show() # Submit your answer using following code ans = [pm_lv0, pm_lv1, pm_lv2, pm_lv3] grade_lab2_ex3(ans) list_stage_plugins("init") print("Plugins run by default init stage") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, init_method="default", seed_transpiler=1000) for task in pm.init.to_flow_controller().tasks: print(" -", type(task).__name__) list_stage_plugins("layout") print("Plugins run by default layout stage") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, layout_method='default', seed_transpiler=seed) qc_tr = pm.run(qc) for controller_group in pm.layout.to_flow_controller().tasks: tasks = getattr(controller_group, "tasks", []) for task in tasks: print(" - " , str(type(task).__name__)) print(qc_tr.layout.final_index_layout()) display(plot_circuit_layout(pm.run(qc), backend)) for option in list_stage_plugins("layout"): pm = generate_preset_pass_manager(backend=backend, optimization_level=3, layout_method=option, seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) print(f"Layout method = {option}") print(f"Score: {score:.6f}") print(f"Layout: {qc_tr.layout.final_index_layout()}\n") list_stage_plugins("routing") print("Number of each gates of transpiled circuit and the score") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, routing_method='basic', seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) for key, value in qc_tr.count_ops().items(): print(key, ":", value) print(f"Score: {score:.6f}") print("Plugins run by basic routing stage") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, routing_method='basic', seed_transpiler=seed) for controller_group in pm.routing.to_flow_controller().tasks: tasks = getattr(controller_group, "tasks", []) for task in tasks: print(" - " , str(type(task).__name__)) display(pm.routing.draw()) print(pm.run(qc).layout.final_index_layout()) ## process stopped due to lookahead options = ['basic','sabre', 'stochastic'] for option in options: print(f"Layout option = {option}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=3, routing_method=option, seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) print(f"Score: {score:.6f}") for key, value in qc_tr.count_ops().items(): print(key, ":", value) print("\n") list_stage_plugins("translation") print("Number of each gates of transpiled circuit") print("=================================") for i in range(4): print(f"\nOptimization level {i}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=i, translation_method='translator', seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) for key, value in qc_tr.count_ops().items(): print(key, ":", value) print(f"Score: {score:.6f}") options = ['translator', 'synthesis'] print("Number of each gates of transpiled circuit") print("=================================") for option in options: print(f"Layout option = {option}:") pm = generate_preset_pass_manager(backend=backend, optimization_level=3, translation_method=option, seed_transpiler=seed) qc_tr = pm.run(qc) score = scoring(qc_tr, backend) for key, value in qc_tr.count_ops().items(): print(key, ":", value) print(f"Score: {score:.6f}") print("\n") tr_depths = [] tr_gate_counts = [] tr_scores = [] options = ['translator', 'synthesis'] for i in range(4): for option in options: pm = generate_preset_pass_manager(backend=backend, optimization_level=i, translation_method=option, seed_transpiler=seed) tr_depths.append(pm.run(qc).depth()) tr_gate_counts.append(sum(pm.run(qc).count_ops().values())) tr_scores.append(scoring(pm.run(qc), backend)) colors = ['#FF6666', '#66B2FF'] markers = [ '^', '*'] linestyles = ['-.', ':'] opt_list = [] for i in range(4): opt_list.append(f"Optimization Level {i}") ax = opt_list fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12)) # Plot 1: Circuit Depth for i in range(2): ax1.plot(ax, tr_depths[i:i+4], label=options[i], marker=markers[i], markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax1.set_xlabel("translation options", fontsize=12) ax1.set_ylabel("Depth", fontsize=12) ax1.set_title("Circuit Depth of Transpiled Circuit", fontsize=14) ax1.legend(fontsize=10) # Plot 2: Total Number of Gates for i in range(2): ax2.plot(ax, tr_gate_counts[i:i+4], label=options[i], marker=markers[i], markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax2.set_xlabel("translation options", fontsize=12) ax2.set_ylabel("# of Total Gates", fontsize=12) ax2.set_title("Total Number of Gates of Transpiled Circuit", fontsize=14) ax2.legend(fontsize=10) # Plot 3: Score of Transpiled Circuit for i in range(2): ax3.plot(ax, tr_scores[i:i+4], label=options[i], marker=markers[i],markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax3.set_xlabel("translation options", fontsize=12) ax3.set_ylabel("Score of Transpiled Circuit", fontsize=12) ax3.set_title("Score of Transpiled Circuit", fontsize=14) ax3.legend(fontsize=10) fig.tight_layout() plt.show() """tr_depths = [] tr_gate_counts = [] tr_scores = [] approximation_degree_list = np.linspace(0,1,10) for i in range(4): for j in approximation_degree_list: # your code here # # your code here # """ """ colors = ['#FF6666', '#FFCC66', '#99FF99', '#66B2FF'] markers = ['o', 's', '^', '*'] linestyles = ['-', '--', '-.', ':'] ax = approximation_degree_list fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 12)) # Plot 1: Circuit Depth for i in range(4): ax1.plot(ax, tr_depths[i::4], label=f"Optimization Level {i}", marker=markers[i], markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax1.set_xlabel("Approximation Degree", fontsize=12) ax1.set_ylabel("Depth", fontsize=12) ax1.set_title("Circuit Depth of Transpiled Circuit", fontsize=14) ax1.legend(fontsize=10) # Plot 2: Total Number of Gates for i in range(4): ax2.plot(ax, tr_gate_counts[i::4], label=f"Optimization Level {i}", marker=markers[i], markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax2.set_xlabel("Approximation Degree", fontsize=12) ax2.set_ylabel("# of Total Gates", fontsize=12) ax2.set_title("Total Number of Gates of Transpiled Circuit", fontsize=14) ax2.legend(fontsize=10) # Plot 3: Score of Transpiled Circuit for i in range(4): ax3.plot(ax, tr_scores[i::4], label=f"Optimization Level {i}", marker=markers[i],markersize=9, linestyle=linestyles[i], color=colors[i], linewidth=2) ax3.set_xlabel("Approximation Degree", fontsize=12) ax3.set_ylabel("Score of Transpiled Circuit", fontsize=12) ax3.set_title("Score of Transpiled Circuit", fontsize=14) ax3.legend(fontsize=10) fig.tight_layout() plt.show() """ list_stage_plugins("scheduling") backend_timing = backend.target.timing_constraints() timing_constraints = TimingConstraints( granularity=backend_timing.granularity, min_length=backend_timing.min_length, pulse_alignment=backend_timing.pulse_alignment, acquire_alignment=backend_timing.acquire_alignment ) # Run with optimization level 3 and 'asap' scheduling pass pm_asap = generate_preset_pass_manager( optimization_level=3, backend=backend, timing_constraints=timing_constraints, scheduling_method="asap", seed_transpiler=seed, ) my_style = { 'formatter.general.fig_width': 40, 'formatter.general.fig_unit_height': 1, } draw(pm_asap.run(qc), style=IQXStandard(**my_style), show_idle=False, show_delays=True) pm_alap = generate_preset_pass_manager( optimization_level=3, backend=backend, timing_constraints=timing_constraints, scheduling_method="alap", seed_transpiler=seed, ) draw(pm_alap.run(qc), style=IQXStandard(**my_style), show_idle=False, show_delays=True) print("Score") print("===============") print(f"asap: {scoring(pm_asap.run(qc), backend):.6f}") print(f"alap: {scoring(pm_alap.run(qc), backend):.6f}") pm_ex4 = generate_preset_pass_manager( backend=backend, ### Write your code below here ### optimization_level = 3, layout_method = 'sabre', routing_method = 'sabre', translation_method = 'synthesis' ### Don't change any code past this line ### ) # Submit your answer using following code grade_lab2_ex4(pm_ex4) X = XGate() Y = YGate() dd_sequence = [X, Y, X, Y] backend=FakeTorino() target = backend.target y_gate_properties = {} for qubit in range(target.num_qubits): y_gate_properties.update( { (qubit,): InstructionProperties( duration=target["x"][(qubit,)].duration, error=target["x"][(qubit,)].error, ) } ) target.add_instruction(YGate(), y_gate_properties) dd_pm = PassManager( [ ## your code here ASAPScheduleAnalysis(target=target), PadDynamicalDecoupling(target=target, dd_sequence=dd_sequence), ## your code here ] ) draw(pm_asap.run(qc), style=IQXStandard(**my_style), show_idle=False, show_delays=True) staged_pm_dd = StagedPassManager( stages=["scheduling"], scheduling=dd_pm ) qc_tr = pm_asap.run(qc) draw(staged_pm_dd.run(qc_tr), style=IQXStandard(**my_style), show_idle=False, show_delays=True) # Submit your answer using following code grade_lab2_ex5(staged_pm_dd)
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# qc-grader should be 0.18.10 (or higher) import qc_grader qc_grader.__version__ # Imports import numpy as np import matplotlib.pyplot as plt from qiskit.circuit.library import EfficientSU2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import QiskitRuntimeService from qiskit_transpiler_service.transpiler_service import TranspilerService # Import for grader from qc_grader.challenges.iqc_2024 import grade_lab3_ait_ex1, grade_lab3_ait_ex2 NUM_QUBITS = 61 circuit = EfficientSU2(NUM_QUBITS, entanglement="circular", reps=1).decompose() print(f"Original circuit -> Depth: {circuit.depth()}, CNOTs: {circuit.num_nonlocal_gates()}") circuit.draw(fold=-1, output="mpl", style="iqp", scale=0.2) # Load saved credentials service = QiskitRuntimeService() transpiler_ai_false = TranspilerService( # Add your code here backend_name="ibm_brisbane", ai="false", optimization_level=3, ) # Submit your answer using following code grade_lab3_ait_ex1(transpiler_ai_false) # Expected result type: TranspilerService circuit_ai_false = transpiler_ai_false.run(circuit) print(f"Transpiled without AI -> Depth: {circuit_ai_false.depth()}, CNOTs: {circuit_ai_false.num_nonlocal_gates()}") circuit_ai_false.draw(fold=-1, output="mpl", scale=0.2) transpiler_ai_true = TranspilerService( # Add your code here backend_name="ibm_brisbane", ai="true", optimization_level=3, ) # Submit your answer using following code grade_lab3_ait_ex2(transpiler_ai_true) # Expected result type: TranspilerService circuit_ai_true = transpiler_ai_true.run(circuit) print(f"Transpiled with AI -> Depth: {circuit_ai_true.depth()}, CNOTs: {circuit_ai_true.num_nonlocal_gates()}") circuit_ai_true.draw(fold=-1, output="mpl", scale=0.2) # Transpiling locally using Qiskit SDK service = QiskitRuntimeService() backend = service.backend("ibm_sherbrooke") pm = generate_preset_pass_manager(backend=backend, optimization_level=3) # Run and compile results num_qubits = [11, 21, 41, 61, 81] num_cnots_local = [] num_cnots_with_ai = [] num_cnots_without_ai = [] for nq in num_qubits: circuit = EfficientSU2(nq, entanglement="circular", reps=1).decompose() # Using the Transpiler locally on Qiskit circuit_local = pm.run(circuit) # Using the transpiler service without AI circuit_without_ai = transpiler_ai_false.run(circuit) # Using the transpiler service with AI circuit_with_ai = transpiler_ai_true.run(circuit) num_cnots_local.append(circuit_local.num_nonlocal_gates()) num_cnots_without_ai.append(circuit_without_ai.num_nonlocal_gates()) num_cnots_with_ai.append(circuit_with_ai.num_nonlocal_gates()) plt.plot(num_qubits, num_cnots_with_ai, '.-') plt.plot(num_qubits, num_cnots_without_ai, '.-') plt.plot(num_qubits, num_cnots_local, '--') plt.xlabel("Number of qubits") plt.ylabel("CNOT count") plt.legend(["Qiskit Transpiler Service with AI", "Qiskit Transpiler Service without AI", "Qiskit SDK"])
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# qc-grader should be 0.18.11 (or higher) import qc_grader qc_grader.__version__ # Imports import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.visualization import plot_gate_map from qiskit.quantum_info import SparsePauliOp from qiskit_aer import AerSimulator from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2 as Sampler from circuit_knitting.cutting import generate_cutting_experiments, cut_gates # Setup the grader from qc_grader.challenges.iqc_2024 import grade_lab3_ckt_ex1, grade_lab3_ckt_ex2 # create a bell pair bell_state = QuantumCircuit(2) bell_state.h(0) bell_state.cx(0,1) bell_state.draw("mpl") ## If this is your first time accessing the backend ## remove # and fill your API key, and run the code #service = QiskitRuntimeService( # channel='ibm_quantum', # instance='ibm-q/open/main', # token='<IBM Quantum API key>' #) service = QiskitRuntimeService(channel="ibm_quantum") # Specify a system to use for transpilation, DO NOT change backend = service.backend("ibm_kyoto") layout=[122, 126] qubit_color = [] for i in range(127): if i in layout: qubit_color.append("#ff0066") else: qubit_color.append("#6600cc") plot_gate_map(backend, qubit_color=qubit_color, qubit_size=60, font_size=25, figsize=(8,8)) # transpile the circuit pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qc = pm.run(bell_state) # original circuit depth isa_qc_depth = isa_qc.depth() print(f"Transpiled circuit depth: ", isa_qc_depth) isa_qc.draw("mpl", scale=0.6, idle_wires=False, fold=False) # Find the indices of the distant gates cut_indices = [ i for i, instruction in enumerate(bell_state.data) if {bell_state.find_bit(q)[0] for q in instruction.qubits} == {0, 1} ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit, bases = cut_gates(bell_state, cut_indices) qpd_circuit.draw("mpl", scale=0.6) observable = SparsePauliOp(["ZI"]) # Generate the sub-experiments and sampling coefficients sub_experiments, coefficients = generate_cutting_experiments( circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf ) # Transpile the circuit pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=layout, seed_transpiler=0) isa_qpd_circuit = pm.run(sub_experiments[5]) # depth using circuit cutting isa_qpd_depth = isa_qpd_circuit.depth() print(f"Original circuit depth after transpile: ", isa_qc_depth) print(f"QPD sub-experiment depth after transpile: ", isa_qpd_depth) print(f"Number of sub-experiments:", len(sub_experiments)) isa_qpd_circuit.draw("mpl", scale=0.6, idle_wires=False, fold=False) x = np.array([c.depth() for c in pm.run(sub_experiments)]) print(x) toffoli_layout = [122, 124, 126] toffoli = QuantumCircuit(3) toffoli.ccx(0, 1, 2) toffoli.draw("mpl") # To know the original circuit depth ### Write your code below here ### # Transpile the circuit pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=toffoli_layout, seed_transpiler=0) isa_qpd_circuit = pm.run(toffoli) # Calculate original circuit depth isa_toffoli_depth = isa_qpd_circuit.depth() ### Don't change any code past this line ### print(f"Transpiled circuit depth: ", isa_toffoli_depth) isa_qc.draw("mpl", scale=0.6, idle_wires=False, fold=False) # To know the depth using circuit cutting # Decompose the toffoli circuit toffoli_ = toffoli.decompose() ### Write your code below here ### # Find the indices of the distant gates gates_connecting_to_cut = {0, 2} # Hint: Expected type: set {int, int}. Docs: https://docs.python.org/3/tutorial/datastructures.html#sets cut_indices = [ i for i, instruction in enumerate(toffoli_.data) if {toffoli.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit, bases = cut_gates(toffoli_, cut_indices) ### Don't change any code past this line ### qpd_circuit.draw("mpl", scale=0.6) # set the observables observable = SparsePauliOp(["ZZZ"]) ### Write your code below here ### # Generate the sub-experiments and sampling coefficients sub_experiments, coefficients = generate_cutting_experiments( circuits=qpd_circuit, observables=observable.paulis, num_samples=np.inf ) # Transpile the circuit # Note: Use optimization_level=1 and seed_transpiler=0 pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=toffoli_layout, seed_transpiler=0) isa_qpd_circuit = pm.run(sub_experiments[5]) # Depth using circuit cutting isa_qpd_toffoli_depth = isa_qpd_circuit.depth() ### Don't change any code past this line ### print(f"Transpiled circuit depth: ", isa_toffoli_depth) print(f"QPD sub-experiment depth after transpile: ", isa_qpd_toffoli_depth) print(f"Number of sub-experiments:", len(sub_experiments)) isa_qpd_circuit.draw("mpl", scale=0.6, idle_wires=False, fold=False) ### Write your code below here ### # mean of the depth of all sub-experiments depth_list = np.array([c.depth() for c in pm.run(sub_experiments)]) isa_qpd_toffoli_depth_mean = np.mean(depth_list) ### Don't change any code past this line ### print(isa_qpd_toffoli_depth_mean) # Submit your answer using following code grade_lab3_ckt_ex1(gates_connecting_to_cut, isa_toffoli_depth, depth_list) # Expected result type: set, int, numpy.ndarray ### Write your code below here ### # Find the indices of the distant gates gates_connecting_to_cut_1 = {0,2} # Hint: Expected type: set {int, int} gates_connecting_to_cut_2 = {1,2} # Hint: Expected type: set {int, int} cut_indices = [ i for i, instruction in enumerate(toffoli_.data) if {toffoli.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut_1 or {toffoli.find_bit(q)[0] for q in instruction.qubits} == gates_connecting_to_cut_2 ] # Decompose distant CNOTs into TwoQubitQPDGate instances qpd_circuit_2, bases = cut_gates(toffoli_, cut_indices) ### Don't change any code past this line ### qpd_circuit_2.draw("mpl", scale=0.6) # set the observables observable = SparsePauliOp(["ZZZ"]) ### Write your code below here ### # Generate the sub-experiments and sampling coefficients sub_experiments_2, coefficients = generate_cutting_experiments( circuits=qpd_circuit_2, observables=observable.paulis, num_samples=np.inf ) # Transpile the circuit # Note: Use optimization_level=1 and seed_transpiler=0 pm = generate_preset_pass_manager(backend=backend, optimization_level=1, initial_layout=toffoli_layout, seed_transpiler=0) isa_qpd_circuit_2 = pm.run(sub_experiments[5]) # Depth using circuit cutting isa_qpd_toffoli_depth_2 = isa_qpd_circuit_2.depth() ### Don't change any code past this line ### print(f"QPD sub-experiment depth after transpile: ", isa_qpd_toffoli_depth_2) print(f"Number of sub-experiments:", len(sub_experiments_2)) isa_qpd_circuit_2.draw("mpl", scale=0.6, idle_wires=False, fold=False) # Submit your answer using following code grade_lab3_ckt_ex2(gates_connecting_to_cut_1, gates_connecting_to_cut_2, sub_experiments_2) # Expected result type: set, set, list[QuantumCircuit] ### Write your code below here ### # mean of the depth of all sub-experiments depth_list_2 = np.array([c.depth() for c in pm.run(sub_experiments_2)]) isa_qpd_toffoli_depth_2_mean = np.mean(depth_list_2) ### Don't change any code past this line ### print(isa_qpd_toffoli_depth_2_mean) # Number of sub-experiments num_sub_experiments_1_cut = len(sub_experiments) num_sub_experiments_2_cut = len(sub_experiments_2) # Data for plotting categories = ['Before Cutting', 'After 1 Cut', 'After 2 Cuts'] depth_values = [isa_toffoli_depth, isa_qpd_toffoli_depth_mean, isa_qpd_toffoli_depth_2_mean] num_sub_experiments = [1, num_sub_experiments_1_cut, num_sub_experiments_2_cut] # Create figure and axis fig, ax1 = plt.subplots() # Plot depth values color = 'tab:blue' ax1.set_xlabel('Number of Cuts') ax1.set_ylabel('Circuit Depth', color=color) bars = ax1.bar(categories, depth_values, color=color, alpha=0.6) ax1.tick_params(axis='y', labelcolor=color) # Add value labels on bars for bar in bars: yval = bar.get_height() ax1.text(bar.get_x() + bar.get_width() / 2, yval + 1, round(yval, 2), ha='center', color=color, fontsize=10) # Create a second y-axis to plot the number of subexperiments ax2 = ax1.twinx() color = 'tab:green' ax2.set_ylabel('Number of Sub-experiments', color=color) ax2.plot(categories, num_sub_experiments, color=color, marker='o') ax2.tick_params(axis='y', labelcolor=color) # Add value labels on points for i, num in enumerate(num_sub_experiments): ax2.text(i, num + 0.1, num, ha='center', color=color, fontsize=10) # Add titles and labels plt.title('Circuit Knitting Toolbox Results') fig.tight_layout() # Adjust layout to make room for both y-axes # Show plot plt.show()
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# please create a 3 qubit GHZ circuit # please create a 2 qubit ch gate with only cx and ry gate # Enter your prompt here - Delete this line
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# qc-grader should be 0.18.11 (or higher) import qc_grader qc_grader.__version__ # Import all in one cell import numpy as np import matplotlib.pyplot as plt from timeit import default_timer as timer import warnings from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import TwoLocal, EfficientSU2 from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, Session, Options from qiskit_serverless import QiskitFunction, save_result, get_arguments, save_result, distribute_task, distribute_qiskit_function, IBMServerlessClient, QiskitFunction from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_transpiler_service.transpiler_service import TranspilerService from qiskit_aer import AerSimulator # Import for grader from qc_grader.challenges.iqc_2024 import grade_lab3_qs_ex1, grade_lab3_qs_ex2 service = QiskitRuntimeService(channel="ibm_quantum") # Specify a system to use for transpilation real_backend = service.backend("ibm_brisbane") # Qiskit Pattern Step 1: Map quantum circuits and operators (Define Ansatz and operators) num_qubits = 3#Add your code here rotation_blocks = ['ry','rz'] #Add your code here entanglement_blocks = 'cz' #Add your code here entanglement = 'full' #Add your code here reps= 1 insert_barriers=True # Define Ansatz ansatz = TwoLocal(num_qubits= num_qubits, rotation_blocks= rotation_blocks, entanglement_blocks= entanglement_blocks, entanglement= entanglement, reps=reps , insert_barriers= insert_barriers) #Add your code here # Define parameters num_params = ansatz.num_parameters # Qiskit Pattern Step 2: Optimize the circuit for quantum execution optimization_level = 2 pm = generate_preset_pass_manager(backend=real_backend, optimization_level=optimization_level) isa_circuit = pm.run(ansatz) # Add your code here # Define Hamiltonian for VQE pauli_op = SparsePauliOp(['ZII', 'IZI', 'IIZ']) hamiltonian_isa = pauli_op.apply_layout(layout=isa_circuit.layout) # Setup Qiskit Serverless Client and Qiskit Runtime client client = IBMServerlessClient("hidden") # Add in your IBM Quantum Token to QiskitServerless Client # For the challenge, we will be using QiskitRuntime Local testing mode. Change to True only if you wish to use real backend. USE_RUNTIME_SERVICE = False if USE_RUNTIME_SERVICE: service = QiskitRuntimeService( channel='ibm_quantum', verify=False ) else: service = None # Define the Qiskit Function if USE_RUNTIME_SERVICE: function = QiskitFunction(title= "vqe", entrypoint="vqe.py", working_dir="./vqe") else: function = QiskitFunction(title= "vqe" , entrypoint="vqe.py", working_dir="./vqe", dependencies=["qiskit_aer"]) # Upload the Qiskit Function using IBMServerlessClient client.upload(function) # Define input_arguments input_arguments = { "ansatz": isa_circuit, # Replace with your transpiled ansatz "operator": hamiltonian_isa, # Replace with the hamiltonian operator "method": "COBYLA", # Using COBYLA method for the optimizer "service": service, # Add your code here } # Qiskit Pattern Step 3: Run the payload on backend job = client.run("vqe", arguments= input_arguments) # Pass the arguments dict here) # Submit your answer using following code grade_lab3_qs_ex1(function, input_arguments, job) # Expected result type: QiskitFunction, dict, Job # Return jobid job # Check job completion status job.status() # Monitor log logs = job.logs() for log in logs.splitlines(): print(log) # Return result from QiskitFunction job job.result() # Qiskit Pattern Step 4: Postprocess and analyze the Estimator V2 results result = job.result() plt.style.use('ggplot') fig, ax = plt.subplots() plt.plot(range(result["iters"]), result["cost_history"], ls='--', c='k') plt.xlabel("Energy") plt.ylabel("Cost") plt.draw() # Setup 3 circuits with Efficient SU2 num_qubits = [41, 51, 61] circuits = [EfficientSU2(nq, su2_gates=["rz","ry"], entanglement="circular", reps=1).decompose() for nq in num_qubits] # Setup Qiskit Runtime Service backend # QiskitRuntimeService.save_account( # channel="ibm_quantum", # token="YOUR_IBM_QUANTUM_TOKEN", # set_as_default=True, # # Use 'overwrite=True' if you're updating your token. # overwrite=True, # ) service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend("ibm_brisbane") # Define Configs optimization_levels = [1,2,3] # Add your code here pass_managers = [{'pass_manager': generate_preset_pass_manager(optimization_level=level, backend=backend), 'optimization_level': level} for level in optimization_levels] transpiler_services = [ {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': False, 'optimization_level': 3}, {'service': TranspilerService(backend_name="ibm_brisbane", ai="true", optimization_level=3,), 'ai': True, 'optimization_level': 3} ] configs = pass_managers + transpiler_services # Local transpilation setup def transpile_parallel_local(circuit: QuantumCircuit, config): """Transpilation for an abstract circuit into an ISA circuit for a given config.""" transpiled_circuit = config.run(circuit) return transpiled_circuit # Run local transpilation warnings.filterwarnings("ignore") start = timer() # Run transpilations locally for baseline results = [] for circuit in circuits: for config in configs: if 'pass_manager' in config: results.append(transpile_parallel_local(circuit, config['pass_manager'])) else: results.append(transpile_parallel_local(circuit, config['service'])) end = timer() # Record local execution time execution_time_local = end - start print("Execution time locally: ", execution_time_local) # Authenticate to the remote cluster and submit the pattern for remote execution if not done in previous exercise serverless = IBMServerlessClient("hidden") transpile_parallel_function = QiskitFunction( title="transpile_parallel", entrypoint="transpile_parallel.py", working_dir="./transpile_parallel", dependencies=["qiskit-transpiler-service"] ) serverless.upload(transpile_parallel_function) # Add your code here # Get list of functions serverless.list() # Fetch the specific function titled "transpile_parallel" transpile_parallel_serverless = serverless.get("transpile_parallel") # Add your code here # Run the "transpile_parallel" function in the serverless environment job = transpile_parallel_serverless.run( circuits= circuits, # Add your code here, backend_name= backend # Add your code here ) # Submit your answer using following code grade_lab3_qs_ex2(optimization_levels, transpiler_services, transpile_parallel_function, transpile_parallel_serverless, job) # Expected result type: list, list, QiskitFunction, QiskitFunction, Job job.status() logs = job.logs() for log in logs.splitlines(): print(log) result = job.result() result_transpiled = result["transpiled_circuits"] # Compare execution times: execution_time_serverless = result["execution_time"] from utils import plot_execution_times plot_execution_times(execution_time_serverless, execution_time_local) from utils import process_transpiled_circuits best_circuits, best_depths, best_methods = process_transpiled_circuits(configs, result_transpiled) # Display the best circuits, depths, and methods for i, (circuit, depth, method) in enumerate(zip(best_circuits, best_depths, best_methods)): print(f"Best result for circuit {i + 1}:") print(f" Depth: {depth}") print(f" Method: {method}") # Display or process the best circuit as needed # e.g., circuit.draw(output="mpl")
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# Import all in one cell import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import minimize from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import RealAmplitudes from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.transpiler import InstructionProperties from qiskit.visualization import plot_distribution from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.primitives import StatevectorEstimator from qiskit_aer import AerSimulator from qiskit_ibm_runtime import ( QiskitRuntimeService, EstimatorV2 as Estimator, SamplerV2 as Sampler, EstimatorOptions ) # qc-grader should be 0.18.12 (or higher) import qc_grader qc_grader.__version__ from qc_grader.challenges.iqc_2024 import ( grade_lab4_ex1, grade_lab4_ex2, grade_lab4_ex3, grade_lab4_ex4, grade_lab4_ex5, grade_lab4_ex6, grade_lab4_ex7 ) # Define num_qubits, the number of qubits, for the rest of the Lab num_qubits = 5 # Load the dictionary birds_dataset = pd.read_csv('birds_dataset.csv') # Check if the dataset is loaded correctly - coefficients should be complex numbers for i in range(2**num_qubits): key = 'c%.0f' %i birds_dataset[key] = birds_dataset[key].astype(np.complex128) # Print the dataset birds_dataset isinstance(birds_dataset, pd.DataFrame) # List to store the coefficient lists for each label coefficients_lists = [] # Iterate over each row in the DataFrame for index, row in birds_dataset.iterrows(): # Extract coefficients as a list coefficients = row[1:].tolist() # Skip the label column # Append the list of coefficients to the main list coefficients_lists.append(coefficients) coefficients_lists lab_birds = [1]*5 + [0]*5 lab_birds list_coefficients = coefficients_lists # Add your code here list_labels = lab_birds# Add your code here # Submit your answer using following code grade_lab4_ex1(list_coefficients, list_labels) index_bird = 1 # You can check different birds by changing the index amplitudes = list_coefficients[index_bird] # Build the amplitude embedding qc = QuantumCircuit(5) qc.initialize(amplitudes, range(num_qubits)) qc.measure_all() # Draw the amplitude embedding circuit qc.draw(output="mpl") # Draw the decomposition of the amplitude embedding circuit qc.decompose(reps=8).draw(output="mpl", fold=40) num_qubits = 5 # Add your code here reps = 1 # Add your code here entanglement = 'full' # Add your code here ansatz = RealAmplitudes(num_qubits=num_qubits, entanglement=entanglement, reps=reps,insert_barriers=True) # Add your code here # Add code here to draw the ansatz circuit ansatz.decompose(reps=6).draw(output="mpl", fold=40) # Submit your answer using following code grade_lab4_ex2(num_qubits, reps, entanglement) # Define the observable obs = SparsePauliOp("ZZZZZ") # Define the estimator and pass manager estimator = StatevectorEstimator() #To train we use StatevectorEstimator to get the exact simulation pm = generate_preset_pass_manager(backend=AerSimulator(), optimization_level=3, seed_transpiler=0) # Define the cost function def cost_func(params, list_coefficients, list_labels, ansatz, obs, estimator, pm, callback_dict): """Return cost function for optimization Parameters: params (ndarray): Array of ansatz parameters list_coefficients (list): List of arrays of complex coefficients list_labels (list): List of labels ansatz (QuantumCircuit): Parameterized ansatz circuit obs (SparsePauliOp): Observable estimator (EstimatorV2): Statevector estimator primitive instance pm (PassManager): Pass manager callback_dict (dict): Dictionary to store callback information Returns: float: Cost function estimate """ cost = 0 for amplitudes,label in zip(list_coefficients, list_labels): qc = QuantumCircuit(num_qubits) # Amplitude embedding qc.initialize(amplitudes) # Compose initial state + ansatz classifier = qc.compose(ansatz) # Transpile classifier transpiled_classifier = pm.run(classifier) # Transpile observable transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) # Run estimator pub = (transpiled_classifier, transpiled_obs, params) job = estimator.run([pub]) # Get result result = job.result()[0].data.evs # Compute cost function (cumulative) cost += np.abs(result - label) callback_dict["iters"] += 1 callback_dict["prev_vector"] = params callback_dict["cost_history"].append(cost) # Print the iterations to screen on a single line print( "Iters. done: {} [Current cost: {}]".format(callback_dict["iters"], cost), end="\r", flush=True, ) return cost # Intialize the lists to store the results from different runs cost_history_list = [] res_list = [] # Retrieve the initial parameters params_0_list = np.load("params_0_list.npy") for it, params_0 in enumerate(params_0_list): print('Iteration number: ', it) # Initialize a callback dictionary callback_dict = { "prev_vector": None, "iters": 0, "cost_history": [], } # Minimize the cost function using scipy res = minimize( cost_func, params_0, args=(list_coefficients, list_labels, ansatz, obs, estimator, pm, callback_dict), method="cobyla", # Classical optimizer options={'maxiter': 200}) # Maximum number of iterations # Print the results after convergence print(res,"\n") # Save the results from different runs res_list.append(res) cost_history_list.append(callback_dict["cost_history"]) ''' fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost history') ax.set_ylabel('Cost') ax.set_xlabel('Iterations') # Add your code here ''' def test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm): """Return the performance of the classifier Parameters: list_coefficients (list): List of arrays of complex coefficients list_labels (list): List of labels ansatz (QuantumCircuit): Parameterized ansatz circuit obs (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters estimator (EstimatorV2): Statevector estimator pm (PassManager): Pass manager for transpilation Returns: list: List of test results """ ### Write your code below here ### results_test = [] for coefficients, label in zip(list_coefficients, list_labels): test_circuit = ansatz.copy() test_circuit.initialize(coefficients) classifier = test_circuit.compose(ansatz) transpiled_classifier = pm.run(classifier) transpiled_obs = obs.apply_layout(layout = transpiled_classifier.layout) pub = (transpiled_classifier, transpiled_obs, opt_params) job = estimator.run([pub]) result = np.abs(job.result()[0].data.evs) results_test.append(result) ### Don't change any code past this line ### return results_test def compute_performance(result_list, list_labels): """Return the performance of the classifier Parameters: result_list (list): List of results list_labels (list): List of labels Returns: float: Performance of the classifier """ ### Write your code below here ### performance = 100* (1 - sum(np.abs(result - label) for result, label in zip(result_list, list_labels))/ (2** num_qubits)) ### Don't change any code past this line ### return performance results_test = test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm) results_test perf = [] for index in range(len(res_list)): opt_params = res_list[index].x results_test = test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm) perf.append(compute_performance(results_test, list_labels)) print(perf) print(perf.index(np.max(perf))) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data') ax.set_ylabel('Cost') ax.set_xlabel('State index') ax.plot(list_labels, 'k-', linewidth=3, alpha=0.6, label='Labels') for index in range(len(res_list)): opt_params = res_list[index].x results_test = test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm) print(f"Performance for trial {index}: {compute_performance(results_test, list_labels)}") ax.plot(results_test, 'o--', label='Predictions trial '+str(index)) ax.legend() plt.show() # Submit your answer using following code best_result_index = perf.index(np.max(perf)) # Choose the index with the best result grade_lab4_ex3(res_list[best_result_index]) # Expected result type: OptimizeResult fake_backend = GenericBackendV2( num_qubits=5, basis_gates=["id", "rz", "sx", "x", "cx"] ) def update_error_rate(backend, error_rates): """Updates the error rates of the backend Parameters: backend (BackendV2): Backend to update error_rates (dict): Dictionary of error rates Returns: None """ default_duration=1e-8 if "default_duration" in error_rates: default_duration = error_rates["default_duration"] # Update the 1-qubit gate properties for i in range(backend.num_qubits): qarg = (i,) if "rz_error" in error_rates: backend.target.update_instruction_properties('rz', qarg, InstructionProperties(error=error_rates["rz_error"], duration=default_duration)) if "x_error" in error_rates: backend.target.update_instruction_properties('x', qarg, InstructionProperties(error=error_rates["x_error"], duration=default_duration)) if "sx_error" in error_rates: backend.target.update_instruction_properties('sx', qarg, InstructionProperties(error=error_rates["sx_error"], duration=default_duration)) if "measure_error" in error_rates: backend.target.update_instruction_properties('measure', qarg, InstructionProperties(error=error_rates["measure_error"], duration=default_duration)) # Update the 2-qubit gate properties (CX gate) for all edges in the chosen coupling map if "cx_error" in error_rates: for edge in backend.coupling_map: backend.target.update_instruction_properties('cx', tuple(edge), InstructionProperties(error=error_rates["cx_error"], duration=default_duration)) error_rates = { "default_duration": 1e-8, "rz_error": 1e-8, "x_error": 1e-8, "sx_error": 1e-8, "measure_error": 1e-8, "cx_error": 1e-8 } update_error_rate(fake_backend, error_rates) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data') ax.set_ylabel('Cost') ax.set_xlabel('State index') ax.plot(list_labels, 'k-', linewidth=3, alpha=0.6, label='Labels') error_rate_list = [1e-1, 1e-2, 1e-3, 1e-4] fake_backend = GenericBackendV2( num_qubits=5, basis_gates=["id", "rz", "sx", "x", "cx"] ) for error_rate_value in error_rate_list: #update_error_rate(fake_backend, {"rz_error": error_rate_value, "cx_error": error_rate_value}) # Add your code here update_error_rate(fake_backend, error_rates = { "default_duration": 1e-8, "rz_error": error_rate_value, "x_error": 1e-8, "sx_error": 1e-8, "measure_error": 1e-8, "cx_error": error_rate_value }) # Add your code here estimator = Estimator(backend= fake_backend) # Add your code here pm = generate_preset_pass_manager(backend= fake_backend, optimization_level=3, seed_transpiler=0) # Add your code here opt_params = res_list[best_result_index].x # Add your code here results_test = test_VQC(list_coefficients, list_labels, ansatz, obs, opt_params, estimator, pm) print(f"Performance for run {index}: {compute_performance(results_test, list_labels)}") ax.plot(results_test, 'o--', label='Predictions error rate '+str(error_rate_value)) ax.legend() # Submit your answer using following code grade_lab4_ex4(fake_backend) # Expected answer type: BackendV2 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_osaka") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 #you can check different birds by changing the index qc = QuantumCircuit(num_qubits) qc.initialize(list_coefficients[index_bird]) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", idle_wires=False, fold=40) def amplitude_embedding(num_qubits, bird_index): """Create amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ def generate_GHZ(qc): qc.h(0) for i, j in zip(range(num_qubits-1), range(1,num_qubits)): qc.cx(i, j) ### Write your code below here ### qc = QuantumCircuit(num_qubits) if bird_index < 5: generate_GHZ(qc) bin_string = format(bird_index, '0{0}b'.format(num_qubits)) for i in reversed(range(len(bin_string))): if bin_string[i] == '1': qc.x(num_qubits-i-1) ### Don't change any code past this line ### return qc index_bird = 2 # You can check different birds by changing the index # Build the amplitude embedding qc = amplitude_embedding(num_qubits, index_bird) qc.measure_all() # Define the backend and the pass manager aer_sim = AerSimulator() pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(qc) # Define the sampler with the number of shots sampler = Sampler(backend=aer_sim) result = sampler.run([isa_circuit]).result() samp_dist = result[0].data.meas.get_counts() plot_distribution(samp_dist, figsize=(15, 5)) index_bird = 0 #You can check different birds by changing the index qc = amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab4_ex5(amplitude_embedding) # Expected answer type Callable old_ansatz = RealAmplitudes(num_qubits, reps=1, entanglement='full', insert_barriers=True) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_ansatz = pm.run(old_ansatz) print('Depth of two-qubit gates: ', transpiled_ansatz.depth(lambda x: len(x.qubits) == 2)) transpiled_ansatz.draw(output="mpl", idle_wires=False, fold=40) ansatz = ansatz = RealAmplitudes(num_qubits=num_qubits, entanglement='pairwise', reps=reps,insert_barriers=True) # Add your code here pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend)# Add your code here transpiled_ansatz = pm.run(qc)# Add your code here print('Depth of two-qubit gates: ', transpiled_ansatz.depth(lambda x: len(x.qubits) == 2)) transpiled_ansatz.draw(output="mpl", fold=False, idle_wires=False) old_mapping = QuantumCircuit(num_qubits) old_mapping.initialize(list_coefficients[index_bird]) old_classifier = old_mapping.compose(old_ansatz) new_mapping = amplitude_embedding(num_qubits, index_bird) new_classifier = new_mapping.compose(ansatz) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) old_transpiled_classifier = pm.run(old_classifier) new_transpiled_classifier = pm.run(new_classifier) print('Old depth of two-qubit gates: ', old_transpiled_classifier.depth(lambda x: len(x.qubits) == 2)) print('Current depth of two-qubit gates: ', new_transpiled_classifier.depth(lambda x: len(x.qubits) == 2)) def test_shallow_VQC(list_labels, ansatz, obs, opt_params, estimator, pm): """Return the performance of the classifier Parameters: list_labels (list): List of labels ansatz (QuantumCircuit): Parameterized ansatz circuit obs (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters estimator (EstimatorV2): Statevector estimator pm (PassManager): Pass manager for transpilation Returns: results_test (list): List of test results """ ### Write your code below here ### results_test = [] for bird_index, label in enumerate(list_labels): qc = QuantumCircuit(num_qubits) new_mapping = amplitude_embedding(num_qubits, bird_index) classifier = new_mapping.compose(ansatz) transpiled_classifier = pm.run(classifier) transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) pub = (transpiled_classifier, transpiled_obs, opt_params) job = estimator.run([pub]) result = abs(job.result()[0].data.evs) results_test.append(result) ### Don't change any code past this line ### return results_test estimator = Estimator(backend=fake_backend) estimator.options.default_shots = 5000 pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) opt_params = np.load('opt_params_shallow_VQC.npy') # Load optimal parameters results_test = test_shallow_VQC(list_labels, ansatz, obs, opt_params, estimator, pm) print(f"Performance: {compute_performance(results_test, list_labels)}") fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data') ax.set_ylabel('Cost') ax.set_xlabel('State index') ax.plot(list_labels, 'k-', linewidth=3, alpha=0.6, label='Labels') ax.plot(results_test, 'o--', label='Fake Backend') ax.legend() # Submit your answer using following code grade_lab4_ex6(results_test) # Expected answer type: list[float] service = QiskitRuntimeService() backend = service.backend("ibm_osaka") def test_shallow_VQC_QPU(list_labels, anstaz, obs, opt_params, options, backend): """Return the performance of the classifier Parameters: list_labels (list): List of labels ansatz (QuantumCircuit): Parameterized ansatz circuit obs (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Estimator options backend (service.backend): Backend to run the job Returns: job_id (str): Job ID """ estimator = Estimator(backend=backend, options=options) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) pubs = [] for bird, label in enumerate(list_labels): ### Write your code below here ### qc = QuantumCircuit(num_qubits) new_mapping = amplitude_embedding(num_qubits, bird) classifier = new_mapping.compose(ansatz) transpiled_classifier = pm.run(classifier) transpiled_obs = obs.apply_layout(layout=transpiled_classifier.layout) pub = (transpiled_classifier, transpiled_obs, opt_params) job = estimator.run([pub]) result = abs(job.result()[0].data.evs) results_test.append(result) ### Don't change any code past this line ### pub = (transpiled_classifier, transpiled_obs, opt_params) pubs.append(pub) job = estimator.run(pubs) job_id = job.job_id() print(f"Job ID: {job_id}") print(f"Status: {job.status()}") return job_id ## No DD, no TREX (no ZNE) options_0 = EstimatorOptions( default_shots= 5000, optimization_level= 0, resilience_level= 0, dynamical_decoupling = {'enable': False, 'sequence_type': 'XpXm'}, twirling= {'enable_measure': False} )#Add your code here ## DD + TREX (no ZNE) options_1 = options_1 = EstimatorOptions() options_1.optimization_level =0 options_1.resilience_level = 1 options_1.default_shots = 5000 options_1.dynamical_decoupling.enable = True options_1.dynamical_decoupling.sequence_type = 'XpXm' options_1.twirling.enable_measure = False #Add your code here # Submit your answer using following code grade_lab4_ex7(options_0, options_1) # Expected answer type: EstimatorOptions, EstimatorOptions def retrieve_job(job_id): ''' Retrieve results from job_id ''' job = service.job(job_id) results_test = [] errors_test = [] for result in job.result(): results_test.append(abs(result.data.evs)) errors_test.append(abs(result.data.stds)) return results_test, errors_test ## No DD, no TREX (no ZNE) job_id_0 = test_shallow_VQC_QPU(list_labels, ansatz, obs, opt_params, options_0, backend) ## DD + TREX (no ZNE) job_id_1 = test_shallow_VQC_QPU(list_labels, ansatz, obs, opt_params, options_1, backend) results_test_0_DD, errors_test_0_DD = retrieve_job() #(Add job_id 0 here) results_test_1_DD, errors_test_1_DD = retrieve_job() #(Add job_id 1 here) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for no DD + no TREX: {compute_performance(results_test_0_DD, list_labels):.3f}") print(f"Performance for DD + TREX: {compute_performance(results_test_1_DD, list_labels):.3f}") ax.errorbar(range(10), results_test_0_DD, fmt='-o', yerr=errors_test_0_DD, color='tab:orange', label='Osaka no EM') ax.errorbar(range(10), results_test_1_DD, fmt='-o', yerr=errors_test_1_DD, color='tab:blue', label='Osaka TREX + DD') ax.plot(list_labels, 'k-', label='Labels') ax.legend()
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
### Install Qiskit and relevant packages, if needed ### IMPORTANT: Make sure you are on 3.10 > python < 3.12 ''' %pip install qiskit[visualization]==1.0.2 %pip install qiskit-ibm-runtime %pip install qiskit-aer %pip install graphviz %pip install qiskit-serverless -U %pip install qiskit-transpiler-service -U ''' %pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git -U # Import all in one cell import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.quantum_info import SparsePauliOp from qiskit.circuit.library import RealAmplitudes from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.visualization import plot_gate_map, plot_circuit_layout, plot_distribution from qiskit.circuit import ParameterVector from qiskit_aer import AerSimulator from qiskit_ibm_runtime import ( QiskitRuntimeService, EstimatorV2 as Estimator, SamplerV2 as Sampler, EstimatorOptions ) import warnings warnings.filterwarnings('ignore') # qc-grader should be 0.18.13 (or higher) import qc_grader qc_grader.__version__ from qc_grader.challenges.iqc_2024 import grade_lab_bonus_ex1, grade_lab_bonus_ex2, grade_lab_bonus_ex3 def old_amplitude_embedding(num_qubits, bird_index): """Create amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ def generate_GHZ(qc): qc.h(0) for i, j in zip(range(num_qubits-1), range(1,num_qubits)): qc.cx(i, j) ### Write your code below here ### qc = QuantumCircuit(num_qubits) if bird_index < 5: generate_GHZ(qc) bin_string = format(bird_index, '0{0}b'.format(num_qubits)) for i in reversed(range(len(bin_string))): if bin_string[i] == '1': qc.x(num_qubits-i-1) ### Don't change any code past this line ### return qc num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_osaka") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 # You can check different birds by changing the index qc = old_amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) def new_amplitude_embedding(num_qubits, bird_index): """Create efficient amplitude embedding circuit Parameters: num_qubits (int): Number of qubits for the ansatz bird_index (int): Data index of the bird Returns: qc (QuantumCircuit): Quantum circuit with amplitude embedding of the bird """ ### Write your code below here ### ### Don't change any code past this line ### return qc num_qubits = 50 index = 0 # Change to different values for testing qc = new_amplitude_embedding(num_qubits, index) qc.measure_all() # Define the backend and the pass manager aer_sim = AerSimulator(method='matrix_product_state') pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(qc) # Define the sampler with the number of shots sampler = Sampler(backend=aer_sim) result = sampler.run([isa_circuit]).result() samp_dist = result[0].data.meas.get_counts() plot_distribution(samp_dist, figsize=(10, 3)) num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_kyoto") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 #You can check different birds by changing the index qc = new_amplitude_embedding(num_qubits, index_bird) pm = generate_preset_pass_manager(optimization_level=3, backend=fake_backend) transpiled_qc = pm.run(qc) print('Depth of two-qubit gates: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab_bonus_ex1(new_amplitude_embedding(50,3)) # Expected answer type: QuantumCircuit def generate_old_ansatz(qubits): qc = RealAmplitudes(qubits, reps=1, entanglement='pairwise') return qc num_qubits = 50 # Choose a real backend service = QiskitRuntimeService() backend = service.backend("ibm_kyoto") # Define a fake backend with the same properties as the real backend fake_backend = AerSimulator.from_backend(backend) index_bird = 0 # You can check different birds by changing the index qc = new_amplitude_embedding(num_qubits, index_bird) ansatz = generate_old_ansatz(num_qubits) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) transpiled_qc = pm.run(qc.compose(ansatz)) print('Depth new mapping + old ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) # transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) def generate_ansatz(num_qubits): """Generate a `RealAmplitudes` ansatz where all qubits are entangled with each other Parameters: num_qubits (int): Number of qubits for the ansatz Returns: qc (QuantumCircuit): Quantum circuit with the generated ansatz """ ### Write your code below here ### ### Don't change any code past this line ### return qc index_bird = 0 # You can check different birds by changing the index new_mapping_qc = new_amplitude_embedding(num_qubits, index_bird) ansatz = generate_ansatz(num_qubits) pm = generate_preset_pass_manager(optimization_level=3, backend=backend) transpiled_qc = pm.run(new_mapping_qc.compose(ansatz)) print('Depth new mapping + new ansatz: ', transpiled_qc.depth(lambda x: len(x.qubits) == 2)) # transpiled_qc.draw(output="mpl", fold=False, idle_wires=False) # Submit your answer using following code grade_lab_bonus_ex2(transpiled_qc) # Expected answer type: QuantumCircuit # Generate this to match your ansatz source_list = # Add your code here def generalize_optimal_params(num_qubits, ansatz, source_list): """Generate a `list of optimal parameters for N qubits Parameters: num_qubits (int): Number of qubits for the ansatz ansatz (QuantumCircuit): Ansatz for our VQC source_list (list): List of qubits used as source to entangle other qubits Returns: opt_params (list): List of optimal parameters generated for N qubits """ opt_params = np.zeros(ansatz.num_parameters) for i in range(ansatz.num_parameters//2): if i in source_list: opt_params[i] = np.pi return opt_params def test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend): """Tests the shallow VQC on a QPU Parameters: num_qubits (int): Number of qubits for the ansatz list_labels (list): List of labels obs: (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Options for Estimator primitive backend (Backend): Real backend from IBM Quantum to run the job Returns: job_id (str): Job ID for Quantum job """ ### Write your code below here ### ### Don't change any code past this line ### return job_id def retrieve_job(job_id): """Retrieve test results from job id Parameters: job_id (str): Job ID Returns: results_test (list): List of test results errors_test (list): List of test errors """ job = service.job(job_id) results_test = [] errors_test = [] for result in job.result(): results_test.append(abs(abs(result.data.evs)-1)) #COST FUNCTION HAS A -1 NOW!!! errors_test.append(abs(result.data.stds)) return results_test, errors_test def test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, backend): """Tests the shallow VQC on a QPU Parameters: num_qubits (int): Number of qubits for the ansatz list_labels (list): List of labels obs: (SparsePauliOp): Observable opt_params (ndarray): Array of optimized parameters options (EstimatorOptions): Options for Estimator primitive backend (Backend): AerSimulator backend to run the job Returns: results_test (list): List of test results """ results_test = [] ### Write your code below here ### ### Don't change any code past this line ### result = job.result()[0].data.evs results_test.append(abs(abs(result)-1)) # COST FUNCTION NOW HAS A -1!!! return results_test def compute_performance(result_list, list_labels): """Return the performance of the classifier Parameters: result_list (list): List of results list_labels (list): List of labels Returns: performance (float): Performance of the classifier """ ### Write your code below here ### ### Don't change any code past this line ### return performance num_qubits = 50 aer_sim = AerSimulator(method='matrix_product_state') pm = generate_preset_pass_manager(backend=aer_sim, optimization_level=3) isa_circuit = pm.run(new_mapping_qc) list_labels = np.append(np.ones(5), np.zeros(5)) obs = SparsePauliOp("Z"*num_qubits) opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list) options = EstimatorOptions() results_test_aer_sim = test_shallow_VQC_CPU(num_qubits, list_labels, obs, opt_params, options, aer_sim) fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title('Cost on test data MPS') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for resilience 0: {compute_performance(results_test_aer_sim, list_labels)}") ax.plot(results_test_aer_sim, 'o-', color='tab:red', label='MPS Num qubits = ' + str(num_qubits)) ax.plot(list_labels, 'k-', label='Labels') ax.legend() # Submit your answer using following code grade_lab_bonus_ex3(results_test_aer_sim) # Expected variable types: List service = QiskitRuntimeService() backend = service.backend("select_your_device") # RUN JOBS num_qubits = 50 obs = SparsePauliOp("Z"*num_qubits) opt_params = generalize_optimal_params(num_qubits, generate_ansatz(num_qubits), source_list) for resilience in [0,1]: DD = True options = EstimatorOptions(default_shots = 5_000, optimization_level=0, resilience_level=resilience) options.dynamical_decoupling.enable = DD options.dynamical_decoupling.sequence_type = 'XpXm' # OPTIONAL # options.resilience.zne_mitigation = True # options.resilience.zne.noise_factors = (1, 1.2, 1.5) # options.resilience.zne.extrapolator = ('exponential', 'linear', 'polynomial_degree_2') #order matters job_id = test_shallow_VQC_QPU(num_qubits, list_labels, obs, opt_params, options, backend) results_test_0_DD, errors_test_0_DD = retrieve_job('Enter your JobID for resilience level 0') results_test_1_DD, errors_test_1_DD = retrieve_job('Enter your JobID for resilience level 1') fig, ax = plt.subplots(1, 1, figsize=(7,5)) ax.set_title(f'Test of a {num_qubits} qubit VQC on {backend.name}') ax.set_ylabel('Cost') ax.set_xlabel('State index') print(f"Performance for no DD + no TREX: {compute_performance(results_test_0_DD, list_labels):.3f}") print(f"Performance for DD + TREX: {compute_performance(results_test_1_DD, list_labels):.3f}") ax.errorbar(range(10), results_test_0_DD, fmt='--o', yerr=errors_test_0_DD, color='tab:orange', label=f'{backend.name} RL=0 shots={options.default_shots} DD={options.dynamical_decoupling.enable}') ax.errorbar(range(10), results_test_1_DD, fmt='--o', yerr=errors_test_1_DD, color='tab:blue', label=f'{backend.name} RL=1 shots={options.default_shots} DD={options.dynamical_decoupling.enable}') ax.plot(list_labels, 'k-', label='Labels') ax.legend()
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# transpile_parallel.py from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_transpiler_service.transpiler_service import TranspilerService from qiskit_serverless import get_arguments, save_result, distribute_task, get from qiskit_ibm_runtime import QiskitRuntimeService from timeit import default_timer as timer @distribute_task(target={"cpu": 2}) def transpile_parallel(circuit: QuantumCircuit, config): """Distributed transpilation for an abstract circuit into an ISA circuit for a given backend.""" transpiled_circuit = config.run(circuit) return transpiled_circuit # Get program arguments arguments = get_arguments() circuits = arguments.get("circuits") backend_name = arguments.get("backend_name") # Get backend service = QiskitRuntimeService(channel="ibm_quantum") backend = service.get_backend(backend_name) # Define Configs optimization_levels = [1,2,3] pass_managers = [generate_preset_pass_manager(optimization_level=level, backend=backend) for level in optimization_levels] transpiler_services = [ {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': False, 'optimization_level': 3}, {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': True, 'optimization_level': 3} ] configs = pass_managers + transpiler_services # Start process print("Starting timer") start = timer() # run distributed tasks as async function # we get task references as a return type sample_task_references = [] for circuit in circuits: sample_task_references.append([transpile_parallel(circuit, config) for config in configs]) # now we need to collect results from task references results = get([task for subtasks in sample_task_references for task in subtasks]) end = timer() # Record execution time execution_time_serverless = end-start print("Execution time: ", execution_time_serverless) save_result({ "transpiled_circuits": results, "execution_time" : execution_time_serverless })
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
import numpy as np from qiskit import transpile, QuantumCircuit def version_check(): import qiskit if qiskit.version.VERSION == '1.0.2': return print("You have the right version! Enjoy the challenge!") else: return print("please install right version by copy/paste and execute - !pip install 'qiskit[visualization]' == 1.0.2'") def transpile_scoring(circ, layout, backend): """ A custom cost function that includes T1 and T2 computed during idle periods Parameters: circ (QuantumCircuit): circuit of interest layouts (list of lists): List of specified layouts backend (IBMQBackend): An IBM Quantum backend instance Returns: list: Tuples of layout and cost """ fid = 1 touched = set() dt = backend.dt num_qubits = backend.num_qubits error=0 t1s = [backend.qubit_properties(qq).t1 for qq in range(num_qubits)] t2s = [backend.qubit_properties(qq).t2 for qq in range(num_qubits)] for item in circ._data: for gate in backend.operation_names: if item[0].name == gate: if (item[0].name == 'cz') or (item[0].name == 'ecr'): q0 = circ.find_bit(item[1][0]).index q1 = circ.find_bit(item[1][1]).index fid *= 1 - backend.target[item[0].name][(q0, q1)].error touched.add(q0) touched.add(q1) elif item[0].name == 'measure': q0 = circ.find_bit(item[1][0]).index fid *= 1 - backend.target[item[0].name][(q0, )].error touched.add(q0) elif item[0].name == 'delay': q0 = circ.find_bit(item[1][0]).index # Ignore delays that occur before gates # This assumes you are in ground state and errors # do not occur. if q0 in touched: time = item[0].duration * dt fid *= 1-qubit_error(time, t1s[q0], t2s[q0]) else: q0 = circ.find_bit(item[1][0]).index fid *= 1 - backend.target[item[0].name][(q0, )].error touched.add(q0) return fid def qubit_error(time, t1, t2): """Compute the approx. idle error from T1 and T2 Parameters: time (float): Delay time in sec t1 (float): T1 time in sec t2 (float): T2 time in sec Returns: float: Idle error """ t2 = min(t1, t2) rate1 = 1/t1 rate2 = 1/t2 p_reset = 1-np.exp(-time*rate1) p_z = (1-p_reset)*(1-np.exp(-time*(rate2-rate1)))/2 return p_z + p_reset
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
from qiskit_aer import AerSimulator import logging from typing import Optional import time import numpy as np from scipy.optimize import minimize from qiskit import QuantumCircuit from qiskit_ibm_runtime import ( EstimatorV2 as Estimator, SamplerV2 as Sampler, QiskitRuntimeService, Session, ) from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_serverless import ( distribute_task, get_arguments, get, save_result, ) def run(params, ansatz, hamiltonian, estimator, callback_dict): """Return callback function that uses Estimator instance, and stores intermediate values into a dictionary. Parameters: params (ndarray): Array of ansatz parameters ansatz (QuantumCircuit): Parameterized ansatz circuit hamiltonian (SparsePauliOp): Operator representation of Hamiltonian estimator (Estimator): Estimator primitive instance callback_dict (dict): Mutable dict for storing values Returns: Callable: Callback function object """ result = estimator.run([(ansatz, [hamiltonian], [params])]).result() energy = result[0].data.evs[0] # Keep track of the number of iterations callback_dict["iters"] += 1 # Set the prev_vector to the latest one callback_dict["prev_vector"] = params # Compute the value of the cost function at the current vector callback_dict["cost_history"].append(energy) # Grab the current time current_time = time.perf_counter() # Find the total time of the execute (after the 1st iteration) if callback_dict["iters"] > 1: callback_dict["_total_time"] += current_time - callback_dict["_prev_time"] # Set the previous time to the current time callback_dict["_prev_time"] = current_time # Compute the average time per iteration and round it time_str = ( round(callback_dict["_total_time"] / (callback_dict["iters"] - 1), 2) if callback_dict["_total_time"] else "-" ) # Print to screen on single line print( "Iters. done: {} [Avg. time per iter: {}]".format( callback_dict["iters"], time_str ), end="\r", flush=True, ) return energy, result def cost_func(*args, **kwargs): """Return estimate of energy from estimator Parameters: params (ndarray): Array of ansatz parameters ansatz (QuantumCircuit): Parameterized ansatz circuit hamiltonian (SparsePauliOp): Operator representation of Hamiltonian estimator (Estimator): Estimator primitive instance Returns: float: Energy estimate """ energy, result = run(*args, **kwargs) return energy def run_vqe(initial_parameters, ansatz, operator, estimator, method): callback_dict = { "prev_vector": None, "iters": 0, "cost_history": [], "_total_time": 0, "_prev_time": None, } result = minimize( cost_func, initial_parameters, args=(ansatz, operator, estimator, callback_dict), method=method, ) return result, callback_dict if __name__ == "__main__": arguments = get_arguments() service = arguments.get("service") ansatz = arguments.get("ansatz") operator = arguments.get("operator") method = arguments.get("method", "COBYLA") initial_parameters = arguments.get("initial_parameters") if initial_parameters is None: initial_parameters = 2 * np.pi * np.random.rand(ansatz.num_parameters) if service: backend = service.least_busy(operational=True, simulator=False) else: backend = AerSimulator(method='density_matrix') if initial_parameters is None: initial_parameters = 2 * np.pi * np.random.rand(ansatz.num_parameters) if service: with Session(service=service, backend=backend) as session: estimator = Estimator(session=session) vqe_result, callback_dict = run_vqe( initial_parameters=initial_parameters, ansatz=ansatz, operator=operator, estimator=estimator, method=method, ) else: estimator = Estimator(backend=backend) vqe_result, callback_dict = run_vqe( initial_parameters=initial_parameters, ansatz=ansatz, operator=operator, estimator=estimator, method=method, ) save_result( { "optimal_point": vqe_result.x.tolist(), "optimal_value": vqe_result.fun, "optimizer_time": callback_dict.get("_total_time", 0), "iters": callback_dict["iters"], "cost_history" : callback_dict["cost_history"] } )
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector, plot_histogram from qiskit_textbook.problems import dj_problem_oracle def lab1_ex1(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) return qc state = Statevector.from_instruction(lab1_ex1()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex1 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex1(lab1_ex1()) def lab1_ex2(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) return qc state = Statevector.from_instruction(lab1_ex2()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex2 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex2(lab1_ex2()) def lab1_ex3(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.x(0) qc.h(0) return qc state = Statevector.from_instruction(lab1_ex3()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex3 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex3(lab1_ex3()) def lab1_ex4(): qc = QuantumCircuit(1) # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.sdg(0) return qc state = Statevector.from_instruction(lab1_ex4()) plot_bloch_multivector(state) from qc_grader import grade_lab1_ex4 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex4(lab1_ex4()) def lab1_ex5(): qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.cx(0,1) qc.x(0) return qc qc = lab1_ex5() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex5 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex5(lab1_ex5()) qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0 qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1 backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities def lab1_ex6(): # # # FILL YOUR CODE IN HERE # # qc = QuantumCircuit(3,3) qc.h(0) qc.cx(0,1) qc.cx(1,2) qc.y(1) return qc qc = lab1_ex6() qc.draw() # we draw the circuit from qc_grader import grade_lab1_ex6 # Note that the grading function is expecting a quantum circuit without measurements grade_lab1_ex6(lab1_ex6()) oraclenr = 4 # determines the oracle (can range from 1 to 5) oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles oracle.name = "DJ-Oracle" def dj_classical(n, input_str): # build a quantum circuit with n qubits and 1 classical readout bit dj_circuit = QuantumCircuit(n+1,1) # Prepare the initial state corresponding to your input bit string for i in range(n): if input_str[i] == '1': dj_circuit.x(i) # append oracle dj_circuit.append(oracle, range(n+1)) # measure the fourth qubit dj_circuit.measure(n,0) return dj_circuit n = 4 # number of qubits input_str = '1111' dj_circuit = dj_classical(n, input_str) dj_circuit.draw() # draw the circuit input_str = '1111' dj_circuit = dj_classical(n, input_str) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit, qasm_sim) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer) def lab1_ex7(): min_nr_inputs = 2 max_nr_inputs = 9 return [min_nr_inputs, max_nr_inputs] from qc_grader import grade_lab1_ex7 # Note that the grading function is expecting a list of two integers grade_lab1_ex7(lab1_ex7()) n=4 def psi_0(n): qc = QuantumCircuit(n+1,n) # Build the state (|00000> - |10000>)/sqrt(2) # # # FILL YOUR CODE IN HERE # # qc.x(4) qc.h(4) return qc dj_circuit = psi_0(n) dj_circuit.draw() def psi_1(n): # obtain the |psi_0> = |00001> state qc = psi_0(n) # create the superposition state |psi_1> # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # # qc.barrier() return qc dj_circuit = psi_1(n) dj_circuit.draw() def psi_2(oracle,n): # circuit to obtain psi_1 qc = psi_1(n) # append the oracle qc.append(oracle, range(n+1)) return qc dj_circuit = psi_2(oracle, n) dj_circuit.draw() def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25]) qc = psi_2(oracle, n) # apply n-fold hadamard gate # # # FILL YOUR CODE IN HERE # # qc.h(0) qc.h(1) qc.h(2) qc.h(3) # add the measurement by connecting qubits to classical bits # # qc.measure(0,0) qc.measure(1,1) qc.measure(2,2) qc.measure(3,3) # # return qc dj_circuit = lab1_ex8(oracle, n) dj_circuit.draw() from qc_grader import grade_lab1_ex8 # Note that the grading function is expecting a quantum circuit with measurements grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n)) qasm_sim = Aer.get_backend('qasm_simulator') transpiled_dj_circuit = transpile(dj_circuit, qasm_sim) qobj = assemble(transpiled_dj_circuit) results = qasm_sim.run(qobj).result() answer = results.get_counts() plot_histogram(answer)
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# transpile_parallel.py from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_transpiler_service.transpiler_service import TranspilerService from qiskit_serverless import get_arguments, save_result, distribute_task, get from qiskit_ibm_runtime import QiskitRuntimeService from timeit import default_timer as timer @distribute_task(target={"cpu": 2}) def transpile_parallel(circuit: QuantumCircuit, config): """Distributed transpilation for an abstract circuit into an ISA circuit for a given backend.""" transpiled_circuit = config.run(circuit) return transpiled_circuit # Get program arguments arguments = get_arguments() circuits = arguments.get("circuits") backend_name = arguments.get("backend_name") # Get backend service = QiskitRuntimeService(channel="ibm_quantum") backend = service.get_backend(backend_name) # Define Configs optimization_levels = [1,2,3] pass_managers = [generate_preset_pass_manager(optimization_level=level, backend=backend) for level in optimization_levels] transpiler_services = [ {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': False, 'optimization_level': 3}, {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': True, 'optimization_level': 3} ] configs = pass_managers + transpiler_services # Start process print("Starting timer") start = timer() # run distributed tasks as async function # we get task references as a return type sample_task_references = [] for circuit in circuits: sample_task_references.append([transpile_parallel(circuit, config) for config in configs]) # now we need to collect results from task references results = get([task for subtasks in sample_task_references for task in subtasks]) end = timer() # Record execution time execution_time_serverless = end-start print("Execution time: ", execution_time_serverless) save_result({ "transpiled_circuits": results, "execution_time" : execution_time_serverless })
https://github.com/ronitd2002/IBM-Quantum-challenge-2024
ronitd2002
# transpile_parallel.py from qiskit import QuantumCircuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_transpiler_service.transpiler_service import TranspilerService from qiskit_serverless import get_arguments, save_result, distribute_task, get from qiskit_ibm_runtime import QiskitRuntimeService from timeit import default_timer as timer @distribute_task(target={"cpu": 2}) def transpile_parallel(circuit: QuantumCircuit, config): """Distributed transpilation for an abstract circuit into an ISA circuit for a given backend.""" transpiled_circuit = config.run(circuit) return transpiled_circuit # Get program arguments arguments = get_arguments() circuits = arguments.get("circuits") backend_name = arguments.get("backend_name") # Get backend service = QiskitRuntimeService(channel="ibm_quantum") backend = service.get_backend(backend_name) # Define Configs optimization_levels = [1,2,3] pass_managers = [generate_preset_pass_manager(optimization_level=level, backend=backend) for level in optimization_levels] transpiler_services = [ {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': False, 'optimization_level': 3}, {'service': TranspilerService(backend_name="ibm_brisbane", ai="false", optimization_level=3,), 'ai': True, 'optimization_level': 3} ] configs = pass_managers + transpiler_services # Start process print("Starting timer") start = timer() # run distributed tasks as async function # we get task references as a return type sample_task_references = [] for circuit in circuits: sample_task_references.append([transpile_parallel(circuit, config) for config in configs]) # now we need to collect results from task references results = get([task for subtasks in sample_task_references for task in subtasks]) end = timer() # Record execution time execution_time_serverless = end-start print("Execution time: ", execution_time_serverless) save_result({ "transpiled_circuits": results, "execution_time" : execution_time_serverless })