
    z	iL                       S r SSKJr  SSKrSSKrSSKrSSKJrJrJ	r	  SSK
Jr  SSKJrJrJr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#  SSK$J%r%  \" S\\\   \4   S9r& " S S\5      r' " S S\'5      r(S r)\RT                  " \'\RV                  S9 H0  u  r,r-\,R]                  S5      (       a  M  \)" \-5      r/\0" \'\,\/5        M2     SS jr1g)FManager for a set of Passes and their scheduling during transpilation.    )annotationsN)IteratorIterableCallablewraps)UnionListAnyTypeVar)QuantumCircuit)circuit_to_dagdag_to_circuit)
DAGCircuit)BasePassManager)Task)FlowControllerLinear)PassManagerError   )BasePass)TranspilerError)TranspileLayout
_CircuitsT)boundc                     ^  \ rS rSrSr  S   SU 4S jjjr    SS jr      SS jr    SU 4S jjr      SU 4S jjr	   SS	S
.           SU 4S jjjjr
SS jrSrU =r$ )PassManager%   r    c                "   > [         TU ]  UUS9  g)zInitialize an empty pass manager object.

Args:
    passes: A pass set to be added to the pass manager schedule.
    max_iteration: The maximum number of iterations the schedule will be looped if the
        condition is not met.
)tasksmax_iterationN)super__init__)selfpassesr"   	__class__s      W/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/transpiler/passmanager.pyr$   PassManager.__init__(   s     	' 	 	
    c                    [        UR                  5       VVs0 s H  u  p4XC_M	     snnU R                  S'   UR                  U R                  S'   [	        USS9$ s  snnf )Noriginal_qubit_indicesnum_input_qubitsTcopy_operations)	enumeratequbitsproperty_set
num_qubitsr   )r%   input_programkwargsibits        r(   _passmanager_frontend!PassManager._passmanager_frontend9   sd     "+=+?+?!@7
!@vqCF!@7
23 1>0H0H,-mTBB	7
s   Ac                   [        USS9nUR                  SS 5      =nb  XTl        [        R                  " XR
                  5      =n b!  Xdl        UR                  U R
                  5        U R
                  S   Ul        U R
                  S   Ul	        U R
                  S   (       aA  / nU R
                  S   nUR                  5        H  n	UR                  X   5        M     Xtl        U$ )NFr.   output_nameclbit_write_latencyconditional_latencynode_start_time)r   getnamer   from_property_setr2   _layoutwrite_into_property_set_clbit_write_latency_conditional_latencytopological_op_nodesappend_op_start_times)
r%   passmanager_ir
in_programr5   out_programout_namelayouttopological_start_timesstart_timesdag_nodes
             r(   _passmanager_backend PassManager._passmanager_backendD   s     %^UK

=$77HD' &77HYHYZZF #)**4+<+<=+/+<+<=R+S(+/+<+<=R+S(./ ')#++,=>K*??A'..{/DE B*A'r*   c                    > [         TU ]  US9  g)zAppend a Pass Set to the schedule of passes.

Args:
    passes: A set of transpiler passes to be added to schedule.

Raises:
    TranspilerError: if a pass in passes is not a proper pass.
r!   N)r#   rG   )r%   r&   r'   s     r(   rG   PassManager.appendc   s     	V$r*   c                    > [         TU ]  XS9  g)zReplace a particular pass in the scheduler.

Args:
    index: Pass index to replace, based on the position in passes().
    passes: A pass set to be added to the pass manager schedule.
rT   N)r#   replace)r%   indexr&   r'   s      r(   rW   PassManager.replaceq   s     	,r*   Nr2   c               B   > Ub  [        U5      n[        TU ]	  UUUUUS9$ )aQ
  Run all the passes on the specified ``circuits``.

Args:
    circuits: Circuit(s) to transform via all the registered passes.
    output_name: The output circuit name. If ``None``, it will be set to the same as the
        input circuit name.
    callback: 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

        .. note::

            Beware that the keyword arguments here are different to those used by the
            generic :class:`.BasePassManager`.  This pass manager will translate those
            arguments into the form described above.

        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']
                ...

        .. note::

            When running transpilation with multi-processing,
            the callback function is invoked within the context
            of each sub-process, independently of the
            parent process.

    num_processes: The maximum number of parallel processes to launch if parallel
        execution is enabled. This argument overrides ``num_processes`` in the user
        configuration file, and the ``QISKIT_NUM_PROCS`` environment variable. If set
        to ``None`` the system default or local user configuration will be used.
    property_set: If given, the initial value to use as the :class:`.PropertySet` for the
        pass manager pipeline.  This can be used to persist analysis from one run to
        another, in cases where you know the analysis is safe to share.  Beware that some
        analysis will be specific to the input circuit and the particular :class:`.Target`,
        so you should take a lot of care when using this argument.

Returns:
    The transformed circuit(s).
)in_programscallbackr;   num_processesr2   )_legacy_style_callbackr#   runr%   circuitsr;   r]   r^   r2   r'   s         r(   r`   PassManager.run   s;    F -h7Hw{ #'%  
 	
r*   c                    SSK Jn  U" XX#S9$ )a  Draw the pass manager.

This function needs `pydot <https://github.com/erocarrera/pydot>`__, which in turn needs
`Graphviz <https://www.graphviz.org/>`__ to be installed.

Args:
    filename (str): file path to save image to.
    style (dict): keys are the pass classes and the values are the colors to make them. An
        example can be seen in the DEFAULT_STYLE. An ordered dict can be used to ensure
        a priority coloring when pass falls into multiple categories. Any values not
        included in the provided dict will be filled in from the default dict.
    raw (bool): If ``True``, save the raw Dot output instead of the image.

Returns:
    Optional[PassManager]: an in-memory representation of the pass manager, or ``None``
    if no image was generated or `Pillow <https://pypi.org/project/Pillow/>`__
    is not installed.

Raises:
    ImportError: when nxpd or pydot not installed.
r   )pass_manager_drawerfilenamestyleraw)qiskit.visualizationre   )r%   rg   rh   ri   re   s        r(   drawPassManager.draw   s    , 	="4%QQr*   )r   i  )r&   Task | list[Task]r"   int)r4   r   returnr   )rI   r   rJ   r   ro   r   r&   rm   ro   None)rX   rn   r&   rm   ro   rq   NNN)rb   r   r;   
str | Noner]   r   r^   rn   r2   dict[str, object] | Nonero   r   NNF)__name__
__module____qualname____firstlineno____doc__r$   r8   rQ   rG   rW   r`   rk   __static_attributes____classcell__r'   s   @r(   r   r   %   s   P %'!
!
 
 
"	C%	C 
		C" #
 
>%!% 
%-- "- 
	-" #'!!L
 26L
L
  L
 	L

 L
 /L
 
L
 L
\R Rr*   r   c                  V  ^  \ rS rSrSr\R                  " S5      rSSU 4S jjjrSS jr	SS jr
\SS j5       r\SS	 j5       rSS
 jrSS jrU 4S jr    S S jr      S!S jrS"S jrS rU 4S jrS rS r   S#SS.           S$U 4S jjjjrS%U 4S jjrS&S jrSrU =r$ )'StagedPassManager   a
  A pass manager pipeline built from individual stages.

This class enables building a compilation pipeline out of fixed stages.
Each ``StagedPassManager`` defines a list of stages which are executed in
a fixed order, and each stage is defined as a standalone :class:`~.PassManager`
instance. There are also ``pre_`` and ``post_`` stages for each defined stage.
This enables easily composing and replacing different stages and also adding
hook points to enable programmatic modifications to a pipeline. When using a staged
pass manager you are not able to modify the individual passes and are only able
to modify stages.

By default, instances of ``StagedPassManager`` define a typical full compilation
pipeline from an abstract virtual circuit to one that is optimized and
capable of running on the specified backend. The default pre-defined stages are:

#. ``init`` - Initial passes to run before embedding the circuit to the backend.
#. ``layout`` - Maps the virtual qubits in the circuit to the physical qubits on
   the backend.
#. ``routing`` - Inserts gates as needed to move the qubit states around until
   the circuit can be run with the chosen layout on the backend's coupling map.
#. ``translation`` - Translates the gates in the circuit to the target backend's
   basis gate set.
#. ``optimization`` - Optimizes the circuit to reduce the cost of executing it.
   These passes will typically run in a loop until a convergence criteria is met.
   For example, the convergence criteria might be that the circuit depth does not
   decrease in successive iterations.
#. ``scheduling`` - Hardware-aware passes that schedule the operations in the
   circuit.

.. note::

    For backwards compatibility the relative positioning of these default
    stages will remain stable moving forward. However, new stages may be
    added to the default stage list in between current stages. For example,
    in a future release a new phase, something like ``logical_optimization``, could be added
    immediately after the existing ``init`` stage in the default stage list.
    This would preserve compatibility for pre-existing ``StagedPassManager``
    users as the relative positions of the stage are preserved so the behavior
    will not change between releases.

These stages will be executed in order and any stage set to ``None`` will be skipped.
If a stage is provided multiple times (i.e. at diferent relative positions), the
associated passes, including pre and post, will run once per declaration.
If a :class:`~qiskit.transpiler.PassManager` input is being used for more than 1 stage here
(for example in the case of a :class:`~.Pass` that covers both Layout and Routing) you will
want to set that to the earliest stage in sequence that it covers.
z>\s|\+|\-|\*|\/|\\|\%|\<|\>|\@|\!|\~|\^|\&|\:|\[|\]|\{|\}|\(|\)Nc                t  > U=(       d    / SQnU R                  U5        [        TU ]	  S[        U5      5        [        TU ]	  S[        U R	                  5       5      5        [        TU ]  5         U R                  U5        [        U R                  5       H!  nUR                  US5      n[        XU5        M#     g)a  Initialize a new StagedPassManager object

Args:
    stages (Iterable[str]): An optional list of stages to use for this
        instance. If this is not specified the default stages list
        ``['init', 'layout', 'routing', 'translation', 'optimization', 'scheduling']`` is
        used. After instantiation, the final list will be immutable and stored as tuple.
        If a stage is provided multiple times (i.e. at diferent relative positions), the
        associated passes, including pre and post, will run once per declaration.
    kwargs: The initial :class:`~.PassManager` values for any stages
        defined in ``stages``. If a argument is not defined the
        stages will default to ``None`` indicating an empty/undefined
        stage.

Raises:
    AttributeError: If a stage in the input keyword arguments is not defined.
    ValueError: If an invalid stage name is specified.
)initrM   routingtranslationoptimization
scheduling_stages_expanded_stagesN)_validate_stagesr#   __setattr__tuple_generate_expanded_stagesr$   _validate_init_kwargssetexpanded_stagesr?   setattr)r%   stagesr5   stagepmr'   s        r(   r$   StagedPassManager.__init__  s    &  
 
 	f%IuV}5.d6T6T6V0WX""6*--.EE4(BD$ /r*   c                h   U Vs/ s H"  o R                   R                  U5      c  M   UPM$     nnU(       af  [        R                  " 5        nUR	                  SUS    35        USS   H  nUR	                  SU 35        M     [        UR                  5       5      eg s  snf ! , (       d  f       g = f)Nz)The following stage names are not valid: r   r   z, )invalid_stage_regexsearchioStringIOwrite
ValueErrorgetvalue)r%   r   r   invalid_stagesmsginvalid_stages         r(   r   "StagedPassManager._validate_stagesB  s    %
%e)A)A)H)H)OEv 	 
 #		EnUVFWEXYZ%3AB%7MII=/23 &8 00 
 s   BBAB##
B1c                    [        U R                  5      nUR                  5        H  nX2;  d  M
  [        U S35      e   g )Nz is not a valid stage.)r   r   keysAttributeError)r%   r5   r   r   s       r(   r   'StagedPassManager._validate_init_kwargsM  s;    d223[[]E+$w.D%EFF #r*   c                    U R                   $ )zPass manager stages)r   r%   s    r(   r   StagedPassManager.stagesS  s     ||r*   c                    U R                   $ )zEExpanded Pass manager stages including ``pre_`` and ``post_`` phases.)r   r   s    r(   r   !StagedPassManager.expanded_stagesX  s     $$$r*   c              #  V   #    U R                    H  nSU-   v   Uv   SU-   v   M     g 7f)Npre_post_)r   )r%   r   s     r(   r   +StagedPassManager._generate_expanded_stages]  s,     [[E5. KE/! !s   ')c                    / U l         U R                   H3  n[        XS 5      nUc  M  U =R                   UR                   -  sl         M5     g N)_tasksr   getattr)r%   r   r   s      r(   _update_passmanager%StagedPassManager._update_passmanagerc  s<    ))Ed+B~ryy( *r*   c                   > X :X  a  XR                   ;   a  [        S5      e[        TU ]  X5        XR                   ;   a  U R	                  5         g g )Nz5Recursive definition of StagedPassManager disallowed.)r   r   r#   r   r   )r%   attrvaluer'   s      r(   r   StagedPassManager.__setattr__j  sI    =T%9%99!"YZZD('''$$& (r*   c                    [         er   NotImplementedError)r%   r&   s     r(   rG   StagedPassManager.appendq  s
     "!r*   c                    [         er   r   )r%   rX   r&   s      r(   rW   StagedPassManager.replacew  s
    
 "!r*   c                    [         er   r   )r%   rX   s     r(   removeStagedPassManager.remove      !!r*   c                t    U R                  5         [        U R                  S9nU R                  U   Ul        U$ )N)r"   )r   r   r"   r   )r%   rX   new_passmanagers      r(   __getitem__StagedPassManager.__getitem__  s7      " &D4F4FG!%U!3r*   c                @   > U R                  5         [        TU ]	  5       $ r   )r   r#   __len__r%   r'   s    r(   r   StagedPassManager.__len__  s      "w  r*   c                    [         er   r   )r%   rX   items      r(   __setitem__StagedPassManager.__setitem__  r   r*   c                    [         er   r   )r%   others     r(   __add__StagedPassManager.__add__  r   r*   rZ   c               @   > U R                  5         [        TU ]	  XX4S9$ )N)r^   )r   r#   r`   ra   s         r(   r`   StagedPassManager.run  s$     	  "w{8({XXr*   c                @   > U R                  5         [        TU ]	  5       $ r   )r   r#   to_flow_controllerr   s    r(   r   $StagedPassManager.to_flow_controller  s      "w)++r*   c                    SSK Jn  U" XX#S9$ )zDraw the staged pass manager.r   )staged_pass_manager_drawerrf   )rj   r   )r%   rg   rh   ri   r   s        r(   rk   StagedPassManager.draw  s    C)$XXr*   )r   r   )r   zIterable[str] | Nonero   rq   )r   zIterable[str]ro   rq   )r5   zdict[str, Any]ro   rq   )ro   ztuple[str, ...])ro   zIterator[str])ro   rq   rp   )rX   rn   r&   zBasePass | list[BasePass]ro   rq   )rX   rn   ro   rq   rr   )rb   r   r;   rs   r]   zCallable | Noner^   rn   r2   rt   ro   r   )ro   r   ru   )rv   rw   rx   ry   rz   recompiler   r$   r   r   propertyr   r   r   r   r   rG   rW   r   r   r   r   r   r`   r   rk   r{   r|   r}   s   @r(   r   r      s.   .` **I#% #%J	1G   % %")'"!" 
""" *" 
	""!"" #'$(!
Y 26
Y
Y  
Y "	
Y
 
Y /
Y 

Y 
Y,Y Yr*   r   c                0   ^  [        T 5      U 4S j5       nU$ )Nc                 z   >  T" U 0 UD6$ ! [          a    e [         a  n[        UR                  5      UeS nAff = fr   )r   r   message)	meth_argsmeth_kwargsexmeths      r(   wrapper_replace_error.<locals>.wrapper  sD    	62k22 	 	6!"**-25	6s    :5:r   )r   r   s   ` r(   _replace_errorr     s     
4[6 6 Nr*   )	predicate_c                   ^  U 4S jnU$ )Nc                   > T" U UUUUS9  g )N)pass_dagtimer2   countr   )taskrI   r2   running_timer   r]   s        r(   _wrapped_callable1_legacy_style_callback.<locals>._wrapped_callable  s    %	
r*   r   )r]   r   s   ` r(   r_   r_     s    
 r*   )r]   r   )2rz   
__future__r   inspectr   r   collections.abcr   r   r   	functoolsr	   typingr
   r   r   r   qiskit.circuitr   qiskit.convertersr   r   qiskit.dagcircuitr   qiskit.passmanager.passmanagerr   qiskit.passmanager.base_tasksr   #qiskit.passmanager.flow_controllersr   qiskit.passmanager.exceptionsr   
basepassesr   
exceptionsr   rM   r   r   r   r   r   
getmembers
isfunction_name_method
startswith_wrappedr   r_   r   r*   r(   <module>r     s    M "  	 	 8 8  , , ) < ( : . D :   ' #\tN/C^/S)TU
@R/ @RFAY AYT ((@R@RSNE7 	g&HK) T
r*   