L iDmlddlZddlZddlZddlZddgZGddZGddeZGddeZy)NAAAFloaterHormannInterpolatorc:eZdZdZdZdZdZdZdZdZ dZ y ) _BarycentricRationalzABase class for barycentric representation of a rational function.c Jtj|}tj|}|j||fi|tjj tj |tj |zj|jddd}||df}||}tj|d\}}||df}|jdd|_ |j||fi|\|_ |_ |_d|_d|_d|_y)Nraxis.T) return_index)npasarray_input_validation logical_andreduceisfiniteisnanreshapeshapeunique_shape_compute_weights_support_points_support_valuesweights_poles _residues_roots)selfxykwargszfto_keepunis f/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/interpolate/_bary_rational.py__init__z_BarycentricRational.__init__&s  JJqM JJqMq!.v...''kk!n"((1+ . 7 7 B G(  gslO gJ1403 c3hKggabk !D ! !!Q 1& 1 Ad2DL   c |jdk7r td|jdk\s td|j|jdk7r tdt j t j |s tdy)Nr z`x` must be 1-D.z`y` must be at least 1-D.rz3`x` be the same size as the first dimension of `y`.z`x` must be finite.)ndim ValueErrorsizerr allr)rr r!r"s r'rz&_BarycentricRational._input_validationAsu 66Q;/0 0vv{89 9 66QWWQZ RS Svvbkk!n%23 3&r)c tN)NotImplementedError)r#r$r"s r'rz%_BarycentricRational._compute_weightsNs!!r)c*tj|}tj|}|jj |jj ddf}|j dtjf}tjdd5dtjj||jz }|||zz||zz }dddtjtj|rDtj||ztj|z tj|<tjtj d}|D]f}tj ||s%tj|||jk(sA||||jk(j#||<htj||j |j$zS#1swY9xYw)zEvaluate the rational approximation at given values. Parameters ---------- z : array_like Input values. rr.ignore)invaliddivider N)r rravelrrrrnewaxiserrstatesubtractouterranyisinfsumnonzerorsqueezer) rr#zvsupport_valuesrCCriijjs r'__call__z_BarycentricRational.__call__Qs JJqM XXa[--55  ! ! ' ' *B / ,,sBJJ/[[( ; AR[[&&r4+?+?@@Bg./2<@A A 66"((2, !vvg&>?!# 1AbhhrlOZZ $Q ' QBxx2rvvbf8L8L.L'M'r"v1E1E'EFNNP" Qzz!QWWt{{233- A As > !Hh? + ))$**,8L8LMN((4<<7**4::<9M9MNNQRRSll#"#U +~~t~~ +~~s B,C00Dcx|j"|jj}tj|dz|jj }d|d<tj |tj|j|j|j}|j|jz|dddf<d|dddf<tj|ddddf|jtjj||}|tj||_|jS)zCompute the zeros of the rational approximation. Returns ------- zeros : array Zeros of the AAA approximation, repeated according to their multiplicity but not in any specific order. Nr rHrrJ)rrr-r rKrIrLrMrrrNrOrPrQr)rrRrSrTzers r'rootsz_BarycentricRational.rootss ;;  !!Aq1uDLL$6$67AAdG ar~~dll6:6J6J6:6J6J(LMA||d&:&::AaeHAab!eH   Qqr12vY(<(< =,,&&q!,Cbkk#./DK{{r)N) __name__ __module__ __qualname____doc__r(rrrFrVr\r_r)r'rr$s)K6 4")4V2*r)rcleZdZdZdddddfd Z d fd Zed Zed Zd Z dd Z xZ S)ru% AAA real or complex rational approximation. As described in [1]_, the AAA algorithm is a greedy algorithm for approximation by rational functions on a real or complex set of points. The rational approximation is represented in a barycentric form from which the roots (zeros), poles, and residues can be computed. Parameters ---------- x : 1D array_like, shape (n,) 1-D array containing values of the independent variable. Values may be real or complex but must be finite. y : 1D array_like, shape (n,) Function values ``f(x)``. Infinite and NaN values of `values` and corresponding values of `points` will be discarded. rtol : float, optional Relative tolerance, defaults to ``eps**0.75``. If a small subset of the entries in `values` are much larger than the rest the default tolerance may be too loose. If the tolerance is too tight then the approximation may contain Froissart doublets or the algorithm may fail to converge entirely. max_terms : int, optional Maximum number of terms in the barycentric representation, defaults to ``100``. Must be greater than or equal to one. clean_up : bool, optional Automatic removal of Froissart doublets, defaults to ``True``. See notes for more details. clean_up_tol : float, optional Poles with residues less than this number times the geometric mean of `values` times the minimum distance to `points` are deemed spurious by the cleanup procedure, defaults to 1e-13. See notes for more details. Attributes ---------- support_points : array Support points of the approximation. These are a subset of the provided `x` at which the approximation strictly interpolates `y`. See notes for more details. support_values : array Value of the approximation at the `support_points`. weights : array Weights of the barycentric approximation. errors : array Error :math:`|f(z) - r(z)|_\infty` over `points` in the successive iterations of AAA. Warns ----- RuntimeWarning If `rtol` is not achieved in `max_terms` iterations. See Also -------- FloaterHormannInterpolator : Floater-Hormann barycentric rational interpolation. pade : Padé approximation. Notes ----- At iteration :math:`m` (at which point there are :math:`m` terms in the both the numerator and denominator of the approximation), the rational approximation in the AAA algorithm takes the barycentric form .. math:: r(z) = n(z)/d(z) = \frac{\sum_{j=1}^m\ w_j f_j / (z - z_j)}{\sum_{j=1}^m w_j / (z - z_j)}, where :math:`z_1,\dots,z_m` are real or complex support points selected from `x`, :math:`f_1,\dots,f_m` are the corresponding real or complex data values from `y`, and :math:`w_1,\dots,w_m` are real or complex weights. Each iteration of the algorithm has two parts: the greedy selection the next support point and the computation of the weights. The first part of each iteration is to select the next support point to be added :math:`z_{m+1}` from the remaining unselected `x`, such that the nonlinear residual :math:`|f(z_{m+1}) - n(z_{m+1})/d(z_{m+1})|` is maximised. The algorithm terminates when this maximum is less than ``rtol * np.linalg.norm(f, ord=np.inf)``. This means the interpolation property is only satisfied up to a tolerance, except at the support points where approximation exactly interpolates the supplied data. In the second part of each iteration, the weights :math:`w_j` are selected to solve the least-squares problem .. math:: \text{minimise}_{w_j}|fd - n| \quad \text{subject to} \quad \sum_{j=1}^{m+1} w_j = 1, over the unselected elements of `x`. One of the challenges with working with rational approximations is the presence of Froissart doublets, which are either poles with vanishingly small residues or pole-zero pairs that are close enough together to nearly cancel, see [2]_. The greedy nature of the AAA algorithm means Froissart doublets are rare. However, if `rtol` is set too tight then the approximation will stagnate and many Froissart doublets will appear. Froissart doublets can usually be removed by removing support points and then resolving the least squares problem. The support point :math:`z_j`, which is the closest support point to the pole :math:`a` with residue :math:`\alpha`, is removed if the following is satisfied .. math:: |\alpha| / |z_j - a| < \verb|clean_up_tol| \cdot \tilde{f}, where :math:`\tilde{f}` is the geometric mean of `support_values`. References ---------- .. [1] Y. Nakatsukasa, O. Sete, and L. N. Trefethen, "The AAA algorithm for rational approximation", SIAM J. Sci. Comp. 40 (2018), A1494-A1522. :doi:`10.1137/16M1106122` .. [2] J. Gilewicz and M. Pindor, Pade approximants and noise: rational functions, J. Comp. Appl. Math. 105 (1999), pp. 285-297. :doi:`10.1016/S0377-0427(02)00674-X` Examples -------- Here we reproduce a number of the numerical examples from [1]_ as a demonstration of the functionality offered by this method. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.interpolate import AAA >>> import warnings For the first example we approximate the gamma function on ``[-3.5, 4.5]`` by extrapolating from 100 samples in ``[-1.5, 1.5]``. >>> from scipy.special import gamma >>> sample_points = np.linspace(-1.5, 1.5, num=100) >>> r = AAA(sample_points, gamma(sample_points)) >>> z = np.linspace(-3.5, 4.5, num=1000) >>> fig, ax = plt.subplots() >>> ax.plot(z, gamma(z), label="Gamma") >>> ax.plot(sample_points, gamma(sample_points), label="Sample points") >>> ax.plot(z, r(z).real, '--', label="AAA approximation") >>> ax.set(xlabel="z", ylabel="r(z)", ylim=[-8, 8], xlim=[-3.5, 4.5]) >>> ax.legend() >>> plt.show() We can also view the poles of the rational approximation and their residues: >>> order = np.argsort(r.poles()) >>> r.poles()[order] array([-3.81591039e+00+0.j , -3.00269049e+00+0.j , -1.99999988e+00+0.j , -1.00000000e+00+0.j , 5.85842812e-17+0.j , 4.77485458e+00-3.06919376j, 4.77485458e+00+3.06919376j, 5.29095868e+00-0.97373072j, 5.29095868e+00+0.97373072j]) >>> r.residues()[order] array([ 0.03658074 +0.j , -0.16915426 -0.j , 0.49999915 +0.j , -1. +0.j , 1. +0.j , -0.81132013 -2.30193429j, -0.81132013 +2.30193429j, 0.87326839+10.70148546j, 0.87326839-10.70148546j]) For the second example, we call `AAA` with a spiral of 1000 points that wind 7.5 times around the origin in the complex plane. >>> z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, 1000)) >>> r = AAA(z, np.tan(np.pi*z/2), rtol=1e-13) We see that AAA takes 12 steps to converge with the following errors: >>> r.errors.size 12 >>> r.errors array([2.49261500e+01, 4.28045609e+01, 1.71346935e+01, 8.65055336e-02, 1.27106444e-02, 9.90889874e-04, 5.86910543e-05, 1.28735561e-06, 3.57007424e-08, 6.37007837e-10, 1.67103357e-11, 1.17112299e-13]) We can also plot the computed poles: >>> fig, ax = plt.subplots() >>> ax.plot(z.real, z.imag, '.', markersize=2, label="Sample points") >>> ax.plot(r.poles().real, r.poles().imag, '.', markersize=5, ... label="Computed poles") >>> ax.set(xlim=[-3.5, 3.5], ylim=[-3.5, 3.5], aspect="equal") >>> ax.legend() >>> plt.show() We now demonstrate the removal of Froissart doublets using the `clean_up` method using an example from [1]_. Here we approximate the function :math:`f(z)=\log(2 + z^4)/(1 + 16z^4)` by sampling it at 1000 roots of unity. The algorithm is run with ``rtol=0`` and ``clean_up=False`` to deliberately cause Froissart doublets to appear. >>> z = np.exp(1j*2*np.pi*np.linspace(0,1, num=1000)) >>> def f(z): ... return np.log(2 + z**4)/(1 - 16*z**4) >>> with warnings.catch_warnings(): # filter convergence warning due to rtol=0 ... warnings.simplefilter('ignore', RuntimeWarning) ... r = AAA(z, f(z), rtol=0, max_terms=50, clean_up=False) >>> mask = np.abs(r.residues()) < 1e-13 >>> fig, axs = plt.subplots(ncols=2) >>> axs[0].plot(r.poles().real[~mask], r.poles().imag[~mask], '.') >>> axs[0].plot(r.poles().real[mask], r.poles().imag[mask], 'r.') Now we call the `clean_up` method to remove Froissart doublets. >>> with warnings.catch_warnings(): ... warnings.simplefilter('ignore', RuntimeWarning) ... r.clean_up() 4 # may vary >>> mask = np.abs(r.residues()) < 1e-13 >>> axs[1].plot(r.poles().real[~mask], r.poles().imag[~mask], '.') >>> axs[1].plot(r.poles().real[mask], r.poles().imag[mask], 'r.') >>> plt.show() The left image shows the poles prior of the approximation ``clean_up=False`` with poles with residue less than ``10^-13`` in absolute value shown in red. The right image then shows the poles after the `clean_up` method has been called. NdTvIh%<=)rtol max_termsclean_up clean_up_tolcTt||||||r|j|yy)N)rhri)superr(rjrr r!rhrirjrk __class__s r'r(z AAA.__init__s- ADI>  MM, ' r)ctj|}|dkr td|jdk7r tdt|||y)Nr zB`max_terms` must be an integer value greater than or equal to one.z`y` must be 1-D.)operatorindexr,r+rmrrns r'rzAAA._input_validationsRNN9- q=-. . 66Q;/0 0 !!Q'r)c|jSr0)rrs r'support_pointszAAA.support_points###r)c|jSr0)rrts r'rAzAAA.support_valuesrvr)c tj|}tj|tj}tj||d}|"tj |j dzn|}|tjj|tjz}tj||} tj||} tj||f|} tj||f|} tj|| jj} tjtj||}t|D]}tj tj"||||z }|||| |<|||| |<tj$dd5d||||z z | dd|f<dddd|tj&|d |<tj$d 5|| |z | dd|fz| dd|f<ddd|j)}||dzk\rt*jj-| |d|dzfdd \}}}|tj.|k(}|j1|ddfj)d tj2|j)z j5|}nbt*jj7| |d|dzfd }|j8d}|j)d tj2|z }|d k7}tj$d 5| ddd|dzfdd|f||| d|dz|zz}| ddd|dzfdd|f||z}dddtj:tj<|z}d||<|||<||z }tjj||z tj}|| |<||ksn|dz k(r t?j@d|dtBd| d|dz} | d|dz} d k7}| d|dz|_"||_#||_$| || |||fS#1swYxYw#1swY~xYw#1swYxYw)NrH?g?)ordr3rXr Fr)r4) full_matrices check_finiter r|rzAAA failed to converge within z iterations.rY stacklevel)%r r-onesbool_rMfinfoepsrPnorminfemptyrealrIrepeatmeanrangeargmaxabsr8r>r=rOsvdminconjsqrtastype null_spacerr<rwarningswarnRuntimeWarningerrors_points_values)rr#r$rhriMmaskrIatolzjfjCArRrRrErows_sVmmwjnmi0rZDD_inf max_error i_non_zeros r'rzAAA._compute_weightsss GGAJwwq)q!S),0Lrxx""D(dbiinnQBFFn33 XXiu - XXiu - HHa^5 1 HHa^5 1)166<<8 IIbggaj! $y!8 A266!D'AdG"345BdGBKBqEdGBKBqEHh? 0q1T72;/!Q$ 0-2DD!!$R( )X. 0r!u9!Q$/!Q$ 088:Dq1u},,**dGa!eGm$E+1a"&&)^ffhr1uo))q)1BGGBFFH4EEMMeTLL++AdGa!eGm,<5+QWWR[UUU^bggbk1qBX. 2a1q5jM!R%(BrFR!a%[_,DEa1q5jM!R%(2b61  2 HHQK"((1+-EAeHxAeHAA q1u"&&9I!F1ID q8 t A  MM:9+\R(Q 8!a%[ !a%[1W Wq1uo   *~r*~r*~=={ 0 0  0 02 2 2s% R&R37AS&R0 3R= S c Rtjjtj|j }tj tjtjj|j|jd}tjdd5tjtj|j|z ||zk}ddddj}|dk(r|Stj |dt"d tj$tjtjj|j&|j|d}tj(|j&||_tj(|j*||_tj,j/tj0j|j|j&d}|j |}|j|} |j&j} dtjj| |j&z } |ddtj2f| z| |j*zz } tj4j7| d \} } }tj8|| dz ddf|_d|_d|_d|_ |S#1swY*xYw) aAutomatic removal of Froissart doublets. Parameters ---------- cleanup_tol : float, optional Poles with residues less than this number times the geometric mean of `values` times the minimum distance to `points` are deemed spurious by the cleanup procedure, defaults to 1e-13. Returns ------- int Number of Froissart doublets detected r r r3rXNrz Froissart doublets detected.rYr~Fr})!rOstatsgmeanr rrrr9r:rVrr8r>r\r-rrrargminrdeleterrr not_equalr7rPrrrrrr)r cleanup_tolgeom_mean_abs_f Z_distancesrDniclosest_spt_pointrr$r#rRrrrrs r'rjz AAA.clean_upsn  ++++BFF4<<,@Aff FF2;;$$TZZ\4<<@ A [[( ; t}}'+5 o8UUB  UZZ 7I 9:N#$ &II FF2;;$$T%9%94::<;KL MTU  "yy)=)=?PQ!yy)=)=?PQ~~$$ LL  t||T-A-A B%  LL  LL   % %  !!!T%9%9: : am q 1t';';#; ;,,""15"91awwqQqz*    [  s 4ALL&)NrfTrg)rg) r`rarbrcr(rpropertyrurArrj __classcell__ros@r'rrs_Vn&*S4#(JN', ($$$$X>tCr)c8eZdZdZddfd ZfdZdZxZS)ru Floater-Hormann barycentric rational interpolator (C∞ smooth on real axis). As described in [1]_, the method of Floater and Hormann computes weights for a barycentric rational interpolant with no poles on the real axis. Parameters ---------- x : 1D array_like, shape (n,) 1-D array containing values of the independent variable. Values may be real or complex but must be finite. y : array_like, shape (n, ...) Array containing values of the dependent variable. Infinite and NaN values of `y` and corresponding values of `x` will be discarded. d : int, default: 3 Integer satisfying ``0 <= d < n``. Floater-Hormann interpolation blends ``n - d`` polynomials of degree `d` together; for ``d = n - 1``, this is equivalent to polynomial interpolation. Attributes ---------- weights : array Weights of the barycentric approximation. See Also -------- AAA : Barycentric rational approximation of real and complex functions. pade : Padé approximation. Notes ----- The Floater-Hormann interpolant is a rational function that interpolates the data with approximation order :math:`O(h^{d+1})`. The rational function blends ``n - d`` polynomials of degree `d` together to produce a rational interpolant that contains no poles on the real axis, unlike `AAA`. The interpolant is given by .. math:: r(x) = \frac{\sum_{i=0}^{n-d} \lambda_i(x) p_i(x)} {\sum_{i=0}^{n-d} \lambda_i(x)}, where :math:`p_i(x)` is an interpolating polynomial of at most degree `d` through the points :math:`(x_i,y_i),\dots,(x_{i+d},y_{i+d})`, and :math:`\lambda_i(z)` are blending functions defined by .. math:: \lambda_i(x) = \frac{(-1)^i}{(x - x_i)\cdots(x - x_{i+d})}. When ``d = n - 1`` this reduces to polynomial interpolation. Due to its stability, the following barycentric representation of the above equation is used for computation .. math:: r(z) = \frac{\sum_{k=1}^m\ w_k f_k / (x - x_k)}{\sum_{k=1}^m w_k / (x - x_k)}, where the weights :math:`w_j` are computed as .. math:: w_k &= (-1)^{k - d} \sum_{i \in J_k} \prod_{j = i, j \neq k}^{i + d} 1/|x_k - x_j|, \\ J_k &= \{ i \in I: k - d \leq i \leq k\},\\ I &= \{0, 1, \dots, n - d\}. References ---------- .. [1] M.S. Floater and K. Hormann, "Barycentric rational interpolation with no poles and high rates of approximation", Numer. Math. 107, 315 (2007). :doi:`10.1007/s00211-007-0093-y` Examples -------- Here we compare the method against polynomial interpolation for an example where the polynomial interpolation fails due to Runge's phenomenon. >>> import numpy as np >>> from scipy.interpolate import (FloaterHormannInterpolator, ... BarycentricInterpolator) >>> def f(x): ... return 1/(1 + x**2) >>> x = np.linspace(-5, 5, num=15) >>> r = FloaterHormannInterpolator(x, f(x)) >>> p = BarycentricInterpolator(x, f(x)) >>> xx = np.linspace(-5, 5, num=1000) >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() >>> ax.plot(xx, f(xx), label="f(x)") >>> ax.plot(xx, r(xx), "--", label="Floater-Hormann") >>> ax.plot(xx, p(xx), "--", label="Polynomial") >>> ax.legend() >>> plt.show() dc*t||||y)Nr)rmr()rpointsvaluesrros r'r(z#FloaterHormannInterpolator.__init__s 1-r)ctj|}d|cxkrt|kstdtdt|||y)Nrz`d` must satisfy 0 <= d < n)rqrrlenr,rmr)rr r!rros r'rz,FloaterHormannInterpolator._input_validationsL NN1 QQ:; ; :; ; !!Q'r)ctj|tj|d}|j}t |D]}t t ||z dt |dz||z D]^}||xxdtjtjtj||||||zdzz ||z z z cc<`|dtj||z zz}|||fS)NryrHrr g) r rLrMr-rmaxrprodrrarange)rr#r$rwnkis r'rz+FloaterHormannInterpolator._compute_weightss MM!2>>!S#9 : FFq UA3qsA;AaC1 6 U!"''"&&1Q4!AA :J3JAPQE)R"STTT U U cRYYq\A% &&!Qwr))r`rarbrcr(rrrrs@r'rrWs_@-..( r)) rrqnumpyr rO__all__rrrrdr)r'rsL4  . /]]@P Pf t!5tr)