Skip to main contentIBM Quantum Documentation
You are viewing the API reference for an old version of Qiskit SDK. Switch to latest version

Utilities

qiskit.utils

add_deprecation_to_docstring

qiskit.utils.add_deprecation_to_docstring(func, msg, *, since, pending)

GitHub(opens in a new tab)

Dynamically insert the deprecation message into func’s docstring.

Parameters

deprecate_arg

qiskit.utils.deprecate_arg(name, *, since, additional_msg=None, deprecation_description=None, pending=False, package_name='qiskit', new_alias=None, predicate=None, removal_timeline='no earlier than 3 months after the release date')

GitHub(opens in a new tab)

Decorator to indicate an argument has been deprecated in some way.

This decorator may be used multiple times on the same function, once per deprecated argument. It should be placed beneath other decorators like @staticmethod and property decorators.

Parameters

  • name (str(opens in a new tab)) – The name of the deprecated argument.
  • since (str(opens in a new tab)) – The version the deprecation started at. If the deprecation is pending, set the version to when that started; but later, when switching from pending to deprecated, update since to the new version.
  • deprecation_description (str(opens in a new tab) | None) – What is being deprecated? E.g. “Setting my_func()’s my_arg argument to None.” If not set, will default to “{func_name}’s argument {name}”.
  • additional_msg (str(opens in a new tab) | None) – Put here any additional information, such as what to use instead (if new_alias is not set). For example, “Instead, use the argument new_arg, which is similar but does not impact the circuit’s setup.”
  • pending (bool(opens in a new tab)) – Set to True if the deprecation is still pending.
  • package_name (str(opens in a new tab)) – The PyPI package name, e.g. “qiskit-nature”.
  • new_alias (str(opens in a new tab) | None) – If the arg has simply been renamed, set this to the new name. The decorator will dynamically update the kwargs so that when the user sets the old arg, it will be passed in as the new_alias arg.
  • predicate (Callable[[Any], bool(opens in a new tab)] | None) – Only log the runtime warning if the predicate returns True. This is useful to deprecate certain values or types for an argument, e.g. lambda my_arg: isinstance(my_arg, dict). Regardless of if a predicate is set, the runtime warning will only log when the user specifies the argument.
  • removal_timeline (str(opens in a new tab)) – How soon can this deprecation be removed? Expects a value like “no sooner than 6 months after the latest release” or “in release 9.99”.

Returns

The decorated callable.

Return type

Callable

deprecate_arguments

qiskit.utils.deprecate_arguments(kwarg_map, category=<class 'DeprecationWarning'>, *, since=None)

GitHub(opens in a new tab)

Deprecated. Instead, use @deprecate_arg.

Parameters

Returns

The decorated callable.

Return type

Callable

deprecate_func

qiskit.utils.deprecate_func(*, since, additional_msg=None, pending=False, package_name='qiskit', removal_timeline='no earlier than 3 months after the release date', is_property=False)

GitHub(opens in a new tab)

Decorator to indicate a function has been deprecated.

It should be placed beneath other decorators like @staticmethod and property decorators.

When deprecating a class, set this decorator on its __init__ function.

Parameters

  • since (str(opens in a new tab)) – The version the deprecation started at. If the deprecation is pending, set the version to when that started; but later, when switching from pending to deprecated, update since to the new version.
  • additional_msg (str(opens in a new tab) | None) – Put here any additional information, such as what to use instead. For example, “Instead, use the function new_func from the module <my_module>.<my_submodule>, which is similar but uses GPU acceleration.”
  • pending (bool(opens in a new tab)) – Set to True if the deprecation is still pending.
  • package_name (str(opens in a new tab)) – The PyPI package name, e.g. “qiskit-nature”.
  • removal_timeline (str(opens in a new tab)) – How soon can this deprecation be removed? Expects a value like “no sooner than 6 months after the latest release” or “in release 9.99”.
  • is_property (bool(opens in a new tab)) – If the deprecated function is a @property, set this to True so that the generated message correctly describes it as such. (This isn’t necessary for property setters, as their docstring is ignored by Python.)

Returns

The decorated callable.

Return type

Callable

deprecate_function

qiskit.utils.deprecate_function(msg, stacklevel=2, category=<class 'DeprecationWarning'>, *, since=None)

GitHub(opens in a new tab)

Deprecated. Instead, use @deprecate_func.

Parameters

  • msg (str(opens in a new tab)) – Warning message to emit.
  • stacklevel (int(opens in a new tab)) – The warning stacklevel to use, defaults to 2.
  • category (Type[Warning(opens in a new tab)]) – Usually either DeprecationWarning or PendingDeprecationWarning.
  • since (str(opens in a new tab) | None) – The version the deprecation started at. Only Optional for backwards compatibility - this should always be set. If the deprecation is pending, set the version to when that started; but later, when switching from pending to deprecated, update since to the new version.

Returns

The decorated, deprecated callable.

Return type

Callable

local_hardware_info

qiskit.utils.local_hardware_info()

GitHub(opens in a new tab)

Basic hardware information about the local machine.

Gives actual number of CPU’s in the machine, even when hyperthreading is turned on. CPU count defaults to 1 when true count can’t be determined.

Returns

The hardware information.

Return type

dict(opens in a new tab)

is_main_process

qiskit.utils.is_main_process()

GitHub(opens in a new tab)

Checks whether the current process is the main one

apply_prefix

qiskit.utils.apply_prefix(value, unit)

GitHub(opens in a new tab)

Given a SI unit prefix and value, apply the prefix to convert to standard SI unit.

Parameters

Returns

Converted value.

Return type

float(opens in a new tab) | ParameterExpression

Note

This may induce tiny value error due to internal representation of float object. See https://docs.python.org/3/tutorial/floatingpoint.html(opens in a new tab) for details.

Raises

ValueError(opens in a new tab) – If the units aren’t recognized.

Return type

float(opens in a new tab) | ParameterExpression

detach_prefix

qiskit.utils.detach_prefix(value, decimal=None)

GitHub(opens in a new tab)

Given a SI unit value, find the most suitable prefix to scale the value.

For example, the value = 1.3e8 will be converted into a tuple of (130.0, "M"), which represents a scaled value and auxiliary unit that may be used to display the value. In above example, that value might be displayed as 130 MHz (unit is arbitrary here).

Example

>>> value, prefix = detach_prefix(1e4)
>>> print(f"{value} {prefix}Hz")
10 kHz

Parameters

  • value (float(opens in a new tab)) – The number to find prefix.
  • decimal (int(opens in a new tab) | None) – Optional. An arbitrary integer number to represent a precision of the value. If specified, it tries to round the mantissa and adjust the prefix to rounded value. For example, 999_999.91 will become 999.9999 k with decimal=4, while 1.0 M with decimal=3 or less.

Returns

A tuple of scaled value and prefix.

Return type

tuple(opens in a new tab)[float(opens in a new tab), str(opens in a new tab)]

Note

This may induce tiny value error due to internal representation of float object. See https://docs.python.org/3/tutorial/floatingpoint.html(opens in a new tab) for details.

Raises

Return type

tuple(opens in a new tab)[float(opens in a new tab), str(opens in a new tab)]

wrap_method

qiskit.utils.wrap_method(cls, name, *, before=None, after=None)

GitHub(opens in a new tab)

Wrap the functionality the instance- or class method cls.name with additional behaviour before and after.

This mutates cls, replacing the attribute name with the new functionality. This is useful when creating class decorators. The method is allowed to be defined on any parent class instead.

If either before or after are given, they should be callables with a compatible signature to the method referred to. They will be called immediately before or after the method as appropriate, and any return value will be ignored.

Parameters

Raises

ValueError(opens in a new tab) – if the named method is not defined on the class or any parent class.


Algorithm Utilities

summarize_circuits

qiskit.utils.summarize_circuits(circuits)

GitHub(opens in a new tab)

Summarize circuits based on QuantumCircuit, and five metrics are summarized.

  • Number of qubits
  • Number of classical bits
  • Number of operations
  • Depth of circuits
  • Counts of different gate operations

The average statistic of the first four is provided if multiple circuits are provided.

Parameters

circuits (QuantumCircuit or [QuantumCircuit]) – the to-be-summarized circuits

Returns

a formatted string records the summary

Return type

str(opens in a new tab)

get_entangler_map

qiskit.utils.get_entangler_map(map_type, num_qubits, offset=0)

GitHub(opens in a new tab)

Utility method to get an entangler map among qubits.

Parameters

  • map_type (str(opens in a new tab)) – ‘full’ entangles each qubit with all the subsequent ones ‘linear’ entangles each qubit with the next ‘sca’ (shifted circular alternating entanglement) is a circular entanglement where the ‘long’ entanglement is shifted by one position every block and every block the role or control/target qubits alternate
  • num_qubits (int(opens in a new tab)) – Number of qubits for which the map is needed
  • offset (int(opens in a new tab)) – Some map_types (e.g. ‘sca’) can shift the gates in the entangler map by the specified integer offset.

Returns

A map of qubit index to an array of indexes to which this should be entangled

Return type

list(opens in a new tab)

Raises

ValueError(opens in a new tab) – if map_type is not valid.

validate_entangler_map

qiskit.utils.validate_entangler_map(entangler_map, num_qubits, allow_double_entanglement=False)

GitHub(opens in a new tab)

Validate a user supplied entangler map and converts entries to ints.

Parameters

Returns

Validated/converted map

Return type

list(opens in a new tab)

Raises

has_ibmq

qiskit.utils.has_ibmq()

GitHub(opens in a new tab)

Check if IBMQ is installed.

Deprecated since version 0.24.0

The function qiskit.utils.backend_utils.has_ibmq() is deprecated as of qiskit-terra 0.24.0. It will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/qi_migration(opens in a new tab).

has_aer

qiskit.utils.has_aer()

GitHub(opens in a new tab)

Check if Aer is installed.

Deprecated since version 0.24.0

The function qiskit.utils.backend_utils.has_aer() is deprecated as of qiskit-terra 0.24.0. It will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/qi_migration(opens in a new tab).

name_args

qiskit.utils.name_args(mapping, skip=0)

GitHub(opens in a new tab)

Decorator to convert unnamed arguments to named ones.

Can be used to deprecate old signatures of a function, e.g.

old_f(a: TypeA, b: TypeB, c: TypeC)
new_f(a: TypeA, d: TypeD, b: TypeB=None, c: TypeC=None)

Then, to support the old signature this decorator can be used as

@name_args([
    ('a'),  # stays the same
    ('d', {TypeB: 'b'}),  # if arg is of type TypeB, call if 'b' else 'd'
    ('b', {TypeC: 'c'})
])
def new_f(a: TypeA, d: TypeD, b: TypeB=None, c: TypeC=None):
    if b is not None:
        # raise warning, this is deprecated!
    if c is not None:
        # raise warning, this is deprecated!

qiskit.utils.algorithm_globals = <qiskit.utils.algorithm_globals.QiskitAlgorithmGlobals object>

Class for global properties.

QuantumInstanceDeprecated: Quantum Backend including execution setting.

A QuantumInstance holds the Qiskit backend as well as a number of compile and runtime parameters controlling circuit compilation and execution. Quantum algorithms are run on a device or simulator by passing a QuantumInstance setup with the desired backend etc.


Optional Dependency Checkers

qiskit.utils.optionals

Qiskit has several features that are enabled only if certain optional dependencies are satisfied. This module is a collection of objects that can be used to test if certain functionality is available, and optionally raise MissingOptionalLibraryError if the functionality is not available.

Available Testers

Qiskit Components

qiskit.utils.optionals.HAS_AERQiskit Aer provides high-performance simulators for the quantum circuits constructed within Qiskit.
qiskit.utils.optionals.HAS_IBMQThe Qiskit IBMQ Provider is used for accessing IBM Quantum hardware in the IBM cloud.
qiskit.utils.optionals.HAS_IGNISQiskit Ignis provides tools for quantum hardware verification, noise characterization, and error correction.
qiskit.utils.optionals.HAS_TOQMQiskit TOQM(opens in a new tab) provides transpiler passes for the Time-optimal Qubit mapping algorithm(opens in a new tab).

External Python Libraries

qiskit.utils.optionals.HAS_CONSTRAINTpython-constraint <https://github.com/python-constraint/python-constraint>__(opens in a new tab) is a constraint satisfaction problem solver, used in the :class:`~.CSPLayout transpiler pass.
qiskit.utils.optionals.HAS_CPLEXThe IBM CPLEX Optimizer(opens in a new tab) is a high-performance mathematical programming solver for linear, mixed-integer and quadratic programming. This is no longer by Qiskit, but it weas historically and the optional remains for backwards compatibility.
qiskit.utils.optionals.HAS_CVXPYCVXPY(opens in a new tab) is a Python package for solving convex optimization problems. It is required for calculating diamond norms with quantum_info.diamond_norm().
qiskit.utils.optionals.HAS_DOCPLEXIBM Decision Optimization CPLEX Modelling(opens in a new tab) is a library for prescriptive analysis. Like CPLEX, this is no longer by Qiskit, but it weas historically and the optional remains for backwards compatibility.
qiskit.utils.optionals.HAS_FIXTURESThe test suite has additional features that are available if the optional fixtures(opens in a new tab) module is installed. This generally also needs HAS_TESTTOOLS as well. This is generally only needed for Qiskit developers.
qiskit.utils.optionals.HAS_IPYTHONIf the IPython kernel(opens in a new tab) is available, certain additional visualisations and line magics are made available.
qiskit.utils.optionals.HAS_IPYWIDGETSMonitoring widgets for jobs running on external backends can be provided if ipywidgets(opens in a new tab) is available.
qiskit.utils.optionals.HAS_JAXSome methods of gradient calculation within opflow.gradients require JAX(opens in a new tab) for autodifferentiation.
qiskit.utils.optionals.HAS_JUPYTERSome of the tests require a complete Jupyter(opens in a new tab) installation to test interactivity features.
qiskit.utils.optionals.HAS_MATPLOTLIBQiskit provides several visualisation tools in the visualization module. Almost all of these are built using Matplotlib(opens in a new tab), which must be installed in order to use them.
qiskit.utils.optionals.HAS_NETWORKXNo longer used by Qiskit. Internally, Qiskit now uses the high-performance rustworkx(opens in a new tab) library as a core dependency, and during the change-over period, it was sometimes convenient to convert things into the Python-only NetworkX(opens in a new tab) format. Some tests of application modules, such as Qiskit Nature(opens in a new tab) still use NetworkX.
qiskit.utils.optionals.HAS_NLOPTNLopt(opens in a new tab) is a nonlinear optimization library, used by the global optimizers in the algorithms.optimizers module.
qiskit.utils.optionals.HAS_PILPIL is a Python image-manipulation library. Qiskit actually uses the pillow(opens in a new tab) fork of PIL if it is available when generating certain visualizations, for example of both QuantumCircuit and DAGCircuit in certain modes.
qiskit.utils.optionals.HAS_PYDOTFor some graph visualisations, Qiskit uses pydot(opens in a new tab) as an interface to GraphViz (see HAS_GRAPHVIZ).
qiskit.utils.optionals.HAS_PYGMENTSPygments is a code highlighter and formatter used by many environments that involve rich display of code blocks, including Sphinx and Jupyter. Qiskit uses this when producing rich output for these environments.
qiskit.utils.optionals.HAS_PYLATEXVarious LaTeX-based visualizations, especially the circuit drawers, need access to the pylatexenc(opens in a new tab) project to work correctly.
qiskit.utils.optionals.HAS_QASM3_IMPORTThe functions qasm3.load() and qasm3.loads() for importing OpenQASM 3 programs into QuantumCircuit instances use an external importer package(opens in a new tab).
qiskit.utils.optionals.HAS_SEABORNQiskit provides several visualisation tools in the visualization module. Some of these are built using Seaborn(opens in a new tab), which must be installed in order to use them.
qiskit.utils.optionals.HAS_SKLEARNSome of the gradient functions in opflow.gradients use regularisation methods from Scikit Learn(opens in a new tab).
qiskit.utils.optionals.HAS_SKQUANTSome of the optimisers in algorithms.optimizers are based on those found in Scikit Quant(opens in a new tab), which must be installed to use them.
qiskit.utils.optionals.HAS_SQSNOBFITSQSnobFit(opens in a new tab) is a library for the “stable noisy optimization by branch and fit” algorithm. It is used by the SNOBFIT optimizer.
qiskit.utils.optionals.HAS_SYMENGINESymengine(opens in a new tab) is a fast C++ backend for the symbolic-manipulation library Sympy(opens in a new tab). Qiskit uses special methods from Symengine to accelerate its handling of Parameters if available.
qiskit.utils.optionals.HAS_TESTTOOLSQiskit’s test suite has more advanced functionality available if the optional testtools(opens in a new tab) library is installed. This is generally only needed for Qiskit developers.
qiskit.utils.optionals.HAS_TWEEDLEDUMTweedledum(opens in a new tab) is an extension library for synthesis and optimization of circuits that may involve classical oracles. Qiskit’s PhaseOracle uses this, which is used in turn by amplification algorithms via the AmplificationProblem.
qiskit.utils.optionals.HAS_Z3Z3(opens in a new tab) is a theorem prover, used in the CrosstalkAdaptiveSchedule and HoareOptimizer transpiler passes.

External Command-Line Tools

qiskit.utils.optionals.HAS_GRAPHVIZFor some graph visualisations, Qiskit uses the GraphViz(opens in a new tab) visualisation tool via its pydot interface (see HAS_PYDOT).
qiskit.utils.optionals.HAS_PDFLATEXVisualisation tools that use LaTeX in their output, such as the circuit drawers, require pdflatex to be available. You will generally need to ensure that you have a working LaTeX installation available, and the qcircuit.tex package.
qiskit.utils.optionals.HAS_PDFTOCAIROVisualisation tools that convert LaTeX-generated files into rasterised images use the pdftocairo tool. This is part of the Poppler suite of PDF tools(opens in a new tab).

Lazy Checker Classes

Each of the lazy checkers is an instance of LazyDependencyManager in one of its two subclasses: LazyImportTester and LazySubprocessTester. These should be imported from utils directly if required, such as:

from qiskit.utils import LazyImportTester

qiskit.utils.LazyDependencyManager(*, name=None, callback=None, install=None, msg=None)

GitHub(opens in a new tab)

A mananger for some optional features that are expensive to import, or to verify the existence of.

These objects can be used as Booleans, such as if x, and will evaluate True if the dependency they test for is available, and False if not. The presence of the dependency will only be tested when the Boolean is evaluated, so it can be used as a runtime test in functions and methods without requiring an import-time test.

These objects also encapsulate the error handling if their dependency is not present, so you can do things such as:

from qiskit.utils import LazyImportManager
HAS_MATPLOTLIB = LazyImportManager("matplotlib")
 
@HAS_MATPLOTLIB.require_in_call
def my_visualisation():
    ...
 
def my_other_visualisation():
    # ... some setup ...
    HAS_MATPLOTLIB.require_now("my_other_visualisation")
    ...
 
def my_third_visualisation():
    if HAS_MATPLOTLIB:
        from matplotlib import pyplot
    else:
        ...

In all of these cases, matplotlib is not imported until the functions are entered. In the case of the decorator, matplotlib is tested for import when the function is called for the first time. In the second and third cases, the loader attempts to import matplotlib when the require_now() method is called, or when the Boolean context is evaluated. For the require methods, an error is raised if the library is not available.

This is the base class, which provides the Boolean context checking and error management. The concrete classes LazyImportTester and LazySubprocessTester provide convenient entry points for testing that certain symbols are importable from modules, or certain command-line tools are available, respectively.

Parameters

  • name – the name of this optional dependency.
  • callback – a callback that is called immediately after the availability of the library is tested with the result. This will only be called once.
  • install – how to install this optional dependency. Passed to MissingOptionalLibraryError as the pip_install parameter.
  • msg – an extra message to include in the error raised if this is required.

_is_available

abstract _is_available()

Subclasses of LazyDependencyManager should override this method to implement the actual test of availability. This method should return a Boolean, where True indicates that the dependency was available. This method will only ever be called once.

Return type

bool(opens in a new tab)

disable_locally

disable_locally()

Create a context, during which the value of the dependency manager will be False. This means that within the context, any calls to this object will behave as if the dependency is not available, including raising errors. It is valid to call this method whether or not the dependency has already been evaluated. This is most useful in tests.

require_in_call

require_in_call(feature_or_callable: Callable) → Callable

require_in_call(feature_or_callable: str) → Callable[[Callable], Callable]

Create a decorator for callables that requires that the dependency is available when the decorated function or method is called.

Parameters

feature_or_callable (str(opens in a new tab) or Callable) – the name of the feature that requires these dependencies. If this function is called directly as a decorator (for example @HAS_X.require_in_call as opposed to @HAS_X.require_in_call("my feature")), then the feature name will be taken to be the function name, or class and method name as appropriate.

Returns

a decorator that will make its argument require this dependency before it is called.

Return type

Callable

require_in_instance

require_in_instance(feature_or_class: Type) → Type

require_in_instance(feature_or_class: str) → Callable[[Type], Type]

A class decorator that requires the dependency is available when the class is initialised. This decorator can be used even if the class does not define an __init__ method.

Parameters

feature_or_class (str(opens in a new tab) orType) – the name of the feature that requires these dependencies. If this function is called directly as a decorator (for example @HAS_X.require_in_instance as opposed to @HAS_X.require_in_instance("my feature")), then the feature name will be taken as the name of the class.

Returns

a class decorator that ensures that the wrapped feature is present if the class is initialised.

Return type

Callable

require_now

require_now(feature)

Eagerly attempt to import the dependencies in this object, and raise an exception if they cannot be imported.

Parameters

feature (str(opens in a new tab)) – the name of the feature that is requiring these dependencies.

Raises

MissingOptionalLibraryError – if the dependencies cannot be imported.

qiskit.utils.LazyImportTester(name_map_or_modules, *, name=None, callback=None, install=None, msg=None)

GitHub(opens in a new tab)

A lazy dependency tester for importable Python modules. Any required objects will only be imported at the point that this object is tested for its Boolean value.

Parameters

name_map_or_modules (str(opens in a new tab) |Dict(opens in a new tab)[str(opens in a new tab), Iterable(opens in a new tab)[str(opens in a new tab)]] | Iterable(opens in a new tab)[str(opens in a new tab)]) – if a name map, then a dictionary where the keys are modules or packages, and the values are iterables of names to try and import from that module. It should be valid to write from <module> import <name1>, <name2>, .... If simply a string or iterable of strings, then it should be valid to write import <module> for each of them.

Raises

ValueError(opens in a new tab) – if no modules are given.

qiskit.utils.LazySubprocessTester(command, *, name=None, callback=None, install=None, msg=None)

GitHub(opens in a new tab)

A lazy checker that a command-line tool is available. The command will only be run once, at the point that this object is checked for its Boolean value.

Parameters

command (str(opens in a new tab) |Iterable(opens in a new tab)[str(opens in a new tab)]) – the strings that make up the command to be run. For example, ["pdflatex", "-version"].

Raises

ValueError(opens in a new tab) – if an empty command is given.

Was this page helpful?
Report a bug or request content on GitHub.