2[c@`sdZddlmZmZmZdZddlZddlZddl j j Z ddl mZmZmZmZmZejddkrddlmZmZmZmZmZmZeZn4ddlmZmZmZmZmZmZmZed Zd Zd Z d e!d Z"dZ#e!dZ$defdYZ%defdYZ&dZ'de(fdYZ)de)fdYZ*de+fdYZ,defdYZ-eddZ.dS(sBA collection of functions designed to help I/O with ascii files. i(tdivisiontabsolute_importtprint_functionsrestructuredtext enN(tasbytest asunicodetbytestasbytes_nestedt basestringi(tbooltinttfloattcomplextobjecttstr(RR R R R tunicodeR cC`sFt|tkrB|dkr0|jd}qB|j|}n|S(snDecode bytes from binary input streams. Defaults to decoding from 'latin1'. That differs from the behavior of np.compat.asunicode that decodes from 'ascii'. Parameters ---------- line : str or bytes Line to be decoded. Returns ------- decoded_line : unicode Unicode in Python 2, a str (unicode) in Python 3. tlatin1N(ttypeRtNonetdecode(tlinetencoding((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt _decode_lines  cC`s+y |dWnttfk r&tSXtS(s2 Check whether obj behaves like a string. t(t TypeErrort ValueErrortFalsetTrue(tobj((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt_is_string_like.s  cC`s+y |dWnttfk r&tSXtS(s8 Check whether obj behaves like a bytes object. R(RRRR(R((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt_is_bytes_like9s  trcC`st|r|jdr<ddl}|j||}n<|jdriddl}|j|}nt||}t}n*t|dr|}t }n t d|r||fS|S(s Returns the filehandle corresponding to a string or a file. If the string ends in '.gz', the file is automatically unzipped. Parameters ---------- fname : string, filehandle Name of the file whose filehandle must be returned. flag : string, optional Flag indicating the status of the file ('r' for read, 'w' for write). return_opened : boolean, optional Whether to return the opening status of the file. s.gziNs.bz2tseeks%fname must be a string or file handle( Rtendswithtgziptopentbz2tBZ2FiletfileRthasattrRR(tfnametflagt return_openedR!tfhdR#topened((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt_to_filehandleDs        cC`s/x(|jpdD]}||jrtSqWtS(s Returns whether one or several fields of a dtype are nested. Parameters ---------- ndtype : dtype Data-type of a structured array. Raises ------ AttributeError If `ndtype` does not have a `names` attribute. Examples -------- >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float)]) >>> np.lib._iotools.has_nested_fields(dt) False ((tnamesRR(tndtypetname((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pythas_nested_fieldsfs cC`s|j}|dkrE|r;|jgttj|jS|jgSg}x;|D]3}|j|}t|d|}|j |qRW|SdS(s< Unpack a structured data-type by collapsing nested fields and/or fields with a shape. Note that the field names are lost. Parameters ---------- ndtype : dtype The datatype to collapse flatten_base : bool, optional If True, transform a field with a shape into several fields. Default is False. Examples -------- >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float), ... ('block', int, (2, 3))]) >>> np.lib._iotools.flatten_dtype(dt) [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')] >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True) [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32')] iN( R-RtbaseR tnptprodtshapetfieldst flatten_dtypetextend(R.t flatten_baseR-ttypestfieldtinfotflat_dt((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyR6s      t LineSplittercB`sPeZdZdZddeddZdZdZdZ dZ RS( s Object to split a string at a given delimiter or at given places. Parameters ---------- delimiter : str, int, or sequence of ints, optional If a string, character used to delimit consecutive fields. If an integer or a sequence of integers, width(s) of each field. comments : str, optional Character used to mark the beginning of a comment. Default is '#'. autostrip : bool, optional Whether to strip each individual field. Default is True. c`s fdS(s Wrapper to strip each member of the output of `method`. Parameters ---------- method : function Function that takes a single argument and returns a sequence of strings. Returns ------- wrapped : function The result of wrapping `method`. `wrapped` takes a single input argument and returns a list of strings that are stripped of white-space. c`s#g|D]}|j^q S(N(tstrip(tinputt_(tmethod(s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyts((tselfRA((RAs1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt autostripst#c C`s3t|}t|}||_|dks<t|trT|pEd}|j}nt|dr|j}tj dgt |}gt |d |dD]\}}t ||^q}n5t |r|jt |}}n|jd}}||_|r|j||_n ||_||_dS(Nt__iter__iii(RtcommentsRt isinstanceRt_delimited_splitterR&t_variablewidth_splitterR2tcumsumtlisttziptsliceR t_fixedwidth_splittert delimiterRDt _handymanR( RCRPRGRDRRQtidxtitj((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt__init__s$      <   cC`sQ|jdk r(|j|jd}n|jd}|sAgS|j|jS(s2Chop off comments, strip, and split at delimiter. is N(RGRtsplitR>RP(RCR((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRIs cC`s|jdk r(|j|jd}n|jd}|sAgS|j}gtdt||D]}t|||^qc}g|D]}||^qS(Nis (RGRRVR>RPtrangetlenRN(RCRtfixedRStslicests((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyROs 8cC`sV|jdk r(|j|jd}n|s2gS|j}g|D]}||^qBS(Ni(RGRRVRP(RCRRZR[((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRJs  cC`s|jt||jS(N(RQRR(RCR((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt__call__ sN( t__name__t __module__t__doc__RDRRRURIRORJR\(((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyR=s  t NameValidatorcB`s\eZdZdddgZedZd d d ddZdd dZdd d Z RS( s$ Object to validate a list of strings to use as field names. The strings are stripped of any non alphanumeric character, and spaces are replaced by '_'. During instantiation, the user can define a list of names to exclude, as well as a list of invalid characters. Names in the exclusion list are appended a '_' character. Once an instance has been created, it can be called with a list of names, and a list of valid names will be created. The `__call__` method accepts an optional keyword "default" that sets the default name in case of ambiguity. By default this is 'f', so that names will default to `f0`, `f1`, etc. Parameters ---------- excludelist : sequence, optional A list of names to exclude. This list is appended to the default list ['return', 'file', 'print']. Excluded names are appended an underscore: for example, `file` becomes `file_` if supplied. deletechars : str, optional A string combining invalid characters that must be deleted from the names. case_sensitive : {True, False, 'upper', 'lower'}, optional * If True, field names are case-sensitive. * If False or 'upper', field names are converted to upper case. * If 'lower', field names are converted to lower case. The default value is True. replace_space : '_', optional Character(s) used in replacement of white spaces. Notes ----- Calling an instance of `NameValidator` is the same as calling its method `validate`. Examples -------- >>> validator = np.lib._iotools.NameValidator() >>> validator(['file', 'field2', 'with space', 'CaSe']) ['file_', 'field2', 'with_space', 'CaSe'] >>> validator = np.lib._iotools.NameValidator(excludelist=['excl'], deletechars='q', case_sensitive='False') >>> validator(['excl', 'field2', 'no_q', 'with space', 'CaSe']) ['excl_', 'field2', 'no_', 'with_space', 'case'] treturnR%tprints~!@#$%^&*()-=+~\|]}[{';: /?.>,treplacetjointgettappendttuple(RCR-t defaultfmttnbfieldstnbnamesRnRjRoRqtvalidatednamestseentnbemptytitemtctcnt((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pytvalidateasL              .        cC`s|j|d|d|S(NR|R}(R(RCR-R|R}((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyR\sN( R]R^R_RiRlRkRRURR\(((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyR`s2 GcC`s<|j}|dkrtS|dkr,tStddS(s Tries to transform a string supposed to represent a boolean to a boolean. Parameters ---------- value : str The string that is transformed to a boolean. Returns ------- boolval : bool The boolean representation of `value`. Raises ------ ValueError If the string is not 'True' or 'False' (case independent) Examples -------- >>> np.lib._iotools.str2bool('TRUE') True >>> np.lib._iotools.str2bool('false') False tTRUEtFALSEsInvalid booleanN(RfRRR(tvalue((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pytstr2bools    tConverterErrorcB`seZdZRS(sR Exception raised when an error occurs in a converter for string values. (R]R^R_(((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRstConverterLockErrorcB`seZdZRS(sR Exception raised when an attempt is made to upgrade a locked converter. (R]R^R_(((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRstConversionWarningcB`seZdZRS(s Warning issued when a string converter has a problem. Notes ----- In `genfromtxt` a `ConversionWarning` is issued if raising exceptions is explicitly suppressed with the "invalid_raise" keyword. (R]R^R_(((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRs tStringConvertercB`seZdZejeefejedfgZ ej ejj ej ej j krve j ej edfne jejeejfejeejdfejejejfejedfejedfgee \ZZZedZedZedZ eddZ"dddedZ#d Z$d Z%d Z&d Z'd Z(dddedZ)RS(sb Factory class for function transforming a string into another object (int, float). After initialization, an instance can be called to transform a string into another object. If the string is recognized as representing a missing value, a default value is returned. Attributes ---------- func : function Function used for the conversion. default : any Default value to return when the input corresponds to a missing value. type : type Type of the output. _status : int Integer representing the order of the conversion. _mapper : sequence of tuples Sequence of tuples (dtype, function, default value) to evaluate in order. _locked : bool Holds `locked` parameter. Parameters ---------- dtype_or_func : {None, dtype, function}, optional If a `dtype`, specifies the input data type, used to define a basic function and a default value for missing data. For example, when `dtype` is float, the `func` attribute is set to `float` and the default value to `np.nan`. If a function, this function is used to convert a string to another object. In this case, it is recommended to give an associated default value as input. default : any, optional Value to return by default, that is, when the string to be converted is flagged as missing. If not given, `StringConverter` tries to supply a reasonable default value. missing_values : {None, sequence of str}, optional ``None`` or sequence of strings indicating a missing value. If ``None`` then missing values are indicated by empty entries. The default is ``None``. locked : bool, optional Whether the StringConverter should be locked to prevent automatic upgrade or not. Default is False. iys???cC`stj|jS(s(Returns the dtype of the input variable.(R2tarraytdtype(tclstval((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt _getdtype.scC`stj|jjS(s4Returns the type of the dtype of the input variable.(R2RRR(RR((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt _getsubdtype4scC`s|jtjkr|S|jS(s9Returns dtype for datetime64 and type of dtype otherwise.(RR2t datetime64(RR((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt _dtypeortype>scC`s&t|dr8|jjd|j|||fdSt|dr"t|dttfrx!|D]}|jjd|qgWdS|dkrdgt|}n0t|}|j dgt|t|xEt ||D]1\}}|jjd|j|||fqWndS(s Upgrade the mapper of a StringConverter by adding a new function and its corresponding default. The input function (or sequence of functions) and its associated default value (if any) is inserted in penultimate position of the mapper. The corresponding type is estimated from the dtype of the default value. Parameters ---------- func : var Function, or sequence of functions Examples -------- >>> import dateutil.parser >>> import datetime >>> dateparser = datetustil.parser.parse >>> defaultdate = datetime.date(2000, 1, 1) >>> StringConverter.upgrade_mapper(dateparser, default=defaultdate) R\iNRFi( R&t_mappertinsertRRHR{RLRRXRzRM(RtfunctdefaultR@tfcttdft((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pytupgrade_mapperFs%   $c C`s)t||_|dkrNt|_d|_|p6t|_tj d}nIyd|_tj |}Wnt k rt |dsd}t |t |n||_|dkry|jd}Wqt k rd}qXn|j|}nXd}xft|jD]U\}\} } } tj|j | r|}|dkr^| |_n ||_PqqW| } xft|jD]U\}\} } } |j | kr|}| } |dkr| |_n ||_PqqW| } |dkrd}||_n||_|jdkr&| |_n|j|jddkrt|j tjrdtj|_qt|j tjrtj|_qd|_n|dkrtd g|_n=t|tr|jd }ntt|d g|_|j|_|j||_ t|_||_dS( NiRR\sOThe input argument `dtype` is neither a function nor a dtype (got '%s' instead)t0iicS`stt|S(N(R R (Rd((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRBsRt,( Rt_lockedRRRt_statusRRR2RRR&RRRt enumerateRt issubdtypet issubclasstuint64tint64Rltmissing_valuesRHRRVRLt _strict_callt_callingfunctionRt_checkedt_initial_default( RCt dtype_or_funcRRtlockedRterrmsgRRStdeftypeRt default_deft last_func((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRUpsv         %   %          cC`s-y|j|SWntk r(|jSXdS(N(RRR(RCR((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt _loose_calls cC`sy]|j|}|jtkrXytj|d|jWqXtk rTtqXXn|SWnRtk r|j|jkr|j st |_ n|j Std|nXdS(NRsCannot convert string '%s'( RR R2RRt OverflowErrorRR>RRRRR(RCRt new_value((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRs     cC`s |j|S(N(R(RCR((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyR\scC`st|_y|j|SWntk r|jrHd}t|nt|j}|j}||krd}t |n||dkr|d7}n|j|\|_ |_ }||_|j dk r|j |_n ||_|j|SXdS(s Find the best converter for a given string, and return the result. The supplied string `value` is converted by testing different converters in order. First the `func` method of the `StringConverter` instance is tried, if this fails other available converters are tried. The order in which these other converters are tried is determined by the `_status` attribute of the instance. Parameters ---------- value : str The string to convert. Returns ------- out : any The result of converting `value` with the appropriate converter. s*Converter is locked and cannot be upgradeds*Could not find a valid conversion functioniN(RRRRRRRXRRRRRRRRtupgrade(RCRRt _statusmaxRR((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRs(        cC`s+t|_t|ds$|f}n|j}yx|D]}||q7WWntk r&|jrzd}t|nt|j}|j }||krt dn||dkr|d7}n|j|\|_ |_ }|j dk r|j |_n ||_||_ |j|nXdS(NRFs*Converter is locked and cannot be upgradeds*Could not find a valid conversion functioni(RRR&RRRRRXRRRRRRRRt iterupgrade(RCRRt_mRRRR((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRs0            RcC`s||_||_|dk rE||_|j|j||_nQy||pTd}Wnttfk rzd}nX|j|j||_|dkrt |_ nPt j |s|g}nt d|Dstdn|j j|dS(s Set StringConverter attributes directly. Parameters ---------- func : function Conversion function. default : any, optional Value to return by default, that is, when the string to be converted is flagged as missing. If not given, `StringConverter` tries to supply a reasonable default value. testing_value : str, optional A string representing a standard input value of the converter. This string is used to help defining a reasonable default value. missing_values : {sequence of str, None}, optional Sequence of strings indicating a missing value. If ``None``, then the existing `missing_values` are cleared. The default is `''`. locked : bool, optional Whether the StringConverter should be locked to prevent automatic upgrade or not. Default is False. Notes ----- `update` takes the same parameters as the constructor of `StringConverter`, except that `func` does not accept a `dtype` whereas `dtype_or_func` in the constructor does. t1cs`s|]}t|tVqdS(N(RHR(t.0tv((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pys iss)missing_values must be strings or unicodeN(RRRRRRRRRRlRR2titerabletalltupdate(RCRRt testing_valueRRttester((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyR4s"       N(*R]R^R_tnxtbool_RRtintegerR RRtitemsizeRRzR7tfloatingR tnantcomplexfloatingR t longdoubletunicode_Rtstring_RRMt _defaulttypet _defaultfunct _defaultfillt classmethodRRRRRRURRR\RRR(((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyRs2/* )  S    - sf%icK`sytj|}Wntk rt|}t|}|d kr]dgt|}n!t|tr~|jd}n||d|d|}tjt d|d|}nBXt|}|d k rvt|}t|tr|jd}n|dkrXt |j gt|}||d|}tjt t ||}q||d|d||_n|dkrt|}|jt dt|Dkr|d kr|dg|d||_q||jd||_n|S( s6 Convenience function to create a `np.dtype` object. The function processes the input `dtype` and matches it with the given names. Parameters ---------- ndtype : var Definition of the dtype. Can be any string or dictionary recognized by the `np.dtype` function, or a sequence of types. names : str or sequence, optional Sequence of strings to use as field names for a structured dtype. For convenience, `names` can be a string of a comma-separated list of names. defaultfmt : str, optional Format string used to define missing names, such as ``"f%i"`` (default) or ``"fields_%02i"``. validationargs : optional A series of optional arguments used to initialize a `NameValidator`. Examples -------- >>> np.lib._iotools.easy_dtype(float) dtype('float64') >>> np.lib._iotools.easy_dtype("i4, f8") dtype([('f0', '>> np.lib._iotools.easy_dtype("i4, f8", defaultfmt="field_%03i") dtype([('field_000', '>> np.lib._iotools.easy_dtype((int, float, float), names="a,b,c") dtype([('a', '>> np.lib._iotools.easy_dtype(float, names="a,b,c") dtype([('a', 'ssf%iN(R2RRR`RXRRHRRVRvR{RRLRMR-RW(R.R-R|tvalidationargsRR}tnbtypesR((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyt easy_dtypens:&    "    !  % (/R_t __future__RRRt __docformat__tsystnumpyR2tnumpy.core.numerictcoretnumericRt numpy.compatRRRRRt version_infotbuiltinsRR R R R R Rt __builtin__RRRRRR,R0R6R=R`Rt ExceptionRRt UserWarningRRR(((s1/tmp/pip-build-fiC0ax/numpy/numpy/lib/_iotools.pyts2  (. 4  "  )d $