Exemplo n.º 1
0
    def from_dict(cls, dict_, keys=None, axis=None):
        """ Initialize a DimArray for a dictionary of DimArrays

        keys, optional: re-order the keys 
        axis, optional: give a name to the keys axis
        """
        assert isinstance(dict_, dict)
        from dimarray.dataset import Dataset
        if keys is None: keys = dict_.keys()
        data = Dataset(dict_)
        return data.to_array(axis=axis, keys=keys, _constructor=cls._constructor)
Exemplo n.º 2
0
    def from_dict(cls, dict_, keys=None, axis=None):
        """ Initialize a DimArray for a dictionary of DimArrays

        keys, optional: re-order the keys 
        axis, optional: give a name to the keys axis
        """
        assert isinstance(dict_, dict)
        from dimarray.dataset import Dataset
        if keys is None: keys = dict_.keys()
        data = Dataset(dict_)
        return data.to_array(axis=axis,
                             keys=keys,
                             _constructor=cls._constructor)
Exemplo n.º 3
0
def read_dataset(f, nms=None, **kwargs):
    """ read several (or all) names from a netCDF file

    nms : list of variables to read (default None for all variables)
    **kwargs: keyword arguments passed to io.nc.read_variable 
    """
    kw = _extract_kw(kwargs, ('verbose', ))
    f, close = check_file(f, 'r', **kw)

    # automatically read all variables to load (except for the dimensions)
    if nms is None:
        nms, dims = scan(f)


#    if nms is str:
#        nms = [nms]

    data = dict()
    for nm in nms:
        data[nm] = read_variable(f, nm, **kwargs)

    data = Dataset(**data)

    # get dataset's metadata
    for k in f.ncattrs():
        setattr(data, k, f.getncattr(k))

    if close: f.close()

    return data
Exemplo n.º 4
0
 def to_dataset(self, axis=0):
     """ split a DimArray into a Dataset object (collection of DimArrays)
     """
     from dimarray.dataset import Dataset
     # iterate over elements of one axis
     #data = [val for k, val in self.iter(axis)]
     # Dataset(data, keys=self.axes[axis].values)
     ds = Dataset()
     for k, val in self.iter(axis):
         if not isinstance(val, DimArray):  # scalar case
             val = DimArray(val)
         ds[k] = val
     return ds
Exemplo n.º 5
0
    def read(self, names=None, indices=None, axis=0, indexing=None, tol=None, keepdims=False,
             verbose=False, # back-compatibility
             ):
        """ Read values from disk

        Parameters
        ----------
        names : list of variables to read, optional
        indices : int or list or slice (single-dimensional indices)
                   or a tuple of those (multi-dimensional)
                   or `dict` of { axis name : axis indices }
            Indices refer to Dataset axes. Any item that does not possess
            one of the dimensions will not be indexed along that dimension.
            For example, scalar items will be left unchanged whatever indices
            are provided.
        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
        -------
        Dataset

        See Also
        --------
        open_nc : examples of use
        DimArrayOnDisk.read, DatasetOnDisk.write, DimArray.take
        """
        if verbose:
            # print "Read ",self.filename
            pass
        # automatically read all variables to load (except for the dimensions)
        if names is None:
            dims = self.dims
            names = self.keys()
        elif isinstance(names, string_types):
            return self[names].read(indices=indices, axis=axis, indexing=indexing, tol=tol, keepdims=keepdims)
        else:
            dims = []
        # else:
        #     raise TypeError("Expected list or str for 'names=', got {}".format(names))

        tuple_indices = self._get_indices(indices, axis=axis, tol=tol, keepdims=keepdims, indexing=indexing)
        dict_indices = {dim:tuple_indices[i] for i, dim in enumerate(self.dims)}

        data = Dataset()

        # first load dimensions
        for dim in dims:
            data.axes.append(self.axes[dim][dict_indices[dim]])

        # then normal variables
        for nm in names:
            data[nm] = self[nm].read(indices={dim:dict_indices[dim] for dim in self[nm].dims}, indexing='position')
        data.attrs.update(self.attrs) # dataset's metadata

        # reorder the axes in the dataset to match input
        data.axes = Axes(data.axes[dim] for dim in self.dims if dim in data.dims)

        return data