
p7]c           @   s  d  Z  d d l Z d d l m Z m Z m Z m Z m Z m Z m	 Z	 m
 Z
 m Z m Z m Z d d l m Z m Z m Z d d l m Z d d l Z d d l Z d d l Z d d l j j Z d d l m Z d d l m Z d d l  m! Z! d	 d
 d d d d d d g Z" d   Z# d   Z$ d e% f d     YZ& d e% f d     YZ' d   Z( d   Z) d   Z* d   Z+ d   Z, d   Z- d   Z. i e j d 6e/ d 6Z0 d  e% f d!     YZ1 d" e2 e3 e4 d#  Z5 e2 d$ d% d&  Z6 d S('   s   
Input/Output tools for working with binary data.

The Stata input tools were originally written by Joe Presbrey as part of PyDTA.

You can find more information here http://presbrey.mit.edu/PyDTA

See Also
--------
numpy.lib.io
iN(   t   zipt   lzipt   lmapt   lranget   string_typest   longt   lfiltert   asbytest   asstrt   ranget   PY3(   t   unpackt   calcsizet   pack(   t   error(   t   isnull(   t   StataMissingValue(   t   get_file_objs   %tcs   %tCs   %tds   %tws   %tms   %tqs   %ths   %tyc         C   s  t  |  t j  s! t d   n  t j d d d  } | d" k rm |  | } | j d | j d | j d S| d# k r d
 d l m } | d t  |  S| d$ k r |  | j S| d% k r d |  j	 | j	 |  t j |  j	 d d  j d S| d& k rd |  j	 | j	 |  j
 d S| d' k rLd |  j	 | j	 t |  j
 d d  S| d( k r}d |  j	 | j	 t |  j
 d k  S| d) k r|  j	 St d  |   d! S(*   s#  
    Convert from datetime to SIF. http://www.stata.com/help.cgi?datetime

    Parameters
    ----------
    date : datetime.datetime
        The date to convert to the Stata Internal Format given by fmt
    fmt : str
        The format to convert to. Can be, tc, td, tw, tm, tq, th, ty
    s'   date should be datetime.datetime formati  i   s   %tct   tci \&i  s   %tCt   tCi(   t   warns'   Stata Internal Format tC not supported.s   %tdt   tds   %twt   twi4   i   s   %tmt   tmi   s   %tqt   tqi   i   s   %tht   thi   i   s   %tyt   tys   fmt %s not understoodN(   s   %tcR   (   s   %tCR   (   s   %tdR   (   s   %twR   (   s   %tmR   (   s   %tqR   (   s   %thR   (   s   %tyR   (   t
   isinstancet   datetimet
   ValueErrort   dayst   secondst   microsecondst   warningsR   t   UserWarningt   yeart   montht   int(   t   datet   fmtt   stata_epocht   deltaR   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _datetime_to_stata_elapsed   s2    
"'%c         C   s  t  |   }  t j d d d  } | d$ k rR d d l m } | | d |  d  S| d% k r d d l m } | d t  |  S| d& k r | t j t  |    S| d' k r t j | j |  d d d  } |  d d } | t j t  |   S| d( k r1| j |  d } |  d d } t j | | d  S| d) k rs| j |  d } |  d d d } t j | | d  S| d* k r| j |  d } |  d d d } t j | | d  S| d+ k r|  d  k rt j |  d d  St	 d!   n t	 d" |   d# S(,   s  
    Convert from SIF to datetime. http://www.stata.com/help.cgi?datetime

    Parameters
    ----------
    date : int
        The Stata Internal Format date to convert to datetime according to fmt
    fmt : str
        The format to convert to. Can be, tc, td, tw, tm, tq, th, ty

    Examples
    --------
    >>> _stata_elapsed_date_to_datetime(52, "%tw")                                datetime.datetime(1961, 1, 1, 0, 0)

    Notes
    -----
    datetime/c - tc
        milliseconds since 01jan1960 00:00:00.000, assuming 86,400 s/day
    datetime/C - tC - NOT IMPLEMENTED
        milliseconds since 01jan1960 00:00:00.000, adjusted for leap seconds
    date - td
        days since 01jan1960 (01jan1960 = 0)
    weekly date - tw
        weeks since 1960w1
        This assumes 52 weeks in a year, then adds 7 * remainder of the weeks.
        The datetime value is the start of the week in terms of days in the
        year, not ISO calendar weeks.
    monthly date - tm
        months since 1960m1
    quarterly date - tq
        quarters since 1960q1
    half-yearly date - th
        half-years since 1960h1 yearly
    date - ty
        years since 0000

    If you don't have pandas with datetime support, then you can't do
    milliseconds accurately.
    i  i   s   %tcR   i(   t   relativedeltaR    i  s   %tCR   (   R   s9   Encountered %tC format. Leaving in Stata Internal Format.s   %tdR   s   %twR   i4   i   s   %tmR   i   s   %tqR   i   i   s   %thR   i   i   s   %tyR   i    s!   Year 0 and before not implementeds   Date fmt %s not understoodN(   s   %tcR   (   s   %tCR   (   s   %tdR   (   s   %twR   (   s   %tmR   (   s   %tqR   (   s   %thR   (   s   %tyR   (
   R%   R   t   dateutil.relativedeltaR+   R!   R   R"   t	   timedeltaR#   R   (   R&   R'   R(   R+   R   R#   t	   day_deltat   month_delta(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _stata_elapsed_date_to_datetimeC   sB    - t   _StataVariablec           B   s   e  Z d  Z d   Z d   Z d   Z e d   d d Z e d   d d Z e d	   d d
 Z	 e d   d d Z
 e d   d d Z e d   d d Z e j e _ e	 j e _ RS(   s'  
    A dataset variable.  Not intended for public use.

    Parameters
    ----------
    variable_data

    Attributes
    ----------
    format : str
        Stata variable format.  See notes for more information.
    index : int
        Zero-index column index of variable.
    label : str
        Data Label
    name : str
        Variable name
    type : str
        Stata data type.  See notes for more information.
    value_format : str
        Value format.

    Notes
    -----
    More information: http://www.stata.com/help.cgi?format
    c         C   s   | |  _  d  S(   N(   t   _data(   t   selft   variable_data(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   __init__   s    c         C   s   |  j  S(   N(   t   index(   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   __int__   s    c         C   s   |  j  S(   N(   t   name(   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   __str__   s    c         C   s   |  j  d S(   Ni    (   R2   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   <lambda>   t    t   docs*   the variable's index within an observationc         C   s   |  j  d S(   Ni   (   R2   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:      R;   sh   the data type of variable

Possible types are:
{1..244:string, b:byte, h:int, l:long, f:float, d:double)c         C   s   |  j  d S(   Ni   (   R2   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:      R;   s   the name of the variablec         C   s   |  j  d S(   Ni   (   R2   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:      R;   s   the variable's Stata formatc         C   s   |  j  d S(   Ni   (   R2   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:      R;   s   the variable's value formatc         C   s   |  j  d S(   Ni   (   R2   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:      R;   s   the variable's label(   t   __name__t
   __module__t   __doc__R5   R7   R9   t   propertyR6   t   typeR8   t   formatt   value_formatt   label(    (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR1      s    							t   StataReaderc           B   s  e  Z d  Z i  Z d Z d) Z e Z e Z e	 e
 e d d  g  e d d  D] Z d e e  ^ qL  d e j f d e j f d e f d e j f d	 e j f g  Z e d  e d
  Z i d* d 6d+ d 6d, d 6d d 
f d 6d d 
f d 6Z e d- d  Z d   Z d   Z d   Z d   Z d   Z e d   Z  d!   Z! d"   Z" d#   Z# d$   Z$ d%   Z% d- d&  Z& d'   Z' d(   Z( RS(.   sJ  
    Stata .dta file reader.

    Provides methods to return the metadata of a Stata .dta file and
    a generator for the data itself.

    Parameters
    ----------
    file : file-like
        A file-like object representing a Stata .dta file.
    missing_values : bool
        If missing_values is True, parse missing_values and return a
        Missing Values object instead of None.
    encoding : string, optional
        Used for Python 3 only. Encoding to use when reading the .dta file.
        Defaults to `locale.getpreferredencoding`

    See Also
    --------
    statsmodels.iolib.foreign.genfromdta
    pandas.read_stata
    pandas.io.stata.StataReader

    Notes
    -----
    This is known only to work on file formats 113 (Stata 8/9), 114
    (Stata 10/11), and 115 (Stata 12).  Needs to be tested on older versions.
    Known not to work on format 104, 108. If you have the documentation for
    older formats, please contact the developers.

    For more information about the .dta format see
    http://www.stata.com/help.cgi?dta
    http://www.stata.com/help.cgi?dta_113
    i    i   i   t   ai   i   i   i   i   t   bhlfdiid   t   bii  t   hi  it   lg_g_Gt   fg      gYt   dc         C   s]   t  j d t  | d  k r: d d  l } | j   |  _ n	 | |  _ | |  _ |  j |  d  S(   Ns   StataReader is deprecated as of 0.10.0 and will be removed in a future version.  Use pandas.read_stata or pandas.io.stata.StataReader instead.i(	   R!   R   t   FutureWarningt   Nonet   localet   getpreferredencodingt	   _encodingt   _missing_valuest   _parse_header(   R3   t   fnamet   missing_valuest   encodingRO   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR5     s    		c         C   s   |  j  S(   s   
        Returns all .dta file headers.

        out: dict
            Has keys typlist, data_label, lbllist, varlist, nvar, filetype,
            ds_format, nobs, fmtlist, vlblist, time_stamp, srtlist, byteorder
        (   t   _header(   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   file_headers  s    c         C   s   |  j  d S(   s   
        Returns the file format.

        Returns
        -------
        out : int

        Notes
        -----
        Format 113: Stata 8/9
        Format 114: Stata 10/11
        Format 115: Stata 12
        t	   ds_format(   RW   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   file_format$  s    c         C   s   |  j  d S(   sc   
        Returns the dataset's label.

        Returns
        -------
        out: string
        t
   data_label(   RW   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt
   file_label4  s    c         C   s   |  j  d S(   s   
        Returns the date and time Stata recorded on last file save.

        Returns
        -------
        out : str
        t
   time_stamp(   RW   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   file_timestamp>  s    c         C   s\   t  t t t |  j d  |  j d |  j d |  j d |  j d |  j d |  j d   S(   sI   
        Returns a list of the dataset's StataVariables objects.
        t   nvart   typlistt   varlistt   srtlistt   fmtlistt   lbllistt   vlblist(   R   R1   R    R   RW   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt	   variablesH  s
    
c         c   s   y |  j  j |  j  Wn t k
 r* n X| r t t |  j    } x` t t |    D]  } t	 t
 | |  j     VqY Wn) x& t |  j d  D] } |  j   Vq Wd S(   s  
        Returns a Python generator object for iterating over the dataset.


        Parameters
        ----------
        as_dict : bool, optional
            If as_dict is True, yield each row of observations as a dict.
            If False, yields each row of observations as a list.

        Returns
        -------
        Generator object for iterating over the dataset.  Yields each row of
        observations as a list by default.

        Notes
        -----
        If missing_values is True during instantiation of StataReader then
        observations with StataMissingValue(s) are not filtered and should
        be handled by your applcation.
        t   nobsN(   t   _filet   seekt   _data_locationt	   ExceptionR   t   strRf   R	   t   lent   dictR    t   _nextRW   (   R3   t   as_dictt   varst   i(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   datasetR  s    !c         C   s   |  j  d S(   s   
        Return the number of observations in the dataset.

        This value is taken directly from the header and includes observations
        with missing values.
        Rg   (   RW   (   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   __len__x  s    c         C   s   t  | t t f  s8 | d k  s8 | t |   d k rG t |   n  |  j t |  j    | } |  j j	   | k r |  j j
 |  n  |  j   S(   s   
        Seek to an observation indexed k in the file and return it, ordered
        by Stata's output to the .dta file.

        k is zero-indexed.  Prefer using R.data() for performance.
        i    i   (   R   R%   R   Rm   t
   IndexErrorRj   t   sumt	   _col_sizeRh   t   tellRi   Ro   (   R3   t   kt   loc(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   __getitem__  s    8c         C   s   t  rI t d  } y  | j |  | j |   } Wn n X| j |  St d  } y | j |  | j |   SWn | SXd  S(   Ns    (   R
   R   t   lstripR6   t   decode(   R3   t   sRV   t	   null_byte(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _null_terminate  s     c   
      C   s9  | |  _  |  j } t d |  j  j d   d |  j d <|  j d d# k re t d |  j d   n  t d |  j  j d   d d k r d	 p d
 } |  j d <t d |  j  j d   d |  j d <|  j  j d  t | d |  j  j d   d } |  j d <t | d |  j  j d   d |  j d <|  j |  j  j d  |  |  j d <|  j |  j  j d  |  |  j d <g  t |  D] } t |  j  j d   ^ q} g  | D] } |  j	 | ^ q|  j d <g  | D] } |  j
 | ^ q|  j d <g  t |  D]$ } |  j |  j  j d  |  ^ q|  j d <t | d | d |  j  j d | d   d  |  j d <|  j d d k rg  t |  D]$ } |  j |  j  j d  |  ^ q|  j d <n> g  t |  D]$ } |  j |  j  j d  |  ^ q|  j d <g  t |  D]$ } |  j |  j  j d  |  ^ q|  j d  <g  t |  D]$ } |  j |  j  j d  |  ^ qM|  j d! <xp t rt | d |  j  j d   d } t | d |  j  j d   d }	 | d k rPn  |  j  j |	  qW|  j  j   |  _ t t d"   |  j d   d k |  _ |  j   d  S($   NRH   i   i    RY   iq   ir   is   sy   Only file formats >= 113 (Stata >= 9) are supported.  Got format %s.  Please report if you think this error is incorrect.t   >t   <t	   byteordert   filetypeRI   i   R_   Rr   i   Rg   iQ   R[   i   R]   R`   t   dtyplisti!   Ra   iRb   i   Rc   i1   Rd   Re   c         S   s   t  |  t  S(   N(   R   R%   (   t   x(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:     R;   (   iq   ir   is   (   Rh   RQ   R   t   readRW   R   R   R	   t   ordt   TYPE_MAPt	   DTYPE_MAPt   TrueRx   Rj   Rm   R   t   _has_string_dataRw   (
   R3   t   file_objectRV   R   R_   Rr   R`   t   typt	   data_typet   data_len(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyRS     sV    		&6&
$*1'';(>;;;	##c         C   s*   t  | t  r | p) t |  j d |  S(   NR   (   R   R%   R   RW   (   R3   R'   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt	   _calcsize  s    c            s\   t    j  d k r: t   f d     j d    _ n  | d k rM   j S  j | Sd S(   s    Calculate size of a data record.i    c            s     j  |   S(   N(   R   (   R   (   R3   (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:     R;   R`   N(   Rm   t
   _col_sizesR   RW   RN   (   R3   Ry   (    (   R3   s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyRw     s    c         C   s   t  |  j d | |  d } | d |  j k r |  j | d \ } } | | k  s` | | k r |  j rv t | |  Sd  Sq n  | S(   NR   i    i(   R   RW   t   MISSING_VALUESRR   R   RN   (   R3   R'   t   bytRL   t   nmint   nmax(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _unpack  s    	
c            s     j  d    j r d  g   j  d } x t t |   D]t } t  | t  r   j   j j	  |    j
  | | <q=   j  |   j j	   j |    | | <q= W| St    f d   t   j  d   Sd  S(   NR`   R_   c            s)     j   |    j j   j |     S(   N(   R   Rh   R   Rw   (   Rr   (   R3   R`   (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:     s   (   RW   R   RN   R	   Rm   R   R%   R   Rh   R   RQ   R   Rw   R   R   (   R3   t   dataRr   (    (   R3   R`   s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyRo     s    	&(    (   iid   (   ii  (   i  iN()   R=   R>   R?   RW   Rj   R   t   FalseR   RR   Rn   R   R   R	   Rr   Rl   t   npt   int16t   int32R%   t   float32t   float64R   t   listR   R   RN   R5   RX   RZ   R\   R^   Rf   Rs   Rt   R{   R   RS   R   Rw   R   Ro   (    (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyRE      s8   ">!"	
		
	
	
&					?	
	c         C   s@   |  j    d k r d S|  j    d k r, d St d |    d  S(   NR   t   littleR   t   bigs   Endianness %s not understood(   R   R   (   R   R   (   t   lowerR   (   t
   endianness(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _set_endianness	  s
    c         C   s   |  j  t j k r t |  j  S|  j  t j k r; t d  S|  t j k rT t d  S|  t j k rm t d  S|  t j k r t d  S|  t j	 k r t d  S|  t j
 k s |  t j k r t d  St d |    d S(	   s  
    Converts dtype types to stata types. Returns the byte of the given ordinal.
    See TYPE_MAP and comments for an explanation. This is also explained in
    the dta spec.
    1 - 244 are strings of this length
    251 - chr(251) - for int8 and int16, byte
    252 - chr(252) - for int32, int
    253 - chr(253) - for int64, long
    254 - chr(254) - for float32, float
    255 - chr(255) - double, double

    If there are dates to convert, then dtype will already have the correct
    type inserted.
    i   i   i   i   i   i   sP   Data type %s not currently understood. Please report an error to the developers.N(   RA   R   t   string_t   chrt   itemsizet   object_R   R   t   int64R   t   int8R   R   (   t   dtype(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _dtype_to_stata_type  s     





c         C   s   |  j  t j k r' d t |  j  d S|  j  t j k r= d S|  t j k rP d S|  t j k rc d S|  t j k rv d S|  t j	 k r d S|  t j
 k s |  t j k r d St d |    d S(	   sY  
    Maps numpy dtype to stata's default format for this type. Not terribly
    important since users can change this in Stata. Semantics are

    string  -> "%DDs" where DD is the length of the string
    float64 -> "%10.0g"
    float32 -> "%9.0g"
    int64   -> "%9.0g"
    int32   -> "%9.0g"
    int16   -> "%9.0g"
    int8    -> "%8.0g"
    t   %R~   s   %244ss   %10.0gs   %9.0gs   %8.0gsP   Data type %s not currently understood. Please report an error to the developers.N(   RA   R   R   Rl   R   R   R   R   R   R   R   R   R   (   R   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _dtype_to_default_stata_fmt5  s     c         C   s   |  d | t  |   S(   sP   
    Takes a char string and pads it wih null bytes until it's length chars
    s    (   Rm   (   R8   t   length(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt
   _pad_bytesU  s    c         C   s(   g  t  d |  d  D] } d | ^ q S(   s7   
    Returns default Stata names v1, v2, ... vnvar
    i   s   v%d(   R	   (   R_   Rr   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _default_names[  s    c         C   s'   |  d k r t  j St d |    d S(   sK   
    Converts from one of the stata date formats to a type in TYPE_MAP
    R   s   %tcR   s   %tdR   s   %twR   s   %tmR   s   %tqR   s   %thR   s   %tys   fmt %s not understoodN(   R   s   %tcR   s   %tdR   s   %twR   s   %tmR   s   %tqR   s   %thR   s   %ty(   R   R   R   (   R'   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _convert_datetime_to_stata_typea  s    	c         C   s   i  } x |  D] } |  | j  d  s; d |  | |  | <n  | | k rk | j i |  | | j |  6 q t | t  s t d   n  | j i |  | | 6 q W| S(   NR   s5   convery_dates key is not in varlist and is not an int(   t
   startswitht   updateR6   R   R%   R   (   t   convert_datesRa   t   new_dictt   key(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _maybe_convert_to_int_keysk  s    $i   i   t   StataWriterc           B   s[  e  Z d  Z e e e d d  g  e d d  D] Z d e e  ^ q.  d e	 j
 f d e	 j f d e f d e	 j f d e	 j f g  Z e d  e d	  Z i d
 d 6d d 6d d 6d d 6d d 6Z d! d d! d  Z d   Z d   Z d   Z d   Z d   Z d! d! d  Z d! d! d! d! d! d  Z d! d  Z d   Z d   Z d    Z RS("   sp  
    A class for writing Stata binary dta files from array-like objects

    Parameters
    ----------
    fname : file path or buffer
        Where to save the dta file.
    data : array-like
        Array-like input to save. Pandas objects are also accepted.
    convert_dates : dict
        Dictionary mapping column of datetime types to the stata internal
        format that you want to use for the dates. Options are
        'tc', 'td', 'tm', 'tw', 'th', 'tq', 'ty'. Column can be either a
        number or a name.
    encoding : str
        Default is latin-1. Note that Stata does not support unicode.
    byteorder : str
        Can be ">", "<", "little", or "big". The default is None which uses
        `sys.byteorder`

    Returns
    -------
    writer : StataWriter instance
        The StataWriter instance has a write_file method, which will
        write the file to the given `fname`.

    Examples
    --------
    >>> writer = StataWriter('./data_file.dta', data)
    >>> writer.write_file()

    Or with dates

    >>> writer = StataWriter('./date_data_file.dta', date, {2 : 'tw'})
    >>> writer.write_file()
    i   i   RF   i   i   i   i   i   RG   ie   RH   i  RI   iRJ   g      GRK   g      RL   s   latin-1c         C   s  t  j d t  | |  _ t j | d   r; |  j |  n t j | d   r t	 j
 |  } t j |  r{ |  j |  q | d  k	 r t d   n  |  j |  n t d t |    | d  k r t j } n  t |  |  _ | |  _ t | d |  |  _ d  S(   Ns   StataWriter is deprecated as of 0.10.0 and will be removed in a future version.  Use pandas.DataFrame.to_stata or pandas.io.stata.StatWriter instead.s-   Not able to convert dates in a plain ndarray.s   Type %s for data not understoodt   wb(   R!   R   RM   t   _convert_datest	   data_utilt   _is_using_pandasRN   t   _prepare_pandast   _is_array_likeR   t   asarrayt   _is_structured_ndarrayt   _prepare_structured_arrayR   t   _prepare_ndarrayRA   t   sysR   R   t
   _byteorderRQ   R   Rh   (   R3   RT   R   R   RV   R   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR5     s&    		c         C   s   |  j  j t |   d S(   sT   
        Helper to call asbytes before writing to file for Python 3 compat.
        N(   Rh   t   writeR   (   R3   t   to_write(    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   _write  s    c         C   s  t  |  |  _ t  | j  |  _ | |  _ t |  |  _ | j } | j } | j d  k rl t
 |  j  } n	 | j } |  j } | d  k	 r t | |  } | |  _ x0 | D]( } | | d t | |  f | | <q Wt j |  } n  | |  _ g  t |  j  D] } t | |  ^ q |  _ g  t |  j  D] } t | |  ^ q/|  _ | d  k	 rx" | D] } | | |  j | <qaWn  d  S(   Ni    (   Rm   Rg   R   R_   R   t   itert   datarowst   descrt   namesRN   R   R   R   R   R   Ra   R	   R   R`   R   Rc   (   R3   R   R   R   Ra   R   R   Rr   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR     s4    								,,c         C   s   | j  d k r( | d  d   d  f } n  | j \ |  _ |  _ | |  _ t |  |  _ | j } t	 |  j  |  _
 g  t |  j  D] } t |  ^ q |  _ g  t |  j  D] } t |  ^ q |  _ d  S(   Ni   (   t   ndimRN   t   shapeRg   R_   R   R   R   R   R   Ra   R	   R   R`   R   Rc   (   R3   R   R   Rr   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR     s    		+c            sP  d t  f   f d     Y}   j     |    |  _   j \ |  _ |  _   |  _   j j   |  _	   j
 } |  j } | d  k	 r t | |  j	  } | |  _ x4 | D]) } t | |  } t j |  | | <q Wn  g  | D] } t |  ^ q |  _ g  | D] } t |  ^ q |  _ | d  k	 rLx" | D] } | | |  j | <q.Wn  d  S(   Nt   DataFrameRowIterc              s    e  Z d    Z   f d   Z RS(   c         S   s   | |  _  d  S(   N(   R   (   R3   R   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR5     s    c         3   s&   x   j    D] \ } } | Vq Wd  S(   N(   t   iterrows(   R3   Rr   t   row(   R   (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   __iter__  s    (   R=   R>   R5   R   (    (   R   (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR     s   	(   t   objectt   reset_indexR   R   Rg   R_   R   t   columnst   tolistRa   t   dtypesR   RN   R   R   R   R   R   R`   R   Rc   (   R3   R   R   R   R   R   t   new_typet   dt(    (   R   s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR     s(    				""c         C   s^   |  j    |  j   |  j   |  j t d d   |  j d  k rP |  j   n
 |  j   d  S(   NR;   i   (	   t   _write_headert   _write_descriptorst   _write_variable_labelsR   R   R   RN   t   _write_data_nodatest   _write_data_dates(   R3   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt
   write_file0  s    


c         C   s\  |  j  } |  j t d d   |  j | d k r7 d p: d  |  j d  |  j d  |  j t | d |  j  d   |  j t | d	 |  j  d
   | d  k r |  j |  j t d d  |  j   n) |  j |  j t | d  d  |  j   | d  k rt	 j	 j
   } n t | t	  s3t d   n  |  j |  j | j d  |  j   d  S(   NRH   ir   R   s   s   s    RI   i   Rr   i   R;   iP   s"   time_stamp should be datetime types   %d %b %Y %H:%M(   R   R   R   R_   Rg   RN   R   R   RQ   R   t   nowR   R   t   strftime(   R3   R[   R]   R   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR   <  s&    	!!c         C   s   |  j  } x |  j D] } |  j |  q WxL |  j D]A } |  j | |  j  } t t | d   d  } |  j |  q4 Wt d d | d  } |  j |  x' |  j D] }	 |  j t |	 d   q Wx* t	 |  D] }
 |  j t d d   q Wd  S(   Ni    i!   R;   i   i   i1   (
   R_   R`   R   Ra   R   RQ   R   R   Rc   R	   (   R3   R`   Ra   Rb   Rc   Rd   R_   R   R8   R'   Rr   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR   [  s    	c         C   sI   |  j  } | d  k rE x- t |  D] } |  j t d d   q" Wn  d  S(   NR;   iQ   (   R_   RN   R	   R   R   (   R3   t   labelsR_   Rr   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR   u  s    	c   	      C   s3  |  j  } |  j } |  j } |  j } x| D] } x t |  D] \ } } t | |  } | d k r t |  | k  r t t |  t |  d  } n  |  j	 |  q> yA | t
 k r t
 | |  } n  |  j	 t | | | |   Wq> t k
 r&|  j	 t | | | t
 | |    q> Xq> Wq+ Wd  S(   Ni   i   (   R   R   R   R`   t	   enumerateR   Rm   R   R   R   t   _type_convertersR   t   struct_error(	   R3   R   R   R   R`   R   Rr   t   varR   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR   {  s$    				""c         C   s3  |  j  } |  j } |  j } |  j } |  j } |  j } x | D] } x t |  D] \ } }	 t | |  }
 | | k r t |	 |  j	 |  }	 n  |
 d k r t
 |	  r d }	 n  t |	  |
 k  r t |	 t |	  d  }	 n  |  j |	  qP t
 |	  r	| |
 }	 n  |  j t | | |
 |	   qP Wq= Wd  S(   Ni   R;   i   (   R   R   R   R   R   R`   R   R   R*   Rc   R   Rm   R   R   R   (   R3   R   R   R   R   R   R`   R   Rr   R   R   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR     s(    							c         C   s5   d } t  r# | | 7} | j |  S| | 7} | Sd  S(   Ns    (   R
   t   encode(   R3   R~   RV   R   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR     s    

N(    R=   R>   R?   Rn   R   R   R	   Rr   Rl   R   R   R   R%   R   R   R   R   R   R   RN   R5   R   R   R   R   R   R   R   R   R   R   R   (    (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR   {  s0   $>!"

 		$		 				g     8c            s  t  j d t  t |  t  rC t t |  d  d t d | } n@ t |  d  sk t	 d t
 |     n t |  d t d | } | j   } | d } | d } | d	 }	 | d
 }
 | d  | d } | d } t j | |	 f  } | j   } t j t |
 |   } t j | d | } xo t |  D]a \ } } d | k rx6 t |  D]% \ } } | d k rU| | | <qUqUWn  t |  | | <q0W| r-d d l m } | j |  } | rt j t d      d } xH | D]=     } | j     |   j t d  | f |   <qWqn | rt j t d      d } | j j } g  t |  D]. \ } } | | k r| d t f n | ^ qk} | j |  } xN | D]C      f d   } t | | | j j    | | j j   <qWn  | S(   s  
    Returns an ndarray or DataFrame from a Stata .dta file.

    Parameters
    ----------
    fname : str or filehandle
        Stata .dta file.
    missing_flt : numeric
        The numeric value to replace missing values with. Will be used for
        any numeric value.
    encoding : string, optional
        Used for Python 3 only. Encoding to use when reading the .dta file.
        Defaults to `locale.getpreferredencoding`
    pandas : bool
        Optionally return a DataFrame instead of an ndarray
    convert_dates : bool
        If convert_dates is True, then Stata formatted dates will be converted
        to datetime types according to the variable's format.
    sn   genfromdta is deprecated as of 0.10.0 and will be removed in a future version.  Use pandas.read_stata instead.t   rbRU   RV   R   s>   The input should be a string or a filehandle. (got %s instead)R   Rg   R_   Ra   Rc   R[   Re   R   i(   t	   DataFramec         S   s
   |  t  k S(   N(   t   _date_formats(   R   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:     R;   i    t   argsc         S   s
   |  t  k S(   N(   R   (   R   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyR:     R;   c            s   t  |      S(   N(   R0   (   R   (   t   colRc   (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   convert  s    N(    R!   R   RM   R   R   RE   t   openR   t   hasattrt	   TypeErrorRA   RX   R   t   zerosRs   R   R   R   RN   t   tuplet   pandasR   t   from_recordst   whereR   R   t   applyR0   R   R   t   astypeR   (   RT   t   missing_fltRV   R   R   t   fhdt   headert   typesRg   t   numvarst   varnamest   datanameR   R   t	   stata_dtaR   t   rownumt   lineRr   t   valR   t   colsR   t	   sub_dtypeR   (    (   R   Rc   s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt
   genfromdta  sb    






>,s   %.18et    c   	   	   C   s  t  |  d  } t j |  } | j d k rr | j j d k r] t j |  j } d } q t	 | j j
  } n | j d } t | t t f  r t	 |  | k r t d t |    n  | j |  } nt t | t  rE| j d  d k r| g | } | j |  } qE| j d  | k r<t d |   qE| } n  | d k rl| j j rl| j j } n  | d k	 r| j | j |  d  n  x) | D]! } | j | t |  d  qWWd QXd S(   s
  
    Save an array to a text file.

    This is just a copy of numpy.savetxt patched to support structured arrays
    or a header of names.  Does not include py3 support now in savetxt.

    Parameters
    ----------
    fname : filename or file handle
        If the filename ends in ``.gz``, the file is automatically saved in
        compressed gzip format.  `loadtxt` understands gzipped files
        transparently.
    X : array_like
        Data to be saved to a text file.
    names : list, optional
        If given names will be the column header in the text file.  If None and
        X is a structured or recarray then the names are taken from
        X.dtype.names.
    fmt : str or sequence of strs
        A single format (%10.5f), a sequence of formats, or a
        multi-format string, e.g. 'Iteration %d -- %10.5f', in which
        case `delimiter` is ignored.
    delimiter : str
        Character separating columns.

    See Also
    --------
    save : Save an array to a binary file in NumPy ``.npy`` format
    savez : Save several arrays into a ``.npz`` compressed archive

    Notes
    -----
    Further explanation of the `fmt` parameter
    (``%[flag]width[.precision]specifier``):

    flags:
        ``-`` : left justify

        ``+`` : Forces to preceed result with + or -.

        ``0`` : Left pad the number with zeros instead of space (see width).

    width:
        Minimum number of characters to be printed. The value is not truncated
        if it has more characters.

    precision:
        - For integer specifiers (eg. ``d,i,o,x``), the minimum number of
          digits.
        - For ``e, E`` and ``f`` specifiers, the number of digits to print
          after the decimal point.
        - For ``g`` and ``G``, the maximum number of significant digits.
        - For ``s``, the maximum number of characters.

    specifiers:
        ``c`` : character

        ``d`` or ``i`` : signed decimal integer

        ``e`` or ``E`` : scientific notation with ``e`` or ``E``.

        ``f`` : decimal floating point

        ``g,G`` : use the shorter of ``e,E`` or ``f``

        ``o`` : signed octal

        ``s`` : string of characters

        ``u`` : unsigned decimal integer

        ``x,X`` : unsigned hexadecimal integer

    This explanation of ``fmt`` is not complete, for an exhaustive
    specification see [1]_.

    References
    ----------
    .. [1] `Format Specification Mini-Language
           <http://docs.python.org/library/string.html#
           format-specification-mini-language>`_, Python Documentation.

    Examples
    --------
    >>> savetxt('test.out', x, delimiter=',')   # x is an array
    >>> savetxt('test.out', (x,y,z))   # x,y,z equal sized 1D arrays
    >>> savetxt('test.out', x, fmt='%1.4e')   # use exponential notation

    t   wi   s   fmt has wrong shape.  %sR   s'   fmt has wrong number of %% formats.  %ss   
N(   R   R   R   R   R   R   RN   t
   atleast_2dt   TRm   R   R   R   R   R   t   AttributeErrorRl   t   joinR   t   countR   (	   RT   t   XR   R'   t	   delimitert   fht   ncolRB   R   (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   savetxt  s4    [		(7   R?   R!   t   statsmodels.compat.pythonR    R   R   R   R   R   R   R   R   R	   R
   t   structR   R   R   R   R   R   R   t   numpyR   t   statsmodels.tools.datat   toolsR   R   R   R   t   pandas.io.stataR   t   statsmodels.iolib.openfileR   R   R*   R0   R   R1   RE   R   R   R   R   R   R   R   R%   R   R   RN   R   R   R  R  (    (    (    s8   lib/python2.7/site-packages/statsmodels/iolib/foreign.pyt   <module>   s<   L	&	T1 B		$	 			
	 >	Z