How to use the xarray.core.pycompat.OrderedDict function in xarray

To help you get started, we’ve selected a few xarray examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pydata / xarray / xarray / core / dataset.py View on Github external
def attrs(self, value):
        self._attrs = OrderedDict(value)
github pydata / xarray / xarray / core / dataset.py View on Github external
"variable or dimension in this dataset" % k)

        variables = OrderedDict()
        coord_names = set()
        for k, v in iteritems(self._variables):
            name = name_dict.get(k, k)
            dims = tuple(name_dict.get(dim, dim) for dim in v.dims)
            var = v.copy(deep=False)
            var.dims = dims
            if name in variables:
                raise ValueError('the new name %r conflicts' % (name,))
            variables[name] = var
            if k in self._coord_names:
                coord_names.add(name)

        dims = OrderedDict((name_dict.get(k, k), v)
                           for k, v in self.dims.items())

        return self._replace_vars_and_dims(variables, coord_names, dims=dims,
                                           inplace=inplace)
github pydata / xarray / xarray / core / dataset.py View on Github external
''.format(n))

        # prepare slices
        kwargs_start = {dim: slice(None, -1)}
        kwargs_end = {dim: slice(1, None)}

        # prepare new coordinate
        if label == 'upper':
            kwargs_new = kwargs_end
        elif label == 'lower':
            kwargs_new = kwargs_start
        else:
            raise ValueError('The \'label\' argument has to be either '
                             '\'upper\' or \'lower\'')

        variables = OrderedDict()

        for name, var in iteritems(self.variables):
            if dim in var.dims:
                if name in self.data_vars:
                    variables[name] = (var.isel(**kwargs_end) -
                                       var.isel(**kwargs_start))
                else:
                    variables[name] = var.isel(**kwargs_new)
            else:
                variables[name] = var

        difference = self._replace_vars_and_dims(variables)

        if n > 1:
            return difference.diff(dim, n - 1)
        else:
github pydata / xarray / xarray / core / dataset.py View on Github external
Returns
        -------
        renamed : Dataset
            Dataset with renamed variables and dimensions.

        See Also
        --------
        Dataset.swap_dims
        DataArray.rename
        """
        for k, v in name_dict.items():
            if k not in self and k not in self.dims:
                raise ValueError("cannot rename %r because it is not a "
                                 "variable or dimension in this dataset" % k)

        variables = OrderedDict()
        coord_names = set()
        for k, v in iteritems(self._variables):
            name = name_dict.get(k, k)
            dims = tuple(name_dict.get(dim, dim) for dim in v.dims)
            var = v.copy(deep=False)
            var.dims = dims
            if name in variables:
                raise ValueError('the new name %r conflicts' % (name,))
            variables[name] = var
            if k in self._coord_names:
                coord_names.add(name)

        dims = OrderedDict((name_dict.get(k, k), v)
                           for k, v in self.dims.items())

        return self._replace_vars_and_dims(variables, coord_names, dims=dims,
github pydata / xarray / xarray / core / dataset.py View on Github external
if len(dim) != len(axis):
            raise ValueError('lengths of dim and axis should be identical.')
        for d in dim:
            if d in self.dims:
                raise ValueError(
                    'Dimension {dim} already exists.'.format(dim=d))
            if (d in self._variables and
                    not utils.is_scalar(self._variables[d])):
                raise ValueError(
                    '{dim} already exists as coordinate or'
                    ' variable name.'.format(dim=d))

        if len(dim) != len(set(dim)):
            raise ValueError('dims should not contain duplicate values.')

        variables = OrderedDict()
        for k, v in iteritems(self._variables):
            if k not in dim:
                if k in self._coord_names:  # Do not change coordinates
                    variables[k] = v
                else:
                    result_ndim = len(v.dims) + len(axis)
                    for a in axis:
                        if a < -result_ndim or result_ndim - 1 < a:
                            raise IndexError(
                                'Axis {a} is out of bounds of the expanded'
                                ' dimension size {dim}.'.format(
                                    a=a, v=k, dim=result_ndim))

                    axis_pos = [a if a >= 0 else result_ndim + a
                                for a in axis]
                    if len(axis_pos) != len(set(axis_pos)):
github pydata / xarray / xarray / core / dataset.py View on Github external
Dataset.rename
        DataArray.swap_dims
        """
        for k, v in dims_dict.items():
            if k not in self.dims:
                raise ValueError('cannot swap from dimension %r because it is '
                                 'not an existing dimension' % k)
            if self.variables[v].dims != (k,):
                raise ValueError('replacement dimension %r is not a 1D '
                                 'variable along the old dimension %r'
                                 % (v, k))

        result_dims = set(dims_dict.get(dim, dim) for dim in self.dims)

        variables = OrderedDict()

        coord_names = self._coord_names.copy()
        coord_names.update(dims_dict.values())

        for k, v in iteritems(self.variables):
            dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
            if k in result_dims:
                var = v.to_index_variable()
            else:
                var = v.to_base_variable()
            var.dims = dims
            variables[k] = var

        return self._replace_vars_and_dims(variables, coord_names,
                                           inplace=inplace)
github xgcm / xgcm / xgcm / models / mitgcm / mds_store.py View on Github external
def _make_layers_variables(layer_name):
    """Translate metadata template to actual variable metadata."""
    from .variables import layers_grid_variables
    lvars = xr.core.pycompat.OrderedDict()
    layer_num = layer_name[0]
    # should always be int
    assert isinstance(int(layer_num), int)
    layer_id = 'l' + layer_num
    for key, vals in layers_grid_variables.items():
        # replace the name template with the actual name
        # e.g. layer_NAME_bounds -> layer_1RHO_bounds
        varname = key.replace('NAME', layer_name)
        metadata = _recursively_replace(vals, 'NAME', layer_name)
        # now fix dimension
        metadata['dims'] = [metadata['dims'][0].replace('l', layer_id)]
        lvars[varname] = metadata
    return lvars
github pydata / xarray / xarray / core / dataset.py View on Github external
A new Dataset with the same contents as this dataset, except each
            array and dimension is indexed by the appropriate indexers.
            If indexer DataArrays have coordinates that do not conflict with
            this object, then these coordinates will be attached.
            In general, each array's data will be a view of the array's data
            in this dataset, unless vectorized indexing was triggered by using
            an array indexer, in which case the data will be a copy.

        See Also
        --------
        Dataset.sel
        DataArray.isel
        """
        indexers_list = self._validate_indexers(indexers)

        variables = OrderedDict()
        for name, var in iteritems(self._variables):
            var_indexers = {k: v for k, v in indexers_list if k in var.dims}
            new_var = var.isel(**var_indexers)
            if not (drop and name in var_indexers):
                variables[name] = new_var

        coord_names = set(variables).intersection(self._coord_names)
        selected = self._replace_vars_and_dims(variables,
                                               coord_names=coord_names)

        # Extract coordinates from indexers
        coord_vars = selected._get_indexers_coordinates(indexers)
        variables.update(coord_vars)
        coord_names = (set(variables)
                       .intersection(self._coord_names)
                       .union(coord_vars))
github xgcm / xgcm / xgcm / models / mitgcm / variables.py View on Github external
units="m", positive="down"),
            filename="RF", slice=(slice(None),0,0)),
    Zu= dict(dims=["k_u"], attrs=dict(
                standard_name="depth_at_lower_w_location",
                long_name="vertical coordinate of lower cell interface",
                units="m", positive="down"),
            filename="RF", slice=(slice(1,None),0,0)),
    Zl= dict(dims=["k_l"], attrs=dict(
                standard_name="depth_at_upper_w_location",
                long_name="vertical coordinate of upper cell interface",
                units="m", positive="down"),
            filename="RF", slice=(slice(None,-1),0,0))
)

# I got these variable names from the default MITgcm netcdf output
horizontal_grid_variables = OrderedDict(
    # tracer cell
    rA  = dict(dims=["j", "i"], attrs=dict(standard_name="cell_area",
                long_name="cell area", units="m2", coordinate="YC XC"),
               filename='RAC'),
    dxG = dict(dims=["j_g", "i"], attrs=dict(
                standard_name="cell_x_size_at_v_location",
                long_name="cell x size", units="m", coordinate="YG XC"),
               filename='DXG'),
    dyG = dict(dims=["j", "i_g"], attrs=dict(
                standard_name="cell_y_size_at_u_location",
                long_name="cell y size", units="m", coordinate="YC XG"),
               filename='DYG'),
    Depth=dict(dims=["j", "i"], attrs=dict( standard_name="ocean_depth",
                long_name="ocean depth", units="m", coordinate="XC YC")),
    # vorticity cell
    rAz  = dict(dims=["j_g", "i_g"], attrs=dict(
github xgcm / xgcm / xgcm / models / mitgcm / mds_store.py View on Github external
def _concat_dicts(list_of_dicts):
    result = xr.core.pycompat.OrderedDict()
    for eachdict in list_of_dicts:
        for k, v in eachdict.items():
            result[k] = v
    return result