
    5[gD                         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!y)    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        S/var/www/html/bid-api/venv/lib/python3.12/site-packages/scipy/integrate/_ivp/bdf.py	compute_Rr%      s    
		!UQY4(A
		!UQYA
%!)UQY'(AQ!#q(Aab!"fIAaD::aa      c                     t        ||      }t        |d      }|j                  |      }t        j                  |j                  | d|dz          | d|dz    y)z<Change differences array in-place when step size is changed.r
   N)r%   dotr   T)Dr   r    RURUs         r$   change_Dr.      sO    % A%A	
qBFF244:EAI/AjuqyMr&   c	                    d}	|j                         }
d}d}t        t              D ]  } | ||
      }t        j                  t        j
                  |            s nr ||||z  |z
  |	z
        }t        ||z        }|d}n||z  }||dk\  s|t        |z
  z  d|z
  z  |z  |kD  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>"qMvvbkk!n%b!a%#+/*rEz"D[(D$!)!+,D9GCcI	R	RqL TQX%6%@3%FI3 #6 a!eQ!!r&   c                   X     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                 0    t        |       t         	  |||||
d       t        |       _        t        || j                        \   _         _         j                   j                   j                        }|Vt         j                   j                   j                  ||| j                  d j                   j                  
       _        nt        |||       _        d  _        d  _        t%        dt&        z  |z  t)        d|dz               _        d  _         j/                  ||	      \   _         _        t5         j2                        r5 fd}d }t7         j                  d	 j                  j8                  
      }n= fd}d }t;        j<                   j                   j                  j8                        }| _        | _         | _!        t;        jD                  g d      }t;        jF                  dt;        jH                  dt;        jJ                  dtL        dz         z        f       _'        d|z
   jN                  z   _(        | jN                  z  dt;        jJ                  dtL        dz         z  z    _)        t;        jT                  tL        dz    j                  f j                  j8                        } j                  |d<   | j                  z   j                  z  |d<   | _+        d _,        d _-        d  _.        y )NT)support_complexr
   r   gQ?      ?c                 D    xj                   dz  c_         t        |       S Nr
   )nlur   Aselfs    r$   luzBDF.__init__.<locals>.lu   s    AAwr&   c                 $    | j                  |      S )N)solver:   bs     r$   r;   zBDF.__init__.<locals>.solve_lu   s    xx{"r&   csc)formatdtypec                 H    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5r&   c                     t        | |d      S )NT)overwrite_b)r   rV   s     r$   r;   zBDF.__init__.<locals>.solve_lu   s    A4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__   sh    	
#b"gz)- 	 	/)(3+D$?	49HHTVVTVV$,TXXtvvtvv-4h-1^^Q-1YY		CDJ
 -ZWEDJ"b3hos4/EF--c<@$&DFF# DFF5=A69 DFF$&&,,7A @AYY299Q1i!m1L-L#MNO
%i4::-
 4::-BIIaQ4O0OOHHi!mTVV,DFFLLAvv!4::~.!
r&   c                      j                   } j                  :%t              rt              t	              }|f fd} ||      }||fS t              r |      } xj                  dz  c_        t        |      rt        |j                        } fd}n(t        j                  |j                        } fd}|j                   j                   j                  fk7  r;t        dj                   j                   j                  f|j                              ||fS t              rt        j                        }n!t        j                  j                        }|j                   j                   j                  fk7  r;t        dj                   j                   j                  f|j                              d }||fS )Nc           	          xj                   dz  c_         j                  | |      }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  sV    		Q	OOAq)%,T-@-@!Q-1YY-5&7"4? r&   r
   r_   c                 j    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  s'    IINI%c!Qirxx@@r&   c                 ~    xj                   dz  c_         t        j                   | |      j                        S r   )r   r   asarrayrZ   r   s     r$   r   z&BDF._validate_jac.<locals>.jac_wrapped   s+    IINI::c!Qirxx@@r&   z8`jac` is expected to have shape {}, but actually has {}.)rh   r?   r   r   r	   callabler   rZ   r   r   shapere   
ValueErrorrY   )rR   rr   r   r}   groupsr   r"   r~   s   ```    @r$   rq   zBDF._validate_jac  s   VVVV;#H%)(3H&x0$f- B#AB A~A c]BAIINI{q1A JJq1A ww466466**  "4"(&$&&$&&)9177"CE E A~ }s"((3JJs"((3ww466466**  "4"(&$&&$&&)9177"CE E KA~r&   c                 
   | j                   }| j                  }| j                  }dt        j                  t        j
                  || j                  t        j                  z        |z
        z  }| j                  |kD  r.|}t        || j                  || j                  z         d| _        nI| j                  |k  r.|}t        || j                  || j                  z         d| _        n| j                  }| j                  }| j                  }| j                  }| j                  }	| j                  }
| j                   }| j"                  }| j$                  }| j&                  d u }d}|s7||k  rd| j(                  fS || j                  z  }||z   }| j                  || j*                  z
  z  dkD  r;| 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    j0                  |
d|dz          |	|   z  }d}||	|   z  }|sw|!| j3                  | j4                  ||z  z
        }t7        | j8                  |||||| j:                  || j<                  	      \  }}}}|s|rn| j'                  ||      }d }d}|sw|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kD  r6tC        tD        ||d
|dz   z  z  z        }||z  }t        |||       d| _        nd}|s7| 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y|dkD  r||dz
     ||   z  }tA        |z        } nt        j                  } |tL        k  r ||dz      ||d	z      z  }!tA        |!z        }"nt        j                  }"t        jN                  | |"g      }#t        jP                  d      5  |#d
t        jR                  ||dz         z  z  }$d d d        t        jT                  $      dz
  }%||%z  }|| _
        tW        tX        t        jB                  |$      z        }| xj                  |z  c_        t        |||       d| _        d | _        y# 1 sw Y   xY w)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_impl6  sU   FFFF==r||At~~/FG!KLL:: EQ

Htzz$9:!"DZZ("EQ

Htzz$9:!"DJJEyyyy





&&FFWWhh$&xd1111&AEE~~!56:E266%!)#4u#<=%&"	AFF1IEq%!)}15I4"&&"333E&&1eai**E!UQY,?@5<OCIE%L A:!a%0B.>HHeY3DMM4??/,+	65! !"	2AB"&K   E6*%&"A.23q>7I9?8@ AF 4"&&-//E&*Eeem,JA~Z#jR5195E&FFHE6*%&" !%}  @ 	a
 1UQY<'%!)%!)%	*+AaDAa!eHD , 	)19!%!),qx7G%0L66L9!%!),q|;G%0L66Lhhj,GH[[)!b299UEAI+F&FGG * ii(1,
Z"&&/!9:

f
E6" *)s    U..U7c           
          t        | j                  | j                  | j                  | j                  z  | j
                  | j                  d | j
                  dz    j                               S rN   )BdfDenseOutputt_oldrh   rj   ri   r   r*   r0   )rR   s    r$   _dense_output_implzBDF._dense_output_impl  sQ    djj$&&$**t~~2M"jj$&&$**q.*A*F*F*HJ 	Jr&   )__name__
__module____qualname____doc__r   r   rc   rq   r   r   __classcell__r   s   @r$   rI   rI   H   s:    {x 79ff4d!d:x3jM^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  | _        || _        y rN   )	rb   rc   r   rh   r   r   t_shiftdenomr*   )rR   r   rh   r   r   r*   r   s         r$   rc   zBdfDenseOutput.__init__  s`    "
vvBIIdjj$9 99!bii

334
r&   c                    |j                   dk(  r2|| j                  z
  | j                  z  }t        j                  |      }nA|| 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  }|S || 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    66Q;T\\!TZZ/A

1AT\\!T'**djjD.AAA

11%AFF466!":<<#66Q;NA  1d
##Ar&   )r   r   r   rc   r   r   r   s   @r$   r   r     s    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      sn     , 2 2 $ 1& & & ) 	

!0!"HJ) JD[ r&   