U
    »mœd·K  ã                   @   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 dddgdddgddd gg¡Ze dddgdddgddd g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d(d)d&gg¡Z#d*Z$d+Z%dZ&d,d-„ Z'd.d/„ Z(G d0d1„ d1eƒZ)G d2d3„ d3eƒZ*dS )4é    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£¢‚Ø¿gFœ§·@g†N¨]ÁøÔ?gïV�õ¿à?gFœ§·Àg†N¨]ÁøÔ¿g!RÅ �Þ?gò§$Zˆà?g˜¥ÊoN“ÀgÑß{ÏÀã?ù              ð?é   gUUUUUU@g«ªªªªªÀé   g«ªªªªª
@é   gUUUUUUÕ?gUUUUUUÀé   gš™™™™™É?c
                 C   sÂ  |j d }
t| }t| }t |¡}|}t d|
f¡}|t }d}t |¡}d}d}t	t
ƒD �]R}t	dƒD ]"}| |||  |||  ƒ||< qjt t |¡¡s¤ �q²|j t¡||d   }|j t¡||d d|d     }|	||ƒ}|	||ƒ}||d< |j|d< |j|d< t|| ƒ}|dk	�r.|| }|dk	�rf|dk�s`|t
|  d|  | |k�rf �q²||7 }t |¡}|dk�s¢|dk	�r¬|d|  | |k �r¬d} �q²|}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ÚallÚ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ÚFÚchZdW_norm_oldZdWÚ	convergedÚrateÚkÚiZf_realZ	f_complexZdW_realZ
dW_complexZdW_norm© rA   úS/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scipy/integrate/_ivp/radau.pyÚsolve_collocation_system0   sR    '


 $




ÿ

ÿÿrC   c              	   C   s`   |dks|dks|dkrd}n| | || d  }t jdd�� td|ƒ|d  }W 5 Q R X |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#   ZerrstateÚmin)Úh_absÚ	h_abs_oldÚ
error_normÚerror_norm_oldÚ
multiplierÚfactorrA   rA   rB   Úpredict_factor‹   s    rM   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 )ÚRadauaZ  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 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` 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              	      sZ  t |ƒ tƒ  |||||
¡ d ˆ _t|ƒˆ _t||ˆ jƒ\ˆ _ˆ _	ˆ  
ˆ jˆ j¡ˆ _|d kr„tˆ 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©ÚselfrA   rB   Úlu8  s    zRadau.__init__.<locals>.luc                 S   s
   |   |¡S ©N)Zsolve©ZLUÚbrA   rA   rB   r7   <  s    z Radau.__init__.<locals>.solve_luZcsc)Úformatc                    s   ˆ  j d7  _ t| dd�S )Nr	   T)Zoverwrite_a)rR   r   rS   rU   rA   rB   rW   A  s    c                 S   s   t | |dd�S )NT)Zoverwrite_b)r   rY   rA   rA   rB   r7   E  s    T)(r   ÚsuperÚ__init__Úy_oldr
   Úmax_stepr   r8   ÚrtolÚatolr/   r0   r1   Úfr   Ú	directionrG   r   rH   rJ   Úmaxr   rF   Ú
newton_tolÚsolÚ
jac_factorÚ_validate_jacÚjacÚJr   r   r#   ÚidentityrW   r7   ÚIÚcurrent_jacr5   r6   r:   )rV   r/   Út0Úy0Út_boundr_   r`   ra   ri   Zjac_sparsityZ
vectorizedZ
first_stepZ
extraneousrW   r7   rl   ©Ú	__class__rU   rB   r]     sL    
      þzRadau.__init__c                    s:  ˆj }ˆj}ˆ d krZˆd k	r<tˆƒr,tˆƒ‰tˆƒ}ˆ|f‰‡‡fdd„}|||ˆjƒ}nØtˆ ƒràˆ ||ƒ}dˆ_t|ƒr”t|ƒ}d‡ ‡fdd„	}ntj	|t
d�}d	‡ ‡fdd„	}|jˆjˆjfkrÞtd ˆjˆjf|j¡ƒ‚nRtˆ ƒròtˆ ƒ}ntj	ˆ t
d�}|jˆjˆjfk�r.td ˆjˆjf|j¡ƒ‚d }||fS )
Nc                    s2   ˆ  j d7  _ tˆ j| ||ˆ jˆ jˆƒ\}ˆ _|S rQ   )Únjevr   Zfun_vectorizedra   rg   )r0   r1   rb   rj   )rV   ÚsparsityrA   rB   Újac_wrapped^  s     þ
z(Radau._validate_jac.<locals>.jac_wrappedr	   c                    s    ˆ j d7  _ tˆ | |ƒtd�S ©Nr	   ©Zdtype)rs   r   Úfloat©r0   r1   Ú_©ri   rV   rA   rB   ru   k  s    rw   c                    s"   ˆ j d7  _ tjˆ | |ƒtd�S rv   )rs   r#   Úasarrayrx   ry   r{   rA   rB   ru   r  s    z8`jac` is expected to have shape {}, but actually has {}.)N)N)r0   r1   r   r   r   rb   Úcallablers   r#   r|   rx   r   r8   Ú
ValueErrorr[   )rV   ri   rt   rn   ro   Úgroupsru   rj   rA   )ri   rV   rt   rB   rh   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 rv|}d }	d }
n| j}| j}	| j}
| j}| j}| j}| j}| j}d}d}d }|�sú||k rÊd| jfS || j	 }|| }| j	|| j  dkrö| j}|| }t |¡}| jd k�r*t d|jd f¡}n|  ||t  ¡j| }|t |¡|  }d}|�sø|d k�sr|d k�r¢|  t| | j | ¡}|  t| | j | ¡}t| j|||||| j ||| j!ƒ
\}}}}|�sX|�rÚ�qø|  |||¡}d}d }d }�qX|�s|d9 }d }d }q²||d  }|j "t#¡| }|  !||| ¡}|t $t |¡t |¡¡|  }t%|| ƒ}dd	t& d
  d	t& |  }|�r¼|d
k�r¼|  !||  ||| ¡| ¡}t%|| ƒ}|d
k�rôt'||	||
ƒ} |t(t)||  ƒ9 }d }d }d}q²d}q²|d k	�o|d	k�o|dk}!t'||	||
ƒ} t*t+||  ƒ} |!�sH| dk �rHd
} nd }d }|  ||¡}"|!�rt||||"ƒ}d}n|d k	�r‚d}| j| _|| _||  | _|| _,|| _ || _|"| _|| _-|| _|| _|| _|| _|| _.|  /¡ | _||fS )Nr   Fr   r   TrP   r   gÍÌÌÌÌÌì?r   r	   rO   g333333ó?)0r0   r1   rb   r_   ra   r`   r#   ÚabsZ	nextafterrc   ÚinfrG   rH   rJ   rj   r5   r6   rm   ri   ZTOO_SMALL_STEPrp   rf   Zzerosr   r%   r*   rW   r   rl   r    rC   r/   re   r7   r"   ÚEÚmaximumr   r'   rM   rd   Ú
MIN_FACTORrF   Ú
MAX_FACTORr^   r:   Út_oldÚ_compute_dense_output)#rV   r0   r1   rb   r_   ra   r`   Zmin_steprG   rH   rJ   rj   r5   r6   rm   ri   ZrejectedZstep_acceptedÚmessager2   Zt_newr3   r4   r=   Zn_iterr:   r>   Zy_newZZEÚerrorrI   ZsafetyrL   Zrecompute_jacZf_newrA   rA   rB   Ú
_step_implˆ  sê    "




        þ ÿ
 ÿ


zRadau._step_implc                 C   s$   t  | jjt¡}t| j| j| j|ƒS rX   )	r#   r"   r:   r*   ÚPÚRadauDenseOutputr†   r0   r^   )rV   ÚQrA   rA   rB   r‡     s    zRadau._compute_dense_outputc                 C   s   | j S rX   )rf   rU   rA   rA   rB   Ú_dense_output_impl  s    zRadau._dense_output_impl)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r#   r�   r]   rh   rŠ   r‡   rŽ   Ú__classcell__rA   rA   rq   rB   rN   ³   s   j    þ55 rN   c                       s$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )rŒ   c                    s8   t ƒ  ||¡ || | _|| _|jd d | _|| _d S rQ   )r\   r]   r2   r�   r   Úorderr^   )rV   r†   r0   r^   r�   rq   rA   rB   r]     s
    
zRadauDenseOutput.__init__c                 C   sš   || j  | j }|jdkr8t || jd ¡}t |¡}n$t || jd df¡}tj|dd�}t | j|¡}|jdkrŒ|| j	d d …d f 7 }n
|| j	7 }|S )Nr   r	   )Zaxisr   )
r†   r2   Úndimr#   Ztiler”   Zcumprodr"   r�   r^   )rV   r0   ÚxÚpr1   rA   rA   rB   Ú
_call_impl&  s    


zRadauDenseOutput._call_impl)r�   r�   r‘   r]   r˜   r“   rA   rA   rq   rB   rŒ     s   rŒ   )+Ú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S6Úarrayr%   r‚   r   r    r*   r!   r+   r,   r‹   r'   r„   r…   rC   rM   rN   rŒ   rA   rA   rA   rB   Ú<module>   sJ   ( $ýý((ý[(  m