repo
stringclasses
885 values
file
stringclasses
741 values
content
stringlengths
4
215k
https://github.com/qiskit-community/qiskit-dell-runtime
qiskit-community
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # Copyright 2021 Dell (www.dell.com) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from qiskit.providers import JobV1 from qiskit.providers import JobStatus, JobError from qiskit import transpile from qiskit_aer import Aer import functools def requires_submit(func): """ Decorator to ensure that a submit has been performed before calling the method. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs): if self.my_job is None: raise JobError("Job not submitted yet!. You have to .submit() first!") return func(self, *args, **kwargs) return _wrapper class EmulatorJob(JobV1): def __init__(self, backend, job_id, circuit, shots): super().__init__(backend, job_id) self.circuit = circuit self.shots = shots self.my_job = None @requires_submit def result(self, timeout=None): return self.my_job.result(timeout=timeout) def submit(self): backend = Aer.get_backend('aer_simulator') self.my_job = backend.run(self.circuit, shots = self.shots) @requires_submit def cancel(self): return self.my_job.cancel() @requires_submit def status(self): return self.my_job.status()
https://github.com/2lambda123/Qiskit-qiskit
2lambda123
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2020. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Sabre Swap pass""" import unittest import itertools import ddt import numpy.random from qiskit.circuit import Clbit, ControlFlowOp, Qubit from qiskit.circuit.library import CCXGate, HGate, Measure, SwapGate from qiskit.circuit.classical import expr from qiskit.circuit.random import random_circuit from qiskit.compiler.transpiler import transpile from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.providers.fake_provider import FakeMumbai, FakeMumbaiV2 from qiskit.transpiler.passes import SabreSwap, TrivialLayout, CheckMap from qiskit.transpiler import CouplingMap, Layout, PassManager, Target, TranspilerError from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.test._canonical import canonicalize_control_flow from qiskit.utils import optionals def looping_circuit(uphill_swaps=1, additional_local_minimum_gates=0): """A circuit that causes SabreSwap to loop infinitely. This looks like (using cz gates to show the symmetry, though we actually output cx for testing purposes): .. parsed-literal:: q_0: ─■──────────────── │ q_1: ─┼──■───────────── │ │ q_2: ─┼──┼──■────────── │ │ │ q_3: ─┼──┼──┼──■─────── │ │ │ │ q_4: ─┼──┼──┼──┼─────■─ │ │ │ │ │ q_5: ─┼──┼──┼──┼──■──■─ │ │ │ │ │ q_6: ─┼──┼──┼──┼──┼──── │ │ │ │ │ q_7: ─┼──┼──┼──┼──■──■─ │ │ │ │ │ q_8: ─┼──┼──┼──┼─────■─ │ │ │ │ q_9: ─┼──┼──┼──■─────── │ │ │ q_10: ─┼──┼──■────────── │ │ q_11: ─┼──■───────────── │ q_12: ─■──────────────── where `uphill_swaps` is the number of qubits separating the inner-most gate (representing how many swaps need to be made that all increase the heuristics), and `additional_local_minimum_gates` is how many extra gates to add on the outside (these increase the size of the region of stability). """ outers = 4 + additional_local_minimum_gates n_qubits = 2 * outers + 4 + uphill_swaps # This is (most of) the front layer, which is a bunch of outer qubits in the # coupling map. outer_pairs = [(i, n_qubits - i - 1) for i in range(outers)] inner_heuristic_peak = [ # This gate is completely "inside" all the others in the front layer in # terms of the coupling map, so it's the only one that we can in theory # make progress towards without making the others worse. (outers + 1, outers + 2 + uphill_swaps), # These are the only two gates in the extended set, and they both get # further apart if you make a swap to bring the above gate closer # together, which is the trick that creates the "heuristic hill". (outers, outers + 1), (outers + 2 + uphill_swaps, outers + 3 + uphill_swaps), ] qc = QuantumCircuit(n_qubits) for pair in outer_pairs + inner_heuristic_peak: qc.cx(*pair) return qc @ddt.ddt class TestSabreSwap(QiskitTestCase): """Tests the SabreSwap pass.""" def test_trivial_case(self): """Test that an already mapped circuit is unchanged. ┌───┐┌───┐ q_0: ──■──┤ H ├┤ X ├──■── ┌─┴─┐└───┘└─┬─┘ │ q_1: ┤ X ├──■────■────┼── └───┘┌─┴─┐ │ q_2: ──■──┤ X ├───────┼── ┌─┴─┐├───┤ │ q_3: ┤ X ├┤ X ├───────┼── └───┘└─┬─┘ ┌─┴─┐ q_4: ───────■───────┤ X ├ └───┘ """ coupling = CouplingMap.from_ring(5) qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(0, 1) # free qc.cx(2, 3) # free qc.h(0) # free qc.cx(1, 2) # F qc.cx(1, 0) qc.cx(4, 3) # F qc.cx(0, 4) passmanager = PassManager(SabreSwap(coupling, "basic")) new_qc = passmanager.run(qc) self.assertEqual(new_qc, qc) def test_trivial_with_target(self): """Test that an already mapped circuit is unchanged with target.""" coupling = CouplingMap.from_ring(5) target = Target(num_qubits=5) target.add_instruction(SwapGate(), {edge: None for edge in coupling.get_edges()}) qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(0, 1) # free qc.cx(2, 3) # free qc.h(0) # free qc.cx(1, 2) # F qc.cx(1, 0) qc.cx(4, 3) # F qc.cx(0, 4) passmanager = PassManager(SabreSwap(target, "basic")) new_qc = passmanager.run(qc) self.assertEqual(new_qc, qc) def test_lookahead_mode(self): """Test lookahead mode's lookahead finds single SWAP gate. ┌───┐ q_0: ──■──┤ H ├─────────────── ┌─┴─┐└───┘ q_1: ┤ X ├──■────■─────────■── └───┘┌─┴─┐ │ │ q_2: ──■──┤ X ├──┼────■────┼── ┌─┴─┐└───┘┌─┴─┐┌─┴─┐┌─┴─┐ q_3: ┤ X ├─────┤ X ├┤ X ├┤ X ├ └───┘ └───┘└───┘└───┘ q_4: ───────────────────────── """ coupling = CouplingMap.from_line(5) qr = QuantumRegister(5, "q") qc = QuantumCircuit(qr) qc.cx(0, 1) # free qc.cx(2, 3) # free qc.h(0) # free qc.cx(1, 2) # free qc.cx(1, 3) # F qc.cx(2, 3) # E qc.cx(1, 3) # E pm = PassManager(SabreSwap(coupling, "lookahead")) new_qc = pm.run(qc) self.assertEqual(new_qc.num_nonlocal_gates(), 7) def test_do_not_change_cm(self): """Coupling map should not change. See https://github.com/Qiskit/qiskit-terra/issues/5675""" cm_edges = [(1, 0), (2, 0), (2, 1), (3, 2), (3, 4), (4, 2)] coupling = CouplingMap(cm_edges) passmanager = PassManager(SabreSwap(coupling)) _ = passmanager.run(QuantumCircuit(coupling.size())) self.assertEqual(set(cm_edges), set(coupling.get_edges())) def test_do_not_reorder_measurements(self): """Test that SabreSwap doesn't reorder measurements to the same classical bit. With the particular coupling map used in this test and the 3q ccx gate, the routing would invariably the measurements if the classical successors are not accurately tracked. Regression test of gh-7950.""" coupling = CouplingMap([(0, 2), (2, 0), (1, 2), (2, 1)]) qc = QuantumCircuit(3, 1) qc.compose(CCXGate().definition, [0, 1, 2], []) # Unroll CCX to 2q operations. qc.h(0) qc.barrier() qc.measure(0, 0) # This measure is 50/50 between the Z states. qc.measure(1, 0) # This measure always overwrites with 0. passmanager = PassManager(SabreSwap(coupling)) transpiled = passmanager.run(qc) last_h = transpiled.data[-4] self.assertIsInstance(last_h.operation, HGate) first_measure = transpiled.data[-2] second_measure = transpiled.data[-1] self.assertIsInstance(first_measure.operation, Measure) self.assertIsInstance(second_measure.operation, Measure) # Assert that the first measure is on the same qubit that the HGate was applied to, and the # second measurement is on a different qubit (though we don't care which exactly - that # depends a little on the randomisation of the pass). self.assertEqual(last_h.qubits, first_measure.qubits) self.assertNotEqual(last_h.qubits, second_measure.qubits) # The 'basic' method can't get stuck in the same way. @ddt.data("lookahead", "decay") def test_no_infinite_loop(self, method): """Test that the 'release value' mechanisms allow SabreSwap to make progress even on circuits that get stuck in a stable local minimum of the lookahead parameters.""" qc = looping_circuit(3, 1) qc.measure_all() coupling_map = CouplingMap.from_line(qc.num_qubits) routing_pass = PassManager(SabreSwap(coupling_map, method)) n_swap_gates = 0 def leak_number_of_swaps(cls, *args, **kwargs): nonlocal n_swap_gates n_swap_gates += 1 if n_swap_gates > 1_000: raise Exception("SabreSwap seems to be stuck in a loop") # pylint: disable=bad-super-call return super(SwapGate, cls).__new__(cls, *args, **kwargs) with unittest.mock.patch.object(SwapGate, "__new__", leak_number_of_swaps): routed = routing_pass.run(qc) routed_ops = routed.count_ops() del routed_ops["swap"] self.assertEqual(routed_ops, qc.count_ops()) couplings = { tuple(routed.find_bit(bit).index for bit in instruction.qubits) for instruction in routed.data if len(instruction.qubits) == 2 } # Asserting equality to the empty set gives better errors on failure than asserting that # `couplings <= coupling_map`. self.assertEqual(couplings - set(coupling_map.get_edges()), set()) # Assert that the same keys are produced by a simulation - this is a test that the inserted # swaps route the qubits correctly. if not optionals.HAS_AER: return from qiskit import Aer sim = Aer.get_backend("aer_simulator") in_results = sim.run(qc, shots=4096).result().get_counts() out_results = sim.run(routed, shots=4096).result().get_counts() self.assertEqual(set(in_results), set(out_results)) def test_classical_condition(self): """Test that :class:`.SabreSwap` correctly accounts for classical conditions in its reckoning on whether a node is resolved or not. If it is not handled correctly, the second gate might not appear in the output. Regression test of gh-8040.""" with self.subTest("1 bit in register"): qc = QuantumCircuit(2, 1) qc.z(0) qc.z(0).c_if(qc.cregs[0], 0) cm = CouplingMap([(0, 1), (1, 0)]) expected = PassManager([TrivialLayout(cm)]).run(qc) actual = PassManager([TrivialLayout(cm), SabreSwap(cm)]).run(qc) self.assertEqual(expected, actual) with self.subTest("multiple registers"): cregs = [ClassicalRegister(3), ClassicalRegister(4)] qc = QuantumCircuit(QuantumRegister(2, name="q"), *cregs) qc.z(0) qc.z(0).c_if(cregs[0], 0) qc.z(0).c_if(cregs[1], 0) cm = CouplingMap([(0, 1), (1, 0)]) expected = PassManager([TrivialLayout(cm)]).run(qc) actual = PassManager([TrivialLayout(cm), SabreSwap(cm)]).run(qc) self.assertEqual(expected, actual) def test_classical_condition_cargs(self): """Test that classical conditions are preserved even if missing from cargs DAGNode field. Created from reproduction in https://github.com/Qiskit/qiskit-terra/issues/8675 """ with self.subTest("missing measurement"): qc = QuantumCircuit(3, 1) qc.cx(0, 2).c_if(0, 0) qc.measure(1, 0) qc.h(2).c_if(0, 0) expected = QuantumCircuit(3, 1) expected.swap(1, 2) expected.cx(0, 1).c_if(0, 0) expected.measure(2, 0) expected.h(1).c_if(0, 0) result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc) self.assertEqual(result, expected) with self.subTest("reordered measurement"): qc = QuantumCircuit(3, 1) qc.cx(0, 1).c_if(0, 0) qc.measure(1, 0) qc.h(0).c_if(0, 0) expected = QuantumCircuit(3, 1) expected.cx(0, 1).c_if(0, 0) expected.measure(1, 0) expected.h(0).c_if(0, 0) result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc) self.assertEqual(result, expected) def test_conditional_measurement(self): """Test that instructions with cargs and conditions are handled correctly.""" qc = QuantumCircuit(3, 2) qc.cx(0, 2).c_if(0, 0) qc.measure(2, 0).c_if(1, 0) qc.h(2).c_if(0, 0) qc.measure(1, 1) expected = QuantumCircuit(3, 2) expected.swap(1, 2) expected.cx(0, 1).c_if(0, 0) expected.measure(1, 0).c_if(1, 0) expected.h(1).c_if(0, 0) expected.measure(2, 1) result = SabreSwap(CouplingMap.from_line(3), seed=12345)(qc) self.assertEqual(result, expected) @ddt.data("basic", "lookahead", "decay") def test_deterministic(self, heuristic): """Test that the output of the SabreSwap pass is deterministic for a given random seed.""" width = 40 # The actual circuit is unimportant, we just need one with lots of scoring degeneracy. qc = QuantumCircuit(width) for i in range(width // 2): qc.cx(i, i + (width // 2)) for i in range(0, width, 2): qc.cx(i, i + 1) dag = circuit_to_dag(qc) coupling = CouplingMap.from_line(width) pass_0 = SabreSwap(coupling, heuristic, seed=0, trials=1) pass_1 = SabreSwap(coupling, heuristic, seed=1, trials=1) dag_0 = pass_0.run(dag) dag_1 = pass_1.run(dag) # This deliberately avoids using a topological order, because that introduces an opportunity # for the re-ordering to sort the swaps back into a canonical order. def normalize_nodes(dag): return [(node.op.name, node.qargs, node.cargs) for node in dag.op_nodes()] # A sanity check for the test - if unequal seeds don't produce different outputs for this # degenerate circuit, then the test probably needs fixing (or Sabre is ignoring the seed). self.assertNotEqual(normalize_nodes(dag_0), normalize_nodes(dag_1)) # Check that a re-run with the same seed produces the same circuit in the exact same order. self.assertEqual(normalize_nodes(dag_0), normalize_nodes(pass_0.run(dag))) def test_rejects_too_many_qubits(self): """Test that a sensible Python-space error message is emitted if the DAG has an incorrect number of qubits.""" pass_ = SabreSwap(CouplingMap.from_line(4)) qc = QuantumCircuit(QuantumRegister(5, "q")) with self.assertRaisesRegex(TranspilerError, "More qubits in the circuit"): pass_(qc) def test_rejects_too_few_qubits(self): """Test that a sensible Python-space error message is emitted if the DAG has an incorrect number of qubits.""" pass_ = SabreSwap(CouplingMap.from_line(4)) qc = QuantumCircuit(QuantumRegister(3, "q")) with self.assertRaisesRegex(TranspilerError, "Fewer qubits in the circuit"): pass_(qc) @ddt.ddt class TestSabreSwapControlFlow(QiskitTestCase): """Tests for control flow in sabre swap.""" def test_shared_block(self): """Test multiple control flow ops sharing the same block instance.""" inner = QuantumCircuit(2) inner.cx(0, 1) qreg = QuantumRegister(4, "q") outer = QuantumCircuit(qreg, ClassicalRegister(1)) for pair in itertools.permutations(range(outer.num_qubits), 2): outer.if_test((outer.cregs[0], 1), inner, pair, []) coupling = CouplingMap.from_line(4) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(circuit_to_dag(outer)) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_blocks_use_registers(self): """Test that control flow ops using registers still use registers after routing.""" num_qubits = 2 qreg = QuantumRegister(num_qubits, "q") cr1 = ClassicalRegister(1) cr2 = ClassicalRegister(1) qc = QuantumCircuit(qreg, cr1, cr2) with qc.if_test((cr1, False)): qc.cx(0, 1) qc.measure(0, cr2[0]) with qc.if_test((cr2, 0)): qc.cx(0, 1) coupling = CouplingMap.from_line(num_qubits) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(circuit_to_dag(qc)) outer_if_op = cdag.op_nodes(ControlFlowOp)[0].op self.assertEqual(outer_if_op.condition[0], cr1) inner_if_op = circuit_to_dag(outer_if_op.blocks[0]).op_nodes(ControlFlowOp)[0].op self.assertEqual(inner_if_op.condition[0], cr2) def test_pre_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[2]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[2]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[2]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(1, 2) expected.cx(0, 1) expected.measure(1, 2) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) efalse_body.x(1) new_order = [0, 2, 1, 3, 4] expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[2]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else_route_post_x(self): """test swap with if else controlflow construct; pre-cx and post x""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[0]]) qc.x(1) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(1, 2) expected.cx(0, 1) expected.measure(1, 2) new_order = [0, 2, 1, 3, 4] etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.x(2) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_post_if_else_route(self): """test swap with if else controlflow construct; post cx""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.barrier(qreg) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.cx(0, 2) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.barrier(qreg) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.barrier(qreg) expected.swap(1, 2) expected.cx(0, 1) expected.barrier(qreg) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else2(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) false_body = QuantumCircuit(qreg, creg[[0]]) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[0]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[0]], creg[[0]]) new_order = [0, 2, 1, 3, 4] expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[0]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_intra_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(1, 2) etrue_body.cx(0, 1) etrue_body.swap(1, 2) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(3, 4) efalse_body.swap(2, 3) efalse_body.cx(1, 2) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.swap(3, 4) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_if_else(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) etrue_body = QuantumCircuit(qreg, creg[[0]]) efalse_body = QuantumCircuit(qreg, creg[[0]]) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body.cx(0, 1) efalse_body.swap(0, 1) efalse_body.swap(3, 4) efalse_body.swap(2, 3) efalse_body.cx(1, 2) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.swap(3, 4) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_post_if_else(self): """test swap with if else controlflow construct; cx before, in, and after if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.h(3) qc.cx(3, 0) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(0, 1) expected.cx(1, 2) expected.measure(1, 0) etrue_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) etrue_body.cx(0, 1) efalse_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.cx(1, 2) efalse_body.swap(0, 1) efalse_body.swap(2, 3) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 2, 3, 4]], creg[[0]]) expected.h(3) expected.swap(1, 2) expected.cx(3, 2) expected.barrier() expected.measure(qreg, creg[[1, 2, 0, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_if_expr(self): """Test simple if conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.if_test(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=58, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_if_else_expr(self): """Test simple if/else conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) true = QuantumCircuit(4) true.cx(0, 1) true.cx(0, 2) true.cx(0, 3) false = QuantumCircuit(4) false.cx(3, 0) false.cx(3, 1) false.cx(3, 2) qc = QuantumCircuit(4, 2) qc.if_else(expr.logic_and(qc.clbits[0], qc.clbits[1]), true, false, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=58, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_no_layout_change(self): """test controlflow with no layout change needed""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 4]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) @ddt.data(1, 2, 3) def test_for_loop(self, nloops): """test stochastic swap with for_loop""" num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) for_body = QuantumCircuit(qreg) for_body.cx(0, 2) loop_parameter = None qc.for_loop(range(nloops), loop_parameter, for_body, qreg, []) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) efor_body = QuantumCircuit(qreg) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) loop_parameter = None expected.for_loop(range(nloops), loop_parameter, efor_body, qreg, []) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop(self): """test while loop""" num_qubits = 4 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(len(qreg)) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) while_body = QuantumCircuit(qreg, creg) while_body.reset(qreg[2:]) while_body.h(qreg[2:]) while_body.cx(0, 3) while_body.measure(qreg[3], creg[3]) qc.while_loop((creg, 0), while_body, qc.qubits, qc.clbits) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) ewhile_body = QuantumCircuit(qreg, creg) ewhile_body.reset(qreg[2:]) ewhile_body.h(qreg[2:]) ewhile_body.swap(0, 1) ewhile_body.swap(2, 3) ewhile_body.cx(1, 2) ewhile_body.measure(qreg[2], creg[3]) ewhile_body.swap(1, 0) ewhile_body.swap(3, 2) expected.while_loop((creg, 0), ewhile_body, expected.qubits, expected.clbits) expected.barrier() expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop_expr(self): """Test simple while loop with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.while_loop(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_switch_implicit_carg_use(self): """Test that a switch statement that uses cargs only implicitly via its ``target`` attribute and not explicitly in bodies of the cases is routed correctly, with the dependencies fulfilled correctly.""" coupling = CouplingMap.from_line(4) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) body = QuantumCircuit([Qubit()]) body.x(0) # If the classical wire condition isn't respected, then the switch would appear in the front # layer and be immediately eligible for routing, which would produce invalid output. qc = QuantumCircuit(4, 1) qc.cx(0, 1) qc.cx(1, 2) qc.cx(0, 2) qc.measure(2, 0) qc.switch(expr.lift(qc.clbits[0]), [(False, body.copy()), (True, body.copy())], [3], []) expected = QuantumCircuit(4, 1) expected.cx(0, 1) expected.cx(1, 2) expected.swap(2, 1) expected.cx(0, 1) expected.measure(1, 0) expected.switch( expr.lift(expected.clbits[0]), [(False, body.copy()), (True, body.copy())], [3], [] ) self.assertEqual(pass_(qc), expected) def test_switch_single_case(self): """Test routing of 'switch' with just a single case.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) expected.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg[:]) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_nonexhaustive(self): """Test routing of 'switch' with several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(2, 3) case2.cx(4, 3) case2.swap(2, 3) expected.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_expr_single_case(self): """Test routing of 'switch' with an `Expr` target and just a single case.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(expr.bit_or(creg, 5), [(0, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) expected.switch(expr.bit_or(creg, 5), [(0, case0)], qreg[[0, 1, 2]], creg[:]) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_expr_nonexhaustive(self): """Test routing of 'switch' with an `Expr` target and several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(2, 3) case2.cx(4, 3) case2.swap(2, 3) expected.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_nested_inner_cnot(self): """test swap in nested if else controlflow construct; swap in inner""" num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(0, 2) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg, []) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_nested_outer_cnot(self): """test swap with nested if else controlflow construct; swap in outer""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(1, 3) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = SabreSwap(coupling, "lookahead", seed=82, trials=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(1, 2) etrue_body.cx(0, 1) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.cx(2, 3) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg[[0, 1, 2, 3, 4]], []) etrue_body.swap(1, 2) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg[[0, 1, 2, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_disjoint_looping(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) loop_body = QuantumCircuit(2) loop_body.cx(0, 1) qc.for_loop((0,), None, loop_body, [0, 2], []) cqc = SabreSwap(cm, "lookahead", seed=82, trials=1)(qc) expected = QuantumCircuit(qr) efor_body = QuantumCircuit(qr[[0, 1, 2]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) expected.for_loop((0,), None, efor_body, [0, 1, 2], []) self.assertEqual(cqc, expected) def test_disjoint_multiblock(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) true_body = QuantumCircuit(qr[0:3] + cr[:]) true_body.cx(0, 1) false_body = QuantumCircuit(qr[0:3] + cr[:]) false_body.cx(0, 2) qc.if_else((cr[0], 1), true_body, false_body, [0, 1, 2], [0]) cqc = SabreSwap(cm, "lookahead", seed=82, trials=1)(qc) expected = QuantumCircuit(qr, cr) etrue_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) etrue_body.cx(0, 1) efalse_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) efalse_body.swap(1, 2) efalse_body.cx(0, 1) efalse_body.swap(1, 2) expected.if_else((cr[0], 1), etrue_body, efalse_body, [0, 1, 2], cr[[0]]) self.assertEqual(cqc, expected) def test_multiple_ops_per_layer(self): """Test circuits with multiple operations per layer""" num_qubits = 6 coupling = CouplingMap.from_line(num_qubits) check_map_pass = CheckMap(coupling) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) # This cx and the for_loop are in the same layer. qc.cx(0, 2) with qc.for_loop((0,)): qc.cx(3, 5) cqc = SabreSwap(coupling, "lookahead", seed=82, trials=1)(qc) check_map_pass(cqc) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qr) expected.swap(1, 2) expected.cx(0, 1) efor_body = QuantumCircuit(qr[[3, 4, 5]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(2, 1) expected.for_loop((0,), None, efor_body, [3, 4, 5], []) self.assertEqual(cqc, expected) def test_if_no_else_restores_layout(self): """Test that an if block with no else branch restores the initial layout.""" qc = QuantumCircuit(8, 1) with qc.if_test((qc.clbits[0], False)): # Just some arbitrary gates with no perfect layout. qc.cx(3, 5) qc.cx(4, 6) qc.cx(1, 4) qc.cx(7, 4) qc.cx(0, 5) qc.cx(7, 3) qc.cx(1, 3) qc.cx(5, 2) qc.cx(6, 7) qc.cx(3, 2) qc.cx(6, 2) qc.cx(2, 0) qc.cx(7, 6) coupling = CouplingMap.from_line(8) pass_ = SabreSwap(coupling, "lookahead", seed=82, trials=1) transpiled = pass_(qc) # Check the pass claims to have done things right. initial_layout = Layout.generate_trivial_layout(*qc.qubits) self.assertEqual(initial_layout, pass_.property_set["final_layout"]) # Check that pass really did do it right. inner_block = transpiled.data[0].operation.blocks[0] running_layout = initial_layout.copy() for instruction in inner_block: if instruction.operation.name == "swap": running_layout.swap(*instruction.qubits) self.assertEqual(initial_layout, running_layout) @ddt.ddt class TestSabreSwapRandomCircuitValidOutput(QiskitTestCase): """Assert the output of a transpilation with stochastic swap is a physical circuit.""" @classmethod def setUpClass(cls): super().setUpClass() cls.backend = FakeMumbai() cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map} cls.basis_gates = set(cls.backend.configuration().basis_gates) cls.basis_gates.update(["for_loop", "while_loop", "if_else"]) def assert_valid_circuit(self, transpiled): """Assert circuit complies with constraints of backend.""" self.assertIsInstance(transpiled, QuantumCircuit) self.assertIsNotNone(getattr(transpiled, "_layout", None)) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name in {"barrier", "measure"}: continue self.assertIn(instruction.operation.name, self.basis_gates) qargs = tuple(qubit_mapping[x] for x in instruction.qubits) if not isinstance(instruction.operation, ControlFlowOp): if len(qargs) > 2 or len(qargs) < 0: raise Exception("Invalid number of qargs for instruction") if len(qargs) == 2: self.assertIn(qargs, self.coupling_edge_set) else: self.assertLessEqual(qargs[0], 26) else: for block in instruction.operation.blocks: self.assertEqual(block.num_qubits, len(instruction.qubits)) self.assertEqual(block.num_clbits, len(instruction.clbits)) new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) # Assert routing ran. _visit_block( transpiled, qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)}, ) @ddt.data(*range(1, 27)) def test_random_circuit_no_control_flow(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, self.backend, routing_method="sabre", layout_method="sabre", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @ddt.data(*range(1, 27)) def test_random_circuit_no_control_flow_target(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, routing_method="sabre", layout_method="sabre", seed_transpiler=12342, target=FakeMumbaiV2().target, ) self.assert_valid_circuit(tqc) @ddt.data(*range(4, 27)) def test_random_circuit_for_loop(self, size): """Test that transpiled random circuits with nested for loops are physical circuits.""" circuit = random_circuit(size, 3, measure=False, seed=12342) for_block = random_circuit(3, 2, measure=False, seed=12342) inner_for_block = random_circuit(2, 1, measure=False, seed=12342) with circuit.for_loop((1,)): with circuit.for_loop((1,)): circuit.append(inner_for_block, [0, 3]) circuit.append(for_block, [1, 0, 2]) circuit.measure_all() tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="sabre", layout_method="sabre", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @ddt.data(*range(6, 27)) def test_random_circuit_if_else(self, size): """Test that transpiled random circuits with if else blocks are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) if_block = random_circuit(3, 2, measure=True, seed=12342) else_block = random_circuit(2, 1, measure=True, seed=12342) rng = numpy.random.default_rng(seed=12342) inner_clbit_count = max((if_block.num_clbits, else_block.num_clbits)) if inner_clbit_count > circuit.num_clbits: circuit.add_bits([Clbit() for _ in [None] * (inner_clbit_count - circuit.num_clbits)]) clbit_indices = list(range(circuit.num_clbits)) rng.shuffle(clbit_indices) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.append(if_block, [0, 2, 1], clbit_indices[: if_block.num_clbits]) with else_: circuit.append(else_block, [2, 5], clbit_indices[: else_block.num_clbits]) tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="sabre", layout_method="sabre", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.quantumcircuitdata import CircuitInstruction from qiskit.circuit import Measure from qiskit.circuit.library import HGate, CXGate qr = QuantumRegister(2) cr = ClassicalRegister(2) instructions = [ CircuitInstruction(HGate(), [qr[0]], []), CircuitInstruction(CXGate(), [qr[0], qr[1]], []), CircuitInstruction(Measure(), [qr[0]], [cr[0]]), CircuitInstruction(Measure(), [qr[1]], [cr[1]]), ] circuit = QuantumCircuit.from_instructions(instructions) circuit.draw("mpl")
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2023, 2024. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Statevector Sampler class """ from __future__ import annotations import warnings from dataclasses import dataclass from typing import Iterable import numpy as np from numpy.typing import NDArray from qiskit import ClassicalRegister, QiskitError, QuantumCircuit from qiskit.circuit import ControlFlowOp from qiskit.quantum_info import Statevector from .base import BaseSamplerV2 from .base.validation import _has_measure from .containers import ( BitArray, DataBin, PrimitiveResult, SamplerPubResult, SamplerPubLike, ) from .containers.sampler_pub import SamplerPub from .containers.bit_array import _min_num_bytes from .primitive_job import PrimitiveJob from .utils import bound_circuit_to_instruction @dataclass class _MeasureInfo: creg_name: str num_bits: int num_bytes: int qreg_indices: list[int] class StatevectorSampler(BaseSamplerV2): """ Simple implementation of :class:`BaseSamplerV2` using full state vector simulation. This class is implemented via :class:`~.Statevector` which turns provided circuits into pure state vectors, and is therefore incompatible with mid-circuit measurements (although other implementations may be). As seen in the example below, this sampler supports providing arrays of parameter value sets to bind against a single circuit. Each tuple of ``(circuit, <optional> parameter values, <optional> shots)``, called a sampler primitive unified bloc (PUB), produces its own array-valued result. The :meth:`~run` method can be given many pubs at once. .. code-block:: python from qiskit.circuit import ( Parameter, QuantumCircuit, ClassicalRegister, QuantumRegister ) from qiskit.primitives import StatevectorSampler import matplotlib.pyplot as plt import numpy as np # Define our circuit registers, including classical registers # called 'alpha' and 'beta'. qreg = QuantumRegister(3) alpha = ClassicalRegister(2, "alpha") beta = ClassicalRegister(1, "beta") # Define a quantum circuit with two parameters. circuit = QuantumCircuit(qreg, alpha, beta) circuit.h(0) circuit.cx(0, 1) circuit.cx(1, 2) circuit.ry(Parameter("a"), 0) circuit.rz(Parameter("b"), 0) circuit.cx(1, 2) circuit.cx(0, 1) circuit.h(0) circuit.measure([0, 1], alpha) circuit.measure([2], beta) # Define a sweep over parameter values, where the second axis is over. # the two parameters in the circuit. params = np.vstack([ np.linspace(-np.pi, np.pi, 100), np.linspace(-4 * np.pi, 4 * np.pi, 100) ]).T # Instantiate a new statevector simulation based sampler object. sampler = StatevectorSampler() # Start a job that will return shots for all 100 parameter value sets. pub = (circuit, params) job = sampler.run([pub], shots=256) # Extract the result for the 0th pub (this example only has one pub). result = job.result()[0] # There is one BitArray object for each ClassicalRegister in the # circuit. Here, we can see that the BitArray for alpha contains data # for all 100 sweep points, and that it is indeed storing data for 2 # bits over 256 shots. assert result.data.alpha.shape == (100,) assert result.data.alpha.num_bits == 2 assert result.data.alpha.num_shots == 256 # We can work directly with a binary array in performant applications. raw = result.data.alpha.array # For small registers where it is anticipated to have many counts # associated with the same bitstrings, we can turn the data from, # for example, the 22nd sweep index into a dictionary of counts. counts = result.data.alpha.get_counts(22) # Or, convert into a list of bitstrings that preserve shot order. bitstrings = result.data.alpha.get_bitstrings(22) print(bitstrings) """ def __init__(self, *, default_shots: int = 1024, seed: np.random.Generator | int | None = None): """ Args: default_shots: The default shots for the sampler if not specified during run. seed: The seed or Generator object for random number generation. If None, a random seeded default RNG will be used. """ self._default_shots = default_shots self._seed = seed @property def default_shots(self) -> int: """Return the default shots""" return self._default_shots @property def seed(self) -> np.random.Generator | int | None: """Return the seed or Generator object for random number generation.""" return self._seed def run( self, pubs: Iterable[SamplerPubLike], *, shots: int | None = None ) -> PrimitiveJob[PrimitiveResult[SamplerPubResult]]: if shots is None: shots = self._default_shots coerced_pubs = [SamplerPub.coerce(pub, shots) for pub in pubs] if any(len(pub.circuit.cregs) == 0 for pub in coerced_pubs): warnings.warn( "One of your circuits has no output classical registers and so the result " "will be empty. Did you mean to add measurement instructions?", UserWarning, ) job = PrimitiveJob(self._run, coerced_pubs) job._submit() return job def _run(self, pubs: Iterable[SamplerPub]) -> PrimitiveResult[SamplerPubResult]: results = [self._run_pub(pub) for pub in pubs] return PrimitiveResult(results) def _run_pub(self, pub: SamplerPub) -> SamplerPubResult: circuit, qargs, meas_info = _preprocess_circuit(pub.circuit) bound_circuits = pub.parameter_values.bind_all(circuit) arrays = { item.creg_name: np.zeros( bound_circuits.shape + (pub.shots, item.num_bytes), dtype=np.uint8 ) for item in meas_info } for index, bound_circuit in np.ndenumerate(bound_circuits): final_state = Statevector(bound_circuit_to_instruction(bound_circuit)) final_state.seed(self._seed) if qargs: samples = final_state.sample_memory(shots=pub.shots, qargs=qargs) else: samples = [""] * pub.shots samples_array = np.array([np.fromiter(sample, dtype=np.uint8) for sample in samples]) for item in meas_info: ary = _samples_to_packed_array(samples_array, item.num_bits, item.qreg_indices) arrays[item.creg_name][index] = ary meas = { item.creg_name: BitArray(arrays[item.creg_name], item.num_bits) for item in meas_info } return SamplerPubResult(DataBin(**meas, shape=pub.shape), metadata={"shots": pub.shots}) def _preprocess_circuit(circuit: QuantumCircuit): num_bits_dict = {creg.name: creg.size for creg in circuit.cregs} mapping = _final_measurement_mapping(circuit) qargs = sorted(set(mapping.values())) qargs_index = {v: k for k, v in enumerate(qargs)} circuit = circuit.remove_final_measurements(inplace=False) if _has_control_flow(circuit): raise QiskitError("StatevectorSampler cannot handle ControlFlowOp") if _has_measure(circuit): raise QiskitError("StatevectorSampler cannot handle mid-circuit measurements") # num_qubits is used as sentinel to fill 0 in _samples_to_packed_array sentinel = len(qargs) indices = {key: [sentinel] * val for key, val in num_bits_dict.items()} for key, qreg in mapping.items(): creg, ind = key indices[creg.name][ind] = qargs_index[qreg] meas_info = [ _MeasureInfo( creg_name=name, num_bits=num_bits, num_bytes=_min_num_bytes(num_bits), qreg_indices=indices[name], ) for name, num_bits in num_bits_dict.items() ] return circuit, qargs, meas_info def _samples_to_packed_array( samples: NDArray[np.uint8], num_bits: int, indices: list[int] ) -> NDArray[np.uint8]: # samples of `Statevector.sample_memory` will be in the order of # qubit_last, ..., qubit_1, qubit_0. # reverse the sample order into qubit_0, qubit_1, ..., qubit_last and # pad 0 in the rightmost to be used for the sentinel introduced by _preprocess_circuit. ary = np.pad(samples[:, ::-1], ((0, 0), (0, 1)), constant_values=0) # place samples in the order of clbit_last, ..., clbit_1, clbit_0 ary = ary[:, indices[::-1]] # pad 0 in the left to align the number to be mod 8 # since np.packbits(bitorder='big') pads 0 to the right. pad_size = -num_bits % 8 ary = np.pad(ary, ((0, 0), (pad_size, 0)), constant_values=0) # pack bits in big endian order ary = np.packbits(ary, axis=-1) return ary def _final_measurement_mapping(circuit: QuantumCircuit) -> dict[tuple[ClassicalRegister, int], int]: """Return the final measurement mapping for the circuit. Parameters: circuit: Input quantum circuit. Returns: Mapping of classical bits to qubits for final measurements. """ active_qubits = set(range(circuit.num_qubits)) active_cbits = set(range(circuit.num_clbits)) # Find final measurements starting in back mapping = {} for item in circuit[::-1]: if item.operation.name == "measure": loc = circuit.find_bit(item.clbits[0]) cbit = loc.index qbit = circuit.find_bit(item.qubits[0]).index if cbit in active_cbits and qbit in active_qubits: for creg in loc.registers: mapping[creg] = qbit active_cbits.remove(cbit) elif item.operation.name not in ["barrier", "delay"]: for qq in item.qubits: _temp_qubit = circuit.find_bit(qq).index if _temp_qubit in active_qubits: active_qubits.remove(_temp_qubit) if not active_cbits or not active_qubits: break return mapping def _has_control_flow(circuit: QuantumCircuit) -> bool: return any(isinstance(instruction.operation, ControlFlowOp) for instruction in circuit)
https://github.com/quantum-tokyo/qiskit-handson
quantum-tokyo
# Qiskitライブラリーを導入 from qiskit import * # 描画のためのライブラリーを導入 import matplotlib.pyplot as plt %matplotlib inline qiskit.__qiskit_version__ grover11=QuantumCircuit(2,2) grover11.draw(output='mpl') # 問題-1 上の回路図を作ってください。 # 正解 grover11.h([0,1]) # ← これが(一番記述が短い正解) grover11.draw(output='mpl') # 問題-2 上の回路図(問題-1に赤枠部分を追加したもの)を作ってください。 grover11.h(1) # 正解 grover11.cx(0,1) # 正解 grover11.h(1) # 正解 grover11.draw(output='mpl') #問題-3 上の回路図(問題-2に赤枠部分を追加したもの)を作ってください。 grover11.i(0) # 回路の見栄えを整えるために、恒等ゲートを差し込む。無くても動くが、表示の見栄えが崩れるのを防止するために、残しておく。 grover11.h([0,1]) # ← 正解 grover11.x([0,1]) # ← 正解 grover11.h(1) # ← 正解 grover11.cx(0,1) # ← 正解 grover11.h(1) # ← 正解 grover11.i(0) # ← 正解 grover11.x([0,1]) # ← 正解 grover11.h([0,1]) # ← 正解 grover11.draw(output='mpl') grover11.measure(0,0) grover11.measure(1,1) grover11.draw(output='mpl') backend = Aer.get_backend('statevector_simulator') # 実行環境の定義 job = execute(grover11, backend) # 処理の実行 result = job.result() # 実行結果 counts = result.get_counts(grover11) # 実行結果の詳細を取り出し print(counts) from qiskit.visualization import * plot_histogram(counts) # ヒストグラムで表示
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import math from qiskit import pulse from qiskit.providers.fake_provider import FakeOpenPulse3Q # TODO: This example should use a real mock backend. backend = FakeOpenPulse3Q() d2 = pulse.DriveChannel(2) with pulse.build(backend) as bell_prep: pulse.u2(0, math.pi, 0) pulse.cx(0, 1) with pulse.build(backend) as decoupled_bell_prep_and_measure: # We call our bell state preparation schedule constructed above. with pulse.align_right(): pulse.call(bell_prep) pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2) pulse.barrier(0, 1, 2) registers = pulse.measure_all() decoupled_bell_prep_and_measure.draw()
https://github.com/samabwhite/Deutsch-Jozsa-Implementation
samabwhite
import qiskit from qiskit.visualization import plot_bloch_multivector import numpy as np import pylatexenc from qiskit import QuantumCircuit, Aer, transpile, assemble from qiskit.visualization import plot_histogram from qiskit.providers.aer import AerSimulator # Function to automatically instantiate the oracle circuit def balancedOracle(circuit): circuit.barrier() circuit.x([0,2]) circuit.cx([0,2] , 3) circuit.x([0,2]) circuit.barrier() return circuit # number of qubits n = 3 # initialize circuit classicalCircuit = QuantumCircuit(n+1,1) # add not gate to output bit classicalCircuit.x(n) # add the oracle to the circuit classicalCircuit = balancedOracle(classicalCircuit) # measure the output bit after the oracle classicalCircuit.measure(n, 0) display(classicalCircuit.draw('mpl')) # initialize circuit dj_Circuit = QuantumCircuit(n+1, n) # add not gate to the output qubit dj_Circuit.x(n) # add hadamard gates to all qubits dj_Circuit.h(range(n+1)) # add the oracle to the circuit dj_Circuit = balancedOracle(dj_Circuit) # finish the "hadamard sandwich" by applying hadamards to the input qubits dj_Circuit.h(range(n)) # measure the values of the input qubits dj_Circuit.measure(range(n), range(n)) display(dj_Circuit.draw('mpl')) # initialize circuit phaseKickback = QuantumCircuit(2,2) # create superposition states phaseKickback.x(1) phaseKickback.h(range(2)) # entangle states phaseKickback.cx(0,1) phaseKickback.h(range(2)) # measure phaseKickback.measure(range(2), range(2)) display(phaseKickback.draw('mpl')) # simulate outputs sim = AerSimulator() compiled = transpile(phaseKickback, sim) job = assemble(compiled) result = sim.run(compiled).result() counts = result.get_counts() print(counts) plot_histogram(counts) display(dj_Circuit.draw('mpl')) # simulate algorithm circuit compiled = transpile(dj_Circuit, sim) job = assemble(compiled) result = sim.run(compiled).result() counts = result.get_counts() print(counts) plot_histogram(counts)
https://github.com/abbarreto/qiskit4
abbarreto
from qiskit import * import numpy as np import math from matplotlib import pyplot as plt import qiskit nshots = 8192 IBMQ.load_account() provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main') device = provider.get_backend('ibmq_belem') simulator = Aer.get_backend('qasm_simulator') from qiskit.tools.monitor import job_monitor from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter #from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.visualization import plot_histogram def qc_dqc1(ph): qr = QuantumRegister(3) qc = QuantumCircuit(qr, name='DQC1') qc.h(0) qc.h(1) # cria o estado de Bell dos qubits 1 e 2, que equivale ao estado de 1 sendo maximamente misto qc.cx(1,2) #qc.barrier() qc.cp(ph, 0, 1) return qc ph = math.pi/2 qc_dqc1_ = qc_dqc1(ph) qc_dqc1_.draw('mpl') qc_dqc1_.decompose().draw('mpl') def pTraceL_num(dl, dr, rhoLR): # Retorna traco parcial sobre L de rhoLR rhoR = np.zeros((dr, dr), dtype=complex) for j in range(0, dr): for k in range(j, dr): for l in range(0, dl): rhoR[j,k] += rhoLR[l*dr+j,l*dr+k] if j != k: rhoR[k,j] = np.conj(rhoR[j,k]) return rhoR def pTraceR_num(dl, dr, rhoLR): # Retorna traco parcial sobre R de rhoLR rhoL = np.zeros((dl, dl), dtype=complex) for j in range(0, dl): for k in range(j, dl): for l in range(0, dr): rhoL[j,k] += rhoLR[j*dr+l,k*dr+l] if j != k: rhoL[k,j] = np.conj(rhoL[j,k]) return rhoL # simulation phmax = 2*math.pi dph = phmax/20 ph = np.arange(0,phmax+dph,dph) d = len(ph); xm = np.zeros(d) ym = np.zeros(d) for j in range(0,d): qr = QuantumRegister(3) qc = QuantumCircuit(qr) qc_dqc1_ = qc_dqc1(ph[j]) qc.append(qc_dqc1_, [0,1,2]) qstc = state_tomography_circuits(qc, [1,0]) job = execute(qstc, backend=simulator, shots=nshots) qstf = StateTomographyFitter(job.result(), qstc) rho_01 = qstf.fit(method='lstsq') rho_0 = pTraceR_num(2, 2, rho_01) xm[j] = 2*rho_0[1,0].real ym[j] = 2*rho_0[1,0].imag qc.draw('mpl') # experiment phmax = 2*math.pi dph = phmax/10 ph_exp = np.arange(0,phmax+dph,dph) d = len(ph_exp); xm_exp = np.zeros(d) ym_exp = np.zeros(d) for j in range(0,d): qr = QuantumRegister(3) qc = QuantumCircuit(qr) qc_dqc1_ = qc_dqc1(ph_exp[j]) qc.append(qc_dqc1_, [0,1,2]) qstc = state_tomography_circuits(qc, [1,0]) job = execute(qstc, backend=device, shots=nshots) print(job.job_id()) job_monitor(job) qstf = StateTomographyFitter(job.result(), qstc) rho_01 = qstf.fit(method='lstsq') rho_0 = pTraceR_num(2, 2, rho_01) xm_exp[j] = 2*rho_0[1,0].real ym_exp[j] = 2*rho_0[1,0].imag plt.plot(ph, xm, label = r'$\langle X\rangle_{sim}$')#, marker='*') plt.plot(ph, ym, label = r'$\langle Y\rangle_{sim}$')#, marker='o') plt.scatter(ph_exp, xm_exp, label = r'$\langle X\rangle_{exp}$', marker='*', color='r') plt.scatter(ph_exp, ym_exp, label = r'$\langle Y\rangle_{exp}$', marker='o', color='g') plt.legend(bbox_to_anchor=(1, 1))#,loc='center right') #plt.xlim(0,2*math.pi) #plt.ylim(-1,1) plt.xlabel(r'$\phi$') plt.show()
https://github.com/chriszapri/qiskitDemo
chriszapri
from qiskit import QuantumCircuit, assemble, Aer # Qiskit features imported from qiskit.visualization import plot_bloch_multivector, plot_histogram # For visualization from qiskit.quantum_info import Statevector # Intermediary statevector saving import numpy as np # Numpy math library sim = Aer.get_backend('aer_simulator') # Simulation that this notebook relies on ### For real quantum computer backend, replace Aer.get_backend with backend object of choice # Widgets for value sliders import ipywidgets as widgets from IPython.display import display # Value sliders theta = widgets.FloatSlider( value=0, min=0, max=180, step=0.5, description='θ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) phi = widgets.FloatSlider( value=0, min=0, max=360, step=0.5, description='φ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) display(theta) # Zenith angle in degrees display(phi) # Azimuthal angle in degrees ## Careful! These act as zenith and azimuthal only when applied to |0> statevector in rx(theta), rz(phi) order qc = QuantumCircuit(1) # 1 qubit quantum circuit, every qubits starts at |0> qc.rx(theta.value/180.0*np.pi,0) # Rotation about Bloch vector x-axis qc.rz(phi.value/180.0*np.pi,0) # Rotation about Bloch vector y-axis qc.save_statevector() # Get final statevector after measurement qc.measure_all() # Measurement: collapses the statevector to either |0> or |1> qobj = assemble(qc) # Quantum circuit saved to an object interStateV = sim.run(qobj).result().get_statevector() finalStates = sim.run(qobj).result().get_counts() qc.draw() plot_bloch_multivector(interStateV) # Plot intermediary statevector after two gates on Bloch sphere plot_histogram(finalStates) # Probability of |0> or |1> from measuring above statevector
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Randomized tests of quantum synthesis.""" import unittest from test.python.quantum_info.test_synthesis import CheckDecompositions from hypothesis import given, strategies, settings import numpy as np from qiskit import execute from qiskit.circuit import QuantumCircuit, QuantumRegister from qiskit.extensions import UnitaryGate from qiskit.providers.basicaer import UnitarySimulatorPy from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.synthesis.two_qubit_decompose import ( two_qubit_cnot_decompose, TwoQubitBasisDecomposer, Ud, ) class TestSynthesis(CheckDecompositions): """Test synthesis""" seed = strategies.integers(min_value=0, max_value=2**32 - 1) rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10) @given(seed) def test_1q_random(self, seed): """Checks one qubit decompositions""" unitary = random_unitary(2, seed=seed) self.check_one_qubit_euler_angles(unitary) self.check_one_qubit_euler_angles(unitary, "U3") self.check_one_qubit_euler_angles(unitary, "U1X") self.check_one_qubit_euler_angles(unitary, "PSX") self.check_one_qubit_euler_angles(unitary, "ZSX") self.check_one_qubit_euler_angles(unitary, "ZYZ") self.check_one_qubit_euler_angles(unitary, "ZXZ") self.check_one_qubit_euler_angles(unitary, "XYX") self.check_one_qubit_euler_angles(unitary, "RR") @settings(deadline=None) @given(seed) def test_2q_random(self, seed): """Checks two qubit decompositions""" unitary = random_unitary(4, seed=seed) self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose) @given(strategies.tuples(*[seed] * 5)) def test_exact_supercontrolled_decompose_random(self, seeds): """Exact decomposition for random supercontrolled basis and random target""" k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data) k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data) basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2 decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary)) self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer) @given(strategies.tuples(*[rotation] * 6), seed) def test_cx_equivalence_0cx_random(self, rnd, seed): """Check random circuits with 0 cx gates locally equivalent to identity.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0) @given(strategies.tuples(*[rotation] * 12), seed) def test_cx_equivalence_1cx_random(self, rnd, seed): """Check random circuits with 1 cx gates locally equivalent to a cx.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1) @given(strategies.tuples(*[rotation] * 18), seed) def test_cx_equivalence_2cx_random(self, rnd, seed): """Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) qc.cx(qr[0], qr[1]) qc.u(rnd[12], rnd[13], rnd[14], qr[0]) qc.u(rnd[15], rnd[16], rnd[17], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2) @given(strategies.tuples(*[rotation] * 24), seed) def test_cx_equivalence_3cx_random(self, rnd, seed): """Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions.""" qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.u(rnd[0], rnd[1], rnd[2], qr[0]) qc.u(rnd[3], rnd[4], rnd[5], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[6], rnd[7], rnd[8], qr[0]) qc.u(rnd[9], rnd[10], rnd[11], qr[1]) qc.cx(qr[0], qr[1]) qc.u(rnd[12], rnd[13], rnd[14], qr[0]) qc.u(rnd[15], rnd[16], rnd[17], qr[1]) qc.cx(qr[1], qr[0]) qc.u(rnd[18], rnd[19], rnd[20], qr[0]) qc.u(rnd[21], rnd[22], rnd[23], qr[1]) sim = UnitarySimulatorPy() unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary() self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3) if __name__ == "__main__": unittest.main()
https://github.com/Qottmann/Quantum-anomaly-detection
Qottmann
"""A quantum auto-encoder (QAE).""" from typing import Union, Optional, List, Tuple, Callable, Any import numpy as np from qiskit import * from qiskit.circuit.quantumcircuit import QuantumCircuit from qiskit.circuit.library import TwoLocal from qiskit.circuit.library.standard_gates import RYGate, CZGate from qiskit.circuit.gate import Gate from qiskit.algorithms.optimizers import Optimizer, SPSA from qiskit.utils import algorithm_globals from qiskit.providers import BaseBackend, Backend class QAEAnsatz(TwoLocal): def __init__( self, num_qubits: int, num_trash_qubits: int, trash_qubits_idxs: Union[np.ndarray, List] = [1, 2], # TODO measure_trash: bool = False, rotation_blocks: Gate = RYGate, entanglement_blocks: Gate = CZGate, parameter_prefix: str = 'θ', insert_barriers: bool = False, initial_state: Optional[Any] = None, ) -> None: """Create a new QAE circuit. Args: num_qubits: The number of qubits of the QAE circuit. num_trash_qubits: The number of trash qubits that should be measured in the end. trash_qubits_idxs: The explicit indices of the trash qubits, i.e., where the trash qubits should be placed. measure_trash: If True, the trash qubits will be measured at the end. If False, no measurement takes place. rotation_blocks: The blocks used in the rotation layers. If multiple are passed, these will be applied one after another (like new sub-layers). entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed, these will be applied one after another. parameter_prefix: The prefix used if default parameters are generated. insert_barriers: If True, barriers are inserted in between each layer. If False, no barriers are inserted. initial_state: A `QuantumCircuit` object which can be used to describe an initial state prepended to the NLocal circuit. """ assert num_trash_qubits < num_qubits self.num_trash_qubits = num_trash_qubits self.trash_qubits_idxs = trash_qubits_idxs self.measure_trash = measure_trash entanglement = [QAEAnsatz._generate_entangler_map( num_qubits, num_trash_qubits, i, trash_qubits_idxs) for i in range(num_trash_qubits)] super().__init__(num_qubits=num_qubits, rotation_blocks=rotation_blocks, entanglement_blocks=entanglement_blocks, entanglement=entanglement, reps=num_trash_qubits, skip_final_rotation_layer=True, parameter_prefix=parameter_prefix, insert_barriers=insert_barriers, initial_state=initial_state) self.add_register(ClassicalRegister(self.num_trash_qubits)) @staticmethod def _generate_entangler_map(num_qubits: int, num_trash_qubits: int, i_permut: int = 1, trash_qubits_idxs: Union[np.ndarray, List] = [1, 2]) -> List[Tuple[int, int]]: """Generates entanglement map for QAE circuit Entangling gates are only added between trash and non-trash-qubits. Args: num_qubits: The number of qubits of the QAE circuit. num_trash_qubits: The number of trash qubits that should be measured in the end. i_permut: Permutation index; increases for every layer of the circuit trash_qubits_idxs: The explicit indices of the trash qubits, i.e., where the trash qubits should be placed. Returns: entanglement map: List of pairs of qubit indices that should be entangled """ result = [] nums_compressed = list(range(num_qubits)) for trashqubit in trash_qubits_idxs: nums_compressed.remove(trashqubit) if trash_qubits_idxs == None: nums_compressed = list(range(num_qubits))[:num_qubits-num_trash_qubits] trash_qubits_idxs = list(range(num_qubits))[-num_trash_qubits:] # combine all trash qubits with themselves for i,trash_q in enumerate(trash_qubits_idxs[:-1]): result.append((trash_qubits_idxs[i+1], trash_qubits_idxs[i])) # combine each of the trash qubits with every n-th # repeat the list of trash indices cyclicly repeated = list(trash_qubits_idxs) * (num_qubits-num_trash_qubits) for i in range(num_qubits-num_trash_qubits): result.append((repeated[i_permut + i], nums_compressed[i])) return result def _build(self) -> None: """Build the circuit.""" if self._data: return _ = self._check_configuration() self._data = [] if self.num_qubits == 0: return # use the initial state circuit if it is not None if self._initial_state: circuit = self._initial_state.construct_circuit('circuit', register=self.qregs[0]) self.compose(circuit, inplace=True) param_iter = iter(self.ordered_parameters) # build the prepended layers self._build_additional_layers('prepended') # main loop to build the entanglement and rotation layers for i in range(self.reps): # insert barrier if specified and there is a preceding layer if self._insert_barriers and (i > 0 or len(self._prepended_blocks) > 0): self.barrier() # build the rotation layer self._build_rotation_layer(param_iter, i) # barrier in between rotation and entanglement layer if self._insert_barriers and len(self._rotation_blocks) > 0: self.barrier() # build the entanglement layer self._build_entanglement_layer(param_iter, i) # add the final rotation layer if self.insert_barriers and self.reps > 0: self.barrier() for j, block in enumerate(self.rotation_blocks): # create a new layer layer = QuantumCircuit(*self.qregs) block_indices = [[i] for i in self.trash_qubits_idxs] # apply the operations in the layer for indices in block_indices: parameterized_block = self._parameterize_block(block, param_iter, i, j, indices) layer.compose(parameterized_block, indices, inplace=True) # add the layer to the circuit self.compose(layer, inplace=True) # add the appended layers self._build_additional_layers('appended') # measure trash qubits if set if self.measure_trash: for i, j in enumerate(self.trash_qubits_idxs): self.measure(self.qregs[0][j], self.cregs[0][i]) @property def num_parameters_settable(self) -> int: """The number of total parameters that can be set to distinct values. Returns: The number of parameters originally available in the circuit. """ return super().num_parameters_settable + self.num_trash_qubits def hamming_distance(out) -> int: """Computes the Hamming distance of a measurement outcome to the all zero state. For example: A single measurement outcome 101 would have a Hamming distance of 2. Args: out: The measurement outcomes; a dictionary containing all possible measurement strings as keys and their occurences as values. Returns: Hamming distance """ return sum(key.count('1') * value for key, value in out.items()) class QAE: def __init__( self, num_qubits: int, num_trash_qubits: int, ansatz: Optional[QuantumCircuit] = None, initial_params: Optional[Union[np.ndarray, List]] = None, optimizer: Optional[Optimizer] = None, shots: int = 1000, num_epochs: int = 100, save_training_curve: Optional[bool] = False, seed: int = 123, backend: Union[BaseBackend, Backend] = Aer.get_backend('qasm_simulator') ) -> None: """Quantum auto-encoder. Args: num_qubits: The number of qubits of the QAE circuit. num_trash_qubits: The number of trash qubits that should be measured in the end. ansatz: A parameterized quantum circuit ansatz to be optimized. initial_params: The initial list of parameters for the circuit ansatz optimizer: The optimizer used for training (default is SPSA) shots: The number of measurement shots when training and evaluating the QAE. num_epochs: The number of training iterations/epochs. save_training_curve: If True, the cost after each optimizer step is computed and stored. seed: Random number seed. backend: The backend on which the QAE is performed. """ algorithm_globals.random_seed = seed np.random.seed(seed) self.costs = [] if save_training_curve: callback = self._store_intermediate_result else: callback = None if optimizer: self.optimizer = optimizer else: self.optimizer = SPSA(num_epochs, callback=callback) self.backend = backend if ansatz: self.ansatz = ansatz else: self.ansatz = QAEAnsatz(num_qubits, num_trash_qubits, measure_trash=True) if initial_params: self.initial_params = initial_params else: self.initial_params = np.random.uniform(0, 2*np.pi, self.ansatz.num_parameters_settable) self.shots = shots self.save_training_curve = save_training_curve def run(self, input_state: Optional[Any] = None, params: Optional[Union[np.ndarray, List]] = None): """Execute ansatz circuit and measure trash qubits Args: input_state: If provided, circuit is initialized accordingly params: If provided, list of optimization parameters for circuit Returns: measurement outcomes """ if params is None: params = self.initial_params if input_state is not None: if type(input_state) == QuantumCircuit: circ = input_state elif type(input_state) == list or type(input_state) == np.ndarray: circ = QuantumCircuit(self.ansatz.num_qubits, self.ansatz.num_trash_qubits) circ.initialize(input_state) else: raise TypeError("input_state has to be an array or a QuantumCircuit.") circ = circ.compose(self.ansatz) else: circ = self.ansatz circ = circ.assign_parameters(params) job_sim = execute(circ, self.backend, shots=self.shots) return job_sim.result().get_counts(circ) def cost(self, input_state: Optional[Any] = None, params: Optional[Union[np.ndarray, List]] = None) -> float: """ Cost function Average Hamming distance of measurement outcomes to zero state. Args: input_state: If provided, circuit is initialized accordingly params: If provided, list of optimization parameters for circuit Returns: Cost """ out = self.run(input_state, params) cost = hamming_distance(out) return cost/self.shots def _store_intermediate_result(self, eval_count, parameters, mean, std, ac): """Callback function to save intermediate costs during training.""" self.costs.append(mean) def train(self, input_state: Optional[Any] = None): """ Trains the QAE using optimizer (default SPSA) Args: input_state: If provided, circuit is initialized accordingly Returns: Result of optimization: optimized parameters, cost, iterations Training curve: Cost function evaluated after each iteration """ result = self.optimizer.optimize( num_vars=len(self.initial_params), objective_function=lambda params: self.cost(input_state, params), initial_point=self.initial_params ) self.initial_params = result[0] return result, self.costs def reset(self): """Resets parameters to random values""" self.costs = [] self.initial_params = np.random.uniform(0, 2*np.pi, self.ansatz.num_parameters_settable) if __name__ == '__main__': num_qubits = 5 num_trash_qubits = 2 qae = QAE(num_qubits, num_trash_qubits, save_training_curve=True) # for demonstration purposes QAE is trained on a random state input_state = np.random.uniform(size=2**num_qubits) input_state /= np.linalg.norm(input_state) result, cost = qae.train(input_state)
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # 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. # TODO: Remove after 0.7 and the deprecated methods are removed # pylint: disable=unused-argument """ Two quantum circuit drawers based on: 0. Ascii art 1. LaTeX 2. Matplotlib """ import errno import logging import os import subprocess import tempfile from PIL import Image from qiskit import user_config from qiskit.visualization import exceptions from qiskit.visualization import latex as _latex from qiskit.visualization import text as _text from qiskit.visualization import utils from qiskit.visualization import matplotlib as _matplotlib logger = logging.getLogger(__name__) def circuit_drawer(circuit, scale=0.7, filename=None, style=None, output=None, interactive=False, line_length=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit to different formats (set by output parameter): 0. text: ASCII art TextDrawing that can be printed in the console. 1. latex: high-quality images, but heavy external software dependencies 2. matplotlib: purely in Python with no external dependencies Args: circuit (QuantumCircuit): the quantum circuit to draw scale (float): scale of image to draw (shrink if < 1) filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file. This option is only used by the `mpl`, `latex`, and `latex_source` output types. If a str is passed in that is the path to a json file which contains that will be open, parsed, and then used just as the input dict. output (str): Select the output method to use for drawing the circuit. Valid choices are `text`, `latex`, `latex_source`, `mpl`. By default the 'text' drawer is used unless a user config file has an alternative backend set as the default. If the output is passed in that backend will always be used. interactive (bool): when set true show the circuit in a new window (for `mpl` this depends on the matplotlib backend being used supporting this). Note when used with either the `text` or the `latex_source` output type this has no effect and will be silently ignored. line_length (int): Sets the length of the lines generated by `text` output type. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). However, if you're running in jupyter the default line length is set to 80 characters. If you don't want pagination at all, set `line_length=-1`. reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (string): Options are `left`, `right` or `none`, if anything else is supplied it defaults to left justified. It refers to where gates should be placed in the output circuit if there is an option. `none` results in each gate being placed in its own column. Currently only supported by text drawer. Returns: PIL.Image: (output `latex`) an in-memory representation of the image of the circuit diagram. matplotlib.figure: (output `mpl`) a matplotlib figure object for the circuit diagram. String: (output `latex_source`). The LaTeX source code. TextDrawing: (output `text`). A drawing that can be printed as ascii art Raises: VisualizationError: when an invalid output method is selected ImportError: when the output methods requieres non-installed libraries. .. _style-dict-doc: The style dict kwarg contains numerous options that define the style of the output circuit visualization. While the style dict is used by the `mpl`, `latex`, and `latex_source` outputs some options in that are only used by the `mpl` output. These options are defined below, if it is only used by the `mpl` output it is marked as such: textcolor (str): The color code to use for text. Defaults to `'#000000'` (`mpl` only) subtextcolor (str): The color code to use for subtext. Defaults to `'#000000'` (`mpl` only) linecolor (str): The color code to use for lines. Defaults to `'#000000'` (`mpl` only) creglinecolor (str): The color code to use for classical register lines `'#778899'`(`mpl` only) gatetextcolor (str): The color code to use for gate text `'#000000'` (`mpl` only) gatefacecolor (str): The color code to use for gates. Defaults to `'#ffffff'` (`mpl` only) barrierfacecolor (str): The color code to use for barriers. Defaults to `'#bdbdbd'` (`mpl` only) backgroundcolor (str): The color code to use for the background. Defaults to `'#ffffff'` (`mpl` only) fontsize (int): The font size to use for text. Defaults to 13 (`mpl` only) subfontsize (int): The font size to use for subtext. Defaults to 8 (`mpl` only) displaytext (dict): A dictionary of the text to use for each element type in the output visualization. The default values are: { 'id': 'id', 'u0': 'U_0', 'u1': 'U_1', 'u2': 'U_2', 'u3': 'U_3', 'x': 'X', 'y': 'Y', 'z': 'Z', 'h': 'H', 's': 'S', 'sdg': 'S^\\dagger', 't': 'T', 'tdg': 'T^\\dagger', 'rx': 'R_x', 'ry': 'R_y', 'rz': 'R_z', 'reset': '\\left|0\\right\\rangle' } You must specify all the necessary values if using this. There is no provision for passing an incomplete dict in. (`mpl` only) displaycolor (dict): The color codes to use for each circuit element. By default all values default to the value of `gatefacecolor` and the keys are the same as `displaytext`. Also, just like `displaytext` there is no provision for an incomplete dict passed in. (`mpl` only) latexdrawerstyle (bool): When set to True enable latex mode which will draw gates like the `latex` output modes. (`mpl` only) usepiformat (bool): When set to True use radians for output (`mpl` only) fold (int): The number of circuit elements to fold the circuit at. Defaults to 20 (`mpl` only) cregbundle (bool): If set True bundle classical registers (`mpl` only) showindex (bool): If set True draw an index. (`mpl` only) compress (bool): If set True draw a compressed circuit (`mpl` only) figwidth (int): The maximum width (in inches) for the output figure. (`mpl` only) dpi (int): The DPI to use for the output image. Defaults to 150 (`mpl` only) margin (list): `mpl` only creglinestyle (str): The style of line to use for classical registers. Choices are `'solid'`, `'doublet'`, or any valid matplotlib `linestyle` kwarg value. Defaults to `doublet`(`mpl` only) """ image = None config = user_config.get_config() # Get default from config file else use text default_output = 'text' if config: default_output = config.get('circuit_drawer', 'text') if output is None: output = default_output if output == 'text': return _text_circuit_drawer(circuit, filename=filename, line_length=line_length, reverse_bits=reverse_bits, plotbarriers=plot_barriers, justify=justify) elif output == 'latex': image = _latex_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'latex_source': return _generate_latex_source(circuit, filename=filename, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) elif output == 'mpl': image = _matplotlib_circuit_drawer(circuit, scale=scale, filename=filename, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) else: raise exceptions.VisualizationError( 'Invalid output type %s selected. The only valid choices ' 'are latex, latex_source, text, and mpl' % output) if image and interactive: image.show() return image # ----------------------------------------------------------------------------- # Plot style sheet option # ----------------------------------------------------------------------------- def qx_color_scheme(): """Return default style for matplotlib_circuit_drawer (IBM QX style).""" return { "comment": "Style file for matplotlib_circuit_drawer (IBM QX Composer style)", "textcolor": "#000000", "gatetextcolor": "#000000", "subtextcolor": "#000000", "linecolor": "#000000", "creglinecolor": "#b9b9b9", "gatefacecolor": "#ffffff", "barrierfacecolor": "#bdbdbd", "backgroundcolor": "#ffffff", "fold": 20, "fontsize": 13, "subfontsize": 8, "figwidth": -1, "dpi": 150, "displaytext": { "id": "id", "u0": "U_0", "u1": "U_1", "u2": "U_2", "u3": "U_3", "x": "X", "y": "Y", "z": "Z", "h": "H", "s": "S", "sdg": "S^\\dagger", "t": "T", "tdg": "T^\\dagger", "rx": "R_x", "ry": "R_y", "rz": "R_z", "reset": "\\left|0\\right\\rangle" }, "displaycolor": { "id": "#ffca64", "u0": "#f69458", "u1": "#f69458", "u2": "#f69458", "u3": "#f69458", "x": "#a6ce38", "y": "#a6ce38", "z": "#a6ce38", "h": "#00bff2", "s": "#00bff2", "sdg": "#00bff2", "t": "#ff6666", "tdg": "#ff6666", "rx": "#ffca64", "ry": "#ffca64", "rz": "#ffca64", "reset": "#d7ddda", "target": "#00bff2", "meas": "#f070aa" }, "latexdrawerstyle": True, "usepiformat": False, "cregbundle": False, "plotbarrier": False, "showindex": False, "compress": True, "margin": [2.0, 0.0, 0.0, 0.3], "creglinestyle": "solid", "reversebits": False } # ----------------------------------------------------------------------------- # _text_circuit_drawer # ----------------------------------------------------------------------------- def _text_circuit_drawer(circuit, filename=None, line_length=None, reverse_bits=False, plotbarriers=True, justify=None, vertically_compressed=True): """ Draws a circuit using ascii art. Args: circuit (QuantumCircuit): Input circuit filename (str): optional filename to write the result line_length (int): Optional. Breaks the circuit drawing to this length. This useful when the drawing does not fit in the console. If None (default), it will try to guess the console width using shutil.get_terminal_size(). If you don't want pagination at all, set line_length=-1. reverse_bits (bool): Rearrange the bits in reverse order. plotbarriers (bool): Draws the barriers when they are there. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. vertically_compressed (bool): Default is `True`. It merges the lines so the drawing will take less vertical room. Returns: TextDrawing: An instances that, when printed, draws the circuit in ascii art. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) text_drawing = _text.TextDrawing(qregs, cregs, ops) text_drawing.plotbarriers = plotbarriers text_drawing.line_length = line_length text_drawing.vertically_compressed = vertically_compressed if filename: text_drawing.dump(filename) return text_drawing # ----------------------------------------------------------------------------- # latex_circuit_drawer # ----------------------------------------------------------------------------- def _latex_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on latex (Qcircuit package) Requires version >=2.6.0 of the qcircuit LaTeX package. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: PIL.Image: an in-memory representation of the circuit diagram Raises: OSError: usually indicates that ```pdflatex``` or ```pdftocairo``` is missing. CalledProcessError: usually points errors during diagram creation. """ tmpfilename = 'circuit' with tempfile.TemporaryDirectory() as tmpdirname: tmppath = os.path.join(tmpdirname, tmpfilename + '.tex') _generate_latex_source(circuit, filename=tmppath, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits, justify=justify) image = None try: subprocess.run(["pdflatex", "-halt-on-error", "-output-directory={}".format(tmpdirname), "{}".format(tmpfilename + '.tex')], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True) except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to compile latex. ' 'Is `pdflatex` installed? ' 'Skipping latex circuit drawing...') raise except subprocess.CalledProcessError as ex: with open('latex_error.log', 'wb') as error_file: error_file.write(ex.stdout) logger.warning('WARNING Unable to compile latex. ' 'The output from the pdflatex command can ' 'be found in latex_error.log') raise else: try: base = os.path.join(tmpdirname, tmpfilename) subprocess.run(["pdftocairo", "-singlefile", "-png", "-q", base + '.pdf', base]) image = Image.open(base + '.png') image = utils._trim(image) os.remove(base + '.png') if filename: image.save(filename, 'PNG') except OSError as ex: if ex.errno == errno.ENOENT: logger.warning('WARNING: Unable to convert pdf to image. ' 'Is `poppler` installed? ' 'Skipping circuit drawing...') raise return image def _generate_latex_source(circuit, filename=None, scale=0.7, style=None, reverse_bits=False, plot_barriers=True, justify=None): """Convert QuantumCircuit to LaTeX string. Args: circuit (QuantumCircuit): input circuit scale (float): image scaling filename (str): optional filename to write latex style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: str: Latex string appropriate for writing to file. """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcimg = _latex.QCircuitImage(qregs, cregs, ops, scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) latex = qcimg.latex() if filename: with open(filename, 'w') as latex_file: latex_file.write(latex) return latex # ----------------------------------------------------------------------------- # matplotlib_circuit_drawer # ----------------------------------------------------------------------------- def _matplotlib_circuit_drawer(circuit, scale=0.7, filename=None, style=None, plot_barriers=True, reverse_bits=False, justify=None): """Draw a quantum circuit based on matplotlib. If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline. We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization. Args: circuit (QuantumCircuit): a quantum circuit scale (float): scaling factor filename (str): file path to save image to style (dict or str): dictionary of style or file name of style file reverse_bits (bool): When set to True reverse the bit order inside registers for the output visualization. plot_barriers (bool): Enable/disable drawing barriers in the output circuit. Defaults to True. justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how the circuit should be justified. Returns: matplotlib.figure: a matplotlib figure object for the circuit diagram """ qregs, cregs, ops = utils._get_layered_instructions(circuit, reverse_bits=reverse_bits, justify=justify) qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style, plot_barriers=plot_barriers, reverse_bits=reverse_bits) return qcd.draw(filename)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, IBMQ, execute, transpile, Aer from qiskit.providers.aer import QasmSimulator from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.compiler import transpile # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity # Suppress warnings import warnings warnings.filterwarnings('ignore') def trotter_gate(dt): qc = QuantumCircuit(2) qc.h(1) qc.cx(1,0) qc.h(1) qc.rz(- 2 * dt, 1) qc.rz(dt, 0) qc.h(1) qc.cx(1,0) qc.h(1) qc.rx(dt, [1]) qc.rz(-dt, [0,1]) qc.rx(-dt, [0,1]) return qc.to_instruction() qc = QuantumCircuit(2) qc.h(1) qc.cx(1,0) qc.h(1) qc.rz(- 2 * np.pi / 6, 1) qc.rz(np.pi / 6, 0) qc.h(1) qc.cx(1,0) qc.h(1) qc.rx(np.pi / 6, [1]) qc.barrier() qc.rz(-np.pi / 6, [0,1]) qc.rx(-np.pi / 6, [0,1]) qc.draw('mpl') # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 2 # Parameterize variable t to be evaluated at t=pi later dt = Parameter('t') # Convert custom quantum circuit into a gate Trot_gate = trotter_gate(dt) # YOUR TROTTERIZATION GOES HERE -- FINISH (end of example) # The final time of the state evolution target_time = np.pi # Number of trotter steps trotter_steps = 4 ### CAN BE >= 4 # Initialize quantum circuit for 3 qubits qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) # init state |10> (= |110>) qc.x(1) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[0], qr[1]]) # qc.cx(qr[3], qr[1]) # qc.cx(qr[5], qr[3]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / trotter_steps}) qc.measure(qr, cr) t0_qc = transpile(qc, optimization_level=0, basis_gates=["sx","rz","cx"]) # t0_qc.draw("mpl") t0_qc = t0_qc.reverse_bits() # t0_qc.draw("mpl") shots = 8192 reps = 1 # WE USE A NOISELESS SIMULATION HERE backend = Aer.get_backend('qasm_simulator') jobs = [] for _ in range(reps): # execute job = execute(t0_qc, backend=backend, shots=shots, optimization_level=0) print('Job ID', job.job_id()) jobs.append(job) counts_01 = [] counts_10 = [] for trotter_steps in range(1, 15, 1): print("number of trotter steps: ", trotter_steps) # Initialize quantum circuit for 3 qubits qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) # init state |10> (= |110>) qc.x(1) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) # Simulate time evolution under H_heis3 Hamiltonian for _ in range(trotter_steps): qc.append(Trot_gate, [qr[0], qr[1]]) # Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time qc = qc.bind_parameters({dt: target_time / trotter_steps}) qc.measure(qr, cr) t0_qc = transpile(qc, optimization_level=0, basis_gates=["sx","rz","cx"]) t0_qc = t0_qc.reverse_bits() print("circuit depth: ", t0_qc.depth()) job = execute(t0_qc, backend=backend, shots=shots, optimization_level=0) print("pribability distribution: ", job.result().get_counts()) counts_01.append(job.result().get_counts().get("01", 0)) counts_10.append(job.result().get_counts().get("10", 0)) print() plt.plot(range(1,15), counts_10) plt.xlabel("trotter steps") plt.ylabel("shot counts of 10") plt.title("counts of |10>") plt.plot(range(1,15), counts_01) plt.xlabel("trotter steps") plt.ylabel("shot counts of 01") plt.title("counts of |01>")
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit rng = CreativeQiskit.qrng() for _ in range(5): print( rng.rand_int() ) for _ in range(5): print( rng.rand() ) rng = CreativeQiskit.qrng(noise_only=True) for _ in range(5): print( rng.rand() ) rng = CreativeQiskit.qrng(noise_only=True,noisy=True) for _ in range(5): print( rng.rand() ) rng = CreativeQiskit.qrng(noise_only=True,noisy=0.2) for _ in range(5): print( rng.rand() )
https://github.com/mentesniker/Quantum-error-mitigation
mentesniker
from qiskit import QuantumCircuit, QuantumRegister, Aer, execute, ClassicalRegister from qiskit.ignis.verification.topological_codes import RepetitionCode from qiskit.ignis.verification.topological_codes import lookuptable_decoding from qiskit.ignis.verification.topological_codes import GraphDecoder from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter) from qiskit.visualization import plot_histogram backend = Aer.get_backend('qasm_simulator') #These two functions were taken from https://stackoverflow.com/questions/10237926/convert-string-to-list-of-bits-and-viceversa def tobits(s): result = [] for c in s: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return ''.join([str(x) for x in result]) def frombits(bits): chars = [] for b in range(int(len(bits) / 8)): byte = bits[b*8:(b+1)*8] chars.append(chr(int(''.join([str(bit) for bit in byte]), 2))) return ''.join(chars) def get_noise(p): error_meas = pauli_error([('X',p), ('I', 1 - p)]) noise_model = NoiseModel() noise_model.add_all_qubit_quantum_error(error_meas, "measure") return noise_model def codificate(bitString): qubits = list() for i in range(len(bitString)): mycircuit = QuantumCircuit(1,1) if(bitString[i] == "1"): mycircuit.x(0) qubits.append(mycircuit) return qubits def count(array): numZero = 0 numOne = 0 for i in array: if i == "0": numZero += 1 elif i == "1": numOne += 1 return dict({"0":numZero, "1":numOne}) m0 = tobits("I like dogs") qubits = codificate(m0) measurements = list() for i in range(len(qubits)): qubit = qubits[i] qubit.measure(0,0) result = execute(qubit, backend, shots=1, memory=True).result() measurements.append(int(result.get_memory()[0])) print(frombits(measurements)) m0 = tobits("I like dogs") qubits = codificate(m0) measurements = list() for i in range(len(qubits)): qubit = qubits[i] qubit.measure(0,0) result = execute(qubit, backend, shots=1, memory=True, noise_model=get_noise(0.2)).result() measurements.append(int(result.get_memory()[0])) print(frombits(measurements)) for state in ['0','1']: qc = QuantumCircuit(1,1) if state[0]=='1': qc.x(0) qc.measure(qc.qregs[0],qc.cregs[0]) print(state+' becomes', execute(qc, Aer.get_backend('qasm_simulator'),noise_model=get_noise(0.2),shots=1000).result().get_counts()) qubit = qubits[0] result = execute(qubit, backend, shots=1000, memory=True, noise_model=get_noise(0.2)).result() print(result.get_counts()) import numpy as np import scipy.linalg as la M = [[0.389,0.611], [0.593,0.407]] Cnoisy = [[397],[603]] Minv = la.inv(M) Cmitigated = np.dot(Minv, Cnoisy) print('C_mitigated =\n',Cmitigated) Cmitigated = np.floor(Cmitigated) if(Cmitigated[1][0] < 0): Cmitigated[1][0] = 0 print('C_mitigated =\n',Cmitigated) qr = QuantumRegister(1) meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') backend = Aer.get_backend('qasm_simulator') job = execute(meas_calibs, backend=backend, shots=1000,noise_model=get_noise(0.2)) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal') print(meas_fitter.cal_matrix) qubit = qubits[2] qubit.measure(0,0) results = execute(qubit, backend=backend, shots=10000, noise_model=get_noise(0.2),memory=True).result() noisy_counts = count(results.get_memory()) print(noisy_counts) Minv = la.inv(meas_fitter.cal_matrix) Cmitigated = np.dot(Minv, np.array(list(noisy_counts.values()))) print('C_mitigated =\n',Cmitigated) outputs = list() for i in range(len(qubits)): qubit = qubits[i] qubit.measure(0,0) results = execute(qubit, backend=backend, shots=10000, memory=True, noise_model=get_noise(0.2)).result() noisy_counts = count(results.get_memory()) Minv = la.inv(meas_fitter.cal_matrix) Cmitigated = np.dot(Minv, np.array(list(noisy_counts.values()))) if(Cmitigated[0] > Cmitigated[1]): outputs.append('0') else: outputs.append('1') print(frombits(''.join(outputs))) outputs = list() meas_filter = meas_fitter.filter for i in range(len(qubits)): qubit = qubits[i] qubit.measure(0,0) results = execute(qubit, backend=backend, shots=10000, memory=True, noise_model=get_noise(0.2)).result() noisy_counts = count(results.get_memory()) # Results with mitigation mitigated_counts = meas_filter.apply(noisy_counts) if('1' not in mitigated_counts): outputs.append('0') elif('0' not in mitigated_counts): outputs.append('1') elif(mitigated_counts['0'] > mitigated_counts['1']): outputs.append('0') else: outputs.append('1') print(frombits(''.join(outputs)))
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
mathelatics
import numpy as np from qiskit import BasicAer from qiskit.transpiler import PassManager from qiskit.aqua import QuantumInstance from qiskit.aqua.operators import MatrixOperator, op_converter from qiskit.aqua.algorithms import EOH from qiskit.aqua.components.initial_states import Custom num_qubits = 2 temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) qubit_op = op_converter.to_weighted_pauli_operator(MatrixOperator(matrix=temp + temp.T)) temp = np.random.random((2 ** num_qubits, 2 ** num_qubits)) evo_op = op_converter.to_weighted_pauli_operator(MatrixOperator(matrix=temp + temp.T)) evo_time = 1 num_time_slices = 1 state_in = Custom(qubit_op.num_qubits, state='uniform') eoh = EOH(qubit_op, state_in, evo_op, evo_time=evo_time, num_time_slices=num_time_slices) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) ret = eoh.run(quantum_instance) print('The result is\n{}'.format(ret))
https://github.com/GiacomoFrn/QuantumTeleportation
GiacomoFrn
import cirq import numpy as np from qiskit import QuantumCircuit, execute, Aer import seaborn as sns import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = (15,10) q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)] circuit = cirq.Circuit() #entagling the 2 quibits in different laboratories #and preparing the qubit to send circuit.append(cirq.H(q0)) circuit.append(cirq.H(q1)) circuit.append(cirq.CNOT(q1, q2)) #entangling the qubit we want to send to the one in the first laboratory circuit.append(cirq.CNOT(q0, q1)) circuit.append(cirq.H(q0)) #measurements circuit.append(cirq.measure(q0, q1)) #last transformations to obtain the qubit information circuit.append(cirq.CNOT(q1, q2)) circuit.append(cirq.CZ(q0, q2)) #measure of the qubit in the receiving laboratory along z axis circuit.append(cirq.measure(q2, key = 'Z')) circuit #starting simulation sim = cirq.Simulator() results = sim.run(circuit, repetitions=100) sns.histplot(results.measurements['Z'], discrete = True) 100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z']) #in qiskit the qubits are integrated in the circuit qc = QuantumCircuit(3, 1) #entangling qc.h(0) qc.h(1) qc.cx(1, 2) qc.cx(0, 1) #setting for measurment qc.h(0) qc.measure([0,1], [0,0]) #transformation to obtain qubit sent qc.cx(1, 2) qc.cz(0, 2) qc.measure(2, 0) print(qc) #simulation simulator = Aer.get_backend('qasm_simulator') job = execute(qc, simulator, shots=100) res = job.result().get_counts(qc) plt.bar(res.keys(), res.values()) res
https://github.com/qiskit-community/prototype-quantum-kernel-training
qiskit-community
# pylint: disable=protected-access from qiskit.circuit.library import ZZFeatureMap from qiskit.circuit import ParameterVector # Define a (non-parameterized) feature map from the Qiskit circuit library fm = ZZFeatureMap(2) input_params = fm.parameters fm.draw() # split params into two disjoint sets input_params = fm.parameters[::2] training_params = fm.parameters[1::2] print("input_params:", input_params) print("training_params:", training_params) # define new parameter vectors for the input and user parameters new_input_params = ParameterVector("x", len(input_params)) new_training_params = ParameterVector("θ", len(training_params)) # resassign the origin feature map parameters param_reassignments = {} for i, p in enumerate(input_params): param_reassignments[p] = new_input_params[i] for i, p in enumerate(training_params): param_reassignments[p] = new_training_params[i] fm.assign_parameters(param_reassignments, inplace=True) input_params = new_input_params training_params = new_training_params print("input_params:", input_params) print("training_params:", training_params) fm.draw() # Define two circuits circ1 = ZZFeatureMap(2) circ2 = ZZFeatureMap(2) input_params = circ1.parameters training_params = ParameterVector("θ", 2) # Reassign new parameters to circ2 so there are no name collisions circ2.assign_parameters(training_params, inplace=True) # Compose to build a parameterized feature map fm = circ2.compose(circ1) print("input_params:", list(input_params)) print("training_params:", training_params) fm.draw() #import qiskit.tools.jupyter # #%qiskit_version_table #%qiskit_copyright
https://github.com/Spintronic6889/Introduction-of-Quantum-walk-its-application-on-search-and-decision-making
Spintronic6889
!python --version !pip install qiskit !pip install pylatexenc from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer from qiskit.visualization import plot_histogram import matplotlib.pyplot as plt from qiskit.visualization import plot_state_city %matplotlib inline import matplotlib as mpl from random import randrange import numpy as np import networkx as nx import random import math from qiskit.tools.monitor import job_monitor from random import randrange pose=[] for i in range(400): pose.append([]) #print(pose) #pose[-1]=1 #print(pose[-1]) pose[0]=200 for k in range(200): rand = randrange(0,2) if rand==0: #print(rand) pose[k+1]=pose[k]+1 if rand==1: pose[k+1]=pose[k]-1 #print(pose) yc=[] for e in range(400): yc.append([]) for q in range(400): yc[q]=0 for h in range(400): if pose[h]==q: yc[q]=yc[q]+1 #print((yc)) #print(len(yc)) xc = np.arange(0, 400, 1) plt.plot(yc) plt.xlim(150, 250) class quantom_walk: def __init__(self): self.__n=2 self.__steps=1 self.__theta=0 self.__phi=0 self.__qtype=1 self.__shot=5000 def main_qw(self,n,steps,qtype,theta,phi): self.__qpos = QuantumRegister(n,'qpos') self.__qcoin = QuantumRegister(1,'qcoin') self.__cpos = ClassicalRegister(n,'cr') self.__QC = QuantumCircuit(self.__qpos, self.__qcoin) if qtype==2: self.__QC.x(self.__qcoin[0]) if qtype==3: self.__QC.u(theta, phi, 0, self.__qcoin[0]) for i in range(steps): self.__QC.h(self.__qcoin[0]) self.__QC.barrier() for i in range(n): self.__QC.mct([self.__qcoin[0]]+self.__qpos[i+1:], self.__qpos[i], None, mode='noancilla') self.__QC.barrier() self.__QC.x(self.__qcoin[0]) for i in range(n): if i+1 < n: self.__QC.x(self.__qpos[i+1:]) self.__QC.mct([self.__qcoin[0]]+self.__qpos[i+1:], self.__qpos[i], None, mode='noancilla') if i+1 < n: self.__QC.x(self.__qpos[i+1:]) self.__QC.barrier() a=n/2 p=math.floor(a) for k in range(n): if(k<p): self.__QC.swap(self.__qpos[n-1-k],self.__qpos[k]) def displayh(self): display(self.__QC.draw(output="mpl")) def histagramh(self,shot): self.__QC.measure_all() job = execute(self.__QC,Aer.get_backend('aer_simulator'),shots=5000) counts = job.result().get_counts(self.__QC) return counts def spacevectorh(self): backend = Aer.get_backend('statevector_simulator') job = execute(self.__QC, backend) result = job.result() outputstate = result.get_statevector(self.__QC, decimals=3) print(outputstate) def plotcityh(self): backend = Aer.get_backend('statevector_simulator') job = execute(self.__QC, backend) result = job.result() outputstate = result.get_statevector(self.__QC, decimals=3) from qiskit.visualization import plot_state_city plot_state_city(outputstate) return outputstate def unitaryh(self): backend = Aer.get_backend('unitary_simulator') job = execute(self.__QC, backend) result = job.result() yy=result.get_unitary(self.__QC, decimals=3) print(yy) def IBMQh(self): from qiskit import IBMQ IBMQ.save_account('d1441affe8622903745ae099f50bce72c21036f85b14600d18195c977b9efcdee621dd4a981b92d8028c03c4dc1860c82d70f501d345023471402f4f8dad0181',overwrite=True) provider = IBMQ.load_account() device = provider.get_backend('ibmq_quito') #we use ibmq_16_melbourne quantum device job = execute(self.__QC, backend = device) #we pass our circuit and backend as usual from qiskit.tools.monitor import job_monitor job_monitor(job) #to see our status in queue result = job.result() counts= result.get_counts(self.__QC) return counts def instructionset(self): print(self.__QC.qasm()) qw = quantom_walk() qw.main_qw(4,4,1,1.5,4) #qw.instructionset() #qw.displayh() #plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None) #qw.histagramh(3000) #qw.spacevectorh() #qw.unitaryh() #qw.plotcityh() #plot_state_city(qw.plotcityh(), figsize=(20, 10)) #plot_histogram(qw.IBMQh(), figsize=(5, 2), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None, filename=None) #qw.IBMQh() qw = quantom_walk() qw.main_qw(2,2,1,1.5,4) qw.displayh() qw.main_qw(6,25,1,1.5,4) plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None) qw.main_qw(3,4,1,1.5,4) qw.spacevectorh() qw.main_qw(3,15,1,1.5,4) plot_state_city(qw.plotcityh(), figsize=(20, 10)) qw.main_qw(2,3,1,1.5,4) qw.unitaryh() qw.main_qw(3,2,1,1.5,4) qw.instructionset() qw.main_qw(2,1,1,1.5,4) plot_histogram(qw.IBMQh(), figsize=(5, 2), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None, filename=None) #hadamrad...qtype=1 qw = quantom_walk() qw.main_qw(3,32,1,0,0) plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None) #optimized ugate applied...qtype=3 qw = quantom_walk() qw.main_qw(3,32,3,1.57,1.57) plot_histogram(qw.histagramh(3000), figsize=(20, 5), color=None, number_to_keep=None, sort='asc', target_string=None, legend=None, bar_labels=True, title=None, ax=None)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import copy # Problem modelling imports from docplex.mp.model import Model # Qiskit imports from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit.utils.algorithm_globals import algorithm_globals from qiskit_optimization.algorithms import MinimumEigenOptimizer, CplexOptimizer from qiskit_optimization import QuadraticProgram from qiskit_optimization.problems.variable import VarType from qiskit_optimization.converters.quadratic_program_to_qubo import QuadraticProgramToQubo from qiskit_optimization.translators import from_docplex_mp def create_problem(mu: np.array, sigma: np.array, total: int = 3) -> QuadraticProgram: """Solve the quadratic program using docplex.""" mdl = Model() x = [mdl.binary_var("x%s" % i) for i in range(len(sigma))] objective = mdl.sum([mu[i] * x[i] for i in range(len(mu))]) objective -= 2 * mdl.sum( [sigma[i, j] * x[i] * x[j] for i in range(len(mu)) for j in range(len(mu))] ) mdl.maximize(objective) cost = mdl.sum(x) mdl.add_constraint(cost == total) qp = from_docplex_mp(mdl) return qp def relax_problem(problem) -> QuadraticProgram: """Change all variables to continuous.""" relaxed_problem = copy.deepcopy(problem) for variable in relaxed_problem.variables: variable.vartype = VarType.CONTINUOUS return relaxed_problem mu = np.array([3.418, 2.0913, 6.2415, 4.4436, 10.892, 3.4051]) sigma = np.array( [ [1.07978412, 0.00768914, 0.11227606, -0.06842969, -0.01016793, -0.00839765], [0.00768914, 0.10922887, -0.03043424, -0.0020045, 0.00670929, 0.0147937], [0.11227606, -0.03043424, 0.985353, 0.02307313, -0.05249785, 0.00904119], [-0.06842969, -0.0020045, 0.02307313, 0.6043817, 0.03740115, -0.00945322], [-0.01016793, 0.00670929, -0.05249785, 0.03740115, 0.79839634, 0.07616951], [-0.00839765, 0.0147937, 0.00904119, -0.00945322, 0.07616951, 1.08464544], ] ) qubo = create_problem(mu, sigma) print(qubo.prettyprint()) result = CplexOptimizer().solve(qubo) print(result.prettyprint()) qp = relax_problem(QuadraticProgramToQubo().convert(qubo)) print(qp.prettyprint()) sol = CplexOptimizer().solve(qp) print(sol.prettyprint()) c_stars = sol.samples[0].x print(c_stars) algorithm_globals.random_seed = 12345 qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0]) exact_mes = NumPyMinimumEigensolver() qaoa = MinimumEigenOptimizer(qaoa_mes) qaoa_result = qaoa.solve(qubo) print(qaoa_result.prettyprint()) from qiskit import QuantumCircuit thetas = [2 * np.arcsin(np.sqrt(c_star)) for c_star in c_stars] init_qc = QuantumCircuit(len(sigma)) for idx, theta in enumerate(thetas): init_qc.ry(theta, idx) init_qc.draw(output="mpl") from qiskit.circuit import Parameter beta = Parameter("β") ws_mixer = QuantumCircuit(len(sigma)) for idx, theta in enumerate(thetas): ws_mixer.ry(-theta, idx) ws_mixer.rz(-2 * beta, idx) ws_mixer.ry(theta, idx) ws_mixer.draw(output="mpl") ws_qaoa_mes = QAOA( sampler=Sampler(), optimizer=COBYLA(), initial_state=init_qc, mixer=ws_mixer, initial_point=[0.0, 1.0], ) ws_qaoa = MinimumEigenOptimizer(ws_qaoa_mes) ws_qaoa_result = ws_qaoa.solve(qubo) print(ws_qaoa_result.prettyprint()) def format_qaoa_samples(samples, max_len: int = 10): qaoa_res = [] for s in samples: if sum(s.x) == 3: qaoa_res.append(("".join([str(int(_)) for _ in s.x]), s.fval, s.probability)) res = sorted(qaoa_res, key=lambda x: -x[1])[0:max_len] return [(_[0] + f": value: {_[1]:.3f}, probability: {1e2*_[2]:.1f}%") for _ in res] format_qaoa_samples(qaoa_result.samples) format_qaoa_samples(ws_qaoa_result.samples) from qiskit_optimization.algorithms import WarmStartQAOAOptimizer qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0]) ws_qaoa = WarmStartQAOAOptimizer( pre_solver=CplexOptimizer(), relax_for_pre_solver=True, qaoa=qaoa_mes, epsilon=0.0 ) ws_result = ws_qaoa.solve(qubo) print(ws_result.prettyprint()) format_qaoa_samples(ws_result.samples) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/IvanIsCoding/Quantum
IvanIsCoding
# Do the necessary imports import numpy as np from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import IBMQ, Aer, transpile, assemble from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex from qiskit.extensions import Initialize from qiskit.ignis.verification import marginal_counts from qiskit.quantum_info import random_statevector # Loading your IBM Quantum account(s) provider = IBMQ.load_account() ## SETUP # Protocol uses 3 qubits and 2 classical bits in 2 different registers qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical bits crx = ClassicalRegister(1, name="crx") # in 2 different registers teleportation_circuit = QuantumCircuit(qr, crz, crx) def create_bell_pair(qc, a, b): qc.h(a) qc.cx(a,b) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.draw() def alice_gates(qc, psi, a): qc.cx(psi, a) qc.h(psi) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) teleportation_circuit.draw() def measure_and_send(qc, a, b): """Measures qubits a & b and 'sends' the results to Bob""" qc.barrier() qc.measure(a,0) qc.measure(b,1) qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) create_bell_pair(teleportation_circuit, 1, 2) teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) measure_and_send(teleportation_circuit, 0 ,1) teleportation_circuit.draw() def bob_gates(qc, qubit, crz, crx): qc.x(qubit).c_if(crx, 1) # Apply gates if the registers qc.z(qubit).c_if(crz, 1) # are in the state '1' qr = QuantumRegister(3, name="q") crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx") teleportation_circuit = QuantumCircuit(qr, crz, crx) ## STEP 1 create_bell_pair(teleportation_circuit, 1, 2) ## STEP 2 teleportation_circuit.barrier() # Use barrier to separate steps alice_gates(teleportation_circuit, 0, 1) ## STEP 3 measure_and_send(teleportation_circuit, 0, 1) ## STEP 4 teleportation_circuit.barrier() # Use barrier to separate steps bob_gates(teleportation_circuit, 2, crz, crx) teleportation_circuit.draw() # Create random 1-qubit state psi = random_statevector(2) # Display it nicely display(array_to_latex(psi, prefix="|\\psi\\rangle =")) # Show it on a Bloch sphere plot_bloch_multivector(psi) init_gate = Initialize(psi) init_gate.label = "init" ## SETUP qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits crz = ClassicalRegister(1, name="crz") # and 2 classical registers crx = ClassicalRegister(1, name="crx") qc = QuantumCircuit(qr, crz, crx) ## STEP 0 # First, let's initialize Alice's q0 qc.append(init_gate, [0]) qc.barrier() ## STEP 1 # Now begins the teleportation protocol create_bell_pair(qc, 1, 2) qc.barrier() ## STEP 2 # Send q1 to Alice and q2 to Bob alice_gates(qc, 0, 1) ## STEP 3 # Alice then sends her classical bits to Bob measure_and_send(qc, 0, 1) ## STEP 4 # Bob decodes qubits bob_gates(qc, 2, crz, crx) # Display the circuit qc.draw() sim = Aer.get_backend('aer_simulator') qc.save_statevector() out_vector = sim.run(qc).result().get_statevector() plot_bloch_multivector(out_vector)
https://github.com/anirban-m/qiskit-superstaq
anirban-m
# -*- coding: utf-8 -*- # 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. import time from typing import Any, Dict, List import qiskit import requests import qiskit_superstaq as qss class SuperstaQJob(qiskit.providers.JobV1): def __init__( self, backend: qss.superstaq_backend.SuperstaQBackend, job_id: str, ) -> None: # Can we stop setting qobj and access_token to None """Initialize a job instance. Parameters: backend (BaseBackend): Backend that job was executed on. job_id (str): The unique job ID from SuperstaQ. access_token (str): The access token. """ super().__init__(backend, job_id) def __eq__(self, other: Any) -> bool: if not (isinstance(other, SuperstaQJob)): return False return self._job_id == other._job_id def _wait_for_results(self, timeout: float = None, wait: float = 5) -> List[Dict]: result_list: List[Dict] = [] job_ids = self._job_id.split(",") # separate aggregated job_ids header = { "Authorization": self._backend._provider.access_token, "SDK": "qiskit", } for jid in job_ids: start_time = time.time() result = None while True: elapsed = time.time() - start_time if timeout and elapsed >= timeout: raise qiskit.providers.JobTimeoutError( "Timed out waiting for result" ) # pragma: no cover b/c don't want slow test or mocking time getstr = f"{self._backend.url}/" + qss.API_VERSION + f"/job/{jid}" result = requests.get( getstr, headers=header, verify=(self._backend.url == qss.API_URL) ).json() if result["status"] == "Done": break if result["status"] == "Error": raise qiskit.providers.JobError("API returned error:\n" + str(result)) time.sleep(wait) # pragma: no cover b/c don't want slow test or mocking time result_list.append(result) return result_list def result(self, timeout: float = None, wait: float = 5) -> qiskit.result.Result: # Get the result data of a circuit. results = self._wait_for_results(timeout, wait) # create list of result dictionaries results_list = [] for result in results: results_list.append( {"success": True, "shots": result["shots"], "data": {"counts": result["samples"]}} ) return qiskit.result.Result.from_dict( { "results": results_list, "qobj_id": -1, "backend_name": self._backend._configuration.backend_name, "backend_version": self._backend._configuration.backend_version, "success": True, "job_id": self._job_id, } ) def status(self) -> str: """Query for the job status.""" header = { "Authorization": self._backend._provider.access_token, "SDK": "qiskit", } job_id_list = self._job_id.split(",") # separate aggregated job ids status = "Done" # when we have multiple jobs, we will take the "worst status" among the jobs # For example, if any of the jobs are still queued, we report Queued as the status # for the entire batch. for job_id in job_id_list: get_url = self._backend.url + "/" + qss.API_VERSION + f"/job/{job_id}" result = requests.get( get_url, headers=header, verify=(self._backend.url == qss.API_URL) ) temp_status = result.json()["status"] if temp_status == "Queued": status = "Queued" break elif temp_status == "Running": status = "Running" assert status in ["Queued", "Running", "Done"] if status == "Queued": status = qiskit.providers.jobstatus.JobStatus.QUEUED elif status == "Running": status = qiskit.providers.jobstatus.JobStatus.RUNNING else: status = qiskit.providers.jobstatus.JobStatus.DONE return status def submit(self) -> None: raise NotImplementedError("Submit through SuperstaQBackend, not through SuperstaqJob")
https://github.com/qiskit-community/qiskit-qcgpu-provider
qiskit-community
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=missing-docstring,redefined-builtin import unittest import os from qiskit import QuantumCircuit from .common import QiskitTestCase from qiskit_jku_provider import QasmSimulator from qiskit import execute class TestQasmSimulatorJKUBasic(QiskitTestCase): """Runs the Basic qasm_simulator tests from Terra on JKU.""" def setUp(self): self.seed = 88 self.backend = QasmSimulator(silent=True) qasm_filename = os.path.join(os.path.dirname(__file__), 'qasms', 'example.qasm') compiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename) compiled_circuit.name = 'test' self.circuit = compiled_circuit def test_qasm_simulator_single_shot(self): """Test single shot run.""" result = execute(self.circuit, self.backend, seed_transpiler=34342, shots=1).result() self.assertEqual(result.success, True) def test_qasm_simulator(self): """Test data counts output for single circuit run against reference.""" shots = 1024 result = execute(self.circuit, self.backend, seed_transpiler=34342, shots=shots).result() threshold = 0.04 * shots counts = result.get_counts('test') target = {'100 100': shots / 8, '011 011': shots / 8, '101 101': shots / 8, '111 111': shots / 8, '000 000': shots / 8, '010 010': shots / 8, '110 110': shots / 8, '001 001': shots / 8} self.assertDictAlmostEqual(counts, target, threshold) if __name__ == '__main__': unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import DensityMatrix from qiskit.visualization import plot_state_city qc = QuantumCircuit(2) qc.h(0) qc.cx(0,1) # plot using a DensityMatrix state = DensityMatrix(qc) plot_state_city(state)
https://github.com/quantumyatra/quantum_computing
quantumyatra
# importing Qiskit from qiskit import IBMQ, BasicAer #from qiskit.providers.ibmq import least_busy from qiskit import QuantumCircuit, execute # import basic plot tools from qiskit.visualization import plot_histogram s='11' n = 2*len(str(s)) ckt = QuantumCircuit(n) barriers = True ckt.h(range(len(str(s)))) # Apply barrier ckt.barrier() # Apply the query function ## 2-qubit oracle for s = 11 ckt.cx(0, len(str(s)) + 0) ckt.cx(0, len(str(s)) + 1) ckt.cx(1, len(str(s)) + 0) ckt.cx(1, len(str(s)) + 1) # Apply barrier ckt.barrier() # Apply Hadamard gates to the input register ckt.h(range(len(str(s)))) # Measure ancilla qubits ckt.measure_all() ckt.draw(output='mpl')
https://github.com/microsoft/qiskit-qir
microsoft
## # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ## from qiskit_qir.translate import to_qir_module from qiskit import ClassicalRegister, QuantumCircuit from qiskit.circuit import Clbit from qiskit.circuit.exceptions import CircuitError import pytest import pyqir import os from pathlib import Path # result_stream, condition value, expected gates falsy_single_bit_variations = [False, 0] truthy_single_bit_variations = [True, 1] invalid_single_bit_varitions = [-1] def compare_reference_ir(generated_bitcode: bytes, name: str) -> None: module = pyqir.Module.from_bitcode(pyqir.Context(), generated_bitcode, f"{name}") ir = str(module) file = os.path.join(os.path.dirname(__file__), f"resources/{name}.ll") expected = Path(file).read_text() assert ir == expected @pytest.mark.parametrize("value", falsy_single_bit_variations) def test_single_clbit_variations_falsy(value: bool) -> None: circuit = QuantumCircuit(2, 0, name=f"test_single_clbit_variations") cr = ClassicalRegister(2, "creg") circuit.add_register(cr) circuit.measure(0, 0) bit: Clbit = cr[0] circuit.measure(1, 1).c_if(bit, value) generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode compare_reference_ir(generated_bitcode, "test_single_clbit_variations_falsy") @pytest.mark.parametrize("value", truthy_single_bit_variations) def test_single_clbit_variations_truthy(value: bool) -> None: circuit = QuantumCircuit(2, 0, name=f"test_single_clbit_variations") cr = ClassicalRegister(2, "creg") circuit.add_register(cr) circuit.measure(0, 0) bit: Clbit = cr[0] circuit.measure(1, 1).c_if(bit, value) generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode compare_reference_ir(generated_bitcode, "test_single_clbit_variations_truthy") @pytest.mark.parametrize("value", truthy_single_bit_variations) def test_single_register_index_variations_truthy(value: bool) -> None: circuit = QuantumCircuit(2, 0, name=f"test_single_register_index_variations") cr = ClassicalRegister(2, "creg") circuit.add_register(cr) circuit.measure(0, 0) circuit.measure(1, 1).c_if(0, value) generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode compare_reference_ir( generated_bitcode, "test_single_register_index_variations_truthy" ) @pytest.mark.parametrize("value", falsy_single_bit_variations) def test_single_register_index_variations_falsy(value: bool) -> None: circuit = QuantumCircuit(2, 0, name=f"test_single_register_index_variations") cr = ClassicalRegister(2, "creg") circuit.add_register(cr) circuit.measure(0, 0) circuit.measure(1, 1).c_if(0, value) generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode compare_reference_ir( generated_bitcode, "test_single_register_index_variations_falsy" ) @pytest.mark.parametrize("value", truthy_single_bit_variations) def test_single_register_variations_truthy(value: bool) -> None: circuit = QuantumCircuit(2, 0, name=f"test_single_register_variations") cr = ClassicalRegister(2, "creg") circuit.add_register(cr) circuit.measure(0, 0) circuit.measure(1, 1).c_if(cr, value) generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode compare_reference_ir(generated_bitcode, "test_single_register_variations_truthy") @pytest.mark.parametrize("value", falsy_single_bit_variations) def test_single_register_variations_falsy(value: bool) -> None: circuit = QuantumCircuit(2, 0, name=f"test_single_register_variations") cr = ClassicalRegister(2, "creg") circuit.add_register(cr) circuit.measure(0, 0) circuit.measure(1, 1).c_if(cr, value) generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode compare_reference_ir(generated_bitcode, "test_single_register_variations_falsy") @pytest.mark.parametrize("value", invalid_single_bit_varitions) def test_single_clbit_invalid_variations(value: int) -> None: circuit = QuantumCircuit(2, 0, name=f"test_single_clbit_invalid_variations") cr = ClassicalRegister(2, "creg") circuit.add_register(cr) circuit.measure(0, 0) bit: Clbit = cr[0] with pytest.raises(CircuitError) as exc_info: _ = circuit.measure(1, 1).c_if(bit, value) assert exc_info is not None @pytest.mark.parametrize("value", invalid_single_bit_varitions) def test_single_register_index_invalid_variations(value: int) -> None: circuit = QuantumCircuit( 2, 0, name=f"test_single_register_index_invalid_variations", ) cr = ClassicalRegister(2, "creg") circuit.add_register(cr) circuit.measure(0, 0) with pytest.raises(CircuitError) as exc_info: _ = circuit.measure(1, 1).c_if(0, value) assert exc_info is not None @pytest.mark.parametrize("value", invalid_single_bit_varitions) def test_single_register_invalid_variations(value: int) -> None: circuit = QuantumCircuit(2, 0, name=f"test_single_register_invalid_variations") cr = ClassicalRegister(2, "creg") circuit.add_register(cr) circuit.measure(0, 0) with pytest.raises(CircuitError) as exc_info: _ = circuit.measure(1, 1).c_if(cr, value) assert exc_info is not None two_bit_variations = [ [False, "falsy"], [0, "falsy"], [True, "truthy"], [1, "truthy"], [2, "two"], [3, "three"], ] # # -1: 11 # # -2: 10 # # -3: 01 # # -4: 00 invalid_two_bit_variations = [-4, -3, -2, -1] @pytest.mark.parametrize("matrix", two_bit_variations) def test_two_bit_register_variations(matrix) -> None: value, name = matrix circuit = QuantumCircuit( 3, 0, name=f"test_two_bit_register_variations", ) cr = ClassicalRegister(2, "creg") circuit.add_register(cr) cond = ClassicalRegister(1, "cond") circuit.add_register(cond) circuit.measure(0, 0) circuit.measure(1, 1) circuit.measure(2, 2).c_if(cr, value) generated_bitcode = to_qir_module(circuit, record_output=False)[0].bitcode compare_reference_ir(generated_bitcode, f"test_two_bit_register_variations_{name}") @pytest.mark.parametrize("value", invalid_two_bit_variations) def test_two_bit_register_invalid_variations(value: int) -> None: circuit = QuantumCircuit( 3, 0, name=f"test_two_bit_register_invalid_variations", ) cr = ClassicalRegister(2, "creg") circuit.add_register(cr) cond = ClassicalRegister(1, "cond") circuit.add_register(cond) circuit.measure(0, 0) circuit.measure(1, 1) with pytest.raises(CircuitError) as exc_info: _ = circuit.measure(2, 2).c_if(cr, value) assert exc_info is not None
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_bloch_multivector qc = QuantumCircuit(2) qc.h(0) qc.x(1) state = Statevector(qc) plot_bloch_multivector(state)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state)
https://github.com/googlercolin/Qiskit-Course
googlercolin
import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * from qiskit.providers.aer import QasmSimulator # Loading your IBM Quantum account(s) provider = IBMQ.load_account() import math desired_state = [ 0, 0, 0, 0, 0, 1 / math.sqrt(2), 0, 1 / math.sqrt(2)] qc = QuantumCircuit(3) qc.initialize(desired_state, [0,1,2]) qc.decompose().decompose().decompose().decompose().decompose().draw() desired_state = [ 1 / math.sqrt(15.25) * 1.5, 0, 1 / math.sqrt(15.25) * -2, 1 / math.sqrt(15.25) * 3] qc = QuantumCircuit(2) qc.initialize(desired_state, [0,1]) qc.decompose().decompose().decompose().decompose().decompose().draw() qc = QuantumCircuit(3) qc.ry(0, 0) qc.ry(math.pi/4, 1) qc.ry(math.pi/2, 2) qc.draw() from qiskit.circuit.library import ZZFeatureMap circuit = ZZFeatureMap(3, reps=1, insert_barriers=True) circuit.decompose().draw() x = [0.1, 0.2, 0.3] encode = circuit.bind_parameters(x) encode.decompose().draw() from qiskit.circuit.library import EfficientSU2 circuit = EfficientSU2(num_qubits=3, reps=1, insert_barriers=True) circuit.decompose().draw() x = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2] encode = circuit.bind_parameters(x) encode.decompose().draw()
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=missing-function-docstring, missing-module-docstring import unittest from inspect import signature from math import pi import numpy as np from scipy.linalg import expm from ddt import data, ddt, unpack from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute from qiskit.exceptions import QiskitError from qiskit.circuit.exceptions import CircuitError from qiskit.test import QiskitTestCase from qiskit.circuit import Gate, ControlledGate from qiskit.circuit.library import ( U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate, XXMinusYYGate, XXPlusYYGate, RZGate, XGate, YGate, GlobalPhaseGate, ) from qiskit import BasicAer from qiskit.quantum_info import Pauli from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix from qiskit.utils.optionals import HAS_TWEEDLEDUM from qiskit.quantum_info import Operator from qiskit import transpile class TestStandard1Q(QiskitTestCase): """Standard Extension Test. Gates with a single Qubit""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier(self): self.circuit.barrier(self.qr[1]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_wires(self): self.circuit.barrier(1) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_barrier_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.barrier, self.cr[0]) self.assertRaises(CircuitError, qc.barrier, self.cr) self.assertRaises(CircuitError, qc.barrier, (self.qr, "a")) self.assertRaises(CircuitError, qc.barrier, 0.0) def test_conditional_barrier_invalid(self): qc = self.circuit barrier = qc.barrier(self.qr) self.assertRaises(QiskitError, barrier.c_if, self.cr, 0) def test_barrier_reg(self): self.circuit.barrier(self.qr) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_barrier_none(self): self.circuit.barrier() self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual( self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0], self.qr2[1], self.qr2[2]), ) def test_ccx(self): self.circuit.ccx(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_wires(self): self.circuit.ccx(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "ccx") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_ccx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ccx, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.ccx, self.qr[0], self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, 0.0, self.qr[0], self.qr[2]) self.assertRaises(CircuitError, qc.ccx, self.cr, self.qr, self.qr) self.assertRaises(CircuitError, qc.ccx, "a", self.qr[1], self.qr[2]) def test_ch(self): self.circuit.ch(self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_wires(self): self.circuit.ch(0, 1) self.assertEqual(self.circuit[0].operation.name, "ch") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_ch_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ch, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ch, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.ch, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.ch, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.ch, self.cr, self.qr) self.assertRaises(CircuitError, qc.ch, "a", self.qr[1]) def test_cif_reg(self): self.circuit.h(self.qr[0]).c_if(self.cr, 7) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr, 7)) def test_cif_single_bit(self): self.circuit.h(self.qr[0]).c_if(self.cr[0], True) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[0],)) self.assertEqual(self.circuit[0].operation.condition, (self.cr[0], True)) def test_crz(self): self.circuit.crz(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry(self): self.circuit.cry(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx(self): self.circuit.crx(1, self.qr[0], self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_wires(self): self.circuit.crz(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_cry_wires(self): self.circuit.cry(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "cry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crx_wires(self): self.circuit.crx(1, 0, 1) self.assertEqual(self.circuit[0].operation.name, "crx") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1])) def test_crz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crz, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crz, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crz, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crz, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crz, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crz, 'a', self.qr[1], self.qr[2]) def test_cry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cry, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cry, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cry, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cry, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.cry, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.cry, 'a', self.qr[1], self.qr[2]) def test_crx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.crx, 0, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.crx, self.qr[2], self.qr[1], self.qr[0]) self.assertRaises(CircuitError, qc.crx, 0, self.qr[1], self.cr[2]) self.assertRaises(CircuitError, qc.crx, 0, (self.qr, 3), self.qr[1]) self.assertRaises(CircuitError, qc.crx, 0, self.cr, self.qr) # TODO self.assertRaises(CircuitError, qc.crx, 'a', self.qr[1], self.qr[2]) def test_cswap(self): self.circuit.cswap(self.qr[0], self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_wires(self): self.circuit.cswap(0, 1, 2) self.assertEqual(self.circuit[0].operation.name, "cswap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2])) def test_cswap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[1], 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.cr[0], self.cr[1], self.qr[0]) self.assertRaises(CircuitError, qc.cswap, self.qr[0], self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, 0.0, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, (self.qr, 3), self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, self.cr, self.qr[0], self.qr[1]) self.assertRaises(CircuitError, qc.cswap, "a", self.qr[1], self.qr[2]) def test_cu1(self): self.circuit.append(CU1Gate(1), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu1_wires(self): self.circuit.append(CU1Gate(1), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3(self): self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr[2]]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cu3_wires(self): self.circuit.append(CU3Gate(1, 2, 3), [1, 2]) self.assertEqual(self.circuit[0].operation.name, "cu3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx(self): self.circuit.cx(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_wires(self): self.circuit.cx(1, 2) self.assertEqual(self.circuit[0].operation.name, "cx") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cx, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cx, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cx, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cx, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cx, self.cr, self.qr) self.assertRaises(CircuitError, qc.cx, "a", self.qr[1]) def test_cy(self): self.circuit.cy(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_wires(self): self.circuit.cy(1, 2) self.assertEqual(self.circuit[0].operation.name, "cy") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cy_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cy, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cy, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cy, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cy, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cy, self.cr, self.qr) self.assertRaises(CircuitError, qc.cy, "a", self.qr[1]) def test_cz(self): self.circuit.cz(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_wires(self): self.circuit.cz(1, 2) self.assertEqual(self.circuit[0].operation.name, "cz") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_cz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.cz, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.cz, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.cz, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.cz, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.cz, self.cr, self.qr) self.assertRaises(CircuitError, qc.cz, "a", self.qr[1]) def test_h(self): self.circuit.h(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_wires(self): self.circuit.h(1) self.assertEqual(self.circuit[0].operation.name, "h") self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_h_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.h, self.cr[0]) self.assertRaises(CircuitError, qc.h, self.cr) self.assertRaises(CircuitError, qc.h, (self.qr, 3)) self.assertRaises(CircuitError, qc.h, (self.qr, "a")) self.assertRaises(CircuitError, qc.h, 0.0) def test_h_reg(self): instruction_set = self.circuit.h(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_h_reg_inv(self): instruction_set = self.circuit.h(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "h") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden(self): self.circuit.i(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_wires(self): self.circuit.i(1) self.assertEqual(self.circuit[0].operation.name, "id") self.assertEqual(self.circuit[0].operation.params, []) def test_iden_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.i, self.cr[0]) self.assertRaises(CircuitError, qc.i, self.cr) self.assertRaises(CircuitError, qc.i, (self.qr, 3)) self.assertRaises(CircuitError, qc.i, (self.qr, "a")) self.assertRaises(CircuitError, qc.i, 0.0) def test_iden_reg(self): instruction_set = self.circuit.i(self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_iden_reg_inv(self): instruction_set = self.circuit.i(self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "id") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) def test_rx(self): self.circuit.rx(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_wires(self): self.circuit.rx(1, 1) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [1]) def test_rx_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rx, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rx, self.qr[1], 0) self.assertRaises(CircuitError, qc.rx, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rx, 0, 0.0) self.assertRaises(CircuitError, qc.rx, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rx, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rx, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rx, 0, "a") def test_rx_reg(self): instruction_set = self.circuit.rx(1, self.qr) self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_rx_reg_inv(self): instruction_set = self.circuit.rx(1, self.qr).inverse() self.assertEqual(len(instruction_set), 3) self.assertEqual(instruction_set[0].operation.name, "rx") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rx_pi(self): qc = self.circuit qc.rx(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rx") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry(self): self.circuit.ry(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_wires(self): self.circuit.ry(1, 1) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_ry_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.ry, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.ry, self.qr[1], 0) self.assertRaises(CircuitError, qc.ry, 0, self.cr[0]) self.assertRaises(CircuitError, qc.ry, 0, 0.0) self.assertRaises(CircuitError, qc.ry, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.ry, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.ry, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.ry, 0, "a") def test_ry_reg(self): instruction_set = self.circuit.ry(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_ry_reg_inv(self): instruction_set = self.circuit.ry(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "ry") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_ry_pi(self): qc = self.circuit qc.ry(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "ry") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) def test_rz(self): self.circuit.rz(1, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_wires(self): self.circuit.rz(1, 1) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rz, self.cr[0], self.cr[1]) self.assertRaises(CircuitError, qc.rz, self.qr[1], 0) self.assertRaises(CircuitError, qc.rz, 0, self.cr[0]) self.assertRaises(CircuitError, qc.rz, 0, 0.0) self.assertRaises(CircuitError, qc.rz, self.qr[2], self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, (self.qr, 3)) self.assertRaises(CircuitError, qc.rz, 0, self.cr) # TODO self.assertRaises(CircuitError, qc.rz, 'a', self.qr[1]) self.assertRaises(CircuitError, qc.rz, 0, "a") def test_rz_reg(self): instruction_set = self.circuit.rz(1, self.qr) self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [1]) def test_rz_reg_inv(self): instruction_set = self.circuit.rz(1, self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "rz") self.assertEqual(instruction_set[2].operation.params, [-1]) def test_rz_pi(self): self.circuit.rz(pi / 2, self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "rz") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_rzz(self): self.circuit.rzz(1, self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_wires(self): self.circuit.rzz(1, 1, 2) self.assertEqual(self.circuit[0].operation.name, "rzz") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_rzz_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.rzz, 1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 1, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.rzz, 1, self.cr, self.qr) self.assertRaises(CircuitError, qc.rzz, 1, "a", self.qr[1]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.rzz, 0.1, self.qr[0], self.qr[0]) def test_s(self): self.circuit.s(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_wires(self): self.circuit.s(1) self.assertEqual(self.circuit[0].operation.name, "s") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_s_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.s, self.cr[0]) self.assertRaises(CircuitError, qc.s, self.cr) self.assertRaises(CircuitError, qc.s, (self.qr, 3)) self.assertRaises(CircuitError, qc.s, (self.qr, "a")) self.assertRaises(CircuitError, qc.s, 0.0) def test_s_reg(self): instruction_set = self.circuit.s(self.qr) self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_s_reg_inv(self): instruction_set = self.circuit.s(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg(self): self.circuit.sdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_wires(self): self.circuit.sdg(1) self.assertEqual(self.circuit[0].operation.name, "sdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_sdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.sdg, self.cr[0]) self.assertRaises(CircuitError, qc.sdg, self.cr) self.assertRaises(CircuitError, qc.sdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.sdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.sdg, 0.0) def test_sdg_reg(self): instruction_set = self.circuit.sdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "sdg") self.assertEqual(instruction_set[2].operation.params, []) def test_sdg_reg_inv(self): instruction_set = self.circuit.sdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "s") self.assertEqual(instruction_set[2].operation.params, []) def test_swap(self): self.circuit.swap(self.qr[1], self.qr[2]) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_wires(self): self.circuit.swap(1, 2) self.assertEqual(self.circuit[0].operation.name, "swap") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1], self.qr[2])) def test_swap_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.swap, self.cr[1], self.cr[2]) self.assertRaises(CircuitError, qc.swap, self.qr[0], self.qr[0]) self.assertRaises(CircuitError, qc.swap, 0.0, self.qr[0]) self.assertRaises(CircuitError, qc.swap, (self.qr, 3), self.qr[0]) self.assertRaises(CircuitError, qc.swap, self.cr, self.qr) self.assertRaises(CircuitError, qc.swap, "a", self.qr[1]) self.assertRaises(CircuitError, qc.swap, self.qr, self.qr2[[1, 2]]) self.assertRaises(CircuitError, qc.swap, self.qr[:2], self.qr2) def test_t(self): self.circuit.t(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_wire(self): self.circuit.t(1) self.assertEqual(self.circuit[0].operation.name, "t") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_t_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.t, self.cr[0]) self.assertRaises(CircuitError, qc.t, self.cr) self.assertRaises(CircuitError, qc.t, (self.qr, 3)) self.assertRaises(CircuitError, qc.t, (self.qr, "a")) self.assertRaises(CircuitError, qc.t, 0.0) def test_t_reg(self): instruction_set = self.circuit.t(self.qr) self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[2].operation.params, []) def test_t_reg_inv(self): instruction_set = self.circuit.t(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[2].operation.params, []) def test_tdg(self): self.circuit.tdg(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_wires(self): self.circuit.tdg(1) self.assertEqual(self.circuit[0].operation.name, "tdg") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_tdg_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.tdg, self.cr[0]) self.assertRaises(CircuitError, qc.tdg, self.cr) self.assertRaises(CircuitError, qc.tdg, (self.qr, 3)) self.assertRaises(CircuitError, qc.tdg, (self.qr, "a")) self.assertRaises(CircuitError, qc.tdg, 0.0) def test_tdg_reg(self): instruction_set = self.circuit.tdg(self.qr) self.assertEqual(instruction_set[0].operation.name, "tdg") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_tdg_reg_inv(self): instruction_set = self.circuit.tdg(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "t") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_u1(self): self.circuit.append(U1Gate(1), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_wires(self): self.circuit.append(U1Gate(1), [1]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [1]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u1_reg(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1]) def test_u1_reg_inv(self): instruction_set = self.circuit.append(U1Gate(1), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u1") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_u1_pi(self): qc = self.circuit qc.append(U1Gate(pi / 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u1") self.assertEqual(self.circuit[0].operation.params, [pi / 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2(self): self.circuit.append(U2Gate(1, 2), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_wires(self): self.circuit.append(U2Gate(1, 2), [1]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [1, 2]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u2_reg(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2]) def test_u2_reg_inv(self): instruction_set = self.circuit.append(U2Gate(1, 2), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u2") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-pi - 2, -1 + pi]) def test_u2_pi(self): self.circuit.append(U2Gate(pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u2") self.assertEqual(self.circuit[0].operation.params, [pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3(self): self.circuit.append(U3Gate(1, 2, 3), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_wires(self): self.circuit.append(U3Gate(1, 2, 3), [1]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [1, 2, 3]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_u3_reg(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]) self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_u3_reg_inv(self): instruction_set = self.circuit.append(U3Gate(1, 2, 3), [self.qr]).inverse() self.assertEqual(instruction_set[0].operation.name, "u3") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_u3_pi(self): self.circuit.append(U3Gate(pi, pi / 2, 0.3 * pi), [self.qr[1]]) self.assertEqual(self.circuit[0].operation.name, "u3") self.assertEqual(self.circuit[0].operation.params, [pi, pi / 2, 0.3 * pi]) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x(self): self.circuit.x(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_wires(self): self.circuit.x(1) self.assertEqual(self.circuit[0].operation.name, "x") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_x_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.x, self.cr[0]) self.assertRaises(CircuitError, qc.x, self.cr) self.assertRaises(CircuitError, qc.x, (self.qr, "a")) self.assertRaises(CircuitError, qc.x, 0.0) def test_x_reg(self): instruction_set = self.circuit.x(self.qr) self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_x_reg_inv(self): instruction_set = self.circuit.x(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "x") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y(self): self.circuit.y(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_wires(self): self.circuit.y(1) self.assertEqual(self.circuit[0].operation.name, "y") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_y_invalid(self): qc = self.circuit self.assertRaises(CircuitError, qc.y, self.cr[0]) self.assertRaises(CircuitError, qc.y, self.cr) self.assertRaises(CircuitError, qc.y, (self.qr, "a")) self.assertRaises(CircuitError, qc.y, 0.0) def test_y_reg(self): instruction_set = self.circuit.y(self.qr) self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_y_reg_inv(self): instruction_set = self.circuit.y(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "y") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z(self): self.circuit.z(self.qr[1]) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_wires(self): self.circuit.z(1) self.assertEqual(self.circuit[0].operation.name, "z") self.assertEqual(self.circuit[0].operation.params, []) self.assertEqual(self.circuit[0].qubits, (self.qr[1],)) def test_z_reg(self): instruction_set = self.circuit.z(self.qr) self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_z_reg_inv(self): instruction_set = self.circuit.z(self.qr).inverse() self.assertEqual(instruction_set[0].operation.name, "z") self.assertEqual(instruction_set[1].qubits, (self.qr[1],)) self.assertEqual(instruction_set[2].operation.params, []) def test_global_phase(self): qc = self.circuit qc.append(GlobalPhaseGate(0.1), []) self.assertEqual(self.circuit[0].operation.name, "global_phase") self.assertEqual(self.circuit[0].operation.params, [0.1]) self.assertEqual(self.circuit[0].qubits, ()) def test_global_phase_inv(self): instruction_set = self.circuit.append(GlobalPhaseGate(0.1), []).inverse() self.assertEqual(len(instruction_set), 1) self.assertEqual(instruction_set[0].operation.params, [-0.1]) def test_global_phase_matrix(self): """Test global_phase matrix.""" theta = 0.1 np.testing.assert_allclose( np.array(GlobalPhaseGate(theta)), np.array([[np.exp(1j * theta)]], dtype=complex), atol=1e-7, ) def test_global_phase_consistency(self): """Tests compatibility of GlobalPhaseGate with QuantumCircuit.global_phase""" theta = 0.1 qc1 = QuantumCircuit(0, global_phase=theta) qc2 = QuantumCircuit(0) qc2.append(GlobalPhaseGate(theta), []) np.testing.assert_allclose( Operator(qc1), Operator(qc2), atol=1e-7, ) def test_transpile_global_phase_consistency(self): """Tests compatibility of transpiled GlobalPhaseGate with QuantumCircuit.global_phase""" qc1 = QuantumCircuit(0, global_phase=0.3) qc2 = QuantumCircuit(0, global_phase=0.2) qc2.append(GlobalPhaseGate(0.1), []) np.testing.assert_allclose( Operator(transpile(qc1, basis_gates=["u"])), Operator(transpile(qc2, basis_gates=["u"])), atol=1e-7, ) @ddt class TestStandard2Q(QiskitTestCase): """Standard Extension Test. Gates with two Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.cr) def test_barrier_reg_bit(self): self.circuit.barrier(self.qr, self.qr2[0]) self.assertEqual(len(self.circuit), 1) self.assertEqual(self.circuit[0].operation.name, "barrier") self.assertEqual(self.circuit[0].qubits, (self.qr[0], self.qr[1], self.qr[2], self.qr2[0])) def test_ch_reg_reg(self): instruction_set = self.circuit.ch(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_reg_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_reg_bit_inv(self): instruction_set = self.circuit.ch(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual( instruction_set[1].qubits, ( self.qr[1], self.qr2[1], ), ) self.assertEqual(instruction_set[2].operation.params, []) def test_ch_bit_reg(self): instruction_set = self.circuit.ch(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "ch") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_crz_reg_reg(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_reg_bit(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_reg_bit_inv(self): instruction_set = self.circuit.crz(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crz_bit_reg(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crz_bit_reg_inv(self): instruction_set = self.circuit.crz(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_reg(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_reg_bit(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_reg_bit_inv(self): instruction_set = self.circuit.cry(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cry_bit_reg(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cry_bit_reg_inv(self): instruction_set = self.circuit.cry(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cry") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_reg(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_reg_bit(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_reg_bit_inv(self): instruction_set = self.circuit.crx(1, self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_crx_bit_reg(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_crx_bit_reg_inv(self): instruction_set = self.circuit.crx(1, self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "crx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_reg_bit(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_reg_bit_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu1_bit_reg(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1]) def test_cu1_bit_reg_inv(self): instruction_set = self.circuit.append(CU1Gate(1), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu1") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1]) def test_cu3_reg_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_reg_bit(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_reg_bit_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr, self.qr2[1]]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cu3_bit_reg(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]) self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [1, 2, 3]) def test_cu3_bit_reg_inv(self): instruction_set = self.circuit.append(CU3Gate(1, 2, 3), [self.qr[1], self.qr2]).inverse() self.assertEqual(instruction_set[0].operation.name, "cu3") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, [-1, -3, -2]) def test_cx_reg_reg(self): instruction_set = self.circuit.cx(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_reg_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_reg_bit_inv(self): instruction_set = self.circuit.cx(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cx_bit_reg_inv(self): instruction_set = self.circuit.cx(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg(self): instruction_set = self.circuit.cy(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_reg_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_reg_bit_inv(self): instruction_set = self.circuit.cy(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cy_bit_reg_inv(self): instruction_set = self.circuit.cy(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cy") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg(self): instruction_set = self.circuit.cz(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_reg_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_reg_bit_inv(self): instruction_set = self.circuit.cz(self.qr, self.qr2[1]).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2) self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cz_bit_reg_inv(self): instruction_set = self.circuit.cz(self.qr[1], self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "cz") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg(self): instruction_set = self.circuit.swap(self.qr, self.qr2) self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_swap_reg_reg_inv(self): instruction_set = self.circuit.swap(self.qr, self.qr2).inverse() self.assertEqual(instruction_set[0].operation.name, "swap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1])) self.assertEqual(instruction_set[2].operation.params, []) @unpack @data( (0, 0, np.eye(4)), ( np.pi / 2, np.pi / 2, np.array( [ [np.sqrt(2) / 2, 0, 0, -np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), ( np.pi, np.pi / 2, np.array([[0, 0, 0, -1], [0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]), ), ( 2 * np.pi, np.pi / 2, np.array([[-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]]), ), ( np.pi / 2, np.pi, np.array( [ [np.sqrt(2) / 2, 0, 0, 1j * np.sqrt(2) / 2], [0, 1, 0, 0], [0, 0, 1, 0], [1j * np.sqrt(2) / 2, 0, 0, np.sqrt(2) / 2], ] ), ), (4 * np.pi, 0, np.eye(4)), ) def test_xx_minus_yy_matrix(self, theta: float, beta: float, expected: np.ndarray): """Test XX-YY matrix.""" gate = XXMinusYYGate(theta, beta) np.testing.assert_allclose(np.array(gate), expected, atol=1e-7) def test_xx_minus_yy_exponential_formula(self): """Test XX-YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXMinusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz1 = np.kron(np.array(RZGate(beta)), np.eye(2)) np.testing.assert_allclose( np.array(gate), rz1 @ expm(-0.25j * theta * (xx - yy)) @ rz1.T.conj(), atol=1e-7, ) def test_xx_plus_yy_exponential_formula(self): """Test XX+YY exponential formula.""" theta, beta = np.random.uniform(-10, 10, size=2) gate = XXPlusYYGate(theta, beta) x = np.array(XGate()) y = np.array(YGate()) xx = np.kron(x, x) yy = np.kron(y, y) rz0 = np.kron(np.eye(2), np.array(RZGate(beta))) np.testing.assert_allclose( np.array(gate), rz0.T.conj() @ expm(-0.25j * theta * (xx + yy)) @ rz0, atol=1e-7, ) class TestStandard3Q(QiskitTestCase): """Standard Extension Test. Gates with three Qubits""" def setUp(self): super().setUp() self.qr = QuantumRegister(3, "q") self.qr2 = QuantumRegister(3, "r") self.qr3 = QuantumRegister(3, "s") self.cr = ClassicalRegister(3, "c") self.circuit = QuantumCircuit(self.qr, self.qr2, self.qr3, self.cr) def test_ccx_reg_reg_reg(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_ccx_reg_reg_inv(self): instruction_set = self.circuit.ccx(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "ccx") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_reg(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3) self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) def test_cswap_reg_reg_inv(self): instruction_set = self.circuit.cswap(self.qr, self.qr2, self.qr3).inverse() self.assertEqual(instruction_set[0].operation.name, "cswap") self.assertEqual(instruction_set[1].qubits, (self.qr[1], self.qr2[1], self.qr3[1])) self.assertEqual(instruction_set[2].operation.params, []) class TestStandardMethods(QiskitTestCase): """Standard Extension Test.""" @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix(self): """test gates implementing to_matrix generate matrix which matches definition.""" from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * (i + 1) for i in range(10)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() simulator = BasicAer.get_backend("unitary_simulator") for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue circ = QuantumCircuit(gate.num_qubits) circ.append(gate, range(gate.num_qubits)) try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue definition_unitary = execute([circ], simulator).result().get_unitary() with self.subTest(gate_class): # TODO check for exact equality once BasicAer can handle global phase self.assertTrue(matrix_equal(definition_unitary, gate_matrix, ignore_phase=True)) self.assertTrue(is_unitary_matrix(gate_matrix)) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") def test_to_matrix_op(self): """test gates implementing to_matrix generate matrix which matches definition using Operator.""" from qiskit.circuit.library.generalized_gates.gms import MSGate from qiskit.circuit.library.generalized_gates.pauli import PauliGate from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate from qiskit.circuit.classicalfunction.boolean_expression import BooleanExpression params = [0.1 * i for i in range(1, 11)] gate_class_list = Gate.__subclasses__() + ControlledGate.__subclasses__() for gate_class in gate_class_list: if hasattr(gate_class, "__abstractmethods__"): # gate_class is abstract continue sig = signature(gate_class) if gate_class == MSGate: # due to the signature (num_qubits, theta, *, n_qubits=Noe) the signature detects # 3 arguments but really its only 2. This if can be removed once the deprecated # n_qubits argument is no longer supported. free_params = 2 else: free_params = len(set(sig.parameters) - {"label", "ctrl_state"}) try: if gate_class == PauliGate: # special case due to PauliGate using string parameters gate = gate_class("IXYZ") elif gate_class == BooleanExpression: gate = gate_class("x") elif gate_class == PauliEvolutionGate: gate = gate_class(Pauli("XYZ")) else: gate = gate_class(*params[0:free_params]) except (CircuitError, QiskitError, AttributeError, TypeError): self.log.info("Cannot init gate with params only. Skipping %s", gate_class) continue if gate.name in ["U", "CX"]: continue try: gate_matrix = gate.to_matrix() except CircuitError: # gate doesn't implement to_matrix method: skip self.log.info('to_matrix method FAILED for "%s" gate', gate.name) continue if not hasattr(gate, "definition") or not gate.definition: continue definition_unitary = Operator(gate.definition).data self.assertTrue(matrix_equal(definition_unitary, gate_matrix)) self.assertTrue(is_unitary_matrix(gate_matrix)) if __name__ == "__main__": unittest.main(verbosity=2)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.wrapper import available_backends, get_backend from qiskit.wrapper import execute as q_execute q = QuantumRegister(2, name='q') c = ClassicalRegister(2, name='c') qc = QuantumCircuit(q,c) qc.h(q[0]) qc.h(q[1]) qc.cx(q[0], q[1]) qc.measure(q, c) z = 0.995004165 + 1j * 0.099833417 z = z / abs(z) u_error = np.array([[1, 0], [0, z]]) noise_params = {'U': {'gate_time': 1, 'p_depol': 0.001, 'p_pauli': [0, 0, 0.01], 'U_error': u_error } } config = {"noise_params": noise_params} ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config) ret = ret.result() print(ret.get_counts())
https://github.com/Tojarieh97/VQE
Tojarieh97
%load_ext autoreload %autoreload 2 import nbimporter from typing import Dict, Tuple, List import numpy as np from tqdm import tqdm QUBITS_NUM = 4 N = 2**QUBITS_NUM NUM_SHOTS = 1024 NUM_ITERATIONS = 100 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals seed = 50 algorithm_globals.random_seed = seed simulator_backend = Aer.get_backend('qasm_simulator') from scipy.optimize import minimize from linear_entangelment_and_full_entangelment_ansatz_circuits import * def get_ansatz_state(thetas, ansatz_entangelment, input_state): if ansatz_entangelment=="full": return get_full_entangelment_ansatz(QUBITS_NUM, thetas, input_state) if ansatz_entangelment=="linear": return get_linear_entangelment_ansatz(QUBITS_NUM, thetas, input_state) def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List: pauli_operators = hamiltonian.to_pauli_op().settings['oplist'] pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators)) pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators)) return pauli_coeffs, pauli_strings from qiskit.circuit.library.standard_gates import HGate, SGate from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister reducing_to_pauli_z_mapping = { 'I': 'I', 'Z': 'Z', 'X': 'Z', 'Y': 'Z' } def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str: reduced_pauli_string = "" for matrix_index in range(QUBITS_NUM): pauli_matrix = str(pauli_string[matrix_index]) reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix] reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string return reduced_pauli_string def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit): quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit") additional_circuit_layer = QuantumCircuit(quantum_registers) for quantum_register_index, pauli_matrix in enumerate(pauli_string): if pauli_matrix == "X": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) if pauli_string == "Y": additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]]) additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]]) extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer) return extended_quantum_circuit def get_probability_distribution(counts: Dict) -> Dict: proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()} return proba_distribution def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict: quantum_state_circuit.measure_all() transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend) Qobj = assemble(transpiled_quantum_state_circuit) result = simulator_backend.run(Qobj).result() counts = result.get_counts(quantum_state_circuit) return get_probability_distribution(counts) def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict: return dict(sorted(proba_distribution.items())) def reset_power_of_minus_1(power_of_minus_1): power_of_minus_1 = 0 return power_of_minus_1 def convert_pauli_string_into_str(pauli_string) -> str: return str(pauli_string) def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit): pauli_string_expectation_value = 0 power_of_minus_1 = 0 pauli_string_str = convert_pauli_string_into_str(pauli_string) extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit) probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit) reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string) sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution) for qubits_string, proba in sorted_probas_distribuition.items(): for string_index in range(QUBITS_NUM): if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"): power_of_minus_1 += 1 pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1) return pauli_string_expectation_value def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings): total_expection_value = 0 for pauli_coeff, pauli_string in zip(pauli_coeffs, pauli_strings): total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas( pauli_string, ansatz_circuit) return total_expection_value from qiskit import assemble, transpile def cost_function(thetas, hamiltonian, ansatz_entangelment): initial_eigenvector = np.identity(N)[0] pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) ansatz_state = get_ansatz_state(thetas, ansatz_entangelment, initial_eigenvector) L = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings) insert_approximated_energy_to_list_of_all_approximated_energies(L) return L def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment): initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM) optimizer_result = minimize(cost_function, x0=initial_thetas, args=(hamiltonian, ansatz_entangelment), method="Nelder-Mead", options={"maxiter":NUM_ITERATIONS, "return_all": True, "disp": True}) optimal_thetas = optimizer_result.x return optimal_thetas def get_approximated_eigenvalue_of_hamiltonian(hamiltonian, ansatz_entangelment): optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian, ansatz_entangelment) print(optimal_thetas) initial_eigenvector = np.identity(N)[3] optimal_ansatz_state = get_ansatz_state(optimal_thetas, ansatz_entangelment, initial_eigenvector) pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian) approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings) return approximated_eigenvalue from numpy import linalg as LA def get_approximation_error(exact_eigenvalue, approximated_eigenvalue): return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue) def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian): eigen_values = LA.eigvals(hamiltonian.to_matrix()) print(sorted(eigen_values)) return min(sorted(eigen_values)) def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue): exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian) print("Exact Eigenvalue:") print(exact_eigenvalue) print("\nApproximated Eigenvalue:") print(approximated_eigenvalue) print("\nApproximation Error") print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue)) plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3) approximated_energies = [] def insert_approximated_energy_to_list_of_all_approximated_energies(energy): approximated_energies.append(energy) import matplotlib.pyplot as plt def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin): plt.title("convergence of optimization process to the exact eigenvalue") plt.margins(0, margin) plt.plot(approximated_energies[-NUM_ITERATIONS:]) plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-') plt.grid() plt.xlabel("# of iterations") plt.ylabel("Energy") def plot_fidelity(): plt.plot(LiH_approximated_energies) plt.xlabel("# of iterations") plt.ylabel("Energy") from qiskit.opflow import X, Z, I, H, Y LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \ -0.0029329964409502266*(X^X^Y^Y) + \ 0.0029329964409502266*(X^Y^Y^X) + \ 0.01291078027311749*(X^Z^X^I) + \ -0.0013743761078958677*(X^Z^X^Z) + \ 0.011536413200774975*(X^I^X^I) + \ 0.0029329964409502266*(Y^X^X^Y) + \ -0.0029329964409502266*(Y^Y^X^X) + \ 0.01291078027311749*(Y^Z^Y^I) + \ -0.0013743761078958677*(Y^Z^Y^Z) + \ 0.011536413200774975*(Y^I^Y^I) + \ 0.16199475388004184*(Z^I^I^I) + \ 0.011536413200774975*(Z^X^Z^X) + \ 0.011536413200774975*(Z^Y^Z^Y) + \ 0.12444770133137588*(Z^Z^I^I) + \ 0.054130445793298836*(Z^I^Z^I) + \ 0.05706344223424907*(Z^I^I^Z) + \ 0.012910780273117487*(I^X^Z^X) + \ -0.0013743761078958677*(I^X^I^X) + \ 0.012910780273117487*(I^Y^Z^Y) + \ -0.0013743761078958677*(I^Y^I^Y) + \ 0.16199475388004186*(I^Z^I^I) + \ 0.05706344223424907*(I^Z^Z^I) + \ 0.054130445793298836*(I^Z^I^Z) + \ -0.013243698330265966*(I^I^Z^I) + \ 0.08479609543670981*(I^I^Z^Z) + \ -0.013243698330265952*(I^I^I^Z) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) %%time LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits, "full") compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue) H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \ + 0.1721839326191554 * (I^I^I^Z) \ - 0.22575349222402372 * (I^I^Z^I) \ + 0.17218393261915543 * (I^Z^I^I) \ - 0.2257534922240237 * (Z^I^I^I) \ + 0.12091263261776627 * (I^I^Z^Z) \ + 0.16892753870087907 * (I^Z^I^Z) \ + 0.045232799946057826 * (Y^Y^Y^Y) \ + 0.045232799946057826 * (X^X^Y^Y) \ + 0.045232799946057826 * (Y^Y^X^X) \ + 0.045232799946057826 * (X^X^X^X) \ + 0.1661454325638241 * (Z^I^I^Z) \ + 0.1661454325638241 * (I^Z^Z^I) \ + 0.17464343068300453 * (Z^I^Z^I) \ + 0.12091263261776627 * (Z^Z^I^I) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue) transverse_ising_4_qubits = 0.0 * (I^I^I^I) \ + 0.8398088405253477 * (X^I^I^I) \ + 0.7989496312070936 * (I^X^I^I) \ + 0.38189710487113193 * (Z^Z^I^I) \ + 0.057753122422666725 * (I^I^X^I) \ + 0.5633292636970458 * (Z^I^Z^I) \ + 0.3152740621483513 * (I^Z^Z^I) \ + 0.07209487981989715 * (I^I^I^X) \ + 0.17892334004292654 * (Z^I^I^Z) \ + 0.2273896497668042 * (I^Z^I^Z) \ + 0.09762902934216211 * (I^I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 3 N = 2**QUBITS_NUM NUM_SHOTS = 1024 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) from qiskit.opflow import X, Z, I transverse_ising_3_qubits = 0.0 * (I^I^I) \ + 0.012764169333459807 * (X^I^I) \ + 0.7691573729160869 * (I^X^I) \ + 0.398094746026449 * (Z^Z^I) \ + 0.15250261906586637 * (I^I^X) \ + 0.2094051920882264 * (Z^I^Z) \ + 0.5131291860752999 * (I^Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue) QUBITS_NUM = 2 N = 2**QUBITS_NUM NUM_SHOTS = 1024 CIRCUIT_DEPTH = 3 PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1) transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \ + 0.43305656297810435 * (X^I) \ + 0.8538597608997253 * (Z^Z) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) %%time TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits, "full") compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue) from qiskit.opflow import X, Z, I H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \ -0.3277380754984016*(Z^I) + \ 0.15567463610622564*(Z^Z) + \ -0.3277380754984016*(I^Z) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "linear") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue) %%time H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits, "full") compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import * from qiskit.visualization import plot_histogram # quantum circuit to make a Bell state bell = QuantumCircuit(2, 2) bell.h(0) bell.cx(0, 1) meas = QuantumCircuit(2, 2) meas.measure([0,1], [0,1]) # execute the quantum circuit backend = BasicAer.get_backend('qasm_simulator') # the device to run on circ = bell.compose(meas) result = backend.run(transpile(circ, backend), shots=1000).result() counts = result.get_counts(circ) print(counts) plot_histogram(counts) # Execute 2-qubit Bell state again second_result = backend.run(transpile(circ, backend), shots=1000).result() second_counts = second_result.get_counts(circ) # Plot results with legend legend = ['First execution', 'Second execution'] plot_histogram([counts, second_counts], legend=legend) plot_histogram([counts, second_counts], legend=legend, sort='desc', figsize=(15,12), color=['orange', 'black'], bar_labels=False) from qiskit.visualization import plot_state_city, plot_bloch_multivector from qiskit.visualization import plot_state_paulivec, plot_state_hinton from qiskit.visualization import plot_state_qsphere # execute the quantum circuit backend = BasicAer.get_backend('statevector_simulator') # the device to run on result = backend.run(transpile(bell, backend)).result() psi = result.get_statevector(bell) plot_state_city(psi) plot_state_hinton(psi) plot_state_qsphere(psi) plot_state_paulivec(psi) plot_bloch_multivector(psi) plot_state_city(psi, title="My City", color=['black', 'orange']) plot_state_hinton(psi, title="My Hinton") plot_state_paulivec(psi, title="My Paulivec", color=['purple', 'orange', 'green']) plot_bloch_multivector(psi, title="My Bloch Spheres") from qiskit.visualization import plot_bloch_vector plot_bloch_vector([0,1,0]) plot_bloch_vector([0,1,0], title='My Bloch Sphere') import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/Pitt-JonesLab/slam_decomposition
Pitt-JonesLab
import logging import os import pickle from inspect import signature from itertools import cycle from typing import List from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.circuit.library.standard_gates import * from qiskit.quantum_info import Operator from config import srcpath from slam.basis_abc import VariationalTemplate from slam.hamiltonian import Hamiltonian from slam.utils.data_utils import filename_encode from slam.utils.gates.custom_gates import * from slam.utils.polytopes.polytope_wrap import ( gate_set_to_coverage, monodromy_range_from_target, ) class HamiltonianTemplate(VariationalTemplate): def __init__(self, h: Hamiltonian): self.filename = filename_encode(repr(h)) self.h = h self.spanning_range = range(1) self.using_bounds = False self.using_constraints = False self.bounds_list = None self.constraint_func = None super().__init__(preseed=False, use_polytopes=False) def get_spanning_range(self, target_u): return range(1, 2) # only need to build once, in lieu of a circuit template def eval(self, Xk): return self.h.construct_U(*Xk).full() def parameter_guess(self, t=1): parent = super().parameter_guess(t) if parent is not None: return parent p_len = len( signature(self.h.construct_U).parameters ) # getting number of parameters from Hamiltonian function definition return np.random.random(p_len) class CircuitTemplate(VariationalTemplate): def __init__( self, n_qubits=2, base_gates=[RiSwapGate(1 / 2)], edge_params=[[(0, 1)]], no_exterior_1q=False, use_polytopes=False, maximum_span_guess=5, preseed=False, ): """Initalizes a qiskit.quantumCircuit object with unbound 1Q gate parameters.""" hash = str(n_qubits) + str(base_gates) + str(edge_params) + str(no_exterior_1q) self.filename = filename_encode(hash) self.n_qubits = n_qubits self.no_exterior_1q = no_exterior_1q self.gate_2q_base = cycle(base_gates) # each gate gets its on cycler self.gate_2q_edges = cycle( [cycle(edge_params_el) for edge_params_el in edge_params] ) self.gen_1q_params = self._param_iter() # compliant with basisv2 optimizer changes self.using_bounds = False self.bounds_list = None self.using_constraints = False self.constraint_func = None # define a range to see how many times we should extend the circuit while in optimization search self.spanning_range = None if not use_polytopes: self.spanning_range = range(1, maximum_span_guess + 1) self.coverage = None # only precomputed in mixedbasis class super().__init__(preseed=preseed, use_polytopes=use_polytopes) self._reset() # deprecated feature self.trotter = False def get_spanning_range(self, target_u): if not self.use_polytopes: return self.spanning_range else: # call monodromy polytope helper return monodromy_range_from_target(self, target_u) def eval(self, Xk): """Returns an Operator after binding parameter array to template.""" return Operator(self.assign_Xk(Xk)).data def parameter_guess(self, t=0): """Returns a np array of random values for each parameter.""" parent = super().parameter_guess(t) if parent is not None: return parent return np.random.random(len(self.circuit.parameters)) * 2 * np.pi def assign_Xk(self, Xk): return self.circuit.assign_parameters( {parameter: i for parameter, i in zip(self.circuit.parameters, Xk)} ) def _reset(self): """Return template to a 0 cycle.""" self.cycles = 0 self.circuit = QuantumCircuit(self.n_qubits) self.gen_1q_params = self._param_iter() # reset p labels def build(self, n_repetitions): self._reset() if n_repetitions <= 0: raise ValueError() if self.trotter: pass # n_repetitions = int(1 / next(self.gate_2q_params)) for i in range(n_repetitions): self._build_cycle(initial=(i == 0), final=(i == n_repetitions - 1)) def _param_iter(self): index = 0 while True: # Check if Parameter already created, then return reference to that variable def _filter_param(param): return param.name == f"P{index}" res = list(filter(_filter_param, self.circuit.parameters)) if len(res) == 0: yield Parameter(f"P{index}") else: yield res[0] index += 1 if self.trotter: index %= 3 * self.n_qubits def _build_cycle(self, initial=False, final=False): """Extends template by next nonlocal gate.""" if initial and not self.no_exterior_1q: # before build by extend, add first pair of 1Qs for qubit in range(self.n_qubits): self.circuit.u(*[next(self.gen_1q_params) for _ in range(3)], qubit) # self.circuit.ry(*[next(self.gen_1q_params) for _ in range(1)], qubit) gate = next(self.gate_2q_base) edge = next( next(self.gate_2q_edges) ) # call cycle twice to increment gate index then edge self.circuit.append(gate, edge) if not (final and self.no_exterior_1q): for qubit in edge: # self.circuit.ry(*[next(self.gen_1q_params) for _ in range(1)], qubit) self.circuit.u(*[next(self.gen_1q_params) for _ in range(3)], qubit) self.cycles += 1 """this might be deprecated, if I want to use gate costs, should be factored in with circuit polytopes already for now, instead just use the mixedbasis instead""" # class CustomCostCircuitTemplate(CircuitTemplate): # # #assigns a cost value to each repeated call to build() # def __init__(self, base_gates=[CustomCostGate]) -> None: # logging.warning("deprecated, use mixedorderbasis with cost assigned to cirucit polytopes") # for gate in base_gates: # if not isinstance(gate, CustomCostGate): # raise ValueError("Gates must have a defined cost") # self.cost = {0:0} # super().__init__(n_qubits=2, base_gates=base_gates, edge_params=[(0,1)], no_exterior_1q=False,use_polytopes=True, preseed=True) # def _build_cycle(self, initial=False, final=False): # """Extends template by next nonlocal gate # add modification which saves cost to dict""" # if initial and not self.no_exterior_1q: # # before build by extend, add first pair of 1Qs # for qubit in range(self.n_qubits): # self.circuit.u(*[next(self.gen_1q_params) for _ in range(3)], qubit) # edge = next(self.gate_2q_edges) # gate = next(self.gate_2q_base) # self.circuit.append(gate, edge) # if not (final and self.no_exterior_1q): # for qubit in edge: # self.circuit.u(*[next(self.gen_1q_params) for _ in range(3)], qubit) # self.cycles += 1 # self.cost[self.cycles] = self.cost[self.cycles-1] + gate.cost # def unit_cost(self, cycles): # if not cycles in self.cost.keys(): # self.build(cycles) # return self.cost[cycles] """if hetereogenous basis, build is always appending in a set order we really want to be able to pick and choose freely when we find monodromy spanning range, we actually need to be checking more combinations of gates find the minimum cost polytope which contains target now when we create basis it should precompute the coverage polytopes and order them based on cost""" class MixedOrderBasisCircuitTemplate(CircuitTemplate): # in previous circuit templates, everytime we call build it extends based on a predefined pattern # now for mixed basis sets, polytope coverage informs a better way to mix and match # this method needs to override the build method # this means monodromy_range_from_target needs to return a circuit polytope # we update template to match circuit polytope shape # then tell optimizer range to be range(1) so it knows not to call build again def __init__( self, base_gates: List[CustomCostGate], chatty_build=True, cost_1q=0, bare_cost=True, coverage_saved_memory=True, use_smush_polytope=False, **kwargs, ) -> None: self.homogenous = len(base_gates) == 1 if cost_1q != 0 or bare_cost is False: logging.warning( "rather than setting cost_1q, use bare_cost=True and scale the cost afterwards - that way don't have misses in saved memory.\ (see bgatev2script.py for implementation)" ) raise ValueError("just don't do this lol") if not all([isinstance(gate, ConversionGainGate) for gate in base_gates]): raise ValueError("all base gates must be ConversionGainGate") # set gc < gg so that we can use the same polytope for both cases # XXX note this means the gate_hash will refer to the wrong gate, but in speedlimit pass we override build() with scaled_gate param anyway new_base_gates = [] for gate in base_gates: if gate.params[2] < gate.params[3]: new_base_gates.append(gate) else: new_params = gate.params # swap gc and gg new_params[2], new_params[3] = new_params[3], new_params[2] temp_new_gate = ConversionGainGate(*new_params) new_base_gates.append(temp_new_gate) base_gates = new_base_gates # assuming bare costs we should normalize the gate duration to 1 for gate in base_gates: gate.normalize_duration(1) super().__init__( n_qubits=2, base_gates=base_gates, edge_params=[[(0, 1)]], no_exterior_1q=False, use_polytopes=True, preseed=False, ) if coverage_saved_memory: # used list comprehension so each CG gate has its own str function called file_hash = str([str(g) for g in base_gates]) if use_smush_polytope: file_hash += "smush" filepath = f"{srcpath}/data/polytopes/polytope_coverage_{file_hash}.pkl" while True: # try load from memory if os.path.exists(filepath): # XXX hardcoded file path' logging.debug("loading polytope coverage from memory") with open(filepath, "rb") as f: # NOTE this is hacky monkey patch, if we had more time we would transfer the old values to use this formatting # non smushes use the h5 data loads, but we wanted to make variations of the gate so overriding that h5 data by storing an optional value in the class if use_smush_polytope: self.coverage, self.gate_hash, self.scores = pickle.load(f) return else: self.coverage, self.gate_hash = pickle.load(f) self.scores = None return elif use_smush_polytope: raise ValueError( "Smush Polytope not in memory, need to compute using parallel_drive_volume.py" ) logging.warning("Failed to load smush, using non-smush instead") file_hash = file_hash[:-5] use_smush_polytope = False filepath = ( f"{srcpath}/data/polytopes/polytope_coverage_{file_hash}.pkl" ) else: # if not in memory, compute and save logging.warning( f"No saved polytope! computing polytope coverage for {file_hash}" ) self.coverage, self.gate_hash = gate_set_to_coverage( *base_gates, chatty=chatty_build, cost_1q=cost_1q, bare_cost=bare_cost, ) with open(filepath, "wb") as f: pickle.dump((self.coverage, self.gate_hash), f) logging.debug("saved polytope coverage to file") return else: self.coverage, self.gate_hash = gate_set_to_coverage( *base_gates, chatty=chatty_build, cost_1q=cost_1q, bare_cost=bare_cost ) def set_polytope(self, circuit_polytope): self.circuit_polytope = circuit_polytope self.cost = circuit_polytope.cost # ? def unit_cost(self, n_): return self.cost def _reset(self): self.circuit_polytope = None super()._reset() def build(self, n_repetitions, scaled_gate=None): """The reason the build method is being overriden is specifically for mixed basis sets we want to be able to build circuits which have an arbitrary order of basis gates so we have to use info from monodromy monodromy communicates the order from a set polytope (which doesn't have access to gate object proper) via a hash that lets override the gate_2q_base generator.""" assert self.circuit_polytope is not None # NOTE: overriding the 2Q gate if we want to use a speed limited gate # used to manually set a duration attirbute if scaled_gate is not None: if not self.homogenous: raise ValueError( "Can't use this hacky substitute method for mixed basis sets" ) gate_list = [scaled_gate] * n_repetitions else: # convert circuit polytope into a qiskit circuit with variation 1q params gate_list = [ self.gate_hash[gate_key] for gate_key in self.circuit_polytope.operations ] self.gate_2q_base = cycle(gate_list) assert n_repetitions == len(gate_list) super().build(n_repetitions=len(gate_list))
https://github.com/anirban-m/qiskit-superstaq
anirban-m
import io from typing import List, Union import applications_superstaq import qiskit import qiskit.circuit.qpy_serialization def serialize_circuits(circuits: Union[qiskit.QuantumCircuit, List[qiskit.QuantumCircuit]]) -> str: """Serialize QuantumCircuit(s) into a single string Args: circuits: a QuantumCircuit or list of QuantumCircuits to be serialized Returns: str representing the serialized circuit(s) """ buf = io.BytesIO() qiskit.circuit.qpy_serialization.dump(circuits, buf) return applications_superstaq.converters._bytes_to_str(buf.getvalue()) def deserialize_circuits(serialized_circuits: str) -> List[qiskit.QuantumCircuit]: """Deserialize serialized QuantumCircuit(s) Args: serialized_circuits: str generated via qiskit_superstaq.serialization.serialize_circuit() Returns: a list of QuantumCircuits """ buf = io.BytesIO(applications_superstaq.converters._str_to_bytes(serialized_circuits)) return qiskit.circuit.qpy_serialization.load(buf)
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw()
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import * qc = QuantumCircuit(2) qc.h(i) qc.crz (PI/4, 0, 1)
https://github.com/daimurat/qiskit-implementation
daimurat
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterVector from qiskit.opflow import StateFn, PauliSumOp, Gradient def generate_random_qnn(qubits, depth): """Generate random QNN's with the same structure from McClean et al.""" param = Parameter('theta') circuit = QuantumCircuit(qubits) for qubit in range(qubits): circuit.ry(np.pi / 4.0, qubit) circuit.barrier() for d in range(depth): # Add a series of single qubit rotations. for qubit in range(qubits): random_n = np.random.uniform() random_rot = np.random.uniform() * 2.0 * np.pi if qubit != 0 or d != 0 else param if random_n > 2. / 3.: # Add a Z. circuit.rz(random_rot, qubit) elif random_n > 1. / 3.: # Add a Y. circuit.ry(random_rot, qubit) else: # Add a X. circuit.rx(random_rot, qubit) circuit.barrier() # Add CZ ladder. for src, dest in zip(range(qubits), range(qubits)[1:]): circuit.cz(src, dest) circuit.barrier() return circuit # 生成される回路の確認(例:3量子ビット) n_qubits = 3 d = 2 qc_test = generate_random_qnn(n_qubits, d) qc_test.draw('mpl') # 勾配の計算 def calc_gradient(qc, hamiltonian, params): expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(qc) state_grad = Gradient().convert(expectation) value_dict = dict(zip(qc.parameters, params)) result = state_grad.assign_parameters(value_dict).eval() return np.round(np.array(result), 10) # # テスト勾配計算 # test_hamiltonian = PauliSumOp.from_list([('Z', 1.0), ('X', 1.0)]) # test_params = np.random.uniform(0, np.pi, qc_test.num_parameters) # calc_gradient(qc_test, test_hamiltonian, test_params) n_qubits = [2 * i for i in range(2, 7)] depth = 30 n_circuits = 100 hamiltonian = PauliSumOp.from_list([('Z', 1.0), ('X', 1.0)]) theta_vars = [] for n in n_qubits: grads = [] # Generate the random circuits and observable for the given n. qc = generate_random_qnn(n, depth) for _ in range(n_circuits): params = np.random.uniform(0, np.pi, qc.num_parameters) grad = calc_gradient(qc, hamiltonian, params) grads.append(grad) theta_vars.append(np.var(grads)) plt.semilogy(n_qubits, theta_vars) plt.title('Gradient Variance in QNNs') plt.xlabel('n_qubits') plt.ylabel('$\\partial \\theta$ variance') plt.show() def generate_2qubit_qnn(label): circuit = QuantumCircuit(2) circuit.ry(np.pi / 4.0, 0) circuit.ry(np.pi / 4.0, 1) circuit.barrier() for i in range(2): if label[i] == 'x': circuit.rx(Parameter('theta'+str(i)), i) elif label[i] == 'y': circuit.ry(Parameter('theta'+str(i)), i) elif label[i] == 'z': circuit.rz(Parameter('theta'+str(i)), i) circuit.barrier() # Add CZ ladder. circuit.cz(0, 1) return circuit qc_test = generate_2qubit_qnn('xy') qc_test.draw('mpl') # 期待値の計算 from qiskit import Aer from qiskit.utils import QuantumInstance from qiskit.opflow import CircuitSampler from qiskit.opflow.expectations import AerPauliExpectation def calculate_exp_val(qc, hamiltonian, params): expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(qc) test_expectation = AerPauliExpectation().convert(expectation) quantum_instance = QuantumInstance(Aer.get_backend('qasm_simulator'), shots = 32768) sampler = CircuitSampler(quantum_instance) value_dict = dict(zip(qc.parameters, params)) result = sampler.convert(test_expectation, params=value_dict).eval() return np.real(result) hamiltonian = PauliSumOp.from_list([('X', 1.0)]) X = np.linspace(0, 2*np.pi, 30) Y = np.linspace(0, 2*np.pi, 30) Z = np.array([[calculate_exp_val(qc_test, hamiltonian, [x, y]) for x in X] for y in Y]).reshape(len(Y), len(X)) xx, yy = np.meshgrid(X, Y) fig = plt.figure(figsize=plt.figaspect(0.3)) ax = fig.add_subplot(projection="3d") surf = ax.plot_surface(xx, yy, Z) plt.show() import qiskit.tools.jupyter %qiskit_version_table
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') result = backend.run(qc, shots = 8192).result()
https://github.com/Hayatto9217/Qiskit13
Hayatto9217
#error でインストール必要あり pip install cvxpy #approximate_error and approximate_noise_model from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model import numpy as np from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error from qiskit.quantum_info import Kraus #Kraus 演算子 gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_string="reset") print(results) p = ( 1 + gamma -np.sqrt(1 - gamma)) / 2 q = 0 print("") print("Expected results:") print("P(0) = {}".format(1 -(p+q))) print("P(1) = {}".format(p)) print("P(2) = {}".format(q)) #error operatorsはリスト、辞書またはハードコードされたチャネルを示す文字列として与える gamma = 0.23 k0 = np.array([[1,0],[0,np.sqrt(1-gamma)]]) k1 = np.array([[0, np.sqrt(gamma)], [0,0]]) results =approximate_quantum_error(Kraus([k0, k1]), operator_string="reset") print(results) reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])]) reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])]) reset_kraus = [reset_to_0, reset_to_1] gamma = 0.23 error = amplitude_damping_error(gamma) results = approximate_quantum_error(error, operator_list=reset_kraus) print(results) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test Qiskit's repeat instruction operation.""" import unittest from numpy import pi from qiskit.transpiler import PassManager from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit.test import QiskitTestCase from qiskit.extensions import UnitaryGate from qiskit.circuit.library import SGate, U3Gate, CXGate from qiskit.circuit import Instruction, Measure, Gate from qiskit.transpiler.passes import Unroller from qiskit.circuit.exceptions import CircuitError class TestRepeatInt1Q(QiskitTestCase): """Test gate_q1.repeat() with integer""" def test_standard_1Q_two(self): """Test standard gate.repeat(2) method.""" qr = QuantumRegister(1, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(SGate(), [qr[0]]) expected_circ.append(SGate(), [qr[0]]) expected = expected_circ.to_instruction() result = SGate().repeat(2) self.assertEqual(result.name, "s*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) def test_standard_1Q_one(self): """Test standard gate.repeat(1) method.""" qr = QuantumRegister(1, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(SGate(), [qr[0]]) expected = expected_circ.to_instruction() result = SGate().repeat(1) self.assertEqual(result.name, "s*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) class TestRepeatInt2Q(QiskitTestCase): """Test gate_q2.repeat() with integer""" def test_standard_2Q_two(self): """Test standard 2Q gate.repeat(2) method.""" qr = QuantumRegister(2, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected = expected_circ.to_instruction() result = CXGate().repeat(2) self.assertEqual(result.name, "cx*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) def test_standard_2Q_one(self): """Test standard 2Q gate.repeat(1) method.""" qr = QuantumRegister(2, "qr") expected_circ = QuantumCircuit(qr) expected_circ.append(CXGate(), [qr[0], qr[1]]) expected = expected_circ.to_instruction() result = CXGate().repeat(1) self.assertEqual(result.name, "cx*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Gate) class TestRepeatIntMeasure(QiskitTestCase): """Test Measure.repeat() with integer""" def test_measure_two(self): """Test Measure.repeat(2) method.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") expected_circ = QuantumCircuit(qr, cr) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected = expected_circ.to_instruction() result = Measure().repeat(2) self.assertEqual(result.name, "measure*2") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Instruction) self.assertNotIsInstance(result, Gate) def test_measure_one(self): """Test Measure.repeat(1) method.""" qr = QuantumRegister(1, "qr") cr = ClassicalRegister(1, "cr") expected_circ = QuantumCircuit(qr, cr) expected_circ.append(Measure(), [qr[0]], [cr[0]]) expected = expected_circ.to_instruction() result = Measure().repeat(1) self.assertEqual(result.name, "measure*1") self.assertEqual(result.definition, expected.definition) self.assertIsInstance(result, Instruction) self.assertNotIsInstance(result, Gate) class TestRepeatUnroller(QiskitTestCase): """Test unrolling Gate.repeat""" def test_unroller_two(self): """Test unrolling gate.repeat(2).""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(SGate().repeat(2), [qr[0]]) result = PassManager(Unroller("u3")).run(circuit) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) self.assertEqual(result, expected) def test_unroller_one(self): """Test unrolling gate.repeat(1).""" qr = QuantumRegister(1, "qr") circuit = QuantumCircuit(qr) circuit.append(SGate().repeat(1), [qr[0]]) result = PassManager(Unroller("u3")).run(circuit) expected = QuantumCircuit(qr) expected.append(U3Gate(0, 0, pi / 2), [qr[0]]) self.assertEqual(result, expected) class TestRepeatErrors(QiskitTestCase): """Test when Gate.repeat() should raise.""" def test_unitary_no_int(self): """Test UnitaryGate.repeat(2/3) method. Raises, since n is not int.""" with self.assertRaises(CircuitError) as context: _ = UnitaryGate([[0, 1j], [-1j, 0]]).repeat(2 / 3) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_no_int(self): """Test standard Gate.repeat(2/3) method. Raises, since n is not int.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(2 / 3) self.assertIn("strictly positive integer", str(context.exception)) def test_measure_zero(self): """Test Measure.repeat(0) method. Raises, since n<1""" with self.assertRaises(CircuitError) as context: _ = Measure().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_1Q_zero(self): """Test standard 2Q gate.repeat(0) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_1Q_minus_one(self): """Test standard 2Q gate.repeat(-1) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = SGate().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_2Q_minus_one(self): """Test standard 2Q gate.repeat(-1) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = CXGate().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_measure_minus_one(self): """Test Measure.repeat(-1) method. Raises, since n<1""" with self.assertRaises(CircuitError) as context: _ = Measure().repeat(-1) self.assertIn("strictly positive integer", str(context.exception)) def test_standard_2Q_zero(self): """Test standard 2Q gate.repeat(0) method. Raises, since n<1.""" with self.assertRaises(CircuitError) as context: _ = CXGate().repeat(0) self.assertIn("strictly positive integer", str(context.exception)) if __name__ == "__main__": unittest.main()
https://github.com/Fergus-Hayes/qiskit_tools
Fergus-Hayes
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ import qiskit_tools as qt import numpy as np import matplotlib.pyplot as plt import matplotlib n = 5 xreg = QuantumRegister(n, 'x') circ = QuantumCircuit(xreg) circ = qt.QFT(circ, xreg) circ.draw(output="latex") backend = Aer.get_backend('unitary_simulator') job = execute(circ, backend) result = job.result() unit_mat = np.array(result.get_unitary(circ, decimals=5)) xreg = QuantumRegister(n, 'x') circ = QuantumCircuit(xreg) QFT_gate = qt.QFT(circ, xreg, wrap=True) circ.append(QFT_gate, xreg); circ.draw(output="latex") backend = Aer.get_backend('unitary_simulator') job = execute(circ, backend) result = job.result() unit_mat_wrap = np.array(result.get_unitary(circ, decimals=5)) print(np.sum(np.abs(unit_mat-unit_mat_wrap)**2)) xreg = QuantumRegister(n, 'x') circ = QuantumCircuit(xreg) QFT_gate = qt.QFT(circ, xreg, wrap=True) circ.append(QFT_gate, xreg); iQFT_gate = qt.QFT(circ, xreg, wrap=True, inverse=True) circ.append(iQFT_gate, xreg); circ.draw(output="latex") backend = Aer.get_backend('unitary_simulator') job = execute(circ, backend) result = job.result() unit_mat = np.array(result.get_unitary(circ, decimals=5)) print(np.sum(np.abs(unit_mat - np.eye(2**n))**2))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import BasicAer, transpile, QuantumRegister, ClassicalRegister, QuantumCircuit qr = QuantumRegister(1) cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(0) qc.measure(0, 0) qc.draw('mpl')
https://github.com/qwqmlf/qwgc
qwqmlf
e1=[0.6286408520623922, 0.6289525825569178, 0.5412940012637213, 0.5399199822334315, 0.49756061144296837, 0.5386496534421491, 0.5110201664171742, 0.4785323556159, 0.4879992233852226, 0.49388898393628267, 0.4227883738901349, 0.47665407322957315, 0.49194537115508497, 0.4784480810071889, 0.5067394759922192, 0.4815508310174932, 0.4480058931682556, 0.5191713001759654, 0.5025600642057176, 0.47646282461622946, 0.4620775882390643, 0.5346632906032827, 0.4886131751452513, 0.5068477238076842, 0.4455982578380637, 0.5182468309511442, 0.5194051409981214, 0.5102047452714895, 0.4224846316777891, 0.4369363754766283, 0.47643414498658937, 0.5205363676955092, 0.5191792358482716, 0.43761845483213274, 0.4410680839960249, 0.5124071742830791, 0.5298468258800075, 0.5061098855038695, 0.48256532980818484, 0.4913228065366606, 0.4972612354925298, 0.4978721811109297, 0.4054224929939014, 0.4689590445321974, 0.47656007392483984, 0.4383041892763407, 0.44729094116756796, 0.4355191217281943, 0.39603253338464445] e2=[0.6445889256767168, 0.6535514888883678, 0.650516819829064, 0.5756429937727983, 0.6142765741620072, 0.5835705610683382, 0.5912615393329274, 0.6146589955098392, 0.6122305885006271, 0.615096288252815, 0.5755860024839088, 0.544477825409265, 0.5426761288272395, 0.5468697195293689, 0.564680589127484, 0.5771165305986262, 0.5684633735633585, 0.5680884419879598, 0.5612183060968275, 0.559276953305883, 0.43673818405890585, 0.4411540650165362, 0.4598893136551889, 0.43005624189179076, 0.45188026405543275, 0.47144659911395703, 0.5244689044281716, 0.41605587984112, 0.4556096201350907, 0.46408102111806254, 0.4693180656437913, 0.4268421245136888, 0.4412494204726097, 0.39367845982910615] e3=[0.662780905315912, 0.557526130143123, 0.5584640419156808, 0.5344490232122784, 0.593609022343057, 0.4937605123293818, 0.49679500580245917, 0.6381938409925619, 0.4969497574371143, 0.5490326065330788, 0.6127879707910444, 0.5089002055028583, 0.5504401226212559, 0.6142692709979238, 0.5721990951978606, 0.5018530856716944, 0.48248730823997454, 0.5393567930056656, 0.41791994591838755, 0.5305910774126542, 0.561185300298215, 0.595460105472618, 0.5115104804811111, 0.4495276525911773, 0.43500401066793454, 0.4161182946891324, 0.42475182877301493, 0.5073871378890902, 0.47263913226342963, 0.5149631515053271, 0.598002020559863, 0.41349915170939194, 0.47894825230795474, 0.5622578158963416, 0.5723435539368699, 0.4462502586322237, 0.4093627693814017, 0.5492960278816822, 0.510461265579312, 0.5808173512459651, 0.5597837733339822, 0.5640112157072309, 0.44698468041157, 0.5070970659950728, 0.48072844551751587, 0.5272173485178996, 0.5376622571610833, 0.5735053315795404, 0.4092035721307091, 0.5440903033836487, 0.5011121569382986, 0.5527630387469133, 0.4941897766576979, 0.470192162722345, 0.47418095121567044, 0.48084680432628457, 0.4239088964655666, 0.46940819486126134, 0.4537334210540194, 0.4864943090841813, 0.4687166558652696, 0.49614205816549944, 0.42874339930129546, 0.4479324170994075, 0.40787039901158556, 0.48786153290305956, 0.40963323764273557, 0.4352159063157325, 0.4888689022690961, 0.47162666268555464, 0.44671000444880116, 0.4967216183541344, 0.4012512434083865, 0.46064594635128436, 0.4049871203999046, 0.47170955324407465, 0.48706359188208187, 0.39931433341039707] e4=[0.631157721764274, 0.626369631668824, 0.6435168046798363, 0.5756890928745755, 0.6805477459512386, 0.5457392115779026, 0.6670013898692743, 0.571441632419972, 0.5711226503295723, 0.5043703755755192, 0.5133700170618634, 0.4890578230830625, 0.48377985095373055, 0.5401161872295855, 0.5231897730483787, 0.5224417136122825, 0.48197008488419696, 0.5430021431008605, 0.48585065976376307, 0.4947049468193294, 0.5128519566834271, 0.5111700349984294, 0.5021240973161041, 0.44473351723091004, 0.5387269935977932, 0.5000663192282513, 0.47768543276690545, 0.4804686186752253, 0.5298907808582913, 0.4752329625280757, 0.44839780034261145, 0.4701039454704951, 0.4918735308810149, 0.4728677770754973, 0.4576550851711339, 0.502450222085708, 0.5163739719069254, 0.5213008138551934, 0.4652131556745651, 0.49846654870033724, 0.5137510967641185, 0.5446460345322064, 0.47656732480459313, 0.4516336465509245, 0.5271248472630446, 0.4559450905739887, 0.49738101909129345, 0.5253791961349298, 0.5135150601261252, 0.44079823430873305, 0.5324834268850102, 0.5035609323350201, 0.5182742329465138, 0.5504791701670207, 0.531284676694358, 0.474503007577341, 0.5366327134778044, 0.5011612366374507, 0.5127348471786759, 0.5019671684236049, 0.44189963776688185, 0.46295316911159845, 0.5348905595183858, 0.5269112370262575, 0.5090272490103386, 0.47609522731817105, 0.491370758355211, 0.4135600347595616, 0.4818512230353636, 0.512062390185624, 0.47933046522657563, 0.4934857435730518, 0.4806171151139013, 0.4608250672563326, 0.41268520144053455, 0.4918494520803791, 0.46745210963432454, 0.48071324978066593, 0.5057204328529747, 0.4996037331029218, 0.5413217090462604, 0.4508761552721001, 0.47468589579687376, 0.5642027975890482, 0.41545508292293726, 0.48314552116470366, 0.3997297679560264] e5=[0.6682606140119535, 0.5778862814702397, 0.571284816447605, 0.5732217554886555, 0.576681243443929, 0.5696738503322155, 0.561619312862779, 0.5550863827708744, 0.5376039510952384, 0.5209829601641807, 0.5787276254893167, 0.5649896199922552, 0.5685287073392442, 0.4857622856463922, 0.5184760505457569, 0.5477220163966926, 0.5677443951422002, 0.546248508606815, 0.48857192683520445, 0.4844910863766792, 0.4503989103757882, 0.42963829512934754, 0.36462205360641897] e6=[0.6052190978338532, 0.6168189279264902, 0.5742753886203199, 0.5916751574417829, 0.6499174495644433, 0.5572021688155816, 0.5875677462728359, 0.5882764329669297, 0.42224941745738764, 0.46388965858198655, 0.46894811449133583, 0.5386172982477864, 0.445138792658842, 0.5659195198584153, 0.4280846453576261, 0.5081342706424578, 0.591777700219891, 0.4300014148912618, 0.44029194146143813, 0.4655751631352384, 0.5144871176051569, 0.4302597905571364, 0.47086406673852405, 0.42197278841497904, 0.5666806007720256, 0.4684396130328333, 0.46515501410751087, 0.5854247908909535, 0.46820092150107384, 0.4542753960527196, 0.5136825397873981, 0.42490230795806355, 0.5681653948495334, 0.4982418526291404, 0.5297805255166854, 0.5255641991721257, 0.46604946752584037, 0.42125778606643877, 0.5572774702893012, 0.4857469072821239, 0.46583437875598993, 0.49471480783108884, 0.4960882334145554, 0.464275426856948, 0.4227442887486467, 0.4736773611229292, 0.49004926134414617, 0.49931503682149486, 0.4988062267806028, 0.49268082475005154, 0.4488809454972674, 0.5174211905808321, 0.42898509257033995, 0.41935662991751776, 0.4804755068098414, 0.5517276889852001, 0.6108761441851374, 0.5106562598517737, 0.5707976053860792, 0.5431404102118769, 0.610686118237394, 0.5640443974179815, 0.45304879473737386, 0.5000248112364134, 0.4302734132332332, 0.48721656167805666, 0.5295429629785897, 0.46752394358529753, 0.6145431584915981, 0.50988218844425, 0.49915956989048965, 0.5278205896473646, 0.620852541372503, 0.4237926102741802, 0.42282174131809014, 0.4208938526055965, 0.487461524736154, 0.4753131817344044, 0.4822918616140902, 0.44156923779603763, 0.41871631240516527, 0.46848062331449036, 0.46980532334976366, 0.4709761803139777, 0.3976063267327049] e7=[0.6343177780040268, 0.619599304033062, 0.6242120198917819, 0.6031668480623487, 0.6402201060305929, 0.6231041583237609, 0.6293624185342378, 0.6458794486207945, 0.6827538772276097, 0.6720506480634977, 0.6899104720222323, 0.669870406811187, 0.6512371597807493, 0.6920056581481943, 0.5914131484170293, 0.6232179447484109, 0.5801354474941912, 0.6763159966305158, 0.56685784250218, 0.6637311529482484, 0.5847709695092046, 0.5633961429876598, 0.560108233954407, 0.52832327254978, 0.5283157800182223, 0.49202826266850064, 0.46519065544218025, 0.458531046376133, 0.48787502470038335, 0.4633186448926279, 0.5231878042415427, 0.5232549990667295, 0.45401437184614385, 0.4628743973973229, 0.46133926646432816, 0.4803737244518355, 0.4908663462940766, 0.47381789765142834, 0.46783045177687643, 0.46850374045145793, 0.4681717836248394, 0.4664232598009578, 0.475161204989716, 0.4698246364777594, 0.46279370428901806, 0.47086318835181673, 0.47130924184490053, 0.48004062896072147, 0.5380318909358003, 0.522459093653992, 0.5086512464786042, 0.4940124113230001, 0.5084629644805148, 0.49907221807047564, 0.5060149840853123, 0.5399783523243797, 0.5411928928687932, 0.5080996494638225, 0.49238446160879457, 0.5090379936341687, 0.4514971394109261, 0.5069246117398007, 0.5122056635240435, 0.5183315031961354, 0.5247657452974124, 0.5358356076290758, 0.5328220546034671, 0.5280624432744783, 0.5274743097746725, 0.4975618714767399, 0.49785887670110296, 0.5172247834730592, 0.5139599573220014, 0.5470670151810273, 0.5289727214355933, 0.5291905638247228, 0.4802756837124825, 0.5105438294031261, 0.4966151637696548, 0.4622230385770683, 0.5028894815058449, 0.5204636049862856, 0.46890755144793184, 0.536715875218253, 0.5287019172764743, 0.49212818638466355, 0.4978716350387547, 0.47170291861259944, 0.537535312754868, 0.5285083683899722, 0.5435672463104038, 0.5362293614488318, 0.48409470635156077, 0.45942009997388766, 0.5383618196483511, 0.5066198888774862, 0.5322328585016302, 0.5380757401024095, 0.5307318705952703, 0.49557513053245256, 0.540221765590457, 0.5319199897476646, 0.4425432496155992, 0.5424946438115121, 0.4967073166823288, 0.522464533354847, 0.48612498629064954, 0.5236114041318946, 0.5270520927976627, 0.5375392206453816, 0.49356780560525965, 0.5055856811585618, 0.5432119154861312, 0.5048427773577933, 0.45663313202496075, 0.45486778712936404, 0.44971790073868045, 0.5149780350294215, 0.5083240728859777, 0.44894944420421445, 0.5042145757006968, 0.48460426559739705, 0.4967351042896734, 0.5044661611141689, 0.43596825173934706, 0.5746881408014808, 0.5560117818174737, 0.48581143997140513, 0.4178848063830119, 0.4124531613792558, 0.41128625935257995, 0.5130877411153815, 0.5702506434152459, 0.5191608795298068, 0.40421862548733356, 0.49370921494417785, 0.47747102686452786, 0.4501159143626001, 0.42434966281242287, 0.5694928908915956, 0.4707648838018859, 0.46308786979076044, 0.5674826460753027, 0.41319744667993896, 0.43378581408673195, 0.5479508775304427, 0.42830800640058475, 0.5040567675034388, 0.5102932814824029, 0.5352098084517855, 0.4711907835610163, 0.4135569939522152, 0.5645434706974641, 0.39392153030740434] e8=[0.5913407969216123, 0.5968027045561548, 0.5807132242546393, 0.6045555424432444, 0.5790465745724817, 0.5146519574308367, 0.5386476154031689, 0.5457725039582826, 0.5544308346069118, 0.5435916500554991, 0.5640535382781875, 0.5419371097075426, 0.5441329113708785, 0.5580210026385325, 0.539490557893939, 0.5427861674156166, 0.5546224894721118, 0.5497072631021152, 0.5562272792102939, 0.5191799008595017, 0.5651000039656113, 0.5648645310545621, 0.5442534059819037, 0.5442239567027761, 0.5569325490735977, 0.5570671528470494, 0.5707478917193466, 0.5520669114088126, 0.5560904525558917, 0.536186225898877, 0.567669985618328, 0.5404920496327675, 0.551565557944254, 0.5425809403646311, 0.5557752017202766, 0.5535524873136072, 0.54511963019625, 0.5578999806184163, 0.5430200803197988, 0.5600545158472466, 0.5495828613081718, 0.554367532743426, 0.5492933831513049, 0.5571854750471325, 0.542362247911772, 0.5480834794851243, 0.5262099870228901, 0.48032788936449317, 0.4782151124259759, 0.49380543526049225, 0.5064807825285621, 0.4947974190672037, 0.4937050456318475, 0.49423348593034644, 0.4934758389741058, 0.5088370646749851, 0.4945296999162127, 0.4980231753465324, 0.4966765276873942, 0.4921028081643773, 0.515243532046272, 0.505921332289337, 0.5040872928584723, 0.4934447759396242, 0.5075192382266717, 0.5097597347103172, 0.4742844879083192, 0.5442708524819456, 0.4999348179754739, 0.461829856728611, 0.4705040366840693, 0.4903857708284842, 0.4924730661893619, 0.5134988021147889, 0.4923443029208326, 0.4727467433790539, 0.5225885499341563, 0.47025597023306087, 0.49101448323887475, 0.5430488000164548, 0.46579466193938523, 0.5151981816002086, 0.5429112242988399, 0.5038012282289347, 0.524662590969537, 0.4958443962133329, 0.4577390007625348, 0.5445978798228361, 0.502963558160195, 0.4894387668322627, 0.5440032976839626, 0.4819860916037589, 0.4654945753767531, 0.5152589293772628, 0.49937169712317414, 0.4864882370386736, 0.4507856824420945, 0.46654016177363283, 0.5097213545853928, 0.5404550468061052, 0.5419278186965883, 0.4495814173506067, 0.5153273272247367, 0.45098667264602854, 0.46487961539249983, 0.5234411744015217, 0.5336811462704812, 0.4455712071824399, 0.5365523056268828, 0.5121995525704492, 0.4736035794709903, 0.4473335804233988, 0.4906554048692217, 0.43056341428429684, 0.48750676622735406, 0.46975202791639503, 0.41985163165128453, 0.42365061155579714, 0.46134934441088365, 0.46918184061159246, 0.4432015336494499, 0.4720567531651249, 0.4683567090279011, 0.42967603770654866, 0.4236602081687182, 0.4135466892675132, 0.45815086391436777, 0.3967556123885781] e9=[0.6650768332261353, 0.5839188975158505, 0.5465120888927283, 0.5550907987683472, 0.567639764704636, 0.5085926678869052, 0.5275917470790742, 0.541221468537061, 0.5704477431835283, 0.5448885505140948, 0.5132874077181068, 0.5101701010115886, 0.5310406275923955, 0.5454947990050796, 0.5625857434190685, 0.5159442036807962, 0.5988034093157687, 0.5943047004640979, 0.551393955716915, 0.5233365342078535, 0.4752450983304961, 0.5050691325599479, 0.5235954093501491, 0.4552512305179317, 0.5831833398610338, 0.4731778439749536, 0.5687028273171127, 0.5889767650973098, 0.6064331743720209, 0.440816151178571, 0.448903119770252, 0.44343653750230294, 0.5001408741585447, 0.49118657617553213, 0.467956850971661, 0.4825464062978623, 0.5399849464121956, 0.47311507777648387, 0.4968562934355171, 0.46528754202033956, 0.5009424715411169, 0.4498238228474625, 0.5111711895467378, 0.46172956095965534, 0.48795037350222076, 0.49779900451624604, 0.41431572809038547, 0.5548793389362827, 0.5592370825347295, 0.47399601371736727, 0.5362121023064179, 0.5389262776700031, 0.48785242517507516, 0.48497470394201003, 0.48853758754813664, 0.452062814504457, 0.48515275520764484, 0.5178452313538177, 0.4370453782697105, 0.5143343530357027, 0.4733976407685126, 0.4377874336752083, 0.4225158612975633, 0.4079474669212051, 0.5525408255038543, 0.5199513551123233, 0.4448075381183994, 0.4889228086780745, 0.5444860707172519, 0.5482472432312546, 0.4715690031152096, 0.5860841514937343, 0.48233223561238736, 0.5260061348833885, 0.5273267432013465, 0.5210076022602085, 0.5551322110634548, 0.43377446518549584, 0.5930831673002215, 0.47734011874861937, 0.5223724082746285, 0.46364564600104363, 0.49103227014858114, 0.5078208924726832, 0.5142013832446156, 0.42539199248715004, 0.573131639889572, 0.4196562315745191, 0.5830005193887268, 0.5093072734962075, 0.5148966644389248, 0.4243085194017081, 0.6687310583399344, 0.46364319971652684, 0.49546870554391054, 0.5366528704484373, 0.5198103049962106, 0.5387543007216663, 0.582636034027522, 0.5363235009290618, 0.48327522215619056, 0.541926394132778, 0.5559785869462495, 0.6016761352697166, 0.5371624283020867, 0.5674319149578625, 0.5300704977548727, 0.5547608427601932, 0.4798895004992304, 0.4660034751436862, 0.524066221672807, 0.48431688551826535, 0.4902196506170733, 0.540522649117206, 0.4411247935696716, 0.5057168246330429, 0.6111460839056243, 0.5640026472940163, 0.5352351126005239, 0.43094285001997823, 0.5156524893462651, 0.43502378139170633, 0.4967973382630091, 0.49812092740202074, 0.5167071715045539, 0.5532030008701334, 0.5617041929433927, 0.5188911940730441, 0.5743757589835153, 0.5189928236553618, 0.4380557607907093, 0.5418787229350316, 0.44821135345496893, 0.5310716701733434, 0.5461678917843644, 0.519134739798097, 0.5511987988747173, 0.5773381630359999, 0.5233184425743422, 0.49873902095696, 0.5038420863478974, 0.5758701606630139, 0.5551576247842767, 0.5159133205832385, 0.5433872211476676, 0.5233134104986293, 0.5134074229814606, 0.49244212787856195, 0.5004507865528482, 0.5177767871179224, 0.5125121555910681, 0.5202937524719504, 0.5158894931633854, 0.518259284945597, 0.49879019957162246, 0.5138751753512852, 0.5193327327927922, 0.520053378362557, 0.4996759240244054, 0.5307492186079692, 0.5321791654099939, 0.512370357644313, 0.5051488492226954, 0.5155795339277843, 0.5850895438525353, 0.49333688234630446, 0.5146387574915534, 0.5152962059410358, 0.4916785527685588, 0.5220270697847215, 0.5108044898684504, 0.5225887670058841, 0.5054755192744912, 0.5200111921446353, 0.6186353617217828, 0.5162420347066328, 0.48991362080819656, 0.49458247546427553, 0.5310543800879368, 0.49156501831817023, 0.5209129827957445, 0.5071274285234982, 0.514889685151172, 0.4876652826616725, 0.5176711547960228, 0.501579488061985, 0.5219832016573605, 0.5211421406724956, 0.6102793042683985, 0.5092234796765647, 0.505841113259587, 0.5191361626567386, 0.509224562794439, 0.5095766326615782, 0.502079751965955, 0.5127003003234921, 0.5099580442929842, 0.5107503813960915, 0.5886776852182013, 0.5220688084678431, 0.5280708084273058, 0.5097898025489782, 0.5047902080968601, 0.5005626889772651, 0.596540291245381, 0.4996027048629127, 0.4934349312367303, 0.5409843332211969, 0.5017001340834972, 0.5094353513995228, 0.5170367406199069, 0.530769105638814, 0.5176185091437396, 0.5094759296400767, 0.5193568466416617, 0.4989014112392066, 0.5279480159795279, 0.5029211093859308, 0.5002122616570341, 0.5009459192487525, 0.5161268696467814, 0.5122714761320836, 0.4996834477594777, 0.5003828952897394, 0.5152310440552359, 0.5268164219017487, 0.4977712336603499, 0.5046063697037492, 0.5049611779603863, 0.471537858447829, 0.426280740636709, 0.4063048376824669, 0.4556689882653091, 0.429043458117716, 0.46098399335733065, 0.4783089903682395, 0.4548024144447215, 0.46235139284638144, 0.4855141050547884, 0.4525664843675803, 0.4752750869575304, 0.39445032834640115] e10=[0.6443296151657899, 0.5846714977547917, 0.5672715023778702, 0.5730989175581916, 0.5384647413211849, 0.645025012113611, 0.5818761835357733, 0.5485799801801237, 0.5470440562426591, 0.6848038874433044, 0.5762873974699276, 0.5210875247502859, 0.5840268965938661, 0.5996170002320559, 0.5675317667073588, 0.530705152494162, 0.43856855545184587, 0.5336486205176295, 0.5041957778265646, 0.5331599343293132, 0.4638759111952121, 0.5702342410880747, 0.4641523004965677, 0.49632076472769915, 0.4134526096867966, 0.6395538621427509, 0.5807024881555874, 0.54209316417008, 0.4917106519049478, 0.5746860150482541, 0.4903252002874721, 0.407509811691121, 0.41193636837385816, 0.5197750790448739, 0.5015629445346276, 0.5122720293420352, 0.5089435162867448, 0.479120258101935, 0.9612299362567398, 0.5322306367524896, 0.5408316328291428, 0.5005022853080526, 0.40517976682543727, 0.4738710242232649, 0.5853321607871663, 0.6350323074683683, 0.6220323108115962, 0.5756956691561051, 0.5785318277560356, 0.5495550621945828, 0.6706174816054492, 0.6379782769471595, 0.7984002265429345, 0.5819019958048154, 0.565515984004764, 0.585069528132984, 0.7163610180148806, 0.5907315843404257, 0.5649416080557663, 0.5797493081636891, 0.5929644452090546, 0.7590981885358427, 0.6029722793981109, 0.753962026409037, 0.6612429927176287, 0.5633060981382474, 0.6934616792472114, 0.599324234927781, 0.6621616927728853, 0.5921192185054662, 0.43641299280375273, 0.5122249502827196, 0.409546418406672, 0.42286517450873307, 0.6224070628071293, 0.5023519159195332, 0.5663255019772804, 0.5678506389375136, 0.464807663895237, 0.4602657015700848, 0.41183164602462163, 0.4275251302283884, 0.5801912671155873, 0.5318028256314792, 0.5397358271202957, 0.4531821739411755, 0.44849727924771193, 0.46869408154450576, 0.4549633610858585, 0.4462452859369011, 0.524381047614326, 0.379113122281514] # errors = [e1, e2, e3, e4, e5, e6, e7, e8, e9] errors = [e1, e4, e2] import numpy as np import matplotlib.pyplot as plt import seaborn as sns fig = plt.figure(figsize=(20, 10)) sns.set() plt.xlabel("The number of iterations", fontsize=30) plt.ylabel("Error", fontsize=30) plt.xticks(fontsize=20) plt.yticks(fontsize=20) for ier, er in enumerate(errors): lens = len(er) plt.plot(range(lens), er, label="Error rate in the training process.") # plt.legend(fontsize=20) plt.title("Error tranisition during the training process.", fontsize=30) plt.show() figure = plt.figure(figsize=(10, 10)) plt.boxplot([0.9473684210526315, 0.7894736842105263, 0.8947368421052632, 0.8947368421052632, 0.7894736842105263, 0.8947368421052632, 0.6842105263157895, 0.7368421052631579, 0.8888888888888888, 0.7777777777777778]) plt.title("Result of 10 cross validation", fontsize=20) plt.xlabel("MUTAG experiment", fontsize=20) plt.tick_params(labelsize=14) plt.ylabel("Accuracy", fontsize=20) e3s=[0.6114993145170406, 0.5580492397062562, 0.551723552407508, 0.5484116800260197, 0.5143462721841497, 0.628101523805724, 0.5356993571948219, 0.5266942280148578, 0.5141310873542365, 0.5638829554297106, 0.5496228055765812, 0.6360133689458043, 0.5201943196959011, 0.5481851459170456, 0.5055907141722972, 0.4941810064365272, 0.49340466605586575, 0.4634544459337397, 0.4611237576608274, 0.45213919591606666, 0.4534383746210488, 0.5054618981122072, 0.5165870609303926, 0.45209150635940387, 0.46805949776885464, 0.46960440853671903, 0.467819372880231, 0.4741484070294051, 0.4820804390230995, 0.4717719920228282, 0.5693892077112471, 0.5511274894354884, 0.5033156791541581, 0.5225321272437906, 0.5036599855410948, 0.51329297604302, 0.46424100042295025, 0.48893838154754043, 0.491828375814068, 0.5032194807511081, 0.4509417716028073, 0.4795241201436505, 0.5327343558753157, 0.4878793485411833, 0.4968022638355129, 0.47016307388363854, 0.5139168596002424, 0.44169284992918284, 0.4970774248606773, 0.5008123176407452, 0.5167832520763408, 0.5080038420660207, 0.48930759606351343, 0.513371961439122, 0.43260350311028717, 0.4378572126596461, 0.44645119576095627, 0.43974257495457336, 0.44501068910222275, 0.5046275199007141, 0.5248927422341266, 0.5057426950560957, 0.44435592756939385, 0.5028020254976295, 0.43205956750536756, 0.5095266443472911, 0.43189189288242835, 0.48790827272910336, 0.4615726181458669, 0.4708616965051463, 0.44032234603084713, 0.5179107099016528, 0.447553212974451, 0.4866584089091045, 0.5095162013165208, 0.5159928986646231, 0.5044830183103161, 0.4292861696424971, 0.5314628116720455, 0.43598839835680664, 0.4577829631040909, 0.4873913033076141, 0.4503809344508515, 0.484440023394841, 0.48888482964533436, 0.4920285335157382, 0.5073922782465428, 0.44670952906510897, 0.49607219758491355, 0.4308090376369893, 0.5268897603175041, 0.503559006011311, 0.5325591799558704, 0.5112110616324055, 0.4217329296463216, 0.4287457162429004, 0.5387852988261452, 0.5221160368806622, 0.509923902633072, 0.4411366299303317, 0.43803455040269307, 0.5335288104235335, 0.5272146852894581, 0.4602714866419109, 0.4465667728038471, 0.49895069098977923, 0.44450285295324765, 0.5251224372640607, 0.5278343169334901, 0.4596689338797286, 0.5217282828884132, 0.42935151668392935, 0.46706278369369864, 0.511648879842166, 0.49038583458744545, 0.4240684556714285, 0.5085615349599282, 0.4667558025833304, 0.5225293906551759, 0.4791700925332441, 0.42187666877056285, 0.4444577598049048, 0.43180975598120047, 0.47279635019359195, 0.40434165271953953, 0.4567439578687747, 0.4047810725738134, 0.45285436709795845, 0.5106699339221253, 0.41760528844233397, 0.463230639757571, 0.4583953066465225, 0.47033013236271226, 0.46012210399176057, 0.48140415708781703, 0.4471153121689473, 0.485398357745934, 0.4602156421568477, 0.48008157966420123, 0.4202314394133098, 0.504311984447005, 0.4655888166277228, 0.43114982313289985, 0.46496997393407696, 0.46041725990525456, 0.4662905080385762, 0.43186752985533855, 0.5113262759807295, 0.4719745720033306, 0.47791479563461675, 0.46799098060250977, 0.40620578584396677, 0.42314041607019615, 0.4162314065076259, 0.41579571768218204, 0.43814693535584737, 0.47413006835703997, 0.4974571568255316, 0.4935654224734384, 0.48136060672275627, 0.4550978367425495, 0.49706958170713433, 0.44513768595224995, 0.4253361121582329, 0.44381941515869333, 0.4761198169714065, 0.47667447892671105, 0.48046363042033574, 0.5199316709111657, 0.48927857372412814, 0.4808599995841265, 0.49799963296315697, 0.4492087033317719, 0.46986478238223167, 0.506700053418057, 0.4987938011003559, 0.4544414206143903, 0.5377744716063275, 0.5140073014745788, 0.42192876338556845, 0.4486045885520557, 0.42644917513144487, 0.4116325393736495, 0.4322134994562949, 0.476302541798784, 0.48675134068911835, 0.41824997807779385, 0.426746519901415, 0.46480259963728177, 0.5214455692010816, 0.41548303889992255, 0.42933136120094717, 0.4838030541852354, 0.494936691128753, 0.49186212498168014, 0.4217631685828114, 0.45602912462583534, 0.5125161938121239, 0.4457479372848052, 0.46618893650081916, 0.48881100807439615, 0.43768350802896466, 0.4739599720363637, 0.4955716129352989, 0.4804280162630706, 0.48163906724030736, 0.4143071427832678, 0.48475848400436833, 0.44899270858594775, 0.4838938111763643, 0.4848282167826762, 0.4838980545767503, 0.4866190119509327, 0.4717631934896995, 0.5165489359356199, 0.48360361419074716, 0.4804091649028527, 0.5097297759525212, 0.4571519002443824, 0.4452585896454598, 0.4414109845063244, 0.4235666003629125, 0.5153951286649423, 0.4883078008311837, 0.4346874565124854, 0.5005732966822127, 0.417852787993552, 0.4145857127347467, 0.48591110524336795, 0.4345903953415311, 0.41977222100784434, 0.5371283981310165, 0.47305277802964524, 0.44317952697867435, 0.4036964309526516, 0.4581214250541329, 0.5463341411652219, 0.46045127199889063, 0.4501169516101683, 0.4179825918218954, 0.49900783694877715, 0.4892906123586632, 0.42840660739898967, 0.47162708436149237, 0.4345798849491902, 0.47562520954776094, 0.4340927110566402, 0.4313336037367724, 0.4129143693247415, 0.5135537564781154, 0.47204003930970917, 0.4210640712529034, 0.4245605754426493, 0.4743745984824515, 0.48794937883439804, 0.4180700741879826, 0.4912515867736354, 0.4903159358869692, 0.49091273489139003, 0.4327263671175196, 0.5112962766853835, 0.418128526296058, 0.4832865396091334, 0.48082133074596606, 0.4832623410972604, 0.41270459153098055, 0.42109973525643424, 0.4998801209675613, 0.46762469008572893, 0.4799947903769364, 0.4736394640658181, 0.47211493605277344, 0.5287411401320841, 0.5200724040148723, 0.5066205296433474, 0.5127730183590961, 0.44369916589791547, 0.48456698587240804, 0.5051576392479146, 0.5081283632369991, 0.4193870952105006, 0.43548458423797165, 0.5146117075667941, 0.6496553944513833, 0.4143930795231045, 0.4289819520927289, 0.5080801555292406, 0.5131411994688787, 0.43696130146368667, 0.5427646826654766, 0.45345802627109194, 0.5433482910534887, 0.5143319170186181, 0.5097298427495505, 0.5136637813655547, 0.5106507420608952, 0.5548887569702587, 0.7065321055530301, 0.5168715814597589, 0.41794267534812685, 0.43090336510087845, 0.7212155749399769, 0.6165544559697002, 0.46033737106777256, 0.5089387495523169, 0.5253975539361965, 0.5115566116956278, 0.42320202401689294, 0.5246174570570632, 0.6281310330202612, 0.4751536510310882, 0.5950102991564058, 0.4978649425068354, 0.46610446928565485, 0.544534190394418, 0.6016255287956038, 0.5631491919128527, 0.6833236214330077, 0.4110880226407702, 0.4722339929634415, 0.5323749024552461, 0.4891842913332914, 0.6762690545068252, 0.41950833442907715, 0.4876659176727193, 0.6046630614307239, 0.4928000945510993, 0.553452844399436, 0.4511162775004234, 0.47151456349690807, 0.4909478739757076, 0.4918155366451409, 0.4431381515130087, 0.48011543632848297, 0.6012506969150045, 0.4602080508155012, 0.4857964362690456, 0.554271610426304, 0.41699549081779524, 0.4613389595659844, 0.413520621478622, 0.5796217614630786, 0.4849478885457273, 0.405352719966207, 0.4885767886098703, 0.5219683081108104, 0.4626909895475748, 0.5026622317544714, 0.5683235089403735, 0.40180703773062326, 0.41191760583198633, 0.39797130773487593] plt.plot(range(len(e3s)), e3s) import numpy as np from sklearn.decomposition import PCA predata = [] with open('../result.txt') as f: lines = f.readlines() for l in lines: temp = [] for lsa in l[1:-2].split(","): temp.append(complex(lsa)) predata.append(temp) print(predata) X = np.array(predata, dtype=complex) reals = [] imags = [] for x in X: temp_re = [] temp_im = [] for ele in x: print(ele.real) temp_re.append(ele.real) temp_im.append(ele.imag) reals.append(temp_re) imags.append(temp_im) labels = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, -1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, 1, -1, 1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, -1, -1, -1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1] import matplotlib.pyplot as plt import seaborn as sns pca = PCA(n_components=2) reals = pca.fit_transform(reals) # class 1 group1 = [i for i, j in zip(reals, labels) if j==1] g1_x, g1_y = [i[0] for i in group1], [i[1] for i in group1] # class -1 group2 = [i for i, j in zip(reals, labels) if j==-1] g2_x, g2_y = [i[0] for i in group2], [i[1] for i in group2] sns.set() fig = plt.figure(figsize=(15, 10)) plt.scatter(g1_x, g1_y, c="red") plt.scatter(g2_x, g2_y, c="blue") pca = PCA(n_components=2) imags = pca.fit_transform(imags) # class 1 group1 = [i for i, j in zip(imags, labels) if j==1] g1_x, g1_y = [i[0] for i in group1], [i[1] for i in group1] # class -1 group2 = [i for i, j in zip(imags, labels) if j==-1] g2_x, g2_y = [i[0] for i in group2], [i[1] for i in group2] sns.set() fig = plt.figure(figsize=(15, 10)) plt.title("Feature Space before learning") plt.scatter(g1_x, g1_y, c="red") plt.scatter(g2_x, g2_y, c="blue") import numpy as np from sklearn.decomposition import PCA predata = [] with open('../result2.txt') as f: lines = f.readlines() for l in lines: temp = [] for lsa in l[1:-2].split(","): temp.append(complex(lsa)) predata.append(temp) print(predata) X = np.array(predata, dtype=complex) reals = [] imags = [] for x in X: temp_re = [] temp_im = [] for ele in x: print(ele.real) temp_re.append(ele.real) temp_im.append(ele.imag) reals.append(temp_re) imags.append(temp_im) pca = PCA(n_components=2) reals = pca.fit_transform(reals) # class 1 group1 = [i for i, j in zip(reals, labels) if j==1] g1_x, g1_y = [i[0] for i in group1], [i[1] for i in group1] # class -1 group2 = [i for i, j in zip(reals, labels) if j==-1] g2_x, g2_y = [i[0] for i in group2], [i[1] for i in group2] sns.set() fig = plt.figure(figsize=(15, 10)) plt.scatter(g1_x, g1_y, c="red") plt.scatter(g2_x, g2_y, c="blue") pca = PCA(n_components=2) imags = pca.fit_transform(imags) # class 1 group1 = [i for i, j in zip(imags, labels) if j==1] g1_x, g1_y = [i[0] for i in group1], [i[1] for i in group1] # class -1 group2 = [i for i, j in zip(imags, labels) if j==-1] g2_x, g2_y = [i[0] for i in group2], [i[1] for i in group2] sns.set() fig = plt.figure(figsize=(15, 10)) plt.title("Feature Space before learning") plt.scatter(g1_x, g1_y, c="red") plt.scatter(g2_x, g2_y, c="blue")
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
#!/usr/bin/env python # coding: utf-8 # In[1]: from qiskit import QuantumCircuit, transpile from qiskit_aer import AerSimulator from qiskit.visualization import plot_histogram # Use Aer's AerSimulator simulator = AerSimulator() # Create a Quantum Circuit acting on the q register circuit = QuantumCircuit(2, 2) # Add a H gate on qubit 0 circuit.h(0) # Add a CX (CNOT) gate on control qubit 0 and target qubit 1 circuit.cx(0, 1) # Map the quantum measurement to the classical bits circuit.measure([0, 1], [0, 1]) # Compile the circuit for the support instruction set (basis_gates) # and topology (coupling_map) of the backend compiled_circuit = transpile(circuit, simulator) # Execute the circuit on the aer simulator job = simulator.run(compiled_circuit, shots=1000) # Grab results from the job result = job.result() # Returns counts counts = result.get_counts(compiled_circuit) print("\nTotal count for 00 and 11 are:", counts) # Draw the circuit circuit.draw() # In[2]: # Plot a histogram plot_histogram(counts) # In[3]: circuit.draw() # In[4]: simulator = AerSimulator() compiled_circuit = transpile(circuit, simulator) job = simulator.run(compiled_circuit, shots=1000) result = job.result() counts = result.get_counts(circuit) print("\nTotal count for 00 and 11 are:",counts) # In[5]: plot_histogram(counts)
https://github.com/carstenblank/dc-qiskit-qml
carstenblank
# -*- coding: utf-8 -*- # Copyright 2018, Carsten Blank. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. import logging import sys import unittest from typing import Dict import numpy as np import qiskit from qiskit import QuantumCircuit, ClassicalRegister from qiskit.providers import BackendV2 from scipy import sparse from dc_qiskit_qml.distance_based.hadamard.state import QmlBinaryDataStateCircuitBuilder from dc_qiskit_qml.distance_based.hadamard.state.cnot import CCXMottonen, CCXToffoli from dc_qiskit_qml.encoding_maps import EncodingMap from dc_qiskit_qml.encoding_maps import FixedLengthQubitEncoding logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stderr) stream_handler.setFormatter(logging._defaultFormatter) logger.addHandler(stream_handler) def extract_gate_info(qc, index): # type: (QuantumCircuit, int) -> list return [qc.data[index][0].name, qc.data[index][0].params, str(qc.data[index][1][-1])] class QubitEncodingClassifierStateCircuitTests(unittest.TestCase): def test_one(self): encoding_map = FixedLengthQubitEncoding(4, 4) X_train = [ [4.4, -9.53], [18.42, 1.0] ] y_train = [0, 1] input = [2.043, 13.84] X_train_in_encoded_space = [encoding_map.map(x) for x in X_train] X_train_in_encoded_space_qubit_notation = [["{:b}".format(i).zfill(2 * 9) for i, _ in elem.keys()] for elem in X_train_in_encoded_space] input_in_feature_space = encoding_map.map(input) input_in_feature_space_qubit_notation = ["{:b}".format(i).zfill(2 * 9) for i, _ in input_in_feature_space.keys()] logger.info("Training samples in encoded space: {}".format(X_train_in_encoded_space_qubit_notation)) logger.info("Input sample in encoded space: {}".format(input_in_feature_space_qubit_notation)) circuit = QmlBinaryDataStateCircuitBuilder(CCXMottonen()) qc = circuit.build_circuit('test', X_train=X_train_in_encoded_space, y_train=y_train, X_input=input_in_feature_space) self.assertIsNotNone(qc) self.assertIsNotNone(qc.data) self.assertEqual(30, len(qc.data)) self.assertListEqual(["h"], [qc.data[0][0].name]) self.assertListEqual(["h"], [qc.data[1][0].name]) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 2)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 3)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 4)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 8)"], extract_gate_info(qc, 5)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 10)"], extract_gate_info(qc, 6)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 11)"], extract_gate_info(qc, 7)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(18, 'f^S'), 15)"], extract_gate_info(qc, 8)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 0)"], extract_gate_info(qc, 9)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 2)"], extract_gate_info(qc, 10)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 11)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 12)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 6)"], extract_gate_info(qc, 13)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 14)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(18, 'f^S'), 14)"], extract_gate_info(qc, 15)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 16)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 10)"], extract_gate_info(qc, 17)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 11)"], extract_gate_info(qc, 18)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 13)"], extract_gate_info(qc, 19)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(18, 'f^S'), 16)"], extract_gate_info(qc, 20)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 21)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 0)"], extract_gate_info(qc, 22)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 2)"], extract_gate_info(qc, 23)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 24)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 25)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 6)"], extract_gate_info(qc, 26)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 27)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(18, 'f^S'), 14)"], extract_gate_info(qc, 28)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 29)) def test_two(self): encoding_map = FixedLengthQubitEncoding(2, 2) X_train = [ [4.4, -9.53], [18.42, 1.0] ] y_train = [0, 1] input = [2.043, 13.84] X_train_in_encoded_space = [encoding_map.map(x) for x in X_train] X_train_in_encoded_space_qubit_notation = [["{:b}".format(i).zfill(2*5) for i, _ in elem.keys()] for elem in X_train_in_encoded_space] input_in_feature_space = encoding_map.map(input) input_in_feature_space_qubit_notation = ["{:b}".format(i).zfill(2*5) for i, _ in input_in_feature_space.keys()] logger.info("Training samples in encoded space: {}".format(X_train_in_encoded_space_qubit_notation)) logger.info("Input sample in encoded space: {}".format(input_in_feature_space_qubit_notation)) circuit = QmlBinaryDataStateCircuitBuilder(CCXMottonen()) qc = circuit.build_circuit('test', X_train=X_train_in_encoded_space, y_train=y_train, X_input=input_in_feature_space) self.assertIsNotNone(qc) self.assertIsNotNone(qc.data) self.assertEqual(len(qc.data), 22) self.assertListEqual(["h"], [qc.data[0][0].name]) self.assertListEqual(["h"], [qc.data[1][0].name]) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 2)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 3)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 4)"], extract_gate_info(qc, 4)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 5)"], extract_gate_info(qc, 5)) self.assertListEqual(["ccx_uni_rot", [0], "Qubit(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 6)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 0)"], extract_gate_info(qc, 7)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 8)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 9)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 10)) self.assertListEqual(["ccx_uni_rot", [1], "Qubit(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 11)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 12)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(10, 'f^S'), 5)"], extract_gate_info(qc, 13)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 14)) self.assertListEqual(["ccx_uni_rot", [2], "Qubit(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 15)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 0)"], extract_gate_info(qc, 16)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 17)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 18)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 19)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 20)) self.assertListEqual(["ccx_uni_rot", [3], "Qubit(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 21)) qregs = qc.qregs cregs = [ClassicalRegister(qr.size, 'c' + qr.name) for qr in qregs] qc2 = QuantumCircuit(*qregs, *cregs, name='test2') qc2.data = qc.data for i in range(len(qregs)): qc2.measure(qregs[i], cregs[i]) execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2 job = qiskit.execute(qc2, execution_backend, shots=8192) counts = job.result().get_counts() # type: dict self.assertListEqual(sorted(counts.keys()), sorted(['0 0100111010 0 0', '0 0100001111 0 1', '1 0100100100 1 0', '1 0100001111 1 1'])) def test_three(self): encoding_map = FixedLengthQubitEncoding(4, 4) X_train = [ [4.4, -9.53], [18.42, 1.0] ] y_train = [0, 1] input = [2.043, 13.84] X_train_in_encoded_space = [encoding_map.map(x) for x in X_train] X_train_in_encoded_space_qubit_notation = [["{:b}".format(i).zfill(2 * 9) for i, _ in elem.keys()] for elem in X_train_in_encoded_space] input_in_feature_space = encoding_map.map(input) input_in_feature_space_qubit_notation = ["{:b}".format(i).zfill(2 * 9) for i, _ in input_in_feature_space.keys()] logger.info("Training samples in encoded space: {}".format(X_train_in_encoded_space_qubit_notation)) logger.info("Input sample in encoded space: {}".format(input_in_feature_space_qubit_notation)) circuit = QmlBinaryDataStateCircuitBuilder(CCXToffoli()) qc = circuit.build_circuit('test', X_train=X_train_in_encoded_space, y_train=y_train, X_input=input_in_feature_space) self.assertIsNotNone(qc) self.assertIsNotNone(qc.data) # TODO: adjust ASAP # self.assertEqual(36, len(qc.data)) # # self.assertListEqual(["h"], [qc.data[0].name]) # self.assertListEqual(["h"], [qc.data[1].name]) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 2)) # self.assertListEqual(["x", [], "(QuantumRegister(1, 'i'), 0)"], extract_gate_info(qc, 3)) # # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 4)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 5)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 6)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 8)"], extract_gate_info(qc, 7)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 10)"], extract_gate_info(qc, 8)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 11)"], extract_gate_info(qc, 9)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 15)"], extract_gate_info(qc, 10)) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 11)) # # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 0)"], extract_gate_info(qc, 12)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 2)"], extract_gate_info(qc, 13)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 14)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 15)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 6)"], extract_gate_info(qc, 16)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 17)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 14)"], extract_gate_info(qc, 18)) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'i'), 0)"], extract_gate_info(qc, 19)) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 20)) # # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 21)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 10)"], extract_gate_info(qc, 22)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 11)"], extract_gate_info(qc, 23)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 13)"], extract_gate_info(qc, 24)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 16)"], extract_gate_info(qc, 25)) # self.assertListEqual(["ccx", [], "(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 26)) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 27)) # # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 0)"], extract_gate_info(qc, 28)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 2)"], extract_gate_info(qc, 29)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 3)"], extract_gate_info(qc, 30)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 4)"], extract_gate_info(qc, 31)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 6)"], extract_gate_info(qc, 32)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 7)"], extract_gate_info(qc, 33)) # self.assertListEqual(["ccx", [], "(QuantumRegister(18, 'f^S'), 14)"], extract_gate_info(qc, 34)) # self.assertListEqual(["ccx", [], "(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 35)) def test_four(self): encoding_map = FixedLengthQubitEncoding(2, 2) X_train = [ [4.4, -9.53], [18.42, 1.0] ] y_train = [0, 1] input = [2.043, 13.84] X_train_in_encoded_space = [encoding_map.map(x) for x in X_train] X_train_in_encoded_space_qubit_notation = [["{:b}".format(i).zfill(2*5) for i, _ in elem.keys()] for elem in X_train_in_encoded_space] input_in_encoded_space = encoding_map.map(input) input_in_encoded_space_qubit_notation = ["{:b}".format(i).zfill(2*5) for i, _ in input_in_encoded_space.keys()] logger.info("Training samples in encoded space: {}".format(X_train_in_encoded_space_qubit_notation)) logger.info("Input sample in encoded space: {}".format(input_in_encoded_space_qubit_notation)) circuit = QmlBinaryDataStateCircuitBuilder(CCXToffoli()) qc = circuit.build_circuit('test', X_train=X_train_in_encoded_space, y_train=y_train, X_input=input_in_encoded_space) self.assertIsNotNone(qc) self.assertIsNotNone(qc.data) # TODO: adjust ASAP # self.assertEqual(28, len(qc.data)) # # self.assertListEqual(["h"], [qc.data[0].name]) # self.assertListEqual(["h"], [qc.data[1].name]) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 2)) # self.assertListEqual(["x", [], "(QuantumRegister(1, 'i'), 0)"], extract_gate_info(qc, 3)) # # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 4)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 5)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 4)"], extract_gate_info(qc, 6)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 5)"], extract_gate_info(qc, 7)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 8)) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 9)) # # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 0)"], extract_gate_info(qc, 10)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 11)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 12)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 13)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 14)) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'i'), 0)"], extract_gate_info(qc, 15)) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 16)) # # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 17)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 5)"], extract_gate_info(qc, 18)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 19)) # self.assertListEqual(["ccx", [], "(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 20)) # # self.assertListEqual(["x", [], "(QuantumRegister(1, 'a'), 0)"], extract_gate_info(qc, 21)) # # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 0)"], extract_gate_info(qc, 22)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 1)"], extract_gate_info(qc, 23)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 2)"], extract_gate_info(qc, 24)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 3)"], extract_gate_info(qc, 25)) # self.assertListEqual(["ccx", [], "(QuantumRegister(10, 'f^S'), 8)"], extract_gate_info(qc, 26)) # # self.assertListEqual(["ccx", [], "(QuantumRegister(1, 'l^q'), 0)"], extract_gate_info(qc, 27)) cregs = [ClassicalRegister(qr.size, 'c' + qr.name) for qr in qc.qregs] qc2 = QuantumCircuit(*qc.qregs, *cregs, name='test2') qc2.data = qc.data for i in range(len(qc.qregs)): qc2.measure(qc.qregs[i], cregs[i]) execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2 job = qiskit.execute([qc2], execution_backend, shots=8192) counts = job.result().get_counts() # type: dict self.assertListEqual(sorted(['0 0100111010 0 0', '0 0100001111 0 1', '1 0100100100 1 0', '1 0100001111 1 1']), sorted(counts.keys())) def test_five(self): X_train = np.asarray([[1.0, 1.0], [-1.0, 1.0], [-1.0, -1.0], [1.0, -1.0]]) y_train = [0, 1, 0, 1] X_test = np.asarray([[0.2, 0.4], [0.4, -0.8]]) y_test = [0, 1] class MyEncodingMap(EncodingMap): def map(self, input_vector: list) -> sparse.dok_matrix: result = sparse.dok_matrix((4, 1)) index = 0 if input_vector[0] > 0 and input_vector[1] > 0: index = 0 if input_vector[0] < 0 and input_vector[1] > 0: index = 1 if input_vector[0] < 0 and input_vector[1] < 0: index = 2 if input_vector[0] > 0 and input_vector[1] < 0: index = 3 result[index, 0] = 1.0 return result initial_state_builder = QmlBinaryDataStateCircuitBuilder(CCXToffoli()) encoding_map = MyEncodingMap() X_train_in_encoded_space = [encoding_map.map(s) for s in X_train] X_test_in_encoded_space = [encoding_map.map(s) for s in X_test] qc = initial_state_builder.build_circuit('test', X_train_in_encoded_space, y_train, X_test_in_encoded_space[0]) self.assertIsNotNone(qc) self.assertIsNotNone(qc.data) # self.assertEqual(len(qc.data), 28) # self.assertListEqual(["h"], [qc.data[0].name]) # self.assertListEqual(["h"], [qc.data[1].name]) qregs = qc.qregs cregs = [ClassicalRegister(qr.size, 'c_' + qr.name) for qr in qregs] qc2 = QuantumCircuit(*qregs, *cregs, name='test2') qc2.data = qc.data for i in range(len(qregs)): qc2.measure(qregs[i], cregs[i]) execution_backend = qiskit.Aer.get_backend('qasm_simulator') # type: BackendV2 job = qiskit.execute(qc2, execution_backend, shots=8192) # type: AerJob counts = job.result().get_counts() # type: Dict[str, int] self.assertListEqual( sorted([ '00 0 00 00 0', '00 0 00 00 1', '00 1 01 01 0', '00 1 00 01 1', '00 0 10 10 0', '00 0 00 10 1', '00 1 11 11 0', '00 1 00 11 1' ]), sorted(counts.keys()) )
https://github.com/epelaaez/QuantumLibrary
epelaaez
from qiskit import QuantumCircuit import numpy as np def sim_z(t, qc, qubits): """ Add gates to simulate a Pauli Z string exponential Parameters: t: float Time parameter to simulate for qc: QuantumCircuit Circuit to append gates to qubits: array Array indicating qubits indeces (in order) to append the gates to """ for i in range(len(qubits) - 1): qc.cx(qubits[i], qubits[i + 1]) qc.rz(-2 * t, qubits[-1]) for i in range(len(qubits) - 1, 0, -1): qc.cx(qubits[i - 1], qubits[i]) qc = QuantumCircuit(3) sim_z(np.pi, qc, [0, 1, 2]) qc.draw() def sim_pauli(arr, t, qc, qubits): """ Append gates to simulate any Pauli string Parameters: arr: array Array encoding the Pauli string t: float Time parameter to simulate for qc: QuantumCircuit Circuit to append gates to qubits: array Array indicating qubits indeces (in order) to append the gates to """ new_arr = [] new_qub = [] for idx in range(len(arr)): if arr[idx] != 'I': new_arr.append(arr[idx]) new_qub.append(qubits[idx]) h_y = 1 / np.sqrt(2) * np.array([[1, -1j], [1j, -1]]) for i in range(len(new_arr)): if new_arr[i] == 'X': qc.h(new_qub[i]) elif new_arr[i] == 'Y': qc.unitary(h_y, [new_qub[i]], r'$H_y$') sim_z(t, qc, new_qub) for i in range(len(new_arr)): if new_arr[i] == 'X': qc.h(new_qub[i]) elif new_arr[i] == 'Y': qc.unitary(h_y, [new_qub[i]], r'$H_y$') def sim_ham(hamiltonian, t, qc, qubits, trotter=1): """ Simulates Hamiltonian given as Pauli string Parameters: hamiltonian: dict Dictionary encoding the hamiltonian with each Pauli product as a key with the coefficient as value t: float Time parameter to simulate for qc: QuantumCircuit Circuit to append gates to qubits: array Array indicating qubits indeces (in order) to append the gates to """ temp = QuantumCircuit(len(qubits)) delta_t = t / trotter for pauli in hamiltonian: sim_pauli(pauli, hamiltonian[pauli] * delta_t, temp, range(len(qubits))) for i in range(trotter): qc.compose(temp, qubits, inplace=True) qc = QuantumCircuit(3) sim_ham({"XZY": 2, "ZXX": 5, "YXZ": 2}, 1 / (2 * np.pi), qc, [0, 1, 2], trotter=1) qc = qc.reverse_bits() # reverse because of Qiskit's endianness qc.draw() from qiskit import Aer, execute from sympy import Matrix qc = QuantumCircuit(3) sim_ham({"XZY": 2, "ZXX": 5, "YXZ": 2}, 1 / (2 * np.pi), qc, [0, 1, 2], trotter=50) qc = qc.reverse_bits() backend = Aer.get_backend('statevector_simulator') result = execute(qc, backend).result() vec = result.get_statevector() vec = vec / vec[0] # global phase qvec = vec / np.linalg.norm(vec) # normalize Matrix(np.round(qvec, 5)) import scipy # Start with |0> state start = np.zeros(2 ** 3) start[0] = 1 # Get the matrix corresponding to some Pauli product # This function can be optimized, but it is left as it # is for clarity purposes def get_pauli(string): init = string[0] string = string[1:] if init == 'X': out = np.array([[0, 1], [1, 0]]) elif init == 'Z': out = np.array([[1, 0], [0, -1]]) elif init == 'Y': out = np.array([[0, -1j], [1j, 0]]) else: out = np.eye(2) for p in string: if p == 'X': out = np.kron(out, np.array([[0, 1], [1, 0]])) elif p == 'Z': out = np.kron(out, np.array([[1, 0], [0, -1]])) elif p == 'Y': out = np.kron(out, np.array([[0, -1j], [1j, 0]])) else: out = np.kron(out, np.eye(2)) return out # Hamiltonian is calculated from the Pauli decomposition decomp = {"XZY": 2, "ZXX": 5, "YXZ": 2} H = np.zeros((2 ** 3, 2 ** 3)) H = H.astype('complex128') for pauli in decomp: H += decomp[pauli] * get_pauli(pauli) # Hamiltonian is exponentiated and we multiply the starting # vector by it to get our result simul = scipy.linalg.expm(1j * H * (1 / (2 * np.pi))) vec = simul @ start vec = vec / vec[0] # global phase cvec = vec / np.linalg.norm(vec) # normalize Matrix(np.round(cvec, 5)) from qiskit.quantum_info import state_fidelity state_fidelity(qvec, cvec)
https://github.com/dimple12M/Qiskit-Certification-Guide
dimple12M
from qiskit import BasicAer from qiskit.providers.basicaer import BasicAerProvider backend_list=BasicAer.backends() backend_list for name in backend_list: print(name) backend=BasicAer.get_backend('qasm_simulator') backend backend.name() backend=BasicAer.backends(name='qasm_simulator') backend provider=BasicAerProvider() backend_list=provider.backends() backend_list for name in backend_list: print(name) backend=provider.backends(name='qasm_simulator') backend backend=provider.get_backend('qasm_simulator') backend backend.name() backend=BasicAer.backends(name='qasm_simulator') backend backend=BasicAer.get_backend('qasm_simulator') backend backend.name() provider=BasicAerProvider() backend=provider.backends(name='qasm_simulator') backend backend=provider.get_backend('qasm_simulator') backend backend.name() from qiskit.providers.basicaer import QasmSimulatorPy backend=QasmSimulatorPy() backend backend.name()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit ghz = QuantumCircuit(5) ghz.h(0) ghz.cx(0,range(1,5)) ghz.draw(output='mpl')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import pulse from qiskit.providers.fake_provider import FakeArmonk backend = FakeArmonk() with pulse.build(backend) as drive_sched: d0 = pulse.drive_channel(0) a0 = pulse.acquire_channel(0) pulse.play(pulse.library.Constant(10, 1.0), d0) pulse.delay(20, d0) pulse.shift_phase(3.14/2, d0) pulse.set_phase(3.14, d0) pulse.shift_frequency(1e7, d0) pulse.set_frequency(5e9, d0) with pulse.build() as temp_sched: pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0) pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0) pulse.call(temp_sched) pulse.acquire(30, a0, pulse.MemorySlot(0)) drive_sched.draw()
https://github.com/microsoft/qiskit-qir
microsoft
## # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ## from io import UnsupportedOperation import logging from abc import ABCMeta, abstractmethod from qiskit import ClassicalRegister, QuantumRegister from qiskit.circuit import Qubit, Clbit from qiskit.circuit.instruction import Instruction from qiskit.circuit.bit import Bit import pyqir.qis as qis import pyqir.rt as rt import pyqir from pyqir import ( BasicBlock, Builder, Constant, Function, FunctionType, IntType, Linkage, Module, PointerType, const, entry_point, qubit_id, ) from typing import List, Union from qiskit_qir.capability import ( Capability, ConditionalBranchingOnResultError, QubitUseAfterMeasurementError, ) from qiskit_qir.elements import QiskitModule _log = logging.getLogger(name=__name__) # This list cannot change as existing clients hardcoded to it # when it wasn't designed to be externally used. # To work around this we are using an additional list to replace # this list which contains the instructions that we can process. # This following three variables can be removed in a future # release after dependency version restrictions have been applied. SUPPORTED_INSTRUCTIONS = [ "barrier", "delay", "measure", "m", "cx", "cz", "h", "reset", "rx", "ry", "rz", "s", "sdg", "t", "tdg", "x", "y", "z", "id", ] _QUANTUM_INSTRUCTIONS = [ "barrier", "ccx", "cx", "cz", "h", "id", "m", "measure", "reset", "rx", "ry", "rz", "s", "sdg", "swap", "t", "tdg", "x", "y", "z", ] _NOOP_INSTRUCTIONS = ["delay"] _SUPPORTED_INSTRUCTIONS = _QUANTUM_INSTRUCTIONS + _NOOP_INSTRUCTIONS class QuantumCircuitElementVisitor(metaclass=ABCMeta): @abstractmethod def visit_register(self, register): raise NotImplementedError @abstractmethod def visit_instruction(self, instruction): raise NotImplementedError class BasicQisVisitor(QuantumCircuitElementVisitor): def __init__(self, profile: str = "AdaptiveExecution", **kwargs): self._module = None self._qiskitModule: QiskitModule | None = None self._builder = None self._entry_point = None self._qubit_labels = {} self._clbit_labels = {} self._profile = profile self._capabilities = self._map_profile_to_capabilities(profile) self._measured_qubits = {} self._emit_barrier_calls = kwargs.get("emit_barrier_calls", False) self._record_output = kwargs.get("record_output", True) def visit_qiskit_module(self, module: QiskitModule): _log.debug( f"Visiting Qiskit module '{module.name}' ({module.num_qubits}, {module.num_clbits})" ) self._module = module.module self._qiskitModule = module context = self._module.context entry = entry_point( self._module, module.name, module.num_qubits, module.num_clbits ) self._entry_point = entry.name self._builder = Builder(context) self._builder.insert_at_end(BasicBlock(context, "entry", entry)) i8p = PointerType(IntType(context, 8)) nullptr = Constant.null(i8p) rt.initialize(self._builder, nullptr) @property def entry_point(self) -> str: return self._entry_point def finalize(self): self._builder.ret(None) def record_output(self, module: QiskitModule): if self._record_output == False: return i8p = PointerType(IntType(self._module.context, 8)) # qiskit inverts the ordering of the results within each register # but keeps the overall register ordering # here we logically loop from n-1 to 0, decrementing in order to # invert the register output. The second parameter is an exclusive # range so we need to go to -1 instead of 0 logical_id_base = 0 for size in module.reg_sizes: rt.array_record_output( self._builder, const(IntType(self._module.context, 64), size), Constant.null(i8p), ) for index in range(size - 1, -1, -1): result_ref = pyqir.result(self._module.context, logical_id_base + index) rt.result_record_output(self._builder, result_ref, Constant.null(i8p)) logical_id_base += size def visit_register(self, register): _log.debug(f"Visiting register '{register.name}'") if isinstance(register, QuantumRegister): self._qubit_labels.update( {bit: n + len(self._qubit_labels) for n, bit in enumerate(register)} ) _log.debug( f"Added labels for qubits {[bit for n, bit in enumerate(register)]}" ) elif isinstance(register, ClassicalRegister): self._clbit_labels.update( {bit: n + len(self._clbit_labels) for n, bit in enumerate(register)} ) else: raise ValueError(f"Register of type {type(register)} not supported.") def process_composite_instruction( self, instruction: Instruction, qargs: List[Qubit], cargs: List[Clbit] ): subcircuit = instruction.definition _log.debug( f"Processing composite instruction {instruction.name} with qubits {qargs}" ) if len(qargs) != subcircuit.num_qubits: raise ValueError( f"Composite instruction {instruction.name} called with the wrong number of qubits; \ {subcircuit.num_qubits} expected, {len(qargs)} provided" ) if len(cargs) != subcircuit.num_clbits: raise ValueError( f"Composite instruction {instruction.name} called with the wrong number of classical bits; \ {subcircuit.num_clbits} expected, {len(cargs)} provided" ) for inst, i_qargs, i_cargs in subcircuit.data: mapped_qbits = [qargs[subcircuit.qubits.index(i)] for i in i_qargs] mapped_clbits = [cargs[subcircuit.clbits.index(i)] for i in i_cargs] _log.debug( f"Processing sub-instruction {inst.name} with mapped qubits {mapped_qbits}" ) self.visit_instruction(inst, mapped_qbits, mapped_clbits) def visit_instruction( self, instruction: Instruction, qargs: List[Bit], cargs: List[Bit], skip_condition=False, ): qlabels = [self._qubit_labels.get(bit) for bit in qargs] clabels = [self._clbit_labels.get(bit) for bit in cargs] qubits = [pyqir.qubit(self._module.context, n) for n in qlabels] results = [pyqir.result(self._module.context, n) for n in clabels] if ( instruction.condition is not None ) and not self._capabilities & Capability.CONDITIONAL_BRANCHING_ON_RESULT: raise ConditionalBranchingOnResultError( self._qiskitModule.circuit, instruction, qargs, cargs, self._profile ) labels = ", ".join([str(l) for l in qlabels + clabels]) if instruction.condition is None or skip_condition: _log.debug(f"Visiting instruction '{instruction.name}' ({labels})") if instruction.condition is not None and skip_condition is False: _log.debug( f"Visiting condition for instruction '{instruction.name}' ({labels})" ) if isinstance(instruction.condition[0], Clbit): bit_label = self._clbit_labels.get(instruction.condition[0]) conditions = [pyqir.result(self._module.context, bit_label)] else: conditions = [ pyqir.result(self._module.context, self._clbit_labels.get(bit)) for bit in instruction.condition[0] ] # Convert value into a bitstring of the same length as classical register # condition should be a # - tuple (ClassicalRegister, int) # - tuple (Clbit, bool) # - tuple (Clbit, int) if isinstance(instruction.condition[0], Clbit): bit: Clbit = instruction.condition[0] value: Union[int, bool] = instruction.condition[1] if value: values = "1" else: values = "0" else: register: ClassicalRegister = instruction.condition[0] value: int = instruction.condition[1] values = format(value, f"0{register.size}b") # Add branches recursively for each bit in the bitstring def __visit(): self.visit_instruction(instruction, qargs, cargs, skip_condition=True) def _branch(conditions_values): try: cond, val = next(conditions_values) def __branch(): qis.if_result( self._builder, cond, one=_branch(conditions_values) if val == "1" else None, zero=_branch(conditions_values) if val == "0" else None, ) except StopIteration: return __visit else: return __branch if len(conditions) < len(values): raise ValueError( f"Value {value} is larger than register width {len(conditions)}." ) # qiskit has the most significant bit on the right, so we # must reverse the bit array for comparisons. _branch(zip(conditions, values[::-1]))() elif ( "measure" == instruction.name or "m" == instruction.name or "mz" == instruction.name ): for qubit, result in zip(qubits, results): self._measured_qubits[qubit_id(qubit)] = True qis.mz(self._builder, qubit, result) else: if not self._capabilities & Capability.QUBIT_USE_AFTER_MEASUREMENT: # If we have a supported instruction, apply the capability # check. If we have a composite instruction then it will call # back into this function with a supported name and we'll # verify at that time if instruction.name in _SUPPORTED_INSTRUCTIONS: if any(map(self._measured_qubits.get, map(qubit_id, qubits))): raise QubitUseAfterMeasurementError( self._qiskitModule.circuit, instruction, qargs, cargs, self._profile, ) if "barrier" == instruction.name: if self._emit_barrier_calls: qis.barrier(self._builder) elif "delay" == instruction.name: pass elif "swap" == instruction.name: qis.swap(self._builder, *qubits) elif "ccx" == instruction.name: qis.ccx(self._builder, *qubits) elif "cx" == instruction.name: qis.cx(self._builder, *qubits) elif "cz" == instruction.name: qis.cz(self._builder, *qubits) elif "h" == instruction.name: qis.h(self._builder, *qubits) elif "reset" == instruction.name: qis.reset(self._builder, qubits[0]) elif "rx" == instruction.name: qis.rx(self._builder, *instruction.params, *qubits) elif "ry" == instruction.name: qis.ry(self._builder, *instruction.params, *qubits) elif "rz" == instruction.name: qis.rz(self._builder, *instruction.params, *qubits) elif "s" == instruction.name: qis.s(self._builder, *qubits) elif "sdg" == instruction.name: qis.s_adj(self._builder, *qubits) elif "t" == instruction.name: qis.t(self._builder, *qubits) elif "tdg" == instruction.name: qis.t_adj(self._builder, *qubits) elif "x" == instruction.name: qis.x(self._builder, *qubits) elif "y" == instruction.name: qis.y(self._builder, *qubits) elif "z" == instruction.name: qis.z(self._builder, *qubits) elif "id" == instruction.name: # See: https://github.com/qir-alliance/pyqir/issues/74 qubit = pyqir.qubit(self._module.context, qubit_id(*qubits)) qis.x(self._builder, qubit) qis.x(self._builder, qubit) elif instruction.definition: _log.debug( f"About to process composite instruction {instruction.name} with qubits {qargs}" ) self.process_composite_instruction(instruction, qargs, cargs) else: raise ValueError( f"Gate {instruction.name} is not supported. \ Please transpile using the list of supported gates: {_SUPPORTED_INSTRUCTIONS}." ) def ir(self) -> str: return str(self._module) def bitcode(self) -> bytes: return self._module.bitcode() def _map_profile_to_capabilities(self, profile: str): value = profile.strip().lower() if "BasicExecution".lower() == value: return Capability.NONE elif "AdaptiveExecution".lower() == value: return Capability.ALL else: raise UnsupportedOperation( f"The supplied profile is not supported: {profile}." )
https://github.com/h-rathee851/Pulse_application_qiskit
h-rathee851
def speak(text): from IPython.display import Javascript as js, clear_output # Escape single quotes text = text.replace("'", r"\'") display(js(f''' if(window.speechSynthesis) {{ var synth = window.speechSynthesis; synth.speak(new window.SpeechSynthesisUtterance('{text}')); }} ''')) # Clear the JS so that the notebook doesn't speak again when reopened/refreshed clear_output(False) import numpy as np # Importing standard Qiskit libraries from qiskit import QuantumCircuit, transpile, Aer, IBMQ from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main') import sys np.set_printoptions(threshold=sys.maxsize) from qiskit import * from matplotlib import pyplot as plt # backend = provider.get_backend('ibmq_armonk') backend = provider.get_backend('ibmq_casablanca') from qiskit import * from qiskit.pulse import * from qiskit.tools.monitor import job_monitor qubit = 0 back_config = backend.configuration() inst_sched_map = backend.defaults().instruction_schedule_map meas_map_idx = None for i, measure_group in enumerate(back_config.meas_map): if qubit in measure_group: meas_map_idx = i break assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!" measure = inst_sched_map.get('measure', qubits=back_config.meas_map[qubit]) pulse_sigma = 40 pulse_duration = (4*pulse_sigma)-((4*pulse_sigma)%16) drive_chan = DriveChannel(0) def create_cal_circuits(amp): sched = Schedule() sched+=Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=amp), drive_chan) measure = inst_sched_map.get('measure', qubits=[qubit]) sched+=measure << sched.duration return sched default_qubit_freq = backend.defaults().qubit_freq_est[0] freq_list = np.linspace(default_qubit_freq-(20*1e+6), default_qubit_freq+(20*1e+6), 75) sched_list = [create_cal_circuits(0.4)]*75 # sweep_exp = assemble(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list]) # sweep_job = backend.run(sweep_exp) sweep_job = execute(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list]) job_monitor(sweep_job) sweep_result = sweep_job.result() sweep_values = [] for i in range(len(sweep_result.results)): res = sweep_result.get_memory(i)*1e-14 sweep_values.append(res[qubit]) scale_factor = 1e+9 freq_list_scaled = freq_list/scale_factor from scipy.optimize import curve_fit def find_init_params(res_values): est_baseline = np.mean(res_values) est_slope = -5 if est_baseline-np.min(res_values) > 2 else 5 return [est_slope, 4.975, 1, est_baseline] def fit_function(x_values, y_values, function, init_params): fitparams, conv = curve_fit(function, x_values, y_values, init_params) y_fit = function(x_values, *fitparams) return fitparams, y_fit init_params = find_init_params(np.real(sweep_values)) # initial parameters for curve_fit # init_params = [5, ] fit_params, y_fit = fit_function(freq_list_scaled, np.real(sweep_values), lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C, init_params ) plt.scatter(freq_list_scaled, np.real(sweep_values), color='black') plt.plot(freq_list_scaled, y_fit, color='red') plt.xlim([min(freq_list_scaled), max(freq_list_scaled)]) # plt.ylim([-7,0]) plt.xlabel("Frequency [GHz]") plt.ylabel("Measured Signal [a.u.]") plt.show() _, qubit_freq_new, _, _ = fit_params qubit_freq_ground = qubit_freq_new*scale_factor speak("The test program is done.") print(f"The new qubit frequency is : {qubit_freq_ground} Hz") #### Moving on to the Rabi experiments for 0->1 transition. amp_list = np.linspace(0, 1.0, 75) rabi_sched_list = [create_cal_circuits(amp) for amp in amp_list] # rabi_exp = assemble(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list)) # rabi_job = backend.run(rabi_exp) rabi_job = execute(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list)) job_monitor(rabi_job) rabi_results = rabi_job.result() scale_factor = 1e-14 rabi_values = [] for i in range(75): # Get the results for `qubit` from the ith experiment rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor) def baseline_remove(values): return np.array(values) - np.mean(values) rabi_values = np.real(baseline_remove(rabi_values)) fit_params, y_fit = fit_function(amp_list, rabi_values, lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B), [3*1e-7, 0, 0.3, 0]) drive_period = fit_params[2] pi_amp_ground = drive_period/2 plt.scatter(amp_list, rabi_values, color='black') plt.plot(amp_list, y_fit, color='red') plt.axvline(drive_period/2, color='red', linestyle='--') plt.axvline(drive_period, color='red', linestyle='--') plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red')) # plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red') plt.xlabel("Drive amp [a.u.]", fontsize=15) plt.ylabel("Measured signal [a.u.]", fontsize=15) plt.show() print(f"The calibrated pi amp is : {pi_amp_ground}") speak("The test program is over. Have a look at it.") from qiskit.pulse import library as pulse_lib def get_pi_pulse_ground(): pulse = pulse_lib.gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=pi_amp_ground) return pulse def get_zero_sched(): zero_sched = Schedule() zero_sched += measure return zero_sched def get_one_sched(): one_sched = Schedule() one_sched += Play(get_pi_pulse_ground(), drive_chan) one_sched += measure << one_sched.duration return one_sched def IQ_plot(zero_data, one_data): """Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given as arguments.""" # zero data plotted in blue plt.scatter(np.real(zero_data), np.imag(zero_data), s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$') # one data plotted in red plt.scatter(np.real(one_data), np.imag(one_data), s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$') x_min = np.min(np.append(np.real(zero_data), np.real(one_data)))-5 x_max = np.max(np.append(np.real(zero_data), np.real(one_data)))+5 y_min = np.min(np.append(np.imag(zero_data), np.imag(one_data)))-5 y_max = np.max(np.append(np.imag(zero_data), np.imag(one_data)))+5 # Plot a large dot for the average result of the 0, 1 and 2 states. mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts mean_one = np.mean(one_data) plt.scatter(np.real(mean_zero), np.imag(mean_zero), s=50, cmap='viridis', c='black',alpha=1.0) plt.scatter(np.real(mean_one), np.imag(mean_one), s=50, cmap='viridis', c='black',alpha=1.0) # plt.xlim(x_min, x_max) # plt.ylim(y_min,y_max) plt.legend() plt.ylabel('I [a.u.]', fontsize=15) plt.xlabel('Q [a.u.]', fontsize=15) plt.title("0-1 discrimination", fontsize=15) return x_min, x_max, y_min, y_max def get_job_data(job, average): scale_factor = 1e-14 job_results = job.result(timeout=120) # timeout parameter set to 120 s result_data = [] for i in range(len(job_results.results)): if average: # get avg data result_data.append(job_results.get_memory(i)[qubit]*scale_factor) else: # get single data result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor) return result_data discrim_01_sched_list = [get_zero_sched(), get_one_sched()] discrim_job = execute(discrim_01_sched_list, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*2) job_monitor(discrim_job) discrim_data = get_job_data(discrim_job, average=False) zero_data = discrim_data[0] one_data = discrim_data[1] x_min, x_max, y_min, y_max = IQ_plot(zero_data, one_data) discrim_job_0 = execute(get_zero_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) # discrim_job_0 = execute(zero_pulse_with_gap(350), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(discrim_job_0) discrim_job_1 = execute(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(discrim_job_1) zero_data_sep = get_job_data(discrim_job_0, average=False) one_data_sep = get_job_data(discrim_job_1, average=False) x_min, x_max, y_min, y_max = IQ_plot(zero_data_sep, one_data_sep) discrim_01_sched_list_assemble = [get_zero_sched(), get_one_sched()] discrim_exp = assemble(discrim_01_sched_list_assemble, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*2) discrim_job_assemble = backend.run(discrim_exp) job_monitor(discrim_job_assemble) discrim_data_assemble = get_job_data(discrim_job_assemble, average=False) zero_data_asmbl = discrim_data_assemble[0] one_data_asmbl = discrim_data_assemble[1] x_min, x_max, y_min, y_max = IQ_plot(zero_data_asmbl, one_data_asmbl) discrim_exp_0 = assemble(get_zero_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) discrim_job_0_asmbl = backend.run(discrim_exp_0) job_monitor(discrim_job_0_asmbl) discrim_exp_1 = assemble(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) discrim_job_1_asmbl = backend.run(discrim_exp_1) job_monitor(discrim_job_1_asmbl) zero_data_sep_asmbl = get_job_data(discrim_job_0_asmbl, average=False) one_data_sep_asmbl = get_job_data(discrim_job_1_asmbl, average=False) x_min, x_max, y_min, y_max = IQ_plot(zero_data_sep_asmbl, one_data_sep_asmbl) def zero_pulse_with_gap(gap): gapped_sched = Schedule() gapped_sched += measure << gap return gapped_sched gap_list = range(0,720,100) gap_sched_list = [zero_pulse_with_gap(gap) for gap in gap_list] print('Gap list : ', [*gap_list]) out_file = open("temp_01_scheds_sep_result_casablanca.txt", "w") for idx, sched in enumerate(gap_sched_list): gap_job = execute(sched, backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) if idx%1==0: print("Running job number %d" % idx) job_monitor(gap_job) gap_data = get_job_data(gap_job, average=False) print('0', idx*10, gap_data[0].tolist(), file=out_file) gap_job = execute(get_one_sched(), backend=backend, meas_level=1, meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(gap_job) gap_data = get_job_data(gap_job, average=False) print('1', '0', gap_data[0].tolist(), file=out_file) out_file.close() import ast res_file = open("temp_01_scheds_sep_result_casablanca.txt",'r') res_array =[] res = res_file.readline() iter=1 while res: res_array.append(ast.literal_eval(res[res.find('['):])) res = res_file.readline() iter += 1 res_file.close() plt.figure() print(len(res_array)) for idx, dat in enumerate(res_array[:9]): plt.scatter(np.real(dat), np.imag(dat), s=5, alpha=0.5) plt.show() for idx, sched in enumerate(gap_sched_list): gap_job = execute(sched, backend=backend, meas_level=2, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) if idx%1==0: print("Running job number %d" % idx) job_monitor(gap_job) result_counts = gap_job.result().get_counts() print('0 : ','Gap : ', idx*10, result_counts) gap_job = execute(get_one_sched(), backend=backend, meas_level=2, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]) job_monitor(gap_job) result_counts = gap_job.result().get_counts() print('1 : ','Gap : 0', result_counts) speak("The complete program is over. Check it out.")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test the Stochastic Swap pass""" import unittest import numpy.random from ddt import ddt, data from qiskit.transpiler.passes import StochasticSwap from qiskit.transpiler import CouplingMap, PassManager, Layout from qiskit.transpiler.exceptions import TranspilerError from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.test._canonical import canonicalize_control_flow from qiskit.transpiler.passes.utils import CheckMap from qiskit.circuit.random import random_circuit from qiskit.providers.fake_provider import FakeMumbai, FakeMumbaiV2 from qiskit.compiler.transpiler import transpile from qiskit.circuit import ControlFlowOp, Clbit, CASE_DEFAULT from qiskit.circuit.classical import expr @ddt class TestStochasticSwap(QiskitTestCase): """ Tests the StochasticSwap pass. All of the tests use a fixed seed since the results may depend on it. """ def test_trivial_case(self): """ q0:--(+)-[H]-(+)- | | q1:---.-------|-- | q2:-----------.-- Coupling map: [1]--[0]--[2] """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) self.assertEqual(dag, after) def test_trivial_in_same_layer(self): """ q0:--(+)-- | q1:---.--- q2:--(+)-- | q3:---.--- Coupling map: [0]--[1]--[2]--[3] """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[2], qr[3]) circuit.cx(qr[0], qr[1]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) self.assertEqual(dag, after) def test_permute_wires_1(self): """ q0:-------- q1:---.---- | q2:--(+)--- Coupling map: [1]--[0]--[2] q0:--x-(+)- | | q1:--|--.-- | q2:--x----- """ coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[2]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 11) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[2]) expected.cx(qr[1], qr[0]) self.assertEqual(circuit_to_dag(expected), after) def test_permute_wires_2(self): """ qr0:---.---[H]-- | qr1:---|-------- | qr2:--(+)------- Coupling map: [0]--[1]--[2] qr0:----.---[H]- | qr1:-x-(+)------ | qr2:-x---------- """ coupling = CouplingMap([[1, 0], [1, 2]]) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[2]) circuit.h(qr[0]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 11) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.swap(qr[1], qr[2]) expected.cx(qr[0], qr[1]) expected.h(qr[0]) self.assertEqual(expected, dag_to_circuit(after)) def test_permute_wires_3(self): """ qr0:--(+)---.-- | | qr1:---|----|-- | | qr2:---|----|-- | | qr3:---.---(+)- Coupling map: [0]--[1]--[2]--[3] qr0:-x------------ | qr1:-x--(+)---.--- | | qr2:-x---.---(+)-- | qr3:-x------------ """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.swap(qr[2], qr[3]) expected.cx(qr[1], qr[2]) expected.cx(qr[2], qr[1]) self.assertEqual(circuit_to_dag(expected), after) def test_permute_wires_4(self): """No qubit label permutation occurs if the first layer has only single-qubit gates. This is suboptimal but seems to be the current behavior. qr0:------(+)-- | qr1:-------|--- | qr2:-------|--- | qr3:--[H]--.--- Coupling map: [0]--[1]--[2]--[3] qr0:------X--------- | qr1:------X-(+)----- | qr2:------X--.------ | qr3:-[H]--X--------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.h(qr[3]) circuit.cx(qr[3], qr[0]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.h(qr[3]) expected.swap(qr[2], qr[3]) expected.swap(qr[0], qr[1]) expected.cx(qr[2], qr[1]) self.assertEqual(circuit_to_dag(expected), after) def test_permute_wires_5(self): """This is the same case as permute_wires_4 except the single qubit gate is after the two-qubit gate, so the layout is adjusted. qr0:--(+)------ | qr1:---|------- | qr2:---|------- | qr3:---.--[H]-- Coupling map: [0]--[1]--[2]--[3] qr0:-x----------- | qr1:-x--(+)------ | qr2:-x---.--[H]-- | qr3:-x----------- """ coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[3], qr[0]) circuit.h(qr[3]) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) expected = QuantumCircuit(qr) expected.swap(qr[0], qr[1]) expected.swap(qr[2], qr[3]) expected.cx(qr[2], qr[1]) expected.h(qr[2]) self.assertEqual(circuit_to_dag(expected), after) def test_all_single_qubit(self): """Test all trivial layers.""" coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circ = QuantumCircuit(qr, cr) circ.h(qr) circ.z(qr) circ.s(qr) circ.t(qr) circ.tdg(qr) circ.measure(qr[0], cr[0]) # intentional duplicate circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) dag = circuit_to_dag(circ) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) self.assertEqual(dag, after) def test_overoptimization_case(self): """Check mapper overoptimization. The mapper should not change the semantics of the input. An overoptimization introduced issue #81: https://github.com/Qiskit/qiskit-terra/issues/81 """ coupling = CouplingMap([[0, 2], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.y(qr[1]) circuit.z(qr[2]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[3]) circuit.s(qr[1]) circuit.t(qr[2]) circuit.h(qr[3]) circuit.cx(qr[1], qr[2]) circuit.measure(qr[0], cr[0]) circuit.measure(qr[1], cr[1]) circuit.measure(qr[2], cr[2]) circuit.measure(qr[3], cr[3]) dag = circuit_to_dag(circuit) # ┌───┐ ┌─┐ # q_0: | 0 >┤ X ├────────────■───────────────────────────┤M├───────── # └───┘┌───┐ ┌─┴─┐ ┌───┐ └╥┘┌─┐ # q_1: | 0 >─────┤ Y ├─────┤ X ├─────┤ S ├────────────■───╫─┤M├────── # └───┘┌───┐└───┘ └───┘┌───┐ ┌─┴─┐ ║ └╥┘┌─┐ # q_2: | 0 >──────────┤ Z ├───────■───────┤ T ├─────┤ X ├─╫──╫─┤M├─── # └───┘ ┌─┴─┐ └───┘┌───┐└───┘ ║ ║ └╥┘┌─┐ # q_3: | 0 >────────────────────┤ X ├──────────┤ H ├──────╫──╫──╫─┤M├ # └───┘ └───┘ ║ ║ ║ └╥┘ # c_0: 0 ══════════════════════════════════════════════╩══╬══╬══╬═ # ║ ║ ║ # c_1: 0 ═════════════════════════════════════════════════╩══╬══╬═ # ║ ║ # c_2: 0 ════════════════════════════════════════════════════╩══╬═ # ║ # c_3: 0 ═══════════════════════════════════════════════════════╩═ # expected = QuantumCircuit(qr, cr) expected.z(qr[2]) expected.y(qr[1]) expected.x(qr[0]) expected.swap(qr[0], qr[2]) expected.cx(qr[2], qr[1]) expected.swap(qr[0], qr[2]) expected.cx(qr[2], qr[3]) expected.s(qr[1]) expected.t(qr[2]) expected.h(qr[3]) expected.measure(qr[0], cr[0]) expected.cx(qr[1], qr[2]) expected.measure(qr[3], cr[3]) expected.measure(qr[1], cr[1]) expected.measure(qr[2], cr[2]) expected_dag = circuit_to_dag(expected) # ┌───┐ ┌─┐ # q_0: ┤ X ├─X───────X──────┤M├──────────────── # ├───┤ │ ┌───┐ │ ┌───┐└╥┘ ┌─┐ # q_1: ┤ Y ├─┼─┤ X ├─┼─┤ S ├─╫────────■──┤M├─── # ├───┤ │ └─┬─┘ │ └───┘ ║ ┌───┐┌─┴─┐└╥┘┌─┐ # q_2: ┤ Z ├─X───■───X───■───╫─┤ T ├┤ X ├─╫─┤M├ # └───┘ ┌─┴─┐ ║ ├───┤└┬─┬┘ ║ └╥┘ # q_3: ────────────────┤ X ├─╫─┤ H ├─┤M├──╫──╫─ # └───┘ ║ └───┘ └╥┘ ║ ║ # c: 4/══════════════════════╩════════╩═══╩══╩═ # 0 3 1 2 # # Layout -- # {qr[0]: 0, # qr[1]: 1, # qr[2]: 2, # qr[3]: 3} pass_ = StochasticSwap(coupling, 20, 19) after = pass_.run(dag) self.assertEqual(expected_dag, after) def test_already_mapped(self): """Circuit not remapped if matches topology. See: https://github.com/Qiskit/qiskit-terra/issues/342 """ coupling = CouplingMap( [ [1, 0], [1, 2], [2, 3], [3, 4], [3, 14], [5, 4], [6, 5], [6, 7], [6, 11], [7, 10], [8, 7], [9, 8], [9, 10], [11, 10], [12, 5], [12, 11], [12, 13], [13, 4], [13, 14], [15, 0], [15, 0], [15, 2], [15, 14], ] ) qr = QuantumRegister(16, "q") cr = ClassicalRegister(16, "c") circ = QuantumCircuit(qr, cr) circ.cx(qr[3], qr[14]) circ.cx(qr[5], qr[4]) circ.h(qr[9]) circ.cx(qr[9], qr[8]) circ.x(qr[11]) circ.cx(qr[3], qr[4]) circ.cx(qr[12], qr[11]) circ.cx(qr[13], qr[4]) for j in range(16): circ.measure(qr[j], cr[j]) dag = circuit_to_dag(circ) pass_ = StochasticSwap(coupling, 20, 13) after = pass_.run(dag) self.assertEqual(circuit_to_dag(circ), after) def test_congestion(self): """Test code path that falls back to serial layers.""" coupling = CouplingMap([[0, 1], [1, 2], [1, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circ = QuantumCircuit(qr, cr) circ.cx(qr[1], qr[2]) circ.cx(qr[0], qr[3]) circ.measure(qr[0], cr[0]) circ.h(qr) circ.cx(qr[0], qr[1]) circ.cx(qr[2], qr[3]) circ.measure(qr[0], cr[0]) circ.measure(qr[1], cr[1]) circ.measure(qr[2], cr[2]) circ.measure(qr[3], cr[3]) dag = circuit_to_dag(circ) # Input: # ┌─┐┌───┐ ┌─┐ # q_0: |0>─────────────────■──────────────────┤M├┤ H ├──■─────┤M├ # ┌───┐ │ └╥┘└───┘┌─┴─┐┌─┐└╥┘ # q_1: |0>──■───────┤ H ├──┼───────────────────╫──────┤ X ├┤M├─╫─ # ┌─┴─┐┌───┐└───┘ │ ┌─┐ ║ └───┘└╥┘ ║ # q_2: |0>┤ X ├┤ H ├───────┼─────────■─────┤M├─╫────────────╫──╫─ # └───┘└───┘ ┌─┴─┐┌───┐┌─┴─┐┌─┐└╥┘ ║ ║ ║ # q_3: |0>───────────────┤ X ├┤ H ├┤ X ├┤M├─╫──╫────────────╫──╫─ # └───┘└───┘└───┘└╥┘ ║ ║ ║ ║ # c_0: 0 ═══════════════════════════════╬══╬══╩════════════╬══╩═ # ║ ║ ║ # c_1: 0 ═══════════════════════════════╬══╬═══════════════╩════ # ║ ║ # c_2: 0 ═══════════════════════════════╬══╩════════════════════ # ║ # c_3: 0 ═══════════════════════════════╩═══════════════════════ # # Expected output (with seed 999): # ┌───┐ ┌─┐ # q_0: ───────X──┤ H ├─────────────────X──────┤M├────── # │ └───┘ ┌─┐ ┌───┐ │ ┌───┐└╥┘ ┌─┐ # q_1: ──■────X────■───────┤M├─X─┤ X ├─X─┤ X ├─╫────┤M├ # ┌─┴─┐┌───┐ │ └╥┘ │ └─┬─┘┌─┐└─┬─┘ ║ └╥┘ # q_2: ┤ X ├┤ H ├──┼────────╫──┼───■──┤M├──┼───╫─────╫─ # └───┘└───┘┌─┴─┐┌───┐ ║ │ ┌───┐└╥┘ │ ║ ┌─┐ ║ # q_3: ──────────┤ X ├┤ H ├─╫──X─┤ H ├─╫───■───╫─┤M├─╫─ # └───┘└───┘ ║ └───┘ ║ ║ └╥┘ ║ # c: 4/═════════════════════╩══════════╩═══════╩══╩══╩═ # 0 2 3 0 1 # # Target coupling graph: # 2 # | # 0 - 1 - 3 expected = QuantumCircuit(qr, cr) expected.cx(qr[1], qr[2]) expected.h(qr[2]) expected.swap(qr[0], qr[1]) expected.h(qr[0]) expected.cx(qr[1], qr[3]) expected.h(qr[3]) expected.measure(qr[1], cr[0]) expected.swap(qr[1], qr[3]) expected.cx(qr[2], qr[1]) expected.h(qr[3]) expected.swap(qr[0], qr[1]) expected.measure(qr[2], cr[2]) expected.cx(qr[3], qr[1]) expected.measure(qr[0], cr[3]) expected.measure(qr[3], cr[0]) expected.measure(qr[1], cr[1]) expected_dag = circuit_to_dag(expected) pass_ = StochasticSwap(coupling, 20, 999) after = pass_.run(dag) self.assertEqual(expected_dag, after) def test_only_output_cx_and_swaps_in_coupling_map(self): """Test that output DAG contains only 2q gates from the the coupling map.""" coupling = CouplingMap([[0, 1], [1, 2], [2, 3]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.measure(qr, cr) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling, 20, 5) after = pass_.run(dag) valid_couplings = [{qr[a], qr[b]} for (a, b) in coupling.get_edges()] for _2q_gate in after.two_qubit_ops(): self.assertIn(set(_2q_gate.qargs), valid_couplings) def test_len_cm_vs_dag(self): """Test error if the coupling map is smaller than the dag.""" coupling = CouplingMap([[0, 1], [1, 2]]) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[2]) circuit.cx(qr[0], qr[3]) circuit.measure(qr, cr) dag = circuit_to_dag(circuit) pass_ = StochasticSwap(coupling) with self.assertRaises(TranspilerError): _ = pass_.run(dag) def test_single_gates_omitted(self): """Test if single qubit gates are omitted.""" coupling_map = [[0, 1], [1, 0], [1, 2], [1, 3], [2, 1], [3, 1], [3, 4], [4, 3]] # q_0: ──■────────────────── # │ # q_1: ──┼─────────■──────── # │ ┌─┴─┐ # q_2: ──┼───────┤ X ├────── # │ ┌────┴───┴─────┐ # q_3: ──┼──┤ U(1,1.5,0.7) ├ # ┌─┴─┐└──────────────┘ # q_4: ┤ X ├──────────────── # └───┘ qr = QuantumRegister(5, "q") cr = ClassicalRegister(5, "c") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[4]) circuit.cx(qr[1], qr[2]) circuit.u(1, 1.5, 0.7, qr[3]) # q_0: ─────────────────X────── # │ # q_1: ───────■─────────X───■── # ┌─┴─┐ │ # q_2: ─────┤ X ├───────────┼── # ┌────┴───┴─────┐ ┌─┴─┐ # q_3: ┤ U(1,1.5,0.7) ├─X─┤ X ├ # └──────────────┘ │ └───┘ # q_4: ─────────────────X────── expected = QuantumCircuit(qr, cr) expected.cx(qr[1], qr[2]) expected.u(1, 1.5, 0.7, qr[3]) expected.swap(qr[0], qr[1]) expected.swap(qr[3], qr[4]) expected.cx(qr[1], qr[3]) expected_dag = circuit_to_dag(expected) stochastic = StochasticSwap(CouplingMap(coupling_map), seed=0) after = PassManager(stochastic).run(circuit) after = circuit_to_dag(after) self.assertEqual(expected_dag, after) @ddt class TestStochasticSwapControlFlow(QiskitTestCase): """Tests for control flow in stochastic swap.""" def test_pre_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[2]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[2]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[2]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=82).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(0, 1) expected.cx(1, 2) expected.measure(2, 2) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[2]]) efalse_body.x(1) new_order = [1, 0, 2, 3, 4] expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[2]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else_route_post_x(self): """test swap with if else controlflow construct; pre-cx and post x""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.measure(2, 2) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[2], 0), true_body, false_body, qreg, creg[[0]]) qc.x(1) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=431).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.swap(1, 2) expected.cx(0, 1) expected.measure(1, 2) new_order = [0, 2, 1, 3, 4] etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[2], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.x(2) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_post_if_else_route(self): """test swap with if else controlflow construct; post cx""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(3) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.barrier(qreg) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.cx(0, 2) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=6508).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[3, 4]], creg[[0]]) efalse_body.x(1) expected.barrier(qreg) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[3, 4]], creg[[0]]) expected.barrier(qreg) expected.swap(0, 1) expected.cx(1, 2) expected.barrier(qreg) expected.measure(qreg, creg[[1, 0, 2, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_if_else2(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) false_body = QuantumCircuit(qreg, creg[[0]]) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=38).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(0, 1) expected.cx(1, 2) expected.measure(1, 0) etrue_body = QuantumCircuit(qreg[[1]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[1]], creg[[0]]) new_order = [1, 0, 2, 3, 4] expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_intra_if_else_route(self): """test swap with if else controlflow construct""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=8).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(0, 1) etrue_body.cx(1, 2) etrue_body.swap(1, 2) etrue_body.swap(3, 4) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(1, 2) efalse_body.swap(3, 4) efalse_body.cx(2, 3) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) new_order = [1, 2, 0, 4, 3] expected.measure(qreg, creg[new_order]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_if_else(self): """test swap with if else controlflow construct; cx in if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap([(i, i + 1) for i in range(num_qubits - 1)]) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=2, trials=20).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) etrue_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) efalse_body = QuantumCircuit(qreg[[1, 2, 3, 4]], creg[[0]]) expected.h(0) expected.x(1) expected.swap(0, 1) expected.cx(1, 2) expected.measure(1, 0) etrue_body.cx(0, 1) etrue_body.swap(2, 3) etrue_body.swap(0, 1) efalse_body.swap(0, 1) efalse_body.swap(2, 3) efalse_body.cx(1, 2) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 2, 3, 4]], creg[[0]]) expected.measure(qreg, creg[[1, 2, 0, 4, 3]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_pre_intra_post_if_else(self): """test swap with if else controlflow construct; cx before, in, and after if statement""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.cx(0, 4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.h(3) qc.cx(3, 0) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=1).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.cx(0, 1) etrue_body.swap(0, 1) etrue_body.swap(4, 3) etrue_body.swap(2, 3) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.swap(0, 1) efalse_body.swap(3, 4) efalse_body.swap(2, 3) efalse_body.cx(1, 2) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[0, 1, 2, 3, 4]], creg[[0]]) expected.swap(1, 2) expected.h(4) expected.swap(3, 4) expected.cx(3, 2) expected.barrier() expected.measure(qreg, creg[[2, 4, 0, 3, 1]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_if_expr(self): """Test simple if conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.if_test(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=58).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_if_else_expr(self): """Test simple if/else conditional with an `Expr` condition.""" coupling = CouplingMap.from_line(4) true = QuantumCircuit(4) true.cx(0, 1) true.cx(0, 2) true.cx(0, 3) false = QuantumCircuit(4) false.cx(3, 0) false.cx(3, 1) false.cx(3, 2) qc = QuantumCircuit(4, 2) qc.if_else(expr.logic_and(qc.clbits[0], qc.clbits[1]), true, false, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=58).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_no_layout_change(self): """test controlflow with no layout change needed""" num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.cx(0, 2) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(2) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.x(4) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.barrier(qreg) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=23).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.swap(1, 2) expected.cx(0, 1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) etrue_body.x(0) efalse_body = QuantumCircuit(qreg[[1, 4]], creg[[0]]) efalse_body.x(1) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg[[1, 4]], creg[[0]]) expected.barrier(qreg) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) @data(1, 2, 3) def test_for_loop(self, nloops): """test stochastic swap with for_loop""" # if the loop has only one iteration it isn't necessary for the pass # to swap back to the starting layout. This test would check that # optimization. num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) for_body = QuantumCircuit(qreg) for_body.cx(0, 2) loop_parameter = None qc.for_loop(range(nloops), loop_parameter, for_body, qreg, []) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=687).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) efor_body = QuantumCircuit(qreg) efor_body.swap(0, 1) efor_body.cx(1, 2) efor_body.swap(0, 1) loop_parameter = None expected.for_loop(range(nloops), loop_parameter, efor_body, qreg, []) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop(self): """test while loop""" num_qubits = 4 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(len(qreg)) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) while_body = QuantumCircuit(qreg, creg) while_body.reset(qreg[2:]) while_body.h(qreg[2:]) while_body.cx(0, 3) while_body.measure(qreg[3], creg[3]) qc.while_loop((creg, 0), while_body, qc.qubits, qc.clbits) qc.barrier() qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=58).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) ewhile_body = QuantumCircuit(qreg, creg[:]) ewhile_body.reset(qreg[2:]) ewhile_body.h(qreg[2:]) ewhile_body.swap(0, 1) ewhile_body.swap(2, 3) ewhile_body.cx(1, 2) ewhile_body.measure(qreg[2], creg[3]) ewhile_body.swap(1, 0) ewhile_body.swap(3, 2) expected.while_loop((creg, 0), ewhile_body, expected.qubits, expected.clbits) expected.barrier() expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_while_loop_expr(self): """Test simple while loop with an `Expr` condition.""" coupling = CouplingMap.from_line(4) body = QuantumCircuit(4) body.cx(0, 1) body.cx(0, 2) body.cx(0, 3) qc = QuantumCircuit(4, 2) qc.while_loop(expr.logic_and(qc.clbits[0], qc.clbits[1]), body, [0, 1, 2, 3], []) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=58).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) def test_switch_single_case(self): """Test routing of 'switch' with just a single case.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) expected.switch(creg, [(0, case0)], qreg[[0, 1, 2]], creg[:]) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_nonexhaustive(self): """Test routing of 'switch' with several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(3, 4) case2.cx(3, 2) case2.swap(3, 4) expected.switch(creg, [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) @data((0, 1, 2, 3), (CASE_DEFAULT,)) def test_switch_exhaustive(self, labels): """Test routing of 'switch' with exhaustive cases; we should not require restoring the layout afterwards.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(2, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) expected.switch(creg, [(labels, case0)], qreg[[0, 1, 2]], creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_switch_nonexhaustive_expr(self): """Test routing of 'switch' with an `Expr` target and several but nonexhaustive cases.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(3, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.cx(3, 1) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.cx(4, 2) qc.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg, creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) case0.swap(0, 1) case1 = QuantumCircuit(qreg, creg[:]) case1.cx(1, 2) case1.cx(2, 3) case1.swap(1, 2) case1.cx(3, 2) case1.swap(1, 2) case2 = QuantumCircuit(qreg, creg[:]) case2.cx(2, 3) case2.cx(3, 4) case2.swap(3, 4) case2.cx(3, 2) case2.swap(3, 4) expected.switch(expr.bit_or(creg, 5), [(0, case0), ((1, 2), case1), (3, case2)], qreg, creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) @data((0, 1, 2, 3), (CASE_DEFAULT,)) def test_switch_exhaustive_expr(self, labels): """Test routing of 'switch' with exhaustive cases on an `Expr` target; we should not require restoring the layout afterwards.""" qreg = QuantumRegister(5, "q") creg = ClassicalRegister(2, "c") qc = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.cx(2, 0) qc.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg) coupling = CouplingMap.from_line(len(qreg)) pass_ = StochasticSwap(coupling, seed=58) test = pass_(qc) check = CheckMap(coupling) check(test) self.assertTrue(check.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) case0 = QuantumCircuit(qreg[[0, 1, 2]], creg[:]) case0.cx(0, 1) case0.cx(1, 2) case0.swap(0, 1) case0.cx(2, 1) expected.switch(expr.bit_or(creg, 3), [(labels, case0)], qreg[[0, 1, 2]], creg) self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected)) def test_nested_inner_cnot(self): """test swap in nested if else controlflow construct; swap in inner""" seed = 1 num_qubits = 3 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) check_map_pass = CheckMap(coupling) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(0, 2) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=seed).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg, []) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg) self.assertEqual(dag_to_circuit(cdag), expected) def test_nested_outer_cnot(self): """test swap with nested if else controlflow construct; swap in outer""" seed = 200 num_qubits = 5 qreg = QuantumRegister(num_qubits, "q") creg = ClassicalRegister(num_qubits) coupling = CouplingMap.from_line(num_qubits) qc = QuantumCircuit(qreg, creg) qc.h(0) qc.x(1) qc.measure(0, 0) true_body = QuantumCircuit(qreg, creg[[0]]) true_body.cx(0, 2) true_body.x(0) for_body = QuantumCircuit(qreg) for_body.delay(10, 0) for_body.barrier(qreg) for_body.cx(1, 3) loop_parameter = None true_body.for_loop(range(3), loop_parameter, for_body, qreg, []) false_body = QuantumCircuit(qreg, creg[[0]]) false_body.y(0) qc.if_else((creg[0], 0), true_body, false_body, qreg, creg[[0]]) qc.measure(qreg, creg) dag = circuit_to_dag(qc) cdag = StochasticSwap(coupling, seed=seed).run(dag) check_map_pass = CheckMap(coupling) check_map_pass.run(cdag) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qreg, creg) expected.h(0) expected.x(1) expected.measure(0, 0) etrue_body = QuantumCircuit(qreg, creg[[0]]) etrue_body.swap(1, 2) etrue_body.cx(0, 1) etrue_body.x(0) efor_body = QuantumCircuit(qreg) efor_body.delay(10, 0) efor_body.barrier(qreg) efor_body.cx(2, 3) etrue_body.for_loop(range(3), loop_parameter, efor_body, qreg[[0, 1, 2, 3, 4]], []) efalse_body = QuantumCircuit(qreg, creg[[0]]) efalse_body.y(0) efalse_body.swap(1, 2) expected.if_else((creg[0], 0), etrue_body, efalse_body, qreg, creg[[0]]) expected.measure(qreg, creg[[0, 2, 1, 3, 4]]) self.assertEqual(dag_to_circuit(cdag), expected) def test_disjoint_looping(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) loop_body = QuantumCircuit(2) loop_body.cx(0, 1) qc.for_loop((0,), None, loop_body, [0, 2], []) cqc = StochasticSwap(cm, seed=0)(qc) expected = QuantumCircuit(qr) efor_body = QuantumCircuit(qr[[0, 1, 2]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(1, 2) expected.for_loop((0,), None, efor_body, [0, 1, 2], []) self.assertEqual(cqc, expected) def test_disjoint_multiblock(self): """Test looping controlflow on different qubit register""" num_qubits = 4 cm = CouplingMap.from_line(num_qubits) qr = QuantumRegister(num_qubits, "q") cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) true_body = QuantumCircuit(3, 1) true_body.cx(0, 1) false_body = QuantumCircuit(3, 1) false_body.cx(0, 2) qc.if_else((cr[0], 1), true_body, false_body, [0, 1, 2], [0]) cqc = StochasticSwap(cm, seed=353)(qc) expected = QuantumCircuit(qr, cr) etrue_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) etrue_body.cx(0, 1) etrue_body.swap(0, 1) efalse_body = QuantumCircuit(qr[[0, 1, 2]], cr[[0]]) efalse_body.swap(0, 1) efalse_body.cx(1, 2) expected.if_else((cr[0], 1), etrue_body, efalse_body, [0, 1, 2], cr[[0]]) self.assertEqual(cqc, expected) def test_multiple_ops_per_layer(self): """Test circuits with multiple operations per layer""" num_qubits = 6 coupling = CouplingMap.from_line(num_qubits) check_map_pass = CheckMap(coupling) qr = QuantumRegister(num_qubits, "q") qc = QuantumCircuit(qr) # This cx and the for_loop are in the same layer. qc.cx(0, 2) with qc.for_loop((0,)): qc.cx(3, 5) cqc = StochasticSwap(coupling, seed=0)(qc) check_map_pass(cqc) self.assertTrue(check_map_pass.property_set["is_swap_mapped"]) expected = QuantumCircuit(qr) expected.swap(0, 1) expected.cx(1, 2) efor_body = QuantumCircuit(qr[[3, 4, 5]]) efor_body.swap(1, 2) efor_body.cx(0, 1) efor_body.swap(2, 1) expected.for_loop((0,), None, efor_body, [3, 4, 5], []) self.assertEqual(cqc, expected) def test_if_no_else_restores_layout(self): """Test that an if block with no else branch restores the initial layout. If there is an else branch, we don't need to guarantee this.""" qc = QuantumCircuit(8, 1) with qc.if_test((qc.clbits[0], False)): # Just some arbitrary gates with no perfect layout. qc.cx(3, 5) qc.cx(4, 6) qc.cx(1, 4) qc.cx(7, 4) qc.cx(0, 5) qc.cx(7, 3) qc.cx(1, 3) qc.cx(5, 2) qc.cx(6, 7) qc.cx(3, 2) qc.cx(6, 2) qc.cx(2, 0) qc.cx(7, 6) coupling = CouplingMap.from_line(8) pass_ = StochasticSwap(coupling, seed=2022_10_13) transpiled = pass_(qc) # Check the pass claims to have done things right. initial_layout = Layout.generate_trivial_layout(*qc.qubits) self.assertEqual(initial_layout, pass_.property_set["final_layout"]) # Check that pass really did do it right. inner_block = transpiled.data[0].operation.blocks[0] running_layout = initial_layout.copy() for instruction in inner_block: if instruction.operation.name == "swap": running_layout.swap(*instruction.qubits) self.assertEqual(initial_layout, running_layout) @ddt class TestStochasticSwapRandomCircuitValidOutput(QiskitTestCase): """Assert the output of a transpilation with stochastic swap is a physical circuit.""" @classmethod def setUpClass(cls): super().setUpClass() cls.backend = FakeMumbai() cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map} cls.basis_gates = set(cls.backend.configuration().basis_gates) cls.basis_gates.update(["for_loop", "while_loop", "if_else"]) def assert_valid_circuit(self, transpiled): """Assert circuit complies with constraints of backend.""" self.assertIsInstance(transpiled, QuantumCircuit) self.assertIsNotNone(getattr(transpiled, "_layout", None)) def _visit_block(circuit, qubit_mapping=None): for instruction in circuit: if instruction.operation.name in {"barrier", "measure"}: continue self.assertIn(instruction.operation.name, self.basis_gates) qargs = tuple(qubit_mapping[x] for x in instruction.qubits) if not isinstance(instruction.operation, ControlFlowOp): if len(qargs) > 2 or len(qargs) < 0: raise Exception("Invalid number of qargs for instruction") if len(qargs) == 2: self.assertIn(qargs, self.coupling_edge_set) else: self.assertLessEqual(qargs[0], 26) else: for block in instruction.operation.blocks: self.assertEqual(block.num_qubits, len(instruction.qubits)) self.assertEqual(block.num_clbits, len(instruction.clbits)) new_mapping = { inner: qubit_mapping[outer] for outer, inner in zip(instruction.qubits, block.qubits) } _visit_block(block, new_mapping) # Assert routing ran. _visit_block( transpiled, qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)}, ) @data(*range(1, 27)) def test_random_circuit_no_control_flow(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, self.backend, routing_method="stochastic", layout_method="dense", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @data(*range(1, 27)) def test_random_circuit_no_control_flow_target(self, size): """Test that transpiled random circuits without control flow are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) tqc = transpile( circuit, routing_method="stochastic", layout_method="dense", seed_transpiler=12342, target=FakeMumbaiV2().target, ) self.assert_valid_circuit(tqc) @data(*range(4, 27)) def test_random_circuit_for_loop(self, size): """Test that transpiled random circuits with nested for loops are physical circuits.""" circuit = random_circuit(size, 3, measure=False, seed=12342) for_block = random_circuit(3, 2, measure=False, seed=12342) inner_for_block = random_circuit(2, 1, measure=False, seed=12342) with circuit.for_loop((1,)): with circuit.for_loop((1,)): circuit.append(inner_for_block, [0, 3]) circuit.append(for_block, [1, 0, 2]) circuit.measure_all() tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="stochastic", layout_method="dense", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) @data(*range(6, 27)) def test_random_circuit_if_else(self, size): """Test that transpiled random circuits with if else blocks are physical circuits.""" circuit = random_circuit(size, 3, measure=True, seed=12342) if_block = random_circuit(3, 2, measure=True, seed=12342) else_block = random_circuit(2, 1, measure=True, seed=12342) rng = numpy.random.default_rng(seed=12342) inner_clbit_count = max((if_block.num_clbits, else_block.num_clbits)) if inner_clbit_count > circuit.num_clbits: circuit.add_bits([Clbit() for _ in [None] * (inner_clbit_count - circuit.num_clbits)]) clbit_indices = list(range(circuit.num_clbits)) rng.shuffle(clbit_indices) with circuit.if_test((circuit.clbits[0], True)) as else_: circuit.append(if_block, [0, 2, 1], clbit_indices[: if_block.num_clbits]) with else_: circuit.append(else_block, [2, 5], clbit_indices[: else_block.num_clbits]) tqc = transpile( circuit, self.backend, basis_gates=list(self.basis_gates), routing_method="stochastic", layout_method="dense", seed_transpiler=12342, ) self.assert_valid_circuit(tqc) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from qiskit import QuantumCircuit, transpile from qiskit.providers.fake_provider import FakeAuckland backend = FakeAuckland() ghz = QuantumCircuit(15) ghz.h(0) ghz.cx(0, range(1, 15)) depths = [] gate_counts = [] non_local_gate_counts = [] levels = [str(x) for x in range(4)] for level in range(4): circ = transpile(ghz, backend, optimization_level=level) depths.append(circ.depth()) gate_counts.append(sum(circ.count_ops().values())) non_local_gate_counts.append(circ.num_nonlocal_gates()) fig, (ax1, ax2) = plt.subplots(2, 1) ax1.bar(levels, depths, label='Depth') ax1.set_xlabel("Optimization Level") ax1.set_ylabel("Depth") ax1.set_title("Output Circuit Depth") ax2.bar(levels, gate_counts, label='Number of Circuit Operations') ax2.bar(levels, non_local_gate_counts, label='Number of non-local gates') ax2.set_xlabel("Optimization Level") ax2.set_ylabel("Number of gates") ax2.legend() ax2.set_title("Number of output circuit gates") fig.tight_layout() plt.show()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/KoljaFrahm/QiskitPerformance
KoljaFrahm
import numpy as np import matplotlib.pyplot as plt from pathlib import Path from scipy.sparse.sputils import getdata from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.utils import gen_batches from qiskit import Aer from qiskit.utils import QuantumInstance, algorithm_globals from qiskit.opflow import AerPauliExpectation from qiskit.circuit.library import TwoLocal, ZFeatureMap, RealAmplitudes from qiskit_machine_learning.neural_networks import TwoLayerQNN from qiskit_machine_learning.connectors import TorchConnector from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA #from IPython.display import clear_output # callback function that draws a live plot when the .fit() method is called def callback_graph(weights, obj_func_eval): #print("callback_graph called") #clear_output(wait=True) objective_func_vals.append(obj_func_eval) plt.figure() plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.savefig("callback_graph_all.png") plt.close() def onehot(data): """ returns the the data vector in one hot enconding. @data :: Numpy array with data of type int. """ return np.eye(int(data.max()+1))[data] def index(onehotdata): """ returns the the data vector in index enconding. @onehotdata :: Numpy array with data of type int on onehot encoding. """ return np.argmax(onehotdata, axis=1) def splitData(x_data, y_data, ratio_train, ratio_test, ratio_val): # Produces test split. x_remaining, x_test, y_remaining, y_test = train_test_split( x_data, y_data, test_size=ratio_test) # Adjusts val ratio, w.r.t. remaining dataset. ratio_remaining = 1 - ratio_test ratio_val_adjusted = ratio_val / ratio_remaining # Produces train and val splits. x_train, x_val, y_train, y_val = train_test_split( x_remaining, y_remaining, test_size=ratio_val_adjusted) return x_train, x_test, x_val, y_train, y_test, y_val def getData(): data_bkg = np.load("QML-HEP-data/x_data_bkg_8features.npy") data_sig = np.load("QML-HEP-data/x_data_sig_8features.npy") y_bkg = np.zeros(data_bkg.shape[0],dtype=int) y_sig = np.ones(data_sig.shape[0],dtype=int) x_data = np.concatenate((data_bkg,data_sig)) y_data = np.concatenate((y_bkg,y_sig)) # Defines ratios, w.r.t. whole dataset. ratio_train, ratio_test, ratio_val = 0.9, 0.05, 0.05 x_train, x_test, x_val, y_train, y_test, y_val = splitData( x_data, y_data, ratio_train, ratio_test, ratio_val) return x_train, x_test, x_val, y_train, y_test, y_val def plot_roc_get_auc(model,sets,labels): aucl = [] plt.figure() for set,label in zip(sets,labels): x,y = set pred = index(model(x)) #index because the prediction is onehot encoded fpr, tpr, thresholds = metrics.roc_curve(y, pred) plt.plot(fpr, tpr, label=label) auc = metrics.roc_auc_score(y, pred) aucl.append(auc) plt.savefig("rocplot.png") plt.close() return aucl def VQCTraining(vqc, x_train, y_train, x_test, y_test, epoch, bs): # create empty array for callback to store evaluations of the objective function plt.figure() plt.rcParams["figure.figsize"] = (12, 6) #training print("fitting starts") for epoch in range(epochs): batches = gen_batches(x_train.shape[0],bs) print(f"Epoch: {epoch + 1}/{epochs}") for batch in batches: vqc.fit(x_train[batch], onehot(y_train[batch])) loss = vqc.score(x_test, onehot(y_test)) print(loss) print("fitting finished") # return to default figsize plt.rcParams["figure.figsize"] = (6, 4) #declare quantum instance #simulator_gpu = Aer.get_backend('aer_simulator_statevector') #simulator_gpu.set_options(device='GPU') #qi = QuantumInstance(simulator_gpu) qi = QuantumInstance(Aer.get_backend("aer_simulator_statevector_gpu")) epochs = 20 nqubits = 8 niter = 20 #how many maximal iterations of the optimizer function bs = 128 # batch size #bs = 50 # test batch size ####Define VQC#### feature_map = ZFeatureMap(nqubits, reps=1) #ansatz = RealAmplitudes(nqubits, reps=1) ansatz = TwoLocal(nqubits, 'ry', 'cx', 'linear', reps=1) #optimizer = SPSA(maxiter=niter) #optimizer = COBYLA(maxiter=niter, disp=True) optimizer = None vqc = VQC( feature_map=feature_map, ansatz=ansatz, loss="cross_entropy", optimizer=optimizer, warm_start=False, quantum_instance=qi, callback=callback_graph, ) print("starting program") print(vqc.circuit) x_train, x_test, x_val, y_train, y_test, y_val = getData() ####reduce events for testing the program#### #num_samples = 256 #x_train, x_test, x_val = x_train[:num_samples], x_test[:num_samples], x_val[:num_samples] #y_train, y_test, y_val = y_train[:num_samples], y_test[:num_samples], y_val[:num_samples] ####VQC##### objective_func_vals = [] VQCTraining(vqc, x_train, y_train, x_test, y_test, epochs, bs) ####score classifier#### aucs = plot_roc_get_auc(vqc.predict,((x_test, y_test),(x_val,y_val)),("test data","validation data")) print(aucs) print("test")
https://github.com/jdanielescanez/quantum-solver
jdanielescanez
from s_aes import QS_SAES_Circuit from qiskit import execute from qiskit_aer import AerSimulator SIZE_REG = 16 CIRCUIT_SIZE = SIZE_REG * 2 msg_indexes = list(range(0, SIZE_REG)) msg_slice = slice(0, SIZE_REG) key_indexes = list(range(SIZE_REG, 2 * SIZE_REG)) for i in range(2 ** 4): msg = '0' * 12 + format(i, f'0{4}b') key = '0' * 16 qc = QS_SAES_Circuit(CIRCUIT_SIZE, msg, key, msg_indexes, key_indexes) qc.s_box() qc.measure(range(4), range(4)) backend = AerSimulator(method='matrix_product_state') job = execute(qc, backend, shots=1) counts = job.result().get_counts(qc) result_bin = ''.join(list(list(counts.keys())[0][::-1][:4][::-1])) print(msg, '-', result_bin[:4])
https://github.com/urwin419/QiskitChecker
urwin419
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) ### added y gate ### qc.cx(0, 1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) qc.h(1) ### added h gate ### qc.h(0) return qc
https://github.com/Alice-Bob-SW/qiskit-alice-bob-provider
Alice-Bob-SW
from qiskit import Aer, IBMQ, execute from qiskit import transpile, assemble from qiskit.tools.monitor import job_monitor from qiskit.tools.monitor import job_monitor import matplotlib.pyplot as plt from qiskit.visualization import plot_histogram, plot_state_city """ Qiskit backends to execute the quantum circuit """ def simulator(qc): """ Run on local simulator :param qc: quantum circuit :return: """ backend = Aer.get_backend("qasm_simulator") shots = 2048 tqc = transpile(qc, backend) qobj = assemble(tqc, shots=shots) job_sim = backend.run(qobj) qc_results = job_sim.result() return qc_results, shots def simulator_state_vector(qc): """ Select the StatevectorSimulator from the Aer provider :param qc: quantum circuit :return: statevector """ simulator = Aer.get_backend('statevector_simulator') # Execute and get counts result = execute(qc, simulator).result() state_vector = result.get_statevector(qc) return state_vector def real_quantum_device(qc): """ Use the IBMQ essex device :param qc: quantum circuit :return: """ provider = IBMQ.load_account() backend = provider.get_backend('ibmq_santiago') shots = 2048 TQC = transpile(qc, backend) qobj = assemble(TQC, shots=shots) job_exp = backend.run(qobj) job_monitor(job_exp) QC_results = job_exp.result() return QC_results, shots def counts(qc_results): """ Get counts representing the wave-function amplitudes :param qc_results: :return: dict keys are bit_strings and their counting values """ return qc_results.get_counts() def plot_results(qc_results): """ Visualizing wave-function amplitudes in a histogram :param qc_results: quantum circuit :return: """ plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False)) def plot_state_vector(state_vector): """Visualizing state vector in the density matrix representation""" plt.show(plot_state_city(state_vector))
https://github.com/erikberter/qiskit-quantum-artificial-life
erikberter
from qiskit import * from qiskit.aqua.circuits.gates import cry from qiskit.visualization import plot_histogram import numpy as np import random import sys import matplotlib.pyplot as plt theta = 2*np.pi/3 thetaR = np.pi/4 fileNum = 30 sim = Aer.get_backend('qasm_simulator') # Devuelve el valor esperado de un circuito con un solo bit de registro def getExpectedValue(qc, shots=8192): job = execute(qc, sim, shots=shots) count = job.result().get_counts() a,b = [count[a]/shots if a in count else 0 for a in ['0','1']] return a-b def printHistogram(qc, shots=8192): job = execute(qc, sim, shots=shots) return plot_histogram(job.result().get_counts()) # Devuelve la Gate time_Lapse que aplica una iteración de paso de tiempo # # Changed : Float que representa el valor en radianes del gate CRY def getDecoherence(changed): decoherenceG = QuantumCircuit(2,1, name='decoherence') decoherenceG.ry(changed,1) decoherenceG.cx(0,1) decoherenceG.ry(-changed,1) decoherenceG.cx(0,1) decoherenceG.cx(1,0) decoherenceG.measure([1],[0]) decoherenceG.reset(1) return decoherenceG # Crea un circuito general de una Artificial Life de población 1 # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de poblacion que tendra el algoritmo def getCircuit(pop=1,time=3, initial=theta, changed=theta, measure = True): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc # Aumenta el la cantidad de capas de tiempo del circuito. def addTimeLapse(qc,time,measure=False, changed = theta): decoherenceG = getDecoherence(changed).to_instruction() qBits = int(len(qc.qubits)/3) for i in range(0,time): #cry for j in range(qBits): qc.append(decoherenceG, [j*3+1,j*3+2],[j]) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) # Crea un escenario general de clonación de población asexual mediante clonación exponencial # # time : Integer representando la cantidad de iteraciones # pop : Integer representando la cantidad de poblacion que tendra el algoritmo # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # mutationRate : Float que representa el ratio de mutación def getCircuitG(time=3, pop=2, initial=theta, changed=theta, mutationRate = 0, mutation=False): decoherenceG = getDecoherence(changed).to_instruction() qc = QuantumCircuit(3*pop,pop) qc.u3(initial,0,0,0) qc.cx(0,1) actPop = 1 qc.barrier() for i in range(0,time): # Adding the Time_Lapse gates for j in range(0,actPop): qc.append(decoherenceG, [3*j+1,3*j+2],[j]) qc.barrier() # Adding the new population actPopi = actPop for z in range(0,min(actPop, pop-actPop)): qc.cx(3*z, 3*actPopi) if mutation: x = np.random.normal(loc=0, scale=mutationRate) qc.rx(x, 3*actPopi) y = np.random.normal(loc=0, scale=mutationRate) qc.ry(y, 3*actPopi) qc.cx(3*actPopi, 3*actPopi+1) qc.barrier() actPopi+=1 actPop = actPopi qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc getCircuitG(pop=2, time=2).draw(output='mpl') getCircuit(pop=2, time=2).draw(output='mpl') color = ["b","g","r"] def checkPopulationParameters(shot = 50, timeSet = [0,1,2], parameter = "changed"): global fileNum for j in range(0,len(timeSet)): x = [] y = [] for i in range(int(shot)): if(i%10==0): sys.stdout.write(f"Work progress: Iteration {j} - {100*float(i)/(shot)}% \r" ) sys.stdout.flush() rand = random.uniform(0, 1) x+= [rand] timeT = timeSet[j] if (parameter=="changed"): qc = getCircuit(time = timeT, changed=rand*np.pi) elif(parameter=="initial"): qc = getCircuit(time = timeT, initial=rand*np.pi) y += [getExpectedValue(qc)] plt.scatter(x, y,c=color[j], label=f"Time {timeSet[j]}") plt.legend(loc="lower left") plt.savefig(f"file_RA{fileNum}_N{shot}.png") fileNum+=1 checkPopulationParameters(parameter="initial") qc = getCircuitG(time=3,pop=3, initial=np.pi, changed = np.pi/5) printHistogram(qc, shots=1000) qc = getCircuitG(pop=2, time=2,mutation=True, mutationRate=0.5) #addTimeLapse(qc, time=3) qc.draw(output='mpl') #Creación del circuito cuantico q=QuantumRegister(10) c=ClassicalRegister(10) qc=QuantumCircuit(q,c) #Asignación aleatoria de sexos a cada individuo qc.h(q[0]) qc.cx(q[0],q[2]) qc.h(q[3]) qc.cx(q[3],q[5]) qc.barrier() #Comprobación de la posibilidad de la reproducción qc.cx(q[2],q[6]) qc.cx(q[5],q[6]) qc.barrier() #Determinación del fenotipo qc.u3(np.pi/4,0,0,q[0]) qc.cx(q[0],q[1]) qc.u3(3*np.pi/4,0,0,q[3]) qc.cx(q[3],q[4]) qc.barrier() #Creación del hijo qc.h(q[8]) qc.cu3(5*np.pi/2,0,0,q[0],q[8]) qc.cu3(5*np.pi/2,0,0,q[3],q[8]) qc.cx(q[8],q[7]) qc.barrier() #Supervivencia del hijo qc.x(q[6]) qc.ccx(q[6],q[7],q[8]) qc.x(q[6]) qc.barrier() qc.cx(q[8],q[9]) #Medida qc.measure(q[6],c[6]) qc.measure(q[8],c[8]) backend=Aer.get_backend('qasm_simulator') result=execute(qc,backend).result().get_counts() qc.draw(output='mpl') plot_histogram(result) # Crea un circuito general de una Artificial Life de población 1 con un background customizado # # time : Integer representando la cantidad de iteraciones # initial : Float que representa los radiones de la gate U3 inicial # changed : Float que representa los radianes de la gate CRY # pop : Integer representando la cantidad de población que tendrá el algoritmo def getCircuitCB(pop=1,time=3, initial=theta, changed=theta, measure = True, background_change=[np.pi/4,np.pi/8,np.pi/4], background_sign = [0,1,0]): qc = QuantumCircuit(3*pop,pop) for i in range(pop): qc.u3(initial,0,0,i*3) qc.cx(i*3,i*3+1) qc.barrier() for i in range(0,time): #cry for j in range(pop): decoherenceG = getDecoherence(background_change[i]).to_instruction() if(background_sign[i]==1): qc.x(j*3+1) qc.append(decoherenceG, [j*3+1,j*3+2],[j]) if(background_sign[i]==1): qc.x(j*3+1) qc.barrier() if(measure): qc.measure([3*j+1 for j in range(pop)],[j for j in range(pop)]) return qc getCircuitCB(pop=1, time=3).draw(output='mpl')
https://github.com/Qiskit/feedback
Qiskit
from qiskit.circuit import Parameter from qiskit import QuantumCircuit from qiskit.primitives import Estimator from qiskit.quantum_info import SparsePauliOp from qiskit.algorithms import TimeEvolutionProblem from qiskit.algorithms.time_evolvers import TrotterQRTE from qiskit.synthesis import LieTrotter import numpy as np A = lambda t: 1 - t B = lambda t: t t_param = Parameter("t") op1 = SparsePauliOp(["X"], np.array([2*A(t_param)])) op2 = SparsePauliOp(["Z"], np.array([2*B(t_param)])) op3 = SparsePauliOp(["Y"], np.array([1000])) H_t = op1 + op2 + op3 print(H_t) aux_op = [SparsePauliOp(["Z"])] T = 2 reps = 10 init = QuantumCircuit(1) # init.h(0) evolution_problem = TimeEvolutionProblem( H_t, time=T, initial_state=init, aux_operators=aux_op, t_param=t_param ) pf = LieTrotter(reps=1) estimator = Estimator() trotter_qrte = TrotterQRTE(product_formula=pf, num_timesteps=reps, estimator=estimator) result = trotter_qrte.evolve(evolution_problem) full_evo_circ = result.evolved_state print(full_evo_circ.decompose().decompose()) aux_op_res = result.aux_ops_evaluated obs_evo = result.observables print(f"final result (previous only aux_op evaluation): {aux_op_res}\n") print("Newly added aux_op evaluations at each time step:") for i, m in enumerate(obs_evo): print(f"step {i}: <Z> = {m}") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_qsphere(state)
https://github.com/BOBO1997/osp_solutions
BOBO1997
import numpy as np import matplotlib.pyplot as plt import itertools from pprint import pprint import pickle import time import datetime # Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z) from qiskit.opflow import Zero, One, I, X, Y, Z from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer from qiskit.tools.monitor import job_monitor from qiskit.circuit import Parameter from qiskit.transpiler.passes import RemoveBarriers # Import QREM package from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter from qiskit.ignis.mitigation import expectation_value # Import mitiq for zne import mitiq # Import state tomography modules from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter from qiskit.quantum_info import state_fidelity import sys import importlib sys.path.append("../../solutions/utils/") import circuit_utils, zne_utils, tomography_utils, sgs_algorithm importlib.reload(circuit_utils) importlib.reload(zne_utils) importlib.reload(tomography_utils) importlib.reload(sgs_algorithm) from circuit_utils import * from zne_utils import * from tomography_utils import * from sgs_algorithm import * # Combine subcircuits into a single multiqubit gate representing a single trotter step num_qubits = 3 # The final time of the state evolution target_time = np.pi # Parameterize variable t to be evaluated at t=pi later dt = Parameter('2t/n') # Convert custom quantum circuit into a gate trot_gate = trotter_gate(dt) # initial layout initial_layout = [5,3,1] # Number of trotter steps num_steps = 4 print("trotter step: ", num_steps) scale_factors = [1.0, 2.0, 3.0] qc = QuantumCircuit(3) subspace_decoder(qc, targets=[0, 1, 2]) qc.draw("mpl") # Initialize quantum circuit for 3 qubits # qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(3) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) qc.barrier() general_subspace_encoder(qc, targets=[0, 1, 2]) # encode qc.barrier() trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian qc.barrier() general_subspace_decoder(qc, targets=[0, 1, 2]) # decode qc = qc.bind_parameters({dt: target_time / num_steps}) qc.draw("mpl") # Initialize quantum circuit for 3 qubits # qr = QuantumRegister(num_qubits, name="q") qc = QuantumCircuit(3) # Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>) make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>) qc.barrier() subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode qc.barrier() trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian qc.barrier() subspace_decoder(qc, targets=[0, 1, 2]) # decode qc = qc.bind_parameters({dt: target_time / num_steps}) qc.draw("mpl") dt = Parameter('2t/n') mdt = Parameter('-2t/n') qc = QuantumCircuit(2) qc.rx(dt, 0) qc.rz(dt, 1) qc.h(1) qc.cx(1, 0) qc.rz(mdt, 0) qc.rx(mdt, 1) qc.rz(dt, 1) qc.cx(1, 0) qc.h(1) qc.rz(dt, 0) qc.draw("mpl") dt = Parameter('2t/n') mdt = Parameter('-2t/n') qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) qc.rz(mdt, 0) qc.rx(mdt, 1) qc.rz(dt, 1) qc.cx(1, 0) qc.h(1) qc.rx(dt, 1) qc.draw("mpl") from qiskit import IBMQ IBMQ.load_account() provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22') print("provider:", provider) backend = provider.get_backend("ibmq_jakarta") print(str(backend)) from qiskit.visualization import plot_error_map device = provider.backend.ibmq_jakarta plot_error_map(device) from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.ignis.mitigation import complete_meas_cal # QREM num_qubits = 3 qr = QuantumRegister(num_qubits, name="calq") meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal') meas_calibs[0].draw("mpl") meas_calibs[1].draw("mpl") meas_calibs[2].draw("mpl") meas_calibs[3].draw("mpl") meas_calibs[4].draw("mpl") meas_calibs[5].draw("mpl") meas_calibs[6].draw("mpl") meas_calibs[7].draw("mpl")
https://github.com/swe-bench/Qiskit__qiskit
swe-bench
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # pylint: disable=wrong-import-order """Main Qiskit public functionality.""" import pkgutil # First, check for required Python and API version from . import util # qiskit errors operator from .exceptions import QiskitError # The main qiskit operators from qiskit.circuit import ClassicalRegister from qiskit.circuit import QuantumRegister from qiskit.circuit import QuantumCircuit # pylint: disable=redefined-builtin from qiskit.tools.compiler import compile # TODO remove after 0.8 from qiskit.execute import execute # The qiskit.extensions.x imports needs to be placed here due to the # mechanism for adding gates dynamically. import qiskit.extensions import qiskit.circuit.measure import qiskit.circuit.reset # Allow extending this namespace. Please note that currently this line needs # to be placed *before* the wrapper imports or any non-import code AND *before* # importing the package you want to allow extensions for (in this case `backends`). __path__ = pkgutil.extend_path(__path__, __name__) # Please note these are global instances, not modules. from qiskit.providers.basicaer import BasicAer # Try to import the Aer provider if installed. try: from qiskit.providers.aer import Aer except ImportError: pass # Try to import the IBMQ provider if installed. try: from qiskit.providers.ibmq import IBMQ except ImportError: pass from .version import __version__ from .version import __qiskit_version__
https://github.com/MAI-cyber/QIT
MAI-cyber
from qiskit import QuantumCircuit from qiskit.circuit.library import QFT from qiskit import Aer, execute from qiskit.visualization import plot_histogram import numpy as np pi = np.pi n=5 qc=QuantumCircuit(n+1,n) for qubit in range(n): qc.h(qubit) init_st=[0, 1] qc.initialize(init_st,n) theta=0.9 for x in range(n): exponent = 2**(n-x-1) qc.cp(2*pi*theta*exponent, x, n) qc.append(QFT(n).inverse(), range(n)) for i in range(n): qc.measure(i,i) qc.draw('mpl') simulator = Aer.get_backend('qasm_simulator') counts = execute(qc, backend=simulator, shots=10000).result().get_counts() plot_histogram(counts) import operator highest_probability_outcome = max(counts.items(), key=operator.itemgetter(1))[0][::-1] highest_probability_outcome measured_theta = int(highest_probability_outcome, 2)/2**n print("Using ", n, " qubits with theta = ",theta, ", measured_theta = ", measured_theta)
https://github.com/Alice-Bob-SW/emulation-examples
Alice-Bob-SW
from qiskit_alice_bob_provider import AliceBobLocalProvider from qiskit_aer import AerSimulator import tempfile from qiskit import transpile, execute, QuantumCircuit from qiskit.circuit import Qubit, Clbit import numpy as np from tqdm.notebook import tqdm from matplotlib import pyplot as plt provider = AliceBobLocalProvider() print(provider.backends()) backend = provider.get_backend('EMU:15Q:LOGICAL_EARLY') def build_teleportation_routine() -> QuantumCircuit: teleportation = QuantumCircuit(3, 2, name='teleport') teleportation.initialize('+', [1]) teleportation.initialize('0', [2]) teleportation.cx(1, 2) teleportation.cx(0, 1) teleportation.measure_x(0, 0) teleportation.measure(1, 1) teleportation.x(2).c_if(1, 1) teleportation.z(2).c_if(0, 1) return teleportation build_teleportation_routine().draw('mpl') def build_teleportation_tomography(teleported_state: str) -> QuantumCircuit: assert teleported_state in {'+', '-', '0', '1'} circuit = QuantumCircuit(3, 3) circuit.initialize(teleported_state, 0) circuit.append(build_teleportation_routine().to_instruction(), [0, 1, 2], [0, 1]) if teleported_state in {'+', '-'}: circuit.measure_x(2, 2) else: circuit.measure(2, 2) return circuit plus_circuit = build_teleportation_tomography('+') plus_circuit.draw('mpl') transpiled = transpile(plus_circuit, backend) transpiled.draw('mpl') execute(plus_circuit, backend).result().get_counts() zero_circuit = build_teleportation_tomography('0') execute(zero_circuit, backend).result().get_counts() k1 = 100 k2 = 100_000 average_nb_photonss = np.linspace(4, 24, 11) distances = 2 * np.arange(1, 10) + 1 shots = 10_000 bit_flips = np.zeros((max(average_nb_photonss.shape), max(distances.shape))) phase_flips = np.zeros((max(average_nb_photonss.shape), max(distances.shape))) plus_circuit = build_teleportation_tomography('+') zero_circuit = build_teleportation_tomography('0') for j, distance in enumerate(tqdm(distances)): for i, average_nb_photons in enumerate(tqdm(average_nb_photonss)): backend = provider.get_backend( 'EMU:40Q:LOGICAL_TARGET', average_nb_photons=average_nb_photons, distance=distance, kappa_2=k2, kappa_1=k1 ) counts = execute(zero_circuit, backend, shots=shots).result().get_counts() for word, count in counts.items(): if word[0] == '1': bit_flips[i][j] += count counts = execute(plus_circuit, backend, shots=shots).result().get_counts() for word, count in counts.items(): if word[0] == '1': phase_flips[i][j] += count plt.figure() plt.title(f'Bit flip rate (k1/k2={k1/k2:.0e})') colors = plt.cm.viridis(np.linspace(0, 1, max(distances.shape))) for j, distance in enumerate(distances): plt.plot(average_nb_photonss, bit_flips[:, j] / shots, label=f'Distance {distance}', c=colors[j]) plt.xlabel('Average number of photons') plt.ylabel('Bit flip rate') plt.legend() plt.show() plt.figure() plt.title(f'Phase flip rate (k1/k2={k1/k2:.0e})') colors = plt.cm.viridis(np.linspace(0, 1, max(distances.shape))) for j, distance in enumerate(distances): plt.plot(average_nb_photonss, phase_flips[:, j] / shots, label=f'Distance {distance}', c=colors[j]) plt.xlabel('Average number of photons') plt.ylabel('Phase flip rate') plt.legend() plt.show()
https://github.com/quantumjim/qreative
quantumjim
import sys sys.path.append('../') import CreativeQiskit n = 2 alps = CreativeQiskit.random_mountain(n) pos,prob = alps.get_mountain() print('coordinates\n',pos) print('\nprobabilities\n',prob) n = 8 alps = CreativeQiskit.random_mountain(n) alps.qc.h(alps.qr[0]) pos,prob = alps.get_mountain() import matplotlib.pyplot as plt import numpy as np from scipy.spatial import Voronoi, voronoi_plot_2d import random def plot_mountain(pos,prob,levels=[0.3,0.8,0.9],log=True,perturb=0.0): [sea,tree,snow] = levels coords = [] Z = [] for node in pos: coords.append( [pos[node][0]+(1-random.random())*perturb,pos[node][1]+(1-random.random())*perturb] ) if log: Z.append(np.log(prob[node])) else: Z.append(prob[node]) vor = Voronoi(coords) minZ = min(Z) maxZ = max(Z) # normalize chosen colormap colors = [] for node in range(len(Z)): z = (Z[node]-minZ)/(maxZ-minZ) if levels: if z<sea: color = (0,0.5,1,1) elif z<tree: color = (1*(z-sea),1*(1-sea),1*(z-sea),1) elif z<snow: color = (0.7,0.7,0.7,1) else: color = (1,1,1,1) else: color = (z,z,z,1) colors.append(color) # plot Voronoi diagram, and fill finite regions with color mapped from speed value voronoi_plot_2d(vor, show_points=True, show_vertices=False, point_size=0, line_width=0.0) for r in range(len(vor.point_region)): region = vor.regions[vor.point_region[r]] if not -1 in region: polygon = [vor.vertices[i] for i in region] plt.fill(*zip(*polygon), color=colors[r]) plt.savefig('outputs/islands.png',dpi=1000) plt.show() pos,prob = alps.get_mountain(noisy=0.3) plot_mountain(pos,prob) from qiskit import IBMQ IBMQ.load_accounts() pos,prob = alps.get_mountain(noisy='ibmq_16_melbourne') plot_mountain(pos,prob) pos,prob = alps.get_mountain(noisy=0.3,method='rings') plot_mountain(pos,prob,levels=[0.35,0.8,0.9]) pos,prob = alps.get_mountain(method='rings',new_data=False) plot_mountain(pos,prob,levels=[0.35,0.8,0.9]) for j in range(n-1): alps.qc.cx(alps.qr[j],alps.qr[j+1]) pos,prob = alps.get_mountain() plot_mountain(pos,prob) pos,prob = alps.get_mountain(noisy=0.3) plot_mountain(pos,prob) plot_mountain(pos,prob,perturb=0.75)
https://github.com/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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/jonasmaziero/computacao_quantica_qiskit
jonasmaziero
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute, IBMQ from qiskit.providers.aer import noise from qiskit.providers.aer.noise import NoiseModel from qiskit.visualization import plot_histogram from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter qr = QuantumRegister(5) qubit_list = [2, 3, 4] # os qubits para os quais aplicaremos calibracao de medidas meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) print(state_labels) meas_calibs # circuitos que serao executados para obter dados para calibracao (uma para cada state_labels) nshots = 8192 simulator = Aer.get_backend('qasm_simulator') job = execute(meas_calibs, backend = simulator, shots = nshots) # executa a calibracao cal_results = job.result() # a matriz de calibracao sem ruido e a identidade meas_fitter = CompleteMeasFitter(cal_results, state_labels) print(meas_fitter.cal_matrix) meas_fitter.plot_calibration() provider = IBMQ.load_account() device = provider.get_backend('ibmq_bogota') noise_model = NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates coupling_map = device.configuration().coupling_map job = execute(meas_calibs, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) print(meas_fitter.cal_matrix) # visualizacao grafica da matriz de calibracao meas_fitter.plot_calibration() qr = QuantumRegister(5); cr = ClassicalRegister(3); qc_ghz = QuantumCircuit(qr, cr) qc_ghz.h(qr[2]); qc_ghz.cx(qr[2], qr[3]); qc_ghz.cx(qr[3], qr[4]) qc_ghz.measure(qr[2], cr[0]); qc_ghz.measure(qr[3], cr[1]); qc_ghz.measure(qr[4], cr[2]); qc_ghz.draw(output = 'mpl') qubit_list = [2, 3, 4] # os qubits para os quais aplicaremos calibracao de medidas meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) job = execute(qc_ghz, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) unmitigated_counts = job.result().get_counts() # resultados sem mitigacao de erros # Resultados com mitigacao de erros mitigated_results = meas_fitter.filter.apply(job.result()) mitigated_counts = mitigated_results.get_counts() plot_histogram([unmitigated_counts, mitigated_counts], legend=['sem mit', 'com mit']) qr = QuantumRegister(3); qc = QuantumCircuit(qr); qc.h([0]); qc.cx([0], [1]) qc.draw(output = 'mpl') from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter qstc = state_tomography_circuits(qc, [qr[0], qr[1]]) job = execute(qstc, backend = simulator, shots = nshots) qstf = StateTomographyFitter(job.result(), qstc) rho = qstf.fit(method = 'lstsq') print(rho.real) from qiskit.visualization import plot_state_city plot_state_city(rho, title=r'$|\Phi_{+}^{sim}\rangle$') device = provider.get_backend('ibmq_bogota') noise_model = NoiseModel.from_backend(device) basis_gates = noise_model.basis_gates coupling_map = device.configuration().coupling_map job = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) qstf = StateTomographyFitter(job.result(), qstc) rho = qstf.fit(method='lstsq') print(rho.real) plot_state_city(rho, title=r'$|\Phi_{+}^{simN}\rangle$') qubit_list = [0, 1] meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) qstc = state_tomography_circuits(qc, [qr[0], qr[1]]) job = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model, basis_gates = basis_gates, coupling_map = coupling_map) mitigated_results = meas_fitter.filter.apply(job.result()) qstf = StateTomographyFitter(mitigated_results, qstc) rho = qstf.fit(method = 'lstsq') print(rho.real) plot_state_city(rho, title=r'$|\Phi_{+}^{simNcal}\rangle$') qr = QuantumRegister(3); qc = QuantumCircuit(qr); qc.h([0]); qc.cx([0], [1]) qc.draw(output = 'mpl') provider = IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main') device = provider.get_backend('ibmq_bogota') from qiskit.tools.monitor import job_monitor qstc = state_tomography_circuits(qc, [qr[0], qr[1]]) job_exp = execute(qstc, backend = device, shots = nshots); job_monitor(job_exp) qstf = StateTomographyFitter(job_exp.result(), qstc) rho = qstf.fit(method = 'lstsq'); print(rho.real) plot_state_city(rho, title=r'$|\Phi_{+}^{exp}\rangle$') qubit_list = [0, 1] # os qubits para os quais aplicaremos calibracao de medidas meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr) job = execute(meas_calibs, backend = device, shots = nshots) job_monitor(job) cal_results = job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels) mitigated_results = meas_fitter.filter.apply(job_exp.result()) qstf = StateTomographyFitter(mitigated_results, qstc) rho = qstf.fit(method = 'lstsq'); print(rho.real) plot_state_city(rho, title=r'$|\Phi_{+}^{ExpCal}\rangle$')
https://github.com/swe-train/qiskit__qiskit
swe-train
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests for circuit templates.""" import unittest from test import combine from inspect import getmembers, isfunction from ddt import ddt import numpy as np from qiskit import QuantumCircuit from qiskit.test import QiskitTestCase from qiskit.quantum_info.operators import Operator import qiskit.circuit.library.templates as templib @ddt class TestTemplates(QiskitTestCase): """Tests for the circuit templates.""" circuits = [o[1]() for o in getmembers(templib) if isfunction(o[1])] for circuit in circuits: if isinstance(circuit, QuantumCircuit): circuit.assign_parameters({param: 0.2 for param in circuit.parameters}, inplace=True) @combine(template_circuit=circuits) def test_template(self, template_circuit): """test to verify that all templates are equivalent to the identity""" target = Operator(template_circuit) value = Operator(np.eye(2**template_circuit.num_qubits)) self.assertTrue(target.equiv(value)) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.circuit.library import MCXGate gate = MCXGate(4) from qiskit import QuantumCircuit circuit = QuantumCircuit(5) circuit.append(gate, [0, 1, 4, 2, 3]) circuit.draw('mpl')
https://github.com/madmen2/QASM
madmen2
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/indian-institute-of-science-qc/qiskit-aakash
indian-institute-of-science-qc
# 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. """`_text_circuit_drawer` draws a circuit in ascii art""" import pathlib import os import tempfile import unittest.mock from codecs import encode from math import pi import numpy from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile from qiskit.circuit import Gate, Parameter, Qubit, Clbit, Instruction from qiskit.quantum_info.operators import SuperOp from qiskit.quantum_info.random import random_unitary from qiskit.test import QiskitTestCase from qiskit.transpiler.layout import Layout, TranspileLayout from qiskit.visualization import circuit_drawer from qiskit.visualization.circuit import text as elements from qiskit.visualization.circuit.circuit_visualization import _text_circuit_drawer from qiskit.extensions import UnitaryGate, HamiltonianGate from qiskit.extensions.quantum_initializer import UCGate from qiskit.circuit.library import ( HGate, U2Gate, U3Gate, XGate, CZGate, ZGate, YGate, U1Gate, SwapGate, RZZGate, CU3Gate, CU1Gate, CPhaseGate, ) from qiskit.transpiler.passes import ApplyLayout from qiskit.utils.optionals import HAS_TWEEDLEDUM from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase if HAS_TWEEDLEDUM: from qiskit.circuit.classicalfunction import classical_function from qiskit.circuit.classicalfunction.types import Int1 class TestTextDrawerElement(QiskitTestCase): """Draw each element""" def assertEqualElement(self, expected, element): """ Asserts the top,mid,bot trio Args: expected (list[top,mid,bot]): What is expected. element (DrawElement): The element to check. """ try: encode("\n".join(expected), encoding="cp437") except UnicodeEncodeError: self.fail("_text_circuit_drawer() should only use extended ascii (aka code page 437).") self.assertEqual(expected[0], element.top) self.assertEqual(expected[1], element.mid) self.assertEqual(expected[2], element.bot) def test_measure_to(self): """MeasureTo element.""" element = elements.MeasureTo() # fmt: off expected = [" ║ ", "═╩═", " "] # fmt: on self.assertEqualElement(expected, element) def test_measure_to_label(self): """MeasureTo element with cregbundle""" element = elements.MeasureTo("1") # fmt: off expected = [" ║ ", "═╩═", " 1 "] # fmt: on self.assertEqualElement(expected, element) def test_measure_from(self): """MeasureFrom element.""" element = elements.MeasureFrom() # fmt: off expected = ["┌─┐", "┤M├", "└╥┘"] # fmt: on self.assertEqualElement(expected, element) def test_text_empty(self): """The empty circuit.""" expected = "" circuit = QuantumCircuit() self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_pager(self): """The pager breaks the circuit when the drawing does not fit in the console.""" expected = "\n".join( [ " ┌───┐ »", "q_0: |0>┤ X ├──■──»", " └─┬─┘┌─┴─┐»", "q_1: |0>──■──┤ X ├»", " └───┘»", " c: 0 1/══════════»", " »", "« ┌─┐┌───┐ »", "«q_0: ┤M├┤ X ├──■──»", "« └╥┘└─┬─┘┌─┴─┐»", "«q_1: ─╫───■──┤ X ├»", "« ║ └───┘»", "«c: 1/═╩═══════════»", "« 0 »", "« ┌─┐┌───┐ ", "«q_0: ┤M├┤ X ├──■──", "« └╥┘└─┬─┘┌─┴─┐", "«q_1: ─╫───■──┤ X ├", "« ║ └───┘", "«c: 1/═╩═══════════", "« 0 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) circuit.measure(qr[0], cr[0]) circuit.cx(qr[1], qr[0]) circuit.cx(qr[0], qr[1]) self.assertEqual(str(_text_circuit_drawer(circuit, fold=20)), expected) def test_text_no_pager(self): """The pager can be disable.""" qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) for _ in range(100): circuit.h(qr[0]) amount_of_lines = str(_text_circuit_drawer(circuit, fold=-1)).count("\n") self.assertEqual(amount_of_lines, 2) class TestTextDrawerGatesInCircuit(QiskitTestCase): """Gate by gate checks in different settings.""" def test_text_measure_cregbundle(self): """The measure operator, using 3-bit-length registers with cregbundle=True.""" expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├──────", " └╥┘┌─┐ ", "q_1: |0>─╫─┤M├───", " ║ └╥┘┌─┐", "q_2: |0>─╫──╫─┤M├", " ║ ║ └╥┘", " c: 0 3/═╩══╩══╩═", " 0 1 2 ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_measure_cregbundle_2(self): """The measure operator, using 2 classical registers with cregbundle=True.""" expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├───", " └╥┘┌─┐", "q_1: |0>─╫─┤M├", " ║ └╥┘", "cA: 0 1/═╩══╬═", " 0 ║ ", "cB: 0 1/════╩═", " 0 ", ] ) qr = QuantumRegister(2, "q") cr_a = ClassicalRegister(1, "cA") cr_b = ClassicalRegister(1, "cB") circuit = QuantumCircuit(qr, cr_a, cr_b) circuit.measure(qr[0], cr_a[0]) circuit.measure(qr[1], cr_b[0]) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_measure_1(self): """The measure operator, using 3-bit-length registers.""" expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├──────", " └╥┘┌─┐ ", "q_1: |0>─╫─┤M├───", " ║ └╥┘┌─┐", "q_2: |0>─╫──╫─┤M├", " ║ ║ └╥┘", " c_0: 0 ═╩══╬══╬═", " ║ ║ ", " c_1: 0 ════╩══╬═", " ║ ", " c_2: 0 ═══════╩═", " ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_measure_1_reverse_bits(self): """The measure operator, using 3-bit-length registers, with reverse_bits""" expected = "\n".join( [ " ┌─┐", "q_2: |0>──────┤M├", " ┌─┐└╥┘", "q_1: |0>───┤M├─╫─", " ┌─┐└╥┘ ║ ", "q_0: |0>┤M├─╫──╫─", " └╥┘ ║ ║ ", " c: 0 3/═╩══╩══╩═", " 0 1 2 ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_measure_2(self): """The measure operator, using some registers.""" expected = "\n".join( [ " ", "q1_0: |0>──────", " ", "q1_1: |0>──────", " ┌─┐ ", "q2_0: |0>┤M├───", " └╥┘┌─┐", "q2_1: |0>─╫─┤M├", " ║ └╥┘", " c1: 0 2/═╬══╬═", " ║ ║ ", " c2: 0 2/═╩══╩═", " 0 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") qr2 = QuantumRegister(2, "q2") cr2 = ClassicalRegister(2, "c2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.measure(qr2, cr2) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_measure_2_reverse_bits(self): """The measure operator, using some registers, with reverse_bits""" expected = "\n".join( [ " ┌─┐", "q2_1: |0>───┤M├", " ┌─┐└╥┘", "q2_0: |0>┤M├─╫─", " └╥┘ ║ ", "q1_1: |0>─╫──╫─", " ║ ║ ", "q1_0: |0>─╫──╫─", " ║ ║ ", " c2: 0 2/═╩══╩═", " 0 1 ", " c1: 0 2/══════", " ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") qr2 = QuantumRegister(2, "q2") cr2 = ClassicalRegister(2, "c2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.measure(qr2, cr2) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_wire_order(self): """Test the wire_order option""" expected = "\n".join( [ " ", "q_2: |0>────────────", " ┌───┐ ", "q_1: |0>┤ X ├───────", " ├───┤ ┌───┐ ", "q_3: |0>┤ H ├─┤ X ├─", " ├───┤ └─╥─┘ ", "q_0: |0>┤ H ├───╫───", " └───┘┌──╨──┐", " c: 0 4/═════╡ 0xa ╞", " └─────┘", "ca: 0 2/════════════", " ", ] ) qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") cr2 = ClassicalRegister(2, "ca") circuit = QuantumCircuit(qr, cr, cr2) circuit.h(0) circuit.h(3) circuit.x(1) circuit.x(3).c_if(cr, 10) self.assertEqual( str(_text_circuit_drawer(circuit, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7])), expected ) def test_text_swap(self): """Swap drawing.""" expected = "\n".join( [ " ", "q1_0: |0>─X────", " │ ", "q1_1: |0>─┼──X─", " │ │ ", "q2_0: |0>─X──┼─", " │ ", "q2_1: |0>────X─", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.swap(qr1, qr2) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_swap_reverse_bits(self): """Swap drawing with reverse_bits.""" expected = "\n".join( [ " ", "q2_1: |0>────X─", " │ ", "q2_0: |0>─X──┼─", " │ │ ", "q1_1: |0>─┼──X─", " │ ", "q1_0: |0>─X────", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.swap(qr1, qr2) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_reverse_bits_read_from_config(self): """Swap drawing with reverse_bits set in the configuration file.""" expected_forward = "\n".join( [ " ", "q1_0: ─X────", " │ ", "q1_1: ─┼──X─", " │ │ ", "q2_0: ─X──┼─", " │ ", "q2_1: ────X─", " ", ] ) expected_reverse = "\n".join( [ " ", "q2_1: ────X─", " │ ", "q2_0: ─X──┼─", " │ │ ", "q1_1: ─┼──X─", " │ ", "q1_0: ─X────", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.swap(qr1, qr2) self.assertEqual(str(circuit_drawer(circuit, output="text")), expected_forward) config_content = """ [default] circuit_reverse_bits = true """ with tempfile.TemporaryDirectory() as dir_path: file_path = pathlib.Path(dir_path) / "qiskit.conf" with open(file_path, "w") as fptr: fptr.write(config_content) with unittest.mock.patch.dict(os.environ, {"QISKIT_SETTINGS": str(file_path)}): test_reverse = str(circuit_drawer(circuit, output="text")) self.assertEqual(test_reverse, expected_reverse) def test_text_cswap(self): """CSwap drawing.""" expected = "\n".join( [ " ", "q_0: |0>─■──X──X─", " │ │ │ ", "q_1: |0>─X──■──X─", " │ │ │ ", "q_2: |0>─X──X──■─", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.cswap(qr[1], qr[0], qr[2]) circuit.cswap(qr[2], qr[1], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cswap_reverse_bits(self): """CSwap drawing with reverse_bits.""" expected = "\n".join( [ " ", "q_2: |0>─X──X──■─", " │ │ │ ", "q_1: |0>─X──■──X─", " │ │ │ ", "q_0: |0>─■──X──X─", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cswap(qr[0], qr[1], qr[2]) circuit.cswap(qr[1], qr[0], qr[2]) circuit.cswap(qr[2], qr[1], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_cu3(self): """cu3 drawing.""" expected = "\n".join( [ " ┌─────────────────┐", "q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├", " ┌────────┴────────┐└────────┬────────┘", "q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────", " └─────────────────┘ │ ", "q_2: |0>────────────────────────────■─────────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cu3_reverse_bits(self): """cu3 drawing with reverse_bits""" expected = "\n".join( [ " ", "q_2: |0>────────────────────────────■─────────", " ┌─────────────────┐ │ ", "q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────", " └────────┬────────┘┌────────┴────────┐", "q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├", " └─────────────────┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_crz(self): """crz drawing.""" expected = "\n".join( [ " ┌─────────┐", "q_0: |0>─────■─────┤ Rz(π/2) ├", " ┌────┴────┐└────┬────┘", "q_1: |0>┤ Rz(π/2) ├─────┼─────", " └─────────┘ │ ", "q_2: |0>────────────────■─────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.crz(pi / 2, qr[0], qr[1]) circuit.crz(pi / 2, qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cry(self): """cry drawing.""" expected = "\n".join( [ " ┌─────────┐", "q_0: |0>─────■─────┤ Ry(π/2) ├", " ┌────┴────┐└────┬────┘", "q_1: |0>┤ Ry(π/2) ├─────┼─────", " └─────────┘ │ ", "q_2: |0>────────────────■─────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cry(pi / 2, qr[0], qr[1]) circuit.cry(pi / 2, qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_crx(self): """crx drawing.""" expected = "\n".join( [ " ┌─────────┐", "q_0: |0>─────■─────┤ Rx(π/2) ├", " ┌────┴────┐└────┬────┘", "q_1: |0>┤ Rx(π/2) ├─────┼─────", " └─────────┘ │ ", "q_2: |0>────────────────■─────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.crx(pi / 2, qr[0], qr[1]) circuit.crx(pi / 2, qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cx(self): """cx drawing.""" expected = "\n".join( [ " ┌───┐", "q_0: |0>──■──┤ X ├", " ┌─┴─┐└─┬─┘", "q_1: |0>┤ X ├──┼──", " └───┘ │ ", "q_2: |0>───────■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.cx(qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cy(self): """cy drawing.""" expected = "\n".join( [ " ┌───┐", "q_0: |0>──■──┤ Y ├", " ┌─┴─┐└─┬─┘", "q_1: |0>┤ Y ├──┼──", " └───┘ │ ", "q_2: |0>───────■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cy(qr[0], qr[1]) circuit.cy(qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cz(self): """cz drawing.""" expected = "\n".join( [ " ", "q_0: |0>─■──■─", " │ │ ", "q_1: |0>─■──┼─", " │ ", "q_2: |0>────■─", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.cz(qr[0], qr[1]) circuit.cz(qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_ch(self): """ch drawing.""" expected = "\n".join( [ " ┌───┐", "q_0: |0>──■──┤ H ├", " ┌─┴─┐└─┬─┘", "q_1: |0>┤ H ├──┼──", " └───┘ │ ", "q_2: |0>───────■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.ch(qr[0], qr[1]) circuit.ch(qr[2], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_rzz(self): """rzz drawing. See #1957""" expected = "\n".join( [ " ", "q_0: |0>─■────────────────", " │ZZ(0) ", "q_1: |0>─■───────■────────", " │ZZ(π/2) ", "q_2: |0>─────────■────────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.rzz(0, qr[0], qr[1]) circuit.rzz(pi / 2, qr[2], qr[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cu1(self): """cu1 drawing.""" expected = "\n".join( [ " ", "q_0: |0>─■─────────■────────", " │U1(π/2) │ ", "q_1: |0>─■─────────┼────────", " │U1(π/2) ", "q_2: |0>───────────■────────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]]) circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cp(self): """cp drawing.""" expected = "\n".join( [ " ", "q_0: |0>─■────────■───────", " │P(π/2) │ ", "q_1: |0>─■────────┼───────", " │P(π/2) ", "q_2: |0>──────────■───────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]) circuit.append(CPhaseGate(pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_cu1_condition(self): """Test cu1 with condition""" expected = "\n".join( [ " ", "q_0: ────────■────────", " │U1(π/2) ", "q_1: ────────■────────", " ║ ", "q_2: ────────╫────────", " ┌────╨────┐ ", "c: 3/═══╡ c_1=0x1 ╞═══", " └─────────┘ ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected) def test_text_rzz_condition(self): """Test rzz with condition""" expected = "\n".join( [ " ", "q_0: ────────■────────", " │ZZ(π/2) ", "q_1: ────────■────────", " ║ ", "q_2: ────────╫────────", " ┌────╨────┐ ", "c: 3/═══╡ c_1=0x1 ╞═══", " └─────────┘ ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.append(RZZGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected) def test_text_cp_condition(self): """Test cp with condition""" expected = "\n".join( [ " ", "q_0: ───────■───────", " │P(π/2) ", "q_1: ───────■───────", " ║ ", "q_2: ───────╫───────", " ┌────╨────┐ ", "c: 3/══╡ c_1=0x1 ╞══", " └─────────┘ ", ] ) qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1) self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected) def test_text_cu1_reverse_bits(self): """cu1 drawing with reverse_bits""" expected = "\n".join( [ " ", "q_2: |0>───────────■────────", " │ ", "q_1: |0>─■─────────┼────────", " │U1(π/2) │U1(π/2) ", "q_0: |0>─■─────────■────────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]]) circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_text_ccx(self): """cx drawing.""" expected = "\n".join( [ " ┌───┐", "q_0: |0>──■────■──┤ X ├", " │ ┌─┴─┐└─┬─┘", "q_1: |0>──■──┤ X ├──■──", " ┌─┴─┐└─┬─┘ │ ", "q_2: |0>┤ X ├──■────■──", " └───┘ ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.ccx(qr[0], qr[1], qr[2]) circuit.ccx(qr[2], qr[0], qr[1]) circuit.ccx(qr[2], qr[1], qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_reset(self): """Reset drawing.""" expected = "\n".join( [ " ", "q1_0: |0>─|0>─", " ", "q1_1: |0>─|0>─", " ", "q2_0: |0>─────", " ", "q2_1: |0>─|0>─", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.reset(qr1) circuit.reset(qr2[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_single_gate(self): """Single Qbit gate drawing.""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>┤ H ├", " ├───┤", "q1_1: |0>┤ H ├", " └───┘", "q2_0: |0>─────", " ┌───┐", "q2_1: |0>┤ H ├", " └───┘", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.h(qr1) circuit.h(qr2[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_id(self): """Id drawing.""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>┤ I ├", " ├───┤", "q1_1: |0>┤ I ├", " └───┘", "q2_0: |0>─────", " ┌───┐", "q2_1: |0>┤ I ├", " └───┘", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.id(qr1) circuit.id(qr2[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_barrier(self): """Barrier drawing.""" expected = "\n".join( [ " ░ ", "q1_0: |0>─░─", " ░ ", "q1_1: |0>─░─", " ░ ", "q2_0: |0>───", " ░ ", "q2_1: |0>─░─", " ░ ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.barrier(qr1) circuit.barrier(qr2[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_no_barriers(self): """Drawing without plotbarriers.""" expected = "\n".join( [ " ┌───┐ ", "q1_0: |0>┤ H ├─────", " ├───┤ ", "q1_1: |0>┤ H ├─────", " ├───┤ ", "q2_0: |0>┤ H ├─────", " └───┘┌───┐", "q2_1: |0>─────┤ H ├", " └───┘", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.h(qr1) circuit.barrier(qr1) circuit.barrier(qr2[1]) circuit.h(qr2) self.assertEqual(str(_text_circuit_drawer(circuit, plot_barriers=False)), expected) def test_text_measure_html(self): """The measure operator. HTML representation.""" expected = "\n".join( [ '<pre style="word-wrap: normal;' "white-space: pre;" "background: #fff0;" "line-height: 1.1;" 'font-family: &quot;Courier New&quot;,Courier,monospace">' " ┌─┐", " q: |0>┤M├", " └╥┘", "c: 0 1/═╩═", " 0 </pre>", ] ) qr = QuantumRegister(1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(_text_circuit_drawer(circuit)._repr_html_(), expected) def test_text_repr(self): """The measure operator. repr.""" expected = "\n".join( [ " ┌─┐", " q: |0>┤M├", " └╥┘", "c: 0 1/═╩═", " 0 ", ] ) qr = QuantumRegister(1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) self.assertEqual(_text_circuit_drawer(circuit).__repr__(), expected) def test_text_justify_left(self): """Drawing with left justify""" expected = "\n".join( [ " ┌───┐ ", "q1_0: |0>┤ X ├───", " ├───┤┌─┐", "q1_1: |0>┤ H ├┤M├", " └───┘└╥┘", " c1: 0 2/══════╩═", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.h(qr1[1]) circuit.measure(qr1[1], cr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_justify_right(self): """Drawing with right justify""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>─────┤ X ├", " ┌───┐└┬─┬┘", "q1_1: |0>┤ H ├─┤M├─", " └───┘ └╥┘ ", " c1: 0 2/═══════╩══", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.h(qr1[1]) circuit.measure(qr1[1], cr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected) def test_text_justify_none(self): """Drawing with none justify""" expected = "\n".join( [ " ┌───┐ ", "q1_0: |0>┤ X ├────────", " └───┘┌───┐┌─┐", "q1_1: |0>─────┤ H ├┤M├", " └───┘└╥┘", " c1: 0 2/═══════════╩═", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.h(qr1[1]) circuit.measure(qr1[1], cr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="none")), expected) def test_text_justify_left_barrier(self): """Left justify respects barriers""" expected = "\n".join( [ " ┌───┐ ░ ", "q1_0: |0>┤ H ├─░──────", " └───┘ ░ ┌───┐", "q1_1: |0>──────░─┤ H ├", " ░ └───┘", ] ) qr1 = QuantumRegister(2, "q1") circuit = QuantumCircuit(qr1) circuit.h(qr1[0]) circuit.barrier(qr1) circuit.h(qr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_justify_right_barrier(self): """Right justify respects barriers""" expected = "\n".join( [ " ┌───┐ ░ ", "q1_0: |0>┤ H ├─░──────", " └───┘ ░ ┌───┐", "q1_1: |0>──────░─┤ H ├", " ░ └───┘", ] ) qr1 = QuantumRegister(2, "q1") circuit = QuantumCircuit(qr1) circuit.h(qr1[0]) circuit.barrier(qr1) circuit.h(qr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected) def test_text_barrier_label(self): """Show barrier label""" expected = "\n".join( [ " ┌───┐ ░ ┌───┐ End Y/X ", "q_0: |0>┤ X ├─░─┤ Y ├────░────", " ├───┤ ░ ├───┤ ░ ", "q_1: |0>┤ Y ├─░─┤ X ├────░────", " └───┘ ░ └───┘ ░ ", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.x(0) circuit.y(1) circuit.barrier() circuit.y(0) circuit.x(1) circuit.barrier(label="End Y/X") self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_overlap_cx(self): """Overlapping CX gates are drawn not overlapping""" expected = "\n".join( [ " ", "q1_0: |0>──■───────", " │ ", "q1_1: |0>──┼────■──", " │ ┌─┴─┐", "q1_2: |0>──┼──┤ X ├", " ┌─┴─┐└───┘", "q1_3: |0>┤ X ├─────", " └───┘ ", ] ) qr1 = QuantumRegister(4, "q1") circuit = QuantumCircuit(qr1) circuit.cx(qr1[0], qr1[3]) circuit.cx(qr1[1], qr1[2]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_overlap_measure(self): """Measure is drawn not overlapping""" expected = "\n".join( [ " ┌─┐ ", "q1_0: |0>┤M├─────", " └╥┘┌───┐", "q1_1: |0>─╫─┤ X ├", " ║ └───┘", " c1: 0 2/═╩══════", " 0 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.measure(qr1[0], cr1[0]) circuit.x(qr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_overlap_swap(self): """Swap is drawn in 2 separate columns""" expected = "\n".join( [ " ", "q1_0: |0>─X────", " │ ", "q1_1: |0>─┼──X─", " │ │ ", "q2_0: |0>─X──┼─", " │ ", "q2_1: |0>────X─", " ", ] ) qr1 = QuantumRegister(2, "q1") qr2 = QuantumRegister(2, "q2") circuit = QuantumCircuit(qr1, qr2) circuit.swap(qr1, qr2) self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected) def test_text_justify_right_measure_resize(self): """Measure gate can resize if necessary""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>┤ X ├", " └┬─┬┘", "q1_1: |0>─┤M├─", " └╥┘ ", " c1: 0 2/══╩══", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.measure(qr1[1], cr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected) def test_text_box_length(self): """The length of boxes is independent of other boxes in the layer https://github.com/Qiskit/qiskit-terra/issues/1882""" expected = "\n".join( [ " ┌───┐ ┌───┐", "q1_0: |0>────┤ H ├────┤ H ├", " └───┘ └───┘", "q1_1: |0>──────────────────", " ┌───────────┐ ", "q1_2: |0>┤ Rz(1e-07) ├─────", " └───────────┘ ", ] ) qr = QuantumRegister(3, "q1") circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.rz(0.0000001, qr[2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_spacing_2378(self): """Small gates in the same layer as long gates. See https://github.com/Qiskit/qiskit-terra/issues/2378""" expected = "\n".join( [ " ", "q_0: |0>──────X──────", " │ ", "q_1: |0>──────X──────", " ┌───────────┐", "q_2: |0>┤ Rz(11111) ├", " └───────────┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.swap(qr[0], qr[1]) circuit.rz(11111, qr[2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) @unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.") def test_text_synth_no_registerless(self): """Test synthesis's label when registerless=False. See https://github.com/Qiskit/qiskit-terra/issues/9363""" expected = "\n".join( [ " ", " a: |0>──■──", " │ ", " b: |0>──■──", " │ ", " c: |0>──o──", " ┌─┴─┐", "return: |0>┤ X ├", " └───┘", ] ) @classical_function def grover_oracle(a: Int1, b: Int1, c: Int1) -> Int1: return a and b and not c circuit = grover_oracle.synth(registerless=False) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextDrawerLabels(QiskitTestCase): """Gates with labels.""" def test_label(self): """Test a gate with a label.""" # fmt: off expected = "\n".join([" ┌───────────┐", "q: |0>┤ an H gate ├", " └───────────┘"]) # fmt: on circuit = QuantumCircuit(1) circuit.append(HGate(label="an H gate"), [0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_gate_with_label(self): """Test a controlled gate-with-a-label.""" expected = "\n".join( [ " ", "q_0: |0>──────■──────", " ┌─────┴─────┐", "q_1: |0>┤ an H gate ├", " └───────────┘", ] ) circuit = QuantumCircuit(2) circuit.append(HGate(label="an H gate").control(1), [0, 1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_label_on_controlled_gate(self): """Test a controlled gate with a label (as a as a whole).""" expected = "\n".join( [ " a controlled H gate ", "q_0: |0>──────────■──────────", " ┌─┴─┐ ", "q_1: |0>────────┤ H ├────────", " └───┘ ", ] ) circuit = QuantumCircuit(2) circuit.append(HGate().control(1, label="a controlled H gate"), [0, 1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_rzz_on_wide_layer(self): """Test a labeled gate (RZZ) in a wide layer. See https://github.com/Qiskit/qiskit-terra/issues/4838""" expected = "\n".join( [ " ", "q_0: |0>────────────────■──────────────────────", " │ZZ(π/2) ", "q_1: |0>────────────────■──────────────────────", " ┌─────────────────────────────────────┐", "q_2: |0>┤ This is a really long long long box ├", " └─────────────────────────────────────┘", ] ) circuit = QuantumCircuit(3) circuit.rzz(pi / 2, 0, 1) circuit.x(2, label="This is a really long long long box") self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cu1_on_wide_layer(self): """Test a labeled gate (CU1) in a wide layer. See https://github.com/Qiskit/qiskit-terra/issues/4838""" expected = "\n".join( [ " ", "q_0: |0>────────────────■──────────────────────", " │U1(π/2) ", "q_1: |0>────────────────■──────────────────────", " ┌─────────────────────────────────────┐", "q_2: |0>┤ This is a really long long long box ├", " └─────────────────────────────────────┘", ] ) circuit = QuantumCircuit(3) circuit.append(CU1Gate(pi / 2), [0, 1]) circuit.x(2, label="This is a really long long long box") self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextDrawerMultiQGates(QiskitTestCase): """Gates implying multiple qubits.""" def test_2Qgate(self): """2Q no params.""" expected = "\n".join( [ " ┌───────┐", "q_1: |0>┤1 ├", " │ twoQ │", "q_0: |0>┤0 ├", " └───────┘", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ") circuit.append(my_gate2, [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_2Qgate_cross_wires(self): """2Q no params, with cross wires""" expected = "\n".join( [ " ┌───────┐", "q_1: |0>┤0 ├", " │ twoQ │", "q_0: |0>┤1 ├", " └───────┘", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ") circuit.append(my_gate2, [qr[1], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_3Qgate_cross_wires(self): """3Q no params, with cross wires""" expected = "\n".join( [ " ┌─────────┐", "q_2: |0>┤1 ├", " │ │", "q_1: |0>┤0 threeQ ├", " │ │", "q_0: |0>┤2 ├", " └─────────┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) my_gate3 = Gate(name="threeQ", num_qubits=3, params=[], label="threeQ") circuit.append(my_gate3, [qr[1], qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_2Qgate_nottogether(self): """2Q that are not together""" expected = "\n".join( [ " ┌───────┐", "q_2: |0>┤1 ├", " │ │", "q_1: |0>┤ twoQ ├", " │ │", "q_0: |0>┤0 ├", " └───────┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ") circuit.append(my_gate2, [qr[0], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_2Qgate_nottogether_across_4(self): """2Q that are 2 bits apart""" expected = "\n".join( [ " ┌───────┐", "q_3: |0>┤1 ├", " │ │", "q_2: |0>┤ ├", " │ twoQ │", "q_1: |0>┤ ├", " │ │", "q_0: |0>┤0 ├", " └───────┘", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ") circuit.append(my_gate2, [qr[0], qr[3]]) self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected) def test_unitary_nottogether_across_4(self): """unitary that are 2 bits apart""" expected = "\n".join( [ " ┌──────────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>┤ ├", " │ Unitary │", "q_2: |0>┤ ├", " │ │", "q_3: |0>┤1 ├", " └──────────┘", ] ) qr = QuantumRegister(4, "q") qc = QuantumCircuit(qr) qc.append(random_unitary(4, seed=42), [qr[0], qr[3]]) self.assertEqual(str(_text_circuit_drawer(qc)), expected) def test_kraus(self): """Test Kraus. See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014""" # fmt: off expected = "\n".join([" ┌───────┐", "q: |0>┤ kraus ├", " └───────┘"]) # fmt: on error = SuperOp(0.75 * numpy.eye(4) + 0.25 * numpy.diag([1, -1, -1, 1])) qr = QuantumRegister(1, name="q") qc = QuantumCircuit(qr) qc.append(error, [qr[0]]) self.assertEqual(str(_text_circuit_drawer(qc)), expected) def test_multiplexer(self): """Test Multiplexer. See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014""" expected = "\n".join( [ " ┌──────────────┐", "q_0: |0>┤0 ├", " │ Multiplexer │", "q_1: |0>┤1 ├", " └──────────────┘", ] ) cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])]) qr = QuantumRegister(2, name="q") qc = QuantumCircuit(qr) qc.append(cx_multiplexer, [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(qc)), expected) def test_label_over_name_2286(self): """If there is a label, it should be used instead of the name See https://github.com/Qiskit/qiskit-terra/issues/2286""" expected = "\n".join( [ " ┌───┐┌───────┐┌────────┐", "q_0: |0>┤ X ├┤ alt-X ├┤0 ├", " └───┘└───────┘│ iswap │", "q_1: |0>──────────────┤1 ├", " └────────┘", ] ) qr = QuantumRegister(2, "q") circ = QuantumCircuit(qr) circ.append(XGate(), [qr[0]]) circ.append(XGate(label="alt-X"), [qr[0]]) circ.append(UnitaryGate(numpy.eye(4), label="iswap"), [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circ)), expected) def test_label_turns_to_box_2286(self): """If there is a label, non-boxes turn into boxes See https://github.com/Qiskit/qiskit-terra/issues/2286""" expected = "\n".join( [ " cz label ", "q_0: |0>─■─────■─────", " │ │ ", "q_1: |0>─■─────■─────", " ", ] ) qr = QuantumRegister(2, "q") circ = QuantumCircuit(qr) circ.append(CZGate(), [qr[0], qr[1]]) circ.append(CZGate(label="cz label"), [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circ)), expected) def test_control_gate_with_base_label_4361(self): """Control gate has a label and a base gate with a label See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐ my ch ┌──────┐", "q_0: |0>┤ my h ├───■────┤ my h ├", " └──────┘┌──┴───┐└──┬───┘", "q_1: |0>────────┤ my h ├───■────", " └──────┘ my ch ", ] ) qr = QuantumRegister(2, "q") circ = QuantumCircuit(qr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch") circ.append(hgate, [0]) circ.append(controlh, [0, 1]) circ.append(controlh, [1, 0]) self.assertEqual(str(_text_circuit_drawer(circ)), expected) def test_control_gate_label_with_cond_1_low(self): """Control gate has a label and a conditional (compression=low) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " │ ", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="low")), expected) def test_control_gate_label_with_cond_1_low_cregbundle(self): """Control gate has a label and a conditional (compression=low) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " │ ", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected ) def test_control_gate_label_with_cond_1_med(self): """Control gate has a label and a conditional (compression=med) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " c: 0 ═══■════", " 0x1 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")), expected, ) def test_control_gate_label_with_cond_1_med_cregbundle(self): """Control gate has a label and a conditional (compression=med) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)), expected, ) def test_control_gate_label_with_cond_1_high(self): """Control gate has a label and a conditional (compression=high) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤ my h ├", " └──╥───┘", " c: 0 ═══■════", " 0x1 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="high")), expected ) def test_control_gate_label_with_cond_1_high_cregbundle(self): """Control gate has a label and a conditional (compression=high) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " my ch ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤ my h ├", " ├──╨──┬┘", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [0, 1]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="high", cregbundle=True)), expected ) def test_control_gate_label_with_cond_2_med_space(self): """Control gate has a label and a conditional (on label, compression=med) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤ my h ├", " └──┬───┘", "q_1: |0>───■────", " my ch ", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="medium")), expected) def test_control_gate_label_with_cond_2_med(self): """Control gate has a label and a conditional (on label, compression=med) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐ ", "q_0: |0>──┤ my h ├─", " └──┬───┘ ", "q_1: |0>─────■─────", " my ctrl-h ", " ║ ", " c: 0 ═════■═════", " 0x1 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ctrl-h").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual( str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")), expected, ) def test_control_gate_label_with_cond_2_med_cregbundle(self): """Control gate has a label and a conditional (on label, compression=med) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤ my h ├", " └──┬───┘", "q_1: |0>───■────", " my ch ", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)), expected, ) def test_control_gate_label_with_cond_2_low(self): """Control gate has a label and a conditional (on label, compression=low) See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤ my h ├", " └──┬───┘", " │ ", "q_1: |0>───■────", " my ch ", " ║ ", " c: 0 ═══■════", " 0x1 ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual( str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="low")), expected ) def test_control_gate_label_with_cond_2_low_cregbundle(self): """Control gate has a label and a conditional (on label, compression=low) with cregbundle See https://github.com/Qiskit/qiskit-terra/issues/4361""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤ my h ├", " └──┬───┘", " │ ", "q_1: |0>───■────", " my ch ", " ┌──╨──┐ ", " c: 0 1/╡ 0x1 ╞═", " └─────┘ ", ] ) qr = QuantumRegister(2, "q") cr = ClassicalRegister(1, "c") circ = QuantumCircuit(qr, cr) hgate = HGate(label="my h") controlh = hgate.control(label="my ch").c_if(cr, 1) circ.append(controlh, [1, 0]) self.assertEqual( str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected ) class TestTextDrawerParams(QiskitTestCase): """Test drawing parameters.""" def test_text_no_parameters(self): """Test drawing with no parameters""" expected = "\n".join( [ " ┌───┐", "q: |0>┤ X ├", " └───┘", ] ) qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.x(0) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_parameters_mix(self): """cu3 drawing with parameters""" expected = "\n".join( [ " ", "q_0: |0>─────────■──────────", " ┌────────┴─────────┐", "q_1: |0>┤ U(π/2,theta,π,0) ├", " └──────────────────┘", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.cu(pi / 2, Parameter("theta"), pi, 0, qr[0], qr[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_bound_parameters(self): """Bound parameters See: https://github.com/Qiskit/qiskit-terra/pull/3876""" # fmt: off expected = "\n".join([" ┌────────────┐", "qr: |0>┤ my_u2(π,π) ├", " └────────────┘"]) # fmt: on my_u2_circuit = QuantumCircuit(1, name="my_u2") phi = Parameter("phi") lam = Parameter("lambda") my_u2_circuit.u(3.141592653589793, phi, lam, 0) my_u2 = my_u2_circuit.to_gate() qr = QuantumRegister(1, name="qr") circuit = QuantumCircuit(qr, name="circuit") circuit.append(my_u2, [qr[0]]) circuit = circuit.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793}) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_pi_param_expr(self): """Text pi in circuit with parameter expression.""" expected = "\n".join( [ " ┌─────────────────────┐", "q: ┤ Rx((π - x)*(π - y)) ├", " └─────────────────────┘", ] ) x, y = Parameter("x"), Parameter("y") circuit = QuantumCircuit(1) circuit.rx((pi - x) * (pi - y), 0) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_text_utf8(self): """Test that utf8 characters work in windows CI env.""" # fmt: off expected = "\n".join([" ┌──────────┐", "q: ┤ U(0,φ,λ) ├", " └──────────┘"]) # fmt: on phi, lam = Parameter("φ"), Parameter("λ") circuit = QuantumCircuit(1) circuit.u(0, phi, lam, 0) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_text_ndarray_parameters(self): """Test that if params are type ndarray, params are not displayed.""" # fmt: off expected = "\n".join([" ┌─────────┐", "q: |0>┤ Unitary ├", " └─────────┘"]) # fmt: on qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.unitary(numpy.array([[0, 1], [1, 0]]), 0) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_qc_parameters(self): """Test that if params are type QuantumCircuit, params are not displayed.""" expected = "\n".join( [ " ┌───────┐", "q_0: |0>┤0 ├", " │ name │", "q_1: |0>┤1 ├", " └───────┘", ] ) my_qc_param = QuantumCircuit(2) my_qc_param.h(0) my_qc_param.cx(0, 1) inst = Instruction("name", 2, 0, [my_qc_param]) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.append(inst, [0, 1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextDrawerVerticalCompressionLow(QiskitTestCase): """Test vertical_compression='low'""" def test_text_conditional_1(self): """Conditional drawing with 1-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", "q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", " ║ ║ ", "c0: 0 ══■════╬══", " 0x1 ║ ", " ║ ", "c1: 0 ═══════■══", " 0x1 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="low")), expected, ) def test_text_conditional_1_bundle(self): """Conditional drawing with 1-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " └─╥─┘ └─╥─┘ ", " ┌──╨──┐ ║ ", "c0: 0 1/╡ 0x1 ╞═══╬═══", " └─────┘ ║ ", " ┌──╨──┐", "c1: 0 1/═══════╡ 0x1 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="low", cregbundle=True)), expected, ) def test_text_conditional_reverse_bits_true(self): """Conditional drawing with 1-bit-length regs.""" 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) expected = "\n".join( [ " ┌───┐ ┌─┐ ┌───┐", "qr_2: |0>┤ H ├─────┤M├─────┤ X ├", " └───┘ └╥┘ └─╥─┘", " ┌───┐ ║ ║ ", "qr_1: |0>┤ H ├──────╫────────╫──", " └───┘ ║ ║ ", " ┌───┐┌───┐ ║ ┌───┐ ║ ", "qr_0: |0>┤ H ├┤ X ├─╫─┤ X ├──╫──", " └───┘└───┘ ║ └───┘ ║ ", " ║ ║ ", " cr2: 0 ═══════════╬════════╬══", " ║ ║ ", " ║ ║ ", " cr_1: 0 ═══════════╩════════■══", " ║ ", " ║ ", " cr_0: 0 ════════════════════o══", " 0x2 ", ] ) self.assertEqual( str( _text_circuit_drawer( circuit, vertical_compression="low", cregbundle=False, reverse_bits=True ) ), expected, ) def test_text_conditional_reverse_bits_false(self): """Conditional drawing with 1-bit-length regs.""" 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) expected = "\n".join( [ " ┌───┐┌───┐┌───┐", "qr_0: |0>┤ H ├┤ X ├┤ X ├", " └───┘└───┘└───┘", " ┌───┐ ", "qr_1: |0>┤ H ├──────────", " └───┘ ", " ┌───┐ ┌─┐ ┌───┐", "qr_2: |0>┤ H ├─┤M├─┤ X ├", " └───┘ └╥┘ └─╥─┘", " ║ ║ ", " cr_0: 0 ═══════╬════o══", " ║ ║ ", " ║ ║ ", " cr_1: 0 ═══════╩════■══", " 0x2 ", " ", " cr2: 0 ═══════════════", " ", ] ) self.assertEqual( str( _text_circuit_drawer( circuit, vertical_compression="low", cregbundle=False, reverse_bits=False ) ), expected, ) def test_text_justify_right(self): """Drawing with right justify""" expected = "\n".join( [ " ┌───┐", "q1_0: |0>─────┤ X ├", " └───┘", " ┌───┐ ┌─┐ ", "q1_1: |0>┤ H ├─┤M├─", " └───┘ └╥┘ ", " ║ ", " c1: 0 2/═══════╩══", " 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") circuit = QuantumCircuit(qr1, cr1) circuit.x(qr1[0]) circuit.h(qr1[1]) circuit.measure(qr1[1], cr1[1]) self.assertEqual( str(_text_circuit_drawer(circuit, justify="right", vertical_compression="low")), expected, ) class TestTextDrawerVerticalCompressionMedium(QiskitTestCase): """Test vertical_compression='medium'""" def test_text_conditional_1(self): """Medium vertical compression avoids box overlap.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", "q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0: 0 ══■════╬══", " 0x1 ║ ", "c1: 0 ═══════■══", " 0x1 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")), expected, ) def test_text_conditional_1_bundle(self): """Medium vertical compression avoids box overlap.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " └─╥─┘ └─╥─┘ ", " ┌──╨──┐ ║ ", "c0: 0 1/╡ 0x1 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 1/═══════╡ 0x1 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)), expected, ) def test_text_measure_with_spaces(self): """Measure wire might have extra spaces Found while reproducing https://quantumcomputing.stackexchange.com/q/10194/1859""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[3]; measure q[0] -> c[1]; if(c==1) x q[1]; """ expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├─────", " └╥┘┌───┐", "q_1: |0>─╫─┤ X ├", " ║ └─╥─┘", " c_0: 0 ═╬═══■══", " ║ ║ ", " c_1: 0 ═╩═══o══", " ║ ", " c_2: 0 ═════o══", " 0x1 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")), expected, ) def test_text_measure_with_spaces_bundle(self): """Measure wire might have extra spaces Found while reproducing https://quantumcomputing.stackexchange.com/q/10194/1859""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[3]; measure q[0] -> c[1]; if(c==1) x q[1]; """ expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├───────", " └╥┘ ┌───┐ ", "q_1: |0>─╫──┤ X ├─", " ║ └─╥─┘ ", " ║ ┌──╨──┐", " c: 0 3/═╩═╡ 0x1 ╞", " 1 └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)), expected, ) def test_text_barrier_med_compress_1(self): """Medium vertical compression avoids connection break.""" circuit = QuantumCircuit(4) circuit.cx(1, 3) circuit.x(1) circuit.barrier((2, 3), label="Bar 1") expected = "\n".join( [ " ", "q_0: |0>────────────", " ┌───┐ ", "q_1: |0>──■───┤ X ├─", " │ └───┘ ", " │ Bar 1 ", "q_2: |0>──┼─────░───", " ┌─┴─┐ ░ ", "q_3: |0>┤ X ├───░───", " └───┘ ░ ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)), expected, ) def test_text_barrier_med_compress_2(self): """Medium vertical compression avoids overprint.""" circuit = QuantumCircuit(4) circuit.barrier((0, 1, 2), label="a") circuit.cx(1, 3) circuit.x(1) circuit.barrier((2, 3), label="Bar 1") expected = "\n".join( [ " a ", "q_0: |0>─░─────────────", " ░ ┌───┐ ", "q_1: |0>─░───■───┤ X ├─", " ░ │ └───┘ ", " ░ │ Bar 1 ", "q_2: |0>─░───┼─────░───", " ░ ┌─┴─┐ ░ ", "q_3: |0>───┤ X ├───░───", " └───┘ ░ ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)), expected, ) def test_text_barrier_med_compress_3(self): """Medium vertical compression avoids conditional connection break.""" qr = QuantumRegister(1, "qr") qc1 = ClassicalRegister(3, "cr") qc2 = ClassicalRegister(1, "cr2") circuit = QuantumCircuit(qr, qc1, qc2) circuit.x(0).c_if(qc1, 3) circuit.x(0).c_if(qc2[0], 1) expected = "\n".join( [ " ┌───┐┌───┐", " qr: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "cr_0: 0 ══■════╬══", " ║ ║ ", "cr_2: 0 ══o════╬══", " ║ ║ ", " cr2: 0 ══╬════■══", " ║ ", "cr_1: 0 ══■═══════", " 0x3 ", ] ) self.assertEqual( str( _text_circuit_drawer( circuit, vertical_compression="medium", wire_order=[0, 1, 3, 4, 2], cregbundle=False, ) ), expected, ) class TestTextConditional(QiskitTestCase): """Gates with conditionals""" def test_text_conditional_1_cregbundle(self): """Conditional drawing with 1-bit-length regs and cregbundle.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " ┌┴─╨─┴┐ └─╥─┘ ", "c0: 0 1/╡ 0x1 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 1/═══════╡ 0x1 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_1(self): """Conditional drawing with 1-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[1]; creg c1[1]; if(c0==1) x q[0]; if(c1==1) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", "q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0: 0 ══■════╬══", " 0x1 ║ ", "c1: 0 ═══════■══", " 0x1 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_2_cregbundle(self): """Conditional drawing with 2-bit-length regs with cregbundle""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[2]; creg c1[2]; if(c0==2) x q[0]; if(c1==2) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " ┌┴─╨─┴┐ └─╥─┘ ", "c0: 0 2/╡ 0x2 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 2/═══════╡ 0x2 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_2(self): """Conditional drawing with 2-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[2]; creg c1[2]; if(c0==2) x q[0]; if(c1==2) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", " q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0_0: 0 ══o════╬══", " ║ ║ ", "c0_1: 0 ══■════╬══", " 0x2 ║ ", "c1_0: 0 ═══════o══", " ║ ", "c1_1: 0 ═══════■══", " 0x2 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_3_cregbundle(self): """Conditional drawing with 3-bit-length regs with cregbundle.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[3]; creg c1[3]; if(c0==3) x q[0]; if(c1==3) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " ┌┴─╨─┴┐ └─╥─┘ ", "c0: 0 3/╡ 0x3 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 3/═══════╡ 0x3 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_3(self): """Conditional drawing with 3-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[3]; creg c1[3]; if(c0==3) x q[0]; if(c1==3) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", " q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0_0: 0 ══■════╬══", " ║ ║ ", "c0_1: 0 ══■════╬══", " ║ ║ ", "c0_2: 0 ══o════╬══", " 0x3 ║ ", "c1_0: 0 ═══════■══", " ║ ", "c1_1: 0 ═══════■══", " ║ ", "c1_2: 0 ═══════o══", " 0x3 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_4(self): """Conditional drawing with 4-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[4]; creg c1[4]; if(c0==4) x q[0]; if(c1==4) x q[0]; """ expected = "\n".join( [ " ┌───┐ ┌───┐ ", " q: |0>─┤ X ├──┤ X ├─", " ┌┴─╨─┴┐ └─╥─┘ ", "c0: 0 4/╡ 0x4 ╞═══╬═══", " └─────┘┌──╨──┐", "c1: 0 4/═══════╡ 0x4 ╞", " └─────┘", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_conditional_5(self): """Conditional drawing with 5-bit-length regs.""" qasm_string = """ OPENQASM 2.0; include "qelib1.inc"; qreg q[1]; creg c0[5]; creg c1[5]; if(c0==5) x q[0]; if(c1==5) x q[0]; """ expected = "\n".join( [ " ┌───┐┌───┐", " q: |0>┤ X ├┤ X ├", " └─╥─┘└─╥─┘", "c0_0: 0 ══■════╬══", " ║ ║ ", "c0_1: 0 ══o════╬══", " ║ ║ ", "c0_2: 0 ══■════╬══", " ║ ║ ", "c0_3: 0 ══o════╬══", " ║ ║ ", "c0_4: 0 ══o════╬══", " 0x5 ║ ", "c1_0: 0 ═══════■══", " ║ ", "c1_1: 0 ═══════o══", " ║ ", "c1_2: 0 ═══════■══", " ║ ", "c1_3: 0 ═══════o══", " ║ ", "c1_4: 0 ═══════o══", " 0x5 ", ] ) circuit = QuantumCircuit.from_qasm_str(qasm_string) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cz_no_space_cregbundle(self): """Conditional CZ without space""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───■───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cz_no_space(self): """Conditional CZ without space""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──■──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cz_cregbundle(self): """Conditional CZ with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───■───", " ║ ", "qr_2: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cz(self): """Conditional CZ with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cz(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──■──", " ║ ", "qr_2: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cx_ct_cregbundle(self): """Conditional CX (control-target) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " ┌─┴─┐ ", "qr_1: |0>─┤ X ├─", " └─╥─┘ ", "qr_2: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cx_ct(self): """Conditional CX (control-target) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " ┌─┴─┐", "qr_1: |0>┤ X ├", " └─╥─┘", "qr_2: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cx_tc_cregbundle(self): """Conditional CX (target-control) with a wire in the middle with cregbundle.""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐ ", "qr_0: |0>─┤ X ├─", " └─┬─┘ ", "qr_1: |0>───■───", " ║ ", "qr_2: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cx_tc(self): """Conditional CX (target-control) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cx(qr[1], qr[0]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐", "qr_0: |0>┤ X ├", " └─┬─┘", "qr_1: |0>──■──", " ║ ", "qr_2: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cu3_ct_cregbundle(self): """Conditional Cu3 (control-target) with a wire in the middle with cregbundle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>─────────■─────────", " ┌────────┴────────┐", "qr_1: |0>┤ U3(π/2,π/2,π/2) ├", " └────────╥────────┘", "qr_2: |0>─────────╫─────────", " ┌──╨──┐ ", " cr: 0 1/══════╡ 0x1 ╞══════", " └─────┘ ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cu3_ct(self): """Conditional Cu3 (control-target) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>─────────■─────────", " ┌────────┴────────┐", "qr_1: |0>┤ U3(π/2,π/2,π/2) ├", " └────────╥────────┘", "qr_2: |0>─────────╫─────────", " ║ ", " cr: 0 ═════════■═════════", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cu3_tc_cregbundle(self): """Conditional Cu3 (target-control) with a wire in the middle with cregbundle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1) expected = "\n".join( [ " ┌─────────────────┐", "qr_0: |0>┤ U3(π/2,π/2,π/2) ├", " └────────┬────────┘", "qr_1: |0>─────────■─────────", " ║ ", "qr_2: |0>─────────╫─────────", " ┌──╨──┐ ", " cr: 0 1/══════╡ 0x1 ╞══════", " └─────┘ ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cu3_tc(self): """Conditional Cu3 (target-control) with a wire in the middle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1) expected = "\n".join( [ " ┌─────────────────┐", "qr_0: |0>┤ U3(π/2,π/2,π/2) ├", " └────────┬────────┘", "qr_1: |0>─────────■─────────", " ║ ", "qr_2: |0>─────────╫─────────", " ║ ", " cr: 0 ═════════■═════════", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_ccx_cregbundle(self): """Conditional CCX with a wire in the middle with cregbundle""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───■───", " ┌─┴─┐ ", "qr_2: |0>─┤ X ├─", " └─╥─┘ ", "qr_3: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_ccx(self): """Conditional CCX with a wire in the middle""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──■──", " ┌─┴─┐", "qr_2: |0>┤ X ├", " └─╥─┘", "qr_3: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_ccx_no_space_cregbundle(self): """Conditional CCX without space with cregbundle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───■───", " ┌─┴─┐ ", "qr_2: |0>─┤ X ├─", " ┌┴─╨─┴┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_ccx_no_space(self): """Conditional CCX without space""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──■──", " ┌─┴─┐", "qr_2: |0>┤ X ├", " └─╥─┘", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_h_cregbundle(self): """Conditional H with a wire in the middle with cregbundle""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐ ", "qr_0: |0>─┤ H ├─", " └─╥─┘ ", "qr_1: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_h(self): """Conditional H with a wire in the middle""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr, 1) expected = "\n".join( [ " ┌───┐", "qr_0: |0>┤ H ├", " └─╥─┘", "qr_1: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_swap_cregbundle(self): """Conditional SWAP with cregbundle""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───X───", " │ ", "qr_1: |0>───X───", " ║ ", "qr_2: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_swap(self): """Conditional SWAP""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.swap(qr[0], qr[1]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──X──", " │ ", "qr_1: |0>──X──", " ║ ", "qr_2: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_conditional_cswap_cregbundle(self): """Conditional CSwap with cregbundle""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>───■───", " │ ", "qr_1: |0>───X───", " │ ", "qr_2: |0>───X───", " ║ ", "qr_3: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_cswap(self): """Conditional CSwap""" qr = QuantumRegister(4, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──■──", " │ ", "qr_1: |0>──X──", " │ ", "qr_2: |0>──X──", " ║ ", "qr_3: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_conditional_reset_cregbundle(self): """Reset drawing with cregbundle.""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.reset(qr[0]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>──|0>──", " ║ ", "qr_1: |0>───╫───", " ┌──╨──┐", " cr: 0 1/╡ 0x1 ╞", " └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_conditional_reset(self): """Reset drawing.""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(1, "cr") circuit = QuantumCircuit(qr, cr) circuit.reset(qr[0]).c_if(cr, 1) expected = "\n".join( [ " ", "qr_0: |0>─|0>─", " ║ ", "qr_1: |0>──╫──", " ║ ", " cr: 0 ══■══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_conditional_multiplexer_cregbundle(self): """Test Multiplexer with cregbundle.""" cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])]) qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(1, "cr") qc = QuantumCircuit(qr, cr) qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]]) expected = "\n".join( [ " ┌──────────────┐", "qr_0: |0>┤0 ├", " │ Multiplexer │", "qr_1: |0>┤1 ├", " └──────╥───────┘", "qr_2: |0>───────╫────────", " ┌──╨──┐ ", " cr: 0 1/════╡ 0x1 ╞═════", " └─────┘ ", ] ) self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=True)), expected) def test_conditional_multiplexer(self): """Test Multiplexer.""" cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])]) qr = QuantumRegister(3, name="qr") cr = ClassicalRegister(1, "cr") qc = QuantumCircuit(qr, cr) qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]]) expected = "\n".join( [ " ┌──────────────┐", "qr_0: |0>┤0 ├", " │ Multiplexer │", "qr_1: |0>┤1 ├", " └──────╥───────┘", "qr_2: |0>───────╫────────", " ║ ", " cr: 0 ═══════■════════", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=False)), expected) def test_text_conditional_measure_cregbundle(self): """Conditional with measure on same clbit with cregbundle""" 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) expected = "\n".join( [ " ┌───┐┌─┐ ", "qr_0: |0>┤ H ├┤M├───────", " └───┘└╥┘ ┌───┐ ", "qr_1: |0>──────╫──┤ H ├─", " ║ ┌┴─╨─┴┐", " cr: 0 2/══════╩═╡ 0x1 ╞", " 0 └─────┘", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_conditional_measure(self): """Conditional with measure on same clbit""" 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) expected = "\n".join( [ " ┌───┐┌─┐ ", "qr_0: |0>┤ H ├┤M├─────", " └───┘└╥┘┌───┐", "qr_1: |0>──────╫─┤ H ├", " ║ └─╥─┘", " cr_0: 0 ══════╩═══■══", " ║ ", " cr_1: 0 ══════════o══", " 0x1 ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_bit_conditional(self): """Test bit conditions on gates""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.h(qr[1]).c_if(cr[1], 0) expected = "\n".join( [ " ┌───┐ ", "qr_0: |0>┤ H ├─────", " └─╥─┘┌───┐", "qr_1: |0>──╫──┤ H ├", " ║ └─╥─┘", " cr_0: 0 ══■════╬══", " ║ ", " cr_1: 0 ═══════o══", " ", ] ) self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected) def test_text_bit_conditional_cregbundle(self): """Test bit conditions on gates when cregbundle=True""" qr = QuantumRegister(2, "qr") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr[0], 1) circuit.h(qr[1]).c_if(cr[1], 0) expected = "\n".join( [ " ┌───┐ ", "qr_0: |0>───┤ H ├────────────────", " └─╥─┘ ┌───┐ ", "qr_1: |0>─────╫─────────┤ H ├────", " ║ └─╥─┘ ", " ┌────╨─────┐┌────╨─────┐", " cr: 0 2/╡ cr_0=0x1 ╞╡ cr_1=0x0 ╞", " └──────────┘└──────────┘", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=True, vertical_compression="medium")), expected, ) def test_text_condition_measure_bits_true(self): """Condition and measure on single bits cregbundle true""" 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]) expected = "\n".join( [ " ┌───┐ ┌─┐", " 0: ───┤ X ├────┤M├", " └─╥─┘ └╥┘", " 1: ─────╫───────╫─", " ║ ║ ", " 0: ═════╬═══════╬═", " ║ ║ ", " 1: ═════╬═══════╩═", " ║ ", "cr: 2/═════╬═════════", " ║ ", " 4: ═════╬═════════", " ┌────╨─────┐ ", "cs: 3/╡ cs_1=0x0 ╞═══", " └──────────┘ ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=True, initial_state=False)), expected ) def test_text_condition_measure_bits_false(self): """Condition and measure on single bits cregbundle false""" 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]) expected = "\n".join( [ " ┌───┐┌─┐", " 0: ┤ X ├┤M├", " └─╥─┘└╥┘", " 1: ──╫───╫─", " ║ ║ ", " 0: ══╬═══╬═", " ║ ║ ", " 1: ══╬═══╩═", " ║ ", "cr_0: ══╬═════", " ║ ", "cr_1: ══╬═════", " ║ ", " 4: ══╬═════", " ║ ", "cs_0: ══╬═════", " ║ ", "cs_1: ══o═════", " ", "cs_2: ════════", " ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, initial_state=False)), expected ) def test_text_conditional_reverse_bits_1(self): """Classical condition on 2q2c circuit with cregbundle=False and reverse bits""" 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) expected = "\n".join( [ " ┌───┐", "qr_1: |0>────────┤ H ├", " ┌───┐┌─┐└─╥─┘", "qr_0: |0>┤ H ├┤M├──╫──", " └───┘└╥┘ ║ ", " cr_1: 0 ══════╬═══o══", " ║ ║ ", " cr_0: 0 ══════╩═══■══", " 0x1 ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected ) def test_text_conditional_reverse_bits_2(self): """Classical condition on 3q3c circuit with cergbundle=False and reverse bits""" qr = QuantumRegister(3, "qr") cr = ClassicalRegister(3, "cr") circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]).c_if(cr, 6) circuit.h(qr[1]).c_if(cr, 1) circuit.h(qr[2]).c_if(cr, 2) circuit.cx(0, 1).c_if(cr, 3) expected = "\n".join( [ " ┌───┐ ", "qr_2: |0>──────────┤ H ├─────", " ┌───┐└─╥─┘┌───┐", "qr_1: |0>─────┤ H ├──╫──┤ X ├", " ┌───┐└─╥─┘ ║ └─┬─┘", "qr_0: |0>┤ H ├──╫────╫────■──", " └─╥─┘ ║ ║ ║ ", " cr_2: 0 ══■════o════o════o══", " ║ ║ ║ ║ ", " cr_1: 0 ══■════o════■════■══", " ║ ║ ║ ║ ", " cr_0: 0 ══o════■════o════■══", " 0x6 0x1 0x2 0x3 ", ] ) self.assertEqual( str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected ) def test_text_condition_bits_reverse(self): """Condition and measure on single bits cregbundle true and reverse_bits true""" bits = [Qubit(), Qubit(), Clbit(), Clbit()] cr = ClassicalRegister(2, "cr") crx = ClassicalRegister(3, "cs") circuit = QuantumCircuit(bits, cr, [Clbit()], crx) circuit.x(0).c_if(bits[3], 0) expected = "\n".join( [ " ", " 1: ─────", " ┌───┐", " 0: ┤ X ├", " └─╥─┘", "cs: 3/══╬══", " ║ ", " 4: ══╬══", " ║ ", "cr: 2/══╬══", " ║ ", " 1: ══o══", " ", " 0: ═════", " ", ] ) self.assertEqual( str( _text_circuit_drawer( circuit, cregbundle=True, initial_state=False, reverse_bits=True ) ), expected, ) class TestTextIdleWires(QiskitTestCase): """The idle_wires option""" def test_text_h(self): """Remove QuWires.""" # fmt: off expected = "\n".join([" ┌───┐", "q1_1: |0>┤ H ├", " └───┘"]) # fmt: on qr1 = QuantumRegister(3, "q1") circuit = QuantumCircuit(qr1) circuit.h(qr1[1]) self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_text_measure(self): """Remove QuWires and ClWires.""" expected = "\n".join( [ " ┌─┐ ", "q2_0: |0>┤M├───", " └╥┘┌─┐", "q2_1: |0>─╫─┤M├", " ║ └╥┘", " c2: 0 2/═╩══╩═", " 0 1 ", ] ) qr1 = QuantumRegister(2, "q1") cr1 = ClassicalRegister(2, "c1") qr2 = QuantumRegister(2, "q2") cr2 = ClassicalRegister(2, "c2") circuit = QuantumCircuit(qr1, qr2, cr1, cr2) circuit.measure(qr2, cr2) self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_text_empty_circuit(self): """Remove everything in an empty circuit.""" expected = "" circuit = QuantumCircuit() self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_text_barrier(self): """idle_wires should ignore barrier See https://github.com/Qiskit/qiskit-terra/issues/4391""" # fmt: off expected = "\n".join([" ┌───┐ ░ ", "qr_1: |0>┤ H ├─░─", " └───┘ ░ "]) # fmt: on qr = QuantumRegister(3, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[1]) circuit.barrier(qr[1], qr[2]) self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_text_barrier_delay(self): """idle_wires should ignore delay""" # fmt: off expected = "\n".join([" ┌───┐ ░ ", "qr_1: |0>┤ H ├─░──", " └───┘ ░ "]) # fmt: on qr = QuantumRegister(4, "qr") circuit = QuantumCircuit(qr) circuit.h(qr[1]) circuit.barrier() circuit.delay(100, qr[2]) self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected) def test_does_not_mutate_circuit(self): """Using 'idle_wires=False' should not mutate the circuit. Regression test of gh-8739.""" circuit = QuantumCircuit(1) before_qubits = circuit.num_qubits circuit.draw(idle_wires=False) self.assertEqual(circuit.num_qubits, before_qubits) class TestTextNonRational(QiskitTestCase): """non-rational numbers are correctly represented""" def test_text_pifrac(self): """u drawing with -5pi/8 fraction""" # fmt: off expected = "\n".join( [" ┌──────────────┐", "q: |0>┤ U(π,-5π/8,0) ├", " └──────────────┘"] ) # fmt: on qr = QuantumRegister(1, "q") circuit = QuantumCircuit(qr) circuit.u(pi, -5 * pi / 8, 0, qr[0]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_complex(self): """Complex numbers show up in the text See https://github.com/Qiskit/qiskit-terra/issues/3640""" expected = "\n".join( [ " ┌────────────────────────────────────┐", "q_0: ┤0 ├", " │ Initialize(0.5+0.1j,0,0,0.86023j) │", "q_1: ┤1 ├", " └────────────────────────────────────┘", ] ) ket = numpy.array([0.5 + 0.1 * 1j, 0, 0, 0.8602325267042626 * 1j]) circuit = QuantumCircuit(2) circuit.initialize(ket, [0, 1]) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_text_complex_pireal(self): """Complex numbers including pi show up in the text See https://github.com/Qiskit/qiskit-terra/issues/3640""" expected = "\n".join( [ " ┌────────────────────────────────┐", "q_0: |0>┤0 ├", " │ Initialize(π/10,0,0,0.94937j) │", "q_1: |0>┤1 ├", " └────────────────────────────────┘", ] ) ket = numpy.array([0.1 * numpy.pi, 0, 0, 0.9493702944526474 * 1j]) circuit = QuantumCircuit(2) circuit.initialize(ket, [0, 1]) self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected) def test_text_complex_piimaginary(self): """Complex numbers including pi show up in the text See https://github.com/Qiskit/qiskit-terra/issues/3640""" expected = "\n".join( [ " ┌────────────────────────────────┐", "q_0: |0>┤0 ├", " │ Initialize(0.94937,0,0,π/10j) │", "q_1: |0>┤1 ├", " └────────────────────────────────┘", ] ) ket = numpy.array([0.9493702944526474, 0, 0, 0.1 * numpy.pi * 1j]) circuit = QuantumCircuit(2) circuit.initialize(ket, [0, 1]) self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected) class TestTextInstructionWithBothWires(QiskitTestCase): """Composite instructions with both kind of wires See https://github.com/Qiskit/qiskit-terra/issues/2973""" def test_text_all_1q_1c(self): """Test q0-c0 in q0-c0""" expected = "\n".join( [ " ┌───────┐", "qr: |0>┤0 ├", " │ name │", " cr: 0 ╡0 ╞", " └───────┘", ] ) qr1 = QuantumRegister(1, "qr") cr1 = ClassicalRegister(1, "cr") inst = QuantumCircuit(qr1, cr1, name="name").to_instruction() circuit = QuantumCircuit(qr1, cr1) circuit.append(inst, qr1[:], cr1[:]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_all_2q_2c(self): """Test q0-q1-c0-c1 in q0-q1-c0-c1""" expected = "\n".join( [ " ┌───────┐", "qr_0: |0>┤0 ├", " │ │", "qr_1: |0>┤1 ├", " │ name │", " cr_0: 0 ╡0 ╞", " │ │", " cr_1: 0 ╡1 ╞", " └───────┘", ] ) qr2 = QuantumRegister(2, "qr") cr2 = ClassicalRegister(2, "cr") inst = QuantumCircuit(qr2, cr2, name="name").to_instruction() circuit = QuantumCircuit(qr2, cr2) circuit.append(inst, qr2[:], cr2[:]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_all_2q_2c_cregbundle(self): """Test q0-q1-c0-c1 in q0-q1-c0-c1. Ignore cregbundle=True""" expected = "\n".join( [ " ┌───────┐", "qr_0: |0>┤0 ├", " │ │", "qr_1: |0>┤1 ├", " │ name │", " cr_0: 0 ╡0 ╞", " │ │", " cr_1: 0 ╡1 ╞", " └───────┘", ] ) qr2 = QuantumRegister(2, "qr") cr2 = ClassicalRegister(2, "cr") inst = QuantumCircuit(qr2, cr2, name="name").to_instruction() circuit = QuantumCircuit(qr2, cr2) circuit.append(inst, qr2[:], cr2[:]) with self.assertWarns(RuntimeWarning): self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected) def test_text_4q_2c(self): """Test q1-q2-q3-q4-c1-c2 in q0-q1-q2-q3-q4-q5-c0-c1-c2-c3-c4-c5""" expected = "\n".join( [ " ", "q_0: |0>─────────", " ┌───────┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤1 ├", " │ │", "q_3: |0>┤2 ├", " │ │", "q_4: |0>┤3 ├", " │ name │", "q_5: |0>┤ ├", " │ │", " c_0: 0 ╡ ╞", " │ │", " c_1: 0 ╡0 ╞", " │ │", " c_2: 0 ╡1 ╞", " └───────┘", " c_3: 0 ═════════", " ", " c_4: 0 ═════════", " ", " c_5: 0 ═════════", " ", ] ) qr4 = QuantumRegister(4) cr4 = ClassicalRegister(2) inst = QuantumCircuit(qr4, cr4, name="name").to_instruction() qr6 = QuantumRegister(6, "q") cr6 = ClassicalRegister(6, "c") circuit = QuantumCircuit(qr6, cr6) circuit.append(inst, qr6[1:5], cr6[1:3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_2q_1c(self): """Test q0-c0 in q0-q1-c0 See https://github.com/Qiskit/qiskit-terra/issues/4066""" expected = "\n".join( [ " ┌───────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>┤ Name ├", " │ │", " c: 0 ╡0 ╞", " └───────┘", ] ) qr = QuantumRegister(2, name="q") cr = ClassicalRegister(1, name="c") circuit = QuantumCircuit(qr, cr) inst = QuantumCircuit(1, 1, name="Name").to_instruction() circuit.append(inst, [qr[0]], [cr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_3q_3c_qlabels_inverted(self): """Test q3-q0-q1-c0-c1-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11 See https://github.com/Qiskit/qiskit-terra/issues/6178""" expected = "\n".join( [ " ┌───────┐", "q_0: |0>┤1 ├", " │ │", "q_1: |0>┤2 ├", " │ │", "q_2: |0>┤ ├", " │ │", "q_3: |0>┤0 ├", " │ Name │", " c_0: 0 ╡0 ╞", " │ │", " c_1: 0 ╡1 ╞", " │ │", " c_2: 0 ╡ ╞", " │ │", "c1_0: 0 ╡2 ╞", " └───────┘", "c1_1: 0 ═════════", " ", ] ) qr = QuantumRegister(4, name="q") cr = ClassicalRegister(3, name="c") cr1 = ClassicalRegister(2, name="c1") circuit = QuantumCircuit(qr, cr, cr1) inst = QuantumCircuit(3, 3, name="Name").to_instruction() circuit.append(inst, [qr[3], qr[0], qr[1]], [cr[0], cr[1], cr1[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_3q_3c_clabels_inverted(self): """Test q0-q1-q3-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11 See https://github.com/Qiskit/qiskit-terra/issues/6178""" expected = "\n".join( [ " ┌───────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>┤1 ├", " │ │", "q_2: |0>┤ ├", " │ │", "q_3: |0>┤2 ├", " │ │", " c_0: 0 ╡1 Name ╞", " │ │", " c_1: 0 ╡ ╞", " │ │", " c_2: 0 ╡ ╞", " │ │", "c1_0: 0 ╡2 ╞", " │ │", "c1_1: 0 ╡0 ╞", " └───────┘", ] ) qr = QuantumRegister(4, name="q") cr = ClassicalRegister(3, name="c") cr1 = ClassicalRegister(2, name="c1") circuit = QuantumCircuit(qr, cr, cr1) inst = QuantumCircuit(3, 3, name="Name").to_instruction() circuit.append(inst, [qr[0], qr[1], qr[3]], [cr1[1], cr[0], cr1[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_3q_3c_qclabels_inverted(self): """Test q3-q1-q2-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11 See https://github.com/Qiskit/qiskit-terra/issues/6178""" expected = "\n".join( [ " ", "q_0: |0>─────────", " ┌───────┐", "q_1: |0>┤1 ├", " │ │", "q_2: |0>┤2 ├", " │ │", "q_3: |0>┤0 ├", " │ │", " c_0: 0 ╡1 ╞", " │ Name │", " c_1: 0 ╡ ╞", " │ │", " c_2: 0 ╡ ╞", " │ │", "c1_0: 0 ╡2 ╞", " │ │", "c1_1: 0 ╡0 ╞", " └───────┘", ] ) qr = QuantumRegister(4, name="q") cr = ClassicalRegister(3, name="c") cr1 = ClassicalRegister(2, name="c1") circuit = QuantumCircuit(qr, cr, cr1) inst = QuantumCircuit(3, 3, name="Name").to_instruction() circuit.append(inst, [qr[3], qr[1], qr[2]], [cr1[1], cr[0], cr1[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextDrawerAppendedLargeInstructions(QiskitTestCase): """Composite instructions with more than 10 qubits See https://github.com/Qiskit/qiskit-terra/pull/4095""" def test_text_11q(self): """Test q0-...-q10 in q0-...-q10""" expected = "\n".join( [ " ┌────────┐", " q_0: |0>┤0 ├", " │ │", " q_1: |0>┤1 ├", " │ │", " q_2: |0>┤2 ├", " │ │", " q_3: |0>┤3 ├", " │ │", " q_4: |0>┤4 ├", " │ │", " q_5: |0>┤5 Name ├", " │ │", " q_6: |0>┤6 ├", " │ │", " q_7: |0>┤7 ├", " │ │", " q_8: |0>┤8 ├", " │ │", " q_9: |0>┤9 ├", " │ │", "q_10: |0>┤10 ├", " └────────┘", ] ) qr = QuantumRegister(11, "q") circuit = QuantumCircuit(qr) inst = QuantumCircuit(11, name="Name").to_instruction() circuit.append(inst, qr) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_text_11q_1c(self): """Test q0-...-q10-c0 in q0-...-q10-c0""" expected = "\n".join( [ " ┌────────┐", " q_0: |0>┤0 ├", " │ │", " q_1: |0>┤1 ├", " │ │", " q_2: |0>┤2 ├", " │ │", " q_3: |0>┤3 ├", " │ │", " q_4: |0>┤4 ├", " │ │", " q_5: |0>┤5 ├", " │ Name │", " q_6: |0>┤6 ├", " │ │", " q_7: |0>┤7 ├", " │ │", " q_8: |0>┤8 ├", " │ │", " q_9: |0>┤9 ├", " │ │", "q_10: |0>┤10 ├", " │ │", " c: 0 ╡0 ╞", " └────────┘", ] ) qr = QuantumRegister(11, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) inst = QuantumCircuit(11, 1, name="Name").to_instruction() circuit.append(inst, qr, cr) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextControlledGate(QiskitTestCase): """Test controlled gates""" def test_cch_bot(self): """Controlled CH (bottom)""" expected = "\n".join( [ " ", "q_0: |0>──■──", " │ ", "q_1: |0>──■──", " ┌─┴─┐", "q_2: |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2), [qr[0], qr[1], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_mid(self): """Controlled CH (middle)""" expected = "\n".join( [ " ", "q_0: |0>──■──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └─┬─┘", "q_2: |0>──■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2), [qr[0], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_top(self): """Controlled CH""" expected = "\n".join( [ " ┌───┐", "q_0: |0>┤ H ├", " └─┬─┘", "q_1: |0>──■──", " │ ", "q_2: |0>──■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2), [qr[2], qr[1], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3h(self): """Controlled Controlled CH""" expected = "\n".join( [ " ", "q_0: |0>──■──", " │ ", "q_1: |0>──■──", " │ ", "q_2: |0>──■──", " ┌─┴─┐", "q_3: |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(3), [qr[0], qr[1], qr[2], qr[3]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3h_middle(self): """Controlled Controlled CH (middle)""" expected = "\n".join( [ " ", "q_0: |0>──■──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └─┬─┘", "q_2: |0>──■──", " │ ", "q_3: |0>──■──", " ", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(3), [qr[0], qr[3], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3u2(self): """Controlled Controlled U2""" expected = "\n".join( [ " ", "q_0: |0>───────■───────", " ┌──────┴──────┐", "q_1: |0>┤ U2(π,-5π/8) ├", " └──────┬──────┘", "q_2: |0>───────■───────", " │ ", "q_3: |0>───────■───────", " ", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(U2Gate(pi, -5 * pi / 8).control(3), [qr[0], qr[3], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_edge(self): """Controlled composite gates (edge) See: https://github.com/Qiskit/qiskit-terra/issues/3546""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>■ ├", " │ ghz │", "q_2: |0>┤1 ├", " │ │", "q_3: |0>┤2 ├", " └──────┘", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1) circuit = QuantumCircuit(4) circuit.append(cghz, [1, 0, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_top(self): """Controlled composite gates (top)""" expected = "\n".join( [ " ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤2 ghz ├", " │ │", "q_3: |0>┤1 ├", " └──────┘", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1) circuit = QuantumCircuit(4) circuit.append(cghz, [0, 1, 3, 2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_bot(self): """Controlled composite gates (bottom)""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤1 ├", " │ │", "q_1: |0>┤0 ghz ├", " │ │", "q_2: |0>┤2 ├", " └──┬───┘", "q_3: |0>───■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1) circuit = QuantumCircuit(4) circuit.append(cghz, [3, 1, 0, 2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_top_bot(self): """Controlled composite gates (top and bottom)""" expected = "\n".join( [ " ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤1 ghz ├", " │ │", "q_3: |0>┤2 ├", " └──┬───┘", "q_4: |0>───■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2) circuit = QuantumCircuit(5) circuit.append(ccghz, [4, 0, 1, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_all(self): """Controlled composite gates (top, bot, and edge)""" expected = "\n".join( [ " ", "q_0: |0>───■────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>■ ├", " │ ghz │", "q_3: |0>┤1 ├", " │ │", "q_4: |0>┤2 ├", " └──┬───┘", "q_5: |0>───■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(3) circuit = QuantumCircuit(6) circuit.append(ccghz, [0, 2, 5, 1, 3, 4]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_even_label(self): """Controlled composite gates (top and bottom) with a even label length""" expected = "\n".join( [ " ", "q_0: |0>────■────", " ┌───┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤1 cghz ├", " │ │", "q_3: |0>┤2 ├", " └───┬───┘", "q_4: |0>────■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="cghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(2) circuit = QuantumCircuit(5) circuit.append(ccghz, [4, 0, 1, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextOpenControlledGate(QiskitTestCase): """Test open controlled gates""" def test_ch_bot(self): """Open controlled H (bottom)""" # fmt: off expected = "\n".join( [" ", "q_0: |0>──o──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └───┘"] ) # fmt: on qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(1, ctrl_state=0), [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cz_bot(self): """Open controlled Z (bottom)""" # fmt: off expected = "\n".join([" ", "q_0: |0>─o─", " │ ", "q_1: |0>─■─", " "]) # fmt: on qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.append(ZGate().control(1, ctrl_state=0), [qr[0], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_ccz_bot(self): """Closed-Open controlled Z (bottom)""" expected = "\n".join( [ " ", "q_0: |0>─■─", " │ ", "q_1: |0>─o─", " │ ", "q_2: |0>─■─", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(ZGate().control(2, ctrl_state="01"), [qr[0], qr[1], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cccz_conditional(self): """Closed-Open controlled Z (with conditional)""" expected = "\n".join( [ " ", "q_0: |0>───■───", " │ ", "q_1: |0>───o───", " │ ", "q_2: |0>───■───", " │ ", "q_3: |0>───■───", " ┌──╨──┐", " c: 0 1/╡ 0x1 ╞", " └─────┘", ] ) qr = QuantumRegister(4, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.append( ZGate().control(3, ctrl_state="101").c_if(cr, 1), [qr[0], qr[1], qr[2], qr[3]] ) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_bot(self): """Controlled CH (bottom)""" expected = "\n".join( [ " ", "q_0: |0>──o──", " │ ", "q_1: |0>──■──", " ┌─┴─┐", "q_2: |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[1], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_mid(self): """Controlled CH (middle)""" expected = "\n".join( [ " ", "q_0: |0>──o──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └─┬─┘", "q_2: |0>──■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_cch_top(self): """Controlled CH""" expected = "\n".join( [ " ┌───┐", "q_0: |0>┤ H ├", " └─┬─┘", "q_1: |0>──o──", " │ ", "q_2: |0>──■──", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(2, ctrl_state="10"), [qr[1], qr[2], qr[0]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3h(self): """Controlled Controlled CH""" expected = "\n".join( [ " ", "q_0: |0>──o──", " │ ", "q_1: |0>──o──", " │ ", "q_2: |0>──■──", " ┌─┴─┐", "q_3: |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(3, ctrl_state="100"), [qr[0], qr[1], qr[2], qr[3]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3h_middle(self): """Controlled Controlled CH (middle)""" expected = "\n".join( [ " ", "q_0: |0>──o──", " ┌─┴─┐", "q_1: |0>┤ H ├", " └─┬─┘", "q_2: |0>──o──", " │ ", "q_3: |0>──■──", " ", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append(HGate().control(3, ctrl_state="010"), [qr[0], qr[3], qr[2], qr[1]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_c3u2(self): """Controlled Controlled U2""" expected = "\n".join( [ " ", "q_0: |0>───────o───────", " ┌──────┴──────┐", "q_1: |0>┤ U2(π,-5π/8) ├", " └──────┬──────┘", "q_2: |0>───────■───────", " │ ", "q_3: |0>───────o───────", " ", ] ) qr = QuantumRegister(4, "q") circuit = QuantumCircuit(qr) circuit.append( U2Gate(pi, -5 * pi / 8).control(3, ctrl_state="100"), [qr[0], qr[3], qr[2], qr[1]] ) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_edge(self): """Controlled composite gates (edge) See: https://github.com/Qiskit/qiskit-terra/issues/3546""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤0 ├", " │ │", "q_1: |0>o ├", " │ ghz │", "q_2: |0>┤1 ├", " │ │", "q_3: |0>┤2 ├", " └──────┘", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1, ctrl_state="0") circuit = QuantumCircuit(4) circuit.append(cghz, [1, 0, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_top(self): """Controlled composite gates (top)""" expected = "\n".join( [ " ", "q_0: |0>───o────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤2 ghz ├", " │ │", "q_3: |0>┤1 ├", " └──────┘", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1, ctrl_state="0") circuit = QuantumCircuit(4) circuit.append(cghz, [0, 1, 3, 2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_bot(self): """Controlled composite gates (bottom)""" expected = "\n".join( [ " ┌──────┐", "q_0: |0>┤1 ├", " │ │", "q_1: |0>┤0 ghz ├", " │ │", "q_2: |0>┤2 ├", " └──┬───┘", "q_3: |0>───o────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() cghz = ghz.control(1, ctrl_state="0") circuit = QuantumCircuit(4) circuit.append(cghz, [3, 1, 0, 2]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_top_bot(self): """Controlled composite gates (top and bottom)""" expected = "\n".join( [ " ", "q_0: |0>───o────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>┤1 ghz ├", " │ │", "q_3: |0>┤2 ├", " └──┬───┘", "q_4: |0>───■────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") 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="01") circuit = QuantumCircuit(5) circuit.append(ccghz, [4, 0, 1, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_controlled_composite_gate_all(self): """Controlled composite gates (top, bot, and edge)""" expected = "\n".join( [ " ", "q_0: |0>───o────", " ┌──┴───┐", "q_1: |0>┤0 ├", " │ │", "q_2: |0>o ├", " │ ghz │", "q_3: |0>┤1 ├", " │ │", "q_4: |0>┤2 ├", " └──┬───┘", "q_5: |0>───o────", " ", ] ) ghz_circuit = QuantumCircuit(3, name="ghz") ghz_circuit.h(0) ghz_circuit.cx(0, 1) ghz_circuit.cx(1, 2) ghz = ghz_circuit.to_gate() ccghz = ghz.control(3, ctrl_state="000") circuit = QuantumCircuit(6) circuit.append(ccghz, [0, 2, 5, 1, 3, 4]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_x(self): """Controlled X gates. See https://github.com/Qiskit/qiskit-terra/issues/4180""" expected = "\n".join( [ " ", "qr_0: |0>──o────o────o────o────■──", " ┌─┴─┐ │ │ │ │ ", "qr_1: |0>┤ X ├──o────■────■────o──", " └───┘┌─┴─┐┌─┴─┐ │ │ ", "qr_2: |0>─────┤ X ├┤ X ├──o────o──", " └───┘└───┘┌─┴─┐┌─┴─┐", "qr_3: |0>───────────────┤ X ├┤ X ├", " └───┘└─┬─┘", "qr_4: |0>──────────────────────■──", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = XGate().control(1, ctrl_state="0") circuit.append(control1, [0, 1]) control2 = XGate().control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2]) control2_2 = XGate().control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2]) control3 = XGate().control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3]) control3 = XGate().control(4, ctrl_state="0101") circuit.append(control3, [0, 1, 4, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_y(self): """Controlled Y gates. See https://github.com/Qiskit/qiskit-terra/issues/4180""" expected = "\n".join( [ " ", "qr_0: |0>──o────o────o────o────■──", " ┌─┴─┐ │ │ │ │ ", "qr_1: |0>┤ Y ├──o────■────■────o──", " └───┘┌─┴─┐┌─┴─┐ │ │ ", "qr_2: |0>─────┤ Y ├┤ Y ├──o────o──", " └───┘└───┘┌─┴─┐┌─┴─┐", "qr_3: |0>───────────────┤ Y ├┤ Y ├", " └───┘└─┬─┘", "qr_4: |0>──────────────────────■──", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = YGate().control(1, ctrl_state="0") circuit.append(control1, [0, 1]) control2 = YGate().control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2]) control2_2 = YGate().control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2]) control3 = YGate().control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3]) control3 = YGate().control(4, ctrl_state="0101") circuit.append(control3, [0, 1, 4, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_z(self): """Controlled Z gates.""" expected = "\n".join( [ " ", "qr_0: |0>─o──o──o──o──■─", " │ │ │ │ │ ", "qr_1: |0>─■──o──■──■──o─", " │ │ │ │ ", "qr_2: |0>────■──■──o──o─", " │ │ ", "qr_3: |0>──────────■──■─", " │ ", "qr_4: |0>─────────────■─", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = ZGate().control(1, ctrl_state="0") circuit.append(control1, [0, 1]) control2 = ZGate().control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2]) control2_2 = ZGate().control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2]) control3 = ZGate().control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3]) control3 = ZGate().control(4, ctrl_state="0101") circuit.append(control3, [0, 1, 4, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_u1(self): """Controlled U1 gates.""" expected = "\n".join( [ " ", "qr_0: |0>─o─────────o─────────o─────────o─────────■────────", " │U1(0.1) │ │ │ │ ", "qr_1: |0>─■─────────o─────────■─────────■─────────o────────", " │U1(0.2) │U1(0.3) │ │ ", "qr_2: |0>───────────■─────────■─────────o─────────o────────", " │U1(0.4) │ ", "qr_3: |0>───────────────────────────────■─────────■────────", " │U1(0.5) ", "qr_4: |0>─────────────────────────────────────────■────────", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = U1Gate(0.1).control(1, ctrl_state="0") circuit.append(control1, [0, 1]) control2 = U1Gate(0.2).control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2]) control2_2 = U1Gate(0.3).control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2]) control3 = U1Gate(0.4).control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3]) control3 = U1Gate(0.5).control(4, ctrl_state="0101") circuit.append(control3, [0, 1, 4, 2, 3]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_swap(self): """Controlled SWAP gates.""" expected = "\n".join( [ " ", "qr_0: |0>─o──o──o──o─", " │ │ │ │ ", "qr_1: |0>─X──o──■──■─", " │ │ │ │ ", "qr_2: |0>─X──X──X──o─", " │ │ │ ", "qr_3: |0>────X──X──X─", " │ ", "qr_4: |0>──────────X─", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = SwapGate().control(1, ctrl_state="0") circuit.append(control1, [0, 1, 2]) control2 = SwapGate().control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2, 3]) control2_2 = SwapGate().control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2, 3]) control3 = SwapGate().control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3, 4]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_controlled_rzz(self): """Controlled RZZ gates.""" expected = "\n".join( [ " ", "qr_0: |0>─o───────o───────o───────o──────", " │ │ │ │ ", "qr_1: |0>─■───────o───────■───────■──────", " │ZZ(1) │ │ │ ", "qr_2: |0>─■───────■───────■───────o──────", " │ZZ(1) │ZZ(1) │ ", "qr_3: |0>─────────■───────■───────■──────", " │ZZ(1) ", "qr_4: |0>─────────────────────────■──────", " ", ] ) qreg = QuantumRegister(5, "qr") circuit = QuantumCircuit(qreg) control1 = RZZGate(1).control(1, ctrl_state="0") circuit.append(control1, [0, 1, 2]) control2 = RZZGate(1).control(2, ctrl_state="00") circuit.append(control2, [0, 1, 2, 3]) control2_2 = RZZGate(1).control(2, ctrl_state="10") circuit.append(control2_2, [0, 1, 2, 3]) control3 = RZZGate(1).control(3, ctrl_state="010") circuit.append(control3, [0, 1, 2, 3, 4]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_open_out_of_order(self): """Out of order CXs See: https://github.com/Qiskit/qiskit-terra/issues/4052#issuecomment-613736911""" expected = "\n".join( [ " ", "q_0: |0>──■──", " │ ", "q_1: |0>──■──", " ┌─┴─┐", "q_2: |0>┤ X ├", " └─┬─┘", "q_3: |0>──o──", " ", "q_4: |0>─────", " ", ] ) qr = QuantumRegister(5, "q") circuit = QuantumCircuit(qr) circuit.append(XGate().control(3, ctrl_state="101"), [qr[0], qr[3], qr[1], qr[2]]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) class TestTextWithLayout(QiskitTestCase): """The with_layout option""" def test_with_no_layout(self): """A circuit without layout""" expected = "\n".join( [ " ", "q_0: |0>─────", " ┌───┐", "q_1: |0>┤ H ├", " └───┘", "q_2: |0>─────", " ", ] ) qr = QuantumRegister(3, "q") circuit = QuantumCircuit(qr) circuit.h(qr[1]) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_mixed_layout(self): """With a mixed layout.""" expected = "\n".join( [ " ┌───┐", " v_0 -> 0 |0>┤ H ├", " └───┘", "ancilla_1 -> 1 |0>─────", " ", "ancilla_0 -> 2 |0>─────", " ┌───┐", " v_1 -> 3 |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(2, "v") ancilla = QuantumRegister(2, "ancilla") circuit = QuantumCircuit(qr, ancilla) circuit.h(qr) pass_ = ApplyLayout() pass_.property_set["layout"] = Layout({qr[0]: 0, ancilla[1]: 1, ancilla[0]: 2, qr[1]: 3}) circuit_with_layout = pass_(circuit) self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected) def test_partial_layout(self): """With a partial layout. See: https://github.com/Qiskit/qiskit-terra/issues/4757""" expected = "\n".join( [ " ┌───┐", "v_0 -> 0 |0>┤ H ├", " └───┘", " 1 |0>─────", " ", " 2 |0>─────", " ┌───┐", "v_1 -> 3 |0>┤ H ├", " └───┘", ] ) qr = QuantumRegister(2, "v") pqr = QuantumRegister(4, "physical") circuit = QuantumCircuit(pqr) circuit.h(0) circuit.h(3) circuit._layout = TranspileLayout( Layout({0: qr[0], 1: None, 2: None, 3: qr[1]}), {qubit: index for index, qubit in enumerate(circuit.qubits)}, ) circuit._layout.initial_layout.add_register(qr) self.assertEqual(str(_text_circuit_drawer(circuit)), expected) def test_with_classical_regs(self): """Involving classical registers""" expected = "\n".join( [ " ", "qr1_0 -> 0 |0>──────", " ", "qr1_1 -> 1 |0>──────", " ┌─┐ ", "qr2_0 -> 2 |0>┤M├───", " └╥┘┌─┐", "qr2_1 -> 3 |0>─╫─┤M├", " ║ └╥┘", " cr: 0 2/═╩══╩═", " 0 1 ", ] ) qr1 = QuantumRegister(2, "qr1") qr2 = QuantumRegister(2, "qr2") cr = ClassicalRegister(2, "cr") circuit = QuantumCircuit(qr1, qr2, cr) circuit.measure(qr2[0], cr[0]) circuit.measure(qr2[1], cr[1]) pass_ = ApplyLayout() pass_.property_set["layout"] = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3}) circuit_with_layout = pass_(circuit) self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected) def test_with_layout_but_disable(self): """With parameter without_layout=False""" expected = "\n".join( [ " ", "q_0: |0>──────", " ", "q_1: |0>──────", " ┌─┐ ", "q_2: |0>┤M├───", " └╥┘┌─┐", "q_3: |0>─╫─┤M├", " ║ └╥┘", "cr: 0 2/═╩══╩═", " 0 1 ", ] ) pqr = QuantumRegister(4, "q") qr1 = QuantumRegister(2, "qr1") cr = ClassicalRegister(2, "cr") qr2 = QuantumRegister(2, "qr2") circuit = QuantumCircuit(pqr, cr) circuit._layout = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3}) circuit.measure(pqr[2], cr[0]) circuit.measure(pqr[3], cr[1]) self.assertEqual(str(_text_circuit_drawer(circuit, with_layout=False)), expected) def test_after_transpile(self): """After transpile, the drawing should include the layout""" expected = "\n".join( [ " ┌─────────┐┌─────────┐┌───┐┌─────────┐┌─┐ ", " userqr_0 -> 0 ┤ U2(0,π) ├┤ U2(0,π) ├┤ X ├┤ U2(0,π) ├┤M├───", " ├─────────┤├─────────┤└─┬─┘├─────────┤└╥┘┌─┐", " userqr_1 -> 1 ┤ U2(0,π) ├┤ U2(0,π) ├──■──┤ U2(0,π) ├─╫─┤M├", " └─────────┘└─────────┘ └─────────┘ ║ └╥┘", " ancilla_0 -> 2 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_1 -> 3 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_2 -> 4 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_3 -> 5 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_4 -> 6 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_5 -> 7 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_6 -> 8 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_7 -> 9 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_8 -> 10 ───────────────────────────────────────╫──╫─", " ║ ║ ", " ancilla_9 -> 11 ───────────────────────────────────────╫──╫─", " ║ ║ ", "ancilla_10 -> 12 ───────────────────────────────────────╫──╫─", " ║ ║ ", "ancilla_11 -> 13 ───────────────────────────────────────╫──╫─", " ║ ║ ", " c0_0: ═══════════════════════════════════════╩══╬═", " ║ ", " c0_1: ══════════════════════════════════════════╩═", " ", ] ) qr = QuantumRegister(2, "userqr") cr = ClassicalRegister(2, "c0") qc = QuantumCircuit(qr, cr) qc.h(qr) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) coupling_map = [ [1, 0], [1, 2], [2, 3], [4, 3], [4, 10], [5, 4], [5, 6], [5, 9], [6, 8], [7, 8], [9, 8], [9, 10], [11, 3], [11, 10], [11, 12], [12, 2], [13, 1], [13, 12], ] qc_result = transpile( qc, basis_gates=["u1", "u2", "u3", "cx", "id"], coupling_map=coupling_map, optimization_level=0, seed_transpiler=0, ) self.assertEqual(qc_result.draw(output="text", cregbundle=False).single_string(), expected) class TestTextInitialValue(QiskitTestCase): """Testing the initial_state parameter""" def setUp(self) -> None: super().setUp() qr = QuantumRegister(2, "q") cr = ClassicalRegister(2, "c") self.circuit = QuantumCircuit(qr, cr) self.circuit.measure(qr, cr) def test_draw_initial_value_default(self): """Text drawer (.draw) default initial_state parameter (False).""" expected = "\n".join( [ " ┌─┐ ", "q_0: ┤M├───", " └╥┘┌─┐", "q_1: ─╫─┤M├", " ║ └╥┘", "c_0: ═╩══╬═", " ║ ", "c_1: ════╩═", " ", ] ) self.assertEqual( self.circuit.draw(output="text", cregbundle=False).single_string(), expected ) def test_draw_initial_value_true(self): """Text drawer .draw(initial_state=True).""" expected = "\n".join( [ " ┌─┐ ", "q_0: |0>┤M├───", " └╥┘┌─┐", "q_1: |0>─╫─┤M├", " ║ └╥┘", " c_0: 0 ═╩══╬═", " ║ ", " c_1: 0 ════╩═", " ", ] ) self.assertEqual( self.circuit.draw(output="text", initial_state=True, cregbundle=False).single_string(), expected, ) def test_initial_value_false(self): """Text drawer with initial_state parameter False.""" expected = "\n".join( [ " ┌─┐ ", "q_0: ┤M├───", " └╥┘┌─┐", "q_1: ─╫─┤M├", " ║ └╥┘", "c: 2/═╩══╩═", " 0 1 ", ] ) self.assertEqual(str(_text_circuit_drawer(self.circuit, initial_state=False)), expected) class TestTextHamiltonianGate(QiskitTestCase): """Testing the Hamiltonian gate drawer""" def test_draw_hamiltonian_single(self): """Text Hamiltonian gate with single qubit.""" # fmt: off expected = "\n".join([" ┌─────────────┐", "q0: ┤ Hamiltonian ├", " └─────────────┘"]) # fmt: on qr = QuantumRegister(1, "q0") circuit = QuantumCircuit(qr) matrix = numpy.zeros((2, 2)) theta = Parameter("theta") circuit.append(HamiltonianGate(matrix, theta), [qr[0]]) circuit = circuit.bind_parameters({theta: 1}) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_draw_hamiltonian_multi(self): """Text Hamiltonian gate with mutiple qubits.""" expected = "\n".join( [ " ┌──────────────┐", "q0_0: ┤0 ├", " │ Hamiltonian │", "q0_1: ┤1 ├", " └──────────────┘", ] ) qr = QuantumRegister(2, "q0") circuit = QuantumCircuit(qr) matrix = numpy.zeros((4, 4)) theta = Parameter("theta") circuit.append(HamiltonianGate(matrix, theta), [qr[0], qr[1]]) circuit = circuit.bind_parameters({theta: 1}) self.assertEqual(circuit.draw(output="text").single_string(), expected) class TestTextPhase(QiskitTestCase): """Testing the draweing a circuit with phase""" def test_bell(self): """Text Bell state with phase.""" expected = "\n".join( [ "global phase: \u03C0/2", " ┌───┐ ", "q_0: ┤ H ├──■──", " └───┘┌─┴─┐", "q_1: ─────┤ X ├", " └───┘", ] ) qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.global_phase = 3.141592653589793 / 2 circuit.h(0) circuit.cx(0, 1) self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_empty(self): """Text empty circuit (two registers) with phase.""" # fmt: off expected = "\n".join(["global phase: 3", " ", "q_0: ", " ", "q_1: ", " "]) # fmt: on qr = QuantumRegister(2, "q") circuit = QuantumCircuit(qr) circuit.global_phase = 3 self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_empty_noregs(self): """Text empty circuit (no registers) with phase.""" expected = "\n".join(["global phase: 4.21"]) circuit = QuantumCircuit() circuit.global_phase = 4.21 self.assertEqual(circuit.draw(output="text").single_string(), expected) def test_registerless_one_bit(self): """Text circuit with one-bit registers and registerless bits.""" # fmt: off expected = "\n".join([" ", "qrx_0: ", " ", "qrx_1: ", " ", " 2: ", " ", " 3: ", " ", " qry: ", " ", " 0: ", " ", " 1: ", " ", "crx: 2/", " "]) # fmt: on qrx = QuantumRegister(2, "qrx") qry = QuantumRegister(1, "qry") crx = ClassicalRegister(2, "crx") circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx) self.assertEqual(circuit.draw(output="text", cregbundle=True).single_string(), expected) class TestCircuitVisualizationImplementation(QiskitVisualizationTestCase): """Tests utf8 and cp437 encoding.""" text_reference_utf8 = path_to_diagram_reference("circuit_text_ref_utf8.txt") text_reference_cp437 = path_to_diagram_reference("circuit_text_ref_cp437.txt") def sample_circuit(self): """Generate a sample circuit that includes the most common elements of quantum circuits. """ qr = QuantumRegister(3, "q") cr = ClassicalRegister(3, "c") circuit = QuantumCircuit(qr, cr) circuit.x(qr[0]) circuit.y(qr[0]) circuit.z(qr[0]) circuit.barrier(qr[0]) circuit.barrier(qr[1]) circuit.barrier(qr[2]) circuit.h(qr[0]) circuit.s(qr[0]) circuit.sdg(qr[0]) circuit.t(qr[0]) circuit.tdg(qr[0]) circuit.sx(qr[0]) circuit.sxdg(qr[0]) circuit.i(qr[0]) circuit.reset(qr[0]) circuit.rx(pi, qr[0]) circuit.ry(pi, qr[0]) circuit.rz(pi, qr[0]) circuit.append(U1Gate(pi), [qr[0]]) circuit.append(U2Gate(pi, pi), [qr[0]]) circuit.append(U3Gate(pi, pi, pi), [qr[0]]) circuit.swap(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cy(qr[0], qr[1]) circuit.cz(qr[0], qr[1]) circuit.ch(qr[0], qr[1]) circuit.append(CU1Gate(pi), [qr[0], qr[1]]) circuit.append(CU3Gate(pi, pi, pi), [qr[0], qr[1]]) circuit.crz(pi, qr[0], qr[1]) circuit.cry(pi, qr[0], qr[1]) circuit.crx(pi, qr[0], qr[1]) circuit.ccx(qr[0], qr[1], qr[2]) circuit.cswap(qr[0], qr[1], qr[2]) circuit.measure(qr, cr) return circuit def test_text_drawer_utf8(self): """Test that text drawer handles utf8 encoding.""" filename = "current_textplot_utf8.txt" qc = self.sample_circuit() output = _text_circuit_drawer( qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="utf8" ) try: encode(str(output), encoding="utf8") except UnicodeEncodeError: self.fail("_text_circuit_drawer() should be utf8.") self.assertFilesAreEqual(filename, self.text_reference_utf8, "utf8") os.remove(filename) def test_text_drawer_cp437(self): """Test that text drawer handles cp437 encoding.""" filename = "current_textplot_cp437.txt" qc = self.sample_circuit() output = _text_circuit_drawer( qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="cp437" ) try: encode(str(output), encoding="cp437") except UnicodeEncodeError: self.fail("_text_circuit_drawer() should be cp437.") self.assertFilesAreEqual(filename, self.text_reference_cp437, "cp437") os.remove(filename) if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_nature.second_q.drivers import GaussianForcesDriver # if you ran Gaussian elsewhere and already have the output file driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log") # if you want to run the Gaussian job from Qiskit # driver = GaussianForcesDriver( # ['#p B3LYP/6-31g Freq=(Anharm) Int=Ultrafine SCF=VeryTight', # '', # 'CO2 geometry optimization B3LYP/6-31g', # '', # '0 1', # 'C -0.848629 2.067624 0.160992', # 'O 0.098816 2.655801 -0.159738', # 'O -1.796073 1.479446 0.481721', # '', # '' from qiskit_nature.second_q.problems import HarmonicBasis basis = HarmonicBasis([2, 2, 2, 2]) from qiskit_nature.second_q.problems import VibrationalStructureProblem from qiskit_nature.second_q.mappers import DirectMapper vibrational_problem = driver.run(basis=basis) vibrational_problem.hamiltonian.truncation_order = 2 main_op, aux_ops = vibrational_problem.second_q_ops() print(main_op) qubit_mapper = DirectMapper() qubit_op = qubit_mapper.map(main_op) print(qubit_op) basis = HarmonicBasis([3, 3, 3, 3]) vibrational_problem = driver.run(basis=basis) vibrational_problem.hamiltonian.truncation_order = 2 main_op, aux_ops = vibrational_problem.second_q_ops() qubit_mapper = DirectMapper() qubit_op = qubit_mapper.map(main_op) print(qubit_op) # for simplicity, we will use the smaller basis again vibrational_problem = driver.run(basis=HarmonicBasis([2, 2, 2, 2])) vibrational_problem.hamiltonian.truncation_order = 2 from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver solver = GroundStateEigensolver( qubit_mapper, NumPyMinimumEigensolver(filter_criterion=vibrational_problem.get_default_filter_criterion()), ) result = solver.solve(vibrational_problem) print(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
mmetcalf14
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ This module contains the definition of a base class for feature map. Several types of commonly used approaches. """ import logging import numpy as np from qiskit import QuantumCircuit from qiskit.aqua.utils.arithmetic import next_power_of_2_base from qiskit.aqua.components.feature_maps import FeatureMap from qiskit.aqua.circuits import StateVectorCircuit logger = logging.getLogger(__name__) class RawFeatureVector(FeatureMap): """ Using raw feature vector as the initial state vector """ CONFIGURATION = { 'name': 'RawFeatureVector', 'description': 'Raw feature vector', 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'raw_feature_vector_schema', 'type': 'object', 'properties': { 'feature_dimension': { 'type': 'integer', 'default': 2, 'minimum': 1 }, }, 'additionalProperties': False } } def __init__(self, feature_dimension=2): """Constructor. Args: feature_vector: The raw feature vector """ self.validate(locals()) super().__init__() self._feature_dimension = feature_dimension self._num_qubits = next_power_of_2_base(feature_dimension) def construct_circuit(self, x, qr=None, inverse=False): """ Construct the second order expansion based on given data. Args: x (numpy.ndarray): 1-D to-be-encoded data. qr (QauntumRegister): the QuantumRegister object for the circuit, if None, generate new registers with name q. Returns: QuantumCircuit: a quantum circuit transform data x. """ if not isinstance(x, np.ndarray): raise TypeError("x must be numpy array.") if x.ndim != 1: raise ValueError("x must be 1-D array.") if x.shape[0] != self._feature_dimension: raise ValueError("Unexpected feature vector dimension.") state_vector = np.pad(x, (0, (1 << self.num_qubits) - len(x)), 'constant') svc = StateVectorCircuit(state_vector) return svc.construct_circuit(register=qr)
https://github.com/hamburgerguy/Quantum-Algorithm-Implementations
hamburgerguy
"""The following is python code utilizing the qiskit library that can be run on extant quantum hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding, for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1, results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>). To find the factor, use the equivalence a^r mod 15. From this: (a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15 Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients, gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15, so the result of running shors algorithm to find the prime factors of an integer using quantum hardware are demonstrated. Note, this is not the same as the technical implementation of shor's algorithm described in this section for breaking the discrete log hardness assumption, though the proof of concept remains.""" # Import libraries from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from numpy import pi from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute from qiskit.providers.ibmq import least_busy from qiskit.visualization import plot_histogram # Initialize qubit registers qreg_q = QuantumRegister(5, 'q') creg_c = ClassicalRegister(5, 'c') circuit = QuantumCircuit(qreg_q, creg_c) circuit.reset(qreg_q[0]) circuit.reset(qreg_q[1]) circuit.reset(qreg_q[2]) circuit.reset(qreg_q[3]) circuit.reset(qreg_q[4]) # Apply Hadamard transformations to qubit registers circuit.h(qreg_q[0]) circuit.h(qreg_q[1]) circuit.h(qreg_q[2]) # Apply first QFT, modular exponentiation, and another QFT circuit.h(qreg_q[1]) circuit.cx(qreg_q[2], qreg_q[3]) circuit.crx(pi/2, qreg_q[0], qreg_q[1]) circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4]) circuit.h(qreg_q[0]) circuit.rx(pi/2, qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.crx(pi/2, qreg_q[1], qreg_q[2]) circuit.cx(qreg_q[0], qreg_q[1]) # Measure the qubit registers 0-2 circuit.measure(qreg_q[2], creg_c[2]) circuit.measure(qreg_q[1], creg_c[1]) circuit.measure(qreg_q[0], creg_c[0]) # Get least busy quantum hardware backend to run on provider = IBMQ.load_account() device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and not x.configuration().simulator and x.status().operational==True)) print("Running on current least busy device: ", device) # Run the circuit on available quantum hardware and plot histogram from qiskit.tools.monitor import job_monitor job = execute(circuit, backend=device, shots=1024, optimization_level=3) job_monitor(job, interval = 2) results = job.result() answer = results.get_counts(circuit) plot_histogram(answer) #largest amplitude results correspond with r values used to find the prime factor of N.
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
GabrielPontolillo
from qiskit import QuantumCircuit def create_bell_pair(): qc = QuantumCircuit(2) qc.h(1) qc.cx(1, 0) return qc def encode_message(qc, qubit, msg): if len(msg) != 2 or not set([0,1]).issubset({0,1}): raise ValueError(f"message '{msg}' is invalid") if msg[1] == "1": qc.x(qubit) if msg[0] == "1": qc.z(qubit) return qc def decode_message(qc): qc.cx(1, 0) ### added y gate ### qc.y(0) qc.h(1) return qc
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from math import pi import numpy as np import rustworkx as rx from qiskit_nature.second_q.hamiltonians.lattices import ( BoundaryCondition, HyperCubicLattice, Lattice, LatticeDrawStyle, LineLattice, SquareLattice, TriangularLattice, ) from qiskit_nature.second_q.hamiltonians import FermiHubbardModel num_nodes = 11 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) line_lattice.draw() line_lattice.draw_without_boundary() num_nodes = 11 boundary_condition = BoundaryCondition.PERIODIC edge_parameter = 1.0 + 1.0j onsite_parameter = 1.0 line_lattice = LineLattice( num_nodes=num_nodes, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(line_lattice.graph.weighted_edge_list()) line_lattice.to_adjacency_matrix() line_lattice.to_adjacency_matrix(weighted=True) rows = 5 cols = 4 boundary_condition = BoundaryCondition.OPEN square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction square_lattice = SquareLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) square_lattice.draw() rows = 5 cols = 4 edge_parameter = (1.0, 1.0 + 1.0j) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.PERIODIC, ) # open in the x-direction, periodic in the y-direction onsite_parameter = 1.0 square_lattice = SquareLattice( rows=rows, cols=cols, edge_parameter=edge_parameter, onsite_parameter=onsite_parameter, boundary_condition=boundary_condition, ) set(square_lattice.graph.weighted_edge_list()) size = (3, 4, 5) boundary_condition = ( BoundaryCondition.OPEN, BoundaryCondition.OPEN, BoundaryCondition.OPEN, ) cubic_lattice = HyperCubicLattice(size=size, boundary_condition=boundary_condition) # function for setting the positions def indextocoord_3d(index: int, size: tuple, angle) -> list: z = index // (size[0] * size[1]) a = index % (size[0] * size[1]) y = a // size[0] x = a % size[0] vec_x = np.array([1, 0]) vec_y = np.array([np.cos(angle), np.sin(angle)]) vec_z = np.array([0, 1]) return_coord = x * vec_x + y * vec_y + z * vec_z return return_coord.tolist() pos = dict([(index, indextocoord_3d(index, size, angle=pi / 4)) for index in range(np.prod(size))]) cubic_lattice.draw(style=LatticeDrawStyle(pos=pos)) rows = 4 cols = 3 boundary_condition = BoundaryCondition.OPEN triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() rows = 4 cols = 3 boundary_condition = BoundaryCondition.PERIODIC triangular_lattice = TriangularLattice(rows=rows, cols=cols, boundary_condition=boundary_condition) triangular_lattice.draw() graph = rx.PyGraph(multigraph=False) # multigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) # make a lattice general_lattice = Lattice(graph) set(general_lattice.graph.weighted_edge_list()) general_lattice.draw() general_lattice.draw(self_loop=True) general_lattice.draw(self_loop=True, style=LatticeDrawStyle(with_labels=True)) square_lattice = SquareLattice(rows=5, cols=4, boundary_condition=BoundaryCondition.PERIODIC) t = -1.0 # the interaction parameter v = 0.0 # the onsite potential u = 5.0 # the interaction parameter U fhm = FermiHubbardModel( square_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) ham = fhm.second_q_op().simplify() print(ham) graph = rx.PyGraph(multigraph=False) # multiigraph shoud be False graph.add_nodes_from(range(6)) weighted_edge_list = [ (0, 1, 1.0 + 1.0j), (0, 2, -1.0), (2, 3, 2.0), (4, 2, -1.0 + 2.0j), (4, 4, 3.0), (2, 5, -1.0), ] graph.add_edges_from(weighted_edge_list) general_lattice = Lattice(graph) # the lattice whose weights are seen as the interaction matrix. u = 5.0 # the interaction parameter U fhm = FermiHubbardModel(lattice=general_lattice, onsite_interaction=u) ham = fhm.second_q_op().simplify() print(ham) from qiskit_nature.second_q.problems import LatticeModelProblem num_nodes = 4 boundary_condition = BoundaryCondition.OPEN line_lattice = LineLattice(num_nodes=num_nodes, boundary_condition=boundary_condition) fhm = FermiHubbardModel( line_lattice.uniform_parameters( uniform_interaction=t, uniform_onsite_potential=v, ), onsite_interaction=u, ) lmp = LatticeModelProblem(fhm) from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver from qiskit_nature.second_q.algorithms import GroundStateEigensolver from qiskit_nature.second_q.mappers import JordanWignerMapper numpy_solver = NumPyMinimumEigensolver() qubit_mapper = JordanWignerMapper() calc = GroundStateEigensolver(qubit_mapper, numpy_solver) res = calc.solve(lmp) print(res) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/zeynepCankara/Introduction-Quantum-Programming
zeynepCankara
# randomly create a 2-dimensional quantum state from random import randrange def random_quantum_state(): first_entry = randrange(101) first_entry = first_entry/100 first_entry = first_entry**0.5 if randrange(2) == 0: first_entry = -1 * first_entry second_entry = 1 - (first_entry**2) second_entry = second_entry**0.5 if randrange(2) == 0: second_entry = -1 * second_entry return [first_entry,second_entry] # import the drawing methods from matplotlib.pyplot import plot, figure # draw a figure figure(figsize=(6,6), dpi=60) # draw the origin plot(0,0,'ro') for i in range(100): # create a random quantum state quantum_state = random_quantum_state(); # draw a blue point for the random quantum state x = quantum_state[0]; y = quantum_state[1]; plot(x,y,'bo') # randomly create a 2-dimensional quantum state from random import randrange def random_quantum_state(): first_entry = randrange(101) first_entry = first_entry/100 first_entry = first_entry**0.5 if randrange(2) == 0: first_entry = -1 * first_entry second_entry = 1 - (first_entry**2) second_entry = second_entry**0.5 if randrange(2) == 0: second_entry = -1 * second_entry return [first_entry,second_entry] # import the drawing methods from matplotlib.pyplot import plot, figure, arrow %run qlatvia.py # draw a figure figure(figsize=(6,6), dpi=60) draw_axes(); # draw the origin plot(0,0,'ro') for i in range(100): # create a random quantum state quantum_state = random_quantum_state(); # draw a blue vector for the random quantum state x = quantum_state[0]; y = quantum_state[1]; # shorten the line length to 0.92 # line_length + head_length (0.08) should be 1 x = 0.92 * x y = 0.92 * y arrow(0,0,x,y,head_width=0.04,head_length=0.08,color="blue") # %%writefile FILENAME.py # import the drawing methods from matplotlib.pyplot import figure, arrow, text def display_quantum_state(x,y,name): x1 = 0.92 * x y1 = 0.92 * y arrow(0,0,x1,y1,head_width=0.04,head_length=0.08,color="blue") x2 = 1.15 * x y2 = 1.15 * y text(x2,y2,name) # # test your function # # import the drawing methods from matplotlib.pyplot import figure figure(figsize=(6,6), dpi=80) # size of the figure # include our predefined functions %run qlatvia.py # draw axes draw_axes() # draw the unit circle draw_unit_circle() for i in range(6): s = random_quantum_state() display_quantum_state(s[0],s[1],"v"+str(i)) #draw_quantum_state(s[0],s[1],"v"+str(i))
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit_optimization.algorithms import MinimumEigenOptimizer from qiskit.utils import algorithm_globals from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver from qiskit.algorithms.optimizers import COBYLA from qiskit.primitives import Sampler from qiskit_optimization.applications.vertex_cover import VertexCover import networkx as nx seed = 123 algorithm_globals.random_seed = seed graph = nx.random_regular_graph(d=3, n=6, seed=seed) pos = nx.spring_layout(graph, seed=seed) prob = VertexCover(graph) prob.draw(pos=pos) qp = prob.to_quadratic_program() print(qp.prettyprint()) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) prob.draw(result, pos=pos) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time) prob.draw(result, pos=pos) from qiskit_optimization.applications import Knapsack prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # Numpy Eigensolver meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver()) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) # QAOA meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, sampler=Sampler(), optimizer=COBYLA())) result = meo.solve(qp) print(result.prettyprint()) print("\nsolution:", prob.interpret(result)) print("\ntime:", result.min_eigen_solver_result.optimizer_time) from qiskit_optimization.converters import QuadraticProgramToQubo # the same knapsack problem instance as in the previous section prob = Knapsack(values=[3, 4, 5, 6, 7], weights=[2, 3, 4, 5, 6], max_weight=10) qp = prob.to_quadratic_program() print(qp.prettyprint()) # intermediate QUBO form of the optimization problem conv = QuadraticProgramToQubo() qubo = conv.convert(qp) print(qubo.prettyprint()) # qubit Hamiltonian and offset op, offset = qubo.to_ising() print(f"num qubits: {op.num_qubits}, offset: {offset}\n") print(op) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
PacktPublishing
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ # Import the required Qiskit classes from qiskit import(QuantumCircuit, execute, Aer) # Import Blochsphere visualization from qiskit.visualization import plot_bloch_multivector, plot_state_qsphere # Import some math that we will need from IPython.core.display import display # Set numbers display options import numpy as np np.set_printoptions(precision=3) # Create a function that requests and display the state vector # Use this function as a diagnositc tool when constructing your circuits def measure(circuit): measure_circuit=QuantumCircuit(circuit.width()) measure_circuit+=circuit measure_circuit.measure_all() #print(measure_circuit) backend_count = Aer.get_backend('qasm_simulator') counts=execute(measure_circuit, backend_count,shots=10000).result().get_counts(measure_circuit) # Print the counts of the measured outcome. print("\nOutcome:\n",{k: v / total for total in (sum(counts.values())/100,) for k, v in counts.items()},"\n") def s_vec(circuit): backend = Aer.get_backend('statevector_simulator') print(circuit.num_qubits, "qubit quantum circuit:\n------------------------") print(circuit) psi=execute(circuit, backend).result().get_statevector(circuit) print("State vector for the",circuit.num_qubits,"qubit circuit:\n\n",psi) print("\nState vector as Bloch sphere:") display(plot_bloch_multivector(psi)) print("\nState vector as Q sphere:") display(plot_state_qsphere(psi)) measure(circuit) input("Press enter to continue...\n") # Main loop def main(): user_input=1 while user_input!=0: print("Ch 7: Running “diagnostics” with the state vector simulator") print("-----------------------------------------------------------") user_input=int(input("\nNumber of qubits:\n")) circ_type=input("Superposition 's or entanglement 'e'?\n(To add a phase angle, use 'sp or 'ep'.)\n") if user_input>0: qc = QuantumCircuit(user_input) s_vec(qc) qc.h(user_input-1) s_vec(qc) if user_input>1: for n in range(user_input-1): if circ_type in ["e","ep"]: qc.cx(user_input-1,n) else: qc.h(n) s_vec(qc) if circ_type in ["sp","ep"]: qc.t(user_input-1) s_vec(qc) if __name__ == '__main__': main()
https://github.com/usamisaori/quantum-expressibility-entangling-capability
usamisaori
import sys sys.path.append('../') from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\ sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\ sampleCircuitF from entanglement import Ent import warnings warnings.filterwarnings('ignore') labels = [ 'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3', 'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F' ] samplers = [ sampleCircuitA, sampleCircuitB1, sampleCircuitB2, sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE, sampleCircuitF ] q = 4 for layer in range(1, 4): print(f'qubtis: {q}') print('-' * 25) for (label, sampler) in zip(labels, samplers): expr = Ent(sampler, layer=layer, epoch=3000) print(f'{label}(layer={layer}): {expr}') print()
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
shesha-raghunathan
from random import randrange for experiment in [100,1000,10000,100000]: heads = tails = 0 for i in range(experiment): if randrange(2) == 0: heads = heads + 1 else: tails = tails + 1 print("experiment:",experiment) print("the ratio of #heads/#tails is",(heads/tails),"heads =",heads,"tails = ",tails) print() # empty line from random import randrange # let's pick a random number between {0,1,...,99} # it is expected to be less than 60 with probability 0.6 # and greater than or equal to 60 with probability 0.4 for experiment in [100,1000,10000,100000]: heads = tails = 0 for i in range(experiment): if randrange(100) <60: heads = heads + 1 # probability with 0.6 else: tails = tails + 1 # probability with 0.4 print("experiment:",experiment) print("the ratio of #heads/#tails is",(heads/tails),"heads =",heads,"tails = ",tails) print() # empty line
https://github.com/1chooo/Quantum-Oracle
1chooo
#Below are examples of using print function print('The name of the language is',"Python") print("The radius of the circle is", 3, '\nIts area is', 3.14159*3**2) #Below are examples of using print function print('The name of the language is',"Python",end=". ") print('Its version is',"3.x",sep="....") print("The radius of the circle is", 3) print("The area of the circle is", 3.14159*3**2) r=input('Please enter the radius of the circle:') print('The radius of the circle:', r) r=input('Please enter the radius of the circle:') ri=int(r) rf=float(r) print('The radius of the circle:', ri) print("The area of the circle:", 3.14159*rf**2) a=123;b=123.456;c=False;d=123+456j;e="123";f=[1,2,3];g=(1,2,3);h={1,2,3};i={1:'x',2:'y',3:'z'} print(type(a),type(b),type(c),type(d),type(e),type(f),type(g),type(h),type(i)) a=3;b=8 print(a+b) #11 print(a-b) #-5 print(a*b) #24 print(a/b) #0.375 print(a//b) #0 print(a%b) #3 print(a**b) #6561 print(a+b//a**b) #3 print((a+b)//a**b) #0 a=3.0;b=8.0;c=8 print(a+b) #11.0 print(a-b) #-5.0 print(a*b) #24.0 print(a/b) #0.375 print(a//b) #0.0 print(a%b) #3.0 print(a**b) #6561.0 print(a+c) #11.0 print(a+b//a**b) #3.0 print((a+b)//a**b) #0.0 a=3.0;b=8.0;c=8 print(a==b) #False print(a!=b) #True print(a>b) #False print(a<b) #True print(a>=b) #False print(a<=b) #True print(not (a==b)) #True print(a==b or a!=b and a>b) #False print(a==b and a>b or a!=b) #True print(a==b and a>b or not (a!=b)) #False a=2+4j;b=3-8j print(a+b) #(5-4j) print(a-b) #(-1+12j) print(a*b) #(38-4j) print(a/b) #(-0.3561643835616438+0.3835616438356164j) print(a+b/a) #(0.7+2.6j) print((a+b)/a) #(-0.3-1.4j) print(a.real) #2.0 print(a.imag) #4.0 print(a.conjugate()) #(2-4j) print(abs(a)) #4.47213595499958 a={1,2,3};b={2,4,6} print(a|b) #{1, 2, 3, 4, 6} print(a.union(b)) #{1, 2, 3, 4, 6} print(a&b) #{2} print(a.intersection(b)) #{2} print(a-b) #{1,3} print(a.difference(b)) #{1,3} print(a^b) #{1,3,4,6} print(a.symmetric_difference(b)) #{1,3,4,6} ex = {"a":1, "b":2, "c":3, 1: "integer", 2.3: "float", 4+5j: "complex", (6,7): "tuple"} print(ex["a"],ex["b"],ex["c"],ex[1],ex[2.3],ex[4+5j],ex[(6,7)]) ex["a"]=100 print(ex["a"]) print(len(ex)) ex["d"]=4 print(ex.get("d")) del ex["d"] print(ex.get("d")) print("e" in ex) print("e" not in ex) print(ex.keys()) print(ex.values()) a=5 a+=3 #a=a+3 (a=8) a-=3 #a=a-3 (a=5) a*=3 #a=a*3 (a=15) a%=8 #a=a%8 (a=7) a//=3 #a=a//3 (a=2) a/=3 #a=a/3 (a=0.6666666666666666) a**=3 #a=a**3 (a=0.2962962962962962) print(a) score=90 if score >=60: print("PASS") score=90 if score >=60: print("PASS") else: print("FAIL") score=90 if score >=90: print("A") elif score >= 80: print("B") elif score >= 70: print("C") elif score >= 60: print("D") else: print("F") i=0 while i<5: i+=1 print(i,end="") i=0 while i<5: i+=1 print(i,end="") else: print("#") for i in [1,2,3,4,5]: print(i,end="") for i in [1,2,3,4,5]: print(i,end="") else: print("#") print(list(range(5))) #range(5)會回傳0、1、2、3、4 print(list(range(2,5))) #range(2,5)會回傳2、3、4 print(list(range(0,5,2))) #range(0,2,5)會回傳0、2、4 print(list(range(5,0,-1))) #range(5,0,-1)會回傳5、4、3、2、1 print(list(range(5,0))) #range(5,0)是一個空序列 i=0 while i<5: i+=1 if i==3: break print(i,end="") for i in range(1,6): if i==3: break print(i,end="") i=0 while i<5: i+=1 if i==3: continue print(i,end="") for i in range(1,6): if i==3: continue print(i,end="") def odd_check(n): """Check if n is odd (return True) or not (return False).""" if n%2==0: return False else: return True print(odd_check(5)) print(odd_check(10)) def test(aa,bb,cc=123,dd='abc'): return aa,bb,cc,dd print(test(1,2,3,4)) print(test(1,2,3)) print(test(1,2,dd='edf')) print(test(1,2)) def adding(*num): sum=0 for n in num: sum+=n return sum print(adding(1,2,3,4,5)) adding = lambda x,y: x+y print(adding(3,8)) #顯示11 print((lambda x,y: x+y)(3,8)) #顯示11 lista=[1,3,5,7,9] #以下將lambda函數當作map函數的參數 listb=list(map(lambda x:x+8, lista)) print(listb) class Rectangle: length=0 width=0 def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*(self.length+self.width) rect1=Rectangle(3,8) rect2=Rectangle(2,4) print('rect1:',rect1.length,rect1.width,rect1.area(),rect1.perimeter()) print('rect2:',rect2.length,rect2.width,rect2.area(),rect2.perimeter()) class NamedRectangle(Rectangle): name='' def __init__(self,length,width,name): super().__init__(length,width) self.name=name def show_name(self): print(self.name) rect1=NamedRectangle(3,8,'rectangle1') rect2=NamedRectangle(2,4,'rectangle2') print('rect1:',rect1.length,rect1.width,rect1.area(),rect1.perimeter()) print('rect2:',rect2.length,rect2.width,rect2.area(),rect2.perimeter()) rect1.show_name() rect2.show_name()
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
MonitSharma
from IPython.display import Image, display Image("ryoko.png", width="70") Image('asteroids_example.png') Image('asteroids_beam_example.png') Image('false_asteroids_example.png') Image('asteroids_example.png') problem_set = \ [[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']], [['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']], [['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']], [['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']], [['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']], [['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']], [['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']], [['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']], [['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']], [['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']], [['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']], [['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]] import numpy as np # import qiskit libraries from qiskit import IBMQ, Aer,QuantumRegister, ClassicalRegister, QuantumCircuit, execute from qiskit.tools.jupyter import * from qiskit.circuit.library import OR as or_gate provider = IBMQ.load_account() #import functions to plot from qiskit.visualization import plot_histogram def week3_ans_func(problem_set): ##### build your quantum circuit here ##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs. def qRAM(qc,add,data, auxiliary, problem_set): problem_set_mapping_dict = {'0' : {'0': 0, '1': 1, '2': 2, '3':3}, '1' : {'0': 4, '1': 5, '2': 6, '3':7}, '2' : {'0': 8, '1': 9, '2': 10, '3':11}, '3' : {'0': 12, '1': 13, '2': 14, '3':15}} for ind in range(len(data)): binary = f'{ind:04b}' if(binary[0] == '0'): qc.x(add[0]) if(binary[1] == '0'): qc.x(add[1]) if(binary[2] == '0'): qc.x(add[2]) if(binary[3] == '0'): qc.x(add[3]) for i, edg in enumerate(problem_set[ind]): qc.ch(add[0],auxiliary[0]) qc.cz(add[1],auxiliary[0]) qc.ch(add[0], auxiliary[0]) #qc.ccx(add[0], add[1], auxiliary[0]) qc.ch(add[2],auxiliary[1]) qc.cz(add[3],auxiliary[1]) qc.ch(add[2], auxiliary[1]) #qc.ccx(add[2], add[3], auxiliary[1]) qc.ch(auxiliary[0],auxiliary[2]) qc.cz(auxiliary[1],auxiliary[2]) qc.ch(auxiliary[0],auxiliary[2]) #qc.ccx(auxiliary[0], auxiliary[1], auxiliary[2]) qc.cx(auxiliary[2], data[problem_set_mapping_dict[edg[0]][edg[1]]]) qc.ch(auxiliary[0],auxiliary[2]) qc.cz(auxiliary[1],auxiliary[2]) qc.ch(auxiliary[0],auxiliary[2]) qc.ch(add[2],auxiliary[1]) qc.cz(add[3],auxiliary[1]) qc.ch(add[2], auxiliary[1]) qc.ch(add[0],auxiliary[0]) qc.cz(add[1],auxiliary[0]) qc.ch(add[0], auxiliary[0]) if(binary[0] == '0'): qc.x(add[0]) if(binary[1] == '0'): qc.x(add[1]) if(binary[2] == '0'): qc.x(add[2]) if(binary[3] == '0'): qc.x(add[3]) qc.barrier() def diffuser(nqubits): qc_diff = QuantumCircuit(nqubits) for qubit in range(nqubits): qc_diff.h(qubit) for qubit in range(nqubits): qc_diff.x(qubit) qc_diff.h(nqubits-1) qc_diff.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli qc_diff.h(nqubits-1) for qubit in range(nqubits): qc_diff.x(qubit) for qubit in range(nqubits): qc_diff.h(qubit) U_f0 = qc_diff.to_gate() U_f0.name = "V" return U_f0 def add_row_counters(qc, data, auxiliary): row_mat = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]] for i, curr_row in enumerate(row_mat): flag_list = [0] * len(data) for curr_flag_index in range(len(data)): if curr_flag_index in curr_row: flag_list[curr_flag_index] = 1 qc.append(or_gate(len(data), flag_list, mcx_mode='noancilla'), [*data, auxiliary[i]]) def add_column_counters(qc, data, auxiliary): col_mat = [[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15]] for i, curr_col in enumerate(col_mat): flag_list = [0] * len(data) for curr_flag_index in range(len(data)): if curr_flag_index in curr_col: flag_list[curr_flag_index] = 1 qc.append(or_gate(len(data), flag_list, mcx_mode='noancilla'), [*data, auxiliary[i]]) def add_lone_counters(qc, data, auxiliary, count_out): lone_mat = [[0, 1, 2, 3, 4, 8, 12], [1, 0, 2, 3, 5, 9, 13], [2, 0, 1, 3, 6, 10, 14], [3, 0, 1, 2, 7, 11, 15], [4, 5, 6, 7, 0, 8, 12], [5, 4, 6, 7, 1, 9, 13], [6, 4, 5, 7, 2, 10, 14], [7, 4, 5, 6, 3, 11, 15], [8, 9, 10, 11, 0, 4, 12], [9, 8, 10, 11, 1, 5, 13], [10, 8, 9, 11, 2, 6, 14], [11, 8, 9, 10, 3, 7, 15], [12, 13, 14, 15, 0, 4, 8], [13, 12, 14, 15, 1, 5, 9], [14, 12, 13, 15, 2, 6, 10], [15, 12, 13, 14, 3, 7, 11]] qc.barrier() #curr_lone_row = [0, 1, 2, 3, 4, 8, 12] for curr_lone_row in lone_mat: n = len(curr_lone_row) for j in range(1,n): qc.x(data[curr_lone_row[j]]) qc.ch(data[curr_lone_row[0]], auxiliary[0]) qc.cz(data[curr_lone_row[1]], auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) #qc.ccx(data[curr_lone_row[0]], data[curr_lone_row[1]], auxiliary[0]) qc.ch(data[curr_lone_row[2]],auxiliary[1]) qc.cz(data[curr_lone_row[3]],auxiliary[1]) qc.ch(data[curr_lone_row[2]],auxiliary[1]) #qc.ccx(data[curr_lone_row[2]], data[curr_lone_row[3]], auxiliary[1]) qc.ch(auxiliary[0],auxiliary[2]) qc.cz(auxiliary[1],auxiliary[2]) qc.ch(auxiliary[0],auxiliary[2]) #qc.ccx(auxiliary[0], auxiliary[1], auxiliary[2]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) qc.cz(data[curr_lone_row[1]],auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) #qc.ccx(data[curr_lone_row[0]], data[curr_lone_row[1]], auxiliary[0]) qc.ch(data[curr_lone_row[4]],auxiliary[0]) qc.cz(data[curr_lone_row[5]],auxiliary[0]) qc.ch(data[curr_lone_row[4]],auxiliary[0]) #qc.ccx(data[curr_lone_row[4]], data[curr_lone_row[5]], auxiliary[0]) qc.ch(auxiliary[0],auxiliary[3]) qc.cz(auxiliary[2],auxiliary[3]) qc.ch(auxiliary[0],auxiliary[3]) #qc.ccx(auxiliary[0], auxiliary[2], auxiliary[3]) #------------------------------------------------------------------------------------------------------------------------ #qc.ch(data[curr_lone_row[6]], count_out[2]) #qc.cz(auxiliary[3],count_out[2]) #qc.ch(data[curr_lone_row[2]],count_out[2]) qc.ccx(data[curr_lone_row[6]], auxiliary[3], count_out[2]) #this CCX is important to avoid #unnecessary addition of relative phase #------------------------------------------------------------------------------------------------------------------------ qc.ch(auxiliary[0],auxiliary[3]) qc.cz(auxiliary[2],auxiliary[3]) qc.ch(auxiliary[0],auxiliary[3]) qc.ch(data[curr_lone_row[4]],auxiliary[0]) qc.cz(data[curr_lone_row[5]],auxiliary[0]) qc.ch(data[curr_lone_row[4]],auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) qc.cz(data[curr_lone_row[1]],auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) qc.ch(auxiliary[0],auxiliary[2]) qc.cz(auxiliary[1],auxiliary[2]) qc.ch(auxiliary[0],auxiliary[2]) qc.ch(data[curr_lone_row[2]],auxiliary[1]) qc.cz(data[curr_lone_row[3]],auxiliary[1]) qc.ch(data[curr_lone_row[2]],auxiliary[1]) qc.ch(data[curr_lone_row[0]], auxiliary[0]) qc.cz(data[curr_lone_row[1]], auxiliary[0]) qc.ch(data[curr_lone_row[0]],auxiliary[0]) for j in range(1,n): qc.x(data[curr_lone_row[j]]) qc.barrier def u3a(data, auxiliary,oracle, count_out): qc_1 = QuantumCircuit(data, auxiliary,oracle, count_out) #Oracle ----------------------------------------------- #Adding Row counters to check if each row has at least 1 asteroid and then flipping a count_out bit if all rows has at least one asteroid add_row_counters(qc_1, data, auxiliary) #compute qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[0], mode = 'noancilla') add_row_counters(qc_1, data, auxiliary) #uncompute #Adding column counters to check if each column has at least 1 asteroid and then flipping a count_out bit if all columns has at least one asteroid add_column_counters(qc_1, data, auxiliary) #compute qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[1], mode = 'noancilla') add_column_counters(qc_1, data, auxiliary) #uncompute #qc_1.barrier() #lone asteroid counter circuit to add add_lone_counters(qc_1, data, auxiliary, count_out) return qc_1 def u3a_dagger(data, auxiliary, oracle, count_out): qc_1 = QuantumCircuit(data, auxiliary,oracle, count_out) #Oracle ----------------------------------------------- #Adding Row counters to check if each row has at least 1 asteroid and then flipping a count_out bit if all rows has at least one asteroid add_row_counters(qc_1, data, auxiliary) #compute qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[0], mode = 'noancilla') add_row_counters(qc_1, data, auxiliary) #uncompute #Adding column counters to check if each column has at least 1 asteroid and then flipping a count_out bit if all columns has at least one asteroid add_column_counters(qc_1, data, auxiliary) #compute qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[1], mode = 'noancilla') add_column_counters(qc_1, data, auxiliary) #uncompute #qc_1.barrier() #lone asteroid counter circuit to add add_lone_counters(qc_1, data, auxiliary, count_out) qc_2 = qc_1.inverse() return qc_2 add = QuantumRegister(4, name = 'address') data = QuantumRegister(16, name = 'data') auxiliary = QuantumRegister(4, name = 'auxiliary') count_out = QuantumRegister(3, name = 'counter_outputs') oracle = QuantumRegister(1, name = 'oracle') cbits = ClassicalRegister(4, name = 'solution') qc = QuantumCircuit(add, data, auxiliary,oracle, count_out, cbits) qc.x(oracle) qc.h(oracle) qc.h(add) qc.barrier() #Add qRAM qRAM(qc,add,data, auxiliary, problem_set) #compute qc.barrier() # counters qc.extend(u3a(data, auxiliary,oracle, count_out)) qc.barrier() # Phase flipping oracle #qc.cx(auxiliary[6], oracle) qc.mct([count_out[0], count_out[1], count_out[2]], oracle, mode = 'noancilla') # ------------------------------------------------------- # counters - dagger qc.extend(u3a_dagger(data, auxiliary,oracle, count_out)) qc.barrier() #qRAM qc.barrier() qRAM(qc,add,data, auxiliary, problem_set) #uncompute qc.barrier() #diffuser qc.append(diffuser(4), add) qc.barrier() #measure qc.measure(add[0], cbits[0]) qc.measure(add[1], cbits[1]) qc.measure(add[2], cbits[2]) qc.measure(add[3], cbits[3]) return qc # Submission code from qc_grader import grade_ex3, prepare_ex3, submit_ex3 # Execute your circuit with following prepare_ex3() function. # The prepare_ex3() function works like the execute() function with only QuantumCircuit as an argument. job = prepare_ex3(week3_ans_func) result = job.result() counts = result.get_counts() original_problem_set_counts = counts[0] original_problem_set_counts # The bit string with the highest number of observations is treated as the solution. # Check your answer by executing following code. # The quantum cost of the QuantumCircuit is obtained as the score. The lower the cost, the better. grade_ex3(job) # Submit your results by executing following code. You can submit as many times as you like during the period. submit_ex3(job)
https://github.com/Z-928/Bugs4Q
Z-928
from qiskit import Aer, QuantumCircuit, transpile from qiskit.circuit.library import PhaseEstimation qc= QuantumCircuit(3,3) # dummy unitary circuit unitary_circuit = QuantumCircuit(1) unitary_circuit.h(0) # QPE qc.append(PhaseEstimation(2, unitary_circuit), list(range(3))) qc.measure(list(range(3)), list(range(3))) backend = Aer.get_backend('qasm_simulator') qc_transpiled = transpile(qc, backend) result = backend.run(qc, shots = 8192).result()
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
mistryiam
# General tools import numpy as np import matplotlib.pyplot as plt # Qiskit Circuit Functions from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile import qiskit.quantum_info as qi # Tomography functions from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter import warnings warnings.filterwarnings('ignore') target = QuantumCircuit(2) #target = # YOUR CODE HERE target.h(0) target.h(1) target.rx(np.pi/2,0) target.rx(np.pi/2,1) target.cx(0,1) target.p(np.pi,1) target.cx(0,1) target_unitary = qi.Operator(target) target.draw('mpl') from qc_grader import grade_lab5_ex1 # Note that the grading function is expecting a quantum circuit with no measurements grade_lab5_ex1(target) simulator = Aer.get_backend('qasm_simulator') qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192) qpt_result = qpt_job.result() # YOUR CODE HERE qpt_tomo= ProcessTomographyFitter(qpt_result,qpt_circs) Choi_qpt= qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(Choi_qpt,target_unitary) from qc_grader import grade_lab5_ex2 # Note that the grading function is expecting a floating point number grade_lab5_ex2(fidelity) # T1 and T2 values for qubits 0-3 T1s = [15000, 19000, 22000, 14000] T2s = [30000, 25000, 18000, 28000] # Instruction times (in nanoseconds) time_u1 = 0 # virtual gate time_u2 = 50 # (single X90 pulse) time_u3 = 100 # (two X90 pulses) time_cx = 300 time_reset = 1000 # 1 microsecond time_measure = 1000 # 1 microsecond from qiskit.providers.aer.noise import thermal_relaxation_error from qiskit.providers.aer.noise import NoiseModel # QuantumError objects errors_reset = [thermal_relaxation_error(t1, t2, time_reset) for t1, t2 in zip(T1s, T2s)] errors_measure = [thermal_relaxation_error(t1, t2, time_measure) for t1, t2 in zip(T1s, T2s)] errors_u1 = [thermal_relaxation_error(t1, t2, time_u1) for t1, t2 in zip(T1s, T2s)] errors_u2 = [thermal_relaxation_error(t1, t2, time_u2) for t1, t2 in zip(T1s, T2s)] errors_u3 = [thermal_relaxation_error(t1, t2, time_u3) for t1, t2 in zip(T1s, T2s)] errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand( thermal_relaxation_error(t1b, t2b, time_cx)) for t1a, t2a in zip(T1s, T2s)] for t1b, t2b in zip(T1s, T2s)] # Add errors to noise model noise_thermal = NoiseModel() for j in range(4): noise_thermal.add_quantum_error(errors_measure[j],'measure',[j]) noise_thermal.add_quantum_error(errors_reset[j],'reset',[j]) noise_thermal.add_quantum_error(errors_u3[j],'u3',[j]) noise_thermal.add_quantum_error(errors_u2[j],'u2',[j]) noise_thermal.add_quantum_error(errors_u1[j],'u1',[j]) for k in range(4): noise_thermal.add_quantum_error(errors_cx[j][k],'cx',[j,k]) # YOUR CODE HERE from qc_grader import grade_lab5_ex3 # Note that the grading function is expecting a NoiseModel grade_lab5_ex3(noise_thermal) np.random.seed(0) noise_qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE noise_qpt_job = execute(noise_qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal) noise_qpt_result = noise_qpt_job.result() # YOUR CODE HERE noise_qpt_tomo= ProcessTomographyFitter(noise_qpt_result,noise_qpt_circs) noise_Choi_qpt= noise_qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(noise_Choi_qpt,target_unitary) from qc_grader import grade_lab5_ex4 # Note that the grading function is expecting a floating point number grade_lab5_ex4(fidelity) np.random.seed(0) # YOUR CODE HERE #qr = QuantumRegister(2) qubit_list = [0,1] meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list) meas_calibs_job = execute(meas_calibs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal) cal_results = meas_calibs_job.result() meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list) Cal_result = meas_fitter.filter.apply(noise_qpt_result) # YOUR CODE HERE Cal_qpt_tomo= ProcessTomographyFitter(Cal_result,noise_qpt_circs) Cal_Choi_qpt= Cal_qpt_tomo.fit(method='lstsq') fidelity = qi.average_gate_fidelity(Cal_Choi_qpt,target_unitary) from qc_grader import grade_lab5_ex5 # Note that the grading function is expecting a floating point number grade_lab5_ex5(fidelity)
https://github.com/msramalho/Teach-Me-Quantum
msramalho
import pylab from qiskit_aqua import run_algorithm from qiskit_aqua.input import get_input_instance from qiskit.tools.visualization import matplotlib_circuit_drawer as draw from qiskit.tools.visualization import plot_histogram with open('3sat3-5.cnf', 'r') as f: sat_cnf = f.read() print(sat_cnf) algorithm_cfg = { 'name': 'Grover' } oracle_cfg = { 'name': 'SAT', 'cnf': sat_cnf } params = { 'problem': {'name': 'search', 'random_seed': 50}, 'algorithm': algorithm_cfg, 'oracle': oracle_cfg, 'backend': {'name': 'qasm_simulator'} } result = run_algorithm(params) print(result['result']) pylab.rcParams['figure.figsize'] = (8, 4) plot_histogram(result['measurements']) #draw(result['circuit'])
https://github.com/weiT1993/qiskit_helper_functions
weiT1993
from .Qbit_original import Qbit from .cz_layer_generation import get_layers from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister import math import sys import numpy as np class Qgrid: """ Class to implement the quantum supremacy circuits as found in https://www.nature.com/articles/s41567-018-0124-x and https://github.com/sboixo/GRCS. Each instance is a 2D array whose entries at Qbit objects. A supremacy circuit can be generated for a given instance by calling the gen_circuit() method. Attributes ---------- n : int number of rows in the grid m : int number of columns in the grid d : int depth of the supremacy circuit (excludes H-layer and measurement i.e. 1+d+1) regname : str optional string to name the quantum and classical registers. This allows for the easy concatenation of multiple QuantumCircuits. qreg : QuantumRegister Qiskit QuantumRegister holding all of the qubits creg : ClassicalRegister Qiskit ClassicalRegister holding all of the classical bits circ : QuantumCircuit Qiskit QuantumCircuit that represents the supremacy circuit grid : array n x m array holding Qbit objects cz_list : list List of the CZ-gate indices for each layer of the supremacy circuit mirror : bool Boolean indicating whether the cz layers should repeat exactly or in reverse order order : list list of indices indicting the order the cz layers should be placed singlegates : bool Boolean indicating whether to include single qubit gates in the circuit """ def __init__( self, n, m, d, order=None, singlegates=True, mirror=True, barriers=True, measure=False, regname=None, ): self.n = n self.m = m self.d = d if regname is None: self.qreg = QuantumRegister(n * m) self.creg = ClassicalRegister(n * m) else: self.qreg = QuantumRegister(n * m, name=regname) self.creg = ClassicalRegister(n * m, name="c" + regname) # It is easier to interface with the circuit cutter # if there is no Classical Register added to the circuit self.measure = measure if self.measure: self.circ = QuantumCircuit(self.qreg, self.creg) else: self.circ = QuantumCircuit(self.qreg) self.grid = self.make_grid(n, m) self.cz_list = get_layers(n, m) self.mirror = mirror self.barriers = barriers if order is None: # Default self.random = False # Use the default Google order (https://github.com/sboixo/GRCS) self.order = [0, 5, 1, 4, 2, 7, 3, 6] elif order == "random": # Random order self.random = True self.order = np.arange(len(self.cz_list)) if self.mirror is True: raise Exception( "Order cannot be random and mirror cannot be True simultaneously. Exiting." ) else: # Convert given order string to list of ints self.random = False self.order = [int(c) for c in order] self.singlegates = singlegates def make_grid(self, n, m): temp_grid = [] index_ctr = 0 for row in range(n): cur_row = [] for col in range(m): cur_row += [Qbit(index_ctr, None)] index_ctr += 1 temp_grid += [cur_row] return temp_grid def get_index(self, index1=None, index2=None): if index2 is None: return self.grid[index1[0]][index1[1]].index else: return self.grid[index1][index2].index def print_circuit(self): print(self.circ.draw(scale=0.6, output="text", reverse_bits=False)) def save_circuit(self): str_order = [str(i) for i in self.order] if self.mirror: str_order.append("m") fn = "supr_{}x{}x{}_order{}.txt".format( self.n, self.m, self.d, "".join(str_order) ) self.circ.draw( scale=0.8, filename=fn, output="text", reverse_bits=False, line_length=160 ) def hadamard_layer(self): for i in range(self.n): for j in range(self.m): self.circ.h(self.qreg[self.grid[i][j].h()]) def measure_circuit(self): self.circ.barrier() for i in range(self.n): for j in range(self.m): qubit_index = self.get_index(i, j) self.circ.measure(self.qreg[qubit_index], self.creg[qubit_index]) def apply_postCZ_gate(self, grid_loc, reserved_qubits): qb_index = self.get_index(grid_loc) if qb_index not in reserved_qubits: gate = self.grid[grid_loc[0]][grid_loc[1]].random_gate() if gate == "Y": # Apply a sqrt-Y gate to qubit at qb_index self.circ.ry(math.pi / 2, self.qreg[qb_index]) elif gate == "X": # Apply a sqrt-X gate to qubit at qb_index self.circ.rx(math.pi / 2, self.qreg[qb_index]) else: print("ERROR: unrecognized gate: {}".format(gate)) # successfully applied random gate return True else: # did not apply gate return False def apply_T(self, grid_loc, reserved_qubits): """ Apply a T gate on the specified qubit if it is not currently involved in a CZ gate grid_loc = [row_idx, col_idx] """ qb_index = self.get_index(grid_loc[0], grid_loc[1]) if qb_index not in reserved_qubits: self.circ.t(self.qreg[qb_index]) # successfully applied T gate return True else: # Currently involved in a CZ gate return False def gen_circuit(self): # print('Generating {}x{}, 1+{}+1 supremacy circuit'.format(self.n,self.m,self.d)) # Initialize with Hadamards self.hadamard_layer() # Iterate through CZ layers cz_idx = -1 nlayer = len(self.cz_list) for i in range(self.d): prev_idx = cz_idx if self.mirror is True: if (i // nlayer) % 2 == 0: cz_idx = self.order[i % nlayer] else: cz_idx = self.order[::-1][i % nlayer] elif self.random is True: cur_mod = i % nlayer if cur_mod == 0: random_order = np.random.permutation(self.order) cz_idx = random_order[cur_mod] else: cz_idx = random_order[cur_mod] else: cz_idx = self.order[i % nlayer] cur_CZs = self.cz_list[cz_idx] pre_CZs = self.cz_list[prev_idx] reserved_qubits = [] # Apply entangling CZ gates for cz in cur_CZs: ctrl = self.get_index(cz[0]) trgt = self.get_index(cz[1]) reserved_qubits += [ctrl, trgt] self.circ.cz(self.qreg[ctrl], self.qreg[trgt]) if i == 0 and self.singlegates: # Apply T gates on all first layer qubits not involved in a CZ for n in range(self.n): for m in range(self.m): self.apply_T([n, m], reserved_qubits) if i > 1 and self.singlegates: # Apply T gates to all qubits which had a X_1_2 or # Y_1_2 in the last cycle and are not involved in # a CZ this cycle for grid_loc in prev_nondiag_gates: self.apply_T(grid_loc, reserved_qubits) if i > 0 and self.singlegates: # Apply non-diagonal single qubit gates to qubits which # were involved in a CZ gate in the previous cycle prev_nondiag_gates = [] for cz in pre_CZs: for grid_loc in cz: success = self.apply_postCZ_gate(grid_loc, reserved_qubits) if success: prev_nondiag_gates.append(grid_loc) if self.barriers: self.circ.barrier() # End CZ-layers # Apply a layer of Hadamards before measurement self.hadamard_layer() # Measurement if self.measure: self.measure_circuit() return self.circ def gen_qasm(self): return self.circ.qasm()
https://github.com/usamisaori/quantum-expressibility-entangling-capability
usamisaori
import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab from mpl_toolkits.mplot3d import Axes3D plt.rc('font',family='Microsoft YaHei') plt.rcParams['axes.unicode_minus'] = False palettes = [ "#999999", "#FFEE00", "#FF9900", "#FF3636", "#99CC33", "#66CCCC", "#3399CC", "#9966CC" ] plt.scatter(0.1, 0.1, color=palettes[0]) plt.scatter(0.2, 0.2, color=palettes[1]) plt.scatter(0.3, 0.3, color=palettes[2]) plt.scatter(0.4, 0.4, color=palettes[3]) plt.scatter(0.5, 0.5, color=palettes[4]) plt.scatter(0.6, 0.6, color=palettes[5]) plt.scatter(0.7, 0.7, color=palettes[6]) plt.scatter(0.8, 0.8, color=palettes[7]) # Expressibility Entanglement plt.figure(figsize=(8, 5)) c1 = "#FF6666" c2 = "#FF9900" c3 = "#66CCFF" # layer 1 # layer 1 qubit 3 plt.grid() plt.xticks([1, 2, 3, 4, 5, 6]) plt.ylim(0.13, 0.7) plt.title("角度编码方案与表达能力", fontsize=14) plt.xlabel("Qubit数", fontsize=13) plt.ylabel("Expr", fontsize=13) plt.scatter(3, 0.1974, color=c1, label="Rx(θ)(·)") plt.scatter(3, 0.1997, color=c2, label="Ry(θ)H(·)") plt.scatter(3, 0.1918, color=c3, label="Rz(θ)H(·)") plt.scatter(4, 0.1462, color=c1) plt.scatter(4, 0.1442, color=c2) plt.scatter(4, 0.1331, color=c3) plt.scatter(5, 0.1711, color=c1) plt.scatter(5, 0.1824, color=c2) plt.scatter(5, 0.1741, color=c3) plt.scatter(1, 0.6515, color=c1) plt.scatter(1, 0.6613, color=c2) plt.scatter(1, 0.6260, color=c3) plt.scatter(2, 0.3435, color=c1) plt.scatter(2, 0.3355, color=c2) plt.scatter(2, 0.3304, color=c3) plt.scatter(6, 0.2582, color=c1) plt.scatter(6, 0.2748, color=c2) plt.scatter(6, 0.2644, color=c3) plt.legend(loc='upper center') plt.figure(figsize=(15, 3.8)) # layer 1 # layer 1 qubit 3 ax = plt.subplot(1,3,1) plt.grid() plt.ylim(0.3, 0.8) plt.xlim(0.4, 2.4) plt.title("Quibts: 3, Layers: 1") plt.xlabel("Expr", fontsize=13) plt.ylabel("Ent", fontsize=13) plt.scatter(1.189, 0.625, color=palettes[0], label="C1") plt.scatter(0.704, 0.377, color=palettes[1], label="C2") plt.scatter(2.175, 0.702, color=palettes[2], label="C3") plt.scatter(2.352, 0.540, color=palettes[3], label="C4") plt.scatter(1.799, 0.542, color=palettes[4], label="C5") plt.scatter(2.287, 0.720, color=palettes[5], label="C6") plt.scatter(1.546, 0.338, color=palettes[6], label="C7") plt.scatter(1.905, 0.456, color=palettes[7], label="C8") ax.legend(loc='upper left', ncol=3, bbox_to_anchor=(0, 1.01)) plt.axvline(2.352, linestyle="--", color="#FF363666") plt.axvline(2.175, linestyle="--", color="#FF990066") plt.axhline(0.540, linestyle="--", color="#FF363666") plt.axhline(0.702, linestyle="--", color="#FF990066") # # layer 1 qubit 4 plt.subplot(1,3,2) plt.grid() plt.ylim(0.3, 0.8) plt.xlim(0.4, 2.4) plt.title("Quibts: 4, Layers: 1") plt.xlabel("Expr", fontsize=13) plt.scatter(1.724, 0.625, color=palettes[0]) plt.scatter(0.503, 0.375, color=palettes[1]) plt.scatter(1.881, 0.704, color=palettes[2]) plt.scatter(1.982, 0.537, color=palettes[3]) plt.scatter(1.837, 0.545, color=palettes[4]) plt.scatter(2.115, 0.721, color=palettes[5]) plt.scatter(1.219, 0.337, color=palettes[6]) plt.scatter(1.390, 0.457, color=palettes[7]) plt.axvline(1.982, linestyle="--", color="#FF363666") plt.axvline(1.881, linestyle="--", color="#FF990066") plt.axhline(0.537, linestyle="--", color="#FF363666") plt.axhline(0.704, linestyle="--", color="#FF990066") # # layer 1 qubit 5 plt.subplot(1,3,3) plt.grid() plt.ylim(0.3, 0.8) plt.xlim(0.4, 2.4) plt.title("Quibts: 5, Layers: 1") plt.xlabel("Expr", fontsize=13) plt.scatter(1.376, 0.625, color=palettes[0]) plt.scatter(0.456, 0.377, color=palettes[1]) plt.scatter(1.465, 0.703, color=palettes[2]) plt.scatter(1.557, 0.536, color=palettes[3]) plt.scatter(1.424, 0.547, color=palettes[4]) plt.scatter(2.113, 0.722, color=palettes[5]) plt.scatter(0.942, 0.339, color=palettes[6]) plt.scatter(1.152, 0.456, color=palettes[7]) plt.axvline(1.557, linestyle="--", color="#FF363666") plt.axvline(1.465, linestyle="--", color="#FF990066") plt.axhline(0.536, linestyle="--", color="#FF363666") plt.axhline(0.703, linestyle="--", color="#FF990066") def depth(circuit_type, n, L): if circuit_type == 1: return (2 * n + 1) * L elif circuit_type >= 2 and circuit_type <= 4: return (n + 1) * L + 1 elif circuit_type == 5: return (2 + n + n // np.gcd(n, 3)) * L elif circuit_type == 6: return (n ** 2 - n + 4) * L elif circuit_type == 7: return 6 * L elif circuit_type == 8: return (n + 2) * L colors2 = ['#FFCC33', '#FF9900', '#FF9966', '#FF6666', '#CC3333'] colors = ['#99CCFF', '#66CCFF', '#0088CC', '#6666FF', '#0000FF'] types = ['o', '^', ',', 'p', 'X'] plt.grid() plt.title("线路深度同量子比特数量关系") plt.xlabel("线路类型", fontsize=13) plt.ylabel("线路深度", fontsize=13) for n in range(2, 7): for ct in range(1, 9): if ct == 1: plt.scatter(ct, depth(ct, n, 1), color=colors[n - 2], marker=types[n - 2], label=f"n={n}, L=1") else: plt.scatter(ct, depth(ct, n, 1), color=colors[n - 2], marker=types[n - 2]) for n in range(2, 7): for ct in range(1, 9): if ct == 1: plt.scatter(ct, depth(ct, n, 3), color=colors2[n - 2], marker=types[n - 2], label=f"n={n}, L=3") else: plt.scatter(ct, depth(ct, n, 3), color=colors2[n - 2], marker=types[n - 2]) plt.axhline(22, 0, 8, linestyle="--", color="#CC6666") plt.legend() plt.figure(figsize=(7, 5)) # layer 1 # layer 1 qubit 3 plt.grid() plt.ylim(0.4, 0.6) plt.xlim(1, 1.7) plt.title("原始线路与丢弃处理后线路的可表达性与纠缠能力", fontsize=13) plt.xlabel("Expr", fontsize=13) plt.ylabel("Ent", fontsize=13) plt.scatter(1.6105, 0.5622, color="#FF9966", label="原始线路") plt.scatter(1.4415, 0.5158, color="#FF6666", label="纠缠丢弃") plt.scatter(1.1185, 0.4283, color="#3399CC", label="旋转丢弃") plt.legend(loc='upper left')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can show the phase of each state and use # degrees instead of radians from qiskit.quantum_info import DensityMatrix import numpy as np from qiskit import QuantumCircuit from qiskit.visualization import plot_state_qsphere qc = QuantumCircuit(2) qc.h([0, 1]) qc.cz(0,1) qc.ry(np.pi/3, 0) qc.rx(np.pi/5, 1) qc.z(1) matrix = DensityMatrix(qc) plot_state_qsphere(matrix, show_state_phases = True, use_degrees = True)
https://github.com/kuehnste/QiskitTutorial
kuehnste
# Importing standard Qiskit libraries from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.visualization import * from qiskit.quantum_info import state_fidelity # Numpy and Scipy for data evaluation and reference calculations import numpy as np from scipy.linalg import expm # Matplotlib for visualization import matplotlib.pyplot as plt # Magic function to render plots in the notebook after the cell executing the plot command %matplotlib inline # Function for convenience which allows for running the simulator and extracting the results def run_on_qasm_simulator(quantum_circuit, num_shots): """Takes a circuit, the number of shots and a backend and returns the counts for running the circuit on the qasm_simulator backend.""" qasm_simulator = Aer.get_backend('qasm_simulator') job = execute(quantum_circuit, backend=qasm_simulator, shots=num_shots) result = job.result() counts = result.get_counts() return counts def Op(M, n ,N): """Given a single site operator, provide the N-body operator string obtained by tensoring identities""" d = M.shape[0] id_left = np.eye(d**n) id_right = np.eye(d**(N-n-1)) res = np.kron(id_left,np.kron(M,id_right)) return res def IsingHamiltonian(N, h): """The Ising Hamiltonian for N sites with parameter h""" Z = np.array([[1., 0.],[0., -1.]]) X = np.array([[0., 1.],[1., 0.]]) H = np.zeros((2**N, 2**N)) for i in range(N): if i<N-1: H += Op(Z, i, N)@Op(Z, i+1, N) H += h*Op(X, i, N) return H # For reference, we provide a function computing the exact solution for # the magnetization as a function of time def get_magnetization_vs_time(h, delta_t, nsteps): """Compute the exact value of the magnetization""" Z = np.array([[1., 0.],[0., -1.]]) X = np.array([[0., 1.],[1., 0.]]) Id = np.eye(2) # The Ising Hamiltonian for 4 sites with parameter h H = IsingHamiltonian(4, h) # The time evolution operator for an interval \Delta t U = expm(-1.0j*delta_t*H) # The operator for the total magnetization M = Op(Z,0,4) + Op(Z,1,4) + Op(Z,2,4) + Op(Z,3,4) # Numpy array to hold the results magnetization = np.zeros(nsteps) # The initial wave function corresponding to |0010> psi = np.zeros(16) psi[int('0010', 2)] = 1 # Evolve in steps of \Delta t and measure the magnetization for n in range(nsteps): psi = U@psi magnetization[n] = np.real(psi.conj().T@M@psi) return magnetization def provide_initial_state(): # Create a quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the necessary gate(s) to provide the inital state |0010> return qc def Uzz(delta_t): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i Z_k Z_k+1 \Delta t) for all neighboring qubits return qc def Ux(delta_t, h): # Create an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the gates for exp(-i h X_k \Delta t) to all qubits return qc def build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, N): """Given the circuits implementing the initial state and the two parts of the trotterized time-evolution operator build the circuit evolving the wave function N steps """ # Generate an empty quantum circuit qc for 4 qubits qc = QuantumCircuit(4) # Add the inital state qc.compose(qc_init_state, inplace=True) # For each time step add qc_Uzz and qc_Ux for i in range(N): qc.compose(qc_Uzz, inplace=True) qc.compose(qc_Ux, inplace=True) # Add the final measurments qc.measure_all() return qc def get_magnetization(counts): """Given the counts resulting form a measurement, compute the site resolved magnetization""" total_counts = sum(counts.values()) res = np.zeros(4) for qubit in range(4): Z_expectation = 0. for key, value in counts.items(): if key[qubit] == '0': Z_expectation += value else: Z_expectation -= value res[qubit] = Z_expectation/total_counts return res # The parameters for the time evolution h = 1.5 delta_t = 0.05 nsteps = 40 nshots = 1000 # Provide the initial state qc_init_state = provide_initial_state() # The time-evolution operators qc_Uzz = Uzz(delta_t) qc_Ux = Ux(delta_t, h) # Numpy array for expectation values of the magnetization magnetization = np.zeros(nsteps) # Numpy array for qubit configuration configuration = np.zeros((4, nsteps)) # Run the time evolution for n in range(1, nsteps+1): # Build the evolution circuit out of qc_init_state, qc_Uzz and qc_Ux for # n steps qc_evo = build_time_evolution_circuit(qc_init_state, qc_Uzz, qc_Ux, n) # Run the evolution circuit on the qasm_simulator res = run_on_qasm_simulator(qc_evo, nshots) # Compute the ovservables configuration[:,n-1] = get_magnetization(res) magnetization[n-1] = sum(configuration[:,n-1]) # For reference we compute the exact solution magnetization_exact = get_magnetization_vs_time(h, delta_t, nsteps) # Plot the total magnetization as a function of time and compare to # the exact result plt.figure() plt.plot(magnetization_exact, '--', label='exact') plt.plot(magnetization, 'o', label='quantum circuit') plt.xlabel('$t/\Delta t$') plt.ylabel('$<\sum_i Z_i(t)>$') plt.title('Total magnetization') plt.legend() # Plot the site resolved spin configuration as a function of time plt.figure() plt.imshow(configuration, aspect='auto') plt.colorbar() plt.xlabel('$t/\Delta t$') plt.ylabel('$<Z_i(t)>$') plt.title('Spatially resolved spin configuration')
https://github.com/dnnagy/qintro
dnnagy
import numpy as np from qiskit import * import matplotlib qr = QuantumRegister(2) #measurements from quantum bits = use classical register cr = ClassicalRegister(2) circuit = QuantumCircuit(qr, cr) circuit.draw() # adding quantum gates to create entanglement (Hadamart gate) circuit.h(qr[0]) %matplotlib inline circuit.draw(output='mpl') #two qubit operation control X (logical if) circuit.cx(qr[0], qr[1]) circuit.draw(output='mpl') #entanglement achieved #measurement, storing measurements into computational register circuit.measure(qr,cr) circuit.draw(output='mpl') #performance simulations simulator = Aer.get_backend('qasm_simulator') execute(circuit, backend = simulator) result = execute(circuit, backend = simulator).result() #plotting results from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit)) #running circuit on quantum computer IBMQ.load_account() provider= IBMQ.get_provider('ibm-q') qcomp = provider.get_backend('ibmq_manila') job= execute(circuit, backend=qcomp) from qiskit.tools import job_monitor job_monitor(job) result = job.result() from qiskit.tools.visualization import plot_histogram plot_histogram(result.get_counts(circuit), title='Performance metric on Quantum Computer')
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import json import time import warnings import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output from qiskit import ClassicalRegister, QuantumRegister from qiskit import QuantumCircuit from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import RealAmplitudes from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals from qiskit_machine_learning.circuit.library import RawFeatureVector from qiskit_machine_learning.neural_networks import SamplerQNN algorithm_globals.random_seed = 42 def ansatz(num_qubits): return RealAmplitudes(num_qubits, reps=5) num_qubits = 5 circ = ansatz(num_qubits) circ.decompose().draw("mpl") def auto_encoder_circuit(num_latent, num_trash): qr = QuantumRegister(num_latent + 2 * num_trash + 1, "q") cr = ClassicalRegister(1, "c") circuit = QuantumCircuit(qr, cr) circuit.compose(ansatz(num_latent + num_trash), range(0, num_latent + num_trash), inplace=True) circuit.barrier() auxiliary_qubit = num_latent + 2 * num_trash # swap test circuit.h(auxiliary_qubit) for i in range(num_trash): circuit.cswap(auxiliary_qubit, num_latent + i, num_latent + num_trash + i) circuit.h(auxiliary_qubit) circuit.measure(auxiliary_qubit, cr[0]) return circuit num_latent = 3 num_trash = 2 circuit = auto_encoder_circuit(num_latent, num_trash) circuit.draw("mpl") def domain_wall(circuit, a, b): # Here we place the Domain Wall to qubits a - b in our circuit for i in np.arange(int(b / 2), int(b)): circuit.x(i) return circuit domain_wall_circuit = domain_wall(QuantumCircuit(5), 0, 5) domain_wall_circuit.draw("mpl") ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(domain_wall_circuit, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") # Here we define our interpret for our SamplerQNN def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=[], weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_domain(params_values): probabilities = qnn.forward([], params_values) # we pick a probability of getting 1 as the output of the network cost = np.sum(probabilities[:, 1]) # plotting part clear_output(wait=True) objective_func_vals.append(cost) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() return cost opt = COBYLA(maxiter=150) initial_point = algorithm_globals.random.random(ae.num_parameters) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(cost_func_domain, initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(domain_wall_circuit) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) test_qc.draw("mpl") test_qc = test_qc.assign_parameters(opt_result.x) domain_wall_state = Statevector(domain_wall_circuit).data output_state = Statevector(test_qc).data fidelity = np.sqrt(np.dot(domain_wall_state.conj(), output_state) ** 2) print("Fidelity of our Output State with our Input State: ", fidelity.real) def zero_idx(j, i): # Index for zero pixels return [ [i, j], [i - 1, j - 1], [i - 1, j + 1], [i - 2, j - 1], [i - 2, j + 1], [i - 3, j - 1], [i - 3, j + 1], [i - 4, j - 1], [i - 4, j + 1], [i - 5, j], ] def one_idx(i, j): # Index for one pixels return [[i, j - 1], [i, j - 2], [i, j - 3], [i, j - 4], [i, j - 5], [i - 1, j - 4], [i, j]] def get_dataset_digits(num, draw=True): # Create Dataset containing zero and one train_images = [] train_labels = [] for i in range(int(num / 2)): # First we introduce background noise empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the one for i, j in one_idx(2, 6): empty[j][i] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(1) if draw: plt.title("This is a One") plt.imshow(train_images[-1]) plt.show() for i in range(int(num / 2)): empty = np.array([algorithm_globals.random.uniform(0, 0.1) for i in range(32)]).reshape( 8, 4 ) # Now we insert the pixels for the zero for k, j in zero_idx(2, 6): empty[k][j] = algorithm_globals.random.uniform(0.9, 1) train_images.append(empty) train_labels.append(0) if draw: plt.imshow(train_images[-1]) plt.title("This is a Zero") plt.show() train_images = np.array(train_images) train_images = train_images.reshape(len(train_images), 32) for i in range(len(train_images)): sum_sq = np.sum(train_images[i] ** 2) train_images[i] = train_images[i] / np.sqrt(sum_sq) return train_images, train_labels train_images, __ = get_dataset_digits(2) num_latent = 3 num_trash = 2 fm = RawFeatureVector(2 ** (num_latent + num_trash)) ae = auto_encoder_circuit(num_latent, num_trash) qc = QuantumCircuit(num_latent + 2 * num_trash + 1, 1) qc = qc.compose(fm, range(num_latent + num_trash)) qc = qc.compose(ae) qc.draw("mpl") def identity_interpret(x): return x qnn = SamplerQNN( circuit=qc, input_params=fm.parameters, weight_params=ae.parameters, interpret=identity_interpret, output_shape=2, ) def cost_func_digits(params_values): probabilities = qnn.forward(train_images, params_values) cost = np.sum(probabilities[:, 1]) / train_images.shape[0] # plotting part clear_output(wait=True) objective_func_vals.append(cost) plt.title("Objective function value against iteration") plt.xlabel("Iteration") plt.ylabel("Objective function value") plt.plot(range(len(objective_func_vals)), objective_func_vals) plt.show() return cost with open("12_qae_initial_point.json", "r") as f: initial_point = json.load(f) opt = COBYLA(maxiter=150) objective_func_vals = [] # make the plot nicer plt.rcParams["figure.figsize"] = (12, 6) start = time.time() opt_result = opt.minimize(fun=cost_func_digits, x0=initial_point) elapsed = time.time() - start print(f"Fit in {elapsed:0.2f} seconds") # Test test_qc = QuantumCircuit(num_latent + num_trash) test_qc = test_qc.compose(fm) ansatz_qc = ansatz(num_latent + num_trash) test_qc = test_qc.compose(ansatz_qc) test_qc.barrier() test_qc.reset(4) test_qc.reset(3) test_qc.barrier() test_qc = test_qc.compose(ansatz_qc.inverse()) # sample new images test_images, test_labels = get_dataset_digits(2, draw=False) for image, label in zip(test_images, test_labels): original_qc = fm.assign_parameters(image) original_sv = Statevector(original_qc).data original_sv = np.reshape(np.abs(original_sv) ** 2, (8, 4)) param_values = np.concatenate((image, opt_result.x)) output_qc = test_qc.assign_parameters(param_values) output_sv = Statevector(output_qc).data output_sv = np.reshape(np.abs(output_sv) ** 2, (8, 4)) fig, (ax1, ax2) = plt.subplots(1, 2) ax1.imshow(original_sv) ax1.set_title("Input Data") ax2.imshow(output_sv) ax2.set_title("Output Data") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# You can set a color for all the bars. from qiskit import QuantumCircuit from qiskit.quantum_info import Statevector from qiskit.visualization import plot_state_paulivec qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) state = Statevector(qc) plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
https://github.com/benkoehlL/Qiskit_Playground
benkoehlL
import numpy as np from qiskit import * from qiskit.visualization import plot_histogram from matplotlib.pyplot import plot, draw, show def SendState(qc1, qc2, qc1_name): ''' This function takes the output of circuit qc1 (made up of only H and X gates) and initialises another circuit qc2 with the same state ''' qs = qc1.qasm().split(sep=';')[4:-1] # process the code to get the instructions for i, instruction in enumerate(qs): qs[i] = instruction.lstrip() # parse the instructions and apply to new circuit for instruction in qs: instruction_gate = instruction[0] instruction_qubit_list = [] i = 0 while instruction[i] != '[': i += 1 i += 1 while instruction[i] != ']': instruction_qubit_list.append(instruction[i]) i += 1 instruction_qubit = 0 for i, dec in enumerate(reversed(instruction_qubit_list)): instruction_qubit += int(dec)*10**i if(instruction_gate == 'x'): old_qr = int(instruction_qubit) qc2.x(qr[old_qr]) elif instruction_gate == 'h': old_qr = int(instruction_qubit) qc2.h(qr[old_qr]) elif instruction_gate == 'm': # exclude measuring pass else: raise Exception('Unable to parse instruction') # declare classical and quantum register n = 16 # for local backend 'n' can go up to 23, #after which a memery error is raised qr = QuantumRegister(n, name='q') cr = ClassicalRegister(n, name='c') # create Alice's circuit alice = QuantumCircuit(qr, cr, name='Alice') # generate a random number expressible by the available qubits alice_key = np.random.randint(0,high=2**n) # cast key to binary representation alice_key = np.binary_repr(alice_key,n) # encode key as alice qubits for i, digit in enumerate(alice_key): if(digit == '1'): alice.x(qr[i]) # switch randomly about half qubits to Hadamard basis alice_table = [] for qubit in qr: if(np.random.rand()>0.5): alice.h(qubit) alice_table.append('H') # indicate the Hadamard-basis else: alice_table.append('Z') # indicate the Z-basis # create Bob's circuit bob = QuantumCircuit(qr, cr, name='Bob') SendState(alice,bob, 'Alice') # Bob does not know which basis to use bob_table = [] for qubit in qr: if(np.random.rand()>0.5): bob.h(qubit) bob_table.append('H') # indicate the Hadamard-basis else: bob_table.append('Z') # indicate the Z-basis # measure all qubits for i, qubit in enumerate(qr): bob.measure(qubit, cr[i]) backend = BasicAer.get_backend('qasm_simulator') # Bob has only one chance of measuring correctly result = execute(bob, backend=backend, shots=1).result() #plot_histogram(result.get_counts(bob)) #draw() #show(block=True) # result of the measurement is Bob's key candidate bob_key = list(result.get_counts(bob))[0] # key is reversed so that first qubit is the first element of the list bob_key = bob_key[::-1] # compare basis and discard qubits not measured in the same basis keep = [] discard = [] print('\n', "Compare Bob's and Alice's basis (without eavesdropping): ") for qubit, basis in enumerate(zip(alice_table,bob_table)): if(basis[0] == basis[1]): print("Same choice for qubit: {}, basis: {}".format(qubit, basis[0])) keep.append(qubit) else: print("Different choice for qubit: {}, Alice has {}, Bob has {}".format(qubit, basis[0], basis[1])) discard.append(qubit) # measure the percentage of qubits to be discarded acc = 0 for bit in zip(alice_key, bob_key): if(bit[0]==bit[1]): acc += 1 print('\n Percentage of qubits to be discarded according to table comparison: ', len(keep)/n) print('Measurement convergence by additional chance: ', acc/n) new_alice_key = [alice_key[qubit] for qubit in keep] new_bob_key = [bob_key[qubit] for qubit in keep] acc = 0 for bit in zip(new_alice_key, new_bob_key): if(bit[0] == bit[1]): acc += 1 print('Percentage of similarity between the keys: ', acc/len(new_alice_key)) if(acc//len(new_alice_key) == 1): print('Key exchange has been succesfull') print("New Alice's key: ", new_alice_key) print("New Bob's key: ", new_bob_key) else: print('Key exchange has been tampered! ---> Check for eavesdropper or try again') print("New Alice's key is invalid: ", new_alice_key) print("New Bob's key is invalid: ", new_bob_key) # let's intrude a eavesdropper Eve (which is initialised to Alice's state) eve = QuantumCircuit(qr, cr, name='Eve') SendState(alice, eve, 'Alice') eve_table = [] for qubit in qr: if(np.random.rand()>0.5): eve.h(qubit) eve_table.append('H') else: eve_table.append('Z') for i, qubit in enumerate(qr): eve.measure(qubit,cr[i]) # Execute (build and run) the quantum circuit backend = BasicAer.get_backend('qasm_simulator') result = execute(eve, backend=backend, shots=1).result() # Result of the measurement is Eve's key eve_key = list(result.get_counts(eve))[0] eve_key = eve_key[::-1] # Update states to new eigenstates (of wrongly chosen basis) print('\n', "Compare Eve's and Alice's basis: ") for i, basis in enumerate(zip(alice_table,eve_table)): if(basis[0] == basis[1]): print("Same choice for qubit: {}, basis: {}".format(qubit, basis[0])) keep.append(i) else: print("Different choice for qubit: {}, Alice has {}, Eve has {}".format(qubit, basis[0], basis[1])) discard.append(i) if eve_key[i] == alice_key[i]: eve.h(qr[i]) else: if (basis[0] == 'H' and basis[1] == 'Z'): alice.h(qr[i]) eve.x(qr[i]) else: eve.x(qr[i]) eve.h(qr[i]) # Eve's state is now sent to Bob SendState(eve, bob, 'Eve') bob_table = [] for qubit in qr: if(np.random.rand()>0.5): bob.h(qubit) bob_table.append('H') else: bob_table.append('Z') for i, qubit in enumerate(qr): bob.measure(qubit, cr[i]) result = execute(bob, backend, shots=1).result() #plot_histogram(result.get_counts(bob)) #draw() #show(block=True) bob_key = list(result.get_counts(bob))[0] bob_key = bob_key[::-1] # Now Alice and Bob will share their table data and perform checking operations keep = [] discard = [] print('\n', "Compare Bob's and Alice's basis (with eavesdropping by Eve): ") for qubit, basis in enumerate(zip(alice_table, bob_table)): if(basis[0] == basis[1]): print("Same choice for qubit: {}, basis: {}".format(qubit, basis[0])) keep.append(qubit) else: print("Different choice for qubit: {}, Alice has {}, Bob has {}".format(qubit, basis[0], basis[1])) discard.append(qubit) # measure the percentage of qubits to be discarded acc = 0 for bit in zip(alice_key, bob_key): if(bit[0]==bit[1]): acc += 1 print('Percentage of qubits to be discarded according to table comparison: ', len(keep)/n) print('Measurement convergence by additional chance: ', acc/n) new_alice_key = [alice_key[qubit] for qubit in keep] new_bob_key = [bob_key[qubit] for qubit in keep] acc = 0 for bit in zip(new_alice_key, new_bob_key): if(bit[0] == bit[1]): acc += 1 print('\n Percentage of similarity between the keys: ', acc/len(new_alice_key)) if(acc//len(new_alice_key) == 1): print('Key exchange has been succesfull') print("New Alice's key: ", new_alice_key) print("New Bob's key: ", new_bob_key) else: print('Key exchange has been tampered! --->', 'Check for eavesdropper or try again') print("New Alice's key is invalid: ", new_alice_key) print("New Bob's key is invalid: ", new_bob_key)
https://github.com/ka-us-tubh/quantum-computing-qiskit-
ka-us-tubh
import numpy as np # Importing standard Qiskit libraries from qiskit import * from qiskit.tools.jupyter import * from qiskit.visualization import * from ibm_quantum_widgets import * # Loading your IBM Quantum account(s) provider = IBMQ.load_account() qr=QuantumRegister(2) cr=ClassicalRegister(2) circuit=QuantumCircuit(cr,qr) %matplotlib inline circuit.draw() circuit.h(qr[0]) circuit.draw() circuit.cx(qr[0],qr[1]) circuit.draw() circuit.measure(qr,cr) circuit.draw() simulator = Aer.get_backend('qasm_simulator') result=execute(circuit,backend= simulator).result() plot_histogram(result.get_counts(circuit)) provider=IBMQ.get_provider('ibm-q') qcomp=provider.get_backend('ibmq_quito')
https://github.com/Qiskit-Extensions/qiskit-ibm-experiment
Qiskit-Extensions
# This code is part of Qiskit. # # (C) Copyright IBM 2021-2022. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Experiment integration tests.""" import os import unittest from unittest import mock, skipIf import contextlib from test.service.ibm_test_case import IBMTestCase import numpy as np from qiskit import transpile, QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.providers import JobStatus from qiskit_experiments.framework import ( ExperimentData, ExperimentDecoder, ExperimentEncoder, ) from qiskit_experiments.framework.experiment_data import ExperimentStatus from qiskit_experiments.framework import AnalysisResult from qiskit_experiments.database_service.exceptions import ExperimentEntryNotFound from qiskit_ibm_runtime import QiskitRuntimeService from qiskit_ibm_experiment import IBMExperimentService from qiskit_ibm_experiment.exceptions import IBMExperimentEntryNotFound from qiskit_ibm_experiment.exceptions import IBMApiError def bell(): """Return a Bell circuit.""" qr = QuantumRegister(2, name="qr") cr = ClassicalRegister(2, name="qc") qc = QuantumCircuit(qr, cr, name="bell") qc.h(qr[0]) qc.cx(qr[0], qr[1]) qc.measure(qr, cr) return qc @skipIf( not os.environ.get("QISKIT_IBM_USE_STAGING_CREDENTIALS", ""), "Only runs on staging" ) class TestExperimentDataIntegration(IBMTestCase): """Test experiment service with experiment data.""" @classmethod def setUpClass(cls): """Initial class level setup.""" super().setUpClass() try: cls._setup_service() cls._setup_provider() cls.circuit = transpile(bell(), cls.backend) except Exception as err: cls.log.info("Error while setting the service/provider: %s", err) raise @classmethod def _setup_service(cls): """Get the service for the class.""" cls.service = IBMExperimentService( token=os.getenv("QISKIT_IBM_STAGING_API_TOKEN"), url=os.getenv("QISKIT_IBM_STAGING_API_URL"), ) @classmethod def _setup_provider(cls): """Get the provider for the class.""" cls.provider = QiskitRuntimeService( channel="ibm_quantum", token=os.getenv("QISKIT_IBM_STAGING_API_TOKEN"), url=os.getenv("QISKIT_IBM_STAGING_API_URL"), instance=os.getenv("QISKIT_IBM_STAGING_HGP"), ) cls.backend = cls.provider.backend(os.getenv("QISKIT_IBM_STAGING_BACKEND")) try: cls.device_components = cls.service.device_components(cls.backend.name) except IBMApiError: cls.device_components = None def setUp(self) -> None: """Test level setup.""" super().setUp() self.experiments_to_delete = [] self.results_to_delete = [] self.jobs_to_cancel = [] def tearDown(self): """Test level tear down.""" for result_uuid in self.results_to_delete: try: with mock.patch("builtins.input", lambda _: "y"): self.service.delete_analysis_result(result_uuid) except Exception as err: # pylint: disable=broad-except self.log.info( "Unable to delete analysis result %s: %s", result_uuid, err ) for expr_uuid in self.experiments_to_delete: try: with mock.patch("builtins.input", lambda _: "y"): self.service.delete_experiment(expr_uuid) except Exception as err: # pylint: disable=broad-except self.log.info("Unable to delete experiment %s: %s", expr_uuid, err) for job in self.jobs_to_cancel: with contextlib.suppress(Exception): job.cancel() super().tearDown() def test_add_data_job(self): """Test add job to experiment data.""" exp_data = ExperimentData( backend=self.backend, provider=self.provider, experiment_type="qiskit_test", service=self.service, ) transpiled = transpile(bell(), self.backend) transpiled.metadata = {"foo": "bar"} job = self._run_circuit(transpiled) exp_data.add_jobs(job) self.assertEqual([job.job_id()], exp_data.job_ids) result = job.result() exp_data.block_for_results() circuit_data = exp_data.data(0) self.assertEqual(result.get_counts(0), circuit_data["counts"]) # currently the returned job_id is different; this is not a qiskit-ibm-experiment # problem but a known behaviour in the new provider # self.assertEqual(job.job_id(), circuit_data["job_id"]) self.assertEqual(transpiled.metadata, circuit_data["metadata"]) def test_new_experiment_data(self): """Test creating a new experiment data.""" metadata = {"complex": 2 + 3j, "numpy": np.zeros(2)} exp_data = ExperimentData( service=self.service, backend=self.backend, provider=self.provider, experiment_type="qiskit_test", tags=["foo", "bar"], share_level="hub", metadata=metadata, notes="some notes", ) job_ids = [] for _ in range(2): job = self._run_circuit() exp_data.add_jobs(job) job_ids.append(job.job_id()) exp_data.block_for_results().save(suppress_errors=False) self.experiments_to_delete.append(exp_data.experiment_id) hub, group, project = list(self.provider._hgps)[0].split("/") rexp = ExperimentData.load(exp_data.experiment_id, self.service) self._verify_experiment_data(exp_data, rexp) self.assertEqual(hub, rexp.hub) # pylint: disable=no-member self.assertEqual(group, rexp.group) # pylint: disable=no-member self.assertEqual(project, rexp.project) # pylint: disable=no-member def test_update_experiment_data(self): """Test updating an experiment.""" exp_data = self._create_experiment_data() for _ in range(2): job = self._run_circuit() exp_data.add_jobs(job) exp_data.tags = ["foo", "bar"] exp_data.share_level = "hub" exp_data.notes = "some notes" exp_data.block_for_results().save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self._verify_experiment_data(exp_data, rexp) def _verify_experiment_data(self, expected, actual): """Verify the input experiment data.""" self.assertEqual(expected.experiment_id, actual.experiment_id) self.assertEqual(expected.job_ids, actual.job_ids) self.assertEqual(expected.share_level, actual.share_level) self.assertEqual(expected.tags, actual.tags) self.assertEqual(expected.notes, actual.notes) self.assertEqual( expected.metadata.get("complex", {}), actual.metadata.get("complex", {}) ) self.assertTrue(actual.creation_datetime) self.assertTrue(getattr(actual, "creation_datetime").tzinfo) def test_add_analysis_results(self): """Test adding an analysis result.""" exp_data = self._create_experiment_data() result_data = {"complex": 2 + 3j, "numpy": np.zeros(2)} aresult = AnalysisResult( name="qiskit_test", value=result_data, device_components=self.device_components, experiment_id=exp_data.experiment_id, quality="good", tags=["foo", "bar"], service=self.service, ) exp_data.add_analysis_results(aresult) exp_data.save(suppress_errors=False) rresult = AnalysisResult.load(aresult.result_id, self.service) self.assertEqual(exp_data.experiment_id, rresult.experiment_id) self._verify_analysis_result(aresult, rresult) def test_update_analysis_result(self): """Test updating an analysis result.""" aresult, exp_data = self._create_analysis_result() rdata = {"complex": 2 + 3j, "numpy": np.zeros(2)} aresult.value = rdata aresult.quality = "good" aresult.tags = ["foo", "bar"] aresult.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) rresult = rexp.analysis_results(0) self._verify_analysis_result(aresult, rresult) def _verify_analysis_result(self, expected, actual): """Verify the input analysis result.""" self.assertEqual(expected.result_id, actual.result_id) self.assertEqual(expected.name, actual.name) ecomp = {str(comp) for comp in expected.device_components} acomp = {str(comp) for comp in actual.device_components} self.assertEqual(ecomp, acomp) self.assertEqual(expected.experiment_id, actual.experiment_id) self.assertEqual(expected.quality, actual.quality) self.assertEqual(expected.tags, actual.tags) self.assertEqual(expected.value["complex"], actual.value["complex"]) self.assertEqual(expected.value["numpy"].all(), actual.value["numpy"].all()) def test_delete_analysis_result(self): """Test deleting an analysis result.""" aresult, exp_data = self._create_analysis_result() with mock.patch("builtins.input", lambda _: "y"): exp_data.delete_analysis_result(0) exp_data.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertRaises( ExperimentEntryNotFound, rexp.analysis_results, aresult.result_id ) self.assertRaises( IBMExperimentEntryNotFound, self.service.analysis_result, aresult.result_id ) def test_add_figures(self): """Test adding a figure to the experiment data.""" exp_data = self._create_experiment_data() hello_bytes = str.encode("hello world") sub_tests = ["hello.svg", None] for idx, figure_name in enumerate(sub_tests): with self.subTest(figure_name=figure_name): exp_data.add_figures( figures=hello_bytes, figure_names=figure_name, save_figure=True ) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertEqual(rexp.figure(idx).figure, hello_bytes) def test_add_figures_plot(self): """Test adding a matplotlib figure.""" import matplotlib.pyplot as plt figure, axes = plt.subplots() axes.plot([1, 2, 3]) exp_data = self._create_experiment_data() exp_data.add_figures(figure, save_figure=True) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertTrue(rexp.figure(0)) def test_add_figures_file(self): """Test adding a figure file.""" exp_data = self._create_experiment_data() hello_bytes = str.encode("hello world") file_name = "hello_world.svg" self.addCleanup(os.remove, file_name) with open(file_name, "wb") as file: file.write(hello_bytes) exp_data.add_figures(figures=file_name, save_figure=True) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertEqual(rexp.figure(0).figure, hello_bytes) def test_update_figure(self): """Test updating a figure.""" exp_data = self._create_experiment_data() hello_bytes = str.encode("hello world") figure_name = "hello.svg" exp_data.add_figures( figures=hello_bytes, figure_names=figure_name, save_figure=True ) self.assertEqual(exp_data.figure(0).figure, hello_bytes) friend_bytes = str.encode("hello friend") exp_data.add_figures( figures=friend_bytes, figure_names=figure_name, overwrite=True, save_figure=True, ) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertEqual(rexp.figure(0).figure, friend_bytes) self.assertEqual(rexp.figure(figure_name).figure, friend_bytes) def test_delete_figure(self): """Test deleting a figure.""" exp_data = self._create_experiment_data() hello_bytes = str.encode("hello world") figure_name = "hello.svg" exp_data.add_figures( figures=hello_bytes, figure_names=figure_name, save_figure=True ) with mock.patch("builtins.input", lambda _: "y"): exp_data.delete_figure(0) exp_data.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertRaises(IBMExperimentEntryNotFound, rexp.figure, figure_name) self.assertRaises( IBMExperimentEntryNotFound, self.service.figure, exp_data.experiment_id, figure_name, ) def test_save_all(self): """Test saving all.""" exp_data = self._create_experiment_data() exp_data.tags = ["foo", "bar"] aresult = AnalysisResult( value={}, name="qiskit_test", device_components=self.device_components, experiment_id=exp_data.experiment_id, ) exp_data.add_analysis_results(aresult) hello_bytes = str.encode("hello world") exp_data.add_figures(hello_bytes, figure_names="hello.svg") exp_data.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) # Experiment tag order is not necessarily preserved # so compare tags with a predictable sort order. self.assertEqual(["bar", "foo"], sorted(rexp.tags)) self.assertEqual(aresult.result_id, rexp.analysis_results(0).result_id) self.assertEqual(hello_bytes, rexp.figure(0).figure) exp_data.delete_analysis_result(0) exp_data.delete_figure(0) with mock.patch("builtins.input", lambda _: "y"): exp_data.save(suppress_errors=False) rexp = ExperimentData.load(exp_data.experiment_id, self.service) self.assertRaises(IBMExperimentEntryNotFound, rexp.figure, "hello.svg") self.assertRaises( ExperimentEntryNotFound, rexp.analysis_results, aresult.result_id ) def test_set_service_job(self): """Test setting service with a job.""" exp_data = ExperimentData(experiment_type="qiskit_test", service=self.service) job = self._run_circuit() exp_data.add_jobs(job) exp_data.save(suppress_errors=False) self.experiments_to_delete.append(exp_data.experiment_id) rexp = self.service.experiment(exp_data.experiment_id) self.assertEqual([job.job_id()], rexp.job_ids) def test_auto_save_experiment(self): """Test auto save.""" exp_data = self._create_experiment_data() exp_data.auto_save = True subtests = [ ( setattr, ( exp_data, "tags", ["foo"], ), ), (setattr, (exp_data, "notes", "foo")), (setattr, (exp_data, "share_level", "hub")), ] for func, params in subtests: with self.subTest(func=func): with mock.patch.object( IBMExperimentService, "create_or_update_experiment", wraps=exp_data.service.create_or_update_experiment, ) as mocked: func(*params) mocked.assert_called_once() data = mocked.call_args[0][0] self.assertEqual(exp_data.experiment_id, data.experiment_id) mocked.reset_mock() def test_auto_save_figure(self): """Test auto saving figure.""" exp_data = self._create_experiment_data() exp_data.auto_save = True figure_name = "hello.svg" with mock.patch.object( IBMExperimentService, "update_experiment", wraps=exp_data.service.update_experiment, ) as mocked_exp: with mock.patch.object( IBMExperimentService, "create_figure", wraps=exp_data.service.create_figure, ) as mocked_fig: exp_data.add_figures( str.encode("hello world"), figure_names=figure_name ) mocked_exp.assert_called_once() mocked_fig.assert_called_once() mocked_exp.reset_mock() with mock.patch.object( IBMExperimentService, "update_figure", wraps=exp_data.service.update_figure, ) as mocked_fig: exp_data.add_figures( str.encode("hello friend"), figure_names=figure_name, overwrite=True ) mocked_fig.assert_called_once() mocked_exp.assert_called_once() mocked_exp.reset_mock() with mock.patch.object( IBMExperimentService, "delete_figure", wraps=exp_data.service.delete_figure, ) as mocked_fig, mock.patch("builtins.input", lambda _: "y"): exp_data.delete_figure(figure_name) mocked_fig.assert_called_once() mocked_exp.assert_called_once() def test_auto_save_analysis_result(self): """Test auto saving analysis result.""" exp_data = self._create_experiment_data() exp_data.auto_save = True aresult = AnalysisResult( value={}, name="qiskit_test", device_components=self.device_components, experiment_id=exp_data.experiment_id, service=self.service, ) with mock.patch.object( IBMExperimentService, "update_experiment", wraps=exp_data.service.update_experiment, ) as mocked_exp: with mock.patch.object( IBMExperimentService, "create_or_update_analysis_result", wraps=exp_data.service.create_or_update_analysis_result, ) as mocked_res: exp_data.add_analysis_results(aresult) mocked_exp.assert_called_once() mocked_res.assert_called_once() mocked_exp.reset_mock() def test_auto_save_analysis_result_update(self): """Test auto saving analysis result updates.""" aresult, exp_data = self._create_analysis_result() aresult.auto_save = True subtests = [ ("tags", ["foo"]), ("value", {"foo": "bar"}), ("quality", "GOOD"), ] for attr, value in subtests: with self.subTest(attr=attr): with mock.patch.object( IBMExperimentService, "create_or_update_analysis_result", wraps=exp_data.service.create_or_update_analysis_result, ) as mocked: setattr(aresult, attr, value) mocked.assert_called_once() data = mocked.call_args[0][0] self.assertEqual(aresult.result_id, data.result_id) mocked.reset_mock() def test_block_for_results(self): """Test blocking for jobs""" exp_data = ExperimentData( backend=self.backend, provider=self.provider, experiment_type="qiskit_test", service=self.service, ) jobs = [] for _ in range(2): job = self._run_circuit() exp_data.add_jobs(job) jobs.append(job) exp_data.block_for_results() self.assertTrue(all(job.status() == JobStatus.DONE for job in jobs)) self.assertEqual(ExperimentStatus.DONE, exp_data.status()) def test_file_upload_download(self): """test upload and download of actual experiment data""" exp_id = self._create_experiment_data().experiment_id qc = QuantumCircuit(2) qc.h(0) qc.measure_all() data = {"string": "b-string", "int": 10, "float": 0.333, "circuit": qc} json_filename = "data.json" self.service.file_upload( exp_id, json_filename, data, json_encoder=ExperimentEncoder ) rjson_data = self.service.file_download( exp_id, json_filename, json_decoder=ExperimentDecoder ) self.assertEqual(data, rjson_data) def _create_experiment_data(self): """Create an experiment data.""" exp_data = ExperimentData( backend=self.backend, provider=self.provider, experiment_type="qiskit_test", verbose=False, service=self.service, ) exp_data.save(suppress_errors=False) self.experiments_to_delete.append(exp_data.experiment_id) return exp_data def _create_analysis_result(self): """Create a simple analysis result.""" exp_data = self._create_experiment_data() aresult = AnalysisResult( value={}, name="qiskit_test", device_components=self.device_components, experiment_id=exp_data.experiment_id, service=self.service, ) exp_data.add_analysis_results(aresult) exp_data.save(suppress_errors=False) self.results_to_delete.append(aresult.result_id) return aresult, exp_data def _run_circuit(self, circuit=None): """Run a circuit.""" circuit = circuit or self.circuit job = self.backend.run(circuit, shots=1) self.jobs_to_cancel.append(job) return job if __name__ == "__main__": unittest.main()
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.dagcircuit import DAGCircuit from qiskit.converters import circuit_to_dag from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate from qiskit.converters import dag_to_circuit q = QuantumRegister(3, 'q') c = ClassicalRegister(3, 'c') circ = QuantumCircuit(q, c) circ.h(q[0]) circ.cx(q[0], q[1]) circ.measure(q[0], c[0]) circ.rz(0.5, q[1]).c_if(c, 2) dag = circuit_to_dag(circ) circuit = dag_to_circuit(dag) circuit.draw('mpl')