
    M/Ph                    V   d Z ddlmZ ddlmZ ddlZddlmZ ddl	Z
ddl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c mZ ddlmZ dd	lmZmZ dd
lmZ  ddl!m"c mc m#Z# ddl$m%Z% ddl&m'Z'm(Z(m)Z)m*Z* ddl+Z+ddl,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9  G d d          Z:dZ;dZ<dZ=dZ>dZ?dZ@dZAdZBdZCdZDd ZE G d de          ZF G d de          ZG G d  d!ejH                  ZI ejJ        eIeG            G d" d#eF          ZK G d$ d%eG          ZLd& ZM G d' d(eI          ZN ejJ        eNeL            G d) d*eF          ZO G d+ d,eG          ZP G d- d.eI          ZQ ejJ        eQeP            G d/ d0e%          ZR G d1 d2ejS                  ZT G d3 d4          ZUdS )5a`  
Procedures for fitting marginal regression models to dependent data
using Generalized Estimating Equations.

References
----------
KY Liang and S Zeger. "Longitudinal data analysis using
generalized linear models". Biometrika (1986) 73 (1): 13-22.

S Zeger and KY Liang. "Longitudinal Data Analysis for Discrete and
Continuous Outcomes". Biometrics Vol. 42, No. 1 (Mar., 1986),
pp. 121-130

A Rotnitzky and NP Jewell (1990). "Hypothesis testing of regression
parameters in semiparametric generalized linear models for cluster
correlated data", Biometrika, 77, 485-497.

Xu Guo and Wei Pan (2002). "Small sample performance of the score
test in GEE".
http://www.sph.umn.edu/faculty1/wp-content/uploads/2012/11/rr2002-013.pdf

LA Mancl LA, TA DeRouen (2001). A covariance estimator for GEE with
improved small-sample properties.  Biometrics. 2001 Mar;57(1):126-34.
    )lzip)AppenderN)stats)defaultdict)cache_readonly)families)GLM
GLMResults)
cov_struct)Link)ConvergenceWarningDomainWarningIterationLimitWarningValueWarning)_plot_added_variable_doc_plot_partial_residuals_doc_plot_ceres_residuals_doc)	_get_margeff_exog_check_margeff_args_effects_atmargeff_cov_with_se_check_at_is_all_transform_names_check_discrete_args_get_dummy_index_get_count_indexc                   6    e Zd ZdZd Zd Zd Zd Zd Zd Z	dS )	ParameterConstraintzV
    A class for managing linear equality constraints for a parameter
    vector.
    c                    t          j        |                                          }|j        dk    rt	          d          t          |          |j        d         k    rt	          d          || _        || _        t           j	        
                    |j        d          \  }}}|ddt          |          df         | _        |dddt          |          f         | _        t          j        | j        | j        f          | _        t          j        | j        t          j        || j                  |z            | _        t          j        || j                  | _        || _        t          j        || j                  | _        dS )a  
        Parameters
        ----------
        lhs : ndarray
           A q x p matrix which is the left hand side of the
           constraint lhs * param = rhs.  The number of constraints is
           q >= 1 and p is the dimension of the parameter vector.
        rhs : ndarray
          A 1-dimensional vector of length q which is the right hand
          side of the constraint equation.
        exog : ndarray
          The n x p exognenous data for the full model.
           z7The right hand side of the constraint must be a vector.r   z~The number of rows of the left hand side constraint matrix L must equal the length of the right hand side constraint vector R.)full_matricesN)np
atleast_1dsqueezendim
ValueErrorlenshapelhsrhslinalgsvdTlhs0lhs1hstacklhsfdotparam0_offset_increment	orig_exogexog_fulltrans)selfr)   r*   exoglhs_ulhs_slhs_vts          s/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/genmod/generalized_estimating_equations.py__init__zParameterConstraint.__init__D   sa   " mCKKMM**8a<< 1 2 2 2 s88sy|## 4 5 5 5
   "y}}SU!}DDuf!!!SZZ[[.)	!!!Qs5zz\/*	Ity$)455	 fTYvtx(@(@")# $ $ "$dk!:!: fT4955    c                     | j         S )z
        Returns a vector that should be added to the offset vector to
        accommodate the constraint.

        Parameters
        ----------
        exog : array_like
           The exogeneous data for the model.
        )r4   r7   s    r<   offset_incrementz$ParameterConstraint.offset_incrementw   s     %%r>   c                 H    | j         ddd| j        j        d         f         S )z
        Returns a linearly transformed exog matrix whose columns span
        the constrained model space.

        Parameters
        ----------
        exog : array_like
           The exogeneous data for the model.
        Nr   r    )r6   r.   r(   r@   s    r<   reduced_exogz ParameterConstraint.reduced_exog   s)     "111a	(:&:#:;;r>   c                     | j         S )zg
        Returns the full exog matrix before it was reduced to
        satisfy the constraint.
        )r5   r@   s    r<   restore_exogz ParameterConstraint.restore_exog   s    
 ~r>   c                 F    | j         t          j        | j        |          z   S )zb
        Converts the parameter vector `params` from reduced to full
        coordinates.
        )r3   r"   r2   r.   r7   paramss     r<   unpack_paramz ParameterConstraint.unpack_param   s     {RVDIv6666r>   c                 p    t          j        | j        t          j        || j        j                            S )za
        Converts the covariance matrix `bcov` from reduced to full
        coordinates.
        )r"   r2   r.   r-   )r7   bcovs     r<   
unpack_covzParameterConstraint.unpack_cov   s(     vdidik!:!:;;;r>   N)
__name__
__module____qualname____doc__r=   rA   rC   rE   rI   rL    r>   r<   r   r   >   sy         
16 16 16f& & &
< 
< 
<  7 7 7< < < < <r>   r   a6  
    Marginal regression model fit using Generalized Estimating Equations.

    GEE can be used to fit Generalized Linear Models (GLMs) when the
    data have a grouped structure, and the observations are possibly
    correlated within groups but not between groups.

    Parameters
    ----------
    endog : array_like
        1d array of endogenous values (i.e. responses, outcomes,
        dependent variables, or 'Y' values).
    exog : array_like
        2d array of exogeneous values (i.e. covariates, predictors,
        independent variables, regressors, or 'X' values). 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`.
    groups : array_like
        A 1d array of length `nobs` containing the group labels.
    time : array_like
        A 2d array of time (or other index) values, used by some
        dependence structures to define similarity relationships among
        observations within a cluster.
    family : family class instance
%(family_doc)s
    cov_struct : CovStruct class instance
        The default is Independence.  To specify an exchangeable
        structure use cov_struct = Exchangeable().  See
        statsmodels.genmod.cov_struct.CovStruct for more
        information.
    offset : array_like
        An offset to be included in the fit.  If provided, must be
        an array whose length is the number of rows in exog.
    dep_data : array_like
        Additional data passed to the dependence structure.
    constraint : (ndarray, ndarray)
        If provided, the constraint is a tuple (L, R) such that the
        model parameters are estimated under the constraint L *
        param = R, where L is a q x p matrix and R is a
        q-dimensional vector.  If constraint is provided, a score
        test is performed to compare the constrained model to the
        unconstrained model.
    update_dep : bool
        If true, the dependence parameters are optimized, otherwise
        they are held fixed at their starting values.
    weights : array_like
        An array of case weights to use in the analysis.
    %(extra_params)s

    See Also
    --------
    statsmodels.genmod.families.family
    :ref:`families`
    :ref:`links`

    Notes
    -----
    Only the following combinations make sense for family and link ::

                   + ident log logit probit cloglog pow opow nbinom loglog logc
      Gaussian     |   x    x                        x
      inv Gaussian |   x    x                        x
      binomial     |   x    x    x     x       x     x    x           x      x
      Poisson      |   x    x                        x
      neg binomial |   x    x                        x          x
      gamma        |   x    x                        x

    Not all of these link functions are currently available.

    Endog and exog are references so that if the data they refer
    to are already arrays and these arrays are changed, endog and
    exog will change.

    The "robust" covariance type is the standard "sandwich estimator"
    (e.g. Liang and Zeger (1986)).  It is the default here and in most
    other packages.  The "naive" estimator gives smaller standard
    errors, but is only correct if the working correlation structure
    is correctly specified.  The "bias reduced" estimator of Mancl and
    DeRouen (Biometrics, 2001) reduces the downward bias of the robust
    estimator.

    The robust covariance provided here follows Liang and Zeger (1986)
    and agrees with R's gee implementation.  To obtain the robust
    standard errors reported in Stata, multiply by sqrt(N / (N - g)),
    where N is the total sample size, and g is the average group size.
    %(notes)s
    Examples
    --------
    %(example)s
z
    The nominal and ordinal GEE models should not have an intercept
    (either implicit or explicit).  Use "0 + " in a formula to
    suppress the intercept.
z        The default is Gaussian.  To specify the binomial
        distribution use `family=sm.families.Binomial()`. Each family
        can take a link instance as an argument.  See
        statsmodels.genmod.families.family for more information.z|        The only family supported is `Binomial`.  The default `Logit`
        link may be replaced with `probit` if desired.z        The default value `None` uses a multinomial logit family
        specifically designed for use with GEE.  Setting this
        argument to a non-default value is not currently supported.a  
    Fits a marginal regression model using generalized estimating
    equations (GEE).

    Parameters
    ----------
    maxiter : int
        The maximum number of iterations
    ctol : float
        The convergence criterion for stopping the Gauss-Seidel
        iterations
    start_params : array_like
        A vector of starting values for the regression
        coefficients.  If None, a default is chosen.
    params_niter : int
        The number of Gauss-Seidel updates of the mean structure
        parameters that take place prior to each update of the
        dependence structure.
    first_dep_update : int
        No dependence structure updates occur before this
        iteration number.
    cov_type : str
        One of "robust", "naive", or "bias_reduced".
    ddof_scale : scalar or None
        The scale parameter is estimated as the sum of squared
        Pearson residuals divided by `N - ddof_scale`, where N
        is the total sample size.  If `ddof_scale` is None, the
        number of covariates (including an intercept if present)
        is used.
    scaling_factor : scalar
        The estimated covariance of the parameter estimates is
        scaled by this value.  Default is 1, Stata uses N / (N - g),
        where N is the total sample size and g is the average group
        size.
    scale : str or float, optional
        `scale` can be None, 'X2', or a float
        If a float, its value is used as the scale parameter.
        The default value is None, which uses `X2` (Pearson's
        chi-square) for Gamma, Gaussian, and Inverse Gaussian.
        The default is 1 for the Binomial and Poisson families.

    Returns
    -------
    An instance of the GEEResults class or subclass

    Notes
    -----
    If convergence difficulties occur, increase the values of
    `first_dep_update` and/or `params_niter`.  Setting
    `first_dep_update` to a greater value (e.g. ~10-20) causes the
    algorithm to move close to the GLM solution before attempting
    to identify the dependence structure.

    For the Gaussian family, there is no benefit to setting
    `params_niter` to a value greater than 1, since the mean
    structure parameters converge in one step.
aE  
    Attributes
    ----------

    cov_params_default : ndarray
        default covariance of the parameter estimates. Is chosen among one
        of the following three based on `cov_type`
    cov_robust : ndarray
        covariance of the parameter estimates that is robust
    cov_naive : ndarray
        covariance of the parameter estimates that is not robust to
        correlation or variance misspecification
    cov_robust_bc : ndarray
        covariance of the parameter estimates that is robust and bias
        reduced
    converged : bool
        indicator for convergence of the optimization.
        True if the norm of the score is smaller than a threshold
    cov_type : str
        string indicating whether a "robust", "naive" or "bias_reduced"
        covariance is used as default
    fit_history : dict
        Contains information about the iterations.
    fittedvalues : ndarray
        Linear predicted values for the fitted model.
        dot(exog, params)
    model : class instance
        Pointer to GEE model instance that called `fit`.
    normalized_cov_params : ndarray
        See GEE docstring
    params : ndarray
        The coefficients of the fitted model.  Note that
        interpretation of the coefficients often depends on the
        distribution family and the data.
    scale : float
        The estimate of the scale / dispersion for the model fit.
        See GEE.fit for more information.
    score_norm : float
        norm of the score at the end of the iterative estimation.
    bse : ndarray
        The standard errors of the fitted GEE parameters.
aF  
    Logistic regression with autoregressive working dependence:

    >>> import statsmodels.api as sm
    >>> family = sm.families.Binomial()
    >>> va = sm.cov_struct.Autoregressive()
    >>> model = sm.GEE(endog, exog, group, family=family, cov_struct=va)
    >>> result = model.fit()
    >>> print(result.summary())

    Use formulas to fit a Poisson GLM with independent working
    dependence:

    >>> import statsmodels.api as sm
    >>> fam = sm.families.Poisson()
    >>> ind = sm.cov_struct.Independence()
    >>> model = sm.GEE.from_formula("y ~ age + trt + base", "subject",
                                 data, cov_struct=ind, family=fam)
    >>> result = model.fit()
    >>> print(result.summary())

    Equivalent, using the formula API:

    >>> import statsmodels.api as sm
    >>> import statsmodels.formula.api as smf
    >>> fam = sm.families.Poisson()
    >>> ind = sm.cov_struct.Independence()
    >>> model = smf.gee("y ~ age + trt + base", "subject",
                    data, cov_struct=ind, family=fam)
    >>> result = model.fit()
    >>> print(result.summary())
a,  
    Fit an ordinal regression model using GEE, with "global
    odds ratio" dependence:

    >>> import statsmodels.api as sm
    >>> gor = sm.cov_struct.GlobalOddsRatio("ordinal")
    >>> model = sm.OrdinalGEE(endog, exog, groups, cov_struct=gor)
    >>> result = model.fit()
    >>> print(result.summary())

    Using formulas:

    >>> import statsmodels.formula.api as smf
    >>> model = smf.ordinal_gee("y ~ 0 + x1 + x2", groups, data,
                                    cov_struct=gor)
    >>> result = model.fit()
    >>> print(result.summary())
a  
    Fit a nominal regression model using GEE:

    >>> import statsmodels.api as sm
    >>> import statsmodels.formula.api as smf
    >>> gor = sm.cov_struct.GlobalOddsRatio("nominal")
    >>> model = sm.NominalGEE(endog, exog, groups, cov_struct=gor)
    >>> result = model.fit()
    >>> print(result.summary())

    Using formulas:

    >>> import statsmodels.api as sm
    >>> model = sm.NominalGEE.from_formula("y ~ 0 + x1 + x2", groups,
                     data, cov_struct=gor)
    >>> result = model.fit()
    >>> print(result.summary())

    Using the formula API:

    >>> import statsmodels.formula.api as smf
    >>> model = smf.nominal_gee("y ~ 0 + x1 + x2", groups, data,
                                cov_struct=gor)
    >>> result = model.fit()
    >>> print(result.summary())
c                 X   | j         |j        d         k    rt          d          |j         | j         k    rt          d          ||j         | j         k    rt          d          ||j         | j         k    rt          d          ||j         | j         k    rt          d          d S d S )Nr   z:Leading dimension of 'exog' should match length of 'endog'z.'groups' and 'endog' should have the same sizez,'time' and 'endog' should have the same sizez-'offset and 'endog' should have the same sizez0'exposure' and 'endog' should have the same size)sizer(   r&   )endogr8   groupstimeoffsetexposures         r<   _check_argsrY     s    zTZ]"" - . . 	. {ej  IJJJTY%*44GHHHv{ej88HIII%*!<!<KLLL !<!<r>   c                       e Zd Zdeej        eeddz  z   ZdZ		 	 	 	 d( fd	Z
e	 	 d) f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          	 	 	 	 d+d            Zd Zd Z	 	 	 d,d!Zd" Zd# Z	 	 d-d%Zd.d'Z  xZ!S )/GEEzF    Marginal Regression Model using Generalized Estimating Equations.
 extra_params
family_docexamplenotesNnoneTc                    t          |           t          u r|                     |           |pt          |j        t          |j                            sId}t          j        |	                    |j        j
        j        |j
        j                  t                     t          j        |          }d|v r:|d         2|d          }||         }|||         }|||         }|	|	|         }	|d= || _        |
| _        || _        || _        t'          t(                    | _         t-                      j        ||f||||	||
||d| t1          | j        | j        | j        | j        t;          | dd           t;          | dd                      | j                            g d           	 | j                             d           | j                             d           n# tB          $ r Y nw xY w|tE          j#                    }n.tI          |j
        tD          j%                  stC          d	          || _&        |tO          j(                    }n.tI          |j
        tN          j)                  stC          d
          || _*        d | _        |tW          |          dk    rtC          d          |d         j,        d         | j        j,        d         k    rtC          d          t[          |d         |d         | j                  | _        | j.        (| xj.        | j        /                                z  c_.        n0| j        /                                0                                | _.        | j        1                                | _        t          j2        | j        d          \  }}tg          j4        t          j5        tW          |                    d          }|6                    |          j        fdto          |          D             }tq          |          | _9        || _:        | ;                    | j                  | _<        | ;                    | j                  | _=        | j>        | ;                    | j>                  | _?        tW          | j<                  | _@        | j        F| j        jA        dk    r| j        d d d f         | _        | ;                    | j                  | _B        n4d | j<        D             | _B        t          jC        | jB                  | _        | j.        $t          jD        | j.                  r| j.        dk    rd | _E        n| ;                    | j.                  | _E        |)| ;                    | j        jF                  | j        _G        || _&        | j*        H                    |            d | j<        D             }t          |          | _J        | j        j,        d         dz
  | _K        | jJ        | j        j,        d         z
  | _L        t          d | j<        D                       }|dk    r	d| _        d S d S )NzDThe {0} link function does not respect the domain of the {1} family.missing_idx)rU   rV   rW   rX   weightsdep_datamissingfamilyrW   rX   )
update_dep
constraintrh   r   freq_weightsvar_weightsz.GEE: `family` must be a genmod family instancez6GEE: `cov_struct` must be a genmod cov_struct instance   z$GEE: `constraint` must be a 2-tuple.r   r    zbGEE: the left hand side of the constraint must have the same number of columns as the exog matrix.T)return_inverseint)indexdtypec                 N    g | ]!\  }}|t          j        |                   f"S rQ   )r"   asarray).0klbgbs      r<   
<listcomp>z GEE.__init__.<locals>.<listcomp>\  s0    KKK%!Rr2:be$$%KKKr>   c                 |    g | ]9}t          j        t          |          t           j                   dddf         :S )rq   N)r"   aranger'   float64rt   ys     r<   rx   z GEE.__init__.<locals>.<listcomp>q  sL     ) ) ) 3q66444QQQW= ) ) )r>           c                 ,    g | ]}t          |          S rQ   r'   r}   s     r<   rx   z GEE.__init__.<locals>.<listcomp>  s    222qCFF222r>   c                 ,    g | ]}t          |          S rQ   r   rt   xs     r<   rx   z GEE.__init__.<locals>.<listcomp>  s    6661A666r>   F)Ntyper[   _check_kwargs
isinstancelinktuple
safe_linkswarningswarnformat	__class__rM   r   r"   rs   rg   rf   rj   ri   r   list_fit_historysuperr=   rY   rT   r8   rU   rV   getattr
_init_keysextendremover&   r   Gaussian
issubclassFamilyrh   cov_structsIndependence	CovStructr   r'   r(   r   _offset_exposurerA   copyrC   uniquepdSeriesr{   groupby	enumeratedictgroup_indicesgroup_labelscluster_listendog_liexog_lire   
weights_li	num_groupr%   time_liconcatenateisscalar	offset_lir6   exog_fulltrans_li
initializesumnobsdf_modeldf_residmax)r7   rT   r8   rU   rV   rh   r   rg   rW   rX   rf   rj   ri   re   kwargsmsgiir   ixsedkgroup_nsmaxgrouprw   r   s                          @r<   r=   zGEE.__init__  s`   
 ::v&&&fk51B+C+CDD -3cjj)>)G)/)9)BD D+- - - F##F""vm'<'H ''BBZFBx!##B<}% $$'-- 	 	2V"6"*G"*G &		2 	2 +1		2 	2 	2 	JIKID(D))D*d++	
 	
 	
 	  .  .  . 	/ 	/ 	/	O"">222O""=1111 	 	 	D	 >&((FFf.@@ 4  "3 4 4 4 $133JJj2K4IJJ 8  "7 8 8 8 % !:!## !GHHH!}"1%);;; EF F F 2*Q-2<Q-26)= =DO $0%%)I)I)K)KK%%% O4466;;== %4466DI 9T[FFFbYRYs2ww//u===ZZ^^"KKKK9\3J3JKKK!"XX( ))$*55((33<#"//==DOT]++ 9 y~"" Iaaag.	,,TY77DLL) )-) ) ) L t|44DI!)[.// *"b((!DNN!..t/DEEDN!!!$/"@AA O- ""4((( 32DM222MM		*Q.	DIOA$66 6666677q==#DOOO =s   .4G# #
G0/G0c                    d                     t          j                   d}
t          |t                    r
|}
||         }t          |t                    r||         }t          |t                    r||         }t          |t                    r||         }|	                    d          }d }|tt          |t                    r1t          j        ||d          }|j        	                                }nt          |          }||         }t          j        |          |	d<   d }d|	v r|	d         }|	d=  t                      j        |g|R |||||||d|	}|||_        |
|_        |S )	Na  
        Create a GEE model instance from a formula and dataframe.

        Parameters
        ----------
        formula : str or generic Formula object
            The formula specifying the model
        groups : array_like or string
            Array of grouping labels.  If a string, this is the name
            of a variable in `data` that contains the grouping labels.
        data : array_like
            The data for the model.
        subset : array_like
            An array-like object of booleans, integers, or index
            values that indicate the subset of the data to used when
            fitting the model.
        time : array_like or string
            The time values, used for dependence structures involving
            distances between observations.  If a string, this is the
            name of a variable in `data` that contains the time
            values.
        offset : array_like or string
            The offset values, added to the linear predictor.  If a
            string, this is the name of a variable in `data` that
            contains the offset values.
        exposure : array_like or string
            The exposure values, only used if the link function is the
            logarithm function, in which case the log of `exposure`
            is added to the offset (if any).  If a string, this is the
            name of a variable in `data` that contains the offset
            values.
        {missing_param_doc}
        args : extra arguments
            These are passed to the model
        kwargs : extra keyword arguments
            These are passed to the model with two exceptions. `dep_data`
            is processed as described below.  The ``eval_env`` keyword is
            passed to patsy. It can be either a
            :class:`patsy:patsy.EvalEnvironment` object or an integer
            indicating the depth of the namespace to use. For example, the
            default ``eval_env=0`` uses the calling namespace.
            If you wish to use a "clean" environment set ``eval_env=-1``.

        Optional arguments
        ------------------
        dep_data : str or array_like
            Data used for estimating the dependence structure.  See
            specific dependence structure classes (e.g. Nested) for
            details.  If `dep_data` is a string, it is interpreted as
            a formula that is applied to `data`. If it is an array, it
            must be an array of strings corresponding to column names in
            `data`.  Otherwise it must be an array-like with the same
            number of rows as data.

        Returns
        -------
        model : GEE model instance

        Notes
        -----
        `data` must define __getitem__ with the keys in the formula
        terms args and kwargs are passed on to the model
        instantiation. E.g., a numpy structured or rec array, a
        dictionary, or a pandas DataFrame.
        )missing_param_docGroupsrf   	dataframe)return_typerh   )datasubsetrU   rV   rW   rX   rh   )r   base_missing_param_docr   strgetpatsydmatrixcolumnstolistr   r"   rs   r   from_formula_dep_data_names_groups_name)clsformularU   r   r   rV   rW   rX   argsr   groups_namerf   dep_data_namesrh   modelr   s                  r<   r   zGEE.from_formula  s   @	@ FT%<F===fc"" 	" K&\FdC   	:Dfc"" 	"&\Fh$$ 	&H~H::j))(C(( * =45@B B B!)!1!8!8!:!:!%h>!#H!5!5F:vH%Fx $$W 6
 '+6 64,2,2.6,2	6 6
 /56 6 %$2E!(r>   c                 l     j         dk    r fd j        D             S  fd j        D             S )zf
        Returns `array` split into subarrays corresponding to the
        cluster structure.
        r    c                 Z    g | ]'}t          j        j        |                            (S rQ   r"   arrayr   rt   ru   r   r7   s     r<   rx   z$GEE.cluster_list.<locals>.<listcomp>  s@     0 0 0 HU4#5a#89:: 0 0 0r>   c                 b    g | ]+}t          j        j        |         d d f                   ,S Nr   r   s     r<   rx   z$GEE.cluster_list.<locals>.<listcomp>  sI     0 0 0 HU4#5a#8!!!#;<== 0 0 0r>   )r%   r   )r7   r   s   ``r<   r   zGEE.cluster_list  sw     :??0 0 0 0 0!.0 0 0 00 0 0 0 0!.0 0 0 0r>   c                 >   |j         j        | _        |j         }| j        j        d         |j        j        d         k    rd}t	          |          | j        j        d         |j        j        d         k    rd}t          j        |           t          | j        t          |j                            sd}t          j        |           t          | j
        t          |j
                            st          j        d           t          j        | j        |j                                                  sd}t          j        |           t          | |j                   \  }}|d	}t	          |          t          j        ||j                  }| j
        }ddl}|                    | j                  }	|j
        | _
        |                     |           |                                 \  }
}|d
}t          j        |t.                     dS t1          | d          s| j        j        d         | _        t1          | d          sd| _        |                                 \  }
}}t          j        |j        |          }	 t          j                            |          }n9# t          j        j        $ r" t          j                             |          }Y nw xY wt          j        |j        t          j        ||                    }t          j        |j        t          j        ||                    }t          j        |j        t          j        ||                    }t          j        |j        t          j        ||                    }t          j        |j        t          j        ||                    }	 t          j        !                    ||          }nL# t          j        j        $ r5 t          j        t          j                             |          |          }Y nw xY w|t          j        |j        |          z
  }	 t          j        !                    ||          }nL# t          j        j        $ r5 t          j        t          j                             |          |          }Y nw xY w|t          j        |j        |          z  }	 t          j        !                    ||          }nL# t          j        j        $ r5 t          j        t          j                             |          |          }Y nw xY w	 t          j        !                    ||          }nL# t          j        j        $ r5 t          j        t          j                             |          |          }Y nw xY w|t          j        |j        t          j        ||                    z  }|| _
        |	| _        ddl"m#} 	 t          j        !                    ||          }nL# t          j        j        $ r5 t          j        t          j                             |          |          }Y nw xY wt          j        ||          }tI          |          }d|%                    ||          z
  }|||dS )a   
        Perform a score test for the given submodel against this model.

        Parameters
        ----------
        submodel : GEEResults instance
            A fitted GEE model that is a submodel of this model.

        Returns
        -------
        A dictionary with keys "statistic", "p-value", and "df",
        containing the score test statistic, its chi^2 p-value,
        and the degrees of freedom used to compute the p-value.

        Notes
        -----
        The score test can be performed without calling 'fit' on the
        larger model.  The provided submodel must be obtained from a
        fitted GEE.

        This method performs the same score test as can be obtained by
        fitting the GEE with a linear constraint and calling `score_test`
        on the results.

        References
        ----------
        Xu Guo and Wei Pan (2002). "Small sample performance of the score
        test in GEE".
        http://www.sph.umn.edu/faculty1/wp-content/uploads/2012/11/rr2002-013.pdf
        r   z3Model and submodel have different numbers of cases.r    z4Model and submodel have the same number of variablesz/Model and submodel have different GLM families.z<Model and submodel have different GEE covariance structures.z0Model and submodel should have the same weights.Nz%The provided model is not a submodel.-Singular matrix encountered in GEE score test
ddof_scalescaling_factorchi2	statisticdfzp-value)&r   	scaletyper8   r(   r&   r   r   r   rh   r   r   r"   equalre   all_score_test_submodelr2   rH   r   deepcopycached_meansupdate_cached_means_update_mean_paramsr   hasattrr   r   _covmatr-   r+   invLinAlgErrorpinvsolvescipy.stats.distributionsr   r'   cdf)r7   submodelsubmodr   qmqc	params_excov_struct_saver   cached_means_save_scorencov1cmatscore2amatbmat_11bmat_22bmat_12amat_11amat_12ab	score_covaar   sc2score_statisticscore_dfscore_pvalues                                r<   compare_score_testzGEE.compare_score_test  s   D "1 9?1!21!555GCS//!9?1!21!555HCM#$+tFM':':;; 	CCM#$/40A+B+BCC 	)M ( ) ) )xfn5599;; 	DCM# &dHN;;B:9CS//! F2x//	 / MM$*;<< #-  +++++--5=ACM#12224t\** 	1"ioa0DOt-.. 	$"#D5$e$$	)9==''DDy$ 	) 	) 	)9>>%((DDD	) &rvdB//00&rvdB//00&rvdB//00&rvdB//00&rvdB//00	:'22BBy$ 	: 	: 	:	w//99BBB	: bfWY333		:'22BBy$ 	: 	: 	:	w//99BBB	: 	RVGIr***		:'22BBy$ 	: 	: 	:	w//99BBB	:	:'22BBy$ 	: 	: 	:	w//99BBB	: 	RVGIrvb"~~666	 *-222222	<)//)V44CCy$ 	< 	< 	<&	22F;;CCC	<&--v;;488OX>>>,') ) 	)sq   >J 3KK9 O AP#"P# Q% %AR.-R. S0 0AT98T9= U AV'&V'/ X AYYc                 :   | j         ?t          | j        t          j        t          j        t          j        t          f          rdS n3t          | j         t                    rt          j
        | j                   S | j        }| j        }| j        }| j        j        }d}d}t          | j                  D ]}t#          ||                   dk    r||         \  }}	t          j         ||                    }
||         |z
  |
z  }| j        B| j        |         }|t          j        ||dz  z            z  }||                                z  }|t          j        |dz            z  }|t#          |          z  }|||| j        z
  z  t          |          z  z  }|S )z0
        Estimate the dispersion/scale.
        N      ?r   r   rm   )r   r   rh   r   BinomialPoissonNegativeBinomial_Multinomialfloatr"   r   r   r   r   varianceranger   r'   sqrtre   r   r   r   )r7   rT   r   r   varfuncscalefsumiexpvalr   sdevresidfs                r<   estimate_scalezGEE.estimate_scale  s   
 >!$+(98;K(0(A(4(6 7 7  r .. 	,8DN+++(y+&t~&& 	# 	#A58}}!!$QIFA7776??++D1X&$.E|'OA&UaZ 0111
+++E

"$$01E$KK?@r>   c                 b    | j         j                            |          }||dddf         z  }|S )a>  
        Derivative of the expected endog with respect to the parameters.

        Parameters
        ----------
        exog : array_like
           The exogeneous data at which the derivative is computed.
        lin_pred : array_like
           The values of the linear predictor.

        Returns
        -------
        The value of the derivative of the expected endog with respect
        to the parameter vector.

        Notes
        -----
        If there is an offset or exposure, it should be added to
        `lin_pred` prior to calling this function.
        N)rh   r   inverse_deriv)r7   r8   lin_predidldmats        r<   
mean_derivzGEE.mean_deriv  s7    , k,,X66c!!!T'l"r>   c                     t          j        ||          }|||z  }| j        j                            |          }t          j        ||          }|S )a	  
        Derivative of the expected endog with respect to exog.

        Parameters
        ----------
        exog : array_like
            Values of the independent variables at which the derivative
            is calculated.
        params : array_like
            Parameter values at which the derivative is calculated.
        offset_exposure : array_like, optional
            Combined offset and exposure.

        Returns
        -------
        The derivative of the expected endog with respect to exog.
        )r"   r2   rh   r   r$  outer)r7   r8   rH   offset_exposurer%  r&  r'  s          r<   mean_deriv_exogzGEE.mean_deriv_exog  sS    & 6$''&'Hk,,X66xV$$r>   c                    | j         }| j        }t          | dd          }| j        }| j        j        }d\  }}t          | j                  D ]}||         \  }	}
||         |	z
  }|                     ||         |
          }t          j
         ||	                    }|||         }||z  }||dddf         z  }n|}|}| j                            |	||||f          }| dS t          |          \  }}|t          j        |j        |          z  }|t          j        |j        |          z  }	 t          j                            ||          }nL# t          j        j        $ r5 t          j        t          j                            |          |          }Y nw xY w| j        d                             | j        j                   ||fS )a  
        Returns
        -------
        update : array_like
            The update vector such that params + update is the next
            iterate when solving the score equations.
        score : array_like
            The current value of the score equations, not
            incorporating the scale parameter.  If desired,
            multiply this vector by the scale parameter to
            incorporate the scale.
        r   Nr   r   NN
cov_adjust)r   r   r   r   rh   r  r  r   r(  r"   r  r   covariance_matrix_solver   r2   r-   r+   r   r   r   r   appendr0  )r7   rT   r8   re   r   r  bmatr   r  r  lprr   r'  r  wwresidwdmatrsltvinv_d
vinv_residupdates                        r<   r   zGEE._update_mean_params  s    |$d33(+&et~&& 	0 	0A&q/KFC!Hv%E??47C00D7776??++D"AJqDz)?::AteV_6 6D|!zz!&tFJBF466***DRVDFJ///EE	9Y__T511FFy$ 	9 	9 	9VBINN400%88FFF	9 	,'..O&	( 	( 	( u}s   2 E AFFc                 `   | j         }| j        }| j        }| j        j        j        }g | _        t          | j                  D ]k}t          ||                   dk    rt          j        ||         |          }||||         z  } ||          }| j                            ||f           ldS )z
        cached_means should always contain the most recent calculation
        of the group-wise mean vectors.  This function should be
        called every time the regression parameters are changed, to
        keep the cached means up to date.
        r   N)r   r   r   rh   r   inverser   r  r   r'   r"   r2   r2  )	r7   mean_paramsrT   r8   rW   linkinvr  r4  r  s	            r<   r   zGEE.update_cached_means8  s     |+"*t~&& 
	4 
	4A58}}!!&a+..C!vay WS\\F$$fc]3333
	4 
	4r>   c                    | j         }| j        }t          | dd          }| j        j        }| j        }d\  }}t          | j                  D ]}||         \  }	}
||         |	z
  }|                     ||         |
          }t          j
         ||	                    }|||         }||z  }||dddf         z  }n|}|}| j                            |	||||f          }| dS t          |          \  }}|t          j        |j        |          z  }t          j        |j        |          }|t          j        ||          z  }|                                 }	 t          j                            |          }n9# t          j        j        $ r" t          j                            |          }Y nw xY w||z  }t          j        |t          j        ||                    }|| j        z  }|| j        z  }|||fS )a  
        Returns the sampling covariance matrix of the regression
        parameters and related quantities.

        Returns
        -------
        cov_robust : array_like
           The robust, or sandwich estimate of the covariance, which
           is meaningful even if the working covariance structure is
           incorrectly specified.
        cov_naive : array_like
           The model-based estimate of the covariance, which is
           meaningful if the covariance structure is correctly
           specified.
        cmat : array_like
           The center matrix of the sandwich expression, used in
           obtaining score test results.
        r   Nr.  NNNN)r   r   r   rh   r  r   r  r   r(  r"   r  r   r1  r   r2   r-   r*  r"  r+   r   r   r   r   )r7   rT   r8   re   r  r   r3  r   r  r  r4  r   r'  r  r5  r6  r7  r8  r9  r:  dvinv_residr  bmati	cov_naive
cov_robusts                            r<   r   zGEE._covmatT  s   ( |$d33+&( 
dt~&& 	7 	7A&q/KFC!Hv%E??47C00D7776??++D"AJqDz)?::4%2 2D|---!&tFJBF466***D&44KBH[+666DD##%%	)IMM$''EEy$ 	) 	) 	)INN4((EEE	) EM	VE26$#6#677
T((	d))
9d**s   E; ;3F10F1c                    || j         z  }| j        }| j        }| j        j        }| j        }|                                 }d}t          | j                  D ]q}||         \  }	}
||         |	z
  }| 	                    ||         |
          }t          j         ||	                    }| j                            |	|||f          }| d S |d         }||z  }t          j        ||          }t          j        ||j                  j        }| j        | j        |         nd}t          j                            t          j        t+          |                    |z
  |          }| j                            |	|||f          }| d S |d         }|t          j        |j        |          z  |z  }|t          j        ||          z  }st          j        |t          j        ||                    }|| j         z  }|S )Nr   r  )r   r   r   rh   r  r   r"  r  r   r(  r"   r  r   r1  r2   r-   re   r   r+   r   eyer'   r*  )r7   rD  rT   r8   r  r   r  bcmr  r  r4  r   r'  r  r8  r9  hmatr!  aresidsrtcov_robust_bcs                        r<   
_bc_covmatzGEE._bc_covmat  s    33	|+&(##%%t~&& 	& 	&A&q/KFC!Hv%E??47C00D7776??++D?::4$* *D|tt!WFeOF6&),,D6$'')D&*l&>""BAY__RVCJJ%7%7$%>FFF?::4&, ,D|ttq'CbfTVS)))E1C28C%%%CCy"&i*@*@AA,,r>   c                     t          j        | j                  rd }n| j        }t          | j        | j        | j        || j                  }|                                }|j	        S )N)rh   rW   rk   )
r"   r   r   r	   rT   r8   rh   re   fitrH   )r7   rW   r   results       r<   _starting_paramszGEE._starting_params  sb    ;t,-- 	+FF*FDJ	$+!> > >}r>   <   ư>r    r   robustr  c
           	      X   |	| _         || j        j        d         | _        n|dk    st	          d          || _        || _        t          t                    | _        | j	        |dk    rt	          d          || 
                                }
n(t          j        |          }|                                }
|                     |
           d}d}t          |          D ]?}|                                 \  }}|t#          j        dt&                      n|
|z  }
|                     |
           t          j        t          j        |dz                      }| j        d	                             |
                                           | j        d
                             |           | j        d                             | j        j                   ||k     r|dk    s	| j        du r n2| j        r)||z  dk    r ||k    r|                     |
           |dz  }A||k    rt#          j        dt6                     |
t#          j        dt&                     d S |                                 \  }}}|t#          j        dt&                     d S d }|dk    r|                     |          }| j        |
                                }|                     |
|          \  }
}|
t#          j        dt&                     d S |                     ||          \  }}|t#          j        dt&                     d S |7|                     ||          \  }}|t#          j        dt&                     d S |                                  }	tC          ||||          }tE          | |
||	z  |	|d|          }| j        |_#        t          t                    | _#        ||_$        ||k     |_%        | j        |_        ||_&        ||_'        ||_(        ||_)        g d|_*        tW          |          S )Nr    r   0ddof_scale must be a non-negative number or Nonenaivez-when using weights, cov_type may not be naiveg      z)Singular matrix encountered in GEE updaterm   rH   r   
dep_paramsFz,Iteration limit reached prior to convergencez"Unable to estimate GEE parameters.z<Estimated covariance structure for GEE estimates is singularbias_reducedz.Unable to estimate constrained GEE parameters.)cov_typerE  rD  rL  )rZ  use_t	attr_kwds)rZ  r[  cov_params_defaultrE  rD  rL  fit_history
score_norm	convergedr   params_niterfirst_dep_updatectolmaxiter),r   r8   r(   r   r&   r   r   r   r   re   rQ  r"   rs   r   r   r  r   r   r   r   r  r   r2  r   rX  ri   _update_assocr   r   rM  rj   _handle_constraintr"  r   
GEEResultsr^  r_  r`  ra  rb  rc  rd  _propsGEEResultsWrapper)r7   rd  rc  start_paramsra  rb  rZ  r   r   r  r>  
del_paramsnum_assoc_updatesitrr;  r   rK   ncovr   bc_covr   r~   res_kwdsresultss                           r<   rO  zGEE.fit  s     "ioa0DOO?? FH H H(DO,'--<#G(;(;LMMM//11KK:l33L&++--K  ---
>> 	' 	'C 4466MFE~I02 2 26!K$$[111 
!3!344Jh'..{/?/?/A/ABBBg&--e444l+22*, , ,
 T!!&**do.F.F  'S<%7A$=$= 000"";///!Q&!MH/1 1 1 M>,. . .4dA<M 23EG G G4~%%__T**F?&  ""A $ 7 7T J JK" ,-?A A At--a66GAty ,-?A A At! 33Av>>	69M #01CE E E4##%% #'"&&,. . . T;ue&.e'/1 1 1
 #/&t,,''$.!_+#3 !% % % !)))r>   c                 b   d\  }}t          | j                  D ]}| j        |         \  }}	| j        |         |z
  }
t	          j        | j                            |                    }| j        |         |d d d f         dz  z  }| j	        
                    ||||
|f          }|d         }|t	          j        |j        |          z  }|d         }|t	          j        |j        |          z  }t	          j        |          }t	          j        ||z  |z
  dt          j                  }||z  ||k    z  }||dz
  |z  z  }||||k    z  z  }|||z   z  }|j        d d |j        d         dz   xx         | j        |z  z  cc<   || j        |z  |z  z  }	 t          j                            ||          }nb# t          j        j        $ rK t	          j        t          j                            |          |          }d}t-          j        |           Y nw xY w||                                 z  }||fS )Nr.  rm   r   r    z1Encountered singularity in regularized GEE update)r  r   r   r   r"   r  rh   r  r   r   r1  r2   r-   absclipinfflatr(   r+   r   r   r   r   r   r"  )r7   rH   pen_wt
scad_paramepssnhmr  r  r   r   r  exr8  sn0hm0apclippedenr;  r   s                        r<   _update_regularizedzGEE._update_regularized_  sH   Bt~&& 	$ 	$A)!,IFAM!$v-E74;//7788Da44=!#33B?::!1dUBK9 9Dq'C"&s###Bq'C"&s###BB
 VF^^'*v-2Arv>>gf-
zA~''
ff%%
cBh
!!"(1+/!"""dnr&99"""
dnr!F**	Y__R,,FFy$ 	 	 	VBINN2..33FECM#	 	d!!###rzs    F4 4AHHc                    |                      |           d}t          | j                  D ]}| j        |         \  }}| j        |         |z
  }t          j        | j                            |                    }| j	        |         |d d d f         dz  z  }| j
                            ||||f          }	t          j        |j        |	d                   }
|t          j        |
|
          z  }|S )Nr   rm   )r   r  r   r   r   r"   r  rh   r  r   r   r1  r2   r-   r*  )r7   r>  mar  r  r   r   r  r|  r8  ma0s              r<   _regularized_covmatzGEE._regularized_covmat  s      ---t~&& 
	% 
	%A)!,IFAM!$v-E74;//7788Da44=!#33B?::!1dUH6 6D&tAw''C"(3$$$BB	r>   皙@d      h㈵>MbP?c
                    |	| _         t          j        | j        j        d                   }
|                     |
           d}t          t                    }|| j        j        d         | _        n|dk    st          d          || _        d}t          |          D ]}|                     |
|||          \  }}|d}t          j        |t                      n||k    r1t          j        t          j        |dz                      |k     rd	} nl|
|z  }
|d
                             |
                                           |                     |
           |dk    r||z  dk    r|                     |
           |sd}t          j        |           d|
t          j        |
          |k     <   |                     |
           |                     |
          }t          j                            ||          }t          j                            ||j                  }t3          d|          }|                                 }	t7          | |
||	d	|          }||_        t;          |          S )a\  
        Regularized estimation for GEE.

        Parameters
        ----------
        pen_wt : float
            The penalty weight (a non-negative scalar).
        scad_param : float
            Non-negative scalar determining the shape of the Scad
            penalty.
        maxiter : int
            The maximum number of iterations.
        ddof_scale : int
            Value to subtract from `nobs` when calculating the
            denominator degrees of freedom for t-statistics, defaults
            to the number of columns in `exog`.
        update_assoc : int
            The dependence parameters are updated every `update_assoc`
            iterations of the mean structure parameter updates.
        ctol : float
            Convergence criterion, default is one order of magnitude
            smaller than proposed in section 3.1 of Wang et al.
        ztol : float
            Coefficients smaller than this value are treated as
            being zero, default is based on section 5 of Wang et al.
        eps : non-negative scalar
            Numerical constant, see section 3.2 of Wang et al.
        scale : float or string
            If a float, this value is used as the scale parameter.
            If "X2", the scale parameter is always estimated using
            Pearson's chi-square method (e.g. as in a quasi-Poisson
            analysis).  If None, the default approach for the family
            is used to estimate the scale parameter.

        Returns
        -------
        GEEResults instance.  Note that not all methods of the results
        class make sense when the model has been fit with regularization.

        Notes
        -----
        This implementation assumes that the link is canonical.

        References
        ----------
        Wang L, Zhou J, Qu A. (2012). Penalized generalized estimating
        equations for high-dimensional longitudinal data analysis.
        Biometrics. 2012 Jun;68(2):353-60.
        doi: 10.1111/j.1541-0420.2011.01678.x.
        https://www.ncbi.nlm.nih.gov/pubmed/21955051
        http://users.stat.umn.edu/~wangx346/research/GEE_selection.pdf
        r    FNr   rV     z5Singular matrix encountered in regularized GEE updaterm   TrH   z$GEE.fit_regularized did not convergerT  )rZ  rE  )regularizedr\  )r   r"   zerosr8   r(   r   r   r   r   r&   r  r  r   r   r   r  r   r2  r   re  rs  r  r+   r   r-   r   r"  rg  r^  ri  )r7   rw  rx  rd  r   update_assocrc  ztolry  r  r>  r`  r^  miniterrm  r;  r{  r   r  covrp  r8  s                         r<   fit_regularizedzGEE.fit_regularized  s{   p htyq122  ---	!$'' "ioa0DOO?? FH H H(DO
 >> 	0 	0C11)6:sD DJFB~Mc#5666W}}	):):!;!;d!B!B 	6!K!(()9)9););<<<$$[111axxS</144"";/// 	8CM#23BF;''$./;'''%%k22ioob"%%ioob#%(( c:::##%%$S%&*h@ @ @& &&&r>   c                 P   t          |          }| j        j        j        d         }t          j        |t	          j        ||z
            f         }| j        }| j        j        | _        ddl	}|
                    | j                  }|                     |           |                                 \  }	}
|
t          j        dt                      dS |                                 \  }	}}|                                 }||dz  z  }|
|d         |z  }t          j                            |          }|d|d|f         }||d|df         }|d||df         }|d|d|f         }|d||df         }|t	          j        |j        t          j                            ||                    z
  }|t	          j        |j        t          j                            ||                    z  }|t	          j        |j        t	          j        t          j                            ||          t          j                            ||                              z  }ddlm} t	          j        |t          j                            ||                    }t          |          }d|                    ||          z
  }|||d| _        | j                            |          }| j                            |          }|| _        || _        | j                                        | _        ||fS )	a  
        Expand the parameter estimate `mean_params` and covariance matrix
        `bcov` to the coordinate system of the unconstrained model.

        Parameters
        ----------
        mean_params : array_like
            A parameter vector estimate for the reduced model.
        bcov : array_like
            The covariance matrix of mean_params.

        Returns
        -------
        mean_params : array_like
            The input parameter vector mean_params, expanded to the
            coordinate system of the full model
        bcov : array_like
            The input covariance matrix bcov, expanded to the
            coordinate system of the full model
        r    r   Nr   r/  rm   r   r   ) r'   rj   r)   r(   r"   r_r  r   r   r   r   r   r   r   r   r   r   r   r"  r+   r   r2   r-   r   r   r   r   score_test_resultsrI   rL   rE   r8   )r7   r>  rK   red_pfull_pmean_params0save_exog_lir   save_cached_meansr   r   r   r   r  r  r  r  r  r  r  r  r	  r   r  r  r  s                             r<   rf  zGEE._handle_constraint  s   . K  $*1-u["(6E>*B*BBC |8 MM$*;<<  ...++--5=MI,. . .:5$##%%eqj uvv&y}}U##qw%'(uvvuvv~&qw'qw%'(qw'bfWY%'Y__Wg%F%FH H H	RVGIIOOGW==? ? 	?	RVGIF29??7G#D#D#%9??7G#D#DF FG G 	G	 	322222&!#F!C!CE Ev;;488OX>>>0?)1.:#< #< o22;??))$//#-O0022	D  r>   c                 :    | j                             |           dS )z3
        Update the association parameters
        N)r   r;  rG   s     r<   re  zGEE._update_assoc^  s     
 	v&&&&&r>   dydxc                    d}|| j         }| j        }|                     |||          }d|v r||z  }d|v r#||                     ||          dddf         z  }|ddlm}  |||||| |          }|ddlm}	  |	||||| |          }|S )a1  
        For computing marginal effects, returns dF(XB) / dX where F(.)
        is the fitted mean.

        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|  eyr   )_get_count_effects)_get_dummy_effects)r8   r   r,  predict%statsmodels.discrete.discrete_marginsr  r  )
r7   rH   r8   	transform	dummy_idx	count_idxr+  margeffr  r  s
             r<   _derivative_exogzGEE._derivative_exoge  s    <9D"3O&&tV_EE9tOG9t||FD11!!!T'::G $ $ $ $ $ $(($	9)-v7 7G $ $ $ $ $ $(($	9)-v7 7Gr>     c                    | j         j        }g }d}t          | j                  D ]h}| j        |         \  }	}
|                    |	           |                     | j        |         |
          }|t          j	        |j
        |          |z  z  }it          j        |          }t          j        | j                  }||z
  }t          j        |          }t          j        dd|          }t          |          D ]B\  }}||dz   |z  dz  z   } ||          }t          j        |dz  |dz   z  |z             ||<   C|d|z  z  }	 ddlm} n# t&          $ r	 dd	lm} Y nw xY w |||d         |d         z
  
          }d|z  d| j        j        d         z  z   }d|z  dt          j        t          j	        ||                    z  z   }|||fS )aB  
        Returns quasi-information criteria and quasi-likelihood values.

        Parameters
        ----------
        params : array_like
            The GEE estimates of the regression parameters.
        scale : scalar
            Estimated scale parameter
        cov_params : array_like
            An estimate of the covariance matrix for the
            model parameters.  Conventionally this is the robust
            covariance matrix.
        n_step : integer
            The number of points in the trapezoidal approximation
            to the quasi-likelihood function.

        Returns
        -------
        ql : scalar
            The quasi-likelihood value
        qic : scalar
            A QIC that can be used to compare the mean and covariance
            structures of the model.
        qicu : scalar
            A simplified QIC that can be used to compare mean structures
            but not covariance structures

        Notes
        -----
        The quasi-likelihood used here is obtained by numerically evaluating
        Wedderburn's integral representation of the quasi-likelihood function.
        This approach is valid for all families and  links.  Many other
        packages use analytical expressions for quasi-likelihoods that are
        valid in special cases where the link function is canonical.  These
        analytical expressions may omit additive constants that only depend
        on the data.  Therefore, the numerical values of our QL and QIC values
        will differ from the values reported by other packages.  However only
        the differences between two QIC values calculated for different models
        using the same data are meaningful.  Our QIC should produce the same
        QIC differences as other software.

        When using the QIC for models with unknown scale parameter, use a
        common estimate of the scale parameter for all models being compared.

        References
        ----------
        .. [*] W. Pan (2001).  Akaike's information criterion in generalized
               estimating equations.  Biometrics (57) 1.
        r   gwJr    g       @rm      r   )	trapezoid)trapz)dx)rh   r  r  r   r   r2  r(  r   r"   r2   r-   r   r   emptylinspacer   r   scipy.integrater  ImportErrorr  r8   r(   trace)r7   rH   r  
cov_paramsn_stepr  meansomegar  r  r4  r'  r   duqvxvguvur  qlqicuqics                          r<   r  zGEE.qic  s   h +& t~&& 	2 	2A+A.KFCLL   ??4<?C88DRVDFD))E11EEu%% >$-00XXf[1f--bMM 	2 	2DAqAER<#--ABVBEQUOb0111BqEE
q5y	;1111111 	; 	; 	;::::::::	; Yrbebem,,,BwTY_Q///2gBHRVE:%>%>????3}s   E EE)
NNNrb   NNNNTNrA  r   )	rR  rS  Nr    r   rT  Nr  N)r  r  Nr  r  r  rS  N)Nr  NN)r  )"rM   rN   rO   _gee_init_docr   r   _gee_family_doc_gee_examplerP   r   r=   classmethodr   r   r  r"  r(  r,  r   r   r   rM  rQ  r   _gee_fit_docrO  r  r  r  rf  re  r  r  __classcell__r   s   @r<   r[   r[     s@       	&0& 	 		  L>B9=:>*.`$ `$ `$ `$ `$ `$H 8<6:o o o o o [ob0 0 0N) N) N)`' ' 'R  4   67 7 7r4 4 48B+ B+ B+L) ) )V
 
 
 Xl6:-.?AK* K* K* K*Z& & &P  ( ?B67>Bs' s' s' s'jL! L! L!\' ' ' =C37" " " "HX X X X X X X Xr>   r[   c                       e Zd Zdez   Z	 d  fd	Zed             Zd!dZed             Z	d Z
ed	             Zed
             Zed             Zd"dZeZeZeZ eeddiz            	 	 	 d#d            Z eeddiz            d$d            Z eeddiz            	 	 d%d            Zd&dZd'dZ	 	 d(dZ	 	 d)dZd ZeZ xZS )*rg  zHThis class summarizes the fit of a marginal regression model using GEE.
rT  Fc                 p   t                                          ||||           |j        | _        |j        | _        |j        | _        |                    di           }	| j                            |	           t          | d          rt          | d          s|| _	        | j	        
                                }
g d}|
|vr'dd                    |          z   }t          |          |dk    r| j        }n|d	k    r| j        }n|d
k    r| j        }|| _        d S | j	        |k    rt          d          d S )N)normalized_cov_paramsr  r\  rZ  r]  rT  rW  rY  zGEE: `cov_type` must be one of , rT  rW  rY  z@cov_type in argument is different from already attached cov_type)r   r=   r   r   rh   pop__dict__r;  r   rZ  lowerjoinr&   rE  rD  rL  r]  )r7   r   rH   r  r  rZ  r[  r  kwdsr\  covariance_typeallowed_covariancesr   r  r   s                 r<   r=   zGEEResults.__init__  si    	65 	 	
 	
 	

 lHH["--	Y''' j)) 	>233	>$DM"m1133O"E"E"E&9998yy!4556 oo%8##oW$$n^++(&)D###}((  "= > > > )(r>   c                     | j         S )z)
        The response residuals.
        )resid_responser@   s    r<   r   zGEEResults.resid  s    
 ""r>   c                    |                                 }g d}||vr'dd                    |          z   }t          |          |dk    r+t          j        t          j        | j                            S |dk    r+t          j        t          j        | j                            S |dk    rA| j        t          d          t          j        t          j        | j                            S dS )	a  
        This is a convenience function that returns the standard
        errors for any covariance type.  The value of `bse` is the
        standard errors for whichever covariance type is specified as
        an argument to `fit` (defaults to "robust").

        Parameters
        ----------
        cov_type : str
            One of "robust", "naive", or "bias_reduced".  Determines
            the covariance used to compute standard errors.  Defaults
            to "robust".
        r  z&GEE: `covariance_type` must be one of r  rT  rW  rY  Nz,GEE: `bias_reduced` covariance not available)	r  r  r&   r"   r  diagrE  rD  rL  )r7   rZ  r  r  r   s        r<   standard_errorszGEEResults.standard_errors  s      #..**AAA"555;990112CS//!h&&7274?33444''7274>22333..!) BD D D7274#566777	 /.r>   c                 6    |                      | j                  S r   )r  rZ  r@   s    r<   bsezGEEResults.bse<  s    ##DM222r>   c                 p    t          | j        d          sd}|dz  }t          |          | j        j        S )a  
        Return the results of a score test for a linear constraint.

        Returns
        -------
        Adictionary containing the p-value, the test statistic,
        and the degrees of freedom for the score test.

        Notes
        -----
        See also GEE.compare_score_test for an alternative way to perform
        a score test.  GEEResults.score_test is more general, in that it
        supports testing arbitrary linear equality constraints.   However
        GEE.compare_score_test might be easier to use when comparing
        two explicit models.

        References
        ----------
        Xu Guo and Wei Pan (2002). "Small sample performance of the score
        test in GEE".
        http://www.sph.umn.edu/faculty1/wp-content/uploads/2012/11/rr2002-013.pdf
        r  z3score_test on results instance only available when z model was fit with constraints)r   r   r&   r  )r7   r   s     r<   
score_testzGEEResults.score_test@  s@    0 tz#788 	"GC44CS//!z,,r>   c                     g }| j         j        D ]4}| j         j        |         }|                    | j        |                    5|S )z
        Returns the residuals, the endogeneous data minus the fitted
        values from the model.  The residuals are returned as a list
        of arrays containing the residuals for each cluster.
        )r   r   r   r2  r   r7   sresidvr   s       r<   resid_splitzGEEResults.resid_split_  sL     ( 	* 	*A)!,BMM$*R.))))r>   c                     | j                                         }| j        j        D ]<}| j        j        |         }||xx         ||                                         z  cc<   =|S )zC
        Returns the residuals centered within each group.
        )r   r   r   r   r   mean)r7   cresidr  r   s       r<   resid_centeredzGEEResults.resid_centeredl  sc    
 ""( 	, 	,A)!,B2JJJ&*//+++JJJJr>   c                     g }| j         j        D ]4}| j         j        |         }|                    | j        |                    5|S )z
        Returns the residuals centered within each group.  The
        residuals are returned as a list of arrays containing the
        centered residuals for each cluster.
        )r   r   r   r2  centered_residr  s       r<   resid_centered_splitzGEEResults.resid_centered_splitw  sN     ( 	3 	3A)!,BMM$-b12222r>   Nr  c                     |t          j        d           || j        }| j                            | j        ||                                 |          \  }}}||fS )zh
        Returns the QIC and QICu information criteria.

        See GEE.qic for documentation.
        NzMQIC values obtained using scale=None are not appropriate for comparing models)r  )r   r   r  r   r  rH   r  )r7   r  r  r   r  r  s         r<   r  zGEEResults.qic  sr     =M = > > > =JEz~~dk5&*oo&7&7-3 & 5 53 Dyr>   extra_params_docr\   Tc                 4    ddl m}  || |||||          }|S )Nr   )plot_added_variable)
resid_typeuse_glm_weights
fit_kwargsax)$statsmodels.graphics.regressionplotsr  )r7   
focus_exogr  r  r  r  r  figs           r<   r  zGEEResults.plot_added_variable  sG    
 	MLLLLL!!$
-72A-7B@ @ @
 
r>   c                 *    ddl m}  || ||          S )Nr   )plot_partial_residuals)r  )r  r  )r7   r  r  r  s       r<   r  z!GEEResults.plot_partial_residuals  s/     	POOOOO%%dJ2>>>>r>   Q?c                 .    ddl m}  || ||||          S )Nr   )plot_ceres_residuals)
cond_meansr  )r  r  )r7   r  fracr  r  r  s         r<   r  zGEEResults.plot_ceres_residuals  s@     	NMMMMM##D*d/9bB B B 	Br>   皙?c                    || j         }n|                     |          }| j        }t          j        }|                    d|dz  z
            }|| j        ||z  z
  }| j        ||z  z   }	n<t          j        |          }||         |||         z  z
  }||         |||         z  z   }	t          j        t          ||	                    S )a  
        Returns confidence intervals for the fitted parameters.

        Parameters
        ----------
        alpha : float, optional
             The `alpha` level for the confidence interval.  i.e., The
             default `alpha` = .05 returns a 95% confidence interval.
        cols : array_like, optional
             `cols` specifies which confidence intervals to return
        cov_type : str
             The covariance type used for computing standard errors;
             must be one of 'robust', 'naive', and 'bias reduced'.
             See `GEE` for details.

        Notes
        -----
        The confidence interval is based on the Gaussian distribution.
        NrZ  r    rm   )	r  r  rH   r   normppfr"   rs   r   )
r7   alphacolsrZ  r  rH   distqr  uppers
             r<   conf_intzGEEResults.conf_int  s    . (CC&&&99CzHHQ]##<K!c')EK!c')EE:d##D4L1s4y=0E4L1s4y=0Ez$ue,,---r>   c                    ddddgfddgfd| j         j        j        j        gfd| j         j        j        j        gfd	d
| j        gfg}d | j         j        D             }dt          |          gfdt          | j         j                  gfdt          |          gfdt          |          gfddt          j        |          z  gfddt          | j        d                   z  gfdd| j        z  gfdg}t          j        | j                  }t          j        | j                  }	t          j        | j                  }
t          j        | j                  }dd|z  gfdd|
z  gfg}dd|	z  gfdd|z  gfg}|| j         j        j        dz   dz   }|| j         j        }|| j         j        }d d!lm}  |            }|                    | |||||"           |                    | |||d#$           |                    | ||||d"           |S )%a|  
        Summarize the GEE regression results

        Parameters
        ----------
        yname : str, optional
            Default is `y`
        xname : list[str], optional
            Names for the exogenous variables, default is `var_#` for ## in
            the number of regressors. Must match the number of parameters in
            the model
        title : str, optional
            Title for the top table. If not None, then this replaces
            the default title
        alpha : float
            significance level for the confidence intervals
        cov_type : str
            The covariance type used to compute the standard errors;
            one of 'robust' (the usual robust sandwich-type covariance
            estimate), 'naive' (ignores dependence), and 'bias
            reduced' (the Mancl/DeRouen estimate).

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

        See Also
        --------
        statsmodels.iolib.summary.Summary : class to hold summary results
        )Dep. Variable:N)zModel:NMethod:Generalizedr\   zEstimating EquationszFamily:zDependence structure:)zDate:NzCovariance type: c                 ,    g | ]}t          |          S rQ   r   r}   s     r<   rx   z&GEEResults.summary.<locals>.<listcomp>  s    222c!ff222r>   zNo. Observations:zNo. clusters:zMin. cluster size:zMax. cluster size:zMean cluster size:z%.1fzNum. iterations:z%drH   zScale:z%.3f)zTime:NzSkew:z%12.4fzCentered skew:z	Kurtosis:zCentered kurtosis:N zRegression Resultsr   )SummarygleftgrightynamexnametitleF)r  r  r  r[  )r   rh   r   rM   r   rZ  r   r   r'   minr   r"   r  r^  r  r   skewr   kurtosisr  
exog_namesendog_namesstatsmodels.iolib.summaryr  add_table_2colsadd_table_params)r7   r  r  r  r  top_leftNY	top_rightskew1kurt1skew2kurt2
diagn_leftdiagn_rightr  smrys                   r<   summaryzGEEResults.summary  s   D -$0012!2!<!E FG,j+5>?A#(4=*;<	 32dj1222)CGG95%DJ,?(@(@'AB*SWWI6*SWWI6*Vbgbkk-A,BC(4+.t/?/I+J+J,K +L M$*!4 56$		 
4:&&tz**
4.//t233E!1 23'(U*:);<>
 $h&6%78,x%/?.@A =J(1C7$%E
 =J)E=J*E 	655555wyyT)#(#( 	 	* 	* 	* 	d%u$) 	 	8 	8 	8T$/u#( 	 	4 	4 	4 r>   overallr  c                 x    | j         j        t          j        dt                     t          | |||||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.

            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.
        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
        -------
        effects : ndarray
            the marginal effect corresponding to the input options

        Notes
        -----
        When using after Poisson, returns the expected number of events
        per period, assuming that the model is loglinear.
        Nz#marginal effects ignore constraints)r   rj   r   r   r   
GEEMargins)r7   atmethodatexogdummycounts         r<   get_margeffzGEEResults.get_margeffF  sG    z : ,M?&( ( ( $VVUE BCCCr>   
   2   c                    ddl m} | j                            | j                  }| j                            | j        j                  }g g ct          ||          D ]\  }}t          j        |j	        d         d          }	||	d                  ||	d                  z  | j
        dz  z  }                    |           t          j        ||	d         ddf         ||	d         ddf         z
  dz                      d                    }
                    |
           t          j                  t          j                  ||                    |          \  }}n|                                }t          j        dk              }t          j        |                   }|z  t          j        |          r#t          j        dt+                    |          }t          j        |          t          j                  }t          j        fd|D                       }t          j        ||k              }||         }t          j        fd|D                       }t          j        fd|D                       }|                    ||d	d
d           |                    d           |                    d           |S )a6  
        Create a plot of the pairwise products of within-group
        residuals against the corresponding time differences.  This
        plot can be used to assess the possible form of an isotropic
        covariance structure.

        Parameters
        ----------
        ax : AxesSubplot
            An axes on which to draw the graph.  If None, new
            figure and axes objects are created
        xpoints : scalar or array_like
            If scalar, the number of points equally spaced points on
            the time difference axis used to define bins for
            calculating local means.  If an array, the specific points
            that define the bins.
        min_n : int
            The minimum sample size in a bin for the mean residual
            product to be included on the plot.
        r   utilsr    rm   Nc                 @    g | ]}t          j        |k              S rQ   )r"   r   )rt   ru   dgs     r<   rx   z8GEEResults.plot_isotropic_dependence.<locals>.<listcomp>  s%    888q26"'??888r>   c                 L    g | ] }t          j        |k                       !S rQ   r"   r  )rt   ru   r7  xres     r<   rx   z8GEEResults.plot_isotropic_dependence.<locals>.<listcomp>  +    ===A"'#bAg,//===r>   c                 L    g | ] }t          j        |k                       !S rQ   r9  )rt   ru   r7  xdts     r<   rx   z8GEEResults.plot_isotropic_dependence.<locals>.<listcomp>  r;  r>   -oranger  )colorlwzTime differencezProduct of scaled residuals)statsmodels.graphicsr5  r   r   r   rV   zipr"   tril_indicesr(   r  r2  r  r   r   create_mpl_ax
get_figureflatnonzeror  r   r  r   digitizer   rs   plot
set_xlabel
set_ylabel)r7   r  xpointsmin_ngutilsr   rV   retir   distsr  r   v0dguhistdgydgxr7  r=  r:  s                     @@@r<   plot_isotropic_dependencez$GEEResults.plot_isotropic_dependence  s   . 	988888
''
33z&&tz77 rS%&& 	 	FB!a00BBqER1Y&q8BJJrNNNGbAlR1qqq\9a?DDQGGHHEJJunS!!nS!!:**2..GC--//C ^C1H%%WSWr	
 ;w 	8k!SXXw77G[g&&immz8888C88899^DEM**"gj========>>j========>>
S#X!444
'(((
3444
r>   c                    | j         }ddl}|                    | j         j                  }|j        }d|_        g }g }	t          j        dd|          D ]}
|
|z  d|
z
  |z  z   }|                    |           |                    |          |_        ||j        _        |	                    | j
        | j        | j        | j        | j                  }|	                    |           ||_        |	S )a  
        Refits the GEE model using a sequence of values for the
        dependence parameters.

        Parameters
        ----------
        dep_params_first : array_like
            The first dep_params in the sequence
        dep_params_last : array_like
            The last dep_params in the sequence
        num_steps : int
            The number of dep_params in the sequence

        Returns
        -------
        results : array_like
            The GEEResults objects resulting from the fits.
        r   NFr    )rj  rc  ra  rb  rZ  )r   r   r   r   ri   r"   r  r2  rX  rO  rH   rc  ra  rb  rZ  )r7   dep_params_firstdep_params_last	num_stepsr   r   r   ri   rX  rq  r   dpr8  s                r<   sensitivity_paramszGEEResults.sensitivity_params  s   * 
]]4:#899
 %
 
Q9-- 	! 	!A_$A1A'AABb!!!#}}Z88E*,E'99$+"&)*.*;.2.C&*m	  5 5D
 NN4    %r>   )rT  FF)rT  )Nr  )NTNNr   )r  NN)r  NN)NNNr  r(  r  NFF)Nr1  r2  ) rM   rN   rO   _gee_results_docrP   r=   r   r   r  r  r  r  r  r  r  split_residr  split_centered_residr   r   r  r   r  r   r  r  r'  r0  rW  r]  params_sensitivityr  r  s   @r<   rg  rg    se       	)	* 
 >C'> '> '> '> '> '>R # # ^#8 8 8 8D 3 3 ^3- - -> 
 
 ^
   ^ 
 
 ^
   . K#N/X&*<b)AABB9==A#   CB X)-?,DDEE? ? ? FE? X'+=r*BBCCEI $B B B DCB&. &. &. &.P_ _ _ _B ?C',AD AD AD ADF :<(*D D D DL0 0 0f ,r>   rg  c                   L    e Zd ZddiZ ej        ej        j        e          ZdS )ri  r  rowsN)	rM   rN   rO   _attrswrapunion_dictslmRegressionResultsWrapper_wrap_attrsrQ   r>   r<   ri  ri  	  s;        &F #$"2#>#J#)+ +KKKr>   ri  c                        e Zd Zdeej        eeedz  z   Z		 	 	 d fd	Z
d Zd Z ee          	 	 	 d fd	            Z xZS )
OrdinalGEEz9    Ordinal Response Marginal Regression Model using GEE
r]   Nrb   c                 B   |t          j                    }n)t          |t           j                  st          d          |t	          j                    }|                     |||||          \  }}}}}t                                          |||||||||	|

  
         d S )Nz&ordinal GEE must use a Binomial family)	r   r  r   r&   r   OrdinalIndependencesetup_ordinalr   r=   r7   rT   r8   rU   rV   rh   r   rg   rW   rf   rj   r   r   s               r<   r=   zOrdinalGEE.__init__	  s     >&((FFfh&788 K !IJJJ$8::J,0,>,>4v-/ -/)tVT6 	fdW:	7 	7 	7 	7 	7r>   c                    |                                 | _        |                                 | _        |                                 | _        ||                                 | _        n(d| _        t          j        t          |                    }||                                 | _        n*d| _        t          j        t          |          df          }t          j	        |          }t          j	        |          }t          j	        |          }t          j	        |          }t          j	        |          }t          j
        |          | _        | j        dd         }t          |          }|t          |          z  }t          j        ||j        d         ft
          j                  }	t          j        |t
          j                  }
t          j        ||ft
          j                  }t          j        ||j                  }t          j        ||j        d         ft
          j                  }t          j        |t
          j                  }d}t          |||||          }|D ]i\  }}}}}t!          |          D ]Q\  }}||	|ddf<   t#          t          j        ||k                        |
|<   d|||f<   |||<   |||<   |||<   |dz  }Rjt          j        ||	fd          }	d |D             }t)          | j                  t*          j        u r |                    | j        j                   n;|                    d t3          d|j        d         dz             D                        t+          j        |	|	          }	t)          | j                  t*          j        u r t+          j        |
| j        j        
          }
|
|	|||fS )z
        Restructure ordinal data as binary indicators so that they can
        be analyzed using Generalized Estimating Equations.
        Nr    r   rz   )axisc                     g | ]}d |z  S )z	I(y>%.1f)rQ   )rt   r  s     r<   rx   z,OrdinalGEE.setup_ordinal.<locals>.<listcomp>g	  s    666a+/666r>   c                     g | ]}d |z  S zx%drQ   rt   ru   s     r<   rx   z,OrdinalGEE.setup_ordinal.<locals>.<listcomp>k	  s    JJJ519JJJr>   r   name)r   
endog_orig	exog_origgroups_origoffset_origr"   r  r'   	time_origrs   r   endog_valuesr(   r|   rq   rC  r   ro   r$   r   r   r   	DataFramer   r   r  r   rz  )r7   rT   r8   rU   rV   rW   
endog_cutsncutnrowsexog_out	endog_out
intercepts
groups_outtime_out
offset_outjrowzipperexog_rowendog_valuegroup_value
time_valueoffset_value	thresh_ixthreshxnamess                            r<   ro  zOrdinalGEE.setup_ordinal+	  s     **,,!;;==%{{}}D#DXc%jj))F!YY[[DNN!DN8SZZO,,Dz$
5!!F##z$F## Ie,,&qt,
:s5zz!8UDJqM2"$*. . .HU"*555	Xudm2:>>>
Xe6<888
8UDJqM2"$*. . .Xe2:666
T5&$77$	 	 X{K &/z%:%:  !	6$,qqq!"%bjv1E&F&F"G"G	$./
4?+#.
4 !+#/
4 	 >:x"8qAAA 76:6662<//MM$.01111MMJJeAtz!}q7H.I.IJJJKKK<&999   BI--	)$/2FGGGI(J*DDr>   c           	          t          | dd           }t          | j        | j        | j        | j        t          j                    | j        |          }|	                                }|j
        S NrX   )rV   rh   rW   rX   r   r[   rT   r8   rU   rV   r   r  rW   rO  rH   r7   rX   r   rP  s       r<   rQ  zOrdinalGEE._starting_paramst	  a    4T22DJ	4;8+<+>+>;; ; ; }r>   rR  rS  r    r   rT  c                   	 t                                          ||||||          		j        		fd	j        D             }t	          | 	j        	                                	j        z  	j        ||          }t          |          S )Nr  c                 2    i | ]}|t          |          S rQ   r   rt   ru   r8  s     r<   
<dictcomp>z"OrdinalGEE.fit.<locals>.<dictcomp>	  %    ===AAwtQ''===r>   rZ  r\  )	r   rO  _resultsrh  OrdinalGEEResultsrH   r  r  OrdinalGEEResultsWrapper)r7   rd  rc  rj  ra  rb  rZ  rp  ord_rsltr8  r   s            @r<   rO  zOrdinalGEE.fit|	  s    
 ww{{7D,')9$,  . . }=======$T4;%)__%6%6%C%)Z.6/7	9 9 9 (111r>   NNNrb   NNNrR  rS  Nr    r   rT  )rM   rN   rO   r  r   r   _gee_ordinal_family_doc_gee_ordinal_example_gee_nointerceptrP   r=   ro  rQ  r   r  rO  r  r  s   @r<   rl  rl  	  s         	E)@'>$8"24 4 	4	4  ?C9=+/7 7 7 7 7 7(GE GE GER   Xl6:-.2 2 2 2 2 2 2 2 2 2r>   rl  c                        e Zd Zdez   ZddZdS )r  z_This class summarizes the fit of a marginal regression modelfor an ordinal response using GEE.
Nc           
      <   ddl m} ||                    |          \  }}n|                                }|i g}| j        j                            d          }d t          | j        j                  D             }|D ][}|	                                D ]"}|| j        j        vrt          d|z            #g }	|D ]}
t          j        | j                  }d||
<   t          | j        j                  D ]%\  }}||v r
||v r||         ||<   ||         ||<   &ddt          j        t          j        || j                             z   z  }|	                    |           |	                    dd           |	                    d           t          j        |	          }	t          j        |	           }|                    | j        j        |d           ]|                    d	           |                    d
           |                    dd           |S )a^  
        Plot the fitted probabilities of endog in an ordinal model,
        for specified values of the predictors.

        Parameters
        ----------
        ax : AxesSubplot
            An axes on which to draw the graph.  If None, new
            figure and axes objects are created
        exog_values : array_like
            A list of dictionaries, with each dictionary mapping
            variable names to values at which the variable is held
            fixed.  The values P(endog=y | exog) are plotted for all
            possible values of y, at the given exog value.  Variables
            not included in a dictionary are held fixed at the mean
            value.

        Example:
        --------
        We have a model with covariates 'age' and 'sex', and wish to
        plot the probabilities P(endog=y | exog) for males (sex=0) and
        for females (sex=1), as separate paths on the plot.  Since
        'age' is not included below in the map, it is held fixed at
        its mean value.

        >>> ev = [{"sex": 1}, {"sex": 0}]
        >>> rslt.distribution_plot(exog_values=ev)
        r   r4  Nc                 B    g | ]\  }}|                     d           |S )zI()
startswith)rt   r  r   s      r<   rx   z7OrdinalGEEResults.plot_distribution.<locals>.<listcomp>	  s<     ( ( ($!QLL&&(A ( ( (r>   !%s is not a variable in the modelr  r    o-Response valueProbability)rB  r5  rE  rF  r   r8   r  r   r  keysr&   r"   
zeros_likerH   expr2   r2  insertrs   diffrI  r  rJ  rK  set_ylim)r7   r  exog_valuesrN  r  
exog_meansix_iceptevru   prjxpr  vnpprds                   r<   plot_distributionz#OrdinalGEEResults.plot_distribution	  sC   < 	988888:**2..GC--//C &KZ_))!,,
( ()DJ,A"B"B ( ( (   	8  	8BWWYY * *DJ111$%H'(&) * * * 2 B  ]4;//1&tz'<== . .EArH}} Rxx "21 !+11RVRVB%<%<$<===>		!IIaOOOIIaLLLBB72;;,CGGDJ+S$7777
&'''
m$$$
Aq
r>   r/  rM   rN   rO   r_  rP   r  rQ   r>   r<   r  r  	  s@        	/
	 
T T T T T Tr>   r  c           	         | j         }|j         }t          j                            |d          \  }}}|j        }t          j                            |          \  }}	|t          j        |t          j        |j        |                    z
  }t          j                            |d          \  }
}}	|
dd|dk    f         }
t          j        t          j        |          dk              }t          j        |dd|f         t          j        |dd|f         j        |          ||df         z            }t          j	        t          j        |t          j        ||          z
                      }|dk    rdS t          j        |dd|f         t          j        |dd|f         j        |
          ||df         z            }||fS )ac  
    Return transformation matrices for design matrices.

    Parameters
    ----------
    par : instance
        The parent model
    sub : instance
        The sub-model

    Returns
    -------
    qm : array_like
        Matrix mapping the design matrix of the parent to the design matrix
        for the sub-model.
    qc : array_like
        Matrix mapping the design matrix of the parent to the orthogonal
        complement of the columnspace of the submodel in the columnspace
        of the parent.

    Notes
    -----
    Returns None, None if the provided submodel is not actually a submodel.
    r   Ng-q=g:0yE>r/  )
r8   r"   r+   r,   r-   qrr2   rG  rs  r   )parsubx1x2r  svtr  ar   x2csbr   r   er   s                   r<   r   r   	  s   4 
B	By}}R##HAq"
A 9<<DAq	BF1bfQS!nn%%%Aq!$$JCQ
aaaem
C 
q		E)	*	*B	!!!R%"&111b5R001RX;>	?	?B
rvb26"b>>)**++A4xxz 
!!!R%"&111b5S11Ab$hK?	@	@Br6Mr>   c                       e Zd ZdS )r  NrM   rN   rO   rQ   r>   r<   r  r  &
          Dr>   r  c                        e Zd Zdeej        eeedz  z   Z		 	 	 d fd	Z
d Zd Zd Zdd	Z ee          	 	 	 d fd	            Z xZS )
NominalGEEz:    Nominal Response Marginal Regression Model using GEE.
r]   Nrb   c                     |                      |||||          \  }}}}}|t          | j        dz             }|t          j                    }t                                          |||||||||	|

  
         d S Nr    )setup_nominalr  r  r   NominalIndependencer   r=   rp  s               r<   r=   zNominalGEE.__init__4
  s     -1,>,>4v-/ -/)tVT6 >!$)a-00F$8::J4vz7Hj	* 	* 	* 	* 	*r>   c           	          t          | dd           }t          | j        | j        | j        | j        t          j                    | j        |          }|	                                }|j
        S r  r  r  s       r<   rQ  zNominalGEE._starting_paramsE
  r  r>   c                    |                                 | _        |                                 | _        |                                 | _        ||                                 | _        n(d| _        t          j        t          |                    }||                                 | _        n*d| _        t          j        t          |          df          }t          j	        |          }t          j	        |          }t          j	        |          }t          j	        |          }t          j	        |          }t          j
        |          | _        | j        dd         }t          |          }|| _        t          |          |j        d         z  }t          |          |j        d         z  }	t          j        ||	ft
          j                  }
t          j        |t
          j                  }t          j        |t
          j                  }t          j        ||j        d         ft
          j                  }t          j        |t
          j                  }d}t          |||||          }|D ]\  }}}}}t!          |          D ]}\  }}t          j        t          |          t
          j                  }d||<   t          j        ||          |
|ddf<   t%          ||k              ||<   |||<   |||<   |||<   |dz  }~t'          | j        t(          j                  r| j        j        }n(d t/          d|j        d         dz             D             }g }|D ]#|                    fd|D                        $t)          j        |
|          }
t)          j        |
|          }
t'          | j        t(          j                  r t)          j        || j        j        	          }||
|||fS )
z
        Restructure nominal data as binary indicators so that they can
        be analyzed using Generalized Estimating Equations.
        Nr    r   rr  rz   c                     g | ]}d |z  S rv  rQ   rw  s     r<   rx   z,NominalGEE.setup_nominal.<locals>.<listcomp>
  s    HHHqHHHr>   c                 "    g | ]}| d ddS )[z.1f]rQ   )rt   r  trs     r<   rx   z,NominalGEE.setup_nominal.<locals>.<listcomp>
  s-    ???a++"++++???r>   rx  ry  )r   r{  r|  r}  r~  r"   r  r'   r  rs   r   r  r  r(   r|   rC  r   kronro   r   r   r  r   r  r   r   rz  )r7   rT   r8   rU   rV   rW   r  r  r  ncolsr  r  r  r  r  r  r  r  r  r  r  r  r  r  r  	xnames_inr  r  s                              @r<   r  zNominalGEE.setup_nominalM
  s     **,,!;;==%{{}}D#DXc%jj))F!YY[[DNN!DN8SZZO,,Dz$
5!!F##z$F## Ie,,&qt,
:	J$*Q-/J$*Q-/8UEN"*===HU"*555	Xe2:666
8UDJqM2"$*. . .Xe2:666
T5&$77$	 	 X{K &/z%:%: 	 	!	6HS__BJ??? )$&GAx$8$8qqq!#&{f'<#=#=	$#.
4 !+#/
4 		 dnbl33 	I.IIHHE!TZ]Q5F,G,GHHHI 	A 	ABMM????Y???@@@@<&999<&999 dory11 	H	)$/2FGGGI(J*DDr>   c                    t          j        |          }t          j        |t          |          | j        z  | j        f          }d|                    d          z   }t          j        |t          j        | j        t           j                            }||z  }|dddf         |z  }|dddf         |z  }||dddf         |z  |dddf         z  z  }|S )a   
        Derivative of the expected endog with respect to the parameters.

        Parameters
        ----------
        exog : array_like
           The exogeneous data at which the derivative is computed,
           number of rows must be a multiple of `ncut`.
        lin_pred : array_like
           The values of the linear predictor, length must be multiple
           of `ncut`.

        Returns
        -------
        The derivative of the expected endog with respect to the
        parameters.
        r    rz   N	r"   r  reshaper'   r  r   r  onesr|   )	r7   r8   r%  r  expval_mdenommprobr'  ddenoms	            r<   r(  zNominalGEE.mean_deriv
  s    & !! :fs6{{di'?'+y'2 3 3 HLLOO#rwty
CCCDD  QQQW~$ 44'aaag'%4.88r>   c                    |t          j        dt                     t          j        ||          }t          j        |          }t          j        |t          |          | j        z  | j        f          }d|	                    d          z   }t          j
        |t          j        | j        t          j                            }t          j        t          j        |j        d                   |          }g }	t          | j                  D ]{}
t          j        | j        t          j                  }d||
<   |	                    t          j
        |t          j        t          |          | j        z                                 |t          j        |	          }	t          j
        t          j        |j        d         | j        z  df          |	          }	||	z  }|dddf         |z  |dddf         z  }t          j
        |t          j        | j        df                    }t          j
        |t          j        d| j        f                    }||dddf         ||z  z  |dddf         dz  z  z  }|S )a  
        Derivative of the expected endog with respect to exog for the
        multinomial model, used in analyzing marginal effects.

        Parameters
        ----------
        exog : array_like
           The exogeneous data at which the derivative is computed,
           number of rows must be a multiple of `ncut`.
        lpr : array_like
           The linear predictor values, length must be multiple of
           `ncut`.

        Returns
        -------
        The value of the derivative of the expected endog with respect
        to exog.

        Notes
        -----
        offset_exposure must be set at None for the multinomial family.
        Nz2Offset/exposure ignored for the multinomial familyr    rz   r   rm   )r   r   r   r"   r2   r  r  r'   r  r   r  r  r|   r*  r(   r  r  r2  r   )r7   r8   rH   r+  r4  r  r  r  bmat0qmatr  eer3  r'  	expval_mbs                  r<   r,  zNominalGEE.mean_deriv_exog
  s-   0 &MN&( ( ( fT6"":fs6{{di'?'+y'2 3 3 HLLOO#rwty
CCCDDA//88 ty!! 	H 	HA$)2:666BBqEKKBGCKK49,D$E$EFFGGGGx~~wrw
1 :A>??FFt|aaag%aaag6GHbgty!n&=&=>>	GIrw49~'>'>??	qqq$w4)#34uQQQW~7JJJr>   rR  rS  r    r   rT  c                 T  	 t                                          ||||||          		t          j        dt                     d S 	j        		fd	j        D             }t          | 	j        		                                	j
        z  	j
        ||          }t          |          S )Nr  zGEE updates did not convergec                 2    i | ]}|t          |          S rQ   r  r  s     r<   r  z"NominalGEE.fit.<locals>.<dictcomp>  r  r>   r  )r   rO  r   r   r   r  rh  NominalGEEResultsrH   r  r  NominalGEEResultsWrapper)r7   rd  rc  rj  ra  rb  rZ  rp  nom_rsltr8  r   s            @r<   rO  zNominalGEE.fit
  s    
 ww{{7D,')9$,  . . <M8,. . .4}=======$T4;%)__%6%6%C%)Z.6/7	9 9 9 (111r>   r  r   r  )rM   rN   rO   r  r   r   _gee_nominal_family_doc_gee_nominal_exampler  rP   r=   rQ  r  r(  r,  r   r  rO  r  r  s   @r<   r  r  +
  s        	F)@'>$8"24 4 	4	4  ?C9=+/* * * * * *"  IE IE IEV) ) )V8 8 8 8t Xl6:-.2 2 2 2 2 2 2 2 2 2r>   r  c                        e Zd Zdez   ZddZdS )r  z^This class summarizes the fit of a marginal regression modelfor a nominal response using GEE.
Nc                    ddl m} ||                    |          \  }}n|                                }|i g}| j        j        j        j        }| j        j        j        }t          | j        j
        j        d         |z            }| j        j
                            d          d|         }| j        j        d|         }	d |	D             }	t          j        | j        |t#          | j                  |z  f          }
|D ]}|                                }|                                D ]8}||	vrt)          d|z            |	                    |          }||         ||<   9t          j        |
|          } ||          }t          j        |d|                                z
  f         }|                    | j        j        |d           |                    d           |                    d	           |                    | j        j                   |                    | j        j                   |                    dd           |S )
a^  
        Plot the fitted probabilities of endog in an nominal model,
        for specified values of the predictors.

        Parameters
        ----------
        ax : AxesSubplot
            An axes on which to draw the graph.  If None, new
            figure and axes objects are created
        exog_values : array_like
            A list of dictionaries, with each dictionary mapping
            variable names to values at which the variable is held
            fixed.  The values P(endog=y | exog) are plotted for all
            possible values of y, at the given exog value.  Variables
            not included in a dictionary are held fixed at the mean
            value.

        Example:
        --------
        We have a model with covariates 'age' and 'sex', and wish to
        plot the probabilities P(endog=y | exog) for males (sex=0) and
        for females (sex=1), as separate paths on the plot.  Since
        'age' is not included below in the map, it is held fixed at
        its mean value.

        >>> ex = [{"sex": 1}, {"sex": 0}]
        >>> rslt.distribution_plot(exog_values=ex)
        r   r4  Nr    c                 D    g | ]}|                     d           d         S )r  r   )splitr   s     r<   rx   z7NominalGEEResults.plot_distribution.<locals>.<listcomp>P  s&    :::!aggcll1o:::r>   r  r  r  r  ) rB  r5  rE  rF  r   rh   r   r=  r  ro   r8   r(   r  r  r"   r  rH   r'   r   r  r&   rp   r2   r  r   rI  r  rJ  rK  
set_xticksset_xticklabelsr  )r7   r  r  rN  r  r   r  ru   r  r  rH   r  r8   r   r4  r  s                   r<   r  z#NominalGEEResults.plot_distribution   sG   < 	988888:**2..GC--//C &Kz %-z %
%a(4/00Z_))!,,QqS1
Z*1Q3/
::z:::
DK!3t{#3#3t#;<> >  	7 	7B??$$DWWYY ! !J&&$%H'(&) * * *  %%a((a5R&&&CcBr1rvvxx<'(BGGDJ+R6666
&'''
m$$$
dj-...
4:2333
Aq
r>   r/  r  rQ   r>   r<   r  r    s@        	.
	 
M M M M M Mr>   r  c                       e Zd ZdS )r  Nr  rQ   r>   r<   r  r  p  r  r>   r  c                       e Zd ZdZd Zd ZdS )_MultinomialLogitac  
    The multinomial logit transform, only for use with GEE.

    Notes
    -----
    The data are assumed coded as binary indicators, where each
    observed multinomial value y is coded as I(y == S[0]), ..., I(y ==
    S[-1]), where S is the set of possible response labels, excluding
    the largest one.  Thererefore functions in this class should only
    be called using vector argument whose length is a multiple of |S|
    = ncut, which is an argument to be provided when initializing the
    class.

    call and derivative use a private method _clean to trim p by 1e-10
    so that p is in (0, 1)
    c                     || _         d S r   )r  )r7   r  s     r<   r=   z_MultinomialLogit.__init__  s    			r>   c                 6   t          j        |          }dt          j        |t          |          | j        z  | j        f                              d          z   }t          j        |t          j        | j        t           j                            }||z  }|S )a  
        Inverse of the multinomial logit transform, which gives the
        expected values of the data as a function of the linear
        predictors.

        Parameters
        ----------
        lpr : array_like (length must be divisible by `ncut`)
            The linear predictors

        Returns
        -------
        prob : ndarray
            Probabilities, or expected values
        r    rz   r  )r7   r4  r  r  probs        r<   r=  z_MultinomialLogit.inverse  s    " BJvFty(@(,	(3 4 447CFF;rwty
CCCDD~r>   N)rM   rN   rO   rP   r=   r=  rQ   r>   r<   r  r  u  s<         "      r>   r  c                   :    e Zd ZdZegZej        ZegZ	ddZ
d ZdS )r  zw
    Pseudo-link function for fitting nominal multinomial models with
    GEE.  Not for use outside the GEE class.
    Tc                 >    || _         |                     |           dS )z
        Parameters
        ----------
        nlevels : int
            The number of distinct categories for the multinomial
            distribution.
        N)_check_linkr   )r7   nlevels
check_links      r<   r=   z_Multinomial.__init__  s$     &     r>   c                 L    |dz
  | _         t          | j                   | _        d S r  )r  r  r   )r7   r  s     r<   r   z_Multinomial.initialize  s"    aK	%di00			r>   N)T)rM   rN   rO   rP   r  linksvarfuncsbinaryr  r   r=   r   rQ   r>   r<   r  r    sZ         
 !EH#&J	! 	! 	! 	!1 1 1 1 1r>   r  c                   r    e Zd ZdZi fdZd Zed             ZddZed             Z	ddZ
dd	Z	 	 ddZdS )r*  a  
    Estimated marginal effects for a regression model fit with GEE.

    Parameters
    ----------
    results : GEEResults instance
        The results instance of a fitted discrete choice model
    args : tuple
        Args are passed to `get_margeff`. This is the same as
        results.get_margeff. See there for more information.
    kwargs : dict
        Keyword args are passed to `get_margeff`. This is the same as
        results.get_margeff. See there for more information.
    c                 <    i | _         || _         | j        |i | d S r   )_cacherq  r0  )r7   rq  r   r   s       r<   r=   zGEEMargins.__init__  s.    $)&)))))r>   c                     i | _         d S r   )r  r@   s    r<   _resetzGEEMargins._reset  s    r>   c                 H    t          | j                   | j        | j        z  S r   )r   margeff_optionsr  
margeff_ser@   s    r<   tvalueszGEEMargins.tvalues  s"    -...|do--r>   r  c           	         t          | j                   ddlm} t          | j        d                  dddddg}| j        j        j                            d          dk    | j        j        j	        }fd	t          |          D             }t          j        | j        | j        | j        | j        |                     |          f          } ||||
          S )aa  
        Returns a DataFrame summarizing the marginal effects.

        Parameters
        ----------
        alpha : float
            Number between 0 and 1. The confidence intervals have the
            probability 1-alpha.

        Returns
        -------
        frame : DataFrames
            A DataFrame summarizing the marginal effects.
        r   )r  r,  z	Std. Err.zzPr(>|z|)zConf. Int. LowzCont. Int. Hi.c                 *    g | ]\  }}|         |S rQ   rQ   )rt   r  rz  inds      r<   rx   z,GEEMargins.summary_frame.<locals>.<listcomp>  s&    IIIga#a&ITIIIr>   )r   rp   )r   r  pandasr  r   rq  r   r8   varr  r   r"   column_stackr  r  r  pvaluesr  )r7   r  r  namesr  	var_namestabler  s          @r<   summary_framezGEEMargins.summary_frame  s     	-...$$$$$$!$"6x"@Ac:!#35 l %))!,,1\'2
IIII:)>)>III	t!%t}}U/C/C!E F FyY????r>   c                     t          | j                   t          j                            t          j        | j                            dz  S )Nrm   )r   r  r   r   sfr"   rs  r  r@   s    r<   r  zGEEMargins.pvalues  s8    -...z}}RVDL1122Q66r>   c                     t          | j                   | j        }t          j                            d|dz  z
            }| j        ||z  z
  }| j        ||z  z   }t          j        t          ||                    S )a  
        Returns the confidence intervals of the marginal effects

        Parameters
        ----------
        alpha : float
            Number between 0 and 1. The confidence intervals have the
            probability 1-alpha.

        Returns
        -------
        conf_int : ndarray
            An array with lower, upper confidence intervals for the marginal
            effects.
        r    rm   )
r   r  r  r   r   r  r  r"   rs   r   )r7   r  me_ser  r  r  s         r<   r  zGEEMargins.conf_int  sq      	-...JNN1uqy=))q5y(q5y(z$ue,,---r>   c           
         t          | j                   | j        }|j        }|j        j        dz   }| j        d         }d|j        gfd|gfd| j        d         gfg}ddlm}m	}m
}	 |j        d	d	         }
 |            }|j        j        }||
                    |           t          t!          |d
d                    }|dk    r!|                    |j        d	d          \  }}n
|j        }|g}|                    | |g ||
|           g }|                     |          }| j        }| j        }| j        }| j        }|dk    rt1          |          D ]}||d	d	|f         |d	d	|f         |d	d	|f         |d	d	|f         |d	d	d	d	|f         f} ||||         |
|dd          }||         |_        dt4          |         ddddd|dz  z
  z  g}|                    d|           |                    |            |	|d          }nK||||||f} ||||
|dd          }dt4          |         ddddd|dz  z
  z  g}|                    d|           |j                            |           |S )aF  
        Returns a summary table for marginal effects

        Parameters
        ----------
        alpha : float
            Number between 0 and 1. The confidence intervals have the
            probability 1-alpha.

        Returns
        -------
        Summary : SummaryTable
            A SummaryTable instance
        z Marginal Effectsr,  r	  r
  zAt:r+  r   )r  summary_paramstable_extendNJr    T)r   r  F)r  r  r  r[  skip_headerr\   zstd errr  zP>|z|z[%3.1f%% Conf. Int.]r  )keep_headers)r   r  rq  r   r   rM   r  r  r  r&  r'  r  r   	const_idxr  ro   r   _get_endog_namer  r  r  r  r  r  r  r  r   insert_header_rowr2  tables)r7   r  rq  r   r  r,  r  r  r&  r'  r  r&  r+  r(  r  
yname_listr  r  r  r  r  r  eqrestuptbleheaders                             r<   r'  zGEEMargins.summary  sS    	-...,(+>>%h/%(9':;)T1$789=	= 	= 	= 	= 	= 	= 	= 	= 	= 	=%aaa(
wyyJ(	 NN9%%%sA&&''q55 ' 7 78I8<$ !8 !H !HE:: %EJT"#(
% 	 	I 	I 	I =='',_
,,q55Ahh # #!7111b5>:aaae3D!!!!R%.'!!!R%.(111aaa8:LN%~fJrN,6e,1268 8 8 (^
.v6	3!0C%#+4EFH &&q&111T"""" LT:::EEw
GWhOF"N6j).eO O OE*62Is5us{9JKMF##Av...5!!!r>   r(  r  NFc                 ~   |                                   |                                }|                                }t          ||           t          ||          | _        | j        }|j        }|j        }|j        	                                }	|	
                    d          dk    }
|j        j        }|r$t          ||           t          |	|          \  }}nd }|r$t          ||           t          |	|          \  }}nd }t!          |	|||
          }	|                    ||	|||          }t%          ||          }|dk    r|d d |
f         | _        d S t)          |||	|                                ||j        |||d
  
        \  }}||
         d d |
f         | _        ||
         | _        ||
         | _        d S )N)r,  r+  r   r   r    )r  r  r   r   r  rq  r   rH   r8   r   r  r   r+  r   r   r   r   r  r   r  r   r  margeff_covr  )r7   r+  r,  r-  r.  r/  rq  r   rH   r8   effects_idxr+  r  r  effectsr5  r  s                    r<   r0  zGEEMargins.get_margefff  s    	 XXZZB'''#6b999,z  hhqkkQ&J(	 	 V,,,/i@@IuuI 	 V,,,/i@@IuuI !r6;?? ((v)2I? ?gr**;;"111k>2DLLL ':vtW%7%7%9%92&	9' '#K  +;7;GD(5DO";/DLLLr>   )r  r^  )rM   rN   rO   rP   r=   r  r   r  r   r  r  r'  r0  rQ   r>   r<   r*  r*    s          .0 * * * *
   . . ^.@ @ @ @6 7 7 ^7. . . ..P P P Pd ?C',10 10 10 10 10 10r>   r*  )VrP   statsmodels.compat.pythonr   statsmodels.compat.pandasr   numpyr"   scipyr   r  r   r   collectionsr   statsmodels.tools.decoratorsr   statsmodels.base.modelr   r   #statsmodels.regression.linear_model
regressionlinear_modelrh  statsmodels.base.wrapperwrapperrf  statsmodels.genmodr   +statsmodels.genmod.generalized_linear_modelr	   r
   r   r   $statsmodels.genmod.families.varfuncsgenmodr
  !statsmodels.genmod.families.linksr   statsmodels.tools.sm_exceptionsr   r   r   r   r   )statsmodels.graphics._regressionplots_docr   r   r   r  r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r_  r  r  r  rY   r[   rg  ri  ri  populate_wrapperrl  r  r   r  r  r  r  r  r   r  r*  rQ   r>   r<   <module>rL     sj   0 + * * * * * . . . . . .                # # # # # # 7 7 7 7 7 7 % % % % % % % % % 0 0 0 0 0 0 0 0 0 ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' G G G G G G G G 8 8 8 8 8 8 7 7 7 7 7 7 7 7 7 7 7 7 2 2 2 2 2 2; ; ; ; ; ; ; ; ; ; ; ;          ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( (g< g< g< g< g< g< g< g<T[z D: G 
8t) VB & 8M M M&    #   D(^, ^, ^, ^, ^, ^, ^, ^,B+ + + + +3 + + +  ' 4 4 4C2 C2 C2 C2 C2 C2 C2 C2L[ [ [ [ [
 [ [ [|1 1 1h	 	 	 	 	0 	 	 	  .0A B B Bk2 k2 k2 k2 k2 k2 k2 k2\T T T T T
 T T Tn	 	 	 	 	0 	 	 	  .0A B B B. . . . . . . .b1 1 1 1 18? 1 1 14W0 W0 W0 W0 W0 W0 W0 W0 W0 W0r>   