mrecords.py 26 KB

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