
    Ui=                         d dl Zd dlmZ d dlmZmZmZmZm	Z	m
Z
 ddlmZ d dlmZ dgZ	 	 dd
Zdddddddddd	dd
dZdS )    N)LinAlgError)get_blas_funcsqrsolvesvd	qr_insertlstsq   )_get_atol_rtol)make_systemgcrotmk Fc	           
      0   |d }|d }t          g d|f          \  }	}
}}|g}g }d}t          j        }|t          |          z   }t          j        t          |          |f|j                  }t          j        d|j                  }t          j        d|j                  }t          j        |j                  j        }d}t          |          D ]}|r|t          |          k     r||         \  }}nm|r!|t          |          k    r ||          }d}nJ|s5||t          |          z
  k    r|||t          |          z
  z
           \  }}n ||d	                   }d}| | | |                    }n|
                                } ||          }t          |          D ]2\  }} |
||          }||||f<    |	|||j        d
         |           }3t          j        |dz   |j                  }t          |          D ]0\  }} |
||          }|||<    |	|||j        d
         |           }1 ||          ||dz   <   t          j        dd          5  d|d	         z  }ddd           n# 1 swxY w Y   t          j        |          r |||          }|d	         ||z  k    sd}|                    |           |                    |           t          j        |dz   |dz   f|j        d          }||d|dz   d|dz   f<   d||dz   |dz   f<   t          j        |dz   |f|j        d          } || d|dz   ddf<   t!          || ||ddd          \  }}t#          |d                   }||k     s|r nt          j        |||f                   st%                      t'          |d|dz   d|dz   f         |d
d|dz   f                                                   \  }}!}!}!|ddd|dz   f         }|||||||fS )a  
    FGMRES Arnoldi process, with optional projection or augmentation

    Parameters
    ----------
    matvec : callable
        Operation A*x
    v0 : ndarray
        Initial vector, normalized to nrm2(v0) == 1
    m : int
        Number of GMRES rounds
    atol : float
        Absolute tolerance for early exit
    lpsolve : callable
        Left preconditioner L
    rpsolve : callable
        Right preconditioner R
    cs : list of (ndarray, ndarray)
        Columns of matrices C and U in GCROT
    outer_v : list of ndarrays
        Augmentation vectors in LGMRES
    prepend_outer_v : bool, optional
        Whether augmentation vectors come before or after
        Krylov iterates

    Raises
    ------
    LinAlgError
        If nans encountered

    Returns
    -------
    Q, R : ndarray
        QR decomposition of the upper Hessenberg H=QR
    B : ndarray
        Projections corresponding to matrix C
    vs : list of ndarray
        Columns of matrix V
    zs : list of ndarray
        Columns of matrix Z
    y : ndarray
        Solution to ||H y - e_1||_2 = min!
    res : float
        The final (preconditioned) residual norm

    Nc                     | S Nr   xs    |/var/www/development/aibuddy-work/election-extract/venv/lib/python3.11/site-packages/scipy/sparse/linalg/_isolve/_gcrotmk.pylpsolvez_fgmres.<locals>.lpsolve@       H    c                     | S r   r   r   s    r   rpsolvez_fgmres.<locals>.rpsolveC   r   r   axpydotscalnrm2)dtype)r
   r
   )r
   r   Fr      r
   ignore)overdivideTFr   ordercol)whichoverwrite_qrucheck_finite)r   r    )r   npnanlenzerosr   onesfinfoepsrangecopy	enumerateshapeerrstateisfiniteappendr   absr   r	   conj)"matvecv0matolr   r   csouter_vprepend_outer_vr   r   r   r   vszsyresBQRr2   	breakdownjzww_normicalphahcurvQ2R2_s"                                     r   _fgmresrW      s	   b 	 	 		 	 	 ++J+J+JRERRD#tT
B	BA
&C	CLLA 	#b''1RX...A 	bh'''A
rx(((A
(28


 CI 1XX K K  		q3w<<//1:DAqq 	c'll!2!2AAA  	Q!c'll*:%:%:1CLL 012DAqq2AA9q		""AA Aa bMM 	/ 	/DAqC1IIEAacFQ171:v..AA x!17+++bMM 	/ 	/DAqC1IIEDGQ171:v..AADGGQqS	[hx888 	 	d2hJE	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ;u 	UAAR3<'' I
		!
		!
 XqsAaCjs;;;4AaC4191Q3qs7XqsAhagS9994AaC46
Rq'+%A A A1 !D'll :::E  ;q1v mm $1Q3$t!t)a$1Q3$inn&6&677KAq!Q	!!!DQqSD&	AaBAs""s   %I==J	J	gh㈵>g        i     oldest)
rtolr?   maxiterMcallbackr>   kCU	discard_Ctruncatec       
         $   t          | |||          \  } }}}t          j        |                                          st	          d          |dvrt	          d|          | j        }|j        }|
g }
|	|}	d\  }}}||                                }n| ||          z
  }t          g d||f          \  }}}} ||          }t          d|||          \  }}|dk    r|}|dfS |rd	 |
D             |
dd<   |
r|
	                    d
            t          j
        | j        d         t          |
          f|j        d          }g }d}|
rJ|
                    d          \  }}| ||          }||dd|f<   |dz  }|                    |           |
Jt!          |ddd          \  }}}~t#          |j                  }g }t'          t          |                    D ]}|||                  }t'          |          D ]0}  ||||                   ||j        d         || |f                    }1t)          |||f                   dt)          |d                   z  k     r n- |d|||f         z  |          }|                    |           t#          t+          ||                    ddd         |
dd<   |
r]t          ddg|f          \  }}|
D ]D\  }} |||          }! ||||j        d         |!          } ||||j        d         |!           }Et'          |          D ]}"| ||            ||          }#t-          |||z            }$|#|$k    r!|"dk    s|
r| ||          z
  } ||          }#|#|$k    rd}" n@|t-          |	t          |
          z
  d          z   }%d |
D             }	 t/          |||#z  |%|t-          |||z            |#z  |          \  }}}&}'}(})}*|)|#z  })n# t0          $ r Y  nw xY w|(d         |)d         z  }+t+          |(dd         |)dd                   D ]\  },}! ||,|+|+j        d         |!          }+|&                    |)          }-t+          |
|-          D ]$\  }.}/|.\  }} |||+|+j        d         |/           }+%t          j        d          5  |                    |                    |)                    }0ddd           n# 1 swxY w Y   |'d         |0d         z  }1t+          |'dd         |0dd                   D ]\  }2}3 ||2|1|1j        d         |3          }1	 d ||1          z  }4t          j        |4          st7                      n# t6          t8          f$ r Y aw xY w ||4|1          }1 ||4|+          }+ ||1|          }5 ||1||j        d         |5           } ||+||j        d         |5          }|dk    r/t          |
          |	k    r|
r|
d= t          |
          |	k    r|
n|dk    rt          |
          |	k    r{|
rxt;          |ddddf         j        |&j                  j        }6t=          |6          \  }7}8}9g }:t?          |7ddd|	dz
  f         j                  D ]\  }};|
d         \  }}||;d         z  }||;d         z  }t+          |
dd         |;dd                   D ]<\  }<}=|<\  }>}? ||>||j        d         |=          } ||?||j        d         |=          }=|:D ]E\  }>}? ||>|          }4 ||>||j        d         |4           } ||?||j        d         |4           }F ||          }4 |d|4z  |          } |d|4z  |          }|:                    ||f           |:|
dd<   |
                    |1|+f           |
                    d|                                f           |rd |
D             |
dd<   ||"dz   fS )a  
    Solve ``Ax = b`` with the flexible GCROT(m,k) algorithm.

    Parameters
    ----------
    A : {sparse array, 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.,
        `LinearOperator`.
    b : ndarray
        Right hand side of the linear system. Has shape (N,) or (N,1).
    x0 : ndarray
        Starting guess for the solution.
    rtol, atol : float, optional
        Parameters for the convergence test. For convergence,
        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
        The default is ``rtol=1e-5`` and ``atol=0.0``.
    maxiter : int, optional
        Maximum number of iterations.  Iteration will stop after maxiter
        steps even if the specified tolerance has not been achieved. The
        default is ``1000``.
    M : {sparse array, ndarray, LinearOperator}, optional
        Preconditioner for `A`.  The preconditioner should approximate the
        inverse of `A`. gcrotmk is a 'flexible' algorithm and the preconditioner
        can vary from iteration to iteration. Effective preconditioning
        dramatically improves the rate of convergence, which implies that
        fewer iterations are needed to reach a given error tolerance.
    callback : function, optional
        User-supplied function to call after each iteration.  It is called
        as ``callback(xk)``, where ``xk`` is the current solution vector.
    m : int, optional
        Number of inner FGMRES iterations per each outer iteration.
        Default: 20
    k : int, optional
        Number of vectors to carry between inner FGMRES iterations.
        According to [2]_, good values are around `m`.
        Default: `m`
    CU : list of tuples, optional
        List of tuples ``(c, u)`` which contain the columns of the matrices
        C and U in the GCROT(m,k) algorithm. For details, see [2]_.
        The list given and vectors contained in it are modified in-place.
        If not given, start from empty matrices. The ``c`` elements in the
        tuples can be ``None``, in which case the vectors are recomputed
        via ``c = A u`` on start and orthogonalized as described in [3]_.
    discard_C : bool, optional
        Discard the C-vectors at the end. Useful if recycling Krylov subspaces
        for different linear systems.
    truncate : {'oldest', 'smallest'}, optional
        Truncation scheme to use. Drop: oldest vectors, or vectors with
        smallest singular values using the scheme discussed in [1,2].
        See [2]_ for detailed comparison.
        Default: 'oldest'

    Returns
    -------
    x : ndarray
        The solution found.
    info : int
        Provides convergence information:

        * 0  : successful exit
        * >0 : convergence to tolerance not achieved, number of iterations

    References
    ----------
    .. [1] E. de Sturler, ''Truncation strategies for optimal Krylov subspace
           methods'', SIAM J. Numer. Anal. 36, 864 (1999).
    .. [2] J.E. Hicken and D.W. Zingg, ''A simplified and flexible variant
           of GCROT for solving nonsymmetric linear systems'',
           SIAM J. Sci. Comput. 32, 172 (2010).
    .. [3] M.L. Parks, E. de Sturler, G. Mackey, D.D. Johnson, S. Maiti,
           ''Recycling Krylov subspaces for sequences of linear systems'',
           SIAM J. Sci. Comput. 28, 1651 (2006).

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse import csc_array
    >>> from scipy.sparse.linalg import gcrotmk
    >>> R = np.random.randn(5, 5)
    >>> A = csc_array(R)
    >>> b = np.random.randn(5)
    >>> x, exit_code = gcrotmk(A, b, atol=1e-5)
    >>> print(exit_code)
    0
    >>> np.allclose(A.dot(x), b)
    True

    z$RHS must contain only finite numbers)rY   smallestzInvalid value for 'truncate': N)NNNr   r   r   c                     g | ]	\  }}d |f
S r   r   .0rP   us      r   
<listcomp>zgcrotmk.<locals>.<listcomp>8  s     ***tq!$***r   c                     | d         d uS )Nr   r   )cus    r   <lambda>zgcrotmk.<locals>.<lambda>=  s    r!uD0 r   )keyr%   r&   r
   Teconomic)overwrite_amodepivotingg-q=)r   r   g      ?r    r   r   c                     g | ]\  }}|S r   r   re   s      r   rh   zgcrotmk.<locals>.<listcomp>  s    DAqar   )r   r?   r@   r"   )invalidrY   rc   c                     g | ]	\  }}d |f
S r   r   )rf   czuzs      r   rh   zgcrotmk.<locals>.<listcomp>  s     ---B$---r   ) r   r,   r8   all
ValueErrorr<   r4   r   r   sortemptyr6   r.   r   popr9   r   listTr3   r:   zipmaxrW   r   r   r7   FloatingPointErrorZeroDivisionErrorr   r   r5   )@Abx0rZ   r?   r[   r\   r]   r>   r^   r_   r`   ra   r   r<   psolver   r   r   rr   b_normCusrK   rP   rg   rH   rI   Pr@   new_usrO   ycj_outerbetabeta_tolmlrG   rC   rD   rE   presuxrL   byrj   bychycxrS   hycrQ   gammaDWsigmaVnew_CUrM   cupwpcpups@                                                                   r   r   r      s	   x !Ab##GAa!;q>> A?@@@---F(FFGGGXFXF	zy&OD#t	zFFHHq		M*+J+J+JQPQFSSD#tTT!WWF  	64>>JD${{1v +**r***111 
 %,
00111 Hagaj#b''*!'EEE 	66!99DAqyF1IIAaaacFFAIIaLLL  	 QDzDIII1a !#YY s2ww 	 	A1Q4A1XX ; ;DAaD1agaj1QqS6'::1QqS6{{US3[[000S1Q3Z##AMM! SV__%%ddd+111	 ,"FE?QD99	c  	, 	,DAqQBQ171:r**AQ171:s++AA >> } }HQKKKtAww tTF]++81FF1IIA477D8GEQR[!$$$B	'.v/0v/17=47d6k4J4J44O24(6 (6 (6$Aq!RQ IAA 	 	 	 EE	2 U1Q4ZABB122'' 	. 	.EAraRXa["--BBUU1XX2r{{ 	0 	0GBDAqaRXa[3$//BB [*** 	! 	!quuQxxB	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!URU]"QRR&"QRR&)) 	/ 	/FAsaRXa[#..BB	dd2hhJE;u%% +(***+"$56 	 	 	H	 T%__T%__ B

DQ
UF++DQ
E** xb''Q,,2,qE b''Q,,2,##2ww!|||!CRCE(*ac**,!!ff5! %a$1Q3$ik22 * *DAqa5DAqAaDAAaDA#&r!""vqu#5#5 8 8R!$B DQ
B77 DQ
B77
 #) < <B #B

 DQ
UF;; DQ
UF;; DGGESY**ASY**AMM1a&))))111 			2r( IItQVVXX .--"---111gk>s6   ?9O99
PP:)S//S3	6S3	0U<<VV)NNr   r   Fr   )numpyr,   numpy.linalgr   scipy.linalgr   r   r   r   r   r	   	iterativer   !scipy.sparse.linalg._isolve.utilsr   __all__rW   r   r   r   r   <module>r      s        $ $ $ $ $ $ K K K K K K K K K K K K K K K K % % % % % % 9 9 9 9 9 9 + MO!g# g# g# g#T4b$$QUDTUX      r   