L iYddlZddlmZmZddlmZmZmZm Z m Z m Z ddl m Z dZdZdZd ZGd d eZGd d eZGddeZGddeZGddeZGddeZy)N) OdeSolver DenseOutput)validate_max_step validate_tolselect_initial_stepnormwarn_extraneousvalidate_first_step)dop853_coefficientsg?皙? c T||d<tt|dd|dddD]F\} \} } tj|d| j| d| |z} ||| |zz|| z|| <H||tj|ddj|zz} |||z| }||d<| |fS)a8Perform 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. rrNstart) enumeratezipnpdotT)funtyfhABCKsacdyy_newf_news ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/integrate/_ivp/rk.pyrk_stepr(s^ AaDs1QR5!AB%0:& 6Aq VVAbqEGGQrU #a '1q1u9a"f%!& BFF1Sb688Q'' 'E Au E AbE %<c0eZdZUdZeZejed<eZ ejed<eZ ejed<eZ ejed<eZ ejed<eZ eed<eZeed<eZeed <ej"d d d d ffd ZdZdZdZdZxZS) RungeKuttaz,Base class for explicit Runge-Kutta methods.rrrEPordererror_estimator_ordern_stagesMbP?ư>FNc t| t | |||||dd|_t ||_t |||j\|_|_ |j|j|j|_ | jt|j|j|j|||j|j|j |j|j |_nt%| |||_t'j(|j*dz|jf|jj,|_d|j dzz |_d|_y)NT)support_complexrdtyper)r super__init__y_oldrmax_steprnrtolatolrrrrr directionr/h_absr remptyr0r6r error_exponent h_previous selfrt0y0t_boundr:r<r= vectorized first_step extraneous __class__s r'r8zRungeKutta.__init__Us  # b"gz)-  / )(3 +D$? 49$&&$&&)  ,$&&$&&'8TVVT^^**DIItyyBDJ-ZWEDJ4==1,dff5TVV\\J D$>$>$BCr)c\tj|j|j|zSN)rrrr,)rDr rs r'_estimate_errorzRungeKutta._estimate_erroris vvacc466"Q&&r)c>t|j|||z SrM)r rN)rDr rscales r'_estimate_error_normzRungeKutta._estimate_error_normlsD((A.677r)c |j}|j}|j}|j}|j}dt j t j||jt jz|z z}|j|kDr|}n|j|kr|}n |j}d}d} |s||krd|jfS||jz} || z} |j| |jz zdkDr |j} | |z } t j | }t|j|||j| |j |j"|j$|j& \} } |t j(t j |t j | |zz}|j+|j&| |}|dkrF|dk(rt,}n$t/t,t0||j2zz}| r t/d|}||z}d}n)|t5t6t0||j2zzz}d} |s |_||_ |_ |_||_  |_y)NrFrrT)TN)rrr:r<r=rabs nextafterr>infr?TOO_SMALL_STEPrGr(rrrrrr maximumrQ MAX_FACTORminSAFETYrAmax MIN_FACTORrBr9)rDrrr:r<r=min_stepr? step_accepted step_rejectedrt_newr%r&rP error_normfactors r' _step_implzRungeKutta._step_implos/ FF FF==yyyyr||At~~/FG!KLL :: E ZZ( "EJJE  xd1111&AEE~~!56:  AFF1IE"488Q4661dff#'66466466;LE52::bffQi?$FFE224661eDJA~?'F !'*8K8K*K!KMF! F^F $ Z#jD4G4G&GGII $ E H  r)c|jjj|j}t |j |j |j|SrM)r rrr- RkDenseOutputt_oldrr9)rDQs r'_dense_output_implzRungeKutta._dense_output_impls9 FFHHLL TZZQ??r))__name__ __module__ __qualname____doc__NotImplementedrrndarray__annotations__rrr,r-r.intr/r0rUr8rNrQrcrh __classcell__rKs@r'r+r+Js6"Arzz""Arzz""Arzz""Arzz""Arzz"E3!/3/"Hc"68ff% ('8AF@r)r+ceZdZdZdZdZdZejgdZ ejgdgdgdgZ ejgdZ ejgd Z ejgd gd gd gd gZ y)RK23aExplicit 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 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)``. Here `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`. vectorized : bool, optional Whether `fun` may be called in a vectorized fashion. False (default) is recommended for this solver. 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 methods 'Radau' and 'BDF', but will result in slower execution for this solver. 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??)rrr)rwrr)rrxr)gqq?gUUUUUU?gqq?)grqDZ?gUUUUUUgqqg?)rgUUUUUUgrq?)rrgUUUUUU)rgUUUUUU?gqq)rrrNrirjrkrlr.r/r0rarrayrrrr,r-r)r'rtrts[x EHA A !A)*A$  Ar)rtc *eZdZdZdZdZdZejgdZ ejgdgdgdgd gd gd gZ ejgd Z ejgd Z ejgdgdgdgdgdgdgdgZ y)RK45aExplicit 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), 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`. 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. )rr g333333?g?gqq?r)rrrrr)r rrrr)g333333?g?rrr)gII?g gqq @rr)gq@g 1'gR<6R#@gE3ҿr)g+@g>%gr!@gE]t?g/pѿ)gUUUUUU?rgVI?gUUUUU?gϡԿg1 0 ?)g2TrgĿ UZkq?ggX ?g{tg?)rg# !gJ<@gFC)rrrr)rgF@gFj'NgDg@)rgdD gaP#$@g 2)rg `_. Nrr1r2Fc t |||||||||| f i| tjtj |j f|jj|_ |jd|jdz|_ y)Nr5r) r7r8rr@r N_STAGES_EXTENDEDr;rr6 K_extendedr0r rCs r'r8zDOP853.__init__sz b"gxt#Z ?3= ?(($7$I$I$(FF$,3766<<A!3$--!"34r)ctj|j|j}tj|j|j}tj tj |dtj |z}tj|}|dkD}tj ||||z ||<||z|zS)Ng?r)rrrE5E3hypotrS ones_like)rDr rerr5err3denomcorrection_factormasks r'rNzDOP853._estimate_errorsvvacc477#vvacc477#sRVVD\'9:LL.qy"$&&d"4uT{"B$4x+++r)ctj|j|j|z }tj|j|j|z }tj j |dz}tj j |dz}|dk(r|dk(ry|d|zz}tj||ztj|t|zz S)Nrvrgg{Gz?) rrrrrlinalgr rSsqrtlen) rDr rrPrr err5_norm_2 err3_norm_2rs r'rQzDOP853._estimate_error_normsvvacc477#e+vvacc477#e+iinnT*A- iinnT*A- !  q 0d[00vvay;&U1C)DDDr)c.|j}|j}tt|j|j |j dzD]c\}\}}tj|d|j|d||z}|j|j||zz|j|z||<etjtj|j f|jj"}|d}|j$|jz } | |d<||z| z |d<d| z||j&|zzz |d<|tj|j(|z|ddt+|j|j,|j|S)Nrrr5rrvru)rrBrrA_EXTRAC_EXTRAr0rrrrrfr9r@r INTERPOLATOR_POWERr;r6rrDDop853DenseOutputr) rDr rr!r"r#r$Ff_olddelta_ys r'rhzDOP853._dense_output_impls_ OO OO"3t||T\\#B)-):< AIAv1"12A'!+B88DJJQ. R@AaD A HH)< "UWWQZ!^  r)c ||jz |jz }|jdk(r9tj||j dz}tj |}n*A 1 ADJJNA./A 11%A FFRVVDFFA& & 66Q; AtG$ $A OAr)rirjrkr8rrqrrs@r'rere(s r)rec$eZdZfdZdZxZS)rcVt|||||z |_||_||_yrM)r7r8rrr9)rDrfrr9rrKs r'r8zDop853DenseOutput.__init__Bs+ "U r)c||jz |jz }|jdk(r tj|j }nR|dddf}tj t|t|j f|j j}tt|jD] \}}||z }|dzdk(r||z}|d|z z}"||j z }|jS)Nrr5rvr) rfrrr zeros_liker9zerosrr6rreversedrr)rDrrrirs r'rzDop853DenseOutput._call_implHs ^tvv % 66Q; djj)A!T' A#a&#djj/2$**:J:JKAhtvv./ DAq FA1uzQQU    TZZss r)rrrs@r'rrAs  r)r)numpyrbaserrcommonrrrr r r r rZr\rXr(r+rtr}rrerr{r)r'rs(AA!    9xj@j@Zk:k\oI:oIdNDZNDbK2 r)