K ipdZddlZddlZddlZddlmZddlZddlm Z dgZ GddejZ y)a Abstract base class for the various polynomial Classes. The ABCPolyBase class provides the methods needed to implement the common API for the various polynomial classes. It operates as a mixin, but uses the abc module from the stdlib, hence it is only available for Python >= 2.6. N)Callable) polyutils ABCPolyBasec PeZdZdZdZdZdZejdddddd d d d d d Z ejddddddddddd Z e jdk( Z edZeej"dZeej"dZeej"dZeej"dZeej"dZeej"d Zeej"d!Zeej"dgd"Zeej"d#Zeej"d$Zeej"d%Zeej"d&Zeej"d'Zeej"d(Z eej"d)Z!d*Z"d+Z#d,Z$d-Z%d.Z&dhd0Z'd1Z(d2Z)d3Z*d4Z+e,d5Z-e,d6Z.e,d7Z/edid8Z0d9e1d:e2d;e2fd<Z3d=Z4d>Z5d?Z6d@Z7dAZ8dBZ9dCZ:dDZ;dEZdHZ?dIZ@dJZAdKZBdLZCdMZDdNZEdOZFdPZGdQZHdRZIdSZJdTZKdUZLdVZMdWZNdXZOdjdYZPdZZQdkd[ZRd\ZSd]gdfd^ZTdld_ZUd`ZVdmdaZWe, dndbZXe,gdd/fdcZYe,dhddZZe,dhdeZ[e,dodfZ\y)praAn abstract base class for immutable series classes. ABCPolyBase provides the standard Python numerical methods '+', '-', '*', '//', '%', 'divmod', '**', and '()' along with the methods listed below. Parameters ---------- coef : array_like Series coefficients in order of increasing degree, i.e., ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``, where ``P_i`` is the basis polynomials of degree ``i``. domain : (2,) array_like, optional Domain to use. The interval ``[domain[0], domain[1]]`` is mapped to the interval ``[window[0], window[1]]`` by shifting and scaling. The default value is the derived class domain. window : (2,) array_like, optional Window, see domain for its use. The default value is the derived class window. symbol : str, optional Symbol used to represent the independent variable in string representations of the polynomial expression, e.g. for printing. The symbol must be a valid Python identifier. Default value is 'x'. .. versionadded:: 1.24 Attributes ---------- coef : (N,) ndarray Series coefficients in order of increasing degree. domain : (2,) ndarray Domain that is mapped to window. window : (2,) ndarray Window that domain is mapped to. symbol : str Symbol representing the independent variable. Class Attributes ---------------- maxpower : int Maximum power allowed, i.e., the largest number ``n`` such that ``p(x)**n`` is allowed. This is to limit runaway polynomial size. domain : (2,) ndarray Default domain of the class. window : (2,) ndarray Default window of the class. Ndu⁰¹²³u⁴u⁵u⁶u⁷u⁸u⁹) 0123456789u₀u₁u₂u₃u₄u₅u₆u₇u₈u₉ntc|jSN)_symbolselfs `/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/numpy/polynomial/_polybase.pysymbolzABCPolyBase.symbolns ||cyrrs rdomainzABCPolyBase.domainr rcyrr rs rwindowzABCPolyBase.windowwr"rcyrr rs r basis_namezABCPolyBase.basis_name|r"rcyrr c1c2s r_addzABCPolyBase._addr"rcyrr r(s r_subzABCPolyBase._subr"rcyrr r(s r_mulzABCPolyBase._mulr"rcyrr r(s r_divzABCPolyBase._divr"rcyrr )cpowmaxpowers r_powzABCPolyBase._powr"rcyrr )xr3s r_valzABCPolyBase._valr"rcyrr )r3mklbndscls r_intzABCPolyBase._intr"rcyrr )r3r;r>s r_derzABCPolyBase._derr"rcyrr )r8ydegrcondfulls r_fitzABCPolyBase._fitr"rcyrr )offr>s r_linezABCPolyBase._liner"rcyrr )r3s r_rootszABCPolyBase._rootsr"rcyrr )rs r _fromrootszABCPolyBase._fromrootsr"rct|jt|jk(xr,tj|j|jk(S)a&Check if coefficients match. Parameters ---------- other : class instance The other class must have the ``coef`` attribute. Returns ------- bool : boolean True if the coefficients are the same, False otherwise. )lencoefnpallrothers r has_samecoefzABCPolyBase.has_samecoefs?  Nc%**o - 0tyyEJJ./ rcZtj|j|jk(S)aCheck if domains match. Parameters ---------- other : class instance The other class must have the ``domain`` attribute. Returns ------- bool : boolean True if the domains are the same, False otherwise. )rSrTr!rUs rhas_samedomainzABCPolyBase.has_samedomain vvdkkU\\122rcZtj|j|jk(S)aCheck if windows match. Parameters ---------- other : class instance The other class must have the ``window`` attribute. Returns ------- bool : boolean True if the windows are the same, False otherwise. )rSrTr$rUs rhas_samewindowzABCPolyBase.has_samewindowrZrc.t||jS)zCheck if types match. Parameters ---------- other : object Class instance. Returns ------- bool : boolean True if other is same class as self ) isinstance __class__rUs r has_sametypezABCPolyBase.has_sametypes%00rct|trt||js tdt j |j |j k(s tdt j |j|jk(s td|j|jk7r td|jS|S)apInterpret other as polynomial coefficients. The `other` argument is checked to see if it is of the same class as self with identical domain and window. If so, return its coefficients, otherwise return `other`. Parameters ---------- other : anything Object to be checked. Returns ------- coef The coefficients of`other` if it is a compatible instance, of ABCPolyBase, otherwise `other`. Raises ------ TypeError When `other` is an incompatible instance of ABCPolyBase. zPolynomial types differzDomains differzWindows differzPolynomial symbols differ) r^rr_ TypeErrorrSrTr!r$r ValueErrorrRrUs r_get_coefficientszABCPolyBase._get_coefficientss0 e[ )eT^^4 9::VVDKK5<<78 011VVDKK5<<78 011 , !<==::  rr8ctj|gd\}||_|:tj|gd\}t|dk7r t d||_|:tj|gd\}t|dk7r t d||_ |js t d ||_ y#t$r tdwxYw)NFtrimz$Domain has wrong number of elements.z$Window has wrong number of elements.z/Symbol string must be a valid Python identifierz!Symbol must be a non-empty string) pu as_seriesrRrQrcr!r$ isidentifierAttributeErrorrbr)rrRr!r$rs r__init__zABCPolyBase.__init__$stf51  ||VH59HV6{a !GHH DK  ||VH59HV6{a !GHH DK A&&( E)  A?@ @ As B??Cc t|jdd}t|jdd}t|jdd}|jj }|d|d|d|d|j d S)N(z , domain=z , window=z , symbol='z'))reprrRr!r$r___name__r)rrRr!r$names r__repr__zABCPolyBase.__repr__BsDIIq$dkk"1R(dkk"1R(~~&&&$y &B;;-r+ ,rc|dk(r|jS|dvrtd|d|jd|dk(r|j|jS|j|j S)N)asciiunicodezUnsupported format string 'z ' passed to z4.__format__. Valid options are 'ascii' and 'unicode'rx)__str__rcr__generate_string_str_term_ascii_str_term_unicode)rfmt_strs r __format__zABCPolyBase.__format__Js b=<<> ! . .-gYl>>"#()  g (()=)=> >$$T%;%;< q=Ioodiil+]]_ U&*&7&78;U'D# | -/#5M 12/ GAt 3JCAJE  (19 $rtD'I II $ruT'J JI UM: :I399T?2./#i.@H3tyy}%))A 9$%--c4; 9 C3 4  ( K  (s;E55FFc|j tdd|j|j|jd|dS)z String representation of single polynomial term using unicode characters for superscripts and subscripts. zZSubclasses must define either a basis_name, or override _str_term_unicode(cls, i, arg_str)·rqr)r&NotImplementedError translate_subscript_mappingclsrarg_strs rr}zABCPolyBase._str_term_unicodesU >> !%5 S^^$Q[[1G1G%H$IG9A rc\|j tdd|jd|d|dS)z String representation of a single polynomial term using ** and _ to represent superscripts and subscripts, respectively. zXSubclasses must define either a basis_name, or override _str_term_ascii(cls, i, arg_str)r_rqrr&rrs rr|zABCPolyBase._str_term_asciisB >> !%3 3>>"!A3ay22rc\|j tdd|jd|d|dS)NzbSubclasses must define either a basis name, or override _repr_latex_term(i, arg_str, needs_parens){z}_{z}(rr)rrrrs r_repr_latex_termzABCPolyBase._repr_latex_terms@ >> !%=> >CNN#53wiq99rc8dtj||dS)Nz\text{r})rir)r8rs r_repr_latex_scalarzABCPolyBase._repr_latex_scalars"//!F;DDDKK= $q11rc|jj}|jj|d<|jj|d<|jj|d<|j |d<|S)NrRr!r$r)__dict__copyrRr!r$r)rrets r __getstate__zABCPolyBase.__getstate__sfmm  "iinn&F  ((*H  ((*H  H  rc||_yr)r)rdicts r __setstate__zABCPolyBase.__setstate__s  rctj||j|j}|j ||j Sr)ri mapdomainr!r$r9rR)rargs r__call__zABCPolyBase.__call__s1ll3 T[[9yydii((rc,t|jSr)iterrRrs r__iter__zABCPolyBase.__iter__sDIIrc,t|jSr)rQrRrs r__len__zABCPolyBase.__len__s499~rc||j|j |j|j|jSrr_rRr!r$rrs r__neg__zABCPolyBase.__neg__ s.~~ YYJ T[[$++  rc|Srr rs r__pos__zABCPolyBase.__pos__s rc|j|} |j|j|}|j ||j |j|jS#t$r tcYSwxYwr) rdr+rR ExceptionNotImplementedr_r!r$rrrV othercoefrRs r__add__zABCPolyBase.__add__e**51  "99TYY 2D~~dDKKdkkJJ "! ! "A!!A32A3c|j|} |j|j|}|j ||j |j|jS#t$r tcYSwxYwr) rdr-rRrrr_r!r$rrs r__sub__zABCPolyBase.__sub__rrc|j|} |j|j|}|j ||j |j|jS#t$r tcYSwxYwr) rdr/rRrrr_r!r$rrs r__mul__zABCPolyBase.__mul__"rrct|tjrt|tr$t dt |dt |d|j |S)Nz&unsupported types for true division: 'z', '')r^rNumberboolrbtype __floordiv__rUs r __truediv__zABCPolyBase.__truediv__*sZ%0Jud4KJ>> np.polynomial.set_default_printstyle("unicode") >>> poly = np.polynomial.Polynomial([1, 7, 4]) >>> print(poly) 1.0 + 7.0·x + 4.0·x² >>> poly.degree() 2 Note that this method does not check for non-zero coefficients. You must trim the polynomial to remove any trailing zeroes: >>> poly = np.polynomial.Polynomial([1, 7, 0]) >>> print(poly) 1.0 + 7.0·x + 0.0·x² >>> poly.degree() 2 >>> poly.trim().degree() 1 r)rQrs rdegreezABCPolyBase.degrees@4y1}rc*|j|dzS)aTruncate series to the given degree. Reduce the degree of the series to `deg` by discarding the high order terms. If `deg` is greater than the current degree a copy of the current series is returned. This can be useful in least squares where the coefficients of the high degree terms may be very small. Parameters ---------- deg : non-negative int The series is reduced to degree `deg` by discarding the high order terms. The value of `deg` must be a non-negative integer. Returns ------- new_series : series New instance of series with reduced degree. r)truncate)rrDs rcutdegzABCPolyBase.cutdegs*}}S1W%%rctj|j|}|j||j|j |j S)aRemove trailing coefficients Remove trailing coefficients until a coefficient is reached whose absolute value greater than `tol` or the beginning of the series is reached. If all the coefficients would be removed the series is set to ``[0]``. A new series instance is returned with the new coefficients. The current instance remains unchanged. Parameters ---------- tol : non-negative number. All trailing coefficients less than `tol` will be removed. Returns ------- new_series : series New instance of series with trimmed coefficients. )ritrimcoefrRr_r!r$r)rtolrRs rrgzABCPolyBase.trims9({{499c*~~dDKKdkkJJrct|}||k7s|dkr td|t|jk\r |j}n|jd|}|j ||j |j |jS)aTruncate series to length `size`. Reduce the series to length `size` by discarding the high degree terms. The value of `size` must be a positive integer. This can be useful in least squares where the coefficients of the high degree terms may be very small. Parameters ---------- size : positive int The series is reduced to length `size` by discarding the high degree terms. The value of `size` must be a positive integer. Returns ------- new_series : series New instance of series with truncated coefficients. rzsize must be a positive integerN)intrcrQrRr_r!r$r)rsizeisizerRs rrzABCPolyBase.truncatesp(D  D=EAI>? ? C N "99D99Ve$D~~dDKKdkkJJrc| |j}| |j}| |j}||j|||jS)aConvert series to a different kind and/or domain and/or window. Parameters ---------- domain : array_like, optional The domain of the converted series. If the value is None, the default domain of `kind` is used. kind : class, optional The polynomial series type class to which the current instance should be converted. If kind is None, then the class of the current instance is used. window : array_like, optional The window of the converted series. If the value is None, the default window of `kind` is used. Returns ------- new_series : series The returned class can be of different type than the current instance and/or have a different domain and/or different window. Notes ----- Conversion between domains and class types can result in numerically ill defined series. )r$r)r_r!r$identityr)rr!kindr$s rconvertzABCPolyBase.convert sL: <>>D >[[F >[[FDMM& MLMMrcVtj|j|jS)aReturn the mapping parameters. The returned values define a linear map ``off + scl*x`` that is applied to the input arguments before the series is evaluated. The map depends on the ``domain`` and ``window``; if the current ``domain`` is equal to the ``window`` the resulting map is the identity. If the coefficients of the series instance are to be used by themselves outside this class, then the linear function must be substituted for the ``x`` in the standard representation of the base polynomials. Returns ------- off, scl : float or complex The mapping function is defined by ``off + scl*x``. Notes ----- If the current domain is the interval ``[l1, r1]`` and the window is ``[l2, r2]``, then the linear mapping function ``L`` is defined by the equations:: L(l1) = l2 L(r1) = r2 )rirr!r$rs rrzABCPolyBase.mapparms0s6{{4;; 44rrc|j\}}|d}n|||zz}|j|j|||d|z }|j||j|j |j S)aIntegrate. Return a series instance that is the definite integral of the current series. Parameters ---------- m : non-negative int The number of integrations to perform. k : array_like Integration constants. The first constant is applied to the first integration, the second to the second, and so on. The list of values must less than or equal to `m` in length and any missing values are set to zero. lbnd : Scalar The lower bound of the definite integral. Returns ------- new_series : series A new series representing the integral. The domain is the same as the domain of the integrated series. rg?)rr?rRr_r!r$r)rr;r<r=rIr>rRs rintegzABCPolyBase.integMsj2==?S <Dt#DyyAq$S9~~dDKKdkkJJrc|j\}}|j|j||}|j||j|j |j S)aDifferentiate. Return a series instance of that is the derivative of the current series. Parameters ---------- m : non-negative int Find the derivative of order `m`. Returns ------- new_series : series A new series representing the derivative. The domain is the same as the domain of the differentiated series. )rrArRr_r!r$r)rr;rIr>rRs rderivzABCPolyBase.derivnsJ$==?SyyAs+~~dDKKdkkJJrc|j|j}tj||j|j S)a/Return the roots of the series polynomial. Compute the roots for the series. Note that the accuracy of the roots decreases the further outside the `domain` they lie. Returns ------- roots : ndarray Array containing the roots of the series. )rLrRrirr$r!)rrootss rr'zABCPolyBase.rootss1 DII&||E4;; <0 >[[F KKq 6!9a 0 G!t rc |;tj|}|d|dk(rE|dxxdzcc<|dxxdz cc<n*t|trt |dk(r |j }| |j }tj|||} |j| |||||} |r| \} } || ||| | fS| } || ||| S)a Least squares fit to data. Return a series instance that is the least squares fit to the data `y` sampled at `x`. The domain of the returned instance can be specified and this will often result in a superior fit with less chance of ill conditioning. Parameters ---------- x : array_like, shape (M,) x-coordinates of the M sample points ``(x[i], y[i])``. y : array_like, shape (M,) y-coordinates of the M sample points ``(x[i], y[i])``. deg : int or 1-D array_like Degree(s) of the fitting polynomials. If `deg` is a single integer all terms up to and including the `deg`'th term are included in the fit. For NumPy versions >= 1.11.0 a list of integers specifying the degrees of the terms to include may be used instead. domain : {None, [beg, end], []}, optional Domain to use for the returned series. If ``None``, then a minimal domain that covers the points `x` is chosen. If ``[]`` the class domain is used. The default value was the class domain in NumPy 1.4 and ``None`` in later versions. The ``[]`` option was added in numpy 1.5.0. rcond : float, optional Relative condition number of the fit. Singular values smaller than this relative to the largest singular value will be ignored. The default value is ``len(x)*eps``, where eps is the relative precision of the float type, about 2e-16 in most cases. full : bool, optional Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned. w : array_like, shape (M,), optional Weights. If not None, the weight ``w[i]`` applies to the unsquared residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are chosen so that the errors of the products ``w[i]*y[i]`` all have the same variance. When using inverse-variance weighting, use ``w[i] = 1/sigma(y[i])``. The default value is None. window : {[beg, end]}, optional Window to use for the returned series. The default value is the default class domain symbol : str, optional Symbol representing the independent variable. Default is 'x'. Returns ------- new_series : series A series that represents the least squares fit to the data and has the domain and window specified in the call. If the coefficients for the unscaled and unshifted basis polynomials are of interest, do ``new_series.convert().coef``. [resid, rank, sv, rcond] : list These values are only returned if ``full == True`` - resid -- sum of squared residuals of the least squares fit - rank -- the numerical rank of the scaled Vandermonde matrix - sv -- singular values of the scaled Vandermonde matrix - rcond -- value of `rcond`. For more details, see `linalg.lstsq`. rr)wrErFr!r$r) ri getdomainr^listrQr!r$rrG)rr8rCrDr!rErFr,r$rxnewrrRstatuss rfitzABCPolyBase.fitsJ >\\!_FayF1I%q Q q Q  %#f+*:ZZF >ZZF||Avv.hhtQqDhA  NT6DvF DtF6&I Ircttj|gd\}|tj|}n*t|trt |dk(r |j }| |j}t |}tj||\}}|||zz}|j|||zz } || |||S)aReturn series instance that has the specified roots. Returns a series representing the product ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a list of roots. Parameters ---------- roots : array_like List of roots. domain : {[], None, array_like}, optional Domain for the resulting series. If None the domain is the interval from the smallest root to the largest. If [] the domain is the class domain. The default is []. window : {None, array_like}, optional Window for the returned series. If None the class window is used. The default is None. symbol : str, optional Symbol representing the independent variable. Default is 'x'. Returns ------- new_series : series Series with the specified roots. Frfrr-) rirjr.r^r/rQr!r$rrO) rr'r!r$rrDrIr>rnewrRs r fromrootszABCPolyBase.fromroots s8,,wU3 >\\%(F  %#f+*:ZZF >ZZF%j;;vv.SS5[ ~~d#c3h.4vfEErc| |j}| |j}tj||\}}|j ||}|||||S)aIdentity function. If ``p`` is the returned series, then ``p(x) == x`` for all values of x. Parameters ---------- domain : {None, array_like}, optional If given, the array must be of the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the domain. If None is given then the class domain is used. The default is None. window : {None, array_like}, optional If given, the resulting array must be if the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the window. If None is given then the class window is used. The default is None. symbol : str, optional Symbol representing the independent variable. Default is 'x'. Returns ------- new_series : series Series of representing the identity. )r!r$rirrJ)rr!r$rrIr>rRs rrzABCPolyBase.identity7sU6 >ZZF >ZZF;;vv.Syyc"400rc| |j}| |j}t|}||k7s|dkr td|dg|zdgz|||S)a;Series basis polynomial of degree `deg`. Returns the series representing the basis polynomial of degree `deg`. Parameters ---------- deg : int Degree of the basis polynomial for the series. Must be >= 0. domain : {None, array_like}, optional If given, the array must be of the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the domain. If None is given then the class domain is used. The default is None. window : {None, array_like}, optional If given, the resulting array must be if the form ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of the window. If None is given then the class window is used. The default is None. symbol : str, optional Symbol representing the independent variable. Default is 'x'. Returns ------- new_series : series A series with the coefficient of the `deg` term set to one and all others zero. rz deg must be non-negative integerr)r!r$rrc)rrDr!r$ridegs rbasiszABCPolyBase.basisZs`: >ZZF >ZZF3x 3;$(?@ @A3:#VVV<ZZF >ZZF~~fc622rr)NNr8)F)r)NNN)r)rN)NNFNNr8)NN)]rs __module__ __qualname____doc____hash____array_ufunc__r5r maketrans_superscript_mappingrosrtrpropertyrabcabstractmethodr!r$r& staticmethodr+r-r/r1r6r9r?rArGrJrLrOrWrYr\r`rdrmrurrzr{ classmethodr}r|rrrfloatrrrrrrrrrrrrrrrrrrrrrrr rr rrrrrgrr rr#r%r'r)r2r5rr9r<r rrrrs/dHOH==           *            (  ww$&L                                &3 3 1 "H<, =; ,\     3 3::@@ "(""u"&&2T )  KKK (   KKK   & P D&.K.K:#NJ5:2DKBK, =<CGXJXJt%'S(F(FT 1 1D$=$=L%3%3r)r?rFrrDcollections.abcrnumpyrSrwrri__all__ABCrr rrrOs7  $ /S3#''S3r