o
    `^hL                     @   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@yrr@Gg)g{g]#-?g;@L¿ghm?)g
}?gQ  ?gmؿ)r	   r	   r   )gF@gN]?gV?)gFgN]Կg!R ?)g$Z?goN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 rd} 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   X/home/air/shanriGPT/back/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 rt }ntj	 t
d}|jjjfkrt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 rt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|rn| |||}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 rd
} nd }d }| ||}"|!r||||"}d}n|d urd}| 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