
    M/Ph(O                     b   d dl Z d dlZd dlZd dlmZ d dlmc m	Z
 d dlmZ  G d dej                  Z G d de          Z G d d	e          Z G d
 de          Z G d dej                  Z G d de
j                  Z e
j        ee           d Z G d de          ZeZeZeZeZdS )    N)model)ConvergenceWarningc                   (     e Zd ZdZ fdZd Z xZS )_DimReductionRegressionzB
    A base class for dimension reduction regression methods.
    c                 >     t                      j        ||fi | d S N)super__init__selfendogexogkwargs	__class__s       ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/regression/dimred.pyr
   z _DimReductionRegression.__init__   s*    ///////    c                    t          j        | j                  }| j        |d d f         }||                    d          z  }t          j        |j        |          |j        d         z  }t           j        	                    |          }t           j        
                    ||j                  j        }|| _        || _        t          j        ||          | _        d S Nr   )npargsortr   r   meandotTshapelinalgcholeskysolvewexog_covxrarray_split_split_wexog)r   n_sliceiixcovxcovxrs         r   _prepz_DimReductionRegression._prep   s     Z
##Ib!!!e 	
QVVAYYvac1~~
*	""4((IOOE13'')
 N1g66r   )__name__
__module____qualname____doc__r
   r'   __classcell__r   s   @r   r   r      sQ         0 0 0 0 07 7 7 7 7 7 7r   r   c                   2    e Zd ZdZddZd Zd Z	 	 dd
ZdS )SlicedInverseRega0  
    Sliced Inverse Regression (SIR)

    Parameters
    ----------
    endog : array_like (1d)
        The dependent variable
    exog : array_like (2d)
        The covariates

    References
    ----------
    KC Li (1991).  Sliced inverse regression for dimension reduction.
    JASA 86, 316-342.
       c                    t          |          dk    rd}t          j        |           | j        j        d         |z  }|                     |           d | j        D             }d | j        D             }t          j        |          }t          j        |          }t          j	        |j
        |dddf         |z            |                                z  }t          j                            |          \  }}	t          j        |           }
||
         }|	dd|
f         }	t          j                            | j        j
        |	          }t#          | ||          }t%          |          S )z
        Estimate the EDR space using Sliced Inverse Regression.

        Parameters
        ----------
        slice_n : int, optional
            Target number of observations per slice
        r   z1SIR.fit does not take any extra keyword argumentsc                 8    g | ]}|                     d           S r   r   .0zs     r   
<listcomp>z(SlicedInverseReg.fit.<locals>.<listcomp>J   s"    333AaffQii333r   c                 (    g | ]}|j         d          S r3   r   r5   s     r   r8   z(SlicedInverseReg.fit.<locals>.<listcomp>K   s    333AQWQZ333r   Neigs)lenwarningswarnr   r   r'   r!   r   asarrayr   r   sumr   eighr   r   r   DimReductionResultsDimReductionResultsWrapper)r   slice_nr   msgr"   mnnmncabjjparamsresultss                r   fitzSlicedInverseReg.fit6   sB    v;;??ECM# )/!$/

733!233333!2333Z^^JqMM fRT1QQQW:?++aeegg5y~~c""1Z^^bEaaaeH22%dF;;;)'222r   c                 f   | j         }| j        }| j        }| j        }d}t	          j        ||| j        f          }t          | j                  D ]@}t	          j        | j	        |d d |f                   }|t	          j
        ||z            z  }At	          j        ||          }	t          j                            |	          \  }
}t	          j        |
t	          j        |
j        |j                            }|j        |z
  }|t	          j        |||z  
                    d                    z  }|S r   )k_vars_covx_slice_means_slice_propsr   reshapendimranger   pen_matrA   r   qrr   )r   Apr%   rG   phvkucovxaq_qdqus                 r   _regularized_objectivez'SlicedInverseReg._regularized_objective[   s    KzJq1di.)) ty!! 	 	At|Qqqq!tW--AAAA tQy||E""1VArvac24(())TBY	RVBba(()))r   c                    | j         }| j        }| j        }| j        }| j        }| j        }|                    ||f          }dt          j        | j	        j
        t          j        | j	        |                    z  }|                    ||f          }t          j        ||          }	t          j        ||	          }
t          j        |	j
        |	          }t          j                            |          }t          j        ||f          }t          j                            ||	j
                  }d g||z  z  }t          |          D ]!}t          |          D ]}|dz  }d|||f<   t          j        |
j
        |          }||j
        z  }t          j        |t          j        ||                     }t          j        t          j        ||          |          }|t          j        |	t          j        ||	j
                            z  }|t          j        |	t          j                            |t          j        |j
        |                              z  }||||z  |z   <   #t          j                            |t          j        |	j
        |j
                            }|t          j        |	|          j
        z
  }t          |          D ]}||d d f         }||d d f         }t          |          D ]f}t          |          D ]T}t          j        |t          j        |||z  |z            |                    }|||fxx         d||         z  |z  z  cc<   Ug|                                S )N   r      )rQ   rV   rR   r"   rS   rT   rU   r   r   rX   r   r   invzerosr   rW   ravel)r   rZ   r[   rV   r%   r"   rG   r\   grr`   covx2aQQijmqcvftra   rumatfmatchcuir_   r]   fs                             r   _regularized_gradz"SlicedInverseReg._regularized_grads   s    Kyz,IIq$i   t|Q(?(?@@@IIq$i  tQe$$F57E""Y]]1Xq$i  iooa))Vq4x q 
	& 
	&A4[[ 	& 	&a1a4vfh++r26$#3#3444vbfT2..44ubfT57&;&;<<<ubiooad9K9K&L&LMMM!%1T6A:	& Y__Quw 5 566"&##%%w 	. 	.A1aaa4A1aaa4A1XX . .t . .Aq"&AdFQJ";";<<Aq!tHHHBqE	A-HHHH..
 xxzzr   rh   Nd   MbP?c                    t          |          dk    rd}t          j        |           |t          d          |                    dd          }|                    dd          }| j        j        d         |z  }	t          j        | j	                  }
| j        |
ddf         }||
                    d          z  }t          j        |j                  }t          j        ||	          }d |D             }d	 |D             }t          j        |          }t          j        |          }||                                z  | _        || _        |j        d         | _        || _        || _        |	| _        || _        |;t          j        | j        |f          }t          j        |          |d|d|f<   |}n$|j        d
         |k    rd}t          |          |}t3          || j        | j        ||          \  }}}|sg|                     |                                          }t          j        t          j        ||                    }d|z  }t          j        |           t?          | |d          }tA          |          S )a  
        Estimate the EDR space using regularized SIR.

        Parameters
        ----------
        ndim : int
            The number of EDR directions to estimate
        pen_mat : array_like
            A 2d array such that the squared Frobenius norm of
            `dot(pen_mat, dirs)`` is added to the objective function,
            where `dirs` is an orthogonal array whose columns span
            the estimated EDR space.
        slice_n : int, optional
            Target number of observations per slice
        maxiter :int
            The maximum number of iterations for estimating the EDR
            space.
        gtol : float
            If the norm of the gradient of the objective function
            falls below this value, the algorithm has converged.

        Returns
        -------
        A results class instance.

        Notes
        -----
        If each row of `exog` can be viewed as containing the values of a
        function evaluated at equally-spaced locations, then setting the
        rows of `pen_mat` to [[1, -2, 1, ...], [0, 1, -2, 1, ..], ...]
        will give smooth EDR coefficients.  This is a form of "functional
        SIR" using the squared second derivative as a penalty.

        References
        ----------
        L. Ferre, A.F. Yao (2003).  Functional sliced inverse regression
        analysis.  Statistics: a journal of theoretical and applied
        statistics 37(6) 475-488.
        r   z3SIR.fit_regularized does not take keyword argumentsNzpen_mat is a required argumentstart_paramsrE   r0   c                 8    g | ]}|                     d           S r3   r4   r5   s     r   r8   z4SlicedInverseReg.fit_regularized.<locals>.<listcomp>   s"    ,,,AaffQii,,,r   c                 (    g | ]}|j         d          S r3   r:   r5   s     r   r8   z4SlicedInverseReg.fit_regularized.<locals>.<listcomp>   s    ,,,AQWQZ,,,r   rh   z1Shape of start_params is not compatible with ndimz,SIR.fit_regularized did not converge, |g|=%fr;   )!r=   r>   r?   
ValueErrorgetr   r   r   r   r   r   covr   r    r@   rA   rT   rV   rQ   rX   rR   r"   rS   rj   eye
_grass_optre   rz   rk   sqrtr   rC   rD   )r   rV   rX   rE   maxitergtolr   rF   r~   r"   r#   r$   r%   
split_exogrG   rH   rM   rb   cnvrgggnrN   s                         r   fit_regularizedz SlicedInverseReg.fit_regularized   sh   T v;;??GCM#?=>>>zz.$77 **Y++ )/!$/ Z
##Ib!!!e	QVVAYYvac{{ ^Aw//
,,,,,,,,,,Z^^JqMMK	jm
Xt{D122F%'VD\\F1T61T6>"FF!!$,,I oo%!F%fd.I&*&<gtM M5  	&&v||~~66A1&&B@2ECM#%dF>>>)'222r   )r0   )rh   Nr0   r{   r|   )r(   r)   r*   r+   rO   re   rz   r    r   r   r/   r/   %   sv          #3 #3 #3 #3J  0- - -^ IL!c3 c3 c3 c3 c3 c3r   r/   c                       e Zd ZdZd ZdS )PrincipalHessianDirectionsa  
    Principal Hessian Directions (PHD)

    Parameters
    ----------
    endog : array_like (1d)
        The dependent variable
    exog : array_like (2d)
        The covariates

    Returns
    -------
    A model instance.  Call `fit` to obtain a results instance,
    from which the estimated parameters can be obtained.

    References
    ----------
    KC Li (1992).  On Principal Hessian Directions for Data
    Visualization and Dimension Reduction: Another application
    of Stein's lemma. JASA 87:420.
    c                    |                     dd          }| j        | j                                        z
  }| j        | j                            d          z
  }|r+ddlm}  |||                                          }|j        }t          j	        d|||          }|t          |          z  }t          j        |j                  }t          j                            ||          }	t          j                            |	          \  }
}t          j        t          j        |
                     }|
|         }
|dd|f         }t%          | ||
          }t'          |          S )a  
        Estimate the EDR space using PHD.

        Parameters
        ----------
        resid : bool, optional
            If True, use least squares regression to remove the
            linear relationship between each covariate and the
            response, before conducting PHD.

        Returns
        -------
        A results instance which can be used to access the estimated
        parameters.
        residFr   )OLSzi,ij,ik->jkNr;   )r   r   r   r   #statsmodels.regression.linear_modelr   rO   r   r   einsumr=   r   r   r   r   eigr   absrC   rD   )r   r   r   yr$   r   rs   cmcxcbrJ   rK   rL   rM   rN   s                  r   rO   zPrincipalHessianDirections.fit  s5   " 

7E**J***I	q))) 	??????Aq		AAY}aA..
c!ffVAC[[Y__R$$y}}R  1Z
##bE111b5%dF;;;)'222r   N)r(   r)   r*   r+   rO   r   r   r   r   r     s-         ,'3 '3 '3 '3 '3r   r   c                   (     e Zd ZdZ fdZd Z xZS )SlicedAverageVarianceEstimationa]  
    Sliced Average Variance Estimation (SAVE)

    Parameters
    ----------
    endog : array_like (1d)
        The dependent variable
    exog : array_like (2d)
        The covariates
    bc : bool, optional
        If True, use the bias-corrected CSAVE method of Li and Zhu.

    References
    ----------
    RD Cook.  SAVE: A method for dimension reduction and graphics
    in regression.
    http://www.stat.umn.edu/RegGraph/RecentDev/save.pdf

    Y Li, L-X Zhu (2007). Asymptotics for sliced average
    variance estimation.  The Annals of Statistics.
    https://arxiv.org/pdf/0708.0462.pdf
    c                      t          t          |           j        ||fi | d| _        d|v r|d         du rd| _        d S d S d S )NFbcT)r	   SAVEr
   r   r   s       r   r
   z(SlicedAverageVarianceEstimation.__init__a  s`    "dD"5$99&9996>>fTld22DGGG >22r   c                 \   |                     dd          }| j        j        d         |z  }|                     |           d | j        D             }d | j        D             }| j        j        d         }| j        s^d}t          ||          D ]7\  }}	t          j	        |          |	z
  }
||t          j
        |
|
          z  z  }8|t          |          z  }n>d}|D ]}|t          j
        ||          z  }|t          |          z  }d}| j        D ]p}||                    d          z
  }t          |j        d                   D ];}||ddf         }t          j        ||          }|t          j
        ||          z  }<q|| j        j        d         z  }t          j        |          }||dz
  z  |dz
  dz  dz   z  }|dz
  |dz
  dz  dz   z  }||z  ||z  z
  }t          j	        |          dt          |          z  t          |          z  z
  |z   }t          j                            |          \  }}t          j        |           }||         }|dd|f         }t          j                            | j        j        |          }t-          | ||	          }t/          |          S )
z
        Estimate the EDR space.

        Parameters
        ----------
        slice_n : int
            Number of observations per slice
        rE   2   r   c                 @    g | ]}t          j        |j                  S r   )r   r   r   r5   s     r   r8   z7SlicedAverageVarianceEstimation.fit.<locals>.<listcomp>z  s"    555abfQSkk555r   c                 (    g | ]}|j         d          S r3   r:   r5   s     r   r8   z7SlicedAverageVarianceEstimation.fit.<locals>.<listcomp>{  s    444Qagaj444r   rh   Nrg   r;   )r   r   r   r'   r!   r   r   zipr   r   r   r=   r   rW   outerrA   r   rB   r   r   r   r   rC   rD   )r   r   rE   r"   cvnsr[   vmwcvxicvavcvnr$   rs   rx   r_   mk1k2av2rJ   rK   rL   rM   rN   s                              r   rO   z#SlicedAverageVarianceEstimation.fith  s    **Y++ )/!$/

7554#455544$"3444JQw 	9Bb"++ + +3fQii#oa"&c****#b''MBB
 B # #bfQll"#b''MB B& ' 'q		Mqwqz** ' 'A!QQQ$AAA"&A,,&BB' $)/!$$BAa!eQ
Q/Ba%QUQJN+Br'BG#CQR[3r7722S8By~~b!!1Z^^bEaaaeH22%dF;;;)'222r   )r(   r)   r*   r+   r
   rO   r,   r-   s   @r   r   r   I  sQ         .    ?3 ?3 ?3 ?3 ?3 ?3 ?3r   r   c                   "     e Zd ZdZ fdZ xZS )rC   aV  
    Results class for a dimension reduction regression.

    Notes
    -----
    The `params` attribute is a matrix whose columns span
    the effective dimension reduction (EDR) space.  Some
    methods produce a corresponding set of eigenvalues
    (`eigs`) that indicate how much information is contained
    in each basis direction.
    c                 Z    t                                          ||           || _        d S r   )r	   r
   r<   )r   r   rM   r<   r   s       r   r
   zDimReductionResults.__init__  s/    V	 	 				r   )r(   r)   r*   r+   r
   r,   r-   s   @r   rC   rC     sB        
 
        r   rC   c                       e Zd ZddiZeZdS )rD   rM   columnsN)r(   r)   r*   _attrs_wrap_attrsr   r   r   rD   rD     s!        )F KKKr   rD   c                    | j         \  }}|                                 }  ||           }d}t          |          D ]}	 ||           }
|
t          j        |
|           | z  t          j        | |           z  z  }
t          j        t          j        |
|
z                      |k     rd} n|
                    ||f          }t          j        	                    |d          \  |                     ||f          }t          j        |j
                  fd}d}|dk    r- ||           } ||          }||k     r|} |}n|dz  }|dk    -|                     ||f          } | ||fS )a  
    Minimize a function on a Grassmann manifold.

    Parameters
    ----------
    params : array_like
        Starting value for the optimization.
    fun : function
        The function to be minimized.
    grad : function
        The gradient of fun.
    maxiter : int
        The maximum number of iterations.
    gtol : float
        Convergence occurs when the gradient norm falls below this value.

    Returns
    -------
    params : array_like
        The minimizing value for the objective function.
    fval : float
        The smallest achieved value of the objective function.
    cnvrg : bool
        True if the algorithm converged to a limit point.

    Notes
    -----
    `params` is 2-d, but `fun` and `grad` should take 1-d arrays
    `params.ravel()` as arguments.

    Reference
    ---------
    A Edelman, TA Arias, ST Smith (1998).  The geometry of algorithms with
    orthogonality constraints. SIAM J Matrix Anal Appl.
    http://math.mit.edu/~edelman/publications/geometry_of_algorithms.pdf
    FTr   c                     t          j        | z            z  t          j        | z            z  z   }t          j        |                                          S r   )r   cossinr   rk   )tpapa0sr_   vts     r   geoz_grass_opt.<locals>.geo  sM     rva!e}}$q26!a%=='88B6"b>>'')))r   g       @g|=rg   )r   rk   rW   r   r   r   rA   rU   r   svdr   )rM   fungradr   r   r[   df0r   rb   r   gmparamsmr   stepr   f1r   r   r_   r   s                    @@@@r   r   r     s   L <DAq\\^^F	VBE7^^   DLL	RVAv'"&*@*@@@726!a%==!!D((EEYY1v9==Q''1b..!Q((fWbd##	* 	* 	* 	* 	* 	* 	* 	* UlldUBRBBwwAID Ull ^^QF##F2ur   c                   6     e Zd ZdZ fdZd Zd Zd	dZ xZS )
CovarianceReductiona/  
    Dimension reduction for covariance matrices (CORE).

    Parameters
    ----------
    endog : array_like
        The dependent variable, treated as group labels
    exog : array_like
        The independent variables.
    dim : int
        The dimension of the subspace onto which the covariance
        matrices are projected.

    Returns
    -------
    A model instance.  Call `fit` on the model instance to obtain
    a results instance, which contains the fitted model parameters.

    Notes
    -----
    This is a likelihood-based dimension reduction procedure based
    on Wishart models for sample covariance matrices.  The goal
    is to find a projection matrix P so that C_i | P'C_iP and
    C_j | P'C_jP are equal in distribution for all i, j, where
    the C_i are the within-group covariance matrices.

    The model and methodology are as described in Cook and Forzani.
    The optimization method follows Edelman et. al.

    References
    ----------
    DR Cook, L Forzani (2008).  Covariance reducing models: an alternative
    to spectral modeling of covariance matrices.  Biometrika 95:4.

    A Edelman, TA Arias, ST Smith (1998).  The geometry of algorithms with
    orthogonality constraints. SIAM J Matrix Anal Appl.
    http://math.mit.edu/~edelman/publications/geometry_of_algorithms.pdf
    c                 6   t                                          ||           g g }}t          j        | j        | j                  }|                    |j                  D ]Q\  }}|                    |	                                j
                   |                    |j        d                    Rt          |          | _        d}	t          |          D ]\  }
}|	||
         ||
         z  z  }	|	| j        z  }	|	| _        || _        || _        || _        d S )N)indexr   )r	   r
   pd	DataFramer   r   groupbyr   appendr   valuesr   r=   nobs	enumeratecovmcovsr   dim)r   r   r   r   r   r   dfrb   r]   r   rx   r   s              r   r
   zCovarianceReduction.__init__@  s   %%%rb\$)4:666JJrx(( 	" 	"DAqKK'''IIagaj!!!!JJ	 dOO 	$ 	$DAqDGbeO#DD			r   c                 "   | j         j        d         }|                    || j        f          }t	          j        |j        t	          j        | j         |                    }t          j                            |          \  }}| j	        |z  dz  }t          | j                  D ]j\  }}t	          j        |j        t	          j        ||                    }t          j                            |          \  }}|| j        |         |z  dz  z  }k|S )z
        Evaluate the log-likelihood

        Parameters
        ----------
        params : array_like
            The projection matrix used to reduce the covariances, flattened
            to 1d.

        Returns the log-likelihood.
        r   rg   )r   r   rU   r   r   r   r   r   slogdetr   r   r   r   )	r   rM   r[   projr   rb   ldetry   js	            r   loglikezCovarianceReduction.loglikeW  s     IOA~~q$(m,,F4626$)T2233)##A&&4Iq di(( 	' 	'DAqtvrva//Ai''**GAtd"Q&&AAr   c                    | j         j        d         }|                    || j        f          }t	          j        |j        t	          j        | j         |                    }t	          j        | j         |          }| j        t          j        	                    ||j                  j        z  }t          | j                  D ]\  }}t	          j        |j        t	          j        ||                    }t	          j        ||          }|| j        |         t          j        	                    ||j                  j        z  z  }|                                S )a  
        Evaluate the score function.

        Parameters
        ----------
        params : array_like
            The projection matrix used to reduce the covariances,
            flattened to 1d.

        Returns the score function evaluated at 'params'.
        r   )r   r   rU   r   r   r   r   r   r   r   r   r   r   rk   )	r   rM   r[   r   c0cPr   r   r   s	            r   scorezCovarianceReduction.scorer  s    IOA~~q$(m,,VDFBF49d3344VDIt$$I	BD1133di(( 	: 	:DAqq$00B4Bbioob"$77999AAwwyyr   N   -C6?c                       j         j        d         } j        }|6t          j        ||f          }t          j        |          |d|d|f<   |}n|}t          | fd fd||          \  }}}|dz  }|so                     |                                          }	t          j	        t          j
        |	|	z                      }
d|
z  }t          j        |t                     t           |d          }||_        t!          |          S )a  
        Fit the covariance reduction model.

        Parameters
        ----------
        start_params : array_like
            Starting value for the projection matrix. May be
            rectangular, or flattened.
        maxiter : int
            The maximum number of gradient steps to take.
        gtol : float
            Convergence criterion for the gradient norm.

        Returns
        -------
        A results instance that can be used to access the
        fitted parameters.
        r   Nc                 0                         |            S r   )r   r$   r   s    r   <lambda>z)CovarianceReduction.fit.<locals>.<lambda>  s    4<<??:J r   c                 0                         |            S r   )r   r   s    r   r   z)CovarianceReduction.fit.<locals>.<lambda>  s    4::a==. r   z/CovReduce optimization did not converge, |g|=%fr;   )r   r   r   r   rj   r   r   r   rk   r   rA   r>   r?   r   rC   llfrD   )r   r~   r   r   r[   r   rM   r   r   r   r   rF   rN   s   `            r   rO   zCovarianceReduction.fit  s#   ( IOAH Xq!f%%F!vayyF1Q3!8FF!F (0J0J0J0J(@(@(@(@'(,. .U 	r	 	3

6<<>>**AA''BCbHCM#1222%dF>>>)'222r   )Nr   r   )	r(   r)   r*   r+   r
   r   r   rO   r,   r-   s   @r   r   r     su        % %N    .  6  6-3 -3 -3 -3 -3 -3 -3 -3r   r   )r>   numpyr   pandasr   statsmodels.baser   statsmodels.base.wrapperbasewrapperwrapstatsmodels.tools.sm_exceptionsr   Modelr   r/   r   r   ResultsrC   ResultsWrapperrD   populate_wrapperr   r   SIRPHDr   COREr   r   r   <module>r      s            " " " " " " ' ' ' ' ' ' ' ' ' > > > > > >7 7 7 7 7ek 7 7 74`3 `3 `3 `3 `3. `3 `3 `3F>3 >3 >3 >3 >3!8 >3 >3 >3B^3 ^3 ^3 ^3 ^3&= ^3 ^3 ^3B    %-   &    !4     0)+ + +N N Nbb3 b3 b3 b3 b31 b3 b3 b3L  &r   