L ir,dZgdZddlZddlmZmZddlmZddl m Z ddl m Z m Z ddlZddl ZddlmZdd lmZd d lmZmZd Zd ZdZdZd!dZGddeZGddeZ d"dZ d"dZ GddZ!dZ"dZ#d#dZ$dZ%dZ&dZ'dZ(d Z)y)$z Sparse matrix functions )expminv matrix_powerN)solvesolve_triangular)issparse)spsolve)is_pydata_spmatrix isintlike)LinearOperator) eye_array) _ident_like _exact_1_normupper_triangularcvt|st|s tdt|}t ||}|S)a Compute the inverse of a sparse arrays Parameters ---------- A : (M, M) sparse arrays square matrix to be inverted Returns ------- Ainv : (M, M) sparse arrays inverse of `A` Notes ----- This computes the sparse inverse of `A`. If the inverse of `A` is expected to be non-sparse, it will likely be faster to convert `A` to dense and use `scipy.linalg.inv`. Examples -------- >>> from scipy.sparse import csc_array >>> from scipy.sparse.linalg import inv >>> A = csc_array([[1., 0.], [1., 2.]]) >>> Ainv = inv(A) >>> Ainv >>> A.dot(Ainv) >>> A.dot(Ainv).toarray() array([[ 1., 0.], [ 0., 1.]]) .. versionadded:: 0.12.0 zInput must be a sparse arrays)rr TypeErrorrr )AIAinvs c/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/sparse/linalg/_matfuncs.pyrrs;P QK-a0788 AA 1a=D Kct||k7s|dkr tdt|}t|jdk7s|jd|jdk7r tdt j |jddft }|j}t|D]}|j|}t j|S)a Compute the 1-norm of a non-negative integer power of a non-negative matrix. Parameters ---------- A : a square ndarray or matrix or sparse arrays Input matrix with non-negative entries. p : non-negative integer The power to which the matrix is to be raised. Returns ------- out : float The 1-norm of the matrix power p of A. rzexpected non-negative integer pr%expected A to be like a square matrixdtype) int ValueErrorlenshapenponesfloatTrangedotmax)rpvMis r_onenorm_matrix_power_nnmr-Ps$ 1v{a!e:;; AA 177|qAGGAJ!''!*4@AA Qu-A A 1X EE!H 66!9rcJt|rDtjj|d}|jdk(xs|j dk(St |r%ddl}|j|d}|jdk(Stj|dj S)Nr) rscipysparsetrilnnz count_nonzeror r"any)r lower_partr1s r_is_upper_triangularr7qs{\\&&q"- ~~"Ej&>&>&@A&EE A [[B' ~~""771b>%%'''rct|jdk7r tdt|jdk7r tdd}|tk(rPt |sEt |s:t |s/t |s$t jjd||f\}||d}||||}|S||j|}|S||j|z}|S)a A matrix product that knows about sparse and structured matrices. Parameters ---------- A : 2d ndarray First matrix. B : 2d ndarray Second matrix. alpha : float The matrix product will be scaled by this constant. structure : str, optional A string describing the structure of both matrices `A` and `B`. Only `upper_triangular` is currently supported. Returns ------- M : 2d ndarray Matrix product of A and B. rz%expected A to be a rectangular matrixz%expected B to be a rectangular matrixN)trmm?) r r!rUPPER_TRIANGULARrr r0linalgget_blas_funcsr')rBalpha structurefouts r_smart_matrix_productrCs, 177|q@AA 177|q@AA A$$ HQK*1-6H6K,,YA?BA} =Eq!n J =%%(C J!%%("C Jrc6eZdZddZdZdZdZedZy)MatrixPowerOperatorNc&|jdk7s|jd|jdk7r td|dkr td||_||_||_|j |_|j|_|j|_y)Nrrrrz'expected p to be a non-negative integer)ndimr!r_A_p _structurer)selfrr)r@s r__init__zMatrixPowerOperator.__init__sy 66Q;!''!* 2DE E q5FG G#WW FF WW rcpt|jD]}|jj|}|SN)r&rIrHr')rKxr,s r_matveczMatrixPowerOperator._matvecs/tww A AA rc|jj}|j}t|jD]}|j |}|SrN)rHr%ravelr&rIr')rKrOA_Tr,s r_rmatveczMatrixPowerOperator._rmatvecsCggii GGItww A A rc~t|jD]$}t|j||j}&|SNr@)r&rIrCrHrJ)rKXr,s r_matmatzMatrixPowerOperator._matmats6tww MA%dggqDOOLA MrcVt|jj|jSrN)rErHr%rIrKs rr%zMatrixPowerOperator.Ts"47799dgg66rrN) __name__ __module__ __qualname__rLrPrTrYpropertyr%rrrErEs*   77rrEc8eZdZdZdZdZdZdZedZ y)ProductOperatorzK For now, this is limited to products of multiple square matrices. c|jdd|_|D]D}t|jdk7s |jd|jdk7s;t d|r]|djd}|D]#}|jD]}||k7s t d%||f|_t|j|_t j|Dcgc]}|jc}|_||_ ycc}w)Nr@rrrzbFor now, the ProductOperator implementation is limited to the product of multiple square matrices.zHThe square matrices of the ProductOperator must all have the same shape.) getrJr r!rrGr" result_typer_operator_sequence)rKargskwargsrndrOs rrLzProductOperator.__init__s **[$7 OA177|q AGGAJ!''!*$< NOO O Q a A AAAAv(!@AAA A QDJDJJDI^^t% Initialize the object. Parameters ---------- A : a dense or sparse square numpy matrix or ndarray The matrix to be exponentiated. structure : str, optional A string describing the structure of matrix `A`. Only `upper_triangular` is currently supported. use_exact_onenorm : bool, optional If True then only the exact one-norm of matrix powers and products will be used. Otherwise, the one-norm of powers and products may initially be estimated. N)r_A2_A4_A6_A8_A10 _d4_exact _d6_exact _d8_exact _d10_exact _d4_approx _d6_approx _d8_approx _d10_approxridentr@use_exact_onenorm)rKrr@rs rrLz_ExpmPadeHelper.__init__[s   ^ "!2rc|j1t|j|j|j|_|jSrV)rrCrr@r[s rA2z_ExpmPadeHelper.A2}s4 88 ,FFDFFdnn>DHxxrc|j1t|j|j|j|_|jSrV)rrCrr@r[s rA4z_ExpmPadeHelper.A45 88 ,GGTWW@DHxxrc|j1t|j|j|j|_|jSrV)rrCrrr@r[s rA6z_ExpmPadeHelper.A6rrc|j1t|j|j|j|_|jSrV)rrCrrr@r[s rA8z_ExpmPadeHelper.A8rrc|j1t|j|j|j|_|jSrV)rrCrrr@r[s rA10z_ExpmPadeHelper.A10s6 99 -GGTWW@DIyyrcl|jt|jdz|_|jS)N?)r_onenormrr[s rd4_tightz_ExpmPadeHelper.d4_tight+ >> !%dgg.6DN~~rcl|jt|jdz|_|jS)NUUUUUU?)rrrr[s rd6_tightz_ExpmPadeHelper.d6_tightrrcl|jt|jdz|_|jS)N?)rrrr[s rd8_tightz_ExpmPadeHelper.d8_tightrrcl|jt|jdz|_|jS)N皙?)rrrr[s r d10_tightz_ExpmPadeHelper.d10_tights+ ?? "&txx059DOrc|jr |jS|j |jS|j*t |j d|j dz|_|jS)NrrWr)rrrrryrr@r[s rd4_loosez_ExpmPadeHelper.d4_loose`  ! !== >> %>> !&":477A"&..#248#:?? "rc|jr |jS|j |jS|j*t |j d|j dz|_|jS)NrWr)rrrrryrr@r[s rd6_loosez_ExpmPadeHelper.d6_looserrc|jr |jS|j |jS|j*t |j d|j dz|_|jS)NrrWr)rrrrryrr@r[s rd8_loosez_ExpmPadeHelper.d8_looserrc|jr |jS|j |jS|j5t |j |j f|jdz|_|jS)NrWr)rrrrr|rrr@r[s r d10_loosez_ExpmPadeHelper.d10_loosesl  ! !>> ! ?? &?? "'#67I"&..$249$; ## #rcd}t|j|d|jz|d|jzz|j}|d|jz|d|jzz}||fS)N)g^@gN@g(@r:rrrWrr)rCrrrr@rKbUVs rpade3z_ExpmPadeHelper.pade3sk  !$&&!TWW qtDJJ... * aDL1Q4 ? *!t rc.d}t|j|d|jz|d|jzz|d|jzz|j }|d|jz|d|jzz|d|jzz}||fS) N)g@g@g@@g@z@g>@r:rrrWrr)rCrrrrr@rs rpade5z_ExpmPadeHelper.pade5s 2 !$&&!TWW qtDGG|+ad4::o=.. * aDL1Q4< '!A$tzz/ 9!t rczd}t|j|d|jz|d|jzz|d|jzz|d|j zz|j }|d|jz|d|jzz|d |jzz|d |j zz}||fS) N)g~pAg~`Ag@t>Ag@Ag@g@gL@r:rrrrWrrr)rCrrrrrr@rs rpade7z_ExpmPadeHelper.pade7s L !$&&!TWW qtDGG|+ad477l:QqT$**_L.. * aDL1Q4< '!A$tww, 61djj H!t rcd}t|j|d|jz|d|jzz|d|jzz|d|j zz|d|j zz|j}|d|jz|d |jzz|d |jzz|d |j zz|d |j zz}||fS) N) gynBgynBgAg@ Ag2|Ag~@Ag@g@gV@r: rrrrrWrrrr)rCrrrrrrr@rs rpade9z_ExpmPadeHelper.pade9s 3 !$&&1dgg!TWW ,qtDGG|;aDL!#$Q4 ?3.. *qT$''\AaDL (1Q4< 7!TWW  tDJJ/!t rc^d}|jd| zz}|jdd|zzz}|jdd|zzz}|jdd|zzz}t ||d|z|d|zz|d|zz|j }t |||d |zz|d |zz|d |zz|d |j zz|j }t ||d|z|d|zz|d|zz|j } | |d|zz|d|zz|d|zz|d|j zz} || fS)N)gD`lCgD`\Cg`=Hb;Cg eCgJXBg"5Bg/cBg\L8BgpķAgsyAgS-Ag@gf@r:ri rrWrrrr rrrr)rrrrrCr@r) rKsrr>B2B4B6U2rV2rs r pade13_scaledz_ExpmPadeHelper.pade13_scaled sn " FFQUN WWq2a4y  WWq2a4y  WWq2a4y  "2"b1R58#ad2g-..* "!ad2g!R'aDGd4::o... *#2"b1R58#ad2g-..* 1bL1Q47 "QqT"W ,qtDJJ >!t r)NF)r\r]r^rrrLr_rrrrrrrrrrrrrrrrrrr`rrr~r~Qs* 3D          # # # # # # $ $ rr~ct|dS)a Compute the matrix exponential using Pade approximation. Parameters ---------- A : (M,M) array_like or sparse array 2D Array or Matrix (sparse or dense) to be exponentiated Returns ------- expA : (M,M) ndarray Matrix exponential of `A` Notes ----- This is algorithm (6.1) which is a simplification of algorithm (5.1). .. versionadded:: 0.12.0 References ---------- .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009) "A New Scaling and Squaring Algorithm for the Matrix Exponential." SIAM Journal on Matrix Analysis and Applications. 31 (3). pp. 970-989. ISSN 1095-7162 Examples -------- >>> from scipy.sparse import csc_array >>> from scipy.sparse.linalg import expm >>> A = csc_array([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> A.toarray() array([[1, 0, 0], [0, 2, 0], [0, 0, 3]], dtype=int64) >>> Aexp = expm(A) >>> Aexp >>> Aexp.toarray() array([[ 2.71828183, 0. , 0. ], [ 0. , 7.3890561 , 0. ], [ 0. , 0. , 20.08553692]]) auto)r)_expm)rs rrr"sZ f --rc t|ttztjzrtj |}t |jdk7s|jd|jdk7r td|jdk(rLtjddg|j}t|s t|r|j|S|S|jdk(rVtj|dgg}t|s t|r|j|Stj|St|tj st|s t|rCtj"|jtj$s|j't(}t+|rt,nd}|dk(r|jdd k}t/||| }t1|j2|j4}|d kr:t7|j8d dk(r!|j;\}}t=||| St1|j>|j4}|dkr:t7|j8ddk(r!|jA\}}t=||| St1|jB|jD} | dkr:t7|j8ddk(r!|jG\}}t=||| S| dkr:t7|j8ddk(r!|jI\}}t=||| St1|jD|jJ} tM| | } d} | dk(rd} n>t1tOtjPtjR| | z d} | t7d| z|j8zdz} |jU| \}}t=||| }|t,k(rtW||j8| }|StY| D]}|j[|}|S)Nrrrzexpected a square matrix)rrr)rrr)r@rg,?rrWg|zی@?rgQi?rg d@rg@r). isinstancelisttupler"matrixasarrayr r!rzerosrrr __class__exparrayndarray issubdtypeinexactastyper$r7r;r~r(rr_ellrr _solve_P_Qrrrrrrrminrceillog2r _fragment_2_1r&r')rrrBr@heta_1rreta_2eta_3eta_4eta_5theta_13rrXr,s rrrRs !TE\BII-. JJqM 177|qAGGAJ!''!*4344 ww&hh1vQWW- A;,Q/;;s# #  ww&qw ! A;,Q/;;s# #xx} Arzz "hqk5G5JMM!''2::6 HHUO%9$; IF"GGAJ,  6G IA  AJJ 'E %%$qssA,!*;wwy1!Q)44  AJJ 'E %%$qssA,!*;wwy1!Q)44  AJJ 'E %%$qssA,!*;wwy1!Q)44 %%$qssA,!*;wwy1!Q)44  AKK (E u EH z  BGGBGGEH$4567 ; DQBb !!A ??1 DAq1a9-A$$ !QSS! $ Hq AaA  Hrc||z}| |z}t|s t|r t||S| t||S|tk(r t ||St dt|z)a A helper function for expm_2009. Parameters ---------- U : ndarray Pade numerator. V : ndarray Pade denominator. structure : str, optional A string describing the structure of both matrices `U` and `V`. Only `upper_triangular` is currently supported. Notes ----- The `structure` argument is inspired by similar args for theano and cvxopt functions. zunsupported matrix structure: )rr r rr;rrstr)rrr@PQs rrrsp( AA QA{(+q!}  Q{ & &1%%9C NJKKrct|dkr5||z}tj|d|dz d|dz d|dz zzzzzzStj||ztj||z z d|zz S)a Stably evaluate exp(a)*sinh(x)/x Notes ----- The strategy of falling back to a sixth order Taylor expansion was suggested by the Spallation Neutron Source docs which was found on the internet by google search. http://www.ornl.gov/~t6p/resources/xal/javadoc/gov/sns/tools/math/ElementaryFunction.html The details of the cutoff point and the Horner-like evaluation was picked without reference to anything in particular. Note that sinch is not currently implemented in scipy.special, whereas the "engineer's" definition of sinc is implemented. The implementation of sinc involves a scaling factor of pi that distinguishes it from the "mathematician's" version of sinc. gS㥋?rg@g4@gE@r)absr"r)arOx2s r _exp_sinchrs{0 1v qSvvayABbfqBsF|-D)D EEFFq1u q1u -!A#66rc@d||zz}d||z z}|t||zS)a Equation (10.42) of Functions of Matrices: Theory and Computation. Notes ----- This is a helper function for _fragment_2_1 of expm_2009. Equation (10.42) is on page 251 in the section on Schur algorithms. In particular, section 10.4.3 explains the Schur-Parlett algorithm. expm([[lam_1, t_12], [0, lam_1]) = [[exp(lam_1), t_12*exp((lam_1 + lam_2)/2)*sinch((lam_1 - lam_2)/2)], [0, exp(lam_2)] g?)r)lam_1lam_2t_12rrs r _eq_10_42rs2& uu}A uu}A *Q" ""rcF|jd}tj|jj }d| z}tj ||z}t |D] }|||||f<t |dz ddD]}|j|}d| z}tj ||z}t |D] }|||||f<t |dz D]9}|||z} |||dzz} ||||dzfz} t| | | } | |||dzf<;|S)a A helper function for expm_2009. Notes ----- The argument X is modified in-place, but this modification is not the same as the returned value of the function. This function also takes pains to do things in ways that are compatible with sparse arrays, for example by avoiding fancy indexing and by using methods of the matrices whenever possible instead of using functions of the numpy or scipy libraries themselves. rrrr/) r!r"rRdiagonalcopyrr&r'r) rXr%rridiag_Tscaleexp_diagkr,rrrvalues rrrsT  A XXajjl'') *F !GEvvefn%H 1X1+!Q$1Q3B  EE!HaR66%&.)q "AqkAadG "qs AF1I%EF1Q3K'E1Q!V9$DeUD1EAa1fI  * Hrct|jdk7s|jd|jdk7r tdddddd d }||}d }tt |d|zdz}|sy|t ||zz }t j||z }tt j|d|zz }t|dS) a! A helper function for expm_2009. Parameters ---------- A : linear operator A linear operator whose norm of power we care about. m : int The power of the linear operator Returns ------- value : int A value related to a bound. rrrrg@g`Bg//Cgu; tDg5G)rrrrrg<) r r!rr-rrr"rrrr() rmc_i abs_c_recipu A_abs_onenormr?log2_alpha_div_urs rrr4s" 177|qAGGAJ!''!*4@AA%4  C a&K A.c!facAg>M  Xa[;6 7EwwuQw' (AE23 4E ua=rcF|j\}}||k7r tdt|rmt|}|dkr t d|dk(rt ||j S|dk(r|jSt||dz}|dzr||z|zS||zSt d)a Raise a square matrix to the integer power, `power`. For non-negative integers, ``A**power`` is computed using repeated matrix multiplications. Negative integers are not supported. Parameters ---------- A : (M, M) square sparse array or matrix sparse array that will be raised to power `power` power : int Exponent used to raise sparse array `A` Returns ------- A**power : (M, M) sparse array or matrix The output matrix will be the same shape as A, and will preserve the class of A, but the format of the output may be changed. Notes ----- This uses a recursive implementation of the matrix power. For computing the matrix power using a reasonably large `power`, this may be less efficient than computing the product directly, using A @ A @ ... @ A. This is contingent upon the number of nonzero entries in the matrix. .. versionadded:: 1.12.0 Examples -------- >>> from scipy import sparse >>> A = sparse.csc_array([[0,1,0],[1,0,1],[0,1,0]]) >>> A.todense() array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) >>> (A @ A).todense() array([[1, 0, 1], [0, 2, 0], [1, 0, 1]]) >>> A2 = sparse.linalg.matrix_power(A, 2) >>> A2.todense() array([[1, 0, 1], [0, 2, 0], [1, 0, 1]]) >>> A4 = sparse.linalg.matrix_power(A, 4) >>> A4.todense() array([[2, 0, 2], [0, 4, 0], [2, 0, 2]]) zsparse matrix is not squarerzexponent must be >= 0rrrzexponent must be an integer) r!rr rrr rrr)rpowerr+Ntmps rrrbsj 77DAqAv566E  1945 5 A:Qagg. . A:668O1eqj) 19s7S= 9 677r)NN)rrFFNrN)*rr__all__numpyr"scipy.linalg._basicrrscipy.sparse._baserscipy.sparse.linalgr scipy.sparse._sputilsr r scipy.sparser0scipy.sparse.linalg._interfacer scipy.sparse._constructr _expm_multiplyrrrr;rr-r7rCrErbryr|r~rrrrrrrrr`rrrs *7''?9-B&.bB ((V!7.!7H,(n,(`CG&#0. b,\J8r