
    M/Ph                       d Z g dZddlmZ ddlZddlZddlmZm	Z	 ddl
mZmZ ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmc mZ ddlmc mZ ddlmZ ddl mc m!Z" ddl#m$Z% ddl&m'Z' ddl(m)c m*Z+ ddl,m-Z.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7 	 ddl8Z8dZ9n# e:$ r dZ9Y nw xY w ej;        e<          j=        Z> ej?         ej;        ej@                  jA                  dz
  ZBdZCdZDdZEdZFdZGd ZHd ZId ZJ G d dejK                  ZL G d d eL          ZM G d! d"eM          ZN G d# d$eL          ZO G d% d&eO          ZP G d' d(eO          ZQ G d) d*eM          ZR G d+ d,eM          ZS G d- d.eN          ZT G d/ d0eO          ZU G d1 d2eO          ZV G d3 d4ejW                  ZX G d5 d6eX          ZY G d7 d8eY          ZZ G d9 d:eZ          Z[ G d; d<eZ          Z\ G d= d>eX          Z] G d? d@eY          Z^ G dA dBe]e^          Z_ G dC dDe]eZ          Z` G dE dFe]e\          Za G dG dHeX          Zb G dI dJeX          Zc G dK dLec          Zd G dM dNec          Ze G dO dPec          Zf G dQ dReX          Zg G dS dTeg          Zh G dU dVe+ji                  Zj ejk        ejeb            G dW dXe+ji                  Zl ejk        eleY            G dY dZe+ji                  Zm ejk        emeZ            G d[ d\e+ji                  Zn ejk        ene[            G d] d^e+ji                  Zo ejk        eoe\            G d_ d`e+ji                  Zp ejk        epe^            G da dbe+ji                  Zq G dc dde+ji                  Zr ejk        ere_            G de dfe+ji                  Zs ejk        ese`            G dg dhe+ji                  Zt ejk        etea            G di dje+ji                  Zu ejk        euec            G dk dle+ji                  Zv ejk        evef            G dm dne+ji                  Zw ejk        eweg            G do dpe+ji                  Zx ejk        exeh           dS )qa  
Limited dependent variable and qualitative variables.

Includes binary outcomes, count data, (ordered) ordinal data and limited
dependent variables.

General References
--------------------

A.C. Cameron and P.K. Trivedi.  `Regression Analysis of Count Data`.
    Cambridge, 1998

G.S. Madalla. `Limited-Dependent and Qualitative Variables in Econometrics`.
    Cambridge, 1983.

W. Greene. `Econometric Analysis`. Prentice Hall, 5th. edition. 2003.
)PoissonLogitProbitMNLogitNegativeBinomialGeneralizedPoissonNegativeBinomialP
CountModel    )AppenderN)
MultiIndexget_dummies)specialstats)digammagammalnloggamma	polygamma)nbinom)handle_data)fit_l1_slsqpfit_constrained_wrap)_prediction_inference)genpoisson_p)datatools)cache_readonly)approx_fprime_cs)PerfectSeparationErrorPerfectSeparationWarningSpecificationWarningTF      ?
a  
    %(one_line_description)s

    Parameters
    ----------
    model : A DiscreteModel instance
    params : array_like
        The parameters of a fitted model.
    hessian : array_like
        The hessian of the fitted model.
    scale : float
        A scale parameter for the covariance matrix.

    Attributes
    ----------
    df_resid : float
        See model definition.
    df_model : float
        See model definition.
    llf : float
        Value of the loglikelihood
    %(extra_attr)sa      nnz_params : int
        The number of nonzero parameters in the model.  Train with
        trim_params == True or else numerical error will distort this.
    trimmed : bool array
        trimmed[i] == True if the ith parameter was trimmed from the model.z
Compute one-step moment estimator for null (constant-only) model

This is a preliminary estimator used as start_params.

Returns
-------
params : ndarray
    parameter estimate based one one-step moment matching

z
    check_rank : bool
        Check exog rank to determine model degrees of freedom. Default is
        True. Setting to False reduces model initialization time when
        exog.shape[1] is large.
    c                 $   | j         dk    r+| j        j        dvr| }t          | j        d                   }nVt          | d          fdt          j        d                   D             }t          j        t                    }||fS ||fS )N   )SO   F)
drop_firstc                 ,    i | ]}|j         |         S  )columns).0idummiess     c/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/discrete/discrete_model.py
<dictcomp>z%_numpy_to_dummies.<locals>.<dictcomp>~   s"    IIIA!W_Q'III    dtype)	ndimr4   kindrangeshaper   npasarrayfloat)endogendog_dummiesynamesr/   s      @r0   _numpy_to_dummiesr?   x   s    zQ5;+:==u{1~&&e666IIIIw}Q7G1H1HIII
7%888f$$&  r2   c                    | j         dk    rB| j        d         dk    r,| j        d         }t          | j        d d df                   }nd}| }n| j        }|d}t          |           }|j                                        }|||fS )Nr%   r(   r
   y)r5   r8   r,   r   ilocnametolist)r<   ynamer=   r>   s       r0   _pandas_to_dummiesrF      s    zQ;q>QM!$E'
111a4(899MME!MM
=E#E**"))++F&%''r2   c                 T    | dvr#t          d                    |                     dS )a  
    As of 0.10.0, the supported values for `method` in `fit_regularized`
    are "l1" and "l1_cvxopt_cp".  If an invalid value is passed, raise
    with a helpful error message

    Parameters
    ----------
    method : str

    Raises
    ------
    ValueError
    )l1l1_cvxopt_cpzG`method` = {method} is not supported, use either "l1" or "l1_cvxopt_cp"methodN)
ValueErrorformatrJ   s    r0   _validate_l1_methodrN      sA     +++ 228&&2G2GI I 	I ,+r2   c                        e Zd ZdZd fd	Zd Zd Zd Zd Z e	e
j        j        j                  	 	 d fd	            Z	 	 	 	 	 d fd	Zd ZddZ	 	 ddZd Z xZS ) DiscreteModelz
    Abstract class for discrete choice models.

    This class does not do anything itself but lays out the methods and
    call signature expected of child classes in addition to those of
    statsmodels.model.LikelihoodModel.
    Tc                 h    || _          t                      j        ||fi | d| _        d| _        d S )NFr
   )_check_ranksuper__init__raise_on_perfect_predictionk_extra)selfr<   exog
check_rankkwargs	__class__s        r0   rT   zDiscreteModel.__init__   s?    %/////+0(r2   c                     | j         rt          j        | j        d          }n| j        j        d         }t          |dz
            | _        t          | j        j        d         |z
            | _        dS )z
        Initialize is called by
        statsmodels.model.LikelihoodModel.__init__
        and should contain any preprocessing that needs to be done for a model.
        qrrJ   r(   r
   N)rR   r   matrix_rankrX   r8   r;   df_modeldf_resid)rW   ranks     r0   
initializezDiscreteModel.initialize   sj      	&$TYt<<<DD 9?1%DdQhdioa04788r2   c                     t           )zD
        The cumulative distribution function of the model.
        NotImplementedErrorrW   Xs     r0   cdfzDiscreteModel.cdf   
     "!r2   c                     t           )zG
        The probability density (mass) function of the model.
        rd   rf   s     r0   pdfzDiscreteModel.pdf   ri   r2   c                     | j         }|                     |          }t          j        ||z
  d          r7| j        rd}t          |          d}t          j        |t                     d S d S )Nr
   z2Perfect separation detected, results not availablezJPerfect separation or prediction detected, parameter may not be identified)category)	r<   predictr9   allcloserU   r   warningswarnr    )rW   paramsargsr<   fittedvaluesmsgs         r0   _check_perfect_predz!DiscreteModel._check_perfect_pred   s    
||F++;|e+Q// 	F/ FJ,S1119c,DEEEEEE	F 	Fr2   Nnewton#   r(   c           
      ^    || j         }n	  t                      j        d||||||d|}|S )z
        Fit the model using maximum likelihood.

        The rest of the docstring is from
        statsmodels.base.model.LikelihoodModel.fit
        Nstart_paramsrK   maxiterfull_outputdispcallbackr+   )rv   rS   fit)
rW   r{   rK   r|   r}   r~   r   rZ   mlefitr[   s
            r0   r   zDiscreteModel.fit   s[     /HH ',$*%,)4"&&.' '  &' ' r2   rH   defined_by_methodr
   auto{Gz?-C6?Q?Fc                    t          |           | j        }t          j        |          }|                                dk    sJ 	 ||d<   n # t
          $ r t          |          }Y nw xY w|d         t          | j        j	        d                   z  |d<   ||d<   |
|d<   |	|d<   ||d<   ||d	<   |d
k    r|dk    rd}n|dk    rd}dt          i}t          r|dk    rddlm} ||d<   n'|                                dk    rt          d          || j        }n	  t#                      j        d||||||||d|}|S )a:  
        Fit the model using a regularized maximum likelihood.

        The regularization method AND the solver used is determined by the
        argument method.

        Parameters
        ----------
        start_params : array_like, optional
            Initial guess of the solution for the loglikelihood maximization.
            The default is an array of zeros.
        method : 'l1' or 'l1_cvxopt_cp'
            See notes for details.
        maxiter : {int, 'defined_by_method'}
            Maximum number of iterations to perform.
            If 'defined_by_method', then use method defaults (see notes).
        full_output : bool
            Set to True to have all available output in the Results object's
            mle_retvals attribute. The output is dependent on the solver.
            See LikelihoodModelResults notes section for more information.
        disp : bool
            Set to True to print convergence messages.
        fargs : tuple
            Extra arguments passed to the likelihood function, i.e.,
            loglike(x,*args).
        callback : callable callback(xk)
            Called after each iteration, as callback(xk), where xk is the
            current parameter vector.
        retall : bool
            Set to True to return list of solutions at each iteration.
            Available in Results object's mle_retvals attribute.
        alpha : non-negative scalar or numpy array (same size as parameters)
            The weight multiplying the l1 penalty term.
        trim_mode : 'auto, 'size', or 'off'
            If not 'off', trim (set to zero) parameters that would have been
            zero if the solver reached the theoretical minimum.
            If 'auto', trim params using the Theory above.
            If 'size', trim params if they have very small absolute value.
        size_trim_tol : float or 'auto' (default = 'auto')
            Tolerance used when trim_mode == 'size'.
        auto_trim_tol : float
            Tolerance used when trim_mode == 'auto'.
        qc_tol : float
            Print warning and do not allow auto trim when (ii) (above) is
            violated by this much.
        qc_verbose : bool
            If true, print out a full QC report upon failure.
        **kwargs
            Additional keyword arguments used when fitting the model.

        Returns
        -------
        Results
            A results instance.

        Notes
        -----
        Using 'l1_cvxopt_cp' requires the cvxopt module.

        Extra parameters are not penalized if alpha is given as a scalar.
        An example is the shape parameter in NegativeBinomial `nb1` and `nb2`.

        Optional arguments for the solvers (available in Results.mle_settings)::

            'l1'
                acc : float (default 1e-6)
                    Requested accuracy as used by slsqp
            'l1_cvxopt_cp'
                abstol : float
                    absolute accuracy (default: 1e-7).
                reltol : float
                    relative accuracy (default: 1e-6).
                feastol : float
                    tolerance for feasibility conditions (default: 1e-7).
                refinement : int
                    number of iterative refinement steps when solving KKT
                    equations (default: 1).

        Optimization methodology

        With :math:`L` the negative log likelihood, we solve the convex but
        non-smooth problem

        .. math:: \min_\beta L(\beta) + \sum_k\alpha_k |\beta_k|

        via the transformation to the smooth, convex, constrained problem
        in twice as many variables (adding the "added variables" :math:`u_k`)

        .. math:: \min_{\beta,u} L(\beta) + \sum_k\alpha_k u_k,

        subject to

        .. math:: -u_k \leq \beta_k \leq u_k.

        With :math:`\partial_k L` the derivative of :math:`L` in the
        :math:`k^{th}` parameter direction, theory dictates that, at the
        minimum, exactly one of two conditions holds:

        (i) :math:`|\partial_k L| = \alpha_k`  and  :math:`\beta_k \neq 0`
        (ii) :math:`|\partial_k L| \leq \alpha_k`  and  :math:`\beta_k = 0`
        r
   alphar   alpha_rescaled	trim_modesize_trim_tolauto_trim_tolqc_tol
qc_verboser   rH   i  rI   F   )fit_l1_cvxopt_cpzXCannot use l1_cvxopt_cp as cvxopt was not found (install it, or use method='l1' instead)N)r{   rK   r|   r}   r~   r   extra_fit_funcscov_params_funcr+   )rN   cov_params_func_l1r9   arraymin	TypeErrordictr;   r<   r8   r   have_cvxoptstatsmodels.base.l1_cvxoptr   lowerrL   rv   rS   r   )rW   r{   rK   r|   r}   r~   r   r   r   r   r   r   r   rZ   r   r   r   r   r[   s                     r0   fit_regularizedzDiscreteModel.fit_regularized   s   T 	F###1
 yy{{a	'#F7OO 	' 	' 	'&&&FFF	'#)'?U4:;KA;N5O5O#O '{"/"/!x)| )))~~>))
  . 	W6^33CCCCCC.>ON++\\^^~-- V W W W /HH ',$*%,)4"&&.-<-<' '  &' ' s   A A*)A*c                    |                     |          }|d         }t          j        |           d         }|                                 }|dk    r5||dddf         |f         }t          j                            |           }	nt          j        d          }	t          j        t          j        |j	                  z  }
|	|
|dddf         |f<   |
S )a  
        Computes cov_params on a reduced parameter space
        corresponding to the nonzero parameters resulting from the
        l1 regularized fit.

        Returns a full cov_params matrix, with entries corresponding
        to zero'd values set to np.nan.
        trimmedr
   N)
hessianr9   nonzerosumlinalginvzerosnanonesr8   )rW   likelihood_modelxoptretvalsHr   nz_idx
nnz_paramsH_restrictedH_restricted_inv
cov_paramss              r0   r   z DiscreteModel.cov_params_func_l1  s     $$T**)$WH%%a(h^^%%
>>VAAAtG_f45L!y}}l];;!x{{Vbgag...
.>
6!!!T'?F*+r2   meanc                     t           )zQ
        Predict response variable of a model given exogenous variables.
        rd   )rW   rr   rX   whichlinears        r0   rn   zDiscreteModel.predict  ri   r2   c                     t           )zQ
        This should implement the derivative of the non-linear function
        rd   )rW   rr   rX   	dummy_idx	count_idxs        r0   _derivative_exogzDiscreteModel._derivative_exog  s
    
 "!r2   c                 ^    ddl m}m} | |||||| |          }| |||||| |          }|S )zK
        Helper for _derivative_exog to wrap results appropriately
        r(   )_get_count_effects_get_dummy_effects)discrete_marginsr   r   )	rW   margeffrr   rX   r   r   	transformr   r   s	            r0   _derivative_exog_helperz%DiscreteModel._derivative_exog_helper  sn    
 	MLLLLLLL (($	9)-v7 7G (($	9)-v7 7G r2   TNrw   rx   r(   r(   N)NrH   r   r(   TNr
   r   r   r   r   FNr   NNNN)__name__
__module____qualname____doc__rT   rb   rh   rk   rv   r   baseLikelihoodModelr   r   r   rn   r   r   __classcell__r[   s   @r0   rP   rP      sO             9 9 9" " "" " "F F F Xd"&.//>@,0     0/. 9=IM:@GK#(	_ _ _ _ _ _B  2" " " " =A#'" " " "      r2   rP   c                        e Zd ZdZd fd	Z	 	 ddZ eej        j	                  	 	 	 	 d fd	            ZddZ
ej	        e
_	        	 	 ddZ	 	 ddZd ZddZ xZS )BinaryModelFNTc                    |                      |            t                      j        ||f||d| t          | j        t
                    s8t          j        | j        dk    | j        dk    z            st          d          |Zt          | d           | j        sEt          j        | j        t          j        | j                  k              rt          d          d S d S d S )N)offsetrY   r
   r(   z#endog must be in the unit interval.r   z#endog must be binary, either 0 or 1)_check_kwargsrS   rT   
issubclassr[   MultinomialModelr9   allr<   rL   delattr_continuous_okanyround)rW   r<   rX   r   rY   rZ   r[   s         r0   rT   zBinaryModel.__init__  s
   6""" 	#V
 	# 	#!	# 	# 	#$.*:;; 	H64:?tzQ?@@ H !FGGG>D(###' HF4:$*)=)==>>H !FGGG >H H H Hr2   r   c                 z   |"d}t          j        |t                     |du rd}||t          | d          r| j        }n|d}|| j        }t          j        ||          |z   }|dk    r|                     |          S |dk    r|S |dk    r|                     |          }|d	|z
  z  }	|	S t          d
          )a  
        Predict response variable of a model given exogenous variables.

        Parameters
        ----------
        params : array_like
            Fitted parameters of the model.
        exog : array_like
            1d or 2d array of exogenous values.  If not supplied, the
            whole exog attribute of the model is used.
        which : {'mean', 'linear', 'var', 'prob'}, optional
            Statistic to predict. Default is 'mean'.

            - 'mean' returns the conditional expectation of endog E(y | x),
              i.e. exp of linear predictor.
            - 'linear' returns the linear predictor of the mean function.
            - 'var' returns the estimated variance of endog implied by the
              model.

            .. versionadded: 0.14

               ``which`` replaces and extends the deprecated ``linear``
               argument.

        linear : bool
            If True, returns the linear predicted values.  If False or None,
            then the statistic specified by ``which`` will be returned.

            .. deprecated: 0.14

               The ``linear` keyword is deprecated and will be removed,
               use ``which`` keyword instead.

        Returns
        -------
        array
            Fitted values at exog.
        N0linear keyword is deprecated, use which="linear"Tr   r           r   varr(   z8Only `which` is "mean", "linear" or "var" are available.)
rp   rq   FutureWarninghasattrr   rX   r9   dotrh   rL   )
rW   rr   rX   r   r   r   ru   linpredmuvar_s
             r0   rn   zBinaryModel.predict  s    P DCM#}---~~  >dlwtX/F/Fl[FF^F<9D&v&&/F??88G$$$hNE>>'""BR=DK + , , ,r2   rH   r   r(   r
   r   r   r   r   c                     t          |            t                      j        d|||||||||	|
|d|}t          | |          }t	          |          S Nr{   rK   r|   r}   r~   r   r   r   r   r   r   r+   )rN   rS   r   L1BinaryResultsL1BinaryResultsWrapper)rW   r{   rK   r|   r}   r~   r   r   r   r   r   r   rZ   bnryfitdiscretefitr[   s                  r0   r   zBinaryModel.fit_regularized-  s~     	F###)%'') 4|17296A/33;054=8E8E174 4 -34 4 &dG44%k222r2   c                 &    t          | |fdd i|}|S )Nr{   r   )rW   constraintsr{   fit_kwdsress        r0   fit_constrainedzBinaryModel.fit_constrainedE  s.    "4 / /4 /%-/ /
r2   dydxc                     || j         }|                     |||d          }|                     |          dddf         |z  }d|v r%||                     |||          dddf         z  }|S )}  
        For computing marginal effects standard errors.

        This is used only in the case of discrete and count regressors to
        get the variance-covariance of the marginal effects. It returns
        [d F / d params] where F is the predict.

        Transform can be 'dydx' or 'eydx'. Checking is done in margeff
        computations for appropriate transform.
        Nr   r   r   eyr   )rX   rn   rk   )rW   rr   rX   r   r   r   dFs          r0   _derivative_predictzBinaryModel._derivative_predictM  s     <9D,,vtF(,KKXXgqqqv&-9$,,vtF,;;AAAdFCCB	r2   c                 R   || j         }|                     |||d          }t          j        |                     |          dddf         |dddf                   }d|v r||z  }d|v r#||                     ||          dddf         z  }|                     ||||||          S )a;  
        For computing marginal effects returns dF(XB) / dX where F(.) is
        the predicted probabilities

        transform can be 'dydx', 'dyex', 'eydx', or 'eyex'.

        Not all of these make sense in the presence of discrete regressors,
        but checks are done in the results in get_margeff.
        Nr   r   exr   )rX   rn   r9   r   rk   r   )	rW   rr   rX   r   r   r   r   r   r   s	            r0   r   zBinaryModel._derivative_exoga  s     <9D,,vtF(,KK&'**111T62QQQ) ) 9tOG9t||FD11!!!T'::G++GVT,5y)M M 	Mr2   c                     | j         }|                     |d          }|                    |          }| j        |dddf         z  }|S )M  
        Derivative of the expected endog with respect to the parameters.

        Parameters
        ----------
        params : ndarray
            parameter at which score is evaluated

        Returns
        -------
        The value of the derivative of the expected endog with respect
        to the parameter vector.
        r   r   N)linkrn   inverse_derivrX   )rW   rr   r   lin_predidldmats         r0   _deriv_mean_dparamszBinaryModel._deriv_mean_dparams}  sP     y<<h<77  **y3qqq$w<'r2   c                 ^    |                      |||          }t          j        |          }|S )a4  Get frozen instance of distribution based on predicted parameters.

        Parameters
        ----------
        params : array_like
            The parameters of the model.
        exog : ndarray, optional
            Explanatory variables for the main count model.
            If ``exog`` is None, then the data from the model will be used.
        offset : ndarray, optional
            Offset is added to the linear predictor of the mean function with
            coefficient equal to 1.
            Default is zero if exog is not None, and the model offset if exog
            is None.
        exposure : ndarray, optional
            Log(exposure) is added to the linear predictor  of the mean
            function with coefficient equal to 1. If exposure is specified,
            then it will be logged by the method. The user does not need to
            log it first.
            Default is one if exog is is not None, and it is the model exposure
            if exog is None.

        Returns
        -------
        Instance of frozen scipy distribution.
        )rX   r   )rn   r   	bernoulli)rW   rr   rX   r   r   distrs         r0   get_distributionzBinaryModel.get_distribution  s/    6 \\&tF\;;##r2   NT)Nr   NNNrH   r   r(   r(   Nr
   r   r   r   r   N)Nr   N)Nr   NNNNN)r   r   r   r   rT   rn   r   rP   r   r   r   r   r   r   r   r  r   r   s   @r0   r   r     s0       NH H H H H H  ?CC, C, C, C,J Xm+3448<IMIM3 3 3 3 3 543.    3:O?E#'   ( =C@DM M M M8  (       r2   r   c                        e Zd Zd Z fdZd fd	Z eej        j	                  	 	 dd	            Z eej
        j	                  	 	 	 	 dd            Z
ddZ	 	 ddZddZ xZS )r   c                 z   t          j        |d           rt          |          \  }}d}nQt          j        |d           rt	          |          \  }}}n(t          j        |          }t          |          \  }}d}t          |t                    s5t          t          t          |j        d                   |                    }|| _        t          ||||fi |}	||	_        ||	_        |	j        | _        |D ]A}
|
dv r	 t%          | |
|	j                            |
                     2# t*          $ r Y >w xY w|	S )NrA   r(   )design_infoformula)
data_tools_is_using_ndarray_typer?   _is_using_pandasrF   r9   r:   
isinstancer   zipr7   r8   _ynames_mapr   r>   
orig_endogr<   wendogsetattr__dict__popKeyError)rW   r<   rX   missinghasconstrZ   r=   r>   rE   r   keys              r0   _handle_datazMultinomialModel._handle_data  sd   ,UD99 	$5e$<$<!M6EE(55 	+=e+D+D(M655Ju%%E$5e$<$<!M6E&$'' 	F#eM$7$:;;VDDEEF!=$LLVLLj  	 	C000c4=#4#4S#9#9::::   s   )D++
D87D8c                 f   t                                                       | j                            d          | _        | j        j        d         | _        | j        j        d         | _        | xj	        | j        dz
  z  c_	        | j        j        d         | j	        z
  | j        dz
  z
  | _
        dS )z4
        Preprocesses the data for MNLogit.
        r(   r
   N)rS   rb   r<   argmaxr  r8   JrX   Kr_   r`   )rW   r[   s    r0   rb   zMultinomialModel.initialize  s     	Z&&q))
"1%#$&(#	*T]:dfQhGr2   Nr   c                 F   |"d}t          j        |t                     |du rd}|| j        }|j        dk    r|d         }t                                          |||          }|dk    r5t          j        t          j	        t          |                    |f          }|S )ag  
        Predict response variable of a model given exogenous variables.

        Parameters
        ----------
        params : array_like
            2d array of fitted parameters of the model. Should be in the
            order returned from the model.
        exog : array_like
            1d or 2d array of exogenous values.  If not supplied, the
            whole exog attribute of the model is used. If a 1d array is given
            it assumed to be 1 row of exogenous variables. If you only have
            one regressor and would like to do prediction, you must provide
            a 2d array with shape[1] == 1.
        which : {'mean', 'linear', 'var', 'prob'}, optional
            Statistic to predict. Default is 'mean'.

            - 'mean' returns the conditional expectation of endog E(y | x),
              i.e. exp of linear predictor.
            - 'linear' returns the linear predictor of the mean function.
            - 'var' returns the estimated variance of endog implied by the
              model.

            .. versionadded: 0.14

               ``which`` replaces and extends the deprecated ``linear``
               argument.

        linear : bool
            If True, returns the linear predicted values.  If False or None,
            then the statistic specified by ``which`` will be returned.

            .. deprecated: 0.14

               The ``linear` keyword is deprecated and will be removed,
               use ``which`` keyword instead.

        Notes
        -----
        Column 0 is the base case, the rest conform to the rows of params
        shifted up one for the base case.
        Nr   Tr   r(   r   )rp   rq   r   rX   r5   rS   rn   r9   column_stackr   len)rW   rr   rX   r   r   ru   predr[   s          r0   rn   zMultinomialModel.predict  s    V DCM#}---~~ <9D9>>:Dwwvt599H?BHSYY$7$7#>??Dr2   rw   rx   r(   c           
      J   |%t          j        | j        | j        dz
  z            }nt          j        |          }|d }t          j        j        | f||||||d|}|j        	                    | j        dd          |_        t          | |          }t          |          S )Nr(   c                     d S r  r+   )xrs   s     r0   <lambda>z&MultinomialModel.fit.<locals>.<lambda>#  s     r2   rz   Forder)r9   r   r  r  r:   r   r   r   rr   reshapeMultinomialResultsMultinomialResultsWrapper)	rW   r{   rK   r|   r}   r~   r   rZ   mnfits	            r0   r   zMultinomialModel.fit  s     8DFdfQh$788LL:l33L--H$( 8lwKH8 8068 8 |++DFBc+BB"4//(///r2   rH   r   r
   r   r   r   r   c                 @   |%t          j        | j        | j        dz
  z            }nt          j        |          }t          j        | f|||||||||	|
|d|}|j                            | j        dd          |_        t          | |          }t          |          S )Nr(   r   r(  r)  r*  )r9   r   r  r  r:   rP   r   rr   r,  L1MultinomialResultsL1MultinomialResultsWrapper)rW   r{   rK   r|   r}   r~   r   r   r   r   r   r   rZ   r/  s                 r0   r   z MultinomialModel.fit_regularized,  s    
 8DFdfQh$788LL:l33L-F#/'dXy+F	F F ?E	F F
 |++DFBc+BB$T511*5111r2   r   c                    || j         }|j        dk    r%|                    | j        | j        dz
  d          }t          j        t          j        ||                    }d|                    d          z   dddf         }t          | j                  }t          | j                  }t          j
        ||d          }t          j        ||dz
            }	| |	z  |dz  z  }
|j        dddddf         |	z  ||z
  z  |dz  z  }|                    d          }t          j        t          j        |dz
            t          j        |                                        t$                     }|j        dddddf          |	z  |z  |dz  z                      d          dd|f         |dd|f<   t          j        |
dddddf         |fd          }d|v r&||                     ||          dddddf         z  }|S )	a  
        For computing marginal effects standard errors.

        This is used only in the case of discrete and count regressors to
        get the variance-covariance of the marginal effects. It returns
        [d F / d params] where F is the predicted probabilities for each
        choice. dFdparams is of shape nobs x (J*K) x (J-1)*K.
        The zero derivatives for the base category are not included.

        Transform can be 'dydx' or 'eydx'. Checking is done in margeff
        computations for appropriate transform.
        Nr(   r)  r*  axisr%   )r(   r
   r%   r   )rX   r5   r,  r  r  r9   expr   r   intrepeattileT	transposekroneyer   astypeboolconcatenatern   )rW   rr   rX   r   eXBsum_eXBr  r  
repeat_eXBrg   F0F1	other_idxdFdXs                 r0   r   z$MultinomialModel._derivative_predict>  s    <9D;!^^DFDF1HC^@@FfRVD&))**swwqzz>111T6*KKKKYsAA...
GD!A#[1_w!|+ U111QQQt8_Q'J"677A:F\\'"" WRVAaC[["'!**55<<TBBB	 U111QQQt8_,Q.z9#QJ()27););AAAyLJ111i<~r!!!T!!!)}b1:::9DLL..qqq!!!Tz::Dr2   c                 Z  	
 t          | j                  }t          | j                  }|| j        }|j        dk    r|                    ||dz
  d          }t          j        t          j        |          |f         | 	                    t          j
        ||                    	t          j        	fdt          t          |                    D                                           d          
t          j        	
fdt          |          D                       }t          j        |d          }d	|v r||z  }d
|v r&||                     ||          dddddf         z  }|                     ||||||          }|                    t#          |          dd          S )a  
        For computing marginal effects returns dF(XB) / dX where F(.) is
        the predicted probabilities

        transform can be 'dydx', 'dyex', 'eydx', or 'eyex'.

        Not all of these make sense in the presence of discrete regressors,
        but checks are done in the results in get_margeff.

        For Multinomial models the marginal effects are

        P[j] * (params[j] - sum_k P[k]*params[k])

        It is returned unshaped, so that each row contains each of the J
        equations. This makes it easier to take derivatives of this for
        standard errors. If you want average marginal effects you can do
        margeff.reshape(nobs, K, J, order='F).mean(0) and the marginal effects
        for choice J are in column J
        Nr(   r)  r*  c                 D    g | ]}d d |gf         d d |f         z  S r  r+   )r-   r.   rh   
zeroparamss     r0   
<listcomp>z5MultinomialModel._derivative_exog.<locals>.<listcomp>  sI     2 2 2 aaa!f+
111a4(88 2 2 2r2   r
   c                 J    g | ]}d d |gf         d d |f         z
  z   S r  r+   )r-   jrh   itermrJ  s     r0   rK  z5MultinomialModel._derivative_exog.<locals>.<listcomp>  sN     / / / !  A3K:aaad+;e+CD / / /r2   )r(   r%   r
   r   r   r(  )r7  r  r  rX   r5   r,  r9   c_r   rh   r   r   r7   r   r;  rn   r   r"  )rW   rr   rX   r   r   r   r  r  r   rh   rN  rJ  s            @@@r0   r   z!MultinomialModel._derivative_exogh  s   * KKKK <9D;!^^Aqs#^66FU28A;;./
hhrvdF++,,  2 2 2 2 2#(Q==2 2 2 3 3363q66 	 ( / / / / / /%*1XX/ / / 0 0 ,w	229tOG9t||FD11!!!D(;;G..w/8)YP Ps4yy"C888r2   c                     t           ),get frozen instance of distribution
        rd   )rW   rr   rX   r   s       r0   r  z!MultinomialModel.get_distribution  
     "!r2   r   r   r  Nr   Nr   NNr  )r   r   r   r  rb   rn   r   rP   r   r   r   r   r   r  r   r   s   @r0   r   r     s&         <
H 
H 
H 
H 
H9 9 9 9 9 9v Xm'((>@,00 0 0 )(0$ Xm+3448<IMIM2 2 2 542"( ( ( (T =C3739 39 39 39j" " " " " " " "r2   r   c                        e Zd Z	 	 d fd	Zd Z fdZddZ	 	 dd	ZddZ	 	 ddZ	d Z
 eej        j                  	 	 d fd	            Z eej        j                  	 	 	 	 d  fd	            Z xZS )!r	   NnoneTc                    |                      |            t                      j        |||f|||d| |<t          j        | j                  | _        t          j        | j                  | _        |t          j        | j                  | _        |                     | j        | j        | j	                   |t          | d           |t          | d           t          j        | j	        j        t          j                  }t          j        | j	        |          | _	        t          j        | j        j        t          j                  }t          j        | j        |          | _        d S )N)r  r   exposurer   rX  )r   rS   rT   r9   r:   rX  logr   _check_inputsr<   r   promote_typesr4   float64rX   )
rW   r<   rX   r   rX  r  rY   rZ   dtr[   s
            r0   rT   zCountModel.__init__  sF   6"""j 	E' &	E 	E=C	E 	E 	EJt}55DMF4=11DM*T[11DK4;tzBBB>D(###D*%%% dj.
;;Z
B//
diorz::Jty"--			r2   c                     |+|j         d         |j         d         k    rt          d          |+|j         d         |j         d         k    rt          d          d S d S )Nr
   z&offset is not the same length as endogz(exposure is not the same length as endog)r8   rL   )rW   r   rX  r<   s       r0   rZ  zCountModel._check_inputs  sg    &,q/U[^"C"CEFFFHN1$5Q$G$GGHHH  $G$Gr2   c                     t                                                      }d|v r%|d         t          j        |d                   |d<   |S )NrX  )rS   _get_init_kwdsr9   r6  rW   kwdsr[   s     r0   r`  zCountModel._get_init_kwds  sM     ww%%''$z"2">!vd:&677Dr2   c                     |&t          j        t          j        |                    }|t          j        |          }|.| j        }|t	          | dd          }|t	          | dd          }nt          j        |          }|d}|d}|||fS )NrX  r
   r   )r9   rY  r:   rX   getattr)rW   rX   r   rX  s       r0   _get_predict_arrayszCountModel._get_predict_arrays  s     vbj2233HZ''F <9D"4Q77~ x33 :d##D~VX%%r2   r   c                    |"d}t          j        |t                     |du rd}||t          | d          r| j        }n|d}||t          | d          r| j        }n|d}nt          j        |          }|| j        }t          j	        ||d|j
        d                            }||z   |z   }	|d	k    rt          j        |	          S |                    d
          r|	S t          d          )ah  
        Predict response variable of a count model given exogenous variables

        Parameters
        ----------
        params : array_like
            Model parameters
        exog : array_like, optional
            Design / exogenous data. Is exog is None, model exog is used.
        exposure : array_like, optional
            Log(exposure) is added to the linear prediction with
            coefficient equal to 1. If exposure is not provided and exog
            is None, uses the model's exposure if present.  If not, uses
            0 as the default value.
        offset : array_like, optional
            Offset is added to the linear prediction with coefficient
            equal to 1. If offset is not provided and exog
            is None, uses the model's offset if present.  If not, uses
            0 as the default value.
        which : 'mean', 'linear', 'var', 'prob' (optional)
            Statitistic to predict. Default is 'mean'.

            - 'mean' returns the conditional expectation of endog E(y | x),
              i.e. exp of linear predictor.
            - 'linear' returns the linear predictor of the mean function.
            - 'var' variance of endog implied by the likelihood model
            - 'prob' predicted probabilities for counts.

            .. versionadded: 0.14

               ``which`` replaces and extends the deprecated ``linear``
               argument.

        linear : bool
            If True, returns the linear predicted values.  If False or None,
            then the statistic specified by ``which`` will be returned.

            .. deprecated: 0.14

               The ``linear` keyword is deprecated and will be removed,
               use ``which`` keyword instead.


        Notes
        -----
        If exposure is specified, then it will be logged by the method.
        The user does not need to log it first.
        Nr   Tr   r   r   rX  r(   r   lin+keyword which has to be "mean" and "linear")rp   rq   r   r   r   rX  r9   rY  rX   r   r8   r6  
startswithrL   )
rW   rr   rX   rX  r   r   r   ru   fittedr   s
             r0   rn   zCountModel.predict  s   d DCM#}---~~  >dlwtX/F/Fl[FF^F z1J1J}HHHHvh''H<9Df^djm^4558#f,F??6'??"e$$ 	LNJKKKr2   r   c                     || j         }|                     ||          dddf         |z  }d|v r#||                     ||          dddf         z  }|S )r   Nr   )rX   rn   )rW   rr   rX   r   r   s        r0   r   zCountModel._derivative_predict8  sj     <9D\\&$''$/$69$,,vt,,QQQtV44B	r2   c                 J   || j         }t          | dd          }|dk    r|n
|d|          }|                     ||          dddf         |dddf         z  }d|v r||z  }d|v r#||                     ||          dddf         z  }|                     ||||||          S )a  
        For computing marginal effects. These are the marginal effects
        d F(XB) / dX
        For the Poisson model F(XB) is the predicted counts rather than
        the probabilities.

        transform can be 'dydx', 'dyex', 'eydx', or 'eyex'.

        Not all of these make sense in the presence of discrete regressors,
        but checks are done in the results in get_margeff.
        NrV   r
   r   r   )rX   rd  rn   r   )	rW   rr   rX   r   r   r   rV   params_exogr   s	            r0   r   zCountModel._derivative_exogK  s     <9D$	1-- '1ff&7(2C,,vt,,QQQtV4{467JJ9tOG9t||FD11!!!D&99G++GVT,5y)M M 	Mr2   c                 H   ddl m} |                                }|                     |d          }|                    |          }| j        |dddf         z  }| j        dk    r<t          j        |j	        d         | j        f          }t          j
        ||f          }|S )r   r
   linksr   r   N)statsmodels.genmod.familiesrp  Logrn   r   rX   rV   r9   r   r8   r!  )rW   rr   rp  r   r   r   r   
dmat_extras           r0   r   zCountModel._deriv_mean_dparamsf  s     	655555yy{{<<h<77  **y3qqq$w<'<!4:a=$,"?@@J?D*#566Dr2   rw   rx   r(   c           
           t                      j        d||||||d|}t          | |          }	t          |	          S Nrz   r+   )rS   r   CountResultsCountResultsWrapper)rW   r{   rK   r|   r}   r~   r   rZ   cntfitr   r[   s             r0   r   zCountModel.fit  s`      ',$*%,)4"&&.' '  &' ' #400";///r2   rH   r   r
   r   r   r   r   c                     t          |            t                      j        d|||||||||	|
|d|}t          | |          }t	          |          S r   )rN   rS   r   L1CountResultsL1CountResultsWrapperrW   r{   rK   r|   r}   r~   r   r   r   r   r   r   rZ   rx  r   r[   s                  r0   r   zCountModel.fit_regularized  s}     	F###(( 
3l06185@.22:/43<M7D06
3 
3 ,2
3 
3 %T622$[111r2   )NNrV  Tr   NNNr   NrS  rT  r   r  )r   r   r   rT   rZ  r`  re  rn   r   r   r   r   rP   r   r   r   r   r   s   @r0   r	   r	     su       HN . . . . . ..I I I    & & & &4 @D%)RL RL RL RLh   & =C37M M M M6  2 Xm'((>@,0
0 
0 
0 
0 
0 )(
0 Xm+3448<IMIM2 2 2 2 2 542 2 2 2 2r2   r	   c                       e Zd Zdej        dej        z   ez   dz  Zed             Z	d Z
d Zd Zd Z ee          d	             Z eej        j                  	 	 d# fd	            Z eej        j                  	 	 	 	 d$ fd	            Zd%dZd Zd Zd Zd Zd Zd%dZ	 	 d& fd	Zd%d Zd%d!Zd'd"Z xZS )(r   z
    Poisson Model

    %(params)s
    %(extra_params)s

    Attributes
    ----------
    endog : ndarray
        A reference to the endogenous response variable
    exog : ndarray
        A reference to the exogenous design.
    zoffset : array_like
        Offset is added to the linear prediction with coefficient equal to 1.
    exposure : array_like
        Log(exposure) is added to the linear prediction with coefficient
        equal to 1.
        rr   extra_paramsc                 6    ddl m} |                                S Nr
   )families)statsmodels.genmodr  r   rW   r  s     r0   familyzPoisson.family  s&    //////!!!r2   c                 t    | j         }t          j                            |t	          j        |                    S )aO  
        Poisson model cumulative distribution function

        Parameters
        ----------
        X : array_like
            `X` is the linear predictor of the model.  See notes.

        Returns
        -------
        The value of the Poisson CDF at each point.

        Notes
        -----
        The CDF is defined as

        .. math:: \exp\left(-\lambda\right)\sum_{i=0}^{y}\frac{\lambda^{i}}{i!}

        where :math:`\lambda` assumes the loglinear model. I.e.,

        .. math:: \ln\lambda_{i}=X\beta

        The parameter `X` is :math:`X\beta` in the above formula.
        )r<   r   poissonrh   r9   r6  rW   rg   rA   s      r0   rh   zPoisson.cdf  s+    2 J}  BF1II...r2   c                     | j         }t          j        t          j                            |t          j        |                              S )a  
        Poisson model probability mass function

        Parameters
        ----------
        X : array_like
            `X` is the linear predictor of the model.  See notes.

        Returns
        -------
        pdf : ndarray
            The value of the Poisson probability mass function, PMF, for each
            point of X.

        Notes
        -----
        The PMF is defined as

        .. math:: \frac{e^{-\lambda_{i}}\lambda_{i}^{y_{i}}}{y_{i}!}

        where :math:`\lambda` assumes the loglinear model. I.e.,

        .. math:: \ln\lambda_{i}=x_{i}\beta

        The parameter `X` is :math:`x_{i}\beta` in the above formula.
        )r<   r9   r6  r   r  logpmfr  s      r0   rk   zPoisson.pdf  s5    6 Jvem**1bfQii88999r2   c           	      F   t          | dd          }t          | dd          }t          j        | j        |          |z   |z   }| j        }t          j        t          j        t          j        |dt                               ||z  z   t          |dz             z
            S )a  
        Loglikelihood of Poisson model

        Parameters
        ----------
        params : array_like
            The parameters of the model.

        Returns
        -------
        loglike : float
            The log-likelihood function of the model evaluated at `params`.
            See notes.

        Notes
        -----
        .. math:: \ln L=\sum_{i=1}^{n}\left[-\lambda_{i}+y_{i}x_{i}^{\prime}\beta-\ln y_{i}!\right]
        r   r
   rX  Nr(   )
rd  r9   r   rX   r<   r   r6  clipEXP_UPPER_LIMITr   rW   rr   r   rX  XBr<   s         r0   loglikezPoisson.loglike  s    & x++4Q//VDIv&&/(:
vVBGBo66777bjeai  !
 
 	
r2   c                     t          | dd          }t          | dd          }t          j        | j        |          |z   |z   }| j        }t          j        |           ||z  z   t          |dz             z
  S )a  
        Loglikelihood for observations of Poisson model

        Parameters
        ----------
        params : array_like
            The parameters of the model.

        Returns
        -------
        loglike : array_like
            The log likelihood for each observation of the model evaluated
            at `params`. See Notes

        Notes
        -----
        .. math:: \ln L_{i}=\left[-\lambda_{i}+y_{i}x_{i}^{\prime}\beta-\ln y_{i}!\right]

        for observations :math:`i=1,...,n`
        r   r
   rX  r(   )rd  r9   r   rX   r<   r6  r   r  s         r0   
loglikeobszPoisson.loglikeobs  st    * x++4Q//VDIv&&/(:
r

{eBh&q)9)999r2   c                     t          | dd          }t          | dd          }| j        t          j        ||z             z                                  }t          j        |          g}|S )Nr   r
   rX  )rd  r<   r9   r6  r   rY  )rW   r   rX  constrr   s        r0   _get_start_params_nullzPoisson._get_start_params_null5  s_    x++4Q//bfVh%6777==??&--r2   Nrw   rx   r(   c           
         |Z| j         j        Ndt          j        | j        j        d                   z  }|                                 d         || j         j        <   i }|                    d          1|                    d          |d<   |                    di           |d<    t          t          |           j
        d||||||d|}	t          | |	fi |}
t          |
          S )NgMbP?r(   r
   cov_typecov_kwdsrz   r+   )r   	const_idxr9   r   rX   r8   r  getrS   r	   r   PoissonResultsPoissonResultsWrapper)rW   r{   rK   r|   r}   r~   r   rZ   rb  rx  r   r[   s              r0   r   zPoisson.fit=  s    DI$7$C 2749?1+=#>#>>L040K0K0M0Ma0PL,-::j!!-%zz*55D%zz*b99D,z4((, 7,4:5<9D266>7 7 067 7 %T6::T::$[111r2   rH   r   r
   r   r   r   r   c                     t          |            t          t          |           j        d|||||||||	|
|d|}t	          | |          }t          |          S r   )rN   rS   r	   r   L1PoissonResultsL1PoissonResultsWrapperr|  s                  r0   r   zPoisson.fit_regularizedV  s     	F###8z4((8 F)&''dXy+F	F F ?E	F F 'tV44&{333r2   c                 6   ddl m} ddlm}m}  || j                                      |          }|j        |j        }	} || ||	||          \  }
}}| 	                    dddd          }|j
                            dt          j                  |j
        d<   |j
                            d	t          j                  |j
        d	<   |j
        d
         |j
        d
<   |
|j        _        ||j        _        |                    dd          }|dk    r||j        _        nd|j        _        t%          |	          }|j        xj        |z  c_        |j        xj        |z  c_        |                    |          |j        _        ||j        _        ||j        _        |S )ae  fit the model subject to linear equality constraints

        The constraints are of the form   `R params = q`
        where R is the constraint_matrix and q is the vector of
        constraint_values.

        The estimation creates a new model with transformed design matrix,
        exog, and converts the results back to the original parameterization.

        Parameters
        ----------
        constraints : formula expression or tuple
            If it is a tuple, then the constraint needs to be given by two
            arrays (constraint_matrix, constraint_value), i.e. (R, q).
            Otherwise, the constraints can be given as strings or list of
            strings.
            see t_test for details
        start_params : None or array_like
            starting values for the optimization. `start_params` needs to be
            given in the original parameter space and are internally
            transformed.
        **fit_kwds : keyword arguments
            fit_kwds are used in the optimization of the transformed model.

        Returns
        -------
        results : Results instance
        r
   )
DesignInfo)r   LinearConstraints)r{   r   nmF)r|   rK   r~   warn_convergencefcall
iterations	convergedr  	nonrobustN)patsyr  statsmodels.base._constraintsr   r  
exog_nameslinear_constraintcoefs	constantsr   mle_retvalsr  r9   r   _resultsrr   cov_params_defaultnormalized_cov_paramsr"  r`   r_   
from_patsyr   k_constrresults_constrained)rW   r   r{   r   r  r   r  lcRqrr   cov
res_constrr   r  r  s                   r0   r   zPoisson.fit_constrainedg  s   D 	%$$$$$	F 	F 	F 	F 	F 	F 	F 	F Z((::;GGx1 #2/$1?K;C#E #E #EZ hhqA(-  / /#-#9#=#=grv#N#N (2(>(B(B8Dbf)N )N%'1'=k'J$$*-'<<
K88{""14CL..15CL.q66))#4#?#?#C#C  (+5(
r2   c                     t          | dd          }t          | dd          }| j        }t          j        t          j        ||          |z   |z             }t          j        | j        |z
  |          S )a\  
        Poisson model score (gradient) vector of the log-likelihood

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        score : ndarray, 1-D
            The score vector of the model, i.e. the first derivative of the
            loglikelihood function, evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial\ln L}{\partial\beta}=\sum_{i=1}^{n}\left(y_{i}-\lambda_{i}\right)x_{i}

        where the loglinear model is assumed

        .. math:: \ln\lambda_{i}=x_{i}\beta
        r   r
   rX  rd  rX   r9   r6  r   r<   rW   rr   r   rX  rg   Ls         r0   scorezPoisson.score  sj    . x++4Q//IF26!F##f,x788vdj1na(((r2   c                     t          | dd          }t          | dd          }| j        }t          j        t          j        ||          |z   |z             }| j        |z
  dddf         |z  S )aK  
        Poisson model Jacobian of the log-likelihood for each observation

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        score : array_like
            The score vector (nobs, k_vars) of the model evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial\ln L_{i}}{\partial\beta}=\left(y_{i}-\lambda_{i}\right)x_{i}

        for observations :math:`i=1,...,n`

        where the loglinear model is assumed

        .. math:: \ln\lambda_{i}=x_{i}\beta
        r   r
   rX  Nr  r  s         r0   	score_obszPoisson.score_obs  sp    0 x++4Q//IF26!F##f,x788
Q$'!++r2   c                     t          | dd          }t          | dd          }| j        }t          j        t          j        ||          |z   |z             }| j        |z
  S )a.  
        Poisson model score_factor for each observation

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        score : array_like
            The score factor (nobs, ) of the model evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial\ln L_{i}}{\partial\beta}=\left(y_{i}-\lambda_{i}\right)

        for observations :math:`i=1,...,n`

        where the loglinear model is assumed

        .. math:: \ln\lambda_{i}=x_{i}\beta
        r   r
   rX  r  r  s         r0   score_factorzPoisson.score_factor  s^    0 x++4Q//IF26!F##f,x788
Qr2   c                     t          | dd          }t          | dd          }| j        }t          j        t          j        ||          |z   |z             }t          j        ||j        z  |           S )aV  
        Poisson model Hessian matrix of the loglikelihood

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        hess : ndarray, (k_vars, k_vars)
            The Hessian, second derivative of loglikelihood function,
            evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial^{2}\ln L}{\partial\beta\partial\beta^{\prime}}=-\sum_{i=1}^{n}\lambda_{i}x_{i}x_{i}^{\prime}

        where the loglinear model is assumed

        .. math:: \ln\lambda_{i}=x_{i}\beta
        r   r
   rX  )rd  rX   r9   r6  r   r:  r  s         r0   r   zPoisson.hessian  sm    . x++4Q//IF26!F##h.788qua    r2   c                     t          | dd          }t          | dd          }| j        }t          j        t          j        ||          |z   |z             }| S )aP  
        Poisson model Hessian factor

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        hess : ndarray, (nobs,)
            The Hessian factor, second derivative of loglikelihood function
            with respect to the linear predictor evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial^{2}\ln L}{\partial\beta\partial\beta^{\prime}}=-\sum_{i=1}^{n}\lambda_{i}

        where the loglinear model is assumed

        .. math:: \ln\lambda_{i}=x_{i}\beta
        r   r
   rX  )rd  rX   r9   r6  r   r  s         r0   hessian_factorzPoisson.hessian_factor"  sY    . x++4Q//IF26!F##h.788r	r2   c                     | j         S )a  derivative of score_obs w.r.t. endog

        Parameters
        ----------
        params : ndarray
            parameter at which score is evaluated
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.

        Returns
        -------
        derivative : ndarray_2d
            The derivative of the score_obs with respect to endog. This
            can is given by `score_factor0[:, None] * exog` where
            `score_factor0` is the score_factor without the residual.
        rX   )rW   rr   scales      r0   _deriv_score_obs_dendogzPoisson._deriv_score_obs_dendog?  s    & yr2   r   c                 r   |"d}t          j        |t                     |du rd}|                    d          rd}|dv r't	                                          ||||||          S |dk    r|                     ||||	          }	|	S |d
k    r|t          j        |          }nAt          j        t          j        dt          j	        | j
                  dz                       }|                     ||||	          dddf         }	t          j                            ||	          S t          d          )a@	  
        Predict response variable of a model given exogenous variables.

        Parameters
        ----------
        params : array_like
            2d array of fitted parameters of the model. Should be in the
            order returned from the model.
        exog : array_like, optional
            1d or 2d array of exogenous values.  If not supplied, then the
            exog attribute of the model is used. If a 1d array is given
            it assumed to be 1 row of exogenous variables. If you only have
            one regressor and would like to do prediction, you must provide
            a 2d array with shape[1] == 1.
        offset : array_like, optional
            Offset is added to the linear predictor with coefficient equal
            to 1.
            Default is zero if exog is not None, and the model offset if exog
            is None.
        exposure : array_like, optional
            Log(exposure) is added to the linear prediction with coefficient
            equal to 1.
            Default is one if exog is is not None, and is the model exposure
            if exog is None.
        which : 'mean', 'linear', 'var', 'prob' (optional)
            Statitistic to predict. Default is 'mean'.

            - 'mean' returns the conditional expectation of endog E(y | x),
              i.e. exp of linear predictor.
            - 'linear' returns the linear predictor of the mean function.
            - 'var' returns the estimated variance of endog implied by the
              model.
            - 'prob' return probabilities for counts from 0 to max(endog) or
              for y_values if those are provided.

            .. versionadded: 0.14

               ``which`` replaces and extends the deprecated ``linear``
               argument.

        linear : bool
            The ``linear` keyword is deprecated and will be removed,
            use ``which`` keyword instead.
            If True, returns the linear predicted values.  If False or None,
            then the statistic specified by ``which`` will be returned.

            .. deprecated: 0.14

               The ``linear` keyword is deprecated and will be removed,
               use ``which`` keyword instead.

        y_values : array_like
            Values of the random variable endog at which pmf is evaluated.
            Only used if ``which="prob"``
        Nr   Tr   rg  )r   r   )rX   rX  r   r   r   r   rX   rX  r   probr
   r(   z-Value of the `which` option is not recognized)rp   rq   r   ri  rS   rn   r9   
atleast_2darangemaxr<   r   r  _pmfrL   )rW   rr   rX   rX  r   r   r   y_valuesru   r   r[   s             r0   rn   zPoisson.predictT  sc   v DCM#}---~~ E"" 	E&&&77??6x*0).v # ? ? ? e^^f4'/     B If__#=22=Ia
!3!3a!788: :f4'/      !4)B =%%h333LMMMr2   c                 2    t          j        |            }|S )rProbability that count is not zero

        internal use in Censored model, will be refactored or removed
        )r9   expm1)rW   r   rr   prob_nzs       r0   _prob_nonzerozPoisson._prob_nonzero  s    
 HbSMM/r2   c                     |S )bvariance implied by the distribution

        internal use, will be refactored or removed
        r+   )rW   r   rr   s      r0   _varzPoisson._var  s	    
 	r2   c                 `    |                      ||||          }t          j        |          }|S )a=  Get frozen instance of distribution based on predicted parameters.

        Parameters
        ----------
        params : array_like
            The parameters of the model.
        exog : ndarray, optional
            Explanatory variables for the main count model.
            If ``exog`` is None, then the data from the model will be used.
        offset : ndarray, optional
            Offset is added to the linear predictor of the mean function with
            coefficient equal to 1.
            Default is zero if exog is not None, and the model offset if exog
            is None.
        exposure : ndarray, optional
            Log(exposure) is added to the linear predictor  of the mean
            function with coefficient equal to 1. If exposure is specified,
            then it will be logged by the method. The user does not need to
            log it first.
            Default is one if exog is is not None, and it is the model exposure
            if exog is None.

        Returns
        -------
        Instance of frozen scipy distribution subclass.
        r  )rn   r   r  )rW   rr   rX   rX  r   r   r  s          r0   r  zPoisson.get_distribution  s1    6 \\&thv\NNb!!r2   r   r  r  NNNr   NNr   ) r   r   r   r   _model_params_doc_missing_param_doc_check_rank_docr   r   r  rh   rk   r  r  r   _get_start_params_null_docsr  rP   r   r   r   r  r  r  r   r  r  rn   r  r  r  r   r   s   @r0   r   r     sH        +
 %&
 )889 99G* " " ^"/ / /8: : :<
 
 
:: : :8 X)**  +* Xm'((>@,02 2 2 2 2 )(20 Xm+3448<IMIM4 4 4 4 4 544 C C C CJ) ) ):, , ,<     <! ! !:  :   * @D48YN YN YN YN YN YNv             r2   r   c                       e Zd Zdej        dej        z   ez   dz  Z	 	 d) fd	Z fd	Z	d
 Z
d Zd Z ee          d             Zd*dZ ed           eej        j                  	 	 	 d+ fd	                        Z eej        j                  	 	 	 	 d, fd	            Zd Zd Zd*dZd  Zd! Zd" Z eej        j                  	 	 d-d$            Zd% Zd*d&Zd' Z eej        j                  d.d(            Z xZ S )/r   z
    Generalized Poisson Model

    %(params)s
    %(extra_params)s

    Attributes
    ----------
    endog : ndarray
        A reference to the endogenous response variable
    exog : ndarray
        A reference to the exogenous design.
    aZ  
    p : scalar
        P denotes parameterizations for GP regression. p=1 for GP-1 and
        p=2 for GP-2. Default is p=1.
    offset : array_like
        Offset is added to the linear prediction with coefficient equal to 1.
    exposure : array_like
        Log(exposure) is added to the linear prediction with coefficient
        equal to 1.r  r(   NrV  Tc                      t                      j        ||f||||d| |dz
  | _        | j                            d           d| _        d| _        d S )Nr   rX  r  rY   r(   r   FrS   rT   parameterizationr  appendrV   _transparams
rW   r<   rX   pr   rX  r  rY   rZ   r[   s
            r0   rT   zGeneralizedPoisson.__init__  s|    	# &"*!($.	# 	# "	# 	# 	# !"Aw'''!r2   c                 b    t                                                      }| j        dz   |d<   |S )Nr(   r  rS   r`  r  ra  s     r0   r`  z!GeneralizedPoisson._get_init_kwds  s.    ww%%'')A-S	r2   c                     | j         d fS r  r  rW   s    r0   
_get_exogszGeneralizedPoisson._get_exogs
      	4  r2   c                 P    t          j        |                     |                    S )ab  
        Loglikelihood of Generalized Poisson model

        Parameters
        ----------
        params : array_like
            The parameters of the model.

        Returns
        -------
        loglike : float
            The log-likelihood function of the model evaluated at `params`.
            See notes.

        Notes
        -----
        .. math:: \ln L=\sum_{i=1}^{n}\left[\mu_{i}+(y_{i}-1)*ln(\mu_{i}+
            \alpha*\mu_{i}^{p-1}*y_{i})-y_{i}*ln(1+\alpha*\mu_{i}^{p-1})-
            ln(y_{i}!)-\frac{\mu_{i}+\alpha*\mu_{i}^{p-1}*y_{i}}{1+\alpha*
            \mu_{i}^{p-1}}\right]
        r9   r   r  rW   rr   s     r0   r  zGeneralizedPoisson.loglike  s     , vdoof--...r2   c                    | j         rt          j        |d                   }n|d         }|dd         }| j        }| j        }|                     |          }t          j        ||          }d||z  z   }||dz
  |z  z   }t          j        d|          }t          j        d|          }t          j        |          |dz
  t          j        |          z  z   |t          j        |          z  z
  t          |dz             z
  ||z  z
  S )a  
        Loglikelihood for observations of Generalized Poisson model

        Parameters
        ----------
        params : array_like
            The parameters of the model.

        Returns
        -------
        loglike : ndarray
            The log likelihood for each observation of the model evaluated
            at `params`. See Notes

        Notes
        -----
        .. math:: \ln L=\sum_{i=1}^{n}\left[\mu_{i}+(y_{i}-1)*ln(\mu_{i}+
            \alpha*\mu_{i}^{p-1}*y_{i})-y_{i}*ln(1+\alpha*\mu_{i}^{p-1})-
            ln(y_{i}!)-\frac{\mu_{i}+\alpha*\mu_{i}^{p-1}*y_{i}}{1+\alpha*
            \mu_{i}^{p-1}}\right]

        for observations :math:`i=1,...,n`
        r(  Nr(   g#B;)
r  r9   r6  r  r<   rn   powermaximumrY  r   )	rW   rr   r   r  r<   r   mu_pa1a2s	            r0   r  zGeneralizedPoisson.loglikeobs%  s	   0  	F6":&&EE2JE!
\\&!!xA26U""Zr""Zr""r

eai26"::55r

9 $UQY//024r': 	;r2   c                    t          | dd          }t          | dd          }| j        t          j        ||z             z                                  }t          j        |          g}|t          j        ||z             z  }| j        |z
  }|                     |||j        d         dz
            }|                    |           t          j	        |          S Nr   r
   rX  r(   r`   
rd  r<   r9   r6  r   rY  _estimate_dispersionr8   r  r   rW   r   rX  r  rr   r   residas           r0   r  z)GeneralizedPoisson._get_start_params_nullM      x++4Q//bfVh%6777==??&--RVFX-...
R%%b%%+a.1:L%MMaxr2   c                     | j         }||j        d         }t          j        |          t          j        |          z  dz
  || z  z                                  |z  }|S )Nr
   r(   )r  r8   r9   abssqrtr   rW   r   r   r`   r  r  s         r0   r  z'GeneralizedPoisson._estimate_dispersion[  s[    !{1~HfUmmbgbkk)A-qb9>>@@8Kr2   o  
        use_transparams : bool
            This parameter enable internal transformation to impose
            non-negativity. True to enable. Default is False.
            use_transparams=True imposes the no underdispersion (alpha > 0)
            constraint. In case use_transparams=True and method="newton" or
            "ncg" transformation is ignored.
        bfgsrx   Fr  c           
         |r|dvrd| _         n#|rt          j        dt                     d| _         |&t	          | dd          t	          | dd          z   }t          j        |          dk    r|dk    rd }dddd	}||                    |           t          | j	        | j
        |
          }t          j                    5  t          j        d            |j        di |}d d d            n# 1 swxY w Y   |j        }|                     |                                |j        |j                  }t          j        |t)          d|                    }|d } t+                      j        d||||||d|}|
||j        d<   |r<|dvr8d| _         t          j        |j        j        d                   |j        j        d<   t3          | |j                  }t5          |          }|	i }	 |j        d|d|
d|	 |S )Nrw   ncgT&Parameter "use_transparams" is ignoredFr   r
   rX  r(   r~   skip_hessianr  r   alwaysr  gc                      | S r  r+   r&  s    r0   r'  z(GeneralizedPoisson.fit.<locals>.<lambda>      ! r2   r{   r|   rK   r~   r}   r   optim_kwds_prelimr(  r  use_selfuse_tr+   )r  rp   rq   RuntimeWarningrd  r9   sizeupdater   r<   rX   catch_warningssimplefilterr   rr   r  rn   r   r`   r  r  rS   mle_settingsr6  r  GeneralizedPoissonResults GeneralizedPoissonResultsWrapper_get_robustcov_results)rW   r{   rK   r|   r}   r~   r   use_transparamsr  r  r  r  rZ   r   kwds_prelimmod_poires_poir  r   gpfitresultr[   s                        r0   r   zGeneralizedPoisson.fitc  s     	&v->>> $D .F,. . . %DT8Q//'$
A2N2NNFwv!##!#$d/46 6K ,""#4555dj$)FCCCG(** 5 5%h///%'+44445 5 5 5 5 5 5 5 5 5 5 5 5 5 5 #>L))'//*;*;W]3:3C * E EA9\3tQ<<@@L#|H ',%,$*"&)4&.' '  &' ' (7HF 34 	Lv->>> %D)+0Fr0J)K)KFO"2&)$@@1%88H%% 	Nx/35	N 	NDL	N 	N 	N   "C33C7:C7rH   r   r
   r   r   r   r   c                 j   t          |           t          j        |          dk    r<|dk    r6| j        j        d         | j        z   }|t          j        |          z  }d|d<   | j        r"t          j        |          dk    r
|d d         n|}d| _        |t          | dd          t          | dd          z   }t          j        |          dk    r|dk    rd }t          | j
        | j        |          }t          j                    5  t          j        d            |j        d||||d||||	|
|d	|j        }d d d            n# 1 swxY w Y   t          j        |d
          } t#          t$          |           j        d|||||||||	|
|d	|}t'          | |          }t)          |          S Nr(   r
   r(  Fr   rX  r   r  r   皙?r+   )rN   r9   r  rX   r8   rV   r   r  rd  r   r<   rp   r  r  r   rr   r  rS   r	   L1GeneralizedPoissonResults"L1GeneralizedPoissonResultsWrapperrW   r{   rK   r|   r}   r~   r   r   r   r   r   r   rZ   k_paramsalpha_pr   r#  rx  r   r[   s                      r0   r   z"GeneralizedPoisson.fit_regularized  s6    	F###75>>Q5A::yq)DL8HBGH---EE"I!%P"'%..12D2D%**5!T8Q//'$
A2N2NNFwv!##!dj$)FCCCG(** 4 4%h///6w6  -!-fg +!h!Y"/}! -  -
 &, -  -
 .4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 9\377L8z4((8 F)&''dXy+F	F F ?E	F F 2$??1+>>>   3E

EEc                 T   | j         rt          j        |d                   }n|d         }|d d         }| j        }| j        }| j        d d d f         }|                     |          d d d f         }t          j        ||          }d||z  z   }|||z  |z  z   }	||z  ||dz
  z  z  }
|
|z  }||z  }|||dz
  |	z  d|z  z
  z  |	|dz  z  z   z  }|| |z  |
|	z  |dz  z  z   d|z   |dz
  |	z  d|z  z
  z  z   d|z  z   z  }t          j        |t          j	        |          fd          S )Nr(  r(   r%   r4  )
r  r9   r6  r  rX   r<   rn   r  r@  r  )rW   rr   r   r  rX   rA   r   r  r  r  a3a4dmudbdalphadparamss                  r0   r  zGeneralizedPoisson.score_obs  s    	F6":&&EE2JE!yJqqqv\\&!!!!!D&)xA%$,""QYA&!VT	!A|a"f45RU
BCB387bAg./FA|a"f'<=> r6" #
 ~wf(=(=>#$& & & 	&r2   c                     t          j        |                     |          d          }| j        r|d         |d         dz  k     |S |S )Nr
   r4  r(  r%   r9   r   r  r  rW   rr   r  s      r0   r  zGeneralizedPoisson.score  sN    t~~f--A666 	"Ira''LLr2   c                    t          j        |          }| j        rt          j        |d                   }n|d         }|d d         }| j        }|| j        n|}|                     |          }t          j        ||          }d||z  z   }|||z  |z  z   }	||z  ||dz
  z  z  }
|
|z  }|}|||dz
  |	z  d|z  z
  z  |	|dz  z  z   z  }|| |z  |
|	z  |dz  z  z   d|z   |dz
  |	z  d|z  z
  z  z   d|z  z   z  }||fS )Nr(  r(   r%   r9   r:   r  r6  r  r<   rn   r  )rW   rr   r<   r   r  rA   r   r  r  r  r2  r3  r4  r5  r6  s                  r0   r  zGeneralizedPoisson.score_factor  sS   F## 	F6":&&EE2JE!-DJJU\\&!!xA%$,""QYA&!V!A|a"f45RU
BCB387bAg./FA|a"f'<=> r6" #
 r2   c                    | j         rt          j        |d                   }n|d         }|dd         }| j        }| j        dddf         }|                     |          dddf         }t          j        ||          }d||z  z   }|||z  |z  z   }t          j        t          j        |          ||z
  |dz
  |z  d|z  z
  z  |dz
  |z  |dz  z  z   z            }	|	S )ad  
        Generalized Poisson model derivative of the log-likelihood by p-parameter

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        dldp : float
            dldp is first derivative of the loglikelihood function,
        evaluated at `p-parameter`.
        r(  Nr(   r%   )	r  r9   r6  r  r<   rn   r  r   rY  )
rW   rr   r   r  rA   r   r  r  r  dps
             r0   _score_pzGeneralizedPoisson._score_p
  s      	F6":&&EE2JE!Jqqqv\\&!!!!!D&)xA%$,""VBF2JJ27A|a"f/D"E$&Fb=27#:#; < = =	r2   c                    | j         rt          j        |d                   }n|d         }|dd         }| j        }| j        }| j        dddf         }|                     |          dddf         }t          j        ||          }d||z  z   }|||z  |z  z   }	||z  ||dz
  z  z  }
|
|z  }|||dz
  z  z  }||z  }|j        d         }t          j	        |dz   |dz   f          }t          |          D ]}t          |dz             D ]}t          j        ||dd|df         z  |dd|df         z  ||
|z  |dz  z  d|
dz  z  |	z  |dz  z  z
  d|
z  |dz   z  |dz  z  z   ||z  ||z  z  z
  |
|z  |	z  ||dz  z  z  z   |dz
  |z  |dz
  z  |	|z  z  z   |dz
  d|z   dz  z  |	dz  z  z
  ||dz
  z  ||z  z  z
  z  |dz
  d|z   z  |	z  d|z   |z  z
  z   z  d          }t          j        |          |||f<   t          j        |d          }|j        |         ||<   t          j        d|z  |z  |dz  z  d|
z  |z  |	z  |dz  z  z
  ||z  |dz
  z  d|z   z  |	dz  z  z
  |d|z   z  |dz  z  z   ||z  |dz
  z  |	z  z   d|z  |z  |z  z
  ||	z  |dz  z  z   |z  d          }||dddf<   ||dddf<   |dz  d|z  |dz  z  ||	z  d	z  |dz
  z  z
  d|	z  |dz  z  z
  z  }|                                |d
<   |S )al  
        Generalized Poisson model Hessian matrix of the loglikelihood

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        hess : ndarray, (k_vars, k_vars)
            The Hessian, second derivative of loglikelihood function,
            evaluated at `params`
        r(  Nr(   r%      r
   r4  k       @r(  r(  )r  r9   r6  r  rX   r<   rn   r  r8   emptyr7   r   squeezetriu_indicesr:  )rW   rr   r   r  rX   rA   r   r  r  r  r2  r3  a5r4  dimhess_arrr.   rM  hess_valtri_idxdldpdadldadas                         r0   r   zGeneralizedPoisson.hessian)  sK     	F6":&&EE2JE!yJqqqv\\&!!!!!D&)xA%$,""QYA&!VAT	 jm8SU3q5M**s 	6 	6A1q5\\ 6 66"tAAAaH~"5QQQqX"F27RU?r1u9r>BE12r6R!V,r1u45 6R"W-. 6B;"r1u*5	6
 ER<1q51R"W=> Ea"fq[02q589 Q<2734 5 1uR(2-2vm$	%
#& -.
/ 
/ 
/ "$H!5!5A6 /#+++$Jw/ R$Q.R$+b!e34QU+q2v6Q>? R2q501 a1q5)B.	/
 R!b) b2q5) -22       "CRC!"R qAEBEMVbLAE23FRUN+ , !**,,r2   c                 h   t          j        |          }| j        rt          j        |d                   }n|d         }|dd         }| j        }| j        }|                     |          }t          j        ||          }d||z  z   }|||z  |z  z   }||z  ||dz
  z  z  }	|	|z  }
|||dz
  z  z  }|}|||	|
z  |dz  z  d|	dz  z  |z  |dz  z  z
  d|	z  |
dz   z  |dz  z  z   |
|z  ||z  z  z
  |	|z  |z  ||dz  z  z  z   |
||z  z  z   |	|z  ||dz  z  z  z
  |dz
  |
z  |dz
  z  ||z  z  z   |dz
  d|
z   dz  z  |dz  z  z
  |
|dz
  z  ||z  z  z
  d|dz  z  z
  z  |
 |z  |	|z  |dz  z  z   |dz
  d|
z   z  |z  z   d|
z   |z  z
  d|z  z   z   z  }d|
z  |z  |dz  z  d|	z  |z  |z  |dz  z  z
  ||z  |dz
  z  d|
z   z  |dz  z  z
  |d|
z   z  |dz  z  z   ||z  |dz
  z  |z  z   d|z  |z  |z  z
  ||z  |dz  z  z   |z  }|dz  d|z  |dz  z  ||z  dz  |dz
  z  z
  d|z  |dz  z  z
  z  }|||fS )a  
        Generalized Poisson model Hessian matrix of the loglikelihood

        Parameters
        ----------
        params : array-like
            The parameters of the model

        Returns
        -------
        hess : ndarray, (nobs, 3)
            The Hessian factor, second derivative of loglikelihood function
            with respect to linear predictor and dispersion parameter
            evaluated at `params`
            The first column contains the second derivative w.r.t. linpred,
            the second column contains the cross derivative, and the
            third column contains the second derivative w.r.t. the dispersion
            parameter.

        r(  Nr(   r%   r@  rC  r;  )rW   rr   r   r  rA   r   r  r  r  r2  r3  rH  r4  dbbdbadaas                   r0   r  z!GeneralizedPoisson.hessian_factoru  s   * F## 	F6":&&EE2JE!J\\&!!xA%$,""QYA&!VA27RU?r1u9r>BE)*r6R!V$r1u,- 6R"W%& 6B;"r1u*-	.
 b>" 7b2q5j)* ER<1q5)R"W56 Ea"fq[(2q501 Q<27+	, r1u9
 
 cBh2gAo1uR 2%& 2vm "f	& BA%R$+b!e34QU+q2v6Q>? R2q501 a1q5)B.	/
 R!b) b2q5) -22 AgQQVbLAE23FRUN+ , C}r2   r   c                    || j         }|t          | dd          }n|dk    rt          j        |          }|t          | dd          }t          j        ||d |j        d                            }||z   |z   }|dk    rt          j        |          S |dk    r|S |dk    r6t          j        |          }	|d         }
| j        }|	d|
|	|z  z  z   d	z  z  }|S |d
k    r|At          j        t          j	        dt          j
        | j                  dz                       }|                     ||||          d d d f         }t          j        |||d         | j        dz             S t          d          )NrX  r
   r   r(   r   r   r   r(  r%   r  r  zkeyword 'which' not recognized)rX   rd  r9   rY  r   r8   r6  r  r  r  r  r<   rn   r   pmfrL   )rW   rr   rX   rX  r   r   r  rj  r   r   r   pm1r   r   s                 r0   rn   zGeneralizedPoisson.predict  s    <9DtZ33HH]]vh''H>T8Q//Ff^djm^4558#f,F??6'??"hNe^^6'??D2JE'C1utSy00144DKf__=1bfTZ6H6H6J)K)KLLf4(%+  - --.QQW6B#Hb&*$($9A$=? ? ? ?@@@r2   c                      ddl m}  fd} | j        dddf         |          }|ddddf          j        z  }|ddddf         }t	          j        ||f          S )#  derivative of score_obs w.r.t. endog

        Parameters
        ----------
        params : ndarray
            parameter at which score is evaluated

        Returns
        -------
        derivative : ndarray_2d
            The derivative of the score_obs with respect to endog.
        r
   _approx_fprime_cs_scalarc                     | j         dk    r| j        d         dk    r| d d df         }                     |           }t          j        |          S Nr%   r(   r
   )r<   r5   r8   r  r9   r!  rA   sfrr   rW   s     r0   fz5GeneralizedPoisson._deriv_score_obs_dendog.<locals>.f  U    v{{qwqzQaaadG""6"33B?2&&&r2   Nr(   r%   statsmodels.tools.numdiffrY  r<   rX   r9   r!  rW   rr   rY  r_  dsfd1d2s   ``     r0   r  z*GeneralizedPoisson._deriv_score_obs_dendog  s     	GFFFFF	' 	' 	' 	' 	' 	' '&tz!!!T'':A>>BQBZ$)#AaC[Bx(((r2   c                 F    |d         }| j         }|d|||z  z  z   dz  z  }|S )r  r(  r(   r%   r  )rW   r   rr   r   rU  r   s         r0   r  zGeneralizedPoisson._var	  s6    
 r
#QS(1,,r2   c                 p    |d         }| j         }t          j        | d|||z  z  z   z            }d|z
  }|S r  r(  r(   )r  r9   r6  )rW   r   rr   r   rU  	prob_zeror  s          r0   r  z GeneralizedPoisson._prob_nonzero	  sF    
 r
#FR41ur3w#6788	i-r2   c                 z    |                      ||||          }| j        dz   }t          ||d         |          }|S )rQ  r  r(   r(  )rn   r  r   )rW   rr   rX   rX  r   r   r  r  s           r0   r  z#GeneralizedPoisson.get_distribution	  sD     \\&thv\NN!A%RQ//r2   )r(   NNrV  Tr  Nr  rx   r(   r(   NFr  NNNr  r}  r   )!r   r   r   r   r  r  r  r   rT   r`  r  r  r  r   r  r  r  rP   r   r   r  r  r  r>  r   r  r   rn   r  r  r  r  r   r   s   @r0   r   r     s        + 01 4CC
D 
DDG0 15;?" " " " " "    
! ! !/ / /0&; &; &;P X)**    +*     X	  Xm'((<>BGOS6 6 6 6 6 )( 6p Xm+3448<IMIM$? $? $? $? $? 54$?L& & &6     6  >J J JXG G GR Xgo%&&?C'+#A #A #A '&#AJ) ) ):   	 	 	 Xg&.//   0/    r2   r   c                       e Zd Zd                    ej        ej        ez             ZdZ	e
d             Zd Zd Ze
d             Zd Zd	 Zd
 Zd Zd Zd Zd Z eej        j                  	 	 d fd	            Zd Z xZS )r   aG  
    Logit Model

    {params}
    offset : array_like
        Offset is added to the linear prediction with coefficient equal to 1.
    {extra_params}

    Attributes
    ----------
    endog : ndarray
        A reference to the endogenous response variable
    exog : ndarray
        A reference to the exogenous design.
    r  Tc                 :    ddl m} |                                }|S Nr
   ro  )rq  rp  r   rW   rp  r   s      r0   r   z
Logit.link5	  s&    555555{{}}r2   c                 `    t          j        |          }ddt          j        |           z   z  S )a  
        The logistic cumulative distribution function

        Parameters
        ----------
        X : array_like
            `X` is the linear predictor of the logit model.  See notes.

        Returns
        -------
        1/(1 + exp(-X))

        Notes
        -----
        In the logit model,

        .. math:: \Lambda\left(x^{\prime}\beta\right)=
                  \text{Prob}\left(Y=1|x\right)=
                  \frac{e^{x^{\prime}\beta}}{1+e^{x^{\prime}\beta}}
        r(   r9   r:   r6  rf   s     r0   rh   z	Logit.cdf;	  s*    * JqMM!BFA2JJ,r2   c                     t          j        |          }t          j        |           dt          j        |           z   dz  z  S )a2  
        The logistic probability density function

        Parameters
        ----------
        X : array_like
            `X` is the linear predictor of the logit model.  See notes.

        Returns
        -------
        pdf : ndarray
            The value of the Logit probability mass function, PMF, for each
            point of X. ``np.exp(-x)/(1+np.exp(-X))**2``

        Notes
        -----
        In the logit model,

        .. math:: \lambda\left(x^{\prime}\beta\right)=\frac{e^{-x^{\prime}\beta}}{\left(1+e^{-x^{\prime}\beta}\right)^{2}}
        r(   r%   rs  rf   s     r0   rk   z	Logit.pdfS	  s9    * JqMMvqbzz1RVQBZZ<!+++r2   c                 6    ddl m} |                                S r  )r  r  Binomialr  s     r0   r  zLogit.familyk	  s&    //////  """r2   c                     d| j         z  dz
  }|                     |d          }t          j        t          j        |                     ||z                                S )a?  
        Log-likelihood of logit model.

        Parameters
        ----------
        params : array_like
            The parameters of the logit model.

        Returns
        -------
        loglike : float
            The log-likelihood function of the model evaluated at `params`.
            See notes.

        Notes
        -----
        .. math::

           \ln L=\sum_{i}\ln\Lambda
           \left(q_{i}x_{i}^{\prime}\beta\right)

        Where :math:`q=2y-1`. This simplification comes from the fact that the
        logistic distribution is symmetric.
        r%   r(   r   r   )r<   rn   r9   r   rY  rh   rW   rr   r  r   s       r0   r  zLogit.loglikep	  sS    2 djL1,,vX,66vbfTXXa'k2233444r2   c                     d| j         z  dz
  }|                     |d          }t          j        |                     ||z                      S )a  
        Log-likelihood of logit model for each observation.

        Parameters
        ----------
        params : array_like
            The parameters of the logit model.

        Returns
        -------
        loglike : ndarray
            The log likelihood for each observation of the model evaluated
            at `params`. See Notes

        Notes
        -----
        .. math::

           \ln L=\sum_{i}\ln\Lambda
           \left(q_{i}x_{i}^{\prime}\beta\right)

        for observations :math:`i=1,...,n`

        where :math:`q=2y-1`. This simplification comes from the fact that the
        logistic distribution is symmetric.
        r%   r(   r   r   )r<   rn   r9   rY  rh   rx  s       r0   r  zLogit.loglikeobs	  sI    6 djL1,,vX,66vdhhq7{++,,,r2   c                 x    | j         }| j        }|                     |          }t          j        ||z
  |          S )a  
        Logit model score (gradient) vector of the log-likelihood

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        score : ndarray, 1-D
            The score vector of the model, i.e. the first derivative of the
            loglikelihood function, evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial\ln L}{\partial\beta}=\sum_{i=1}^{n}\left(y_{i}-\Lambda_{i}\right)x_{i}
        )r<   rX   rn   r9   r   rW   rr   rA   rg   rj  s        r0   r  zLogit.score	  s9    ( JIf%%va&j!$$$r2   c                 l    | j         }| j        }|                     |          }||z
  dddf         |z  S )a  
        Logit model Jacobian of the log-likelihood for each observation

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        jac : array_like
            The derivative of the loglikelihood for each observation evaluated
            at `params`.

        Notes
        -----
        .. math:: \frac{\partial\ln L_{i}}{\partial\beta}=\left(y_{i}-\Lambda_{i}\right)x_{i}

        for observations :math:`i=1,...,n`
        N)r<   rX   rn   r{  s        r0   r  zLogit.score_obs	  s?    , JIf%%F
AAAdF#a''r2   c                 D    | j         }|                     |          }||z
  S )aj  
        Logit model derivative of the log-likelihood with respect to linpred.

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        score_factor : array_like
            The derivative of the loglikelihood for each observation evaluated
            at `params`.

        Notes
        -----
        .. math:: \frac{\partial\ln L_{i}}{\partial\beta}=\left(y_{i}-\lambda_{i}\right)

        for observations :math:`i=1,...,n`

        where the loglinear model is assumed

        .. math:: \ln\lambda_{i}=x_{i}\beta
        )r<   rn   )rW   rr   rA   rj  s       r0   r  zLogit.score_factor	  s&    2 Jf%%F
r2   c                     | j         }|                     |          }t          j        |d|z
  z  |j        z  |           S )a  
        Logit model Hessian matrix of the log-likelihood

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        hess : ndarray, (k_vars, k_vars)
            The Hessian, second derivative of loglikelihood function,
            evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial^{2}\ln L}{\partial\beta\partial\beta^{\prime}}=-\sum_{i}\Lambda_{i}\left(1-\Lambda_{i}\right)x_{i}x_{i}^{\prime}
        r(   )rX   rn   r9   r   r:  )rW   rr   rg   r  s       r0   r   zLogit.hessian	  s?    & ILL  q!A#wqs{1%%%%r2   c                 >    |                      |          }| d|z
  z  S )ak  
        Logit model Hessian factor

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        hess : ndarray, (nobs,)
            The Hessian factor, second derivative of loglikelihood function
            with respect to the linear predictor evaluated at `params`
        r(   )rn   )rW   rr   r  s      r0   r  zLogit.hessian_factor
  s%     LL  rQU|r2   Nrw   rx   r(   c           
           t                      j        d||||||d|}t          | |          }	t          |	          S ru  )rS   r   LogitResultsBinaryResultsWrapperrW   r{   rK   r|   r}   r~   r   rZ   r   r   r[   s             r0   r   z	Logit.fit&
  s`     %''+ (<%+&-*5#''/( ( !'( ( #411#K000r2   c                     | j         S )  derivative of score_obs w.r.t. endog

        Parameters
        ----------
        params : ndarray
            parameter at which score is evaluated

        Returns
        -------
        derivative : ndarray_2d
            The derivative of the score_obs with respect to endog. This
            can is given by `score_factor0[:, None] * exog` where
            `score_factor0` is the score_factor without the residual.
        r  r  s     r0   r  zLogit._deriv_score_obs_dendog4
  s     yr2   r   )r   r   r   rM   r   r  r  r  r   r   r   r   rh   rk   r  r  r  r  r  r  r   r  r   rP   r   r  r   r   s   @r0   r   r   !	  sc        	d,//A 	 	C 	C " N  ^
     0, , ,0 # # ^#5 5 5:- - ->% % %2( ( (6  :& & &.  $ Xm'((>@,01 1 1 1 1 )(1      r2   r   c                        e Zd Zd                    ej        ej        ez             Ze	d             Z
d Zd Zd Zd Zd Zd	 Zd
 Zd Zd Z eej        j                  	 	 d fd	            Zd Z xZS )r   aH  
    Probit Model

    {params}
    offset : array_like
        Offset is added to the linear prediction with coefficient equal to 1.
    {extra_params}

    Attributes
    ----------
    endog : ndarray
        A reference to the endogenous response variable
    exog : ndarray
        A reference to the exogenous design.
    r  c                 :    ddl m} |                                }|S rp  )rq  rp  r   rq  s      r0   r   zProbit.linkX
  s&    555555||~~r2   c                 @    t           j                            |          S )an  
        Probit (Normal) cumulative distribution function

        Parameters
        ----------
        X : array_like
            The linear predictor of the model (XB).

        Returns
        -------
        cdf : ndarray
            The cdf evaluated at `X`.

        Notes
        -----
        This function is just an alias for scipy.stats.norm.cdf
        )r   norm_cdfrf   s     r0   rh   z
Probit.cdf^
  s    $ zq!!!r2   c                 h    t          j        |          }t          j                            |          S )a  
        Probit (Normal) probability density function

        Parameters
        ----------
        X : array_like
            The linear predictor of the model (XB).

        Returns
        -------
        pdf : ndarray
            The value of the normal density function for each point of X.

        Notes
        -----
        This function is just an alias for scipy.stats.norm.pdf
        )r9   r:   r   r  _pdfrf   s     r0   rk   z
Probit.pdfr
  s%    $ JqMMzq!!!r2   c           
          d| j         z  dz
  }|                     |d          }t          j        t          j        t          j        |                     ||z            t          d                              S )a=  
        Log-likelihood of probit model (i.e., the normal distribution).

        Parameters
        ----------
        params : array_like
            The parameters of the model.

        Returns
        -------
        loglike : float
            The log-likelihood function of the model evaluated at `params`.
            See notes.

        Notes
        -----
        .. math:: \ln L=\sum_{i}\ln\Phi\left(q_{i}x_{i}^{\prime}\beta\right)

        Where :math:`q=2y-1`. This simplification comes from the fact that the
        normal distribution is symmetric.
        r%   r(   r   r   )r<   rn   r9   r   rY  r  rh   	FLOAT_EPSrx  s       r0   r  zProbit.loglike
  sa    . djL1,,vX,66vbfRWTXXa'k%:%:IqIIJJKKKr2   c                     d| j         z  dz
  }|                     |d          }t          j        t          j        |                     ||z            t          d                    S )ai  
        Log-likelihood of probit model for each observation

        Parameters
        ----------
        params : array_like
            The parameters of the model.

        Returns
        -------
        loglike : array_like
            The log likelihood for each observation of the model evaluated
            at `params`. See Notes

        Notes
        -----
        .. math:: \ln L_{i}=\ln\Phi\left(q_{i}x_{i}^{\prime}\beta\right)

        for observations :math:`i=1,...,n`

        where :math:`q=2y-1`. This simplification comes from the fact that the
        normal distribution is symmetric.
        r%   r(   r   r   )r<   rn   r9   rY  r  rh   r  rx  s       r0   r  zProbit.loglikeobs
  sW    2 djL1,,vX,66vbgdhhqy119a@@AAAr2   c                 0   | j         }| j        }|                     |d          }d|z  dz
  }||                     ||z            z  t	          j        |                     ||z            t          dt          z
            z  }t	          j        ||          S )a  
        Probit model score (gradient) vector

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        score : ndarray, 1-D
            The score vector of the model, i.e. the first derivative of the
            loglikelihood function, evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial\ln L}{\partial\beta}=\sum_{i=1}^{n}\left[\frac{q_{i}\phi\left(q_{i}x_{i}^{\prime}\beta\right)}{\Phi\left(q_{i}x_{i}^{\prime}\beta\right)}\right]x_{i}

        Where :math:`q=2y-1`. This simplification comes from the fact that the
        normal distribution is symmetric.
        r   r   r%   r(   )	r<   rX   rn   rk   r9   r  rh   r  r   rW   rr   rA   rg   r  r  r  s          r0   r  zProbit.score
  s    , JI\\&\11aC!GdhhqtnnRWTXXad^^YINNNva{{r2   c                 $   | j         }| j        }|                     |d          }d|z  dz
  }||                     ||z            z  t	          j        |                     ||z            t          dt          z
            z  }|dddf         |z  S )a  
        Probit model Jacobian for each observation

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        jac : array_like
            The derivative of the loglikelihood for each observation evaluated
            at `params`.

        Notes
        -----
        .. math:: \frac{\partial\ln L_{i}}{\partial\beta}=\left[\frac{q_{i}\phi\left(q_{i}x_{i}^{\prime}\beta\right)}{\Phi\left(q_{i}x_{i}^{\prime}\beta\right)}\right]x_{i}

        for observations :math:`i=1,...,n`

        Where :math:`q=2y-1`. This simplification comes from the fact that the
        normal distribution is symmetric.
        r   r   r%   r(   N)r<   rX   rn   rk   r9   r  rh   r  r  s          r0   r  zProbit.score_obs
  s    0 JI\\&\11aC!GdhhqtnnRWTXXad^^YINNN4y1}r2   c                     | j         }|                     |d          }d|z  dz
  }||                     ||z            z  t          j        |                     ||z            t          dt          z
            z  }|S )a  
        Probit model Jacobian for each observation

        Parameters
        ----------
        params : array-like
            The parameters of the model

        Returns
        -------
        score_factor : array_like (nobs,)
            The derivative of the loglikelihood function for each observation
            with respect to linear predictor evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial\ln L_{i}}{\partial\beta}=\left[\frac{q_{i}\phi\left(q_{i}x_{i}^{\prime}\beta\right)}{\Phi\left(q_{i}x_{i}^{\prime}\beta\right)}\right]x_{i}

        for observations :math:`i=1,...,n`

        Where :math:`q=2y-1`. This simplification comes from the fact that the
        normal distribution is symmetric.
        r   r   r%   r(   )r<   rn   rk   r9   r  rh   r  )rW   rr   rA   r  r  r  s         r0   r  zProbit.score_factor
  so    0 J\\&\11aC!GdhhqtnnRWTXXad^^YINNNr2   c                    | j         }|                     |d          }d| j        z  dz
  }||                     ||z            z  |                     ||z            z  }t          j        | ||z   z  |j        z  |          S )a  
        Probit model Hessian matrix of the log-likelihood

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        hess : ndarray, (k_vars, k_vars)
            The Hessian, second derivative of loglikelihood function,
            evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial^{2}\ln L}{\partial\beta\partial\beta^{\prime}}=-\lambda_{i}\left(\lambda_{i}+x_{i}^{\prime}\beta\right)x_{i}x_{i}^{\prime}

        where

        .. math:: \lambda_{i}=\frac{q_{i}\phi\left(q_{i}x_{i}^{\prime}\beta\right)}{\Phi\left(q_{i}x_{i}^{\prime}\beta\right)}

        and :math:`q=2y-1`
        r   r   r%   r(   )rX   rn   r<   rk   rh   r9   r   r:  )rW   rr   rg   r  r  r  s         r0   r   zProbit.hessian  s}    2 I\\&\11djL1dhhqtnnTXXad^^+vqb!B$imA&&&r2   c                     |                      |d          }d| j        z  dz
  }||                     ||z            z  |                     ||z            z  }| ||z   z  S )a  
        Probit model Hessian factor of the log-likelihood

        Parameters
        ----------
        params : array-like
            The parameters of the model

        Returns
        -------
        hess : ndarray, (nobs,)
            The Hessian factor, second derivative of loglikelihood function
            with respect to linear predictor evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial^{2}\ln L}{\partial\beta\partial\beta^{\prime}}=-\lambda_{i}\left(\lambda_{i}+x_{i}^{\prime}\beta\right)x_{i}x_{i}^{\prime}

        where

        .. math:: \lambda_{i}=\frac{q_{i}\phi\left(q_{i}x_{i}^{\prime}\beta\right)}{\Phi\left(q_{i}x_{i}^{\prime}\beta\right)}

        and :math:`q=2y-1`
        r   r   r%   r(   )rn   r<   rk   rh   )rW   rr   r  r  r  s        r0   r  zProbit.hessian_factor>  sh    2 \\&\11
NQR   488AF#3#33rQV}r2   Nrw   rx   r(   c           
           t                      j        d||||||d|}t          | |          }	t          |	          S ru  )rS   r   ProbitResultsr  r  s             r0   r   z
Probit.fit\  s`     %''+ (<%+&-*5#''/( ( !'( ( $D'22#K000r2   c                    |                      |d          }|                     |          }t          j        |                     |          t
          dt
          z
            }||z  d|z
  z  }|dddf         | j        z  S )r  r   r   r(   N)rn   rk   r9   r  rh   r  rX   )rW   rr   r   pdf_cdf_derivs         r0   r  zProbit._deriv_score_obs_dendogi  sx      ,,vX,66xx  wtxx(()Q]CCtq4x(QQQW~	))r2   r   )r   r   r   rM   r   r  r  r  r   r   r   rh   rk   r  r  r  r  r  r   r  r   rP   r   r  r   r   s   @r0   r   r   F
  sK        	d,//A 	 	C 	C "   ^
" " "(" " ",L L L6B B B<  <  @  @' ' '>  < Xm'((>@,0
1 
1 
1 
1 
1 )(
1* * * * * * *r2   r   c                        e Zd Zd                    ej        ez             Zd fd	Zd Z	d Z
d Zd Zd	 Zd
 Zd Zd Z xZS )r   a  
    Multinomial Logit Model

    Parameters
    ----------
    endog : array_like
        `endog` is an 1-d vector of the endogenous response.  `endog` can
        contain strings, ints, or floats or may be a pandas Categorical Series.
        Note that if it contains strings, every distinct string will be a
        category.  No stripping of whitespace is done.
    exog : array_like
        A nobs x k array where `nobs` is the number of observations and `k`
        is the number of regressors. An intercept is not included by default
        and should be added by the user. See `statsmodels.tools.add_constant`.
    {extra_params}

    Attributes
    ----------
    endog : ndarray
        A reference to the endogenous response variable
    exog : ndarray
        A reference to the exogenous design.
    J : float
        The number of choices for the endogenous variable. Note that this
        is zero-indexed.
    K : float
        The actual number of parameters for the exogenous design.  Includes
        the constant if the design has one.
    names : dict
        A dictionary mapping the column number in `wendog` to the variables
        in `endog`.
    wendog : ndarray
        An n x j array where j is the number of unique categories in `endog`.
        Each column of j is a dummy variable indicating the category of
        each observation. See `names` for a dictionary mapping each column to
        its category.

    Notes
    -----
    See developer notes for further information on `MNLogit` internals.
    )r  Tc                 ^    t                      j        ||fd|i| | j        }| j        t                                        fdt          t          | j                            D             t          j
        dd          | j        j        f|d f          }|| j        _        d S )NrY   c                      g | ]
}|         S r+   r+   r-   r  r>   s     r0   rK  z$MNLogit.__init__.<locals>.<listcomp>  s    <<<#&+<<<r2   r(   )names)rS   rT   endog_namesr  r-  _maybe_convert_ynames_intr7   r7  r  r   from_productr   xnames	cov_names)	rW   r<   rX   rY   rZ   rE   idxr>   r[   s	          @r0   rT   zMNLogit.__init__  s    FFFvFFF  !#==fEE<<<<s46{{););<<<%vabbz493C&D-2DM; ; ;!	r2   c                     t           )z 
        NotImplemented
        rd   )rW   rA  s     r0   rk   zMNLogit.pdf  ri   r2   c                     t          j        t          j        t          |                    t          j        |          f          }||                    d          dddf         z  S )a  
        Multinomial logit cumulative distribution function.

        Parameters
        ----------
        X : ndarray
            The linear predictor of the model XB.

        Returns
        -------
        cdf : ndarray
            The cdf evaluated at `X`.

        Notes
        -----
        In the multinomial logit model.
        .. math:: \frac{\exp\left(\beta_{j}^{\prime}x_{i}\right)}{\sum_{k=0}^{J}\exp\left(\beta_{k}^{\prime}x_{i}\right)}
        r(   N)r9   r!  r   r"  r6  r   )rW   rg   rA  s      r0   rh   zMNLogit.cdf  sP    & orws1vvq		:;;3771::aaaf%%%r2   c                     |                     | j        dd          }| j        }t          j        |                     t          j        | j        |                              }t          j        ||z            S )a  
        Log-likelihood of the multinomial logit model.

        Parameters
        ----------
        params : array_like
            The parameters of the multinomial logit model.

        Returns
        -------
        loglike : float
            The log-likelihood function of the model evaluated at `params`.
            See notes.

        Notes
        -----
        .. math::

           \ln L=\sum_{i=1}^{n}\sum_{j=0}^{J}d_{ij}\ln
           \left(\frac{\exp\left(\beta_{j}^{\prime}x_{i}\right)}
           {\sum_{k=0}^{J}
           \exp\left(\beta_{k}^{\prime}x_{i}\right)}\right)

        where :math:`d_{ij}=1` if individual `i` chose alternative `j` and 0
        if not.
        r(  r)  r*  )	r,  r  r  r9   rY  rh   r   rX   r   rW   rr   dlogprobs       r0   r  zMNLogit.loglike  sa    6 #66K&"&6":":;;<<va'k"""r2   c                     |                     | j        dd          }| j        }t          j        |                     t          j        | j        |                              }||z  S )a  
        Log-likelihood of the multinomial logit model for each observation.

        Parameters
        ----------
        params : array_like
            The parameters of the multinomial logit model.

        Returns
        -------
        loglike : array_like
            The log likelihood for each observation of the model evaluated
            at `params`. See Notes

        Notes
        -----
        .. math::

           \ln L_{i}=\sum_{j=0}^{J}d_{ij}\ln
           \left(\frac{\exp\left(\beta_{j}^{\prime}x_{i}\right)}
           {\sum_{k=0}^{J}
           \exp\left(\beta_{k}^{\prime}x_{i}\right)}\right)

        for observations :math:`i=1,...,n`

        where :math:`d_{ij}=1` if individual `i` chose alternative `j` and 0
        if not.
        r(  r)  r*  )r,  r  r  r9   rY  rh   r   rX   r  s       r0   r  zMNLogit.loglikeobs  sW    : #66K&"&6":":;;<<7{r2   c                 8   |                     | j        dd          }| j        ddddf         |                     t	          j        | j        |                    ddddf         z
  }t	          j        |j        | j                                                  S )a8  
        Score matrix for multinomial logit model log-likelihood

        Parameters
        ----------
        params : ndarray
            The parameters of the multinomial logit model.

        Returns
        -------
        score : ndarray, (K * (J-1),)
            The 2-d score vector, i.e. the first derivative of the
            loglikelihood function, of the multinomial logit model evaluated at
            `params`.

        Notes
        -----
        .. math:: \frac{\partial\ln L}{\partial\beta_{j}}=\sum_{i}\left(d_{ij}-\frac{\exp\left(\beta_{j}^{\prime}x_{i}\right)}{\sum_{k=0}^{J}\exp\left(\beta_{k}^{\prime}x_{i}\right)}\right)x_{i}

        for :math:`j=1,...,J`

        In the multinomial model the score matrix is K x J-1 but is returned
        as a flattened array to work with the solvers.
        r(  r)  r*  Nr(   )	r,  r  r  rh   r9   r   rX   r:  flattenrW   rr   	firstterms      r0   r  zMNLogit.score  s    2 #66K!""%	282: 2: ); );;<11QRR4)A A	 vik49--55777r2   c                    |                     | j        dd          }|                     t          j        | j        |                    }t          j        | j        t          j        |          z            }| j        ddddf         |ddddf         z
  }t          j        |j	        | j                  
                                }||fS )z
        Returns log likelihood and score, efficiently reusing calculations.

        Note that both of these returned quantities will need to be negated
        before being minimized by the maximum likelihood fitting machinery.
        r(  r)  r*  Nr(   )r,  r  rh   r9   r   rX   r   r  rY  r:  r  )rW   rr   cdf_dot_exog_paramsloglike_valuer  score_arrays         r0   loglike_and_scorezMNLogit.loglike_and_score7  s     #66"hhrvdi'@'@AAt{RV4G-H-HHIIK122&)<QQQU)CC	fY[$)44<<>>k))r2   c                 f   |                     | j        dd          }| j        ddddf         |                     t	          j        | j        |                    ddddf         z
  }|dddddf         | j        dddddf         z                       | j        j        d         d          S )a\  
        Jacobian matrix for multinomial logit model log-likelihood

        Parameters
        ----------
        params : ndarray
            The parameters of the multinomial logit model.

        Returns
        -------
        jac : array_like
            The derivative of the loglikelihood for each observation evaluated
            at `params` .

        Notes
        -----
        .. math:: \frac{\partial\ln L_{i}}{\partial\beta_{j}}=\left(d_{ij}-\frac{\exp\left(\beta_{j}^{\prime}x_{i}\right)}{\sum_{k=0}^{J}\exp\left(\beta_{k}^{\prime}x_{i}\right)}\right)x_{i}

        for :math:`j=1,...,J`, for observations :math:`i=1,...,n`

        In the multinomial model the score vector is K x (J-1) but is returned
        as a flattened array. The Jacobian has the observations in rows and
        the flattened array of derivatives in columns.
        r(  r)  r*  Nr(   r
   )r,  r  r  rh   r9   r   rX   r8   r  s      r0   r  zMNLogit.score_obsE  s    2 #66K!""%	282: 2: ); );;<11QRR4)A A	 !!!AAAd(#di$qqq&99BB49?STCUWYZZZr2   c                 R   |                     | j        dd          }| j        }|                     t	          j        ||                    }g }| j        }| j        }t          |dz
            D ]}t          |dz
            D ]}||k    r\|                    t	          j        |dd|dz   f         d|dd|dz   f         z
  z  dddf         |z  j	        |                      d|                    t	          j        |dd|dz   f         |dd|dz   f          z  dddf         |z  j	        |                      t	          j
        |          }	t	          j        |	                     |dz
  |dz
  ||          d                               |dz
  |z  |dz
  |z            }	|	S )a  
        Multinomial logit Hessian matrix of the log-likelihood

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        hess : ndarray, (J*K, J*K)
            The Hessian, second derivative of loglikelihood function with
            respect to the flattened parameters, evaluated at `params`

        Notes
        -----
        .. math:: \frac{\partial^{2}\ln L}{\partial\beta_{j}\partial\beta_{l}}=-\sum_{i=1}^{n}\frac{\exp\left(\beta_{j}^{\prime}x_{i}\right)}{\sum_{k=0}^{J}\exp\left(\beta_{k}^{\prime}x_{i}\right)}\left[\boldsymbol{1}\left(j=l\right)-\frac{\exp\left(\beta_{l}^{\prime}x_{i}\right)}{\sum_{k=0}^{J}\exp\left(\beta_{k}^{\prime}x_{i}\right)}\right]x_{i}x_{l}^{\prime}

        where
        :math:`\boldsymbol{1}\left(j=l\right)` equals 1 if `j` = `l` and 0
        otherwise.

        The actual Hessian matrix has J**2 * K x K elements. Our Hessian
        is reshaped to be square (J*K, J*K) so that the solvers can use it.

        This implementation does not take advantage of the symmetry of
        the Hessian and could probably be refactored for speed.
        r(  r)  r*  r(   N)r
   r%   r(   r@  )r,  r  rX   rh   r9   r   r  r7   r  r:  r   r;  )
rW   rr   rg   prpartialsr  r  r.   rM  r   s
             r0   r   zMNLogit.hessiand  s   : #66IXXbfQv&&''FFqs 	U 	UA1Q3ZZ U U66OO"QQQqsU)Qr!!!AaC%y["9111T6!B1!D GJJJL L L L OORVb1Q3iAAAacE
.BAAAdF-KA-M,PQR%S%S$STTTTU HXL1Q3!Q22LAAII1Q3PQ'TUVWTWYZSZ[[r2   r   )r   r   r   rM   r   r  r  r   rT   rk   rh   r  r  r  r  r  r   r   r   s   @r0   r   r     s        (P 	D3oEFFQ T" " " " " "" " "& & &,# # #@     D8 8 8>* * *[ [ [>- - - - - - -r2   r   c                       e Zd Zdej        dej        z   ez   dz  Z	 	 d* fd	Zd	 Z	d
 Z
d Zd+dZd Zd Zd Zd Zd Zd+dZd Zd Zd Zd Zd Z eej        j                  	 	 d,d            Z ee          d             Zd-dZ	 	 	 	 d. fd!	Z	 	 	 	 d/ fd(	Z eej         j                  d0d)            Z  xZ!S )1r   a  
    Negative Binomial Model

    %(params)s
    %(extra_params)s

    Attributes
    ----------
    endog : ndarray
        A reference to the endogenous response variable
    exog : ndarray
        A reference to the exogenous design.

    References
    ----------
    Greene, W. 2008. "Functional forms for the negative binomial model
        for count data". Economics Letters. Volume 99, Number 3, pp.585-590.
    Hilbe, J.M. 2011. "Negative binomial regression". Cambridge University
        Press.
    a>  loglike_method : str
        Log-likelihood type. 'nb2','nb1', or 'geometric'.
        Fitted value :math:`\mu`
        Heterogeneity parameter :math:`\alpha`

        - nb2: Variance equal to :math:`\mu + \alpha\mu^2` (most common)
        - nb1: Variance equal to :math:`\mu + \alpha\mu`
        - geometric: Variance equal to :math:`\mu + \mu^2`
    offset : array_like
        Offset is added to the linear prediction with coefficient equal to 1.
    exposure : array_like
        Log(exposure) is added to the linear prediction with coefficient
        equal to 1.
    r  nb2NrV  Tc                     t                      j        ||f||||d| || _        |                                  |dv r"| j                            d           d| _        nd| _        | j                            d           d S )Nr  )r  nb1r   r(   r
   loglike_method)rS   rT   r  _initializer  r  rV   
_init_keys)
rW   r<   rX   r  r   rX  r  rY   rZ   r[   s
            r0   rT   zNegativeBinomial.__init__  s    	# &"*!($.	# 	# "	# 	# 	# -^++O""7+++DLLDL 	/00000r2   c                 b   | j         dk    r-| j        | _        | j        | _        | j        | _        d| _        d S | j         dk    r-| j        | _        | j	        | _        | j
        | _        d| _        d S | j         dk    r&| j        | _        | j        | _        | j        | _        d S t          d          )Nr  Tr  	geometricz0Likelihood type must "nb1", "nb2" or "geometric")r  _hessian_nb2r   _score_nbinr  _ll_nb2r  r  _hessian_nb1
_score_nb1_ll_nb1_hessian_geom_score_geom_ll_geometricrL   r  s    r0   r  zNegativeBinomial._initialize	  s    %'',DL)DJ"lDO $D E)),DLDJ"lDO $D K//-DL)DJ"0DOOO . / / /r2   c                 J    | j                                         }|d= |d= |d= |S )Nr   r  r  )r  copy)rW   odicts     r0   __getstate__zNegativeBinomial.__getstate__  s1    ""$$)'N,r2   c                 b    | j                             |           |                                  d S r  )r  r  r  )rW   indicts     r0   __setstate__zNegativeBinomial.__setstate__$  s0    V$$$r2   r
   c                    t          j        t          j        |                    st          j        |          rt          }nt          }| j        }|                     |          }d|z  ||z  z  }|||z   z  } |||z              ||dz             z
   ||          z
  }	|	|t          j        |          z  z   |t          j        d|z
            z  z   }
|
S )Nr(   )r9   r   	iscomplexr   r   r<   rn   rY  )rW   rr   r   Qgamma_lnr<   r   r  r  coeffllfs              r0   _ll_nbinzNegativeBinomial._ll_nbin(  s    6",v&&'' 	2<+>+> 	HHH
\\&!!wQT"W~$u*%%q(9(99$ d26$<<''%qv*>>
r2   c                     | j         rt          j        |d                   }n|d         }|                     |d d         |d          S )Nr(  r
   r  r  r9   r6  r  rW   rr   r   s      r0   r  zNegativeBinomial._ll_nb26  K     	F6":&&EE2JE}}VCRC[%1}555r2   c                     | j         rt          j        |d                   }n|d         }|                     |d d         |d          S )Nr(  r(   r  r  r  s      r0   r  zNegativeBinomial._ll_nb1=  r  r2   c                 0    |                      |dd          S Nr(   r
   )r  r  s     r0   r  zNegativeBinomial._ll_geometricD  s    }}VQ***r2   c                 T    t          j        |                     |                    }|S )a  
        Loglikelihood for negative binomial model

        Parameters
        ----------
        params : array_like
            The parameters of the model. If `loglike_method` is nb1 or
            nb2, then the ancillary parameter is expected to be the
            last element.

        Returns
        -------
        llf : float
            The loglikelihood value at `params`

        Notes
        -----
        Following notation in Greene (2008), with negative binomial
        heterogeneity parameter :math:`\alpha`:

        .. math::

           \lambda_i &= exp(X\beta) \\
           \theta &= 1 / \alpha \\
           g_i &= \theta \lambda_i^Q \\
           w_i &= g_i/(g_i + \lambda_i) \\
           r_i &= \theta / (\theta+\lambda_i) \\
           ln \mathcal{L}_i &= ln \Gamma(y_i+g_i) - ln \Gamma(1+y_i) + g_iln (r_i) + y_i ln(1-r_i)

        where :math`Q=0` for NB2 and geometric and :math:`Q=1` for NB1.
        For the geometric, :math:`\alpha=0` as well.
        r  )rW   rr   r  s      r0   r  zNegativeBinomial.loglikeH  s%    B fT__V,,--
r2   c                     | j         }| j        d d d f         }|                     |          d d d f         }|||z
  z  |dz   z  }|                    d          S r  )rX   r<   rn   r   )rW   rr   rX   rA   r   r6  s         r0   r  zNegativeBinomial._score_geoml  sa    yJqqq$w\\&!!!!!T'*!B$-A&{{1~~r2   c                    | j         rt          j        |d                   }n|d         }|dd         }| j        }| j        dddf         }|                     |          dddf         }d|z  ||z  z  }|||z   z  }|dk    rt          ||z             t          |          z
  }	||z  t          j        |          |	z   z  }
|||t          j        |          z  z
  ||	dz   z  z
  z  |t          j        |          |	z   z  z
  |dz  |dz   z  z                                  }n|dk    rt          ||z             t          |          z
  }	||z  ||z
  z  ||z   z  }
|dz   }|	t          j        |          z   t          j        ||z             z
  ||z
  ||z   z  z
                                  |z  }| j         r*t          j	        |
                    d          ||z  f         S t          j	        |
                    d          |f         S )z,
        Score vector for NB2 model
        r(  Nr(   r%   r
   )
r  r9   r6  rX   r<   rn   r   rY  r   r_)rW   rr   r  r   rX   rA   r   r  r  dgpartr6  r5  da1s                r0   r  zNegativeBinomial._score_nbins  s'     	F6":&&EE2JEyJqqqv\\&!!!!!D&)uWr1u_R"W~66QV__wr{{2FRi26$<<$ GB$5 5 &1*o!. /RVD\\!" ## q%!),	. 03suu	 F !VVQV__wr{{2F2g2&2.G"9*Crvbzz)&B--(+,R4"R%.9:=#%%#FF  	15Q5665Q/00r2   c                 0    |                      |d          S )Nr(   r  )r  r  s     r0   r  zNegativeBinomial._score_nb1  s    !,,,r2   c                    | j         }| j        d d d f         }|                     |          d d d f         }|j        d         }t	          j        ||f          }|d|z   z  |dz   dz  z  }t          |          D ]e}t          |          D ]S}	|	|k    r	t	          j        t	          j        |d d |d f          |d d |	d f         z  |z  d                    |||	f<   Tft	          j	        |d          }
|j
        |
         ||
<   |S )Nr(   r%   r
   r4  rA  )rX   r<   rn   r8   r9   rE  r7   rF  r   rG  r:  )rW   rr   rX   rA   r   rI  rJ  	const_arrr.   rM  rL  s              r0   r  zNegativeBinomial._hessian_geom  s8   yJqqqv\\&!!!!!D&) jm8S#J''!HbdQY&	s 	 	A3ZZ  q55 "
FD1TN?T!!!Ad(^;iG !  ! !1 /#+++$Jw/r2   c                    | j         rt          j        |d                   }n|d         }|dd         }| j        }| j        dddf         }|                     |          dddf         }||z  }t          ||z             t          |          z
  }dd|z   z  }|j        d         }	t          j        |	dz   |	dz   f          }
||z  t          j	        |          |z   z  }||z  }||z  }t          j        d||z             t          j        d|          z
  }t          |	          D ]}t          |	          D ]n}||k    r	t          j        t          j        |dd|df         |dd|df         z  |dd|df         |dd|df         z  |z  z   d                    |
||f<   ot          j        |	d          }|
j        |         |
|<   t          j        | |z  ||z  | |z  |dz  z  |z
  z  z   d          }||
dddf<   ||
dddf<   t          j	        |          }|dz  }|dz  }|dz  }||z  d|z  d|z  z   dz   z  d|z  |z  z
  d	|z  |z  ||z   z  z   |d|z  |z
  z  z   d|z  |z  |z  z   ||z  z   ||z  |z  z   d|z  |z  ||z   z  z   |d	z  |d|z  z   dz   z  z  }|                                |
d
<   |
S )z'
        Hessian of NB1 model.
        r(  Nr(   r
   r4  rA  r%   r@     rD  )r  r9   r6  rX   r<   rn   r   r8   rE  rY  r   r   r7   rF  r   rG  r:  )rW   rr   r   rX   rA   r   r  r  r  rI  rJ  r6  r4  	xmu_alphatrigammar.   rM  rL  rM  	log_alphaalpha3alpha2mu2dadas                           r0   r  zNegativeBinomial._hessian_nb1  s     	F6":&&EE2JEyJqqqv\\&!!!!!D&)XR72;;.AI jm8SU3q5M** ,"&,,"(#) * R2I	%aa00%a,,-s 
	 
	A3ZZ 	 	q55 "
F!D)E!!!Ad(O;!!!!Ad(+i!D.AAHLM  ! !1	 /#+++$Jw/ gr	"2eQh.5)7 7=>@ @ @ "CRC!"RF4LL	!eAiK!F(2Q676!6"i&012 1R4!8$% 5X%	& ),h	7 :@#9P	Q
 5Y/01 1Hfqw.235 ((**r2   c           	         | j         rt          j        |d                   }n|d         }d|z  }|dd         }| j        }| j        dddf         }|                     |          dddf         }|||z   z  }t          ||z             t          |          z
  }|j        d         }	t          j        |	dz   |	dz   f          }
||z  ||z   z  ||z   dz  z  }t          |	          D ]e}t          |	          D ]S}||k    r	t          j
        |dd|df          |dd|df         z  |z  d                                          |
||f<   Tft          j        |	d          }|
j        |         |
|<   |dz   }t          j
        ||z  ||z
  z  |dz  z  ||z   dz  z  d           }||
dddf<   ||
dddf<   d|d	z  z  }||t          j        |          z   ||z
  ||z   z  z
  z  }||z  |z  |dz  t          j        d||z             t          j        d|          z
  d|z  z   d||z   z  z
  ||z
  ||z   dz  z  z   z  z   
                                }||
d
<   |
S )z'
        Hessian of NB2 model.
        r(  r(   Nr%   r
   r4  rA  r  rD  )r  r9   r6  rX   r<   rn   r   r8   rE  r7   r   rF  rG  r:  rY  r   r   )rW   rr   r   r  rX   rA   r   r  r  rI  rJ  r  r.   rM  rL  r  rM  da2r5  r  s                       r0   r  zNegativeBinomial._hessian_nb2  s     	F6":&&EE2JEuWyJqqqv\\&!!!!!D&)R"W~a72;;. jm8SU3q5M**rE2a4L"R%!+	s 	D 	DA3ZZ D Dq55 "QQQqXaaa$h'G'0(178!: !: !::A')) 1D
 /#+++$Jw/ byj&D!B$A-r"uqj8BBBB!CRC!"R r	kF4LL!$%FRU#34 5fS 36W->q"Q$-G-G%a,,.-/0t.467bk.BVb2g\).* $+ +,/CEE 	 r2   c                 0    t          || j                  }|S r  )r   r  )rW   rr   scs      r0   r  zNegativeBinomial.score_obs'  s    fdo66	r2   r   c                 R   |"d}t          j        |t                     |du rd}|dk    r|                     ||||          }	|0t	          j        dt	          j        | j                  dz             }nt	          j        |          }|j	        dk    sJ |d         }|	
                    |          j        S |                     |||	          \  }}}t	          j        ||d |j        d                            }
|
|z   |z   }|d
k    rt	          j        |          S |                    d          r|S |dk    r^t	          j        |          }| j        dk    r	|d|z   z  }n4| j        dk    rd}n| j        dk    rd}|d         }|d|||dz
  z  z  z   z  }|S t%          d          )Nr   Tr   r  r  r
   r(   ).N)rX   r   rX  r   rg  r   r  r  r%   r  r(  rh  )rp   rq   r   r  r9   r  r  r<   r:   r5   rT  r:  re  r   r8   r6  ri  r  rL   )rW   rr   rX   rX  r   r   r   r  ru   r  rj  r   r   r   r  r   s                   r0   rn   zNegativeBinomial.predict+  s    DCM#}---~~  F??))!	 *  E 9Qtz(:(:Q(>??:h//=A%%%%	*H99X&&((!%!9!9 ": " "fh f^djm^4558#f,F??6'??"e$$ 	LNe^^B"k11QV}&%//AA(E11Ar
Qa!e!445KJKKKr2   c                    t          | dd          }t          | dd          }| j        t          j        ||z             z                                  }t          j        |          g}|t          j        ||z             z  }| j        |z
  }|                     |||j        d         dz
            }|                    |           t          j	        |          S r  r  r  s           r0   r  z'NegativeBinomial._get_start_params_nulla  s    x++4Q//bfVh%6777==??&--RVFX-...
R%%b%%+a.1:L%MMaxr2   c                     ||j         d         }| j        dk    r$|dz  |z  dz
  |z                                  |z  }n |dz  |z  dz
                                  |z  }|S )Nr
   r  r%   r(   )r8   r  r   )rW   r   r   r`   r  s        r0   r  z%NegativeBinomial._estimate_dispersionm  ss    {1~H%''(R-!#r)..008;AAB"''))H4Ar2   r  rx   r(   r  c           
      *   d| _         | j                            d          r|dvrd| _         n!| j                            d          rd| _         |At          | dd          t          | dd          z   }t	          j        |          dk    r|dk    rd }dddd	}|
|                    |
           t          | j        | j	        |
          }t          j                    5  t          j        d            |j        di |}d d d            n# 1 swxY w Y   |j        }| j                            d          rW|                     |                                |j        |j                  }t	          j        |t)          d|                    }n<| j         du r3t	          j        |d          }t	          j        |d                   |d<   |d } t/                      j        d||||||d|}|

|
|j        d<   | j                            d          rad| _         |dvr1t	          j        |j        j        d                   |j        j        d<   t7          | |j                  }t9          |          }n|}|i } |j        d|d|	d| |S )NFnbr
  Tr   r
   rX  r(   r  r   r  r  皙?)r  r(  c                      | S r  r+   r  s    r0   r'  z&NegativeBinomial.fit.<locals>.<lambda>  r  r2   r  r  r  r+   )r  r  ri  rd  r9   r  r  r   r<   rX   rp   r  r  r   rr   r  rn   r   r`   r  r  r   rY  rS   r  r6  r  NegativeBinomialResultsNegativeBinomialResultsWrapperr   )rW   r{   rK   r|   r}   r~   r   r  r  r  r  rZ   r   r"  r#  r$  r  r   nbinfitr&  r[   s                       r0   r   zNegativeBinomial.fitw  s.    "))$// 	&F CJ 5J 5J $D ++D11 	& %D T8Q//'$
A2N2NNFwv!##!#$dPUVVK ,""#4555dj$)FCCCG(** 5 5%h///%'+44445 5 5 5 5 5 5 5 5 5 5 5 5 5 5 #>L"--d33 E--goo.?.?7>7G . I I!ys4||DD D((!x4@@@#%6,r*:#;#;R #|H ',%,V$)4x' '  &' ' (7HF 34))$// 
	 %D...-/VFO4J24N-O-O&r*-dFODDG3G<<FFFH%%`x$e``W_```s   ""DDDrH   r   r   r   r   r   c                    t          |           | j                            d          rTt          j        |          dk    r<|dk    r6| j        j        d         | j        z   }|t          j        |          z  }d|d<   | j        r"t          j        |          dk    r
|d d         n|}d| _	        |t          | dd          t          | dd          z   }t          j        |          dk    r|dk    rd }t          | j        | j        |          }t          j                    5  t          j        d	            |j        d||||d||||	|
|d
|j        }d d d            n# 1 swxY w Y   | j                            d          rt          j        |d          } t'          t(          |           j        d|||||||||	|
|d
|}t+          | |          }t-          |          S )Nr  r(   r
   r(  Fr   rX  r   r  r   r*  r+   )rN   r  ri  r9   r  rX   r8   rV   r   r  rd  r   r<   rp   r  r  r   rr   r  rS   r	   L1NegativeBinomialResults L1NegativeBinomialResultsWrapperr-  s                      r0   r   z NegativeBinomial.fit_regularized  sl   
 	F###))$// 	RWU^^q5H5H5:aZZyq)DL8HBGH---EE"I "&P"'%..12D2D%**5! T8Q//'$
A2N2NNFwv!##!dj$)FCCCG(** 4 4%h///6w6  -!-fg +!h!Y"/}! -  -
 &, -  -
 .4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 "--d33 <!ys;;8z4((8 F)&''dXy+F	F F ?E	F F 0f==/<<<s   %3E$$E(+E(c                    |                      ||||          }| j        dk    rt          j        dd|z   z  d          }nK| j        dk    rd}n| j        dk    rd}|d         }d|z
  }	d	|z  ||	z  z  }
|
|
|z   z  }t	          |
|          }|S )
rQ  r  r  r(   r(  )locr  r%   r  r"   )rn   r  r   geomr   )rW   rr   rX   rX  r   r   r  r  r   r  r  r  s               r0   r  z!NegativeBinomial.get_distribution  s     \\&thv\NN+--JqAF|444EE"e++$--2JEAA:A%D4"9%D4&&Er2   )r  NNrV  Tr
   r  r  )
Nr  rx   r(   r(   Nr  NNNr  r   )"r   r   r   r   r  r  r  r   rT   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   rn   r  r  r  r   r   r  r   r   s   @r0   r   r     s{       & + 
!" %445 5'"5GH BF;?1 1 1 1 1 1(/ / /(       6 6 66 6 6+ + +" " "H  $1 $1 $1 $1L- - -  .A A AF. . .b   Xgo%&&?C483L 3L 3L '&3Lj X)**	  	  +*	     =?,07;"@ @ @ @ @ @F 9=IMIM+= += += += += +=Z Xg&.//   0/    r2   r   c                       e Zd Zdej        dej        z   ez   dz  Z	 	 d) fd	Z fd	Z	d
 Z
d Zd Zd Zd Zd*dZd Zd Z ee          d             Zd*dZ eej        j                  	 	 	 	 d+ fd	            Z eej        j                  	 	 	 	 d, fd!	            Z eej        j                  	 	 d-d#            Zd$ Zd% Zd*d&Zd' Z eej        j                  d.d(            Z xZ S )/r   a  
    Generalized Negative Binomial (NB-P) Model

    %(params)s
    %(extra_params)s

    Attributes
    ----------
    endog : ndarray
        A reference to the endogenous response variable
    exog : ndarray
        A reference to the exogenous design.
    p : scalar
        P denotes parameterizations for NB-P regression. p=1 for NB-1 and
        p=2 for NB-2. Default is p=1.
    a^  p : scalar
        P denotes parameterizations for NB regression. p=1 for NB-1 and
        p=2 for NB-2. Default is p=2.
    offset : array_like
        Offset is added to the linear prediction with coefficient equal to 1.
    exposure : array_like
        Log(exposure) is added to the linear prediction with coefficient
        equal to 1.
        r  r%   NrV  Tc                      t                      j        ||f||||d| || _        | j                            d           d| _        d| _        d S )Nr  r   r(   Fr  r  s
            r0   rT   zNegativeBinomialP.__init__  sz     		# &"*!($.	# 	# "	# 	# 	# !"w'''!r2   c                 \    t                                                      }| j        |d<   |S )Nr  r  ra  s     r0   r`  z NegativeBinomialP._get_init_kwds*  s)    ww%%'')S	r2   c                     | j         d fS r  r  r  s    r0   r  zNegativeBinomialP._get_exogs/  r  r2   c                 P    t          j        |                     |                    S )aU  
        Loglikelihood of Generalized Negative Binomial (NB-P) model

        Parameters
        ----------
        params : array_like
            The parameters of the model.

        Returns
        -------
        loglike : float
            The log-likelihood function of the model evaluated at `params`.
            See notes.
        r  r  s     r0   r  zNegativeBinomialP.loglike2  s      vdoof--...r2   c                    | j         rt          j        |d                   }n|d         }|dd         }| j        }| j        }|                     |          }|d|z
  z  }||z  }||z   }t          ||z             t          |dz             z
  t          |          z
  |t          j        |          z  z   |t          j        |          z  z   ||z   t          j        |          z  z
  }	|	S )as  
        Loglikelihood for observations of Generalized Negative Binomial (NB-P) model

        Parameters
        ----------
        params : array_like
            The parameters of the model.

        Returns
        -------
        loglike : ndarray
            The log likelihood for each observation of the model evaluated
            at `params`. See Notes
        r(  Nr%   r(   )r  r9   r6  r  r<   rn   r   rY  )
rW   rr   r   r  rA   r   r  r  r  r  s
             r0   r  zNegativeBinomialP.loglikeobsC  s      	F6":&&EE2JE!J\\&!!AE{E\"Wq2vQ/'"++=BF2JJ!"RVBZZ0B"&**$% 
r2   c                 2   | j         rt          j        |d                   }n|d         }|dd         }d| j        z
  }| j        }|                     |          }||z  }||z  }||z   }||z   }	||z  |z  }
t          |	          t          |          z
  }|t          j        ||z            z   dz   |	|z  z
  }|
|z  |	|z  z
  ||z  z   }| j        j	        |z  |z  j	        }| |z  |z  }t          j
        |t          j        |          j	        fd          S )a  
        Generalized Negative Binomial (NB-P) model score (gradient) vector of the log-likelihood for each observations.

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        score : ndarray, 1-D
            The score vector of the model, i.e. the first derivative of the
            loglikelihood function, evaluated at `params`
        r(  Nr%   r(   r4  )r  r9   r6  r  r<   rn   r   rY  rX   r:  r@  r  )rW   rr   r   r  rA   r   r  r  r  r2  r3  r  dgtermr6  r5  s                  r0   r  zNegativeBinomialP.score_obsf  sE     	F6":&&EE2JE%%J\\&!!1uE\"WVVb[wr{{*"&b//)A-R7 ;7r6 9;#g-0uv%~wf(=(=(?@#$& & & 	&r2   c                     t          j        |                     |          d          }| j        r|d         |d         dz  k     |S |S )a  
        Generalized Negative Binomial (NB-P) model score (gradient) vector of the log-likelihood

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        score : ndarray, 1-D
            The score vector of the model, i.e. the first derivative of the
            loglikelihood function, evaluated at `params`
        r
   r4  r(  r%   r8  r9  s      r0   r  zNegativeBinomialP.score  sP     t~~f--A666 	"Ira''LLr2   c                 6   t          j        |          }| j        rt          j        |d                   }n|d         }|dd         }d| j        z
  }|| j        n|}|                     |          }||z  }||z  }||z   }	||z   }
||z  |z  }t          |
          t          |          z
  }||z  |
|	z  z
  ||z  z   |d|
|	z  z
  t          j        ||	z            z   z  z   }||z  j	        }| |z  |t          j        ||	z            z   dz   |
|	z  z
  z  }||fS )a  
        Generalized Negative Binomial (NB-P) model score (gradient) vector of the log-likelihood for each observations.

        Parameters
        ----------
        params : array-like
            The parameters of the model

        Returns
        -------
        score : ndarray, 1-D
            The score vector of the model, i.e. the first derivative of the
            loglikelihood function, evaluated at `params`
        r(  Nr%   r(   )
r9   r:   r  r6  r  r<   rn   r   rY  r:  )rW   rr   r<   r   r  rA   r   r  r  r  r2  r3  r  r6  r5  s                  r0   r  zNegativeBinomialP.score_factor  sY    F## 	F6":&&EE2JE%%-DJJU\\&!!1uE\"WVVb[wr{{*K7r6!b2g+rBw"?@A <"#+!#R"1!""#%'"W"- . r2   c                    | j         rt          j        |d                   }n|d         }|dd         }d| j        z
  }| j        }| j        }|                     |          }||z  }||z  }||z   }	||z   }
||z  |z  }||	z  }t          j        |          }t          |
          t          |          z
  }t          d|
          t          d|          z
  }|j
        d         }t          j        |dz   |dz   f          }|dz  d|z   dz  |
z  |	dz  z  |
|	z  |dz
  z  |z  |z  z
  ||dz  z  z
  d|z  d|z   z  |	z  z
  ||z  |z  ||z   dz   z  z   ||z  ||z   dz   z  z
  |dz  |z  z   d|z    |
z  |	z  ||z  z   |||z   dz   z  z   |z  z   z  }t          |          D ]J}t          j        | j        ddddf         j        | j        dd|f         z  |z  d          ||ddf<   K| j        ddddf         j        |z  |z  d|z   d|
|	z  z
  z  |	z  |||z   dz   z  |z  z
  ||z  |
||z  z   z  |	z  z   ||z  z
  z  |z                      d          |dddf<   |d|z  d|z  z   dz   d|
z  |	z  z
  ||z  z   d|z  z
  ||
z  |	z  z   z  |dz  z  }|                                |d<   t          j        |dz   d          }|j        |         ||<   |S )	a:  
        Generalized Negative Binomial (NB-P) model hessian maxtrix of the log-likelihood

        Parameters
        ----------
        params : array_like
            The parameters of the model

        Returns
        -------
        hessian : ndarray, 2-D
            The hessian matrix of the model.
        r(  Nr%   r(   r4  r@  rD  rA  )r  r9   r6  r  r<   rX   rn   rY  r   r   r8   r   r7   r   r:  rG  )rW   rr   r   r  rA   rX   r   r  r  r  r2  r3  r  lprobr  pgpartrI  rJ  r  r.   r  rL  s                         r0   r   zNegativeBinomialP.hessian  s     	F6":&&EE2JE%%Jy\\&!!1uE\"WVVb[Bwtwr{{*1b!!Ia$4$44jm8S1WcAg.//A1r6A+*RU2r'QU+b0256b!e)$ b&AF+b01 b&2+!);<	=
 r'UV^a%789 a%&.) F)b.2-b&! 23479:	: 	; s 	[ 	[A!vdi111o&7$)AAAqD/&IE&QXYZZZHQV !IaaadO-2R7b&Qb[)B.efnq()B./R2B;'",- f !&	& (+ss{{	 	CRC QYZ "#$Vb[! F{# 4x	 
 BY^$ %
 (-ax0 7799/#'Q///$Jw/r2   c                 j   t          j        |          }| j        rt          j        |d                   }n|d         }|dd         }d| j        z
  }| j        }|                     |          }||z  }||z  }||z   }||z   }	||z  |z  }
|
|z  |z  }t          |	          t          |          z
  }|dz  d|
z   dz  |	z  |dz  z  |	||
|z  z
  z  |z  z
  ||dz  z  z
  d|
z  d|
z   z  |z  z
  |t          j        |          t          j        |          z
  |z   dz   z  z   |
t          j        |          t          j        |          z
  |z   dz   z  |z  z
  |
dz  t          d|          t          d|	          z
  z  z
  d|
z    |	z  |z  ||z  z   |
t          j        |          t          j        |          z
  |z   dz   z  z   |z  z   z  }|}||z  d|
z   d|	|z  z
  z  |z  |t          j        ||z            |z   dz   z  |z  z
  ||	|z  |
z   z  |z  z   |
t          d|          t          d|	          z
  z  z   z  |z  }|dt          j        ||z            z  d|z  z   dz   d|	z  |z  z
  |t          d|          z  z
  |t          d|	          z  z   d|z  |z  z
  ||	z  |dz  z  z   z  |dz  z  }|||fS )a:  
        Generalized Negative Binomial (NB-P) model hessian maxtrix of the log-likelihood

        Parameters
        ----------
        params : array-like
            The parameters of the model

        Returns
        -------
        hessian : ndarray, 2-D
            The hessian matrix of the model.
        r(  Nr%   r(   r@  )
r9   r:   r  r6  r  r<   rn   r   rY  r   )rW   rr   r   r  rA   r   r  r  r  r2  r3  rH  r  r  hfbbhfbahfaas                    r0   r  z NegativeBinomialP.hessian_factor  sx    F## 	F6":&&EE2JE%%J\\&!!1uE\"WVVb[!Vb[wr{{*A1r6A+*RU2R"W-23b!e)$ b&AF+b01 r

RVBZZ 7& @1 DE	F
 r

RVBZZ 7& @1 DEJK a%9Q#3#3i26F6F#FGH F)b.2-b&!r

RVBZZ 7& @1 DEFIKL	L 	M Rb&Qb[)B.bfR"Woo.23b89b2gl#b() yB'')Ar*:*::;<= @E	E a"&b//)Z "#$Vb[!#%	!R(8(8#89 )Ar***+ ./Vb[9 "Wr1u_	% & ).q	1 T4r2   c                    t          | dd          }t          | dd          }| j        t          j        ||z             z                                  }t          j        |          g}|t          j        ||z             z  }| j        |z
  }|                     |||j        d         dz
            }|                    |           t          j	        |          S r  r  r  s           r0   r  z(NegativeBinomialP._get_start_params_null\  r  r2   c                     | j         dz
  }||j        d         }|dz  |z  dz
  || z  z                                  |z  }|S )Nr(   r
   r%   )r  r8   r   r  s         r0   r  z&NegativeBinomialP._estimate_dispersionj  sS    !A%{1~HQhma28+0022X=r2   r  rx   r(   Fr  c           
         |r|dvrd| _         n#|rt          j        dt                     d| _         |&t	          | dd          t	          | dd          z   }t          j        |          d	k    r|dk    rd}dddd
}||                    |           t          | j	        | j
        |          }t          j                    5  t          j        d            |j        di |}ddd           n# 1 swxY w Y   |j        }|                     |                                |j        |j                  }t          j        |t)          d|                    }|d } t+                      j        d||||||d|}|
||j        d<   |r<|dvr8d| _         t          j        |j        j        d                   |j        j        d<   t3          | |j                  }t5          |          }|	i }	 |j        d|d|
d|	 |S )r  r
  Tr  FNr   r
   rX  r(   r  r   r  r  r   c                      | S r  r+   r  s    r0   r'  z'NegativeBinomialP.fit.<locals>.<lambda>  r  r2   r  r  r(  r  r+   )r  rp   rq   r  rd  r9   r  r  r   r<   rX   r  r  r   rr   r  rn   r   r`   r  r  rS   r  r6  r  NegativeBinomialPResultsNegativeBinomialPResultsWrapperr   )rW   r{   rK   r|   r}   r~   r   r!  r  r  r  r  rZ   r   r"  r#  r$  r  r   r  r&  r[   s                        r0   r   zNegativeBinomialP.fitq  s     	&v->>> $D .F,. . . %DT8Q//'$
A2N2NNFwv!##!#$dPUVVK ,""#4555dj$)FCCCG(** 5 5%h///%'+44445 5 5 5 5 5 5 5 5 5 5 5 5 5 5 #>L))'//*;*;W]3:3C * E EA9\3tQ<<@@L#|H ", 'T$/(" " !" " (7HF 34 	Lv->>> %D)+0Fr0J)K)KFO"2&*4AA099H%% 	Lx-1	L 	LBJ	L 	L 	Lr'  rH   r   r
   r   r   r   r   c                 j   t          |           t          j        |          dk    r<|dk    r6| j        j        d         | j        z   }|t          j        |          z  }d|d<   | j        r"t          j        |          dk    r
|d d         n|}d| _        |t          | dd          t          | dd          z   }t          j        |          dk    r|dk    rd }t          | j
        | j        |          }t          j                    5  t          j        d            |j        d||||d||||	|
|d	|j        }d d d            n# 1 swxY w Y   t          j        |d
          } t#          t$          |           j        d|||||||||	|
|d	|}t'          | |          }t)          |          S r)  )rN   r9   r  rX   r8   rV   r   r  rd  r   r<   rp   r  r  r   rr   r  rS   r	   r  r  r-  s                      r0   r   z!NegativeBinomialP.fit_regularized  s6    	F###75>>Q5A::yq)DL8HBGH---EE"I!%P"'%..12D2D%**5!T8Q//'$
A2N2NNFwv!##!dj$)FCCCG(** 4 4%h///6w6  -!-fg +!h!Y"/}! -  -
 &, -  -
 .4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 9\377L8z4((8 F)&''dXy+F	F F ?E	F F 0f==/<<<r0  r   c                    || j         }|t          | dd          }n|dk    rt          j        |          }|t          | dd          }t          j        ||d |j        d                            }||z   |z   }|dk    rt          j        |          S |dk    r|S |dk    r6t          j        |          }	|d         }
| j        }|	d|
|	|dz
  z  z  z   z  }|S |d	k    r|At          j        t          j	        dt          j
        | j                  dz                       }|                     ||||          }|                     ||          \  }}t          j        ||d d d f         |d d d f                   S t!          d
|z            )NrX  r
   r   r(   r   r   r   r(  r  z#keyword "which" = %s not recognized)rX   rd  r9   rY  r   r8   r6  r  r  r  r  r<   rn   convert_paramsr   rT  rL   )rW   rr   rX   rX  r   r   r  rj  r   r   r   r  r   r   r  r  s                   r0   rn   zNegativeBinomialP.predict  s    <9DtZ33HH]]vh''H>T8Q//Ff^djm^4558#f,F??6'??"hNe^^6'??D2JE%A1uta!e}445DKf__=1bfTZ6H6H6J)K)KLLfdHf==B,,VR88JD$:hQQQWtAAAtG}EEEBUJKKKr2   c                 T    |d         }d| j         z
  }d|z  ||z  z  }|||z   z  }||fS )Nr(  r%   r"   rh  )rW   rr   r   r   r  r  r  s          r0   r%  z NegativeBinomialP.convert_params  sB    r
%%EzBE!tby!d|r2   c                      ddl m}  fd} | j        dddf         |          }|ddddf          j        z  }|ddddf         }t	          j        ||f          S )rW  r
   rX  c                     | j         dk    r| j        d         dk    r| d d df         }                     |           }t          j        |          S r[  r\  r]  s     r0   r_  z4NegativeBinomialP._deriv_score_obs_dendog.<locals>.f  r`  r2   Nr(   r%   ra  rc  s   ``     r0   r  z)NegativeBinomialP._deriv_score_obs_dendog  s     	GFFFFF	' 	' 	' 	' 	' 	' '&tz!!!T'':A>>BQBZ$)#AaC[Bx(((r2   c                 F    |d         }| j         }|d|||dz
  z  z  z   z  }|S )r  r(  r(   rh  )rW   r   rr   r   r  r   s         r0   r  zNegativeBinomialP._var!  s6    
 r
!Qa!e,,-r2   c                 R    |d         }| j         }dd|||dz
  z  z  z   d|z  z  z
  }|S rj  rh  )rW   r   rr   r   r  r  s         r0   r  zNegativeBinomialP._prob_nonzero+  s?    
 r
!q52!9,,e<<r2   c                     |                      ||||          }|                     ||          \  }}t          ||          }|S )rQ  r  )rn   r%  r   )	rW   rr   rX   rX  r   r   r  r  r  s	            r0   r  z"NegativeBinomialP.get_distribution5  sJ     \\&thv\NN((44
dtT""r2   )r%   NNrV  Tr  rm  r  r}  r   )!r   r   r   r   r  r  r  r   rT   r`  r  r  r  r  r  r  r   r  r   r  r  r  rP   r   r   r   rn   r%  r  r  r  r  r   r   s   @r0   r   r     s        + %& )88
9 
99G6 15;?" " " " " "    
! ! !/ / /"! ! !F*& *& *&X  ,* * * *XI I IV;  ;  ; z X)**    +*     Xm'((<>BG7;"9 9 9 9 9 )(9v Xm+3448<IMIM&= &= &= &= &= 54&=P Xgo%&&?C'+#L #L #L '&#LJ  ) ) )8      Xg&.//   0/    r2   r   c                      e Zd Zedddz  Z	 	 d%dZd Zed             Zed	             Z	ed
             Z
d&dZed             Zed             Zed             Zed             Zed             Zed             Zed             Zd'dZ	 	 	 d(dZej        j        e_        	 	 	 	 d)dZd&dZd Z	 	 d*dZd  Z	 	 d+d"Z	 	 d,d$ZdS )-DiscreteResultsz;A results class for the discrete dependent variable models. one_line_description
extra_attrr  Nc                    || _         d| _        |j        | _        |j        | _        i | _        |j        j        d         | _        | j        	                    |j                   |j
        d         | _        t          | d          s9||| _        |dk    rd| _        ddi| _        d S |i }ddlm}  || f|d	d
| d S d S )NMLEr
   r  r  r  descriptionzWStandard Errors assume that the covariance matrix of the errors is correctly specified.)get_robustcov_resultsT)r  r  )modelrK   r_   r`   _cacherX   r8   nobsr  r  r  r  r   r  r  r  statsmodels.base.covtyper5  )rW   r6  r   r  r  r  r5  s          r0   rT   zDiscreteResults.__init__G  s    
J$Q'	V_---+K8tZ(( 	7  "
;&& +!. 2. !/ #!HJJJJJJ%%d 7X 7 7-57 7 7 7 7	7 	7r2   c                 Z    t          | dd           }|d|v rd |d<   d|v rd |d<   | j        S )Nr  r   r   )rd  r  )rW   r  s     r0   r  zDiscreteResults.__getstate__f  sL    t^T::#\))+/Z( L0026./}r2   c                 &    d| j         | j        z  z
  S )zC
        McFadden's pseudo-R-squared. `1 - (llf / llnull)`
        r(   )r  llnullr  s    r0   	prsquaredzDiscreteResults.prsquaredp  s    
 48DK'''r2   c                 &    d| j         | j        z
  z  S )zM
        Likelihood ratio chi-squared statistic; `-2*(llnull - llf)`
        r  )r<  r  r  s    r0   llrzDiscreteResults.llrw  s    
 4;)**r2   c                 `    t           j        j                            | j        | j                  S )z
        The chi-squared probability of getting a log-likelihood ratio
        statistic greater than llr.  llr has a chi-squared distribution
        with degrees of freedom `df_model`.
        )r   distributionschi2r^  r?  r_   r  s    r0   
llr_pvaluezDiscreteResults.llr_pvalue~  s$     "'**48T]CCCr2   Tc                 6   | j                             dd           | j                             dd           | j                             dd           | j                             dd           t          | d          r| `|
|| j         d<   || _        || _        dS )a  
        Set the fit options for the Null (constant-only) model.

        This resets the cache for related attributes which is potentially
        fragile. This only sets the option, the null model is estimated
        when llnull is accessed, if llnull is not yet in cache.

        Parameters
        ----------
        llnull : {None, float}
            If llnull is not None, then the value will be directly assigned to
            the cached attribute "llnull".
        attach_results : bool
            Sets an internal flag whether the results instance of the null
            model should be attached. By default without calling this method,
            thenull model results are not attached and only the loglikelihood
            value llnull is stored.
        **kwargs
            Additional keyword arguments used as fit keyword arguments for the
            null model. The override and model default values.

        Notes
        -----
        Modifies attributes of this instance, and so has no return.
        r<  Nr?  rC  r=  res_null)r7  r  r   rE  _attach_nullmodel_optim_kwds_null)rW   r<  attach_resultsrZ   s       r0   set_null_optionsz DiscreteResults.set_null_options  s    : 	$'''t$$$d+++T***4$$ 	$*DK!!/ &r2   c                    | j         }|                                                                }t          |dg           D ]}||=  |j        |j        t          j        | j                  fi |}t          | di                                           }d|v r|	                    d          }n't          |d          r|                                }nd}t          dddd	
          }|                    |           |r |j        dd|i|}n9|                    |dddd	          }|                    |j        dddd	          }t          | dd          dur|| _        |j        S )z:
        Value of the constant-only loglikelihood
        _null_drop_keysrG  r{   r  Nr  Fi'  r
   )rK   r  r|   r~   r  )r{   rK   r  r|   r~   rF  r+   )r6  r`  r  rd  r[   r<   r9   r   r8  r  r   r  r   r  r   rr   rE  r  )	rW   r6  rb  r  mod_null
optim_kwdssp_nullopt_kwdsrE  s	            r0   r<  zDiscreteResults.llnull  s   
 
##%%**,,5"3R88 	 	CS		"5?5;	0B0BKKdKK
 T#5r::??AA
Z'' nn^44GGU455 	2244GGGvu     
### 		;#x|EEEHEEHH  ||5:,1 $ ; ;H  ||5:,1 $ ; ;H 4,e44EAA$DM|r2   c                     t          j        | j        j        | j        d| j        j        j        d                            S )z&
        Linear predictor XB.
        Nr(   )r9   r   r6  rX   rr   r8   r  s    r0   rt   zDiscreteResults.fittedvalues  s3    
 vdjot{3LDJO4I!4L3L'MNNNr2   c                 D    | j         j        |                                 z
  S )zj
        Respnose residuals. The response residuals are defined as
        `endog - fittedvalues`
        r6  r<   rn   r  s    r0   resid_responsezDiscreteResults.resid_response  s     z$,,..00r2   c                 f    |                      d          }| j        t          j        |          z  S )z}
        Pearson residuals defined as response residuals divided by standard
        deviation implied by the model.
        r   r   )rn   rS  r9   r  )rW   r   s     r0   resid_pearsonzDiscreteResults.resid_pearson  s-     ||%|(("RWT]]22r2   c                 ^    t          | j        dd          }d| j        | j        dz   |z   z
  z  S )z
        Akaike information criterion.  `-2*(llf - p)` where `p` is the number
        of regressors including the intercept.
        rV   r
   r  r(   )rd  r6  r  r_   rW   rV   s     r0   aiczDiscreteResults.aic  s5     $*i3348t}q07:;<<r2   c                     t          | j        dd          }d| j        z  t          j        | j                  | j        dz   |z   z  z   S )z
        Bayesian information criterion. `-2*llf + ln(nobs)*p` where `p` is the
        number of regressors including the intercept.
        rV   r
   r  r(   )rd  r6  r  r9   rY  r8  r_   rW  s     r0   biczDiscreteResults.bic  sE     $*i33$({RVDI..0AG0KLLLr2   c                 *    t          j        |           S r  )pinferim_ratior  s    r0   r]  zDiscreteResults.im_ratio  s    t$$$r2   r
   c                    |                                 }t          | j        dd          }| j        dz   |z   |z   }|dk    rd| j        z  d|z  z   S |dk    r6| j        | j        z   dz   }d| j        z  |t          j        |          z  z   }|S |dk    rt          j	        |           S |d	k    rt          j
        |           S t          d
          )a8  Return an information criterion for the model.

        Parameters
        ----------
        crit : string
            One of 'aic', 'bic', 'tic' or 'gbic'.
        dk_params : int or float
            Correction to the number of parameters used in the information
            criterion.

        Returns
        -------
        Value of information criterion.

        Notes
        -----
        Tic and gbic

        References
        ----------
        Burnham KP, Anderson KR (2002). Model Selection and Multimodel
        Inference; Springer New York.
        rV   r
   r(   rX  r  r%   rZ  ticgbicz-Name of information criterion not recognized.)r   rd  r6  r_   r  r`   r9   rY  r\  r_  r`  rL   )rW   crit	dk_paramsrV   r.  r8  rZ  s          r0   info_criteriazDiscreteResults.info_criteria  s    0 zz||$*i33=1$w.:5===1x<//U]]=4=014DTX+ 55CJU]]:d###V^^;t$$$LMMMr2   jointc           
      >    t          j        | |||||||          }|S )N)
exog_extraparams_constrained
hypothesisr  r  k_constraintsobserved)r\  
score_test)	rW   rf  rg  rh  r  r  ri  rj  r   s	            r0   rk  zDiscreteResults.score_test5  s7     3E+5)1H.;)13 3 3 
r2   r   Fc	           
      \    |du rd}|	}
|||
d<   t          j        | |||||||
          }|S )a7  
        Compute prediction results when endpoint transformation is valid.

        Parameters
        ----------
        exog : array_like, optional
            The values for which you want to predict.
        transform : bool, optional
            If the model was fit via a formula, do you want to pass
            exog through the formula. Default is True. E.g., if you fit
            a model y ~ log(x1) + log(x2), and transform is True, then
            you can pass a data structure that contains x1 and x2 in
            their original form. Otherwise, you'd need to log the data
            first.
        which : str
            Which statistic is to be predicted. Default is "mean".
            The available statistics and options depend on the model.
            see the model.predict docstring
        linear : bool
            Linear has been replaced by the `which` keyword and will be
            deprecated.
            If linear is True, then `which` is ignored and the linear
            prediction is returned.
        row_labels : list of str or None
            If row_lables are provided, then they will replace the generated
            labels.
        average : bool
            If average is True, then the mean prediction is computed, that is,
            predictions are computed for individual exog and then the average
            over observation is used.
            If average is False, then the results are the predictions for all
            observations, i.e. same length as ``exog``.
        agg_weights : ndarray, optional
            Aggregation weights, only used if average is True.
            The weights are not normalized.
        y_values : None or nd_array
            Some predictive statistics like which="prob" are computed at
            values of the response variable. If y_values is not None, then
            it will be used instead of the default set of y_values.

            **Warning:** ``which="prob"`` for count models currently computes
            the pmf for all y=k up to max(endog). This can be a large array if
            the observed endog values are large.
            This will likely change so that the set of y_values will be chosen
            to limit the array size.
        **kwargs :
            Some models can take additional keyword arguments, such as offset,
            exposure or additional exog in multi-part models like zero inflated
            models.
            See the predict method of the model for the details.

        Returns
        -------
        prediction_results : PredictionResults
            The prediction results instance contains prediction and prediction
            variance and can on demand calculate confidence intervals and
            summary dataframe for the prediction.

        Notes
        -----
        Status: new in 0.14, experimental
        Tr   Nr  )rX   r   r   
row_labelsaverageagg_weights	pred_kwds)r#  get_prediction)rW   rX   r   r   r   rm  rn  ro  r  rZ   rp  r   s               r0   rq  zDiscreteResults.get_predictionC  s^    H T>>E	$,Ij!!!#	 	 	 
r2   c                     |                      ||          \  }}|t          j        |          } | j        j        | j        fd|i|}|S )N)r   rX   )_transform_predict_exogr9   r:   r6  r  rr   )rW   rX   r   rZ   _r  s         r0   r  z DiscreteResults.get_distribution  si    ..ty.IIa:d##D+
+DK . .15..4. . r2   c                 B    || j         j        }|| j         j        }||fS r  )r6  r  )rW   rE   
yname_lists      r0   _get_endog_namezDiscreteResults._get_endog_name  s,    =J*E/Jj  r2   overallr   c                 z    t          | j        dd          t          d          ddlm}  || |||||f          S )a  Get marginal effects of the fitted model.

        Parameters
        ----------
        at : str, optional
            Options are:

            - 'overall', The average of the marginal effects at each
              observation.
            - 'mean', The marginal effects at the mean of each regressor.
            - 'median', The marginal effects at the median of each regressor.
            - 'zero', The marginal effects at zero for each regressor.
            - 'all', The marginal effects at each observation. If `at` is all
              only margeff will be available from the returned object.

            Note that if `exog` is specified, then marginal effects for all
            variables not specified by `exog` are calculated using the `at`
            option.
        method : str, optional
            Options are:

            - 'dydx' - dy/dx - No transformation is made and marginal effects
              are returned.  This is the default.
            - 'eyex' - estimate elasticities of variables in `exog` --
              d(lny)/d(lnx)
            - 'dyex' - estimate semi-elasticity -- dy/d(lnx)
            - 'eydx' - estimate semi-elasticity -- d(lny)/dx

            Note that tranformations are done after each observation is
            calculated.  Semi-elasticities for binary variables are computed
            using the midpoint method. 'dyex' and 'eyex' do not make sense
            for discrete variables. For interpretations of these methods
            see notes below.
        atexog : array_like, optional
            Optionally, you can provide the exogenous variables over which to
            get the marginal effects.  This should be a dictionary with the key
            as the zero-indexed column number and the value of the dictionary.
            Default is None for all independent variables less the constant.
        dummy : bool, optional
            If False, treats binary variables (if present) as continuous.  This
            is the default.  Else if True, treats binary variables as
            changing from 0 to 1.  Note that any variable that is either 0 or 1
            is treated as binary.  Each binary variable is treated separately
            for now.
        count : bool, optional
            If False, treats count variables (if present) as continuous.  This
            is the default.  Else if True, the marginal effect is the
            change in probabilities when each observation is increased by one.

        Returns
        -------
        DiscreteMargins : marginal effects instance
            Returns an object that holds the marginal effects, standard
            errors, confidence intervals, etc. See
            `statsmodels.discrete.discrete_margins.DiscreteMargins` for more
            information.

        Notes
        -----
        Interpretations of methods:

        - 'dydx' - change in `endog` for a change in `exog`.
        - 'eyex' - proportional change in `endog` for a proportional change
          in `exog`.
        - 'dyex' - change in `endog` for a proportional change in `exog`.
        - 'eydx' - proportional change in `endog` for a change in `exog`.

        When using after Poisson, returns the expected number of events per
        period, assuming that the model is loglinear.
        r   Nz&Margins with offset are not available.r
   )DiscreteMargins)rd  r6  re   %statsmodels.discrete.discrete_marginsrz  )rW   atrK   atexogdummycountrz  s          r0   get_margeffzDiscreteResults.get_margeff  sW    P 4:x..:%&NOOOIIIIIItb&&%%GHHHr2   c                 $    ddl m}  ||           S am  
        Get an instance of MLEInfluence with influence and outlier measures

        Returns
        -------
        infl : MLEInfluence instance
            The instance has methods to calculate the main influence and
            outlier measures as attributes.

        See Also
        --------
        statsmodels.stats.outliers_influence.MLEInfluence
        r
   )MLEInfluence$statsmodels.stats.outliers_influencer  rW   r  s     r0   get_influencezDiscreteResults.get_influence  '     	FEEEEE|D!!!r2   r   c           	      ^   dd| j         j        j        gfd| j        gfdddd| j        d         z  gfg}d	d
ddd| j        z  gfddd| j        z  gfdd| j        z  gfg}t          | d          r|	                    d| j
        gf           || j         j        j        dz   dz   }ddlm}  |            }	|                     ||          \  }}|	                    | |||||           |	                    | |||| j                   t          | d          r|	                    dg           |	S )am  
        Summarize the Regression Results.

        Parameters
        ----------
        yname : str, optional
            The name of the endog variable in the tables. The default is `y`.
        xname : list[str], optional
            The 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
            The significance level for the confidence intervals.

        Returns
        -------
        Summary
            Class that holds the summary tables and text, which can be printed
            or converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary : Class that hold summary results.
        )zDep. Variable:NzModel:zMethod:)zDate:N)zTime:Nz
converged:z%sr  )zNo. Observations:N)zDf Residuals:N)z	Df Model:NzPseudo R-squ.:z%#6.4g)zLog-Likelihood:NzLL-Null:z%#8.5gzLLR p-value:r  zCovariance Type:N zRegression Resultsr
   )Summary)gleftgrightrE   xnametitle)rE   r  r   r  r   @Model has been estimated subject to linear equality constraints.)r6  r[   r   rK   r  r=  r<  rC  r   r  r  statsmodels.iolib.summaryr  rw  add_table_2colsadd_table_paramsr  add_extra_txt)
rW   rE   r  r  r   rv  top_left	top_rightr  smrys
             r0   summaryzDiscreteResults.summary  s   : -!5!> ?@$+/$$"TD,<[,I%I$JK 1,(&DN)B(CD. 8dk#9":;$x$/'A&BC	 4$$ 	COO/$-ABBB=J(1C7:NNE 	655555wyy 00
CCz 	T)#(U 	 	D 	D 	D 	d*E$(J 	 	0 	0 	0 4'' 	: !8  9 : : : r2   %.4fc                     ddl m} |                                }|                    | |||||           t	          | d          r|                    d           |S )a  
        Experimental function to summarize regression results.

        Parameters
        ----------
        yname : str
            Name of the dependent variable (optional).
        xname : list[str], optional
            List of strings of length equal to the number of parameters
            Names of the independent variables (optional).
        title : str, optional
            Title for the top table. If not None, then this replaces the
            default title.
        alpha : float
            The significance level for the confidence intervals.
        float_format : str
            The print format for floats in parameters summary.

        Returns
        -------
        Summary
            Instance that contains the summary tables and text, which can be
            printed or converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary2.Summary : Class that holds summary results.
        r
   summary2)resultsr   float_formatr  rE   r  r   r  )statsmodels.iolibr  r  add_baser   add_text)rW   rE   r  r  r   r  r  r  s           r0   r  zDiscreteResults.summary2S  s    < 	/.....!!d%l!e 	 	= 	= 	= 4'' 	3MM 2 3 3 3 r2   )r  NNr  r  )NNrd  NNNT)NTr   NNFNN)rx  r   NFFNNNr   N)NNNr   r  )r   r   r   _discrete_results_docsr   rT   r  r   r=  r?  rC  rI  r<  rt   rS  rU  rX  rZ  r]  rc  rk  r\  rq  r  rw  r  r  r  r  r+   r2   r0   r-  r-  B  s       $E( ( G FJ7 7 7 7>   ( ( ^( + + ^+ D D ^D'' '' '' ''R + + ^+Z O O ^O 1 1 ^1 3 3 ^3 = = ^= M M ^M % % ^%'N 'N 'N 'NR >B?C04
 
 
 
  *2J"&<@0526W W W Wr	 	 	 	! ! ! ?C$KI KI KI KIZ" " "" ADE E E EN BE$' ' ' ' ' 'r2   r-  c                   <    e Zd Zedddz  Zed             ZddZdS )rv  zA results class for count datar.  r/  c                 D    | j         j        |                                 z
  S )z
        Residuals

        Notes
        -----
        The residuals for Count models are defined as

        .. math:: y - p

        where :math:`p = \exp(X\beta)`. Any exposure and offset variables
        are also handled.
        rR  r  s    r0   r   zCountResults.resid  s     z$,,..00r2   Nc                 (    ddl m}  || |          S )a  
        Get instance of class with specification and diagnostic methods.

        experimental, API of Diagnostic classes will change

        Returns
        -------
        CountDiagnostic instance
            The instance has methods to perform specification and diagnostic
            tesst and plots

        See Also
        --------
        statsmodels.statsmodels.discrete.diagnostic.CountDiagnostic
        r
   )CountDiagnosticy_max)statsmodels.discrete.diagnosticr  )rW   r  r  s      r0   get_diagnosticzCountResults.get_diagnostic  s,      	DCCCCCt51111r2   r  )r   r   r   r  r   r   r   r  r+   r2   r0   rv  rv  }  s]        $ @( ( G 1 1 ^12 2 2 2 2 2r2   rv  c                   v    e Zd Zedddz  Zed             Zed             Zed             Zed             Z	dS )	r  z,A results class for NegativeBinomial 1 and 2r.  r/  c                 @    t          j        | j        d                   S )zNatural log of alphar(  )r9   rY  rr   r  s    r0   lnalphazNegativeBinomialResults.lnalpha  s     vdk"o&&&r2   c                 8    | j         d         | j        d         z  S )z!Natural log of standardized errorr(  )bserr   r  s    r0   lnalpha_std_errz'NegativeBinomialResults.lnalpha_std_err  s     x|dk"o--r2   c                 h    t          | j        dd          }d| j        | j        | j        z   |z   z
  z  S NrV   r
   r  )rd  r6  r  r_   
k_constantrW  s     r0   rX  zNegativeBinomialResults.aic  s7     $*i3348t}t>HIJJr2   c                     t          | j        dd          }d| j        z  t          j        | j                  | j        | j        z   |z   z  z   S r  )rd  r6  r  r9   rY  r8  r_   r  rW  s     r0   rZ  zNegativeBinomialResults.bic  sX     $*i33$({RVDI..041@BI1J K K 	Kr2   N)
r   r   r   r  r   r   r  r  rX  rZ  r+   r2   r0   r  r    s        $ N( ( G ' ' ^' . . ^. K K ^K
 K K ^K K Kr2   r  c                       e Zd Zedddz  ZdS )r!  z%A results class for NegativeBinomialPr.  r/  Nr   r   r   r  r   r+   r2   r0   r!  r!    s(        $ G( ( GGGr2   r!  c                   4    e Zd Zedddz  Zed             ZdS )r  z'A results class for Generalized Poissonr.  r/  c                     t          | j        dd          }|                                 }d| j        d         ||z  z  z   dz  S )Nr  r
   r(   r(  r%   )rd  r6  rn   rr   )rW   r  r   s      r0   _dispersion_factorz,GeneralizedPoissonResults._dispersion_factor  sB    DJ 2A66\\^^DKOb!e++a//r2   N)r   r   r   r  r   r   r  r+   r2   r0   r  r    sI        $ I( ( G 0 0 ^0 0 0r2   r  c                   .     e Zd Zededz  Z fdZ xZS )rz  z7A results class for count data fit by l1 regularizationr/  c                 f   t                                          ||           |j        d         | _        | j                                         | _        t          | j        dd          }| j        dz
  |z
  | _        t          | j        j
        j        d         | j        z
            |z   | _        d S )Nr   rV   r
   r(   )rS   rT   r  r   r   r   rd  r6  r_   r;   r<   r8   r`   )rW   r6  rx  rV   r[   s       r0   rT   zL1CountResults.__init__  s    ''' ))4 L=--//
 $*i33!+g5dj.4Q7$/IJJWTr2   r   r   r   r  _l1_results_attrr   rT   r   r   s   @r0   rz  rz    s[        $E+(- (- -GU U U U U U U U Ur2   rz  c                   >    e Zd Z	 	 ddZed             Zd ZddZdS )	r  NTc                 D   |t          j        |          }nFt          j        t          j        dt          j        | j        j                  dz                       }|                     ||||d          dddf         }t          j        	                    ||          S )am  
        Return predicted probability of each count level for each observation

        Parameters
        ----------
        n : array_like or int
            The counts for which you want the probabilities. If n is None
            then the probabilities for each count from 0 to max(y) are
            given.

        Returns
        -------
        ndarray
            A nobs x n array where len(`n`) columns are indexed by the count
            n. If n is None, then column 0 is the probability that each
            observation is 0, column 1 is the probability that each
            observation is 1, etc.
        Nr
   r(   r   )rX   rX  r   r   r   )
r9   r  r  r  r6  r<   rn   r   r  rT  )rW   nrX   rX  r   r   countsr   s           r0   predict_probzPoissonResults.predict_prob  s    ( =]1%%FF]29Qtz7G0H0H0J#K#KLLF\\thv$-V  = ==>QQtVE }  ,,,r2   c                 r    |                                  }| j        j        |z
  t          j        |          z  S )l  
        Pearson residuals

        Notes
        -----
        Pearson residuals are defined to be

        .. math:: r_j = \frac{(y - M_jp_j)}{\sqrt{M_jp_j(1-p_j)}}

        where :math:`p_j=cdf(X\beta)` and :math:`M_j` is the total number of
        observations sharing the covariate pattern :math:`j`.

        For now :math:`M_j` is always set to 1.
        )rn   r6  r<   r9   r  )rW   r  s     r0   rU  zPoissonResults.resid_pearson	  s.    " LLNN
 1$bgajj00r2   c                 $    ddl m}  ||           S r  r  r  s     r0   r  zPoissonResults.get_influence  r  r2   c                 (    ddl m}  || |          S )a  
        Get instance of class with specification and diagnostic methods

        experimental, API of Diagnostic classes will change

        Returns
        -------
        PoissonDiagnostic instance
            The instance has methods to perform specification and diagnostic
            tesst and plots

        See Also
        --------
        statsmodels.statsmodels.discrete.diagnostic.PoissonDiagnostic
        r
   )PoissonDiagnosticr  )r  r  )rW   r  r  s      r0   r  zPoissonResults.get_diagnostic.  s6     	 	 	 	 	 	  U3333r2   )NNNNTr  )r   r   r   r  propertyrU  r  r  r+   r2   r0   r  r    sl        DH#- - - -: 1 1 X1&" " ""4 4 4 4 4 4r2   r  c                       e Zd ZdS )r  Nr   r   r   r+   r2   r0   r  r  C          Dr2   r  c                       e Zd ZdS )r  Nr  r+   r2   r0   r  r  F  r  r2   r  c                       e Zd ZdS )r+  Nr  r+   r2   r0   r+  r+  I  r  r2   r+  c                       e Zd Zedddz  ZdS )OrderedResultsz*A results class for ordered discrete data.r.  r/  Nr  r+   r2   r0   r  r  L  s0        $Am  @B  (C  (C  CGDr2   r  c                        e Zd Zedddz  ZddZ eej        j                  	 	 d fd	            Ze	d	             Z
e	d
             Ze	d             Z xZS )BinaryResultszA results class for binary datar.  r/        ?c                     | j         }|j        }t          j        |                                 |k    t
                    }t          j        g d          }t          j        |||          d         S )a  
        Prediction table

        Parameters
        ----------
        threshold : scalar
            Number between 0 and 1. Threshold above which a prediction is
            considered 1 and below which a prediction is considered 0.

        Notes
        -----
        pred_table[i,j] refers to the number of times "i" was observed and
        the model predicted "j". Correct predictions are along the diagonal.
        r3   )r
   r  r(   binsr
   )r6  r<   r9   r   rn   r;   histogram2d)rW   	thresholdr6  actualr#  r  s         r0   
pred_tablezBinaryResults.pred_tableS  sb     
x2%@@@x$$~fd666q99r2   Nr   c                 >   t                                          |||||          }| j                            | j                  }t          j        | j        j        |z
            }|dk                                     }	|	t          |          z  }
g }|	t          |          k    r,d}|dz  }|dz  }|dz  }|dz  }|
                    |           n4|
dk    r.d}|d	|
z  z  }|d
z  }|dz  }|dz  }|
                    |           |r|                    |           |S )Nr   z3Complete Separation: The results show that there isz+complete separation or perfect prediction.
z3In this case the Maximum Likelihood Estimator does znot exist and the parameters
zare not identified.r*  z/Possibly complete quasi-separation: A fraction z%4.2f of observations can be
z4perfectly predicted. This might indicate that there z0is complete
quasi-separation. In this case some z"parameters will not be identified.)rS   r  r6  rh   rt   r9   r  r<   r   r"  r  r  )rW   rE   r  r  r   rv  r  rt   absprederrorpredclose_sumpredclose_fracetextwstrr[   s                r0   r  zBinaryResults.summaryh  sR    wwueUE2<> >z~~d&788vdj.=>>%,1133&\):):: C----HDBBDIID44D))DLLc!!DD4~EEDJJDGGD88DLL 	&u%%%r2   c           
      ^   | j         j        }d}|                                 }d|z
   t          j        d|z  t          j        t          j        d|z
                      z            z  |t          j        d|z  t          j        t          j        |                    z            z  z   }|S )a  
        Deviance residuals

        Notes
        -----
        Deviance residuals are defined

        .. math:: d_j = \pm\left(2\left[Y_j\ln\left(\frac{Y_j}{M_jp_j}\right) + (M_j - Y_j\ln\left(\frac{M_j-Y_j}{M_j(1-p_j)} \right) \right] \right)^{1/2}

        where

        :math:`p_j = cdf(X\beta)` and :math:`M_j` is the total number of
        observations sharing the covariate pattern :math:`j`.

        For now :math:`M_j` is always set to 1.
        r(   r%   )r6  r<   rn   r9   r  r  rY  )rW   r<   Mr  r   s        r0   	resid_devzBinaryResults.resid_dev  s    ( 
  LLNN %j1RVBF1Q3KK%8%8!8999bgac"&"3"334445
r2   c                     | j         j        }d}|                                 }|||z  z
  t          j        ||z  d|z
  z            z  S )r  r(   )r6  r<   rn   r9   r  )rW   r<   r  r  s       r0   rU  zBinaryResults.resid_pearson  sK    $ 
 
 LLNN!RWQqS!A#Y////r2   c                 D    | j         j        |                                 z
  S )z
        The response residuals

        Notes
        -----
        Response residuals are defined to be

        .. math:: y - p

        where :math:`p=cdf(X\beta)`.
        rR  r  s    r0   rS  zBinaryResults.resid_response  s     z$,,..00r2   )r  r  )r   r   r   r  r   r  r   r-  r  r   r  rU  rS  r   r   s   @r0   r  r  P  s        $Absu'v'vvG: : : :* Xo%-..@C     /.:   ^@ 0 0 ^04 1 1 ^1 1 1 1 1r2   r  c                   :    e Zd Zedddz  Zed             Zd ZdS )r  zA results class for Logit Modelr.  r/  c                 D    | j         j        |                                 z
  S )a  
        Generalized residuals

        Notes
        -----
        The generalized residuals for the Logit model are defined

        .. math:: y - p

        where :math:`p=cdf(X\beta)`. This is the same as the `resid_response`
        for the Logit model.
        rR  r  s    r0   resid_generalizedzLogitResults.resid_generalized  s     z$,,..00r2   c                 $    ddl m}  ||           S r  r  r  s     r0   r  zLogitResults.get_influence  r  r2   N)r   r   r   r  r   r   r  r  r+   r2   r0   r  r    sX        $ A( ( G 1 1 ^1 " " " " "r2   r  c                   4    e Zd Zedddz  Zed             ZdS )r  z A results class for Probit Modelr.  r/  c                     | j         }|j        }|                     d          }|                    |          }|                    |          }||z  |z  d|z
  |z  d|z
  z  z
  S )z
        Generalized residuals

        Notes
        -----
        The generalized residuals for the Probit model are defined

        .. math:: y\frac{\phi(X\beta)}{\Phi(X\beta)}-(1-y)\frac{\phi(X\beta)}{1-\Phi(X\beta)}
        r   r   r(   )r6  r<   rn   rk   rh   )rW   r6  r<   r  rk   rh   s         r0   r  zProbitResults.resid_generalized  sg     
\\\))iimmiimms{3!E'3#!666r2   N)r   r   r   r  r   r   r  r+   r2   r0   r  r    sI        $ B( ( G 7 7 ^7 7 7r2   r  c                   .     e Zd Zededz  Z fdZ xZS )r   z9Results instance for binary data fit by l1 regularizationr/  c                 .   t                                          ||           |j        d         | _        | j                                         | _        | j        dz
  | _        t          | j        j	        j
        d         | j        z
            | _        d S Nr   r(   r
   )rS   rT   r  r   r   r   r_   r;   r6  r<   r8   r`   )rW   r6  r   r[   s      r0   rT   zL1BinaryResults.__init__  sz    ((( *95 L=--//!+dj.4Q7$/IJJr2   r  r   s   @r0   r   r     s[        $?#(% (% %GK K K K K K K K Kr2   r   c                        e Zd Zedddz  Z fdZed             ZddZd Z	e
d	             Ze
d
             Ze
d             Zd fd	Zd Zd Ze
d             ZddZ xZS )r-  z$A results class for multinomial datar.  r/  c                 |    t                                          ||           |j        | _        |j        | _        d S r  )rS   rT   r  r  rW   r6  r   r[   s      r0   rT   zMultinomialResults.__init__$  s3    '''r2   c                 @   d}d}| D ]z}	 | |         dz  dk    r&t          t          | |                             | |<   nd}t          | |                   | |<   S# t          $ r t          | |                   | |<   Y ww xY w|rt          j        |t
                     | S )NFzendog contains values are that not int-like. Uses string representation of value. Use integer-valued endog to suppress this warning.r(   r
   T)strr7  r   rp   rq   r!   )r>   issue_warningru   r.   s       r0   r  z,MultinomialResults._maybe_convert_ynames_int)  s     (  	+ 	+A+!9q=A%% #Cq	NN 3 3F1II$(M #F1IF1I + + +q	NNq			+ 	5M#3444s   AA"A?>A?Fc                     | j         }|j        |f|j        |                               fdt	          t          |j                            D             fdD             |sdd         }n}|fS )zE
        If all is False, the first variable name is dropped
        Nc                      g | ]
}|         S r+   r+   r  s     r0   rK  z6MultinomialResults._get_endog_name.<locals>.<listcomp>I  s    AAAcfSkAAAr2   c                 >    g | ]}d                      |g          S )=)join)r-   rC   rE   s     r0   rK  z6MultinomialResults._get_endog_name.<locals>.<listcomp>J  s)    AAA$chht}--AAAr2   r(   )r6  r  r  r  r7   r7  r  )rW   rE   rv  r   r6  r>   s    `   @r0   rw  z"MultinomialResults._get_endog_name>  s     
=%E&F33F;;FAAAAU3uw<<-@-@AAAFAAAA&AAAF $#ABBZ

#
j  r2   c                    | j         j        dz
  }t          j        dgt          j        d|dz
  |          |gf          }t          j        | j         j        |                                                     d          |          d         S )z
        Returns the J x J prediction table.

        Notes
        -----
        pred_table[i,j] refers to the number of times "i" was observed and
        the model predicted "j". Correct predictions are along the diagonal.
        r(   r
   r  r  )	r6  r  r9   r@  linspacer  r<   rn   r  )rW   jur  s      r0   r  zMultinomialResults.pred_tableQ  s     Z\A ~sBKR#Xr$B$BRDIJJ~dj.0E0Ea0H0H#') ) ))*, 	,r2   c                     t          j        t          j        |                                                     }|                    | j        j        d          S )Nr)  r*  )r9   r  diagr   r,  rr   r8   )rW   r  s     r0   r  zMultinomialResults.bsea  s@    gbgdoo//0011{{4;,C{888r2   c                 F    d| j         | j        | j        j        z   dz
  z
  z  S Nr  r(   )r  r_   r6  r  r  s    r0   rX  zMultinomialResults.aicf  s$    48t}TZ\9!;<==r2   c                 z    d| j         z  t          j        | j                  | j        | j        j        z   dz
  z  z   S r   )r  r9   rY  r8  r_   r6  r  r  s    r0   rZ  zMultinomialResults.bicj  s4    $({RVDI..djl0J10LMMMr2   r   Nc                     t          t          |                               ||          }|                    ddd          S )N)r   colsr%   r
   r(   )rS   r-  conf_intr;  )rW   r   r  confintr[   s       r0   r  zMultinomialResults.conf_intn  sF    ..77eAE 8 G G  1Q'''r2   c                     t           )z(Not implemented for Multinomial
        rd   r  s    r0   rq  z!MultinomialResults.get_predictions  rR  r2   c                      t          d          )NzUse get_margeff insteadrd   r  s    r0   r   zMultinomialResults.margeffx  s    !";<<<r2   c                     | j         j                            d          |                                                     d          k                        t
                    S )a^  
        Residuals indicating which observations are misclassified.

        Notes
        -----
        The residuals for the multinomial model are defined as

        .. math:: argmax(y_i) \neq argmax(p_i)

        where :math:`argmax(y_i)` is the index of the category for the
        endogenous variable and :math:`argmax(p_i)` is the index of the
        predicted probabilities for each category. That is, the residual
        is a binary indicator that is 0 if the category with the highest
        predicted probability is the same as that of the observed variable
        and 1 otherwise.
        r(   )r6  r  r  rn   r>  r;   r  s    r0   resid_misclassifiedz&MultinomialResults.resid_misclassified{  sH    & 
!((++%%a(()*0&--	8r2   r  c           
         ddl m} |                                }|                    |                    |                      | j        j        d         }|                     |          }t          |          D ]}|	                    | | j        dd|f         | j
        dd|f         | j        dd|f         | j        dd|f         ||         f|          }| j        j        dz   t          |          z   }	|j        ||	<   |j        ddg df         }|                    |dd	|
           |                    |            |S )a8  Experimental function to summarize regression results

        Parameters
        ----------
        alpha : float
            significance level for the confidence intervals
        float_format : str
            print format for floats in parameters summary

        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.summary2.Summary : class to hold summary results
        r
   r  r(   Nr   z = )r(  r
   r(   r%   r@  r     FT)indexheaderr  )r  )r  r  r  add_dictsummary_modelrr   r8   r  r7   summary_paramsr  tvaluespvaluesr6  r  r  r  rB   add_df	add_title)
rW   r   r  r  r  eqnr  r.   r  	level_strs
             r0   r  zMultinomialResults.summary2  ss   * 	/.....!!h,,T22333k"--&&s 	) 	)A++T4;qqq!t3D-1Xaaad^-1\!!!Q$-?-1\!!!Q$-?-4QZ	-9
 38 , 9 9E /%7#a&&@I${E)Jqqq"8"8"889EKKU4%1  3 3 3NN4N((((r2   )F)r   N)r   r  )r   r   r   r  r   rT   staticmethodr  rw  r  r   r  rX  rZ  r  rq  r   r	  r  r   r   s   @r0   r-  r-     sQ       $22(G (G GG    
   \(! ! ! !&, , ,  9 9 ^9 > > ^> N N ^N( ( ( ( ( (
" " "
= = = 8 8 ^8*) ) ) ) ) ) ) )r2   r-  c                   .     e Zd Zededz  Z fdZ xZS )r1  z=A results class for multinomial data fit by l1 regularizationr/  c                 H   t                                          ||           |j        d         | _        | j                                         | _        | j        | j        j        dz
  z
  | _        t          | j        j
        j        d         | j        z
            | _        d S r  )rS   rT   r  r   r   r   r6  r  r_   r;   r<   r8   r`   r  s      r0   rT   zL1MultinomialResults.__init__  s    ''' ))4 L=--// 4:<!+;<dj.4Q7$/IJJr2   r  r   s   @r0   r1  r1    s[        $G'() () )G	K 	K 	K 	K 	K 	K 	K 	K 	Kr2   r1  c                       e Zd ZdS )OrderedResultsWrapperNr  r+   r2   r0   r  r    r  r2   r  c                       e Zd ZdS )rw  Nr  r+   r2   r0   rw  rw    r  r2   rw  c                       e Zd ZdS )r  Nr  r+   r2   r0   r  r    r  r2   r  c                       e Zd ZdS )r"  Nr  r+   r2   r0   r"  r"    r  r2   r"  c                       e Zd ZdS )r  Nr  r+   r2   r0   r  r    r  r2   r  c                       e Zd ZdS )r  Nr  r+   r2   r0   r  r    r  r2   r  c                       e Zd ZdS )r{  Nr  r+   r2   r0   r{  r{    r  r2   r{  c                       e Zd ZdS )r  Nr  r+   r2   r0   r  r     r  r2   r  c                       e Zd ZdS )r  Nr  r+   r2   r0   r  r    r  r2   r  c                       e Zd ZdS )r,  Nr  r+   r2   r0   r,  r,    r  r2   r,  c                   R    e Zd ZdddddZ ej        ej        j        e          ZdS )r  rows)r  r  rU  rS  N)	r   r   r   _attrswrapunion_dictslmRegressionResultsWrapper_wrap_attrsr+   r2   r0   r  r    sG        !#)% & F
 #$"2#>#J#)+ +KKKr2   r  c                       e Zd ZdS )r   Nr  r+   r2   r0   r   r   $  r  r2   r   c                       e Zd ZddiZ ej        ej        j        e          ZddiZ	 ej        ej        j
        e	          Z
dS )r.  r	  r&  r  multivariate_confintN)r   r   r   r'  r(  r)  r*  r+  r,  _methods_wrap_methodsr+   r2   r0   r.  r.  +  sa        #V,F"$"2#>#J#)+ +K23H$D$R%@%N%-/ /MMMr2   r.  c                       e Zd ZdS )r2  Nr  r+   r2   r0   r2  r2  7  r  r2   r2  )yr   __all__statsmodels.compat.pandasr   rp   numpyr9   pandasr   r   scipyr   r   scipy.specialr   r   r   r   scipy.statsr   statsmodels.base.datar   statsmodels.base.l1_slsqpr   statsmodels.base.modelr   r6  statsmodels.base.wrapperwrapperr(  r  r   %statsmodels.base._parameter_inference_parameter_inferencer\  statsmodels.baser   r#  statsmodels.distributionsr   #statsmodels.regression.linear_model
regressionlinear_modelr*  statsmodels.toolsr   r  r   statsmodels.tools.decoratorsr   rb  r   statsmodels.tools.sm_exceptionsr   r    r!   cvxoptr   ImportErrorfinfor;   epsr  rY  r\  r  r  _discrete_models_docsr  r  r  r  r?   rF   rN   r   rP   r   r   r	   r   r   r   r   r   r   r   LikelihoodModelResultsr-  rv  r  r!  r  rz  r  r  r  r+  r  r  r  r  r   r-  r1  r+  r  populate_wrapperrw  r  r"  r  r  r{  r  r  r,  r  r   r.  r2  r+   r2   r0   <module>rP     s   "D D D / . . . . .      * * * * * * * *                 ? ? ? ? ? ? ? ? ? ? ? ?       - - - - - - 2 2 2 2 2 2 % % % % % % % % % ' ' ' ' ' ' ' ' ' > > > > > > 6 6 6 6 6 6 6 6 6 : : : : : : 2 2 2 2 2 2 0 0 0 0 0 0 0 0 0 7 7 7 7 7 7 7 7 7 7 7 7 7 7 6 6 6 6 6 6         MMMKK   KKK BHUOO	 "&"*--122S8
  .O 
 ! ! !( ( ($I I I,d d d d dD( d d dN	Z Z Z Z Z- Z Z Zzn" n" n" n" n"{ n" n" n"b~2 ~2 ~2 ~2 ~2 ~2 ~2 ~2Ht t t t tj t t tn@	 @	 @	 @	 @	 @	 @	 @	Fb b b b bK b b bJ	y* y* y* y* y*[ y* y* y*x	O O O O O O O O\
l l l l lz l l l^~ ~ ~ ~ ~
 ~ ~ ~Fx x x x xd1 x x xv&2 &2 &2 &2 &2? &2 &2 &2RK K K K Kl K K K:    6   	0 	0 	0 	0 	0 7 	0 	0 	0U U U U U_ U U U*V4 V4 V4 V4 V4\ V4 V4 V4r	 	 	 	 	~~ 	 	 		 	 	 	 	0G 	 	 		 	 	 	 	.2K 	 	 		 	 	 	 	_ 	 	 	1 1 1 1 1O 1 1 1D%" %" %" %" %"= %" %" %"P7 7 7 7 7M 7 7 70K K K K Km K K KZ Z Z Z Z Z Z ZzK K K K K- K K K$	 	 	 	 	B7 	 	 	  +^ < < <	 	 	 	 	"5 	 	 	  )< 8 8 8	 	 	 	 	R%@ 	 	 	  4-/ / /	 	 	 	 	b&A 	 	 	  5.0 0 0	 	 	 	 	r'B 	 	 	  6/1 1 1	 	 	 	 	B7 	 	 	  +^ < < <	 	 	 	 	B7 	 	 		 	 	 	 	b9 	 	 	  -/? @ @ @	 	 	 	 	r'B 	 	 	  6/1 1 1	 	 	 	 	)D 	 	 	  813 3 3+ + + + +26 + + +  *M : : :	 	 	 	 	R8 	 	 	  ,o > > >/ / / / / ; / / /  /1C D D D	 	 	 	 	""= 	 	 	  13G H H H H Hs   B B)(B)