diff --git a/docs/apidoc/index.rst b/docs/apidoc/index.rst index 3fc3e25e457d..9116ccfb4662 100644 --- a/docs/apidoc/index.rst +++ b/docs/apidoc/index.rst @@ -34,7 +34,6 @@ API Reference qpy quantum_info result - tools transpiler transpiler_passes transpiler_preset diff --git a/docs/apidoc/tools.rst b/docs/apidoc/tools.rst deleted file mode 100644 index c1dd7018a6d9..000000000000 --- a/docs/apidoc/tools.rst +++ /dev/null @@ -1,6 +0,0 @@ -.. _qiskit-tools: - -.. automodule:: qiskit.tools - :no-members: - :no-inherited-members: - :no-special-members: diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index 06d056a05f89..b27fe47a02e6 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -34,7 +34,7 @@ converters, QobjHeader, ) -from qiskit.tools.parallel import parallel_map +from qiskit.utils.parallel import parallel_map PulseLibrary = Dict[str, List[complex]] diff --git a/qiskit/compiler/scheduler.py b/qiskit/compiler/scheduler.py index b714b8d46923..0a30b07a49b1 100644 --- a/qiskit/compiler/scheduler.py +++ b/qiskit/compiler/scheduler.py @@ -25,7 +25,7 @@ from qiskit.providers.backend import Backend from qiskit.scheduler import ScheduleConfig from qiskit.scheduler.schedule_circuit import schedule_circuit -from qiskit.tools.parallel import parallel_map +from qiskit.utils.parallel import parallel_map logger = logging.getLogger(__name__) diff --git a/qiskit/passmanager/passmanager.py b/qiskit/passmanager/passmanager.py index 74d5feb91088..f480ff1c3954 100644 --- a/qiskit/passmanager/passmanager.py +++ b/qiskit/passmanager/passmanager.py @@ -21,7 +21,7 @@ import dill -from qiskit.tools.parallel import parallel_map +from qiskit.utils.parallel import parallel_map from .base_tasks import Task, PassManagerIR from .exceptions import PassManagerError from .flow_controllers import FlowControllerLinear diff --git a/qiskit/providers/fake_provider/__init__.py b/qiskit/providers/fake_provider/__init__.py index dae7311c68e0..9411cf309ae1 100644 --- a/qiskit/providers/fake_provider/__init__.py +++ b/qiskit/providers/fake_provider/__init__.py @@ -37,7 +37,7 @@ from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeManilaV2 from qiskit import transpile - from qiskit.tools.visualization import plot_histogram + from qiskit.visualization import plot_histogram # Get a fake backend from the fake provider diff --git a/qiskit/test/base.py b/qiskit/test/base.py index 9bac2a629ff0..ab1f011a7bb3 100644 --- a/qiskit/test/base.py +++ b/qiskit/test/base.py @@ -28,8 +28,8 @@ import unittest from unittest.util import safe_repr +from qiskit.utils.parallel import get_platform_parallel_default from qiskit.exceptions import QiskitWarning -from qiskit.tools.parallel import get_platform_parallel_default from qiskit.utils import optionals as _optionals from qiskit.circuit import QuantumCircuit from .decorators import enforce_subclasses_call diff --git a/qiskit/tools/__init__.py b/qiskit/tools/__init__.py deleted file mode 100644 index 38354279117a..000000000000 --- a/qiskit/tools/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# 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. - -""" -================================== -Qiskit Tools (:mod:`qiskit.tools`) -================================== - -.. currentmodule:: qiskit.tools - -Parallel Routines ------------------ - -A helper function for calling a custom function with python ``ProcessPoolExecutor``. -Tasks can be executed in parallel using this function. -It has a built-in event publisher to show the progress of the parallel tasks. - -.. autofunction:: parallel_map - -Monitoring ----------- - -.. automodule:: qiskit.tools.events - -""" - -from .parallel import parallel_map -from .events import progressbar diff --git a/qiskit/tools/events/__init__.py b/qiskit/tools/events/__init__.py deleted file mode 100644 index d15a537bb942..000000000000 --- a/qiskit/tools/events/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# 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. - -""" -=================================== -Events (:mod:`qiskit.tools.events`) -=================================== - -A helper component for publishing and subscribing to events. - -.. currentmodule:: qiskit.tools.events - -.. autoclass:: TextProgressBar -""" - -from .progressbar import TextProgressBar diff --git a/qiskit/tools/events/progressbar.py b/qiskit/tools/events/progressbar.py deleted file mode 100644 index 459662e87a9b..000000000000 --- a/qiskit/tools/events/progressbar.py +++ /dev/null @@ -1,195 +0,0 @@ -# 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. - -# This file is part of QuTiP: Quantum Toolbox in Python. -# -# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson. -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names -# of its contributors may be used to endorse or promote products derived -# from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -############################################################################### - -"""Progress bars module""" - -import time -import datetime -import sys -from qiskit.tools.events.pubsub import Subscriber - - -class BaseProgressBar(Subscriber): - """An abstract progress bar with some shared functionality.""" - - def __init__(self): - super().__init__() - self.type = "progressbar" - self.touched = False - self.iter = None - self.t_start = None - self.t_done = None - - def start(self, iterations): - """Start the progress bar. - - Parameters: - iterations (int): Number of iterations. - """ - self.touched = True - self.iter = int(iterations) - self.t_start = time.time() - - def update(self, n): - """Update status of progress bar.""" - pass - - def time_elapsed(self): - """Return the time elapsed since start. - - Returns: - elapsed_time: Time since progress bar started. - """ - return "%6.2fs" % (time.time() - self.t_start) - - def time_remaining_est(self, completed_iter): - """Estimate the remaining time left. - - Parameters: - completed_iter (int): Number of iterations completed. - - Returns: - est_time: Estimated time remaining. - """ - if completed_iter: - t_r_est = (time.time() - self.t_start) / completed_iter * (self.iter - completed_iter) - else: - t_r_est = 0 - date_time = datetime.datetime(1, 1, 1) + datetime.timedelta(seconds=t_r_est) - time_string = "%02d:%02d:%02d:%02d" % ( - date_time.day - 1, - date_time.hour, - date_time.minute, - date_time.second, - ) - - return time_string - - def finished(self): - """Run when progress bar has completed.""" - pass - - -class TextProgressBar(BaseProgressBar): - """ - A simple text-based progress bar. - - output_handler : the handler the progress bar should be written to, default - is sys.stdout, another option is sys.stderr - - Examples: - - The progress bar can be used to track the progress of a `parallel_map`. - - .. code-block:: python - - import numpy as np - import qiskit.tools.jupyter - from qiskit.tools.parallel import parallel_map - from qiskit.tools.events import TextProgressBar - - TextProgressBar() - %qiskit_progress_bar -t text - parallel_map(np.sin, np.linspace(0,10,100)); - - And it can also be used individually. - - .. code-block:: python - - from qiskit.tools.events import TextProgressBar - - iterations = 100 - t = TextProgressBar() - t.start(iterations=iterations) - for i in range(iterations): - # step i of heavy calculation ... - t.update(i + 1) # update progress bar - - """ - - def __init__(self, output_handler=None): - super().__init__() - self._init_subscriber() - - self.output_handler = output_handler if output_handler else sys.stdout - - def _init_subscriber(self): - def _initialize_progress_bar(num_tasks): - self.start(num_tasks) - - self.subscribe("terra.parallel.start", _initialize_progress_bar) - - def _update_progress_bar(progress): - self.update(progress) - - self.subscribe("terra.parallel.done", _update_progress_bar) - - def _finish_progress_bar(): - self.unsubscribe("terra.parallel.start", _initialize_progress_bar) - self.unsubscribe("terra.parallel.done", _update_progress_bar) - self.unsubscribe("terra.parallel.finish", _finish_progress_bar) - self.finished() - - self.subscribe("terra.parallel.finish", _finish_progress_bar) - - def start(self, iterations): - self.touched = True - self.iter = int(iterations) - self.t_start = time.time() - pbar = "-" * 50 - self.output_handler.write("\r|{}| {}{}{} [{}]".format(pbar, 0, "/", self.iter, "")) - - def update(self, n): - # Don't update if we are not initialized or - # the update iteration number is greater than the total iterations set on start. - if not self.touched or n > self.iter: - return - filled_length = int(round(50 * n / self.iter)) - pbar = "█" * filled_length + "-" * (50 - filled_length) - time_left = self.time_remaining_est(n) - self.output_handler.write("\r|{}| {}{}{} [{}]".format(pbar, n, "/", self.iter, time_left)) - if n == self.iter: - self.output_handler.write("\n") - self.output_handler.flush() diff --git a/qiskit/tools/events/pubsub.py b/qiskit/tools/events/pubsub.py deleted file mode 100644 index 0b2a6d664679..000000000000 --- a/qiskit/tools/events/pubsub.py +++ /dev/null @@ -1,158 +0,0 @@ -# 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. - -""" -Message broker for the Publisher / Subscriber mechanism -""" - -from qiskit.exceptions import QiskitError - - -class _Broker: - """The event/message broker. It's a singleton. - - In order to keep consistency across all the components, it would be great to - have a specific format for new events, documenting their usage. - It's the responsibility of the component emitting an event to document it's usage in - the component docstring. - - Event format: - "terra..." - - Examples: - "terra.transpiler.compile.start" - "terra.job.status.changed" - "terra.backend.run.start" - "terra.job.result.received" - """ - - _instance = None - _subscribers = {} - - def __new__(cls): - if _Broker._instance is None: - _Broker._instance = object.__new__(cls) - return _Broker._instance - - class _Subscription: - def __init__(self, event, callback): - self.event = event - self.callback = callback - - def __eq__(self, other): - """Overrides the default implementation""" - if isinstance(other, self.__class__): - return self.event == other.event and id(self.callback) == id( - other.callback - ) # Allow 1:N subscribers - return False - - def subscribe(self, event, callback): - """Subscribes to an event, so when it's emitted all the callbacks subscribed, - will be executed. We are not allowing double registration. - - Args: - event (string): The event to subscribed in the form of: - "terra..." - callback (callable): The callback that will be executed when an event is - emitted. - """ - if not callable(callback): - raise QiskitError("Callback is not a callable!") - - if event not in self._subscribers: - self._subscribers[event] = [] - - new_subscription = self._Subscription(event, callback) - if new_subscription in self._subscribers[event]: - # We are not allowing double subscription - return False - - self._subscribers[event].append(new_subscription) - return True - - def dispatch(self, event, *args, **kwargs): - """Emits an event if there are any subscribers. - - Args: - event (String): The event to be emitted - args: Arguments linked with the event - kwargs: Named arguments linked with the event - """ - # No event, no subscribers. - if event not in self._subscribers: - return - - for subscriber in self._subscribers[event]: - subscriber.callback(*args, **kwargs) - - def unsubscribe(self, event, callback): - """Unsubscribe the specific callback to the event. - - Args - event (String): The event to unsubscribe - callback (callable): The callback that won't be executed anymore - - Returns - True: if we have successfully unsubscribed to the event - False: if there's no callback previously registered - """ - - try: - self._subscribers[event].remove(self._Subscription(event, callback)) - except KeyError: - return False - - return True - - def clear(self): - """Unsubscribe everything, leaving the Broker without subscribers/events.""" - self._subscribers.clear() - - -class Publisher: - """Represents a Publisher, every component (class) can become a Publisher and - send events by inheriting this class. Functions can call this class like: - Publisher().publish("event", args, ... ) - """ - - def __init__(self): - self._broker = _Broker() - - def publish(self, event, *args, **kwargs): - """Triggers an event, and associates some data to it, so if there are any - subscribers, their callback will be called synchronously.""" - return self._broker.dispatch(event, *args, **kwargs) - - -class Subscriber: - """Represents a Subscriber, every component (class) can become a Subscriber and - subscribe to events, that will call callback functions when they are emitted. - """ - - def __init__(self): - self._broker = _Broker() - - def subscribe(self, event, callback): - """Subscribes to an event, associating a callback function to that event, so - when the event occurs, the callback will be called. - This is a blocking call, so try to keep callbacks as lightweight as possible.""" - return self._broker.subscribe(event, callback) - - def unsubscribe(self, event, callback): - """Unsubscribe a pair event-callback, so the callback will not be called anymore - when the event occurs.""" - return self._broker.unsubscribe(event, callback) - - def clear(self): - """Unsubscribe everything""" - self._broker.clear() diff --git a/qiskit/tools/visualization.py b/qiskit/tools/visualization.py deleted file mode 100644 index c3e2ff06cc33..000000000000 --- a/qiskit/tools/visualization.py +++ /dev/null @@ -1,16 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2017, 2019. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. - -# pylint: disable=unused-wildcard-import,missing-module-docstring,wildcard-import - -# NOTE(mtreinish): Import public API here to maintain backwards compat -from qiskit.visualization import * diff --git a/qiskit/transpiler/passes/layout/sabre_layout.py b/qiskit/transpiler/passes/layout/sabre_layout.py index ca71ebee2777..2859fb6075c8 100644 --- a/qiskit/transpiler/passes/layout/sabre_layout.py +++ b/qiskit/transpiler/passes/layout/sabre_layout.py @@ -43,7 +43,7 @@ from qiskit.transpiler.passes.routing.sabre_swap import _build_sabre_dag, _apply_sabre_result from qiskit.transpiler.target import Target from qiskit.transpiler.coupling import CouplingMap -from qiskit.tools.parallel import CPU_COUNT +from qiskit.utils.parallel import CPU_COUNT logger = logging.getLogger(__name__) diff --git a/qiskit/transpiler/passes/routing/sabre_swap.py b/qiskit/transpiler/passes/routing/sabre_swap.py index 250b310d3a80..e8d8a437ed63 100644 --- a/qiskit/transpiler/passes/routing/sabre_swap.py +++ b/qiskit/transpiler/passes/routing/sabre_swap.py @@ -29,7 +29,7 @@ from qiskit.transpiler.target import Target from qiskit.transpiler.passes.layout import disjoint_utils from qiskit.dagcircuit import DAGCircuit -from qiskit.tools.parallel import CPU_COUNT +from qiskit.utils.parallel import CPU_COUNT from qiskit._accelerate.sabre_swap import ( build_swap_map, diff --git a/qiskit/utils/__init__.py b/qiskit/utils/__init__.py index a9b73b85f95d..d1cecf05d6b0 100644 --- a/qiskit/utils/__init__.py +++ b/qiskit/utils/__init__.py @@ -30,6 +30,13 @@ .. autofunction:: wrap_method +Parallel Routines +----------------- +A helper function for calling a custom function with python +:class:`~concurrent.futures.ProcessPoolExecutor`. Tasks can be executed in parallel using this function. + +.. autofunction:: parallel_map + Optional Dependency Checkers (:mod:`qiskit.utils.optionals`) ============================================================ @@ -51,6 +58,8 @@ from . import optionals +from .parallel import parallel_map + __all__ = [ "LazyDependencyManager", "LazyImportTester", @@ -63,4 +72,5 @@ "local_hardware_info", "is_main_process", "apply_prefix", + "parallel_map", ] diff --git a/qiskit/tools/parallel.py b/qiskit/utils/parallel.py similarity index 93% rename from qiskit/tools/parallel.py rename to qiskit/utils/parallel.py index 1b48791e3477..b46c3bc7c9b8 100644 --- a/qiskit/tools/parallel.py +++ b/qiskit/utils/parallel.py @@ -54,7 +54,6 @@ from qiskit.exceptions import QiskitError from qiskit.utils.multiprocessing import local_hardware_info -from qiskit.tools.events.pubsub import Publisher from qiskit import user_config @@ -151,13 +150,6 @@ def func(_): if len(values) == 1: return [task(values[0], *task_args, **task_kwargs)] - Publisher().publish("terra.parallel.start", len(values)) - nfinished = [0] - - def _callback(_): - nfinished[0] += 1 - Publisher().publish("terra.parallel.done", nfinished[0]) - # Run in parallel if not Win and not in parallel already if ( num_processes > 1 @@ -172,18 +164,15 @@ def _callback(_): future = executor.map(_task_wrapper, param) results = list(future) - Publisher().publish("terra.parallel.done", len(results)) except (KeyboardInterrupt, Exception) as error: if isinstance(error, KeyboardInterrupt): - Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise QiskitError("Keyboard interrupt in parallel_map.") from error # Otherwise just reset parallel flag and error os.environ["QISKIT_IN_PARALLEL"] = "FALSE" raise error - Publisher().publish("terra.parallel.finish") os.environ["QISKIT_IN_PARALLEL"] = "FALSE" return results @@ -193,6 +182,4 @@ def _callback(_): for _, value in enumerate(values): result = task(value, *task_args, **task_kwargs) results.append(result) - _callback(0) - Publisher().publish("terra.parallel.finish") return results diff --git a/qiskit/visualization/circuit/circuit_visualization.py b/qiskit/visualization/circuit/circuit_visualization.py index a70ef9c2822b..00c0e4d390a9 100644 --- a/qiskit/visualization/circuit/circuit_visualization.py +++ b/qiskit/visualization/circuit/circuit_visualization.py @@ -184,7 +184,7 @@ def circuit_drawer( :include-source: from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit - from qiskit.tools.visualization import circuit_drawer + from qiskit.visualization import circuit_drawer q = QuantumRegister(1) c = ClassicalRegister(1) qc = QuantumCircuit(q, c) diff --git a/releasenotes/notes/remove-tools-2d13fc5ec1f45336.yaml b/releasenotes/notes/remove-tools-2d13fc5ec1f45336.yaml new file mode 100644 index 000000000000..d5e2e611a576 --- /dev/null +++ b/releasenotes/notes/remove-tools-2d13fc5ec1f45336.yaml @@ -0,0 +1,18 @@ +--- +upgrade: + - | + The deprecated ``qiskit.tools.visualization`` module has removed. This module + was deprecated in the Qiskit 0.46.0 release. This module was a legacy redirect + from the original location of Qiskit's visualization module and was moved to + :mod:`qiskit.visualization` in Qiskit 0.8.0. If you're still using this path + you can just update your imports from ``qiskit.tools.visualization`` + to :mod:`qiskit.visualization`. + - | + The deprecated ``qiskit.tools.events`` module and the corresponding + ``qiskit.tools.progressbar`` utility it exposed has been removed. It was deprecated + in the Qiskit 0.46.0 release. This module's functionality was not widely used and + better covered by dedicated packages such as `tqdm `__. + - | + The ``qiskit.tools`` module has been removed. This module was deprecated in Qiskit 0.46.0. + All the contents from this module have been removed except for the ``qiskit.tools.parallel_map`` + function which now can be used from :func:`qiskit.utils.parallel_map` instead. diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index 900f5641cffb..ebf2f4e11c8a 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -36,7 +36,7 @@ from qiskit.quantum_info import Operator from qiskit.test import QiskitTestCase from qiskit.providers.fake_provider import FakeOurense -from qiskit.tools import parallel_map +from qiskit.utils import parallel_map def raise_if_parameter_table_invalid(circuit): diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 2a13f35adfb9..3f52a06fb760 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -85,7 +85,7 @@ from qiskit.pulse import InstructionScheduleMap from qiskit.quantum_info import Operator, random_unitary from qiskit.test import QiskitTestCase, slow_test -from qiskit.tools import parallel +from qiskit.utils import parallel from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass from qiskit.transpiler.exceptions import TranspilerError, CircuitTooWideForTarget from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout diff --git a/test/python/tools/__init__.py b/test/python/tools/__init__.py deleted file mode 100644 index 39afed863464..000000000000 --- a/test/python/tools/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# 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. - -"""Qiskit tools tests.""" diff --git a/test/python/tools/test_pubsub.py b/test/python/tools/test_pubsub.py deleted file mode 100644 index 673c8e5445d1..000000000000 --- a/test/python/tools/test_pubsub.py +++ /dev/null @@ -1,92 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2017. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. - -"""Tests for qiskit/tools/events/_pubsub.py""" - -from qiskit.tools.events.pubsub import Publisher, Subscriber -from qiskit.test import QiskitTestCase - - -class DummySubscriber(Subscriber): - """Simulates a component behaving like a Subscriber""" - - def __del__(self): - self.clear() - - -class TestPubSub(QiskitTestCase): - """A class for testing Publisher/Subscriber functionality.""" - - def test_pusbsub(self): - """Test subscribing works""" - sub = DummySubscriber() - - def action_callback(test): - """Callback called when 'publisher.action` event occurs""" - test.assertTrue(True) - - sub.subscribe("publisher.action", action_callback) - Publisher().publish("publisher.action", self) - - def test_single_broker(self): - """Testing a single broker is instantiated no matter how many - Publishers or Subscribers we have""" - - publishers = [Publisher() for _ in range(10)] - subscribers = [DummySubscriber() for _ in range(10)] - - for pub, sub in zip(publishers, subscribers): - self.assertEqual(id(pub._broker), id(sub._broker)) - - def test_double_subscribe(self): - """Testing that we cannot subscribe the same callback to the same event""" - - def callback(): - """This should be ever called""" - pass - - sub = DummySubscriber() - sub2 = DummySubscriber() - - sub.subscribe("event", callback) - self.assertFalse(sub.subscribe("event", callback)) - self.assertFalse(sub2.subscribe("event", callback)) - - def test_unsubscribe_simple(self): - """Testing a simple unsubscribe works""" - sub = DummySubscriber() - - def callback(_who, test): - """This should have ever been called""" - test.fail("We shouldn't have reach this code!") - - sub.subscribe("publisher.action", callback) - sub.unsubscribe("publisher.action", callback) - Publisher().publish("publisher.action", self) - - def test_unsubscribe_multiple(self): - """Testing unsubscribe works with many other subscribed event works""" - - sub = DummySubscriber() - - def callback(test): - """This should have ever been called""" - test.fail("We shouldn't have reach this code!") - - def dummy_callback(_test): - """Just a dummy callback, it won't be executed""" - pass - - sub.subscribe("publisher.action", callback) - sub.subscribe("publisher.action", dummy_callback) - sub.unsubscribe("publisher.action", callback) - Publisher().publish("publisher.action", self) diff --git a/test/python/tools/test_parallel.py b/test/python/utils/test_parallel.py similarity index 97% rename from test/python/tools/test_parallel.py rename to test/python/utils/test_parallel.py index 27801c1f6175..1194150ce4d7 100644 --- a/test/python/tools/test_parallel.py +++ b/test/python/utils/test_parallel.py @@ -16,7 +16,7 @@ from unittest.mock import patch -from qiskit.tools.parallel import get_platform_parallel_default, parallel_map +from qiskit.utils.parallel import get_platform_parallel_default, parallel_map from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.pulse import Schedule from qiskit.test import QiskitTestCase