o
    EbK                     @   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CZ
empty_likerangeNEWTON_MAXITERallZisfiniteTTI_REAL
TI_COMPLEXrealimagr   )funtyhZ0scaleZtolLU_real
LU_complexsolve_lunZM_realZ	M_complexWZFZchZdW_norm_oldZdW	convergedratekiZf_realZ	f_complexZdW_realZ
dW_complexZdW_norm r@   </usr/lib/python3/dist-packages/scipy/integrate/_ivp/radau.pysolve_collocation_system0   sR   
'

 $




rB   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)Zdivideg      п)r$   Zerrstatemin)h_abs	h_abs_old
error_normerror_norm_oldZ
multiplierfactorr@   r@   rA   predict_factor   s   
rJ   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 )RadauaT  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 calling signature is ``fun(t, y)``.
        Here ``t`` is a scalar, and there are two options for the ndarray ``y``:
        It can either have shape (n,); then ``fun`` must return array_like with
        shape (n,). Alternatively it can have shape (n, k); then ``fun``
        must return an array_like with shape (n, k), i.e., each column
        corresponds to a single column in ``y``. The choice between the two
        options is determined by `vectorized` argument (see below). The
        vectorized implementation allows a faster approximation of the Jacobian
        by finite differences (required for this solver).
    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 lower than the lowest 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 lower
        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` is implemented in a vectorized fashion. Default is False.

    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              	      sX  t | t |||||
 d  _t| _t|| j\ _ _	 
 j j _|d u rBt 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selfr@   rA   lu8  s   zRadau.__init__.<locals>.luc                 S   s
   |  |S N)ZsolveZLUbr@   r@   rA   r7   <  s   
z Radau.__init__.<locals>.solve_luZcsc)formatc                    s     j d7  _ t| ddS )Nr	   T)Zoverwrite_a)rO   r   rP   rR   r@   rA   rT   A  s   c                 S   s   t | |ddS )NT)Zoverwrite_b)r   rV   r@   r@   rA   r7   E  s   T)(r   super__init__y_oldr
   max_stepr   r8   rtolatolr/   r0   r1   fr   	directionrE   r   rF   rH   maxr   rD   
newton_tolsol
jac_factor_validate_jacjacJr   r   r$   identityrT   r7   Icurrent_jacr5   r6   r:   )rS   r/   t0y0t_boundr\   r]   r^   rf   Zjac_sparsityZ
vectorizedZ
first_stepZ
extraneousrT   r7   ri   	__class__rR   rA   rZ     s@   



zRadau.__init__c                    sD  j }j} d u r0d urtrtt}|ffdd}|||j}||fS t rv ||}d_t|rMt|}d fdd	}ntj	|t
d}d fdd	}|jjjfkrrtdjjf|j||fS t rt }ntj	 t
d}|jjjfkrtdjjf|jd }||fS )	Nc                    s2     j d7  _ t j| || j j\} _|S rN   )njevr   Zfun_vectorizedr^   rd   )r0   r1   r_   rg   )rS   sparsityr@   rA   jac_wrapped^  s   
z(Radau._validate_jac.<locals>.jac_wrappedr	   c                    s     j d7  _ t | |tdS Nr	   Zdtype)rp   r   floatr0   r1   _rf   rS   r@   rA   rr   k  s   rt   c                    s"    j d7  _ tj | |tdS rs   )rp   r$   asarrayru   rv   rx   r@   rA   rr   r  s   z8`jac` is expected to have shape {}, but actually has {}.rU   )r0   r1   r   r   r   r_   callablerp   r$   ry   ru   r   r8   
ValueErrorrX   )rS   rf   rq   rk   rl   groupsrr   rg   r@   )rf   rS   rq   rA   re   S  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   TrM   r   g?r   r	   rL   g333333?)0r0   r1   r_   r\   r^   r]   r$   absZ	nextafterr`   infrE   rF   rH   rg   r5   r6   rj   rf   ZTOO_SMALL_STEPrm   rc   Zzerosr   r&   r*   rT   r    ri   r!   rB   r/   rb   r7   r#   EZmaximumr   r(   rJ   ra   
MIN_FACTORrD   
MAX_FACTORr[   r:   t_old_compute_dense_output)#rS   r0   r1   r_   r\   r^   r]   Zmin_steprE   rF   rH   rg   r5   r6   rj   rf   ZrejectedZstep_acceptedmessager2   Zt_newr3   r4   r<   Zn_iterr:   r=   Zy_newZZEerrorrG   ZsafetyrI   Zrecompute_jacZf_newr@   r@   rA   
_step_impl  s   "





 
D


zRadau._step_implc                 C   s$   t | jjt}t| j| j| j|S rU   )	r$   r#   r:   r*   PRadauDenseOutputr   r0   r[   )rS   Qr@   r@   rA   r     s   zRadau._compute_dense_outputc                 C   s   | j S rU   )rc   rR   r@   r@   rA   _dense_output_impl  s   zRadau._dense_output_impl)__name__
__module____qualname____doc__r$   r~   rZ   re   r   r   r   __classcell__r@   r@   rn   rA   rK      s    j55 rK   c                       s$   e Zd Z fddZdd Z  ZS )r   c                    s8   t  || || | _|| _|jd d | _|| _d S rN   )rY   rZ   r2   r   r   orderr[   )rS   r   r0   r[   r   rn   r@   rA   rZ     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	   )Zaxisr   )
r   r2   ndimr$   Ztiler   Zcumprodr#   r   r[   )rS   r0   xpr1   r@   r@   rA   
_call_impl&  s   


zRadauDenseOutput._call_impl)r   r   r   rZ   r   r   r@   r@   rn   rA   r     s    r   )+Znumpyr$   Zscipy.linalgr   r   Zscipy.sparser   r   r   Zscipy.sparse.linalgr   Zscipy.optimize._numdiffr   commonr
   r   r   r   r   r   r   r   baser   r   ZS6Zarrayr&   r   r    r!   r*   r"   r+   r,   r   r(   r   r   rB   rJ   rK   r   r@   r@   r@   rA   <module>   sL    ( $(([(  m