a
    BCCfM                     @   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 ]R}t	dD ]"}| |||  |||  ||< qjtt|s q|jt||d   }|jt||d d|d     }|	||}|	||}||d< |j|d< |j|d< t|| }|dur.|| }|durf|dks`|t
|  d|  | |krf q||7 }t|}|dks|du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 rB   V/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/integrate/_ivp/radau.pysolve_collocation_system0   sR    '


 $






rD   c                 C   st   |du s|du s|dkrd}n| | || d  }t jdd" td||d  }W d   n1 sf0    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)divideg      п)r$   Zerrstatemin)h_abs	h_abs_old
error_normerror_norm_old
multiplierfactorrB   rB   rC   predict_factor   s    0rN   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 time derivative of the state ``y``
        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
        return an array of the same shape as ``y``. See `vectorized` for more
        information.
    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` can be called in a vectorized fashion. Default is False.

        If ``vectorized`` is False, `fun` will always be called with ``y`` of
        shape ``(n,)``, where ``n = len(y0)``.

        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
        the returned array is the time derivative of the state corresponding
        with a column of ``y``).

        Setting ``vectorized=True`` allows for faster finite difference
        approximation of the Jacobian by this method, but may result in slower
        execution overall in some circumstances (e.g. small ``len(y0)``).

    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 u 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selfrB   rC   luA  s    zRadau.__init__.<locals>.luc                 S   s
   |  |S N)ZsolveZLUbrB   rB   rC   r8   E  s    z Radau.__init__.<locals>.solve_luZcsc)formatc                    s     j d7  _ t| ddS )Nr	   T)Zoverwrite_a)rS   r   rT   rV   rB   rC   rX   J  s    c                 S   s   t | |ddS )NT)Zoverwrite_b)r   rZ   rB   rB   rC   r8   N  s    T)(r   super__init__y_oldr
   max_stepr   r9   rtolatolr0   r1   r2   fr   	directionrH   r   rI   rK   maxr   rG   
newton_tolsol
jac_factor_validate_jacjacJr   r   r$   identityrX   r8   Icurrent_jacr6   r7   r;   )rW   r0   t0y0t_boundr`   ra   rb   rj   Zjac_sparsityZ
vectorizedZ
first_stepZ
extraneousrX   r8   rm   	__class__rV   rC   r^   '  s@    

zRadau.__init__c                    s:  j }j} d u rZd u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 rR   )njevr   Zfun_vectorizedrb   rh   )r1   r2   rc   rk   )rW   sparsityrB   rC   jac_wrappedg  s    
z(Radau._validate_jac.<locals>.jac_wrappedr	   c                    s     j d7  _ t | |tdS Nr	   Zdtype)rt   r   floatr1   r2   _rj   rW   rB   rC   rv   t  s    rx   c                    s"    j d7  _ tj | |tdS rw   )rt   r$   asarrayry   rz   r|   rB   rC   rv   {  s    z8`jac` is expected to have shape {}, but actually has {}.)N)N)r1   r2   r   r   r   rc   callablert   r$   r}   ry   r   r9   
ValueErrorr\   )rW   rj   ru   ro   rp   groupsrv   rk   rB   )rj   rW   ru   rC   ri   \  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 }|s||k rd| jfS || j	 }|| }| j	|| j  dkr| j}|| }t|}| jd u r*td|jd f}n| ||t  j| }|t||  }d}|s|d u sr|d u 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 uo|d	ko|dk}!t'||	||
} t*t+||  } |!sH| dk rHd
} nd }d }| ||}"|!rt||||"}d}n|d urd}| j| _|| _||  | _|| _,|| _ || _|"| _|| _-|| _|| _|| _|| _|| _.| / | _||fS )Nr   Fr   r   TrQ   r   g?r   r	   rP   g333333?)0r1   r2   rc   r`   rb   ra   r$   abs	nextafterrd   infrH   rI   rK   rk   r6   r7   rn   rj   ZTOO_SMALL_STEPrq   rg   Zzerosr   r&   r+   rX   r    rm   r!   rD   r0   rf   r8   r#   Emaximumr   r(   rN   re   
MIN_FACTORrG   
MAX_FACTORr_   r;   t_old_compute_dense_output)#rW   r1   r2   rc   r`   rb   ra   Zmin_steprH   rI   rK   rk   r6   r7   rn   rj   ZrejectedZstep_acceptedmessager3   Zt_newr4   r5   r>   Zn_iterr;   r?   Zy_newZZEerrorrJ   ZsafetyrM   Zrecompute_jacZf_newrB   rB   rC   
_step_impl  s    "




 



zRadau._step_implc                 C   s$   t | jjt}t| j| j| j|S rY   )	r$   r#   r;   r+   PRadauDenseOutputr   r1   r_   )rW   QrB   rB   rC   r     s    zRadau._compute_dense_outputc                 C   s   | j S rY   )rg   rV   rB   rB   rC   _dense_output_impl#  s    zRadau._dense_output_impl)__name__
__module____qualname____doc__r$   r   r^   ri   r   r   r   __classcell__rB   rB   rr   rC   rO      s   s55 rO   c                       s$   e Zd Z fddZdd Z  ZS )r   c                    s8   t  || || | _|| _|jd d | _|| _d S rR   )r]   r^   r3   r   r   orderr_   )rW   r   r1   r_   r   rr   rB   rC   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   r3   ndimr$   Ztiler   Zcumprodr#   r   r_   )rW   r1   xpr2   rB   rB   rC   
_call_impl/  s    


zRadauDenseOutput._call_impl)r   r   r   r^   r   r   rB   rB   rr   rC   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   rD   rN   rO   r   rB   rB   rB   rC   <module>   sJ   ( $(([(  v