
    ge~w                     ,   d Z g dZddlZddlmZ ddl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 dddddZdZdZd Zd Zd+dZ eddd           e            d,d                        Z eddd           e            d,d                         Z ed!d"d#           e            d,d$                        Z ed%d&d'           e            d,d(                        Z e            	 	 d-d)            Z e            	 	 d.d*            ZdS )/z,Iterative methods for solving linear systems)bicgbicgstabcgcgsgmresqmr    N)dedent   )
_iterative)LinearOperator)make_system)_aligned_zeros)non_reentrantsdcz)fr   FDzC
Parameters
----------
A : {sparse matrix, ndarray, LinearOperator}aX  b : ndarray
    Right hand side of the linear system. Has shape (N,) or (N,1).

Returns
-------
x : ndarray
    The converged solution.
info : integer
    Provides convergence information:
        0  : successful exit
        >0 : convergence to tolerance not achieved, number of iterations
        <0 : illegal input or breakdown

Other Parameters
----------------
x0 : ndarray
    Starting guess for the solution.
tol, atol : float, optional
    Tolerances for convergence, ``norm(residual) <= max(tol*norm(b), atol)``.
    The default for ``atol`` is ``'legacy'``, which emulates
    a different legacy behavior.

    .. warning::

       The default value for `atol` will be changed in a future release.
       For future compatibility, specify `atol` explicitly.
maxiter : integer
    Maximum number of iterations.  Iteration will stop after maxiter
    steps even if the specified tolerance has not been achieved.
M : {sparse matrix, ndarray, LinearOperator}
    Preconditioner for A.  The preconditioner should approximate the
    inverse of A.  Effective preconditioning dramatically improves the
    rate of convergence, which implies that fewer iterations are needed
    to reach a given error tolerance.
callback : function
    User-supplied function to call after each iteration.  It is called
    as callback(xk), where xk is the current solution vector.
c                 \    t           j                            |           }||k    r|dfS |dfS )z;
    Successful termination condition for the solvers.
    r
   r   nplinalgnorm)residualatolresids      Elib/python3.11/site-packages/scipy/sparse/linalg/_isolve/iterative.py	_stoptestr    C   s2     INN8$$E}}axax    c                 F   |2t          j        d                    |          t          d           d}t	          |           } |dk    r, |            }|| k    rdS |dk    r| S | t	          |          z  S t          t	          |          | t	          |          z            S )	a  
    Parse arguments for absolute tolerance in termination condition.

    Parameters
    ----------
    tol, atol : object
        The arguments passed into the solver routine by user.
    bnrm2 : float
        2-norm of the rhs vector.
    get_residual : callable
        Callable ``get_residual()`` that returns the initial value of
        the residual.
    routine_name : str
        Name of the routine.
    Na	  scipy.sparse.linalg.{name} called without specifying `atol`. The default value will be changed in a future release. For compatibility, specify a value for `atol` explicitly, e.g., ``{name}(..., atol=0)``, or to retain the old behavior ``{name}(..., atol='legacy')``)name   category
stacklevellegacyexitr   )warningswarnformatDeprecationWarningfloatmax)tolr   bnrm2get_residualroutine_namer   s         r   	_get_atolr4   N   s    " | 7 8>v<v7P7P1a	A 	A 	A 	A 
**CxC<<6A::Ju%%5;;eEll 2333r!    0c                       fd}|S )Nc           	          d                     t          d                    dd          z   t          t	                    f          | _        | S )N
z    z
    )joincommon_doc1replacecommon_doc2r	   __doc__)fnAinfofooterheaders    r   combinezset_docstring.<locals>.combinex   sI    YY &tX)F)F F +VF^^ = > >
 	r!    )rB   r@   rA   atol_defaultrC   s   ```  r   set_docstringrF   w   s/          
 Nr!   z7Use BIConjugate Gradient iteration to solve ``Ax = b``.zThe real or complex N-by-N matrix of the linear system.
Alternatively, ``A`` can be a linear operator which can
produce ``Ax`` and ``A^T x`` using, e.g.,
``scipy.sparse.linalg.LinearOperator``.a1                 Examples
               --------
               >>> import numpy as np
               >>> from scipy.sparse import csc_matrix
               >>> from scipy.sparse.linalg import bicg
               >>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
               >>> b = np.array([2, 4, -1], dtype=float)
               >>> x, exitCode = bicg(A, b)
               >>> print(exitCode)            # 0 indicates successful convergence
               0
               >>> np.allclose(A.dot(x), b)
               True

               )rA   h㈵>c                    t          | ||          \  } }}t                    }	||	dz  }| j        | j        c}
|j        |j        }}t          j        j                 }t          t          |dz             }fd}t          ||t          j                                      |d          }|dk    r |          dfS |}d}d}t          d	|	z  j        
          }d}d}d}|}	 |} ||||||||	  	        \	  }}}}}}}}|||k    r |           t          |dz
  |dz
  |	z             }t          |dz
  |dz
  |	z             }|dk    r| |           n|dk    r3||xx         |z  cc<   ||xx         | ||                   z  z  cc<   n|dk    r3||xx         |z  cc<   ||xx         | |
||                   z  z  cc<   n|dk    r |||                   ||<   ns|dk    r |||                   ||<   nX|dk    r-||xx         |z  cc<   ||xx         |           z  z  cc<   n%|d	k    r|rd}d}t          ||         |          \  }}d}}|dk    r||k    r||k    s|} |          |fS )N
   
bicgrevcomc                  Z    t           j                                        z
            S Nr   bmatvecxs   r   r2   zbicg.<locals>.get_residual   #    y~~ffQii!m,,,r!   r   r)   r   r
      dtypeT      r$      F)r   lenrO   rmatvec
_type_convrU   chargetattrr   r4   r   r   r   r   slicer    )ArN   x0r0   maxiterMcallbackr   postprocessnrZ   psolverpsolveltrrevcomr2   r   ndx1ndx2workijobinfoftflagiter_olditersclr1sclr2slice1slice2rO   rP   s    `                           @@r   r   r      sT   . &aB22Aa!KAAB$h	OFGh	GF
QW\
"CZ|!344F- - - - - - -S$	q 1 1<HHDv~~{1~~q  EDD!A#AG,,,DDDFE6!QeUD$dCC 	>5%tT5%EGOOHQKKKtAvtAvax((tAvtAvax((BJJ#aiiLLLE!LLLLLLE&&f"6"666LLLLaiiLLLE!LLLLLLE''$v,"7"777LLLLaii!6$v,//DLLaii"74<00DLLaiiLLLE!LLLLLLE&&))O+LLLLaii #DL$77KE4=@ axxEW$$etmm;q>>4r!   zBUse BIConjugate Gradient STABilized iteration to solve ``Ax = b``.zThe real or complex N-by-N matrix of the linear system.
Alternatively, ``A`` can be a linear operator which can
produce ``Ax`` using, e.g.,
``scipy.sparse.linalg.LinearOperator``.a                 Examples
               --------
               >>> import numpy as np
               >>> from scipy.sparse import csc_matrix
               >>> from scipy.sparse.linalg import bicgstab
               >>> R = np.array([[4, 2, 0, 1],
               ...               [3, 0, 0, 2],
               ...               [0, 1, 1, 1],
               ...               [0, 2, 1, 0]])
               >>> A = csc_matrix(R)
               >>> b = np.array([-1, -0.5, -1, 2])
               >>> x, exit_code = bicgstab(A, b)
               >>> print(exit_code)  # 0 indicates successful convergence
               0
               >>> np.allclose(A.dot(x), b)
               True
               c                 T   t          | ||          \  } }}t                    }	||	dz  }| j        |j        }
t          j        j                 }t          t          |dz             }fd}t          ||t          j
                                      |d          }|dk    r |          dfS |}d}d}t          d	|	z  j        
          }d}d}d}|}	 |} ||||||||	  	        \	  }}}}}}}}|||k    r |           t          |dz
  |dz
  |	z             }t          |dz
  |dz
  |	z             }|dk    r| |           n|dk    r3||xx         |z  cc<   ||xx         | ||                   z  z  cc<   ns|dk    r |
||                   ||<   nX|dk    r-||xx         |z  cc<   ||xx         |           z  z  cc<   n%|dk    r|rd}d}t          ||         |          \  }}d}(|dk    r||k    r||k    s|} |          |fS )NrI   bicgstabrevcomc                  Z    t           j                                        z
            S rL   r   rM   s   r   r2   zbicgstab.<locals>.get_residual   rQ   r!   r   r)   r   r
   rR      rT   TrV   rW   r$   Fr   rY   rO   r[   rU   r\   r]   r   r4   r   r   r   r   r^   r    r_   rN   r`   r0   ra   rb   rc   r   rd   re   rf   rh   ri   r2   r   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rO   rP   s    `                         @@r   r   r      s   4 *!QA66Aq!QAAB$XFXF
QW\
"CZ'7!788F- - - - - - -S$	q 1 1<LLDv~~{1~~q  EDD!A#AG,,,DDDFE6!QeUD$dCC 	>5%tT5%EGOOHQKKKtAvtAvax((tAvtAvax((BJJ#aiiLLLE!LLLLLLE&&f"6"666LLLLaii!6$v,//DLLaiiLLLE!LLLLLLE&&))O+LLLLaii #DL$77KE436 axxEW$$etmm;q>>4r!   z5Use Conjugate Gradient iteration to solve ``Ax = b``.zThe real or complex N-by-N matrix of the linear system.
``A`` must represent a hermitian, positive definite matrix.
Alternatively, ``A`` can be a linear operator which can
produce ``Ax`` using, e.g.,
``scipy.sparse.linalg.LinearOperator``.a                 Examples
               --------
               >>> import numpy as np
               >>> from scipy.sparse import csc_matrix
               >>> from scipy.sparse.linalg import cg
               >>> P = np.array([[4, 0, 1, 0],
               ...               [0, 5, 0, 0],
               ...               [1, 0, 3, 2],
               ...               [0, 0, 2, 4]])
               >>> A = csc_matrix(P)
               >>> b = np.array([-1, -0.5, -1, 2])
               >>> x, exit_code = cg(A, b)
               >>> print(exit_code)    # 0 indicates successful convergence
               0
               >>> np.allclose(A.dot(x), b)
               True

               c                    t          | ||          \  } }}t                    }	||	dz  }| j        |j        }
t          j        j                 }t          t          |dz             }fd}t          ||t          j
                                      |d          }|dk    r |          dfS |}d}d}t          d	|	z  j        
          }d}d}d}|}	 |} ||||||||	  	        \	  }}}}}}}}|||k    r |           t          |dz
  |dz
  |	z             }t          |dz
  |dz
  |	z             }|dk    r| |           n|dk    r3||xx         |z  cc<   ||xx         | ||                   z  z  cc<   n|dk    r |
||                   ||<   n|dk    r-||xx         |z  cc<   ||xx         |           z  z  cc<   n[|d	k    rU|rd}d}t          ||         |          \  }}|dk    r0|dk    r*           z
  ||<   t          ||         |          \  }}d}^|dk    r||k    r||k    s|} |          |fS )NrI   cgrevcomc                  Z    t           j                                        z
            S rL   r   rM   s   r   r2   zcg.<locals>.get_residualT  rQ   r!   r   r)   r   r
   rR   r$   rT   TrV   rW   Frz   r{   s    `                         @@r   r   r   .  s   6 *!QA66Aq!QAAB$XFXF
QW\
"CZz!122F- - - - - - -S$	q 1 1<FFDv~~{1~~q  EDD!A#AG,,,DDDFE6!QeUD$dCC 	>5%tT5%EGOOHQKKKtAvtAvax((tAvtAvax((BJJ#aiiLLLE!LLLLLLE&&f"6"666LLLLaii!6$v,//DLLaiiLLLE!LLLLLLE&&))O+LLLLaii #DL$77KE4qyyUQYY  !66!99}V'Vd;;t=@ axxEW$$etmm;q>>4r!   z=Use Conjugate Gradient Squared iteration to solve ``Ax = b``.zThe real-valued N-by-N matrix of the linear system.
Alternatively, ``A`` can be a linear operator which can
produce ``Ax`` using, e.g.,
``scipy.sparse.linalg.LinearOperator``.a                 Examples
               --------
               >>> import numpy as np
               >>> from scipy.sparse import csc_matrix
               >>> from scipy.sparse.linalg import cgs
               >>> R = np.array([[4, 2, 0, 1],
               ...               [3, 0, 0, 2],
               ...               [0, 1, 1, 1],
               ...               [0, 2, 1, 0]])
               >>> A = csc_matrix(R)
               >>> b = np.array([-1, -0.5, -1, 2])
               >>> x, exit_code = cgs(A, b)
               >>> print(exit_code)  # 0 indicates successful convergence
               0
               >>> np.allclose(A.dot(x), b)
               True
               c                    t          | ||          \  } }}t                    }	||	dz  }| j        |j        }
t          j        j                 }t          t          |dz             }fd}t          ||t          j
                                      |d          }|dk    r |          dfS |}d}d}t          d	|	z  j        
          }d}d}d}|}	 |} ||||||||	  	        \	  }}}}}}}}|||k    r |           t          |dz
  |dz
  |	z             }t          |dz
  |dz
  |	z             }|dk    r| |           n|dk    r3||xx         |z  cc<   ||xx         | ||                   z  z  cc<   n|dk    r |
||                   ||<   n|dk    r-||xx         |z  cc<   ||xx         |           z  z  cc<   n[|dk    rU|rd}d}t          ||         |          \  }}|dk    r0|dk    r*           z
  ||<   t          ||         |          \  }}d}^|dk    r#t                     z
  |          \  }}|rd}|dk    r||k    r||k    s|} |          |fS )NrI   	cgsrevcomc                  Z    t           j                                        z
            S rL   r   rM   s   r   r2   zcgs.<locals>.get_residual  rQ   r!   r   r)   r   r
   rR   ry   rT   TrV   rW   r$   Firz   )r_   rN   r`   r0   ra   rb   rc   r   rd   re   rf   rh   ri   r2   r   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   okrO   rP   s    `                          @@r   r   r     sN   4 *!QA66Aq!QAAB$XFXF
QW\
"CZ{!233F- - - - - - -S$	q 1 1<GGDv~~{1~~q  EDD!A#AG,,,DDDFE6!QeUD$dCC 	>5%tT5%EGOOHQKKKtAvtAvax((tAvtAvax((BJJ#aiiLLLE!LLLLLLE&&f"6"666LLLLaii!6$v,//DLLaiiLLLE!LLLLLLE&&))O+LLLLaii #DL$77KE4qyyUQYY  !66!99}V'Vd;;t=@ s{{a&&))mT22	r 	DaxxEW$$etmm;q>>4r!   c                   )* ||}n/|t          d          d}t          j        |t          d           ||
t          j        dt          d           |
d	}
|
d
vrt          d|
          |d}
t	          | ||          \  } }*}t                    }||dz  }|d}t          ||          }| j        )|j        }t          *j	        j
                 }t          t          |dz             }t          j                                      }t          j                             |                    })*fd}t!          ||	||d          }	|	dk    r |*          dfS |dk    r |          dfS d}|t          ||	|z            z  }t          j        }t          j        }d}d}t%          d|z   |z  *j	                  }t%          |dz   d|z  dz   z  *j	                  }d}d}d}|}|} d}!d}"d}#	 |}$ |*||||||||||          \	  *}}}}}}%}&}|
dk    r||$k    r |*           t'          |dz
  |dz
  |z             }'t'          |dz
  |dz
  |z             }(|dk    r(|
dv r|"r |||z             n|
dk    r |*           n9|dk    r-||(xx         |&z  cc<   ||(xx         |% )*          z  z  cc<   n|dk    r! |||(                   ||'<   |!s| dk    rd}"d}!n|dk    rN||(xx         |&z  cc<   ||(xx         |% )||'                   z  z  cc<   |"r|
dv r |||z             d}"|#dz   }#nv|dk    rp|rd}d}t)          ||'         |	          \  }}|s||k    rt          dd|z            }nt+          dd |z            }|dk    r|t          ||	|z            z  }n||z  }|} d}|
d	k    r	|#|k    r|}n|dk    r||	k    s|} |*          |fS )!aU  
    Use Generalized Minimal RESidual iteration to solve ``Ax = b``.

    Parameters
    ----------
    A : {sparse matrix, ndarray, LinearOperator}
        The real or complex N-by-N matrix of the linear system.
        Alternatively, ``A`` can be a linear operator which can
        produce ``Ax`` using, e.g.,
        ``scipy.sparse.linalg.LinearOperator``.
    b : ndarray
        Right hand side of the linear system. Has shape (N,) or (N,1).

    Returns
    -------
    x : ndarray
        The converged solution.
    info : int
        Provides convergence information:
          * 0  : successful exit
          * >0 : convergence to tolerance not achieved, number of iterations
          * <0 : illegal input or breakdown

    Other parameters
    ----------------
    x0 : ndarray
        Starting guess for the solution (a vector of zeros by default).
    tol, atol : float, optional
        Tolerances for convergence, ``norm(residual) <= max(tol*norm(b), atol)``.
        The default for ``atol`` is ``'legacy'``, which emulates
        a different legacy behavior.

        .. warning::

           The default value for `atol` will be changed in a future release.
           For future compatibility, specify `atol` explicitly.
    restart : int, optional
        Number of iterations between restarts. Larger values increase
        iteration cost, but may be necessary for convergence.
        Default is 20.
    maxiter : int, optional
        Maximum number of iterations (restart cycles).  Iteration will stop
        after maxiter steps even if the specified tolerance has not been
        achieved.
    M : {sparse matrix, ndarray, LinearOperator}
        Inverse of the preconditioner of A.  M should approximate the
        inverse of A and be easy to solve for (see Notes).  Effective
        preconditioning dramatically improves the rate of convergence,
        which implies that fewer iterations are needed to reach a given
        error tolerance.  By default, no preconditioner is used.
        In this implementation, left preconditioning is used,
        and the preconditioned residual is minimized.
    callback : function
        User-supplied function to call after each iteration.  It is called
        as `callback(args)`, where `args` are selected by `callback_type`.
    callback_type : {'x', 'pr_norm', 'legacy'}, optional
        Callback function argument requested:
          - ``x``: current iterate (ndarray), called on every restart
          - ``pr_norm``: relative (preconditioned) residual norm (float),
            called on every inner iteration
          - ``legacy`` (default): same as ``pr_norm``, but also changes the
            meaning of 'maxiter' to count inner iterations instead of restart
            cycles.
    restrt : int, optional, deprecated

        .. deprecated:: 0.11.0
           `gmres` keyword argument `restrt` is deprecated infavour of
           `restart` and will be removed in SciPy 1.12.0.

    See Also
    --------
    LinearOperator

    Notes
    -----
    A preconditioner, P, is chosen such that P is close to A but easy to solve
    for. The preconditioner parameter required by this routine is
    ``M = P^-1``. The inverse should preferably not be calculated
    explicitly.  Rather, use the following template to produce M::

      # Construct a linear operator that computes P^-1 @ x.
      import scipy.sparse.linalg as spla
      M_x = lambda x: spla.spsolve(P, x)
      M = spla.LinearOperator((n, n), M_x)

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csc_matrix
    >>> from scipy.sparse.linalg import gmres
    >>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
    >>> b = np.array([2, 4, -1], dtype=float)
    >>> x, exitCode = gmres(A, b)
    >>> print(exitCode)            # 0 indicates successful convergence
    0
    >>> np.allclose(A.dot(x), b)
    True
    NzOCannot specify both restart and restrt keywords. Preferably use 'restart' only.zj'gmres' keyword argument 'restrt' is deprecated infavour of 'restart' and will be removed in SciPy 1.12.0.rV   )r'   a4  scipy.sparse.linalg.gmres called without specifying `callback_type`. The default value will be changed in a future release. For compatibility, specify a value for `callback_type` explicitly, e.g., ``{name}(..., callback_type='pr_norm')``, or to retain the old behavior ``{name}(..., callback_type='legacy')``rW   r%   r(   )rP   pr_normr(   zUnknown callback_type: nonerI      gmresrevcomc                  Z    t           j                                        z
            S rL   r   rM   s   r   r2   zgmres.<locals>.get_residual  rQ   r!   r   r)   r   g      ?r
   rR   rS   rT   TFrP   )r   r(   r$   g      ?gؗҜ<g      ?)
ValueErrorr*   r+   r-   r   rY   minrO   r[   rU   r\   r]   r   r   r   r   r4   nanr   r^   r    r/   )+r_   rN   r`   r0   restartra   rb   rc   restrtr   callback_typemsgrd   re   rf   rh   ri   r1   Mb_nrm2r2   ptol_max_factorptolr   presidrj   rk   rl   work2rm   rn   ro   rp   old_ijob
first_passresid_readyiter_numrq   rr   rs   rt   ru   rO   rP   s+    `                                       @@r   r   r     s_   N ~		 : ; ; 	;@c-!<<<< 5 	 @
  2a	A 	A 	A 	A  666D=DDEEE(Ar155Aq!Q{AAB$~^^FXFXF
QW\
"CZ}!455FINN1EinnVVAYY''G- - - - - - -S$|W==Dv~~{1~~q  zz{1~~q   OS$,777DFEVFDD1V8Q,QW555DF1Hqxz2AAAEDDFEHJKH:6!QeUFD$dTXYY 	?5&$dE5$CEW$4$4HQKKKtAvtAvax((tAvtAvax((BJJ 555 -HVe^,,,#%%aiiLLLE!LLLLLLE&&))O+LLLLaii!6$v,//DL #(a--"JJaiiLLLE!LLLLLLE&&f"6"666LLL & $999HVe^,,,##A:aii #DL$77KE4  Ev}}"%c3+@"A"A #&eTO-C"D"DzzOTE\ B BB/H$$'!!u:x qyy%4--;q>>4r!   c	                    !"  !t           d|          \   }	"}
||t          !d          rC!fd}!fd}!fd}!fd}t           j        ||          }t           j        ||          }n1d }t           j        ||          }t           j        ||          }t	                    }||d	z  }t
          "j        j                 }t          t          |d
z             } "fd}t          ||t          j                                      |d          }|dk    r |
"          dfS |}d}d}t          d|z  "j                  }d}d}d}|}	 |} |"|||||||	  	        \	  "}}}}}}}}|||k    r |"           t          |dz
  |dz
  |z             }t          |dz
  |dz
  |z             } |dk    r| |"           n|dk    r>|| xx         |z  cc<   || xx         |                     ||                   z  z  cc<   n9|dk    r=|| xx         |z  cc<   || xx         |                     ||                   z  z  cc<   n|dk    r|                    ||                    ||<   n|dk    r|                    ||                    ||<   n|dk    r|                    ||                    ||<   n|dk    r|                    ||                    ||<   nb|dk    r7|| xx         |z  cc<   || xx         |                     "          z  z  cc<   n%|dk    r|rd}d}t%          ||         |          \  }}d}|dk    r||k    r||k    s|} |
"          |fS )a	  Use Quasi-Minimal Residual iteration to solve ``Ax = b``.

    Parameters
    ----------
    A : {sparse matrix, ndarray, LinearOperator}
        The real-valued N-by-N matrix of the linear system.
        Alternatively, ``A`` can be a linear operator which can
        produce ``Ax`` and ``A^T x`` using, e.g.,
        ``scipy.sparse.linalg.LinearOperator``.
    b : ndarray
        Right hand side of the linear system. Has shape (N,) or (N,1).

    Returns
    -------
    x : ndarray
        The converged solution.
    info : integer
        Provides convergence information:
            0  : successful exit
            >0 : convergence to tolerance not achieved, number of iterations
            <0 : illegal input or breakdown

    Other Parameters
    ----------------
    x0 : ndarray
        Starting guess for the solution.
    tol, atol : float, optional
        Tolerances for convergence, ``norm(residual) <= max(tol*norm(b), atol)``.
        The default for ``atol`` is ``'legacy'``, which emulates
        a different legacy behavior.

        .. warning::

           The default value for `atol` will be changed in a future release.
           For future compatibility, specify `atol` explicitly.
    maxiter : integer
        Maximum number of iterations.  Iteration will stop after maxiter
        steps even if the specified tolerance has not been achieved.
    M1 : {sparse matrix, ndarray, LinearOperator}
        Left preconditioner for A.
    M2 : {sparse matrix, ndarray, LinearOperator}
        Right preconditioner for A. Used together with the left
        preconditioner M1.  The matrix M1@A@M2 should have better
        conditioned than A alone.
    callback : function
        User-supplied function to call after each iteration.  It is called
        as callback(xk), where xk is the current solution vector.

    See Also
    --------
    LinearOperator

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csc_matrix
    >>> from scipy.sparse.linalg import qmr
    >>> A = csc_matrix([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
    >>> b = np.array([2, 4, -1], dtype=float)
    >>> x, exitCode = qmr(A, b)
    >>> print(exitCode)            # 0 indicates successful convergence
    0
    >>> np.allclose(A.dot(x), b)
    True
    Nrf   c                 0                         | d          S Nleftrf   rN   A_s    r   left_psolvezqmr.<locals>.left_psolve(  s    yy6***r!   c                 0                         | d          S Nrightr   r   s    r   right_psolvezqmr.<locals>.right_psolve+  s    yy7+++r!   c                 0                         | d          S r   rg   r   s    r   left_rpsolvezqmr.<locals>.left_rpsolve.  s    zz!F+++r!   c                 0                         | d          S r   r   r   s    r   right_rpsolvezqmr.<locals>.right_rpsolve1  s    zz!G,,,r!   )rO   rZ   c                     | S rL   rD   )rN   s    r   idzqmr.<locals>.id6  s    r!   rI   	qmrrevcomc                  n    t           j                                                           z
            S rL   )r   r   r   rO   )r_   rN   rP   s   r   r2   zqmr.<locals>.get_residualB  s%    y~~ahhqkkAo...r!   r   r)   r   r
   rR      TrV   rW   r$   rX   rS   ry      F)r   hasattrr   shaperY   r[   rU   r\   r]   r   r4   r   r   r   r   r^   rO   rZ   r    )#r_   rN   r`   r0   ra   M1M2rc   r   rb   rd   r   r   r   r   r   re   rh   ri   r2   r   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   r   rP   s#   ``                               @@r   r   r     sy   H 
B)!T2q99Aq!Q	zbj2h 	@+ + + + +, , , , ,, , , , ,- - - - -\RRRBmTTTBB  B???BB???BAAB$
QW\
"CZ{!233F/ / / / / / /S$	q 1 1<GGDv~~{1~~q  EDD"Q$qw''DDDFE"6!QeUD$dCC 	>5%tT5%EGOOHQKKKtAvtAvax((tAvtAvax((BJJ#aiiLLLE!LLLLLLE!((4<"8"888LLLLaiiLLLE!LLLLLLE!))DL"9"999LLLLaii99T&\22DLLaii99T&\22DLLaii::d6l33DLLaii::d6l33DLLaiiLLLE!LLLLLLE!((1++--LLLLaii #DL$77KE4E"H axxEW$$etmm;q>>4r!   )r5   r6   )NrG   NNNN)	NrG   NNNNNNN)NrG   NNNNN)r>   __all__r*   textwrapr	   numpyr   r5   r   scipy.sparse.linalg._interfacer   utilsr   scipy._lib._utilr   scipy._lib._threadsafetyr   r[   r;   r=   r    r4   rF   r   r   r   r   r   r   rD   r!   r   <module>r      s   2 2
6
6
6                  9 9 9 9 9 9       + + + + + + 2 2 2 2 2 23CS11

0 % R  &4 &4 &4R    H9  * ?  ?  ?  + ,? D  9  0 :  :  :  1 2: z F9
  2 ?  ?  ?  3 4? D N9  0 E  E  E  1 2E P PT04p  p  p  p f JNY  Y  Y  Y  Y  Y r!   