B
    Z                 @   s  d Z ddlmZmZmZmZ ddlZddlZ	ddl
mZ ddlmZmZmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZm Z m!Z! dddddddddddddddddgZ"dd  Z#d=d"dZ$d>d#dZ%d?d$dZ&d%d& Z'di d'i dd(fd)dZ(d@d*dZ)dAd+dZ*dBd,dZ+dCd-dZ,dDd2dZ-dEd3dZ.dFd4dZ/ed5d6i e/_ dGd7dZ0e d5d6i e0_ dHd9dZ1e!d5d6i e1_ dId:dZ2d;d Z3dJd<dZ4dS )KzPartial Regression plot and residual plots to find misspecification


Author: Josef Perktold
License: BSD-3
Created: 2011-01-23

update
2011-06-05 : start to convert example to usable functions
2011-10-27 : docstrings

    )lrangestring_typeslziprangeN)dmatrix)OLSGLSWLS)GLM)GEE)wls_prediction_std)utils)lowess)maybe_unwrap_results)model   )_plot_added_variable_doc_plot_partial_residuals_doc_plot_ceres_residuals_docplot_fitplot_regress_exogplot_partregress	plot_ccprplot_partregress_gridplot_ccpr_grid
add_lowessabline_plotinfluence_plotplot_leverage_resid2added_variable_residspartial_residsceres_residsplot_added_variableplot_partial_residualsplot_ceres_residualsc             C   s   d| j d  | j S )Ng       @r   )Zdf_modelnobs)results r'   Clib/python3.7/site-packages/statsmodels/graphics/regressionplots.py_high_leverage(   s    r)   皙?c             K   sb   |   | j}|   | j}t||fd|i|}| j|dddf |dddf ddd | jS )a  
    Add Lowess line to a plot.

    Parameters
    ----------
    ax : matplotlib Axes instance
        The Axes to which to add the plot
    lines_idx : int
        This is the line on the existing plot to which you want to add
        a smoothed lowess line.
    frac : float
        The fraction of the points to use when doing the lowess fit.
    lowess_kwargs
        Additional keyword arguments are passes to lowess.

    Returns
    -------
    fig : matplotlib Figure instance
        The figure that holds the instance.
    fracNr   r   rg      ?)Zlw)	get_linesZ_yZ_xr   plotfigure)axZ	lines_idxr+   Zlowess_kwargsy0Zx0Zlresr'   r'   r(   r   -   s
    *c             K   s  t |\}}t || j\}}t| } | jj}| jjdd|f }t|}	||	 }||	 }|j	||d| jj
d |dk	r|j	|||	 ddd d| }
t| \}}}|j	|| j|	 dfdd	d
| |j|||	 ||	 dddd ||
 || || jj
 |jddd |S )a  Plot fit against one regressor.

    This creates one graph with the scatterplot of observed values compared to
    fitted values.

    Parameters
    ----------
    results : result instance
        result instance with resid, model.endog and model.exog as attributes
    x_var : int or str
        Name or index of regressor in exog matrix.
    y_true : array_like
        (optional) If this is not None, then the array is added to the plot
    ax : Matplotlib AxesSubplot instance, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    kwargs
        The keyword arguments are passed to the plot command for the fitted
        values points.

    Returns
    -------
    fig : Matplotlib figure instance
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.

    Examples
    --------
    Load the Statewide Crime data set and perform linear regression with
    `poverty` and `hs_grad` as variables and `murder` as the response

    >>> import statsmodels.api as sm
    >>> import matplotlib.pyplot as plt

    >>> data = sm.datasets.statecrime.load_pandas().data
    >>> murder = data['murder']
    >>> X = data[['poverty', 'hs_grad']]

    >>> X["constant"] = 1
    >>> y = murder
    >>> model = sm.OLS(y, X)
    >>> results = model.fit()

    Create a plot just for the variable 'Poverty':

    >>> fig, ax = plt.subplots()
    >>> fig = sm.graphics.plot_fit(results, 0, ax=ax)
    >>> ax.set_ylabel("Murder Rate")
    >>> ax.set_xlabel("Poverty Level")
    >>> ax.set_title("Linear Regression")

    >>> plt.show()

    .. plot:: plots/graphics_plot_fit_ex.py

    NZbo)labelzb-zTrue valueszFitted values versus %sDr,   fitted)colorr2   r   kgffffff?)	linewidthr5   alphabest)locZ	numpoints)r   create_mpl_axmaybe_name_or_idxr   r   endogexognpZargsortr.   endog_namesr   fittedvaluesvlines	set_title
set_xlabel
set_ylabellegend)r&   exog_idxZy_truer0   kwargsfig	exog_nameyx1Z
x1_argsorttitleprstdiv_liv_ur'   r'   r(   r   I   s,    :


c             C   s  t |}t || j\}}t| } | jj}| jjdd|f }t| \}}}|ddd}	|	j	|| jj
ddd|d |	j	|| jdd	d
dd |	j|||dddd |	jddd |	| |	| |	jdd |ddd}	|		|| jd |	jddd |	jd| dd |	| |	d |ddd}	t| jjjd t}
d|
|< | jjdd|
f }ddlm} t| jjj|||| jjjd|d|	d}|	jddd |ddd }	t| ||	d!}|	jd"dd |jd#| dd |  |j dd$ |S )%ag  Plot regression results against one regressor.

    This plots four graphs in a 2 by 2 figure: 'endog versus exog',
    'residuals versus exog', 'fitted versus exog' and
    'fitted plus residual versus exog'

    Parameters
    ----------
    results : result instance
        result instance with resid, model.endog and model.exog as attributes
    exog_idx : int
        index of regressor in exog matrix
    fig : Matplotlib figure instance, optional
        If given, this figure is simply returned.  Otherwise a new figure is
        created.

    Returns
    -------
    fig : matplotlib figure instance
    N   r   obg?)r5   r8   r2   r3   r,   r4   g      ?)r5   r2   r8   r6   gffffff?)r7   r5   r8   zY and Fitted vs. Xlarge)fontsizer9   )r:   r   black)rK   r5   zResiduals versus %sresid   F)Series)nameindex)
obs_labelsr0   zPartial regression plot   )r0   z	CCPR PlotzRegression Plots for %s)top)!r   create_mpl_figr<   r   r   r@   r>   r   add_subplotr.   r=   rA   rB   rC   rD   rE   rF   rW   Zaxhliner?   ZonesshapeboolpandasrY   r   dataZ
orig_endog
row_labelsr   suptitletight_layoutsubplots_adjust)r&   rG   rI   rJ   Zy_namerL   rN   rO   rP   r0   Z	exog_notiexog_othersrY   r'   r'   r(   r      sL    





c             C   s:   t | | }t || }t |j|j }|||ffS )a  Partial regression.

    regress endog on exog_i conditional on exog_others

    uses OLS

    Parameters
    ----------
    endog : array_like
    exog : array_like
    exog_others : array_like

    Returns
    -------
    res1c : OLS results instance

    (res1a, res1b) : tuple of OLS results instances
         results from regression of endog on exog_others and of exog_i on
         exog_others

    )r   fitrW   )r=   exog_iri   Zres1aZres1bZres1cr'   r'   r(   _partial_regression   s    rl   TFc	             K   s  t |\}
}t| tr&t| d |} t|tr<t||}n$t|tr\d|}t||}n|}d}t|tjr|j	dkrd}nt|t
jr|jrd}t|trt|d |}|r|j| |df|	 t| | }t|tjrdn|j}t| tjrdn
| jjd }nXt| | }t|| }|j}|j}|jj}|jj}|j||df|	 t|| }td|jd d	|d
}
|dkrd}|d|  |d|  |jd| |dkr|dk	r|j}nt|dr|j}n
|jjj}|dkrtt |}|dk	rlt |t |kr t!d|"t#ddd t j$tt ||t%|j|jdgt | dfd|i|}|r|
|j|jffS |
S dS )au	  Plot partial regression for a single regressor.

    Parameters
    ----------
    endog : ndarray or string
       endogenous or response variable. If string is given, you can use a
       arbitrary translations as with a formula.
    exog_i : ndarray or string
        exogenous, explanatory variable. If string is given, you can use a
        arbitrary translations as with a formula.
    exog_others : ndarray or list of strings
        other exogenous, explanatory variables. If a list of strings is given,
        each item is a term in formula. You can use a arbitrary translations
        as with a formula. The effect of these variables will be removed by
        OLS regression.
    data : DataFrame, dict, or recarray
        Some kind of data structure with names if the other variables are
        given as strings.
    title_kwargs : dict
        Keyword arguments to pass on for the title. The key to control the
        fonts is fontdict.
    obs_labels : bool or array-like
        Whether or not to annotate the plot points with their observation
        labels. If obs_labels is a boolean, the point labels will try to do
        the right thing. First it will try to use the index of data, then
        fall back to the index of exog_i. Alternatively, you may give an
        array-like object corresponding to the obseveration numbers.
    labels_kwargs : dict
        Keyword arguments that control annotate for the observation labels.
    ax : Matplotlib AxesSubplot instance, optional
        If given, this subplot is used to plot in instead of a new figure being
        created.
    ret_coords : bool
        If True will return the coordinates of the points in the plot. You
        can use this to add your own annotations.
    kwargs
        The keyword arguments passed to plot for the points.

    Returns
    -------
    fig : Matplotlib figure instance
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.
    coords : list, optional
        If ret_coords is True, return a tuple of arrays (x_coords, y_coords).

    Notes
    -----
    The slope of the fitted line is the that of `exog_i` in the full
    multiple regression. The individual points can be used to assess the
    influence of points on the estimated coefficient.

    See Also
    --------
    plot_partregress_grid : Plot partial regression for a set of regressors.
    z-1+Fr   TrR   xrK   r6   )r5   r0   z	e(%s | X)Partial Regression PlotNr[   z*obs_labels does not match length of exog_icenterbottom)hava)r      zx-larger0   )ro   )&r   r;   
isinstancer   r   listjoinr?   Zndarraysizepd	DataFrameemptyr.   r   rj   rZ   Zdesign_infoZcolumn_namesrW   r   r@   r   paramsrD   rE   rC   r[   hasattrrd   re   r   len
ValueErrorupdatedictannotate_axesr   )r=   rk   ri   rd   title_kwargsr\   Zlabel_kwargsr0   Z
ret_coordsrH   rI   ZRHSZRHS_isemtpyZfitted_lineZx_axis_endog_nameZy_axis_endog_nameZ	res_yaxisZ	res_xaxisZxaxis_residZyaxis_residr'   r'   r(   r     sl    =










c          	   C   sf  ddl }t|}t|| j\}}|j| jj| jjd}| jj}|j	d }|dk	r^|\}	}
nDt
|dkrttt
|d }	d}
ddd	ii}nt
|}	d}
i }t| jj}xt|D ]\}}t|}|| |j|dd|f || d
}||	|
|d }t||j|dd|f || d|||dd |d qW |jddd |  |jdd |S )a)  Plot partial regression for a set of regressors.

    Parameters
    ----------
    results : results instance
        A regression model results instance
    exog_idx : None, list of ints, list of strings
        (column) indices of the exog used in the plot, default is all.
    grid : None or tuple of int (nrows, ncols)
        If grid is given, then it is used for the arrangement of the subplots.
        If grid is None, then ncol is one, if there are only 2 subplots, and
        the number of columns is two otherwise.
    fig : Matplotlib figure instance, optional
        If given, this figure is simply returned.  Otherwise a new figure is
        created.

    Returns
    -------
    fig : Matplotlib figure instance
        If `fig` is None, the created figure.  Otherwise `fig` itself.

    Notes
    -----
    A subplot is created for each explanatory variable given by exog_idx.
    The partial regression plot shows the relationship between the response
    and the given explanatory variable after removing the effect of all other
    explanatory variables in exog.

    See Also
    --------
    plot_partregress : Plot partial regression for a single regressor.
    plot_ccpr

    References
    ----------
    See http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/partregr.htm

    r   N)rZ   r   rQ   g       @ZfontdictrU   Zsmall)columnsF)r0   r   r\    zPartial Regression PlotrT   )rU   gffffff?)r^   )rc   r   r_   r<   r   rY   r=   r@   r>   ra   r~   intr?   ceilZarray
exog_names	enumerater   poprz   r`   r   rC   rf   rg   rh   )r&   rG   gridrI   rc   rJ   rK   r>   Zk_varsnrowsncolsr   Zother_namesiidxZothersri   r0   r'   r'   r(   r     s>    '




c       
      C   s   t |\}}t || j\}}t| } | jjdd|f }|| j|  }|||| j d ddl	m
} t||| }|j}	t|	t|d}|d |d||f  |d|  |S )	a  Plot CCPR against one regressor.

    Generates a CCPR (component and component-plus-residual) plot.

    Parameters
    ----------
    results : result instance
        A regression results instance.
    exog_idx : int or string
        Exogenous, explanatory variable. If string is given, it should
        be the variable name that you want to use, and you can use arbitrary
        translations as with a formula.
    ax : Matplotlib AxesSubplot instance, optional
        If given, it is used to plot in instead of a new figure being
        created.

    Returns
    -------
    fig : Matplotlib figure instance
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.

    See Also
    --------
    plot_ccpr_grid : Creates CCPR plot for multiple regressors in a plot grid.

    Notes
    -----
    The CCPR plot provides a way to judge the effect of one regressor on the
    response variable by taking into account the effects of the other
    independent variables. The partial residuals plot is defined as
    Residuals + B_i*X_i versus X_i. The component adds the B_i*X_i versus
    X_i to show where the fitted line would lie. Care should be taken if X_i
    is highly correlated with any of the other independent variables. If this
    is the case, the variance evident in the plot will be an underestimate of
    the true variance.

    References
    ----------
    http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/ccpr.htm
    NrR   r   )add_constant)r0   z*Component and component plus residual plotzResidual + %s*beta_%dz%s)r   r;   r<   r   r   r>   r|   r.   rW   statsmodels.tools.toolsr   r   rj   r   r   rC   rE   rD   )
r&   rG   r0   rI   rJ   rL   Zx1betar   modr|   r'   r'   r(   r     s    *
c             C   s   t |}t || j\}}|dk	r.|\}}n4t|dkrVttt|d }d}nt|}d}d}xdt|D ]X\}}	| jj	dd|	f 
 dkrd}qp||||d | }
t| |	|
d}|
d qpW |jdd	d
 |  |jdd |S )a  Generate CCPR plots against a set of regressors, plot in a grid.

    Generates a grid of CCPR (component and component-plus-residual) plots.

    Parameters
    ----------
    results : result instance
        uses exog and params of the result instance
    exog_idx : None or list of int
        (column) indices of the exog used in the plot
    grid : None or tuple of int (nrows, ncols)
        If grid is given, then it is used for the arrangement of the subplots.
        If grid is None, then ncol is one, if there are only 2 subplots, and
        the number of columns is two otherwise.
    fig : Matplotlib figure instance, optional
        If given, this figure is simply returned.  Otherwise a new figure is
        created.

    Returns
    -------
    fig : Matplotlib figure instance
        If `ax` is None, the created figure.  Otherwise the figure to which
        `ax` is connected.

    Notes
    -----
    Partial residual plots are formed as::

        Res + Betahat(i)*Xi versus Xi

    and CCPR adds::

        Betahat(i)*Xi versus Xi

    See Also
    --------
    plot_ccpr : Creates CCPR plot for a single regressor.

    References
    ----------
    See http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/ccpr.htm
    NrQ   g       @r   r   )rG   r0   r   z&Component-Component Plus Residual PlotrT   )rU   gffffff?)r^   )r   r_   r<   r   r~   r   r?   r   r   r>   varr`   r   rC   rf   rg   rh   )r&   rG   r   rI   rJ   r   r   Zseen_constantr   r   r0   r'   r'   r(   r   ,  s*    +

c                sB  |dk	r|  }nd}t|\}}|rl|j\|dkr|jjdddf  |jjdddf  g}n(dk	r|dk	std|dkr|  }|d   |d   g}	|	| ddl
m}
 G  fddd|
  ||	f|}|| |jd|j|_|jd	|j|_|r.|| |r>|| |S )
a  
    Plots a line given an intercept and slope.

    intercept : float
        The intercept of the line
    slope : float
        The slope of the line
    horiz : float or array-like
        Data for horizontal lines on the y-axis
    vert : array-like
        Data for verterical lines on the x-axis
    model_results : statsmodels results instance
        Any object that has a two-value `params` attribute. Assumed that it
        is (intercept, slope)
    ax : axes, optional
        Matplotlib axes instance
    kwargs
        Options passed to matplotlib.pyplot.plt

    Returns
    -------
    fig : Figure
        The figure given by `ax.figure` or a new instance.

    Examples
    --------
    >>> import numpy as np
    >>> import statsmodels.api as sm
    >>> np.random.seed(12345)
    >>> X = sm.add_constant(np.random.normal(0, 20, size=30))
    >>> y = np.dot(X, [25, 3.5]) + np.random.normal(0, 30, size=30)
    >>> mod = sm.OLS(y,X).fit()
    >>> fig = sm.graphics.abline_plot(model_results=mod)
    >>> ax = fig.axes[0]
    >>> ax.scatter(X[:,1], y)
    >>> ax.margins(.1)
    >>> import matplotlib.pyplot as plt
    >>> plt.show()
    Nr   z-specify slope and intercepty or model_resultsr   )Line2Dc                   s:   e Zd Z fddZ fddZfddZ  ZS )zabline_plot.<locals>.ABLine2Dc                s"   t  | j|| d | _d | _d S )N)super__init__id_xlim_callbackid_ylim_callback)selfargsrH   )ABLine2D	__class__r'   r(   r     s    z&abline_plot.<locals>.ABLine2D.__init__c                s@   | j }| jr|j| j | jr.|j| j t |   d S )N)Zaxesr   	callbacksZ
disconnectr   r   remove)r   r0   )r   r   r'   r(   r     s    z$abline_plot.<locals>.ABLine2D.removec                sp   | d | } fdd|D }|d }| }|d   |d   g}||| |jj  d S )NFc                s   g | ]}| kr|qS r'   r'   ).0Zchild)r   r'   r(   
<listcomp>  s    z@abline_plot.<locals>.ABLine2D.update_datalim.<locals>.<listcomp>r   r   )Zset_autoscale_onZget_childrenget_xlimset_datar/   ZcanvasZdraw)r   r0   ZchildrenZablinesZablinern   rK   )	interceptslope)r   r(   update_datalim  s    
 z,abline_plot.<locals>.ABLine2D.update_datalim)__name__
__module____qualname__r   r   r   __classcell__r'   )r   r   r   )r   r(   r     s   r   Zxlim_changedZylim_changed)r   r   r;   r|   r   r>   minmaxr   Zset_xlimZmatplotlib.linesr   Zadd_liner   Zconnectr   r   r   ZhlineZvline)r   r   ZhorizZvertZmodel_resultsr0   rH   rn   rI   Zdata_yr   liner'   )r   r   r   r(   r   w  s4    )

 



皙?cooks0         ?c          	   K   s  t |\}}|  }	| dr0|	jd }
n,| drPt|	jd }
nt	d| t
|
}|d d }|
|
  | | d }
|	j}|r|	j}n|	j}ddlm} |jd|d  | j}t||k}|t| k}t||}|j|||
|d	 | jjj}|d
krtt|}t t|d |t||t|
d d  |
d d d|}ddd}|jd| |j d| |j!d| |S )ad  
    Plot of influence in regression. Plots studentized resids vs. leverage.

    Parameters
    ----------
    results : results instance
        A fitted model.
    external : bool
        Whether to use externally or internally studentized residuals. It is
        recommended to leave external as True.
    alpha : float
        The alpha value to identify large studentized residuals. Large means
        abs(resid_studentized) > t.ppf(1-alpha/2, dof=results.df_resid)
    criterion : str {'DFFITS', 'Cooks'}
        Which criterion to base the size of the points on. Options are
        DFFITS or Cook's D.
    size : float
        The range of `criterion` is mapped to 10**2 - size**2 in points.
    plot_alpha : float
        The `alpha` of the plotted points.
    ax : matplotlib Axes instance
        An instance of a matplotlib Axes.

    Returns
    -------
    fig : matplotlib figure
        The matplotlib figure that contains the Axes.

    Notes
    -----
    Row labels for the observations in which the leverage, measured by the
    diagonal of the hat matrix, is high or the residuals are large, as the
    combination of large residuals and a high influence value indicates an
    influence point. The value of large residuals can be controlled using the
    `alpha` parameter. Large leverage points are identified as
    hat_i > 2 * (df_model + 1)/nobs.
    Zcoor   ZdffzCriterion %s not understoodrQ   @   )statsg      ?)sr8   Ng      ?zx-large   rV   )rU   r5   Studentized Residuals
H LeverageInfluence Plot)r   )r   )r   )"r   r;   get_influencelower
startswithZcooks_distancer?   absZdffitsr   Zptpr   hat_matrix_diagZresid_studentized_externalZresid_studentized_internalZscipyr   tppfZdf_residr)   
logical_orZscatterr   rd   re   r   r~   r   wherer   rE   rD   rC   )r&   Zexternalr8   Z	criterionrx   Z
plot_alphar0   rH   rI   inflZpsizeZ	old_rangeZ	new_rangeleverageZresidsr   cutofflarge_residlarge_leverageZlarge_pointslabelsZfontr'   r'   r(   r     s@    '



c          
   K   s  ddl m}m} t|\}}|  }|j}|| j}	|j|	d |df| |	d |
d |d |t| k}
|d|d  }t|	|k}| jjj}|d	krtt| j}tt|
|d }tj||t|	d |d
gt| j d|ddd}|dd |S )a  
    Plots leverage statistics vs. normalized residuals squared

    Parameters
    ----------
    results : results instance
        A regression results instance
    alpha : float
        Specifies the cut-off for large-standardized residuals. Residuals
        are assumed to be distributed N(0, 1) with alpha=alpha.
    ax : Axes instance
        Matplotlib Axes instance

    Returns
    -------
    fig : matplotlib Figure
        A matplotlib figure instance.
    r   )zscorenormrQ   rR   zNormalized residuals**2ZLeveragez)Leverage vs. Normalized residuals squaredg      ?N)r   rt   rT   rp   rq   )r0   rr   rs   g333333?)Zscipy.statsr   r   r   r;   r   r   rW   r.   rD   rE   rC   r)   r   r?   r   r   rd   re   r   r   r%   r   r   r   r   Zmargins)r&   r8   r0   rH   r   r   rI   r   r   rW   r   r   r   r   r[   r'   r'   r(   r   8  s*    




c             C   s   | j }t|\}}t| ||||d\}}	|j|	|ddd |jddd t|tkr\|}
n
|j| }
|j	|
dd	 |j
|jd
 dd	 |S )N)
resid_typeuse_glm_weights
fit_kwargsrR   g333333?)r8   zAdded variable plotrT   )rU      )rx   z
 residuals)r   r   r;   r   r.   rC   typestrr   rD   rE   r@   )r&   
focus_exogr   r   r   r0   r   rI   endog_residfocus_exog_residxnamer'   r'   r(   r"   e  s    
Zextra_params_docz6results: object
	Results for a fitted regression modelc       	      C   s   | j }t||\}}t| |}| j jd d |f }t|\}}|j||ddd |jddd t|t	krt|}n
|j
| }|j|dd |jd	dd |S )
NrR   g333333?)r8   zPartial residuals plotrT   )rU   r   )rx   zComponent plus residual)r   r   r<   r    r>   r;   r.   rC   r   r   r   rD   rE   )	r&   r   r0   r   	focus_colZprfocus_exog_valsrI   r   r'   r'   r(   r#     s    

Q?c       
      C   s   | j }t||\}}t| |||d}|jd d |f }t|\}	}|j||ddd |jddd |j|dd	 |j	d
dd	 |	S )N)r+   
cond_meansrR   g333333?)r8   zCERES residuals plotrT   )rU   r   )rx   zComponent plus residual)
r   r   r<   r!   r>   r;   r.   rC   rD   rE   )
r&   r   r+   r   r0   r   r   presidr   rI   r'   r'   r(   r$     s    c             C   s  | j }t|tttfs&td|jj t	||\}}t
t| j}t|}|| t|}|dkr,|jdd|f }||d8 }tj|d\}	}
}t|
dk}|	dd|f }|jdd|f }tt||jd f}xFt
|jd D ]4}|dd|f }t|||dd}||dd|f< qW tj|jdd|f |fdd}|j}| }||j|f|}| }|j|j }t|ttfr||jj|j9 }|jd |kr|t |dd|df |j|d 7 }|S )	a  
    Calculate the CERES residuals (Conditional Expectation Partial
    Residuals) for a fitted model.

    Parameters
    ----------
    results : model results instance
        The fitted model for which the CERES residuals are calculated.
    focus_exog : int
        The column of results.model.exog used as the 'focus variable'.
    frac : float, optional
        Lowess smoothing parameter for estimating the conditional
        means.  Not used if `cond_means` is provided.
    cond_means : array-like, optional
        If provided, the columns of this array are the conditional
        means E[exog | focus exog], where exog ranges over some
        or all of the columns of exog other than focus exog.  If
        this is an empty nx0 array, the conditional means are
        treated as being zero.  If None, the conditional means are
        estimated.

    Returns
    -------
    An array containing the CERES residuals.

    Notes
    -----
    If `cond_means` is not provided, it is obtained by smoothing each
    column of exog (except the focus column) against the focus column.

    Currently only supports GLM, GEE, and OLS models.
    z$ceres residuals not available for %sNr   gư>r   F)r+   Zreturn_sorted)Zaxis)!r   ru   r
   r   r   r   r   r   r   r<   r   r~   r|   rv   r   r>   Zmeanr?   ZlinalgZsvdZflatnonzeror{   ra   r   Zconcatenate_get_init_kwdsr=   rj   rA   familylinkderivdot)r&   r   r+   r   r   r   Zix_nfZnnfZpexogur   ZvtiiZfcoljr1   ZcfZnew_exogklassZinit_kwargs	new_model
new_resultr   r'   r'   r(   r!     s@    "

 *c             C   s   | j }|j|   }t|ttfr8||jj| j	9 }n"t|t
ttfrJntdt| t|tkrt|j|}n|}| j| |jdd|f  }|| S )a:  
    Returns partial residuals for a fitted model with respect to a
    'focus predictor'.

    Parameters
    ----------
    results : results instance
        A fitted regression model.
    focus col : int
        The column index of model.exog with respect to which the
        partial residuals are calculated.

    Returns
    -------
    An array of partial residuals.

    References
    ----------
    RD Cook and R Croos-Dabrera (1998).  Partial residual plots in
    generalized linear models.  Journal of the American Statistical
    Association, 93:442.
    z+Partial residuals for '%s' not implemented.N)r   r=   Zpredictru   r
   r   r   r   r   rA   r   r   r	   r   r   r   r   r[   r|   r>   )r&   r   r   rW   r   Z	focus_valr'   r'   r(   r      s    c             C   s  | j }t|tttfs&td|jj |j}|j	}t
||\}}|dd|f }	|dkrrt|ttfrnd}nd}t|jd }
t|
}
|
| |dd|
f }| j|
 }|j}| }|||f|}d|i}|dk	r|| |jf |}|jstdyt||}W n" tk
r,   td| Y nX d	dlm  m} t|ttfr|r|j| j}t|d
rz||j }||	|| }n||	| }|j }||fS )aY  
    Residualize the endog variable and a 'focus' exog variable in a
    regression model with respect to the other exog variables.

    Parameters
    ----------
    results : regression results instance
        A fitted model including the focus exog and all other
        predictors of interest.
    focus_exog : integer or string
        The column of results.model.exog or a variable name that is
        to be residualized against the other predictors.
    resid_type : string
        The type of residuals to use for the dependent variable.  If
        None, uses `resid_deviance` for GLM/GEE and `resid` otherwise.
    use_glm_weights : bool
        Only used if the model is a GLM or GEE.  If True, the
        residuals for the focus predictor are computed using WLS, with
        the weights obtained from the IRLS calculations for fitting
        the GLM.  If False, unweighted regression is used.
    fit_kwargs : dict, optional
        Keyword arguments to be passed to fit when refitting the
        model.

    Returns
    -------
    endog_resid : array-like
        The residuals for the original exog
    focus_exog_resid : array-like
        The residuals for the focus predictor

    Notes
    -----
    The 'focus variable' residuals are always obtained using linear
    regression.

    Currently only GLM, GEE, and OLS models are supported.
    z8model type %s not supported for added variable residualsNZresid_deviancerW   r   start_paramsz>fit did not converge when calculating added variable residualsz '%s' residual type not availabler   data_weights)!r   ru   r   r
   r   r   r   r   r>   r=   r   r<   r   ra   rv   r   r|   r   r   rj   Z	convergedgetattrAttributeError#statsmodels.regression.linear_modelZ
regressionZlinear_modelr   weightsrA   r}   r   r	   rW   )r&   r   r   r   r   r   r>   r=   r   r   r   Zreduced_exogr   r   rH   r   r   r   r   Zlmr   Z
lm_resultsr   r'   r'   r(   r   A  sN    )



)r   r*   )NN)N)NNN)N)NNN)NNNNNN)Tr   r   r   r   N)r   N)NTNN)N)r   NN)r   N)NTN)5__doc__Zstatsmodels.compat.pythonr   r   r   r   Znumpyr?   rc   ry   Zpatsyr   r   r   r   r	   Z+statsmodels.genmod.generalized_linear_modelr
   Z3statsmodels.genmod.generalized_estimating_equationsr   Z&statsmodels.sandbox.regression.predstdr   Zstatsmodels.graphicsr   Z*statsmodels.nonparametric.smoothers_lowessr   r   r   Zstatsmodels.baser   Z_regressionplots_docr   r   r   __all__r)   r   r   r   rl   r   r   r   r   r   r   r   r"   r#   r$   r!   r    r   r'   r'   r'   r(   <module>   sf   

Z
L 

U
?
K 
e 
Z
- 

 

Y0 