B >> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float)]) >>> np.lib._iotools.has_nested_fields(dt) False rTF)names)ndtypenamerrrhas_nested_fieldsWs r,cCsn|j}|dkr2|r*|jgtt|jS|jgSg}x.|D]&}|j|}t|d|}||q>> 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')] Nr) r)baser npZprodshapeZfields flatten_dtypeextend)r*Z flatten_baser)typesZfieldinfoZflat_dtrrrr0rs  r0c@sBeZdZdZddZdddZd d Zd d Zd dZddZ dS) LineSplittera 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. cs fddS)a 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. csdd|DS)NcSsg|] }|qSr)strip).0_rrr sz...r)input)methodrrrz(LineSplitter.autostrip..r)selfr:r)r:r autostripszLineSplitter.autostripN#TcCs||_t|tr|d}|dks*t|r:|p0d}|j}npt|dr|j}t dgt |}ddt |dd|ddD}n&t |r|j t |}}n |jd}}||_|r|||_n||_dS)Nr__iter__rcSsg|]\}}t||qSr)slice)r6ijrrrr8sz)LineSplitter.__init__..)comments isinstancerencoder_delimited_splitterr&_variablewidth_splitterr.Zcumsumlistzipr _fixedwidth_splitter delimiterr= _handyman)r<rMrEr=rNidxrrr__init__s"   & zLineSplitter.__init__cCs8|jdk r||jd}|d}|s,gS||jS)Nrs )rEsplitr5rM)r<linerrrrHs   z LineSplitter._delimited_splittercsb|jdk r|jdds,gS|jfddtdtD}fdd|DS)Nrs csg|]}t||qSr)r@)r6rA)fixedrrr8sz5LineSplitter._fixedwidth_splitter..csg|] }|qSrr)r6r)rRrrr8s)rErQr5rMrangelen)r<rRslicesr)rSrRrrLs  z!LineSplitter._fixedwidth_splittercs:|jdk r|jds"gS|j}fdd|DS)Nrcsg|] }|qSrr)r6r)rRrrr8sz8LineSplitter._variablewidth_splitter..)rErQrM)r<rRrVr)rRrrIs  z$LineSplitter._variablewidth_splittercCs ||S)N)rN)r<rRrrr__call__szLineSplitter.__call__)Nr>T) __name__ __module__ __qualname____doc__r=rPrHrLrIrWrrrrr4s    r4c@s@eZdZdZdddgZedZddd Zdd d Zdd dZ dS) NameValidatora$ 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'] returnr%printz~!@#$%^&*()-=+~\|]}[{';: /?.>,.FucSs|S)N)upper)r`rrrr;ErlcSs|S)N)lower)r`rrrr;Grz%unrecognized case_sensitive value %s.) r1defaultexcludelist excludelistdefaultdeletecharssetadd deletecharscase_converter startswithr replace_space)r<rfrjZcase_sensitivermdeletemsgrrrrP3s$      zNameValidator.__init__f%ic sh|dkr|dkrdSg}t|tr(|g}|dk rlt|}||krXt|dg||}n||krl|d|}|j|j}|j}|j}g}t} d} x|D]} ||  } |r| d|} d fdd| D} | dkr || } x| |kr| d7} || } qW| d7} n| |kr| d7} | | d} | dkrF| | d | n | | | d| | <qWt|S) a Validate a list of strings as field names for a structured array. Parameters ---------- names : sequence of str Strings to be validated. defaultfmt : str, optional Default format string, used if validating a given string reduces its length to zero. nbfields : integer, optional Final number of validated names, used to expand or shrink the initial list of names. Returns ------- validatednames : list of str The list of validated field names. Notes ----- A `NameValidator` instance can be called directly, which is the same as calling `validate`. For examples, see `NameValidator`. Nrr csg|]}|kr|qSrr)r6c)rjrrr8sz*NameValidator.validate..rDr7z_%d)rFrrUrJrjrfrkrmdictr5replacejoingetappendtuple) r<r) defaultfmtnbfieldsZnbnamesrfrkrmZvalidatednamesseenZnbemptyitemZcntr)rjrvalidateNsL             zNameValidator.validatecCs|j|||dS)N)ryrz)r})r<r)ryrzrrrrWszNameValidator.__call__)NNNr7)rpN)rpN) rXrYrZr[rerhrgrPr}rWrrrrr\s2   Gr\cCs,|}|dkrdS|dkr dStddS)a 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 sTRUETsFALSEFzInvalid booleanN)rbr)valuerrrstr2bools rc@seZdZdZdS)ConverterErrorzR Exception raised when an error occurs in a converter for string values. N)rXrYrZr[rrrrrsrc@seZdZdZdS)ConverterLockErrorzR Exception raised when an attempt is made to upgrade a locked converter. N)rXrYrZr[rrrrrsrc@seZdZdZdS)ConversionWarningz 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. N)rXrYrZr[rrrrrs rc@seZdZdZejedfejedfgZ e ejj e ej j krRe ej edfe ejeejfeeejdfejejejfejedfgee \ZZZeddZedd Zed d Zedd dZdddZ ddZ!ddZ"ddZ#ddZ$ddZ%d ddZ&d S)!StringConvertera 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 : sequence of str, optional Sequence of strings indicating a missing value. locked : bool, optional Whether the StringConverter should be locked to prevent automatic upgrade or not. Default is False. FrCys???cCs t|jS)z(Returns the dtype of the input variable.)r.arraydtype)clsvalrrr _getdtypeszStringConverter._getdtypecCst|jjS)z4Returns the type of the dtype of the input variable.)r.rrtype)rrrrr _getsubdtypeszStringConverter._getsubdtypecCs|jtjkr|S|jS)z9Returns dtype for datetime64 and type of dtype otherwise.)rr.Z datetime64)rrrrr _dtypeortype(s zStringConverter._dtypeortypeNcCst|dr(|jd||||fdSt|drt|dttfrdx|D]}|jd|qJWdS|dkr|dgt|}n$t|}|dgt|t|x0t ||D]"\}}|jd||||fqWdS)a 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) rWrCNr?r) r&_mapperinsertrrFrxrJrUrwrK)rfuncdefaultr7ZfctZdftrrrupgrade_mapper0s   zStringConverter.upgrade_mapperc Csrt|trt|}nt|ttfr*t|}t||_|dkr`t|_ d|_ |pNd|_ t d}nyd|_ t |}Wnrtk rt|dsd}t|t|||_ |dkry| d}Wntk rd}YnX||}YnXd}xHt|jD]:\}\} } } t |j| r|}|dkr*| |_ n||_ PqW| } xLt|jD]>\}\} } } |j| krF|}| } |dkrz| |_ n||_ PqFW| } |dkrd}||_ ||_ |j dkr| |_ |j |jddkr t|jt jrt j|_ n$t|jt jrt j|_ n d d |_ |dkr$td g|_n*t|tr:|d }tt|d g|_|j|_|||_d|_ ||_!dS) NrFr rWzOThe input argument `dtype` is neither a function nor a dtype (got '%s' instead)0rCrDcSs tt|S)N)r r )r`rrrr;rz*StringConverter.__init__..r,)"rFrrrJrxrr _lockedrr_statusrr.rrr&rrr enumeraterZ issubdtype issubclassZuint64int64rhmissing_valuesrrQ _strict_call_callingfunctionr_checked_initial_default) r<Z dtype_or_funcrrlockedrerrmsgrrAZdeftyperZ default_defZ last_funcrrrrPZs~                  zStringConverter.__init__cCs&y ||Stk r |jSXdS)N)rrr)r<r~rrr _loose_calls zStringConverter._loose_callcCsyF||}|jtkrDytj||jdWntk rBtYnX|Stk r||jkrv|j spd|_ |j Std|YnXdS)N)rFzCannot convert string '%s') rr r.rr OverflowErrorrr5rrrr)r<r~Z new_valuerrrrs   zStringConverter._strict_callcCs ||S)N)r)r<r~rrrrWszStringConverter.__call__cCsd|_y ||Stk r|jr2d}t|t|j}|j}||krXd}t|n||dkrl|d7}|j|\|_ |_ }||_|j dk r|j |_ n||_ | |SXdS)a 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. Tz*Converter is locked and cannot be upgradedz*Could not find a valid conversion functionrDN)rrrrrrUrrrrrrrupgrade)r<r~r _statusmaxrrrrrrs(      zStringConverter.upgradecCsd|_t|ds|f}|j}yx|D] }||q$WWntk r|jrXd}t|t|j}|j}||krzt dn||dkr|d7}|j|\|_ |_ }|j dk r|j |_ n||_ ||_||YnXdS)NTr?z*Converter is locked and cannot be upgradedz*Could not find a valid conversion functionrD)rr&rrrrrUrrrrrrr iterupgrade)r<r~r_mrrrrrrrrs0      zStringConverter.iterupgraderc Cs||_||_|dk r.||_||||_n@y||p8d}Wnttfk rZd}YnX||||_|dk rt|r|j |qt |drx |D]}|j |qWng|_ dS)a; 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, optional Sequence of strings indicating a missing value. 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. N1r?) rrrrrrrrrrrir&)r<rrZ testing_valuerrZtesterrrrrupdate#s"   zStringConverter.update)N)NNNF)NNrF)'rXrYrZr[nxZbool_rZintegerr rritemsizerrwr1Zfloatingr nanr rZ longdoubleZstring_rrKZ _defaulttypeZ _defaultfuncZ _defaultfill classmethodrrrrrPrrrWrrrrrrrrs0-    ) X-rf%ic Kshyt|}Wnrtk rtf|}t|}|dkrHdgt|}nt|tr\|d}||||d}tt||d}YnXt|}|dk rtf|}t|tr|d}|dkrt |j gt|}|||d}tt t ||}n||||d|_ nb|dkrdtf|}|j t dd t|DkrT|d krT|dg||d|_ n||j |d|_ |S) a6 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', 'szeasy_dtype..zf%i)r.rrr\rUrFrrQrsrxrrJrKr)rT)r*r)ryZvalidationargsr}rzZnbtypesrrrr easy_dtypeXs:&            r)rF)F)Nr)-r[Z __future__rrrZ __docformat__sysZnumpyr.Znumpy.core.numericZcoreZnumericrZ numpy.compatrrrr version_infobuiltinsr r r r rrrZ __builtin__rrrrr(r,r0r4r\r Exceptionrr UserWarningrrrrrrrs@ $   " )`$