Skip to content

Dimension slicing utility #68

@pp-mo

Description

@pp-mo

Found myself writing this just to use it.
So a "simple" approach is pretty simple ...
(see below)

But a "nice" approach is also rather fine :
see #120 which supports "choose your dims, apply a slice"

"Nice" examples:

data = Slicer(ncdata, 'time')[:10]
data = Slicer(ncdata, 'level')[[1, 2, 5]]
data = Slicer(ncdata, 'level', 'time', 'x', 'y')[1, :3, 2:10:3, ::-1]

simple code:

slicedim_name = "time"
slicedim_len = 2
ncds.dimensions[slicedim_name].size = slicedim_len
for var in ncds.variables.values():
    if slicedim_name in var.dimensions:
        (i_slicedim,) = [
            i for i, name in enumerate(var.dimensions)
            if name == slicedim_name
        ]
        slices = [slice(None) for dim in var.dimensions]
        slices[i_slicedim] = slice(0, slicedim_len)
        var.data = var.data[tuple(slices)]

Probably wants to be slightly generalised.
Maybe control with a map dim_name: dim_slice
Then new dim length can be deduced for any-old input slice something like
dim.size = da.zeros(dim.size)[dim_slice].shape[0]
(using dask to avoid actually making an array)

N.B. goes in a 'utilities' space : cf #64

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions