_iotools.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. """A collection of functions designed to help I/O with ascii files.
  2. """
  3. __docformat__ = "restructuredtext en"
  4. import numpy as np
  5. import numpy.core.numeric as nx
  6. from numpy.compat import asbytes, asunicode
  7. def _decode_line(line, encoding=None):
  8. """Decode bytes from binary input streams.
  9. Defaults to decoding from 'latin1'. That differs from the behavior of
  10. np.compat.asunicode that decodes from 'ascii'.
  11. Parameters
  12. ----------
  13. line : str or bytes
  14. Line to be decoded.
  15. encoding : str
  16. Encoding used to decode `line`.
  17. Returns
  18. -------
  19. decoded_line : str
  20. """
  21. if type(line) is bytes:
  22. if encoding is None:
  23. encoding = "latin1"
  24. line = line.decode(encoding)
  25. return line
  26. def _is_string_like(obj):
  27. """
  28. Check whether obj behaves like a string.
  29. """
  30. try:
  31. obj + ''
  32. except (TypeError, ValueError):
  33. return False
  34. return True
  35. def _is_bytes_like(obj):
  36. """
  37. Check whether obj behaves like a bytes object.
  38. """
  39. try:
  40. obj + b''
  41. except (TypeError, ValueError):
  42. return False
  43. return True
  44. def has_nested_fields(ndtype):
  45. """
  46. Returns whether one or several fields of a dtype are nested.
  47. Parameters
  48. ----------
  49. ndtype : dtype
  50. Data-type of a structured array.
  51. Raises
  52. ------
  53. AttributeError
  54. If `ndtype` does not have a `names` attribute.
  55. Examples
  56. --------
  57. >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float)])
  58. >>> np.lib._iotools.has_nested_fields(dt)
  59. False
  60. """
  61. for name in ndtype.names or ():
  62. if ndtype[name].names is not None:
  63. return True
  64. return False
  65. def flatten_dtype(ndtype, flatten_base=False):
  66. """
  67. Unpack a structured data-type by collapsing nested fields and/or fields
  68. with a shape.
  69. Note that the field names are lost.
  70. Parameters
  71. ----------
  72. ndtype : dtype
  73. The datatype to collapse
  74. flatten_base : bool, optional
  75. If True, transform a field with a shape into several fields. Default is
  76. False.
  77. Examples
  78. --------
  79. >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
  80. ... ('block', int, (2, 3))])
  81. >>> np.lib._iotools.flatten_dtype(dt)
  82. [dtype('S4'), dtype('float64'), dtype('float64'), dtype('int64')]
  83. >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True)
  84. [dtype('S4'),
  85. dtype('float64'),
  86. dtype('float64'),
  87. dtype('int64'),
  88. dtype('int64'),
  89. dtype('int64'),
  90. dtype('int64'),
  91. dtype('int64'),
  92. dtype('int64')]
  93. """
  94. names = ndtype.names
  95. if names is None:
  96. if flatten_base:
  97. return [ndtype.base] * int(np.prod(ndtype.shape))
  98. return [ndtype.base]
  99. else:
  100. types = []
  101. for field in names:
  102. info = ndtype.fields[field]
  103. flat_dt = flatten_dtype(info[0], flatten_base)
  104. types.extend(flat_dt)
  105. return types
  106. class LineSplitter:
  107. """
  108. Object to split a string at a given delimiter or at given places.
  109. Parameters
  110. ----------
  111. delimiter : str, int, or sequence of ints, optional
  112. If a string, character used to delimit consecutive fields.
  113. If an integer or a sequence of integers, width(s) of each field.
  114. comments : str, optional
  115. Character used to mark the beginning of a comment. Default is '#'.
  116. autostrip : bool, optional
  117. Whether to strip each individual field. Default is True.
  118. """
  119. def autostrip(self, method):
  120. """
  121. Wrapper to strip each member of the output of `method`.
  122. Parameters
  123. ----------
  124. method : function
  125. Function that takes a single argument and returns a sequence of
  126. strings.
  127. Returns
  128. -------
  129. wrapped : function
  130. The result of wrapping `method`. `wrapped` takes a single input
  131. argument and returns a list of strings that are stripped of
  132. white-space.
  133. """
  134. return lambda input: [_.strip() for _ in method(input)]
  135. def __init__(self, delimiter=None, comments='#', autostrip=True,
  136. encoding=None):
  137. delimiter = _decode_line(delimiter)
  138. comments = _decode_line(comments)
  139. self.comments = comments
  140. # Delimiter is a character
  141. if (delimiter is None) or isinstance(delimiter, str):
  142. delimiter = delimiter or None
  143. _handyman = self._delimited_splitter
  144. # Delimiter is a list of field widths
  145. elif hasattr(delimiter, '__iter__'):
  146. _handyman = self._variablewidth_splitter
  147. idx = np.cumsum([0] + list(delimiter))
  148. delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])]
  149. # Delimiter is a single integer
  150. elif int(delimiter):
  151. (_handyman, delimiter) = (
  152. self._fixedwidth_splitter, int(delimiter))
  153. else:
  154. (_handyman, delimiter) = (self._delimited_splitter, None)
  155. self.delimiter = delimiter
  156. if autostrip:
  157. self._handyman = self.autostrip(_handyman)
  158. else:
  159. self._handyman = _handyman
  160. self.encoding = encoding
  161. def _delimited_splitter(self, line):
  162. """Chop off comments, strip, and split at delimiter. """
  163. if self.comments is not None:
  164. line = line.split(self.comments)[0]
  165. line = line.strip(" \r\n")
  166. if not line:
  167. return []
  168. return line.split(self.delimiter)
  169. def _fixedwidth_splitter(self, line):
  170. if self.comments is not None:
  171. line = line.split(self.comments)[0]
  172. line = line.strip("\r\n")
  173. if not line:
  174. return []
  175. fixed = self.delimiter
  176. slices = [slice(i, i + fixed) for i in range(0, len(line), fixed)]
  177. return [line[s] for s in slices]
  178. def _variablewidth_splitter(self, line):
  179. if self.comments is not None:
  180. line = line.split(self.comments)[0]
  181. if not line:
  182. return []
  183. slices = self.delimiter
  184. return [line[s] for s in slices]
  185. def __call__(self, line):
  186. return self._handyman(_decode_line(line, self.encoding))
  187. class NameValidator:
  188. """
  189. Object to validate a list of strings to use as field names.
  190. The strings are stripped of any non alphanumeric character, and spaces
  191. are replaced by '_'. During instantiation, the user can define a list
  192. of names to exclude, as well as a list of invalid characters. Names in
  193. the exclusion list are appended a '_' character.
  194. Once an instance has been created, it can be called with a list of
  195. names, and a list of valid names will be created. The `__call__`
  196. method accepts an optional keyword "default" that sets the default name
  197. in case of ambiguity. By default this is 'f', so that names will
  198. default to `f0`, `f1`, etc.
  199. Parameters
  200. ----------
  201. excludelist : sequence, optional
  202. A list of names to exclude. This list is appended to the default
  203. list ['return', 'file', 'print']. Excluded names are appended an
  204. underscore: for example, `file` becomes `file_` if supplied.
  205. deletechars : str, optional
  206. A string combining invalid characters that must be deleted from the
  207. names.
  208. case_sensitive : {True, False, 'upper', 'lower'}, optional
  209. * If True, field names are case-sensitive.
  210. * If False or 'upper', field names are converted to upper case.
  211. * If 'lower', field names are converted to lower case.
  212. The default value is True.
  213. replace_space : '_', optional
  214. Character(s) used in replacement of white spaces.
  215. Notes
  216. -----
  217. Calling an instance of `NameValidator` is the same as calling its
  218. method `validate`.
  219. Examples
  220. --------
  221. >>> validator = np.lib._iotools.NameValidator()
  222. >>> validator(['file', 'field2', 'with space', 'CaSe'])
  223. ('file_', 'field2', 'with_space', 'CaSe')
  224. >>> validator = np.lib._iotools.NameValidator(excludelist=['excl'],
  225. ... deletechars='q',
  226. ... case_sensitive=False)
  227. >>> validator(['excl', 'field2', 'no_q', 'with space', 'CaSe'])
  228. ('EXCL', 'FIELD2', 'NO_Q', 'WITH_SPACE', 'CASE')
  229. """
  230. defaultexcludelist = ['return', 'file', 'print']
  231. defaultdeletechars = set(r"""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""")
  232. def __init__(self, excludelist=None, deletechars=None,
  233. case_sensitive=None, replace_space='_'):
  234. # Process the exclusion list ..
  235. if excludelist is None:
  236. excludelist = []
  237. excludelist.extend(self.defaultexcludelist)
  238. self.excludelist = excludelist
  239. # Process the list of characters to delete
  240. if deletechars is None:
  241. delete = self.defaultdeletechars
  242. else:
  243. delete = set(deletechars)
  244. delete.add('"')
  245. self.deletechars = delete
  246. # Process the case option .....
  247. if (case_sensitive is None) or (case_sensitive is True):
  248. self.case_converter = lambda x: x
  249. elif (case_sensitive is False) or case_sensitive.startswith('u'):
  250. self.case_converter = lambda x: x.upper()
  251. elif case_sensitive.startswith('l'):
  252. self.case_converter = lambda x: x.lower()
  253. else:
  254. msg = 'unrecognized case_sensitive value %s.' % case_sensitive
  255. raise ValueError(msg)
  256. self.replace_space = replace_space
  257. def validate(self, names, defaultfmt="f%i", nbfields=None):
  258. """
  259. Validate a list of strings as field names for a structured array.
  260. Parameters
  261. ----------
  262. names : sequence of str
  263. Strings to be validated.
  264. defaultfmt : str, optional
  265. Default format string, used if validating a given string
  266. reduces its length to zero.
  267. nbfields : integer, optional
  268. Final number of validated names, used to expand or shrink the
  269. initial list of names.
  270. Returns
  271. -------
  272. validatednames : list of str
  273. The list of validated field names.
  274. Notes
  275. -----
  276. A `NameValidator` instance can be called directly, which is the
  277. same as calling `validate`. For examples, see `NameValidator`.
  278. """
  279. # Initial checks ..............
  280. if (names is None):
  281. if (nbfields is None):
  282. return None
  283. names = []
  284. if isinstance(names, str):
  285. names = [names, ]
  286. if nbfields is not None:
  287. nbnames = len(names)
  288. if (nbnames < nbfields):
  289. names = list(names) + [''] * (nbfields - nbnames)
  290. elif (nbnames > nbfields):
  291. names = names[:nbfields]
  292. # Set some shortcuts ...........
  293. deletechars = self.deletechars
  294. excludelist = self.excludelist
  295. case_converter = self.case_converter
  296. replace_space = self.replace_space
  297. # Initializes some variables ...
  298. validatednames = []
  299. seen = dict()
  300. nbempty = 0
  301. for item in names:
  302. item = case_converter(item).strip()
  303. if replace_space:
  304. item = item.replace(' ', replace_space)
  305. item = ''.join([c for c in item if c not in deletechars])
  306. if item == '':
  307. item = defaultfmt % nbempty
  308. while item in names:
  309. nbempty += 1
  310. item = defaultfmt % nbempty
  311. nbempty += 1
  312. elif item in excludelist:
  313. item += '_'
  314. cnt = seen.get(item, 0)
  315. if cnt > 0:
  316. validatednames.append(item + '_%d' % cnt)
  317. else:
  318. validatednames.append(item)
  319. seen[item] = cnt + 1
  320. return tuple(validatednames)
  321. def __call__(self, names, defaultfmt="f%i", nbfields=None):
  322. return self.validate(names, defaultfmt=defaultfmt, nbfields=nbfields)
  323. def str2bool(value):
  324. """
  325. Tries to transform a string supposed to represent a boolean to a boolean.
  326. Parameters
  327. ----------
  328. value : str
  329. The string that is transformed to a boolean.
  330. Returns
  331. -------
  332. boolval : bool
  333. The boolean representation of `value`.
  334. Raises
  335. ------
  336. ValueError
  337. If the string is not 'True' or 'False' (case independent)
  338. Examples
  339. --------
  340. >>> np.lib._iotools.str2bool('TRUE')
  341. True
  342. >>> np.lib._iotools.str2bool('false')
  343. False
  344. """
  345. value = value.upper()
  346. if value == 'TRUE':
  347. return True
  348. elif value == 'FALSE':
  349. return False
  350. else:
  351. raise ValueError("Invalid boolean")
  352. class ConverterError(Exception):
  353. """
  354. Exception raised when an error occurs in a converter for string values.
  355. """
  356. pass
  357. class ConverterLockError(ConverterError):
  358. """
  359. Exception raised when an attempt is made to upgrade a locked converter.
  360. """
  361. pass
  362. class ConversionWarning(UserWarning):
  363. """
  364. Warning issued when a string converter has a problem.
  365. Notes
  366. -----
  367. In `genfromtxt` a `ConversionWarning` is issued if raising exceptions
  368. is explicitly suppressed with the "invalid_raise" keyword.
  369. """
  370. pass
  371. class StringConverter:
  372. """
  373. Factory class for function transforming a string into another object
  374. (int, float).
  375. After initialization, an instance can be called to transform a string
  376. into another object. If the string is recognized as representing a
  377. missing value, a default value is returned.
  378. Attributes
  379. ----------
  380. func : function
  381. Function used for the conversion.
  382. default : any
  383. Default value to return when the input corresponds to a missing
  384. value.
  385. type : type
  386. Type of the output.
  387. _status : int
  388. Integer representing the order of the conversion.
  389. _mapper : sequence of tuples
  390. Sequence of tuples (dtype, function, default value) to evaluate in
  391. order.
  392. _locked : bool
  393. Holds `locked` parameter.
  394. Parameters
  395. ----------
  396. dtype_or_func : {None, dtype, function}, optional
  397. If a `dtype`, specifies the input data type, used to define a basic
  398. function and a default value for missing data. For example, when
  399. `dtype` is float, the `func` attribute is set to `float` and the
  400. default value to `np.nan`. If a function, this function is used to
  401. convert a string to another object. In this case, it is recommended
  402. to give an associated default value as input.
  403. default : any, optional
  404. Value to return by default, that is, when the string to be
  405. converted is flagged as missing. If not given, `StringConverter`
  406. tries to supply a reasonable default value.
  407. missing_values : {None, sequence of str}, optional
  408. ``None`` or sequence of strings indicating a missing value. If ``None``
  409. then missing values are indicated by empty entries. The default is
  410. ``None``.
  411. locked : bool, optional
  412. Whether the StringConverter should be locked to prevent automatic
  413. upgrade or not. Default is False.
  414. """
  415. _mapper = [(nx.bool_, str2bool, False),
  416. (nx.int_, int, -1),]
  417. # On 32-bit systems, we need to make sure that we explicitly include
  418. # nx.int64 since ns.int_ is nx.int32.
  419. if nx.dtype(nx.int_).itemsize < nx.dtype(nx.int64).itemsize:
  420. _mapper.append((nx.int64, int, -1))
  421. _mapper.extend([(nx.float64, float, nx.nan),
  422. (nx.complex128, complex, nx.nan + 0j),
  423. (nx.longdouble, nx.longdouble, nx.nan),
  424. # If a non-default dtype is passed, fall back to generic
  425. # ones (should only be used for the converter)
  426. (nx.integer, int, -1),
  427. (nx.floating, float, nx.nan),
  428. (nx.complexfloating, complex, nx.nan + 0j),
  429. # Last, try with the string types (must be last, because
  430. # `_mapper[-1]` is used as default in some cases)
  431. (nx.unicode_, asunicode, '???'),
  432. (nx.string_, asbytes, '???'),
  433. ])
  434. @classmethod
  435. def _getdtype(cls, val):
  436. """Returns the dtype of the input variable."""
  437. return np.array(val).dtype
  438. @classmethod
  439. def _getsubdtype(cls, val):
  440. """Returns the type of the dtype of the input variable."""
  441. return np.array(val).dtype.type
  442. @classmethod
  443. def _dtypeortype(cls, dtype):
  444. """Returns dtype for datetime64 and type of dtype otherwise."""
  445. # This is a bit annoying. We want to return the "general" type in most
  446. # cases (ie. "string" rather than "S10"), but we want to return the
  447. # specific type for datetime64 (ie. "datetime64[us]" rather than
  448. # "datetime64").
  449. if dtype.type == np.datetime64:
  450. return dtype
  451. return dtype.type
  452. @classmethod
  453. def upgrade_mapper(cls, func, default=None):
  454. """
  455. Upgrade the mapper of a StringConverter by adding a new function and
  456. its corresponding default.
  457. The input function (or sequence of functions) and its associated
  458. default value (if any) is inserted in penultimate position of the
  459. mapper. The corresponding type is estimated from the dtype of the
  460. default value.
  461. Parameters
  462. ----------
  463. func : var
  464. Function, or sequence of functions
  465. Examples
  466. --------
  467. >>> import dateutil.parser
  468. >>> import datetime
  469. >>> dateparser = dateutil.parser.parse
  470. >>> defaultdate = datetime.date(2000, 1, 1)
  471. >>> StringConverter.upgrade_mapper(dateparser, default=defaultdate)
  472. """
  473. # Func is a single functions
  474. if hasattr(func, '__call__'):
  475. cls._mapper.insert(-1, (cls._getsubdtype(default), func, default))
  476. return
  477. elif hasattr(func, '__iter__'):
  478. if isinstance(func[0], (tuple, list)):
  479. for _ in func:
  480. cls._mapper.insert(-1, _)
  481. return
  482. if default is None:
  483. default = [None] * len(func)
  484. else:
  485. default = list(default)
  486. default.append([None] * (len(func) - len(default)))
  487. for fct, dft in zip(func, default):
  488. cls._mapper.insert(-1, (cls._getsubdtype(dft), fct, dft))
  489. @classmethod
  490. def _find_map_entry(cls, dtype):
  491. # if a converter for the specific dtype is available use that
  492. for i, (deftype, func, default_def) in enumerate(cls._mapper):
  493. if dtype.type == deftype:
  494. return i, (deftype, func, default_def)
  495. # otherwise find an inexact match
  496. for i, (deftype, func, default_def) in enumerate(cls._mapper):
  497. if np.issubdtype(dtype.type, deftype):
  498. return i, (deftype, func, default_def)
  499. raise LookupError
  500. def __init__(self, dtype_or_func=None, default=None, missing_values=None,
  501. locked=False):
  502. # Defines a lock for upgrade
  503. self._locked = bool(locked)
  504. # No input dtype: minimal initialization
  505. if dtype_or_func is None:
  506. self.func = str2bool
  507. self._status = 0
  508. self.default = default or False
  509. dtype = np.dtype('bool')
  510. else:
  511. # Is the input a np.dtype ?
  512. try:
  513. self.func = None
  514. dtype = np.dtype(dtype_or_func)
  515. except TypeError:
  516. # dtype_or_func must be a function, then
  517. if not hasattr(dtype_or_func, '__call__'):
  518. errmsg = ("The input argument `dtype` is neither a"
  519. " function nor a dtype (got '%s' instead)")
  520. raise TypeError(errmsg % type(dtype_or_func))
  521. # Set the function
  522. self.func = dtype_or_func
  523. # If we don't have a default, try to guess it or set it to
  524. # None
  525. if default is None:
  526. try:
  527. default = self.func('0')
  528. except ValueError:
  529. default = None
  530. dtype = self._getdtype(default)
  531. # find the best match in our mapper
  532. try:
  533. self._status, (_, func, default_def) = self._find_map_entry(dtype)
  534. except LookupError:
  535. # no match
  536. self.default = default
  537. _, func, _ = self._mapper[-1]
  538. self._status = 0
  539. else:
  540. # use the found default only if we did not already have one
  541. if default is None:
  542. self.default = default_def
  543. else:
  544. self.default = default
  545. # If the input was a dtype, set the function to the last we saw
  546. if self.func is None:
  547. self.func = func
  548. # If the status is 1 (int), change the function to
  549. # something more robust.
  550. if self.func == self._mapper[1][1]:
  551. if issubclass(dtype.type, np.uint64):
  552. self.func = np.uint64
  553. elif issubclass(dtype.type, np.int64):
  554. self.func = np.int64
  555. else:
  556. self.func = lambda x: int(float(x))
  557. # Store the list of strings corresponding to missing values.
  558. if missing_values is None:
  559. self.missing_values = {''}
  560. else:
  561. if isinstance(missing_values, str):
  562. missing_values = missing_values.split(",")
  563. self.missing_values = set(list(missing_values) + [''])
  564. self._callingfunction = self._strict_call
  565. self.type = self._dtypeortype(dtype)
  566. self._checked = False
  567. self._initial_default = default
  568. def _loose_call(self, value):
  569. try:
  570. return self.func(value)
  571. except ValueError:
  572. return self.default
  573. def _strict_call(self, value):
  574. try:
  575. # We check if we can convert the value using the current function
  576. new_value = self.func(value)
  577. # In addition to having to check whether func can convert the
  578. # value, we also have to make sure that we don't get overflow
  579. # errors for integers.
  580. if self.func is int:
  581. try:
  582. np.array(value, dtype=self.type)
  583. except OverflowError:
  584. raise ValueError
  585. # We're still here so we can now return the new value
  586. return new_value
  587. except ValueError:
  588. if value.strip() in self.missing_values:
  589. if not self._status:
  590. self._checked = False
  591. return self.default
  592. raise ValueError("Cannot convert string '%s'" % value)
  593. def __call__(self, value):
  594. return self._callingfunction(value)
  595. def _do_upgrade(self):
  596. # Raise an exception if we locked the converter...
  597. if self._locked:
  598. errmsg = "Converter is locked and cannot be upgraded"
  599. raise ConverterLockError(errmsg)
  600. _statusmax = len(self._mapper)
  601. # Complains if we try to upgrade by the maximum
  602. _status = self._status
  603. if _status == _statusmax:
  604. errmsg = "Could not find a valid conversion function"
  605. raise ConverterError(errmsg)
  606. elif _status < _statusmax - 1:
  607. _status += 1
  608. self.type, self.func, default = self._mapper[_status]
  609. self._status = _status
  610. if self._initial_default is not None:
  611. self.default = self._initial_default
  612. else:
  613. self.default = default
  614. def upgrade(self, value):
  615. """
  616. Find the best converter for a given string, and return the result.
  617. The supplied string `value` is converted by testing different
  618. converters in order. First the `func` method of the
  619. `StringConverter` instance is tried, if this fails other available
  620. converters are tried. The order in which these other converters
  621. are tried is determined by the `_status` attribute of the instance.
  622. Parameters
  623. ----------
  624. value : str
  625. The string to convert.
  626. Returns
  627. -------
  628. out : any
  629. The result of converting `value` with the appropriate converter.
  630. """
  631. self._checked = True
  632. try:
  633. return self._strict_call(value)
  634. except ValueError:
  635. self._do_upgrade()
  636. return self.upgrade(value)
  637. def iterupgrade(self, value):
  638. self._checked = True
  639. if not hasattr(value, '__iter__'):
  640. value = (value,)
  641. _strict_call = self._strict_call
  642. try:
  643. for _m in value:
  644. _strict_call(_m)
  645. except ValueError:
  646. self._do_upgrade()
  647. self.iterupgrade(value)
  648. def update(self, func, default=None, testing_value=None,
  649. missing_values='', locked=False):
  650. """
  651. Set StringConverter attributes directly.
  652. Parameters
  653. ----------
  654. func : function
  655. Conversion function.
  656. default : any, optional
  657. Value to return by default, that is, when the string to be
  658. converted is flagged as missing. If not given,
  659. `StringConverter` tries to supply a reasonable default value.
  660. testing_value : str, optional
  661. A string representing a standard input value of the converter.
  662. This string is used to help defining a reasonable default
  663. value.
  664. missing_values : {sequence of str, None}, optional
  665. Sequence of strings indicating a missing value. If ``None``, then
  666. the existing `missing_values` are cleared. The default is `''`.
  667. locked : bool, optional
  668. Whether the StringConverter should be locked to prevent
  669. automatic upgrade or not. Default is False.
  670. Notes
  671. -----
  672. `update` takes the same parameters as the constructor of
  673. `StringConverter`, except that `func` does not accept a `dtype`
  674. whereas `dtype_or_func` in the constructor does.
  675. """
  676. self.func = func
  677. self._locked = locked
  678. # Don't reset the default to None if we can avoid it
  679. if default is not None:
  680. self.default = default
  681. self.type = self._dtypeortype(self._getdtype(default))
  682. else:
  683. try:
  684. tester = func(testing_value or '1')
  685. except (TypeError, ValueError):
  686. tester = None
  687. self.type = self._dtypeortype(self._getdtype(tester))
  688. # Add the missing values to the existing set or clear it.
  689. if missing_values is None:
  690. # Clear all missing values even though the ctor initializes it to
  691. # set(['']) when the argument is None.
  692. self.missing_values = set()
  693. else:
  694. if not np.iterable(missing_values):
  695. missing_values = [missing_values]
  696. if not all(isinstance(v, str) for v in missing_values):
  697. raise TypeError("missing_values must be strings or unicode")
  698. self.missing_values.update(missing_values)
  699. def easy_dtype(ndtype, names=None, defaultfmt="f%i", **validationargs):
  700. """
  701. Convenience function to create a `np.dtype` object.
  702. The function processes the input `dtype` and matches it with the given
  703. names.
  704. Parameters
  705. ----------
  706. ndtype : var
  707. Definition of the dtype. Can be any string or dictionary recognized
  708. by the `np.dtype` function, or a sequence of types.
  709. names : str or sequence, optional
  710. Sequence of strings to use as field names for a structured dtype.
  711. For convenience, `names` can be a string of a comma-separated list
  712. of names.
  713. defaultfmt : str, optional
  714. Format string used to define missing names, such as ``"f%i"``
  715. (default) or ``"fields_%02i"``.
  716. validationargs : optional
  717. A series of optional arguments used to initialize a
  718. `NameValidator`.
  719. Examples
  720. --------
  721. >>> np.lib._iotools.easy_dtype(float)
  722. dtype('float64')
  723. >>> np.lib._iotools.easy_dtype("i4, f8")
  724. dtype([('f0', '<i4'), ('f1', '<f8')])
  725. >>> np.lib._iotools.easy_dtype("i4, f8", defaultfmt="field_%03i")
  726. dtype([('field_000', '<i4'), ('field_001', '<f8')])
  727. >>> np.lib._iotools.easy_dtype((int, float, float), names="a,b,c")
  728. dtype([('a', '<i8'), ('b', '<f8'), ('c', '<f8')])
  729. >>> np.lib._iotools.easy_dtype(float, names="a,b,c")
  730. dtype([('a', '<f8'), ('b', '<f8'), ('c', '<f8')])
  731. """
  732. try:
  733. ndtype = np.dtype(ndtype)
  734. except TypeError:
  735. validate = NameValidator(**validationargs)
  736. nbfields = len(ndtype)
  737. if names is None:
  738. names = [''] * len(ndtype)
  739. elif isinstance(names, str):
  740. names = names.split(",")
  741. names = validate(names, nbfields=nbfields, defaultfmt=defaultfmt)
  742. ndtype = np.dtype(dict(formats=ndtype, names=names))
  743. else:
  744. # Explicit names
  745. if names is not None:
  746. validate = NameValidator(**validationargs)
  747. if isinstance(names, str):
  748. names = names.split(",")
  749. # Simple dtype: repeat to match the nb of names
  750. if ndtype.names is None:
  751. formats = tuple([ndtype.type] * len(names))
  752. names = validate(names, defaultfmt=defaultfmt)
  753. ndtype = np.dtype(list(zip(names, formats)))
  754. # Structured dtype: just validate the names as needed
  755. else:
  756. ndtype.names = validate(names, nbfields=len(ndtype.names),
  757. defaultfmt=defaultfmt)
  758. # No implicit names
  759. elif ndtype.names is not None:
  760. validate = NameValidator(**validationargs)
  761. # Default initial names : should we change the format ?
  762. numbered_names = tuple("f%i" % i for i in range(len(ndtype.names)))
  763. if ((ndtype.names == numbered_names) and (defaultfmt != "f%i")):
  764. ndtype.names = validate([''] * len(ndtype.names),
  765. defaultfmt=defaultfmt)
  766. # Explicit initial names : just validate
  767. else:
  768. ndtype.names = validate(ndtype.names, defaultfmt=defaultfmt)
  769. return ndtype