U
    GvfK                     @   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@yrr@Ggg{g]#-?g;@L¿ghm?g
}?gQ  ?gmؿgF@gN]?gV?gFgN]Կg!R ?g$Z?goN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 rd} 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   >/tmp/pip-unpacked-wheel-96ln3f52/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_oldZ
multiplierfactorrA   rA   rB   predict_factor   s    rL   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rt 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)rQ   r   rR   rT   rA   rB   rV   A  s    c                 S   s   t | |ddS )NT)Zoverwrite_b)r   rX   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#   identityrV   r7   Icurrent_jacr5   r6   r:   )rU   r/   t0y0t_boundr^   r_   r`   rh   Zjac_sparsityZ
vectorizedZ
first_stepZ
extraneousrV   r7   rk   	__class__rT   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}nt r ||}d_t|rt|}d fdd	}ntj	|t
d}d	 fdd	}|jjjfkrtdjjf|jnRt rt }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 rP   )njevr   Zfun_vectorizedr`   rf   )r0   r1   ra   ri   )rU   sparsityrA   rB   jac_wrapped^  s     
z(Radau._validate_jac.<locals>.jac_wrappedr	   c                    s     j d7  _ t | |tdS Nr	   Zdtype)rr   r   floatr0   r1   _rh   rU   rA   rB   rt   k  s    rv   c                    s"    j d7  _ tj | |tdS ru   )rr   r#   asarrayrw   rx   rz   rA   rB   rt   r  s    z8`jac` is expected to have shape {}, but actually has {}.)N)N)r0   r1   r   r   r   ra   callablerr   r#   r{   rw   r   r8   
ValueErrorrZ   )rU   rh   rs   rm   rn   groupsrt   ri   rA   )rh   rU   rs   rB   rg   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 rd| 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rt'||	||
} |t(t)||  9 }d }d }d}qd}q|d k	o|d	ko|dk}!t'||	||
} t*t+||  } |!sH| dk rHd
} nd }d }| ||}"|!rt||||"}d}n|d k	rd}| j| _|| _||  | _|| _,|| _ || _|"| _|| _-|| _|| _|| _|| _|| _.| / | _||fS )Nr   Fr   r   TrO   r   g?r   r	   rN   g333333?)0r0   r1   ra   r^   r`   r_   r#   absZ	nextafterrb   infrG   rH   rJ   ri   r5   r6   rl   rh   ZTOO_SMALL_STEPro   re   zerosr   r%   r*   rV   r   rk   r    rC   r/   rd   r7   r"   Emaximumr   r'   rL   rc   
MIN_FACTORrF   
MAX_FACTORr]   r:   t_old_compute_dense_output)#rU   r0   r1   ra   r^   r`   r_   Zmin_steprG   rH   rJ   ri   r5   r6   rl   rh   ZrejectedZstep_acceptedmessager2   Zt_newr3   r4   r=   Zn_iterr:   r>   Zy_newZZEerrorrI   ZsafetyrK   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 rW   )	r#   r"   r:   r*   PRadauDenseOutputr   r0   r]   )rU   QrA   rA   rB   r     s    zRadau._compute_dense_outputc                 C   s   | j S rW   )re   rT   rA   rA   rB   _dense_output_impl  s    zRadau._dense_output_impl)__name__
__module____qualname____doc__r#   r   r\   rg   r   r   r   __classcell__rA   rA   rp   rB   rM      s   j    55 rM   c                       s$   e Zd Z fddZdd Z  ZS )r   c                    s8   t  || || | _|| _|jd d | _|| _d S rP   )r[   r\   r2   r   r   orderr]   )rU   r   r0   r]   r   rp   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]   )rU   r0   xpr1   rA   rA   rB   
_call_impl&  s    


zRadauDenseOutput._call_impl)r   r   r   r\   r   r   rA   rA   rp   rB   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S6arrayr%   r   r   r    r*   r!   r+   r,   r   r'   r   r   rC   rL   rM   r   rA   rA   rA   rB   <module>   sJ   ( $(([(  m