
    Mhn                      % S r SSKJr  SSKJr  SSKJrJr  SSKJr  SSK	r	SSK
r
SSKrSSKJrJrJrJrJrJr  SSKrSSKrSSKJr  SS	KJr  SS
KJr  SSKJrJrJrJ r   SSK!J"r"J#r#  SSK$J%r%  SSK&J'r'  SSK(J)r)J*r*J+r+  SSK,J-r-  SSK.J/r/J0r0J1r1J2r2J3r3J4r4J5r5  SSK6J7r7  SSK8J9r9  SSK:J;r;  SSK<J=r=  SSK>J?r?  SSK@JArA  \(       a$  SSKBJCrCJDrD  SSKEJFrF  SSKJGrG  SSKHJIrIJJrJJKrKJLrLJMrMJNrN  SrOSrPSrQSrRS rSS!rTS"\P S#\Q S#\R S#\S S#\?S$   S%-   S#\?S&    S'\T S(3rUS)\P S#\Q S*3rVS+\P S#\Q S#\R S#\?S$    S#\?S&    S,\T S#3rW/ S-QrX\" S.S/S/5      rYS0\ZS1'   SaS2 jr[SaS3 jr\S4r]S0\ZS5'   S6r^S0\ZS7'   S8r_S0\ZS9'   S:r`S0\ZS;'   S<raS0\ZS='   SbS> jrb " S? S@5      rc " SA SB\c5      rd " SC SD5      re " SE SF5      rf " SG SH\f\R                  5      rh\"" \U5      SISISSJSISSISSJSKSSL.                         ScSM jj5       riSdSN jrjSeSO jrkSfSP jrlSgSQ jrmShSR jrn Si       SjSS jjro\#" \?S&   \?ST   SU-  SV9 " SW SX\f5      5       rpSkSY jrqSlSZ jrr " S[ S\5      rs " S] S^\p5      rt " S_ S`\t5      rug)ma  
Module contains tools for processing Stata files into DataFrames

The StataReader below was originally written by Joe Presbrey as part of PyDTA.
It has been extended and improved by Skipper Seabold from the Statsmodels
project who also developed the StataWriter and was finally added to pandas in
a once again improved version.

You can find more information on http://presbrey.mit.edu/PyDTA and
https://www.statsmodels.org/devel/
    )annotations)abc)datetime	timedelta)BytesION)IOTYPE_CHECKINGAnyStrCallableFinalcast)lib)infer_dtype)max_len_string_array)CategoricalConversionWarningInvalidColumnNamePossiblePrecisionLossValueLabelTypeMismatch)Appenderdoc)find_stack_level)ExtensionDtype)ensure_objectis_numeric_dtypeis_string_dtype)CategoricalDtype)CategoricalDatetimeIndexNaT	Timestampisnato_datetimeto_timedelta)	DataFrame)Index)
RangeIndex)Series)_shared_docs)
get_handle)HashableSequence)TracebackType)Literal)CompressionOptionsFilePath
ReadBufferSelfStorageOptionsWriteBufferzVersion of given Stata file is {version}. pandas supports importing versions 105, 108, 111 (Stata 7SE), 113 (Stata 8/9), 114 (Stata 10/11), 115 (Stata 12), 117 (Stata 13), 118 (Stata 14/15/16),and 119 (Stata 15/16, over 32,767 variables).zconvert_dates : bool, default True
    Convert date variables to DataFrame time values.
convert_categoricals : bool, default True
    Read value labels and convert columns to Categorical/Factor variables.a  index_col : str, optional
    Column to set as index.
convert_missing : bool, default False
    Flag indicating whether to convert missing values to their Stata
    representations.  If False, missing values are replaced with nan.
    If True, columns containing missing values are returned with
    object data types and missing values are represented by
    StataMissingValue objects.
preserve_dtypes : bool, default True
    Preserve Stata datatypes. If False, numeric data are upcast to pandas
    default types for foreign data (float64 or int64).
columns : list or None
    Columns to retain.  Columns will be returned in the given order.  None
    returns all columns.
order_categoricals : bool, default True
    Flag indicating whether converted categorical data are ordered.zzchunksize : int, default None
    Return StataReader object for iterations, returns chunks with
    given number of lines.z=iterator : bool, default False
    Return StataReader object.zNotes
-----
Categorical variables read through an iterator may not have the same
categories and dtype. This occurs when  a variable stored in a DTA
file is associated to an incomplete set of value labels that only
label a strict subset of the values.a>  
Read Stata file into DataFrame.

Parameters
----------
filepath_or_buffer : str, path object or file-like object
    Any valid string path is acceptable. The string could be a URL. Valid
    URL schemes include http, ftp, s3, and file. For file URLs, a host is
    expected. A local file could be: ``file://localhost/path/to/table.dta``.

    If you want to pass in a path object, pandas accepts any ``os.PathLike``.

    By file-like object, we refer to objects with a ``read()`` method,
    such as a file handle (e.g. via builtin ``open`` function)
    or ``StringIO``.

decompression_optionsfilepath_or_bufferstorage_optionsz

Returns
-------
DataFrame or pandas.api.typing.StataReader

See Also
--------
io.stata.StataReader : Low-level reader for Stata data files.
DataFrame.to_stata: Export Stata data files.

a  

Examples
--------

Creating a dummy stata for this example

>>> df = pd.DataFrame({'animal': ['falcon', 'parrot', 'falcon', 'parrot'],
...                     'speed': [350, 18, 361, 15]})  # doctest: +SKIP
>>> df.to_stata('animals.dta')  # doctest: +SKIP

Read a Stata dta file:

>>> df = pd.read_stata('animals.dta')  # doctest: +SKIP

Read a Stata dta file in 10,000 line chunks:

>>> values = np.random.randint(0, 10, size=(20_000, 1), dtype="uint8")  # doctest: +SKIP
>>> df = pd.DataFrame(values, columns=["i"])  # doctest: +SKIP
>>> df.to_stata('filename.dta')  # doctest: +SKIP

>>> with pd.read_stata('filename.dta', chunksize=10000) as itr: # doctest: +SKIP
>>>     for chunk in itr:
...         # Operate on a single chunk, e.g., chunk.mean()
...         pass  # doctest: +SKIP
zReads observations from Stata file, converting them into a dataframe

Parameters
----------
nrows : int
    Number of lines to read from data file, if None read whole file.
z

Returns
-------
DataFrame
zClass for reading Stata dta files.

Parameters
----------
path_or_buf : path (string), buffer or path object
    string, path object (pathlib.Path or py._path.local.LocalPath) or object
    implementing a binary read() functions.
z

)	%tc%tC%td%d%tw%tm%tq%th%ty     r   stata_epochc                $  ^^^^^^ [         R                  R                  [         R                  R                  smm[         R                  [	        SSS5      -
  R
                  m[         R                  [	        SSS5      -
  R
                  mTS-  S-  S-  mTS-  S-  S-  mS"UU4S jjnS"UU4S jjnS"UUUU4S jjn[        R                  " U 5      nS	nUR                  5       (       a  S
nSU R                  U'   U R                  [        R                  5      n UR                  S5      (       a  [        nU nU" XxS5      n	GOUR                  S5      (       a<  [        R                  " S[!        5       S9  [#        U [$        S9n	U(       a  [&        X'   U	$ UR                  S5      (       a  [        nU n
U" XzS5      n	GOAUR                  S5      (       a(  [        R                  U S-  -   nU S-  S-  n
U" X5      n	GOUR                  S5      (       a'  [        R                  U S-  -   nU S-  S-   nU" X5      n	OUR                  S5      (       a*  [        R                  U S-  -   nU S-  S-  S-   nU" X5      n	OUR                  S5      (       a*  [        R                  U S-  -   nU S-  S-  S-   nU" X5      n	OFUR                  S5      (       a!  U n[        R(                  " U 5      nU" X5      n	O[+        S U S!35      eU(       a  [&        X'   U	$ )#ac  
Convert from SIF to datetime. https://www.stata.com/help.cgi?datetime

Parameters
----------
dates : Series
    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
    Returns

Returns
-------
converted : Series
    The converted dates

Examples
--------
>>> dates = pd.Series([52])
>>> _stata_elapsed_date_to_datetime_vec(dates , "%tw")
0   1961-01-01
dtype: datetime64[ns]

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
rA   rB      i    c                   > U R                  5       T:  a$  U R                  5       T:  a  [        SU -  U-   SS9$ [        U SS5      n[	        [        X5       VVs/ s H  u  p4[        X4S5      PM     snnUS9$ s  snnf )z
Convert year and month to datetimes, using pandas vectorized versions
when the date range falls within the range supported by pandas.
Otherwise it falls back to a slower but more robust method
using datetime.
d   z%Y%mformatindexNrB   rK   )maxminr"   getattrr'   zipr   )yearmonthrK   ymMAX_YEARMIN_YEARs        A/var/www/html/env/lib/python3.13/site-packages/pandas/io/stata.pyconvert_year_month_safeD_stata_elapsed_date_to_datetime_vec.<locals>.convert_year_month_safe!  st     88: TXXZ(%:sTzE1&AAD'40ET9IJ9I8A!,9IJRWXXJs   A9
c           
     6  > U R                  5       TS-
  :  a)  U R                  5       T:  a  [        U SS9[        USS9-   $ [	        U SS5      n[        X5       VVs/ s H%  u  p4[        USS5      [        [        U5      S9-   PM'     nnn[        XRS	9$ s  snnf )
zc
Converts year (e.g. 1999) and days since the start of the year to a
datetime or datetime64 Series
rB   %YrI   dunitrK   NdaysrL   )
rM   rN   r"   r#   rO   rP   r   r   intr'   )rQ   r`   rK   rS   r\   valuerU   rV   s         rW   convert_year_days_safeC_stata_elapsed_date_to_datetime_vec.<locals>.convert_year_days_safe.  s    
 88:A&488:+@tD1LC4PPPD'40EGJ4GVtqAq!I3q6$::   %--s   ,Bc           	       > [        USS5      nUS:X  aV  UR                  5       T:  d  UR                  5       T:  a-  U Vs/ s H  o@[        [	        U5      S9-   PM     nn[        XSS9$ OjUS:X  aY  UR                  5       T:  d  UR                  5       T	:  a0  U Vs/ s H  o@[        [	        U5      S-  S9-   PM     nn[        XSS9$ O[        S	5      e[        U 5      n [        XS
9nX-   $ s  snf s  snf )z
Convert base dates and deltas to datetimes, using pandas vectorized
versions if the deltas satisfy restrictions required to be expressed
as dates in pandas.
rK   Nr\   r_   rL   msrF   )microsecondszformat not understoodr]   )	rO   rM   rN   r   ra   r'   
ValueErrorr"   r#   )
basedeltasr^   rK   r\   valuesMAX_DAY_DELTAMAX_MS_DELTAMIN_DAY_DELTAMIN_MS_DELTAs
         rW   convert_delta_safe?_stata_elapsed_date_to_datetime_vec.<locals>.convert_delta_safe<  s     .3;zz|m+vzz|m/KAGHAA!77Hf22 0L T\zz|l*fjjl\.ILRLRq93q6D=BBF   f22	 /J 4554 f0} Is   C-!C2FTg      ?r8   tcrf   r9   tCz9Encountered %tC format. Leaving in Stata Internal Format.
stackleveldtype)r:   tdr;   r\   r\   r<   tw4      r=   tm   r>   tq      r?   th      r@   tyz	Date fmt  not understood)returnr'   )r    rN   rQ   rM   r   r`   npisnanany_valuesastypeint64
startswithrC   warningswarnr   r'   objectr   	ones_likerh   )datesfmtrX   rc   rp   bad_locshas_bad_valuesri   rf   
conv_datesr`   rQ   rR   quarter_monthfirst_monthrl   rm   rU   rn   ro   rV   s                  @@@@@@rW   #_stata_elapsed_date_to_datetime_vecr      s   \ #++Y]]-?-?Hh]]XdAq%99??M]]XdAq%99??M 2%,t3L 2%,t3LY Y. . 2 xxHN||~~"%hLL"E
~~m$$'$7
		&	&G')	
 E0
#&J 	0	1	1'C8
 
	&	&%2+-
a+D7
		&	&%2+-q ,T9
		&	&%1*,a!+,TA
		&	&%1*,a!#,T9
		&	&ll5),T?
9SE9::"
    c                  ^^^	 U R                   m	SmTS-  m S#       S$UUU	4S jjjn[        U 5      nU R                   m	UR                  5       (       aV  [        R                  " U R
                  S5      (       a  [        [        5      U R                  U'   O[        U R                  U'   US;   a  U" U SS9nUR                  S-  nGO}US	;   a!  [        R                  " S
[        5       S9  U nGOVUS;   a  U" U SS9nUR                  T-  nGO8US;   a9  U" U SSS9nSUR                  [        R                  -
  -  UR                  S-  -   nOUS;   a8  U" U SS9nSUR                  [        R                  -
  -  UR                  -   S-
  nOUS;   a;  U" U SS9nSUR                  [        R                  -
  -  UR                  S-
  S-  -   nOzUS;   aK  U" U SS9nSUR                  [        R                  -
  -  UR                  S:  R!                  ["        5      -   nO)US;   a  U" U SS9nUR                  nO[%        SU S35      e['        U[(        R*                  SS9n[,        R.                  " SS 5      S!   nXeU'   ['        UT	SS"9$ )%a+  
Convert from datetime to SIF. https://www.stata.com/help.cgi?datetime

Parameters
----------
dates : Series
    Series or array containing datetime or datetime64[ns] 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
l     "R: rF   Fc                $  > 0 n[         R                  " U R                  S5      (       Ga  U(       aP  U [        [        5      R                  S5      -
  nUR                  R                  [        R                  5      S-  US'   U(       d  U(       a=  [        U 5      nUR                  R                  US'   UR                  R                  US'   U(       af  U R                  R                  [        R                  5      [        US   SS9R                  R                  [        R                  5      -
  nUT-  US	'   O[        U S
S9S:X  a  U(       a<  U R                  [        -
  nSU4S jjn[        R                   " U5      n	U	" U5      US'   U(       a<  U R#                  S 5      n
U
R                  S-  US'   U
R                  US   S-  -
  US'   U(       a&  SS jn[        R                   " U5      n	U	" U 5      US	'   O[%        S5      e['        UTS9$ )NMnsrF   deltarQ   rR   r[   rI   r`   Fskipnar   c                \   > TU R                   -  SU R                  -  -   U R                  -   $ )Ni@B )r`   secondsrg   )x
US_PER_DAYs    rW   fC_datetime_to_stata_elapsed_vec.<locals>.parse_dates_safe.<locals>.f  s)    %.1991DDq~~UUr   c                :    SU R                   -  U R                  -   $ )NrH   )rQ   rR   r   s    rW   <lambda>J_datetime_to_stata_elapsed_vec.<locals>.parse_dates_safe.<locals>.<lambda>  s    3<!''3Ir   rH   c                J    U [        U R                  SS5      -
  R                  $ )NrB   )r   rQ   r`   r   s    rW   gC_datetime_to_stata_elapsed_vec.<locals>.parse_dates_safe.<locals>.g  s     A 66<<<r   zQColumns containing dates must contain either datetime64, datetime or null values.rL   )r   r   r   float)r   r   r   ra   )r   is_np_dtypery   r    rC   as_unitr   viewr   r   r   _datarQ   rR   r"   r   	vectorizeapplyrh   r$   )r   r   rQ   r`   r\   
time_delta
date_index
days_in_nsr   v
year_monthr   
NS_PER_DAYr   rK   s               rW   parse_dates_safe8_datetime_to_stata_elapsed_vec.<locals>.parse_dates_safe  s    ??5;;,,"Y{%;%C%CD%II
'//44RXX>$F'
t*51
&,,11&	'--33'
"]]//9KfId='$$rxx.)
 '*4&	u-;3V LLOuX'
"[[)IJ
&..#5&	'//!F)c/A'
= LLOeH&	7 
 %((r   r   rr   T)r   rt   z'Stata Internal Format tC not supported.rv   )r:   rz   r{   )rQ   r`   r}   r~   r   )rQ   r   rB   r   r   r   r   r   r   r   Format z! is not a known Stata date format)ry   copy<d         r   rK   r   )FFF)r   r'   r   boolrQ   r   r`   r   )rK   r!   r   r   r   ry   r"   rC   r   r   r   r   r   rQ   r`   rR   r   ra   rh   r'   r   float64structunpack)
r   r   r   bad_locr\   r   missing_valuer   r   rK   s
          @@@rW   _datetime_to_stata_elapsed_vecr     sw    KKE/Jd"J NS,),)",)26,)FJ,) ,)\ 5kGKKE{{}}??5;;,,%0%=EMM'"%0EMM'"
mU$/WWt^
		5')	
 
		U$/WW
*
		UD9166K$4$445!C
		U.166K$4$445?!C
		U.!&&;#3#334!7II
		U.!&&;#3#334!7K7KC7PP
		U.VV
73%'HIJJ
"**5AJMM$(KLQOM'w*E66r   z
Fixed width strings in Stata .dta files are limited to 244 (or fewer)
characters.  Column '{0}' does not satisfy this restriction. Use the
'version=117' parameter to write the newer (Stata 13 and later) format.
excessive_string_length_errorz
Column converted from {0} to {1}, and some data are outside of the lossless
conversion range. This may result in a loss of precision in the saved data.
precision_loss_docz
Stata value labels (pandas categories) must be strings. Column {0} contains
non-string labels which will be converted to strings.  Please check that the
Stata data file created has not lost information due to duplicate labels.
value_label_mismatch_doca;  
Not all pandas column names were valid Stata variable names.
The following replacements have been made:

    {0}

If this is not what you expect, please make sure you have Stata-compliant
column names in your DataFrame (strings only, max 32 characters, only
alphanumerics and underscores, no Stata reserved words)
invalid_name_doca  
One or more series with value labels are not fully labeled. Reading this
dataset with an iterator results in categorical variable with different
categories. This occurs since it is not possible to know all possible values
until the entire dataset has been read. To avoid this warning, you can either
read dataset without an iterator, or manually convert categorical data by
``convert_categoricals`` to False and then accessing the variable labels
through the value_labels method of the reader.
categorical_conversion_warningc           
        Sn[         R                  [         R                  [         R                  4[         R                  [         R                  [         R                  4[         R
                  [         R                  [         R                  4[         R                  [         R                  [         R                  4[         R                  [         R                  [         R                  44n[        R                  " SS5      S   n[        R                  " SS5      S   nU  GH  n[        X   R                  [        5      =(       a    X   R                  R                   S;   nX   R#                  5       nU(       a[  X   R                  R                   S;   a  SOS	nX   R%                  U5      R'                  X   R                  R(                  5      X'   O[        X   R                  [        5      (       aw  [+        X   R                  S
S5      b,  X   R'                  X   R                  R(                  5      X'   O1[-        X   R                  5      (       a  X   R'                  S5      X'   X   R                  n	U R.                  S   S:H  n
U H  nXS   :X  d  M  U
(       d7  X   R1                  5       [         R2                  " US   5      R0                  ::  a  US   n	OUS   n	US   [         R                  :X  a,  X   R1                  5       S:  a  [4        R7                  SS5      nX   R'                  U	5      X'   M     U	[         R                  :X  aX  U
(       dQ  X   R1                  5       S:  d  X   R9                  5       S:  a#  X   R'                  [         R                  5      X'   GOU	[         R                  :X  aX  U
(       dQ  X   R1                  5       S:  d  X   R9                  5       S:  a#  X   R'                  [         R                  5      X'   GOU	[         R                  :X  a  U
(       d,  X   R1                  5       S::  a;  X   R9                  5       S:  a%  X   R'                  [         R                  5      X'   GOAX   R'                  [         R                  5      X'   X   R1                  5       S:  d  X   R9                  5       S::  a  [4        R7                  SS5      nOU	[         R:                  [         R                  4;   a  [         R<                  " X   5      R?                  5       (       a  [A        SU S35      eX   R1                  5       nU	[         R:                  :X  a)  X:  a$  X   R'                  [         R                  5      X'   O.U	[         R                  :X  a  X:  a  [A        SU SU SU S35      eU(       d  GM  UR?                  5       (       d  GM  [B        RD                  X   R                  RF                     nXRH                  Xu4'   GM     U(       a"  [J        RL                  " U[N        [Q        5       S9  U $ ) a  
Checks the dtypes of the columns of a pandas DataFrame for
compatibility with the data types and ranges supported by Stata, and
converts if necessary.

Parameters
----------
data : DataFrame
    The DataFrame to check and convert

Notes
-----
Numeric columns in Stata must be one of int8, int16, int32, float32 or
float64, with some additional value restrictions.  int8 and int16 columns
are checked for violations of the value restrictions and upcast if needed.
int64 data is not usable in Stata, and so it is downcast to int32 whenever
the value are in the int32 range, and sidecast to float64 when larger than
this range.  If the int64 values are outside of the range of those
perfectly representable as float64 values, a warning is raised.

bool columns are cast to int8.  uint columns are converted to int of the
same size if there is no loss in precision, otherwise are upcast to a
larger type.  uint64 is currently not supported since it is concerted to
object in a DataFrame.
 <f   ~r   r      iubiuFnumpy_dtypeNr   rB   r   l          uint64r   rH       l       r   zColumn zM contains infinity or -infinitywhich is outside the range supported by Stata.z has a maximum value (z() outside the range supported by Stata ()rv   ))r   bool_int8uint8int16uint16int32uint32r   r   r   r   r   
isinstancery   r   kindr!   fillnar   r   rO   r   shaperM   iinfor   rJ   rN   float32isinfr   rh   StataMissingValueBASE_MISSING_VALUESnamelocr   r   r   r   )datawsconversion_datafloat32_maxfloat64_maxcolis_nullable_intorig_missingfvry   empty_dfc_datarb   sentinels                 rW   _cast_to_stata_typesr  #  s   4 
B 
277BGG$	277BHH%	BHHbhh'	BHHbhh'	BHHbjj)	  --&9:1=K--&IJ1MK ty7 .	$$- 	
 y~~'ioo**d2B	((,33DIOO4O4OPDI	88tyt<H I,,TY__-H-HI	 11 I,,X6		::a=A%%Fq	!ty}}"((6!92E2I2II"1IE"1IE!9(y}}%//66xK I,,U3	 & BGGHy}}$	$(> I,,RXX6	bhhxy}}&$)--/F*B I,,RXX6	bhh	:-$)--/[2P I,,RXX6	 I,,RZZ8	9==?e+ty}}(/J+227IFBrzz2::..xx	"&&(( cU #E E  IMMOE

"u': I,,RZZ8	"**$&$!#&<UG D//:m1>  ?!!,@@AUAUV.6*+I J 
!')	
 Kr   c                  F    \ rS rSrSr S     S	S jjrS
S jrSS jrSrg)StataValueLabeli  z
Parse a categorical column and prepare formatted output

Parameters
----------
catarray : Series
    Categorical Series to encode
encoding : {"latin-1", "utf-8"}
    Encoding to use for value labels.
c                    US;  a  [        S5      eUR                  U l        X l        UR                  R
                  n[        U5      U l        U R                  5         g )Nlatin-1utf-8%Only latin-1 and utf-8 are supported.)	rh   r   labname	_encodingcat
categories	enumeratevalue_labels_prepare_value_labels)selfcatarrayencodingr  s       rW   __init__StataValueLabel.__init__  sQ     //DEE}}!\\,,
%j1""$r   c                J   SU l         / U l        SU l        [        R                  " / [        R
                  S9U l        [        R                  " / [        R
                  S9U l        SU l        / n/ nU R                   GH  nUS   n[        U[        5      (       dJ  [        U5      n[        R                  " [        R                  U R                   5      ["        [%        5       S9  UR'                  U R(                  5      nUR+                  U R                   5        U =R                   [        U5      S-   -  sl         UR+                  US   5        U R                  R+                  U5        U =R                  S-  sl        GM     U R                   S:  a  [-        S5      e[        R                  " U[        R
                  S9U l        [        R                  " U[        R
                  S9U l        SSU R                  -  -   SU R                  -  -   U R                   -   U l        g	)
zEncode value labels.r   rx   rB   rv   i }  zaStata value labels for a single variable must have a combined length less than 32,000 characters.   r   N)text_lentxtnr   arrayr   offvallenr  r   strr   r   r   rJ   r  r   r   encoder  appendrh   )r  offsetsrk   vlcategorys        rW   r  %StataValueLabel._prepare_value_labels  s     "88Bbhh/88Bbhh/   ##B$&qEHh,,x=,33DLLA*/1
  t~~6HNN4==)MMS]Q..MMM"Q% HHOOH%FFaKFF $  ==5 F  88G288488F"((3 1tvv:%DFF
2T]]Br   c                   U R                   n[        5       nSnUR                  [        R                  " US-   U R
                  5      5        [        U R                  5      SS R                  U5      nUS;  a  SOSn[        XVS-   5      nUR                  U5        [        S5       H)  nUR                  [        R                  " S	U5      5        M+     UR                  [        R                  " US-   U R                  5      5        UR                  [        R                  " US-   U R                  5      5        U R                   H,  nUR                  [        R                  " US-   U5      5        M.     U R                   H,  n	UR                  [        R                  " US-   U	5      5        M.     U R                   H  n
UR                  X-   5        M     UR!                  5       $ )
z
Generate the binary representation of the value labels.

Parameters
----------
byteorder : str
    Byte order of the output

Returns
-------
value_label : bytes
    Bytes containing the formatted value label
    iN    )r	  utf8   rB   r   c)r  r   writer   packr  r   r  r!  
_pad_bytesranger  r  r  r  r  getvalue)r  	byteorderr  bio	null_byter  lab_lenr)  offsetrb   texts              rW   generate_value_label$StataValueLabel.generate_value_label  sq    >>i	 			&++i#otxx89 dll#CR(//9 (99"sWk2		' qAIIfkk#y12 
 			&++i#otvv67 			&++i#ot}}=> hhFIIfkk)c/6:;  XXEIIfkk)c/59:  HHDIId&'  ||~r   )	r  r  r  r  r  r  r  r  r  Nr  )r  r'   r  Literal['latin-1', 'utf-8']r   Noner   r=  )r3  r   r   bytes)	__name__
__module____qualname____firstlineno____doc__r  r  r9  __static_attributes__ r   rW   r  r    s7    	 IR
%
%*E
%	
%*CX2r   r  c                  6    \ rS rSrSr S       SS jjrSrg)StataNonCatValueLabeli  z
Prepare formatted version of value labels

Parameters
----------
labname : str
    Value label name
value_labels: Dictionary
    Mapping of values to labels
encoding : {"latin-1", "utf-8"}
    Encoding to use for value labels.
c                    US;  a  [        S5      eXl        X0l        [        UR	                  5       S S9U l        U R                  5         g )Nr  r
  c                    U S   $ )Nr   rF  r   s    rW   r   0StataNonCatValueLabel.__init__.<locals>.<lambda>2  s    !r   )key)rh   r  r  sorteditemsr  r  )r  r  r  r  s       rW   r  StataNonCatValueLabel.__init__&  sL     //DEE!" n
 	""$r   )r  r  r  Nr;  )r  r   r  dict[float, str]r  r<  r   r=  )r@  rA  rB  rC  rD  r  rE  rF  r   rW   rH  rH    s<    " 1:	%% '% .	%
 
% %r   rH  c                     \ rS rSr% Sr0 rS\S'   SrS\S'   \ H,  rS\\'   \	" S	S
5       H  r
S\" S\
-   5      -   \\
\-   '   M     M.     SrS\S'   \R                  " SS5      S   rS\S'   \	" S
5       Hw  r
\R                  " S\5      S   rS\\'   \
S:  a  \\==   \" S\
-   5      -  ss'   \R                  " S\R"                  " S\5      5      S   \-   r\R"                  " S\5      rMy     SrS\S'   \R                  " SS5      S   r\	" S
5       Hw  r
\R                  " S\5      S   rS\\'   \
S:  a  \\==   \" S\
-   5      -  ss'   \R                  " S\R"                  " S\5      5      S   \-   r\R"                  " S\5      rMy     SSS\R                  " S\5      S   \R                  " S\5      S   S.rS\S'   S(S jr\S)S  j5       r\S*S! j5       rS)S" jrS)S# jrS+S$ jr\S,S% j5       rS&rg')-r   i7  a   
An observation's missing value.

Parameters
----------
value : {int, float}
    The Stata missing value code

Notes
-----
More information: <https://www.stata.com/help.cgi?missing>

Integer missing values make the code '.', '.a', ..., '.z' to the ranges
101 ... 127 (for int8), 32741 ... 32767  (for int16) and 2147483621 ...
2147483647 (for int32).  Missing values for floating point data types are
more complex but the pattern is simple to discern from the following table.

np.float32 missing values (float in Stata)
0000007f    .
0008007f    .a
0010007f    .b
...
00c0007f    .x
00c8007f    .y
00d0007f    .z

np.float64 missing values (double in Stata)
000000000000e07f    .
000000000001e07f    .a
000000000002e07f    .b
...
000000000018e07f    .x
000000000019e07f    .y
00000000001ae07f    .z
rP  MISSING_VALUES)e     r   bases.rB      `         r?  float32_basez<is      r   ra   increment_32r   r   float64_baseqs          r   rS  rT  rU  )r   r   r   r   r   r   c                p    Xl         US:  a  [        U5      O
[        U5      nU R                  U   U l        g )Nl        )_valuera   r   rR  _strr  rb   s     rW   r  StataMissingValue.__init__  s/    #j0E
eEl''.	r   c                    U R                   $ )z
The Stata representation of the missing value: '.', '.a'..'.z'

Returns
-------
str
    The representation of the missing value.
)ra  r  s    rW   stringStataMissingValue.string  s     yyr   c                    U R                   $ )z
The binary representation of the missing value.

Returns
-------
{int, float}
    The binary representation of the missing value.
)r`  re  s    rW   rb   StataMissingValue.value  s     {{r   c                    U R                   $ N)rf  re  s    rW   __str__StataMissingValue.__str__  s    {{r   c                $    [        U 5       SU  S3$ )N(r   )typere  s    rW   __repr__StataMissingValue.__repr__  s    t*QtfA&&r   c                    [        U[        U 5      5      =(       a9    U R                  UR                  :H  =(       a    U R                  UR                  :H  $ rk  )r   rp  rf  rb   )r  others     rW   __eq__StataMissingValue.__eq__  s?    ud4j) *u||+*

ekk)	
r   c                   UR                   [        R                  L a  U R                  S   nU$ UR                   [        R                  L a  U R                  S   nU$ UR                   [        R
                  L a  U R                  S   nU$ UR                   [        R                  L a  U R                  S   nU$ UR                   [        R                  L a  U R                  S   nU$ [        S5      e)Nr   r   r   r   r   zUnsupported dtype)	rp  r   r   r   r   r   r   r   rh   )clsry   rb   s      rW   get_base_missing_value(StataMissingValue.get_base_missing_value  s    :: ++F3E  ZZ288#++G4E  ZZ288#++G4E  ZZ2::%++I6E
 	 ZZ2::%++I6E  011r   )ra  r`  N)rb   r   r   r=  r   r   )r   r   )rt  r   r   r   )ry   np.dtyper   r   ) r@  rA  rB  rC  rD  rR  __annotations__rV  br1  r)  chrr[  r   r   r\  rL  r/  	int_valuer]  increment_64r   r  propertyrf  rb   rl  rq  ru  classmethodry  rE  rF  r   rW   r   r   7  s9   "J (*N$)+E5+qq"A$'#b1f+$5N1q5!   .L%-d,?@CL#C2YmmD,/2!sq533rAv;.MM$D#(>?B\Q	{{43  >L%===&IJ1ML2YmmD,/2!sq533rAv;.MM#v{{4'=>qALP	{{3	2  ==|4Q7==|4Q7" / 	 	 	 	'
  r   r   c                      \ rS rSrSS jrSrg)StataParseri  c                   [        [        SS5       Vs/ s H  o[        R                  " SU 35      4PM     snS[        R                  " [        R                  5      4S[        R                  " [        R
                  5      4S[        R                  " [        R                  5      4S[        R                  " [        R                  5      4S[        R                  " [        R                  5      4/-   5      U l	        [        R                  " [        R                  5      [        R                  " [        R                  5      [        R                  " [        R                  5      [        R                  " [        R                  5      [        R                  " [        R
                  5      [        R                  " [        R                  5      S	.U l        [        [        [        S5      5      [        S
5      -   5      U l        SSSSSSS	.U l        SnSnSnSnSSS[        R                  " [         R"                  " SU5      S   5      [        R                  " [         R"                  " SU5      S   5      4[        R                  " [         R"                  " SU5      S   5      [        R                  " [         R"                  " SU5      S   5      4S.U l        SSSSSS.U l        SSS[        R                  " [         R"                  " SS 5      S   5      [        R                  " [         R"                  " SS!5      S   5      S.U l        S"S#S$S%S&S'S(.U l        1 S)kU l        g s  snf )*NrB      S               )             bhlfdQr\   r   lhr~  s   r   s   r   )r   rH   )r   r   )r   r   r   r   r   )r~  r  r  r   r\   )b   i   l   f   rH   rS  rT  rU  rZ  r   i1i2i4f4f8u8)r~  r  r  r   r\   r  ><   _N_b_ndoifin_pi_rc_seendforra   NULL_allbytecaseelseenumgotolongquadstrLwith_coef_cons_pred_skipr  breakcatchclassconstr   localshortusingdeletedoubleexportfriendglobalinlinepragmabooleancomplexdefaulttypedefvirtualcontinuedelegateexplicitexternalfunctiontypename	aggregate	colvector	eltypedef	protected	rowvectorstr#)dictr1  r   ry   r   r   r   r   r   	DTYPE_MAPr   DTYPE_MAP_XMLlisttupleTYPE_MAPTYPE_MAP_XMLr   r   VALID_RANGEOLD_TYPE_MAPPINGrR  NUMPY_TYPE_MAPRESERVED_WORDS)r  r)  float32_minr   float64_minr   s         rW   r  StataParser.__init__  s     -21c];]AaS'"#];bhhrww'(bhhrxx()bhhrxx()bhhrzz*+bhhrzz*+	
 88BHH%88BJJ'88BJJ'88BHH%88BHH%88BGG$3
 U5:.w?@ 
 *)99 *

6=={;A>?

6=={;A>?
 

6=={;A>?

6=={;A>?
 !
 FMM$0CDQGHd$GHK
 
=
[ <s   $M))	r  r  rR  r  r  r  r  r  r  Nr>  )r@  rA  rB  rC  r  rE  rF  r   rW   r  r    s    [
r   r  c                    ^  \ rS rSr% \rS\S'             S1                       S2U 4S jjjrS3S jrS3S jr	S4S jr
        S5S jrS3S	 jrS3S
 jrS6S jrS6S jrS6S jrS6S jrS6S jrS6S jrS6S jrS6S jrS7S jrS8S jrS3S jrS3S jr    S9S jrS:S jrS:S jrS:S jrS:S jrS6S jrS;S jr S;S jr!S6S jr"S<S  jr#S=S! jr$S>S" jr%S3S# jr&S3S$ jr'S?S% jr(S@SAS& jjr)\*" \+5              SB                 SCS' jj5       r,SDS( jr-SES) jr.SFS* jr/          SGS+ jr0\1S;S, j5       r2\1S;S- j5       r3SHS. jr4SIS/ jr5S0r6U =r7$ )JStataReaderi\  z	IO[bytes]_path_or_bufc                  > [         TU ]  5         X l        X0l        X@l        XPl        X`l        Xpl        Xl        Xl	        Xl
        Xl        SU l        Xl        SU l        SU l        U R                  c  SU l        O&[!        U	["        5      (       a  U	S::  a  [%        S5      eS U l        SU l        SU l        SU l        SU l        SU l        S U l        SU l        [7        [8        R:                  5      U l        g )Nr   FrB   r   z.chunksize must be a positive integer when set.)superr  _convert_dates_convert_categoricals
_index_col_convert_missing_preserve_dtypes_columns_order_categoricals_original_path_or_buf_compression_storage_optionsr  
_chunksize_using_iterator_enteredr   ra   rh   _close_file_missing_values_can_read_value_labels_column_selector_set_value_labels_read
_data_read_dtype_lines_read_set_endiannesssysr3  _native_byteorder)r  path_or_bufconvert_datesconvert_categoricals	index_colconvert_missingpreserve_dtypescolumnsorder_categoricals	chunksizecompressionr7   	__class__s               rW   r  StataReader.__init__a  s     	 ,%9"# / /#5 %0"' /#$??"DOIs++yA~MNN 7;$&+#$)!"''+!0!?r   c                H    [        U S5      (       d  U R                  5         gg)z;
Ensure the file has been opened and its header data read.
r  N)hasattr
_open_filere  s    rW   _ensure_openStataReader._ensure_open  s      t^,,OO -r   c                x   U R                   (       d"  [        R                  " S[        [	        5       S9  [        U R                  SU R                  SU R                  S9n[        UR                  S5      (       aB  UR                  R                  5       (       a#  UR                  U l        UR                  U l        ONU   [        UR                  R!                  5       5      U l        SSS5        U R                  R                  U l        U R#                  5         U R%                  5         g! , (       d  f       NJ= f)zN
Open the file (with compression options, etc.), and read header information.
zStataReader is being used without using a context manager. Using StataReader as a context manager is the only supported method.rv   rbF)r7   is_textr  seekableN)r  r   r   ResourceWarningr   r)   r  r  r  r  handler  r  closer  r   read_read_header_setup_dtype)r  handless     rW   r  StataReader._open_file  s     }}MMW+-	 && 11))
 7>>:..7>>3J3J3L3L 'D&}}D $+GNN,?,?,A$B! #0066D s   >)D++
D9c                    SU l         U $ )zenter context managerT)r  re  s    rW   	__enter__StataReader.__enter__  s    r   c                H    U R                   (       a  U R                  5         g g rk  )r  )r  exc_type	exc_value	tracebacks       rW   __exit__StataReader.__exit__  s      r   c                    [         R                  " S[        [        5       S9  U R                  (       a  U R	                  5         gg)zClose the handle if its open.

.. deprecated: 2.0.0

   The close method is not part of the public API.
   The only supported way to use StataReader is to use it as a context manager.
zThe StataReader.close() method is not part of the public API and will be removed in a future version without notice. Using StataReader as a context manager is the only supported method.rv   N)r   r   FutureWarningr   r  re  s    rW   r  StataReader.close  s=     	S ')	
  r   c                B    U R                   S:  a  SU l        gSU l        g)z3
Set string encoding which depends on file version
v   r  r	  N)_format_versionr  re  s    rW   _set_encodingStataReader._set_encoding  s      #%&DN$DNr   c                h    [         R                  " SU R                  R                  S5      5      S   $ )Nr~  rB   r   r   r   r  r  re  s    rW   
_read_int8StataReader._read_int8  )    }}S$"3"3"8"8";<Q??r   c                h    [         R                  " SU R                  R                  S5      5      S   $ )NBrB   r   r5  re  s    rW   _read_uint8StataReader._read_uint8  r8  r   c                    [         R                  " U R                   S3U R                  R	                  S5      5      S   $ )NHr   r   r   r   
_byteorderr  r  re  s    rW   _read_uint16StataReader._read_uint16  5    }}02D4E4E4J4J14MNqQQr   c                    [         R                  " U R                   S3U R                  R	                  S5      5      S   $ )NIr   r   r?  re  s    rW   _read_uint32StataReader._read_uint32  rC  r   c                    [         R                  " U R                   S3U R                  R	                  S5      5      S   $ )Nr  r  r   r?  re  s    rW   _read_uint64StataReader._read_uint64  rC  r   c                    [         R                  " U R                   S3U R                  R	                  S5      5      S   $ )Nr  r   r   r?  re  s    rW   _read_int16StataReader._read_int16  rC  r   c                    [         R                  " U R                   S3U R                  R	                  S5      5      S   $ )Nr)  r   r   r?  re  s    rW   _read_int32StataReader._read_int32  rC  r   c                    [         R                  " U R                   S3U R                  R	                  S5      5      S   $ )Nr^  r  r   r?  re  s    rW   _read_int64StataReader._read_int64  rC  r   c                h    [         R                  " SU R                  R                  S5      5      S   $ )Nr-  rB   r   r5  re  s    rW   _read_char8StataReader._read_char8  r8  r   c                    [         R                  " U R                   SU-   3U R                  R	                  SU-  5      5      $ )Nr  r   r?  )r  counts     rW   _read_int16_countStataReader._read_int16_count  s@    }}e}-""1u9-
 	
r   c                t    U R                  5       nUS:X  a  U R                  5         g U R                  U5        g )N   <)rU  _read_new_header_read_old_header)r  
first_chars     rW   r  StataReader._read_header  s2    %%'
!!#!!*-r   c                   U R                   R                  S5        [        U R                   R                  S5      5      U l        U R                  S;  a&  [	        [
        R                  U R                  S95      eU R                  5         U R                   R                  S5        U R                   R                  S5      S:X  a  SOSU l        U R                   R                  S	5        U R                  S
::  a  U R                  5       OU R                  5       U l        U R                   R                  S5        U R                  5       U l        U R                   R                  S5        U R                  5       U l        U R                   R                  S5        U R!                  5       U l        U R                   R                  S5        U R                   R                  S5        U R                   R                  S5        U R%                  5       S-   U l        U R%                  5       S-   U l        U R%                  5       S-   U l        U R%                  5       S-   U l        U R%                  5       S-   U l        U R1                  5       U l        U R                   R                  S5        U R%                  5       S-   U l        U R%                  5       S-   U l        U R%                  5       S-   U l        U R;                  U R&                  5      u  U l        U l        U R                   RA                  U R(                  5        U RC                  5       U l"        U R                   RA                  U R*                  5        U RG                  U R                  S-   5      S S U l$        U R                   RA                  U R,                  5        U RK                  5       U l&        U R                   RA                  U R.                  5        U RO                  5       U l(        U R                   RA                  U R2                  5        U RS                  5       U l*        g )NrX  r   u   r0  w   version   s   MSF><   r0  r~            r     
   	   r      rB   )+r  r  ra   r1  rh   _version_errorrJ   r2  r@  rA  rF  _nvar	_get_nobs_nobs_get_data_label_data_label_get_time_stamp_time_stamprR  _seek_vartypes_seek_varnames_seek_sortlist_seek_formats_seek_value_label_names_get_seek_variable_labels_seek_variable_labels_data_location_seek_strls_seek_value_labels_get_dtypes_typlist	_dtyplistseek_get_varlist_varlistrY  _srtlist_get_fmtlist_fmtlist_get_lbllist_lbllist_get_variable_labels_variable_labelsre  s    rW   r]  StataReader._read_new_header	  se   r""4#4#4#9#9!#<=6^224;O;O2PQQr"!%!2!2!7!7!:f!D##r"#'#7#73#>DDDUDUDW 	
 	q!^^%
r"//1r"//1r"q!q!"..025"..025"..025!--/!3'+'7'7'9B'>$ &*%C%C%E"q!"..014++-1"&"2"2"4r"9(,(8(89L9L(M%t~t223))+t223..tzzA~>sCt112))+t;;<))+t99: $ 9 9 ;r   c                   U R                   R                  U5        / n/ n[        U R                  5       H  nU R	                  5       nUS::  a-  UR                  U5        UR                  [        U5      5        MF   UR                  U R                  U   5        UR                  U R                  U   5        M     X#4$ ! [         a  n[        SU S35      UeS nAff = f)N  cannot convert stata types [])r  r  r1  rt  rA  r"  r   r  r  KeyErrorrh   )r  seek_vartypestyplistdtyplist_typerrs          rW   r  StataReader._get_dtypesA  s     	}-tzz"A##%Cd{s#C)UNN4#4#4S#9:OOD$6$6s$;< #      U$'CC5%JKQTTUs   <<B??
C	CCc                    U R                   S:  a  SOSn[        U R                  5       Vs/ s H,  o R                  U R                  R                  U5      5      PM.     sn$ s  snf )Nr0  !      r1  r1  rt  _decoder  r  r  r~  r  s      rW   r  StataReader._get_varlistU  sQ    &&,B#AFtzzARSARAT..33A67ARSSSs   3A"c                   U R                   S:  a  SnO(U R                   S:  a  SnOU R                   S:  a  SnOSn[        U R                  5       Vs/ s H,  o R                  U R                  R                  U5      5      PM.     sn$ s  snf )Nr0  9   q   1   h   r   r~   r  r  s      rW   r  StataReader._get_fmtlist[  s{    3&A!!C'A!!C'AAAFtzzARSARAT..33A67ARSSSs   3B	c                    U R                   S:  a  SnOU R                   S:  a  SnOSn[        U R                  5       Vs/ s H,  o R                  U R                  R                  U5      5      PM.     sn$ s  snf )Nr0  r  r  r  rp  r  r  s      rW   r  StataReader._get_lbllisth  sh    3&A!!C'AAAFtzzARSARAT..33A67ARSSSs    3A6c                4   U R                   S:  aN  [        U R                  5       Vs/ s H,  oR                  U R                  R                  S5      5      PM.     nnU$ U R                   S:  aN  [        U R                  5       Vs/ s H,  oR                  U R                  R                  S5      5      PM.     nnU$ [        U R                  5       Vs/ s H,  oR                  U R                  R                  S5      5      PM.     nnU$ s  snf s  snf s  snf )Nr0  iA  r  Q   r*  r  )r  r  vlblists      rW   r   StataReader._get_variable_labelsq  s   3&CHCTCTaT..33C89CT    !!C'BG

BSBSQT..33B78BS    CH

BSBSQT..33B78BS   s   3D3D3Dc                b    U R                   S:  a  U R                  5       $ U R                  5       $ )Nr0  )r1  rI  rF  re  s    rW   ru  StataReader._get_nobs  s.    3&$$&&$$&&r   c                   U R                   S:  a:  U R                  5       nU R                  U R                  R	                  U5      5      $ U R                   S:X  a:  U R                  5       nU R                  U R                  R	                  U5      5      $ U R                   S:  a*  U R                  U R                  R	                  S5      5      $ U R                  U R                  R	                  S5      5      $ )Nr0  rc  r  r  r*  )r1  rA  r  r  r  r6  r  strlens     rW   rw  StataReader._get_data_label  s    3&&&(F<< 1 1 6 6v >??!!S(__&F<< 1 1 6 6v >??!!C'<< 1 1 6 6r :;;<< 1 1 6 6r :;;r   c                   U R                   S:  a:  U R                  5       nU R                  R                  U5      R	                  S5      $ U R                   S:X  a:  U R                  5       nU R                  U R                  R                  U5      5      $ U R                   S:  a*  U R                  U R                  R                  S5      5      $ [        5       e)Nr0  r	  rc  r     )r1  r6  r  r  decoder  rh   r  s     rW   ry  StataReader._get_time_stamp  s    3&__&F$$))&188AA!!S(__&F<< 1 1 6 6v >??!!C'<< 1 1 6 6r :;;,r   c                    U R                   S:X  a=  U R                  R                  S5        U R                  SU R                  -  -   S-   S-   $ U R                   S:  a  U R                  5       S-   $ [        5       e)Nrc  r  r        r0  )r1  r  r  r  rt  rR  rh   re  s    rW   r  %StataReader._get_seek_variable_labels  ss    3&""1% //2

?CbH2MM!!S(##%**,r   c           	     2	   [        US   5      U l        U R                  S;  a&  [        [        R	                  U R                  S95      eU R                  5         U R                  5       S:X  a  SOSU l        U R                  5       U l        U R                  R                  S5        U R                  5       U l        U R                  5       U l        U R                  5       U l        U R#                  5       U l        U R                  S:  a?  U R                  R                  U R                  5       Vs/ s H  n[        U5      PM     nnOU R                  R                  U R                  5      n[&        R(                  " U[&        R*                  S9n/ nU HF  nX`R,                  ;   a   UR/                  U R,                  U   5        M2  UR/                  US	-
  5        MH      U Vs/ s H  opR0                  U   PM     snU l         U Vs/ s H  opR8                  U   PM     snU l        U R                  S:  aS  [=        U R                  5       Vs/ s H,  oR?                  U R                  R                  S5      5      PM.     snU l         OR[=        U R                  5       Vs/ s H,  oR?                  U R                  R                  S5      5      PM.     snU l         U RC                  U R                  S-   5      S S U l"        U RG                  5       U l$        U RK                  5       U l&        U RO                  5       U l(        U R                  S:  af   U R                  5       nU R                  S:  a  U RS                  5       nOU RU                  5       nUS:X  a  OU R                  R                  U5        Me  U R                  RW                  5       U l,        g s  snf s  snf ! [         aF  nS
R5                  U V	s/ s H  n	[7        U	5      PM     Os  sn	f sn	5      n
[        SU
 S35      UeS nAff = fs  snf ! [         aF  nS
R5                  U V	s/ s H  n	[7        U	5      PM     Os  sn	f sn	5      n[        SU S35      UeS nAff = fs  snf s  snf )Nr   )r  r  r  o   r  r   s   re  rB   rh  ri  r  rx      ,r  r  zcannot convert stata dtypes [r  rp  rr  r  )-ra   r1  rh   rs  rJ   r2  r6  r@  	_filetyper  r  rA  rt  ru  rv  rw  rx  ry  rz  r   
frombufferr   r  r"  r  r  joinr   r  r  r1  r  r  rY  r  r  r  r  r  r  r  rO  rL  tellr  )r  r_  r-  r  buftyplistbtpr  r  r   invalid_typesinvalid_dtypesr  	data_typedata_lens                  rW   r^  StataReader._read_old_header  s   ":a=1'JJ^224;O;O2PQQ!%!2c!9#s*q!&&(
^^%
//1//1 #%'+'8'8'='=djj'IJ'I!s1v'IGJG##((4C}}S9HG...NN4#8#8#<=NN28,	 	W;BC7C]]3/7CDM	Y=DEWcnnS1WEDN
 #%BG

BSBSQT..33B78BSDM
 BGtzzARARAT..33A67ARDM ..tzzA~>sC))+))+ $ 9 9 ; #% OO-	''#-#//1H#//1H>!!&&x0  #//446o K D 	WHHg%>gc!fg%>?M;M?!LMSVV	W F 	Y XXw&?w!s1vw&?@N<^<LANOUXX	Y
s~   2O!O$ %O=O$ P< 
P7"P< 3R$3RO$ $
P4.P/=P
P//P47P< <
RRQ+
*RRc                   U R                   b  U R                   $ / n[        U R                  5       Hp  u  p#X0R                  ;   aC  [	        [
        U5      nUR                  SU 3U R                   U R                  U    345        MW  UR                  SU 3SU 345        Mr     [        R                  " U5      U l         U R                   $ )z"Map between numpy and state dtypessr  )
r  r  r  r  r   r   r"  r@  r   ry   )r  dtypesr)  r  s       rW   r   StataReader._setup_dtype  s    ;;";;.FA)))3n1#w4??*;D<O<OPS<T;U(VWX1#w!C5	23 / hhv&{{r   c                   UR                  S5      S   n UR                  U R                  5      $ ! [         aH    U R                  nSU S3n[        R
                  " U[        [        5       S9  UR                  S5      s $ f = f)Nr(  r   z@
One or more strings in the dta file could not be decoded using z, and
so the fallback encoding of latin-1 is being used.  This can happen when a file
has been incorrectly encoded by Stata or some other software. You should verify
the string values returned are correct.rv   r  )	partitionr  r  UnicodeDecodeErrorr   r   UnicodeWarningr   )r  r  r  msgs       rW   r  StataReader._decode  s    KKq!	'88DNN++! 	' ~~H@@Hz J(+C
 MM+-
 88I&&	's   1 ABBc                :   U R                  5         U R                  (       a  g U R                  S::  a  SU l        0 U l        g U R                  S:  a&  U R                  R                  U R                  5        OZU R                  c   eU R                  U R                  R                  -  nU R                  R                  U R                  U-   5        SU l        0 U l         U R                  S:  a!  U R                  R                  S5      S:X  a  GOU R                  R                  S5      nU(       d  GOU R                  S::  a+  U R                  U R                  R                  S5      5      nO*U R                  U R                  R                  S5      5      nU R                  R                  S	5        U R                  5       nU R                  5       n[        R                  " U R                  R                  SU-  5      U R                    S
3US9n[        R                  " U R                  R                  SU-  5      U R                    S
3US9n[        R"                  " U5      nXh   nXx   nU R                  R                  U5      n	0 U R                  U'   [%        U5       H<  n
XS-
  :  a  XjS-      OUnU R                  XU
   U 5      U R                  U   Xz   '   M>     U R                  S:  a  U R                  R                  S5        GM4  SU l        g )Nr  Trc     s   </valr   r  r  r   r  ry   rX  rB   r   )r  r  r1  _value_label_dictr  r  r  r  rv  itemsizer  r  r  rF  r   r  r@  argsortr1  )r  r7  slengthr  r  txtlenr  r  iir  r)  r  s               rW   _read_value_labelsStataReader._read_value_labels  s   ""3&&*D#BDD"3&""4#:#:;;;***ZZ$++"6"66F""4#6#6#?@"&!###s*$$))!,8'',,Q/G##s*,,t'8'8'='=b'AB,,t'8'8'='=c'BC""1%!!#A&&(F--!!&&q1u-7H5KSTC --!!&&q1u-7H5KSTC CB'C'C##((0C.0D""7+1X$%AIca%j6:>,,A%;&&w/7 
 ##s*!!&&q)C D #'r   c                   U R                   R                  U R                  5        SS0U l         U R                   R	                  S5      S:w  a  g U R
                  S:X  a  U R                  5       nOvU R                   R	                  S5      nU R
                  S:X  a  SOSnU R                  S	:X  a  US
U USSU-
   -   nOUS
U USU-   S  -   n[        R                  " SU5      S
   nU R                  5       nU R                  5       nU R                   R	                  U5      nUS:X  a  US
S R                  U R                  5      nO[        U5      nXpR                  [        U5      '   GM<  )N0r   r   s   GSOrc  r   r0  r   ri  r   r   r     rr  )r  r  r  GSOr  r1  rI  r@  r   r   r;  rF  r  r  r   )r  v_or  v_sizer  lengthva
decoded_vas           rW   _read_strlsStataReader._read_strlsS  sV   t//09  %%a(F2##s*'')'',,R0"22c9q??c)a-#a2;*@@C a-#q6zn*==CmmC-a0""$C&&(F""''/Bcz"X__T^^<
 !W
!+HHSX3 r   c                B    SU l         U R                  U R                  S9$ )NTnrows)r  r  r  re  s    rW   __next__StataReader.__next__r  s    #yyty//r   c                >    Uc  U R                   nU R                  US9$ )z
Reads lines from Stata file and returns as dataframe

Parameters
----------
size : int, defaults to None
    Number of lines to read.  If None, reads whole file.

Returns
-------
DataFrame
r  )r  r  )r  sizes     rW   	get_chunkStataReader.get_chunkv  s#     <??Dyyty$$r   c	           	       ^ U R                  5         Uc  U R                  nUc  U R                  nUc  U R                  nUc  U R                  nUc  U R
                  nUc  U R                  nUc  U R                  nUc  U R                  nU R                  S:X  a  US:X  a  SU l	        SU l
        [        U R                  S9n	[        U	R                  5       H\  u  pU R                  U
   n[!        U["        R$                  5      (       d  M5  UR&                  S:w  d  MG  X   R)                  U5      X'   M^     Ub  U R+                  X5      n	U	$ U R,                  S:  a(  U R.                  (       d  SU l	        U R1                  5         U R2                  c   eU R2                  nU R                  U R4                  -
  UR6                  -  nXR6                  -  n[9        X5      nUS::  a  U(       a  U R;                  5         [<        eU R4                  UR6                  -  nU R>                  RA                  U RB                  U-   5        [9        XR                  U R4                  -
  5      n["        RD                  " U R>                  RG                  U5      UUS9nU =R4                  U-  sl        U R4                  U R                  :X  a  SU l	        SU l
        U RH                  U RJ                  :w  a7  URM                  5       RO                  UR$                  RQ                  5       5      nU(       a  U R;                  5         [S        U5      S:X  a  [        U R                  S9n	O0[        RT                  " U5      n	[W        U R                  5      U	l        Uc(  [Y        U R4                  U-
  U R4                  5      U	l-        Ub  U R+                  X5      n	[]        XR^                  5       H<  u  nn[!        U[`        5      (       d  M  X   Rc                  U Rd                  5      X'   M>     U Rg                  U	5      n	[        U R                  5       V
Vs/ s H  u  n
nUc  M  U
PM     nn
n["        R$                  " [h        5      nU Hi  nU	Rj                  S S 2U4   R$                  nUUU R                  U   4;  d  M7  U	Rm                  UU	Rj                  S S 2U4   R)                  U5      5        Mk     U Ro                  X5      n	U(       al  [        U Rp                  5       HS  u  n
m[s        U4S j[t         5       5      (       d  M&  U	Rm                  U
[w        U	Rj                  S S 2U
4   T5      5        MU     U(       a7  U R,                  S:  a'  U Ry                  XRz                  U R|                  U5      n	U(       Gdo  / nS	nU	 GH>  nX   R$                  nU["        R$                  " ["        R~                  5      ["        R$                  " ["        R                  5      4;   a'  ["        R$                  " ["        R                  5      nSnOU["        R$                  " ["        R                  5      ["        R$                  " ["        R                  5      ["        R$                  " ["        R                  5      4;   a&  ["        R$                  " ["        R                  5      nSnUR                  XU   R)                  U5      45        GMA     U(       a  [        R                  " [        U5      5      n	Ub   U	R                  U	R                  U5      5      n	U	$ s  snn
f )
Nr   T)r  r  rc  r  c              3  F   >#    U  H  nTR                  U5      v   M     g 7frk  )r   ).0date_fmtr   s     rW   	<genexpr>#StataReader.read.<locals>.<genexpr>  s     NHs~~h//s   !r  F)Kr  r  r  r  r  r  r  r  rv  r  r   r$   r  r  r  r  r   r   ry   charr   _do_select_columnsr1  r  r  r  r  r  rN   r  StopIterationr  r  r  r  r  r@  r  byteswapr   newbyteorderr  from_recordsr%   r&   rK   rP   r  ra   r   r  _insert_strlsr   ilocisetitem_do_convert_missingr  r   _date_formatsr   _do_convert_categoricalsr  r  float16r   r   r   r   r   r   r"  	from_dictr  	set_indexpop)r  r  r  r  r	  r
  r  r  r  r   r)  r   dtry   max_read_lenread_lenr7  
read_linesraw_datar  dtypvalid_dtypesobject_typeidxretyped_dataconvertr   s                             @rW   r  StataReader.read  s    	   //M'#'#=#= ""33O""33O?mmG%!%!9!9I=JJE
 JJ!O!*.D'"DOT]]3D#DLL1^^A&b"((++ww#~$(I$4$4R$8		 2
 "..t=K  C'$2I2I*.D' {{&&&

T%5%55G>>)x.q= $'')!!ENN2t22V;<

T-=-= =>
==""8,E
 	J&tzz)*.D'"DO??d444((*//0K0K0MNH##%x=AT]]3D))(3D /DL #  :-t/?/?DJ **49D D--0HC#s## IOODLL9	 1 !!$' *34>>)BW)Bgad)BWhhv&CIIaf%++E[$..*=>>c499QV#4#;#;E#BC  
 ''>#DMM23NNNNMM>tyyAPST 3  D$8$83$>00,,dmm=OD LG	RXXbjj1288BJJ3GHHHHRZZ0E"GHHRWW%HHRXX&HHRXX& 
 HHRXX.E"G##Ss)*:*:5*A$BC   **4+=> >>$((9"56DW Xs   
]]c                   0 n[        [        UR                  5      5       GH  nU R                  U   nXPR                  ;  a  M$  [        [        U5      nU R                  U   u  pgUR                  S S 2U4   nUR                  n	X:  X:  -  n
U
R                  5       (       d  M  U(       a  [        R                  " [        R                  " U
5      5      S   n[        R                  " X   SS9u  p[        U[        S9n[!        U5       H'  u  nn[#        U5      nXU:H     nUUR                  U'   M)     OUR$                  nU[        R&                  [        R(                  4;  a  [        R(                  n[        UUS9nUR                  R*                  S   (       d  UR-                  5       n[        R.                  UR                  U
'   XU'   GM     U(       a,  UR1                  5        H  u  nnUR3                  UU5        M     U$ )Nr   T)return_inverserx   	WRITEABLE)r1  r  r  r  r  r   r   r  r   r   r   nonzeroasarrayuniquer'   r   r  r   ry   r   r   flagsr   nanrN  r	  )r  r   r
  replacementsr)  r   nminnmaxseriessvalsmissingmissing_locumissingumissing_locreplacementjumr   r   ry   r  rb   s                         rW   r
  StataReader._do_convert_missing  s   s4<<()A--"C***sC.C))#.JDYYq!t_F NNE|5G;;== jjG)<=a@)+6?SW)X&$V6:&x0EAr$5b$9M%a&78C,9K$$S)	 1 RZZ 88JJE$V59"**00= #."2"2"4K 02vv##G,)OK *L *002
Uc5) 3r   c                D   [        U S5      (       a  [        U R                  5      S:X  a  U$ [        U R                  5       HU  u  p#US:w  a  M  UR                  X!R                  S S 2U4    Vs/ s H  o@R                  [        U5         PM     sn5        MW     U$ s  snf )Nr  r   r  )r  r  r  r  r  r	  r  r   )r  r   r)  r  ks        rW   r  StataReader._insert_strlsM  s    tU##s488}'9K.FAczMM!		!Q$H1hhs1v.HI	 /
  Is   /!Bc                   U R                   (       Gd;  [        U5      n[        U5      [        U5      :w  a  [        S5      eUR	                  UR
                  5      nU(       a(  SR                  [        U5      5      n[        SU 35      e/ n/ n/ n/ n	U H  n
UR
                  R                  U
5      nUR                  U R                  U   5        UR                  U R                  U   5        UR                  U R                  U   5        U	R                  U R                  U   5        M     X`l
        Xpl        Xl        Xl        SU l         X   $ )Nz"columns contains duplicate entriesz, z<The following columns were not found in the Stata data set: T)r  setr  rh   
differencer  r  r  get_locr"  r  r  r  r  )r  r   r  
column_set	unmatchedjoinedr  r  fmtlistlbllistr   r)  s               rW   r  StataReader._do_select_columnsW  s&   (((WJ:#g,. !EFF"--dll;I4	?3 44:8= 
 HGGGLL((-q 12t}}Q/0t}}Q/0t}}Q/0  &N#M#M#M(,D%}r   c                   U(       d  U$ / n[        X5       GHl  u  pgXr;   GaK  X'   n[        R                  " [        UR	                  5       5      5      n	X   n
U
R                  U	5      nU R                  (       a  UR                  5       (       a  U	nO9U R                  (       a&  [        R                  " [        [        [        5       S9  Sn[        XUS9nUcA  / nUR                   H.  nX;   a  UR                  X   5        M  UR                  U5        M0     O[        UR!                  5       5      n UR#                  U5      n['        XR*                  SS9nUR                  UU45        GMW  UR                  XaU   45        GMo     [/        [1        U5      SS9nU$ ! [$         aa  n['        USS9R)                  5       n[        UR*                  US:     5      nSSR-                  U5      -   nS	U S
U S3n[%        U5      UeSnAff = f)z3
Converts categorical columns to Categorical type.
rv   N)r  orderedF)r   rB   zQ--------------------------------------------------------------------------------
r4   z
Value labels for column a    are not unique. These cannot be converted to
pandas categoricals.

Either read the file with `convert_categoricals` set to False or use the
low level interface in `StataReader` to separately read the values and the
value_labels.

The repeated labels are:
r   )rP   r   r  r  keysisinr  allr   r   r   r   r   r   r  r"  rk   rename_categoriesrh   r'   value_countsrK   r  r$   r  )r  r   value_label_dictr=  r  cat_converted_datar   labelr$  rA  columnkey_matchesinitial_categoriescat_datar  r%  r  vcrepeated_catsrepeatsr  
cat_seriess                         rW   r  $StataReader._do_convert_categoricalsw  s     Kd,JC(%,xxRWWY0$kk$/''KOO,=,=<@& ++ :8'7'9
 *.&&CU &-!#J$,$7$7#>&--bl;&--h7	 %8 "&biik!2J3  (99*EH& $HJJUK
"))3
*;<"))3S	*:;{ -| 01>/ " 3
7DDFB$("q&)9$:M-		-0HHG  		 

C %S/s2!3s   3F
H'AHHc                :    U R                  5         U R                  $ )a  
Return data label of Stata file.

Examples
--------
>>> df = pd.DataFrame([(1,)], columns=["variable"])
>>> time_stamp = pd.Timestamp(2000, 2, 29, 14, 21)
>>> data_label = "This is a data file."
>>> path = "/My_path/filename.dta"
>>> df.to_stata(path, time_stamp=time_stamp,    # doctest: +SKIP
...             data_label=data_label,  # doctest: +SKIP
...             version=None)  # doctest: +SKIP
>>> with pd.io.stata.StataReader(path) as reader:  # doctest: +SKIP
...     print(reader.data_label)  # doctest: +SKIP
This is a data file.
)r  rx  re  s    rW   
data_labelStataReader.data_label  s    $ 	r   c                :    U R                  5         U R                  $ )z"
Return time stamp of Stata file.
)r  rz  re  s    rW   
time_stampStataReader.time_stamp  s    
 	r   c                t    U R                  5         [        [        U R                  U R                  5      5      $ )a  
Return a dict associating each variable name with corresponding label.

Returns
-------
dict

Examples
--------
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=["col_1", "col_2"])
>>> time_stamp = pd.Timestamp(2000, 2, 29, 14, 21)
>>> path = "/My_path/filename.dta"
>>> variable_labels = {"col_1": "This is an example"}
>>> df.to_stata(path, time_stamp=time_stamp,  # doctest: +SKIP
...             variable_labels=variable_labels, version=None)  # doctest: +SKIP
>>> with pd.io.stata.StataReader(path) as reader:  # doctest: +SKIP
...     print(reader.variable_labels())  # doctest: +SKIP
{'index': '', 'col_1': 'This is an example', 'col_2': ''}
>>> pd.read_stata(path)  # doctest: +SKIP
    index col_1 col_2
0       0    1    2
1       1    3    4
)r  r  rP   r  r  re  s    rW   variable_labelsStataReader.variable_labels  s,    0 	Ct'<'<=>>r   c                \    U R                   (       d  U R                  5         U R                  $ )a  
Return a nested dict associating each variable name to its value and label.

Returns
-------
dict

Examples
--------
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=["col_1", "col_2"])
>>> time_stamp = pd.Timestamp(2000, 2, 29, 14, 21)
>>> path = "/My_path/filename.dta"
>>> value_labels = {"col_1": {3: "x"}}
>>> df.to_stata(path, time_stamp=time_stamp,  # doctest: +SKIP
...             value_labels=value_labels, version=None)  # doctest: +SKIP
>>> with pd.io.stata.StataReader(path) as reader:  # doctest: +SKIP
...     print(reader.value_labels())  # doctest: +SKIP
{'col_1': {3: 'x'}}
>>> pd.read_stata(path)  # doctest: +SKIP
    index col_1 col_2
0       0    1    2
1       1    x    4
)r  r  r  re  s    rW   r  StataReader.value_labels  s%    0 &&##%%%%r   )1r  r@  r  r  r  r  r  r  r  r  r  rx  r  r   r  r  r  r  r  r  r1  r  r  r  r  r  rv  rt  r  r  r  r  r~  r}  r  r  r  r  r|  r{  r  r  rz  r  r  r  r  r  r  )
TTNFTNTNinferN)r  FilePath | ReadBuffer[bytes]r  r   r  r   r	  
str | Noner
  r   r  r   r  Sequence[str] | Noner  r   r  
int | Noner  r.   r7   StorageOptions | Noner   r=  r>  )r   r1   )r'  ztype[BaseException] | Noner(  zBaseException | Noner)  zTracebackType | Noner   r=  )r   ra   )r   r?  )rX  ra   r   ztuple[int, ...])r  ra   r   z,tuple[list[int | str], list[str | np.dtype]])r   z	list[str]r{  )r_  r?  r   r=  )r   r|  )r  r?  r   r   )r   r$   rk  )r  ra  r   r$   )NNNNNNNN)r  ra  r  bool | Noner  rc  r	  r_  r
  rc  r  rc  r  r`  r  rc  r   r$   )r   r$   r
  r   r   r$   r   r$   r   r$   )r   r$   r  Sequence[str]r   r$   )
r   r$   rF  dict[str, dict[float, str]]r=  re  r  r   r   r$   )r   zdict[str, str])r   rf  )8r@  rA  rB  rC  _stata_reader_docrD  r}  r  r  r  r$  r*  r  r2  r6  r;  rA  rF  rI  rL  rO  rR  rU  rY  r  r]  r  r  r  r  r  ru  rw  ry  r  r^  r   r  r  r  r  r  r   _read_method_docr  r
  r  r  r  r  rS  rV  rY  r  rE  __classcell__r  s   @rW   r  r  \  s   G
 #%) $ % $(,#' $*115/@1/@ /@ #	/@
 /@ /@ /@ &/@ !/@ /@ (/@ //@ 
/@ /@b>
, ( (	
 
$%@@RRRRRR@
.5<p! !	5!(T
TT'
<

I7V '*7'r,>0%"  !%),0 $'+'+(,*.UU #U *	U
 U %U %U &U (U 
U  Un,\@LL 6L 	L
 !L 
L\    (    ?6& &r   r  TFr]  )r  r  r	  r
  r  r  r  r  iteratorr  r7   c                   [        U UUUUUUUUUU
S9nU	(       d  U(       a  U$ U   UR                  5       sS S S 5        $ ! , (       d  f       g = f)N)
r  r  r	  r
  r  r  r  r  r7   r  )r  r  )r6   r  r  r	  r
  r  r  r  r  rk  r  r7   readers                rW   
read_statarn    sQ      #1''-'F 9	{{} 
s   A  
Ac                t    U R                  5       S;   a  gU R                  5       S;   a  g[        SU  S35      e)N)ri  littleri  )rh  bigrh  zEndianness r   )lowerrh   )
endiannesss    rW   r  r  @  s>    _,				|	+;zl/BCCr   c                |    [        U [        5      (       a  U SU[        U 5      -
  -  -   $ U SU[        U 5      -
  -  -   $ )zI
Take a char string and pads it with null bytes until it's length chars.
r(   )r   r?  r  r   r  s     rW   r0  r0  I  sC     $g#d)!3444&FSY.///r   c                t    U S;   a$  [         R                  " [         R                  5      $ [        SU  S35      e)zC
Convert from one of the stata date formats to a type in TYPE_MAP.
)rs   r8   rz   r:   r|   r<   r   r=   r   r>   r   r?   r   r@   r   z not implemented)r   ry   r   NotImplementedError)r   s    rW   _convert_datetime_to_stata_typery  R  s;         xx

##!GC50@"ABBr   c                   0 nU  H  nX   R                  S5      (       d	  SX   -   X'   X1;   a&  UR                  UR                  U5      X   05        MO  [        U[        5      (       d  [        S5      eUR                  X0U   05        M     U$ )N%z0convert_dates key must be a column or an integer)r   updaterK   r   ra   rh   )r  varlistnew_dictrL  s       rW   _maybe_convert_to_int_keysr  k  s    H!,,S11!$}'9!9M>OOW]]3/1CDEc3'' !STTOOS"456  Or   c                   U R                   [        R                  L a*  [        [	        UR
                  5      5      n[        US5      $ U R                   [        R                  L a  gU R                   [        R                  L a  gU R                   [        R                  L a  gU R                   [        R                  L a  gU R                   [        R                  L a  g[        SU  S35      e)	a  
Convert 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
                     Pandas    Stata
251 - for int8      byte
252 - for int16     int
253 - for int32     long
254 - for float32   float
255 - for double    double

If there are dates to convert, then dtype will already have the correct
type inserted.
rB   r  r  r  r  r  
Data type  not supported.rp  r   object_r   r   r   rM   r   r   r   r   r   rx  )ry   rI  r  s      rW   _dtype_to_stata_typer  y  s    " zzRZZ (fnn(EF8Q	rzz	!	rzz	!	rxx		rxx		rww	!Jug_"EFFr   c                "   US:  a  SnO
SnU(       a  gU R                   [        R                  L am  [        [	        UR
                  5      5      nXT:  a/  US:  a  g[        [        R                  UR                  5      5      eS[        [        US5      5      -   S-   $ U [        R                  :X  a  gU [        R                  :X  a  g	U [        R                  :X  a  g
U [        R                  [        R                   4;   a  g[#        SU  S35      e)ar  
Map numpy dtype to stata's default format for this type. Not terribly
important since users can change this in Stata. Semantics are

object  -> "%DDs" where DD is the length of the string.  If not a string,
            raise ValueError
float64 -> "%10.0g"
float32 -> "%9.0g"
int64   -> "%9.0g"
int32   -> "%12.0g"
int16   -> "%8.0g"
int8    -> "%8.0g"
strl    -> "%9s"
rc     r  z%9sr{  rB   r  z%10.0gz%9.0gz%12.0gz%8.0gr  r  )rp  r   r  r   r   r   rh   r   rJ   r   r   rM   r   r   r   r   r   rx  )ry   rI  dta_version
force_strlmax_str_lenr  s         rW   _dtype_to_default_stata_fmtr    s    & SzzRZZ'fnn(EF!c! !>!E!Efkk!RSSSXq)**S00	"**		"**		"((		277BHH%	%!Jug_"EFFr   compression_optionsfname)r7   r  c                    ^  \ rS rSr% SrSrSrS\S'           S*SS.                       S+U 4S	 jjjjrS,S
 jr	S-S jr
    S.S jrS/S jrS/S jrS0S jrS1S jrS/S jrS2S jrS3S jrS0S jrS0S jrS0S jrS0S jrS0S jrS0S jrS0S jrS0S jrS0S jr  S4     S5S jjrS0S jrS0S jrS0S  jrS0S! jr S0S" jr!S0S# jr"S/S$ jr#S6S% jr$S7S& jr%\&S8S' j5       r'S9S( jr(S)r)U =r*$ ):StataWriteri  aj
  
A class for writing Stata binary dta files

Parameters
----------
fname : path (string), buffer or path object
    string, path object (pathlib.Path or py._path.local.LocalPath) or
    object implementing a binary write() functions. If using a buffer
    then the buffer will not be automatically closed after the file
    is written.
data : DataFrame
    Input to save
convert_dates : dict
    Dictionary mapping columns containing datetime types to stata internal
    format to use when writing the dates. Options are 'tc', 'td', 'tm',
    'tw', 'th', 'tq', 'ty'. Column can be either an integer or a name.
    Datetime columns that do not have a conversion type specified will be
    converted to 'tc'. Raises NotImplementedError if a datetime column has
    timezone information
write_index : bool
    Write the index to Stata dataset.
byteorder : str
    Can be ">", "<", "little", or "big". default is `sys.byteorder`
time_stamp : datetime
    A datetime to use as file creation date.  Default is the current time
data_label : str
    A label for the data set.  Must be 80 characters or smaller.
variable_labels : dict
    Dictionary containing columns as keys and variable labels as values.
    Each label must be 80 characters or smaller.
{compression_options}

    .. versionchanged:: 1.4.0 Zstandard support.

{storage_options}

value_labels : dict of dicts
    Dictionary containing columns as keys and dictionaries of column value
    to labels as values. The combined length of all labels for a single
    variable must be 32,000 characters or smaller.

    .. versionadded:: 1.4.0

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

Raises
------
NotImplementedError
    * If datetimes contain timezone information
ValueError
    * Columns listed in convert_dates are neither datetime64[ns]
      or datetime
    * Column dtype is not representable in Stata
    * Column listed in convert_dates is not in DataFrame
    * Categorical label contains more than 32,000 characters

Examples
--------
>>> data = pd.DataFrame([[1.0, 1]], columns=['a', 'b'])
>>> writer = StataWriter('./data_file.dta', data)
>>> writer.write_file()

Directly write a zip file
>>> compression = {{"method": "zip", "archive_name": "data_file.dta"}}
>>> writer = StataWriter('./data_file.zip', data, compression=compression)
>>> writer.write_file()

Save a DataFrame with dates
>>> from datetime import datetime
>>> data = pd.DataFrame([[datetime(2000,1,1)]], columns=['date'])
>>> writer = StataWriter('./date_data_file.dta', data, {{'date' : 'tw'}})
>>> writer.write_file()
r  r  r<  r  Nr  c                 > [         TU ]  5         X l        Uc  0 OUU l        X@l        X`l        Xpl        Xl        Xl        / U l	        [        R                  " / [        S9U l        Xl        S U l        0 U l        U R#                  U5        Xl        Uc  [&        R(                  n[+        U5      U l        Xl        [        R0                  [        R2                  [        R4                  S.U l        g )Nrx   )r  r  r  )r  r  r   r  _write_indexrz  rx  r  _non_cat_value_labels_value_labelsr   r  r   _has_value_labelsr  _output_file_converted_names_prepare_pandasr7   r  r3  r  r@  _fnamer   r   r   type_converters)r  r  r   r  write_indexr3  rV  rS  rY  r  r7   r  r  s               rW   r  StataWriter.__init__ 	  s     		$1$9b}'%% /%1"46!#"D!9'.257T".I))4%'XXBHH277Kr   c                    U R                   R                  R                  UR                  U R                  5      5        g)zC
Helper to call encode before writing to file for Python 3 compat.
N)r!  r  r.  r!  r  )r  to_writes     rW   _writeStataWriter._writeF	  s)     	!!(//$.."ABr   c                N    U R                   R                  R                  U5        g)z/
Helper to assert file is open before writing.
N)r!  r  r.  rb  s     rW   _write_bytesStataWriter._write_bytesL	  s     	!!%(r   c                   / nU R                   c  U$ U R                   R                  5        H  u  p4X0R                  ;   a  U R                  U   nO*X1R                  ;   a  [	        U5      nO[        SU S35      e[        X   R                  5      (       d  [        SU S35      e[        XTU R                  5      nUR                  U5        M     U$ )zK
Check for value labels provided for non-categorical columns. Value
labels
zCan't create value labels for z!, it wasn't found in the dataset.z6, value labels can only be applied to numeric columns.)r  rN  r  r  r   r  r   ry   rh   rH  r  r"  )r  r   non_cat_value_labelsr  labelscolnamesvls          rW   _prepare_non_cat_value_labels)StataWriter._prepare_non_cat_value_labelsR	  s     =?%%-''#99??AOG/////8LL(g,4WI >, , 
 $DM$7$788 !4WI >> >  (HC '','  B( $#r   c                   UR                    Vs/ s H  n[        U[        5      PM     nn[        U5      (       d  U$ U =R                  [
        R                  " U5      -  sl        [        R                  n/ n[        X5       GH  u  pgU(       Ga  [        X   U R                  S9nU R                  R                  U5        X   R                  R                  R                   nU[
        R"                  :X  a  [%        S5      eX   R                  R                  R&                  R)                  5       n	U	R+                  5       U" U5      :  a  U[
        R,                  :X  a%  [
        R                   " [
        R.                  5      nO]U[
        R.                  :X  a%  [
        R                   " [
        R0                  5      nO$[
        R                   " [
        R2                  5      n[
        R                  " XS9n	U" U5      XS:H  '   UR                  Xi45        GM  UR                  XaU   45        GM     [4        R6                  " [9        U5      5      $ s  snf )zr
Check for categorical columns, retain categorical information for
Stata file and convert categorical data to int
)r  zCIt is not possible to export int64-based categorical data to Stata.rx   rr  )r  r   r   r   r  r   r  r   ry  rP   r  r  r  r"  r  codesry   r   rh   r   r   rM   r   r   r   r   r$   r  r  )
r  r   ry   is_catry  data_formattedr   
col_is_catr  rk   s
             rW   _prepare_categoricals!StataWriter._prepare_categoricalss	  s   
 DH;;O;%*U$45;O6{{K"((6"22!2!I!I"40OC%di$..I""))#.	++11BHH$$A  ,,4499; ::<#9%#@@' " 2"((* " 2 " 4XXf:F (>e'D|$%%sm4%%sI&675  16 ""4#788G Ps   Ic                   U H  nX   R                   nU[        R                  [        R                  4;   d  M7  U[        R                  :X  a  U R                  S   nOU R                  S   nX   R                  U5      X'   M     U$ )zn
Checks floating point data columns for nans, and replaces these with
the generic Stata for missing value (.)
r   r\   )ry   r   r   r   rR  r   )r  r   r-  ry   r.  s        rW   _replace_nansStataWriter._replace_nans	  ss     AGMMERZZ00BJJ&"&"5"5c":K"&"5"5c":K'..5  r   c                    g)zNo-op, forward compatibilityNrF  re  s    rW   _update_strl_namesStataWriter._update_strl_names	      r   c                    U HG  nUS:  d  US:  d  M  US:  d  US:  d  M  US:  d  US:  d  M-  US:w  d  M5  UR                  US5      nMI     U$ )a  
Validate variable names for Stata export.

Parameters
----------
name : str
    Variable name

Returns
-------
str
    The validated name with invalid characters replaced with
    underscores.

Notes
-----
Stata 114 and 117 support ascii characters in a-z, A-Z, 0-9
and _.
AZazr  9r  )replacer  r   r-  s      rW   _validate_variable_name#StataWriter._validate_variable_name	  sS    ( ASAGWCWCH||As+  r   c                   0 n[        UR                  5      nUSS nSn[        U5       H  u  pgUn[        U[        5      (       d  [	        U5      nU R                  U5      nXpR                  ;   a  SU-   nSUS   s=::  a  S::  a  O  OSU-   nUS[        [        U5      S5       nXx:X  d^  UR                  U5      S:  aE  S[	        U5      -   U-   nUS[        [        U5      S5       nUS-  nUR                  U5      S:  a  ME  XrU'   XsU'   M     [        U5      Ul        U R                  (       aD  [        X45       H5  u  pX:w  d  M  U R                  U
   U R                  U	'   U R                  U
	 M7     U(       ay  / nUR                  5        H  u  pU SU 3nUR                  U5        M     [        R!                  S	R#                  U5      5      n[$        R&                  " U[(        [+        5       S
9  X l        U R/                  5         U$ )a|  
Checks column names to ensure that they are valid Stata column names.
This includes checks for:
    * Non-string names
    * Stata keywords
    * Variables that start with numbers
    * Variables with names that are too long

When an illegal variable name is detected, it is converted, and if
dates are exported, the variable name is propagated to the date
conversion dictionary
Nr   r  r  r  r*  rB   z   ->   z
    rv   )r  r  r  r   r   r  r  rN   r  rX  r%   r  rP   rN  r"  r   rJ   r  r   r   r   r   r  r  )r  r   converted_namesr  original_columnsduplicate_var_idr/  r   	orig_namer-  oconversion_warningr  r   s                 rW   _check_column_namesStataWriter._check_column_names	  s    02t||$"1: )GAIdC((4y//5D ***Tz d1g$$Tz,#c$i,-D$mmD)A-%5!66=D 4#c$i"45D$)$	 mmD)A-
 .2	*AJ5 *8 W~ G66-1-@-@-CD''*++A. 7
 !##2#8#8#:	"8D62"))#. $; "((7I)JKBMM!+- !0!r   c                   / U l         / U l        UR                  5        Hg  u  p#U R                   R                  [	        X0R
                  U   5      5        U R                  R                  [        X0R
                  U   5      5        Mi     g rk  )r<  r  rN  r"  r  r   r  )r  r  r   ry   s       rW   _set_formats_and_types"StataWriter._set_formats_and_types
  sb    "$"$ ,,.JCLL ;E99S> RSLL 4UIIcN KL )r   c                d   UR                  5       nU R                  (       a'  UR                  5       n[        U[        5      (       a  UnU R                  U5      n[        U5      nU R                  U5      n[        R                  " SUR                  S   5      U l        U R                  U5      nU Vs/ s H  oDR                  PM     nnUR                  R                  U5      nU =R                  U-  sl        U R                   R#                  U5        U R%                  U5      nUR                  u  U l        U l        Xl        UR                  R-                  5       U l        UR0                  nU HM  nXR2                  ;   a  M  [4        R6                  " X   R8                  S5      (       d  M>  SU R2                  U'   MO     [;        U R2                  U R.                  5      U l        U R2                   H>  n	[=        U R2                  U	   5      n
[        R8                  " U
5      UR>                  U	'   M@     U RA                  5         U RC                  U5        U R2                  bG  U R2                   H6  n	[        U	[D        5      (       d  M  U R2                  U	   U RF                  U	'   M8     g g s  snf )NFrB   r   rs   )$r   r  reset_indexr   r$   r  r  r  r   repeatr   r  r  r  r  rB  r  extendr  nobsnvarr   tolistr}  r  r  r   r   ry   r  ry  r  _encode_stringsr  ra   r<  )r  r   tempr  r  non_cat_columnshas_non_cat_val_labelsr  r   rL  new_types              rW   r  StataWriter._prepare_pandas
  s<    yy{##%D$	** ''- $D) !!$' "$5$**Q-!@  $AA$G2FG2F3;;2FG!%!2!2?!C"88!!"67 ))$/#zz	49	||**, C)))ty44+/##C(	  9
 &&C6t7J7J37OPH!xx1FKK '
 	##F+ ***c3''(,(;(;C(@DLL% + +E Hs   4J-c                N   U R                   n[        U S/ 5      n[        U R                  5       H  u  p4X1;   d  XB;   a  M  U R                  U   nUR                  nUR
                  [        R                  L d  MK  [        USS9nUS:X  d*  [        U5      S:X  d  UR                  n[        SU S35      eU R                  U   R                  R                  U R                  5      n[        [!        UR"                  5      5      U R$                  ::  d  M  XR                  U'   M     g)	z
Encode strings in dta-specific encoding

Do not encode columns marked for date conversion or for strL
conversion. The strL converter independently handles conversion and
also accepts empty string arrays.
_convert_strlTr   rf  r   zColumn `a  ` cannot be exported.

Only string-like object arrays
containing all strings or a mix of strings and None can be exported.
Object arrays containing only null values are prohibited. Other object
types cannot be exported and must first be converted to one of the
supported types.N)r  rO   r  r   ry   rp  r   r  r   r  r   rh   r   r!  r  r   r   r   _max_string_length)	r  r  convert_strlr)  r   rI  ry   inferred_dtypeencodeds	            rW   r  StataWriter._encode_stringsa
  s    ++t_b9		*FA!S%8YYs^FLLEzzRZZ'!,VD!A'83Fq8H ++C$		   ))C.,,33DNNC )w)GH../ &-IIcN1 +r   c           	        [        U R                  SU R                  SU R                  S9 U l        U R                  R
                  S   bn  U R                  R                  [        5       sU l        U R                  l        U R                  R                  R                  U R                  R                  5         U R                  U R                  U R                  S9  U R                  5         U R                  5         U R!                  5         U R#                  5         U R%                  5         U R'                  5         U R)                  5         U R+                  5         U R-                  5         U R/                  5       nU R1                  U5        U R3                  5         U R5                  5         U R7                  5         U R                  5         U R9                  5          SSS5        g! [:         a  nU R                  R=                  5         [?        U R                  [@        [B        RD                  45      (       a  [B        RF                  RI                  U R                  5      (       ad   [B        RJ                  " U R                  5        Ue! [L         a4    [N        RP                  " SU R                   S3[R        [U        5       S	9   Uef = fUeSnAff = f! , (       d  f       g= f)
aI  
Export DataFrame object to Stata dta format.

Examples
--------
>>> df = pd.DataFrame({"fully_labelled": [1, 2, 3, 3, 1],
...                    "partially_labelled": [1.0, 2.0, np.nan, 9.0, np.nan],
...                    "Y": [7, 7, 9, 8, 10],
...                    "Z": pd.Categorical(["j", "k", "l", "k", "j"]),
...                    })
>>> path = "/My_path/filename.dta"
>>> labels = {"fully_labelled": {1: "one", 2: "two", 3: "three"},
...           "partially_labelled": {1.0: "one", 2.0: "two"},
...           }
>>> writer = pd.io.stata.StataWriter(path,
...                                  df,
...                                  value_labels=labels)  # doctest: +SKIP
>>> writer.write_file()  # doctest: +SKIP
>>> df = pd.read_stata(path)  # doctest: +SKIP
>>> df  # doctest: +SKIP
    index fully_labelled  partially_labeled  Y  Z
0       0            one                one  7  j
1       1            two                two  7  k
2       2          three                NaN  9  l
3       3          three                9.0  8  k
4       4            one                NaN 10  j
wbF)r  r  r7   methodN)rS  rV  z!This save was not successful but z. could not be deleted. This file is not valid.rv   )+r)   r  r  r7   r!  r  r  r   r  created_handlesr"  _write_headerrx  rz  
_write_map_write_variable_types_write_varnames_write_sortlist_write_formats_write_value_label_names_write_variable_labels_write_expansion_fields_write_characteristics_prepare_data_write_data_write_strls_write_value_labels_write_file_close_tag_close	Exceptionr  r   r   osPathLikepathisfileunlinkOSErrorr   r   r  r   )r  recordsexcs      rW   
write_fileStataWriter.write_file
  sN   8 KK)) 00
 \||''1= :>9L9Lgi6!4<<#6,,33DLL4G4GH"""#//D<L<L #  !**,$$&$$&##%--/++-,,.++-,,.  )!!#((***,!A
 
B  ""$dkkC+=>>277>>KKD D		$++. 	 #  ?} MB B+'7'9	 	 	C
 
sP   BK;D%G**
K4A7K, JK:KKKKKK
K'c                >   U R                   b  [        U R                  R                  [        5      (       d   eU R                  R                  U R                   soR                  l        U R                  R                  R                  UR                  5       5        gg)z
Close the file if it was created by the writer.

If a buffer or file-like object was passed in, for example a GzipFile,
then leave this file open for the caller to close.
N)r  r   r!  r  r   r.  r2  )r  r4  s     rW   r  StataWriter._close
  sq     (dll117;;;;'+||':':D<M<M$C$LL%%clln5 )r   c                    gNo-op, future compatibilityNrF  re  s    rW   r  StataWriter._write_map
  r  r   c                    gr  rF  re  s    rW   r  !StataWriter._write_file_close_tag
  r  r   c                    gr  rF  re  s    rW   r  "StataWriter._write_characteristics
  r  r   c                    gr  rF  re  s    rW   r  StataWriter._write_strls
  r  r   c                :    U R                  [        SS5      5        g)z"Write 5 zeros for expansion fieldsr   r  N)r  r0  re  s    rW   r  #StataWriter._write_expansion_fields
  s    Jr1%&r   c                ~    U R                    H-  nU R                  UR                  U R                  5      5        M/     g rk  )r  r  r9  r@  )r  r$  s     rW   r  StataWriter._write_value_labels
  s/    $$Bb55dooFG %r   c           	        U R                   nU R                  [        R                  " SS5      5        U R	                  US:H  =(       a    S=(       d    S5        U R	                  S5        U R	                  S5        U R                  [        R                  " US-   U R
                  5      S S 5        U R                  [        R                  " US	-   U R                  5      S S
 5        Uc+  U R                  U R                  [        SS5      5      5        O-U R                  U R                  [        US S S5      5      5        Uc  [        R                  " 5       nO [        U[        5      (       d  [        S5      e/ SQn[        U5       VVs0 s H  u  pVUS-   U_M     nnnUR                  S5      XrR                     -   UR                  S5      -   nU R                  U R                  U5      5        g s  snnf )Nr~  r  rh  ru  r  r   r)  r   r   P   "time_stamp should be datetime typeJanFebMarAprMayJunJulAugSepOctNovDecrB   %d 	 %Y %H:%M)r@  r  r   r/  r  r  r  _null_terminate_bytesr0  r   nowr   rh   r  strftimerR   )	r  rS  rV  r3  monthsr)  rR   month_lookuptss	            rW   r  StataWriter._write_header
  s   
 OO	&++c3/0I$/96:FF&++i#otyyA"1EF&++i#otyyA"1EFd88B9KLM**:j"or+JK
 !JJ11ABB
 6?v5FG5FAu5FG&++,-!!+./ 	
 	$44R89 Hs   G5c                v    U R                    H)  nU R                  [        R                  " SU5      5        M+     g )Nr:  )r  r  r   r/  )r  r  s     rW   r  !StataWriter._write_variable_types+  s)    <<Cfkk#s34  r   c                    U R                    H4  nU R                  U5      n[        US S S5      nU R                  U5        M6     g )Nr*  r  )r}  _null_terminate_strr0  r  )r  r   s     rW   r  StataWriter._write_varnames/  s@     LLD++D1Dd3Bi,DKK !r   c                ^    [        SSU R                  S-   -  5      nU R                  U5        g )Nr   r   rB   )r0  r  r  )r  srtlists     rW   r  StataWriter._write_sortlist7  s'    Rdii!m!45Gr   c                `    U R                    H  nU R                  [        US5      5        M      g )Nr  )r<  r  r0  )r  r   s     rW   r  StataWriter._write_formats<  s#    <<CKK
3+,  r   c                   [        U R                  5       Ht  nU R                  U   (       aB  U R                  U   nU R	                  U5      n[        US S S5      nU R                  U5        MY  U R                  [        SS5      5        Mv     g )Nr*  r  r   )r1  r  r  r}  r0  r0  r  )r  r)  r   s      rW   r  $StataWriter._write_value_label_namesA  sq    tyy!A%%a(||A//5!$s)R0D!Jr2./ "r   c                   [        SS5      nU R                  c.  [        U R                  5       H  nU R	                  U5        M     g U R
                   H  nX0R                  ;   aj  U R                  U   n[        U5      S:  a  [        S5      e[        S U 5       5      nU(       d  [        S5      eU R	                  [        US5      5        M|  U R	                  U5        M     g )Nr   r  r  .Variable labels must be 80 characters or fewerc              3  >   #    U  H  n[        U5      S :  v   M     g7f)   N)ord)r  r-  s     rW   r  5StataWriter._write_variable_labels.<locals>.<genexpr>[  s     <eAes   zKVariable labels must contain only characters that can be encoded in Latin-1)	r0  r  r1  r  r  r   r  rh   rC  )r  blankr)  r   rH  	is_latin1s         rW   r  "StataWriter._write_variable_labelsM  s    2r"  (499%E" &99C+++--c2u:?$%UVV<e<<	 $4  Jub12E" r   c                    U$ )r  rF  )r  r   s     rW   _convert_strlsStataWriter._convert_strlse  s    r   c                B   U R                   nU R                  nU R                  nU R                  b8  [        U5       H)  u  pEXC;   d  M  [	        X   U R
                  U   5      X'   M+     U R                  U5      n0 nU R                  [        [        R                  5      :H  n[        U5       H  u  pEX$   nXR                  ::  a  [        R                  " 5          [        R                  " SS[        S9  X   R!                  S5      n	S S S 5        W	R#                  [$        U4S9X'   SU 3n
XU'   X   R'                  U
5      X'   M  X   R(                  nU(       d  UR+                  U R                  5      nXU'   M     UR-                  SUS9$ ! , (       d  f       N= f)	NignorezDowncasting object dtype arrays)r%  r   )argsr  F)rK   column_dtypes)r   r  r  r  r   r<  rC  r@  r  r  r3  r  r   catch_warningsfilterwarningsr-  r   r   r0  r   ry   r  
to_records)r  r   r  r  r)  r   r  native_byteorderr  dcstypery   s               rW   r  StataWriter._prepare_datai  sq   yy,,++*#D/% >	4<<?!DI * ""4( ??ocmm.LLoFA*C---,,.++ 9!.
 ))"-B / HHZsfH=	C5	#s I,,U3		'!..t?E#s% &( U&AA# /.s   .F
F	c                B    U R                  UR                  5       5        g rk  )r  tobytesr  r  s     rW   r  StataWriter._write_data  s    '//+,r   c                    U S-  n U $ )Nru  rF  )r  s    rW   r0  StataWriter._null_terminate_str  s    	Vr   c                V    U R                  U5      R                  U R                  5      $ rk  )r0  r!  r  )r  r  s     rW   r&  !StataWriter._null_terminate_bytes  s"    ''*11$..AAr   )r@  r  r  r  rx  r  r  r  r  rz  r  r  r  r   r<  r!  r  r  r7   r  r  r}  )NTNNNNr]  N)r  FilePath | WriteBuffer[bytes]r   r$   r  dict[Hashable, str] | Noner  r   r3  r_  rV  datetime | NonerS  r_  rY  rY  r  r.   r7   rb  r  'dict[Hashable, dict[float, str]] | Noner   r=  )r  r   r   r=  )rb   r?  r   r=  )r   r$   r   zlist[StataNonCatValueLabel]rd  r>  r   r   r   r   r  r'   r   r=  )r   r$   r   r=  NNrS  r_  rV  rZ  r   r=  )r   np.rec.recarray)r  r`  r   r=  )r  r   r   r   )r  r   r   r?  )+r@  rA  rB  rC  rD  r  r  r}  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  rC  r  r  staticmethodr0  r&  rE  ri  rj  s   @rW   r  r    s   
L\ -6I*6 59  $&*!%6:*115$L AE$L,$L $L 2	$L
 $L $L $$L $L 4$L ($L /$L >$L 
$L $LLC)$$	$$B(9T"+<GRM@AD#-JKZ6****'H "&&*5:5: $5: 
	5:n5
-

0#0%BN-  B Br   r  c                   U(       a  gU R                   [        R                  L a3  [        [	        UR
                  5      5      n[        US5      nUS::  a  U$ gU R                   [        R                  L a  gU R                   [        R                  L a  gU R                   [        R                  L a  gU R                   [        R                  L a  gU R                   [        R                  L a  g[        S	U  S
35      e)a  
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 - 2045 are strings of this length
            Pandas    Stata
32768 - for object    strL
65526 - for int8      byte
65527 - for int16     int
65528 - for int32     long
65529 - for float32   float
65530 - for double    double

If there are dates to convert, then dtype will already have the correct
type inserted.
r  rB   r  r  r  r  r  r  r  r  r  )ry   rI  r  r  s       rW   _dtype_to_stata_type_117rc    s    $ zzRZZ (fnn(EFx#tO	rzz	!	rzz	!	rxx		rxx		rww	!Jug_"EFFr   c                l    [        U [        5      (       a  [        U S5      n U SU[        U 5      -
  -  -   $ )zM
Takes a bytes instance and pads it with null bytes until it's length chars.
r	  r(  )r   r   r?  r  rv  s     rW   _pad_bytes_newre    s6     $T7#'Vc$i/000r   c                  Z    \ rS rSrSr  S	         S
S jjrSS jrSS jrSS jrSr	g)StataStrLWriteri  au  
Converter for Stata StrLs

Stata StrLs map 8 byte values to strings which are stored using a
dictionary-like format where strings are keyed to two values.

Parameters
----------
df : DataFrame
    DataFrame to convert
columns : Sequence[str]
    List of columns names to convert to StrL
version : int, optional
    dta version.  Currently supports 117, 118 and 119
byteorder : str, optional
    Can be ">", "<", "little", or "big". default is `sys.byteorder`

Notes
-----
Supports creation of the StrL block of a dta file for dta versions
117, 118 and 119.  These differ in how the GSO is stored.  118 and
119 store the GSO lookup value as a uint32 and a uint64, while 117
uses two uint32s. 118 and 119 also encode all strings as unicode
which is required by the format.  117 uses 'latin-1' a fixed width
encoding that extends the 7-bit ascii table with an additional 128
characters.
Nc                *   US;  a  [        S5      eX0l        Xl        X l        SS0U l        Uc  [
        R                  n[        U5      U l        SnSnSU l	        US:X  a  S	nSnS
U l	        OUS:X  a  SnOSnSSSU-
  -  -  U l
        X`l        XPl        g )Nrb  z,Only dta versions 117, 118 and 119 supportedr   r   r   rE  r  r	  rc  r   r  r0  r   r  r   r  )rh   _dta_verdfr  
_gso_tabler  r3  r  r@  r  _o_offet_gso_o_type_gso_v_type)r  rk  r  rf  r3  
gso_v_type
gso_o_typeo_sizes           rW   r  StataStrLWriter.__init__  s     /)KLLv,I))4

 c>FJ&DN^FFa1v:./%%r   c                ,    Uu  p#X R                   U-  -   $ rk  )rm  )r  rL  r   r  s       rW   _convert_keyStataStrLWriter._convert_key  s    ==1$$$r   c                   U R                   nU R                  n[        UR                  5      nX R                     nU R                   Vs/ s H  oUUR	                  U5      4PM     nn[
        R                  " UR                  [
        R                  S9n[        UR                  5       5       Hb  u  nu  p[        U5       HK  u  nu  p\X   nUc  SOUnUR                  US5      nUc  US-   US-   4nXU'   U R                  U5      XxU4'   MM     Md     [        U R                  5       H  u  pUSS2U4   X%'   M     X4$ s  snf )aP  
Generates the GSO lookup table for the DataFrame

Returns
-------
gso_table : dict
    Ordered dictionary using the string found as keys
    and their lookup position (v,o) as values
gso_df : DataFrame
    DataFrame where strl columns have been converted to
    (v,o) values

Notes
-----
Modifies the DataFrame in-place.

The DataFrame returned encodes the (v,o) values as uint64s. The
encoding depends on the dta version, and can be expressed as

enc = v + o * 2 ** (o_size * 8)

so that v is stored in the lower bits and o is in the upper
bits. o_size is

  * 117: 4
  * 118: 6
  * 119: 5
rx   Nr   rB   )rl  rk  r  r  rK   r   emptyr   r   r  iterrowsgetru  )r  	gso_tablegso_dfr  selectedr   	col_indexrA  r  r  rowr/  r   r  rL  r)  s                   rW   generate_tableStataStrLWriter.generate_table  s+   : OO	v~~&,,':>,,G,37==-.,	Gxxbii8&x'8'8':;MAz(38ChKbSmmC.;q5!a%.C%(cN!..s3T
  4 <  -FAq!t*FK .   ! Hs   
E c           	     B   [        5       n[        SS5      n[        R                  " U R                  S-   S5      n[        R                  " U R                  S-   S5      nU R                  U R
                  -   nU R                  U R                  -   nU R                  S-   nUR                  5        H  u  pU
S:X  a  M  U
u  pUR                  U5        UR                  [        R                  " Xk5      5        UR                  [        R                  " X|5      5        UR                  U5        [        U	S5      nUR                  [        R                  " U[        U5      S	-   5      5        UR                  U5        UR                  U5        M     UR                  5       $ )
aw  
Generates the binary blob of GSOs that is written to the dta file.

Parameters
----------
gso_table : dict
    Ordered dictionary (str, vo)

Returns
-------
gso : bytes
    Binary content of dta file to be placed between strl tags

Notes
-----
Output format depends on dta version.  117 uses two uint32s to
express v and o while 118+ uses a uint32 for v and a uint64 for o.
r  asciir:  r  r   rE  ri  r	  rB   )r   r?  r   r/  r@  ro  rn  rN  r.  r  r2  )r  r{  r4  gsogso_typenullv_typeo_typelen_typestrlvor   r  utf8_strings                 rW   generate_blobStataStrLWriter.generate_blobD  sB   : iE7#;;t4c:{{4??S0!44#3#334#3#33??S(!)HDV|DA IIcN IIfkk&,- IIfkk&,- IIh  g.KIIfkk(C,<q,@AB IIk"IIdO/ *2 ||~r   )	r@  rj  r  rn  rl  ro  rm  r  rk  )rc  N)
rk  r$   r  re  rf  ra   r3  r_  r   r=  )rL  ztuple[int, int]r   ra   )r   z,tuple[dict[str, tuple[int, int]], DataFrame])r{  zdict[str, tuple[int, int]]r   r?  )
r@  rA  rB  rC  rD  r  ru  r  r  rE  rF  r   rW   rg  rg    sV    @  $&& & 	&
 & 
&B%1!f=r   rg  c                  b  ^  \ rS rSrSrSrSr         SSS.                         SU 4S jjjjr\SS j5       r	SS	 jr
  S      S!S
 jjrS"S jrS"S jrS"S jrS"S jrS"S jrS"S jrS"S jrS"S jrS"S jrS"S jrS"S jrS"S jrS"S jrS"S jrS#S jrS$S jrSrU =r$ )%StataWriter117i  aY  
A class for writing Stata binary dta files in Stata 13 format (117)

Parameters
----------
fname : path (string), buffer or path object
    string, path object (pathlib.Path or py._path.local.LocalPath) or
    object implementing a binary write() functions. If using a buffer
    then the buffer will not be automatically closed after the file
    is written.
data : DataFrame
    Input to save
convert_dates : dict
    Dictionary mapping columns containing datetime types to stata internal
    format to use when writing the dates. Options are 'tc', 'td', 'tm',
    'tw', 'th', 'tq', 'ty'. Column can be either an integer or a name.
    Datetime columns that do not have a conversion type specified will be
    converted to 'tc'. Raises NotImplementedError if a datetime column has
    timezone information
write_index : bool
    Write the index to Stata dataset.
byteorder : str
    Can be ">", "<", "little", or "big". default is `sys.byteorder`
time_stamp : datetime
    A datetime to use as file creation date.  Default is the current time
data_label : str
    A label for the data set.  Must be 80 characters or smaller.
variable_labels : dict
    Dictionary containing columns as keys and variable labels as values.
    Each label must be 80 characters or smaller.
convert_strl : list
    List of columns names to convert to Stata StrL format.  Columns with
    more than 2045 characters are automatically written as StrL.
    Smaller columns can be converted by including the column name.  Using
    StrLs can reduce output file size when strings are longer than 8
    characters, and either frequently repeated or sparse.
{compression_options}

    .. versionchanged:: 1.4.0 Zstandard support.

value_labels : dict of dicts
    Dictionary containing columns as keys and dictionaries of column value
    to labels as values. The combined length of all labels for a single
    variable must be 32,000 characters or smaller.

    .. versionadded:: 1.4.0

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

Raises
------
NotImplementedError
    * If datetimes contain timezone information
ValueError
    * Columns listed in convert_dates are neither datetime64[ns]
      or datetime
    * Column dtype is not representable in Stata
    * Column listed in convert_dates is not in DataFrame
    * Categorical label contains more than 32,000 characters

Examples
--------
>>> data = pd.DataFrame([[1.0, 1, 'a']], columns=['a', 'b', 'c'])
>>> writer = pd.io.stata.StataWriter117('./data_file.dta', data)
>>> writer.write_file()

Directly write a zip file
>>> compression = {"method": "zip", "archive_name": "data_file.dta"}
>>> writer = pd.io.stata.StataWriter117(
...     './data_file.zip', data, compression=compression
...     )
>>> writer.write_file()

Or with long strings stored in strl format
>>> data = pd.DataFrame([['A relatively long string'], [''], ['']],
...                     columns=['strls'])
>>> writer = pd.io.stata.StataWriter117(
...     './data_file_with_long_strings.dta', data, convert_strl=['strls'])
>>> writer.write_file()
r  rc  Nr  c                  > / U l         U	b  U R                   R                  U	5        [        TU ]  UUUUUUUUUU
US9  0 U l        SU l        g )N)r3  rV  rS  rY  r  r  r7   r   )r  r  r  r  _map
_strl_blob)r  r  r   r  r  r3  rV  rS  rY  r  r  r7   r  r  s                rW   r  StataWriter117.__init__  sj    " .0#%%l3!!+%#+ 	 	
 %'	r   c                    [        U [        5      (       a  [        U S5      n [        SU-   S-   S5      U -   [        SU-   S-   S5      -   $ )zSurround val with <tag></tag>r	  ri  rh  z</)r   r   r?  )r  tags     rW   _tagStataWriter117._tag  sL     c3W%CS3Y_g.4uTCZ#=Mw7WWWr   c                    U R                   R                  c   eU R                   R                  R                  5       U R                  U'   g)z.Update map location for tag with file positionN)r!  r  r  r  )r  r  s     rW   _update_mapStataWriter117._update_map	  s8    ||""...,,113		#r   c           	        U R                   nU R                  [        SS5      5        [        5       nUR	                  U R                  [        [        U R                  5      S5      S5      5        UR	                  U R                  US:H  =(       a    S=(       d    SS5      5        U R                  S::  a  S	OS
nUR	                  U R                  [        R                  " X5-   U R                  5      S5      5        U R                  S:X  a  S
OSnUR	                  U R                  [        R                  " X6-   U R                  5      S5      5        Ub  USS OSnUR                  U R                  5      nU R                  S:X  a  SOS	n	[        R                  " X9-   [        U5      5      n
X-   nUR	                  U R                  US5      5        Uc  [        R                   " 5       nO [#        U[        5      (       d  [%        S5      e/ SQn['        U5       VVs0 s H  u  pUS-   U_M     nnnUR)                  S5      XR*                     -   UR)                  S5      -   nS[        US5      -   nUR	                  U R                  US5      5        U R                  U R                  UR-                  5       S5      5        gs  snnf )zWrite the file headerz<stata_dta>r	  releaserh  MSFLSFr3  r0  r>  rE  Krc  r  NNr  r   r:  rH  r  r  rB   r$  r%     	timestampheader)r@  r  r?  r   r.  r  r   _dta_versionr   r/  r  r  r!  r  r  r   r'  r   rh   r  r(  rR   r2  )r  rS  rV  r3  r4  	nvar_type	nobs_sizerH  encoded_label
label_size	label_lenr)  r)  rR   r*  r+  stata_tss                    rW   r  StataWriter117._write_header  sA    OO	%w78i		$))E#d&7&7"8'BINO		$))I,6?%MN,,3C			$))FKK	(=tyyI3OP,,3C			$))FKK	(=tyyI3OP#-#9
3BrT^^4 --4S#
KK	 6M8JK	!1		$))M734 !JJ11ABB
 6?v5FG5FAu5FG&++,-!!+./ 	 U2w//		$))Hk23$))CLLNH=> Hs   Kc                   U R                   (       d8  SU R                  R                  R                  5       SSSSSSSSSSSSS.U l         U R                  R                  R	                  U R                   S   5        [        5       nU R                   R                  5        H6  nUR                  [        R                  " U R                  S-   U5      5        M8     U R                  U R                  UR                  5       S5      5        g)z
Called twice during file write. The first populates the values in
the map with 0s.  The second call writes the final map locations when
all blocks have been written.
r   )
stata_datamapvariable_typesvarnamessortlistformatsvalue_label_namesrY  characteristicsr   strlsr  stata_data_closeend-of-filer  r  N)r  r!  r  r  r  r   rk   r.  r   r/  r@  r  r  r2  )r  r4  r  s      rW   r  StataWriter117._write_mapH  s     yy||**//1"#%&#$#$ !$% DI" 	  5!12i99##%CIIfkk$//C"7=> &$))CLLNE:;r   c                $   U R                  S5        [        5       nU R                   H6  nUR                  [        R
                  " U R                  S-   U5      5        M8     U R                  U R                  UR                  5       S5      5        g )Nr  r>  )
r  r   r  r.  r   r/  r@  r  r  r2  )r  r4  r  s      rW   r  $StataWriter117._write_variable_typesf  sf    )*i<<CIIfkk$//C"7=>  $))CLLN4DEFr   c                   U R                  S5        [        5       nU R                  S:X  a  SOSnU R                   HP  nU R	                  U5      n[        US S R                  U R                  5      US-   5      nUR                  U5        MR     U R                  U R                  UR                  5       S5      5        g )Nr  rc  r*  r,  rB   )r  r   r  r}  r0  re  r!  r  r.  r  r  r2  )r  r4  vn_lenr   s       rW   r  StataWriter117._write_varnamesm  s    $i((C/SLLD++D1D!$s)"2"24>>"BFQJODIIdO ! 	$))CLLNJ?@r   c                    U R                  S5        U R                  S:  a  SOSnU R                  U R                  SU-  U R                  S-   -  S5      5        g )Nr  rd  r   r   r(  rB   )r  r  r  r  r  )r  	sort_sizes     rW   r  StataWriter117._write_sortlistx  sO    $**S0Aa	$))Gi$7499q=$I:VWr   c                N   U R                  S5        [        5       nU R                  S:X  a  SOSnU R                   H7  nUR	                  [        UR                  U R                  5      U5      5        M9     U R                  U R                  UR                  5       S5      5        g )Nr  rc  r  r  )r  r   r  r<  r.  re  r!  r  r  r  r2  )r  r4  fmt_lenr   s       rW   r  StataWriter117._write_formats}  sx    #i))S0"b<<CIInSZZ%?IJ  $))CLLNI>?r   c                   U R                  S5        [        5       nU R                  S:X  a  SOSn[        U R                  5       Hu  nSnU R
                  U   (       a  U R                  U   nU R                  U5      n[        US S R                  U R                  5      US-   5      nUR                  U5        Mw     U R                  U R                  UR                  5       S5      5        g )Nr  rc  r*  r,  r   rB   )r  r   r  r1  r  r  r}  r0  re  r!  r  r.  r  r  r2  )r  r4  vl_lenr)  r   encoded_names         rW   r  'StataWriter117._write_value_label_names  s    ,-i((C/Styy!AD%%a(||A++D1D)$s)*:*:4>>*JFUVJWLIIl# " 	$))CLLN4GHIr   c                6   U R                  S5        [        5       nU R                  S:X  a  SOSn[        SUS-   5      nU R                  c]  [        U R                  5       H  nUR                  U5        M     U R                  U R                  UR                  5       S5      5        g U R                   H  nXPR                  ;   ad  U R                  U   n[        U5      S:  a  [        S5      e UR                  U R                  5      nUR                  [        XrS-   5      5        Mv  UR                  U5        M     U R                  U R                  UR                  5       S5      5        g ! [          a  n[        SU R                   35      UeS nAff = f)	NrY  rc  r  i@  r   rB   r:  zDVariable labels must contain only characters that can be encoded in )r  r   r  re  r  r1  r  r.  r  r  r2  r   r  rh   r!  r  UnicodeEncodeError)	r  r4  r  r?  r  r   rH  r  r  s	            rW   r  %StataWriter117._write_variable_labels  s_   *+i((C/Sr6A:.  (499%		%  &dii8IJK99C+++--c2u:?$%UVV#ll4>>:G 		.1*=>		%    	$))CLLN4EFG * $--1^^,<> s   1E00
F:FFc                h    U R                  S5        U R                  U R                  SS5      5        g )Nr  r   )r  r  r  re  s    rW   r  %StataWriter117._write_characteristics  s+    *+$))C):;<r   c                    U R                  S5        U R                  S5        U R                  UR                  5       5        U R                  S5        g )Nr   s   <data>s   </data>)r  r  rQ  rR  s     rW   r  StataWriter117._write_data  sA     )$'//+,*%r   c                |    U R                  S5        U R                  U R                  U R                  S5      5        g )Nr  )r  r  r  r  re  s    rW   r  StataWriter117._write_strls  s-    !$))DOOW=>r   c                    g)zNo-op in dta 117+NrF  re  s    rW   r  &StataWriter117._write_expansion_fields  r  r   c                :   U R                  S5        [        5       nU R                   HA  nUR                  U R                  5      nU R                  US5      nUR                  U5        MC     U R                  U R                  UR                  5       S5      5        g )Nr  lbl)	r  r   r  r9  r@  r  r.  r  r2  )r  r4  r$  labs       rW   r  "StataWriter117._write_value_labels  sw    (i$$B))$//:C))C'CIIcN % 	$))CLLNNCDr   c                ~    U R                  S5        U R                  [        SS5      5        U R                  S5        g )Nr  z</stata_dta>r	  r  )r  r  r?  re  s    rW   r  $StataWriter117._write_file_close_tag  s4    +,%89'r   c                    U R                   R                  5        H?  u  pXR                  ;   d  M  U R                  R                  U5      nX R                  U'   MA     g)zn
Update column names for conversion to strl if they might have been
changed to comply with Stata naming rules
N)r  rN  r  rK   )r  orignewr  s       rW   r  !StataWriter117._update_strl_names  sO     ..446ID)))((..t4*-""3' 7r   c                "   [        U5       VVs/ s H+  u  p#U R                  U   S:X  d  X0R                  ;   d  M)  UPM-     nnnU(       a>  [        XU R                  S9nUR                  5       u  pgUnUR                  U5      U l        U$ s  snnf )zO
Convert columns to StrLs if either very large or in the
convert_strl variable
r  re  )r  r  r  rg  r  r  r  r  )r  r   r)  r   convert_colssswtabnew_datas           rW   rC  StataWriter117._convert_strls  s     $D/
)||A%'32D2D+D ) 	 
 !$d>O>OPC..0MCD!//4DO
s
   (BBc                N   / U l         / U l        UR                  5        H  u  p#X R                  ;   n[	        UU R
                  U   U R                  US9nU R                  R                  U5        U R                   R                  [        X0R
                  U   U5      5        M     g )N)r  r  )	r  r<  rN  r  r  r   r  r"  rc  )r  r  r   ry   r  r   s         rW   r  %StataWriter117._set_formats_and_types  s     ,,.JC 2 22J-		# --%	C LL$LL(		#
K )r   )r  r  r  r<  r  )	NTNNNNNr]  N)r  rX  r   r$   r  rY  r  r   r3  r_  rV  rZ  rS  r_  rY  rY  r  Sequence[Hashable] | Noner  r.   r7   rb  r  r[  r   r=  )r  str | bytesr  r   r   r?  )r  r   r   r=  r^  r_  r>  rd  r]  )r@  rA  rB  rC  rD  r  r  r  ra  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rC  r  rE  ri  rj  s   @rW   r  r    sm   Sj L 59  $&*!%6:26*115# AE#,# # 2	#
 # # $# # 4# 0# (# /# ># 
# #J X X4 "&&*8?8? $8? 
	8?t<<G	AX
@JH@=&? E(
	.$ r   r  c                     ^  \ rS rSr% SrSrS\S'             SSS.                           SU 4S jjjjrSS	 jrS
r	U =r
$ )StataWriterUTF8i  u  
Stata binary dta file writing in Stata 15 (118) and 16 (119) formats

DTA 118 and 119 format files support unicode string data (both fixed
and strL) format. Unicode is also supported in value labels, variable
labels and the dataset label. Format 119 is automatically used if the
file contains more than 32,767 variables.

Parameters
----------
fname : path (string), buffer or path object
    string, path object (pathlib.Path or py._path.local.LocalPath) or
    object implementing a binary write() functions. If using a buffer
    then the buffer will not be automatically closed after the file
    is written.
data : DataFrame
    Input to save
convert_dates : dict, default None
    Dictionary mapping columns containing datetime types to stata internal
    format to use when writing the dates. Options are 'tc', 'td', 'tm',
    'tw', 'th', 'tq', 'ty'. Column can be either an integer or a name.
    Datetime columns that do not have a conversion type specified will be
    converted to 'tc'. Raises NotImplementedError if a datetime column has
    timezone information
write_index : bool, default True
    Write the index to Stata dataset.
byteorder : str, default None
    Can be ">", "<", "little", or "big". default is `sys.byteorder`
time_stamp : datetime, default None
    A datetime to use as file creation date.  Default is the current time
data_label : str, default None
    A label for the data set.  Must be 80 characters or smaller.
variable_labels : dict, default None
    Dictionary containing columns as keys and variable labels as values.
    Each label must be 80 characters or smaller.
convert_strl : list, default None
    List of columns names to convert to Stata StrL format.  Columns with
    more than 2045 characters are automatically written as StrL.
    Smaller columns can be converted by including the column name.  Using
    StrLs can reduce output file size when strings are longer than 8
    characters, and either frequently repeated or sparse.
version : int, default None
    The dta version to use. By default, uses the size of data to determine
    the version. 118 is used if data.shape[1] <= 32767, and 119 is used
    for storing larger DataFrames.
{compression_options}

    .. versionchanged:: 1.4.0 Zstandard support.

value_labels : dict of dicts
    Dictionary containing columns as keys and dictionaries of column value
    to labels as values. The combined length of all labels for a single
    variable must be 32,000 characters or smaller.

    .. versionadded:: 1.4.0

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

Raises
------
NotImplementedError
    * If datetimes contain timezone information
ValueError
    * Columns listed in convert_dates are neither datetime64[ns]
      or datetime
    * Column dtype is not representable in Stata
    * Column listed in convert_dates is not in DataFrame
    * Categorical label contains more than 32,000 characters

Examples
--------
Using Unicode data and column names

>>> from pandas.io.stata import StataWriterUTF8
>>> data = pd.DataFrame([[1.0, 1, 'ᴬ']], columns=['a', 'β', 'ĉ'])
>>> writer = StataWriterUTF8('./data_file.dta', data)
>>> writer.write_file()

Directly write a zip file
>>> compression = {"method": "zip", "archive_name": "data_file.dta"}
>>> writer = StataWriterUTF8('./data_file.zip', data, compression=compression)
>>> writer.write_file()

Or with long strings stored in strl format

>>> data = pd.DataFrame([['ᴀ relatively long ŝtring'], [''], ['']],
...                     columns=['strls'])
>>> writer = StataWriterUTF8('./data_file_with_long_strings.dta', data,
...                          convert_strl=['strls'])
>>> writer.write_file()
r	  zLiteral['utf-8']r  Nr  c                  > U
c  UR                   S   S::  a  SOSn
O5U
S;  a  [        S5      eU
S:X  a  UR                   S   S:  a  [        S5      e[        TU ]  UUUUUUUUUU	UUS9  Xl        g )	NrB   i  r0  rd  )r0  rd  z"version must be either 118 or 119.zKYou must use version 119 for data sets containing more than32,767 variables)
r  r  r3  rV  rS  rY  r  r  r  r7   )r   rh   r  r  r  )r  r  r   r  r  r3  rV  rS  rY  r  rf  r  r7   r  r  s                 rW   r  StataWriterUTF8.__init__d  s    " ?!ZZ]e3cGJ&ABB^

1 5# 
 	'#!!+%%#+ 	 	
 $r   c                    U Hn  n[        U5      S:  a*  US:  d  US:  a  US:  d  US:  a  US:  d  US:  a  US:w  d   S[        U5      s=::  a  S	:  d
  O  US
;   d  M\  UR                  US5      nMp     U$ )a]  
Validate variable names for Stata export.

Parameters
----------
name : str
    Variable name

Returns
-------
str
    The validated name with invalid characters replaced with
    underscores.

Notes
-----
Stata 118+ support most unicode characters. The only limitation is in
the ascii range where the characters supported are a-z, A-Z, 0-9 and _.
r,  r  r  r  r  r  r  r     >      ×   ÷)r=  r  r  s      rW   r  'StataWriterUTF8._validate_variable_name  sy    * A FSLSAGSAGSAGS#a&&3&$||As+  r   )r  )
NTNNNNNNr]  N)r  rX  r   r$   r  rY  r  r   r3  r_  rV  rZ  rS  r_  rY  rY  r  r  rf  ra  r  r.   r7   rb  r  r[  r   r=  r\  )r@  rA  rB  rC  rD  r  r}  r  r  rE  ri  rj  s   @rW   r  r    s    ^@ #*I) 59  $&*!%6:26"*115*$ AE*$,*$ *$ 2	*$
 *$ *$ $*$ *$ 4*$ 0*$ *$ (*$ /*$ >*$  
!*$ *$X# #r   r  )r   r'   r   r   r   r'   rd  )r6   r^  r  r   r  r   r	  r_  r
  r   r  r   r  r`  r  r   r  ra  rk  r   r  r.   r7   rb  r   zDataFrame | StataReader)rs  r   r   r   )r   r
   r  ra   r   r
   )r   r   r   r|  )r  r  r}  zlist[Hashable]r   r  )ry   r|  rI  r'   r   ra   )r  F)rI  r'   r  ra   r  r   r   r   )ry   r|  rI  r'   r  r   r   ra   )r   r  r  ra   r   r?  )vrD  
__future__r   collectionsr   r   r   ior   r  r   r  typingr   r	   r
   r   r   r   r   numpyr   pandas._libsr   pandas._libs.libr   pandas._libs.writersr   pandas.errorsr   r   r   r   pandas.util._decoratorsr   r   pandas.util._exceptionsr   pandas.core.dtypes.baser   pandas.core.dtypes.commonr   r   r   pandas.core.dtypes.dtypesr   pandasr   r   r   r    r!   r"   r#   pandas.core.framer$   pandas.core.indexes.baser%   pandas.core.indexes.ranger&   pandas.core.seriesr'   pandas.core.shared_docsr(   pandas.io.commonr)   collections.abcr*   r+   typesr,   r-   pandas._typingr.   r/   r0   r1   r2   r3   rs  _statafile_processing_params1_statafile_processing_params2_chunksize_params_iterator_params_reader_notes_read_stata_docrh  rg  r  rC   r}  r   r   r   r   r   r   r   r  r  rH  r   r  Iteratorr  rn  r  r0  ry  r  r  r  r  rc  re  rg  r  r  rF  r   rW   <module>r     s  
 #   	  
     ( 5  5 2 
 7   ( * 0 % 0 ' $ 4 !N !G $ 
" (           %&)== > ?  ! "  ?8t                 %& ' (  ! "  $ O dAq)U )]@h7V( u  E # % 	 % 	)  yxv vr%O %>C CL\
 \
~|&+s|| |&~ 
/ !% ! $(# &--1!4! ! 	!
 ! ! ! "! ! ! ! $! +! ! !HD0C2!GJ GL*G*G(+*G?C*G*GZ  !23$%:;gEKB+ KB	KB\'GT1r rjz[ zzrn rr   