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