B
    Z݆                 @   s  d dl mZmZmZmZmZ d dlZd dlm	Z	 d dl
mZmZmZmZmZ d!ddZd"d
dZd#ddZd$ddZd%ddZd&ddZd'ddZd(ddZd)ddZd*ddZG dd deZed krd dlmZ ej j!" Z#e$e#j%e#_%e&e#j'e#j%( Z)dS )+    )rangelrangelmaplzipzip_longestN)SimpleTable)gen_fmtfmt_2
fmt_paramsfmt_base	fmt_2cols   c             C   sl   |dkr2t | dks t | dk r(d|  S d|  S n6|dkrdt | dksRt | dk rZd|  S d|  S ntd S )	Nr   g     @g-C6?z%9.3gz%9.3f   z%10.4gz%10.4f)absNotImplementedError)xprec r   8lib/python3.7/site-packages/statsmodels/iolib/summary.pyforg	   s    

r   皙?textc       %         s6  ddl }ddddddd	}d
d
d
d
ddd	}	|dkrB|| jjj }|dkrpy| jj}W n tk
rn   d}Y nX |dkry| jj}W n, tk
r   dd tt| j	D }Y nX |
 }
|d|
g}|d|
}| jjj}| j}| j}| j}d|gfd|gfd|fd|gfg}t| \}}|}d}t||||td}d}|g||g|gf}t||||td}|| ||  |  |  |  |  |  d	}| j| j| j| j| j| jd	}td| d d }dddd|d gdddd|d gdddd|d gdddd|d gdddd|d gdddd |d gd!}|}| j	| | | jtt|}|| || tfd"d|D fd#d|D fd$d|D fd%d|D  fd&d|D } t| || |dtdfd'd(}!d)d* }"fd+d,}#|!|#d-}$|d.kr2y
|$|  S  tk
r0   |$d/  S X dS )0a  
    Parameters
    -----------
    yname : string
            optional, Default is `Y`
    xname : list of strings
            optional, Default is `X.#` for # in p the number of regressors
    Confidance interval : (0,1) not implimented
    title : string
            optional, Defualt is 'Generalized linear model'
    returns : string
              'text', 'table', 'csv', 'latex', 'html'

    Returns
    -------
    Default :
    returns='print'
            Prints the summarirized results

    Option :
    returns='text'
            Prints the summarirized results

    Option :
    returns='table'
             SimpleTable instance : summarizing the fit of a linear model.

    Option :
    returns='csv'
            returns a string of csv of the results, to import into a spreadsheet

    Option :
    returns='latex'
    Not implimented yet

    Option :
    returns='HTML'
    Not implimented yet


    Examples (needs updating)
    --------
    >>> import statsmodels as sm
    >>> data = sm.datasets.longley.load()
    >>> data.exog = sm.add_constant(data.exog)
    >>> ols_results = sm.OLS(data.endog, data.exog).results
    >>> print ols_results.summary()
    ...

    Notes
    -----
    conf_int calculated from normal dist.
    r   NzOrdinary least squareszGeneralized least squaresz$Generalized least squares with AR(p)zWeighted least squareszRobust linear modelzGeneralized linear model)OLSGLSGLSARWLSRLMGLMzLeast Squares?yc             S   s   g | ]}d | qS )zvar_%dr   ).0ir   r   r   
<listcomp>n   s    zsummary.<locals>.<listcomp>z%H:%M:%Sz%a, %d %b %YzModel type:zDate:zDependent Variable:zdf model)titletxt_fmt)zMethod:zTime:zNumber of Obs:zdf resid   d   %coefzstd errtzP>|t|z Conf. IntervalzzP>|z|)r   r   r   r   r   r   c                s   g | ]}d  |  qS )z%#6.4gr   )r    r!   )paramsr   r   r"      s    c                s   g | ]}d  |  qS )z%#6.4fr   )r    r!   )std_errr   r   r"      s    c                s   g | ]}d  |  qS )z%#6.4fr   )r    r!   )tstatr   r   r"      s    c                s   g | ]}d  |  qS )z%#6.4fr   )r    r!   )	prob_statr   r   r"      s    c                s   g | ]}d t  |  qS )z(%#5g, %#5g))tuple)r    r!   )conf_intr   r   r"      s    c                 s   t  d t  } | S )z4
        print summary table for ols models
        
)str)table)general_tableparameter_tabler   r   ols_printer   s    zsummary.<locals>.ols_printerc               S   s   dS )z1
        exports ols summary data to csv
        Nr   r   r   r   r   
ols_to_csv   s    zsummary.<locals>.ols_to_csvc                 s   t  d t  } | S )Nr1   )r2   )r3   )r4   r5   r   r   glm_printer   s    zsummary.<locals>.glm_printer)r   r   printr   )timemodel	__class____name__endog_namesAttributeError
exog_namesr   lenr+   	localtimestrftimenobsdf_modeldf_residr   r   r   extend_rightr)   pvaluesr2   r0   bser   r   r	   KeyError)%selfynamexnamer#   alphaZreturnsZ
model_infor:   Zmodel_typesZmodel_methodstime_nowtime_of_daydateZ	modeltyperD   rE   rF   gen_leftgen_stubs_leftgen_data_left	gen_title
gen_headergen_table_leftgen_stubs_rightgen_data_rightgen_table_rightZtstatsZ
prob_statsalpparam_headerparams_stubsZexog_lenparams_datar6   r7   r8   Zprintersr   )r0   r4   r5   r+   r.   r,   r-   r   summary   s    7








r_   c             C   sx   |dkr.t | jdr*| jjdk	r*| jj}nd}|dkrpt | jdrX| jjdk	rX| jj}ndd tt| jD }||fS )z0extract names from model or construct names
    Nr>   r   r@   c             S   s   g | ]}d | qS )zvar_%dr   )r    r!   r   r   r   r"     s    z_getnames.<locals>.<listcomp>)hasattrr;   r>   r@   r   rA   r+   )rK   rL   rM   r   r   r   	_getnames  s    

ra   c                s  || }}ddl }| }	|d|	g|d|	 t|d\}tdfddfd	fd
dfdfddfd fddfdfddfdfddfdfddfdfddfdfddfdfddfg
}
|dkrjjjd }|dkr0ddddd d!g}yj}|	d" W n   Y nX g }|}d}g }x4|D ],\}}|dkr^|
|  }|	||f qBW |}|rg }x4|D ],\}}|dkr|
|  }|	||f qW |}d#d$ || D }|g kst
||rlt|t|k r|d%gt|t|  7 }n,t|t|kr>|d%gt|t|  7 }d&d$ |D }t| \}}t||||td'}ng }t| \}}t||||td'}|| |}|S )(zgenerate top table(s)


    TODO: this still uses predefined model_methods
    ? allow gleft, gright to be 1 element tuples instead of filling with None?

    r   Nz%H:%M:%Sz%a, %d %b %Y)rL   rM   zDependent Variable:c                  s    gS )Nr   r   )rL   r   r   <lambda>.  s    zsummary_top.<locals>.<lambda>zDep. Variable:c                  s    gS )Nr   r   )rL   r   r   rb   /  s    zModel:c                  s    j jjgS )N)r;   r<   r=   r   )resultsr   r   rb   0  s    zDate:c                  s    gS )Nr   r   )rQ   r   r   rb   2  s    zTime:c                  s    S )Nr   r   )rP   r   r   rb   3  s    zNumber of Obs:c                  s    j gS )N)rD   r   )rc   r   r   rb   4  s    zNo. Observations:c                  s   d j  gS )Nz%#6d)rD   r   )rc   r   r   rb   6  s    z	Df Model:c                  s   d j  gS )Nz%#6d)rE   r   )rc   r   r   rb   8  s    zDf Residuals:c                  s   d j  gS )Nz%#6d)rF   r   )rc   r   r   rb   :  s    zLog-Likelihood:c                  s   d j  gS )Nz%#8.5g)llfr   )rc   r   r   rb   =  s    zRegression Results)zDep. Variable:N)zModel type:N)zDate:N)zNo. Observations:N)z	Df model:N)z	Df resid:N)zLog-LikelihoodNc             S   s   g | ]\}}|d kr|qS )Nr   )r    kvr   r   r   r"   k  s    zsummary_top.<locals>.<listcomp>) rg   c             S   s    g | ]\}}d d|  |fqS )z%-21sz  r   )r    re   rf   r   r   r   r"   y  s    )r#   r$   )r:   rB   rC   ra   dictr;   r<   r=   rd   appendAssertionErrorrA   r   r   r   rG   )rc   r#   gleftgrightrL   rM   rR   Z	gen_rightr:   rO   Zdefault_itemsrd   rU   rV   Z	gen_left_itemvalueZ
gen_right_Zmissing_valuesrX   rY   rZ   rS   rT   rW   r4   r   )rQ   rc   rP   rL   r   summary_top  s    	







ro   TFc          	      sZ  t | tr| \}  n"| j| j| j| j| | |rpdddddt|d  td|d  d g}n,ddd	d
dt|d  td|d  d g}|rd}t| ||d\}}t	|t	krt
d|}	tt	|}
tfdd|
D fdd|
D fdd|
D fdd|
D  fdd|
D  fdd|
D }t|||	|td}|S )a,  create a summary table for the parameters

    Parameters
    ----------
    res : results instance
        some required information is directly taken from the result
        instance
    yname : string or None
        optional name for the endogenous variable, default is "y"
    xname : list of strings or 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_headers : bool
        If false (default), then the header row is added. If true, then no
        header row is added.

    Returns
    -------
    params_table : SimpleTable instance
    r(   zstd errr)   zP>|t|[   r%   ]r*   zP>|z|N)rL   rM   z-xnames and params do not have the same lengthc                s   g | ]}t  | d dqS )r   )r   )r   )r    r!   )r+   r   r   r"     s    z"summary_params.<locals>.<listcomp>c                s   g | ]}t  | qS r   )r   )r    r!   )r,   r   r   r"     s    c                s   g | ]}t  | qS r   )r   )r    r!   )tvaluesr   r   r"     s    c                s   g | ]}d  |  qS )z%#6.3fr   )r    r!   )rH   r   r   r"     s    c                s   g | ]}t  |d f qS )r   )r   )r    r!   )r0   r   r   r"     s    c                s   g | ]}t  |d f qS )r%   )r   )r    r!   )r0   r   r   r"     s    )r#   r$   )
isinstancer/   r+   rI   rs   rH   r0   r2   ra   rA   
ValueErrorr   r   r   r
   )rc   rL   rM   rN   use_tskip_headerr#   r\   _r]   Zexog_idxr^   r5   r   )r0   r+   rH   r,   rs   r   summary_params  s>    

&$ry   c             C   s   t | tr| \} }}}}}	n"| j}| j}| j}| j}| |}	td| d d }
|rhdddddd	g}nddd
ddd	g}t| ||d\}}ddl	m
} t|||||	f}||||dS )a,  create a summary table for the parameters

    Parameters
    ----------
    res : results instance
        some required information is directly taken from the result
        instance
    yname : string or None
        optional name for the endogenous variable, default is "y"
    xname : list of strings or 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_headers : bool
        If false (default), then the header row is added. If true, then no
        header row is added.

    Returns
    -------
    params_table : SimpleTable instance
    r%   r&   r'   r(   zstd errr)   zP>|t|zConf. Int. LowzConf. Int. Upp.r*   zP>|z|)rL   rM   r   )	DataFrame)columnsindex)rt   r/   r+   rI   rs   rH   r0   r2   ra   Zpandasrz   npZcolumn_stack)rc   rL   rM   rN   rv   r+   r,   rs   rH   r0   r[   r\   rx   rz   r3   r   r   r   summary_params_frame  s"    


r~   c                s  |dkr(dd t  jjdd D }|dkrHdd tt jD }dd  jD }|r fdd|D }t|f| }dd |D }t|fd	gt| gt|  }d
d |D }n|}|}ddl}	|		t
}
|
tdg jjd  d t|||||
dS )a  create summary table of regression parameters with several equations

    This allows interleaving of parameters with bse and/or tvalues

    Parameters
    ----------
    result : result instance
        the result instance with params and attributes in extras
    extras : list of strings
        additional attributes to add below a parameter row, e.g. bse or tvalues
    endog_names : None or list of strings
        names for rows of the parameter array (multivariate endog)
    exog_names : None or list of strings
        names for columns of the parameter array (exog)
    alpha : float
        level for confidence intervals, default 0.95
    title : None or string

    Returns
    -------
    tables : list of SimpleTable
        this contains a list of all seperate Subtables
    table_all : SimpleTable
        the merged table with results concatenated for each row of the parameter
        array

    Nc             S   s   g | ]}d | qS )zendog_%dr   )r    r!   r   r   r   r"   I  s    z%summary_params_2d.<locals>.<listcomp>r%   c             S   s   g | ]}d | qS )zvar%dr   )r    r!   r   r   r   r"   L  s    c             S   s   g | ]}d d |D qS )c             S   s   g | ]}t |d dqS )r   )r   )r   )r    rm   r   r   r   r"   P  s    z0summary_params_2d.<locals>.<listcomp>.<listcomp>r   )r    rowr   r   r   r"   P  s    c                s    g | ]}d d t  |D qS )c             S   s   g | ]}d d |D qS )c             S   s(   g | ] }d dt |dd  d  qS )z%10s(r   )r   ))r   strip)r    rf   r   r   r   r"   T  s   z;summary_params_2d.<locals>.<listcomp>.<listcomp>.<listcomp>r   )r    colr   r   r   r"   T  s   z0summary_params_2d.<locals>.<listcomp>.<listcomp>)getattr)r    Zwhat)resultr   r   r"   T  s   c             S   s   g | ]}|D ]}|qqS r   r   )r    jr!   r   r   r   r"   Z  s     c             S   s   g | ]}|D ]}|qqS r   r   )r    r   r!   r   r   r   r"   \  s    r   z%s)Z	data_fmts)Zheadersstubsr#   r$   )r}   uniquer;   endogr   rA   r+   r   copydeepcopyr
   updaterh   shaper   )r   Zextrasr>   r@   r#   Z
res_paramsZextras_listdatar   r   r$   r   )r   r   summary_params_2d*  s,    
"
r   c          	   C   sJ  | }|j }|jdkr:|jd }	t||jd ksVtdnt|t|ksRtdd}	t|ts|dkrnd}
n|}
|jjdd }g }xt	|	D ]|}||j dd|f |j
dd|f |jdd|f |jdd|f ||| f}d}t||| ||||d}|| qW x$t	t|D ]}|| || _qW t||d}||fS )	a  summary table for parameters that are 2d, e.g. multi-equation models

    Parameters
    ----------
    result : result instance
        the result instance with params, bse, tvalues and conf_int
    endog_names : None or list of strings
        names for rows of the parameter array (multivariate endog)
    exog_names : None or list of strings
        names for columns of the parameter array (exog)
    alpha : float
        level for confidence intervals, default 0.95
    use_t : bool
        indicator whether the p-values are based on the Student-t
        distribution (if True) or on the normal distribution (if False)
    keep_headers : bool
        If true (default), then sub-tables keep their headers. If false, then
        only the first headers are kept, the other headerse are blanked out
    endog_cols : bool
        If false (default) then params and other result statistics have
        equations by rows. If true, then equations are assumed to be in columns.
        Not implemented yet.

    Returns
    -------
    tables : list of SimpleTable
        this contains a list of all seperate Subtables
    table_all : SimpleTable
        the merged table with results concatenated for each row of the parameter
        array

    rq   r%   zendog_names has wrong lengthNr   F)rL   rM   rN   rv   rw   )keep_headers)r+   ndimr   rA   ru   rt   listr;   r>   r   rI   rs   rH   r0   ry   ri   r#   table_extend)r   r>   r@   rN   rv   r   Z
endog_colsresr+   Zn_equZendog_basenametableseqZrestupZskiphZtbler!   	table_allr   r   r   summary_params_2dflatn  s6    $



2 
r   c             C   s   ddl m} xt| dd D ]\}}||}|d jdkr|j|d d _d|d d _|d d j|d d _|s|dkrx|d dd D ]
}d|_qW |dkr|}q|d }|jdd	d
 |	| qW d|_|S )a  extend a list of SimpleTables, adding titles to header of subtables

    This function returns the merged table as a deepcopy, in contrast to the
    SimpleTable extend method.

    Parameters
    ----------
    tables : list of SimpleTable instances
    keep_headers : bool
        If true, then all headers are kept. If falls, then the headers of
        subtables are blanked out.

    Returns
    -------
    table_all : SimpleTable
        merged tables as a single SimpleTable instance

    r   )r   Nheaderr%   r   txt-)Zrow_dec_below)
r   r   	enumerateZdatatyper#   r   Z	_datatyper   Z
add_formatextend)r   r   r   Ziir)   cr   Zr1r   r   r   r     s"    
r   c             C   s   |dkr6dd }d t|| d d t| d g S |dkrB| S |dkr^d tdd | S |d	krd
d l}|| d
 }|d= x| dd  D ]}|| qW | S |dkrd dd | D S tdd S )Nr   c             S   s   t | ddd S )Nr1   r%   r   )r2   rsplit)r   r   r   r   rb     s    z summary_return.<locals>.<lambda>r1   r   r   csvc             S   s   |   S )N)as_csv)r   r   r   r   rb     s    latexr   r%   htmlc             s   s   | ]}|  V  qd S )N)as_html)r    r3   r   r   r   	<genexpr>  s    z!summary_return.<locals>.<genexpr>z3available output formats are text, csv, latex, html)	joinr   r2   mapr   r   r   Zas_latex_tabularru   )r   
return_fmtZstrdropr   r3   partr   r   r   summary_return  s"    &r   c               @   sl   e Zd ZdZdd Zdd Zdd Zdd	 ZdddZdddZ	dd Z
dd Zdd Zdd Zdd Zd
S )Summarya  class to hold tables for result summary presentation

    Construction does not take any parameters. Tables and text can be added
    with the `add_` methods.

    Attributes
    ----------
    tables : list of tables
        Contains the list of SimpleTable instances, horizontally concatenated tables are not saved separately.
    extra_txt : string
        extra lines that are added to the text output, used for warnings and explanations.
    c             C   s   g | _ d | _d S )N)r   	extra_txt)rK   r   r   r   __init__  s    zSummary.__init__c             C   s   |   S )N)as_text)rK   r   r   r   __str__  s    zSummary.__str__c             C   s   t t| d |   d S )Nz
"""
z
""")r2   typer   )rK   r   r   r   __repr__  s    zSummary.__repr__c             C   s   |   S )z$Display as HTML in IPython notebook.)r   )rK   r   r   r   _repr_html_#  s    zSummary._repr_html_Nc             C   s$   t ||||||d}| j| dS )ar  add a double table, 2 tables with one column merged horizontally

        Parameters
        ----------
        res : results instance
            some required information is directly taken from the result
            instance
        title : string or None
            if None, then a default title is used.
        gleft : list of tuples
            elements for the left table, tuples are (name, value) pairs
            If gleft is None, then a default table is created
        gright : list of tuples or None
            elements for the right table, tuples are (name, value) pairs
        yname : string or None
            optional name for the endogenous variable, default is "y"
        xname : list of strings or None
            optional names for the exogenous variables, default is "var_xx"

        Returns
        -------
        None : tables are attached

        )r#   rk   rl   rL   rM   N)ro   r   ri   )rK   r   r#   rk   rl   rL   rM   r3   r   r   r   add_table_2cols'  s    

zSummary.add_table_2cols皙?Tc             C   s\   |j jdkr t|||||d}n,|j jdkrDt|||||d\}}ntd| j| dS )a  create and add a table for the parameter estimates

        Parameters
        ----------
        res : results instance
            some required information is directly taken from the result
            instance
        yname : string or None
            optional name for the endogenous variable, default is "y"
        xname : list of strings or 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)

        Returns
        -------
        None : table is attached

        r%   )rL   rM   rN   rv   rq   )r>   r@   rN   rv   zparams has to be 1d or 2dN)r+   r   ry   r   ru   r   ri   )rK   r   rL   rM   rN   rv   r3   rx   r   r   r   add_table_paramsF  s    

zSummary.add_table_paramsc             C   s   d || _dS )zadd additional text that will be added at the end in text format

        Parameters
        ----------
        etext : list[str]
            string with lines that are added to the text output.

        r1   N)r   r   )rK   Zetextr   r   r   add_extra_txtk  s    	zSummary.add_extra_txtc             C   s*   t | jdd}| jdk	r&|d | j }|S )zreturn tables as string

        Returns
        -------
        txt : string
            summary tables and extra text as one string

        r   )r   Nz

)r   r   r   )rK   r   r   r   r   r   v  s    	
zSummary.as_textc             C   s2   t | jdd}| jdk	r.|d | jdd }|S )aY  return tables as string

        Returns
        -------
        latex : string
            summary tables and extra text as string of Latex

        Notes
        -----
        This currently merges tables with different number of columns.
        It is recommended to use `as_latex_tabular` directly on the individual
        tables.

        r   )r   Nz

r1   z \newline
 )r   r   r   replace)rK   r   r   r   r   as_latex  s    
zSummary.as_latexc             C   s*   t | jdd}| jdk	r&|d | j }|S )zreturn tables as string

        Returns
        -------
        csv : string
            concatenated summary tables in comma delimited format

        r   )r   Nz

)r   r   r   )rK   r   r   r   r   r     s    	
zSummary.as_csvc             C   s2   t | jdd}| jdk	r.|d | jdd }|S )zreturn tables as string

        Returns
        -------
        html : string
            concatenated summary tables in HTML format

        r   )r   Nz
<br/><br/>r1   z<br/>)r   r   r   r   )rK   r   r   r   r   r     s    	
zSummary.as_html)NNNNN)NNr   T)r=   
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s    
 
$r   __main__)r   )NNr   r   r   N)NN)NNNNN)NNr   TFN)NNr   T)NNNN)NNr   TTF)T)r   )*Zstatsmodels.compat.pythonr   r   r   r   r   Znumpyr}   Zstatsmodels.iolib.tabler   Z!statsmodels.iolib.tableformattingr   r	   r
   r   r   r   r_   ra   ro   ry   r~   r   r   r   r   objectr   r=   Zstatsmodels.apiZapiZsmZdatasetsZlongleyloadr   Zadd_constantZexogr   r   Zfitr   r   r   r   r   <module>   s6   
 
 i

  
R 
? 
C 
V
-
 +
