U
    KvfW                  	   @   s   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	Z
d dlZddlmZ ddlmZmZ G dd	 d	Zd
d ZddddddddZdd Zd-ddZd.ddZd/ddZd d! Zd0d#d$Zd1d%d&Zd2d)d*Zd3d+d,ZdS )4    )FUTURE_STACK)lzipN)reduce   )SimpleTable)	fmt_latexfmt_txtc                   @   s   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zd%ddZd&ddZ	d'ddZ
dd Zd(ddZd)ddZdd Zd d! Zd*d#d$ZdS )+Summaryc                 C   s"   g | _ g | _g | _d | _d| _d S )NF)tablessettings	extra_txttitle_merge_latexself r   >/tmp/pip-unpacked-wheel-2v6byqio/statsmodels/iolib/summary2.py__init__   s
    zSummary.__init__c                 C   s   |   S Nas_textr   r   r   r   __str__   s    zSummary.__str__c                 C   s   t t| d |   d S )Nz
"""
z
""")strtyper   r   r   r   r   __repr__   s    zSummary.__repr__c                 C   s   |   S )z$Display as HTML in IPython notebook.as_htmlr   r   r   r   _repr_html_   s    zSummary._repr_html_c                 C   s   |   S )z9Display as LaTeX when converting IPython notebook to PDF.)as_latexr   r   r   r   _repr_latex_"   s    zSummary._repr_latex_T%.4frc                 C   s*   ||||d}| j | | j| dS )a  
        Add the contents of a DataFrame to summary table

        Parameters
        ----------
        df : DataFrame
        header : bool
            Reproduce the DataFrame column labels in summary table
        index : bool
            Reproduce the DataFrame row labels in summary table
        float_format : str
            Formatting to float data columns
        align : str
            Data alignment (l/c/r)
        indexheaderfloat_formatalignN)r
   appendr   )r   dfr#   r$   r%   r&   r   r   r   r   add_df&   s     zSummary.add_dfc                 C   s"   t |}| j|dd||d dS )a  Add the contents of a Numpy array to summary table

        Parameters
        ----------
        array : numpy array (2D)
        float_format : str
            Formatting to array if type is float
        align : str
            Data alignment (l/c/r)
        Fr"   N)pd	DataFramer)   )r   arrayr&   r%   tabler   r   r   	add_array=   s
    

 zSummary.add_array   lc           	         s    fdd|  D } fdd| D }tt||}|jd | dkr~||jd |  }t|t|ddgg g}t||}tdd |}| j	||d d	S )
a  Add the contents of a Dict to summary table

        Parameters
        ----------
        d : dict
            Keys and values are automatically coerced to strings with str().
            Users are encouraged to format them before using add_dict.
        ncols : int
            Number of columns of the output table
        align : str
            Data alignment (l/c/r)
        float_format : str
            Formatting to float data columns
        c                    s   g | ]}t | qS r   
_formatter.0xr%   r   r   
<listcomp>]   s     z$Summary.add_dict.<locals>.<listcomp>c                    s   g | ]}t | qS r   r1   r3   r6   r   r   r7   ^   s     r    c                 S   s   t | |gS r   )nphstackr5   yr   r   r   <lambda>f       z"Summary.add_dict.<locals>.<lambda>r&   N)
keysvaluesr9   r,   r   shapevstacksplitr   r.   )	r   dZncolsr&   r%   r@   valsdatapadr   r6   r   add_dictM   s    zSummary.add_dictc                 C   s   | j | dS )zAppend a note to the bottom of the summary table. In ASCII tables,
        the note will be wrapped to table width. Notes are not indented.
        N)r   r'   )r   stringr   r   r   add_texti   s    zSummary.add_textNc                 C   sJ   t |tr|| _n4|dk	r@|jjj}|tkr4t| }d| | _nd| _dS )a  Insert a title on top of the summary table. If a string is provided
        in the title argument, that string is printed. If no title string is
        provided but a results instance is provided, statsmodels attempts
        to construct a useful title automatically.
        Nz	Results: r8   )
isinstancer   r   model	__class____name___model_types)r   r   resultsrM   r   r   r   	add_titleo   s    

zSummary.add_title皙?c           	      C   sd   t |||jd}t|}|dk	r&||_|dk	r6||d< | j|dd | j||d | j||d dS )aL  Try to construct a basic summary instance.

        Parameters
        ----------
        results : Model results instance
        alpha : float
            significance level for the confidence intervals (optional)
        float_format: str
            Float formatting for summary of parameters (optional)
        title : str
            Title of the summary table (optional)
        xname : list[str] of length equal to the number of parameters
            Names of the independent variables (optional)
        yname : str
            Name of the dependent variable (optional)
        )alphause_tNDependent Variable:r0   r?   r6   )r   rQ   )summary_paramsrU   summary_modelr#   rI   r)   rR   )	r   rQ   rT   r%   r   xnameynameparaminfor   r   r   add_base   s    zSummary.add_basec                    s   | j }| j}| j}| j}t||\}}  d }t||||}dd |D }	d|	}	|	d}	||	d< |	| d|	}	|dk	r|}t	| k rdt
 d t	|d   | }nd	} fd
d|D }
dd |
D }
d|
}
d||	|
g}|S )z%Generate ASCII Summary Table
        =c                 S   s   g | ]}|  qS r   r   r3   r   r   r   r7      s     z#Summary.as_text.<locals>.<listcomp>
r   N r/   r8   c                    s   g | ]}t | qS r   )textwrapwrapr3   Zwidestr   r   r7      s     c                 S   s   g | ]}d  |qS )r_   )joinr3   r   r   r   r7      s     )r
   r   r   r   _measure_tables_simple_tablesrd   rD   r'   lenint)r   r
   r   r   r   pad_col	pad_indexZ
rule_equalsimple_tablestabtxtoutr   rc   r   r      s.    



"
zSummary.as_textc                 C   sZ   | j }| j}t||}dd |D }d|}dd | jD }d|}d||g}|S )z$Generate HTML Summary Table
        c                 S   s   g | ]}|  qS r   r   r3   r   r   r   r7      s     z#Summary.as_html.<locals>.<listcomp>r_   c                 S   s   g | ]}| d dqS )r_   <br/>
)replace)r4   str   r   r   r7      s     ro   )r
   r   rf   rd   r   )r   r
   r   rk   rl   Ztemp_txtrm   rn   r   r   r   r      s    


zSummary.as_htmlr8   c                 C   s   | j }| j}| j}|dk	r(d| d }nd}d| d }t||}dd |D }d|}d	}| jrrt|d
|}d|||df}d|}d| j}	|d |	 }
|
S )zGenerate LaTeX Summary Table

        Parameters
        ----------
        label : str
            Label of the summary table that can be referenced
            in a latex document (optional)
        Nz	\caption{}z
\caption{}z\label{c                 S   s   g | ]}|  qS r   )Zas_latex_tabularr3   r   r   r   r7      s     z$Summary.as_latex.<locals>.<listcomp>z

z8\\hline\n\\hline\n\\end{tabular}\n\\begin{tabular}{.*}\nz\\midrule\nz\begin{table}z\end{table}r_   z \newline 
z

\bigskip
)	r
   r   r   rf   rd   r   resubr   )r   labelr
   r   r   rk   rl   Z
to_replaceZnon_captionedrm   rn   r   r   r   r      s$    	


zSummary.as_latex)TTr    r!   )r!   r    )r/   r0   r    )NN)rS   r    NNN)r8   )rO   
__module____qualname__r   r   r   r   r   r)   r.   rI   rK   rR   r]   r   r   r   r   r   r   r   r	      s&     



    
%r	   c                 C   s   t | |}dd |D }dd |D }t|}g }g }tt|D ]X}t| | jd d d}	t|||  |	 }
||
 || |	|
  }|||  qB||t|fS )zCompare width of ascii tables in a list and calculate padding values.
    We add space to each col_sep to get us as close as possible to the
    width of the largest table. Then, we add a few spaces to the first
    column to pad the rest.
    c                 S   s   g | ]}|  qS r   r   r3   r   r   r   r7     s     z#_measure_tables.<locals>.<listcomp>c                 S   s   g | ]}t | d  qS r   )rg   
splitlinesr3   r   r   r   r7     s     r   )rf   maxrangerg   rB   rh   r'   )r
   r   rk   rl   lengthZlen_maxZpad_seprj   iZnseprH   Zlen_newr   r   r   re      s    

re   zOrdinary least squareszGeneralized least squaresz$Generalized least squares with AR(p)zWeighted least squareszRobust linear modelzNegative binomial modelzGeneralized linear model)ZOLSZGLSZGLSARZWLSZRLMZNBinZGLMc                 C   s  dd }i }dd |d< dd |d< dd |d	< d
d |d< ||d< dd |d< dd |d< dd |d< dd |d< dd |d< dd |d< dd |d< dd |d< dd |d< | j rdnd }d!d |d"| d# < d$d |d%| d# < d&d |d'< d(d |d)< d*d |d+< d,d |d-< d.d |d/< d0d |d1< d2d |d3< d4d |d5< d6d |d7< d8d |d9< d:d |d;< i }| D ]8\}}z|| ||< W n tttfk
r   Y nX qv|S )<z8
    Create a dict with information about the model
    c                  _   s   t j  }|dS )Nz%Y-%m-%d %H:%M)datetimenowstrftime)argskwdsr   r   r   r   time_now%  s    
zsummary_model.<locals>.time_nowc                 S   s
   | j jjS r   )rM   rN   rO   r5   r   r   r   r=   *  r>   zsummary_model.<locals>.<lambda>zModel:c                 S   s
   | j jjS r   )familyZ__classrO   r   r   r   r   r=   +  r>   zModel Family:c                 S   s   | j jjjS r   )r   linkrN   rO   r   r   r   r   r=   ,  r>   zLink Function:c                 S   s   | j jS r   )rM   endog_namesr   r   r   r   r=   -  r>   rV   zDate:c                 S   s
   d| j  S Nz%#6d)Znobsr   r   r   r   r=   /  r>   zNo. Observations:c                 S   s
   d| j  S r   )Zdf_modelr   r   r   r   r=   0  r>   z	Df Model:c                 S   s
   d| j  S r   )Zdf_residr   r   r   r   r=   1  r>   zDf Residuals:c                 S   s
   | j d S )NZ	convergedZmle_retvalsr   r   r   r   r=   2  r>   z
Converged:c                 S   s
   | j d S )NZ
iterationsr   r   r   r   r   r=   3  r>   zNo. Iterations:c                 S   s   | j S r   )methodr   r   r   r   r=   4  r>   zMethod:c                 S   s
   | j d S )NZnormZfit_optionsr   r   r   r   r=   5  r>   zNorm:c                 S   s
   | j d S )NZ	scale_estr   r   r   r   r   r=   6  r>   zScale Est.:c                 S   s
   | j d S )NZcovr   r   r   r   r   r=   7  r>   z
Cov. Type:r8   z (uncentered)c                 S   s
   d| j  S Nz%#8.3f)rsquaredr   r   r   r   r=   :  r>   	R-squared:c                 S   s
   d| j  S r   )rsquared_adjr   r   r   r   r=   ;  r>   zAdj. R-squaredc                 S   s
   d| j  S r   )Z	prsquaredr   r   r   r   r=   <  r>   zPseudo R-squared:c                 S   s
   d| j  S Nz%8.4f)Zaicr   r   r   r   r=   =  r>   zAIC:c                 S   s
   d| j  S r   )Zbicr   r   r   r   r=   >  r>   zBIC:c                 S   s
   d| j  S Nz%#8.5g)Zllfr   r   r   r   r=   ?  r>   zLog-Likelihood:c                 S   s
   d| j  S r   )Zllnullr   r   r   r   r=   @  r>   zLL-Null:c                 S   s
   d| j  S r   )Z
llr_pvaluer   r   r   r   r=   A  r>   zLLR p-value:c                 S   s
   d| j  S r   )Zdeviancer   r   r   r   r=   B  r>   z	Deviance:c                 S   s
   d| j  S Nz%#6.3g)Zpearson_chi2r   r   r   r   r=   C  r>   zPearson chi2:c                 S   s
   d| j  S )Nz%#8.4g)Zfvaluer   r   r   r   r=   D  r>   zF-statistic:c                 S   s
   d| j  S r   )Zf_pvaluer   r   r   r   r=   E  r>   zProb (F-statistic):c                 S   s
   d| j  S r   )Zscaler   r   r   r   r=   F  r>   zScale:)Z
k_constantitemsAttributeErrorKeyErrorNotImplementedError)rQ   r   r\   Zrsquared_typern   keyfuncr   r   r   rX      sJ    
rX   rS   TFr    c              	   C   s  t | tr| \} }}}	}
}n"| j}| j}| j}	| j}
| |}t|||	|
gj	}t
||g}t|}|rdddddt|d  td|d  d g|_n.ddd	d
dt|d  td|d  d g|_|sz| jjj|_W n  tk
r   | jj|_Y nX n||_|S )ax  create a summary table of parameters from results instance

    Parameters
    ----------
    res : results instance
        some required information is directly taken from the result
        instance
    yname : {str, None}
        optional name for the endogenous variable, default is "y"
    xname : {list[str], None}
        optional names for the exogenous variables, default is "var_xx"
    alpha : float
        significance level for the confidence intervals
    use_t : bool
        indicator whether the p-values are based on the Student-t
        distribution (if True) or on the normal distribution (if False)
    skip_header : bool
        If false (default), then the header row is added. If true, then no
        header row is added.
    float_format : str
        float formatting options (e.g. ".3g")

    Returns
    -------
    params_table : SimpleTable instance
    zCoef.zStd.Err.tzP>|t|[r/   r   ]zzP>|z|)rL   tupleparamsbsetvaluespvaluesconf_intr9   r,   Tr:   r*   r+   r   columnsrM   rG   Zparam_namesr#   r   Z
exog_names)rQ   rZ   rY   rT   rU   Zskip_headerr%   r   r   r   r   r   rG   r   r   r   rW   R  s4    


  rW   c           
         s  t | }|jdd D ]}||  fdd||< qd|jdddf  d |jdddf< |r|jdddf d	k }|j||jd
 f d |j||jd
 f< |jdddf dk }|j||jd
 f d |j||jd
 f< |jdddf dk }|j||jd
 f d |j||jd
 f< |jddddf }|jf t}|rt| dtj	}t| dtj	}t
||d}	|	  r|	 fdd}	t
j||	gd
d}t
|}t| jjg|_|S )z<Stack coefficients and standard errors in single column
    Nr/   c                    s    |  S r   r   r   r6   r   r   r=     r>   z_col_params.<locals>.<lambda>(r   )   g?r   *rS   g{Gz?r   r   )r   r8   )zR-squared Adj.r8   c                    s    |  S r   r   r   r6   r   r   r=     r>   )Zaxis)rW   r   applyiloclocstackr   getattrr9   nanr*   SeriesZnotnullanyconcatr+   r   rM   r   )
resultr%   stars
include_r2rescolidxr   r   Zr2r   r6   r   _col_params  s2    ((((
r   c              	   C   s   |dkri }g }g }|D ]T}t || tr,qz||| |  W n tk
r`   |d Y nX || qtjt| jj|i|d}|S )z!Stack model info in a column
    Nr8   )r#   )	rL   dictr'   r   r*   r+   r   rM   r   )r   	info_dictrn   r#   r}   r   r   r   	_col_info  s    r   c                 C   sd   t t| t | kr| S ddlm} |t}g }| D ]*}||  d7  < ||d ||   q4|S )Nr   )defaultdictIr`   )rg   setcollectionsr   r   r'   )Zlist_of_namesr   Zname_counterr$   _namer   r   r   _make_unique  s    r   r   c                    s  t | ts| g}  fdd| D }|r4t|}	ntdd |D }	tt|D ]}
|	|
 g||
 _qRdd }t|d j}|dd D ]"}|jD ]}||kr|| qqd	D ]&}||kr|| |	t|| qt
||}||}r|jd t }|j|d
k j fddD }fddD }|| fdd|jdD }|7 |r|D ]}| q~|jdd}g }|jd}td|jd d
D ]\}
|||
  |
d |jd k r||
 ||
d  kr|d n|||
d   q||_r>fdd| D }ndd | D }t|tdd |D D ]\}}|g|_qdt
||}tt||g}|j|_t|j |j  |_|}|d}t }d|_|j|ddd |d r|d |S )a@  
    Summarize multiple results instances side-by-side (coefs and SEs)

    Parameters
    ----------
    results : statsmodels results instance or list of result instances
    float_format : str, optional
        float format for coefficients and standard errors
        Default : '%.4f'
    model_names : list[str], optional
        Must have same length as the number of results. If the names are not
        unique, a roman number will be appended to all model names
    stars : bool
        print significance stars
    info_dict : dict, default None
        dict of functions to be applied to results instances to retrieve
        model info. To use specific information for different models, add a
        (nested) info_dict with model name as the key.
        Example: `info_dict = {"N":lambda x:(x.nobs), "R2": ..., "OLS":{
        "R2":...}}` would only show `R2` for OLS regression models, but
        additionally `N` for all other results.
        Default : None (use the info_dict specified in
        result.default_model_infos, if this property exists)
    regressor_order : list[str], optional
        list of names of the regressors in the desired order. All regressors
        not specified will be appended to the end of the list.
    drop_omitted : bool, optional
        Includes regressors that are not specified in regressor_order. If
        False, regressors not specified will be appended to end of the list.
        If True, only regressors in regressor_order will be included.
    include_r2 : bool, optional
        Includes R2 and adjusted R2 in the summary table.
    c                    s   g | ]}t | d qS ))r   r%   r   )r   r3   )r%   r   r   r   r   r7      s   zsummary_col.<locals>.<listcomp>c                 S   s   g | ]}|j d  qS rx   r   r3   r   r   r   r7     s     c                 S   s   | j |ddddS )NouterT)howZright_indexZ
left_index)merger;   r   r   r   merg  s    zsummary_col.<locals>.mergr   r   Nr   r/   c                    s   g | ]}| kr|qS r   r   r3   )varnamesr   r   r7      s      c                    s   g | ]}| kr|qS r   r   r3   )regressor_orderr   r   r7   !  s      c                    s   g | ]}| kr|qS r   r   r3   )	new_orderr   r   r7   #  s    )levelr8   c                    s$   g | ]}t | |jjj qS r   )r   getrM   rN   rO   r3   )r   r   r   r7   7  s   c                 S   s   g | ]}t |t|d dqS )Zdefault_model_infosN)r   r   r3   r   r   r   r7   :  s     c                 S   s   g | ]}|j d  qS rx   r   )r4   r(   r   r   r   r7   =  s     Tr0   )r$   r&   zStandard errors in parentheses.z* p<.1, ** p<.05, ***p<.01)rL   listr   r{   rg   r   r#   r'   removeinsertr   ZreindexZget_level_valuestolistr*   r   Zvalue_countsr   rB   zipr+   r9   rC   ZIndexZfillnar	   r   r)   rK   )rQ   r%   Zmodel_namesr   r   r   Zdrop_omittedr   colsZcolnamesr}   r   r#   r   r   specialZsummZvcZordered	unorderedotherZuor   r(   namer\   datZsmryr   )r%   r   r   r   r   r   r   r   summary_col  s    %





*
 



r   c              	   C   s6   z||  }W n  t tfk
r,   t| }Y nX | S r   )
ValueError	TypeErrorr   strip)elementr%   rn   r   r   r   r2   R  s
    r2   r!   -c
                    s>  |   }
z|
 fdd}
W n& tk
rD   |
 fdd}
Y nX |r`dd |
j D }nd }|rfdd|
j D }n2fdd|
jd d df D |
jd d df< d }tt	
|
||ttd	}||jd
 d< ||jd
 d< ||jd d< ||jd d< ||jd d< ||jd d< dt|d  |jd d< |S )Nc                    s
   t |  S r   r1   r   r6   r   r   r=   _  r>   z$_df_to_simpletable.<locals>.<lambda>c                    s
   t |  S r   r1   r   r6   r   r   r=   a  r>   c                 S   s   g | ]}t |qS r   )r   r3   r   r   r   r7   c  s     z&_df_to_simpletable.<locals>.<listcomp>c                    s    g | ]}t |t d   qS r`   r   rh   r3   rj   r   r   r7   g  s     c                    s    g | ]}t |t d   qS r   r   r3   r   r   r   r7   i  s   r   )headersstubsZltx_fmtZtxt_fmtZlatexZdata_alignsZheader_alignrm   table_dec_abovetable_dec_belowheader_dec_belowr`   r   Zcolsep)copymapr   Zapplymapr   r   r#   r   r   r9   r,   r   r   Zoutput_formatsrh   )r(   r&   r%   r$   r#   r   r   r   ri   rj   r   r   r   rq   r   )r%   rj   r   _df_to_simpletableZ  s4    
 r   c                 C   s   g }|r|d d nd}|d kr.dgt |  }|d krDdgt |  }t| D ]P\}}|| d }|| d }	|| d }
|t||
||	||| || d qL|S )Nr   r%   r    r#   r$   r&   )r&   r%   r$   r#   ri   rj   )rg   	enumerater'   r   )r
   r   ri   rj   rk   r%   r}   vr#   r$   r&   r   r   r   rf   x  s$    
 
rf   )NNrS   TFr    )r    TF)N)r    r   FNr   FT)r    )	r!   r    TTr   Nr   r   r   )NN)Zstatsmodels.compat.pandasr   Zstatsmodels.compat.pythonr   r~   	functoolsr   rs   ra   Znumpyr9   Zpandasr*   r-   r   Ztableformattingr   r   r	   re   rP   rX   rW   r   r   r   r   r2   r   rf   r   r   r   r   <module>   sX    m
2    
=
'
       
z
           
