mudata 0.3.1__tar.gz → 0.3.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. {mudata-0.3.1 → mudata-0.3.2}/.pre-commit-config.yaml +1 -1
  2. {mudata-0.3.1 → mudata-0.3.2}/LICENSE +1 -0
  3. {mudata-0.3.1 → mudata-0.3.2}/PKG-INFO +10 -8
  4. {mudata-0.3.1 → mudata-0.3.2}/README.md +5 -4
  5. {mudata-0.3.1 → mudata-0.3.2}/pyproject.toml +3 -2
  6. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/io.py +11 -1
  7. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/mudata.py +138 -35
  8. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_version.py +9 -4
  9. {mudata-0.3.1 → mudata-0.3.2}/tests/test_merge.py +0 -3
  10. mudata-0.3.2/tests/test_view_copy.py +223 -0
  11. mudata-0.3.1/tests/test_view_copy.py +0 -83
  12. {mudata-0.3.1 → mudata-0.3.2}/.codecov.yml +0 -0
  13. {mudata-0.3.1 → mudata-0.3.2}/.editorconfig +0 -0
  14. {mudata-0.3.1 → mudata-0.3.2}/.gitignore +0 -0
  15. {mudata-0.3.1 → mudata-0.3.2}/.readthedocs.yaml +0 -0
  16. {mudata-0.3.1 → mudata-0.3.2}/CITATION.cff +0 -0
  17. {mudata-0.3.1 → mudata-0.3.2}/CONTRIBUTING.md +0 -0
  18. {mudata-0.3.1 → mudata-0.3.2}/DESIGN.md +0 -0
  19. {mudata-0.3.1 → mudata-0.3.2}/MANIFEST.in +0 -0
  20. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/__init__.py +0 -0
  21. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/__init__.py +0 -0
  22. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/compat.py +0 -0
  23. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/config.py +0 -0
  24. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/file_backing.py +0 -0
  25. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/merge.py +0 -0
  26. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/repr.py +0 -0
  27. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/to_.py +0 -0
  28. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/utils.py +0 -0
  29. {mudata-0.3.1 → mudata-0.3.2}/src/mudata/_core/views.py +0 -0
  30. {mudata-0.3.1 → mudata-0.3.2}/tests/__init__.py +0 -0
  31. {mudata-0.3.1 → mudata-0.3.2}/tests/conftest.py +0 -0
  32. {mudata-0.3.1 → mudata-0.3.2}/tests/test_axis_-1.py +0 -0
  33. {mudata-0.3.1 → mudata-0.3.2}/tests/test_io.py +0 -0
  34. {mudata-0.3.1 → mudata-0.3.2}/tests/test_mod_order.py +0 -0
  35. {mudata-0.3.1 → mudata-0.3.2}/tests/test_nullable.py +0 -0
  36. {mudata-0.3.1 → mudata-0.3.2}/tests/test_obs_var.py +0 -0
  37. {mudata-0.3.1 → mudata-0.3.2}/tests/test_pull_push.py +0 -0
  38. {mudata-0.3.1 → mudata-0.3.2}/tests/test_repr.py +0 -0
  39. {mudata-0.3.1 → mudata-0.3.2}/tests/test_to_.py +0 -0
  40. {mudata-0.3.1 → mudata-0.3.2}/tests/test_update.py +0 -0
  41. {mudata-0.3.1 → mudata-0.3.2}/tests/test_update_axis_1.py +0 -0
@@ -1,6 +1,6 @@
1
1
  repos:
2
2
  - repo: https://github.com/psf/black
3
- rev: 20.8b1 # Replace by any tag/version: https://github.com/psf/black/tags
3
+ rev: 24.10.0 # Replace by any tag/version: https://github.com/psf/black/tags
4
4
  hooks:
5
5
  - id: black
6
6
  language_version: python3
@@ -1,6 +1,7 @@
1
1
  BSD 3-Clause License
2
2
 
3
3
  Copyright (c) 2020, Danila Bredikhin
4
+ Copyright (c) 2025, scverse®
4
5
  All rights reserved.
5
6
 
6
7
  Redistribution and use in source and binary forms, with or without
@@ -1,8 +1,8 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: mudata
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: Multimodal data
5
- Project-URL: Documentation, https://muon.readthedocs.io/en/latest/
5
+ Project-URL: Documentation, https://mudata.readthedocs.io/en/latest/
6
6
  Project-URL: Source, https://github.com/scverse/mudata
7
7
  Project-URL: Home-page, https://muon.scverse.org/
8
8
  Author: Danila Bredikhin
@@ -28,7 +28,8 @@ Requires-Dist: sphinx; extra == 'docs'
28
28
  Requires-Dist: sphinx-automodapi; extra == 'docs'
29
29
  Requires-Dist: sphinx-book-theme; extra == 'docs'
30
30
  Provides-Extra: test
31
- Requires-Dist: zarr; extra == 'test'
31
+ Requires-Dist: pytest; extra == 'test'
32
+ Requires-Dist: zarr<3; extra == 'test'
32
33
  Description-Content-Type: text/markdown
33
34
 
34
35
  ![mudata header](./docs/img/mudata.svg)
@@ -133,15 +134,16 @@ You can cite the scverse publication as follows:
133
134
  >
134
135
  > _Nat Biotechnol._ 2023 Apr 10. doi: [10.1038/s41587-023-01733-8](https://doi.org/10.1038/s41587-023-01733-8).
135
136
 
136
- [//]: # "numfocus-fiscal-sponsor-attribution"
137
+ [//]: # (numfocus-fiscal-sponsor-attribution)
137
138
 
138
- `mudata` is part of the scverse project ([website](https://scverse.org), [governance](https://scverse.org/about/roles)) and is fiscally sponsored by [NumFOCUS](https://numfocus.org/).
139
- Please consider making a tax-deductible [donation](https://numfocus.org/donate-to-scverse) to help the project pay for developer time, professional services, travel, workshops, and a variety of other needs.
139
+ mudata is part of the scverse® project ([website](https://scverse.org), [governance](https://scverse.org/about/roles)) and is fiscally sponsored by [NumFOCUS](https://numfocus.org/).
140
+ If you like scverse® and want to support our mission, please consider making a tax-deductible [donation](https://numfocus.org/donate-to-scverse) to help the project pay for developer time, professional services, travel, workshops, and a variety of other needs.
140
141
 
142
+ <div align="center">
141
143
  <a href="https://numfocus.org/project/scverse">
142
144
  <img
143
145
  src="https://raw.githubusercontent.com/numfocus/templates/master/images/numfocus-logo.png"
144
146
  width="200"
145
147
  >
146
148
  </a>
147
-
149
+ </div>
@@ -100,15 +100,16 @@ You can cite the scverse publication as follows:
100
100
  >
101
101
  > _Nat Biotechnol._ 2023 Apr 10. doi: [10.1038/s41587-023-01733-8](https://doi.org/10.1038/s41587-023-01733-8).
102
102
 
103
- [//]: # "numfocus-fiscal-sponsor-attribution"
103
+ [//]: # (numfocus-fiscal-sponsor-attribution)
104
104
 
105
- `mudata` is part of the scverse project ([website](https://scverse.org), [governance](https://scverse.org/about/roles)) and is fiscally sponsored by [NumFOCUS](https://numfocus.org/).
106
- Please consider making a tax-deductible [donation](https://numfocus.org/donate-to-scverse) to help the project pay for developer time, professional services, travel, workshops, and a variety of other needs.
105
+ mudata is part of the scverse® project ([website](https://scverse.org), [governance](https://scverse.org/about/roles)) and is fiscally sponsored by [NumFOCUS](https://numfocus.org/).
106
+ If you like scverse® and want to support our mission, please consider making a tax-deductible [donation](https://numfocus.org/donate-to-scverse) to help the project pay for developer time, professional services, travel, workshops, and a variety of other needs.
107
107
 
108
+ <div align="center">
108
109
  <a href="https://numfocus.org/project/scverse">
109
110
  <img
110
111
  src="https://raw.githubusercontent.com/numfocus/templates/master/images/numfocus-logo.png"
111
112
  width="200"
112
113
  >
113
114
  </a>
114
-
115
+ </div>
@@ -28,7 +28,7 @@ dependencies = [
28
28
  dynamic = ["version"]
29
29
 
30
30
  [project.urls]
31
- Documentation = "https://muon.readthedocs.io/en/latest/"
31
+ Documentation = "https://mudata.readthedocs.io/en/latest/"
32
32
  Source = "https://github.com/scverse/mudata"
33
33
  Home-page = "https://muon.scverse.org/"
34
34
 
@@ -46,7 +46,8 @@ docs = [
46
46
  "recommonmark"
47
47
  ]
48
48
  test = [
49
- "zarr"
49
+ "zarr<3",
50
+ "pytest"
50
51
  ]
51
52
 
52
53
  [tool.pytest.ini_options]
@@ -121,18 +121,28 @@ def write_zarr(
121
121
  Matrices - sparse or dense - are currently stored as they are.
122
122
  """
123
123
  import zarr
124
+ from anndata import settings
124
125
  from anndata._io.specs.registry import write_elem
125
126
  from anndata._io.zarr import write_zarr as anndata_write_zarr
126
127
 
127
128
  from .. import __anndataversion__, __mudataversion__, __version__
128
129
 
130
+ zarr_format = 2
131
+ if hasattr(settings, "zarr_write_format"):
132
+ zarr_format = settings.zarr_write_format
133
+
129
134
  if isinstance(data, AnnData):
130
135
  adata = data
131
136
  anndata_write_zarr(store, adata, chunks=chunks, **kwargs)
132
137
  elif isinstance(data, MuData):
133
138
  if isinstance(store, Path):
134
139
  store = str(store)
135
- file = zarr.open(store, mode="w")
140
+ zarr_format = kwargs.pop("zarr_format", zarr_format)
141
+ try:
142
+ file = zarr.open(store, mode="w", zarr_format=zarr_format)
143
+ except TypeError:
144
+ # zarr_format is not supported in this version of zarr
145
+ file = zarr.open(store, mode="w")
136
146
  mdata = data
137
147
  write_elem(
138
148
  file,
@@ -134,7 +134,7 @@ class MuData:
134
134
 
135
135
  def __init__(
136
136
  self,
137
- data: Union[AnnData, Mapping[str, AnnData], "MuData"] = None,
137
+ data: Union[AnnData, Mapping[str, AnnData], "MuData"] | None = None,
138
138
  feature_types_names: dict | None = {
139
139
  "Gene Expression": "rna",
140
140
  "Peaks": "atac",
@@ -150,6 +150,7 @@ class MuData:
150
150
  data
151
151
  AnnData object or dictionary with AnnData objects as values.
152
152
  If a dictionary is passed, the keys will be used as modality names.
153
+ If None, creates an empty MuData object.
153
154
  feature_types_names
154
155
  Dictionary to map feature types encoded in data.var["feature_types"] to modality names.
155
156
  Only relevant when data is an AnnData object.
@@ -168,7 +169,10 @@ class MuData:
168
169
 
169
170
  # Add all modalities to a MuData object
170
171
  self.mod = ModDict()
171
- if isinstance(data, abc.Mapping):
172
+ if data is None:
173
+ # Initialize an empty MuData object
174
+ pass
175
+ elif isinstance(data, abc.Mapping):
172
176
  for k, v in data.items():
173
177
  self.mod[k] = v
174
178
  elif isinstance(data, AnnData):
@@ -204,16 +208,23 @@ class MuData:
204
208
  if isinstance(self._var, abc.Mapping) or self._var is None:
205
209
  self._var = pd.DataFrame(self._var)
206
210
 
207
- # Get global obsm
208
- self._obsm = MuAxisArrays(self, axis=0, store=kwargs.get("obsm", {}))
209
- # Get global varm
210
- self._varm = MuAxisArrays(self, axis=1, store=kwargs.get("varm", {}))
211
+ # Ensure no keys are missing
212
+ for key in ("obsm", "varm", "obsp", "varp", "obsmap", "varmap"):
213
+ kwargs[key] = kwargs.get(key) or {}
211
214
 
212
- self._obsp = PairwiseArrays(self, axis=0, store=kwargs.get("obsp", {}))
213
- self._varp = PairwiseArrays(self, axis=1, store=kwargs.get("varp", {}))
215
+ # Map each attribute to its class and axis value
216
+ attr_to_axis_arrays = {
217
+ "obsm": (MuAxisArrays, 0),
218
+ "varm": (MuAxisArrays, 1),
219
+ "obsp": (PairwiseArrays, 0),
220
+ "varp": (PairwiseArrays, 1),
221
+ "obsmap": (MuAxisArrays, 0),
222
+ "varmap": (MuAxisArrays, 1),
223
+ }
214
224
 
215
- self._obsmap = MuAxisArrays(self, axis=0, store=kwargs.get("obsmap", {}))
216
- self._varmap = MuAxisArrays(self, axis=1, store=kwargs.get("varmap", {}))
225
+ # Initialise each attribute
226
+ for attr, (cls, axis) in attr_to_axis_arrays.items():
227
+ setattr(self, f"_{attr}", cls(self, axis=axis, store=kwargs[attr]))
217
228
 
218
229
  self._axis = kwargs.get("axis") or 0
219
230
 
@@ -224,10 +235,10 @@ class MuData:
224
235
 
225
236
  return
226
237
 
227
- # Initialise global observations
238
+ # Initialize global observations
228
239
  self._obs = pd.DataFrame()
229
240
 
230
- # Initialise global variables
241
+ # Initialize global variables
231
242
  self._var = pd.DataFrame()
232
243
 
233
244
  # Make obs map for each modality
@@ -242,6 +253,7 @@ class MuData:
242
253
 
243
254
  self._axis = 0
244
255
 
256
+ # Only call update() if there are modalities
245
257
  self.update()
246
258
 
247
259
  def _init_common(self):
@@ -261,6 +273,7 @@ class MuData:
261
273
 
262
274
  def _init_as_view(self, mudata_ref: "MuData", index):
263
275
  from anndata._core.index import _normalize_indices
276
+ from anndata._core.views import _resolve_idxs
264
277
 
265
278
  obsidx, varidx = _normalize_indices(index, mudata_ref.obs.index, mudata_ref.var.index)
266
279
 
@@ -300,29 +313,39 @@ class MuData:
300
313
  cvaridx = slice(None)
301
314
  if a.is_view:
302
315
  if isinstance(a, MuData):
303
- self.mod[m] = a._mudata_ref[cobsidx, cvaridx]
316
+ self.mod[m] = a._mudata_ref[
317
+ _resolve_idxs((a._oidx, a._vidx), (cobsidx, cvaridx), a._mudata_ref)
318
+ ]
304
319
  else:
305
- self.mod[m] = a._adata_ref[cobsidx, cvaridx]
320
+ self.mod[m] = a._adata_ref[
321
+ _resolve_idxs((a._oidx, a._vidx), (cobsidx, cvaridx), a._adata_ref)
322
+ ]
306
323
  else:
307
324
  self.mod[m] = a[cobsidx, cvaridx]
308
325
 
309
326
  self._obs = DataFrameView(mudata_ref.obs.iloc[obsidx, :], view_args=(self, "obs"))
310
327
  self._obsm = mudata_ref.obsm._view(self, (obsidx,))
311
- self._obsp = mudata_ref.obsp._view(self, obsidx)
328
+ self._obsp = mudata_ref.obsp._view(self, (obsidx, obsidx))
312
329
  self._var = DataFrameView(mudata_ref.var.iloc[varidx, :], view_args=(self, "var"))
313
330
  self._varm = mudata_ref.varm._view(self, (varidx,))
314
- self._varp = mudata_ref.varp._view(self, varidx)
331
+ self._varp = mudata_ref.varp._view(self, (varidx, varidx))
315
332
 
316
333
  for attr, idx in (("obs", obsidx), ("var", varidx)):
317
334
  posmap = {}
335
+ size = getattr(self, attr).shape[0]
318
336
  for mod, mapping in getattr(mudata_ref, attr + "map").items():
319
- posmap[mod] = mapping[idx].copy()
337
+ cposmap = np.zeros((size,), dtype=mapping.dtype)
338
+ cidx = (mapping[idx] > 0).ravel()
339
+ cposmap[cidx > 0] = np.arange(cidx.sum()) + 1
340
+ posmap[mod] = cposmap
320
341
  setattr(self, "_" + attr + "map", posmap)
321
342
 
322
343
  self.is_view = True
323
344
  self.file = mudata_ref.file
324
345
  self._axis = mudata_ref._axis
325
346
  self._uns = mudata_ref._uns
347
+ self._oidx = obsidx
348
+ self._vidx = varidx
326
349
 
327
350
  if mudata_ref.is_view:
328
351
  self._mudata_ref = mudata_ref._mudata_ref
@@ -674,8 +697,14 @@ class MuData:
674
697
 
675
698
  data_global = data_global.rename_axis(col_index, axis=0).reset_index()
676
699
  for mod in self.mod.keys():
677
- data_global[mod + ":" + rowcol] = getattr(self, attr + "map")[mod]
678
- attrmap_columns = (mod + ":" + rowcol for mod in self.mod.keys())
700
+ # Only add mapping for modalities that exist in attrmap
701
+ if mod in getattr(self, attr + "map"):
702
+ data_global[mod + ":" + rowcol] = getattr(self, attr + "map")[mod]
703
+ attrmap_columns = [
704
+ mod + ":" + rowcol
705
+ for mod in self.mod.keys()
706
+ if mod in getattr(self, attr + "map")
707
+ ]
679
708
 
680
709
  data_mod = data_mod.merge(
681
710
  data_global, on=[col_index, *attrmap_columns], how="left", sort=False
@@ -780,8 +809,11 @@ class MuData:
780
809
  data_global[col_range] = np.arange(len(data_global))
781
810
 
782
811
  for mod in self.mod.keys():
783
- data_global[mod + ":" + rowcol] = getattr(self, attr + "map")[mod]
784
- attrmap_columns = [mod + ":" + rowcol for mod in self.mod.keys()]
812
+ if mod in getattr(self, attr + "map"):
813
+ data_global[mod + ":" + rowcol] = getattr(self, attr + "map")[mod]
814
+ attrmap_columns = [
815
+ mod + ":" + rowcol for mod in self.mod.keys() if mod in getattr(self, attr + "map")
816
+ ]
785
817
 
786
818
  data_mod = data_mod.merge(data_global, on=attrmap_columns, how="left", sort=False)
787
819
 
@@ -1279,7 +1311,7 @@ class MuData:
1279
1311
 
1280
1312
  # Update .obsp/.varp (size might have changed)
1281
1313
  for mx_key, mx in attrp.items():
1282
- attrp[mx_key] = attrp[mx_key][index_order, index_order]
1314
+ attrp[mx_key] = attrp[mx_key][index_order, :][:, index_order]
1283
1315
  attrp[mx_key][index_order == -1, :] = -1
1284
1316
  attrp[mx_key][:, index_order == -1] = -1
1285
1317
 
@@ -1440,7 +1472,11 @@ class MuData:
1440
1472
  self.update_obs()
1441
1473
 
1442
1474
  for k in self.mod:
1443
- self.mod[k].obs_names_make_unique()
1475
+ if isinstance(self.mod[k], AnnData):
1476
+ self.mod[k].obs_names_make_unique()
1477
+ # Only propagate to individual modalities with shared vars
1478
+ elif isinstance(self.mod[k], MuData) and getattr(self.mod[k], "axis", 1) == 1:
1479
+ self.mod[k].obs_names_make_unique()
1444
1480
 
1445
1481
  # Check if there are observations with the same name in different modalities
1446
1482
  common_obs = []
@@ -1467,13 +1503,44 @@ class MuData:
1467
1503
  def obs_names(self) -> pd.Index:
1468
1504
  """
1469
1505
  Names of variables (alias for `.obs.index`)
1470
-
1471
- This property is read-only.
1472
- To be modified, obs_names of individual modalities
1473
- should be changed, and .update_obs() should be called then.
1474
1506
  """
1475
1507
  return self.obs.index
1476
1508
 
1509
+ @obs_names.setter
1510
+ def obs_names(self, names: Sequence[str]):
1511
+ """
1512
+ Set the observation names for all the nested AnnData/MuData objects.
1513
+ """
1514
+ if isinstance(names, pd.Index):
1515
+ if not isinstance(names.name, str | type(None)):
1516
+ raise ValueError(
1517
+ f"MuData expects .obs.index.name to be a string or None, "
1518
+ f"but you passed a name of type {type(names.name).__name__!r}"
1519
+ )
1520
+ else:
1521
+ names = pd.Index(names)
1522
+ if not isinstance(names.name, str | type(None)):
1523
+ names.name = None
1524
+
1525
+ mod_obs_sum = np.sum([a.n_obs for a in self.mod.values()])
1526
+ if mod_obs_sum != self.n_obs:
1527
+ self.update_obs()
1528
+
1529
+ if len(names) != self.n_obs:
1530
+ raise ValueError(
1531
+ f"The length of provided observation names {len(names)} does not match the length {self.shape[0]} of MuData.obs."
1532
+ )
1533
+
1534
+ if self.is_view:
1535
+ self._init_as_actual(self.copy())
1536
+
1537
+ self._obs.index = names
1538
+ for mod, a in self.mod.items():
1539
+ indices = self.obsmap[mod]
1540
+ self.mod[mod].obs_names = names[indices[indices != 0] - 1]
1541
+
1542
+ self.update_obs()
1543
+
1477
1544
  @property
1478
1545
  def var(self) -> pd.DataFrame:
1479
1546
  """
@@ -1542,7 +1609,11 @@ class MuData:
1542
1609
  self.update_var()
1543
1610
 
1544
1611
  for k in self.mod:
1545
- self.mod[k].var_names_make_unique()
1612
+ if isinstance(self.mod[k], AnnData):
1613
+ self.mod[k].var_names_make_unique()
1614
+ # Only propagate to individual modalities with shared obs
1615
+ elif isinstance(self.mod[k], MuData) and getattr(self.mod[k], "axis", 0) == 0:
1616
+ self.mod[k].var_names_make_unique()
1546
1617
 
1547
1618
  # Check if there are variables with the same name in different modalities
1548
1619
  common_vars = []
@@ -1569,13 +1640,44 @@ class MuData:
1569
1640
  def var_names(self) -> pd.Index:
1570
1641
  """
1571
1642
  Names of variables (alias for `.var.index`)
1572
-
1573
- This property is read-only.
1574
- To be modified, var_names of individual modalities
1575
- should be changed, and .update_var() should be called then.
1576
1643
  """
1577
1644
  return self.var.index
1578
1645
 
1646
+ @var_names.setter
1647
+ def var_names(self, names: Sequence[str]):
1648
+ """
1649
+ Set the variable names for all the nested AnnData/MuData objects.
1650
+ """
1651
+ if isinstance(names, pd.Index):
1652
+ if not isinstance(names.name, str | type(None)):
1653
+ raise ValueError(
1654
+ f"MuData expects .var.index.name to be a string or None, "
1655
+ f"but you passed a name of type {type(names.name).__name__!r}"
1656
+ )
1657
+ else:
1658
+ names = pd.Index(names)
1659
+ if not isinstance(names.name, str | type(None)):
1660
+ names.name = None
1661
+
1662
+ mod_var_sum = np.sum([a.n_vars for a in self.mod.values()])
1663
+ if mod_var_sum != self.n_vars:
1664
+ self.update_var()
1665
+
1666
+ if len(names) != self.n_vars:
1667
+ raise ValueError(
1668
+ f"The length of provided variable names {len(names)} does not match the length {self.shape[0]} of MuData.var."
1669
+ )
1670
+
1671
+ if self.is_view:
1672
+ self._init_as_actual(self.copy())
1673
+
1674
+ self._var.index = names
1675
+ for mod, a in self.mod.items():
1676
+ indices = self.varmap[mod]
1677
+ self.mod[mod].var_names = names[indices[indices != 0] - 1]
1678
+
1679
+ self.update_var()
1680
+
1579
1681
  # Multi-dimensional annotations (.obsm and .varm)
1580
1682
 
1581
1683
  @property
@@ -1722,8 +1824,9 @@ class MuData:
1722
1824
 
1723
1825
  NOTE: From v0.4, it will not pull columns from modalities by default.
1724
1826
  """
1725
- self.update_var()
1726
- self.update_obs()
1827
+ if len(self.mod) > 0:
1828
+ self.update_var()
1829
+ self.update_obs()
1727
1830
 
1728
1831
  @property
1729
1832
  def axis(self) -> int:
@@ -1895,7 +1998,7 @@ class MuData:
1895
1998
  for m, mod in self.mod.items():
1896
1999
  if mods is not None and m not in mods:
1897
2000
  continue
1898
- mod_map = attrmap[m]
2001
+ mod_map = attrmap[m].ravel()
1899
2002
  mod_n_attr = mod.n_vars if attr == "var" else mod.n_obs
1900
2003
  mask = mod_map != 0
1901
2004
 
@@ -1,8 +1,13 @@
1
- # file generated by setuptools_scm
1
+ # file generated by setuptools-scm
2
2
  # don't change, don't track in version control
3
+
4
+ __all__ = ["__version__", "__version_tuple__", "version", "version_tuple"]
5
+
3
6
  TYPE_CHECKING = False
4
7
  if TYPE_CHECKING:
5
- from typing import Tuple, Union
8
+ from typing import Tuple
9
+ from typing import Union
10
+
6
11
  VERSION_TUPLE = Tuple[Union[int, str], ...]
7
12
  else:
8
13
  VERSION_TUPLE = object
@@ -12,5 +17,5 @@ __version__: str
12
17
  __version_tuple__: VERSION_TUPLE
13
18
  version_tuple: VERSION_TUPLE
14
19
 
15
- __version__ = version = '0.3.1'
16
- __version_tuple__ = version_tuple = (0, 3, 1)
20
+ __version__ = version = '0.3.2'
21
+ __version_tuple__ = version_tuple = (0, 3, 2)
@@ -1,5 +1,3 @@
1
- import unittest
2
-
3
1
  import numpy as np
4
2
  import pytest
5
3
  from anndata import AnnData
@@ -7,7 +5,6 @@ from anndata import AnnData
7
5
  import mudata
8
6
  from mudata import MuData
9
7
 
10
-
11
8
  N, D1, D2 = 100, 20, 30
12
9
  N1 = 15
13
10
  N2 = N - N1
@@ -0,0 +1,223 @@
1
+ from pathlib import Path
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import pytest
6
+ from anndata import AnnData
7
+ from scipy import sparse
8
+
9
+ import mudata
10
+ from mudata import MuData
11
+
12
+
13
+ @pytest.fixture()
14
+ def mdata():
15
+ rng = np.random.default_rng(42)
16
+ mod1 = AnnData(
17
+ np.arange(0, 100, 0.1).reshape(-1, 10),
18
+ obs=pd.DataFrame(index=rng.choice(150, size=100, replace=False)),
19
+ )
20
+ mod2 = AnnData(
21
+ np.arange(101, 2101, 1).reshape(-1, 20),
22
+ obs=pd.DataFrame(index=rng.choice(150, size=100, replace=False)),
23
+ )
24
+ mods = {"mod1": mod1, "mod2": mod2}
25
+ # Make var_names different in different modalities
26
+ for m in ["mod1", "mod2"]:
27
+ mods[m].var_names = [f"{m}_var{i}" for i in range(mods[m].n_vars)]
28
+ mdata = MuData(mods)
29
+ return mdata
30
+
31
+
32
+ @pytest.fixture()
33
+ def mdata_with_obsp():
34
+ """Create a MuData object with populated obsp and varp fields."""
35
+ rng = np.random.default_rng(42)
36
+ mod1 = AnnData(
37
+ np.arange(0, 100, 0.1).reshape(-1, 10),
38
+ obs=pd.DataFrame(index=rng.choice(150, size=100, replace=False)),
39
+ )
40
+ mod2 = AnnData(
41
+ np.arange(101, 2101, 1).reshape(-1, 20),
42
+ obs=pd.DataFrame(index=rng.choice(150, size=100, replace=False)),
43
+ )
44
+ mods = {"mod1": mod1, "mod2": mod2}
45
+ # Make var_names different in different modalities
46
+ for m in ["mod1", "mod2"]:
47
+ mods[m].var_names = [f"{m}_var{i}" for i in range(mods[m].n_vars)]
48
+ mdata = MuData(mods)
49
+
50
+ # Create and add sparse matrices to obsp
51
+ n_obs = mdata.n_obs
52
+ n_var = mdata.n_var
53
+
54
+ # Create sparse distances matrix (symmetric)
55
+ distances = sparse.random(n_obs, n_obs, density=0.2, random_state=42)
56
+ distances = sparse.triu(distances)
57
+ distances = distances + distances.T
58
+
59
+ # Create sparse connectivities matrix (symmetric)
60
+ connectivities = sparse.random(n_obs, n_obs, density=0.1, random_state=42)
61
+ connectivities = sparse.triu(connectivities)
62
+ connectivities = connectivities + connectivities.T
63
+
64
+ # Add to obsp
65
+ mdata.obsp["distances"] = distances
66
+ mdata.obsp["connectivities"] = connectivities
67
+
68
+ # Create and add a sparse matrix to varp
69
+ varp_matrix = sparse.random(n_var, n_var, density=0.05, random_state=42)
70
+ varp_matrix = sparse.triu(varp_matrix)
71
+ varp_matrix = varp_matrix + varp_matrix.T
72
+
73
+ mdata.varp["correlations"] = varp_matrix
74
+
75
+ return mdata
76
+
77
+
78
+ @pytest.mark.usefixtures("filepath_h5mu", "filepath2_h5mu")
79
+ class TestMuData:
80
+ def test_copy(self, mdata):
81
+ mdata_copy = mdata.copy()
82
+ assert mdata.shape == mdata_copy.shape
83
+ assert np.array_equal(mdata.obs_names.values, mdata_copy.obs_names.values)
84
+ assert np.array_equal(mdata.var_names.values, mdata_copy.var_names.values)
85
+ assert np.array_equal(mdata.obs.columns.values, mdata_copy.obs.columns.values)
86
+ assert np.array_equal(mdata.var.columns.values, mdata_copy.var.columns.values)
87
+
88
+ def test_view_attributes(self, mdata):
89
+ mdata_copy = mdata.copy()
90
+ n, d = mdata.n_obs, mdata.n_var
91
+ # Populate attributes
92
+ mdata_copy.uns["uns_key"] = {"key": "value"}
93
+ mdata_copy.obs["obs_column"] = False
94
+ mdata_copy.var["var_column"] = False
95
+ mdata_copy.obsm["obsm_key"] = np.arange(n).reshape(-1, 1)
96
+ mdata_copy.varm["varm_key"] = np.arange(d).reshape(-1, 1)
97
+ mdata_copy.obsp["obsp_key"] = np.arange(n * n).reshape(n, n)
98
+ mdata_copy.varp["varp_key"] = np.arange(d * d).reshape(d, d)
99
+
100
+ view_n_obs = 7
101
+ mdata_view = mdata_copy[list(range(view_n_obs)), :]
102
+ assert mdata_view.shape == (view_n_obs, mdata.n_var)
103
+ assert len(mdata_view.mod) == len(mdata_copy.mod)
104
+ # AnnData/MuData interface
105
+ for attr in "obs", "var", "obsm", "varm", "obsp", "varp", "uns":
106
+ assert hasattr(mdata_view, attr)
107
+ assert list(getattr(mdata_view, attr).keys()) == list(getattr(mdata_copy, attr).keys())
108
+ # MuData-specific interface
109
+ for attr in "mod", "axis", "obsmap", "varmap":
110
+ assert hasattr(mdata_view, attr)
111
+ assert mdata_view.axis == mdata_copy.axis
112
+
113
+ def test_view_copy(self, mdata):
114
+ view_n_obs = 5
115
+ mdata_view = mdata[list(range(view_n_obs)), :]
116
+ assert mdata_view.is_view
117
+ assert mdata_view.n_obs == view_n_obs
118
+ mdata_copy = mdata_view.copy()
119
+ assert not mdata_copy.is_view
120
+ assert mdata_copy.n_obs == view_n_obs
121
+
122
+ def test_view_view(self, mdata):
123
+ view_n_obs = 5
124
+ mdata_view = mdata[list(range(view_n_obs)), :]
125
+ assert mdata_view.is_view
126
+ assert mdata_view.n_obs == view_n_obs
127
+
128
+ for modname, mod in mdata_view.mod.items():
129
+ assert mdata_view.obsmap[modname].max() == mod.n_obs
130
+ idx = mdata_view.obsmap[modname]
131
+ assert np.all(mdata_view.obs_names[idx > 0] == mod.obs_names[idx[idx > 0] - 1])
132
+
133
+ view_view_n_obs = 2
134
+ mdata_view_view = mdata_view[list(range(view_view_n_obs)), :]
135
+ assert mdata_view_view.is_view
136
+ assert mdata_view_view.n_obs == view_view_n_obs
137
+
138
+ for modname, mod in mdata_view_view.mod.items():
139
+ ref_obsmap = mdata_view.obsmap[modname][:view_view_n_obs]
140
+ ref_obsmap = ref_obsmap[ref_obsmap > 0] - 1
141
+ assert (mod.obs_names == mdata_view[modname].obs_names[ref_obsmap]).all()
142
+ assert (mod.var_names == mdata_view[modname].var_names).all()
143
+
144
+ # test reordering
145
+ mdata_view_view = mdata_view[:, :]
146
+ for modname, mod in mdata_view_view.mod.items():
147
+ assert (mod.obs_names == mdata_view[modname].obs_names).all()
148
+ assert (mod.var_names == mdata_view[modname].var_names).all()
149
+
150
+ def test_backed_copy(self, mdata, filepath_h5mu, filepath2_h5mu):
151
+ mdata.write(filepath_h5mu)
152
+ mdata_b = mudata.read_h5mu(filepath_h5mu, backed="r")
153
+ assert mdata_b.n_obs == mdata.n_obs
154
+ mdata_b_copy = mdata_b.copy(filepath2_h5mu)
155
+ assert mdata_b_copy.file._filename.name == Path(filepath2_h5mu).name
156
+
157
+ def test_obsp_slicing(self, mdata_with_obsp):
158
+ """Test that obsp matrices are correctly sliced when subsetting a MuData object."""
159
+ orig_n_obs = mdata_with_obsp.n_obs
160
+
161
+ # Check initial shapes
162
+ assert mdata_with_obsp.obsp["distances"].shape == (orig_n_obs, orig_n_obs)
163
+ assert mdata_with_obsp.obsp["connectivities"].shape == (orig_n_obs, orig_n_obs)
164
+
165
+ # Slice a subset of cells
166
+ n_obs_subset = 50
167
+ random_indices = np.random.choice(
168
+ mdata_with_obsp.obs_names, size=n_obs_subset, replace=False
169
+ )
170
+
171
+ # Create a slice view
172
+ mdata_slice = mdata_with_obsp[random_indices]
173
+
174
+ # Check that the sliced obsp matrices have correct shape in the view
175
+ assert mdata_slice.obsp["distances"].shape == (
176
+ n_obs_subset,
177
+ n_obs_subset,
178
+ ), f"Expected shape in view: {(n_obs_subset, orig_n_obs)}, got: {mdata_slice.obsp['distances'].shape}"
179
+ assert mdata_slice.obsp["connectivities"].shape == (
180
+ n_obs_subset,
181
+ n_obs_subset,
182
+ ), f"Expected shape in view: {(n_obs_subset, orig_n_obs)}, got: {mdata_slice.obsp['connectivities'].shape}"
183
+
184
+ # Make a copy of the sliced MuData object
185
+ mdata_copy = mdata_slice.copy()
186
+ # Check shapes after copy - these should be (n_obs_subset, n_obs_subset) if correctly copied
187
+ assert mdata_copy.obsp["distances"].shape == (
188
+ n_obs_subset,
189
+ n_obs_subset,
190
+ ), f"Expected shape after copy: {(n_obs_subset, n_obs_subset)}, got: {mdata_copy.obsp['distances'].shape}"
191
+ assert mdata_copy.obsp["connectivities"].shape == (
192
+ n_obs_subset,
193
+ n_obs_subset,
194
+ ), f"Expected shape after copy: {(n_obs_subset, n_obs_subset)}, got: {mdata_copy.obsp['connectivities'].shape}"
195
+
196
+ def test_varp_slicing(self, mdata_with_obsp):
197
+ """Test that varp matrices are correctly sliced when subsetting a MuData object."""
198
+ orig_n_var = mdata_with_obsp.n_var
199
+
200
+ # Check initial shape
201
+ assert mdata_with_obsp.varp["correlations"].shape == (orig_n_var, orig_n_var)
202
+
203
+ # Slice a subset of variables
204
+ n_var_subset = 15
205
+ all_var_names = mdata_with_obsp.var_names
206
+ random_var_indices = np.random.choice(all_var_names, size=n_var_subset, replace=False)
207
+
208
+ # Create a slice view
209
+ mdata_slice = mdata_with_obsp[:, random_var_indices]
210
+
211
+ # Check that the sliced varp matrix has correct shape in the view
212
+ assert mdata_slice.varp["correlations"].shape == (
213
+ n_var_subset,
214
+ n_var_subset,
215
+ ), f"Expected shape in view: {(n_var_subset, orig_n_var)}, got: {mdata_slice.varp['correlations'].shape}"
216
+
217
+ # Copy the sliced MuData object
218
+ mdata_copy = mdata_slice.copy()
219
+ # Check shapes after copy
220
+ assert mdata_copy.varp["correlations"].shape == (
221
+ n_var_subset,
222
+ n_var_subset,
223
+ ), f"Expected shape after copy: {(n_var_subset, n_var_subset)}, got: {mdata_copy.varp['correlations'].shape}"
@@ -1,83 +0,0 @@
1
- from pathlib import Path
2
-
3
- import numpy as np
4
- import pytest
5
- from anndata import AnnData
6
-
7
- import mudata
8
- from mudata import MuData
9
-
10
-
11
- @pytest.fixture()
12
- def mdata():
13
- mod1 = AnnData(np.arange(0, 100, 0.1).reshape(-1, 10))
14
- mod2 = AnnData(np.arange(101, 2101, 1).reshape(-1, 20))
15
- mods = {"mod1": mod1, "mod2": mod2}
16
- # Make var_names different in different modalities
17
- for m in ["mod1", "mod2"]:
18
- mods[m].var_names = [f"{m}_var{i}" for i in range(mods[m].n_vars)]
19
- mdata = MuData(mods)
20
- return mdata
21
-
22
-
23
- @pytest.mark.usefixtures("filepath_h5mu", "filepath2_h5mu")
24
- class TestMuData:
25
- def test_copy(self, mdata):
26
- mdata_copy = mdata.copy()
27
- assert mdata.shape == mdata_copy.shape
28
- assert np.array_equal(mdata.obs_names.values, mdata_copy.obs_names.values)
29
- assert np.array_equal(mdata.var_names.values, mdata_copy.var_names.values)
30
- assert np.array_equal(mdata.obs.columns.values, mdata_copy.obs.columns.values)
31
- assert np.array_equal(mdata.var.columns.values, mdata_copy.var.columns.values)
32
-
33
- def test_view_attributes(self, mdata):
34
- mdata_copy = mdata.copy()
35
- n, d = mdata.n_obs, mdata.n_var
36
- # Populate attributes
37
- mdata_copy.uns["uns_key"] = {"key": "value"}
38
- mdata_copy.obs["obs_column"] = False
39
- mdata_copy.var["var_column"] = False
40
- mdata_copy.obsm["obsm_key"] = np.arange(n).reshape(-1, 1)
41
- mdata_copy.varm["varm_key"] = np.arange(d).reshape(-1, 1)
42
- mdata_copy.obsp["obsp_key"] = np.arange(n * n).reshape(n, n)
43
- mdata_copy.varp["varp_key"] = np.arange(d * d).reshape(d, d)
44
-
45
- view_n_obs = 7
46
- mdata_view = mdata_copy[list(range(view_n_obs)), :]
47
- assert mdata_view.shape == (view_n_obs, mdata.n_var)
48
- assert len(mdata_view.mod) == len(mdata_copy.mod)
49
- # AnnData/MuData interface
50
- for attr in "obs", "var", "obsm", "varm", "obsp", "varp", "uns":
51
- assert hasattr(mdata_view, attr)
52
- assert list(getattr(mdata_view, attr).keys()) == list(getattr(mdata_copy, attr).keys())
53
- # MuData-specific interface
54
- for attr in "mod", "axis", "obsmap", "varmap":
55
- assert hasattr(mdata_view, attr)
56
- assert mdata_view.axis == mdata_copy.axis
57
-
58
- def test_view_copy(self, mdata):
59
- view_n_obs = 5
60
- mdata_view = mdata[list(range(view_n_obs)), :]
61
- assert mdata_view.is_view
62
- assert mdata_view.n_obs == view_n_obs
63
- mdata_copy = mdata_view.copy()
64
- assert not mdata_copy.is_view
65
- assert mdata_copy.n_obs == view_n_obs
66
-
67
- def test_view_view(self, mdata):
68
- view_n_obs = 5
69
- mdata_view = mdata[list(range(view_n_obs)), :]
70
- assert mdata_view.is_view
71
- assert mdata_view.n_obs == view_n_obs
72
-
73
- view_view_n_obs = 2
74
- mdata_view_view = mdata_view[list(range(view_view_n_obs)), :]
75
- assert mdata_view_view.is_view
76
- assert mdata_view_view.n_obs == view_view_n_obs
77
-
78
- def test_backed_copy(self, mdata, filepath_h5mu, filepath2_h5mu):
79
- mdata.write(filepath_h5mu)
80
- mdata_b = mudata.read_h5mu(filepath_h5mu, backed="r")
81
- assert mdata_b.n_obs == mdata.n_obs
82
- mdata_b_copy = mdata_b.copy(filepath2_h5mu)
83
- assert mdata_b_copy.file._filename.name == Path(filepath2_h5mu).name
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes