o
    Ö­jÜL  ã                   @   sÀ  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e d
e d d
e d dg¡Ze dde  dde  dg¡d ZdZdZe g d¢g d¢g d¢g¡Ze g d¢g d¢g d¢g¡Z e d  Z!e d de d   Z"e dde d  dde d  dde  gdde d  dde d  dde  gg d¢g¡Z#d Z$d!Z%dZ&d"d#„ Z'd$d%„ Z(G d&d'„ d'eƒZ)G d(d)„ d)eƒZ*dS )*é    N)Ú	lu_factorÚlu_solve)Ú
csc_matrixÚissparseÚeye)Úsplu)Úgroup_columnsé   )Úvalidate_max_stepÚvalidate_tolÚselect_initial_stepÚnormÚnum_jacÚEPSÚwarn_extraneousÚvalidate_first_step)Ú	OdeSolverÚDenseOutputg.!	Ž˜@é   é
   ióÿÿÿé   éÿÿÿÿé   gs>ØH@yrÆà“Ûr@¶üÃòGgÀ)g{g]„#-¸?g÷;@L§Â¿gŽhmù¿ž?)gí¡
ç}Ð?gQµ é Ê?gím£¢‚Ø¿)r	   r	   r   )gFœ§·@g†N¨]ÁøÔ?gïV�õ¿à?)gFœ§·Àg†N¨]ÁøÔ¿g!RÅ �Þ?)gò§$Zˆà?g˜¥ÊoN“ÀgÑß{ÏÀã?ù              ð?é   gUUUUUU@g«ªªªªªÀé   ç«ªªªªª
@é   )gUUUUUUÕ?gUUUUUUÀr   é   gš™™™™™É?c
                 C   s¬  |j d }
t| }t| }t |¡}|}t d|
f¡}|t }d}t |¡}d}d}t	t
ƒD ]Ÿ}t	dƒD ]}| |||  |||  ƒ||< q4t t |¡¡sP n~|j t¡||d   }|j t¡||d d|d     }|	||ƒ}|	||ƒ}||d< |j|d< |j|d< t|| ƒ}|dur”|| }|dur¬|dksª|t
|  d|  | |kr¬ n"||7 }t |¡}|dksÇ|durË|d|  | |k rËd} n|}q.||d ||fS )	a^  Solve the collocation system.

    Parameters
    ----------
    fun : callable
        Right-hand side of the system.
    t : float
        Current time.
    y : ndarray, shape (n,)
        Current state.
    h : float
        Step to try.
    Z0 : ndarray, shape (3, n)
        Initial guess for the solution. It determines new values of `y` at
        ``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants.
    scale : ndarray, shape (n)
        Problem tolerance scale, i.e. ``rtol * abs(y) + atol``.
    tol : float
        Tolerance to which solve the system. This value is compared with
        the normalized by `scale` error.
    LU_real, LU_complex
        LU decompositions of the system Jacobians.
    solve_lu : callable
        Callable which solves a linear system given a LU decomposition. The
        signature is ``solve_lu(LU, b)``.

    Returns
    -------
    converged : bool
        Whether iterations converged.
    n_iter : int
        Number of completed iterations.
    Z : ndarray, shape (3, n)
        Found solution.
    rate : float
        The rate of convergence.
    r   r   NFr	   r   r   T)ÚshapeÚMU_REALÚ
MU_COMPLEXÚTIÚdotÚnpÚemptyÚCÚ
empty_likeÚrangeÚNEWTON_MAXITERÚallÚisfiniteÚTÚTI_REALÚ
TI_COMPLEXÚrealÚimagr   )ÚfunÚtÚyÚhÚZ0ÚscaleÚtolÚLU_realÚ
LU_complexÚsolve_luÚnÚM_realÚ	M_complexÚWÚZÚFÚchÚdW_norm_oldÚdWÚ	convergedÚrateÚkÚiÚf_realÚ	f_complexÚdW_realÚ
dW_complexÚdW_norm© rM   úW/var/www/html/CropPilot/venv/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.pyÚsolve_collocation_system0   sJ   
'

 $




rO   c                 C   sv   |du s|du s|dkrd}n
| | || d  }t jdd�� td|ƒ|d  }W d  ƒ |S 1 s4w   Y  |S )a9  Predict by which factor to increase/decrease the step size.

    The algorithm is described in [1]_.

    Parameters
    ----------
    h_abs, h_abs_old : float
        Current and previous values of the step size, `h_abs_old` can be None
        (see Notes).
    error_norm, error_norm_old : float
        Current and previous values of the error norm, `error_norm_old` can
        be None (see Notes).

    Returns
    -------
    factor : float
        Predicted factor.

    Notes
    -----
    If `h_abs_old` and `error_norm_old` are both not None then a two-step
    algorithm is used, otherwise a one-step algorithm is used.

    References
    ----------
    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
           Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8.
    Nr   r	   g      Ð?Úignore)Údivideg      Ð¿)r$   ÚerrstateÚmin)Úh_absÚ	h_abs_oldÚ
error_normÚerror_norm_oldÚ
multiplierÚfactorrM   rM   rN   Úpredict_factor‹   s   
ÿýrZ   c                       sR   e Zd ZdZejddddddf‡ fdd„	Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
‡  ZS )ÚRadauaÂ  Implicit Runge-Kutta method of Radau IIA family of order 5.

    The implementation follows [1]_. The error is controlled with a
    third-order accurate embedded formula. A cubic polynomial which satisfies
    the collocation conditions is used for the dense output.

    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)``. HHere `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 [2]_. 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] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
           Stiff and Differential-Algebraic Problems", Sec. IV.8.
    .. [2] 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.
    çü©ñÒMbP?g�íµ ÷Æ°>NFc                    s\  t |ƒ tƒ  |||||
¡ d ˆ _t|ƒˆ _t||ˆ jƒ\ˆ _ˆ _	ˆ  
ˆ jˆ j¡ˆ _|d u rDtˆ j
ˆ jˆ j||ˆ jˆ jdˆ jˆ j	ƒ
ˆ _nt|||ƒˆ _d ˆ _d ˆ _tdt | td|d ƒƒˆ _d ˆ _d ˆ _ˆ  ||	¡\ˆ _ˆ _tˆ jƒr‡‡ fdd„}dd„ }tˆ jd	d
�}n‡ fdd„}dd„ }t  ˆ j¡}|ˆ _!|ˆ _"|ˆ _#dˆ _$d ˆ _%d ˆ _&d ˆ _'d S )Nr   r   g¸…ëQ¸ž?ç      à?c                    s   ˆ  j d7  _ t| ƒS ©Nr	   )Únlur   ©ÚA©ÚselfrM   rN   ÚluA  s   zRadau.__init__.<locals>.luc                 S   s
   |   |¡S ©N)Úsolve©ÚLUÚbrM   rM   rN   r:   E  s   
z Radau.__init__.<locals>.solve_luÚcsc)Úformatc                    s   ˆ  j d7  _ t| dd�S )Nr	   T)Úoverwrite_a)r_   r   r`   rb   rM   rN   rd   J  s   c                 S   s   t | |dd�S )NT)Úoverwrite_b)r   rg   rM   rM   rN   r:   N  s   T)(r   ÚsuperÚ__init__Úy_oldr
   Úmax_stepr   r;   ÚrtolÚatolr1   r2   r3   Úfr   Ú	directionrT   r   rU   rW   Úmaxr   rS   Ú
newton_tolÚsolÚ
jac_factorÚ_validate_jacÚjacÚJr   r   r$   Úidentityrd   r:   ÚIÚcurrent_jacr8   r9   r?   )rc   r1   Út0Úy0Út_boundrq   rr   rs   r{   Újac_sparsityÚ
vectorizedÚ
first_stepÚ
extraneousrd   r:   r~   ©Ú	__class__rb   rN   ro   '  s@   

þ

zRadau.__init__c                    sP  ˆj }ˆj}ˆ d u r0ˆd urtˆƒrtˆƒ‰tˆƒ}ˆ|f‰‡‡fdd„}|||ˆjƒ}||fS tˆ ƒryˆ ||ƒ}dˆ_t|ƒrMt|ƒ}d
‡ ‡fdd„	}ntj	|t
d�}d
‡ ‡fdd„	}|jˆjˆjfkrutdˆjˆjf› d|j› d	�ƒ‚||fS tˆ ƒr‚tˆ ƒ}ntj	ˆ t
d�}|jˆjˆjfkr¢tdˆjˆjf› d|j› d	�ƒ‚d }||fS )Nc                    s2   ˆ  j d7  _ tˆ j| ||ˆ jˆ jˆƒ\}ˆ _|S r^   )Únjevr   Úfun_vectorizedrs   ry   )r2   r3   rt   r|   )rc   ÚsparsityrM   rN   Újac_wrappedg  s   
þz(Radau._validate_jac.<locals>.jac_wrappedr	   c                    s    ˆ j d7  _ tˆ | |ƒtd�S ©Nr	   ©Údtype)r‰   r   Úfloat©r2   r3   Ú_©r{   rc   rM   rN   rŒ   t  s   rŽ   c                    s"   ˆ j d7  _ tjˆ | |ƒtd�S r�   )r‰   r$   Úasarrayr�   r‘   r“   rM   rN   rŒ   {  s   z `jac` is expected to have shape z, but actually has Ú.re   )r2   r3   r   r   r   rt   Úcallabler‰   r$   r”   r�   r   r;   Ú
ValueError)rc   r{   r‹   r€   r�   ÚgroupsrŒ   r|   rM   )r{   rc   r‹   rN   rz   \  sB    á

ÿö

ÿzRadau._validate_jacc           #      C   sÜ  | j }| j}| j}| j}| j}| j}dt t || j	tj
 ¡| ¡ }| j|kr/|}d }	d }
n| j|k r;|}d }	d }
n	| j}| j}	| j}
| j}| j}| j}| j}| j}d}d}d }|�sw||k red| jfS || j	 }|| }| j	|| j  dkr{| j}|| }t |¡}| jd u r”t d|jd f¡}n|  ||t  ¡j| }|t |¡|  }d}|sõ|d u sµ|d u rÍ|  t| | j | ¡}|  t| | j | ¡}t| j|||||| j ||| j!ƒ
\}}}}|só|ræn|  |||¡}d}d }d }|r­|�s|d9 }d }d }qY||d  }|j "t#¡| }|  !||| ¡}|t $t |¡t |¡¡|  }t%|| ƒ}dd	t& d
  d	t& |  }|�rW|d
k�rW|  !||  ||| ¡| ¡}t%|| ƒ}|d
k�rst'||	||
ƒ} |t(t)||  ƒ9 }d }d }d}nd}|r\|d u�o„|d	k�o„|dk}!t'||	||
ƒ} t*t+||  ƒ} |!�sž| dk �ržd
} nd }d }|  ||¡}"|!�r´||||"ƒ}d}n|d u�r»d}| j| _|| _||  | _|| _,|| _ || _|"| _|| _-|| _|| _|| _|| _|| _.|  /¡ | _||fS )Nr   Fr   r   Tr]   r   gÍÌÌÌÌÌì?r   r	   r\   g333333ó?)0r2   r3   rt   rq   rs   rr   r$   ÚabsÚ	nextafterru   ÚinfrT   rU   rW   r|   r8   r9   r   r{   ÚTOO_SMALL_STEPr‚   rx   Úzerosr   r&   r,   rd   r    r~   r!   rO   r1   rw   r:   r#   ÚEÚmaximumr   r)   rZ   rv   Ú
MIN_FACTORrS   Ú
MAX_FACTORrp   r?   Út_oldÚ_compute_dense_output)#rc   r2   r3   rt   rq   rs   rr   Úmin_steprT   rU   rW   r|   r8   r9   r   r{   ÚrejectedÚstep_acceptedÚmessager4   Út_newr5   r6   rD   Ún_iterr?   rE   Úy_newÚZEÚerrorrV   ÚsafetyrY   Úrecompute_jacÚf_newrM   rM   rN   Ú
_step_impl�  sÜ   "





þð ÿ
ÿ¾D


zRadau._step_implc                 C   s$   t  | jjt¡}t| j| j| j|ƒS re   )	r$   r#   r?   r,   ÚPÚRadauDenseOutputr¢   r2   rp   )rc   ÚQrM   rM   rN   r£     s   zRadau._compute_dense_outputc                 C   s   | j S re   )rx   rb   rM   rM   rN   Ú_dense_output_impl!  s   zRadau._dense_output_impl)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r$   r›   ro   rz   r°   r£   r´   Ú__classcell__rM   rM   r‡   rN   r[   ³   s    sþ53 r[   c                       s$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )r²   c                    s8   t ƒ  ||¡ || | _|| _|jd d | _|| _d S r^   )rn   ro   r4   r³   r   Úorderrp   )rc   r¢   r2   rp   r³   r‡   rM   rN   ro   &  s
   

zRadauDenseOutput.__init__c                 C   sœ   || j  | j }|jdkrt || jd ¡}t |¡}nt || jd df¡}tj|dd�}t | j|¡}|jdkrG|| j	d d …d f 7 }|S || j	7 }|S )Nr   r	   )Úaxisr   )
r¢   r4   Úndimr$   Útilerº   Úcumprodr#   r³   rp   )rc   r2   ÚxÚpr3   rM   rM   rN   Ú
_call_impl-  s   


þzRadauDenseOutput._call_impl)rµ   r¶   r·   ro   rÁ   r¹   rM   rM   r‡   rN   r²   %  s    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   ÚS6Úarrayr&   rž   r    r!   r,   r"   r-   r.   r±   r)   r    r¡   rO   rZ   r[   r²   rM   rM   rM   rN   Ú<module>   sL    ( $ýý((ý[(  t