
    >hmR                         S r SSKrSSKJr  SSKJr  SSKJ	r	  SSK
Jr  SSKrSr\R                  " \\5        SS jrS rS	 rSS
 jrSS jrSS jr " S S5      r " S S\5      rg)a  
Bspines and smoothing splines.

General references:

    Craven, P. and Wahba, G. (1978) "Smoothing noisy data with spline functions.
    Estimating the correct degree of smoothing by
    the method of generalized cross-validation."
    Numerische Mathematik, 31(4), 377-403.

    Hastie, Tibshirani and Friedman (2001). "The Elements of Statistical
    Learning." Springer-Verlag. 536 pages.

    Hutchison, M. and Hoog, F. "Smoothing noisy data with spline functions."
    Numerische Mathematik, 47(1), 99-106.
    N)solveh_bandedgolden)	_hbsplinez
The bspline code is technology preview and requires significant work
on the public API and documentation. The API will likely change in the future
c                    U R                   S   nU R                   S   nSnU(       d  [        U5       H{  n[        R                  " XS-
  U-
     US9XtU-   2XtU-   24   nXh-  nU(       a  US:  a  XhR                  -  nMN  U(       d  MW  US:  d  M_  XhR                  5       R                  -  nM}     U$ [        U5       Hq  n[        R                  " X   US9SU2SU24   nXh-  nU(       a  US:  a  XhR                  -  nMD  U(       d  MM  US:  d  MU  XhR                  5       R                  -  nMs     UR                  nU$ )a  
Take an upper or lower triangular banded matrix and return a
numpy array.

INPUTS:
   a         -- a matrix in upper or lower triangular banded matrix
   lower     -- is the matrix upper or lower triangular?
   symmetric -- if True, return the original result plus its transpose
   hermitian -- if True (and symmetric False), return the original
                result plus its conjugate transposed
   r   )k)shaperangenpdiagT	conjugate)	alower	symmetric	hermitiannr_aj_bs	            nC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\statsmodels/sandbox/bspline.py_band2arrayr   "   s!    	

A	
A	
BqAQ3q5A&qA#wqA#w7BHBQUdd
q1ulln&&& " I qA"1Q3qs7+BHBQUdd
q1ulln&&&  TTI    c                    [         R                  " U R                  U R                  5      nU R                  u  p#[	        U R                  S   5       H.  nXS-
  U-
  XC24   XSX4-
  24'   XS-
  U-
  SU24   XX4-
  S24'   M0     U$ )z
Convert upper triangular banded matrix to lower banded form.

INPUTS:
   ub  -- an upper triangular banded matrix

OUTPUTS: lb
   lb  -- a lower triangular banded matrix with same entries
          as ub
r   r   Nr   zerosr
   dtyper   )ublbnrowncolis        r   _upper2lowerr%   H   s     
"((BHH	%BJD288A;1fQhqvo.QZ<!VAXac\*dfY;   Ir   c                    [         R                  " U R                  U R                  5      nU R                  u  p#[	        U R                  S   5       H.  nXSX4-
  24   XS-
  U-
  XC24'   XX4-
  S24   XS-
  U-
  SU24'   M0     U$ )z
Convert lower triangular banded matrix to upper banded form.

INPUTS:
   lb  -- a lower triangular banded matrix

OUTPUTS: ub
   ub  -- an upper triangular banded matrix with same entries
          as lb
r   r   Nr   )r!   r    r"   r#   r$   s        r   _lower2upperr'   [   s     
"((BHH	%BJD288A; 1df:.6!8AF?	k?6!8AaC<   Ir   c                     U(       a  U S   R                  5       nOU S   R                  5       nU(       a  X U-  4$ [        U 5      nU[        X2-  5      4$ )a  
Take a banded triangular matrix and return its diagonal and the
unit matrix: the banded triangular matrix with 1's on the diagonal,
i.e. each row is divided by the corresponding entry on the diagonal.

INPUTS:
   tb    -- a lower triangular banded matrix
   lower -- if True, then tb is assumed to be lower triangular banded,
            in which case return value is also lower triangular banded.

OUTPUTS: d, b
   d     -- diagonal entries of tb
   b     -- unit matrix: if lower is False, b is upper triangular
            banded and its rows of have been divided by d,
            else lower is True, b is lower triangular banded
            and its columns have been divieed by d.
r   )copyr%   r'   )tbr   dlnums       r   _triangle2unitr.   n   sP    & qEJJLrFKKM6{B,tx(((r   c                     U(       a6  [        X-  SS9nUS   R                  5       SUSS R                  5       -  -   $ [        X-  SS9nUS   R                  5       SUSS R                  5       -  -   $ )a/  
Compute the trace(ab) for two upper or banded real symmetric matrices
stored either in either upper or lower form.

INPUTS:
   a, b    -- two banded real symmetric matrices (either lower or upper)
   lower   -- if True, a and b are assumed to be the lower half


OUTPUTS: trace
   trace   -- trace(ab)
r   r   r      Nr)   )_zero_tribandsum)r   br   ts       r   _trace_symbandedr6      sn     !%q)txxzA!"		O++!%q)uyy{Q3B---r   c                     U R                   u  p#U(       a  [        U5       H  nSXX4-
  S24'   M     U $ [        U5       H  nSXSU24'   M     U $ )z
Explicitly zero out unused elements of a real symmetric banded matrix.

INPUTS:
   a   -- a real symmetric banded matrix (either upper or lower hald)
   lower   -- if True, a is assumed to be the lower half
        Nr   )r
   r   )r   r   r"   r#   r$   s        r   r2   r2      sZ     JDtA A$&lO 
 H tAA1fI Hr   c                   d    \ rS rSrSrSS jrS rS r\" \\5      r	S r
SS jrSS	 jrSS
 jrSrg)BSpline   aE  

Bsplines of a given order and specified knots.

Implementation is based on description in Chapter 5 of

Hastie, Tibshirani and Friedman (2001). "The Elements of Statistical
Learning." Springer-Verlag. 536 pages.


INPUTS:
   knots  -- a sorted array of knots with knots[0] the lower boundary,
             knots[1] the upper boundary and knots[1:-1] the internal
             knots.
   order  -- order of the Bspline, default is 4 which yields cubic
             splines
   M      -- number of additional boundary knots, if None it defaults
             to order
   coef   -- an optional array of real-valued coefficients for the Bspline
             of shape (knots.shape + 2 * (M - 1) - order,).
   x      -- an optional set of x values at which to evaluate the
             Bspline to avoid extra evaluation in the __call__ method

Nc                 0   [         R                  " [         R                  " [         R                  " U5      5      5      nUR                  S:w  a  [        S5      eX l        Uc  U R                  nX0l        [         R                  " US   /U R                  S-
  -  XS   /U R                  S-
  -  /5      U l	        UR                  S   S-
  U l        UcR  [         R                  " U R                  SU R                  -  -   U R                  -
  [         R                  5      U l        Og[         R                  " U5      U l        U R                  R                  U R                  SU R                  -  -   U R                  -
  :w  a  [        S5      eUb  XPl        g g )Nr   zexpecting 1d array for knotsr   r)   r1   z,coefficients of Bspline have incorrect shape)r   squeezeuniqueasarrayndim
ValueErrormMhstacktaur
   Kr   float64coefx)selfknotsorderrC   rH   rI   s         r   __init__BSpline.__init__   s+   

299RZZ%678::?;<<9A99uQxj$&&(3U2YKPQ<RSTQ!#<$&&1tvv:"5">LDI

4(DIyy466AJ#6#?@ !OPP=F r   c                 P    Xl         U R                  U R                   5      U l        g N)_xbasis_basisx)rJ   rI   s     r   _setxBSpline._setx   s    zz$''*r   c                     U R                   $ rP   )rQ   rJ   s    r   _getxBSpline._getx   s    wwr   c                    U(       d  U R                   R                  nO4US   n[        R                  " U R	                  U5      5      R                  n[        R
                  " [        R                  " X R                  5      5      $ )a  
Evaluate the BSpline at a given point, yielding
a matrix B and return

B * self.coef


INPUTS:
   args -- optional arguments. If None, it returns self._basisx,
           the BSpline evaluated at the x values passed in __init__.
           Otherwise, return the BSpline evaluated at the
           first argument args[0].

OUTPUTS: y
   y    -- value of Bspline at specified x values

BUGS:
   If self has no attribute x, an exception will be raised
   because self has no attribute _basisx.
r   )rS   r   r   r?   rR   r=   dotrH   )rJ   argsr4   rI   s       r   __call__BSpline.__call__   sU    , AQA

4::a=)++Azz"&&II.//r   c           	         [         R                  " U[         R                  5      nUR                  nUS:X  a  SUl        [         R                  " USS94Ul        X R
                  R                  S   S-
  :  a1  [        R                  " XR
                  U R                  X2US-   5      nO/[         R                  " UR                  [         R                  5      $ X R
                  R                  S   U R                  -
  :X  a9  [         R                  " [         R                  " XR
                  S   5      SU5      nXEl        U$ )aQ  
Evaluate a particular basis element of the BSpline,
or its derivative.

INPUTS:
   x  -- x values at which to evaluate the basis element
   i  -- which element of the BSpline to return
   d  -- the order of derivative

OUTPUTS: y
   y  -- value of d-th derivative of the i-th basis element
         of the BSpline at specified x values
 r   r   axisr   r)   )r   r?   rG   r
   productrE   r   evaluaterB   r   whereequal)rJ   rI   r$   r,   _shapevs         r   basis_elementBSpline.basis_element  s     JJq"**%R<AG::f!,.xx~~a 1$$""1hhacBA88AGGRZZ00"TVV++!XXb\2Aq9Ar   c                    [         R                  " U5      nUR                  nUS:X  a  SUl        [         R                  " USS94Ul        Uc&  U R                  R                  S   U R
                  -
  nUc  Sn[        X@R                  R                  S   U R
                  -
  5      n[        SU5      n[         R                  " U5      nUR                  S:X  a7  [        R                  " XR                  U R
                  [        U5      X45      nO{UR                  S   S:w  a  [        S5      eSn[        UR                  S   5       H?  nXbSU4   [        R                  " XR                  U R
                  USU4   X45      -  -  nMA     XC-
  4U-   Ul        X@R                  R                  S   U R
                  -
  :X  a?  [         R                  " [         R                  " XR                  S   5      SUS   5      US'   U$ )	a8  
Evaluate the basis of the BSpline or its derivative.
If lower or upper is specified, then only
the [lower:upper] elements of the basis are returned.

INPUTS:
   x     -- x values at which to evaluate the basis element
   i     -- which element of the BSpline to return
   d     -- the order of derivative
   lower -- optional lower limit of the set of basis
            elements
   upper -- optional upper limit of the set of basis
            elements

OUTPUTS: y
   y  -- value of d-th derivative of the basis elements
         of the BSpline at specified x values
r`   ra   r   rb   r1   if d is not an integer, expecting a jx2                    array with first row indicating order                    of derivative, second row coefficient in front.r   r)   )r   r?   r
   rd   rE   rB   minmaxr   re   intrA   r   rf   rg   )rJ   rI   r,   r   upperrh   ri   r$   s           r   rR   BSpline.basis2  s   & JJqMR<AG::f!,.=HHNN1%.E=EE88>>!,tvv56AuJJqM77b=""1hhAMAwwqzQ  "D E E A1771:&qsVi00HHdffa!fe[[[ ' ;.6)HHNN1%..HHRXXa"61R5AAbEr   c                 z   [         R                  " U5      n[         R                  " U5      R                  S:X  aE  [        R
                  " U R                  U R                  [        U5      [        U5      5      U l	        O[         R                  " U5      nUR                  S   S:w  a  [        S5      eUR                  S:X  a  SUl        SU l	        [        UR                  S   5       H  n[        UR                  S   5       Ho  nU =R                  USU4   USU4   -  [        R
                  " U R                  U R                  [        USU4   5      [        USU4   5      5      -  -  sl	        Mq     M     U R                  R                  U l	        Xl        [         R                  " U R                  5      $ )a  
Compute Gram inner product matrix, storing it in lower
triangular banded form.

The (i,j) entry is

G_ij = integral b_i^(d) b_j^(d)

where b_i are the basis elements of the BSpline and (d) is the
d-th derivative.

If d is a matrix then, it is assumed to specify a differential
operator as follows: the first row represents the order of derivative
with the second row the coefficient corresponding to that order.

For instance:

[[2, 3],
 [3, 1]]

represents 3 * f^(2) + 1 * f^(3).

INPUTS:
   d    -- which derivative to apply to each basis element,
           if d is a matrix, it is assumed to specify
           a differential operator as above

OUTPUTS: gram
   gram -- the matrix of inner products of (derivatives)
           of the BSpline elements
r`   r   r1   rm   )r1   )r1   r   r   )r   r=   r?   r
   r   gramrE   rB   rp   grA   r   r   r,   
nan_to_num)rJ   r,   r$   r   s       r   rt   BSpline.gramc  sU   B JJqM::a="$^^DHHdffc!fc!fEDF

1AwwqzQ  "D E E ww$DF1771:&qwwqz*AFFa!fa!fny~~dhhPSTUVWXYVYTZP[]`abcdefcfag]h/iiiF + ' }}TVV$$r   )
rF   rC   rS   rQ   rH   r,   ru   rB   rE   rI   )   NNNr   )r   NN)__name__
__module____qualname____firstlineno____doc__rM   rT   rX   propertyrI   r]   rj   rR   rt   __static_attributes__r`   r   r   r:   r:      s9    :0+ 	A0:>/b2%r   r:   c                   r    \ rS rSrSrSrSrSrSr SS jr	SS	 jr
S
 rS rS rS r  SS jr  SS jrSrg)SmoothingSplinei  g      >@	target_df   MbP?TNc           	         SnUc'  U R                   nU R                  R                  5       nOU R                  U5      nUS:X  a  SnUR                  UR                  :w  a  [        S5      eX@R                  :  a  U R                  nUb  X0l        OSU l        [        R                  " U R                  5      nXg-  n[        R                  " S[        R                  " [        R                  " US5      SS	9-
  5      nUSS2U4   nX   nUR                  S   U l        [        R                  " [        R                  " XgU-  5      5      n	UR                  S   U l        U(       d  [        R                  " XfR"                  5      U l        ['        U R(                  SSS
9n
[*        R,                  " U R$                  XJ-  -   U	5      SS u  U l        ol        [3        U R0                  U R$                  R                  S   5      U l        A
O[        R4                  " U R(                  R                  [        R6                  5      U l        U R(                  R                  u  p[9        U5       HI  n[9        [3        XU-
  5      5       H+  nXn   XnU-      -  R;                  5       U R$                  X4'   M-     MK     SU	R                  S   4U	l        X@l        [?        U R$                  X@R(                  -  -   U	SS9u  U l         U l        [        R                  " U R.                  5      U l        XR                  -  [        R                  " U R.                  U5      -
  U l!        X@l        A	AAg)a  
Fit the smoothing spline to a set of (x,y) pairs.

INPUTS:
   y       -- response variable
   x       -- if None, uses self.x
   weights -- optional array of weights
   pen     -- constant in front of Gram matrix

OUTPUTS: None
   The smoothing spline is determined by self.coef,
   subsequent calls of __call__ will be the smoothing spline.

ALGORITHM:
   Formally, this solves a minimization:

   fhat = ARGMIN_f SUM_i=1^n (y_i-f(x_i))^2 + pen * int f^(2)^2

   int is integral. pen is lambda (from Hastie)

   See Chapter 5 of

   Hastie, Tibshirani and Friedman (2001). "The Elements of Statistical
   Learning." Springer-Verlag. 536 pages.

   for more details.

TODO:
   Should add arbitrary derivative penalty instead of just
   second derivative.
TNr8   FzXx and y shape do not agree, by default x are                the Bspline's internal knotsg      ?r   r   rb   )r   r      r0   )"rQ   rS   r*   rR   r
   rA   penmaxweightsr   sqrtflatnonzeroallrg   df_totalr=   r[   Nr   btbr   ru   LlstsqrH   rankrn   r   rG   r   r3   penr   cholresid)rJ   yrI   r   r   bandedbt_wmaskbty_g_nbandnbasisr$   r	   s                   r   fitSmoothingSpline.fit  s   B 9A""$BAB"9F77agg . / / ++++C "LDLWWT\\"
 ~~a"&&"aq"AAB$ZG
jjF+,vvb$$'DHTVV1=B&'ggdhh.?&Ea&J#DIq)DIItxx~~a'89DIxxbjj9DH FFLLME6]s5(34A%'UR!W_$9$9$;DHHQSM 5 # 399Q<(CIH#014VV2<14A$? DIty JJtyy)	%tyy"(==
r   c                     U R                   S:X  aG  [        U S5      (       a  U R                  XX0R                  S9  g U R	                  XX0R
                  S9  g U R                   S:X  a  U R                  XUS9  g g )Nr   r   rI   r   r   )rI   r   dfoptimize_gcv)rI   r   )methodhasattrr   r   fit_target_dfr   fit_optimize_gcv)rJ   r   rI   r   s       r   smoothSmoothingSpline.smooth
  sj    ;;+%tU##hh?""17~~"N[[N*!!!'!: +r   c                 z    U R                   S-  R                  5       nXR                  U R                  5       -
  -  $ )z
Generalized cross-validation score of current fit.

Craven, P. and Wahba, G.  "Smoothing noisy data with spline functions.
Estimating the correct degree of smoothing by
the method of generalized cross-validation."
Numerische Mathematik, 31(4), 377-403.
r1   )r   r3   r   trace)rJ   
norm_resids     r   gcvSmoothingSpline.gcv  s2     jj!m((*
]]TZZ\9::r   c                 <    U R                   U R                  5       -
  $ )zy
Residual degrees of freedom in the fit.

self.N - self.trace()

where self.N is the number of observations of last fit.
)r   r   rW   s    r   df_residSmoothingSpline.df_resid"  s     vv

$$r   c                 "    U R                  5       $ )z<
How many degrees of freedom used in the fit?

self.trace()
)r   rW   s    r   df_fitSmoothingSpline.df_fit-  s     zz|r   c                     U R                   S:  aD  [        R                  " U R                  R	                  5       5      n[        XR                  SS9nU$ U R                  $ )zb
Trace of the smoothing matrix S(pen)

TODO: addin a reference to Wahba, and whoever else I used.
r   r   r0   )r   r   invbandr   r*   r6   r   r   )rJ   _invbandtrs      r   r   SmoothingSpline.trace5  sI     88a< (()9:H!(HHA>BI99r   c                 X   U=(       d    U R                   nUR                  S   U R                  -
  n[        U S5      (       aw  U R	                  XX@R
                  S9  U R                  5       n	[        R                  " X-
  5      U-  U:  a  gX:  a  U R
                  SU R
                  -  pvOSU R
                  pv SXg-   -  n
U R	                  XXJS9  U R                  5       n	X:  a  U
SU
-  pvOXjpvX`R                  :  a  [        S5      e[        R                  " X-
  5      U-  U:  a  gMq  )	a  
Fit smoothing spline with approximately df degrees of freedom
used in the fit, i.e. so that self.trace() is approximately df.

Uses binary search strategy.

In general, df must be greater than the dimension of the null space
of the Gram inner product. For cubic smoothing splines, this means
that df > 2.

INPUTS:
   y       -- response variable
   x       -- if None, uses self.x
   df      -- target degrees of freedom
   weights -- optional array of weights
   tol     -- (relative) tolerance for convergence
   apen    -- lower bound of penalty for binary search
   bpen    -- upper bound of penalty for binary search

OUTPUTS: None
   The smoothing spline is determined by self.coef,
   subsequent calls of __call__ will be the smoothing spline.
r   r   r   Nr1   r8   g      ?zPpenalty too large, try setting penmax                    higher or decreasing df)r   r
   rB   r   r   r   r   r   fabsr   rA   )rJ   r   rI   r   r   tolapenbpenolddfcurdfcurpens              r   r   SmoothingSpline.fit_target_dfC  s   4 !4>>
TVV#4HHQW((H;JJLEwwuz"R'#-z!XXq488|ddDK(FHHQWH9JJLEz#QZd!d{{"  ", - -wwuz"R'#- r   c                 *   ^  U 4S jn[        XaU4XTS9ng)ar  
Fit smoothing spline trying to optimize GCV.

Try to find a bracketing interval for scipy.optimize.golden
based on bracket.

It is probably best to use target_df instead, as it is
sometimes difficult to find a bracketing interval.

INPUTS:
   y       -- response variable
   x       -- if None, uses self.x
   df      -- target degrees of freedom
   weights -- optional array of weights
   tol     -- (relative) tolerance for convergence
   brack   -- an initial guess at the bracketing interval

OUTPUTS: None
   The smoothing spline is determined by self.coef,
   subsequent calls of __call__ will be the smoothing spline.
c                 p   > TR                  X[        R                  " U 5      S9  TR                  5       nU$ )N)rI   r   )r   r   expr   )r   r   rI   r   rJ   s       r   _gcv.SmoothingSpline.fit_optimize_gcv.<locals>._gcv  s+    HHQH-
AHr   )r\   brackr   Nr   )rJ   r   rI   r   r   r   r   r   s   `       r   r    SmoothingSpline.fit_optimize_gcvz  s    0	
 4e5:r   )	r   r   r   rH   r   r   r   r   r   )NNr8   )NN)NNNr   r   r   )NNr   )i   )rz   r{   r|   r}   r   r   r   default_penoptimizer   r   r   r   r   r   r   r   r   r`   r   r   r   r     s^    FFIKHaF;;	% CJ#*5n =D(;r   r   )r   FFry   )r~   numpyr   numpy.linalglinalgr   scipy.linalgr   scipy.optimizer   modelsr   warnings_msgwarnFutureWarningr   r%   r'   r.   r6   r2   r:   r   r`   r   r   <module>r      sq   "   & !   	dM "#L&&)>.,&_% _%B@;g @;r   