
    z	iS                    T   S r SSKJr  SSKJr  SSKrSSKJr  SSK	J
r
JrJr  SSKJrJr  SSKJrJrJrJrJr    S       SS	 jjrSS
 jrSS jrSS jrSS jrSS jrSSS jjrSS jrSS S jjr SS jr!SS jr" S!       S"S jjr#SS S jjr$SS jr%SS jr&S#S jr'S#S jr(g)$zXModule containing multi-controlled circuits synthesis with and without ancillary qubits.    )annotations)ceilN)QiskitError)QuantumCircuitQuantumRegisterAncillaRegister)HGateCU1Gate)c3xc4xsynth_mcx_n_dirty_i15synth_mcx_noaux_v24synth_mcx_noaux_hp24c                B    [         R                  " [        XU5      5      $ )a  
Synthesize a multi-controlled X gate with :math:`k` controls based on the paper
by Iten et al. [1].

For :math:`k\ge 4` the method uses :math:`k - 2` dirty ancillary qubits, producing a circuit
with :math:`2 * k - 1` qubits and at most :math:`8 * k - 6` CX gates. For :math:`k\le 3`
explicit efficient circuits are used instead.

Args:
    num_ctrl_qubits: The number of control qubits.

    relative_phase: when set to ``True``, the method applies the optimized multi-controlled X gate
        up to a relative phase, in a way that, by lemma 8 of [1], the relative
        phases of the ``action part`` cancel out with the phases of the ``reset part``.

    action_only: when set to ``True``, the method applies only the ``action part`` of lemma 8 of [1].

Returns:
    The synthesized quantum circuit.

References:
    1. Iten et. al., *Quantum Circuits for Isometries*, Phys. Rev. A 93, 032318 (2016),
       `arXiv:1501.06911 <http://arxiv.org/abs/1501.06911>`_
)r   _from_circuit_datasynth_mcx_n_dirty_i15_rs)num_ctrl_qubitsrelative_phaseaction_onlys      i/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/synthesis/multi_controlled/mcx_synthesis.pyr   r   #   s!    : ,, +N     c                   SU -  S-
  n[        USS9n[        USS9nUSU  nX    nX S-   S nUR                  US   US   US   5        Sn[        SU S-
  5       H$  nUR                  XH   Xg   XgS-      5        US-  nM&     UR	                  US   Xg   U5        [        [        SU S-
  5      5       H$  nUR                  XH   XgS-
     Xg   5        US-  nM&     UR                  US   US   Xg   5        U$ )	a  
Synthesize a multi-controlled X gate with :math:`k` controls using :math:`k - 2`
clean ancillary qubits with producing a circuit with :math:`2 * k - 1` qubits
and at most :math:`6 * k - 6` CX gates, by Maslov [1].

Args:
    num_ctrl_qubits: The number of control qubits.

Returns:
    The synthesized quantum circuit.

References:
    1. Maslov., Phys. Rev. A 93, 022311 (2016),
       `arXiv:1508.03273 <https://arxiv.org/pdf/1508.03273>`_
      qname
mcx_vchainNr   )r   r   rccxrangeccxreversed)	r   
num_qubitsr   qc
q_controlsq_target
q_ancillasijs	            r   synth_mcx_n_clean_m15r+   E   s#   " _$q(J
-A		-B#O$J!HQ&()JGGJqM:a=*Q-8	A1o)*

z}jQ.?@	Q +
 FF:b>:=(3eA234

za%0*-@	Q 5
 GGJqM:a=*-8Ir   c                b   U S:X  a
  [        5       $ U S:X  a
  [        5       $ U S-   n[        USS9n[        USS9n[	        U5      S-
  n US   nUS	   n[        U S-  5      n/ US
U Qn[        [	        U5      SS9n/ UQUPX&XhR                  -   [	        U5      -
  S-
   Qn	/ X&U S-
   QUPn
[        [	        U
5      S9n/ U
QUPUSUR                  [	        U
5      -
  S-
   QnUR                  XSS9  UR                  XSS9  UR                  UR                  5       U	SS9  UR                  XSS9  U$ )a|  
Synthesize a multi-controlled X gate with :math:`k` controls using a single
clean ancillary qubit producing a circuit with :math:`k + 2` qubits and at most
:math:`16 * k - 24` CX gates, by [1], [2].

Args:
    num_ctrl_qubits: The number of control qubits.

Returns:
    The synthesized quantum circuit.

References:
    1. Barenco et. al., *Elementary gates for quantum computation*, Phys.Rev. A52 3457 (1995),
       `arXiv:quant-ph/9503016 <https://arxiv.org/abs/quant-ph/9503016>`_
    2. Iten et. al., *Quantum Circuits for Isometries*, Phys. Rev. A 93, 032318 (2016),
       `arXiv:1501.06911 <http://arxiv.org/abs/1501.06911>`_
      r   r   r   mcx_recursiver   r   NT)r   r   r   r   inplace)
	synth_c3x	synth_c4xr   r   lenr   r   r$   composeinverse)r   r$   r   r%   	q_ancillar'   middle	controls1mcx1qubits1	controls2mcx2
qc2_qubitss                r   synth_mcx_1_clean_b95rA   p   sh   & !{	A	{ 1$J
-A		0B!fqjO"IuH/A%&F !GV*I YPTUDa	a9aq&??2JSQZ^2[^_2_'`aG=!_q01=9=I Y@DU9UhU1tY/ORS/S)TUJJJtdJ+JJtJ.JJt||~wJ5JJtJ.Ir   c                V   SSK Jn  U S-   n[        USS9n[        USS9nUR	                  [        5       US   // 5        [        R                  SU S-
  -  -  n[        U5      nU" X0U5      nU H  u  pn
UR	                  XU
5        M     UR	                  [        5       US   // 5        U$ )	a[  
Synthesize a multi-controlled X gate with :math:`k` controls using the Gray code.

Produces a quantum circuit with :math:`k + 1` qubits. This method
produces exponentially many CX gates and should be used only for small
values of :math:`k`.

Args:
    num_ctrl_qubits: The number of control qubits.

Returns:
    The synthesized quantum circuit.
r   )_gray_code_chainr   r   r   mcx_grayr   r   )	(qiskit.circuit.library.standard_gates.u3rC   r   r   _appendr	   nppir
   )r   rC   r$   r   r%   
scaled_lambottom_gate
definitioninstrqargscargss              r   synth_mcx_gray_coderO      s     J 1$J
-A	
	+BJJuw2$!! 345J*%K!!kBJ)e


5'  *JJuw2$Ir   c                D    [         R                  " [        U 5      5      nU$ )av  
Synthesize a multi-controlled X gate with :math:`k` controls based on
the implementation for MCPhaseGate.

In turn, the MCPhase gate uses the decomposition for multi-controlled
special unitaries described in [1].

Produces a quantum circuit with :math:`k + 1` qubits.
The number of CX-gates is quadratic in :math:`k`.

Args:
    num_ctrl_qubits: The number of control qubits.

Returns:
    The synthesized quantum circuit.

References:
    1. Vale et. al., *Circuit Decomposition of Multicontrolled Special Unitary
       Single-Qubit Gates*, IEEE TCAD 43(3) (2024),
       `arXiv:2302.06377 <https://arxiv.org/abs/2302.06377>`_
)r   r   synth_mcx_noaux_v24_rsr   circs     r   r   r      s    , ,,-CO-TUDKr   c                D    [         R                  " [        U 5      5      nU$ )a  
Synthesize a multi-controlled X gate with :math:`k` controls based on
the work by Huang and Palsberg.

Produces a quantum circuit with :math:`k + 1` qubits. The number of CX-gates
is linear in :math:`k`.

Args:
    num_ctrl_qubits: The number of control qubits.

Returns:
    The synthesized quantum circuit.

References:
    1. Huang and Palsberg, *Compiling Conditional Quantum Gates without Using
       Helper Qubits*, PLDI (2024),
       <https://dl.acm.org/doi/10.1145/3656436>`_
)r   r   synth_mcx_noaux_hp24_rsrR   s     r   r   r      s    & ,,-D_-UVDKr   c                    SU -  n[        USS9n[        USU  3S9nUSU  X0SU -   USU -  S pvnU(       a  UR                  U5        UR                  XVU5        U$ )a  
Construct a quantum circuit for creating n-condionally clean ancillae using 3n qubits. This
implements Fig. 4a of [1]. The circuit applies n relative CCX (RCCX) gates . If apply_x is True,
each RCCX gate is preceded by an X gate on the target qubit. The order of returned qubits is
qr_a, qr_b, qr_target.

Args:
    n: Number of conditionally clean ancillae to create.
    apply_x: If True, apply X gate to the target qubit.

Returns:
    QuantumCircuit: The quantum circuit for creating n-conditionally clean ancillae.

References:
    1. Khattar and Gidney, Rise of conditionally clean ancillae for optimizing quantum circuits
    `arXiv:2407.17966 <https://arxiv.org/abs/2407.17966>`__
r-   r   r   ccxn_Nr   )r   r   xr    )napply_xn_qubitsr   r%   qr_aqr_b	qr_targets           r   _n_parallel_ccx_xr_      so    & 1uHs+A	%s	,BbqE1Q<1q57	D
YGGD	"Ir   c                x   U S::  a  [        S5      eU S-   n[        U5      n[        [        U5      5      n[        SUS-
  S5       H5  nUR	                  X4S-      X4S-      X4   5        UR                  X4   5        M7     US-  S:w  a  US-
  US-
  US-
  pvnOUS-
  US-
  US-
  pvnUS:  a,  UR	                  X5   X6   X7   5        UR                  X7   5        [        USS	5       H8  nUR	                  X4   X4S-
     X4S-
     5        UR                  X4S-
     5        M:     S[        SSU-
  5      -   nX8   S-
  n	X)4$ )
a  
Helper function to create linear-depth ladder operations used in Khattar and Gidney's MCX synthesis.
In particular, this implements Step-1 and Step-2 on Fig. 3 of [1] except for the first and last
CCX gates.

Args:
    num_ladder_qubits: No. of qubits involved in the ladder operation.

Returns:
    A tuple consisting of the linear-depth ladder circuit and the index of control qubit to
    apply the final CCX gate.

Raises:
    QiskitError: If num_ladder_qubits <= 2.

References:
    1. Khattar and Gidney, Rise of conditionally clean ancillae for optimizing quantum circuits
    `arXiv:2407.17966 <https://arxiv.org/abs/2407.17966>`__
r   z2n_ctrls >= 3 to use MCX ladder. Otherwise, use CCXr   r   r-         r.   r0   )r   r   listr!   r    rX   max)
num_ladder_qubitsrY   r%   qregr)   abtargetmid_second_ctrl
final_ctrls
             r   _linear_depth_ladder_opsrl     sS   * ANOOAA		Ba>D 1a!eQ
UTa%[$'2
TW  
 	1uz1ua!eQUff1ua!eQUfz
$,/
T\61b!
!edq5k2
Ta%[ " #aQ-'O&*J>r   c                j   U S::  a  [        S5      e[        U SS9n[        SSS9n[        SSS9n[        X#USS9n[	        U 5      u  pgUR                  US	   US   US	   5        UR                  XdS
S
 US
S
 -   SS9  UR                  XBU   U5        UR                  UR                  5       US
S
 US
S
 -   SS9  UR                  US	   US   US	   5        U(       dV  UR                  XdS
S
 US
S
 -   SS9  UR                  XBU   U5        UR                  UR                  5       US
S
 US
S
 -   SS9  U$ )a  
Synthesize a multi-controlled X gate with :math:`k` controls using :math:`1` ancillary qubit as
described in Sec. 5 of [1].

Args:
    num_ctrl_qubits: The number of control qubits.
    clean: If True, the ancilla is clean, otherwise it is dirty.

Returns:
    The synthesized quantum circuit.

Raises:
    QiskitError: If num_ctrl_qubits <= 2.

References:
    1. Khattar and Gidney, Rise of conditionally clean ancillae for optimizing quantum circuits
    `arXiv:2407.17966 <https://arxiv.org/abs/2407.17966>`__
r   Dkg24 synthesis requires at least 3 control qubits. Use CCX directly.ctrlr   r   targancmcx_linear_depthr   NTr2   )	r   r   r   r   rl   r    r7   r"   r8   )r   cleanr&   r'   r9   r%   
ladder_opsrk   s           r   synth_mcx_1_kg24ru   L  sR   ( !`aa v>Jqv.H.I	
i>P	QB5oFJGGJqM:a=)A,7JJzQ<*Q-7JFFF9,h7JJ!z!}$  
 GGJqM:a=)A,7


:|jm;T
J
yZ0(;


:%%'1
1)Et
TIr   c                    [        U SS9$ )a.  
Synthesize a multi-controlled X gate with :math:`k` controls using :math:`1` clean ancillary qubit
producing a circuit with :math:`2k-3` Toffoli gates or :math:`6k-6` CX gates and depth
:math:`O(k)` as described in Sec. 5.1 of [1].

Args:
    num_ctrl_qubits: The number of control qubits.

Returns:
    The synthesized quantum circuit.

Raises:
    QiskitError: If num_ctrl_qubits <= 2.

References:
    1. Khattar and Gidney, Rise of conditionally clean ancillae for optimizing quantum circuits
    `arXiv:2407.17966 <https://arxiv.org/abs/2407.17966>`__
Trs   ru   r1   s    r   synth_mcx_1_clean_kg24ry   }      ( O488r   c                    [        U SS9$ )a0  
Synthesize a multi-controlled X gate with :math:`k` controls using :math:`1` dirty ancillary qubit
producing a circuit with :math:`4k-8` Toffoli gates or :math:`12k-18` CX gates and depth
:math:`O(k)` as described in Sec. 5.3 of [1].

Args:
    num_ctrl_qubits: The number of control qubits.

Returns:
    The synthesized quantum circuit.

Raises:
    QiskitError: If num_ctrl_qubits <= 2.

References:
    1. Khattar and Gidney, Rise of conditionally clean ancillae for optimizing quantum circuits
    `arXiv:2407.17966 <https://arxiv.org/abs/2407.17966>`__
Frw   rx   r1   s    r   synth_mcx_1_dirty_kg24r|         ( O599r   c           
     :   [        [        U5      S-   5      nU /n/ n[        U5      S:  Ga[  [        [        U5      S-   [        U5      5      nXS USU pq/ n[        U5      S:  a  [        U5      S-  n	[        [        U5      S-  5      n
XzX-    XzU	-   S XI* S pn[        U5      [        U5      s=:X  a  U	s=:X  a  S:  d4  O  [	        S[        U5      < S[        U5      < S[        U	5      < 35      eX/:w  a   UR                  [        U	5      X-   U-   SS9  O#U(       d  UR                  US	   US	   US	   5        XU
S -  nXSU
 -   nUSU	*  n[        U5      S:  a  M  [        XH-   5      nXW-  n[        U5      S:  a  GM[  XQ-  n[        U5      nX5SS
 4$ )a  
Helper function to build a log-depth ladder compose of CCX and X gates as shown in Fig. 4b of [1].

Args:
    ancilla_idx: Index of the ancillary qubit.
    ctrls: List of control qubits.
    skip_cond_clean: If True, do not include the conditionally clean ancilla (step 1 and 5 in
        Fig. 4b of [1]).

Returns:
    A tuple consisting of the log-depth ladder circuit of conditionally clean ancillae and the
    list of indices of control qubit to apply the linear-depth MCX gate.

Raises:
    QiskitError: If no. of qubits in parallel CCX + X gates are not the same.

References:
    1. Khattar and Gidney, Rise of conditionally clean ancillae for optimizing quantum circuits
    `arXiv:2407.17966 <https://arxiv.org/abs/2407.17966>`__
r   Nr   z(Invalid CCX gate parameters: len(ccx_x)=z != len(ccx_y)=z != len(ccx_n)=Tr2   r   r   )	r   r6   minintr   r7   r_   r    sorted)ancilla_idxctrlsskip_cond_cleanr%   rq   final_ctrlsnext_batch_len	nxt_batchnew_ancccx_nstccx_xccx_yccx_ts                 r   _build_logn_depth_ccx_ladderr     s   0 
E
Q	'B-CK
e*q.SX\3u:6 15.3Iy)nq 	Na'ES^a'(Brz*u*,'FG  E
 u:U9u99!?CJ=@PSZMQaVYZ_V`Ubc  %

,U3U]U5JTX
Y&GGE!HeAha9~%G#2.Igv,C) )nq , S]# 7 e*q.: K%K3Br   c                   U S::  a  [        S5      e[        U SS9n[        SSS9n[        SSS9n[        X#USS9n[	        U [        [        U 5      5      5      u  pgUR                  XbS	S	 US
   /-   SS9  [        U5      S:X  a  UR                  US
   X'S
      U5        O>[        [        U5      S-   5      nUR                  UUS
   /X'   -   US	S	 -   US   /-   SS9  UR                  UR                  5       US	S	 US
   /-   SS9  U(       d  [	        U [        [        U 5      5      SS9u  pUR                  XS	S	 US
   /-   SS9  [        U5      S:X  a  UR                  US
   X'S
      U5        O'UR                  WUS
   /X'   -   US	S	 -   US   /-   SS9  UR                  U	R                  5       US	S	 US
   /-   SS9  U$ )a  
Synthesize a multi-controlled X gate with :math:`k` controls using :math:`2` ancillary qubits.
as described in Sec. 5 of [1].

Args:
    num_ctrl_qubits: The number of control qubits.
    clean: If True, the ancilla is clean, otherwise it is dirty.

Returns:
    The synthesized quantum circuit.

Raises:
    QiskitError: If num_ctrl_qubits <= 2.

References:
    1. Khattar and Gidney, Rise of conditionally clean ancillae for optimizing quantum circuits
    `arXiv:2407.17966 <https://arxiv.org/abs/2407.17966>`__
r   rn   ro   r   r   rp   rq   mcx_logn_depthNr   Tr2   )r   )r   r   r   r   r   rc   r!   r7   r6   r"   ry   r8   )
r   rs   	q_controlr'   r9   r%   rt   r   mid_mcxladder_ops_news
             r   synth_mcx_2_kg24r     s   ( !`aaf=Iqv.H.I		Y=M	NB:eO45J JJzQ<9Q<.8$JG
;1
y|Y1~6A([)9A)=>


q\N$%qk |n  	 	
 JJz!!#Yq\Yq\N%BDJQ&BT%"894'
# 	

>Q<9Q<.#@$
O{q FF9Q<q>!:HEJJ1!77(1+ESTV  
 	

>))+Yq\Yq\N-JTX
YIr   c                    [        U SS9$ )a5  
Synthesize a multi-controlled X gate with :math:`k` controls using :math:`2` clean ancillary qubits
producing a circuit with :math:`2k-3` Toffoli gates or :math:`6k-6` CX gates and
depth :math:`O(\log(k))` as described in Sec. 5.2 of [1].

Args:
    num_ctrl_qubits: The number of control qubits.

Returns:
    The synthesized quantum circuit.

Raises:
    QiskitError: If num_ctrl_qubits <= 2.

References:
    1. Khattar and Gidney, Rise of conditionally clean ancillae for optimizing quantum circuits
    `arXiv:2407.17966 <https://arxiv.org/abs/2407.17966>`__
Trw   r   r1   s    r   synth_mcx_2_clean_kg24r   *  rz   r   c                    [        U SS9$ )a7  
Synthesize a multi-controlled X gate with :math:`k` controls using :math:`2` dirty ancillary qubits
producing a circuit with :math:`4k-8` Toffoli gates or :math:`12k-18` CX gates and depth
:math:`O(\log(k))` as described in Sec. 5.4 of [1].

Args:
    num_ctrl_qubits: The number of control qubits.

Returns:
    The synthesized quantum circuit.

Raises:
    QiskitError: If num_ctrl_qubits <= 2.

References:
    1. Khattar and Gidney, Rise of conditionally clean ancillae for optimizing quantum circuits
    `arXiv:2407.17966 <https://arxiv.org/abs/2407.17966>`__
Frw   r   r1   s    r   synth_mcx_2_dirty_kg24r   A  r}   r   c                 >    [         R                  " [        5       5      $ )z+Efficient synthesis of 3-controlled X-gate.)r   r   c3x_rs r   r   r4   r4   X      ,,VX66r   c                 >    [         R                  " [        5       5      $ )z+Efficient synthesis of 4-controlled X-gate.)r   r   c4x_rsr   r   r   r5   r5   ]  r   r   )FF)r   r   r   boolr   r   returnr   )r   r   r   r   )T)rY   r   rZ   r   r   r   )re   r   r    tuple[QuantumCircuit, list[int]])r   r   rs   r   r   r   )F)r   r   r   z	list[int]r   r   r   r   )r   r   ))__doc__
__future__r   mathr   numpyrG   qiskit.exceptionsr   qiskit.circuit.quantumcircuitr   r   r   %qiskit.circuit.library.standard_gatesr	   r
   -qiskit._accelerate.synthesis.multi_controlledr   r   r   r   r   r   r   rQ   r   rU   r+   rA   rO   r_   rl   ru   ry   r|   r   r   r   r   r4   r5   r   r   r   <module>r      s    _ "   ) Z Z
  !  	D(V7t:4.@1h.b9.:0 AF; ; &; 9=; %; |>B9.:.7
7r   