
    z	iJ                       S r SSKJ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  SSKJr  SSKJrJr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  SSK J!r!  SSK"J#r#  SSK$J%r%  \RL                  " \'5      r( " S S\#5      r)SS jr*g)z$Dynamical Decoupling insertion pass.    )annotationsN)GateParameterExpressionQubit)Delay)IGateUGateU3Gate)Reset)
DAGCircuitDAGNode	DAGInNode	DAGOpNode
DAGOutNode)matrix_equal)OneQubitEulerDecomposer)TranspilerError)InstructionDurations)Optimize1qGates)BasePadding)Targetc                     ^  \ rS rSrSr        S
               SU 4S jjjrSU 4S jjrSS jrSS jr            SS jr	\
SS j5       rS	rU =r$ )PadDynamicalDecoupling$   a  Dynamical decoupling insertion pass.

This pass works on a scheduled, physical circuit. It scans the circuit for
idle periods of time (i.e. those containing delay instructions) and inserts
a DD sequence of gates in those spots. These gates amount to the identity,
so do not alter the logical action of the circuit, but have the effect of
mitigating decoherence in those idle periods.

As a special case, the pass allows a length-1 sequence (e.g. ``[XGate()]``).
In this case the DD insertion happens only when the gate inverse can be
absorbed into a neighboring gate in the circuit (so we would still be
replacing Delay with something that is equivalent to the identity).
This can be used, for instance, as a Hahn echo.

This pass ensures that the inserted sequence preserves the circuit exactly
(including global phase).

.. plot::
   :alt: Output from the previous code.
   :include-source:

    import numpy as np
    from qiskit.circuit import QuantumCircuit
    from qiskit.circuit.library import XGate
    from qiskit.transpiler import PassManager, InstructionDurations, Target, CouplingMap
    from qiskit.transpiler.passes import ALAPScheduleAnalysis, PadDynamicalDecoupling
    from qiskit.visualization import timeline_drawer

    circ = QuantumCircuit(4)
    circ.h(0)
    circ.cx(0, 1)
    circ.cx(1, 2)
    circ.cx(2, 3)
    circ.measure_all()
    durations = InstructionDurations(
        [("h", 0, 50), ("cx", [0, 1], 700), ("reset", None, 10),
         ("cx", [1, 2], 200), ("cx", [2, 3], 300),
         ("x", None, 50), ("measure", None, 1000)],
        dt=1e-7
    )
    target = Target.from_configuration(
        ["h", "cx", "reset", "x", "measure"],
        num_qubits=4,
        coupling_map=CouplingMap.from_line(4, bidirectional=False),
        instruction_durations=durations,
        dt=1e-7,
    )

    # balanced X-X sequence on all qubits
    dd_sequence = [XGate(), XGate()]
    pm = PassManager([ALAPScheduleAnalysis(durations),
                      PadDynamicalDecoupling(durations, dd_sequence)])
    circ_dd = pm.run(circ)
    timeline_drawer(circ_dd, target=target)

    # Uhrig sequence on qubit 0
    n = 8
    dd_sequence = [XGate()] * n
    def uhrig_pulse_location(k):
        return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2
    spacing = []
    for k in range(n):
        spacing.append(uhrig_pulse_location(k) - sum(spacing))
    spacing.append(1 - sum(spacing))
    pm = PassManager(
        [
            ALAPScheduleAnalysis(durations),
            PadDynamicalDecoupling(durations, dd_sequence, qubits=[0], spacing=spacing),
        ]
    )
    circ_dd = pm.run(circ)
    timeline_drawer(circ_dd, target=target)

.. note::

    You may need to call alignment pass before running dynamical decoupling to guarantee
    your circuit satisfies acquisition alignment constraints.
c	                  > [         T
U ]  XS9  Xl        Uc  [        S5      eX l        X0l        XPl        X`l        X@l        Xpl	        [        5       U l        0 U l        SU l        Ubb  UR                  5       U l        UR                  U l        U H5  n	U	R                   UR"                  ;  d  M  [%        U	R                    S35      e   gg)a	  Dynamical decoupling initializer.

Args:
    durations: Durations of instructions to be used in scheduling.
    dd_sequence: Sequence of gates to apply in idle spots.
    qubits: Physical qubits on which to apply DD.
        If None, all qubits will undergo DD (when possible).
    spacing: A list of spacings between the DD gates.
        The available slack will be divided according to this.
        The list length must be one more than the length of dd_sequence,
        and the elements must sum to 1. If None, a balanced spacing
        will be used [d/2, d, d, ..., d, d, d/2].
    skip_reset_qubits: If True, does not insert DD on idle periods that
        immediately follow initialized/reset qubits
        (as qubits in the ground state are less susceptible to decoherence).
    pulse_alignment: The hardware constraints for gate timing allocation.
        This is usually provided from ``backend.configuration().timing_constraints``.
        If provided, the delay length, i.e. ``spacing``, is implicitly adjusted to
        satisfy this constraint.
    extra_slack_distribution: The option to control the behavior of DD sequence generation.
        The duration of the DD sequence should be identical to an idle time in the
        scheduled quantum circuit, however, the delay in between gates comprising the sequence
        should be integer number in units of dt, and it might be further truncated
        when ``pulse_alignment`` is specified. This sometimes results in the duration of
        the created sequence being shorter than the idle time
        that you want to fill with the sequence, i.e. `extra slack`.
        This option takes following values.

            - "middle": Put the extra slack to the interval at the middle of the sequence.
            - "edges": Divide the extra slack as evenly as possible into
              intervals at beginning and end of the sequence.
    target: The :class:`~.Target` representing the target backend.
        Target takes precedence over other arguments when they can be inferred from target.
        Therefore specifying target as well as other arguments like ``durations`` or
        ``pulse_alignment`` will cause those other arguments to be ignored.

Raises:
    TranspilerError: When invalid DD sequence is specified.
    TranspilerError: When pulse gate with the duration which is
        non-multiple of the alignment constraint value is found.
    TypeError: If ``dd_sequence`` is not specified
)target	durationsNz0required argument 'dd_sequence' is not specifiedr   z. in dd_sequence is not supported in the target)super__init__
_durations	TypeError_dd_sequence_qubits_skip_reset_qubits
_alignment_spacing_extra_slack_distributionset_no_dd_qubits_dd_sequence_lengths_sequence_phaser   pulse_alignmentnameoperation_namesr   )selfr   dd_sequencequbitsspacingskip_reset_qubitsr,   extra_slack_distributionr   gate	__class__s             z/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/transpiler/passes/scheduling/padding/dynamical_decoupling.pyr   PadDynamicalDecoupling.__init__t   s    j 	<#NOO'"3))A&'*u<>! $..0DO$44DO#99F$:$::)99+%ST  $	     c                  > [         TU ]  U5        [        5       nU R                  b1  UR	                  U R                  [        U R                  SS 5      5        [        U R                  5      n[        UR                  5      S:w  d  UR                  R                  SS 5      c  [        S5      eU R                  c!  SU-  nUS-  nU/U/US-
  -  -   U/-   U l        OE[        U R                  5      S:w  d!  [        S U R                   5       5      (       a  [        S5      eUS:w  a  US-  S:w  a  [        S	5      e[        R                  " S5      nU R                   H"  nUR!                  UR#                  5       5      nM$     [%        U['        5       R#                  5       S
S9(       d  [        S5      e[        R(                  " US   S   5      U l        [-        UR.                  5       Hl  u  pU R                   HW  nU R1                  Xx5      (       a  M  U R2                  R5                  U5        [6        R9                  SXR:                  5          Mj     Mn     [-        UR.                  5       H  u  pU R=                  U
5      (       d  M  / n[-        U R                  5       HK  u  pUR                  Xz5      nUR?                  U5        URA                  5       nXpR                  U'   Xl!        MM     XRD                  U'   M     g )Ndt   qz"DD runs on physical circuits only.   c              3  *   #    U  H	  oS :  v   M     g7f)r   N ).0as     r7   	<genexpr>6PadDynamicalDecoupling._pre_runhook.<locals>.<genexpr>   s     -K]!e]s   zRThe spacings must be given in terms of fractions of the slack period and sum to 1.r   z8DD sequence must contain an even number of gates (or 1).T)ignore_phasez4The DD sequence does not make an identity operation.z3No DD on qubit %d as gate %s is not supported on it)#r   _pre_runhookr   r    updategetattrlenr"   qregsgetr   r&   sumanynpeyedot	to_matrixr   r   angler+   	enumerater1   '_PadDynamicalDecoupling__gate_supportedr)   addloggerdebugr-   $_PadDynamicalDecoupling__is_dd_qubitappend
to_mutabledurationr*   )r/   dagr   
num_pulsesmidendnoopr5   qarg_physical_indexqubitsequence_lengthsindexgate_lengthr6   s                  r7   rF   #PadDynamicalDecoupling._pre_runhook   s   S!(*	??&T__gdootT.RS**+
 syy>Q#))--T":"B!"FGG == j.C'C ESEZ!^$<<uDDM4==!Q&#-KT]]-K*K*K%8  ?A~"%&`aa66!9D))xx 01 *eg&7&7&9M%&\]]#%88DGAJ#7D  !,GD)),,T88&&**40LLMtU^U^  * - &/szz%:!N%%n55!():):;'mmDA ''4(+/!!%( +  < 0@%%e, &;r9   c                t    U R                   b*  U R                   R                  UR                  U4S9(       a  gg)z/A gate is supported on the qubit (qarg) or not.)qargsTF)r   instruction_supportedr-   )r/   r5   ra   s      r7   __gate_supported'PadDynamicalDecoupling.__gate_supported   s0    ;;$++"C"CDIIVZU\"C"]r9   c                d    XR                   ;   d   U R                  (       a  XR                  ;  a  gg)z'DD can be inserted in the qubit or not.FT)r)   r#   )r/   qubit_indexs     r7   __is_dd_qubit$PadDynamicalDecoupling.__is_dd_qubit  s$    ---LL[<r9   c                *
  ^  XC-
  nUT R                   -  S:w  a4  [        SU ST R                    S[        U5       S[        U5       S3	5      eT R                  UR                  R                  U5      5      (       d'  T R                  X[        XqR                  5      U5        g T R                  (       a[  [        U[        5      (       d  [        UR                  [        5      (       a'  T R                  X[        XqR                  5      U5        g U[        R                  " T R                   U   5      -
  nT R"                  n	US::  a'  T R                  X[        XqR                  5      U5        g [%        T R&                  5      S:X  Ga  T R&                  S   R)                  5       R+                  5       n
[-        5       R/                  U
5      u  pp[        U[0        5      (       ak  [        UR                  [2        [4        45      (       aF  UR                  nUR6                  u  nnn[8        R:                  " UUUXU5      Ul        Xl        X-  n	O[        U[0        5      (       a  [        UR                  [2        [4        45      (       a  UR                  nUR6                  u  nnn[8        R:                  " XUUUU5      Ul        UR=                  Xo5      nT R>                  S   RA                  U5      nUb  UT R>                  S   U'   X-  n	O'T R                  X[        XqR                  5      U5        g U 4S	 jnU" U[        RB                  " T RD                  5      -  5      nU[        R                  " U5      -
  nT RF                  S
:X  aJ  [I        [%        U5      S-
  S-  5      nU" U5      nUU==   U-  ss'   UU-
  (       a  US==   UU-
  -  ss'   ORT RF                  S:X  a)  U" US-  5      nUS==   U-  ss'   US==   UU-
  -  ss'   O[        ST RF                   S35      e[K        [%        T R&                  5      [%        U5      5      nUn[M        U5       H  n U [%        U5      :  a8  UU    n!U!S:  a-  T R                  UU[        U!UR                  5      U5        UU!-  nU [%        T R&                  5      :  d  Me  T R&                  U    n"T R                   U   U    n#T R                  UUU"U5        UU#-  nM     URN                  U	-   Ul'        g )Nr   zTime interval z is not divisible by alignment z	 between z and .r<   node_start_timec                d   > TR                   [        R                  " U TR                   -  5      -  $ )N)r%   rN   floor)valuesr/   s    r7   _constrained_length8PadDynamicalDecoupling._pad.<locals>._constrained_lengthe  s$    ??RXXft.F%GGGr9   middler>   edgesz"Option extra_slack_distribution = z is invalid.)(r%   r   _format_noderX   r1   rf   _apply_scheduled_opr   _unitr$   
isinstancer   opr   rN   rL   r*   r+   rI   r"   inverserQ   r   angles_and_phaser   r	   r
   paramsr   
compose_u3substitute_nodeproperty_setpopasarrayr&   r'   intmaxrangeglobal_phase)$r/   r\   rd   t_startt_end	next_node	prev_nodetime_intervalslacksequence_gphaseu_invthetaphilamphaser   theta_rphi_rlam_rtheta_lphi_llam_lnew_prev_node
start_timerx   tausextra_slackmid_ind	to_middleto_begin_edgenum_elements
idle_afterdd_indtaur5   rg   s$   `                                   r7   _padPadDynamicalDecoupling._pad
  s   L 4??*a/! /NtN_ `'	235i9P8QQRT 
 !!#**"2"25"9::$$S5		3RTYZ""y),,
9<<0O0O $$S5		3RTYZt'@'@'G HH..A:$$S5		3RTYZt  !Q&%%a(002<<>E%<%>%O%OPU%V"E)Y//Jy||eU[_4]4]\\(*		%+66wueZ]^	!(Iy11jPUW]6_6_\\(*		%+66u3QVX]^	 # 3 3I B!../@AEEiP
)JTD%%&78G( ((u]II7VX]^	H #52::dmm+D#DEbffTl* ))X53t9q=A-.G+K8IMY&MY& RK)33++w6/a@MG}$GHm33H!4T5S5S4TT`a 
 3t0013t9=
L)FD	!6l7,,S*eC>SUZ[#%JD--..((0"77>vF((j$Fk)
 * ++o=r9   c                    / nU R                    HV  n[        U[        5      (       a-  UR                  (       d  UR	                  [        U5      5        ME  UR	                  U5        MX     [        U5      $ )zAReturn gate params with any bound parameters replaced with floats)r   r   r   
parametersrY   floattuple)r5   r   ps      r7   _resolve_params&PadDynamicalDecoupling._resolve_params  sS     A!011!,,eAh'a 	 
 V}r9   )
r%   r"   r*   r    r'   r)   r#   r+   r$   r&   )NNNNTr<   rz   N)r   r   r0   z
list[Gate]r1   zlist[int] | Noner2   zlist[float] | Noner3   boolr,   r   r4   strr   r   )r\   r   )r5   r   ra   r   returnr   )ro   r   r   r   )r\   r   rd   r   r   r   r   r   r   r   r   r   )r5   r   r   r   )__name__
__module____qualname____firstlineno____doc__r   rF   rT   rX   r   staticmethodr   __static_attributes____classcell__)r6   s   @r7   r   r   $   s    Mb +/"&#'&*"& (0K'K  K !	K
 $K  K K #&K K KZ9@vC>C> C> 	C>
 C> C> C>J  r9   r   c                    [        U [        [        45      (       a%  U R                  R                   SU R
                   3$ SU R                   SU R                   3$ )z6Util to format the DAGNode, DAGInNode, and DAGOutNode.z	 on qarg zDAGNode z
 on qargs )r   r   r   r6   r   wirer-   rj   )nodes    r7   r}   r}     sO    $J/00..))*)DII;??dii[
4::,77r9   )r   r   r   r   )+r   
__future__r   loggingnumpyrN   qiskit.circuitr   r   r   qiskit.circuit.delayr   %qiskit.circuit.library.standard_gatesr   r	   r
   qiskit.circuit.resetr   qiskit.dagcircuitr   r   r   r   r   (qiskit.quantum_info.operators.predicatesr   qiskit.synthesis.one_qubitr   qiskit.transpiler.exceptionsr   'qiskit.transpiler.instruction_durationsr   %qiskit.transpiler.passes.optimizationr   8qiskit.transpiler.passes.scheduling.padding.base_paddingr   qiskit.transpiler.targetr   	getLoggerr   rV   r   r}   r@   r9   r7   <module>r      sf    + "   ; ; & F F & S S A > 8 H A P + 
		8	$t[ tn8r9   