mrecords.py 27 KB

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