Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Add slice_by_idx methods to gammapy.maps #1443
This PR adds
@adonath - Here's what I think:
Suggest to only do this later, in a follow-up PR, maybe. Slicing by coord requires rounding and is thus an extra can of worms because probably we need to offer options like "nearest", "inclusive", "left".
For now, I think we should leave it to the user to go to
I think adding
I think instead we should support both int index and slice range in
Now the question is how to support this in the API and implementation. For coord and index @woodmd started with tuples, following the example of Numpy, and then we added dict and MapCoord for named axes support similar to http://xarray.pydata.org/ and having something like a WCS on the extra axes. That's visible in the examples here:
How about we try to do the same and add a
class MapSlice: def __init__(self, slice): self.slice = slice @classmethod def from_any(cls, slice): # only support dict for now, # maybe add tuple or MapCoord or spatial axes support later return cls(slice) def to_data(self): slice = [...] # ignore spatial axes (not sure if ellipses is the way to do it) return (..., *self.slice.values()) class Map: def slice_by_idx(self, slices): map_slice = MapSlice.from_any(slices) geom = self.geom.slice_by_idx(map_slice.to_geom()) data = self.data[map_slice.to_data()]
Given that both
There's a line missing that sorts slices to match the axis order. That could be done e.g. by passing
This would allow the following ways to slice, which is how I like to do it (very explicit and by name):
I think this might be a simple and extensible way to do it?
Maybe add both? Having an explicit list of
Suggest to move that discussion to a separate PR or issue, or continue it in the existing #513 though.
Another comment: can you please add a few more explicit tests, e.g. of a 4D map with
One thing to assert on is the output shape when slicing, but also checking that the sliced map data is a view would be important, so that we don't accidentally make copies. I've never done this, but looking at https://stackoverflow.com/a/11524746/498873 I think this might do it:
If you don't think a
My main suggestion is to support this:
and to drop the
@adonath - I think you added a new "Indexing and Slicing" section in the docs, but there was already an empty one further down on that docs page:
You could give one example in the docs where you show how to compute an
indx from a given
energy coord. It's pretty common that people will want to do that, and it's possible now with ~ 2 lines of computing the idx first.
@cdeil Thanks for your comments! For now I decided against the
I'll go ahead an merge, the failing test is unrelated.