mrecords.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. """:mod:`numpy.ma..mrecords`
  2. Defines the equivalent of :class:`numpy.recarrays` for masked arrays,
  3. where fields can be accessed as attributes.
  4. Note that :class:`numpy.ma.MaskedArray` already supports structured datatypes
  5. and the masking of individual fields.
  6. .. moduleauthor:: Pierre Gerard-Marchant
  7. """
  8. from __future__ import division, absolute_import, print_function
  9. # We should make sure that no field is called '_mask','mask','_fieldmask',
  10. # or whatever restricted keywords. An idea would be to no bother in the
  11. # first place, and then rename the invalid fields with a trailing
  12. # underscore. Maybe we could just overload the parser function ?
  13. import sys
  14. import warnings
  15. import numpy as np
  16. from numpy.compat import basestring
  17. from numpy import (
  18. bool_, dtype, ndarray, recarray, array as narray
  19. )
  20. from numpy.core.records import (
  21. fromarrays as recfromarrays, fromrecords as recfromrecords
  22. )
  23. _byteorderconv = np.core.records._byteorderconv
  24. import numpy.ma as ma
  25. from numpy.ma import (
  26. MAError, MaskedArray, masked, nomask, masked_array, getdata,
  27. getmaskarray, filled
  28. )
  29. _check_fill_value = ma.core._check_fill_value
  30. __all__ = [
  31. 'MaskedRecords', 'mrecarray', 'fromarrays', 'fromrecords',
  32. 'fromtextfile', 'addfield',
  33. ]
  34. reserved_fields = ['_data', '_mask', '_fieldmask', 'dtype']
  35. def _checknames(descr, names=None):
  36. """
  37. Checks that field names ``descr`` are not reserved keywords.
  38. If this is the case, a default 'f%i' is substituted. If the argument
  39. `names` is not None, updates the field names to valid names.
  40. """
  41. ndescr = len(descr)
  42. default_names = ['f%i' % i for i in range(ndescr)]
  43. if names is None:
  44. new_names = default_names
  45. else:
  46. if isinstance(names, (tuple, list)):
  47. new_names = names
  48. elif isinstance(names, str):
  49. new_names = names.split(',')
  50. else:
  51. raise NameError("illegal input names %s" % repr(names))
  52. nnames = len(new_names)
  53. if nnames < ndescr:
  54. new_names += default_names[nnames:]
  55. ndescr = []
  56. for (n, d, t) in zip(new_names, default_names, descr.descr):
  57. if n in reserved_fields:
  58. if t[0] in reserved_fields:
  59. ndescr.append((d, t[1]))
  60. else:
  61. ndescr.append(t)
  62. else:
  63. ndescr.append((n, t[1]))
  64. return np.dtype(ndescr)
  65. def _get_fieldmask(self):
  66. mdescr = [(n, '|b1') for n in self.dtype.names]
  67. fdmask = np.empty(self.shape, dtype=mdescr)
  68. fdmask.flat = tuple([False] * len(mdescr))
  69. return fdmask
  70. class MaskedRecords(MaskedArray, object):
  71. """
  72. Attributes
  73. ----------
  74. _data : recarray
  75. Underlying data, as a record array.
  76. _mask : boolean array
  77. Mask of the records. A record is masked when all its fields are
  78. masked.
  79. _fieldmask : boolean recarray
  80. Record array of booleans, setting the mask of each individual field
  81. of each record.
  82. _fill_value : record
  83. Filling values for each field.
  84. """
  85. def __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None,
  86. formats=None, names=None, titles=None,
  87. byteorder=None, aligned=False,
  88. mask=nomask, hard_mask=False, fill_value=None, keep_mask=True,
  89. copy=False,
  90. **options):
  91. self = recarray.__new__(cls, shape, dtype=dtype, buf=buf, offset=offset,
  92. strides=strides, formats=formats, names=names,
  93. titles=titles, byteorder=byteorder,
  94. aligned=aligned,)
  95. mdtype = ma.make_mask_descr(self.dtype)
  96. if mask is nomask or not np.size(mask):
  97. if not keep_mask:
  98. self._mask = tuple([False] * len(mdtype))
  99. else:
  100. mask = np.array(mask, copy=copy)
  101. if mask.shape != self.shape:
  102. (nd, nm) = (self.size, mask.size)
  103. if nm == 1:
  104. mask = np.resize(mask, self.shape)
  105. elif nm == nd:
  106. mask = np.reshape(mask, self.shape)
  107. else:
  108. msg = "Mask and data not compatible: data size is %i, " + \
  109. "mask size is %i."
  110. raise MAError(msg % (nd, nm))
  111. copy = True
  112. if not keep_mask:
  113. self.__setmask__(mask)
  114. self._sharedmask = True
  115. else:
  116. if mask.dtype == mdtype:
  117. _mask = mask
  118. else:
  119. _mask = np.array([tuple([m] * len(mdtype)) for m in mask],
  120. dtype=mdtype)
  121. self._mask = _mask
  122. return self
  123. def __array_finalize__(self, obj):
  124. # Make sure we have a _fieldmask by default
  125. _mask = getattr(obj, '_mask', None)
  126. if _mask is None:
  127. objmask = getattr(obj, '_mask', nomask)
  128. _dtype = ndarray.__getattribute__(self, 'dtype')
  129. if objmask is nomask:
  130. _mask = ma.make_mask_none(self.shape, dtype=_dtype)
  131. else:
  132. mdescr = ma.make_mask_descr(_dtype)
  133. _mask = narray([tuple([m] * len(mdescr)) for m in objmask],
  134. dtype=mdescr).view(recarray)
  135. # Update some of the attributes
  136. _dict = self.__dict__
  137. _dict.update(_mask=_mask)
  138. self._update_from(obj)
  139. if _dict['_baseclass'] == ndarray:
  140. _dict['_baseclass'] = recarray
  141. return
  142. @property
  143. def _data(self):
  144. """
  145. Returns the data as a recarray.
  146. """
  147. return ndarray.view(self, recarray)
  148. @property
  149. def _fieldmask(self):
  150. """
  151. Alias to mask.
  152. """
  153. return self._mask
  154. def __len__(self):
  155. """
  156. Returns the length
  157. """
  158. # We have more than one record
  159. if self.ndim:
  160. return len(self._data)
  161. # We have only one record: return the nb of fields
  162. return len(self.dtype)
  163. def __getattribute__(self, attr):
  164. try:
  165. return object.__getattribute__(self, attr)
  166. except AttributeError:
  167. # attr must be a fieldname
  168. pass
  169. fielddict = ndarray.__getattribute__(self, 'dtype').fields
  170. try:
  171. res = fielddict[attr][:2]
  172. except (TypeError, KeyError):
  173. raise AttributeError("record array has no attribute %s" % attr)
  174. # So far, so good
  175. _localdict = ndarray.__getattribute__(self, '__dict__')
  176. _data = ndarray.view(self, _localdict['_baseclass'])
  177. obj = _data.getfield(*res)
  178. if obj.dtype.names is not None:
  179. raise NotImplementedError("MaskedRecords is currently limited to"
  180. "simple records.")
  181. # Get some special attributes
  182. # Reset the object's mask
  183. hasmasked = False
  184. _mask = _localdict.get('_mask', None)
  185. if _mask is not None:
  186. try:
  187. _mask = _mask[attr]
  188. except IndexError:
  189. # Couldn't find a mask: use the default (nomask)
  190. pass
  191. tp_len = len(_mask.dtype)
  192. hasmasked = _mask.view((bool, ((tp_len,) if tp_len else ()))).any()
  193. if (obj.shape or hasmasked):
  194. obj = obj.view(MaskedArray)
  195. obj._baseclass = ndarray
  196. obj._isfield = True
  197. obj._mask = _mask
  198. # Reset the field values
  199. _fill_value = _localdict.get('_fill_value', None)
  200. if _fill_value is not None:
  201. try:
  202. obj._fill_value = _fill_value[attr]
  203. except ValueError:
  204. obj._fill_value = None
  205. else:
  206. obj = obj.item()
  207. return obj
  208. def __setattr__(self, attr, val):
  209. """
  210. Sets the attribute attr to the value val.
  211. """
  212. # Should we call __setmask__ first ?
  213. if attr in ['mask', 'fieldmask']:
  214. self.__setmask__(val)
  215. return
  216. # Create a shortcut (so that we don't have to call getattr all the time)
  217. _localdict = object.__getattribute__(self, '__dict__')
  218. # Check whether we're creating a new field
  219. newattr = attr not in _localdict
  220. try:
  221. # Is attr a generic attribute ?
  222. ret = object.__setattr__(self, attr, val)
  223. except Exception:
  224. # Not a generic attribute: exit if it's not a valid field
  225. fielddict = ndarray.__getattribute__(self, 'dtype').fields or {}
  226. optinfo = ndarray.__getattribute__(self, '_optinfo') or {}
  227. if not (attr in fielddict or attr in optinfo):
  228. raise
  229. else:
  230. # Get the list of names
  231. fielddict = ndarray.__getattribute__(self, 'dtype').fields or {}
  232. # Check the attribute
  233. if attr not in fielddict:
  234. return ret
  235. if newattr:
  236. # We just added this one or this setattr worked on an
  237. # internal attribute.
  238. try:
  239. object.__delattr__(self, attr)
  240. except Exception:
  241. return ret
  242. # Let's try to set the field
  243. try:
  244. res = fielddict[attr][:2]
  245. except (TypeError, KeyError):
  246. raise AttributeError("record array has no attribute %s" % attr)
  247. if val is masked:
  248. _fill_value = _localdict['_fill_value']
  249. if _fill_value is not None:
  250. dval = _localdict['_fill_value'][attr]
  251. else:
  252. dval = val
  253. mval = True
  254. else:
  255. dval = filled(val)
  256. mval = getmaskarray(val)
  257. obj = ndarray.__getattribute__(self, '_data').setfield(dval, *res)
  258. _localdict['_mask'].__setitem__(attr, mval)
  259. return obj
  260. def __getitem__(self, indx):
  261. """
  262. Returns all the fields sharing the same fieldname base.
  263. The fieldname base is either `_data` or `_mask`.
  264. """
  265. _localdict = self.__dict__
  266. _mask = ndarray.__getattribute__(self, '_mask')
  267. _data = ndarray.view(self, _localdict['_baseclass'])
  268. # We want a field
  269. if isinstance(indx, basestring):
  270. # Make sure _sharedmask is True to propagate back to _fieldmask
  271. # Don't use _set_mask, there are some copies being made that
  272. # break propagation Don't force the mask to nomask, that wreaks
  273. # easy masking
  274. obj = _data[indx].view(MaskedArray)
  275. obj._mask = _mask[indx]
  276. obj._sharedmask = True
  277. fval = _localdict['_fill_value']
  278. if fval is not None:
  279. obj._fill_value = fval[indx]
  280. # Force to masked if the mask is True
  281. if not obj.ndim and obj._mask:
  282. return masked
  283. return obj
  284. # We want some elements.
  285. # First, the data.
  286. obj = np.array(_data[indx], copy=False).view(mrecarray)
  287. obj._mask = np.array(_mask[indx], copy=False).view(recarray)
  288. return obj
  289. def __setitem__(self, indx, value):
  290. """
  291. Sets the given record to value.
  292. """
  293. MaskedArray.__setitem__(self, indx, value)
  294. if isinstance(indx, basestring):
  295. self._mask[indx] = ma.getmaskarray(value)
  296. def __str__(self):
  297. """
  298. Calculates the string representation.
  299. """
  300. if self.size > 1:
  301. mstr = ["(%s)" % ",".join([str(i) for i in s])
  302. for s in zip(*[getattr(self, f) for f in self.dtype.names])]
  303. return "[%s]" % ", ".join(mstr)
  304. else:
  305. mstr = ["%s" % ",".join([str(i) for i in s])
  306. for s in zip([getattr(self, f) for f in self.dtype.names])]
  307. return "(%s)" % ", ".join(mstr)
  308. def __repr__(self):
  309. """
  310. Calculates the repr representation.
  311. """
  312. _names = self.dtype.names
  313. fmt = "%%%is : %%s" % (max([len(n) for n in _names]) + 4,)
  314. reprstr = [fmt % (f, getattr(self, f)) for f in self.dtype.names]
  315. reprstr.insert(0, 'masked_records(')
  316. reprstr.extend([fmt % (' fill_value', self.fill_value),
  317. ' )'])
  318. return str("\n".join(reprstr))
  319. def view(self, dtype=None, type=None):
  320. """
  321. Returns a view of the mrecarray.
  322. """
  323. # OK, basic copy-paste from MaskedArray.view.
  324. if dtype is None:
  325. if type is None:
  326. output = ndarray.view(self)
  327. else:
  328. output = ndarray.view(self, type)
  329. # Here again.
  330. elif type is None:
  331. try:
  332. if issubclass(dtype, ndarray):
  333. output = ndarray.view(self, dtype)
  334. dtype = None
  335. else:
  336. output = ndarray.view(self, dtype)
  337. # OK, there's the change
  338. except TypeError:
  339. dtype = np.dtype(dtype)
  340. # we need to revert to MaskedArray, but keeping the possibility
  341. # of subclasses (eg, TimeSeriesRecords), so we'll force a type
  342. # set to the first parent
  343. if dtype.fields is None:
  344. basetype = self.__class__.__bases__[0]
  345. output = self.__array__().view(dtype, basetype)
  346. output._update_from(self)
  347. else:
  348. output = ndarray.view(self, dtype)
  349. output._fill_value = None
  350. else:
  351. output = ndarray.view(self, dtype, type)
  352. # Update the mask, just like in MaskedArray.view
  353. if (getattr(output, '_mask', nomask) is not nomask):
  354. mdtype = ma.make_mask_descr(output.dtype)
  355. output._mask = self._mask.view(mdtype, ndarray)
  356. output._mask.shape = output.shape
  357. return output
  358. def harden_mask(self):
  359. """
  360. Forces the mask to hard.
  361. """
  362. self._hardmask = True
  363. def soften_mask(self):
  364. """
  365. Forces the mask to soft
  366. """
  367. self._hardmask = False
  368. def copy(self):
  369. """
  370. Returns a copy of the masked record.
  371. """
  372. copied = self._data.copy().view(type(self))
  373. copied._mask = self._mask.copy()
  374. return copied
  375. def tolist(self, fill_value=None):
  376. """
  377. Return the data portion of the array as a list.
  378. Data items are converted to the nearest compatible Python type.
  379. Masked values are converted to fill_value. If fill_value is None,
  380. the corresponding entries in the output list will be ``None``.
  381. """
  382. if fill_value is not None:
  383. return self.filled(fill_value).tolist()
  384. result = narray(self.filled().tolist(), dtype=object)
  385. mask = narray(self._mask.tolist())
  386. result[mask] = None
  387. return result.tolist()
  388. def __getstate__(self):
  389. """Return the internal state of the masked array.
  390. This is for pickling.
  391. """
  392. state = (1,
  393. self.shape,
  394. self.dtype,
  395. self.flags.fnc,
  396. self._data.tobytes(),
  397. self._mask.tobytes(),
  398. self._fill_value,
  399. )
  400. return state
  401. def __setstate__(self, state):
  402. """
  403. Restore the internal state of the masked array.
  404. This is for pickling. ``state`` is typically the output of the
  405. ``__getstate__`` output, and is a 5-tuple:
  406. - class name
  407. - a tuple giving the shape of the data
  408. - a typecode for the data
  409. - a binary string for the data
  410. - a binary string for the mask.
  411. """
  412. (ver, shp, typ, isf, raw, msk, flv) = state
  413. ndarray.__setstate__(self, (shp, typ, isf, raw))
  414. mdtype = dtype([(k, bool_) for (k, _) in self.dtype.descr])
  415. self.__dict__['_mask'].__setstate__((shp, mdtype, isf, msk))
  416. self.fill_value = flv
  417. def __reduce__(self):
  418. """
  419. Return a 3-tuple for pickling a MaskedArray.
  420. """
  421. return (_mrreconstruct,
  422. (self.__class__, self._baseclass, (0,), 'b',),
  423. self.__getstate__())
  424. def _mrreconstruct(subtype, baseclass, baseshape, basetype,):
  425. """
  426. Build a new MaskedArray from the information stored in a pickle.
  427. """
  428. _data = ndarray.__new__(baseclass, baseshape, basetype).view(subtype)
  429. _mask = ndarray.__new__(ndarray, baseshape, 'b1')
  430. return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,)
  431. mrecarray = MaskedRecords
  432. ###############################################################################
  433. # Constructors #
  434. ###############################################################################
  435. def fromarrays(arraylist, dtype=None, shape=None, formats=None,
  436. names=None, titles=None, aligned=False, byteorder=None,
  437. fill_value=None):
  438. """
  439. Creates a mrecarray from a (flat) list of masked arrays.
  440. Parameters
  441. ----------
  442. arraylist : sequence
  443. A list of (masked) arrays. Each element of the sequence is first converted
  444. to a masked array if needed. If a 2D array is passed as argument, it is
  445. processed line by line
  446. dtype : {None, dtype}, optional
  447. Data type descriptor.
  448. shape : {None, integer}, optional
  449. Number of records. If None, shape is defined from the shape of the
  450. first array in the list.
  451. formats : {None, sequence}, optional
  452. Sequence of formats for each individual field. If None, the formats will
  453. be autodetected by inspecting the fields and selecting the highest dtype
  454. possible.
  455. names : {None, sequence}, optional
  456. Sequence of the names of each field.
  457. fill_value : {None, sequence}, optional
  458. Sequence of data to be used as filling values.
  459. Notes
  460. -----
  461. Lists of tuples should be preferred over lists of lists for faster processing.
  462. """
  463. datalist = [getdata(x) for x in arraylist]
  464. masklist = [np.atleast_1d(getmaskarray(x)) for x in arraylist]
  465. _array = recfromarrays(datalist,
  466. dtype=dtype, shape=shape, formats=formats,
  467. names=names, titles=titles, aligned=aligned,
  468. byteorder=byteorder).view(mrecarray)
  469. _array._mask.flat = list(zip(*masklist))
  470. if fill_value is not None:
  471. _array.fill_value = fill_value
  472. return _array
  473. def fromrecords(reclist, dtype=None, shape=None, formats=None, names=None,
  474. titles=None, aligned=False, byteorder=None,
  475. fill_value=None, mask=nomask):
  476. """
  477. Creates a MaskedRecords from a list of records.
  478. Parameters
  479. ----------
  480. reclist : sequence
  481. A list of records. Each element of the sequence is first converted
  482. to a masked array if needed. If a 2D array is passed as argument, it is
  483. processed line by line
  484. dtype : {None, dtype}, optional
  485. Data type descriptor.
  486. shape : {None,int}, optional
  487. Number of records. If None, ``shape`` is defined from the shape of the
  488. first array in the list.
  489. formats : {None, sequence}, optional
  490. Sequence of formats for each individual field. If None, the formats will
  491. be autodetected by inspecting the fields and selecting the highest dtype
  492. possible.
  493. names : {None, sequence}, optional
  494. Sequence of the names of each field.
  495. fill_value : {None, sequence}, optional
  496. Sequence of data to be used as filling values.
  497. mask : {nomask, sequence}, optional.
  498. External mask to apply on the data.
  499. Notes
  500. -----
  501. Lists of tuples should be preferred over lists of lists for faster processing.
  502. """
  503. # Grab the initial _fieldmask, if needed:
  504. _mask = getattr(reclist, '_mask', None)
  505. # Get the list of records.
  506. if isinstance(reclist, ndarray):
  507. # Make sure we don't have some hidden mask
  508. if isinstance(reclist, MaskedArray):
  509. reclist = reclist.filled().view(ndarray)
  510. # Grab the initial dtype, just in case
  511. if dtype is None:
  512. dtype = reclist.dtype
  513. reclist = reclist.tolist()
  514. mrec = recfromrecords(reclist, dtype=dtype, shape=shape, formats=formats,
  515. names=names, titles=titles,
  516. aligned=aligned, byteorder=byteorder).view(mrecarray)
  517. # Set the fill_value if needed
  518. if fill_value is not None:
  519. mrec.fill_value = fill_value
  520. # Now, let's deal w/ the mask
  521. if mask is not nomask:
  522. mask = np.array(mask, copy=False)
  523. maskrecordlength = len(mask.dtype)
  524. if maskrecordlength:
  525. mrec._mask.flat = mask
  526. elif mask.ndim == 2:
  527. mrec._mask.flat = [tuple(m) for m in mask]
  528. else:
  529. mrec.__setmask__(mask)
  530. if _mask is not None:
  531. mrec._mask[:] = _mask
  532. return mrec
  533. def _guessvartypes(arr):
  534. """
  535. Tries to guess the dtypes of the str_ ndarray `arr`.
  536. Guesses by testing element-wise conversion. Returns a list of dtypes.
  537. The array is first converted to ndarray. If the array is 2D, the test
  538. is performed on the first line. An exception is raised if the file is
  539. 3D or more.
  540. """
  541. vartypes = []
  542. arr = np.asarray(arr)
  543. if arr.ndim == 2:
  544. arr = arr[0]
  545. elif arr.ndim > 2:
  546. raise ValueError("The array should be 2D at most!")
  547. # Start the conversion loop.
  548. for f in arr:
  549. try:
  550. int(f)
  551. except (ValueError, TypeError):
  552. try:
  553. float(f)
  554. except (ValueError, TypeError):
  555. try:
  556. complex(f)
  557. except (ValueError, TypeError):
  558. vartypes.append(arr.dtype)
  559. else:
  560. vartypes.append(np.dtype(complex))
  561. else:
  562. vartypes.append(np.dtype(float))
  563. else:
  564. vartypes.append(np.dtype(int))
  565. return vartypes
  566. def openfile(fname):
  567. """
  568. Opens the file handle of file `fname`.
  569. """
  570. # A file handle
  571. if hasattr(fname, 'readline'):
  572. return fname
  573. # Try to open the file and guess its type
  574. try:
  575. f = open(fname)
  576. except IOError:
  577. raise IOError("No such file: '%s'" % fname)
  578. if f.readline()[:2] != "\\x":
  579. f.seek(0, 0)
  580. return f
  581. f.close()
  582. raise NotImplementedError("Wow, binary file")
  583. def fromtextfile(fname, delimitor=None, commentchar='#', missingchar='',
  584. varnames=None, vartypes=None):
  585. """
  586. Creates a mrecarray from data stored in the file `filename`.
  587. Parameters
  588. ----------
  589. fname : {file name/handle}
  590. Handle of an opened file.
  591. delimitor : {None, string}, optional
  592. Alphanumeric character used to separate columns in the file.
  593. If None, any (group of) white spacestring(s) will be used.
  594. commentchar : {'#', string}, optional
  595. Alphanumeric character used to mark the start of a comment.
  596. missingchar : {'', string}, optional
  597. String indicating missing data, and used to create the masks.
  598. varnames : {None, sequence}, optional
  599. Sequence of the variable names. If None, a list will be created from
  600. the first non empty line of the file.
  601. vartypes : {None, sequence}, optional
  602. Sequence of the variables dtypes. If None, it will be estimated from
  603. the first non-commented line.
  604. Ultra simple: the varnames are in the header, one line"""
  605. # Try to open the file.
  606. ftext = openfile(fname)
  607. # Get the first non-empty line as the varnames
  608. while True:
  609. line = ftext.readline()
  610. firstline = line[:line.find(commentchar)].strip()
  611. _varnames = firstline.split(delimitor)
  612. if len(_varnames) > 1:
  613. break
  614. if varnames is None:
  615. varnames = _varnames
  616. # Get the data.
  617. _variables = masked_array([line.strip().split(delimitor) for line in ftext
  618. if line[0] != commentchar and len(line) > 1])
  619. (_, nfields) = _variables.shape
  620. ftext.close()
  621. # Try to guess the dtype.
  622. if vartypes is None:
  623. vartypes = _guessvartypes(_variables[0])
  624. else:
  625. vartypes = [np.dtype(v) for v in vartypes]
  626. if len(vartypes) != nfields:
  627. msg = "Attempting to %i dtypes for %i fields!"
  628. msg += " Reverting to default."
  629. warnings.warn(msg % (len(vartypes), nfields), stacklevel=2)
  630. vartypes = _guessvartypes(_variables[0])
  631. # Construct the descriptor.
  632. mdescr = [(n, f) for (n, f) in zip(varnames, vartypes)]
  633. mfillv = [ma.default_fill_value(f) for f in vartypes]
  634. # Get the data and the mask.
  635. # We just need a list of masked_arrays. It's easier to create it like that:
  636. _mask = (_variables.T == missingchar)
  637. _datalist = [masked_array(a, mask=m, dtype=t, fill_value=f)
  638. for (a, m, t, f) in zip(_variables.T, _mask, vartypes, mfillv)]
  639. return fromarrays(_datalist, dtype=mdescr)
  640. def addfield(mrecord, newfield, newfieldname=None):
  641. """Adds a new field to the masked record array
  642. Uses `newfield` as data and `newfieldname` as name. If `newfieldname`
  643. is None, the new field name is set to 'fi', where `i` is the number of
  644. existing fields.
  645. """
  646. _data = mrecord._data
  647. _mask = mrecord._mask
  648. if newfieldname is None or newfieldname in reserved_fields:
  649. newfieldname = 'f%i' % len(_data.dtype)
  650. newfield = ma.array(newfield)
  651. # Get the new data.
  652. # Create a new empty recarray
  653. newdtype = np.dtype(_data.dtype.descr + [(newfieldname, newfield.dtype)])
  654. newdata = recarray(_data.shape, newdtype)
  655. # Add the existing field
  656. [newdata.setfield(_data.getfield(*f), *f)
  657. for f in _data.dtype.fields.values()]
  658. # Add the new field
  659. newdata.setfield(newfield._data, *newdata.dtype.fields[newfieldname])
  660. newdata = newdata.view(MaskedRecords)
  661. # Get the new mask
  662. # Create a new empty recarray
  663. newmdtype = np.dtype([(n, bool_) for n in newdtype.names])
  664. newmask = recarray(_data.shape, newmdtype)
  665. # Add the old masks
  666. [newmask.setfield(_mask.getfield(*f), *f)
  667. for f in _mask.dtype.fields.values()]
  668. # Add the mask of the new field
  669. newmask.setfield(getmaskarray(newfield),
  670. *newmask.dtype.fields[newfieldname])
  671. newdata._mask = newmask
  672. return newdata