B
    0dtJ                 @   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{?y              ?   gUUUUUU@g   g
@   gUUUUUU?gUUUUUU   g?c
             C   s  |j d }
t| }t| }t|}|}td|
f}|t }d}t|}d}d}xXt	t
D ]J}x.t	dD ]"}| |||  |||  ||< qpW tt|sP |jt||d   }|jt||d d|d     }|	||}|	||}||d< |j|d< |j|d< t|| }|dk	r2|| }|dk	rf|dksd|t
|  d|  | |krfP ||7 }t|}|dks|dk	r|d|  | |k rd}P |}q`W ||d ||fS )	aQ  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 : float
        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	   y              ?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 r@   L/var/www/html/venv/lib/python3.7/site-packages/scipy/integrate/_ivp/radau.pysolve_collocation_system0   sJ    '


"$






 rB   c          	   C   s`   |dks|dks|dkrd}n| | || d  }t jdd td||d  }W d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factorr@   r@   rA   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 )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 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)``. Here `rtol` controls a
        relative accuracy (number of correct digits). But if a component of `y`
        is approximately below `atol`, the error only needs to fall within
        the same `atol` threshold, and the number of correct digits is not
        guaranteed. 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.
    gMbP?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?g      ?c                s     j d7  _ t| S )Nr	   )nlur   )A)selfr@   rA   lu4  s    zRadau.__init__.<locals>.luc             S   s
   |  |S )N)Zsolve)LUbr@   r@   rA   r6   8  s    z Radau.__init__.<locals>.solve_luZcsc)formatc                s     j d7  _ t| ddS )Nr	   T)Zoverwrite_a)rN   r   )rO   )rP   r@   rA   rQ   =  s    c             S   s   t | |ddS )NT)Zoverwrite_b)r   )rR   rS   r@   r@   rA   r6   A  s    T)(r   super__init__y_oldr
   max_stepr   r7   rtolatolr.   r/   r0   fr   	directionrF   r   rG   rI   maxr   rE   
newton_tolsol
jac_factor_validate_jacjacJr   r   r"   identityrQ   r6   Icurrent_jacr4   r5   r9   )rP   r.   t0y0t_boundrX   rY   rZ   rb   Zjac_sparsityZ
vectorizedZ
first_stepZ
extraneousrQ   r6   re   )	__class__)rP   rA   rV     s>    
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 )Nr	   )njevr   Zfun_vectorizedrZ   r`   )r/   r0   r[   rc   )rP   sparsityr@   rA   jac_wrappedZ  s
    z(Radau._validate_jac.<locals>.jac_wrappedr	   c                s     j d7  _ t | |tdS )Nr	   )dtype)rk   r   float)r/   r0   _)rb   rP   r@   rA   rm   g  s    )rn   c                s"    j d7  _ tj | |tdS )Nr	   )rn   )rk   r"   asarrayro   )r/   r0   rp   )rb   rP   r@   rA   rm   n  s    z8`jac` is expected to have shape {}, but actually has {}.)N)N)r/   r0   r   r   r   r[   callablerk   r"   rq   ro   r   r7   
ValueErrorrT   )rP   rb   rl   rg   rh   groupsrm   rc   r@   )rb   rP   rl   rA   ra   O  s:    

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 }xL|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}x|s|d ksx|d kr| t| | j | }| t| | j | }t| j|||||| j ||| j!
\}}}}|s^|rP | |||}d}d }d }q^W |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}qW |d k	o|d	ko|dk}!t'||	||
} t*t+||  } |!sP| dk rPd
} nd }d }| ||}"|!r|||||"}d}n|d k	rd}| j| _|| _||  | _|| _,|| _ || _|"| _|| _-|| _|| _|| _|| _|| _.| / | _||fS )Nr   Fr   r   Tg      ?r   g?r   r	   gMbP?g333333?)0r/   r0   r[   rX   rZ   rY   r"   absZ	nextafterr\   infrF   rG   rI   rc   r4   r5   rf   rb   ZTOO_SMALL_STEPri   r_   Zzerosr   r$   r)   rQ   r   re   r   rB   r.   r^   r6   r!   Emaximumr   r&   rL   r]   
MIN_FACTORrE   
MAX_FACTORrW   r9   t_old_compute_dense_output)#rP   r/   r0   r[   rX   rZ   rY   Zmin_steprF   rG   rI   rc   r4   r5   rf   rb   ZrejectedZstep_acceptedmessager1   Zt_newr2   r3   r<   Zn_iterr9   r=   Zy_newZZEerrorrH   ZsafetyrK   Zrecompute_jacZf_newr@   r@   rA   
_step_impl  s    "






 



zRadau._step_implc             C   s$   t | jjt}t| j| j| j|S )N)	r"   r!   r9   r)   PRadauDenseOutputr{   r/   rW   )rP   Qr@   r@   rA   r|     s    zRadau._compute_dense_outputc             C   s   | j S )N)r_   )rP   r@   r@   rA   _dense_output_impl  s    zRadau._dense_output_impl)__name__
__module____qualname____doc__r"   rv   rV   ra   r   r|   r   __classcell__r@   r@   )rj   rA   rM      s   f3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 )Nr	   )rU   rV   r1   r   r   orderrW   )rP   r{   r/   rW   r   )rj   r@   rA   rV     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{   r1   ndimr"   Ztiler   Zcumprodr!   r   rW   )rP   r/   xpr0   r@   r@   rA   
_call_impl"  s    


zRadauDenseOutput._call_impl)r   r   r   rV   r   r   r@   r@   )rj   rA   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$   rw   r   r   r)   r    r*   r+   r   r&   ry   rz   rB   rL   rM   r   r@   r@   r@   rA   <module>   sD   ( $(([(  i