
    ^j@                         d Z ddlZddlmZmZ ddlmZ ddlZddl	m
Z
mZmZ ddlmZ ddlmZ dd	lmZ g d
Zd ZdedddfdZ edd      	 	 dd       Z ed      dd       Zy)zQR decomposition functions.    N)_apply_over_batch_deprecate_dtypes)_NoValue   )_normalize_lapack_dtypeget_lapack_funcs	HAS_ILP64)_datacopied)_format_emit_errors_warnings)_batched_linalg)qrqr_multiplyrqc                     |j                  dd      }|dv r?d|d<    | |i |}|d   d   j                  j                  t        j                        |d<    | |i |}|d   dk  rt        d|d     d|       |dd S )	z[Call a LAPACK routine, determining lwork automatically and handling
    error return valueslworkN)Nr   r   zillegal value in zth argument of internal )getrealastypenpint_
ValueError)fnameargskwargsr   rets         P/opt/ringagent/.cad-venv/lib/python3.12/site-packages/scipy/linalg/_decomp_qr.pysafecallr       s     JJw%E
w  b'!*//009w
T
V
C
2w{,c"gXJ6NtfUVVs8O    FfullTc                 P   dddddd}||j                         vr%t        dt        |j                                      ||   }|rt        j                  |       }nt        j
                  |       }t        d|       |j                  dk  rt        d	      |j                  d
   |j                  d   }
}	|t        ur6||dk7  r||	k  rt        d|       t        j                  dt        d       t        ||      \  }}|j                  dk(  r<t        |	|
      }|j                  dd
 }|dvrQt        j                   |||	|	fz         }t        j"                  |	      |dddddf<   t        j                   |      }n8t        j                   |||	|fz         }t        j                   ||||
fz         }|r>|t        j$                  |
t&        rt        j(                  nt        j*                        f}n|f}|dk(  r|S |dk(  r?t        j                   |||	|
fz         }t        j,                  |||fz         }||ff|z   S |f|z   S |j.                  d   r|j0                  j2                  dk(  sd}|j5                         }|xs t7        ||       }|xr  |j                  dk(  xr |j.                  d   }t9        j:                  ||||      \  }}}}}|rt=        |       |r||f}n|f}||d   k(  r||f}n||d   k(  r|	|
k  r|dddd|	f   }||d   k(  r|S |f|z   S )a  
    Compute QR decomposition of a matrix.

    Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
    and R upper triangular.

    Parameters
    ----------
    a : (..., M, N) array_like
        Matrix to be decomposed
    overwrite_a : bool, optional
        Whether to overwrite data in `a` (may improve performance). Default is False.
        See :ref:`tutorial_linalg_overwrite` for details.
    lwork : int, optional
        Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
        is computed.

        .. deprecated:: 1.18.0
            This keyword is deprecated as well as no longer in use and will be
            removed in 1.20.0.

    mode : {'full', 'r', 'economic', 'raw'}, optional
        Determines what information is to be returned: either both Q and R
        ('full', default), only R ('r') or both Q and R but computed in
        economy-size ('economic', see Notes). The final option 'raw'
        (added in SciPy 0.11) makes the function return two matrices
        (Q, TAU) in the internal format used by LAPACK.
    pivoting : bool, optional
        Whether or not factorization should include pivoting for rank-revealing
        qr decomposition. If pivoting, compute the decomposition
        ``A[..., :, P] = Q @ R`` as above, but where P is chosen such that the
        diagonal of R is non-increasing. Equivalently, albeit less efficiently,
        an explicit P matrix may be formed explicitly by permuting the rows or columns
        (depending on the side of the equation on which it is to be used) of
        an identity matrix. See Examples.
    check_finite : bool, optional
        Whether to check that the input matrix contains only finite numbers.
        Disabling may give a performance gain, but may result in problems
        (crashes, non-termination) if the inputs do contain infinities or NaNs.

    Returns
    -------
    Q : float or complex ndarray
        Of shape (..., M, M), or (..., M, K) for ``mode='economic'``. Not returned
        if ``mode='r'``. Replaced by tuple ``(Q, TAU)`` if ``mode='raw'``.
    R : float or complex ndarray
        Of shape (..., M, N), or (..., K, N) for ``mode in ['economic', 'raw']``.
        ``K = min(M, N)``.
    P : int ndarray
        Of shape (..., N,) for ``pivoting=True``. Not returned if
        ``pivoting=False``.

    Raises
    ------
    LinAlgError
        Raised if decomposition fails

    Notes
    -----
    This is an interface to the LAPACK routines dgeqrf, zgeqrf,
    dorgqr, zungqr, dgeqp3, and zgeqp3.

    If ``mode=economic``, the shapes of Q and R are (..., M, K) and (..., K, N) instead
    of (..., M,M) and (..., M,N), with ``K=min(M,N)``.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy import linalg
    >>> rng = np.random.default_rng()
    >>> a = rng.standard_normal((9, 6))

    >>> q, r = linalg.qr(a)
    >>> np.allclose(a, np.dot(q, r))
    True
    >>> q.shape, r.shape
    ((9, 9), (9, 6))

    >>> r2 = linalg.qr(a, mode='r')
    >>> np.allclose(r, r2)
    True

    >>> q3, r3 = linalg.qr(a, mode='economic')
    >>> q3.shape, r3.shape
    ((9, 6), (6, 6))

    >>> q4, r4, p4 = linalg.qr(a, pivoting=True)
    >>> d = np.abs(np.diag(r4))
    >>> np.all(d[1:] <= d[:-1])
    True
    >>> np.allclose(a[:, p4], np.dot(q4, r4))
    True
    >>> P = np.eye(p4.size)[p4]
    >>> np.allclose(a, np.dot(q4, r4) @ P)
    True
    >>> np.allclose(a @ P.T, np.dot(q4, r4))
    True
    >>> q4.shape, r4.shape, p4.shape
    ((9, 9), (9, 6), (6,))

    >>> q5, r5, p5 = linalg.qr(a, mode='economic', pivoting=True)
    >>> q5.shape, r5.shape, p5.shape
    ((9, 6), (6, 6), (6,))
    >>> P = np.eye(6)[:, p5]
    >>> np.allclose(a @ P, np.dot(q5, r5))
    True
    r            )r"   r   rraweconomiczMode argument should be one of z	linalg.qr   zExpected at least a 2-D arrayr   r   Nz%lwork should be None, -1 or > M, got z{scipy.linalg: the `lwork` keyword is deprecated and no longer in use as of SciPy 1.18.0 and will be removed in SciPy 1.20.0)
stacklevelr   )r)   r(   shape.dtyper'   r(   ALIGNED=TF_CONTIGUOUSr)   )keysr   listr   asarray_chkfiniteasarrayr   ndimr-   r   warningswarnDeprecationWarningr   sizemin
empty_likeidentityaranger	   int64int32
zeros_likeflagsr/   	byteordercopyr
   r   _qrr   )aoverwrite_ar   modepivotingcheck_finitemodesmodeFlaga1MNKbatch_shapeQRRjr   taujpvterr_lsts                       r   r   r       s,   ^ E 5::<:4

;M:NOPPT{H!!!$ZZ]k2&	ww{89988B<"qA H"!DUGLMM MMJ"	 .b+>OB 
ww!|1Ihhsm**bq!f(<=A;;q>Ac1aiLb!Abq!f(<=Abq!f(<=ABIIa9rxx"((KKBB3;IU]r1v)=>B--+*<=CI<"$$tbyHHYBHH$6$6#$=WWY5+b!"4KM277a<MRXXn5MK  /222{HhWAq#tW$W- WT5<H	U:&	&1q5c1bqbjM5:	tbyr!   )rG   r*   )cz1|2c           
         |dvrt        d| d      t        j                  |      }|j                  dk  r)d}t        j                  |      }|dk(  r|j
                  }nd}t        j                  t        j                  |             } | j                  \  }}	|dk(  rJ|j                  d   t        ||	|||	z
  z  z         k7  r\t        d	| j                   d
|j                         ||j                  d   k7  r%t        d|j                   d
| j                         t        | |d|      }
|
d   \  }}|j                  dk(  rt        j                  |      f|
dd z   S t        d|f      \  }|j                  dv rd}nd}|dddt        ||	      f   }||	kD  r|dk(  r|s|rGt        j                  |j                  d   |f|j                  d      }|j
                  |ddd|	f<   n>t        j                  ||j                  d   f|j                  d      }||d|	ddf<   d}|rd}nd}d}n;|j                   d   r|dk(  s|r|j
                  }|dk(  rd}nd}nd}|}|dk(  rd}nd}t#        |d||||||      \  }|dk7  r|j
                  }|dk(  r|dddt        ||	      f   }|r|j%                         }|f|
dd z   S )a3
  
    Calculate the QR decomposition and multiply Q with a matrix.

    Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
    and R upper triangular. Multiply Q with a vector or a matrix c.

    Parameters
    ----------
    a : (M, N), array_like
        Input array
    c : array_like
        Input array to be multiplied by ``q``.
    mode : {'left', 'right'}, optional
        ``Q @ c`` is returned if mode is 'left', ``c @ Q`` is returned if
        mode is 'right'.
        The shape of c must be appropriate for the matrix multiplications,
        if mode is 'left', ``min(a.shape) == c.shape[0]``,
        if mode is 'right', ``a.shape[0] == c.shape[1]``.
    pivoting : bool, optional
        Whether or not factorization should include pivoting for rank-revealing
        qr decomposition, see the documentation of qr.
    conjugate : bool, optional
        Whether Q should be complex-conjugated. This might be faster
        than explicit conjugation.
    overwrite_a : bool, optional
        Whether to overwrite data in `a` (may improve performance). Default is False.
        See :ref:`tutorial_linalg_overwrite` for details.
    overwrite_c : bool, optional
        Whether data in c is overwritten (may improve performance).
        If this is used, c must be big enough to keep the result,
        i.e. ``c.shape[0]`` = ``a.shape[0]`` if mode is 'left'.
        See :ref:`tutorial_linalg_overwrite` for details.

    Returns
    -------
    CQ : ndarray
        The product of ``Q`` and ``c``.
    R : (K, N), ndarray
        R array of the resulting QR factorization where ``K = min(M, N)``.
    P : (N,) ndarray
        Integer pivot array. Only returned when ``pivoting=True``.

    Raises
    ------
    LinAlgError
        Raised if QR decomposition fails.

    Notes
    -----
    This is an interface to the LAPACK routines ``?GEQRF``, ``?ORMQR``,
    ``?UNMQR``, and ``?GEQP3``.

    .. versionadded:: 0.11.0

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.linalg import qr_multiply, qr
    >>> A = np.array([[1, 3, 3], [2, 3, 2], [2, 3, 3], [1, 3, 2]])
    >>> qc, r1, piv1 = qr_multiply(A, 2*np.eye(4), pivoting=1)
    >>> qc
    array([[-1.,  1., -1.],
           [-1., -1.,  1.],
           [-1., -1., -1.],
           [-1.,  1.,  1.]])
    >>> r1
    array([[-6., -3., -5.            ],
           [ 0., -1., -1.11022302e-16],
           [ 0.,  0., -1.            ]])
    >>> piv1
    array([1, 0, 2], dtype=int32)
    >>> q2, r2, piv2 = qr(A, mode='economic', pivoting=1)
    >>> np.allclose(2*q2 - qc, np.zeros((4, 3)))
    True

    )leftrightz5Mode argument can only be 'left' or 'right' but not ''r*   Tr[   Fr   z5Array shapes are not compatible for Q @ c operation: z vs r   z5Array shapes are not compatible for c @ Q operation: r(   )rI   rJ   N)ormqr)sdTCF)r/   orderrP   rT   LC_CONTIGUOUSzgormqr/gunmqr)overwrite_cr\   )r   r   r5   r7   
atleast_2dra   r6   r-   r<   r   r;   r=   r   typecodezerosr/   rC   r    ravel)rG   rY   rI   rJ   	conjugaterH   rg   onedimrO   rP   r(   rS   rV   
gor_un_mqrtranscclrcQs                     r   r   r      s   ^ $$ !!%a) * 	*
QAvvzMM!6>A
bjjm$A77DAqv~771:QK1$5 566 ,,-GG9D	C D D 
? ,,-GG9D	C D D Q%(
;CVFAs 	vv{a "SW,,":t4KJj(	!Zc!QiZ-A1u1771:q/DBBq"1"uI1aggaj/DBBrr1uIEBB	
	 Uc\YSS6>BB6>BB
:E1c2*,CB|TTw:C1I:XXZ53qr7?r!   c                 6   |dvrt        d      |rt        j                  |       }nt        j                  |       }t	        |j
                        dk7  rt        d      |j
                  \  }}|j                  dk(  rt        ||      }|dk(  sGt        j                  |      }	t        j                  |||f      }
t        j                  |      |
d<   n2t        j                  |||f      }	t        j                  |||f      }
|d	k(  r|	S |	|
fS |xs t        ||       }t        d
|f      \  }t        |d|||      \  }}|dk(  r||k  rt        j                  |||z
        }	n t        j                  || d| df         }	|d	k(  r|	S t        d|f      \  }||k  rt        |d|| d ||d      \  }
|	|
fS |dk(  rt        |d|||d      \  }
|	|
fS t        j                  ||f|j                        }||| d t        |d|||d      \  }
|	|
fS )a,  
    Compute RQ decomposition of a matrix.

    Calculate the decomposition ``A = R Q`` where Q is unitary/orthogonal
    and R upper triangular.

    Parameters
    ----------
    a : (M, N) array_like
        Matrix to be decomposed
    overwrite_a : bool, optional
        Whether to overwrite data in `a` (may improve performance). Default is False.
        See :ref:`tutorial_linalg_overwrite` for details.
    lwork : int, optional
        Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
        is computed.
    mode : {'full', 'r', 'economic'}, optional
        Determines what information is to be returned: either both Q and R
        ('full', default), only R ('r') or both Q and R but computed in
        economy-size ('economic', see Notes).
    check_finite : bool, optional
        Whether to check that the input matrix contains only finite numbers.
        Disabling may give a performance gain, but may result in problems
        (crashes, non-termination) if the inputs do contain infinities or NaNs.

    Returns
    -------
    R : float or complex ndarray
        Of shape (M, N) or (M, K) for ``mode='economic'``. ``K = min(M, N)``.
    Q : float or complex ndarray
        Of shape (N, N) or (K, N) for ``mode='economic'``. Not returned
        if ``mode='r'``.

    Raises
    ------
    LinAlgError
        If decomposition fails.

    Notes
    -----
    This is an interface to the LAPACK routines sgerqf, dgerqf, cgerqf, zgerqf,
    sorgrq, dorgrq, cungrq and zungrq.

    If ``mode=economic``, the shapes of Q and R are (K, N) and (M, K) instead
    of (N,N) and (M,N), with ``K=min(M,N)``.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy import linalg
    >>> rng = np.random.default_rng()
    >>> a = rng.standard_normal((6, 9))
    >>> r, q = linalg.rq(a)
    >>> np.allclose(a, r @ q)
    True
    >>> r.shape, q.shape
    ((6, 9), (9, 9))
    >>> r2 = linalg.rq(a, mode='r')
    >>> np.allclose(r, r2)
    True
    >>> r3, q3 = linalg.rq(a, mode='economic')
    >>> r3.shape, q3.shape
    ((6, 6), (6, 9))

    )r"   r'   r)   z8Mode argument should be one of ['full', 'r', 'economic']r*   zexpected matrixr   r)   r,   .r'   )gerqfrt   )r   rH   N)orgrqzgorgrq/gungrqr   r.   )r   r   r5   r6   lenr-   r;   r<   r=   r>   r
   r   r    triuemptyr/   )rG   rH   r   rI   rK   rN   rO   rP   rQ   rT   rS   rt   r   rV   
gor_un_grqrq1s                   r   r   r     s=   F ,,KM 	M !!!$ZZ]
288}*++88DAq 
ww!|1Iz!b!AbA/A[[^AcFbA/AbA/A3;H!t5+b!"4Kj2%0FEugr#.0GB:QGGB!GGBrsQBCxL!s{":u5KJ1uj/2qbc7Cu"#% a4K 
	j/2s%"#% a4K hh1vRXX.QBCj/35"#% a4Kr!   )r\   FFFF)FNr"   T)__doc__numpyr   scipy._lib._utilr   r   scipy._lib.deprecationr   r8   lapackr   r   r	   _miscr
   _basicr    r   __all__r    r   r   r    r!   r   <module>r      s    !  A +  I H  0 
% 8&5Pf 8\*>C/4W +Wt 8z zr!   