§
    º³Ùg±n  ã                  ó¦   — d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
mZ ddlmZ ddlmZ  G d	„ d
¦  «        Ze G d„ d¦  «        ¦   «         ZdS )zå
A two-ways dict to represent a layout.

Layout is the relation between virtual (qu)bits and physical (qu)bits.
Virtual (qu)bits are tuples, e.g. `(QuantumRegister(3, 'qr'), 2)` or simply `qr[2]`.
Physical (qu)bits are integers.
é    )Úannotations)ÚList)Ú	dataclass)Úcircuit)ÚQubitÚQuantumRegister)ÚLayoutError©Úisinstanceintc                  óþ   — e Zd ZdZdZd%d„Zd„ Zd„ Zed„ ¦   «         Z	d„ Z
d	„ Zd
„ Zd„ Zd„ Zd„ Zd„ Zd„ Zd%d„Zd„ Zd„ Zd„ Zd„ Zd„ Zd„ Zd&d„Zed„ ¦   «         Zed„ ¦   «         Zed„ ¦   «         Zd'd „Zd(d#„Zd)d$„ZdS )*ÚLayoutz$Two-ways dict to represent a Layout.)Ú_regsÚ_p2vÚ_v2pNc                óª   — g | _         i | _        i | _        |�;t          |t          ¦  «        st          d¦  «        ‚|                      |¦  «         dS dS )zaconstruct a Layout from a bijective dictionary, mapping
        virtual qubits to physical qubitsNzLayout constructor takes a dict)r   r   r   Ú
isinstanceÚdictr	   Ú	from_dict)ÚselfÚ
input_dicts     úN/granary/edev/quantum/lib/python3.11/site-packages/qiskit/transpiler/layout.pyÚ__init__zLayout.__init__#   sa   € ð ˆŒ
ØˆŒ	ØˆŒ	ØÐ!Ý˜j­$Ñ/Ô/ð EÝ!Ð"CÑDÔDÐDØ�NŠN˜:Ñ&Ô&Ð&Ð&Ð&ð "Ð!ó    c                óÚ   — g }| j                              ¦   «         D ] \  }}|                     |› d|› d�¦  «         Œ!|r|d         dd…         |d<   dd                     |¦  «        z   dz   S )zRepresentation of a Layoutz: ú,éÿÿÿÿNz	Layout({
ú
z
}))r   ÚitemsÚappendÚjoin)r   Ústr_listÚkeyÚvals       r   Ú__repr__zLayout.__repr__.   s†   € àˆØœ	ŸšÑ)Ô)ð 	.ð 	.‰HˆC�Ø�OŠO˜sÐ,Ð, cÐ,Ð,Ð,Ñ-Ô-Ð-Ð-Øð 	-Ø# Bœ<¨¨¨Ô,ˆH�R‰LØ˜dŸiši¨Ñ1Ô1Ñ1°FÑ:Ð:r   c                ó¤   — |                      ¦   «         D ]:\  }}t                               ||¦  «        \  }}|| j        |<   |€Œ0|| j        |<   Œ;dS )aÌ  Populates a Layout from a dictionary.

        The dictionary must be a bijective mapping between
        virtual qubits (tuple) and physical qubits (int).

        Args:
            input_dict (dict):
                e.g.::

                {(QuantumRegister(3, 'qr'), 0): 0,
                 (QuantumRegister(3, 'qr'), 1): 1,
                 (QuantumRegister(3, 'qr'), 2): 2}

                Can be written more concisely as follows:

                * virtual to physical::

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

                * physical to virtual::

                    {0: qr[0],
                     1: qr[1],
                     2: qr[2]}
        N)r   r   Úorder_based_on_typer   r   )r   r   r"   ÚvalueÚvirtualÚphysicals         r   r   zLayout.from_dict7   sj   € ð8 %×*Ò*Ñ,Ô,ð 	*ð 	*‰JˆC�Ý &× :Ò :¸3ÀÑ FÔ FÑˆG�XØ")ˆDŒI�hÑØˆØØ!)ˆDŒI�gÑÐð	*ð 	*r   c                ó~  — t          | ¦  «        r6t          |t          t          d¦  «        f¦  «        rt	          | ¦  «        }|}nut          |¦  «        r6t          | t          t          d¦  «        f¦  «        rt	          |¦  «        }| }n0t          dt          | ¦  «        › dt          |¦  «        › d�¦  «        ‚||fS )zTdecides which one is physical/virtual based on the type. Returns (virtual, physical)Nz	The map (z -> z7) has to be a (Bit -> integer) or the other way around.)r   r   r   ÚtypeÚintr	   )Úvalue1Úvalue2r)   r(   s       r   r&   zLayout.order_based_on_typeZ   sÍ   € õ ˜Ñ Ô ð 
	¥Z°½ÅÀTÁ
Ä
Ð8KÑ%LÔ%Lð 
	Ý˜6‘{”{ˆHØˆGˆGÝ˜6Ñ"Ô"ð 	¥z°&½5Å$ÀtÁ*Ä*Ð:MÑ'NÔ'Nð 	Ý˜6‘{”{ˆHØˆGˆGåð,�D ™LœLð ,ð ,­d°6©l¬lð ,ð ,ð ,ñô ð ð ˜Ð Ð r   c                ó€   — || j         v r| j         |         S || j        v r| j        |         S t          d|› d�¦  «        ‚)Nz	The item z does not exist in the Layout)r   r   ÚKeyError©r   Úitems     r   Ú__getitem__zLayout.__getitem__j   sN   € Ø�4”9ÐÐØ”9˜T”?Ð"Ø�4”9ÐÐØ”9˜T”?Ð"ÝÐF 4ÐFÐFÐFÑGÔGÐGr   c                ó&   — || j         v p|| j        v S ©N)r   r   r1   s     r   Ú__contains__zLayout.__contains__q   s   € Ø�t”yÐ Ð5 D¨D¬IÐ$5Ð5r   c                ón   — t                                ||¦  «        \  }}|                      ||¦  «         d S r5   )r   r&   Ú_set_type_checked_item)r   r"   r'   r(   r)   s        r   Ú__setitem__zLayout.__setitem__t   s8   € Ý"×6Ò6°s¸EÑBÔBÑˆ�Ø×#Ò# G¨XÑ6Ô6Ð6Ð6Ð6r   c                ó  — | j                              |d ¦  «        }| j                             |d ¦  «         | j                             |d ¦  «        }| j                              |d ¦  «         || j        |<   |�|| j         |<   d S d S r5   )r   Úpopr   )r   r(   r)   Úolds       r   r8   zLayout._set_type_checked_itemx   s„   € ØŒi�mŠm˜G TÑ*Ô*ˆØŒ	�Š�c˜4Ñ Ô Ð ØŒi�mŠm˜H dÑ+Ô+ˆØŒ	�Š�c˜4Ñ Ô Ð à%ˆŒ	�(ÑØÐØ!)ˆDŒI�gÑÐÐð Ðr   c                ó
  — t          |t          ¦  «        r| j        | j        |         = | j        |= d S t          |t          ¦  «        r| j        | j        |         = | j        |= d S t          dt          |¦  «        › d�¦  «        ‚)Nz>The key to remove should be of the form Qubit or integer) and z was provided)r   r,   r   r   r   r	   r+   )r   r"   s     r   Ú__delitem__zLayout.__delitem__‚   s“   € Ý�c�3ÑÔð 
	Ø”	˜$œ) Cœ.Ð)Ø”	˜#���Ý˜�UÑ#Ô#ð 	Ø”	˜$œ) Cœ.Ð)Ø”	˜#���åðCÝ*.¨s©)¬)ðCð Cð Cñô ð r   c                ó*   — t          | j        ¦  «        S r5   )Úlenr   ©r   s    r   Ú__len__zLayout.__len__�   s   € Ý�4”9‰~Œ~Ðr   c                óp   — t          |t          ¦  «        r | j        |j        k    o| j        |j        k    S dS )NF)r   r   r   r   )r   Úothers     r   Ú__eq__zLayout.__eq__’   s7   € Ý�e�VÑ$Ô$ð 	GØ”9 ¤
Ò*ÐF¨t¬y¸E¼JÒ/FÐFØˆur   c                óè   —  t          | ¦  «        ¦   «         }| j                             ¦   «         |_        | j                             ¦   «         |_        | j                             ¦   «         |_        |S )z$Returns a copy of a Layout instance.)r+   r   Úcopyr   r   )r   Úlayout_copys     r   rG   zLayout.copy—   sU   € à •d˜4‘j”j‘l”lˆà œJŸOšOÑ-Ô-ˆÔØœ9Ÿ>š>Ñ+Ô+ˆÔØœ9Ÿ>š>Ñ+Ô+ˆÔàÐr   c                óº   — |€St          | j        ¦  «        dk    rd}n8t          | j        ¦  «        }t          |¦  «        D ]}|| j        vr|} nŒ|dz   }|| |<   dS )aC  
        Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not
        defined, `bit` will be mapped to a new physical bit.

        Args:
            virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'), 2).
            physical_bit (int): A physical bit. For example, 3.
        Nr   é   )r@   r   ÚmaxÚrange)r   Úvirtual_bitÚphysical_bitÚmax_physicalÚphysical_candidates        r   Úaddz
Layout.add¡   s�   € ð ÐÝ�4”9‰~Œ~ Ò"Ð"Ø ��å" 4¤9™~œ~�å*/°Ñ*=Ô*=ð 4ð 4Ð&Ø)°´Ð:Ð:Ø'9˜Ø˜ð ;ð
 $0°!Ñ#3�Là(ˆˆ[ÑÐÐr   c                óv   — | j                              |¦  «         |D ]}|| vr|                      |¦  «         ŒdS )z¨Adds at the end physical_qubits that map each bit in reg.

        Args:
            reg (Register): A (qu)bit Register. For example, QuantumRegister(3, 'qr').
        N)r   r   rQ   )r   ÚregÚbits      r   Úadd_registerzLayout.add_registerº   sL   € ð 	Œ
×Ò˜#ÑÔÐØð 	ð 	ˆCØ˜$ˆˆØ—’˜‘”�øð	ð 	r   c                ó*   — t          | j        ¦  «        S )z¯
        Returns the registers in the layout [QuantumRegister(2, 'qr0'), QuantumRegister(3, 'qr1')]
        Returns:
            Set: A set of Registers in the layout
        )Úsetr   rA   s    r   Úget_registerszLayout.get_registersÅ   s   € õ �4”:‰ŒÐr   c                ó   — | j         S )zz
        Returns the dictionary where the keys are virtual (qu)bits and the
        values are physical (qu)bits.
        )r   rA   s    r   Úget_virtual_bitszLayout.get_virtual_bitsÍ   ó   € ð
 ŒyÐr   c                ó   — | j         S )zz
        Returns the dictionary where the keys are physical (qu)bits and the
        values are virtual (qu)bits.
        )r   rA   s    r   Úget_physical_bitszLayout.get_physical_bitsÔ   r[   r   c                ó�   — t          |¦  «        t          |¦  «        urt          d¦  «        ‚| |         }| |         | |<   || |<   dS )a  Swaps the map between left and right.

        Args:
            left (tuple or int): Item to swap with right.
            right (tuple or int): Item to swap with left.
        Raises:
            LayoutError: If left and right have not the same type.
        z:The method swap only works with elements of the same type.N)r+   r	   )r   ÚleftÚrightÚtemps       r   ÚswapzLayout.swapÛ   sM   € õ �‰:Œ:�T %™[œ[Ð(Ð(ÝÐZÑ[Ô[Ð[Ø�DŒzˆØ˜%”[ˆˆT‰
ØˆˆU‰ˆˆr   c                óŽ   — i }| j                              ¦   «         D ](\  }}||j        vrt          d¦  «        ‚||         ||<   Œ)|S )aŒ  Combines self and another_layout into an "edge map".

        For example::

              self       another_layout  resulting edge map
           qr_1 -> 0        0 <- q_2         qr_1 -> q_2
           qr_2 -> 2        2 <- q_1         qr_2 -> q_1
           qr_3 -> 3        3 <- q_0         qr_3 -> q_0

        The edge map is used to compose dags via, for example, compose.

        Args:
            another_layout (Layout): The other layout to combine.
        Returns:
            dict: A "edge map".
        Raises:
            LayoutError: another_layout can be bigger than self, but not smaller.
                Otherwise, raises.
        zfThe wire_map_from_layouts() method does not support when the other layout (another_layout) is smaller.)r   r   r   r	   )r   Úanother_layoutÚedge_mapr(   r)   s        r   Úcombine_into_edge_mapzLayout.combine_into_edge_mapê   sh   € ð( ˆà!%¤§¢Ñ!2Ô!2ð 	9ð 	9ÑˆG�XØ˜~Ô2Ð2Ð2Ý!ðAñô ð ð !/¨xÔ 8ˆH�WÑÐàˆr   Úreturnú	list[int]c                óp   — dgt          |¦  «        z  }t          |¦  «        D ]\  }}| |         }|||<   Œ|S )a  Given an ordered list of bits, reorder them according to this layout.

        The list of bits must exactly match the virtual bits in this layout.

        Args:
            bits (list[Bit]): the bits to reorder.

        Returns:
            List: ordered bits.
        r   )r@   Ú	enumerate)r   ÚbitsÚorderÚiÚvÚjs         r   Úreorder_bitszLayout.reorder_bits
  sI   € ð �•c˜$‘i”i‘ˆõ ˜d‘O”Oð 	ð 	‰DˆAˆqØ�Q”ˆAØˆE�!‰HˆHàˆr   c                 ó¬   — t          ¦   «         }| D ]B}t          |t          ¦  «        r|                     |¦  «         Œ-|                     |¦  «         ŒC|S )a  Creates a trivial ("one-to-one") Layout with the registers and qubits in `regs`.

        Args:
            *regs (Registers, Qubits): registers and qubits to include in the layout.
        Returns:
            Layout: A layout with all the `regs` in the given order.
        )r   r   r   rU   rQ   )ÚregsÚlayoutrS   s      r   Úgenerate_trivial_layoutzLayout.generate_trivial_layout  s[   € õ ‘”ˆØð 	 ð 	 ˆCÝ˜#�Ñ/Ô/ð  Ø×#Ò# CÑ(Ô(Ð(Ð(à—
’
˜3‘”��Øˆr   c           	     ój  — t          d„ | D ¦   «         ¦  «        st          d¦  «        ‚t          | ¦  «        t          t          | ¦  «        ¦  «        k    rt          d¦  «        ‚t	          d„ |D ¦   «         ¦  «        }t          | ¦  «        |k    r&t          dt          | ¦  «        › d|› d| › d�¦  «        ‚t          ¦   «         }d	}|D ]D}t          |j        ¦  «        D ]}| |         |||         <   |d
z  }Œ|                     |¦  «         ŒE|t          | ¦  «        k    r| |d…         D ]}d||<   Œ|S )a»  Converts a list of integers to a Layout
        mapping virtual qubits (index of the list) to
        physical qubits (the list values).

        Args:
            int_list (list): A list of integers.
            *qregs (QuantumRegisters): The quantum registers to apply
                the layout to.
        Returns:
            Layout: The corresponding Layout object.
        Raises:
            LayoutError: Invalid input layout.
        c              3  ó4   K  — | ]}t          |¦  «        V — Œd S r5   r
   )Ú.0rm   s     r   ú	<genexpr>z&Layout.from_intlist.<locals>.<genexpr>>  s*   è è € Ð6Ð6¨•= Ñ#Ô#Ð6Ð6Ð6Ð6Ð6Ð6r   zExpected a list of intsú4Duplicate values not permitted; Layout is bijective.c              3  ó$   K  — | ]}|j         V — Œd S r5   )Úsize)rw   rS   s     r   rx   z&Layout.from_intlist.<locals>.<genexpr>B  s$   è è € Ð3Ð3 c˜œÐ3Ð3Ð3Ð3Ð3Ð3r   zInteger list length (z*) must equal number of qubits in circuit (z): ú.r   rJ   N)	Úallr	   r@   rW   Úsumr   rL   r{   rU   )Úint_listÚqregsÚ
num_qubitsÚoutÚmain_idxÚqregÚidxÚint_items           r   Úfrom_intlistzLayout.from_intlist/  sz  € õ Ð6Ð6¨XÐ6Ñ6Ô6Ñ6Ô6ð 	9ÝÐ7Ñ8Ô8Ð8Ýˆx‰=Œ=�C¥ H¡¤Ñ.Ô.Ò.Ð.ÝÐTÑUÔUÐUÝÐ3Ð3¨UÐ3Ñ3Ô3Ñ3Ô3ˆ
åˆx‰=Œ=˜JÒ&Ð&Ýð:­¨H©¬ð :ð :Ø)ð:ð :Ø.6ð:ð :ð :ñô ð õ ‰hŒhˆØˆØð 	#ð 	#ˆDÝ˜TœYÑ'Ô'ð ð �Ø!)¨(Ô!3��D˜”I‘Ø˜A‘��Ø×Ò˜TÑ"Ô"Ð"Ð"Ø•s˜8‘}”}Ò$Ð$Ø$ X Y YÔ/ð %ð %�Ø $��H‘�Øˆ
r   c                ó  — t          ¦   «         }t          | ¦  «        D ]I\  }}|€Œt          |t          ¦  «        r||j        v rt          d¦  «        ‚|||<   Œ;t          d¦  «        ‚|D ]}|                     |¦  «         Œ|S )a»  
        Populates a Layout from a list containing virtual
        qubits, Qubit or None.

        Args:
            qubit_list (list):
                e.g.: [qr[0], None, qr[2], qr[3]]
            *qregs (QuantumRegisters): The quantum registers to apply
                the layout to.
        Returns:
            Layout: the corresponding Layout object
        Raises:
            LayoutError: If the elements are not Qubit or None
        Nry   z9The list should contain elements of the Bits or NoneTypes)r   rj   r   r   r   r	   rU   )Ú
qubit_listr€   r‚   r)   r(   r„   s         r   Úfrom_qubit_listzLayout.from_qubit_listU  s§   € õ  ‰hŒhˆÝ!*¨:Ñ!6Ô!6ð 	_ð 	_ÑˆH�gØˆØÝ˜'¥5Ñ)Ô)ð _Ø˜cœhÐ&Ð&Ý%Ð&\Ñ]Ô]Ð]Ø'��G‘�å!Ð"]Ñ^Ô^Ð^Øð 	#ð 	#ˆDØ×Ò˜TÑ"Ô"Ð"Ð"Øˆ
r   rD   ÚqubitsúList[Qubit]c                ó”   ‡‡— |                      ¦   «         Št          ˆˆfd„| j                             ¦   «         D ¦   «         ¦  «        S )a#  Compose this layout with another layout.

        If this layout represents a mapping from the P-qubits to the positions of the Q-qubits,
        and the other layout represents a mapping from the Q-qubits to the positions of
        the R-qubits, then the composed layout represents a mapping from the P-qubits to the
        positions of the R-qubits.

        Args:
            other: The existing :class:`.Layout` to compose this :class:`.Layout` with.
            qubits: A list of :class:`.Qubit` objects over which ``other`` is defined,
                used to establish the correspondence between the positions of the ``other``
                qubits and the actual qubits.

        Returns:
            A new layout object the represents this layout composed with the ``other`` layout.
        c                ó4   •— i | ]\  }}|‰‰|                  “ŒS © r�   )rw   ÚvirtÚphysÚ	other_v2pr‹   s      €€r   ú
<dictcomp>z"Layout.compose.<locals>.<dictcomp>…  s(   ø€ ÐYÐYÐY¹¸¸t�t˜Y v¨d¤|Ô4ÐYÐYÐYr   )rZ   r   r   r   )r   rD   r‹   r’   s     `@r   ÚcomposezLayout.composes  sI   øø€ ð" ×*Ò*Ñ,Ô,ˆ	ÝÐYÐYÐYÐYÐYÀtÄyÇÂÑGXÔGXÐYÑYÔYÑZÔZÐZr   Úsource_qubitsÚtarget_qubitsc                óž   ‡‡— d„ t          |¦  «        D ¦   «         Št          ˆˆfd„| j                             ¦   «         D ¦   «         ¦  «        S )aM  Finds the inverse of this layout.

        This is possible when the layout is a bijective mapping, however the input
        and the output qubits may be different (in particular, this layout may be
        the mapping from the extended-with-ancillas virtual qubits to physical qubits).
        Thus, if this layout represents a mapping from the P-qubits to the positions
        of the Q-qubits, the inverse layout represents a mapping from the Q-qubits
        to the positions of the P-qubits.

        Args:
            source_qubits: A list of :class:`.Qubit` objects representing the domain
                of the layout.
            target_qubits: A list of :class:`.Qubit` objects representing the image
                of the layout.

        Returns:
            A new layout object the represents the inverse of this layout.
        c                ó   — i | ]\  }}||“Œ	S r�   r�   )rw   ÚpÚqs      r   r“   z"Layout.inverse.<locals>.<dictcomp>š  s   € Ð#NÐ#NÐ#N©T¨Q° A qÐ#NÐ#NÐ#Nr   c                ó4   •— i | ]\  }}‰|         ‰|         “ŒS r�   r�   )rw   r�   Úpos_physÚsource_qubit_to_positionr–   s      €€r   r“   z"Layout.inverse.<locals>.<dictcomp>œ  s:   ø€ ð ð ð á"�D˜(ð ˜hÔ'Ð)AÀ$Ô)Gðð ð r   )rj   r   r   r   )r   r•   r–   r�   s     `@r   ÚinversezLayout.inverse‡  sl   øø€ ð& $OÐ#NµY¸}Ñ5MÔ5MÐ#NÑ#NÔ#NÐ Ýðð ð ð ð à&*¤i§o¢oÑ&7Ô&7ðñ ô ñ
ô 
ð 	
r   c                óz   — dgt          |¦  «        z  }t          |¦  «        D ]\  }}| j        |         }|||<   Œ|S )a:  Creates a permutation corresponding to this layout.

        This is possible when the layout is a bijective mapping with the same
        source and target qubits (for instance, a "final_layout" corresponds
        to a permutation of the physical circuit qubits). If this layout is
        a mapping from qubits to their new positions, the resulting permutation
        describes which qubits occupy the positions 0, 1, 2, etc. after
        applying the permutation.

        For example, suppose that the list of qubits is ``[qr_0, qr_1, qr_2]``,
        and the layout maps ``qr_0`` to ``2``, ``qr_1`` to ``0``, and
        ``qr_2`` to ``1``. In terms of positions in ``qubits``, this maps ``0``
        to ``2``, ``1`` to ``0`` and ``2`` to ``1``, with the corresponding
        permutation being ``[1, 2, 0]``.
        N)r@   rj   r   )r   r‹   Úpermrm   rš   Úposs         r   Úto_permutationzLayout.to_permutation¢  sL   € ð" ˆv�˜F™œÑ#ˆÝ˜fÑ%Ô%ð 	ð 	‰DˆAˆqØ”)˜A”,ˆCØˆD�‰IˆIØˆr   r5   )rg   rh   )rD   r   r‹   rŒ   rg   r   )r•   rŒ   r–   rŒ   )r‹   rŒ   ) Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	__slots__r   r$   r   Ústaticmethodr&   r3   r6   r9   r8   r>   rB   rE   rG   rQ   rU   rX   rZ   r]   rb   rf   rp   rt   r‡   rŠ   r”   rž   r¢   r�   r   r   r   r      sý  € € € € € Ø.Ð.à)€Ið	'ð 	'ð 	'ð 	'ð;ð ;ð ;ð!*ð !*ð !*ðF ð!ð !ñ „\ð!ðHð Hð Hð6ð 6ð 6ð7ð 7ð 7ð*ð *ð *ðð ð ðð ð ðð ð ð
ð ð ð)ð )ð )ð )ð2	ð 	ð 	ðð ð ðð ð ðð ð ðð ð ðð ð ð@ð ð ð ð( ðð ñ „\ðð  ð#ð #ñ „\ð#ðJ ðð ñ „\ðð:[ð [ð [ð [ð(
ð 
ð 
ð 
ð6ð ð ð ð ð r   r   c                  ó‚   — e Zd ZU dZded<   ded<   dZded<   dZd	ed
<   dZded<   ddd„Zddd„Z	dd„Z
ddd„Zddd„ZdS )ÚTranspileLayouta  Layout attributes for the output circuit from transpiler.

    The :mod:`~qiskit.transpiler` is unitary-preserving up to the "initial layout"
    and "final layout" permutations. The initial layout permutation is caused by
    setting and applying the initial layout during the :ref:`transpiler-preset-stage-layout`.
    The final layout permutation is caused by :class:`~.SwapGate` insertion during
    the :ref:`transpiler-preset-stage-routing`. This class provides an interface to reason about
    these permutations using a variety of helper methods.

    During the layout stage, the transpiler can potentially remap the order of the
    qubits in the circuit as it fits the circuit to the target backend. For example,
    let the input circuit be:

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

       from qiskit.circuit import QuantumCircuit, QuantumRegister

       qr = QuantumRegister(3, name="MyReg")
       qc = QuantumCircuit(qr)
       qc.h(0)
       qc.cx(0, 1)
       qc.cx(0, 2)
       qc.draw("mpl")


    Suppose that during the layout stage the transpiler reorders the qubits to be:

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

       from qiskit import QuantumCircuit

       qc = QuantumCircuit(3)
       qc.h(2)
       qc.cx(2, 1)
       qc.cx(2, 0)
       qc.draw("mpl")

    Then the output of the :meth:`.initial_virtual_layout` method is
    equivalent to::

        Layout({
            qr[0]: 2,
            qr[1]: 1,
            qr[2]: 0,
        })

    (it is also this attribute in the :meth:`.QuantumCircuit.draw` and
    :func:`.circuit_drawer` which is used to display the mapping of qubits to
    positions in circuit visualizations post-transpilation).

    Building on the above example, suppose that during the routing stage
    the transpiler needs to insert swap gates, and the output circuit
    becomes:

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

       from qiskit import QuantumCircuit

       qc = QuantumCircuit(3)
       qc.h(2)
       qc.cx(2, 1)
       qc.swap(0, 1)
       qc.cx(2, 1)
       qc.draw("mpl")

    Then the output of the :meth:`routing_permutation` method is::

        [1, 0, 2]

    which maps positions of qubits before routing to their final positions
    after routing.

    There are three public attributes associated with the class, however these
    are mostly provided for backwards compatibility and represent the internal
    state from the transpiler. They are defined as:

      * :attr:`initial_layout` - This attribute is used to model the
        permutation caused by the :ref:`transpiler-preset-stage-layout`. It is a
        :class:`~.Layout` object that maps the input :class:`~.QuantumCircuit`\s
        :class:`~.circuit.Qubit` objects to the position in the output
        :class:`.QuantumCircuit.qubits` list.
      * :attr:`input_qubit_mapping` - This attribute is used to retain
        input ordering of the original :class:`~.QuantumCircuit` object. It
        maps the virtual :class:`~.circuit.Qubit` object from the original circuit
        (and :attr:`initial_layout`) to its corresponding position in
        :attr:`.QuantumCircuit.qubits` in the original circuit. This
        is needed when computing the permutation of the :class:`Operator` of
        the circuit (and used by :meth:`.Operator.from_circuit`).
      * :attr:`final_layout` - This attribute is used to model the
        permutation caused by the :ref:`transpiler-preset-stage-routing`. It is a
        :class:`~.Layout` object that maps the output circuit's qubits from
        :class:`.QuantumCircuit.qubits` in the output circuit to their final
        positions after routing. Importantly, this only represents the
        permutation caused by inserting :class:`~.SwapGate`\s into
        the :class:`~.QuantumCircuit` during the :ref:`transpiler-preset-stage-routing`.
        It is **not** a mapping from the original input circuit's position
        to the final position at the end of the transpiled circuit.
        If you need this, you can use the :meth:`.final_index_layout` to generate this.
        If :attr:`final_layout` is set to ``None``, this indicates that routing was not
        run, and can be considered equivalent to a trivial layout with the qubits from
        the output circuit's :attr:`~.QuantumCircuit.qubits` list.
    r   Úinitial_layoutzdict[circuit.Qubit, int]Úinput_qubit_mappingNzLayout | NoneÚfinal_layoutz
int | NoneÚ_input_qubit_countzList[Qubit] | NoneÚ_output_qubit_listFÚfilter_ancillasÚboolrg   c                óž   ‡ — |s‰ j         S t          ˆ fd„‰ j                              ¦   «                              ¦   «         D ¦   «         ¦  «        S )aÐ  Return a :class:`.Layout` object for the initial layout.

        This returns a mapping of virtual :class:`~.circuit.Qubit` objects in the input
        circuit to the positions of the physical qubits selected during layout.
        This is analogous to the :attr:`.initial_layout` attribute.

        Args:
            filter_ancillas: If set to ``True`` only qubits in the input circuit
                will be in the returned layout. Any ancilla qubits added to the
                output circuit will be filtered from the returned object.
        Returns:
            A layout object mapping the input circuit's :class:`~.circuit.Qubit`
            objects to the positions of the selected physical qubits.
        c                óH   •— i | ]\  }}‰j         |         ‰j        k     ¯||“ŒS r�   )r¬   r®   )rw   Úkrn   r   s      €r   r“   z:TranspileLayout.initial_virtual_layout.<locals>.<dictcomp>A  s?   ø€ ð ð ð á�A�qØÔ+¨AÔ.°Ô1HÒHÐHð �1àHÐHÐHr   )r«   r   rZ   r   )r   r°   s   ` r   Úinitial_virtual_layoutz&TranspileLayout.initial_virtual_layout/  si   ø€ ð ð 	'ØÔ&Ð&Ýðð ð ð à Ô/×@Ò@ÑBÔB×HÒHÑJÔJðñ ô ñ
ô 
ð 	
r   ú	List[int]c                ó  — | j                              ¦   «         }|rdg| j        z  }ndgt          |¦  «        z  }t	          |                     ¦   «         ¦  «        D ])\  }\  }}|r|| j        k    r n| j        |         }|||<   Œ*|S )a_  Generate an initial layout as an array of integers.

        Args:
            filter_ancillas: If set to ``True`` any ancilla qubits added
                to the transpiler will not be included in the output.

        Return:
            A layout array that maps a position in the array to its new position in the output
            circuit.
        N)r«   rZ   r®   r@   rj   r   r¬   )r   r°   Úvirtual_mapÚoutputÚindexr�   r‘   r¡   s           r   Úinitial_index_layoutz$TranspileLayout.initial_index_layoutH  s¨   € ð Ô)×:Ò:Ñ<Ô<ˆØð 	/Ø�V˜dÔ5Ñ5ˆFˆFà�V�c +Ñ.Ô.Ñ.ˆFÝ#,¨[×->Ò->Ñ-@Ô-@Ñ#AÔ#Að 	ð 	ÑˆE‘<�D˜$Øð  5¨DÔ,CÒ#CÐ#CØ�ØÔ*¨4Ô0ˆCØˆF�3‰KˆKØˆr   c                óÆ   ‡— | j         €.t          t          t          | j        ¦  «        ¦  «        ¦  «        S | j                              ¦   «         Šˆfd„| j        D ¦   «         S )a»  Generate a final layout as an array of integers.

        If there is no :attr:`.final_layout` attribute present then that indicates
        there was no output permutation caused by routing or other transpiler
        transforms. In this case the function will return a list of ``[0, 1, 2, .., n]``.

        Returns:
            A layout array that maps a position in the array to its new position in the output
            circuit.
        Nc                ó    •— g | ]
}‰|         ‘ŒS r�   r�   )rw   r�   r¸   s     €r   ú
<listcomp>z7TranspileLayout.routing_permutation.<locals>.<listcomp>n  s   ø€ ÐFÐFÐF d�˜DÔ!ÐFÐFÐFr   )r­   ÚlistrL   r@   r¯   rZ   )r   r¸   s    @r   Úrouting_permutationz#TranspileLayout.routing_permutation`  s`   ø€ ð ÔÐ$Ý��c $Ô"9Ñ:Ô:Ñ;Ô;Ñ<Ô<Ð<ØÔ'×8Ò8Ñ:Ô:ˆØFÐFÐFÐF¨dÔ.EÐFÑFÔFÐFr   Tc                óî  — | j         €t          d„ | j        D ¦   «         ¦  «        }n| j         }| j        €'t	          | j                             ¦   «         ¦  «        }n| j        }d„ | j                             ¦   «         D ¦   «         }g }|r|}nt          | j        ¦  «        }t          |¦  «        D ]D}| j	        ||                  }| j        �| j        ||                  }| 
                    |¦  «         ŒE|S )aB  Generate the final layout as an array of integers.

        This method will generate an array of final positions for each qubit in the input circuit.
        For example, if you had an input circuit like::

            qc = QuantumCircuit(3)
            qc.h(0)
            qc.cx(0, 1)
            qc.cx(0, 2)

        and the output from the transpiler was::

            tqc = QuantumCircuit(3)
            tqc.h(2)
            tqc.cx(2, 1)
            tqc.swap(0, 1)
            tqc.cx(2, 1)

        then the :meth:`.final_index_layout` method returns::

            [2, 0, 1]

        This can be seen as follows. Qubit 0 in the original circuit is mapped to qubit 2
        in the output circuit during the layout stage, which is mapped to qubit 2 during the
        routing stage. Qubit 1 in the original circuit is mapped to qubit 1 in the output
        circuit during the layout stage, which is mapped to qubit 0 during the routing
        stage. Qubit 2 in the original circuit is mapped to qubit 0 in the output circuit
        during the layout stage, which is mapped to qubit 1 during the routing stage.
        The output list length will be as wide as the input circuit's number of qubits,
        as the output list from this method is for tracking the permutation of qubits in the
        original circuit caused by the transpiler.

        Args:
            filter_ancillas: If set to ``False`` any ancillas allocated in the output circuit will be
                included in the layout.

        Returns:
            A list of final positions for each input circuit qubit.
        Nc                óZ   — g | ](}t          |d d¦  «                             d¦  «        ¯&|‘Œ)S )Ú	_registerÚ Úancilla)ÚgetattrÚ
startswith)rw   Úxs     r   r¾   z6TranspileLayout.final_index_layout.<locals>.<listcomp>œ  sH   € ð ð ð àÝ˜q +¨rÑ2Ô2×=Ò=¸iÑHÔHðØðð ð r   c                ó   — i | ]\  }}||“Œ	S r�   r�   ©rw   r´   rn   s      r   r“   z6TranspileLayout.final_index_layout.<locals>.<dictcomp>©  ó   € ÐIÐIÐI¡  1�q˜!ÐIÐIÐIr   )r®   r@   r¬   r¯   r¿   r­   rZ   r   rL   r«   r   )	r   r°   Únum_source_qubitsÚcircuit_qubitsÚpos_to_virtÚqubit_indicesr�   rº   Ú	qubit_idxs	            r   Úfinal_index_layoutz"TranspileLayout.final_index_layoutp  s#  € ðP Ô"Ð*õ !$ðð à!Ô5ðñ ô ñ!ô !ÐÐð !%Ô 7ÐØÔ"Ð*Ý! $Ô"3×"DÒ"DÑ"FÔ"FÑGÔGˆNˆNà!Ô4ˆNàIÐI¨Ô(@×(FÒ(FÑ(HÔ(HÐIÑIÔIˆØˆØð 	6Ø*ˆJˆJå˜TÔ4Ñ5Ô5ˆJÝ˜:Ñ&Ô&ð 	,ð 	,ˆEØÔ+¨K¸Ô,>Ô?ˆIØÔ Ð,Ø Ô-¨n¸YÔ.GÔH�	Ø× Ò  Ñ+Ô+Ð+Ð+ØÐr   c                óÆ   ‡— |                       |¬¦  «        }d„ | j                             ¦   «         D ¦   «         Št          ˆfd„t	          |¦  «        D ¦   «         ¦  «        S )aÇ  Generate the final layout as a :class:`.Layout` object.

        This method will generate an array of final positions for each qubit in the input circuit.
        For example, if you had an input circuit like::

            qc = QuantumCircuit(3)
            qc.h(0)
            qc.cx(0, 1)
            qc.cx(0, 2)

        and the output from the transpiler was::

            tqc = QuantumCircuit(3)
            tqc.h(2)
            tqc.cx(2, 1)
            tqc.swap(0, 1)
            tqc.cx(2, 1)

        then the return from this function would be a layout object::

            Layout({
                qc.qubits[0]: 2,
                qc.qubits[1]: 0,
                qc.qubits[2]: 1,
            })

        This can be seen as follows. Qubit 0 in the original circuit is mapped to qubit 2
        in the output circuit during the layout stage, which is mapped to qubit 2 during the
        routing stage. Qubit 1 in the original circuit is mapped to qubit 1 in the output
        circuit during the layout stage, which is mapped to qubit 0 during the routing
        stage. Qubit 2 in the original circuit is mapped to qubit 0 in the output circuit
        during the layout stage, which is mapped to qubit 1 during the routing stage.
        The output list length will be as wide as the input circuit's number of qubits,
        as the output list from this method is for tracking the permutation of qubits in the
        original circuit caused by the transpiler.

        Args:
            filter_ancillas: If set to ``False`` any ancillas allocated in the output circuit will be
                included in the layout.

        Returns:
            A layout object mapping to the final positions for each qubit.
        )r°   c                ó   — i | ]\  }}||“Œ	S r�   r�   rÊ   s      r   r“   z8TranspileLayout.final_virtual_layout.<locals>.<dictcomp>ã  rË   r   c                ó(   •— i | ]\  }}‰|         |“ŒS r�   r�   )rw   rº   r‘   rÎ   s      €r   r“   z8TranspileLayout.final_virtual_layout.<locals>.<dictcomp>ä  s$   ø€ ÐRÐRÐR±K°E¸4�{ 5Ô)¨4ÐRÐRÐRr   )rÑ   r¬   r   r   rj   )r   r°   ÚresrÎ   s      @r   Úfinal_virtual_layoutz$TranspileLayout.final_virtual_layout¶  sg   ø€ ðX ×%Ò%°oÐ%ÑFÔFˆØIÐI¨Ô(@×(FÒ(FÑ(HÔ(HÐIÑIÔIˆÝÐRÐRÐRÐRÅ9ÈSÁ>Ä>ÐRÑRÔRÑSÔSÐSr   )F)r°   r±   rg   r   )r°   r±   rg   r¶   )rg   r¶   )T)r£   r¤   r¥   r¦   Ú__annotations__r­   r®   r¯   rµ   r»   rÀ   rÑ   rÖ   r�   r   r   rª   rª   º  sû   € € € € € € ðkð kðZ ÐÐÑØ1Ð1Ð1Ñ1Ø"&€LÐ&Ð&Ð&Ñ&Ø%)ÐÐ)Ð)Ð)Ñ)Ø-1ÐÐ1Ð1Ð1Ñ1ð
ð 
ð 
ð 
ð 
ð2ð ð ð ð ð0Gð Gð Gð Gð Dð Dð Dð Dð DðL.Tð .Tð .Tð .Tð .Tð .Tð .Tr   rª   N)r¦   Ú
__future__r   Útypingr   Údataclassesr   Úqiskitr   Úqiskit.circuit.quantumregisterr   r   Úqiskit.transpiler.exceptionsr	   Úqiskit.convertersr   r   rª   r�   r   r   ú<module>rß      s  ððð ð #Ð "Ð "Ð "Ð "Ð "Ø Ð Ð Ð Ð Ð Ø !Ð !Ð !Ð !Ð !Ð !à Ð Ð Ð Ð Ð Ø AÐ AÐ AÐ AÐ AÐ AÐ AÐ AØ 4Ð 4Ð 4Ð 4Ð 4Ð 4Ø +Ð +Ð +Ð +Ð +Ð +ðYð Yð Yð Yð Yñ Yô Yð Yðx ðiTð iTð iTð iTð iTñ iTô iTñ „ðiTð iTð iTr   