Beispiel #1
0
 def view(self, dtype=None, type=None):
     u"""Return view of *data* i.e. new *ValueArray* object but pointing to
        same data.
     """
     if type is None:
         return self.__class__(ndarray.view(self), self.info, copy=False)
     else:
         return ndarray.view(self, dtype, type)
Beispiel #2
0
 def view(self, dtype=None, type=None):
     u"""Return view of *data* i.e. new *hfarray* object but pointing to
        same data.
     """
     if type is None:
         return self.__class__(ndarray.view(self, dtype=self.dtype),
                               dims=self.dims, copy=False)
     else:
         return ndarray.view(self, dtype=self.dtype, type=type)
Beispiel #3
0
 def view(self, obj):
     """Returns a view of the mrecarray."""
     try:
         if issubclass(obj, ndarray):
             return ndarray.view(self, obj)
     except TypeError:
         pass
     dtype = np.dtype(obj)
     if dtype.fields is None:
         return self.__array__().view(dtype)
     return ndarray.view(self, obj)
Beispiel #4
0
 def view(self, obj):
     """Returns a view of the mrecarray."""
     try:
         if issubclass(obj, ndarray):
             return ndarray.view(self, obj)
     except TypeError:
         pass
     dtype_ = np.dtype(obj)
     if dtype_.fields is None:
         return self.__array__().view(dtype_)
     return ndarray.view(self, obj)
Beispiel #5
0
    def test_subtype_view(self):
        from numpy import ndarray, array

        class matrix(ndarray):
            def __new__(subtype, data, dtype=None, copy=True):
                if isinstance(data, matrix):
                    return data
                return data.view(subtype)

        a = array(range(5))
        b = matrix(a)
        assert isinstance(b, matrix)
        assert b.__array_priority__ == 0.0
        assert (b == a).all()
        assert isinstance(b.view(), matrix)
        a = array(5)[()]
        for s in [matrix, ndarray]:
            b = a.view(s)
            assert b == a
            assert type(b) is type(a)
        a = matrix(array(range(5)))
        for s in [matrix, ndarray]:
            b = ndarray.view(a, s)
            assert (b == a).all()
            assert type(b) is s
Beispiel #6
0
    def __getitem__(self, indx):
        """Returns all the fields sharing the same fieldname base.
The fieldname base is either `_data` or `_mask`."""
        _localdict = self.__dict__
        _mask = ndarray.__getattribute__(self, '_mask')
        _data = ndarray.view(self, _localdict['_baseclass'])
        # We want a field ........
        if isinstance(indx, basestring):
            #!!!: Make sure _sharedmask is True to propagate back to _fieldmask
            #!!!: Don't use _set_mask, there are some copies being made...
            #!!!: ...that break propagation
            #!!!: Don't force the mask to nomask, that wrecks easy masking
            obj = _data[indx].view(MaskedArray)
            obj._mask = _mask[indx]
            obj._sharedmask = True
            fval = _localdict['_fill_value']
            if fval is not None:
                obj._fill_value = fval[indx]
            # Force to masked if the mask is True
            if not obj.ndim and obj._mask:
                return masked
            return obj
        # We want some elements ..
        # First, the data ........
        obj = np.array(_data[indx], copy=False).view(mrecarray)
        obj._mask = np.array(_mask[indx], copy=False).view(recarray)
        return obj
Beispiel #7
0
    def __getitem__(self, indx):
        """
        Returns all the fields sharing the same fieldname base.

        The fieldname base is either `_data` or `_mask`.

        """
        _localdict = self.__dict__
        _mask = ndarray.__getattribute__(self, '_mask')
        _data = ndarray.view(self, _localdict['_baseclass'])
        # We want a field
        if isinstance(indx, str):
            # Make sure _sharedmask is True to propagate back to _fieldmask
            # Don't use _set_mask, there are some copies being made that
            # break propagation Don't force the mask to nomask, that wreaks
            # easy masking
            obj = _data[indx].view(MaskedArray)
            obj._mask = _mask[indx]
            obj._sharedmask = True
            fval = _localdict['_fill_value']
            if fval is not None:
                obj._fill_value = fval[indx]
            # Force to masked if the mask is True
            if not obj.ndim and obj._mask:
                return masked
            return obj
        # We want some elements.
        # First, the data.
        obj = np.array(_data[indx], copy=False).view(mrecarray)
        obj._mask = np.array(_mask[indx], copy=False).view(recarray)
        return obj
Beispiel #8
0
 def __getitem__(self, indx):
     """Returns all the fields sharing the same fieldname base.
 The fieldname base is either `_data` or `_mask`."""
     _localdict = self.__dict__
     # We want a field ........
     if indx in ndarray.__getattribute__(self, 'dtype').names:
         obj = self._data[indx].view(TimeSeries)
         obj._dates = _localdict['_dates']
         obj._mask = make_mask(_localdict['_mask'][indx])
         return obj
     # We want some elements ..
     obj = TimeSeries.__getitem__(self, indx)
     if isinstance(obj, MaskedArray) and not isinstance(obj, TimeSeries):
         obj = ndarray.view(obj, MaskedRecords)
     return obj
 def __getitem__(self, indx):
     """Returns all the fields sharing the same fieldname base.
 The fieldname base is either `_data` or `_mask`."""
     _localdict = self.__dict__
     # We want a field ........
     if indx in ndarray.__getattribute__(self, "dtype").names:
         obj = self._data[indx].view(TimeSeries)
         obj._dates = _localdict["_dates"]
         obj._mask = make_mask(_localdict["_mask"][indx])
         return obj
     # We want some elements ..
     obj = TimeSeries.__getitem__(self, indx)
     if isinstance(obj, MaskedArray) and not isinstance(obj, TimeSeries):
         obj = ndarray.view(obj, MaskedRecords)
     return obj
Beispiel #10
0
 def __getattribute__(self, attr):
     try:
         return object.__getattribute__(self, attr)
     except AttributeError:
         # attr must be a fieldname
         pass
     fielddict = ndarray.__getattribute__(self, 'dtype').fields
     try:
         res = fielddict[attr][:2]
     except (TypeError, KeyError) as e:
         raise AttributeError(
             f'record array has no attribute {attr}') from e
     # So far, so good
     _localdict = ndarray.__getattribute__(self, '__dict__')
     _data = ndarray.view(self, _localdict['_baseclass'])
     obj = _data.getfield(*res)
     if obj.dtype.names is not None:
         raise NotImplementedError("MaskedRecords is currently limited to"
                                   "simple records.")
     # Get some special attributes
     # Reset the object's mask
     hasmasked = False
     _mask = _localdict.get('_mask', None)
     if _mask is not None:
         try:
             _mask = _mask[attr]
         except IndexError:
             # Couldn't find a mask: use the default (nomask)
             pass
         tp_len = len(_mask.dtype)
         hasmasked = _mask.view((bool, ((tp_len, ) if tp_len else
                                        ()))).any()
     if (obj.shape or hasmasked):
         obj = obj.view(MaskedArray)
         obj._baseclass = ndarray
         obj._isfield = True
         obj._mask = _mask
         # Reset the field values
         _fill_value = _localdict.get('_fill_value', None)
         if _fill_value is not None:
             try:
                 obj._fill_value = _fill_value[attr]
             except ValueError:
                 obj._fill_value = None
     else:
         obj = obj.item()
     return obj
Beispiel #11
0
 def __getattribute__(self, attr):
     try:
         return object.__getattribute__(self, attr)
     except AttributeError:
         # attr must be a fieldname
         pass
     fielddict = ndarray.__getattribute__(self, 'dtype').fields
     try:
         res = fielddict[attr][:2]
     except (TypeError, KeyError):
         raise AttributeError("record array has no attribute %s" % attr)
     # So far, so good
     _localdict = ndarray.__getattribute__(self, '__dict__')
     _data = ndarray.view(self, _localdict['_baseclass'])
     obj = _data.getfield(*res)
     if obj.dtype.fields:
         raise NotImplementedError("MaskedRecords is currently limited to"
                                   "simple records.")
     # Get some special attributes
     # Reset the object's mask
     hasmasked = False
     _mask = _localdict.get('_mask', None)
     if _mask is not None:
         try:
             _mask = _mask[attr]
         except IndexError:
             # Couldn't find a mask: use the default (nomask)
             pass
         hasmasked = _mask.view((np.bool, (len(_mask.dtype) or 1))).any()
     if (obj.shape or hasmasked):
         obj = obj.view(MaskedArray)
         obj._baseclass = ndarray
         obj._isfield = True
         obj._mask = _mask
         # Reset the field values
         _fill_value = _localdict.get('_fill_value', None)
         if _fill_value is not None:
             try:
                 obj._fill_value = _fill_value[attr]
             except ValueError:
                 obj._fill_value = None
     else:
         obj = obj.item()
     return obj
Beispiel #12
0
 def test_subtype_view(self):
     from numpy import ndarray, array
     class matrix(ndarray):
         def __new__(subtype, data, dtype=None, copy=True):
             if isinstance(data, matrix):
                 return data
             return data.view(subtype)
     a = array(range(5))
     b = matrix(a)
     assert isinstance(b, matrix)
     assert b.__array_priority__ == 0.0
     assert (b == a).all()
     assert isinstance(b.view(), matrix) 
     a = array(5)[()]
     for s in [matrix, ndarray]:
         b = a.view(s)
         assert b == a
         assert type(b) is type(a)
     a = matrix(array(range(5)))
     for s in [matrix, ndarray]:
         b = ndarray.view(a, s)
         assert (b == a).all()
         assert type(b) is s
Beispiel #13
0
 def __getattribute__(self, attr):
     try:
         return object.__getattribute__(self, attr)
     except AttributeError:  # attr must be a fieldname
         pass
     fielddict = ndarray.__getattribute__(self, 'dtype').fields
     try:
         res = fielddict[attr][:2]
     except (TypeError, KeyError):
         raise AttributeError, "record array has no attribute %s" % attr
     # So far, so good...
     _localdict = ndarray.__getattribute__(self, '__dict__')
     _data = ndarray.view(self, _localdict['_baseclass'])
     obj = _data.getfield(*res)
     if obj.dtype.fields:
         raise NotImplementedError("MaskedRecords is currently limited to"\
                                   "simple records...")
     obj = obj.view(MaskedArray)
     obj._baseclass = ndarray
     obj._isfield = True
     # Get some special attributes
     _fill_value = _localdict.get('_fill_value', None)
     _mask = _localdict.get('_mask', None)
     # Reset the object's mask
     if _mask is not None:
         try:
             obj._mask = _mask[attr]
         except IndexError:
             # Couldn't find a mask: use the default (nomask)
             pass
     # Reset the field values
     if _fill_value is not None:
         try:
             obj._fill_value = _fill_value[attr]
         except ValueError:
             obj._fill_value = None
     return obj
Beispiel #14
0
 def __getattribute__(self, attr):
     try:
         return object.__getattribute__(self, attr)
     except AttributeError:  # attr must be a fieldname
         pass
     fielddict = ndarray.__getattribute__(self, "dtype").fields
     try:
         res = fielddict[attr][:2]
     except (TypeError, KeyError):
         raise AttributeError, "record array has no attribute %s" % attr
     # So far, so good...
     _localdict = ndarray.__getattribute__(self, "__dict__")
     _data = ndarray.view(self, _localdict["_baseclass"])
     obj = _data.getfield(*res)
     if obj.dtype.fields:
         raise NotImplementedError("MaskedRecords is currently limited to" "simple records...")
     obj = obj.view(MaskedArray)
     obj._baseclass = ndarray
     obj._isfield = True
     # Get some special attributes
     _fill_value = _localdict.get("_fill_value", None)
     _mask = _localdict.get("_mask", None)
     # Reset the object's mask
     if _mask is not None:
         try:
             obj._mask = _mask[attr]
         except IndexError:
             # Couldn't find a mask: use the default (nomask)
             pass
     # Reset the field values
     if _fill_value is not None:
         try:
             obj._fill_value = _fill_value[attr]
         except ValueError:
             obj._fill_value = None
     return obj
Beispiel #15
0
    def view(self, dtype=None, type=None):
        """
        Returns a view of the mrecarray.

        """
        # OK, basic copy-paste from MaskedArray.view.
        if dtype is None:
            if type is None:
                output = ndarray.view(self)
            else:
                output = ndarray.view(self, type)
        # Here again.
        elif type is None:
            try:
                if issubclass(dtype, ndarray):
                    output = ndarray.view(self, dtype)
                    dtype = None
                else:
                    output = ndarray.view(self, dtype)
            # OK, there's the change
            except TypeError:
                dtype = np.dtype(dtype)
                # we need to revert to MaskedArray, but keeping the possibility
                # of subclasses (eg, TimeSeriesRecords), so we'll force a type
                # set to the first parent
                if dtype.fields is None:
                    basetype = self.__class__.__bases__[0]
                    output = self.__array__().view(dtype, basetype)
                    output._update_from(self)
                else:
                    output = ndarray.view(self, dtype)
                output._fill_value = None
        else:
            output = ndarray.view(self, dtype, type)
        # Update the mask, just like in MaskedArray.view
        if (getattr(output, '_mask', nomask) is not nomask):
            mdtype = ma.make_mask_descr(output.dtype)
            output._mask = self._mask.view(mdtype, ndarray)
            output._mask.shape = output.shape
        return output
Beispiel #16
0
    def view(self, dtype=None, type=None):
        """
        Returns a view of the mrecarray.

        """
        # OK, basic copy-paste from MaskedArray.view.
        if dtype is None:
            if type is None:
                output = ndarray.view(self)
            else:
                output = ndarray.view(self, type)
        # Here again.
        elif type is None:
            try:
                if issubclass(dtype, ndarray):
                    output = ndarray.view(self, dtype)
                    dtype = None
                else:
                    output = ndarray.view(self, dtype)
            # OK, there's the change
            except TypeError:
                dtype = np.dtype(dtype)
                # we need to revert to MaskedArray, but keeping the possibility
                # of subclasses (eg, TimeSeriesRecords), so we'll force a type
                # set to the first parent
                if dtype.fields is None:
                    basetype = self.__class__.__bases__[0]
                    output = self.__array__().view(dtype, basetype)
                    output._update_from(self)
                else:
                    output = ndarray.view(self, dtype)
                output._fill_value = None
        else:
            output = ndarray.view(self, dtype, type)
        # Update the mask, just like in MaskedArray.view
        if (getattr(output, '_mask', nomask) is not nomask):
            mdtype = ma.make_mask_descr(output.dtype)
            output._mask = self._mask.view(mdtype, ndarray)
            output._mask.shape = output.shape
        return output
Beispiel #17
0
 def _getdata(self):
     "Returns the data as a recarray."
     return ndarray.view(self, recarray)
Beispiel #18
0
    def _data(self):
        """
        Returns the data as a recarray.

        """
        return ndarray.view(self, recarray)
Beispiel #19
0
 def _getdata(self):
     "Returns the data as a recarray."
     return ndarray.view(self, recarray)
Beispiel #20
0
    def _data(self):
        """
        Returns the data as a recarray.

        """
        return ndarray.view(self, recarray)