Ejemplo n.º 1
0
    def read(self, indices=None, axis=0, indexing=None, tol=None, keepdims=False):
        """ Read values from disk

        Parameters
        ----------
        indices : int or list or slice (single-dimensional indices)
                   or a tuple of those (multi-dimensional)
                   or `dict` of { axis name : axis values }
        axis : None or int or str, optional
            if specified and indices is a slice, scalar or an array, assumes 
            indexing is along this axis.
        indexing : {'label', 'position'}, optional
            Indexing mode. 
            - "label": indexing on axis labels (default)
            - "position": use numpy-like position index
            Default value can be changed in dimarray.rcParams['indexing.by']
        tol : float, optional
            tolerance when looking for numerical values, e.g. to use nearest 
            neighbor search, default `None`.
        keepdims : bool, optional 
            keep singleton dimensions (default False)

        Returns
        -------
        DimArray instance or scalar

        See Also
        --------
        DimArray.take, DatasetOnDisk.read, DimArrayOnDisk.write
        """
        if type(indices) is slice and indices == slice(None) and self.ndim == 0:
            indices = ()
        return AbstractDimArray._getitem(self, indices=indices, axis=axis, 
                                         indexing=indexing, tol=tol, keepdims=keepdims)
Ejemplo n.º 2
0
    def write(self, indices, values, axis=0, indexing=None, tol=None):
        """ Write numpy array or DimArray to netCDF file (The 
        variable must have been created previously)

        Parameters
        ----------
        indices : int or list or slice (single-dimensional indices)
                   or a tuple of those (multi-dimensional)
                   or `dict` of { axis name : axis values }
        values : np.ndarray or DimArray
        axis : None or int or str, optional
            if specified and indices is a slice, scalar or an array, assumes 
            indexing is along this axis.
        indexing : {'label', 'position'}, optional
            Indexing mode. 
            - "label": indexing on axis labels (default)
            - "position": use numpy-like position index
            Default value can be changed in dimarray.rcParams['indexing.by']
        tol : float, optional
            tolerance when looking for numerical values, e.g. to use nearest 
            neighbor search, default `None`.

        See Also
        --------
        DimArray.put, DatasetOnDisk.write, DimArrayOnDisk.read
        """
        # just create the variable and dimensions
        ds = self._ds
        dima = values # internal convention: values is a numpy array
        values, nctype, cf_attrs = maybe_encode_values(values, format=self._ds.file_format)

        assert self._name in ds.variables.keys(), "variable does not exist, should have been created earlier!"

        # add attributes
        if hasattr(dima,'attrs'):
            self.attrs.update(dima.attrs)
            self.attrs.update(cf_attrs) # calendar?

        # special case: index == slice(None) and self.ndim == 0
        # This would fail with numpy, but not with netCDF4
        if type(indices) is slice and indices == slice(None) and self.ndim == 0:
            indices = ()

        indices = self._get_indices(indices,axis=axis, indexing=indexing, tol=tol)

        # Perform additional checks on axes if the Data to assign is a DimArray
        if isinstance(dima, DimArray):
            for i, ax in enumerate(self.axes):
                idx = indices[i]
                axis = dima.axes[ax.name]
                # write unlimited dimensions
                if self._ds.dimensions[ax.name].isunlimited():
                    self.axes[ax.name][idx] = axis
                else:
                    # dimension variable already written, simple check
                    ondisk = self.axes[ax.name][idx if not (np.isscalar(idx) or np.ndim(idx)==0)  else [idx]].values
                    inmemory = axis.values
                    # inmemory, _ = maybe_encode_values(axis.values)
                    if not np.all(ondisk == inmemory):
                        # assert np.all(ondisk == inmemory)
                        warnings.warn("axes values differ in the netCDF file, try using a numpy array instead, or re-index\
                                      the dimarray prior to assigning to netCDF", RuntimeWarning)

        # do all the indexing and assignment via IndexedArray class
        # ==> it will set the values via _setvalues_ortho below
        # super(DimArrayOnDisk)._setitem(self, indices, values, **kwargs)
        AbstractDimArray._setitem(self, indices, values, indexing='position')