
    J/Ph                        g d Z ddlZddlmZmZmZmZmZ ddl	m
Z
 erddlZd Zd Zd Zd Zd	 Zd
 Zd Zd Zd Zd Zd Zd'dZd(dZd)dZ	 d*dZd Zd Z G d de          Z G d de          Z e
e          Z  G d de          Z! e
e!          Z"d Z#d Z$de$_%        d  Z& G d! d"e          Z' e
e'          Z(d# Z)d$ Z*d% Z+d& Z,dS )+)crccte    N)have_pandasatleast_2d_column_defaultno_picklingassert_no_picklingsafe_string_eq)stateful_transformc                    	 ddl m} n# t          $ r t          d          w xY w| dd         | dd         z
  }|dd         |dd         z   dz  }|dd         dz  }t          j        t          j        d	|f         |t          j        |d	f         g          }t          j        | j        d
z
  | j        f          }t          | j        d
z
            D ]I}d||         z  |||f<   d||dz            z  |||d
z   f<   |||f          |||d
z   f         z
  |||dz   f<   J|	                    d||          }t          j
        t          j        | j                  |t          j        | j                  g          S )a  Returns mapping of natural cubic spline values to 2nd derivatives.

    .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, pp 145-146

    :param knots: The 1-d array knots used for cubic spline parametrization,
     must be sorted in ascending order.
    :return: A 2-d array mapping natural cubic spline values at
     knots to second derivatives.

    :raise ImportError: if scipy is not found, required for
     ``linalg.solve_banded()``
    r   linalg*Cubic spline functionality requires scipy.   N      @      @                 ?)r   r   )scipyr   ImportErrornparrayr_zerossizerangesolve_bandedvstack)	knotsr   hdiagul_diagbanded_bdifms	            X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/patsy/mgcv_cubic_splines.py_get_natural_fr*      s   H        H H HFGGGH 	abb	E#2#JAcrcFQqrrUNc!D"gmGxsG|,dBE'3,4GHIIH
%*q.%*-..A5:>"" - -!*!Q$Aa!eHn!QU(Awh1a!e8,!QU(			VXq	1	1B9bhuz**B0D0DEFFF   	 #c                     ||k    rt          d|d|d          t          j        |           } || | |k             |z
  ||z
  z  z   | | |k    <   ||| | |k              z
  ||z
  z  z
  | | |k     <   | S )aH  Maps values into the interval [lbound, ubound] in a cyclic fashion.

    :param x: The 1-d array values to be mapped.
    :param lbound: The lower bound of the interval.
    :param ubound: The upper bound of the interval.
    :return: A new 1-d array containing mapped x values.

    :raise ValueError: if lbound >= ubound.
    zInvalid argument: lbound (z) should be less than ubound ().)
ValueErrorr   copy)xlboundubounds      r)   _map_cyclicr3   =   s     j(.8
 
 	

 	

AaF
mf4&IIAa&jMfqV}4&IIAa&jMH    c                     t          j        g d          } t          j        |           }t          j        g d          }t          | dd          }t          j        | |          sJ t          j        ||          sJ d S )N)g      ?@g?g@gffffff%@)r   r6   g@g333333@g	@g @@)r   r   r/   r3   allclose)r0   x_origexpected_mapped_xmapped_xs       r)   test__map_cyclicr<   T   s    
+++,,AWQZZF!:!:!:;;1c3''H;q&!!!!!;x!23333333r4   c                      dd l } t          j        ddd          }|                     t          t
          |dd           |                     t          t
          |dd           d S )Nr   g?g@
   g      @r7   )pytestr   linspaceraisesr.   r3   r?   r0   s     r)   test__map_cyclic_errorsrC   ]   sX    MMM
Cb!!A
MM*k1c3777
MM*k1c377777r4   c                 B   | dd         | dd         z
  }| j         dz
  }t          j        ||f          }t          j        ||f          }||dz
           |d         z   dz  |d<   ||dz
           dz  |d|dz
  f<   ||dz
           dz  ||dz
  df<   d|d         z  d	||dz
           z  z
  |d<   d	||dz
           z  |d|dz
  f<   d	||dz
           z  ||dz
  df<   t          d|          D ]}||dz
           ||         z   dz  |||f<   ||dz
           dz  |||dz
  f<   ||dz
           dz  ||dz
  |f<   d||dz
           z  d	||         z  z
  |||f<   d	||dz
           z  |||dz
  f<   d	||dz
           z  ||dz
  |f<   t          j                            ||          S )
ao  Returns mapping of cyclic cubic spline values to 2nd derivatives.

    .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, pp 146-147

    :param knots: The 1-d array knots used for cubic spline parametrization,
     must be sorted in ascending order.
    :return: A 2-d array mapping cyclic cubic spline values at
     knots to second derivatives.
    r   Nr   r   r   )r   r   r   g      r   )r   r   r   r   r   solve)r!   r"   nbr&   r'   s         r)   _get_cyclic_frH   e   s    	abb	E#2#JA
QA
!QA
!QAQx!A$#%AdGAE(S.AaQhKAE(S.Aa!eQhKQqTkC!AE(N*AdG!a%.AaQhK!a%.Aa!eQhK1a[[ % %QU8ad?c)!Q$Ahn!QU(Ahn!a%(1q5/C!A$J.!Q$Aa!eHn!QU(Aa!eHn!a%(9??1a   r4   c                    t          |           dk    rt          d          | D ]}|j        dk    rt          d          | d         j        d         }d}| D ]2}|j        d         |k    rt          d          ||j        d         z  }3t	          j        ||f          }| d         |dd| d         j        d          df<   | d         j        d         }| d	dd         D ]{}| |j        d         z  }t          |j        d                   D ]=}|dd|f         }t          | d          D ]}	|dd|	f         |z  |dd|f<   |dz  }>||j        d         z  }||S )
a8  Computes row-wise tensor product of given arguments.

    .. note:: Custom algorithm to precisely match what is done in 'mgcv',
    in particular look out for order of result columns!
    For reference implementation see 'mgcv' source code,
    file 'mat.c', mgcv_tensor_mm(), l.62

    :param dms: A sequence of 2-d arrays (marginal design matrices).
    :return: The 2-d array row-wise tensor product of given arguments.

    :raise ValueError: if argument sequence is empty, does not contain only
     2-d arrays or if the arrays number of rows does not match.
    r   z3Tensor product arrays sequence should not be empty.r   z.Tensor product arguments should be 2-d arrays.r   z9Tensor product arguments should have same number of rows.r   N)lenr.   ndimshaper   r   r   )
dmsdmtp_nrowstp_ncolstpfilled_tp_ncolspjxjts
             r)   _row_tensor_productrX      s    3xx1}}NOOO O O7a<<MNNN  1v|AHH    8A;(""N   	BHQK	8X&	'	'B!$RBqqq3r7=


"gmA&O"&b&k ' 'rx{*rx{## 	 	AAAAqDBO+Q//  aaad8b=111a4Q 	28A;&Ir4   c            	      *   dd l } |                     t          t          g            |                     t          t          t	          j        dd          g           |                     t          t          t	          j        dd          t	          j        dd          g           |                     t          t          t	          j        dd                              d          t	          j        dd                              d          g           d S )Nr   r         )      )r]   r\   )r?   rA   r.   rX   r   arangereshaper?   s    r)   test__row_tensor_product_errorsra      s    MMM
MM*12666
MM*1BIaOO3DEEE
MM*1BIaOORYqRS__3UVVV
MM	1b			!	!&	)	)29Q+;+;+C+CF+K+KL    r4   c                     t          j        dd                              d          } t          j        t	          | g          |           sJ t          j        d                              d          }t	          || g          }t          j        ||           sJ t	          | |g          }t          j        ||           sJ d|z  }t	          || g          }t          j        |d| z            sJ t	          | |g          }t          j        |d| z            sJ t          j        ddgddgg          }t          j        dd                              d          }t          j        g d	g d
g          }	t	          ||g          }
t          j        |
|	          sJ t          j        g dg dg          }t	          ||g          }t          j        ||          sJ d S )Nr      r]   r]   r]   )r]   r   r      )r   r\   )r   r   r\   r   r]      )r]   rZ   rf      r>      )r   r   r   r]   r\   rf   )r]   rg   rZ   r>   rf   rh   )r   r^   r_   array_equalrX   onesr   )dm1rj   tp1tp2twostp3tp4dm2dm3expected_tp5tp5expected_tp6tp6s                r)   test__row_tensor_productrw      s   
)Ar


"
"6
*
*C>-se44c:::::71::f%%D
tSk
*
*C>#s#####
sDk
*
*C>#s##### t8D
tSk
*
*C>#q3w'''''
sDk
*
*C>#q3w''''' (QFQF#
$
$C
)Aq//
!
!&
)
)C8///1E1E1EFGGL
sCj
)
)C>#|,,,,,8///1E1E1EFGGL
sCj
)
)C>#|,,,,,,,r4   c                 z    t          j        ||           dz
  }d||dk    <   |j        dz
  |||j        dz
  k    <   |S )aZ  Finds knots lower bounds for given values.

    Returns an array of indices ``I`` such that
    ``0 <= I[i] <= knots.size - 2`` for all ``i``
    and
    ``knots[I[i]] < x[i] <= knots[I[i] + 1]`` if
    ``np.min(knots) < x[i] <= np.max(knots)``,
    ``I[i] = 0`` if ``x[i] <= np.min(knots)``
    ``I[i] = knots.size - 2`` if ``np.max(knots) < x[i]``

    :param x: The 1-d array values whose knots lower bounds are to be found.
    :param knots: The 1-d array knots used for cubic spline parametrization,
     must be sorted in ascending order.
    :return: An array of knots lower bounds indices.
    r   r   r   r   )r   searchsortedr   )r0   r!   lbs      r)   _find_knots_lower_boundsr{      sK      
	"	"Q	&B BrRxL  %zA~BrUZ!^Ir4   c                    t          | |          }|dd         |dd         z
  }||         }||dz            | z
  }| ||         z
  }||z  }||z  }||z  |z  d|z  z  }	d|	| t          j        |          k    <   ||z  dz  }
|	|
z
  }||z  |z  d|z  z  }d|| t          j        |          k     <   ||z  dz  }||z
  }|||||fS )a  Computes base functions used for building cubic splines basis.

    .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, p. 146
      and for the special treatment of ``x`` values outside ``knots`` range
      see 'mgcv' source code, file 'mgcv.c', function 'crspl()', l.249

    :param x: The 1-d array values for which base functions should be computed.
    :param knots: The 1-d array knots used for cubic spline parametrization,
     must be sorted in ascending order.
    :return: 4 arrays corresponding to the 4 base functions ajm, ajp, cjm, cjp
     + the 1-d array of knots lower bounds indices corresponding to
     the given ``x`` values.
    r   Nr   r   r   )r{   r   maxmin)r0   r!   rU   r"   hjxj1_xx_xjajmajpcjm_3cjm_1cjmcjp_3cjp_1cjps                  r)   _compute_base_functionsr      s    	!E**Aabb	E#2#JA	
1B!a%L1EuQx<D
"*C
)CEME!S2X.E"E!bfUmm
JE
%-C4K$#(+E"E!bfUmm
IOE
%-CS#q  r4   c                     	 ddl m} n# t          $ r t          d          w xY w|j        d         }|                    t          j        |                    \  }}t          j        | |dd|df                   S )a*  Absorb model parameters constraints into the design matrix.

    :param design_matrix: The (2-d array) initial design matrix.
    :param constraints: The 2-d array defining initial model parameters
     (``betas``) constraints (``np.dot(constraints, betas) = 0``).
    :return: The new design matrix with absorbed parameters constraints.

    :raise ImportError: if scipy is not found, used for ``scipy.linalg.qr()``
      which is cleaner than numpy's version requiring a call like
      ``qr(..., mode='complete')`` to get a full QR decomposition.
    r   r   r   N)r   r   r   rM   qrr   	transposedot)design_matrixconstraintsr   mqrs         r)   _absorb_constraintsr   "  s    H        H H HFGGGH 	!A99R\+..//DAq6-111abb5***r+   Fc                    |j         }|r0t          | t          |          t          |                    } |dz  }t	          | |          \  }}}}}|dz   }	|r	d|	|	|k    <   t          j        |          }
|rt          |          }nt          |          }||
|ddf         j	        z  ||
|	ddf         j	        z  z   |||ddf         j	        z  z   |||	ddf         j	        z  z   }|j	        S )a  Builds an unconstrained cubic regression spline design matrix.

    Returns design matrix with dimensions ``len(x) x n``
    for a cubic regression spline smoother
    where
     - ``n = len(knots)`` for natural CRS
     - ``n = len(knots) - 1`` for cyclic CRS

    .. note:: See 'Generalized Additive Models', Simon N. Wood, 2006, p. 145

    :param x: The 1-d array values.
    :param knots: The 1-d array knots used for cubic spline parametrization,
     must be sorted in ascending order.
    :param cyclic: Indicates whether used cubic regression splines should
     be cyclic or not. Default is ``False``.
    :return: The (2-d array) design matrix.
    r   r   N)
r   r3   r~   r}   r   r   identityrH   r*   T)r0   r!   cyclicrF   r   r   r   r   rU   j1r'   fdmts                r)   _get_free_crs_dmatrixr   9  s   $ 	
A 3u::s5zz22	Q3Au==Cc3	
QB 27
AA "%  5!!
!QQQ$	/C!BE(*,
,sQq!!!tWY
>qQQQxzAQ
QC5Lr4   c                 L    t          | ||          }|t          ||          }|S )a  Builds a cubic regression spline design matrix.

    Returns design matrix with dimensions len(x) x n
    where:
     - ``n = len(knots) - nrows(constraints)`` for natural CRS
     - ``n = len(knots) - nrows(constraints) - 1`` for cyclic CRS
    for a cubic regression spline smoother

    :param x: The 1-d array values.
    :param knots: The 1-d array knots used for cubic spline parametrization,
     must be sorted in ascending order.
    :param constraints: The 2-d array defining model parameters (``betas``)
     constraints (``np.dot(constraints, betas) = 0``).
    :param cyclic: Indicates whether used cubic regression splines should
     be cyclic or not. Default is ``False``.
    :return: The (2-d array) design matrix.
    )r   r   )r0   r!   r   r   rO   s        r)   _get_crs_dmatrixr   b  s/    $ 
q%	0	0B [11Ir4   c                 H    t          |           }|t          ||          }|S )aN  Builds tensor product design matrix, given the marginal design matrices.

    :param design_matrices: A sequence of 2-d arrays (marginal design matrices).
    :param constraints: The 2-d array defining model parameters (``betas``)
     constraints (``np.dot(constraints, betas) = 0``).
    :return: The (2-d array) design matrix.
    )rX   r   )design_matricesr   rO   s      r)   _get_te_dmatrixr   {  s+     
_	-	-B [11Ir4   c                 ,   || j         dk    rt          d          || j         dk    rt          j        |           }|| j         dk    rt          d          || j         dk    rt          j        |           }||k     rt          d|d|d          |||dk     rt          d|          | || k    | |k    z           } t          j        |           } | j         dk    r[t          j        dd	|d
z             dd         }t          j        t          j        | |	                                                    }n|dk    rt          j
        g           }nt          d|d|d|d          |t          j        |          }|&||j         k    rt          d|d|j         d          |j         }t          j        ||k               r t          d|||k              d|d          t          j        ||k              r t          d|||k             d|d          nt          d          t          j        ||g|f          }t          j        |          }|j         |d
z   k    r!t          d|d| j         d|d|d	          |S )a  Gets all knots locations with lower and upper exterior knots included.

    If needed, inner knots are computed as equally spaced quantiles of the
    input data falling between given lower and upper bounds.

    :param x: The 1-d array data values.
    :param n_inner_knots: Number of inner knots to compute.
    :param inner_knots: Provided inner knots if any.
    :param lower_bound: The lower exterior knot location. If unspecified, the
     minimum of ``x`` values is used.
    :param upper_bound: The upper exterior knot location. If unspecified, the
     maximum of ``x`` values is used.
    :return: The array of ``n_inner_knots + 2`` distinct knots.

    :raise ValueError: for various invalid parameters sets or if unable to
     compute ``n_inner_knots + 2`` distinct knots.
    Nr   zXCannot set lower exterior knot location: empty input data and lower_bound not specified.zXCannot set upper exterior knot location: empty input data and upper_bound not specified.zlower_bound > upper_bound (z > )z)Invalid requested number of inner knots: d   r   r   r   z$No data values between lower_bound(=z) and upper_bound(=z): cannot compute requested z inner knot(s).zNeeded number of inner knots=z/ does not match provided number of inner knots=.zSome knot values (z) fall below lower bound (r-   z) fall above upper bound (z5Must specify either 'n_inner_knots' or 'inner_knots'.z!Unable to compute n_inner_knots(=z) + 2 distinct knots: z* data value(s) found between lower_bound(=)r   r.   r   r~   r}   uniquer@   asarray
percentiletolistr   anyconcatenate)r0   n_inner_knotsinner_knotslower_boundupper_boundinner_knots_q	all_knotss          r)   _get_all_sorted_knotsr     s>   ( qv{{8
 
 	
 
	1fQiiqv{{8
 
 	
 
	1fQii[  j5@[[+++N
 
 	
 }81*ANP   {aA$456IaLL6Q;;K30ABB1R4HM*R]1m6J6J6L6L%M%MNNKKa(2,,KK* (3{{KKKP  
 
	 i,,$+:J)J)J*8E{GWGWGWY   $(6++,, 	*&{['@AAA;;;P   6++,, 	*&{['@AAA;;;P  	 PQQQk :KHIII	)$$I~***j }}afffkkk;;;@
 
 	
 r4   c                  z   dd l } |                     t          t          t	          j        g           d           |                     t          t          t	          j        g           d           |                     t          t          t	          j        g           dd           |                     t          t          t	          j        g           dd           |                     t          t          t	          j        g           ddd           t	          j        t          t	          j        g           ddd          ddg          sJ |                     t          t          t	          j        g           ddd           t	          j        d	          d
z  }|                     t          t          |d           t	          j        t          |d          ddg          sJ t	          j        t          |ddd          ddg          sJ t	          j        t          |d
dd          g d          sJ |                     t          t          |d
dd           |                     t          t          |ddd           t	          j        t          |ddd          g d          sJ |                     t          t          |dd
d           |                     t          t          |dd
dg           |                     t          t          |d
d           t	          j        t          |ddg          g d          sJ t	          j        t          |ddgd
          g d          sJ |                     t          t          |ddgd           |                     t          t          |ddgd	           d S )Nr   r   r   )r   rZ   )r   r\   )r   r   rf   r   rJ   r>   rg   	   )r   r]   rf   r   g?gffffff?)r   r   r\   )r   re   )r   r\   re   r>   )r   r   )r   r\   re   r>   r]   )r   r   )r?   rA   r.   r   r   r   ri   r^   rB   s     r)   test__get_all_sorted_knotsr     s   MMM
MM*3RXb\\2FFF
MM*3RXb\\1EEE
MM*3RXb\\1RSMTTT
MM*3RXb\\1RSMTTT
MM)28B<<WX     >bhrllA1!LLLqRSf     MM)28B<<WX     		!qA
MM*3Q;;;>/1552w?????>aqAAAAq6     >aqAAA<<<     MM*3QqVWMXXX
MM)1aSc     >aqAAA999     MM*3QqVWMXXX
MM*3Q1vMNNN
MM*3QASTMUUU>/1vFFFVVVVV>aaVCCC]]]     MM)11a&a     MM)11a&a      r4   c                 n    |                      d                              d| j        d         f          S )a  Computes the centering constraint from the given design matrix.

    We want to ensure that if ``b`` is the array of parameters, our
    model is centered, ie ``np.mean(np.dot(design_matrix, b))`` is zero.
    We can rewrite this as ``np.dot(c, b)`` being zero with ``c`` a 1-row
    constraint matrix containing the mean of each column of ``design_matrix``.

    :param design_matrix: The 2-d array design matrix.
    :return: A 2-d array (1 x ncols(design_matrix)) defining the
     centering constraint.
    r   axisr   )meanr_   rM   )r   s    r)   &_get_centering_constraint_from_dmatrixr     s6     1%%--q-2Ea2H.IJJJr4   c                   J    e Zd ZdZdZd Z	 	 	 	 	 ddZd Z	 	 	 	 	 ddZe	Z
dS )	CubicRegressionSplinea  Base class for cubic regression spline stateful transforms

    This class contains all the functionality for the following stateful
    transforms:
     - ``cr(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None)``
       for natural cubic regression spline
     - ``cc(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None)``
       for cyclic cubic regression spline
    a   
    :arg df: The number of degrees of freedom to use for this spline. The
      return value will have this many columns. You must specify at least one
      of ``df`` and ``knots``.
    :arg knots: The interior knots to use for the spline. If unspecified, then
      equally spaced quantiles of the input data are used. You must specify at
      least one of ``df`` and ``knots``.
    :arg lower_bound: The lower exterior knot location.
    :arg upper_bound: The upper exterior knot location.
    :arg constraints: Either a 2-d array defining general linear constraints
     (that is ``np.dot(constraints, betas)`` is zero, where ``betas`` denotes
     the array of *initial* parameters, corresponding to the *initial*
     unconstrained design matrix), or the string
     ``'center'`` indicating that we should apply a centering constraint
     (this constraint will be computed from the input data, remembered and
     re-used for prediction from the fitted model).
     The constraints are absorbed in the resulting design matrix which means
     that the model is actually rewritten in terms of
     *unconstrained* parameters. For more details see :ref:`spline-regression`.

    This is a stateful transforms (for details see
    :ref:`stateful-transforms`). If ``knots``, ``lower_bound``, or
    ``upper_bound`` are not specified, they will be calculated from the data
    and then the chosen values will be remembered and re-used for prediction
    from the fitted model.

    Using this function requires scipy be installed.

    .. versionadded:: 0.3.0
    c                 L    || _         || _        i | _        d | _        d | _        d S N)_name_cyclic_tmp
_all_knots_constraints)selfnamer   s      r)   __init__zCubicRegressionSpline.__init__U  s,    
	 r4   Nc                 D   |||||d}|| j         d<   t          j        |          }|j        dk    r|j        d         dk    r|d d df         }|j        dk    rt          d| j        d          | j                             dg                               |           d S )	N)dfr!   r   r   r   argsr   r   r   	Input to % must be 1-d, or a 2-d column vector.xs)	r   r   
atleast_1drL   rM   r.   r   
setdefaultappend)r   r0   r   r!   r   r   r   r   s           r)   memorize_chunkz$CubicRegressionSpline.memorize_chunk\  s     &&&
 
 !	&M!6Q;;171:??!!!Q$A6A::*IMU   		T2&&--a00000r4   c                    | j         d         }| j         d         }| ` t          j        |          }|d         |d         t          d          |d         }d}|Nt	          |d          rd	}n;t          j        |          }|j        d
k    rt          d          |j        d         }d }|d         Sd	}| j        s|dk    rd
}|d         |k     rt          d|d         d|d          |d         d
z
  |z   }| j        r|d	z  }t          |||d         |d         |d                   | _
        |t	          |d          r)t          t          || j
        | j                            }| j
        j        }| j        r|d	z  }|j        d	         |k    r!t          d|d|j        d	         d          || _        d S d S )Nr   r   r   r!   z$Must specify either 'df' or 'knots'.r   r   centerr   r   ,Constraints must be 2-d array or 1-d vector.z'df'=z" must be greater than or equal to r   r   r   )r   r   r   r   r   zConstraints array should have z columns but z found.)r   r   r   r.   r
   
atleast_2drL   rM   r   r   r   r   r   r   r   )	r   r   r   r0   r   n_constraintsr   min_dfdf_before_constraintss	            r)   memorize_finishz%CubicRegressionSpline.memorize_finishx  s9   y Yt_IN2:$w-"7CDDD=)"k844 5 !" mK88#q(($%VWWW + 1! 4:!F< MQ$6$6DzF"" jDzzz666+   !JN]:M| #"/'W]+]+
 
 
 "k844 D)!T_T\RRR  %)O$8!| +%*% #'<<< j$9$9$9;;LQ;O;O;OQ   !,D #"r4   c                    |}t          j        |          }|j        dk    r|j        d         dk    r|d d df         }|j        dk    rt	          d| j        d          t          || j        | j        | j	                  }t          rFt          |t          j        t          j        f          r t          j        |          }|j        |_        |S )Nr   r   r   r   r   r   )r   r   rL   rM   r.   r   r   r   r   r   r   
isinstancepandasSeries	DataFrameindex)	r   r0   r   r!   r   r   r   r9   rO   s	            r)   	transformzCubicRegressionSpline.transform  s     M!6Q;;171:??!!!Q$A6A::*IMU   t 1$,
 
 
  	(&6=&2B"CDD (%b))!<	r4   )NNNNN)__name__
__module____qualname____doc__
common_docr   r   r   r   r   __getstate__ r4   r)   r   r   +  s         J>! ! ! 1 1 1 18:, :, :,~    4 LLLr4   r   c                   0    e Zd ZdZer
eej        z  Zd ZdS )CRa(  cr(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None)

    Generates a natural cubic spline basis for ``x``
    (with the option of absorbing centering or more general parameters
    constraints), allowing non-linear fits. The usual usage is something like::

      y ~ 1 + cr(x, df=5, constraints='center')

    to fit ``y`` as a smooth function of ``x``, with 5 degrees of freedom
    given to the smooth, and centering constraint absorbed in
    the resulting design matrix. Note that in this example, due to the centering
    constraint, 6 knots will get computed from the input data ``x``
    to achieve 5 degrees of freedom.


    .. note:: This function reproduce the cubic regression splines 'cr' and 'cs'
      as implemented in the R package 'mgcv' (GAM modelling).

    c                 @    t                               | dd           d S )Nr   Fr   r   r   r   r   s    r)   r   zCR.__init__  s#    &&t$u&EEEEEr4   Nr   r   r   r   r   r   r   r   r4   r)   r   r     sJ         *  4(33F F F F Fr4   r   c                   0    e Zd ZdZer
eej        z  Zd ZdS )CCa)  cc(x, df=None, knots=None, lower_bound=None, upper_bound=None, constraints=None)

    Generates a cyclic cubic spline basis for ``x``
    (with the option of absorbing centering or more general parameters
    constraints), allowing non-linear fits. The usual usage is something like::

      y ~ 1 + cc(x, df=7, constraints='center')

    to fit ``y`` as a smooth function of ``x``, with 7 degrees of freedom
    given to the smooth, and centering constraint absorbed in
    the resulting design matrix. Note that in this example, due to the centering
    and cyclic constraints, 9 knots will get computed from the input data ``x``
    to achieve 7 degrees of freedom.

    .. note:: This function reproduce the cubic regression splines 'cc'
      as implemented in the R package 'mgcv' (GAM modelling).

    c                 @    t                               | dd           d S )Nr   Tr   r   r   s    r)   r   zCC.__init__	  s#    &&t$t&DDDDDr4   Nr   r   r4   r)   r   r     sJ         (  4(33E E E E Er4   r   c            	         dd l } |                     t          t          t	          j        d                              d          d           |                     t          t                      j        t	          j        d                              d          d           |                     t          t          t	          j        d                     |                     t          t          t	          j        d          dt	          j        d                              d          	           |                     t          t          t	          j        d          dt	          j        d
          	           |                     t          t          t	          j        d          d           |                     t          t          t	          j        d          d           d S )Nr      rd   r]   r   2      r\   r\   r\   r   r   rf   r   )
r?   rA   r.   r   r   r^   r_   r   r   r   r`   s    r)   test_crs_errorsr     sR   MMM MM*b")B--"7"7"?"?AMFFF
MM*bddnbimm.C.CF.K.KPQMRRR
MM*b")B--000
MM

	"IbMM)))44     MM*b")B--A29Q<<MPPP
MM*b")B--AM666
MM*b")B--AM66666r4   c                     ddl m}  ddlm}m}m} |                    d          }d}|                    d          }	 ||         dk    snz|dz  }|                    d|          }|||         }i }	|D ] }
|
                    d	d          \  }}||	|<   !d}|	d
         dk    s|	d
         dk    rt          }n1|	d
         dk    rt          }|dz  }nt          d|	d
                   i }|	d         dk    r
d|d<   |dz  }|	d         dk    r_t          j        t          |	d                             }|                                 |dd         |d<   |d         |d<   |d         |d<   nt          |	d                   |z
  |d<   t          j        t          |	d                             } | |d||fi | |dz  }|dz   }||k    sJ d S )Nr   )check_stateful)R_crs_test_xR_crs_test_dataR_crs_num_tests
z--BEGIN TEST CASE--Tr   z--END TEST CASE--=spline_typer   csr   zUnrecognized spline type absorb_consTRUEr   r   r!   Noner   r   r   nb_knotsr   outputF)patsy.test_stater   patsy.test_splines_crs_datar   r   r   splitr   r   r   r.   r   r   evalsort)r   r   r   r   lines	tests_ran	start_idxstop_idxblock	test_datalinekeyvalue	adjust_dfr  kwargsr   r  s                     r)   test_crs_compatr  )  sw   //////          !!$''EI122I&!Y#888Q	;;2I>>i()	 	# 	#DC++JC"IcNN	]#t++y/G4/O/OKK}%--KNII*1:=1I1IK   ]#v--$,F=!NIW''
4	'(:#;#;<<INN'"oF7O$-aLF=!$-bMF=!!	* 566BF4LD8!45566{E<JJ6JJJQ	qL	M&!N ''''''r4   Tc                     ddl m} m}m} dt	          j        d          z  }t	          j        g d          }t	          j        g dg          }t	          j        g d          } |d          }d	|d d
         id	|d
d          igd	|i} | dfd          }	 ||	g|          d         }
t	          j        ||
dd          sJ d S )Nr   )incr_dbuilderbuild_design_matricesdmatrix         )g  Qg    |:Ig      пg    @@g   I@)g o?ggEW;?gM֎gͩGX?gI z3?)g     pg      ig     r@g     @@zscr(new_x, knots=knots_R[1:-1], lower_bound=knots_R[0], upper_bound=knots_R[-1], constraints=centering_constraint_R)r0   r>   z!cr(x, df=4, constraints='center')c                  "    t                     S r   iterdata_chunkeds   r)   <lambda>z3test_crs_with_specific_constraint.<locals>.<lambda>  s    T,5G5G r4   -q=r   rtolatol)patsy.highlevelr  r  r  r   r^   r   r8   )r  r  r  r0   knots_Rcentering_constraint_Rnew_xresult1new_databuilderresult2r#  s              @r)   !test_crs_with_specific_constraintr1  a  s8   MMMMMMMMMM	")B--A h	
 	
 	
 G  X  	

 
 H55566Eg	. G !CRC&MC233=1LU|Hm+-G-G-G-G G $#WIx88;G;we#>>>>>>>>r4   c                   .    e Zd ZdZd Zd Zd Zd ZeZ	dS )TEa>  te(s1, .., sn, constraints=None)

    Generates smooth of several covariates as a tensor product of the bases
    of marginal univariate smooths ``s1, .., sn``. The marginal smooths are
    required to transform input univariate data into some kind of smooth
    functions basis producing a 2-d array output with the ``(i, j)`` element
    corresponding to the value of the ``j`` th basis function at the ``i`` th
    data point.
    The resulting basis dimension is the product of the basis dimensions of
    the marginal smooths. The usual usage is something like::

      y ~ 1 + te(cr(x1, df=5), cc(x2, df=6), constraints='center')

    to fit ``y`` as a smooth function of both ``x1`` and ``x2``, with a natural
    cubic spline for ``x1`` marginal smooth and a cyclic cubic spline for
    ``x2`` (and centering constraint absorbed in the resulting design matrix).

    :arg constraints: Either a 2-d array defining general linear constraints
     (that is ``np.dot(constraints, betas)`` is zero, where ``betas`` denotes
     the array of *initial* parameters, corresponding to the *initial*
     unconstrained design matrix), or the string
     ``'center'`` indicating that we should apply a centering constraint
     (this constraint will be computed from the input data, remembered and
     re-used for prediction from the fitted model).
     The constraints are absorbed in the resulting design matrix which means
     that the model is actually rewritten in terms of
     *unconstrained* parameters. For more details see :ref:`spline-regression`.

    Using this function requires scipy be installed.

    .. note:: This function reproduce the tensor product smooth 'te' as
      implemented in the R package 'mgcv' (GAM modelling).
      See also 'Generalized Additive Models', Simon N. Wood, 2006, pp 158-163

    .. versionadded:: 0.3.0
    c                 "    i | _         d | _        d S r   )r   r   r   s    r)   r   zTE.__init__  s    	 r4   c                    | j                             d|                    d                    }t          |d          r g }|D ]@}t	          |          }|j        dk    rt          d          |                    |           At          |          }| j                             dd           | j         dxx         |j	        d         z  cc<   t          j        |                    d                    }| j                             dt          j        |j	                             | j         dxx         |z  cc<   d S d S )	Nr   r   r   ?Each tensor product argument must be a 2-d array or 1-d vector.countr   r   sum)r   r   getr
   r   rL   r.   r   rX   rM   r   r   r8  r   )r   r   r  r   args_2dargrR   	chunk_sums           r)   r   zTE.memorize_chunk  sG   i**=&**]:S:STT+x00 	*G $ $/448q==$5   s####$W--BI  !,,,Ig"(1+-bff!fnn55II  (A(ABBBIe	)#	* 	*r4   c                    | j         }| j         d         }| ` |bt          |d          r$t          j        |d         |d         z            }n.t          j        |          }|j        dk    rt          d          || _        d S )Nr   r   r8  r7  r   r   )r   r
   r   r   rL   r.   r   )r   tmpr   s      r)   r   zTE.memorize_finish  s    ii.I"k844 X mCJW,EFF mK88#q(($%VWWW'r4   c                     g }|D ]@}t          |          }|j        dk    rt          d          |                    |           At	          || j                  S )Nr   r6  )r   rL   r.   r   r   r   )r   r   r  r:  r;  s        r)   r   zTE.transform  sm     	  	 C+C00Cx1}} X   NN3w(9:::r4   N)
r   r   r   r   r   r   r   r   r   r   r   r4   r)   r3  r3    s\        # #J! ! !* * **( ( ( 
; 
; 
; LLLr4   r3  c                     dd l } t          j        d          }|                     t          t
          |                    d                     |                     t          t
          |                    d          d           |                     t          t
          |t          j        d                              d                     d S )Nr   r   r   r   r   rg   )r   r   r   )r?   r   r^   rA   r.   r   r_   rB   s     r)   test_te_errorsrB    s    MMM
	"A
MM*b!))I"6"6777
MM*b!))I"6"6HMMMM
MM*b!11E1Ei1P1PMQQQQQr4   c            	         ddl m}  dt          j        d          z  }t          j        t          |d          t          t          |d                              sJ t          j        t          |d          t          t          |d                              sJ t          j         | |d          t           | |d                              sJ t          j        t          |d	d
          t          t          |d          d
                    sJ t          j        dd          }t          j        t          |d	|          t          t          |d          |                    sJ d S )Nr   )bsr  r  rf   r   rZ   r]   r\   r   r   rA  r   )patsy.splinesrD  r   r^   r8   r   r   r   )rD  r0   center_constraints      r)   test_te_1smoothrG    ss          
")B--A;r!{{{Br!{{{OO44444;r!{{{Br!{{{OO44444;rr!{{{Brr!{{{OO44444;
1)))2bqkkkx+P+P+P     	!Q;
1 1222
2aA;;;$5666      r4   c                     ddl m} m} dt          j        d          z  }dt          j        d          z  }t          j        g dg dg          }t          j        g dg d	g          }t          j        d
dg          }t          j        ddg          }||d}|d d         |d d         d|dd          |dd          dg | dfd          }	 ||	g|          d         }
t          j        |
|dd          sJ  | dfd          }	 ||	g|          d         }t          j        ||dd          sJ d S )Nr   r  r  r  r  皙?)gKA Ҿgn\>gr~>g@sgSPFT>gd=gcJ8|?g?gGHoVg	*Fti2?g~p$پgGV؀>g ?nпgw?g_:5,i?g$qgH2n,#|?ghu=
g-&gy8%?ge`?gmQr`Xgq(%?g\Ng̽p>go|Tgqg_W>gm?g" @o=)gN4fHNg	fU(FI?g찛0?gG	#gjb	?g4gw%@g7zBghxqNg/Z?g,DMKӿgNM?gyzAg׼p=@gc"@gA[gpi@grXm'gyU,A@g_[Hz<g !gY@g!JYg5&@gQ@m?gp]Hg!i%Rʿg$7n?g7찿gwc?)g k?gl
%?gB'> gȎF%?g"ugvg`ѿ?gOYc+g& ig

A?g7zWyog>Td(gD)]?gʴ]?gDRUgzK?gp+<U{?gRR\I¿gAeA?glp)Pb?gzwZg#]g=Hjg,Oo&%gM_9?gD?gC(:۴AgA8`3?gOW-)g[\7?gGzQ?gSg*E?g݁g]+@/gu0@g«	2g.o?g^οg?g#gDM-V@g{Cx"@gU^V)?g*&@gL=վ%gL;6L:@g{V65g7"gȬ@gKygrQ%@g&.gW{:@gL%Gɿg_?gxavg32?g     &@g   @g0@gÉؗҜ@)x1x2r>   z"te(cr(x1, df=5), cc(x2, df=6)) - 1c                  "    t                     S r   r   r"  s   r)   r$  z"test_te_2smooths.<locals>.<lambda>  s    d<6H6H r4   r%  r   r&  z8te(cr(x1, df=5), cc(x2, df=6), constraints='center') - 1c                  "    t                     S r   r   r"  s   r)   r$  z"test_te_2smooths.<locals>.<lambda>  s    \"" r4   r)  r  r  r   r^   r   r8   )r  r  rK  rL  dmatrix_R_noconsdmatrix_R_consnew_x1new_x2r.  r/  dmatrix_noconsdmatrix_consr#  s               @r)   test_te_2smoothsrV    s   DDDDDDDD
29R==	 B
")B--	B x  @  CA	
C CJ X  >  A?	
A AND Xy"7899FX,.CDEEFF++Hcrc7"SbS'222bcc7"RSS'4R4RSLm,.H.H.H.H G +*G9h??BN;~'7e#NNNNNNmE"""" G )('H==a@L;|^%cJJJJJJJJr4   c                    	 ddl m} m} dt          j        d          z  }dt          j        d          z  }dt          j        d          z  }t          j        g dg          }dd	d
d}|d d         |d d         |d d         d|dd          |dd          |dd          dg	 | d	fd          } ||g|          d         }t          j        ||dd          sJ d S )Nr   rI  r  r  rJ  g333333)gVh?g;)D`?g~:i?gYDw_[/?g(ӭV|?gk؇Zg6O;=g<A+gsvNLh>g'YZ4vȄ?gw?gEr/Fg>?g}tZ?g/HF̿g(mog]gq[W@>gGx<#g/qg38qP?g񉃻@g}xRgu~k?gcFN>gJ>gC}⛡yg    8Cg&.Q@gu)rK  rL  x3r>   z0te(cr(x1, df=3), cr(x2, df=3), cc(x3, df=3)) - 1c                  "    t                     S r   r   r"  s   r)   r$  z"test_te_3smooths.<locals>.<lambda>  s    DDVDV r4   r%  r   r&  rO  )
r  r  rK  rL  rX  design_matrix_Rr.  r/  r   r#  s
            @r)   test_te_3smoothsr[    sC   DDDDDDDD
29R==	 B
")B--	B
29R==	 Bh  	
   OD %#$ H #2#wb"gRW55"##wbgRW55L m:<V<V<V<V G *)7)X>>qAM;}oELLLLLLLLr4   )F)NFr   )NNNN)-__all__numpyr   
patsy.utilr   r   r   r	   r
   patsy.stater   r   r*   r3   r<   rC   rH   rX   ra   rw   r{   r   r   r   r   r   r   r   r   objectr   r   r   r   r   r   r  slowr1  r3  r   rB  rG  rV  r[  r   r4   r)   <module>rb     sD   

                  + * * * * * MMMG G GH  .4 4 48 8 8 !  !  !L( ( (V
 
 
- - ->  6"! "! "!J+ + +.& & & &R   2   & LP] ] ] ]@, , ,^K K Kc c c c cF c c cLF F F F F	 F F F: E E E E E	 E E E8 7 7 722( 2( 2(j  *? *? *?Z[ [ [ [ [ [ [ [| R R R  *^K ^K ^KB5M 5M 5M 5M 5Mr4   