Skip to content

Commit d84f4de

Browse files
committed
slice sparse matrices in dicts in in .uns
1 parent 2ca754b commit d84f4de

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

anndata/base.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -555,17 +555,19 @@ class AnnData(IndexMixin):
555555
-----
556556
Multi-dimensional annotations are stored in ``.obsm`` and ``.varm``.
557557
558+
If the unstructured annotations `.uns` contain a sparse matrix of shape
559+
`.n_obs` × `.n_obs`, these are also sliced.
560+
558561
:class:`~anndata.AnnData` stores observations (samples) of variables
559562
(features) in the rows of a matrix. This is the convention of the modern
560-
classics of stats [Hastie09]_ and Machine Learning [Murphy12]_, the convention of
561-
dataframes both in R and Python and the established stats and machine
562-
learning packages in Python (`statsmodels
563+
classics of statistics [Hastie09]_ and machine learning [Murphy12]_, the
564+
convention of dataframes both in R and Python and the established statistics
565+
and machine learning packages in Python (`statsmodels
563566
<http://www.statsmodels.org/stable/index.html>`_, `scikit-learn
564-
<http://scikit-learn.org/>`_). It is the opposite of the convention for
565-
storing genomic data.
567+
<http://scikit-learn.org/>`_).
566568
567569
A data matrix is flattened if either #observations (`n_obs`) or #variables
568-
(`n_vars`) is 1, so that Numpy's slicing behavior is reproduced::
570+
(`n_vars`) is 1, so that numpy's slicing behavior is reproduced::
569571
570572
adata = AnnData(np.ones((2, 2)))
571573
adata[:, 0].X == adata.X[:, 0]
@@ -1126,12 +1128,12 @@ def __delitem__(self, index):
11261128
def __getitem__(self, index):
11271129
"""Returns a sliced view of the object."""
11281130
return self._getitem_view(index)
1129-
# return self._getitem_copy(index)
11301131

11311132
def _getitem_view(self, index):
11321133
oidx, vidx = self._normalize_indices(index)
11331134
return AnnData(self, oidx=oidx, vidx=vidx, asview=True)
11341135

1136+
# this is no longer needed but remains here for reference for now
11351137
def _getitem_copy(self, index):
11361138
oidx, vidx = self._normalize_indices(index)
11371139
if isinstance(oidx, (int, np.int64)): oidx = slice(oidx, oidx+1, 1)
@@ -1187,6 +1189,9 @@ def _slice_uns_sparse_matrices_inplace(self, uns, oidx):
11871189
if not (isinstance(oidx, slice) and
11881190
oidx.start is None and oidx.step is None and oidx.stop is None):
11891191
for k, v in uns.items():
1192+
# treat nested dicts
1193+
if isinstance(v, Mapping):
1194+
self._slice_uns_sparse_matrices_inplace(v, oidx)
11901195
if isinstance(v, sparse.spmatrix) and v.shape == (
11911196
self.n_obs, self.n_obs):
11921197
uns[k] = v.tocsc()[:, oidx].tocsr()[oidx, :]

0 commit comments

Comments
 (0)