
    M/PhI                     X   d Z ddlZddlmc mZ ddlmc mZ	 ddl
mc mZ ddlmZmZ ddlZddlZddlZ G d dej                  Z G d de          Z G d d	e          Z G d
 dej                  Z G d de          Z G d de	j                  Z ej        ee           dS )zA
Conditional logistic, Poisson, and multinomial logit regression
    N)MultinomialResultsMultinomialResultsWrapperc                   t     e Zd Zd fd	Zd Z	 	 	 	 	 	 	 	 	 d fd
	Z	 	 	 	 ddZe	 	 d fd	            Z xZ	S )_ConditionalModelnonec                    d|vrt          d          |d         }|j        |j        k    rd}t          |          |j        d         |j        k    rd}t          |           t                      j        ||fd|i| | j        j        d}t          |          | j        }|j        d         | _        i }t          |          D ])\  }}	|	|vrg ||	<   ||	         
                    |           *t          j        |          t          j        |          }}|                    d	          }
g | _        g | _        g | _        |
t          j        |
          }
g | _        g | _        g | _        d| _        ddg}|                                D ])\  }	}||         j        }t          j        |          dk    r.|dxx         dz  cc<   |dxx         t1          |          z  cc<   Y| xj        t1          |          z  c_        | j        
                    |           |
 | j        
                    |
|                    | j        
                    t1          |                     | j        
                    ||d d f                    | j        
                    t          j        |                     +|d         dk    r&d
t5          |          z  }t7          j        |           |
Yg | _        t          | j                  D ]=\  }}| j        
                    t          j        | j        |         |                     >t1          | j                  | _        g | _         g | _!        tE          | j                  D ]|}	| j         
                    t          j        | j        |	         | j        |	                              | j!        
                    t          j        | j        |	                              }d S )Ngroups'groups' is a required argumentz4'endog' and 'groups' should have the same dimensionsr   zBThe leading dimension of 'exog' should equal the length of 'endog'missingzDConditional models should not have an intercept in the design matrix   offsetzIDropped %d groups and %d observations for having no within-group variance)#
ValueErrorsizeshapesuper__init__data	const_idxexogk_params	enumerateappendnpasarrayget
_endog_grp	_exog_grp
_groupsize_offset_grp_offset_sumynobsitemsflatstdlensumtuplewarningswarn_endofsdot	_n_groups_xy_n1range)selfendogr   r   kwargsr	   msgrow_ixigr   dropsixykofs	__class__s                   g/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/discrete/conditional_models.pyr   z_ConditionalModel.__init__   s   6!!>???!;%*$$HCS//!:a=EJ&&VCS//!4	4 	4!(	4,2	4 	4 	4 9*"CS//!y
1 f%% 	  	 DAqq	1IQ j''D)9)9tH%%Z''F!D
	A\\^^ 	) 	)EArb	AvayyA~~aAaCFF"IIQIIO""1%%%! ''r
333O""3q66***N!!$r111u+...JbfQii((((8a<<.16u>CM# DL#D$455 E E3##BF4?1+=s$C$CDDDD T_-- t~&& 	8 	8AHOOBF4?1#5t~a7HIIJJJHOOBF4?1#5667777	8 	8    c                 \    ddl m}  ||| j                  }t          j        |          }|S )Nr   )approx_fprime)statsmodels.tools.numdiffrA   scorer   
atleast_2d)r1   paramsrA   hesss       r>   hessianz_ConditionalModel.hessianb   s;    ;;;;;;}VTZ00}T""r?   NBFGSd   TF c
                    t                                          ||||||	          }t          | |j        |                                d          }||_        | j        |_        | j        |_        dt          | j
                  z  dt          | j
                  z  dt          j        | j
                  z  g|_        t          |          }|S )Nstart_paramsmethodmaxiterfull_outputdispskip_hessianr   z%dz%.1f)r   fitConditionalResultsrE   
cov_paramsrN   r"   r-   n_groupsminr   maxr   mean_group_statsConditionalResultsWrapper)r1   rM   rN   rO   rP   rQ   fargscallbackretallrR   r3   rsltcrsltr=   s                r>   rS   z_ConditionalModel.fiti   s     ww{{%#%  ' ' #4doo6G6GKKY
3t'''3t'''RWT_---

 )//r?   elastic_net        c                     ddl m} |dk    rt          d          ddddd}|                    |            || f||||d	|S )
a  
        Return a regularized fit to a linear regression model.

        Parameters
        ----------
        method : {'elastic_net'}
            Only the `elastic_net` approach is currently implemented.
        alpha : scalar or array_like
            The penalty weight.  If a scalar, the same penalty weight
            applies to all variables in the model.  If a vector, it
            must have the same length as `params`, and contains a
            penalty weight for each coefficient.
        start_params : array_like
            Starting values for `params`.
        refit : bool
            If True, the model is refit using only the variables that
            have non-zero coefficients in the regularized fit.  The
            refitted model is not regularized.
        **kwargs
            Additional keyword argument that are used when fitting the model.

        Returns
        -------
        Results
            A results instance.
        r   )fit_elasticnetra   z.method for fit_regularized must be elastic_net2   r   g|=)rO   L1_wt	cnvrg_tolzero_tol)rN   alpharM   refit)statsmodels.base.elastic_netrd   r   update)r1   rN   ri   rM   rj   r3   rd   defaultss           r>   fit_regularizedz!_ConditionalModel.fit_regularized   s    B 	@?????]""MNNN!AE %' '~d *6$)+7$)* * !)	* * 	*r?   c                 .   	 |d         }|d= n# t           $ r t          d          w xY wt          |t                    r||         }d|                    dd          vrt          j        d            t                      j        |g|R ||d|}|S )Nr	   r
   z0+  z2Conditional models should not include an intercept)r   r	   )	KeyErrorr   
isinstancestrreplacer)   r*   r   from_formula)
clsformular   subset	drop_colsargsr3   r	   modelr=   s
            r>   rv   z_ConditionalModel.from_formula   s    	@H%Fx   	@ 	@ 	@>???	@ fc"" 	"&\FwsB////MNOOO$$@04@ @v@ @8>@ @ s    )r   	NrH   rI   TFrJ   NFF)ra   rb   NF)NN)
__name__
__module____qualname__r   rG   rS   rn   classmethodrv   __classcell__r=   s   @r>   r   r      s        N8 N8 N8 N8 N8 N8`        B  - %)#	.* .* .* .*b  !#	     [    r?   r   c                   L     e Zd ZdZd fd	Zd Zd ZddZddZd	 Z	d
 Z
 xZS )ConditionalLogita  
    Fit a conditional logistic regression model to grouped data.

    Every group is implicitly given an intercept, but the model is fit using
    a conditional likelihood in which the intercepts are not present.  Thus,
    intercept estimates are not given, but the other parameter estimates can
    be interpreted as being adjusted for any group-level confounders.

    Parameters
    ----------
    endog : array_like
        The response variable, must contain only 0 and 1.
    exog : array_like
        The array of covariates.  Do not include an intercept
        in this array.
    groups : array_like
        Codes defining the groups. This is a required keyword parameter.
    r   c                     t                      j        ||fd|i| t          j        t          j        | j                  t          j        d         k              rd}t          |          | j        j	        d         | _
        d S )Nr   )r   r   zendog must be coded as 0, 1r   )r   r   r   anyuniquer2   r_r   r   r   K)r1   r2   r   r   r3   r4   r=   s         r>   r   zConditionalLogit.__init__   s    4	4 	4!(	4,2	4 	4 	4 6")DJ''25;677 	"/CS//!#r?   c                     d}t          t          | j                            D ]}||                     ||          z  }|S Nr   )r0   r&   r   loglike_grp)r1   rE   llr7   s       r>   loglikezConditionalLogit.loglike   sI    s4?++,, 	. 	.A$""1f---BB	r?   c                 j    d}t          | j                  D ]}||                     ||          z  }|S r   )r0   r-   	score_grp)r1   rE   rC   r7   s       r>   rC   zConditionalLogit.score   s?    t~&& 	/ 	/AT^^Av...EEr?   Nc                     |d}t          j        t          j        | j        |         |          |z             i fd | j        |         | j        |                   S )Nr   c                     | |k     rdS |dk    rdS 	 | |f         S # t           $ r Y nw xY w | dz
  |           | dz
  |dz
            | dz
           z  z   }|| |f<   |S )Nr   r   )rr   )tr;   vexbfmemos      r>   r   z"ConditionalLogit._denom.<locals>.f  s    1uuqAvvqQF|#    !a%aaAq1uooAE
::AD!QLHs   	 
**)r   expr,   r   r   r/   )r1   grprE   r<   r   r   r   s       @@@r>   _denomzConditionalLogit._denom  s    ;CfRVDN3/883>?? 	 	 	 	 	 	 	  q%tx}555r?   c                      |d} j         |         t          j        t          j        |          |z             i  fd  j        |          j        |                   S )Nr   c                 Z   | |k     rdt          j        j                  fS |dk    rdS 	 | |f         S # t          $ r Y nw xY w| dz
           } | dz
  |          \  }} | dz
  |dz
            \  }}||z  
| dz
  d d f         z  }|||z  z   ||z   ||z  z   }	}||	f| |f<   ||	fS )Nr   )r   r   r   )r   zerosr   rr   )r   r;   habcedur   exr   r   sr1   s             r>   r   z'ConditionalLogit._denom_grad.<locals>.s.  s    1uu"(4=1111AvvtQF|#    AE
A1QUA;;DAq1QUAE??DAqA1q5!!!8$Aq1u9a!ea!emqAq6D!QLa4Ks   	6 
AA)r   r   r   r,   r   r/   )r1   r   rE   r<   r   r   r   r   s   `   @@@@r>   _denom_gradzConditionalLogit._denom_grad"  s    ;C^C fRVB''#-.. 	 	 	 	 	 	 	 	 	, q%tx}555r?   c                     d }t          | d          r| j        |         }t          j        | j        |         |          }||| j        |         z  }|t          j        |                     |||                    z  }|S )Nr   )hasattrr   r   r,   r.   r+   logr   )r1   r   rE   r<   llgs        r>   r   zConditionalLogit.loglike_grpF  s|    4"" 	("3'CfTXc]F++?4<$$Crvdkk#vs33444
r?   c                     d}t          | d          r| j        |         }|                     |||          \  }}| j        |         ||z  z
  S )Nr   r   )r   r   r   r.   )r1   r   rE   r<   r   r   s         r>   r   zConditionalLogit.score_grpU  sV    4"" 	("3'CVS111x}q1u$$r?   r}   )N)r   r   r   __doc__r   r   rC   r   r   r   r   r   r   s   @r>   r   r      s         &	$ 	$ 	$ 	$ 	$ 	$    6 6 6 6:"6 "6 "6 "6H  % % % % % % %r?   r   c                       e Zd ZdZd Zd ZdS )ConditionalPoissonaU  
    Fit a conditional Poisson regression model to grouped data.

    Every group is implicitly given an intercept, but the model is fit using
    a conditional likelihood in which the intercepts are not present.  Thus,
    intercept estimates are not given, but the other parameter estimates can
    be interpreted as being adjusted for any group-level confounders.

    Parameters
    ----------
    endog : array_like
        The response variable
    exog : array_like
        The covariates
    groups : array_like
        Codes defining the groups. This is a required keyword parameter.
    c                    d }t          | d          r| j        }d}t          t          | j                            D ]}t          j        | j        |         |          }||||         z  }t          j        |          }| j        |         }|t          j        ||          z  }|	                                }|| j
        |         t          j        |          z  z  }|S Nr   rb   )r   r   r0   r&   r   r   r,   r   r   r'   r!   r   )	r1   rE   r<   r   r6   xbr   r:   r   s	            r>   r   zConditionalPoisson.logliker  s    4"" 	#"Cs4?++,, 		, 		,Aq)622Bc!f&**C"A"&B--B		A$*Q-"&))++BB	r?   c                    d }t          | d          r| j        }d}t          t          | j                            D ]}| j        |         }t          j        ||          }||||         z  }t          j        |          }|	                                }| j        |         }	|t          j        |	|          z  }|| j
        |         t          j        ||          z  |z  z  }|S r   )r   r   r0   r&   r   r   r   r,   r   r'   r!   )
r1   rE   r<   rC   r6   xr   r   r   r:   s
             r>   rC   zConditionalPoisson.score  s    4"" 	#"Cs4?++,, 
	8 
	8Aq!A6""Bc!f&**C		A"ARVAq\\!ETZ]RVC^^3a77EEr?   N)r   r   r   r   r   rC   rJ   r?   r>   r   r   _  s<         $  *    r?   r   c                   &     e Zd Z fdZddZ xZS )rT   c                 R    t                                          ||||           d S )N)normalized_cov_paramsscale)r   r   )r1   r|   rE   r   r   r=   s        r>   r   zConditionalResults.__init__  s:    "7	 	 	 	 	 	 	r?   N皙?c                 4   dddd| j         gfddg}dd| j        gfd	| j        d
         gfd| j        d         gfd| j        d         gfg}|d}d
dlm}  |            }|                    | |||||           |                    | |||| j                   |S )a<  
        Summarize the fitted model.

        Parameters
        ----------
        yname : str, optional
            Default is `y`
        xname : list[str], optional
            Names for the exogenous variables, default is "var_xx".
            Must match the number of parameters in the model
        title : str, optional
            Title for the top table. If not None, then this replaces the
            default title
        alpha : float
            Significance level for the confidence intervals

        Returns
        -------
        smry : Summary instance
            This holds the summary tables and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary : class to hold summary
            results
        )zDep. Variable:N)zModel:N)zLog-Likelihood:NzMethod:)zDate:N)zTime:N)zNo. Observations:NzNo. groups:zMin group size:r   zMax group size:r   zMean group size:   Nz*Conditional Logit Model Regression Results)Summary)gleftgrightynamexnametitle)r   r   ri   use_t)rN   rV   rZ   statsmodels.iolib.summaryr   add_table_2colsadd_table_paramsr   )	r1   r   r   r   ri   top_left	top_rightr   smrys	            r>   summaryzConditionalResults.summary  s   < %%&
 (T]O,!21!5 67!21!5 67$"3A"6!78
	 =@E 	655555wyy 	 	 	 	 	U%tz 	 	K 	K 	K r?   )NNNr   )r   r   r   r   r   r   r   s   @r>   rT   rT     sL            > > > > > > > >r?   rT   c                   J     e Zd ZdZd fd	Z	 	 	 	 	 	 	 	 	 dd
Zd Zd Z xZS )ConditionalMNLogita  
    Fit a conditional multinomial logit model to grouped data.

    Parameters
    ----------
    endog : array_like
        The dependent variable, must be integer-valued, coded
        0, 1, ..., c-1, where c is the number of response
        categories.
    exog : array_like
        The independent variables.
    groups : array_like
        Codes defining the groups. This is a required keyword parameter.

    Notes
    -----
    Equivalent to femlogit in Stata.

    References
    ----------
    Gary Chamberlain (1980).  Analysis of covariance with qualitative
    data. The Review of Economic Studies.  Vol. 47, No. 1, pp. 225-238.
    r   c                 l    t                      j        ||fd|i| | j                            t                    | _        | j                                        dz   | _        | j        dz
  | j        j        d         z  | _	        | j
        | j	        z
  | _        d t          | j                  D             | _        | j        | _        | j        j        d         | _        | j                                        dk     rd}t#          |          t%          j        t(                    t+          | j                  D ] \  }}|                             |           !t)                                                    | _        | j                                         fd| j        D             | _        d S )Nr   r   c                 .    i | ]}|t          |          S rJ   )rt   ).0js     r>   
<dictcomp>z/ConditionalMNLogit.__init__.<locals>.<dictcomp>  s     AAA!As1vvAAAr?   r   z%endog may not contain negative valuesc                      g | ]
}|         S rJ   rJ   )r   r;   grxs     r>   
<listcomp>z/ConditionalMNLogit.__init__.<locals>.<listcomp>  s    ;;;1A;;;r?   )r   r   r2   astypeintrX   k_catr   r   df_modelr"   df_residr0   _ynames_mapJr   rW   r   collectionsdefaultdictlistr   r	   r   keys_group_labelssort_grp_ix)
r1   r2   r   r   r3   r4   r;   r   r   r=   s
           @r>   r   zConditionalMNLogit.__init__   s   4	4 	4!(	4,2	4 	4 	4 Z&&s++
Z^^%%)
a49?1+==	DM1AAuTZ/@/@AAA#:>>a9CS//!%d++dk** 	 	DAqFMM!!#((**--!!!;;;;(:;;;r?   NrH   rI   TFrJ   c
           	         |?| j         j        d         }| j        dz
  }t          j                            ||z            }t          j                            | ||||||	          }|j	        
                    | j         j        d         df          |_	        t          | |          }|                    t          j                   t          |          S )Nr   )r   rL   )llnull)r   r   r   r   randomnormalbaseLikelihoodModelrS   rE   reshaper   set_null_optionsnanr   )r1   rM   rN   rO   rP   rQ   r\   r]   r^   rR   r3   qr   r_   s                 r>   rS   zConditionalMNLogit.fit  s     	"A
QA9++Q+77L #''%#% ( ' ' k))49?1+=r*BCC!$--
 	RV,,,(...r?   c                    | j         j        d         }| j        dz
  }|                    ||f          }t	          j        t	          j        |df          |fd          }t	          j        | j         |          }d}| j        D ]}||d d f         }t	          j	        |j        d         t                    }	| j        |         }
d}t          j        |
          D ]3}|t	          j        ||	|f                                                   z  }4|||	|
f                                         t	          j        |          z
  z  }|S )Nr   axisrb   r   dtype)r   r   r   r   r   concatenater   r,   r   aranger   r2   	itertoolspermutationsr   r'   r   )r1   rE   r   r   pmatlprr   iir   jjr:   denomps                r>   r   zConditionalMNLogit.loglike?  s-   IOAJN~~q!f%%~rxA//6Q???fTY%%, 	3 	3BBE
A171:S111B
2AE+A.. 2 22q'
 0 0111!RG*..""RVE]]22BB	r?   c                    | j         j        d         }| j        dz
  }|                    ||f          }t	          j        t	          j        |df          |fd          }t	          j        | j         |          }t	          j        ||f          }| j        D ]=}||d d f         }t	          j	        |j        d         t                    }	| j        |         }
d}t	          j        ||f          }t          j        |
          D ]}t	          j        ||	|f                                                   }||z  }t!          |          D ]:\  }}|dk    r/|d d |dz
  fxx         || j         ||         d d f         z  z  cc<   ;t!          |
          D ]7\  }}|dk    r,|d d |dz
  fxx         | j         ||         d d f         z  cc<   8|||z  z  }?|                                S )Nr   r   r   r   rb   )r   r   r   r   r   r   r   r,   r   r   r   r2   r   r   r   r'   r   flatten)r1   rE   r   r   r   r   gradr   r   r   r:   r   denomgr   r   r6   rs                    r>   rC   zConditionalMNLogit.scoreU  s   IOAJN~~q!f%%~rxA//6Q???fTY%%xA, 	# 	#BBE
A171:S111B
2AEXq!f%%F+A.. D DF1b!W:>>++,,
%aLL D DDAqAvvqqq!a%x(((A	"Q%(0C,CC(((D "! : :166AENNNdi1qqq&99NNNFUN"DD||~~r?   r}   r~   )	r   r   r   r   r   rS   r   rC   r   r   s   @r>   r   r     s         0< < < < < <6 #/ #/ #/ #/J  ,      r?   r   c                       e Zd ZdS )r[   N)r   r   r   rJ   r?   r>   r[   r[   v  s        Dr?   r[   )r   numpyr   statsmodels.base.modelr   r|   #statsmodels.regression.linear_model
regressionlinear_modellmstatsmodels.base.wrapperwrapperwrap#statsmodels.discrete.discrete_modelr   r   r   r)   r   r   r   r   r   LikelihoodModelResultsrT   r   RegressionResultsWrapperr[   populate_wrapperrJ   r?   r>   <module>r     s        % % % % % % % % % 0 0 0 0 0 0 0 0 0 ' ' ' ' ' ' ' ' '! ! ! ! ! ! ! !         B B B B B, B B BJG% G% G% G% G%( G% G% G%T< < < < <* < < <~G G G G G4 G G GRK K K K K* K K K^	 	 	 	 	 ; 	 	 	  /1C D D D D Dr?   