
    z	i.G                         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JrJ	r	J
r
  SSKJr  SSKJr  SSKJr  SSKJr  \R&                  " \5      r " S	 S
\5      rS r " S S\5      rg)zNVF2PostLayout pass to find a layout after transpile using subgraph isomorphism    )EnumN)	PyDiGraphvf2_mappingPyGraph)Layout)AnalysisPass)TranspilerError)	vf2_utilsc                   (    \ rS rSrSrSrSrSrSrSr	g)	VF2PostLayoutStopReason    z$Stop reasons for VF2PostLayout pass.zsolution foundzno better solution foundznonexistent solutionz>2q gates in basis N)
__name__
__module____qualname____firstlineno____doc__SOLUTION_FOUNDNO_BETTER_SOLUTION_FOUNDNO_SOLUTION_FOUNDMORE_THAN_2Q__static_attributes__r       i/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/transpiler/passes/layout/vf2_post_layout.pyr   r       s    .%N9.'Lr   r   c                     [        U [        5      (       a  U R                  UR                  5       5      $ [        U 5      R	                  U5      $ )N)
isinstanceset
issupersetkeysissubset)node_anode_bs     r   _target_matchr#   )   s?     &#  // 6{##F++r   c                   H   ^  \ rS rSrSr      SU 4S jjrS rS rSrU =r	$ )VF2PostLayout4   aM
  A pass for improving an existing Layout after transpilation of a circuit onto a
Coupling graph, as a subgraph isomorphism problem, solved by VF2++.

Unlike the :class:`~.VF2Layout` transpiler pass which is designed to find an
initial layout for a circuit early in the transpilation pipeline this transpiler
pass is designed to try and find a better layout after transpilation is complete.
The initial layout phase of the transpiler doesn't have as much information available
as we do after transpilation. This pass is designed to be paired in a similar pipeline
as the layout passes. This pass will strip any idle wires from the circuit, use VF2
to find a subgraph in the coupling graph for the circuit to run on with better fidelity
and then update the circuit layout to use the new qubits. The algorithm used in this
pass is described in `arXiv:2209.15512 <https://arxiv.org/abs/2209.15512>`__.

If a solution is found that means there is a lower error layout available for the
circuit. If a solution is found the layout will be set in the property set as
``property_set['post_layout']``. However, if no solution or no better solution is found, no
``property_set['post_layout']`` is set. The stopping reason is
set in ``property_set['VF2PostLayout_stop_reason']`` in all the cases and will be
one of the values enumerated in ``VF2PostLayoutStopReason`` which has the
following values:

    * ``"solution found"``: If a solution was found.
    * ``"no better solution found"``: If the initial layout of the circuit is the best solution.
    * ``"nonexistent solution"``: If no solution was found.
    * ``">2q gates in basis"``: If VF2PostLayout can't work with the basis of the circuit.

By default, this pass will construct a heuristic scoring map based on
the error rates in the provided ``target``. However, analysis passes can be run prior to this pass
and set ``vf2_avg_error_map`` in the property set with a :class:`~.ErrorMap`
instance. If a value is ``NaN`` that is treated as an ideal edge
For example if an error map is created as::

    from qiskit.transpiler.passes.layout.vf2_utils import ErrorMap

    error_map = ErrorMap(3)
    error_map.add_error((0, 0), 0.0024)
    error_map.add_error((0, 1), 0.01)
    error_map.add_error((1, 1), 0.0032)

that represents the error map for a 2 qubit target, where the avg 1q error
rate is ``0.0024`` on qubit 0 and ``0.0032`` on qubit 1. Then the avg 2q
error rate for gates that operate on (0, 1) is 0.01 and (1, 0) is not
supported by the target. This will be used for scoring if it's set as the
``vf2_avg_error_map`` key in the property set when :class:`~.VF2PostLayout`
is run.
c                 x   > [         TU ]  5         Xl        X0l        X@l        X`l        X l        XPl        SU l        g)a   Initialize a ``VF2PostLayout`` pass instance

Args:
    target (Target): A target representing the backend device to run ``VF2PostLayout`` on.
    seed (int): Sets the seed of the PRNG. -1 Means no node shuffling.
    call_limit (int): The number of state visits to attempt in each execution of
        VF2.
    time_limit (float): The total time limit in seconds to run ``VF2PostLayout``
    strict_direction (bool): Whether the pass is configured to follow
        the strict direction in the coupling graph. If this is set to
        false, the pass will treat any edge in the coupling graph as
        a weak edge and the interaction graph will be undirected. For
        the purposes of evaluating layouts the avg error rate for
        each qubit and 2q link will be used. This enables the pass to be
        run prior to basis translation and work with any 1q and 2q operations.
        However, if ``strict_direction=True`` the pass expects the input
        :class:`~.DAGCircuit` object to :meth:`~.VF2PostLayout.run` to be in
        the target set of instructions.
    max_trials (int): The maximum number of trials to run VF2 to find
        a layout. A value of ``0`` (the default) means 'unlimited'.

Raises:
    TypeError: At runtime, if ``target`` isn't provided.
N)	super__init__target
call_limit
time_limit
max_trialsseedstrict_directionavg_error_map)selfr*   r.   r+   r,   r/   r-   	__class__s          r   r)   VF2PostLayout.__init__d   s8    B 	$$$	 0!r   c                 Z   U R                   c  [        S5      eU R                  (       dG  U R                  S   U l        U R                  c&  [
        R                  " U R                   S5      U l        [
        R                  " XR                  5      nUc  [        R                  U R                  S'   gUu  p4pVU R                  (       aD  U(       a=  [        U5      S:  a  [        R                  U R                  S'   gUR                  5         [
        R                  " X45      n[
        R                  " U5      nU R                   R                  c  gU R                  (       a
  [!        SS9n	O	[#        SS9n	Sn
SU R                   R                  ;   a  / / S.n
U R                   R%                  S5       H  nU R                   R'                  U5      n[(        R*                  " U5      (       a*  U
S   R-                  U5        U
S	   R-                  U5        Mc  UR.                  nX;   d  Mv  X   R-                  U5        M     / n[1        U R                   R.                  5       HQ  n [3        U R                   R%                  U45      5      nU
b  UR7                  U
S   5        UR-                  U5        MS     U	R9                  U5        U R                   R                   Hj  n[        U5      nUS	:X  d  M  [3        U R                   R%                  U5      5      nU
b  UR7                  U
S	   5        U	R;                  US
   US   U5        Ml     [=        U	R?                  5       5      nU R                  (       d  [3        [@        RB                  RE                  U R                   R                  5      5      n[3        U	RG                  5       5      RI                  U5      nU(       a  U	RK                  [=        U5      5        [L        RO                  S5        U R                   (       a4  U R                  (       a#  [Q        U	U[R        [R        SSSU RT                  S9nO[Q        U	USSSU RT                  S9nSn U R                  (       aJ  [W        [Y        URZ                  5       VVs0 s H	  u  nnUU_M     snn5      nU R]                  UUUU5      nOe[Y        URZ                  5       VVs0 s H  u  nnUU;   d  M  UU   U_M     nnn[
        R^                  " U R                  UUUUU R                  UUS9nUn[        R                  n[L        RO                  SU5        [b        Rb                  " 5       nS
nU GH  n US-  n[L        RO                  SU5        U Re                  5        V!V"s0 s H  u  n!n"U"UU!   _M     n#n!n"U R                  (       aG  [W        U#Re                  5        V$V%s0 s H  u  n$n%UU$   U%_M     sn%n$5      n&U R]                  U&XEU5      n'O/[
        R^                  " U R                  U#UUUU R                  UUS9n'[L        RO                  SUU'5        U'U:  a`  [W        U#Re                  5        V$V%s0 s H  u  n$n%UU$   U%_M     sn%n$5      n&[L        RO                  SU&U'UU5        U&nU'n[        Rf                  nU Rh                  (       a3  UU Rh                  :  a#  [L        RO                  SUU Rh                  5          O`[b        Rb                  " 5       U-
  n(U Rj                  c  GM  U(U Rj                  :  d  GM  [L        RO                  SU(U Rj                  5          O   U[        Rf                  :X  Ga2  [
        Rl                  " UUU	Ro                  5       UU R                  5      nU R                  S   n)U)b  [        U)5      [        U5      :  a  URq                  5       n*[3        U*Rs                  5       5      n+[        U	5      nURZ                   Hc  n[        U5      [        U)5      :X  a    OJUU*;  d  M%  [1        U5       H/  nUU+;  d  M  U+Ru                  U5        URu                  UU5          Ma     Me     [
        Rv                  " XR                   U5      U R                  S'   OUc  [        R`                  nUU R                  S'   g! [4         a    [3        5       n GNWf = fs  snnf s  snnf ! [4         a     [        R`                  U R                  S'    gf = fs  sn"n!f s  sn%n$f s  sn%n$f )zrun the layout methodNz=A target must be specified or a coupling map must be providedvf2_avg_error_mapVF2PostLayout_stop_reason   F)
multigraph)r7      r9   r   z+Running VF2 to find post transpile mappingsT)node_matcheredge_matchersubgraphid_orderinducedr+   )r<   r=   r>   r+   )	edge_listbit_listzInitial layout has score %szRunning trial: %szTrial %s has score %szAFound layout %s has a lower score (%s) than previous best %s (%s)z'Trial %s is >= configured max trials %sz?VFPostLayout has taken %s which exceeds configured max time: %slayoutpost_layout)<r*   r	   r/   property_setr0   r
   build_average_error_mapbuild_interaction_graphr   r   lenr   clearbuild_bit_listbuild_edge_listqargsr   r   operation_names_for_qargsoperation_for_nameinspectisclassappend
num_qubitsranger   KeyErrorupdateadd_nodes_fromadd_edgelistnode_indexes	itertoolschainfrom_iterablenode_indices
differenceremove_nodes_fromloggerdebugr   r#   r+   r   	enumeratequbits_score_layoutscore_layoutr   timeitemsr   r-   r,   map_free_qubits	num_nodesget_virtual_bitsvaluesaddallocate_idle_qubits),r1   dagresultim_graphim_graph_node_mapreverse_im_graph_node_map
free_nodesscoring_bit_listscoring_edge_listcm_graph
global_opsop	operationrP   op_namesientryrJ   len_argsopscm_nodeshas_operations	to_removemappingschosen_layoutindexbitinitial_layoutchosen_layout_scorestop_reason
start_timetrialsmappingcm_iim_ilayout_mappingkvrA   layout_scoreelapsed_timeexisting_layoutvirtual_bits	used_bitss,                                               r   runVF2PostLayout.run   s   ;;!"abb$$!%!2!23F!GD!!)%.%F%Ft{{TX%Y"2238M8MN>=T=a=aD9:MSJ%>  Z :"+DD !!"=> $33HP%55h? ;;$   E2H%0H
 
4;;$$$BJkk;;DA KK::2>	 ??9--qM((,qM((,!*!5!5J!/".55b9 B t{{--.ADKKAA1$GH %Z]+OOE" / 	)[[&&E5zH 1}$++??FG)JJz!}-!!%(E!Hc: ' --/0 $$ !>!>t{{?P?P!QRNH1134??OI**4	?;BC;;400"**??	H #??H  	$$!'iPSPZPZF[(\F[
seF[(\!]&*&8&8"%-	'# '0

&;"&;
s// 2%c*E1&;  "
 '0&<&<&&"%-))/-	'# +M1JJK 	24GHYY[
GaKFLL,f5EL]]_U_ztTdHTN2_NU$$AOAUAUAWXAWA.q114AWX  $11-(   )55&&"%-))/-	  LL0&,G11AOAUAUAWXAWA.q114AWX W !' !'&2#5DD6T__#<FPTP_P_`99;3L*|t/NU OO
 c  d 1@@@%55""$)""M #//9O*s?/Cc-FX/X,==? 3 3 56	 ]
::C=)S-AA,.!&z!2A 	1 )a 0 - 1 1#q 9 %	 "3	 & 09/M/M[[-0Dm, $5GG9D56O  f )]"$  	'99 9: 		 V Y& Ys[   "%c,.c. c"
*5c. c(0
c(:Ac. dd!1d'cc"c. .'ddc                    UR                  5       nSnU R                  GbT  UR                  5        H  u  pxXH   n	U	R                  5        Hj  u  pU R                  U
   c  M  S U R                  U
   ;  d  M,  U R                  U
   XW   4   nUc  MF  UR                  c  MU  USUR                  -
  U-  -  nMl     M     UR	                  5       R                  5        H  nXSUS         XSUS         4nUS   n	U	R                  5        Hg  u  pU R                  U
   c  M  S U R                  U
   ;  d  M,  U R                  U
   U   nUc  MC  UR                  c  MR  USUR                  -
  U-  -  nMi     M     SU-
  $ )Nr7   r   r9   )rh   r*   re   erroredge_index_mapri   )r1   rA   bit_mapreverse_bit_maprn   bitsfidelityr   
node_indexgate_countsgatecountpropsedgerJ   s                  r   rb   VF2PostLayout._score_layouts  so   &&(;;"#*==?&2#.#4#4#6KD{{4(4T[[QUEV9V $D 149, ? ,1H$U[[U(BBH	 $7 $3 !//188:d1g67dSTg>V9WX"1g#.#4#4#6KD{{4(4T[[QUEV9V $D 1% 8 ,1H$U[[U(BBH	 $7 ; 8|r   )r0   r+   r-   r.   r/   r*   r,   )NNNNTr   )
r   r   r   r   r   r)   r   rb   r   __classcell__)r2   s   @r   r%   r%   4   s5    -b ("TcEJ r   r%   )r   enumr   loggingrM   rX   rd   	rustworkxr   r   r   qiskit.transpiler.layoutr   qiskit.transpiler.basepassesr   qiskit.transpiler.exceptionsr	   qiskit.transpiler.passes.layoutr
   	getLoggerr   r^   r   r#   r%   r   r   r   <module>r      s]    U      5 5 + 5 8 5 
		8	$(d (,SL Sr   