
    z	i9y                       S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSK	J
r
  SSKJr  SSKJrJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  \R@                  (       a  SSKJ!r!  SSKJ"r"  \RF                  " \$5      r%                  S                                     SS jjr&              SS jr'\RP                  RS                  S5      \RT                  RS                  S5      \RV                  RS                  S5                 SS j5       5       5       r,           SS jr-               SS jr.g)a8  
Module for the primary interface to the circuit drawers.

This module contains the end user facing API for drawing quantum circuits.
There are 3 available drawer backends:

 0. ASCII art
 1. LaTeX
 2. Matplotlib

This provides a single function entry point to drawing a circuit object with
any of the backends.
    )annotationsN)warn)user_config)ControlFlowOpMeasure)	optionals   )VisualizationError)_trim   )_utils)latex)
matplotlib)text)Any)QuantumCircuitc                  ^ Sn[        US5      n[        R                  " 5       nSnSnUR                  SS5      nUR                  SS5      nU(       aG  UR                  S	S5      nUS:X  a  [        R
                  (       a  S
nOSnUc  UR                  SS5      nUc  UnUc  UnU
c  Un
[        U
[        5      (       a7  U
S:X  a"  [        U S5      =(       a    U R                  SL n
O[        SU
 S35      eUc  UnUb  U(       a  [        S5      eUnUb  [        U5      nU R                  U R                  -   nUU R                  U4;  a  [        SU SU R                   SU S35      e[        [        U5      5      [        U5      :w  a  [        S5      eUU R                  :X  a"  U[        [!        U R                  U5      5      -   nU R"                  (       ah  U(       d  Ub^  [        U=(       d    / 5      R%                  [        [!        U R                  5      5      5      (       d  U(       a  ['        S[(        S5        SnU4S jmT" X5      nUS:X  a  [+        U UUUUU	U
UUUUUUUS9$ US:X  a  [-        U UUUUUUU
UUUUS9nOJUS:X  a  [/        U UUUUUUU
UUUUS9$ US
:X  a  [1        U 4UUUUUUU
UUUUUUUUS.6nO[        SU S35      eU(       a  U(       a  UR3                  5         U$ )a<  Draw the quantum circuit. Use the output parameter to choose the drawing format:

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

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

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

**latex_source**: raw uncompiled latex output.

.. warning::

    Support for :class:`~.expr.Expr` nodes in conditions and :attr:`.SwitchCaseOp.target`
    fields is preliminary and incomplete.  The ``text`` and ``mpl`` drawers will make a
    best-effort attempt to show data dependencies, but the LaTeX-based drawers will skip
    these completely.

Args:
    circuit: The circuit to visualize.
    scale: Scale of image to draw (shrink if ``< 1.0``). Only used by
        the ``mpl``, ``latex`` and ``latex_source`` outputs. Defaults to ``1.0``.
    filename: File path to save image to. Defaults to ``None`` (result not saved in a file).
    style: Style name, file name of style JSON file, or a dictionary specifying the style.

        * The supported style names are ``"iqp"`` (default), ``"iqp-dark"``, ``"clifford"``,
            ``"textbook"`` and ``"bw"``.
        * If given a JSON file, e.g. ``my_style.json`` or ``my_style`` (the ``.json``
            extension may be omitted), this function attempts to load the style dictionary
            from that location. Note, that the JSON file must completely specify the
            visualization specifications. The file is searched for in
            ``qiskit/visualization/circuit/styles``, the current working directory, and
            the location specified in ``~/.qiskit/settings.conf``.
        * If a dictionary, every entry overrides the default configuration. If the
            ``"name"`` key is given, the default configuration is given by that style.
            For example, ``{"name": "textbook", "subfontsize": 5}`` loads the ``"texbook"``
            style and sets the subfontsize (e.g. the gate angles) to ``5``.
        * If ``None`` the default style ``"iqp"`` is used or, if given, the default style
            specified in ``~/.qiskit/settings.conf``.

    output: 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: 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: When set to ``True``, reverse the bit order inside
        registers for the output visualization. Defaults to ``False`` unless the
        user config file (usually ``~/.qiskit/settings.conf``) has an
        alternative value set. For example, ``circuit_reverse_bits = True``.
    plot_barriers: Enable/disable drawing barriers in the output
        circuit. Defaults to ``True``.
    justify: Options are ``"left"``, ``"right"`` or ``"none"`` (str).
        If anything else is supplied, left justified will be used instead.
        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. Defaults to ``left``.
    vertical_compression: ``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: Include (or not) idle wires (wires with no circuit elements)
        in output visualization. The string ``"auto"`` is also possible, in which
        case idle wires are show except that the circuit has a layout attached.
        Default is ``"auto"`` unless the
        user config file (usually ``~/.qiskit/settings.conf``) has an
        alternative value set. For example, ``circuit_idle_wires = False``.
    with_layout: Include layout information, with labels on the
        physical layout. Default is ``True``.
    fold: 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: Only used by the `mpl` backend. An optional ``matplotlib.axes.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: Adds :math:`|0\rangle` in the beginning of the qubit wires and
        :math:`0` to classical wires. Default is ``False``.
    cregbundle: If set to ``True``, bundle classical registers.
        Default is ``True``, except for when ``output`` is set to  ``"text"``.
    wire_order: A list of integers used to reorder the display
        of the bits. The list must have an entry for every bit with the bits
        in the range 0 to (``num_qubits`` + ``num_clbits``).
    expr_len: The number of characters to display if an :class:`~.expr.Expr`
        is used for the condition in a :class:`.ControlFlowOp`. If this number is exceeded,
        the string will be truncated at that number and '...' added to the end.
    measure_arrows: If True, draw an arrow from each measure box down the the classical bit
        or register where the measure value is placed. If False, do not draw arrow, but
        instead place the name of the bit or register in the measure box.
        Default is ``True`` unless the user config file (usually ``~/.qiskit/settings.conf``)
        has an alternative value set. For example, ``circuit_measure_arrows = False``.

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

    * ``TextDrawing`` (if ``output='text'``)
        A drawing that can be printed as ascii art.
    * ``matplotlib.figure.Figure`` (if ``output='mpl'``)
        A matplotlib figure object for the circuit diagram.
    * ``PIL.Image`` (if ``output='latex``')
        An in-memory representation of the image of the circuit diagram.
    * ``str`` (if ``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.

Example:
    .. plot::
        :alt: Circuit diagram output by the previous code.
        :include-source:

        from qiskit import QuantumCircuit
        from qiskit.visualization import circuit_drawer
        qc = QuantumCircuit(1, 1)
        qc.h(0)
        qc.measure(0, 0)
        circuit_drawer(qc, output="mpl", style={"backgroundcolor": "#EEEEEE"})
Nr   r   Fcircuit_idle_wiresautocircuit_measure_arrowsTcircuit_drawermplcircuit_reverse_bits_layoutzParameter idle_wires=z unrecognized.zIThe wire_order option cannot be set when the reverse_bits option is True.zThe wire_order list (length z*) should as long as the number of qubits (z4) or the total numbers of qubits and classical bits .z6The wire_order list should not have repeated elements.zbcregbundle set to False since either reverse_bits or wire_order (over classical bit) has been set.r	   c                d  > USL a  gU R                    H  n[        UR                  [        5      (       a-  UR                  R                   H  nT" X15      SL d  M      g   MO  UR
                  (       d  Mb  [        UR                  [        5      (       a  M  USLa  [        S[        S5          g   g)NFzXCregbundle set to False since an instruction needs to refer to individual classical wire   T)	data
isinstance	operationr   blocksclbitsr   r   RuntimeWarning)circuit
cregbundleinstblockcheck_clbit_in_insts       l/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/visualization/circuit/circuit_visualization.pyr(   +circuit_drawer.<locals>.check_clbit_in_inst  s    LLD$..-88!^^22E*5=F$ 3 Z%H%HU*8&	  !     )filenamereverse_bitsplot_barriersjustifyvertical_compression
idle_wireswith_layoutfoldinitial_stater%   
wire_orderexpr_lenmeasure_arrowsr   r,   scalestyler.   r-   r/   r1   r2   r4   r%   r5   latex_source)r9   r,   r:   r.   r-   r/   r1   r2   r3   axr4   r%   r5   r6   r7   zInvalid output type zH selected. The only valid choices are text, latex, latex_source, and mpl)maxr   
get_configget
_optionalsHAS_MATPLOTLIBr   strhasattrr   r
   len
num_qubits
num_clbitssetlistranger"   issubsetr   r#   _text_circuit_drawer_latex_circuit_drawer_generate_latex_source_matplotlib_circuit_drawershow)r$   r9   r,   r:   outputinteractiver.   r-   r/   r0   r1   r2   r3   r<   r4   r%   r5   r6   r7   imageconfigdefault_outputdefault_reverse_bitsdefault_idle_wiresdefault_measure_arrowscomplete_wire_orderwire_order_lentotal_wire_lenr(   s                               @r)   r   r   8   s   t E8QH##%FN $8&A#ZZ(@$G$4f=V#((!&!'#)::.De#L ~+'
*c"" )4PD9PJ$'<ZL%WXX/, W
 	
 %Z ++g.@.@@'"4"4n!EE$.~.> ?))0););(< =>>L=MQP  s:3z?2$%]^^W///",tE':L:Ln4]/^"^ 	Z3J$"%..s59K9K3L/MNN5	 
( %W9J#%'!5!#'!*)
 	
  
7	%'%!#'!*
 
>	!%'%!#'!*
 	
 
5*
'%!#'!*)!
& !"6( +5 5
 	
 

Lr+   c                    [         R                  " U UUUUUS9u  nnn[        R                  " UUUU UU	U
UUUUS9nUUl        UUl        UUl        U(       a  UR                  XS9  U$ )a  Draws a circuit using ascii art.

Args:
    circuit (QuantumCircuit): Input circuit
    filename (str): Optional filename to write the result
    reverse_bits (bool): Rearrange the bits in reverse order.
    plot_barriers (bool): Draws the barriers when they are there.
    justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
        the circuit should be justified.
    vertical_compression (string): `high`, `medium`, or `low`. It merges the
        lines so the drawing will take less vertical room. Default is `high`.
    idle_wires (bool): Include idle wires. Default is True.
    with_layout (bool): Include layout information with labels on the physical
        layout. Default: True
    fold (int): Optional. Breaks the circuit drawing to this length. 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()`. If you don't want pagination
        at all, set `fold=-1`.
    initial_state (bool): Optional. Adds |0> in the beginning of the line.
        Default: `False`.
    cregbundle (bool): Optional. If set True, bundle classical registers.
        Default: ``True``.
    encoding (str): Optional. Sets the encoding preference of the output.
        Default: ``sys.stdout.encoding``.
    wire_order (list): Optional. A list of integers used to reorder the display
        of the bits. The list must have an entry for every bit with the bits
        in the range 0 to (num_qubits + num_clbits).
    expr_len (int): Optional. The number of characters to display if an :class:`~.expr.Expr`
        is used for the condition in a :class:`.ControlFlowOp`. If this number is exceeded,
        the string will be truncated at that number and '...' added to the end.
    measure_arrows: If True, draw an arrow from each measure box down the the classical bit
        or register where the measure value is placed. If False, do not draw arrow, but
        instead place the name of the bit or register in the measure box.

Returns:
    TextDrawing: An instance that, when printed, draws the circuit in ascii art.

Raises:
    VisualizationError: When the filename extension is not .txt.
r-   r/   r1   r5   r7   )r-   r4   r%   encodingr2   r6   r7   )r]   )r   _get_layered_instructions_textTextDrawingplotbarriersline_lengthr0   dump)r$   r,   r-   r.   r/   r0   r1   r2   r3   r4   r%   r]   r5   r6   r7   qubitsr"   nodestext_drawings                      r)   rK   rK     s    t #<<!%FFE $$!#%L !.L#L(<L%(6r+   zLaTeX circuit drawingc                   SSK Jn  Sn[        R                  " 5        n[        R
                  R                  XS-   5      n[        U UUUUUUUUU	U
US9   [        R                  " SSSU 3US-    /[        R                  [        R                  S	S
9  [        R
                  R                  X5      n [        R                  " SSSSUS-   U/S	S9  UR                  US-   5      n[)        U5      nU(       aC  UR+                  S5      (       a  [,        R.                  " US-   U5        O UR1                  U5        UsSSS5        $ ! [         a  n[        S5      UeSnAf[        R                   ah  n[        SS5       nUR!                  UR"                  5        SSS5        O! , (       d  f       O= f[$        R'                  S5        [        S5      UeSnAff = f! [        [        R                  4 a(  nSn[$        R'                  U5        [        U5      UeSnAff = f! [2        [        4 a  n[        SU S35      UeSnAff = f! , (       d  f       g= f)a1  Draw a quantum circuit based on latex (Qcircuit package)

Requires version >=2.6.0 of the qcircuit LaTeX package.

Args:
    circuit (QuantumCircuit): a quantum circuit
    scale (float): scaling factor
    style (dict or str): dictionary of style or file name of style file
    filename (str): file path to save image to
    reverse_bits (bool): When set to True reverse the bit order inside
        registers for the output visualization.
    plot_barriers (bool): Enable/disable drawing barriers in the output
        circuit. Defaults to True.
    justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
        the circuit should be justified.
    idle_wires (bool): Include idle wires. Default is True.
    with_layout (bool): Include layout information, with labels on the physical
        layout. Default: True
    initial_state (bool): Optional. Adds |0> in the beginning of the line.
        Default: `False`.
    cregbundle (bool): Optional. If set True, bundle classical registers.  On by default, if
        this is possible for the given circuit, otherwise off.
    wire_order (list): Optional. A list of integers used to reorder the display
        of the bits. The list must have an entry for every bit with the bits
        in the range 0 to (num_qubits + num_clbits).

Returns:
    PIL.Image: an in-memory representation of the circuit diagram

Raises:
    MissingOptionalLibraryError: if pillow, pdflatex, or poppler are not installed
    VisualizationError: if one of the conversion utilities failed for some internal or
        file-access reason.
r   )Imager$   z.texr8   pdflatexz-halt-on-errorz-output-directory=T)stdoutstderrcheckz$`pdflatex` command could not be run.Nzlatex_error.logwbzUnable to compile LaTeX. Perhaps you are missing the `qcircuit` package. The output from the `pdflatex` command is in `latex_error.log`.z7`pdflatex` call did not succeed: see `latex_error.log`.
pdftocairoz-singlefilez-pngz-qz.pdf)rl   z(`pdftocairo` failed to produce an image.z.pngz'Pillow could not write the image file 'z'.)PILrh   tempfileTemporaryDirectoryospathjoinrM   
subprocessrunPIPEDEVNULLOSErrorr
   CalledProcessErroropenwriterj   loggerwarning
trim_imageendswithshutilmovesave
ValueError)r$   r9   r:   r,   r.   r-   r/   r1   r2   r4   r%   r5   rh   tmpfilename
tmpdirnametmppathexc
error_filebasemessagerR   s                        r)   rL   rL     s>   f K		$	$	&*'',,z+?@'%!#'!!	
	NN$(5"V+,	 "!))
2 ww||J4	7NN}fdD6M4P 

4&=)5!  ((D6M84JJx(
 C 
'	&:  	V %%KLRUU,, 		'.*  , /..NNS %I		  667 	7@GNN7#$W-36	7 #G, ,A(2N{ 
'	&s   7I>EI4GAI*H#;I
GEG3G?F$	G$
F2.(GGIH 8#HH  I#I3III
Ic                   [         R                  " U UUUUS9u  pn[        R                  " UUUUUUUU	U
UU S9nUR	                  5       nU(       a(  [        US5       nUR                  U5        SSS5        U$ U$ ! , (       d  f       U$ = f)a  Convert QuantumCircuit to LaTeX string.

Args:
    circuit (QuantumCircuit): a quantum circuit
    scale (float): scaling factor
    style (dict or str): dictionary of style or file name of style file
    filename (str): optional filename to write latex
    reverse_bits (bool): When set to True reverse the bit order inside
        registers for the output visualization.
    plot_barriers (bool): Enable/disable drawing barriers in the output
        circuit. Defaults to True.
    justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
        the circuit should be justified.
    idle_wires (bool): Include idle wires. Default is True.
    with_layout (bool): Include layout information, with labels on the physical
        layout. Default: True
    initial_state (bool): Optional. Adds |0> in the beginning of the line.
        Default: `False`.
    cregbundle (bool): Optional. If set True, bundle classical registers.
    wire_order (list): Optional. A list of integers used to reorder the display
        of the bits. The list must have an entry for every bit with the bits
        in the range 0 to (num_qubits + num_clbits).

Returns:
    str: Latex string appropriate for writing to file.
)r-   r/   r1   r5   )r:   r-   r.   r4   r%   r2   r$   wN)r   r^   _latexQCircuitImager   r{   r|   )r$   r,   r9   r:   r-   r.   r/   r1   r2   r4   r%   r5   rd   r"   re   qcimgr   
latex_files                     r)   rM   rM   V  s    P #<<!FE   !##E KKME(C JU# ! L5L !  Ls   A;;
B
c                    [         R                  " U UUUUUS9u  nnnU	c  Sn	[        R                  " UUUU UUUUU	U
UUUUUS9nUR	                  U5      $ )a3	  Draw a quantum circuit based on matplotlib.
If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.

Args:
    circuit (QuantumCircuit): a quantum circuit
    scale (float): scaling factor
    filename (str): file path to save image to
    style (dict or str): dictionary of style or file name of style file
    reverse_bits (bool): When set to True, reverse the bit order inside
        registers for the output visualization.
    plot_barriers (bool): Enable/disable drawing barriers in the output
        circuit. Defaults to True.
    justify (str): `left`, `right` or `none`. Defaults to `left`. Says how
        the circuit should be justified.
    idle_wires (bool): Include idle wires. Default is True.
    with_layout (bool): Include layout information, with labels on the physical
        layout. Default: True.
    fold (int): Number of vertical layers allowed 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.
    initial_state (bool): Optional. Adds |0> in the beginning of the line.
        Default: `False`.
    cregbundle (bool): Optional. If set True bundle classical registers.
        Default: ``True``.
    wire_order (list): Optional. A list of integers used to reorder the display
        of the bits. The list must have an entry for every bit with the bits
        in the range 0 to (num_qubits + num_clbits).
    expr_len (int): Optional. The number of characters to display if an :class:`~.expr.Expr`
        is used for the condition in a :class:`.ControlFlowOp`. If this number is exceeded,
        the string will be truncated at that number and '...' added to the end.
    measure_arrows: If True, draw an arrow from each measure box down the the classical bit
        or register where the measure value is placed. If False, do not draw arrow, but
        instead place the name of the bit or register in the measure box.

Returns:
    matplotlib.figure: a matplotlib figure object for the circuit diagram
        if the ``ax`` kwarg is not set.
r\      )r9   r:   r-   r.   r3   r<   r4   r%   r2   r6   r7   )r   r^   _matplotlibMatplotlibDrawerdraw)r$   r9   r,   r:   r.   r-   r/   r1   r2   r3   r<   r4   r%   r5   r6   r7   rd   r"   re   qcds                       r)   rN   rN     s    x #<<!%FFE |

&
&!##%C" 88Hr+   )NNNNFTNNmediumNTNNFNN   N)&r$   r   r9   zfloat | Noner,   
str | Noner:   zdict | str | NonerP   r   rQ   boolr.   r   r-   bool | Noner/   r   r0   r   r1   zbool | str | Noner2   r   r3   z
int | Noner<   z
Any | Noner4   r   r%   r   r5   zlist[int] | Noner6   intr7   r   )NFTNhighTTNTNNNr   T)ffffff?NNTFNTTFNN)Nr   NFTNTTFNN)NNNTFNTTNNFNNr   N)/__doc__
__future__r   loggingrr   r   ru   rp   typingwarningsr   qiskitr   qiskit.circuitr   r   qiskit.utilsr   r@   
exceptionsr
   utilsr   r    r   r   r   r   r   r   r_   TYPE_CHECKINGr   r   	getLogger__name__r}   r   rK   HAS_PDFLATEXrequire_in_callHAS_PDFTOCAIROHAS_PILrL   rM   rN    r+   r)   <module>r      s   #  	       1 0 + '   ' 	- 
		8	$
 # $'/$( "#'"&+  	
      % "    	!" #$ %& !'( )*  +R
 	Uz (()@A**+BC##$;< 
t = D Btr 

AV 
	!Xr+   