Dataset Viewer
Auto-converted to Parquet
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()
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
2