mrecords.py 26 KB

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