_iotools.py 30 KB

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