B
    0dFS                 @   s   d dl ZddlmZmZ ddlmZmZmZm	Z	m
Z
mZ ddlmZ dZdZdZd	d
 ZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZdS )    N   )	OdeSolverDenseOutput)validate_max_stepvalidate_tolselect_initial_stepnormwarn_extraneousvalidate_first_step)dop853_coefficientsg?g?
   c	             C   s   ||d< xnt t|dd |dd ddD ]H\}	\}
}t|d|	 j|
d|	 | }| |||  || ||	< q,W ||t|dd j|  }| || |}||d< ||fS )a8  Perform a single Runge-Kutta step.

    This function computes a prediction of an explicit Runge-Kutta method and
    also estimates the error of a less accurate method.

    Notation for Butcher tableau is as in [1]_.

    Parameters
    ----------
    fun : callable
        Right-hand side of the system.
    t : float
        Current time.
    y : ndarray, shape (n,)
        Current state.
    f : ndarray, shape (n,)
        Current value of the derivative, i.e., ``fun(x, y)``.
    h : float
        Step to use.
    A : ndarray, shape (n_stages, n_stages)
        Coefficients for combining previous RK stages to compute the next
        stage. For explicit methods the coefficients at and above the main
        diagonal are zeros.
    B : ndarray, shape (n_stages,)
        Coefficients for combining RK stages for computing the final
        prediction.
    C : ndarray, shape (n_stages,)
        Coefficients for incrementing time for consecutive RK stages.
        The value for the first stage is always zero.
    K : ndarray, shape (n_stages + 1, n)
        Storage array for putting RK stages here. Stages are stored in rows.
        The last row is a linear combination of the previous rows with
        coefficients

    Returns
    -------
    y_new : ndarray, shape (n,)
        Solution at t + h computed with a higher accuracy.
    f_new : ndarray, shape (n,)
        Derivative ``fun(t + h, y_new)``.

    References
    ----------
    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
           Equations I: Nonstiff Problems", Sec. II.4.
    r   r   N)start)	enumeratezipnpdotT)funtyfhABCKsacdyy_newf_new r#   I/var/www/html/venv/lib/python3.7/site-packages/scipy/integrate/_ivp/rk.pyrk_step   s    /0"r%   c                   s   e Zd ZU dZeZejed< eZ	ejed< eZ
ejed< eZejed< eZejed< eZeed< eZeed< eZeed	< ejd
dddf fdd	Zdd Zdd Zdd Zdd Z  ZS )
RungeKuttaz,Base class for explicit Runge-Kutta methods.r   r   r   EPordererror_estimator_ordern_stagesgMbP?gư>FNc
          	      s   t |
 t j|||||dd d | _t|| _t||| j\| _| _	| 
| j| j| _|	d krt| j
| j| j| j| j| j| j| j	| _nt|	||| _tj| jd | jf| jjd| _d| jd  | _d | _d S )NT)Zsupport_complexr   )dtyper   )r	   super__init__y_oldr   max_stepr   nrtolatolr   r   r   r   r   	directionr*   h_absr
   r   emptyr+   r,   r   error_exponent
h_previous)selfr   t0y0t_boundr0   r2   r3   
vectorized
first_step
extraneous)	__class__r#   r$   r.   U   s    
 zRungeKutta.__init__c             C   s   t |j| j| S )N)r   r   r   r'   )r9   r   r   r#   r#   r$   _estimate_errori   s    zRungeKutta._estimate_errorc             C   s   t | ||| S )N)r   rA   )r9   r   r   scaler#   r#   r$   _estimate_error_norml   s    zRungeKutta._estimate_error_normc          
   C   s  | j }| j}| j}| j}| j}dtt|| jtj	 |  }| j
|krP|}n| j
|k r`|}n| j
}d}d}	x|s||k rd| jfS || j }
||
 }| j|| j  dkr| j}|| }
t|
}t| j||| j|
| j| j| j| j	\}}|tt|t||  }| | j|
|}|dk rl|dkr:t}nttt|| j  }|	r^td|}||9 }d}qr|ttt|| j  9 }d}	qrW |
| _|| _|| _ || _|| _
|| _dS )Nr   Fr   r   T)TN)r   r   r0   r2   r3   r   absZ	nextafterr4   infr5   ZTOO_SMALL_STEPr<   r%   r   r   r   r   r   r   maximumrC   
MAX_FACTORminSAFETYr7   max
MIN_FACTORr8   r/   )r9   r   r   r0   r2   r3   Zmin_stepr5   Zstep_acceptedZstep_rejectedr   Zt_newr!   r"   rB   Z
error_normfactorr#   r#   r$   
_step_implo   sZ    "





 


zRungeKutta._step_implc             C   s$   | j j| j}t| j| j| j|S )N)r   r   r   r(   RkDenseOutputt_oldr   r/   )r9   Qr#   r#   r$   _dense_output_impl   s    zRungeKutta._dense_output_impl)__name__
__module____qualname____doc__NotImplementedr   r   Zndarray__annotations__r   r   r'   r(   r)   intr*   r+   rE   r.   rA   rC   rM   rQ   __classcell__r#   r#   )r@   r$   r&   J   s    
Cr&   c               @   s   e Zd ZdZdZdZdZedddgZ	edddgdddgdddggZ
eddd	gZed
dddgZedddgdddgdddgdddggZdS )RK23a  Explicit Runge-Kutta method of order 3(2).

    This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled
    assuming accuracy of the second-order method, but steps are taken using the
    third-order accurate formula (local extrapolation is done). A cubic Hermite
    polynomial is used for the dense output.

    Can be applied in the complex domain.

    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 ndarray ``y``.
        It can either have shape (n,), then ``fun`` must return array_like with
        shape (n,). Or alternatively it can have shape (n, k), then ``fun``
        must return 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).
    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`.
    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 evaluations of the system's right-hand side.
    njev : int
        Number of evaluations of the Jacobian. Is always 0 for this solver as it does not use the Jacobian.
    nlu : int
        Number of LU decompositions. Is always 0 for this solver.

    References
    ----------
    .. [1] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
           Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
          r   g      ?g      ?gqq?gUUUUUU?gqq?grqǱ?gUUUUUUgqqg      ?r   gUUUUUUgrq?gUUUUUUgUUUUUU?gqqr   N)rR   rS   rT   rU   r)   r*   r+   r   arrayr   r   r   r'   r(   r#   r#   r#   r$   rZ      s   KrZ   c               @   s  e Zd ZdZdZdZdZeddddd	d
gZ	edddddgdddddgdddddgdddddgdddddgdddddggZ
eddddddgZedddd d!d"d#gZed
d$d%d&gddddgdd'd(d)gdd*d+d,gdd-d.d/gdd0d1d2gdd3d4d5ggZd6S )7RK45a  Explicit Runge-Kutta method of order 5(4).

    This uses the Dormand-Prince pair of formulas [1]_. The error is controlled
    assuming accuracy of the fourth-order method accuracy, but steps are taken
    using the fifth-order accurate formula (local extrapolation is done).
    A quartic interpolation polynomial is used for the dense output [2]_.

    Can be applied in the complex domain.

    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).
    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`.
    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 evaluations of the system's right-hand side.
    njev : int
        Number of evaluations of the Jacobian. Is always 0 for this solver as it does not use the Jacobian.
    nlu : int
        Number of LU decompositions. Is always 0 for this solver.

    References
    ----------
    .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
           formulae", Journal of Computational and Applied Mathematics, Vol. 6,
           No. 1, pp. 19-26, 1980.
    .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
           of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
             r   g?g333333?g?gqq?r   g333333?g?gII?ggqq@gq@g 1'gR<6R#@gE3ҿg+@g>%gr!@gE]t?g/pѿgUUUUUU?gVI?gUUUUU?gϡԿg10?g2TgĿ
UZkq?ggX
?g{tg?g#
!gJ<@gFCgF@gFj'NgDg@gdDgaP#$@g2g<p@g@갘g,@gRq#g_40g.
@gFg'?g'gK@N)rR   rS   rT   rU   r)   r*   r+   r   r]   r   r   r   r'   r(   r#   r#   r#   r$   r^     s6   N

r^   c                   s   e Zd ZdZejZdZdZej	dedef Z	ej
Z
ejde ZejZejZejZej	ed d Zejed d Zejddddf fd	d
	Zdd Zdd Zdd Z  ZS )DOP853a  Explicit Runge-Kutta method of order 8.

    This is a Python implementation of "DOP853" algorithm originally written
    in Fortran [1]_, [2]_. Note that this is not a literate translation, but
    the algorithmic core and coefficients are the same.

    Can be applied in the complex domain.

    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).
    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`.
    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 evaluations of the system's right-hand side.
    njev : int
        Number of evaluations of the Jacobian. Is always 0 for this solver
        as it does not use the Jacobian.
    nlu : int
        Number of LU decompositions. Is always 0 for this solver.

    References
    ----------
    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
           Equations I: Nonstiff Problems", Sec. II.
    .. [2] `Page with original Fortran code of DOP853
            <http://www.unige.ch/~hairer/software.html>`_.
          Nr   gMbP?gư>Fc
          
      sV   t  j|||||||||	f	|
 tjtj| jf| jjd| _	| j	d | j
d  | _d S )N)r,   r   )r-   r.   r   r6   r   ZN_STAGES_EXTENDEDr1   r   r,   
K_extendedr+   r   )r9   r   r:   r;   r<   r0   r2   r3   r=   r>   r?   )r@   r#   r$   r.     s
    zDOP853.__init__c             C   st   t |j| j}t |j| j}t t |dt | }t |}|dk}t || ||  ||< || | S )Ng?r   )r   r   r   E5E3hypotrD   Z	ones_like)r9   r   r   err5err3denomZcorrection_factormaskr#   r#   r$   rA     s    
zDOP853._estimate_errorc       	      C   s   t |j| j| }t |j| j| }t j|d }t j|d }|dkr\|dkr\dS |d|  }t || t |t	|  S )Nr\   r   g        g{Gz?)
r   r   r   rf   rg   Zlinalgr   rD   sqrtlen)	r9   r   r   rB   ri   rj   Zerr5_norm_2Zerr3_norm_2rk   r#   r#   r$   rC     s    zDOP853._estimate_error_normc       
      C   s
  | j }| j}xntt| j| j| jd dD ]N\}\}}t|d | j	|d | | }| 
| j||  | j| ||< q*W tjtj| jf| jjd}|d }| j| j }	|	|d< || |	 |d< d|	 || j|   |d< |t| j| |dd < t| j| j| j|S )Nr   )r   )r,   r   r\   r[   )re   r8   r   r   A_EXTRAC_EXTRAr+   r   r   r   r   rO   r/   r6   r   ZINTERPOLATOR_POWERr1   r,   r   r   DDop853DenseOutputr   )
r9   r   r   r   r   r   r    FZf_oldZdelta_yr#   r#   r$   rQ     s    "$zDOP853._dense_output_impl)rR   rS   rT   rU   r   ZN_STAGESr+   r)   r*   r   r   r   rg   rf   rq   ro   rp   r   rE   r.   rA   rC   rQ   rY   r#   r#   )r@   r$   rb     s$   M	
rb   c                   s$   e Zd Z fddZdd Z  ZS )rN   c                s8   t  || || | _|| _|jd d | _|| _d S )Nr   )r-   r.   r   rP   shaper)   r/   )r9   rO   r   r/   rP   )r@   r#   r$   r.     s
    
zRkDenseOutput.__init__c             C   s   || j  | j }|jdkr8t|| jd }t|}n$t|| jd df}tj|dd}| jt| j| }|jdkr|| j	d d d f 7 }n
|| j	7 }|S )Nr   r   )Zaxisr\   )
rO   r   ndimr   Ztiler)   Zcumprodr   rP   r/   )r9   r   xpr   r#   r#   r$   
_call_impl  s    


zRkDenseOutput._call_impl)rR   rS   rT   r.   rx   rY   r#   r#   )r@   r$   rN     s   rN   c                   s$   e Zd Z fddZdd Z  ZS )rr   c                s(   t  || || | _|| _|| _d S )N)r-   r.   r   rs   r/   )r9   rO   r   r/   rs   )r@   r#   r$   r.   (  s    
zDop853DenseOutput.__init__c             C   s   || j  | j }|jdkr(t| j}n0|d d d f }tjt|t| jf| jjd}xDt	t
| jD ]2\}}||7 }|d dkr||9 }qh|d| 9 }qhW || j7 }|jS )Nr   )r,   r\   r   )rO   r   ru   r   Z
zeros_liker/   Zzerosrn   r,   r   reversedrs   r   )r9   r   rv   r   ir   r#   r#   r$   rx   .  s    
 

zDop853DenseOutput._call_impl)rR   rS   rT   r.   rx   rY   r#   r#   )r@   r$   rr   '  s   rr   )numpyr   baser   r   commonr   r   r   r   r	   r
    r   rI   rK   rG   r%   r&   rZ   r^   rb   rN   rr   r#   r#   r#   r$   <module>   s    <m]m 