Esempio n. 1
0
    def __init__(self,
                 qregs,
                 cregs,
                 ops,
                 scale=1.0,
                 style=None,
                 plot_barriers=True,
                 reverse_bits=False):

        if not HAS_MATPLOTLIB:
            raise ImportError('The class MatplotlibDrawer needs matplotlib. '
                              'Run "pip install matplotlib" before.')

        self._ast = None
        self._scale = DEFAULT_SCALE * scale
        self._creg = []
        self._qreg = []
        self._registers(cregs, qregs)
        self._ops = ops

        self._qreg_dict = collections.OrderedDict()
        self._creg_dict = collections.OrderedDict()
        self._cond = {
            'n_lines': 0,
            'xmax': 0,
            'ymax': 0,
        }
        config = user_config.get_config()
        if config and (style is None):
            config_style = config.get('circuit_mpl_style', 'default')
            if config_style == 'default':
                self._style = DefaultStyle()
            elif config_style == 'bw':
                self._style = BWStyle()
        elif style is False:
            self._style = BWStyle()
        else:
            self._style = DefaultStyle()

        self.plot_barriers = plot_barriers
        self.reverse_bits = reverse_bits
        if style:
            if isinstance(style, dict):
                self._style.set_style(style)
            elif isinstance(style, str):
                with open(style, 'r') as infile:
                    dic = json.load(infile)
                self._style.set_style(dic)

        self.figure = plt.figure()
        self.figure.patch.set_facecolor(color=self._style.bg)
        self.ax = self.figure.add_subplot(111)
        self.ax.axis('off')
        self.ax.set_aspect('equal')
        self.ax.tick_params(labelbottom=False,
                            labeltop=False,
                            labelleft=False,
                            labelright=False)

        self.x_offset = 0
Esempio n. 2
0
    def test_set_config_all_options_valid(self):
        self.addCleanup(os.remove, self.file_path)

        user_config.set_config("circuit_drawer",
                               "latex",
                               file_path=self.file_path)
        user_config.set_config("circuit_mpl_style",
                               "default",
                               file_path=self.file_path)
        user_config.set_config("circuit_mpl_style_path",
                               "~:~/.qiskit",
                               file_path=self.file_path)
        user_config.set_config("transpile_optimization_level",
                               "3",
                               file_path=self.file_path)
        user_config.set_config("parallel", "false", file_path=self.file_path)
        user_config.set_config("num_processes", "15", file_path=self.file_path)

        config_settings = None
        with mock.patch.dict(os.environ, {"QISKIT_SETTINGS": self.file_path},
                             clear=True):
            config_settings = user_config.get_config()

        self.assertEqual(
            {
                "circuit_drawer": "latex",
                "circuit_mpl_style": "default",
                "circuit_mpl_style_path": ["~", "~/.qiskit"],
                "transpile_optimization_level": 3,
                "num_processes": 15,
                "parallel_enabled": False,
            },
            config_settings,
        )
Esempio n. 3
0
def circuit_drawer(
    circuit,
    scale=None,
    filename=None,
    style=None,
    output=None,
    interactive=False,
    plot_barriers=True,
    reverse_bits=False,
    justify=None,
    vertical_compression="medium",
    idle_wires=True,
    with_layout=True,
    fold=None,
    ax=None,
    initial_state=False,
    cregbundle=True,
):
    """Draw the quantum circuit. Use the output parameter to choose the drawing format:

    **text**: ASCII art TextDrawing that can be printed in the console.

    **matplotlib**: images with color rendered purely in Python.

    **latex**: high-quality images compiled via latex.

    **latex_source**: raw uncompiled latex output.

    Args:
        circuit (QuantumCircuit): the quantum circuit to draw
        scale (float): scale of image to draw (shrink if < 1.0). Only used by
            the `mpl`, `latex` and `latex_source` outputs. Defaults to 1.0.
        filename (str): file path to save image to. Defaults to None.
        style (dict or str): dictionary of style or file name of style json file.
            This option is only used by the `mpl` or `latex` output type.
            If `style` is a str, it is used as the path to a json file
            which contains a style dict. The file will be opened, parsed, and
            then any style elements in the dict will replace the default values
            in the input dict. A file to be loaded must end in ``.json``, but
            the name entered here can omit ``.json``. For example,
            ``style='iqx.json'`` or ``style='iqx'``.
            If `style` is a dict and the ``'name'`` key is set, that name
            will be used to load a json file, followed by loading the other
            items in the style dict. For example, ``style={'name': 'iqx'}``.
            If `style` is not a str and `name` is not a key in the style dict,
            then the default value from the user config file (usually
            ``~/.qiskit/settings.conf``) will be used, for example,
            ``circuit_mpl_style = iqx``.
            If none of these are set, the `default` style will be used.
            The search path for style json files can be specified in the user
            config, for example,
            ``circuit_mpl_style_path = /home/user/styles:/home/user``.
            See: :class:`~qiskit.visualization.qcstyle.DefaultStyle` for more
            information on the contents.
        output (str): select the output method to use for drawing the circuit.
            Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``.
            By default the `text` drawer is used unless the user config file
            (usually ``~/.qiskit/settings.conf``) has an alternative backend set
            as the default. For example, ``circuit_drawer = latex``. If the output
            kwarg is set, that backend will always be used over the default in
            the user config file.
        interactive (bool): when set to 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. Defaults to False.
        reverse_bits (bool): when set to True, reverse the bit order inside
            registers for the output visualization. Defaults to False.
        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.
        vertical_compression (string): ``high``, ``medium`` or ``low``. It
            merges the lines generated by the `text` output so the drawing
            will take less vertical room.  Default is ``medium``. Only used by
            the `text` output, will be silently ignored otherwise.
        idle_wires (bool): include idle wires (wires with no circuit elements)
            in output visualization. Default is True.
        with_layout (bool): include layout information, with labels on the
            physical layout. Default is True.
        fold (int): sets pagination. It can be disabled using -1. In `text`,
            sets the length of the lines. This is 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
            running in jupyter, the default line length is set to 80 characters.
            In `mpl`, it is the number of (visual) layers before folding.
            Default is 25.
        ax (matplotlib.axes.Axes): Only used by the `mpl` backend. An optional
            Axes object to be used for the visualization output. If none is
            specified, a new matplotlib Figure will be created and used.
            Additionally, if specified there will be no returned Figure since
            it is redundant.
        initial_state (bool): optional. Adds ``|0>`` in the beginning of the wire.
            Default is False.
        cregbundle (bool): optional. If set True, bundle classical registers.
            Default is True.

    Returns:
        :class:`TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or
        :class:`str`:

        * `TextDrawing` (output='text')
            A drawing that can be printed as ascii art.
        * `matplotlib.figure.Figure` (output='mpl')
            A matplotlib figure object for the circuit diagram.
        * `PIL.Image` (output='latex')
            An in-memory representation of the image of the circuit diagram.
        * `str` (output='latex_source')
            The LaTeX source code for visualizing the circuit diagram.

    Raises:
        VisualizationError: when an invalid output method is selected
        MissingOptionalLibraryError: when the output methods requires non-installed libraries.

    Example:
        .. jupyter-execute::

            from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
            from qiskit.tools.visualization import circuit_drawer
            q = QuantumRegister(1)
            c = ClassicalRegister(1)
            qc = QuantumCircuit(q, c)
            qc.h(q)
            qc.measure(q, c)
            circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
    """
    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 default_output == "auto":
            if _matplotlib.HAS_MATPLOTLIB:
                default_output = "mpl"
            else:
                default_output = "text"
    if output is None:
        output = default_output

    if output == "text":
        return _text_circuit_drawer(
            circuit,
            filename=filename,
            reverse_bits=reverse_bits,
            plot_barriers=plot_barriers,
            justify=justify,
            vertical_compression=vertical_compression,
            idle_wires=idle_wires,
            with_layout=with_layout,
            fold=fold,
            initial_state=initial_state,
            cregbundle=cregbundle,
        )
    elif output == "latex":
        image = _latex_circuit_drawer(
            circuit,
            filename=filename,
            scale=scale,
            style=style,
            plot_barriers=plot_barriers,
            reverse_bits=reverse_bits,
            justify=justify,
            idle_wires=idle_wires,
            with_layout=with_layout,
            initial_state=initial_state,
            cregbundle=cregbundle,
        )
    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,
            idle_wires=idle_wires,
            with_layout=with_layout,
            initial_state=initial_state,
            cregbundle=cregbundle,
        )
    elif output == "mpl":
        image = _matplotlib_circuit_drawer(
            circuit,
            scale=scale,
            filename=filename,
            style=style,
            plot_barriers=plot_barriers,
            reverse_bits=reverse_bits,
            justify=justify,
            idle_wires=idle_wires,
            with_layout=with_layout,
            fold=fold,
            ax=ax,
            initial_state=initial_state,
            cregbundle=cregbundle,
        )
    else:
        raise VisualizationError(
            "Invalid output type %s selected. The only valid choices "
            "are text, latex, latex_source, and mpl" % output
        )
    if image and interactive:
        image.show()
    return image
Esempio n. 4
0
def transpile(circuits: Union[QuantumCircuit, List[QuantumCircuit]],
              backend: Optional[Union[Backend, BaseBackend]] = None,
              basis_gates: Optional[List[str]] = None,
              coupling_map: Optional[Union[CouplingMap, List[List[int]]]] = None,
              backend_properties: Optional[BackendProperties] = None,
              initial_layout: Optional[Union[Layout, Dict, List]] = None,
              layout_method: Optional[str] = None,
              routing_method: Optional[str] = None,
              translation_method: Optional[str] = None,
              scheduling_method: Optional[str] = None,
              instruction_durations: Optional[InstructionDurationsType] = None,
              dt: Optional[float] = None,
              seed_transpiler: Optional[int] = None,
              optimization_level: Optional[int] = None,
              pass_manager: Optional[PassManager] = None,
              callback: Optional[Callable[[BasePass, DAGCircuit, float,
                                           PropertySet, int], Any]] = None,
              output_name: Optional[Union[str, List[str]]] = None) -> Union[QuantumCircuit,
                                                                            List[QuantumCircuit]]:
    """Transpile one or more circuits, according to some desired transpilation targets.

    All arguments may be given as either a singleton or list. In case of a list,
    the length must be equal to the number of circuits being transpiled.

    Transpilation is done in parallel using multiprocessing.

    Args:
        circuits: Circuit(s) to transpile
        backend: If set, transpiler options are automatically grabbed from
            ``backend.configuration()`` and ``backend.properties()``.
            If any other option is explicitly set (e.g., ``coupling_map``), it
            will override the backend's.

            .. note::

                The backend arg is purely for convenience. The resulting
                circuit may be run on any backend as long as it is compatible.
        basis_gates: List of basis gate names to unroll to
            (e.g: ``['u1', 'u2', 'u3', 'cx']``). If ``None``, do not unroll.
        coupling_map: Coupling map (perhaps custom) to target in mapping.
            Multiple formats are supported:

            #. ``CouplingMap`` instance
            #. List, must be given as an adjacency matrix, where each entry
               specifies all two-qubit interactions supported by backend,
               e.g: ``[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]``

        backend_properties: properties returned by a backend, including information on gate
            errors, readout errors, qubit coherence times, etc. Find a backend
            that provides this information with: ``backend.properties()``
        initial_layout: Initial position of virtual qubits on physical qubits.
            If this layout makes the circuit compatible with the coupling_map
            constraints, it will be used. The final layout is not guaranteed to be the same,
            as the transpiler may permute qubits through swaps or other means.
            Multiple formats are supported:

            #. ``Layout`` instance
            #. Dict
               * virtual to physical::

                    {qr[0]: 0,
                     qr[1]: 3,
                     qr[2]: 5}

               * physical to virtual::

                    {0: qr[0],
                     3: qr[1],
                     5: qr[2]}

            #. List

               * virtual to physical::

                    [0, 3, 5]  # virtual qubits are ordered (in addition to named)

               * physical to virtual::

                    [qr[0], None, None, qr[1], None, qr[2]]

        layout_method: Name of layout selection pass ('trivial', 'dense', 'noise_adaptive', 'sabre')
        routing_method: Name of routing pass ('basic', 'lookahead', 'stochastic', 'sabre', 'none')
        translation_method: Name of translation pass ('unroller', 'translator', 'synthesis')
        scheduling_method: Name of scheduling pass.
            * ``'as_soon_as_possible'``: Schedule instructions greedily, as early as possible
            on a qubit resource. alias: ``'asap'``)
            * ``'as_late_as_possible'``: Schedule instructions late, i.e. keeping qubits
            in the ground state when possible. (alias: ``'alap'``)
            If ``None``, no scheduling will be done.
        instruction_durations: Durations of instructions.
            The gate lengths defined in ``backend.properties`` are used as default.
            They are overwritten if this ``instruction_durations`` is specified.
            The format of ``instruction_durations`` must be as follows.
            The `instruction_durations` must be given as a list of tuples
            [(instruction_name, qubits, duration, unit), ...].
            | [('cx', [0, 1], 12.3, 'ns'), ('u3', [0], 4.56, 'ns')]
            | [('cx', [0, 1], 1000), ('u3', [0], 300)]
            If unit is omitted, the default is 'dt', which is a sample time depending on backend.
            If the time unit is 'dt', the duration must be an integer.
        dt: Backend sample time (resolution) in seconds.
            If ``None`` (default), ``backend.configuration().dt`` is used.
        seed_transpiler: Sets random seed for the stochastic parts of the transpiler
        optimization_level: How much optimization to perform on the circuits.
            Higher levels generate more optimized circuits,
            at the expense of longer transpilation time.
            * 0: no optimization
            * 1: light optimization
            * 2: heavy optimization
            * 3: even heavier optimization
            If ``None``, level 1 will be chosen as default.
        pass_manager: The pass manager to use for a custom pipeline of transpiler passes.
            If this arg is present, all other args will be ignored and the
            pass manager will be used directly (Qiskit will not attempt to
            auto-select a pass manager based on transpile options).
        callback: A callback function that will be called after each
            pass execution. The function will be called with 5 keyword
            arguments,
            | ``pass_``: the pass being run.
            | ``dag``: the dag output of the pass.
            | ``time``: the time to execute the pass.
            | ``property_set``: the property set.
            | ``count``: the index for the pass execution.
            The exact arguments passed expose the internals of the pass manager,
            and are subject to change as the pass manager internals change. If
            you intend to reuse a callback function over multiple releases, be
            sure to check that the arguments being passed are the same.
            To use the callback feature, define a function that will
            take in kwargs dict and access the variables. For example::

                def callback_func(**kwargs):
                    pass_ = kwargs['pass_']
                    dag = kwargs['dag']
                    time = kwargs['time']
                    property_set = kwargs['property_set']
                    count = kwargs['count']
                    ...
                transpile(circ, callback=callback_func)

        output_name: A list with strings to identify the output circuits. The length of
            the list should be exactly the length of the ``circuits`` parameter.

    Returns:
        The transpiled circuit(s).

    Raises:
        TranspilerError: in case of bad inputs to transpiler (like conflicting parameters)
            or errors in passes
    """
    arg_circuits_list = isinstance(circuits, list)
    circuits = circuits if arg_circuits_list else [circuits]

    # transpiling schedules is not supported yet.
    start_time = time()
    if all(isinstance(c, Schedule) for c in circuits):
        warnings.warn("Transpiling schedules is not supported yet.", UserWarning)
        end_time = time()
        _log_transpile_time(start_time, end_time)
        if arg_circuits_list:
            return circuits
        else:
            return circuits[0]

    if pass_manager is not None:
        _check_conflicting_argument(optimization_level=optimization_level, basis_gates=basis_gates,
                                    coupling_map=coupling_map, seed_transpiler=seed_transpiler,
                                    backend_properties=backend_properties,
                                    initial_layout=initial_layout, layout_method=layout_method,
                                    routing_method=routing_method,
                                    translation_method=translation_method,
                                    backend=backend)

        warnings.warn("The parameter pass_manager in transpile is being deprecated. "
                      "The preferred way to tranpile a circuit using a custom pass manager is"
                      " pass_manager.run(circuit)", DeprecationWarning, stacklevel=2)
        return pass_manager.run(circuits, output_name=output_name, callback=callback)

    if optimization_level is None:
        # Take optimization level from the configuration or 1 as default.
        config = user_config.get_config()
        optimization_level = config.get('transpile_optimization_level', 1)

    if scheduling_method is not None and backend is None and not instruction_durations:
        warnings.warn("When scheduling circuits without backend,"
                      " 'instruction_durations' should be usually provided.",
                      UserWarning)

    # Get transpile_args to configure the circuit transpilation job(s)
    transpile_args = _parse_transpile_args(circuits, backend, basis_gates, coupling_map,
                                           backend_properties, initial_layout,
                                           layout_method, routing_method, translation_method,
                                           scheduling_method, instruction_durations, dt,
                                           seed_transpiler, optimization_level,
                                           callback, output_name)

    _check_circuits_coupling_map(circuits, transpile_args, backend)

    # Transpile circuits in parallel
    circuits = parallel_map(_transpile_circuit, list(zip(circuits, transpile_args)))

    end_time = time()
    _log_transpile_time(start_time, end_time)

    if arg_circuits_list:
        return circuits
    else:
        return circuits[0]
def state_drawer(state, output=None, **drawer_args):
    """Returns a visualization of the state.

    **repr**: ASCII TextMatrix of the state's ``_repr_``.

    **text**: ASCII TextMatrix that can be printed in the console.

    **latex**: An IPython Latex object for displaying in Jupyter Notebooks.

    **latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX.

    **qsphere**: Matplotlib figure, rendering of statevector using `plot_state_qsphere()`.

    **hinton**: Matplotlib figure, rendering of statevector using `plot_state_hinton()`.

    **bloch**: Matplotlib figure, rendering of statevector using `plot_bloch_multivector()`.

    **city**: Matplotlib figure, rendering of statevector using `plot_state_city()`.

    **paulivec**: Matplotlib figure, rendering of statevector using `plot_state_paulivec()`.

    Args:
        output (str): Select the output method to use for drawing the
            circuit. Valid choices are ``text``, ``latex``, ``latex_source``,
            ``qsphere``, ``hinton``, ``bloch``, ``city`` or ``paulivec``.
            Default is `'text`'.
        drawer_args: Arguments to be passed to the relevant drawer. For
            'latex' and 'latex_source' see ``array_to_latex``

    Returns:
        :class:`matplotlib.figure` or :class:`str` or
        :class:`TextMatrix` or :class:`IPython.display.Latex`:
        Drawing of the state.

    Raises:
        MissingOptionalLibraryError: when `output` is `latex` and IPython is not installed.
        ValueError: when `output` is not a valid selection.
    """
    config = user_config.get_config()
    # Get default 'output' from config file else use 'repr'
    default_output = "repr"
    if output is None:
        if config:
            default_output = config.get("state_drawer", "repr")
        output = default_output
    output = output.lower()

    # Choose drawing backend:
    drawers = {
        "text": TextMatrix,
        "latex_source": state_to_latex,
        "qsphere": plot_state_qsphere,
        "hinton": plot_state_hinton,
        "bloch": plot_bloch_multivector,
        "city": plot_state_city,
        "paulivec": plot_state_paulivec,
    }
    if output == "latex":
        try:
            from IPython.display import Latex
        except ImportError as err:
            raise MissingOptionalLibraryError(
                libname="IPython",
                name="state_drawer",
                pip_install="\"pip install ipython\", or set output='latex_source' "
                "instead for an ASCII string.",
            ) from err
        else:
            draw_func = drawers["latex_source"]
            return Latex(f"$${draw_func(state, **drawer_args)}$$")

    if output == "repr":
        return state.__repr__()

    try:
        draw_func = drawers[output]
        return draw_func(state, **drawer_args)
    except KeyError as err:
        raise ValueError(
            """'{}' is not a valid option for drawing {} objects. Please choose from:
            'text', 'latex', 'latex_source', 'qsphere', 'hinton',
            'bloch', 'city' or 'paulivec'.""".format(
                output, type(state).__name__
            )
        ) from err
Esempio n. 6
0
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset

# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)

# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer

_config = _user_config.get_config()

# Try to import the Aer provider if installed.
try:
    from qiskit.providers.aer import Aer
except ImportError:
    suppress_warnings = os.environ.get('QISKIT_SUPPRESS_PACKAGING_WARNINGS',
                                       '')
    if suppress_warnings.upper() != 'Y':
        if not _config.get('suppress_packaging_warnings'
                           ) or suppress_warnings.upper() == 'N':
            warnings.warn(
                'Could not import the Aer provider from the qiskit-aer '
                'package. Install qiskit-aer or check your installation.',
                RuntimeWarning)
# Try to import the IBMQ provider if installed.
Esempio n. 7
0
def load_style(style):
    """Utility function to load style from json files and call set_style."""
    current_style = DefaultStyle().style
    style_name = "default"
    def_font_ratio = current_style["fs"] / current_style["sfs"]

    config = user_config.get_config()
    if style is None:
        if config:
            style = config.get("circuit_mpl_style", "default")
        else:
            style = "default"

    if style is False:
        style_name = "bw"
    elif isinstance(style, dict) and "name" in style:
        style_name = style["name"]
    elif isinstance(style, str):
        style_name = style
    elif not isinstance(style, (str, dict)):
        warn(
            f"style parameter '{style}' must be a str or a dictionary. Will use default style.",
            UserWarning,
            2,
        )
    if style_name.endswith(".json"):
        style_name = style_name[:-5]

    # Search for file in 'styles' dir, then config_path, and finally 'cwd'
    style_path = []
    if style_name != "default":
        style_name = style_name + ".json"
        spath = os.path.dirname(os.path.abspath(__file__))
        style_path.append(os.path.join(spath, "styles", style_name))
        if config:
            config_path = config.get("circuit_mpl_style_path", "")
            if config_path:
                for path in config_path:
                    style_path.append(
                        os.path.normpath(os.path.join(path, style_name)))
        style_path.append(os.path.normpath(os.path.join("", style_name)))

        for path in style_path:
            exp_user = os.path.expanduser(path)
            if os.path.isfile(exp_user):
                try:
                    with open(exp_user) as infile:
                        json_style = json.load(infile)
                    set_style(current_style, json_style)
                    break
                except json.JSONDecodeError as err:
                    warn(
                        f"Could not decode JSON in file '{path}': {str(err)}. "
                        "Will use default style.",
                        UserWarning,
                        2,
                    )
                    break
                except (OSError, FileNotFoundError):
                    warn(
                        f"Error loading JSON file '{path}'. Will use default style.",
                        UserWarning,
                        2,
                    )
                    break
        else:
            warn(
                f"Style JSON file '{style_name}' not found in any of these locations: "
                f"{', '.join(style_path)}. "
                "Will use default style.",
                UserWarning,
                2,
            )

    if isinstance(style, dict):
        set_style(current_style, style)

    return current_style, def_font_ratio
###############################################################################
"""
Routines for running Python functions in parallel using process pools
from the multiprocessing library.
"""

import os
from concurrent.futures import ProcessPoolExecutor
import sys

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

CONFIG = user_config.get_config()

if os.getenv("QISKIT_PARALLEL", None) is not None:
    PARALLEL_DEFAULT = os.getenv("QISKIT_PARALLEL", None).lower() == "true"
else:
    # Default False on Windows
    if sys.platform == "win32":
        PARALLEL_DEFAULT = False
    # On python 3.9 default false to avoid deadlock issues
    elif sys.version_info[0] == 3 and sys.version_info[1] == 9:
        PARALLEL_DEFAULT = False
    # On macOS default false on Python >=3.8
    elif sys.platform == "darwin":
        if sys.version_info[0] == 3 and sys.version_info[1] >= 8:
            PARALLEL_DEFAULT = False
        else:
Esempio n. 9
0
    def __init__(self, qregs, cregs, ops,
                 scale=1.0, style=None, plot_barriers=True,
                 reverse_bits=False, layout=None, fold=25, ax=None,
                 initial_state=False, cregbundle=True):

        if not HAS_MATPLOTLIB:
            raise ImportError('The class MatplotlibDrawer needs matplotlib. '
                              'To install, run "pip install matplotlib".')

        self._ast = None
        self._scale = DEFAULT_SCALE * scale
        self._creg = []
        self._qreg = []
        self._registers(cregs, qregs)
        self._ops = ops

        self._qreg_dict = collections.OrderedDict()
        self._creg_dict = collections.OrderedDict()
        self._cond = {
            'n_lines': 0,
            'xmax': 0,
            'ymax': 0,
        }
        config = user_config.get_config()
        if config and (style is None):
            config_style = config.get('circuit_mpl_style', 'default')
            if config_style == 'default':
                self._style = DefaultStyle()
            elif config_style == 'bw':
                self._style = BWStyle()
        elif style is False:
            self._style = BWStyle()
        else:
            self._style = DefaultStyle()

        self.plot_barriers = plot_barriers
        self.reverse_bits = reverse_bits
        self.layout = layout
        self.initial_state = initial_state
        if style and 'cregbundle' in style.keys():
            self.cregbundle = style['cregbundle']
            del style['cregbundle']
            warn("The style dictionary key 'cregbundle' has been deprecated and will be removed"
                 " in a future release. cregbundle is now a parameter to draw()."
                 " Example: circuit.draw(output='mpl', cregbundle=False)", DeprecationWarning, 2)
        else:
            self.cregbundle = cregbundle

        if style:
            if isinstance(style, dict):
                self._style.set_style(style)
            elif isinstance(style, str):
                with open(style, 'r') as infile:
                    dic = json.load(infile)
                self._style.set_style(dic)

        if ax is None:
            self.return_fig = True
            self.figure = plt.figure()
            self.figure.patch.set_facecolor(color=self._style.bg)
            self.ax = self.figure.add_subplot(111)
        else:
            self.return_fig = False
            self.ax = ax
            self.figure = ax.get_figure()

        self.x_offset = 0
        self._reg_long_text = 0

        # default is to use character table for text width,
        # but get_renderer will work with some mpl backends
        """fig = plt.figure()
        if hasattr(fig.canvas, 'get_renderer'):
            self.renderer = fig.canvas.get_renderer()
        else:
            self.renderer = None"""
        self.renderer = None

        self.fold = fold
        if self.fold < 2:
            self.fold = -1

        self.ax.axis('off')
        self.ax.set_aspect('equal')
        self.ax.tick_params(labelbottom=False, labeltop=False,
                            labelleft=False, labelright=False)

        # these char arrays are for finding text_width when not
        # using get_renderer method for the matplotlib backend
        self._latex_chars = ('$', '{', '}', '_', '\\left', '\\right',
                             '\\dagger', '\\rangle')
        self._latex_chars1 = ('\\mapsto', '\\pi', '\\;')
        self._char_list = {' ': (0.0958, 0.0583), '!': (0.1208, 0.0729), '"': (0.1396, 0.0875),
                           '#': (0.2521, 0.1562), '$': (0.1917, 0.1167), '%': (0.2854, 0.1771),
                           '&': (0.2333, 0.1458), "'": (0.0833, 0.0521), '(': (0.1167, 0.0729),
                           ')': (0.1167, 0.0729), '*': (0.15, 0.0938), '+': (0.25, 0.1562),
                           ',': (0.0958, 0.0583), '-': (0.1083, 0.0667), '.': (0.0958, 0.0604),
                           '/': (0.1021, 0.0625), '0': (0.1875, 0.1167), '1': (0.1896, 0.1167),
                           '2': (0.1917, 0.1188), '3': (0.1917, 0.1167), '4': (0.1917, 0.1188),
                           '5': (0.1917, 0.1167), '6': (0.1896, 0.1167), '7': (0.1917, 0.1188),
                           '8': (0.1896, 0.1188), '9': (0.1917, 0.1188), ':': (0.1021, 0.0604),
                           ';': (0.1021, 0.0604), '<': (0.25, 0.1542), '=': (0.25, 0.1562),
                           '>': (0.25, 0.1542), '?': (0.1583, 0.0979), '@': (0.2979, 0.1854),
                           'A': (0.2062, 0.1271), 'B': (0.2042, 0.1271), 'C': (0.2083, 0.1292),
                           'D': (0.2312, 0.1417), 'E': (0.1875, 0.1167), 'F': (0.1708, 0.1062),
                           'G': (0.2312, 0.1438), 'H': (0.225, 0.1396), 'I': (0.0875, 0.0542),
                           'J': (0.0875, 0.0542), 'K': (0.1958, 0.1208), 'L': (0.1667, 0.1042),
                           'M': (0.2583, 0.1604), 'N': (0.225, 0.1396), 'O': (0.2354, 0.1458),
                           'P': (0.1812, 0.1125), 'Q': (0.2354, 0.1458), 'R': (0.2083, 0.1292),
                           'S': (0.1896, 0.1188), 'T': (0.1854, 0.1125), 'U': (0.2208, 0.1354),
                           'V': (0.2062, 0.1271), 'W': (0.2958, 0.1833), 'X': (0.2062, 0.1271),
                           'Y': (0.1833, 0.1125), 'Z': (0.2042, 0.1271), '[': (0.1167, 0.075),
                           '\\': (0.1021, 0.0625), ']': (0.1167, 0.0729), '^': (0.2521, 0.1562),
                           '_': (0.1521, 0.0938), '`': (0.15, 0.0938), 'a': (0.1854, 0.1146),
                           'b': (0.1917, 0.1167), 'c': (0.1646, 0.1021), 'd': (0.1896, 0.1188),
                           'e': (0.1854, 0.1146), 'f': (0.1042, 0.0667), 'g': (0.1896, 0.1188),
                           'h': (0.1896, 0.1188), 'i': (0.0854, 0.0521), 'j': (0.0854, 0.0521),
                           'k': (0.1729, 0.1083), 'l': (0.0854, 0.0521), 'm': (0.2917, 0.1812),
                           'n': (0.1896, 0.1188), 'o': (0.1833, 0.1125), 'p': (0.1917, 0.1167),
                           'q': (0.1896, 0.1188), 'r': (0.125, 0.0771), 's': (0.1562, 0.0958),
                           't': (0.1167, 0.0729), 'u': (0.1896, 0.1188), 'v': (0.1771, 0.1104),
                           'w': (0.2458, 0.1521), 'x': (0.1771, 0.1104), 'y': (0.1771, 0.1104),
                           'z': (0.1562, 0.0979), '{': (0.1917, 0.1188), '|': (0.1, 0.0604),
                           '}': (0.1896, 0.1188)}
Esempio n. 10
0
def transpile(circuits,
              backend=None,
              basis_gates=None,
              coupling_map=None,
              backend_properties=None,
              initial_layout=None,
              seed_transpiler=None,
              optimization_level=None,
              pass_manager=None,
              callback=None,
              output_name=None):
    """Transpile one or more circuits, according to some desired transpilation targets.

    All arguments may be given as either singleton or list. In case of list,
    the length must be equal to the number of circuits being transpiled.

    Transpilation is done in parallel using multiprocessing.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]):
            Circuit(s) to transpile

        backend (BaseBackend):
            If set, transpiler options are automatically grabbed from
            backend.configuration() and backend.properties().
            If any other option is explicitly set (e.g. coupling_map), it
            will override the backend's.

            Note: the backend arg is purely for convenience. The resulting
            circuit may be run on any backend as long as it is compatible.

        basis_gates (list[str]):
            List of basis gate names to unroll to.
            e.g::

                ['u1', 'u2', 'u3', 'cx']

            If None, do not unroll.

        coupling_map (CouplingMap or list):
            Coupling map (perhaps custom) to target in mapping.
            Multiple formats are supported:

            1. CouplingMap instance
            2. list
                Must be given as an adjacency matrix, where each entry
                specifies all two-qubit interactions supported by backend
                e.g::

                    [[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]

        backend_properties (BackendProperties):
            properties returned by a backend, including information on gate
            errors, readout errors, qubit coherence times, etc. For a backend
            that provides this information, it can be obtained with:
            ``backend.properties()``

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits.
            If this layout makes the circuit compatible with the coupling_map
            constraints, it will be used.
            The final layout is not guaranteed to be the same, as the transpiler
            may permute qubits through swaps or other means.

            Multiple formats are supported:

            1. Layout instance
            2. dict
                * virtual to physical::

                    {qr[0]: 0,
                     qr[1]: 3,
                     qr[2]: 5}

                * physical to virtual::

                    {0: qr[0],
                     3: qr[1],
                     5: qr[2]}

            3. list
                * virtual to physical::

                    [0, 3, 5]  # virtual qubits are ordered (in addition to named)

                * physical to virtual::

                    [qr[0], None, None, qr[1], None, qr[2]]

        seed_transpiler (int):
            sets random seed for the stochastic parts of the transpiler

        optimization_level (int):
            How much optimization to perform on the circuits.
            Higher levels generate more optimized circuits,
            at the expense of longer transpilation time.

                * 0: no optimization
                * 1: light optimization
                * 2: heavy optimization
                * 3: even heavier optimization

            If None, level 1 will be chosen as default.

        pass_manager (PassManager):
            The pass manager to use for a custom pipeline of transpiler passes.
            If this arg is present, all other args will be ignored and the
            pass manager will be used directly (Qiskit will not attempt to
            auto-select a pass manager based on transpile options).

        callback (func):
            A callback function that will be called after each
            pass execution. The function will be called with 5 keyword
            arguments:
                pass_ (Pass): the pass being run
                dag (DAGCircuit): the dag output of the pass
                time (float): the time to execute the pass
                property_set (PropertySet): the property set
                count (int): the index for the pass execution

            The exact arguments pass expose the internals of the pass manager
            and are subject to change as the pass manager internals change. If
            you intend to reuse a callback function over multiple releases be
            sure to check that the arguments being passed are the same.

            To use the callback feature you define a function that will
            take in kwargs dict and access the variables. For example::

                def callback_func(**kwargs):
                    pass_ = kwargs['pass_']
                    dag = kwargs['dag']
                    time = kwargs['time']
                    property_set = kwargs['property_set']
                    count = kwargs['count']
                    ...

                transpile(circ, callback=callback_func)

        output_name (str or list[str]) :
            A list with strings to identify the output circuits. The length of
            `list[str]` should be exactly the length of `circuits` parameter.

    Returns:
        QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).

    Raises:
        TranspilerError: in case of bad inputs to transpiler or errors in passes
    """
    # transpiling schedules is not supported yet.
    if isinstance(circuits, Schedule) or \
            (isinstance(circuits, list) and all(isinstance(c, Schedule) for c in circuits)):
        return circuits

    if optimization_level is None:
        config = user_config.get_config()
        optimization_level = config.get('transpile_optimization_level', None)

    # Get TranspileConfig(s) to configure the circuit transpilation job(s)
    circuits = circuits if isinstance(circuits, list) else [circuits]
    transpile_configs = _parse_transpile_args(circuits, backend, basis_gates,
                                              coupling_map, backend_properties,
                                              initial_layout, seed_transpiler,
                                              optimization_level, pass_manager,
                                              callback, output_name)
    # Check circuit width against number of qubits in coupling_map(s)
    coupling_maps_list = list(config.coupling_map
                              for config in transpile_configs)
    for circuit, parsed_coupling_map in zip(circuits, coupling_maps_list):
        # If coupling_map is not None or n_qubits == 1
        n_qubits = len(circuit.qubits)
        max_qubits = None
        if isinstance(parsed_coupling_map, CouplingMap):
            max_qubits = parsed_coupling_map.size()

        # If coupling_map is None, the limit might be in the backend (like in 1Q devices)
        elif backend is not None and not backend.configuration().simulator:
            max_qubits = backend.configuration().n_qubits

        if max_qubits is not None and (n_qubits > max_qubits):
            raise TranspilerError(
                'Number of qubits ({}) '.format(n_qubits) +
                'in {} '.format(circuit.name) +
                'is greater than maximum ({}) '.format(max_qubits) +
                'in the coupling_map')
    # Transpile circuits in parallel
    circuits = parallel_map(_transpile_circuit,
                            list(zip(circuits, transpile_configs)))

    if len(circuits) == 1:
        return circuits[0]
    return circuits
Esempio n. 11
0
def transpile(
    circuits: Union[QuantumCircuit, List[QuantumCircuit]],
    backend: Optional[Union[Backend, BaseBackend]] = None,
    basis_gates: Optional[List[str]] = None,
    inst_map: Optional[List[InstructionScheduleMap]] = None,
    coupling_map: Optional[Union[CouplingMap, List[List[int]]]] = None,
    backend_properties: Optional[BackendProperties] = None,
    initial_layout: Optional[Union[Layout, Dict, List]] = None,
    layout_method: Optional[str] = None,
    routing_method: Optional[str] = None,
    translation_method: Optional[str] = None,
    scheduling_method: Optional[str] = None,
    instruction_durations: Optional[InstructionDurationsType] = None,
    dt: Optional[float] = None,
    approximation_degree: Optional[float] = None,
    timing_constraints: Optional[Dict[str, int]] = None,
    seed_transpiler: Optional[int] = None,
    optimization_level: Optional[int] = None,
    callback: Optional[Callable[
        [BasePass, DAGCircuit, float, PropertySet, int], Any]] = None,
    output_name: Optional[Union[str, List[str]]] = None,
    unitary_synthesis_method: str = "default",
    unitary_synthesis_plugin_config: dict = None,
    target: Target = None,
) -> Union[QuantumCircuit, List[QuantumCircuit]]:
    """Transpile one or more circuits, according to some desired transpilation targets.

    All arguments may be given as either a singleton or list. In case of a list,
    the length must be equal to the number of circuits being transpiled.

    Transpilation is done in parallel using multiprocessing.

    Args:
        circuits: Circuit(s) to transpile
        backend: If set, transpiler options are automatically grabbed from
            ``backend.configuration()`` and ``backend.properties()``.
            If any other option is explicitly set (e.g., ``coupling_map``), it
            will override the backend's.

            .. note::

                The backend arg is purely for convenience. The resulting
                circuit may be run on any backend as long as it is compatible.
        basis_gates: List of basis gate names to unroll to
            (e.g: ``['u1', 'u2', 'u3', 'cx']``). If ``None``, do not unroll.
        inst_map: Mapping of unrolled gates to pulse schedules. If this is not provided,
            transpiler tries to get from the backend. If any user defined calibration
            is found in the map and this is used in a circuit, transpiler attaches
            the custom gate definition to the circuit. This enables one to flexibly
            override the low-level instruction implementation. This feature is available
            iff the backend supports the pulse gate experiment.
        coupling_map: Coupling map (perhaps custom) to target in mapping.
            Multiple formats are supported:

            #. ``CouplingMap`` instance
            #. List, must be given as an adjacency matrix, where each entry
               specifies all two-qubit interactions supported by backend,
               e.g: ``[[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]``

        backend_properties: properties returned by a backend, including information on gate
            errors, readout errors, qubit coherence times, etc. Find a backend
            that provides this information with: ``backend.properties()``
        initial_layout: Initial position of virtual qubits on physical qubits.
            If this layout makes the circuit compatible with the coupling_map
            constraints, it will be used. The final layout is not guaranteed to be the same,
            as the transpiler may permute qubits through swaps or other means.
            Multiple formats are supported:

            #. ``Layout`` instance
            #. Dict
               * virtual to physical::

                    {qr[0]: 0,
                     qr[1]: 3,
                     qr[2]: 5}

               * physical to virtual::

                    {0: qr[0],
                     3: qr[1],
                     5: qr[2]}

            #. List

               * virtual to physical::

                    [0, 3, 5]  # virtual qubits are ordered (in addition to named)

               * physical to virtual::

                    [qr[0], None, None, qr[1], None, qr[2]]

        layout_method: Name of layout selection pass ('trivial', 'dense', 'noise_adaptive', 'sabre')
        routing_method: Name of routing pass ('basic', 'lookahead', 'stochastic', 'sabre', 'none')
        translation_method: Name of translation pass ('unroller', 'translator', 'synthesis')
        scheduling_method: Name of scheduling pass.
            * ``'as_soon_as_possible'``: Schedule instructions greedily, as early as possible
            on a qubit resource. (alias: ``'asap'``)
            * ``'as_late_as_possible'``: Schedule instructions late, i.e. keeping qubits
            in the ground state when possible. (alias: ``'alap'``)
            If ``None``, no scheduling will be done.
        instruction_durations: Durations of instructions.
            Applicable only if scheduling_method is specified.
            The gate lengths defined in ``backend.properties`` are used as default.
            They are overwritten if this ``instruction_durations`` is specified.
            The format of ``instruction_durations`` must be as follows.
            The `instruction_durations` must be given as a list of tuples
            [(instruction_name, qubits, duration, unit), ...].
            | [('cx', [0, 1], 12.3, 'ns'), ('u3', [0], 4.56, 'ns')]
            | [('cx', [0, 1], 1000), ('u3', [0], 300)]
            If unit is omitted, the default is 'dt', which is a sample time depending on backend.
            If the time unit is 'dt', the duration must be an integer.
        dt: Backend sample time (resolution) in seconds.
            If ``None`` (default), ``backend.configuration().dt`` is used.
        approximation_degree (float): heuristic dial used for circuit approximation
            (1.0=no approximation, 0.0=maximal approximation)
        timing_constraints: An optional control hardware restriction on instruction time resolution.
            A quantum computer backend may report a set of restrictions, namely:

            - granularity: An integer value representing minimum pulse gate
              resolution in units of ``dt``. A user-defined pulse gate should have
              duration of a multiple of this granularity value.
            - min_length: An integer value representing minimum pulse gate
              length in units of ``dt``. A user-defined pulse gate should be longer
              than this length.
            - pulse_alignment: An integer value representing a time resolution of gate
              instruction starting time. Gate instruction should start at time which
              is a multiple of the alignment value.
            - acquire_alignment: An integer value representing a time resolution of measure
              instruction starting time. Measure instruction should start at time which
              is a multiple of the alignment value.

            This information will be provided by the backend configuration.
            If the backend doesn't have any restriction on the instruction time allocation,
            then ``timing_constraints`` is None and no adjustment will be performed.
        seed_transpiler: Sets random seed for the stochastic parts of the transpiler
        optimization_level: How much optimization to perform on the circuits.
            Higher levels generate more optimized circuits,
            at the expense of longer transpilation time.
            * 0: no optimization
            * 1: light optimization
            * 2: heavy optimization
            * 3: even heavier optimization
            If ``None``, level 1 will be chosen as default.
        callback: A callback function that will be called after each
            pass execution. The function will be called with 5 keyword
            arguments,
            | ``pass_``: the pass being run.
            | ``dag``: the dag output of the pass.
            | ``time``: the time to execute the pass.
            | ``property_set``: the property set.
            | ``count``: the index for the pass execution.
            The exact arguments passed expose the internals of the pass manager,
            and are subject to change as the pass manager internals change. If
            you intend to reuse a callback function over multiple releases, be
            sure to check that the arguments being passed are the same.
            To use the callback feature, define a function that will
            take in kwargs dict and access the variables. For example::

                def callback_func(**kwargs):
                    pass_ = kwargs['pass_']
                    dag = kwargs['dag']
                    time = kwargs['time']
                    property_set = kwargs['property_set']
                    count = kwargs['count']
                    ...
                transpile(circ, callback=callback_func)

        output_name: A list with strings to identify the output circuits. The length of
            the list should be exactly the length of the ``circuits`` parameter.
        unitary_synthesis_method (str): The name of the unitary synthesis
            method to use. By default 'default' is used, which is the only
            method included with qiskit. If you have installed any unitary
            synthesis plugins you can use the name exported by the plugin.
        unitary_synthesis_plugin_config: An optional configuration dictionary
            that will be passed directly to the unitary synthesis plugin. By
            default this setting will have no effect as the default unitary
            synthesis method does not take custom configuration. This should
            only be necessary when a unitary synthesis plugin is specified with
            the ``unitary_synthesis`` argument. As this is custom for each
            unitary synthesis plugin refer to the plugin documentation for how
            to use this option.
        target: A backend transpiler target. Normally this is specified as part of
            the ``backend`` argument, but if you have manually constructed a
            :class:`~qiskit.transpiler.Target` object you can specify it manually here.
            This will override the target from ``backend``.
    Returns:
        The transpiled circuit(s).

    Raises:
        TranspilerError: in case of bad inputs to transpiler (like conflicting parameters)
            or errors in passes
    """
    arg_circuits_list = isinstance(circuits, list)
    circuits = circuits if arg_circuits_list else [circuits]

    if not circuits:
        return []

    # transpiling schedules is not supported yet.
    start_time = time()
    if all(isinstance(c, Schedule) for c in circuits):
        warnings.warn("Transpiling schedules is not supported yet.",
                      UserWarning)
        end_time = time()
        _log_transpile_time(start_time, end_time)
        if arg_circuits_list:
            return circuits
        else:
            return circuits[0]

    if optimization_level is None:
        # Take optimization level from the configuration or 1 as default.
        config = user_config.get_config()
        optimization_level = config.get("transpile_optimization_level", 1)

    if (scheduling_method is not None and backend is None and target is None
            and not instruction_durations):
        warnings.warn(
            "When scheduling circuits without backend,"
            " 'instruction_durations' should be usually provided.",
            UserWarning,
        )

    # Get transpile_args to configure the circuit transpilation job(s)
    transpile_args = _parse_transpile_args(
        circuits,
        backend,
        basis_gates,
        inst_map,
        coupling_map,
        backend_properties,
        initial_layout,
        layout_method,
        routing_method,
        translation_method,
        scheduling_method,
        instruction_durations,
        dt,
        approximation_degree,
        seed_transpiler,
        optimization_level,
        callback,
        output_name,
        timing_constraints,
        unitary_synthesis_method,
        unitary_synthesis_plugin_config,
        target,
    )

    _check_circuits_coupling_map(circuits, transpile_args, backend)

    # Transpile circuits in parallel
    circuits = parallel_map(_transpile_circuit,
                            list(zip(circuits, transpile_args)))

    end_time = time()
    _log_transpile_time(start_time, end_time)

    if arg_circuits_list:
        return circuits
    else:
        return circuits[0]
Esempio n. 12
0
    def _load_style(self, style):
        current_style = DefaultStyle().style
        style_name = 'default'
        def_font_ratio = current_style['fs'] / current_style['sfs']

        config = user_config.get_config()
        if style is not None:
            if style is False:
                style_name = 'bw'
            elif isinstance(style, dict) and 'name' in style:
                style_name = style['name']
            elif isinstance(style, str):
                style_name = style
            elif config:
                style_name = config.get('circuit_mpl_style', 'default')
            elif not isinstance(style, (str, dict)):
                warn("style parameter '{}' must be a str or a dictionary."
                     " Will use default style.".format(style), UserWarning, 2)
        if style_name.endswith('.json'):
            style_name = style_name[:-5]

        # Search for file in 'styles' dir, then config_path, and finally 'cwd'
        style_path = []
        if style_name != 'default':
            style_name = style_name + '.json'
            spath = os.path.dirname(os.path.abspath(__file__))
            style_path.append(os.path.join(spath, 'styles', style_name))
            if config:
                config_path = config.get('circuit_mpl_style_path', '')
                if config_path:
                    for path in config_path:
                        style_path.append(os.path.normpath(os.path.join(path, style_name)))
            style_path.append(os.path.normpath(os.path.join('', style_name)))

            for path in style_path:
                exp_user = os.path.expanduser(path)
                if os.path.isfile(exp_user):
                    try:
                        with open(exp_user) as infile:
                            json_style = json.load(infile)
                        set_style(current_style, json_style)
                        break
                    except json.JSONDecodeError as e:
                        warn("Could not decode JSON in file '{}': {}. ".format(
                            path, str(e)) + "Will use default style.", UserWarning, 2)
                        break
                    except (OSError, FileNotFoundError):
                        warn("Error loading JSON file '{}'. Will use default style.".format(
                            path), UserWarning, 2)
                        break
            else:
                warn("Style JSON file '{}' not found in any of these locations: {}. Will use"
                     " default style.".format(style_name, ', '.join(style_path)), UserWarning, 2)

        if isinstance(style, dict):
            set_style(current_style, style)

        # If font/subfont ratio changes from default, have to scale width calculations for
        # subfont. Font change is auto scaled in the self._figure.set_size_inches call in draw()
        self._subfont_factor = current_style['sfs'] * def_font_ratio / current_style['fs']

        return current_style
def state_drawer(state, output=None, **drawer_args):
    """Returns a visualization of the state.

        **repr**: ASCII TextMatrix of the state's ``_repr_``.

        **text**: ASCII TextMatrix that can be printed in the console.

        **latex**: An IPython Latex object for displaying in Jupyter Notebooks.

        **latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX.

        **qsphere**: Matplotlib figure, rendering of statevector using `plot_state_qsphere()`.

        **hinton**: Matplotlib figure, rendering of statevector using `plot_state_hinton()`.

        **bloch**: Matplotlib figure, rendering of statevector using `plot_bloch_multivector()`.

        Args:
            output (str): Select the output method to use for drawing the
                circuit. Valid choices are ``text``, ``latex``, ``latex_source``,
                ``qsphere``, ``hinton``, or ``bloch``. Default is `'text`'.
            drawer_args: Arguments to be passed to the relevant drawer. For
                'latex' and 'latex_source' see ``array_to_latex``

        Returns:
            :class:`matplotlib.figure` or :class:`str` or
            :class:`TextMatrix` or :class:`IPython.display.Latex`:
            Drawing of the state.

        Raises:
            ImportError: when `output` is `latex` and IPython is not installed.
            ValueError: when `output` is not a valid selection.
    """
    config = user_config.get_config()
    # Get default 'output' from config file else use 'repr'
    default_output = 'repr'
    if output is None:
        if config:
            default_output = config.get('state_drawer', 'repr')
        output = default_output
    output = output.lower()

    # Choose drawing backend:
    drawers = {
        'text': TextMatrix,
        'latex_source': state_to_latex,
        'qsphere': plot_state_qsphere,
        'hinton': plot_state_hinton,
        'bloch': plot_bloch_multivector
    }
    if output == 'latex':
        try:
            from IPython.display import Latex
        except ImportError as err:
            raise ImportError(
                'IPython is not installed, to install run: '
                '"pip install ipython", or set output=\'latex_source\' '
                'instead for an ASCII string.') from err
        else:
            draw_func = drawers['latex_source']
            return Latex(f"$${draw_func(state, **drawer_args)}$$")

    if output == 'repr':
        return state.__repr__()

    try:
        draw_func = drawers[output]
        return draw_func(state, **drawer_args)
    except KeyError as err:
        raise ValueError(
            """'{}' is not a valid option for drawing {} objects. Please choose from:
            'text', 'latex', 'latex_source', 'qsphere', 'hinton',
            'bloch' or 'auto'.""".format(output,
                                         type(state).__name__)) from err
def state_drawer(state,
                 output=None,
                 max_size=None,
                 dims=None,
                 prefix=None,
                 **drawer_args):
    """Returns a visualization of the state.

        **text**: ASCII TextMatrix that can be printed in the console.

        **latex**: An IPython Latex object for displaying in Jupyter Notebooks.

        **latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX.

        **qsphere**: Matplotlib figure, rendering of statevector using `plot_state_qsphere()`.

        **hinton**: Matplotlib figure, rendering of statevector using `plot_state_hinton()`.

        **bloch**: Matplotlib figure, rendering of statevector using `plot_bloch_multivector()`.

        Args:
            output (str): Select the output method to use for drawing the
                circuit. Valid choices are ``text``, ``latex``, ``latex_source``,
                ``qsphere``, ``hinton``, or ``bloch``. Default is `'text`'.
            max_size (int): Maximum number of elements before array is
                summarized instead of fully represented. For ``latex``
                drawer, this is also the maximum number of elements that will
                be drawn in the output array, including elipses elements. For
                ``text`` drawer, this is the ``threshold`` parameter in
                ``numpy.array2string()``.
            dims (bool): For `text`, `latex` and `latex_source`. Whether to
                display the dimensions. If `None`, will only display if state
                is not a qubit state.
            prefix (str): For `text`, `latex`, and `latex_source`. Text to be
                displayed before the rest of the state.

        Returns:
            :class:`matplotlib.figure` or :class:`str` or
            :class:`TextMatrix`: or :class:`IPython.display.Latex`

        Raises:
            ImportError: when `output` is `latex` and IPython is not installed.
            ValueError: when `output` is not a valid selection.
    """
    # set 'output'
    config = user_config.get_config()
    # Get default 'output' from config file else use text
    default_output = 'text'
    if config:
        default_output = config.get('state_drawer', 'auto')
        if default_output == 'auto':
            try:
                from IPython.display import Latex
                default_output = 'latex'
            except ImportError:
                default_output = 'text'
    if output in [None, 'auto']:
        output = default_output
    output = output.lower()
    # Set 'dims'
    if dims is None:  # show dims if state is not only qubits
        if set(state.dims()) == {2}:
            dims = False
        else:
            dims = True
    if prefix is None:
        prefix = ''
    if max_size is None:
        max_size = (8, 8)
    if isinstance(max_size, int):
        max_size = (max_size, max_size)

    # Choose drawing backend:
    # format is {'key': (<drawer-function>, (<drawer-specific-args>))}
    drawers = {
        'text': (TextMatrix, (max_size, dims, prefix)),
        'latex_source': (_repr_state_latex, (max_size, dims, prefix)),
        'qsphere': (plot_state_qsphere, ()),
        'hinton': (plot_state_hinton, ()),
        'bloch': (plot_bloch_multivector, ())
    }
    if output == 'latex':
        try:
            from IPython.display import Latex
        except ImportError as err:
            raise ImportError(
                'IPython is not installed, to install run: '
                '"pip install ipython", or set output=\'latex_source\' '
                'instead for an ASCII string.') from err
        else:
            draw_func, args = drawers['latex_source']
            return Latex(draw_func(state, *args))
    try:
        draw_func, specific_args = drawers[output]
        return draw_func(state, *specific_args, **drawer_args)
    except KeyError as err:
        raise ValueError(
            """'{}' is not a valid option for drawing {} objects. Please choose from:
            'text', 'latex', 'latex_source', 'qsphere', 'hinton',
            'bloch' or 'auto'.""".format(output,
                                         type(state).__name__)) from err
def circuit_drawer(circuit,
                   scale=None,
                   filename=None,
                   style=None,
                   output=None,
                   interactive=False,
                   plot_barriers=True,
                   reverse_bits=False,
                   justify=None,
                   vertical_compression='medium',
                   idle_wires=True,
                   with_layout=True,
                   fold=None,
                   ax=None,
                   initial_state=False,
                   cregbundle=True):
    """Draw the quantum circuit. Use the output parameter to choose the drawing format:

    **text**: ASCII art TextDrawing that can be printed in the console.

    **matplotlib**: images with color rendered purely in Python.

    **latex**: high-quality images compiled via latex.

    **latex_source**: raw uncompiled latex output.

    Args:
        circuit (QuantumCircuit): the quantum circuit to draw
        scale (float): scale of image to draw (shrink if < 1.0). Only used by
            the `mpl`, `latex` and `latex_source` outputs. Defaults to 1.0.
        filename (str): file path to save image to. Defaults to None.
        style (dict or str): dictionary of style or file name of style json file.
            This option is only used by the `mpl` output type. If a str, it
            is used as the path to a json file which contains a style dict.
            The file will be opened, parsed, and then any style elements in the
            dict will replace the default values in the input dict. A file to
            be loaded must end in ``.json``, but the name entered here can omit
            ``.json``. For example, ``style='iqx.json'`` or ``style='iqx'``.
            If `style` is a dict and the ``'name'`` key is set, that name
            will be used to load a json file, followed by loading the other
            items in the style dict. For example, ``style={'name': 'iqx'}``.
            If `style` is not a str and `name` is not a key in the style dict,
            then the default value from the user config file (usually
            ``~/.qiskit/settings.conf``) will be used, for example,
            ``circuit_mpl_style = iqx``.
            If none of these are set, the `default` style will be used.
            The search path for style json files can be specified in the user
            config, for example,
            ``circuit_mpl_style_path = /home/user/styles:/home/user``.
            See: :ref:`Style Dict Doc <style-dict-doc>` for more
            information on the contents.
        output (str): select the output method to use for drawing the circuit.
            Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``.
            By default the `text` drawer is used unless the user config file
            (usually ``~/.qiskit/settings.conf``) has an alternative backend set
            as the default. For example, ``circuit_drawer = latex``. If the output
            kwarg is set, that backend will always be used over the default in
            the user config file.
        interactive (bool): when set to 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. Defaults to False.
        reverse_bits (bool): when set to True, reverse the bit order inside
            registers for the output visualization. Defaults to False.
        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.
        vertical_compression (string): ``high``, ``medium`` or ``low``. It
            merges the lines generated by the `text` output so the drawing
            will take less vertical room.  Default is ``medium``. Only used by
            the `text` output, will be silently ignored otherwise.
        idle_wires (bool): include idle wires (wires with no circuit elements)
            in output visualization. Default is True.
        with_layout (bool): include layout information, with labels on the
            physical layout. Default is True.
        fold (int): sets pagination. It can be disabled using -1. In `text`,
            sets the length of the lines. This is 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
            running in jupyter, the default line length is set to 80 characters.
            In `mpl`, it is the number of (visual) layers before folding.
            Default is 25.
        ax (matplotlib.axes.Axes): Only used by the `mpl` backend. An optional
            Axes object to be used for the visualization output. If none is
            specified, a new matplotlib Figure will be created and used.
            Additionally, if specified there will be no returned Figure since
            it is redundant.
        initial_state (bool): optional. Adds ``|0>`` in the beginning of the wire.
            Default is False.
        cregbundle (bool): optional. If set True, bundle classical registers.
            Default is True.

    Returns:
        :class:`TextDrawing` or :class:`matplotlib.figure` or :class:`PIL.Image` or
        :class:`str`:

        * `TextDrawing` (output='text')
            A drawing that can be printed as ascii art.
        * `matplotlib.figure.Figure` (output='mpl')
            A matplotlib figure object for the circuit diagram.
        * `PIL.Image` (output='latex')
            An in-memory representation of the image of the circuit diagram.
        * `str` (output='latex_source')
            The LaTeX source code for visualizing the circuit diagram.

    Raises:
        VisualizationError: when an invalid output method is selected
        ImportError: when the output methods requires non-installed libraries.

    .. _style-dict-doc:

    **Style Dict Details**

    The style dict kwarg contains numerous options that define the style of the
    output circuit visualization. The style dict is only used by the `mpl`
    output. The options available in the style dict are defined below:

    Args:
        name (str): the name of the style. The name can be set to ``iqx``,
            ``bw``, ``default``, or the name of a user-created json file. This
            overrides the setting in the user config file (usually
            ``~/.qiskit/settings.conf``).
        textcolor (str): the color code to use for all text not inside a gate.
            Defaults to ``#000000``
        subtextcolor (str): the color code to use for subtext. Defaults to
            ``#000000``
        linecolor (str): the color code to use for lines. Defaults to
            ``#000000``
        creglinecolor (str): the color code to use for classical register
            lines. Defaults to ``#778899``
        gatetextcolor (str): the color code to use for gate text. Defaults to
            ``#000000``
        gatefacecolor (str): the color code to use for a gate if no color
            specified in the 'displaycolor' dict. Defaults to ``#BB8BFF``
        barrierfacecolor (str): the color code to use for barriers. Defaults to
            ``#BDBDBD``
        backgroundcolor (str): the color code to use for the background.
            Defaults to ``#FFFFFF``
        edgecolor (str): the color code to use for gate edges when using the
            `bw` style. Defaults to ``#000000``.
        fontsize (int): the font size to use for text. Defaults to 13.
        subfontsize (int): the font size to use for subtext. Defaults to 8.
        showindex (bool): if set to True, show the index numbers at the top.
            Defaults to False.
        figwidth (int): the maximum width (in inches) for the output figure.
            If set to -1, the maximum displayable width will be used.
            Defaults to -1.
        dpi (int): the DPI to use for the output image. Defaults to 150.
        margin (list): a list of margin values to adjust spacing around output
            image. Takes a list of 4 ints: [x left, x right, y bottom, y top].
            Defaults to [2.0, 0.1, 0.1, 0.3].
        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``.
        displaytext (dict): a dictionary of the text to use for certain element
            types in the output visualization. These items allow the use of
            LaTeX formatting for gate names. The 'displaytext' dict can contain
            any number of elements from one to the entire dict above.The default
            values are (`default.json`)::

                {
                    'u1': '$\\mathrm{U}_1$',
                    'u2': '$\\mathrm{U}_2$',
                    'u3': '$\\mathrm{U}_3$',
                    'u': 'U',
                    'p': 'P',
                    'id': 'I',
                    'x': 'X',
                    'y': 'Y',
                    'z': 'Z',
                    'h': 'H',
                    's': 'S',
                    'sdg': '$\\mathrm{S}^\\dagger$',
                    'sx': '$\\sqrt{\\mathrm{X}}$',
                    'sxdg': '$\\sqrt{\\mathrm{X}}^\\dagger$',
                    't': 'T',
                    'tdg': '$\\mathrm{T}^\\dagger$',
                    'dcx': 'Dcx',
                    'iswap': 'Iswap',
                    'ms': 'MS',
                    'r': 'R',
                    'rx': '$\\mathrm{R}_\\mathrm{X}$',
                    'ry': '$\\mathrm{R}_\\mathrm{Y}$',
                    'rz': '$\\mathrm{R}_\\mathrm{Z}$',
                    'rxx': '$\\mathrm{R}_{\\mathrm{XX}}$',
                    'ryy': '$\\mathrm{R}_{\\mathrm{YY}}$',
                    'rzx': '$\\mathrm{R}_{\\mathrm{ZX}}$',
                    'rzz': '$\\mathrm{R}_{\\mathrm{ZZ}}$',
                    'reset': '$\\left|0\\right\\rangle$',
                    'initialize': '$|\\psi\\rangle$'
                }

        displaycolor (dict): the color codes to use for each circuit element in
            the form (gate_color, text_color). Colors can also be entered without
            the text color, such as 'u1': '#FA74A6', in which case the text color
            will always be `gatetextcolor`. The `displaycolor` dict can contain
            any number of elements from one to the entire dict above. The default
            values are (`default.json`)::

                {
                    'u1': ('#FA74A6', '#000000'),
                    'u2': ('#FA74A6', '#000000'),
                    'u3': ('#FA74A6', '#000000'),
                    'id': ('#05BAB6', '#000000'),
                    'u': ('#BB8BFF', '#000000'),
                    'p': ('#BB8BFF', '#000000'),
                    'x': ('#05BAB6', '#000000'),
                    'y': ('#05BAB6', '#000000'),
                    'z': ('#05BAB6', '#000000'),
                    'h': ('#6FA4FF', '#000000'),
                    'cx': ('#6FA4FF', '#000000'),
                    'ccx': ('#BB8BFF', '#000000'),
                    'mcx': ('#BB8BFF', '#000000'),
                    'mcx_gray': ('#BB8BFF', '#000000),
                    'cy': ('#6FA4FF', '#000000'),
                    'cz': ('#6FA4FF', '#000000'),
                    'swap': ('#6FA4FF', '#000000'),
                    'cswap': ('#BB8BFF', '#000000'),
                    'ccswap': ('#BB8BFF', '#000000'),
                    'dcx': ('#6FA4FF', '#000000'),
                    'cdcx': ('#BB8BFF', '#000000'),
                    'ccdcx': ('#BB8BFF', '#000000'),
                    'iswap': ('#6FA4FF', '#000000'),
                    's': ('#6FA4FF', '#000000'),
                    'sdg': ('#6FA4FF', '#000000'),
                    't': ('#BB8BFF', '#000000'),
                    'tdg': ('#BB8BFF', '#000000'),
                    'sx': ('#BB8BFF', '#000000'),
                    'sxdg': ('#BB8BFF', '#000000')
                    'r': ('#BB8BFF', '#000000'),
                    'rx': ('#BB8BFF', '#000000'),
                    'ry': ('#BB8BFF', '#000000'),
                    'rz': ('#BB8BFF', '#000000'),
                    'rxx': ('#BB8BFF', '#000000'),
                    'ryy': ('#BB8BFF', '#000000'),
                    'rzx': ('#BB8BFF', '#000000'),
                    'reset': ('#000000', #FFFFFF'),
                    'target': ('#FFFFFF, '#FFFFFF'),
                    'measure': ('#000000', '#FFFFFF'),
                }

    Example:
        .. jupyter-execute::

            from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
            from qiskit.tools.visualization import circuit_drawer
            q = QuantumRegister(1)
            c = ClassicalRegister(1)
            qc = QuantumCircuit(q, c)
            qc.h(q)
            qc.measure(q, c)
            circuit_drawer(qc, output='mpl', style={'showindex': True})
    """
    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 default_output == 'auto':
            if _matplotlib.HAS_MATPLOTLIB:
                default_output = 'mpl'
            else:
                default_output = 'text'
    if output is None:
        output = default_output

    if output == 'text':
        return _text_circuit_drawer(circuit,
                                    filename=filename,
                                    reverse_bits=reverse_bits,
                                    plot_barriers=plot_barriers,
                                    justify=justify,
                                    vertical_compression=vertical_compression,
                                    idle_wires=idle_wires,
                                    with_layout=with_layout,
                                    fold=fold,
                                    initial_state=initial_state,
                                    cregbundle=cregbundle)
    elif output == 'latex':
        image = _latex_circuit_drawer(circuit,
                                      filename=filename,
                                      scale=scale,
                                      plot_barriers=plot_barriers,
                                      reverse_bits=reverse_bits,
                                      justify=justify,
                                      idle_wires=idle_wires,
                                      with_layout=with_layout,
                                      initial_state=initial_state,
                                      cregbundle=cregbundle)
    elif output == 'latex_source':
        return _generate_latex_source(circuit,
                                      filename=filename,
                                      scale=scale,
                                      plot_barriers=plot_barriers,
                                      reverse_bits=reverse_bits,
                                      justify=justify,
                                      idle_wires=idle_wires,
                                      with_layout=with_layout,
                                      initial_state=initial_state,
                                      cregbundle=cregbundle)
    elif output == 'mpl':
        image = _matplotlib_circuit_drawer(circuit,
                                           scale=scale,
                                           filename=filename,
                                           style=style,
                                           plot_barriers=plot_barriers,
                                           reverse_bits=reverse_bits,
                                           justify=justify,
                                           idle_wires=idle_wires,
                                           with_layout=with_layout,
                                           fold=fold,
                                           ax=ax,
                                           initial_state=initial_state,
                                           cregbundle=cregbundle)
    else:
        raise exceptions.VisualizationError(
            'Invalid output type %s selected. The only valid choices '
            'are text, latex, latex_source, and mpl' % output)
    if image and interactive:
        image.show()
    return image
Esempio n. 16
0
def transpile(circuits,
              backend=None,
              basis_gates=None,
              coupling_map=None,
              backend_properties=None,
              initial_layout=None,
              seed_transpiler=None,
              optimization_level=None,
              pass_manager=None):
    """transpile one or more circuits, according to some desired
    transpilation targets.

    All arguments may be given as either singleton or list. In case of list,
    the length must be equal to the number of circuits being transpiled.

    Transpilation is done in parallel using multiprocessing.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]):
            Circuit(s) to transpile

        backend (BaseBackend):
            If set, transpiler options are automatically grabbed from
            backend.configuration() and backend.properties().
            If any other option is explicitly set (e.g. coupling_map), it
            will override the backend's.
            Note: the backend arg is purely for convenience. The resulting
                circuit may be run on any backend as long as it is compatible.

        basis_gates (list[str]):
            List of basis gate names to unroll to.
            e.g:
                ['u1', 'u2', 'u3', 'cx']
            If None, do not unroll.

        coupling_map (CouplingMap or list):
            Coupling map (perhaps custom) to target in mapping.
            Multiple formats are supported:
            a. CouplingMap instance

            b. list
                Must be given as an adjacency matrix, where each entry
                specifies all two-qubit interactions supported by backend
                e.g:
                    [[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]

        backend_properties (BackendProperties):
            properties returned by a backend, including information on gate
            errors, readout errors, qubit coherence times, etc. For a backend
            that provides this information, it can be obtained with:
            ``backend.properties()``

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits.
            If this layout makes the circuit compatible with the coupling_map
            constraints, it will be used.
            The final layout is not guaranteed to be the same, as the transpiler
            may permute qubits through swaps or other means.

            Multiple formats are supported:
            a. Layout instance

            b. dict
                virtual to physical:
                    {qr[0]: 0,
                     qr[1]: 3,
                     qr[2]: 5}

                physical to virtual:
                    {0: qr[0],
                     3: qr[1],
                     5: qr[2]}

            c. list
                virtual to physical:
                    [0, 3, 5]  # virtual qubits are ordered (in addition to named)

                physical to virtual:
                    [qr[0], None, None, qr[1], None, qr[2]]

        seed_transpiler (int):
            sets random seed for the stochastic parts of the transpiler

        optimization_level (int):
            How much optimization to perform on the circuits.
            Higher levels generate more optimized circuits,
            at the expense of longer transpilation time.
                0: no optimization
                1: light optimization
                2: heavy optimization
                3: even heavier optimization

        pass_manager (PassManager):
            The pass manager to use for a custom pipeline of transpiler passes.
            If this arg is present, all other args will be ignored and the
            pass manager will be used directly (Qiskit will not attempt to
            auto-select a pass manager based on transpile options).


    Returns:
        QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).

    Raises:
        TranspilerError: in case of bad inputs to transpiler or errors in passes
    """

    # transpiling schedules is not supported yet.
    if isinstance(circuits, Schedule) or \
       (isinstance(circuits, list) and all(isinstance(c, Schedule) for c in circuits)):
        return circuits

    if optimization_level is None:
        config = user_config.get_config()
        optimization_level = config.get('transpile_optimization_level', None)

    # Get TranspileConfig(s) to configure the circuit transpilation job(s)
    circuits = circuits if isinstance(circuits, list) else [circuits]
    transpile_configs = _parse_transpile_args(circuits, backend, basis_gates,
                                              coupling_map, backend_properties,
                                              initial_layout, seed_transpiler,
                                              optimization_level, pass_manager)
    # Check circuit width against number of qubits in coupling_map(s)
    coupling_maps_list = list(config.coupling_map
                              for config in transpile_configs)
    for circuit, parsed_coupling_map in zip(circuits, coupling_maps_list):
        # If coupling_map is not None
        if isinstance(parsed_coupling_map, CouplingMap):
            n_qubits = len(circuit.qubits)
            max_qubits = parsed_coupling_map.size()
            if n_qubits > max_qubits:
                raise TranspilerError(
                    'Number of qubits ({}) '.format(n_qubits) +
                    'in {} '.format(circuit.name) +
                    'is greater than maximum ({}) '.format(max_qubits) +
                    'in the coupling_map')
    # Transpile circuits in parallel
    circuits = parallel_map(_transpile_circuit,
                            list(zip(circuits, transpile_configs)))

    if len(circuits) == 1:
        return circuits[0]
    return circuits
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,
                   vertical_compression='medium',
                   idle_wires=True,
                   with_layout=True,
                   fold=None,
                   ax=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): Deprecated. See `fold`.
        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.
        vertical_compression (string): `high`, `medium` or `low`. It merges the
            lines generated by `text` so the drawing will take less vertical room.
            Default is `medium`. It is ignored if output is not `text`.
        idle_wires (bool): Include idle wires. Default is True.
        with_layout (bool): Include layout information, with labels on the physical
            layout.
        fold (int): Sets pagination. It can be disabled using -1.
            In `text`, sets the length of the lines. 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
            running in jupyter, the default line length is set to 80 characters.
            In `mpl` is the amount of operations before folding. Default is 25.
        ax (matplotlib.axes.Axes): An optional Axes object to be used for
            the visualization output. If none is specified a new matplotlib
            Figure will be created and used. Additionally, if specified there
            will be no returned Figure since it is redundant. This is only used
            when the ``output`` kwarg is set to use the ``mpl`` backend. It
            will be silently ignored with all other outputs.
    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, if the ``ax`` kwarg is not set
        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. Defaults to `'#778899'`(`mpl` only)
        gatetextcolor (str): The color code to use for gate text. Defaults to
            `'#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.
            The default values are:
            {
                'id': '#F0E442',
                'u0': '#E7AB3B',
                'u1': '#E7AB3B',
                'u2': '#E7AB3B',
                'u3': '#E7AB3B',
                'x': '#58C698',
                'y': '#58C698',
                'z': '#58C698',
                'h': '#70B7EB',
                's': '#E0722D',
                'sdg': '#E0722D',
                't': '#E0722D',
                'tdg': '#E0722D',
                'rx': '#ffffff',
                'ry': '#ffffff',
                'rz': '#ffffff',
                'reset': '#D188B4',
                'target': '#70B7EB',
                'meas': '#D188B4'
           }
           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 default_output == 'auto':
            if _matplotlib.HAS_MATPLOTLIB:
                default_output = 'mpl'
            else:
                default_output = '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,
                                    plot_barriers=plot_barriers,
                                    justify=justify,
                                    vertical_compression=vertical_compression,
                                    idle_wires=idle_wires,
                                    with_layout=with_layout,
                                    fold=fold)
    elif output == 'latex':
        image = _latex_circuit_drawer(circuit,
                                      scale=scale,
                                      filename=filename,
                                      style=style,
                                      plot_barriers=plot_barriers,
                                      reverse_bits=reverse_bits,
                                      justify=justify,
                                      idle_wires=idle_wires,
                                      with_layout=with_layout)
    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,
                                      idle_wires=idle_wires,
                                      with_layout=with_layout)
    elif output == 'mpl':
        image = _matplotlib_circuit_drawer(circuit,
                                           scale=scale,
                                           filename=filename,
                                           style=style,
                                           plot_barriers=plot_barriers,
                                           reverse_bits=reverse_bits,
                                           justify=justify,
                                           idle_wires=idle_wires,
                                           with_layout=with_layout,
                                           fold=fold,
                                           ax=ax)
    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
def circuit_drawer(circuit,
                   scale=0.7,
                   filename=None,
                   style=None,
                   output=None,
                   interactive=False,
                   plot_barriers=True,
                   reverse_bits=False,
                   justify=None,
                   vertical_compression='medium',
                   idle_wires=True,
                   with_layout=True,
                   fold=None,
                   ax=None,
                   initial_state=False,
                   cregbundle=False):
    """Draw a quantum circuit to different formats (set by output parameter):

    **text**: ASCII art TextDrawing that can be printed in the console.

    **latex**: high-quality images compiled via latex.

    **latex_source**: raw uncompiled latex output.

    **matplotlib**: images with color rendered purely in Python.

    Args:
        circuit (QuantumCircuit): the quantum circuit to draw
        scale (float): scale of image to draw (shrink if < 1). Only used by the ``mpl``,
            ``latex``, and ``latex_source`` outputs.
        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`` output type. 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. See:
            :ref:`Style Dict Doc <style-dict-doc>` for more information on the
            contents.
        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 kwarg
            is set, that backend will always be used over the default in a user
            config file.
        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.
        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.
        vertical_compression (string): ``high``, ``medium`` or ``low``. It
            merges the lines generated by the ``text`` output so the drawing
            will take less vertical room.  Default is ``medium``. Only used by
            the ``text`` output, will be silently ignored otherwise.
        idle_wires (bool): Include idle wires (wires with no circuit elements)
            in output visualization. Default is True.
        with_layout (bool): Include layout information, with labels on the
            physical layout. Default is True.
        fold (int): Sets pagination. It can be disabled using -1.
            In `text`, sets the length of the lines. 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 running in jupyter, the default line length is set to
            80 characters. In ``mpl`` it is the number of (visual) layers before
            folding. Default is 25.
        ax (matplotlib.axes.Axes): An optional Axes object to be used for
            the visualization output. If none is specified a new matplotlib
            Figure will be created and used. Additionally, if specified there
            will be no returned Figure since it is redundant. This is only used
            when the ``output`` kwarg is set to use the ``mpl`` backend. It
            will be silently ignored with all other outputs.
        initial_state (bool): Optional. Adds ``|0>`` in the beginning of the wire.
            Default: ``False``.
        cregbundle (bool): Optional. If set True bundle classical registers.
            Default: ``False``.

    Returns:
        :class:`PIL.Image` or :class:`matplotlib.figure` or :class:`str` or
        :class:`TextDrawing`:

        * `PIL.Image` (output='latex')
            an in-memory representation of the image of the circuit diagram.
        * `matplotlib.figure.Figure` (output='mpl')
            a matplotlib figure object for the circuit diagram.
        * `str` (output='latex_source')
            The LaTeX source code for visualizing the circuit diagram.
        * `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 requires non-installed libraries.

    .. _style-dict-doc:

    **Style Dict Details**

    The style dict kwarg contains numerous options that define the style of the
    output circuit visualization. The style dict is only used by the ``mpl``
    output. The options available in the style dict are defined below:

    Args:
        textcolor (str): The color code to use for text. Defaults to
            `'#000000'`
        subtextcolor (str): The color code to use for subtext. Defaults to
            `'#000000'`
        linecolor (str): The color code to use for lines. Defaults to
            `'#000000'`
        creglinecolor (str): The color code to use for classical register
            lines. Defaults to `'#778899'`
        gatetextcolor (str): The color code to use for gate text. Defaults to
            `'#000000'`
        gatefacecolor (str): The color code to use for gates. Defaults to
            `'#ffffff'`
        barrierfacecolor (str): The color code to use for barriers. Defaults to
            `'#bdbdbd'`
        backgroundcolor (str): The color code to use for the background.
            Defaults to `'#ffffff'`
        fontsize (int): The font size to use for text. Defaults to 13
        subfontsize (int): The font size to use for subtext. Defaults to 8
        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.
        displaycolor (dict):
            The color codes to use for each circuit element. The default values are::

                {
                    'id': '#F0E442',
                    'u0': '#E7AB3B',
                    'u1': '#E7AB3B',
                    'u2': '#E7AB3B',
                    'u3': '#E7AB3B',
                    'x': '#58C698',
                    'y': '#58C698',
                    'z': '#58C698',
                    'h': '#70B7EB',
                    's': '#E0722D',
                    'sdg': '#E0722D',
                    't': '#E0722D',
                    'tdg': '#E0722D',
                    'rx': '#ffffff',
                    'ry': '#ffffff',
                    'rz': '#ffffff',
                    'reset': '#D188B4',
                    'target': '#70B7EB',
                    'meas': '#D188B4'
                }

           Also, just like  `displaytext` there is no provision for an
           incomplete dict passed in.

        latexdrawerstyle (bool): When set to True enable latex mode which will
            draw gates like the `latex` output modes.
        usepiformat (bool): When set to True use radians for output
        fold (int): The number of circuit elements to fold the circuit at.
            Defaults to 20
        cregbundle (bool): If set True bundle classical registers
        showindex (bool): If set True draw an index.
        compress (bool): If set True draw a compressed circuit
        figwidth (int): The maximum width (in inches) for the output figure.
        dpi (int): The DPI to use for the output image. Defaults to 150
        margin (list): A list of margin values to adjust spacing around output
            image. Takes a list of 4 ints: [x left, x right, y bottom, y top].
        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`

    Example:
        .. jupyter-execute::

            from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
            from qiskit.tools.visualization import circuit_drawer
            q = QuantumRegister(1)
            c = ClassicalRegister(1)
            qc = QuantumCircuit(q, c)
            qc.h(q)
            qc.measure(q, c)
            circuit_drawer(qc)
    """
    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 default_output == 'auto':
            if _matplotlib.HAS_MATPLOTLIB:
                default_output = 'mpl'
            else:
                default_output = 'text'
    if output is None:
        output = default_output

    if output == 'text':
        return _text_circuit_drawer(circuit,
                                    filename=filename,
                                    reverse_bits=reverse_bits,
                                    plot_barriers=plot_barriers,
                                    justify=justify,
                                    vertical_compression=vertical_compression,
                                    idle_wires=idle_wires,
                                    with_layout=with_layout,
                                    fold=fold,
                                    initial_state=initial_state,
                                    cregbundle=cregbundle)
    elif output == 'latex':
        image = _latex_circuit_drawer(circuit,
                                      scale=scale,
                                      filename=filename,
                                      style=style,
                                      plot_barriers=plot_barriers,
                                      reverse_bits=reverse_bits,
                                      justify=justify,
                                      idle_wires=idle_wires,
                                      with_layout=with_layout,
                                      initial_state=initial_state,
                                      cregbundle=cregbundle)
    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,
                                      idle_wires=idle_wires,
                                      with_layout=with_layout,
                                      initial_state=initial_state,
                                      cregbundle=cregbundle)
    elif output == 'mpl':
        image = _matplotlib_circuit_drawer(circuit,
                                           scale=scale,
                                           filename=filename,
                                           style=style,
                                           plot_barriers=plot_barriers,
                                           reverse_bits=reverse_bits,
                                           justify=justify,
                                           idle_wires=idle_wires,
                                           with_layout=with_layout,
                                           fold=fold,
                                           ax=ax,
                                           initial_state=initial_state,
                                           cregbundle=cregbundle)
    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