
    M/Phh                         d dl mZ d dlZd dlmZ d dlmZ d Zd Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z edddd          Z G d d          Z G d d          ZdS )    )lzipN)norm)cache_readonlyc                 ^    | dvrt          d| z            |dvrt          d|z            dS )z*
    Checks valid options for margeff
    )overallmeanmedianzeroallz%s not a valid option for `at`.dydxeyexdyexeydxz!method is not understood.  Got %sN
ValueErroratmethods     e/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/discrete/discrete_margins.py_check_margeff_argsr      sL     
999:R?@@@222<vEFFF 32    c                 ^    |dv rt          d|z            | dv rt          d| z            dS )zS
    Checks the arguments for margeff if the exogenous variables are discrete.
    )r   r   z%%s not allowed for discrete variables)r	   r
   Nr   r   s     r   _check_discrete_argsr      sK       @6IJJJ	@2EFFF  r   c                     |                      d          dk    }t          j        |           rt          j        |           d         }nd}||fS )z
    Returns a boolean array of non-constant column indices in exog and
    an scalar array of where the constant is or None
    r   N)varnpanywhere)exogeffects_idx	const_idxs      r   _get_const_indexr#      sT    
 ((1++"K	v{l Hk\**1-				!!r   c                    t          j        |           } | j        dk    r7t          j        | j        d                                       t                    }t          j        | d          dk    }t          j        | d          dk    }t          j	        | dz  dk    d          }||z  |z  }| j        dk    rt          j        |g          }t          j
        |          d         S )ac  
    Given an array X, returns the column indices for the dummy variables.

    Parameters
    ----------
    X : array_like
        A 1d or 2d array of numbers

    Examples
    --------
    >>> X = np.random.randint(0, 2, size=(15,5)).astype(float)
    >>> X[:,1:3] = np.random.randn(15,2)
    >>> ind = _isdummy(X)
    >>> ind
    array([0, 3, 4])
       r   axis      ?)r   asarrayndimzerosshapeastypeboolmaxminr   r   )Xindr/   r0   	remainders        r   _isdummyr4   *   s    " 	
1Avzzhqwqz""))$//6!!!C6!!!Cq2v{+++I
)i
Cv{{j#8C==r   c                 J    t          |           }d}|j        dk    rd}d }||fS NTr   F)r4   size)r1   r"   	dummy_inddummys       r   _get_dummy_indexr:   F   4    IE~	er   c                    t          j        |           } t          j        t          j        t          j        | dz  dk    d          |                     d          dk              t          j        | dk    d                    }t          |           }t          j        |          d                                         }|D ]}|                    |           t          j	        |          S )a`  
    Given an array X, returns the column indices for count variables.

    Parameters
    ----------
    X : array_like
        A 1d or 2d array of numbers

    Examples
    --------
    >>> X = np.random.randint(0, 10, size=(15,5)).astype(float)
    >>> X[:,1:3] = np.random.randn(15,2)
    >>> ind = _iscount(X)
    >>> ind
    array([0, 3, 4])
    r(   r   r&   )
r   r)   logical_andr   r   r4   r   tolistremovearray)r1   r3   r9   idxs       r   _iscountrB   O   s    " 	
1Ar~bfQVq[.K.K.K uuQxx1} .  ./1va1f1/E/E/EG GIQKKE##A&--//I  8Ir   c                 J    t          |           }d}|j        dk    rd}d }||fS r6   )rB   r7   )r1   r"   	count_indcounts       r   _get_count_indexrF   i   r;   r   c                 P   |t          |t                    r|D ]}||         | d d |f<   nmt          |t          j                  rS|j        dk    rt          |          }n|j        d         }	 || j        d         k    sJ n#  t          d          xY w|} |dk    r(t          j        | 	                    d                    } n^|dk    r)t          j        t          j
        | d                    } n/|dk    r)t          j        d| j        d         f          } d| d| f<   | S )Nr%   z9atexog does not have the same number of variables as exogr   r   r	   r&   r
   )
isinstancedictr   ndarrayr*   lenr,   r   
atleast_2dr   r	   r+   )r    r   atexogr2   keyk_varss         r   _get_margeff_exogrP   r   sH   fd## 	 * *$SkQQQsU*
++ 
	{aVa0A.....0  "/ 0 0 0D 
V||}TYYq\\**	x}RYt!44455	vx4:a=)**QtVKs   0B Bc                 V   |D ]}|                                 }|dd|fxx         dz  cc<   |                    ||          }|dd|fxx         dz  cc<   |                    ||          }	d|v r(t          j        |          }t          j        |	          }	|	|z
  dz  | dd|f<   | S )z
    If there's a count variable, the predicted difference is taken by
    subtracting one and adding one to exog then averaging the difference
    Nr%      eycopypredictr   log)
effectsr    rD   r   modelparamsiexog0effect0effect1s
             r   _get_count_effectsr_      s      0 0		aaadq--..aaadq--.. 6>>fWooGfWooG!G+Q.1Nr   c                 $   |D ]}|                                 }d|dd|f<   |                    ||          }d|dd|f<   |                    ||          }	d|v r(t          j        |          }t          j        |	          }	|	|z
  | dd|f<   | S )zW
    If there's a dummy variable, the predicted difference is taken at
    0 and 1
    r   Nr%   rS   rT   )
rX   r    r8   r   rY   rZ   r[   r\   r]   r^   s
             r   _get_dummy_effectsra      s      
, 
,		aaac
--..aaac
--..6>>fWooGfWooG 7*1Nr   c                 h    |dk    r| } n(|dk    r|                      d          } n| dd d f         } | S )Nr   r   r   )r   )rX   r   s     r   _effects_atrc      sB    	U{{	y,,q//!AAA#,Nr   c                    |D ]}|                                 }|                                 }	d|dd|f<   d|	dd|f<   |                     |||          }
|                     ||	|          }||
z
  }|j        dk    r|                    d          }|dk    r |j        d         |dz
  z  }|||d|ddf<   |||dt          |          f<   |S )aN  
    Returns the Jacobian for discrete regressors for use in margeff_cov_params.

    For discrete regressors the marginal effect is

    \Delta F = F(XB) | d = 1 - F(XB) | d = 0

    The row of the Jacobian for this variable is given by

    f(XB)*X | d = 1 - f(XB)*X | d = 0

    Where F is the default prediction of the model.
    r   Nr%   rR   rU   _derivative_predictr*   r   r,   rK   )rY   cov_marginsrZ   r    r8   r   Jr[   r\   exog1dfdb0dfdb1dfdbKs                 r   _margeff_cov_params_dummyrn      s      . .				aaac
aaac
))&%@@))&%@@9>>99Q<<Dq55
1!A#&A#'K1aaa   *.K:CII:&&r   c                    |D ]}|                                 }|dd|fxx         dz  cc<   |                     |||          }	|dd|fxx         dz  cc<   |                     |||          }
|
|	z
  }|j        dk    r|                    d          dz  }|dk    r |j        d         |dz
  z  }|||d|ddf<   |||dt          |          f<   |S )aY  
    Returns the Jacobian for discrete regressors for use in margeff_cov_params.

    For discrete regressors the marginal effect is

    \Delta F = F(XB) | d += 1 - F(XB) | d -= 1

    The row of the Jacobian for this variable is given by

    (f(XB)*X | d += 1 - f(XB)*X | d -= 1) / 2

    where F is the default prediction for the model.
    Nr%   rR   r   re   )rY   rg   rZ   r    rD   r   rh   r[   r\   rj   rk   rl   rm   s                r   _margeff_cov_params_countrp      s     . .		aaac


a


))&%@@aaac


a


))&%@@9>>99Q<<!#Dq55
11%A#'K1aaa   *.K:CII:&&r   c
           	         t          |          rddlm}
 |                    d          }	  |
||||f          }n&# t          $ r ddlm}  |||||f          }Y nw xY w|dk    rt          j        |d          }n|                                }|t          | ||||||	          }|t          | ||||||	          }n|}t          j        t          j        ||          |j                  S )	a=  
    Computes the variance-covariance of marginal effects by the delta method.

    Parameters
    ----------
    model : model instance
        The model that returned the fitted results. Its pdf method is used
        for computing the Jacobian of discrete variables in dummy_ind and
        count_ind
    params : array_like
        estimated model parameters
    exog : array_like
        exogenous variables at which to calculate the derivative
    cov_params : array_like
        The variance-covariance of the parameters
    at : str
       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.

        Only overall has any effect here.you

    derivative : function or array_like
        If a function, it returns the marginal effects of the model with
        respect to the exogenous variables evaluated at exog. Expected to be
        called derivative(params, exog). This will be numerically
        differentiated. Otherwise, it can be the Jacobian of the marginal
        effects with respect to the parameters.
    dummy_ind : array_like
        Indices of the columns of exog that contain dummy variables
    count_ind : array_like
        Indices of the columns of exog that contain count variables

    Notes
    -----
    For continuous regressors, the variance-covariance is given by

    Asy. Var[MargEff] = [d margeff / d params] V [d margeff / d params]'

    where V is the parameter variance-covariance.

    The outer Jacobians are computed via numerical differentiation if
    derivative is a function.
    r   )approx_fprime_csF)args)approx_fprimer   r%   r&   )callablestatsmodels.tools.numdiffrr   ravel	TypeErrorru   r   r   squeezern   rp   dotT)rY   rZ   r    
cov_paramsr   
derivativer8   rD   r   rh   rr   jacobian_matru   s                r   margeff_cov_paramsr      sf   f 
 ">>>>>>c""	@++FJ26v@ @ @LL 	@ 	@ 	@??????(=26v@ @ @LLL	@ ??7<a888LL'//11L 4UL &iD DL 4UL &iD DL " 6"&z22LNCCCs   =  A A c
                     t          | |||||||||	
  
        }
|
t          j        t          j        |
                    fS )z
    See margeff_cov_params.

    Same function but returns both the covariance of the marginal effects
    and their standard errors.
    )r   r   sqrtdiag)rY   rZ   r    r}   r   r~   r8   rD   r   rh   cov_mes              r   margeff_cov_with_ser   L  sJ      vtZ.8).7D DF 27276??++++r   c                      t           NNotImplementedError r   r   margeffr   Z  s    
r   c                 <    | d         dk    rt          d          d S )Nr   r   znOnly margeff are available when `at` is 'all'. Please input specific points if you would like to do inference.r   )r   s    r   _check_at_is_allr   _  s0    d|u 1 2 2 	2 r   zdy/dxzd(lny)/d(lnx)z	dy/d(lnx)z	d(lny)/dxr   c                       e Zd ZdZ	 	 ddZd Zd Zed             Zed             Z	ed	             Z
d
 Zed             ZddZddZdS )Marginsz
    Mostly a do nothing class. Lays out the methods expected of a sub-class.

    This is just a sketch of what we may want out of a general margins class.
    I (SS) need to look at details of other models.
    Nr   c                 Z    i | _         || _        || _        |                     |           d S r   )_cacheresultsdistget_margeff)selfr   r   r~   r   margeff_argss         r   __init__zMargins.__init__r  s1    	&&&&&r   c                     i | _         d S r   r   r   s    r   _resetzMargins._resety      r   c                 L    |                                    | j        | | _        d S r   )r   r   r   )r   rt   kwargss      r   r   zMargins.get_margeff|  s$    't'.r   c                     t           r   r   r   s    r   tvalueszMargins.tvalues      !!r   c                     t           r   r   r   s    r   rg   zMargins.cov_margins  r   r   c                     t           r   r   r   s    r   
margins_sezMargins.margins_se  r   r   c                     t           r   r   r   s    r   summary_framezMargins.summary_frame      !!r   c                     t           r   r   r   s    r   pvalueszMargins.pvalues  r   r   皙?c                     t           r   r   r   alphas     r   conf_intzMargins.conf_int  r   r   c                     t           r   r   r   s     r   summaryzMargins.summary  r   r   )Nr   r   )__name__
__module____qualname____doc__r   r   r   r   r   rg   r   r   r   r   r   r   r   r   r   r   k  s          ?C$&' ' ' '  / / / " " ^" " " ^" " " ^"" " " " " ^"" " " "" " " " " "r   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 )DiscreteMarginsa  Get marginal effects of a Discrete Choice model.

    Parameters
    ----------
    results : DiscreteResults 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   )r   r   r   )r   r   rt   r   s       r   r   zDiscreteMargins.__init__  s.    $)&)))))r   c                     i | _         d S r   r   r   s    r   r   zDiscreteMargins._reset  r   r   c                 H    t          | j                   | j        | j        z  S r   )r   margeff_optionsr   
margeff_ser   s    r   r   zDiscreteMargins.tvalues  s"    -...|do--r   r   c                 L   t          | j                   | j        }| j        j        }ddlm}m} t          | j        d                  dddddg}| j        j        j        	                    d          dk    | j        j        j
        }t          |d	d          }|dk    r|d
|          }fdt          |          D             }	| j        j        dk    r |                     |          }
t!          j        d | j        | j        | j        | j        |
d
d
dd
d
f         |
d
d
dd
d
f         fD                       }|                    |j        d
d          \  }}t!          j        |t1          |	                    }t!          j        |	t1          |                    }|                    t7          t9          ||                    ddg          }nBt!          j        | j        | j        | j        | j        |                     |          f          }|	} ||||          S )a  
        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.

        Notes
        -----
        The dataframe is created on each call and not cached, as are the
        tables build in `summary()`
        r   )	DataFrame
MultiIndexr   z	Std. Err.zzPr(>|z|)zConf. Int. LowzCont. Int. Hi.k_extraNc                 *    g | ]\  }}|         |S r   r   ).0r[   namer2   s      r   
<listcomp>z1DiscreteMargins.summary_frame.<locals>.<listcomp>  s&    HHHfaQHTHHHr   rR   c                 8    g | ]}|                     d           S )rs   )rx   )r   r[   s     r   r   z1DiscreteMargins.summary_frame.<locals>.<listcomp>  s4     %B %B %BaQWWS\\ %B %B %Br   r%   Tr   endogr    )names)columnsindex)r   r   r   rY   pandasr   r   _transform_namesr    r   
exog_namesgetattr	enumerater   r*   r   r   column_stackr   r   r   _get_endog_nameendog_namesrepeatrK   tilefrom_tupleslistzip)r   r   r   rY   r   r   r   r   r   	var_namescitable_
yname_listynamesxnamesr   r2   s                    @r   r   zDiscreteMargins.summary_frame  sZ   ( 	-...,"00000000!$"6x"@A"-sJ"24DF l %))!,,1\'2
%A..Q;;#IgXI.JHHHH	*(=(=HHH	<!!u%%BO %B %Btr!!!Q'{Bqqq!QQQwKA%B %B %B C CE $33E4E8<$ 4 H HMAzYz3y>>::FWYJ88F**4FF0C0C+D+D2961B + D DEE OT\4?DL%)\4==3G3G%I J JEEyU;;;;r   c                     t          | j                   t          j        t	          j        | j                            dz  S )NrR   )r   r   r   sfr   absr   r   s    r   r   zDiscreteMargins.pvalues  s4    -...wrvdl++,,q00r   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%   rR   )	r   r   r   r   ppfr   r   r)   r   )r   r   me_seqloweruppers         r   r   zDiscreteMargins.conf_int  sm      	-...HQ]##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	         }
 |            }t          |j                  \  }}||
                    |d                    t          |d
d          dk    r|
d	|j                  }
t#          t          |dd                    }|dk    r!|                    |j        d	d          \  }}n
|j        }|g}|                    | |g ||
|           g }|                     |          }| j        }| j        }| j        }| j        }|dk    rt3          |          D ]}||d	d	|f         |d	d	|f         |d	d	|f         |d	d	|f         |d	d	d	d	|f         f} ||||         |
|dd          }||         |_        dt6          |         ddddt9          |dz            z   t9          d|dz  z
            dz   g}|                    d|           |                    |            |	|d          }nl||||||f} ||||
|dd          }dt6          |         ddddt9          |dz            z   t9          d|dz  z
            d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   zDep. Variable:zMethod:zAt:r   r   )Summarysummary_paramstable_extendNr   rh   r%   Tr   )gleftgrightynamexnametitleF)r   r   r   use_tskip_header zstd errr   zP>|z|[rR   ])keep_headers) r   r   r   rY   	__class__r   r   statsmodels.iolib.summaryr   r   r   r   r#   r    popr   r   intr   add_table_2colsr   r   r   r   r   ranger   r   strinsert_header_rowappendtables)r   r   r   rY   r   r   top_leftr   r   r   r   smryr   r"   rh   r   r   r   r   r   r   r   r   eqrestuptbleheaders                              r   r   zDiscreteMargins.summary  s    	-...,(+>>%h/%(9':;VH%-d3458	> 	> 	> 	> 	> 	> 	> 	> 	> 	>%aaa(
wyy (
339 NN9Q<(((5)Q''!++#Oem^O4JsA&&''q55 ' 7 78I04$ !8 !@ !@E:: %EJT":U 	 	< 	< 	< =='',_
,,q55Ahh # #!7111R4=*QQQrT2B!!!!B$-2111R8HJ%~fJrN$.e5*.0 0 0 (^
.v6	3s57||!3S57^^c5IK&&q&111T"""" LT:::EEw
GWhOF"N6ju$@ @ @E*62Iss57||!3S57^^c5IKF##Av...5!!!r   r   r   NFc                    |                                   |                                }|                                }t          ||           t          ||          | _        | j        }|j        }|j        }|j        	                                }	t          |	          \  }
}|r$t          ||           t          |	|          \  }}nd}|r$t          ||           t          |	|          \  }}nd}|| _        || _        t!          |	|||
          }	|                    ||	|||          }t%          |dd          }t'          j        |
|          }
t+          ||          }|dk    r`|dk    rG|j        t'          j        |
           z
  }|dd|
f                             d||d          | _        dS |dd|
f         | _        dS t5          |||	|                                ||j        ||||
  
        \  }}|dk    r||j        t'          j        |
           z
  }||
                             ||d          | _        ||
                             ||d          | _        ||
         dd|
f         | _        dS |
dt=          |                   }
||
         dd|
f         | _        ||
         | _        ||
         | _        dS )	ay
  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.
        )r   r   Nrh   r%   r   rs   )order)r   r   r   rI   r   r   rY   rZ   r    rU   r#   r   r:   rF   	dummy_idx	count_idxrP   _derivative_exogr   r   r   rc   rm   r   reshaper   r   r}   r   margeff_covrK   )r   r   r   rM   r9   rE   r   rY   rZ   r    r!   r"   r  r  rX   rh   rm   r  r   s                      r   r   zDiscreteMargins.get_margeffZ  s   x 	 XXZZB'''#6b999,z  "24"8"8Y 	 V,,,/i@@IuuI 	 V,,,/i@@IuuI #" !r6;?? ((v4=yJ J E3""gk1--gr**;;1uuGbfk\222&qqq+~6>>r1aFI  ?  K  K  'qqq+~6 ':%070B0B0D0Db050F09906	'; ';#K 1uuGbfk\222&{3;;Aq;LL",["9"A"A!QHK #B #M #M#.{#;AAA{N#K   
 *-3w<<-8#.{#;AAA{N#K ",["9&{3r   r   )r   r   NFF)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s          .0 * * * *
   . . ^.4< 4< 4< 4<n 1 1 ^1. . . ..P P P Pd ?C-2B4 B4 B4 B4 B4 B4r   r   )statsmodels.compat.pythonr   numpyr   scipy.statsr   statsmodels.tools.decoratorsr   r   r   r#   r4   r:   rB   rF   rP   r_   ra   rc   rn   rp   r   r   r   r   rI   r   r   r   r   r   r   <module>r     s   + * * * * *           7 7 7 7 7 7G G GG G G
" 
" 
"  8    4    8  (  &    B  @KD KD KDZ, , ,  
2 2 2 4W,((* * * 
," ," ," ," ," ," ," ,"^B4 B4 B4 B4 B4 B4 B4 B4 B4 B4r   