m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

774 lines
26 KiB

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