
    ^Mh]D                         d dl Zd dlmZm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mZmZmZmZmZmZmZ ddlmZmZ d	Zd
ZdZdZd Zd Zd Z G d de          Z  G d de          Z!dS )    N)	lu_factorlu_solve)issparse
csc_matrixeye)splu)group_columns   )validate_max_stepvalidate_tolselect_initial_stepnormEPSnum_jacvalidate_first_stepwarn_extraneous)	OdeSolverDenseOutput      g?
   c                    t          j        d| dz             dddf         }t          j        d| dz             }t          j        | dz   | dz   f          }|dz
  ||z  z
  |z  |ddddf<   d|d<   t          j        |d          S )z6Compute the matrix for changing the differences array.r
   Nr   axis)nparangezeroscumprod)orderfactorIJMs        X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/integrate/_ivp/bdf.py	compute_Rr%      s    
	!UQY4(A
	!UQYA
%!)UQY'((AQ!#q(Aabb!""fIAaD:aa        c                     t          ||          }t          |d          }|                    |          }t          j        |j        | d|dz                      | d|dz   <   dS )z<Change differences array in-place when step size is changed.r
   N)r%   dotr   T)Dr   r    RURUs         r$   change_Dr.      s^    %  A%A	
qBF24:EAI://AjuqyjMMMr&   c	                    d}	|                                 }
d}d}t          t                    D ]} | ||
          }t          j        t          j        |                    s n} ||||z  |z
  |	z
            }t          ||z            }|d}n||z  }|"|dk    s|t          |z
  z  d|z
  z  |z  |k    r n(|
|z  }
|	|z  }	|dk    s||d|z
  z  |z  |k     rd} n|}||dz   |
|	fS )z5Solve the algebraic system resulting from BDF method.r   NFr
   T)copyrangeNEWTON_MAXITERr   allisfiniter   )funt_new	y_predictcpsiLUsolve_luscaletoldydy_norm_old	convergedkfdydy_normrates                     r$   solve_bdf_systemrG   $   s=   	AAKI>""  CqMMvbk!nn%% 	EXb!a%#+/**rEz""DD[(D$!))!+,D9GCcIIE	R	RqLL TQX%6%@3%F%FIEa!eQ!!r&   c                   N     e Zd ZdZej        ddddddf fd	Zd Zd Zd	 Z	 xZ
S )
BDFa  Implicit method based on backward-differentiation formulas.

    This is a variable order method with the order varying automatically from
    1 to 5. The general framework of the BDF algorithm is described in [1]_.
    This class implements a quasi-constant step size as explained in [2]_.
    The error estimation strategy for the constant-step BDF is derived in [3]_.
    An accuracy enhancement using modified formulas (NDF) [2]_ is also implemented.

    Can be applied in the complex domain.

    Parameters
    ----------
    fun : callable
        Right-hand side of the system: the time derivative of the state ``y``
        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
        return an array of the same shape as ``y``. See `vectorized` for more
        information.
    t0 : float
        Initial time.
    y0 : array_like, shape (n,)
        Initial state.
    t_bound : float
        Boundary time - the integration won't continue beyond it. It also
        determines the direction of the integration.
    first_step : float or None, optional
        Initial step size. Default is ``None`` which means that the algorithm
        should choose.
    max_step : float, optional
        Maximum allowed step size. Default is np.inf, i.e., the step size is not
        bounded and determined solely by the solver.
    rtol, atol : float and array_like, optional
        Relative and absolute tolerances. The solver keeps the local error
        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
        relative accuracy (number of correct digits), while `atol` controls
        absolute accuracy (number of correct decimal places). To achieve the
        desired `rtol`, set `atol` to be smaller than the smallest value that
        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
        number of correct digits is not guaranteed. Conversely, to achieve the
        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
        than `atol`. If components of y have different scales, it might be
        beneficial to set different `atol` values for different components by
        passing array_like with shape (n,) for `atol`. Default values are
        1e-3 for `rtol` and 1e-6 for `atol`.
    jac : {None, array_like, sparse_matrix, callable}, optional
        Jacobian matrix of the right-hand side of the system with respect to y,
        required by this method. The Jacobian matrix has shape (n, n) and its
        element (i, j) is equal to ``d f_i / d y_j``.
        There are three ways to define the Jacobian:

            * If array_like or sparse_matrix, the Jacobian is assumed to
              be constant.
            * If callable, the Jacobian is assumed to depend on both
              t and y; it will be called as ``jac(t, y)`` as necessary.
              For the 'Radau' and 'BDF' methods, the return value might be a
              sparse matrix.
            * If None (default), the Jacobian will be approximated by
              finite differences.

        It is generally recommended to provide the Jacobian rather than
        relying on a finite-difference approximation.
    jac_sparsity : {None, array_like, sparse matrix}, optional
        Defines a sparsity structure of the Jacobian matrix for a
        finite-difference approximation. Its shape must be (n, n). This argument
        is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
        elements in *each* row, providing the sparsity structure will greatly
        speed up the computations [4]_. A zero entry means that a corresponding
        element in the Jacobian is always zero. If None (default), the Jacobian
        is assumed to be dense.
    vectorized : bool, optional
        Whether `fun` can be called in a vectorized fashion. Default is False.

        If ``vectorized`` is False, `fun` will always be called with ``y`` of
        shape ``(n,)``, where ``n = len(y0)``.

        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
        the returned array is the time derivative of the state corresponding
        with a column of ``y``).

        Setting ``vectorized=True`` allows for faster finite difference
        approximation of the Jacobian by this method, but may result in slower
        execution overall in some circumstances (e.g. small ``len(y0)``).

    Attributes
    ----------
    n : int
        Number of equations.
    status : string
        Current status of the solver: 'running', 'finished' or 'failed'.
    t_bound : float
        Boundary time.
    direction : float
        Integration direction: +1 or -1.
    t : float
        Current time.
    y : ndarray
        Current state.
    t_old : float
        Previous time. None if no steps were made yet.
    step_size : float
        Size of the last successful step. None if no steps were made yet.
    nfev : int
        Number of evaluations of the right-hand side.
    njev : int
        Number of evaluations of the Jacobian.
    nlu : int
        Number of LU decompositions.

    References
    ----------
    .. [1] G. D. Byrne, A. C. Hindmarsh, "A Polyalgorithm for the Numerical
           Solution of Ordinary Differential Equations", ACM Transactions on
           Mathematical Software, Vol. 1, No. 1, pp. 71-96, March 1975.
    .. [2] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
           COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
    .. [3] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations I:
           Nonstiff Problems", Sec. III.2.
    .. [4] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
           sparse Jacobian matrices", Journal of the Institute of Mathematics
           and its Applications, 13, pp. 117-120, 1974.
    gMbP?gư>NFc                     t          |           t                                          |||||
d           t          |           _        t          || j                  \   _         _         	                     j
         j                  }|<t           j	         j
         j        ||| j        d j         j        
  
         _        nt          |||           _        d  _        d  _        t%          dt&          z  |z  t)          d|dz                       _        d  _                             ||	          \   _         _        t5           j                  r* fd}d }t7           j        d	 j        j        
          }n- fd}d }t;          j         j         j        j                  }| _        | _         | _!        t;          j"        g d          }t;          j#        dt;          j$        dt;          j%        dtL          dz             z            f           _'        d|z
   j'        z   _(        | j'        z  dt;          j%        dtL          dz             z  z    _)        t;          j*        tL          dz    j        f j        j                  } j        |d<   | j        z   j        z  |d<   | _+        d _,        d _-        d  _.        d S )NT)support_complexr
   r   gQ?      ?c                 B    xj         dz  c_         t          |           S Nr
   )nlur   Aselfs    r$   luzBDF.__init__.<locals>.lu   s    AAwwr&   c                 ,    |                      |          S )N)solver:   bs     r$   r;   zBDF.__init__.<locals>.solve_lu   s    xx{{"r&   csc)formatdtypec                 F    xj         dz  c_         t          | d          S )Nr
   T)overwrite_a)rO   r   rP   s    r$   rS   zBDF.__init__.<locals>.lu   s%    A 5555r&   c                 &    t          | |d          S )NT)overwrite_b)r   rV   s     r$   r;   zBDF.__init__.<locals>.solve_lu   s    A48888r&   rZ   )r   gGzǿgqqgugsh|?r   r         )/r   super__init__r   max_stepr   nrtolatolr5   tr?   r   	directionh_absr   	h_abs_olderror_norm_oldmaxr   min
newton_tol
jac_factor_validate_jacjacr"   r   r   rZ   r   identityrS   r;   r!   arrayhstackcumsumr   	MAX_ORDERgammaalphaerror_constemptyr*   r   n_equal_stepsr:   )rR   r5   t0y0t_boundrd   rf   rg   rr   jac_sparsity
vectorized
first_step
extraneousrC   rS   r;   r!   kappar*   	__class__s   `                  r$   rc   zBDF.__init__   s    	
###b"gz)- 	 	/ 	/ 	/)(33+D$??	49HHTVTV$$,TXtvtv-4h-1^Q-1Y	C CDJJ
 -ZWEEDJ"b3hos4/E/EFF--c<@@$&DF 	8    # # # DF5===AA6 6 6 6 69 9 9 DF$&,777A @@@AAY29Q1i!m1L1L-L#M#MNOO
%i4:-
 4:-BIaQ4O4O0OOHi!mTV,DFLAAAv!4:~.!
r&   c                 4     j         } j        G1t                    rt                    t	                    }|f fd} ||          }n:t                    r |          } xj        dz  c_        t          |          rt          |j                  } fd}n"t          j	        |j                  } fd}|j
         j         j        fk    r't          d j         j        f d|j
         d          nt                    rt          j                  }nt          j	        j                  }|j
         j         j        fk    r't          d j         j        f d|j
         d          d }||fS )	Nc           	          xj         dz  c_                             | |          }t          j        | ||j        j                  \  }_        |S rN   )njev
fun_singler   fun_vectorizedrg   rp   )rh   r?   rC   r"   rR   sparsitys       r$   jac_wrappedz&BDF._validate_jac.<locals>.jac_wrapped  sY    		Q		OOAq))%,T-@!Q-1Y-5&7 &7"4? r&   r
   r_   c                 d    xj         dz  c_         t           | |          j                  S Nr
   r_   )r   r   rZ   rh   r?   rr   rR   r~   s     r$   r   z&BDF._validate_jac.<locals>.jac_wrapped  s1    IINII%cc!Qiirx@@@@r&   c                 n    xj         dz  c_         t          j         | |          j                  S r   )r   r   asarrayrZ   r   s     r$   r   z&BDF._validate_jac.<locals>.jac_wrapped   s3    IINII:cc!Qiirx@@@@r&   z `jac` is expected to have shape z, but actually has .)rh   r?   r   r   r	   callabler   rZ   r   r   shapere   
ValueError)rR   rr   r   r}   groupsr   r"   r~   s   ```    @r$   rq   zBDF._validate_jac  sW   VV;#H%% 4)(33H&x00$f-      B##AAc]] 	BAIINII{{ Aq111A A A A A A A A Jq111A A A A A A A w4646***  "ATVTVDT "A "A67g"A "A "A B B B + }} 4s"(333Js"(333w4646***  "ATVTVDT "A "A67g"A "A "A B B BKA~r&   c                 n
   | j         }| j        }| j        }dt          j        t          j        || j        t          j        z            |z
            z  }| j        |k    r(|}t          || j
        || j        z             d| _        n:| j        |k     r(|}t          || j
        || j        z             d| _        n| j        }| j        }| j        }| j
        }| j        }	| j        }
| j        }| j        }| j        }| j        d u }d}|s;||k     r	d| j        fS || j        z  }||z   }| j        || j        z
  z  dk    r9| j        }t          ||t          j        ||z
            |z             d| _        d }||z
  }t          j        |          }t          j        |d |dz            d          }||t          j        |          z  z   }t          j        |d|dz            j        |
d|dz                      |	|         z  }d}||	|         z  }|sn| |                     | j        ||z  z
            }t7          | j        |||||| j        || j        	  	        \  }}}}|s|rn|                     ||          }d }d}|n|s#d}||z  }t          |||           d| _        d }dd	t>          z  dz   z  d	t>          z  |z   z  }||t          j        |          z  z   }||         |z  }tA          ||z            }|dk    r?tC          tD          ||d
|dz   z  z  z            }||z  }t          |||           d| _        nd}|;| xj        dz  c_        || _         || _#        || _        || _        || _        |||dz            z
  ||d	z   <   |||dz   <   tI          tK          |dz                       D ]}||xx         ||dz            z  cc<   | j        |dz   k     rdS |dk    r'||dz
           ||         z  }tA          ||z            } nt          j        } |tL          k     r*||dz            ||d	z            z  }!tA          |!|z            }"nt          j        }"t          j'        | ||"g          }#t          j(        d          5  |#d
t          j)        ||dz             z  z  }$d d d            n# 1 swxY w Y   t          j*        |$          dz
  }%||%z  }|| _
        tW          tX          |t          j!        |$          z            }| xj        |z  c_        t          |||           d| _        d | _        dS )Nr   r   Fr
   r   TrL   g?r`   )TNignore)dividera   )-rh   r*   rd   r   abs	nextafterri   infrj   r.   r   r|   rg   rf   ry   rx   rz   r"   r:   rr   TOO_SMALL_STEPr   sumr(   r)   rS   r!   rG   r5   r;   ro   r2   r   rm   
MIN_FACTORr?   reversedr1   rw   rt   errstater   argmaxrn   
MAX_FACTOR)&rR   rh   r*   rd   min_steprj   rg   rf   r   ry   rx   rz   r"   r:   current_jacstep_acceptedhr6   r7   r<   r9   rA   r8   n_itery_newr>   r    safetyerror
error_normierror_merror_m_normerror_perror_p_normerror_normsfactorsdelta_orders&                                         r$   
_step_implzBDF._step_impl4  s!   FF=r|At~/FGG!KLLL:  EQ
Htz$9:::!"DZ(""EQ
Htz$9:::!"DJEyy


&FWh$& >	%xd111&AEE~!56::E26%!)#4#4u#<===%&"	AF1IIEq%!)}1555I4"&"3"333E&1eai<*E!UQY,,?@@5<OCIE%L A ':!a%00B.>HeY3DM4?/, /,+	65! ! '" 	22AB"&K   '  E6***%&"A.23q>7I9?8@ AF 4"&--//E&*Eeem,,JA~~Z#jR5195E&FFH HE6***%&"" !%}   >	%@ 	a
 1UQY<'%!)%!)%	**++ 	 	AaDDDAa!eHDDDD	)):199!%!),qx7G%00LL6L9!%!),q|;G%00LL6Lhj,GHH[))) 	H 	H!b29UEAI+F+F&FGG	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H 	H i((1,
Z"&//!9::

f

E6"""zs   R..R25R2c           
          t          | j        | j        | j        | j        z  | j        | j        d | j        dz                                                      S rN   )BdfDenseOutputt_oldrh   rj   ri   r   r*   r0   )rR   s    r$   _dense_output_implzBDF._dense_output_impl  sN    dj$&$*t~2M"j$&$*q.*A*F*F*H*HJ J 	Jr&   )__name__
__module____qualname____doc__r   r   rc   rq   r   r   __classcell__r   s   @r$   rI   rI   H   s        { {x 79f4d!d: : : : : :x1 1 1fM M M^J J J J J J Jr&   rI   c                   $     e Zd Z fdZd Z xZS )r   c                    t                                          ||           || _        | j        |t	          j        | j                  z  z
  | _        |dt	          j        | j                  z   z  | _        || _        d S rN   )	rb   rc   r   rh   r   r   t_shiftdenomr*   )rR   r   rh   r   r   r*   r   s         r$   rc   zBdfDenseOutput.__init__  sk    """
vBIdj$9$9 99!bi
3334
r&   c                    |j         dk    r'|| j        z
  | j        z  }t          j        |          }n<|| j        d d d f         z
  | j        d d d f         z  }t          j        |d          }t          j        | j        dd          j        |          }|j         dk    r|| j        d         z  }n|| j        dd d d f         z  }|S )Nr   r   r
   )ndimr   r   r   r   r(   r*   r)   )rR   rh   xpr?   s        r$   
_call_implzBdfDenseOutput._call_impl  s    6Q;;T\!TZ/A
1AAT\!!!T'**djD.AAA
11%%%AF46!"":<##6Q;;NAA111d
##Ar&   )r   r   r   rc   r   r   r   s   @r$   r   r     sG                  r&   r   )"numpyr   scipy.linalgr   r   scipy.sparser   r   r   scipy.sparse.linalgr   scipy.optimize._numdiffr	   commonr   r   r   r   r   r   r   r   baser   r   rw   r2   r   r   r%   r.   rG   rI   r    r&   r$   <module>r      s       , , , , , , , , 2 2 2 2 2 2 2 2 2 2 $ $ $ $ $ $ 1 1 1 1 1 1& & & & & & & & & & & & & & & & & & & & ) ( ( ( ( ( ( ( 	

! ! !0 0 0!" !" !"H}J }J }J }J }J) }J }J }J@    [     r&   