
    z	iP                       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
r
SSKrSSKJrJr  SSKJrJrJrJrJrJrJr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&  \	(       a  SSK'J(r(J)r)  \
RT                  " \+5      r,\\\\\\\\\\\\S.r-SS jr. " S S5      r/ " S S5      r0 " S S5      r1 " S S\15      r2\2" 5       r3g)a  
Expand 2-qubit Unitary operators into an equivalent
decomposition over SU(2)+fixed 2q basis gate, using the KAK method.

May be exact or approximate expansion. In either case uses the minimal
number of basis applications.

Method is described in Appendix B of Cross, A. W., Bishop, L. S., Sheldon, S., Nation, P. D. &
Gambetta, J. M. Validating quantum computers using randomized model circuits.
arXiv:1811.12926 [quant-ph] (2018).
    )annotationsN)OptionalTypeTYPE_CHECKING)QuantumCircuitGate)CXGateU3GateU2GateU1GateUGate	PhaseGateRXGateRYGateRZGateSXGateXGateRGate)QiskitError)Operator)DEFAULT_ATOL)deprecate_func)two_qubit_decompose)
DAGCircuit	DAGOpNode)cxrxsxxrzupu1u2u3ryrc                Z   [         R                  " U [        S9n [        R                  " U 5      u  pn[         R
                  " X5      n[        [        UR                  5       R                  R                  U 5      R                  5       5      S-
  5      nUS:  a  [        SU 35      eXU4$ )zDecompose :math:`U = U_l \otimes U_r` where :math:`U \in SU(4)`,
and :math:`U_l,~U_r \in SU(2)`.

Args:
    special_unitary_matrix: special unitary matrix to decompose
Raises:
    QiskitError: if decomposition isn't possible.
dtype   gvIh%<=zMdecompose_two_qubit_product_gate: decomposition failed: deviation too large: )npasarraycomplexr    decompose_two_qubit_product_gatekronabsconjTdottracer   )special_unitary_matrixLRphasetemp	deviations         h/home/james-whalen/.local/lib/python3.13/site-packages/qiskit/synthesis/two_qubit/two_qubit_decompose.pyr/   r/   Q   s      ZZ(>gN'HHI_`MQ5771=DC		))*@AGGIJQNOI7$$-;0
 	

 %=    c                  @   \ rS rSr% SrS\S'   S\S'   S\S'   S\S'   S\S	'   S\S
'   S\S'   S\S'   S\S'   S\S'   S\S'   \R                  r S SS.     S!S jjjr	\
" SSS9S 5       rSS\S.       S"S jjrS#S jrS r\SS.       S$S jj5       rS rSrg)%TwoQubitWeylDecompositioni   a  Two-qubit Weyl decomposition.

Decompose two-qubit unitary

.. math::

    U = ({K_1}^l \otimes {K_1}^r) e^{(i a XX + i b YY + i c ZZ)} ({K_2}^l \otimes {K_2}^r)

where

.. math::

    U \in U(4),~
    {K_1}^l, {K_1}^r, {K_2}^l, {K_2}^r \in SU(2)

and we stay in the "Weyl Chamber"

.. math::

    \pi /4 \geq a \geq b \geq |c|

This class avoids some problems of numerical instability near high-symmetry loci within the Weyl
chamber. If there is a high-symmetry gate "nearby" (in terms of the requested average gate fidelity),
then it return a canonicalized decomposition of that high-symmetry gate.

References:
    1. Cross, A. W., Bishop, L. S., Sheldon, S., Nation, P. D. & Gambetta, J. M.,
       *Validating quantum computers using randomized model circuits*,
       `arXiv:1811.12926 [quant-ph] <https://arxiv.org/abs/1811.12926>`_
    2. B. Kraus, J. I. Cirac, *Optimal Creation of Entanglement Using a Two-Qubit Gate*,
       `arXiv:0011050 [quant-ph] <https://arxiv.org/abs/quant-ph/0011050>`_
    3. B. Drury, P. J. Love, *Constructive Quantum Shannon Decomposition from Cartan
       Involutions*, `arXiv:0806.4015 [quant-ph] <https://arxiv.org/abs/0806.4015>`_

floatabcglobal_phase
np.ndarrayK1lK2lK1rK2runitary_matrixzOptional[float]requested_fidelitycalculated_fidelityN)_specializationc                  [         R                  " U[        S9n[        R                  " XUS9U l        U R
                  R                  U l        U R
                  R                  U l        U R
                  R                  U l        U R
                  R                  U l	        U R
                  R                  U l
        U R
                  R                  U l        U R
                  R                  U l        U R
                  R                  U l        Xl        X l        U R
                  R                   U l        ["        R%                  [&        R(                  5      (       a}  U R+                  5       n["        R-                  SU R                  U R                   U5        [/        U R                   U-
  5      S:  a$  ["        R1                  SU R                   U-
  5        g g g )Nr)   fidelityrN   zARequested fidelity: %s calculated fidelity: %s actual fidelity %sg-q=z.Requested fidelity different from actual by %s)r,   r-   r.   r   r?   _inner_decompositionrB   rC   rD   rE   rG   rI   rH   rJ   rK   rL   rM   loggerisEnabledForloggingDEBUGactual_fidelitydebugr1   warning)selfrK   rQ   rN   rW   s        r<   __init__"TwoQubitWeylDecomposition.__init__   sp    N'B$7$Q$Q%
! **,,**,,**,, 55BB,,00,,00,,00,,00,"*#'#<#<#P#P w}}--"224OLLS''((	 4++o=>HD,,> I .r=   z1.1.0zin the 2.0.0 release)sinceremoval_timelinec                    [         e)zMake changes to the decomposition to comply with any specializations.

This method will always raise a ``NotImplementedError`` because
there are no specializations to comply with in the current implementation.
)NotImplementedErrorrZ   s    r<   
specialize$TwoQubitWeylDecomposition.specialize   s
     "!r=   Feuler_basissimplifyatolc               `    U R                   R                  XUS9n[        R                  " USS9$ )z+Returns Weyl decomposition in circuit form.rd   Tlegacy_qubits)rR   circuitr   _from_circuit_data)rZ   re   rf   rg   circuit_datas        r<   rk   !TwoQubitWeylDecomposition.circuit   s9     0088#T 9 
 00TRRr=   c                    U R                   " S0 UD6n[        R                  " [        U5      R                  R
                  R                  5       U R                  -  5      n[        R                  " U5      $ )zNCalculates the actual fidelity of the decomposed circuit to the input unitary. )
rk   r,   r5   r   datar3   r2   rK   r   trace_to_fid)rZ   kwargscircr5   s       r<   rW   )TwoQubitWeylDecomposition.actual_fidelity   sV    ||%f%$,,..3358K8KKL"//66r=   c           	        [        U 5      R                   S3n[        R                  " 5        n[        R
                  " X R                  SS9  [        R                  " UR                  5       5      R                  5       nSSS5        W Vs/ s H  n[        U5      PM     nnUS==   S-  ss'   [        U 5      R                  5        Vs/ s H  nSUR                  5        3PM     nnSn[        U R                  R                  5      R!                  S	5      S
   n[        U 5      R                   SU 3n	U/U-   U-   SU R"                   S3SU	 S3SU R$                   S3SU R'                  5        S3SU R(                  U R*                  U R,                  4 S3/-   n
UR/                  U
5      $ ! , (       d  f       GN7= fs  snf s  snf )zQRepresent with enough precision to allow copy-paste debugging of all corner casesz.from_bytes(Fallow_pickleN,z# z
    .   z._specializations.zrequested_fidelity=z_specialization=zcalculated_fidelity=zactual_fidelity=zabc=))type__qualname__ioBytesIOr,   saverK   base64encodebytesgetvalue
splitlinesreprstrrstriprR   specializationsplitrL   rM   rW   rB   rC   rD   join)rZ   prefixfb64r   b64asciiprettyindentspecialization_variantspecialization_reprliness              r<   __repr__"TwoQubitWeylDecomposition.__repr__   s   J++,L9ZZ\QGGA**?$$QZZ\2==?C  &))SDGS)-0Y-A-A-CD-CBqxxzl#-CD!$T%>%>%M%M!N!T!TUX!YZ[!\!%d!8!8 99KLbKcdH &d&=&=%>a@"#6"7q9&t'?'?&@B"4#7#7#9":!</02	 	 {{5!!+ \ *Ds   AF0GG0
F?c                   A[         R                  " U5      n[        R                  " U5       n[        R
                  " USS9nSSS5        U " WX#S9$ ! , (       d  f       N= f)z6Decode bytes into :class:`.TwoQubitWeylDecomposition`.Frw   NrP   )r   decodebytesr   r   r,   load)clsbytes_inrL   rN   rs   r   r   arrs           r<   
from_bytes$TwoQubitWeylDecomposition.from_bytes   sO       *ZZ_''!%0C 3!3UU _s   A
A!c                "   [        U R                  R                  5      R                  S5      S   nU R                  R
                   SU S3nSR                  U R                  SS9R                  S5      R                  S	5      5      nU U S
3$ )Nr{   r|   z [specialization=z] (
	z
	T)rf   textry   z
))
r   rR   r   r   	__class____name__r   rk   drawr   )rZ   r   precirc_indents       r<   __str__!TwoQubitWeylDecomposition.__str__  s    T66EEFLLSQRST(()):>:J'Rkk$,,,"="B"B6"J"P"PQS"TU{m3''r=   )rG   rI   rH   rJ   rR   rB   rC   rD   rM   rE   rL   rK   )gv?)rK   rF   rQ   float | NonerN   )two_qubit_decompose.Specialization | None)re   z
str | Nonerf   boolrg   rA   returnr   )r   rA   )r   bytesrL   rA   rN   r   r   z'TwoQubitWeylDecomposition')r   
__module__r   __firstlineno____doc____annotations__r   Specialization_specializationsr[   r   rb   r   rk   rW   r   classmethodr   r   __static_attributes__rp   r=   r<   r?   r?   i   s-   "J HHH	O	O	O	O''*99
 "."
 FJ""" "
 C"H '4JK" L" ,0%WcS(S;?SOTS	S7"4  FJVV "	V
 CV 
%V V (r=   r?   c                  D    \ rS rSrSrSS	S jjr S
\S.   SS jjjrSrg)TwoQubitControlledUDecomposeri  zDecompose two-qubit unitary in terms of a desired
:math:`U \sim U_d(\alpha, 0, 0) \sim \text{Ctrl-U}`
gate that is locally equivalent to an :class:`.RXXGate`.c                &   UR                   bB  [        R                  " UR                   U5      U l        UR                   R                  U l        O[        R                  " X5      U l        Xl        U R                  R                  U l        X l        g)a  Initialize the KAK decomposition.

Args:
    rxx_equivalent_gate: Gate that is locally equivalent to an :class:`.RXXGate`:
        :math:`U \sim U_d(\alpha, 0, 0) \sim \text{Ctrl-U}` gate.
        Valid options are [:class:`.RZZGate`, :class:`.RXXGate`, :class:`.RYYGate`,
        :class:`.RZXGate`, :class:`.CPhaseGate`, :class:`.CRXGate`, :class:`.CRYGate`,
        :class:`.CRZGate`].
    euler_basis: Basis string to be provided to :class:`.OneQubitEulerDecomposer`
        for 1Q synthesis.
        Valid options are [``'ZXZ'``, ``'ZYZ'``, ``'XYX'``, ``'XZX'``, ``'U'``, ``'U3'``,
        ``'U321'``, ``'U1X'``, ``'PSX'``, ``'ZSX'``, ``'ZSXX'``, ``'RR'``].

Raises:
    QiskitError: If the gate is not locally equivalent to an :class:`.RXXGate`.
N)	_standard_gater   r   _inner_decomposername	gate_namerxx_equivalent_gatescalere   )rZ   r   re   s      r<   r[   &TwoQubitControlledUDecomposer.__init__  sz    " --9%8%V%V#22K&D" 1??DDDN%8%V%V#&D" $7 ++11
&r=   )rg   c               ~    U R                  [        R                  " U[        S9U5      n[        R
                  " USS9$ )zReturns the Weyl decomposition in circuit form.

Args:
    unitary (Operator or ndarray): :math:`4     imes 4` unitary to synthesize.

Returns:
    QuantumCircuit: Synthesized quantum circuit.

Note: atol is passed to OneQubitEulerDecomposer.
r)   Tri   )r   r,   r-   r.   r   rl   )rZ   unitaryapproximateuse_dagrg   	circ_datas         r<   __call__&TwoQubitControlledUDecomposer.__call__/  s4     **2::gW+MtT	00$OOr=   )r   re   r   r   r   N)ZXZ)r   z
Type[Gate]re   r   )FF)r   Operator | np.ndarrayr   r   )	r   r   r   r   r   r[   r   r   r   rp   r=   r<   r   r     s;    @'> JOPXdP,P	P Pr=   r   c                      \ rS rSrSr   S       SS jjrS r\S 5       rS r	S r
S	 r   SSS
.           SS jjjrS rSrg)TwoQubitBasisDecomposeri@  ax  A class for decomposing 2-qubit unitaries into minimal number of uses of a 2-qubit
basis gate.

Args:
    gate: Two-qubit gate to be used in the KAK decomposition.
    basis_fidelity: Fidelity to be assumed for applications of KAK Gate. Defaults to ``1.0``.
    euler_basis: Basis string to be provided to :class:`.OneQubitEulerDecomposer` for 1Q synthesis.
        Valid options are [``'ZYZ'``, ``'ZXZ'``, ``'XYX'``, ``'U'``, ``'U3'``, ``'U1X'``,
        ``'PSX'``, ``'ZSX'``, ``'RR'``].
    pulse_optimize: If ``True``, try to do decomposition which minimizes
        local unitaries in between entangling gates. This will raise an exception if an
        optimal decomposition is not implemented. Currently, only [{CX, SX, RZ}] is known.
        If ``False``, don't attempt optimization. If ``None``, attempt optimization but don't raise
        if unknown.


.. automethod:: __call__
Nc                .   Xl         X l        X@l        UR                  U l        [
        R                  " U[        U5      R                  UUUS9U l	        U R                  R                  U l        U R                  (       d  [        R                  " SSS9  g g )N)basis_fidelityre   pulse_optimizezEOnly know how to decompose properly for a supercontrolled basis gate.   )
stacklevel)gater   r   r   r   r   r   r   rq   r   super_controlledis_supercontrolledwarningswarn)rZ   r   r   re   r   s        r<   r[    TwoQubitBasisDecomposer.__init__T  s     	,,!4!L!LTN)#)"
 #'"8"8"I"I&&MMW 'r=   c                j    [         R                  " U[        S9nU R                  R	                  U5      $ )zNComputes the number of basis gates needed in
a decomposition of input unitary
r)   )r,   r-   r.   r   num_basis_gatesrZ   r   s     r<   r   'TwoQubitBasisDecomposer.num_basis_gatesn  s+     **WG4%%55g>>r=   c                @    [         R                  R                  U 5      $ )a4  
Decompose target :math:`\sim U_d(x, y, z)` with :math:`0` uses of the basis gate.
Result :math:`U_r` has trace:

.. math::

    \Big\vert\text{Tr}(U_r\cdot U_\text{target}^{\dag})\Big\vert =
    4\Big\vert (\cos(x)\cos(y)\cos(z)+ j \sin(x)\sin(y)\sin(z)\Big\vert

which is optimal for all targets and bases
)r   r   decomp0)targets    r<   r   TwoQubitBasisDecomposer.decomp0u  s     #::BB6JJr=   c                8    U R                   R                  U5      $ )at  Decompose target :math:`\sim U_d(x, y, z)` with :math:`1` use of the basis gate
:math:`\sim U_d(a, b, c)`.
Result :math:`U_r` has trace:

.. math::

    \Big\vert\text{Tr}(U_r \cdot U_\text{target}^{\dag})\Big\vert =
    4\Big\vert \cos(x-a)\cos(y-b)\cos(z-c) + j \sin(x-a)\sin(y-b)\sin(z-c)\Big\vert

which is optimal for all targets and bases with ``z==0`` or ``c==0``.
)r   decomp1rZ   r   s     r<   r   TwoQubitBasisDecomposer.decomp1  s     %%--f55r=   c                8    U R                   R                  U5      $ )a  
Decompose target :math:`\sim U_d(x, y, z)` with :math:`2` uses of the basis gate.

For supercontrolled basis :math:`\sim U_d(\pi/4, b, 0)`, all b, result :math:`U_r` has trace

.. math::

    \Big\vert\text{Tr}(U_r \cdot U_\text{target}^\dag) \Big\vert = 4\cos(z)

which is the optimal approximation for basis of CNOT-class :math:`\sim U_d(\pi/4, 0, 0)`
or DCNOT-class :math:`\sim U_d(\pi/4, \pi/4, 0)` and any target. It may
be sub-optimal for :math:`b \neq 0` (i.e. there exists an exact decomposition for any target
using :math:`B \sim U_d(\pi/4, \pi/8, 0)`, but it may not be this decomposition).
This is an exact decomposition for supercontrolled basis and target :math:`\sim U_d(x, y, 0)`.
No guarantees for non-supercontrolled basis.
)r   decomp2_supercontrolledr   s     r<   r   /TwoQubitBasisDecomposer.decomp2_supercontrolled  s    " %%==fEEr=   c                8    U R                   R                  U5      $ )z
Decompose target with :math:`3` uses of the basis.
This is an exact decomposition for supercontrolled basis :math:`\sim U_d(\pi/4, b, 0)`, all b,
and any target. No guarantees for non-supercontrolled basis.
)r   decomp3_supercontrolledr   s     r<   r   /TwoQubitBasisDecomposer.decomp3_supercontrolled  s     %%==fEEr=   _num_basis_usesc                   [         R                  " U[        S9nU(       a  U R                  R	                  XX55      $ U R                  R                  UUUUS9n[        R                  " USS9$ )aQ  Decompose a two-qubit ``unitary`` over fixed basis and :math:`SU(2)` using the best
approximation given that each basis application has a finite ``basis_fidelity``.

Args:
    unitary (Operator or ndarray): :math:`4 \times 4` unitary to synthesize.
    basis_fidelity (float or None): Fidelity to be assumed for applications of KAK Gate.
        If given, overrides ``basis_fidelity`` given at init.
    approximate (bool): Approximates if basis fidelities are less than 1.0.
    use_dag (bool): If true a :class:`.DAGCircuit` is returned instead of a
        :class:`QuantumCircuit` when this class is called.
    _num_basis_uses (int): force a particular approximation by passing a number in [0, 3].

Returns:
    QuantumCircuit: Synthesized quantum circuit.

Raises:
    QiskitError: if ``pulse_optimize`` is True but we don't know how to do it.
r)   r   Tri   )r,   r-   r.   r   to_dag
to_circuitr   rl   )rZ   r   r   r   r   r   r   s          r<   r    TwoQubitBasisDecomposer.__call__  ss    8 **WG4))00  ..99 /	 : I "44YdSSr=   c                L    U R                   R                  UR                  5      $ )z
Give the expected traces :math:`\Big\vert\text{Tr}(U \cdot U_\text{target}^{\dag})\Big\vert`
for a different number of basis gates.
)r   tracesrR   r   s     r<   r   TwoQubitBasisDecomposer.traces  s!    
 %%,,V-H-HIIr=   )r   r   r   r   r   r   )g      ?UN)r   r   r   rA   re   r   r   zbool | None)NTF)r   r   r   r   r   r   r   r   r   z
int | Noner   zQuantumCircuit | DAGCircuit)r   r   r   r   r   r[   r   staticmethodr   r   r   r   r   r   r   rp   r=   r<   r   r   @  s    , !$&*  	
 $4? K K6F&F (, (T '+(T&(T %(T 	(T
 (T $(T 
%(TTJr=   r   c                  L    \ rS rSrSrS rS rSS jrS rS r	S r
S	 rS
 rSrg)_LazyTwoQubitCXDecomposeri  _innerc                    S U l         g Nr   ra   s    r<   r[   "_LazyTwoQubitCXDecomposer.__init__  s	    r=   c                P    U R                   c  [        [        5       5      U l         g g r   )r   r   r	   ra   s    r<   _load_LazyTwoQubitCXDecomposer._load  s    ;;1&(;DK r=   c                F    U R                  5         U R                  " U0 UD6$ r   )r   r   )rZ   argsrs   s      r<   r   "_LazyTwoQubitCXDecomposer.__call__  s    

{{D+F++r=   c                X    U R                  5         U R                  R                  U5      $ r   )r   r   r   r   s     r<   r    _LazyTwoQubitCXDecomposer.traces  s     

{{!!&))r=   c                X    U R                  5         U R                  R                  U5      $ r   )r   r   r   r   s     r<   r   !_LazyTwoQubitCXDecomposer.decomp1  s     

{{""6**r=   c                X    U R                  5         U R                  R                  U5      $ r   )r   r   r   r   s     r<   r   1_LazyTwoQubitCXDecomposer.decomp2_supercontrolled       

{{226::r=   c                X    U R                  5         U R                  R                  U5      $ r   )r   r   r   r   s     r<   r   1_LazyTwoQubitCXDecomposer.decomp3_supercontrolled  r  r=   c                X    U R                  5         U R                  R                  U5      $ r   )r   r   r   r   s     r<   r   )_LazyTwoQubitCXDecomposer.num_basis_gates  s     

{{**733r=   N)r   r   )r   r   r   r   	__slots__r[   r   r   r   r   r   r   r   r   rp   r=   r<   r   r     s/    I<,*+;;4r=   r   )r6   rF   )4r   
__future__r   r   r   r   typingr   r   r   rU   numpyr,   qiskit.circuitr   r   %qiskit.circuit.library.standard_gatesr	   r
   r   r   r   r   r   r   r   r   r   r   qiskit.exceptionsr   qiskit.quantum_info.operatorsr   .qiskit.synthesis.one_qubit.one_qubit_decomposer   qiskit.utils.deprecationr   qiskit._accelerater   qiskit.dagcircuit.dagcircuitr   r   	getLoggerr   rS   GATE_NAME_MAPr/   r?   r   r   r   two_qubit_cnot_decomposerp   r=   r<   <module>r     s   
 # 	   0 0   /    * 2 4 2B			8	$ 

	
		



	 0`( `(F1P 1Ph]J ]JP 4 7  4F 56 r=   