_iotools.py 32 KB

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