Esempio n. 1
0
def test_sanitize_slice(item, ndim, expected):
    new_item = sanitize_slices(item, ndim)
    # FIXME: do we still need the first two since the third assert
    # should cover it all?
    assert len(new_item) == ndim
    assert all(isinstance(i, (slice, int)) for i in new_item)
    assert new_item == expected
Esempio n. 2
0
    def __getitem__(self, item):
        # override the error for consistency
        try:
            sane_item = sanitize_slices(item, self.n_inputs)
        except ValueError as ex:
            raise ValueError("Can not slice with incorrect length") from ex

        if not self.mesh:
            return type(self)(self.table[item],
                              mesh=False,
                              names=self.names,
                              physical_types=self.physical_types)
        else:
            self._slice = [
                self.combine_slices(a, b)
                for a, b in zip(sane_item, self._slice)
            ]
            if all([isinstance(s, Integral) for s in self._slice]):
                # Here we rebuild the SkyCoord with the slice applied to the individual components.
                new_sc = SkyCoord(
                    self.table.realize_frame(
                        type(self.table.data)(*self._sliced_components)))
                return type(self)(new_sc,
                                  mesh=False,
                                  names=self.names,
                                  physical_types=self.physical_types)
            return self
Esempio n. 3
0
    def _slice(self, item):
        """Construct a set of keyword arguments to initialise a new (sliced)
        instance of the class. This method is called in
        `astropy.nddata.mixins.NDSlicingMixin.__getitem__`.

        This method extends the `~astropy.nddata.mixins.NDSlicingMixin` method
        to add support for  ``extra_coords`` and overwrites the astropy
        handling of wcs slicing.

        Parameters
        ----------
        item : slice
            The slice passed to ``__getitem__``. Note that the item parameter corresponds
            to numpy ordering, keeping with the convention for NDCube.

        Returns
        -------
        dict :
            Containing all the attributes after slicing - ready to
            use them to create ``self.__class__.__init__(**kwargs)`` in
            ``__getitem__``.
        """

        item = tuple(sanitize_slices(item, len(self.dimensions)))
        kwargs = super()._slice(item)

        # Store the original dimension of NDCube object before slicing
        len(self.dimensions)

        kwargs['extra_coords'] = self.extra_coords[item]

        return kwargs
Esempio n. 4
0
    def __getitem__(self, item):
        """
        Apply a given slice to all the lookup tables stored in this object.

        If no lookup tables remain after slicing `None` is returned.
        """
        item = sanitize_slices(item, self.model.n_inputs)

        ind = 0
        new_dmodels = []
        new_frames = []
        for dmodel, frame in zip(self.delayed_models, self.frames):
            # We have to instantiate the actual model to know how many inputs
            # it has, as the lookup table to model conversion is an arbitrary
            # function.
            model = dmodel()
            n_axes = model.n_inputs

            # Extract the parts of the slice that correspond to this model
            sub_items = tuple(item[i] for i in range(ind, ind + n_axes))
            ind += n_axes

            # If all the slice elements are ints then we are dropping this model
            if not all(isinstance(it, Integral) for it in sub_items):
                new_dmodels.append(dmodel[sub_items])
                new_frames.append(frame)

        if not new_dmodels:
            return

        # Return a new instance with the smaller tables
        new_lutc = type(self)()
        new_lutc.delayed_models = new_dmodels
        new_lutc.frames = new_frames
        return new_lutc
Esempio n. 5
0
def create_sliced_wcs(wcs, item, dim):
    """
    Creates a sliced `SlicedFITSWCS` object from the given slice item
    """

    # Sanitize the slices
    item = sanitize_slices(item, dim)
    return SlicedFITSWCS(wcs, item)
Esempio n. 6
0
 def _array_slice_to_reference_slice(self, aslice):
     """
     Convert a slice for the reconstructed array to a slice for the reference_array.
     """
     shape = self.shape
     aslice = list(sanitize_slices(aslice, len(self.output_shape)))
     if shape[0] == 1:
         # Insert a blank slice for the removed dimension
         aslice.insert(len(shape) - 1, slice(None))
     aslice = aslice[len(shape):]
     return tuple(aslice)
Esempio n. 7
0
    def __getitem__(self, item):
        """
        Override the parent class method to explicitly catch `None` indices.

        This method calls ``_slice`` and then constructs a new object
        using the kwargs returned by ``_slice``.
        """
        if item is None or (isinstance(item, tuple) and None in item):
            raise IndexError("None indices not supported")

        item = tuple(sanitize_slices(item, len(self.dimensions)))
        sliced_cube = super().__getitem__(item)

        sliced_cube._global_coords._internal_coords = self.global_coords._internal_coords
        sliced_cube._extra_coords = self.extra_coords[item]

        return sliced_cube
Esempio n. 8
0
    def _getitem_wcs(self, item):
        item = sanitize_slices(item, self.wcs.pixel_n_dim)

        # It's valid to slice down the EC such that there is nothing left,
        # which is not a valid way to slice the WCS
        if len(item) == self.wcs.pixel_n_dim and all(
                isinstance(i, Integral) for i in item):
            return type(self)()

        subwcs = self.wcs[item]

        new_mapping = [
            self.mapping[i] for i, subitem in enumerate(item)
            if not isinstance(subitem, Integral)
        ]

        return type(self)(wcs=subwcs, mapping=new_mapping)
Esempio n. 9
0
    def __init__(self, *tables, mesh=False, names=None, physical_types=None):
        if not len(tables) == 1 and isinstance(tables[0], SkyCoord):
            raise ValueError(
                "SkyCoordLookupTable can only be constructed from a single SkyCoord object"
            )

        if isinstance(names, str):
            names = [names]
        if names is not None and len(names) != 2:
            raise ValueError(
                "The number of names must equal two for a SkyCoord table.")
        if physical_types is not None and len(physical_types) != 2:
            raise ValueError(
                "The number of physical types must equal two for a SkyCoord table."
            )

        sc = tables[0]

        super().__init__(sc,
                         mesh=mesh,
                         names=names,
                         physical_types=physical_types)
        self.table = self.table[0]
        self._slice = sanitize_slices(np.s_[...], self.n_inputs)
Esempio n. 10
0
 def __getitem__(self, item):
     item = sanitize_slices(item, self._reference_array.ndim)
     return SlicedFileManagerProxy(self, item)