This repository has been archived by the owner on Oct 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_model.py
1608 lines (1472 loc) · 62 KB
/
_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import logging
import os
import warnings
from collections.abc import Sequence
from copy import deepcopy
from functools import partial
from typing import Literal
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import numpyro.distributions as dist
import pandas as pd
import seaborn as sns
import xarray as xr
from anndata import AnnData
from scvi import REGISTRY_KEYS
from scvi.data import AnnDataManager
from scvi.data.fields import (
CategoricalObsField,
LayerField,
NumericalJointObsField,
NumericalObsField,
)
from scvi.model.base import BaseModelClass, JaxTrainingMixin
from sklearn.mixture import GaussianMixture
from statsmodels.stats.multitest import multipletests
from tqdm import tqdm
from ._components import MLP
from ._constants import MRVI_REGISTRY_KEYS
from ._module import MrVAE
from ._tree_utils import (
compute_dendrogram_from_distance_matrix,
convert_pandas_to_colors,
)
from ._types import MrVIReduction
from ._utils import (
_parse_local_statistics_requirements,
compute_statistic,
permutation_test,
rowwise_max_excluding_diagonal,
)
logger = logging.getLogger(__name__)
DEFAULT_TRAIN_KWARGS = {
"max_epochs": 100,
"early_stopping": True,
"early_stopping_patience": 15,
"check_val_every_n_epoch": 1,
"batch_size": 256,
"train_size": 0.9,
"plan_kwargs": {
"lr": 2e-3,
"n_epochs_kl_warmup": 20,
"max_norm": 40,
"eps": 1e-8,
"weight_decay": 1e-8,
},
}
class MrVI(JaxTrainingMixin, BaseModelClass):
"""
Multi-resolution Variational Inference (MrVI).
Parameters
----------
adata
AnnData object that has been registered via ``setup_anndata``.
n_latent
Dimensionality of the latent space.
n_latent_donor
Dimensionality of the latent space for sample embeddings.
encoder_n_hidden
Number of nodes per hidden layer in the encoder.
px_kwargs
Keyword args for :class:`~mrvi.DecoderZX`.
qz_kwargs
Keyword args for :class:`~mrvi.EncoderUZ`.
qu_kwargs
Keyword args for :class:`~mrvi.EncoderXU`.
"""
def __init__(
self,
adata,
**model_kwargs,
):
super().__init__(adata)
n_sample = self.summary_stats.n_sample
n_batch = self.summary_stats.n_batch
n_labels = self.summary_stats.n_labels
n_continuous_cov = self.summary_stats.get("n_extra_continuous_covs", 0)
obs_df = adata.obs.copy()
obs_df = obs_df.loc[~obs_df._scvi_sample.duplicated("first")]
self.donor_info = obs_df.set_index("_scvi_sample").sort_index()
self.sample_key = self.adata_manager.get_state_registry("sample").original_key
self.sample_order = self.adata_manager.get_state_registry(
MRVI_REGISTRY_KEYS.SAMPLE_KEY
).categorical_mapping
self.n_obs_per_sample = jnp.array(
adata.obs._scvi_sample.value_counts().sort_index().values
)
self.data_splitter = None
self.can_compute_normalized_dists = (
model_kwargs.get("qz_nn_flavor", "linear") == "linear"
)
self.module = MrVAE(
n_input=self.summary_stats.n_vars,
n_sample=n_sample,
n_batch=n_batch,
n_labels=n_labels,
n_continuous_cov=n_continuous_cov,
n_obs_per_sample=self.n_obs_per_sample,
**model_kwargs,
)
self.can_compute_normalized_dists = (
model_kwargs.get("qz_nn_flavor", "linear") == "linear"
) and (
(model_kwargs.get("n_latent_u", None) is None)
or (model_kwargs.get("n_latent", 10) == model_kwargs.get("n_latent_u", None))
)
self.init_params_ = self._get_init_params(locals())
def to_device(self, device):
# TODO(jhong): remove this once we have a better way to handle device.
pass
def _generate_stacked_rngs(
self, n_sets: int | tuple
) -> dict[str, jax.random.PRNGKey]:
return_1d = isinstance(n_sets, int)
if return_1d:
n_sets_1d = n_sets
else:
n_sets_1d = np.prod(n_sets)
rngs_list = [self.module.rngs for _ in range(n_sets_1d)]
# Combine list of RNG dicts into a single list. This is necessary for vmap/map.
rngs = {
required_rng: jnp.concatenate(
[rngs_dict[required_rng][None] for rngs_dict in rngs_list], axis=0
)
for required_rng in self.module.required_rngs
}
if not return_1d:
# Reshaping the random keys to the desired shape in
# the case of multiple sets.
rngs = {
key: random_key.reshape(n_sets + random_key.shape[1:])
for (key, random_key) in rngs.items()
}
return rngs
@classmethod
def setup_anndata(
cls,
adata: AnnData,
layer: str | None = None,
sample_key: str | None = None,
batch_key: str | None = None,
labels_key: str | None = None,
continuous_covariate_keys: list[str] | None = None,
**kwargs,
):
setup_method_args = cls._get_setup_method_args(**locals())
# Add index for batched computation of local statistics.
adata.obs["_indices"] = np.arange(adata.n_obs).astype(int)
anndata_fields = [
LayerField(REGISTRY_KEYS.X_KEY, layer, is_count_data=True),
CategoricalObsField(MRVI_REGISTRY_KEYS.SAMPLE_KEY, sample_key),
CategoricalObsField(REGISTRY_KEYS.BATCH_KEY, batch_key),
CategoricalObsField(REGISTRY_KEYS.LABELS_KEY, labels_key),
NumericalJointObsField(
REGISTRY_KEYS.CONT_COVS_KEY, continuous_covariate_keys
),
NumericalObsField(REGISTRY_KEYS.INDICES_KEY, "_indices"),
]
if labels_key is None:
# Hack to load old models pre labels field.
# TODO: remove. not necessary for official release
sr = kwargs.get("source_registry", None)
if sr is not None:
sr["field_registries"][REGISTRY_KEYS.LABELS_KEY] = {
"state_registry": {"categorical_mapping": np.array([0])}
}
adata_manager = AnnDataManager(
fields=anndata_fields, setup_method_args=setup_method_args
)
adata_manager.register_fields(adata, **kwargs)
cls.register_manager(adata_manager)
def train(
self,
max_epochs: int | None = None,
accelerator: str | None = "auto",
devices: int | list[int] | str = "auto",
train_size: float = 0.9,
validation_size: float | None = None,
batch_size: int = 128,
early_stopping: bool = False,
plan_kwargs: dict | None = None,
**trainer_kwargs,
):
train_kwargs = dict(
max_epochs=max_epochs,
accelerator=accelerator,
devices=devices,
train_size=train_size,
validation_size=validation_size,
batch_size=batch_size,
early_stopping=early_stopping,
**trainer_kwargs,
)
train_kwargs = dict(deepcopy(DEFAULT_TRAIN_KWARGS), **train_kwargs)
plan_kwargs = plan_kwargs or {}
train_kwargs["plan_kwargs"] = dict(
deepcopy(DEFAULT_TRAIN_KWARGS["plan_kwargs"]), **plan_kwargs
)
super().train(**train_kwargs)
def get_latent_representation(
self,
adata: AnnData | None = None,
indices=None,
batch_size: int | None = None,
use_mean: bool = True,
give_z: bool = False,
) -> np.ndarray:
"""
Computes the latent representation of the data.
Parameters
----------
adata
AnnData object to use. Defaults to the AnnData object used to initialize the model.
indices
Indices of cells to use.
batch_size
Batch size to use for computing the latent representation.
use_mean
Whether to use the mean of the distribution as the latent representation.
give_z
Whether to return the z latent representation or the u latent representation.
Returns
-------
The latent representation of the data.
"""
self._check_if_trained(warn=False)
adata = self._validate_anndata(adata)
scdl = self._make_data_loader(
adata=adata, indices=indices, batch_size=batch_size, iter_ndarray=True
)
us = []
zs = []
jit_inference_fn = self.module.get_jit_inference_fn(
inference_kwargs={"use_mean": use_mean}
)
for array_dict in tqdm(scdl):
outputs = jit_inference_fn(self.module.rngs, array_dict)
if give_z:
zs.append(jax.device_get(outputs["z"]))
else:
us.append(jax.device_get(outputs["u"]))
if give_z:
return np.array(jnp.concatenate(zs, axis=0))
else:
return np.array(jnp.concatenate(us, axis=0))
def compute_local_statistics(
self,
reductions: list[MrVIReduction],
adata: AnnData | None = None,
indices: Sequence[int] | None = None,
batch_size: int | None = None,
use_vmap: bool = True,
norm: str = "l2",
mc_samples: int = 10,
) -> xr.Dataset:
"""
Compute local statistics from counterfactual sample representations.
Local statistics are reductions over either the local counterfactual latent representations
or the resulting local sample distance matrices. For a large number of cells and/or samples,
this method can avoid scalability issues by grouping over cell-level covariates.
Parameters
----------
reductions
List of reductions to compute over local counterfactual sample representations.
adata
AnnData object to use.
indices
Indices of cells to use.
batch_size
Batch size to use for computing the local statistics.
use_vmap
Whether to use vmap to compute the local statistics.
norm
Norm to use for computing the distances.
mc_samples
Number of Monte Carlo samples to use for computing the local statistics. Only applies if using
sampled representations.
"""
if not reductions or len(reductions) == 0:
raise ValueError("At least one reduction must be provided.")
adata = self.adata if adata is None else adata
self._check_if_trained(warn=False)
# Hack to ensure new AnnDatas have indices.
adata.obs["_indices"] = np.arange(adata.n_obs).astype(int)
adata = self._validate_anndata(adata)
scdl = self._make_data_loader(
adata=adata, indices=indices, batch_size=batch_size, iter_ndarray=True
)
n_sample = self.summary_stats.n_sample
reqs = _parse_local_statistics_requirements(reductions)
vars_in = {"params": self.module.params, **self.module.state}
@partial(jax.jit, static_argnames=["use_mean", "mc_samples"])
def mapped_inference_fn(
stacked_rngs,
x,
sample_index,
cf_sample,
use_mean,
mc_samples=None,
):
# TODO: use `self.module.get_jit_inference_fn` when it supports traced values.
def inference_fn(
rngs,
cf_sample,
):
return self.module.apply(
vars_in,
rngs=rngs,
method=self.module.inference,
x=x,
sample_index=sample_index,
cf_sample=cf_sample,
use_mean=use_mean,
mc_samples=mc_samples,
)["z"]
if use_vmap:
return jax.vmap(inference_fn, in_axes=(0, 0), out_axes=-2)(
stacked_rngs,
cf_sample,
)
else:
def per_sample_inference_fn(pair):
rngs, cf_sample = pair
return inference_fn(rngs, cf_sample)
return jax.lax.transpose(
jax.lax.map(per_sample_inference_fn, (stacked_rngs, cf_sample)),
(1, 0, 2),
)
ungrouped_data_arrs = {}
grouped_data_arrs = {}
for ur in reqs.ungrouped_reductions:
ungrouped_data_arrs[ur.name] = []
for gr in reqs.grouped_reductions:
grouped_data_arrs[
gr.name
] = {} # Will map group category to running group sum.
for array_dict in tqdm(scdl):
indices = array_dict[REGISTRY_KEYS.INDICES_KEY].astype(int).flatten()
n_cells = array_dict[REGISTRY_KEYS.X_KEY].shape[0]
cf_sample = np.broadcast_to(
np.arange(n_sample)[:, None, None], (n_sample, n_cells, 1)
)
inf_inputs = self.module._get_inference_input(
array_dict,
)
stacked_rngs = self._generate_stacked_rngs(cf_sample.shape[0])
# Compute necessary inputs.
if reqs.needs_mean_representations:
mean_zs_ = mapped_inference_fn(
stacked_rngs=stacked_rngs, # OK to use stacked rngs here since there is no stochasticity for mean rep.
x=jnp.array(inf_inputs["x"]),
sample_index=jnp.array(inf_inputs["sample_index"]),
cf_sample=jnp.array(cf_sample),
use_mean=True,
)
mean_zs = xr.DataArray(
mean_zs_,
dims=["cell_name", "sample", "latent_dim"],
coords={
"cell_name": self.adata.obs_names[indices],
"sample": self.sample_order,
},
name="sample_representations",
)
if reqs.needs_sampled_representations:
sampled_zs_ = mapped_inference_fn(
stacked_rngs=stacked_rngs,
x=jnp.array(inf_inputs["x"]),
sample_index=jnp.array(inf_inputs["sample_index"]),
cf_sample=jnp.array(cf_sample),
use_mean=False,
mc_samples=mc_samples,
) # (n_mc_samples, n_cells, n_samples, n_latent)
sampled_zs_ = sampled_zs_.transpose((1, 0, 2, 3))
sampled_zs = xr.DataArray(
sampled_zs_,
dims=["cell_name", "mc_sample", "sample", "latent_dim"],
coords={
"cell_name": self.adata.obs_names[indices],
"sample": self.sample_order,
},
name="sample_representations",
)
if reqs.needs_mean_distances:
mean_dists = self._compute_distances_from_representations(
mean_zs_, indices, norm=norm
)
if reqs.needs_sampled_distances or reqs.needs_normalized_distances:
sampled_dists = self._compute_distances_from_representations(
sampled_zs_, indices, norm=norm
)
if reqs.needs_normalized_distances:
if norm != "l2":
raise ValueError(
f"Norm must be 'l2' when using normalized distances. Got {norm}."
)
(
normalization_means,
normalization_vars,
) = self._compute_local_baseline_dists(
array_dict, mc_samples=mc_samples
) # both are shape (n_cells,)
normalization_means = normalization_means.reshape(-1, 1, 1, 1)
normalization_vars = normalization_vars.reshape(-1, 1, 1, 1)
normalized_dists = (
np.clip(sampled_dists - normalization_means, a_min=0, a_max=None)
/ (normalization_vars**0.5)
).mean(dim="mc_sample") # (n_cells, n_samples, n_samples)
# Compute each reduction
for r in reductions:
if r.input == "mean_representations":
inputs = mean_zs
elif r.input == "sampled_representations":
inputs = sampled_zs
elif r.input == "mean_distances":
inputs = mean_dists
elif r.input == "sampled_distances":
inputs = sampled_dists
elif r.input == "normalized_distances":
inputs = normalized_dists
else:
raise ValueError(f"Unknown reduction input: {r.input}")
outputs = r.fn(inputs)
if r.group_by is not None:
group_by = self.adata.obs[r.group_by][indices]
group_by_cats = group_by.unique()
for cat in group_by_cats:
cat_summed_outputs = outputs.sel(
cell_name=self.adata.obs_names[indices][
group_by == cat
].values
).sum(dim="cell_name")
cat_summed_outputs = cat_summed_outputs.assign_coords(
{f"{r.group_by}_name": cat}
)
if cat not in grouped_data_arrs[r.name]:
grouped_data_arrs[r.name][cat] = cat_summed_outputs
else:
grouped_data_arrs[r.name][cat] += cat_summed_outputs
else:
ungrouped_data_arrs[r.name].append(outputs)
# Combine all outputs.
final_data_arrs = {}
for ur_name, ur_outputs in ungrouped_data_arrs.items():
final_data_arrs[ur_name] = xr.concat(ur_outputs, dim="cell_name")
for gr in reqs.grouped_reductions:
group_by = adata.obs[gr.group_by]
group_by_counts = group_by.value_counts()
averaged_grouped_data_arrs = []
for cat, count in group_by_counts.items():
averaged_grouped_data_arrs.append(
grouped_data_arrs[gr.name][cat] / count
)
final_data_arr = xr.concat(
averaged_grouped_data_arrs, dim=f"{gr.group_by}_name"
)
final_data_arrs[gr.name] = final_data_arr
return xr.Dataset(data_vars=final_data_arrs)
def _compute_local_baseline_dists(
self, batch: dict, mc_samples: int = 250
) -> tuple[np.ndarray, np.ndarray]:
"""
Approximate the distributions used as baselines for normalizing the local sample distances.
Approximates the means and variances of the Euclidean distance between two samples of
the z latent representation for the original sample for each cell in ``adata``.
Reference: https://www.overleaf.com/read/mhdxcrknzxpm.
Parameters
----------
batch
Batch of data to compute the local sample representation for.
mc_samples
Number of Monte Carlo samples to use for computing the local baseline distributions.
"""
def get_A_s(module, u, sample_covariate):
sample_covariate = sample_covariate.astype(int).flatten()
if getattr(module.qz, "use_nonlinear", False):
A_s = module.qz.A_s_enc(sample_covariate, training=False)
else:
# A_s output by a non-linear function without an explicit intercept
sample_one_hot = jax.nn.one_hot(sample_covariate, module.qz.n_sample)
A_s_dec_inputs = jnp.concatenate([u, sample_one_hot], axis=-1)
if isinstance(module.qz.A_s_enc, MLP):
A_s = module.qz.A_s_enc(A_s_dec_inputs, training=False)
else:
# nn.Embed does not support training kwarg
A_s = module.qz.A_s_enc(A_s_dec_inputs)
# cells by n_latent by n_latent
return A_s.reshape(sample_covariate.shape[0], module.qz.n_latent, -1)
def apply_get_A_s(u, sample_covariate):
vars_in = {"params": self.module.params, **self.module.state}
rngs = self.module.rngs
A_s = self.module.apply(
vars_in,
rngs=rngs,
method=get_A_s,
u=u,
sample_covariate=sample_covariate,
)
return A_s
if self.can_compute_normalized_dists:
jit_inference_fn = self.module.get_jit_inference_fn()
qu = jit_inference_fn(self.module.rngs, batch)["qu"]
qu_vars_diag = jax.vmap(jnp.diag)(qu.variance)
sample_index = self.module._get_inference_input(batch)["sample_index"]
A_s = apply_get_A_s(
qu.mean, sample_index
) # use mean of latent representation to compute the baseline
B = jnp.expand_dims(jnp.eye(A_s.shape[1]), 0) + A_s
u_diff_sigma = 2 * jnp.einsum(
"cij, cjk, clk -> cil", B, qu_vars_diag, B
) # 2 * (I + A_s) @ qu_vars_diag @ (I + A_s).T
eigvals = jax.vmap(jnp.linalg.eigh)(u_diff_sigma)[0].astype(float)
normal_rng = self.module.rngs[
"params"
] # Hack to get new rng for normal samples.
normal_samples = jax.random.normal(
normal_rng, shape=(eigvals.shape[0], mc_samples, eigvals.shape[1])
) # n_cells by mc_samples by n_latent
squared_l2_dists = jnp.sum(
jnp.einsum("cij, cj -> cij", (normal_samples**2), eigvals), axis=2
)
l2_dists = squared_l2_dists**0.5
else:
mc_samples_per_cell = (
mc_samples * 2
) # need double for pairs of samples to compute distance between
jit_inference_fn = self.module.get_jit_inference_fn(
inference_kwargs={"use_mean": False, "mc_samples": mc_samples_per_cell}
)
outputs = jit_inference_fn(self.module.rngs, batch)
# figure out how to compute dists here
z = outputs["z"]
first_half_z, second_half_z = z[:mc_samples], z[mc_samples:]
l2_dists = jnp.sqrt(jnp.sum((first_half_z - second_half_z) ** 2, axis=2)).T
return np.array(jnp.mean(l2_dists, axis=1)), np.array(jnp.var(l2_dists, axis=1))
def _compute_distances_from_representations(
self, reps, indices, norm="l2"
) -> xr.DataArray:
@jax.jit
def _compute_distance(rep):
delta_mat = jnp.expand_dims(rep, 0) - jnp.expand_dims(rep, 1)
if norm == "l2":
res = delta_mat**2
res = jnp.sqrt(res.sum(-1))
elif norm == "l1":
res = jnp.abs(delta_mat).sum(-1)
elif norm == "linf":
res = jnp.abs(delta_mat).max(-1)
else:
raise ValueError(f"norm {norm} not supported")
return res
if reps.ndim == 3:
dists = jax.vmap(_compute_distance)(reps)
return xr.DataArray(
dists,
dims=["cell_name", "sample_x", "sample_y"],
coords={
"cell_name": self.adata.obs_names[indices],
"sample_x": self.sample_order,
"sample_y": self.sample_order,
},
name="sample_distances",
)
else:
# Case with sampled representations
dists = jax.vmap(jax.vmap(_compute_distance))(reps)
return xr.DataArray(
dists,
dims=["cell_name", "mc_sample", "sample_x", "sample_y"],
coords={
"cell_name": self.adata.obs_names[indices],
"mc_sample": np.arange(reps.shape[1]),
"sample_x": self.sample_order,
"sample_y": self.sample_order,
},
name="sample_distances",
)
def get_local_sample_representation(
self,
adata: AnnData | None = None,
indices: list[str] | None = None,
batch_size: int = 256,
use_mean: bool = True,
use_vmap: bool = True,
) -> xr.DataArray:
"""
Computes the local sample representation of the cells in the adata object.
For each cell, it returns a matrix of size (n_sample, n_features).
Parameters
----------
adata
AnnData object to use for computing the local sample representation.
batch_size
Batch size to use for computing the local sample representation.
use_mean
Whether to use the mean of the latent representation as the local sample representation.
use_vmap
Whether to use vmap for computing the local sample representation.
Disabling vmap can be useful if running out of memory on a GPU.
"""
reductions = [
MrVIReduction(
name="sample_representations",
input="mean_representations" if use_mean else "sampled_representations",
fn=lambda x: x,
group_by=None,
)
]
return self.compute_local_statistics(
reductions,
adata=adata,
indices=indices,
batch_size=batch_size,
use_vmap=use_vmap,
).sample_representations
def get_local_sample_distances(
self,
adata: AnnData | None = None,
batch_size: int = 256,
use_mean: bool = True,
normalize_distances: bool = False,
use_vmap: bool = True,
groupby: list[str] | str | None = None,
keep_cell: bool = True,
norm: str = "l2",
mc_samples: int = 10,
) -> xr.Dataset:
"""
Computes local sample distances as `xr.Dataset`.
Computes cell-specific distances between samples, of size (n_sample, n_sample),
stored as a Dataset, with variable name `cell`, of size (n_cell, n_sample, n_sample).
If in addition, groupby is provided, distances are also aggregated by group.
In this case, the group-specific distances via group name key.
Parameters
----------
adata
AnnData object to use for computing the local sample representation.
batch_size
Batch size to use for computing the local sample representation.
use_mean
Whether to use the mean of the latent representation as the local sample representation.
normalize_distances
Whether to normalize the local sample distances. Normalizes by
the standard deviation of the original intra-sample distances.
Only works with ``use_mean=False``.
use_vmap
Whether to use vmap for computing the local sample representation.
Disabling vmap can be useful if running out of memory on a GPU.
groupby
List of categorical keys or single key of the anndata that is
used to group the cells.
keep_cell
Whether to keep the original cell sample-sample distance matrices.
norm
Norm to use for computing the local sample distances.
mc_samples
Number of Monte Carlo samples to use for computing the local sample distances.
Only relevants if ``use_mean=False``.
"""
input = "mean_distances" if use_mean else "sampled_distances"
if normalize_distances:
if use_mean:
warnings.warn(
"Normalizing distances uses sampled distances. Ignoring ``use_mean``.",
UserWarning,
stacklevel=2,
)
input = "normalized_distances"
if groupby and not isinstance(groupby, list):
groupby = [groupby]
reductions = []
if not keep_cell and not groupby:
raise ValueError(
"Undefined computation because not keep_cell and no groupby."
)
if keep_cell:
reductions.append(
MrVIReduction(
name="cell",
input=input,
fn=lambda x: x,
)
)
if groupby:
for groupby_key in groupby:
reductions.append(
MrVIReduction(
name=groupby_key,
input=input,
group_by=groupby_key,
)
)
return self.compute_local_statistics(
reductions,
adata=adata,
batch_size=batch_size,
use_vmap=use_vmap,
norm=norm,
mc_samples=mc_samples,
)
def get_aggregated_posterior(
self,
adata: AnnData | None = None,
indices: list[str] | None = None,
batch_size: int = 256,
) -> dist.Distribution:
"""
Computes the aggregated posterior over the ``u`` latent representations.
Parameters
----------
adata
AnnData object to use. Defaults to the AnnData object used to initialize the model.
indices
Indices of cells to use.
batch_size
Batch size to use for computing the latent representation.
Returns
-------
A mixture distribution of the aggregated posterior.
"""
self._check_if_trained(warn=False)
adata = self._validate_anndata(adata)
scdl = self._make_data_loader(
adata=adata, indices=indices, batch_size=batch_size, iter_ndarray=True
)
qu_locs = []
qu_scales = []
jit_inference_fn = self.module.get_jit_inference_fn(
inference_kwargs={"use_mean": True}
)
for array_dict in scdl:
outputs = jit_inference_fn(self.module.rngs, array_dict)
qu_locs.append(outputs["qu"].loc)
qu_scales.append(outputs["qu"].scale)
qu_loc = jnp.concatenate(qu_locs, axis=0).T
qu_scale = jnp.concatenate(qu_scales, axis=0).T
return dist.MixtureSameFamily(
dist.Categorical(probs=jnp.ones(qu_loc.shape[1]) / qu_loc.shape[1]),
dist.Normal(qu_loc, qu_scale),
)
def get_outlier_cell_sample_pairs(
self,
adata=None,
flavor: Literal["ball", "ap", "MoG"] = "ball",
subsample_size: int = 5_000,
quantile_threshold: float = 0.05,
admissibility_threshold: float = 0.0,
minibatch_size: int = 256,
) -> xr.Dataset:
"""Utils function to get outlier cell-sample pairs.
This function fits a GMM for each sample based on the latent representation
of the cells in the sample or computes an approximate aggregated posterior for each sample.
Then, for every cell, it computes the log-probability of the cell under the approximated posterior
of each sample as a measure of admissibility.
Parameters
----------
adata
AnnData object containing the cells for which to compute the outlier cell-sample pairs.
flavor
Method of approximating posterior on latent representation.
subsample_size
Number of cells to use from each sample to approximate the posterior. If None, uses all of the available cells.
quantile_threshold
Quantile of the within-sample log probabilities to use as a baseline for admissibility.
admissibility_threshold
Threshold for admissibility. Cell-sample pairs with admissibility below this threshold are considered outliers.
"""
adata = self.adata if adata is None else adata
adata = self._validate_anndata(adata)
# Compute u reps
us = self.get_latent_representation(adata, use_mean=True, give_z=False)
adata.obsm["U"] = us
log_probs = []
threshs = []
unique_samples = adata.obs[self.sample_key].unique()
for sample_name in tqdm(unique_samples):
sample_idxs = np.where(adata.obs[self.sample_key] == sample_name)[0]
if subsample_size is not None and sample_idxs.shape[0] > subsample_size:
sample_idxs = np.random.choice(
sample_idxs, size=subsample_size, replace=False
)
adata_s = adata[sample_idxs]
if flavor == "MoG":
n_components = min(adata_s.n_obs // 4, 20)
gmm_ = GaussianMixture(n_components=n_components).fit(adata_s.obsm["U"])
log_probs_s = jnp.quantile(
gmm_.score_samples(adata_s.obsm["U"]), q=quantile_threshold
)
log_probs_ = gmm_.score_samples(adata.obsm["U"])[:, None]
elif flavor == "ap":
ap = self.get_aggregated_posterior(adata=adata, indices=sample_idxs)
log_probs_s = jnp.quantile(
ap.log_prob(adata_s.obsm["U"]).sum(axis=1), q=quantile_threshold
)
n_splits = adata.n_obs // minibatch_size
log_probs_ = []
for u_rep in np.array_split(adata.obsm["U"], n_splits):
log_probs_.append(
jax.device_get(ap.log_prob(u_rep).sum(-1, keepdims=True))
)
log_probs_ = np.concatenate(log_probs_, axis=0) # (n_cells, 1)
elif flavor == "ball":
ap = self.get_aggregated_posterior(adata=adata, indices=sample_idxs)
in_max_comp_log_probs = ap.component_distribution.log_prob(
np.expand_dims(adata_s.obsm["U"], ap.mixture_dim)
).sum(axis=1)
log_probs_s = rowwise_max_excluding_diagonal(in_max_comp_log_probs)
log_probs_ = []
n_splits = adata.n_obs // minibatch_size
for u_rep in np.array_split(adata.obsm["U"], n_splits):
log_probs_.append(
jax.device_get(
ap.component_distribution.log_prob(
np.expand_dims(u_rep, ap.mixture_dim)
)
.sum(axis=1)
.max(axis=1, keepdims=True)
)
)
log_probs_ = np.concatenate(log_probs_, axis=0) # (n_cells, 1)
else:
raise ValueError(f"Unknown flavor {flavor}")
threshs.append(np.array(log_probs_s))
log_probs.append(np.array(log_probs_))
if flavor == "ball":
# Compute a threshold across all samples
threshs_all = np.concatenate(threshs)
global_thresh = np.quantile(threshs_all, q=quantile_threshold)
threshs = len(log_probs) * [global_thresh]
log_probs = np.concatenate(log_probs, 1)
threshs = np.array(threshs)
log_ratios = log_probs - threshs
coords = {
"cell_name": adata.obs_names.to_numpy(),
"sample": unique_samples,
}
data_vars = {
"log_probs": (["cell_name", "sample"], log_probs),
"log_ratios": (
["cell_name", "sample"],
log_ratios,
),
"is_admissible": (
["cell_name", "sample"],
log_ratios > admissibility_threshold,
),
}
return xr.Dataset(data_vars, coords=coords)
def perform_multivariate_analysis(
self,
adata: AnnData | None = None,
donor_keys: list[tuple] = None,
donor_subset: list[str] | None = None,
batch_size: int = 256,
use_vmap: bool = True,
normalize_design_matrix: bool = True,
add_batch_specific_offsets: bool = False,
mc_samples: int = 100,
store_lfc: bool = False,
store_lfc_metadata_subset: list[str] | None = None,
store_baseline: bool = False,
eps_lfc: float = 1e-3,
filter_donors: bool = False,
lambd: float = 0.0,
delta: float | None = 0.3,
**filter_donors_kwargs,
) -> xr.Dataset:
"""Utility function to perform cell-specific multivariate analysis.
For every cell, we first compute all counterfactual cell-state shifts, defined as
e_d = z_d - u, where z_d is the latent representation of the cell for donor d and u is the donor-unaware latent representation.
Then, we fit a linear model in each cell of the form
e_d = X_d * beta_d + iid gaussian noise.
Parameters
----------
adata
AnnData object to use for computing the local sample representation.
If None, the analysis is performed on all cells in the dataset.
donor_keys
List of donor metadata to consider for the multivariate analysis.
These keys should be present in `adata.obs`.
donor_subset
Optional list of donors to consider for the multivariate analysis.
If None, all donors are considered.
batch_size
Batch size to use for computing the local sample representation.
use_vmap
Whether to use vmap for computing the local sample representation.
normalize_design_matrix
Whether to normalize the design matrix.
add_batch_specific_offsets
Whether to offset the design matrix by adding batch-specific offsets to the design matrix.
Setting this option to True is recommended when considering multi-site datasets.
mc_samples
How many MC samples should be taken for computing betas.
store_lfc
Whether to store the log-fold changes in the module.
Storing log-fold changes is memory-intensive and may require to specify
a smaller set of cells to analyze, e.g., by specifying `adata`.
store_lfc_metadata_subset