-
Notifications
You must be signed in to change notification settings - Fork 59
/
deprecated.py
1853 lines (1581 loc) · 77.6 KB
/
deprecated.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
import re
import warnings
from typing import Callable, Iterable, List, Optional, Tuple, Union
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
import functools
import anndata
import numpy as np
import numpy.typing as npt
import pandas as pd
import statsmodels.api as sm
from anndata import AnnData
from scipy.sparse import csr_matrix, issparse
from sklearn.decomposition import FastICA
from ..configuration import DKM, DynamoAdataConfig, DynamoAdataKeyManager
from ..dynamo_logger import (
LoggerManager,
main_debug,
main_info,
main_info_insert_adata_obsm,
main_warning,
)
from ..tools.utils import update_dict
from ..utils import copy_adata
from .cell_cycle import cell_cycle_scores
from .gene_selection import calc_dispersion_by_svr
from .normalization import calc_sz_factor, get_sz_exprs, normalize_mat_monocle, sz_util
from .pca import pca
from .QC import basic_stats, filter_genes_by_clusters, filter_genes_by_outliers
from .transform import _Freeman_Tukey
from .utils import (
_infer_labeling_experiment_type,
add_noise_to_duplicates,
calc_new_to_total_ratio,
collapse_species_adata,
compute_gene_exp_fraction,
convert2symbol,
convert_layers2csr,
detect_experiment_datatype,
get_inrange_shared_counts_mask,
get_nan_or_inf_data_bool_mask,
get_svr_filter,
merge_adata_attrs,
unique_var_obs_adata,
)
def deprecated(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
warnings.warn(
f"{func.__name__} is deprecated and will be removed in a future release. "
f"Please update your code to use the new replacement function.",
category=DeprecationWarning,
stacklevel=2,
)
return func(*args, **kwargs)
return wrapper
# ---------------------------------------------------------------------------------------------------
# implmentation of Cooks' distance (but this is for Poisson distribution fitting)
# https://stackoverflow.com/questions/47686227/poisson-regression-in-statsmodels-and-r
# from __future__ import division, print_function
# https://stats.stackexchange.com/questions/356053/the-identity-link-function-does-not-respect-the-domain-of-the-gamma-
# family
def _weight_matrix_legacy(fitted_model: sm.Poisson) -> np.ndarray:
"""Calculates weight matrix in Poisson regression.
Args:
fitted_model: a fitted Poisson model
Returns:
A diagonal weight matrix in Poisson regression.
"""
return np.diag(fitted_model.fittedvalues)
def _hessian_legacy(X: np.ndarray, W: np.ndarray) -> np.ndarray:
"""Hessian matrix calculated as -X'*W*X.
Args:
X: the matrix of covariates.
W: the weight matrix.
Returns:
The result Hessian matrix.
"""
return -np.dot(X.T, np.dot(W, X))
def _hat_matrix_legacy(X: np.ndarray, W: np.ndarray) -> np.ndarray:
"""Calculate hat matrix = W^(1/2) * X * (X'*W*X)^(-1) * X'*W^(1/2)
Args:
X: the matrix of covariates.
W: the diagonal weight matrix
Returns:
The result hat matrix
"""
# W^(1/2)
Wsqrt = W ** (0.5)
# (X'*W*X)^(-1)
XtWX = -_hessian_legacy(X=X, W=W)
XtWX_inv = np.linalg.inv(XtWX)
# W^(1/2)*X
WsqrtX = np.dot(Wsqrt, X)
# X'*W^(1/2)
XtWsqrt = np.dot(X.T, Wsqrt)
return np.dot(WsqrtX, np.dot(XtWX_inv, XtWsqrt))
@deprecated
def cook_dist(*args, **kwargs):
return _cook_dist_legacy(*args, **kwargs)
def _cook_dist_legacy(model: sm.Poisson, X: np.ndarray, good: npt.ArrayLike) -> np.ndarray:
"""calculate Cook's distance
Args:
model: a fitted Poisson model.
X: the matrix of covariates.
good: the dispersion table for MSE calculation.
Returns:
The result Cook's distance.
"""
# Weight matrix
W = _weight_matrix_legacy(model)
# Hat matrix
H = _hat_matrix_legacy(X, W)
hii = np.diag(H) # Diagonal values of hat matrix # fit.get_influence().hat_matrix_diag
# Pearson residuals
r = model.resid_pearson
# Cook's distance (formula used by R = (res/(1 - hat))^2 * hat/(dispersion * p))
# Note: dispersion is 1 since we aren't modeling overdispersion
resid = good.disp - model.predict(good)
rss = np.sum(resid**2)
MSE = rss / (good.shape[0] - 2)
# use the formula from: https://www.mathworks.com/help/stats/cooks-distance.html
cooks_d = r**2 / (2 * MSE) * hii / (1 - hii) ** 2 # (r / (1 - hii)) ** 2 * / (1 * 2)
return cooks_d
def _disp_calc_helper_NB_legacy(
adata: AnnData, layers: str = "X", min_cells_detected: int = 1
) -> Tuple[List[str], List[pd.DataFrame]]:
"""Helper function to calculate the dispersion parameter.
This function is partly based on Monocle R package (https://github.com/cole-trapnell-lab/monocle3).
Args:
adata: an Anndata object.
layers: the layer of data used for dispersion fitting. Defaults to "X".
min_cells_detected: the minimal required number of cells with expression for selecting gene for dispersion
fitting. Defaults to 1.
Returns:
layers: a list of layers available.
res_list: a list of pd.DataFrames with mu, dispersion for each gene that passes filters.
"""
main_warning(__name__ + " is deprecated.")
layers = DKM.get_available_layer_keys(adata, layers=layers, include_protein=False)
res_list = []
for layer in layers:
if layer == "raw":
CM = adata.raw.X
szfactors = adata.obs[layer + "Size_Factor"][:, None]
elif layer == "X":
CM = adata.X
szfactors = adata.obs["Size_Factor"][:, None]
else:
CM = adata.layers[layer]
szfactors = adata.obs[layer + "Size_Factor"][:, None]
if issparse(CM):
CM.data = np.round(CM.data, 0)
rounded = CM
else:
rounded = CM.round().astype("int")
lowerDetectedLimit = adata.uns["lowerDetectedLimit"] if "lowerDetectedLimit" in adata.uns.keys() else 1
nzGenes = (rounded > lowerDetectedLimit).sum(axis=0)
nzGenes = nzGenes > min_cells_detected
nzGenes = nzGenes.A1 if issparse(rounded) else nzGenes
if layer.startswith("X_"):
x = rounded[:, nzGenes]
else:
x = (
rounded[:, nzGenes].multiply(csr_matrix(1 / szfactors))
if issparse(rounded)
else rounded[:, nzGenes] / szfactors
)
xim = np.mean(1 / szfactors) if szfactors is not None else 1
f_expression_mean = x.mean(axis=0)
# For NB: Var(Y) = mu * (1 + mu / k)
# x.A.var(axis=0, ddof=1)
f_expression_var = (
(x.multiply(x).mean(0).A1 - f_expression_mean.A1**2) * x.shape[0] / (x.shape[0] - 1)
if issparse(x)
else x.var(axis=0, ddof=0) ** 2
) # np.mean(np.power(x - f_expression_mean, 2), axis=0) # variance with n - 1
# https://scialert.net/fulltext/?doi=ajms.2010.1.15 method of moments
disp_guess_meth_moments = f_expression_var - xim * f_expression_mean # variance - mu
disp_guess_meth_moments = disp_guess_meth_moments / np.power(
f_expression_mean, 2
) # this is dispersion parameter (1/k)
res = pd.DataFrame(
{
"mu": np.array(f_expression_mean).flatten(),
"disp": np.array(disp_guess_meth_moments).flatten(),
}
)
res.loc[res["mu"] == 0, "mu"] = None
res.loc[res["mu"] == 0, "disp"] = None
res.loc[res["disp"] < 0, "disp"] = 0
res["gene_id"] = adata.var_names[nzGenes]
res_list.append(res)
return layers, res_list
def _parametric_dispersion_fit_legacy(
disp_table: pd.DataFrame, initial_coefs: np.ndarray = np.array([1e-6, 1])
) -> Tuple[sm.formula.glm, np.ndarray, pd.DataFrame]:
"""Perform the dispersion parameter fitting with initial guesses of coefficients.
This function is partly based on Monocle R package (https://github.com/cole-trapnell-lab/monocle3).
Args:
disp_table: A pandas dataframe with mu, dispersion for each gene that passes filters.
initial_coefs: Initial parameters for the gamma fit of the dispersion parameters. Defaults to
np.array([1e-6, 1]).
Returns:
A tuple (fit, coefs, good), where fit is a statsmodels fitting object, coefs contains the two resulting gamma
fitting coefficient, and good is the subsetted dispersion table that is subjected to Gamma fitting.
"""
main_warning(__name__ + " is deprecated.")
coefs = initial_coefs
iter = 0
while True:
residuals = disp_table["disp"] / (coefs[0] + coefs[1] / disp_table["mu"])
good = disp_table.loc[(residuals > initial_coefs[0]) & (residuals < 10000), :]
# https://stats.stackexchange.com/questions/356053/the-identity-link-function-does-not-respect-the-domain-of-the
# -gamma-family
fit = sm.formula.glm(
"disp ~ I(1 / mu)",
data=good,
family=sm.families.Gamma(link=sm.genmod.families.links.identity),
).train(start_params=coefs)
oldcoefs = coefs
coefs = fit.params
if coefs[0] < initial_coefs[0]:
coefs[0] = initial_coefs[0]
if coefs[1] < 0:
main_warning("Parametric dispersion fit may be failed.")
if np.sum(np.log(coefs / oldcoefs) ** 2 < coefs[0]):
break
iter += 1
if iter > 10:
main_warning("Dispersion fit didn't converge")
break
if not np.all(coefs > 0):
main_warning("Parametric dispersion fit may be failed.")
return fit, coefs, good
def _estimate_dispersion_legacy(
adata: AnnData,
layers: str = "X",
modelFormulaStr: str = "~ 1",
min_cells_detected: int = 1,
removeOutliers: bool = False,
) -> AnnData:
"""This function is partly based on Monocle R package (https://github.com/cole-trapnell-lab/monocle3).
Args:
adata: an AnnData object.
layers: the layer(s) to be used for calculating dispersion. Default is "X" if there is no spliced layers.
modelFormulaStr: the model formula used to calculate dispersion parameters. Not used. Defaults to "~ 1".
min_cells_detected: the minimum number of cells detected for calculating the dispersion. Defaults to 1.
removeOutliers: whether to remove outliers when performing dispersion fitting. Defaults to False.
Raises:
Exception: there is no valid DataFrames with mu for genes.
Returns:
An updated annData object with dispFitInfo added to uns attribute as a new key.
"""
main_warning(__name__ + " is deprecated.")
logger = LoggerManager.gen_logger("dynamo-preprocessing")
# mu = None
model_terms = [x.strip() for x in re.compile("~|\\*|\\+").split(modelFormulaStr)]
model_terms = list(set(model_terms) - set([""]))
cds_pdata = adata.obs # .loc[:, model_terms]
cds_pdata["rowname"] = cds_pdata.index.values
layers, disp_tables = _disp_calc_helper_NB_legacy(adata[:, :], layers, min_cells_detected)
# disp_table['disp'] = np.random.uniform(0, 10, 11)
# disp_table = cds_pdata.apply(disp_calc_helper_NB(adata[:, :], min_cells_detected))
# cds_pdata <- dplyr::group_by_(dplyr::select_(rownames_to_column(pData(cds)), "rowname", .dots=model_terms), .dots
# =model_terms)
# disp_table <- as.data.frame(cds_pdata %>% do(disp_calc_helper_NB(cds[,.$rowname], cds@expressionFamily, min_cells_
# detected)))
for ind in range(len(layers)):
layer, disp_table = layers[ind], disp_tables[ind]
if disp_table is None:
raise Exception("Parametric dispersion fitting failed, please set a different lowerDetectionLimit")
disp_table = disp_table.loc[np.where(disp_table["mu"] != np.nan)[0], :]
res = _parametric_dispersion_fit_legacy(disp_table)
fit, coefs, good = res[0], res[1], res[2]
if removeOutliers:
# influence = fit.get_influence().cooks_distance()
# #CD is the distance and p is p-value
# (CD, p) = influence.cooks_distance
CD = cook_dist(fit, 1 / good["mu"][:, None], good)
cooksCutoff = 4 / good.shape[0]
main_debug("Removing " + str(len(CD[CD > cooksCutoff])) + " outliers")
outliers = CD > cooksCutoff
# use CD.index.values? remove genes that lost when doing parameter fitting
lost_gene = set(good.index.values).difference(set(range(len(CD))))
outliers[lost_gene] = True
res = _parametric_dispersion_fit_legacy(good.loc[~outliers, :])
fit, coefs = res[0], res[1]
def ans(q):
return coefs[0] + coefs[1] / q
if layer == "X":
logger.info_insert_adata("dispFitInfo", "uns")
adata.uns["dispFitInfo"] = {
"disp_table": good,
"disp_func": ans,
"coefs": coefs,
}
else:
logger.info_insert_adata(layer + "_dispFitInfo", "uns")
adata.uns[layer + "_dispFitInfo"] = {
"disp_table": good,
"disp_func": ans,
"coefs": coefs,
}
return adata
def _top_table_legacy(
adata: AnnData, layer: str = "X", mode: Literal["dispersion", "gini"] = "dispersion"
) -> pd.DataFrame:
"""Retrieve a table that contains gene names and other info whose dispersions/gini index are highest.
This function is partly based on Monocle R package (https://github.com/cole-trapnell-lab/monocle3).
Get information of the top layer.
Args:
adata: an AnnData object.
layer: the layer(s) that would be searched for. Defaults to "X".
mode: either "dispersion" or "gini", deciding whether dispersion data or gini data would be acquired. Defaults
to "dispersion".
Raises:
KeyError: if mode is set to dispersion but there is no available dispersion model.
Returns:
The data frame of the top layer with the gene_id, mean_expression, dispersion_fit and dispersion_empirical as
the columns.
"""
layer = DKM.get_available_layer_keys(adata, layers=layer, include_protein=False)[0]
if layer in ["X"]:
key = "dispFitInfo"
else:
key = layer + "_dispFitInfo"
if mode == "dispersion":
if adata.uns[key] is None:
_estimate_dispersion_legacy(adata, layers=[layer])
raise KeyError(
"Error: for adata.uns.key=%s, no dispersion model found. Please call estimate_dispersion() before calling this function"
% key
)
top_df = pd.DataFrame(
{
"gene_id": adata.uns[key]["disp_table"]["gene_id"],
"mean_expression": adata.uns[key]["disp_table"]["mu"],
"dispersion_fit": adata.uns[key]["disp_func"](adata.uns[key]["disp_table"]["mu"]),
"dispersion_empirical": adata.uns[key]["disp_table"]["disp"],
}
)
top_df = top_df.set_index("gene_id")
elif mode == "gini":
top_df = adata.var[layer + "_gini"]
return top_df
def _calc_mean_var_dispersion_general_mat_legacy(
data_mat: Union[np.ndarray, csr_matrix], axis: int = 0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""calculate mean, variance, and dispersion of a matrix.
Args:
data_mat: the matrix to be evaluated, either a ndarray or a scipy sparse matrix.
axis: the axis along which calculation is performed. Defaults to 0.
Returns:
A tuple (mean, var, dispersion) where mean is the mean of the array along the given axis, var is the variance of
the array along the given axis, and dispersion is the dispersion of the array along the given axis.
"""
if not issparse(data_mat):
return _calc_mean_var_dispersion_ndarray_legacy(data_mat, axis)
else:
return _calc_mean_var_dispersion_sparse_legacy(data_mat, axis)
def _calc_mean_var_dispersion_ndarray_legacy(
data_mat: np.ndarray, axis: int = 0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""calculate mean, variance, and dispersion of a non-sparse matrix.
Args:
data_mat: the matrix to be evaluated.
axis: the axis along which calculation is performed. Defaults to 0.
Returns:
A tuple (mean, var, dispersion) where mean is the mean of the array along the given axis, var is the variance of
the array along the given axis, and dispersion is the dispersion of the array along the given axis.
"""
# per gene mean, var and dispersion
mean = np.nanmean(data_mat, axis=axis).flatten()
# <class 'anndata._core.views.ArrayView'> has bug after using operator "==" (e.g. mean == 0), which changes mean.
mean = np.array(mean)
mean[mean == 0] += 1e-7 # prevent division by zero
var = np.nanvar(data_mat, axis=axis)
dispersion = var / mean
return mean.flatten(), var.flatten(), dispersion.flatten()
def _calc_mean_var_dispersion_sparse_legacy(
sparse_mat: csr_matrix, axis: int = 0
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""calculate mean, variance, and dispersion of a matrix.
Args:
sparse_mat: the sparse matrix to be evaluated.
axis: the axis along which calculation is performed. Defaults to 0.
Returns:
A tuple (mean, var, dispersion), where mean is the mean of the array along the given axis, var is the variance
of the array along the given axis, and dispersion is the dispersion of the array along the given axis.
"""
sparse_mat = sparse_mat.copy()
nan_mask = get_nan_or_inf_data_bool_mask(sparse_mat.data)
temp_val = (sparse_mat != 0).sum(axis)
sparse_mat.data[nan_mask] = 0
nan_count = temp_val - (sparse_mat != 0).sum(axis)
non_nan_count = sparse_mat.shape[axis] - nan_count
mean = (sparse_mat.sum(axis) / sparse_mat.shape[axis]).A1
mean[mean == 0] += 1e-7 # prevent division by zero
# same as numpy var behavior: denominator is N, var=(data_arr-mean)/N
var = np.power(sparse_mat - mean, 2).sum(axis) / sparse_mat.shape[axis]
dispersion = var / mean
return np.array(mean).flatten(), np.array(var).flatten(), np.array(dispersion).flatten()
@deprecated
def calc_sz_factor_legacy(*args, **kwargs):
return _calc_sz_factor_legacy(*args, **kwargs)
def _calc_sz_factor_legacy(
adata_ori: anndata.AnnData,
layers: Union[str, list] = "all",
total_layers: Union[list, None] = None,
splicing_total_layers: bool = False,
X_total_layers: bool = False,
locfunc: Callable = np.nanmean,
round_exprs: bool = False,
method: Literal["mean-geometric-mean-total", "geometric", "median"] = "median",
scale_to: Union[float, None] = None,
use_all_genes_cells: bool = True,
genes_use_for_norm: Union[list, None] = None,
) -> anndata.AnnData:
"""Calculate the size factor of the each cell using geometric mean of total UMI across cells for a AnnData object.
This function is partly based on Monocle R package (https://github.com/cole-trapnell-lab/monocle3).
Args:
adata_ori: an AnnData object.
layers: the layer(s) to be normalized, including RNA (X, raw) or spliced, unspliced, protein, etc. Defaults to
"all".
total_layers: the layer(s) that can be summed up to get the total mRNA. For example, ["spliced", "unspliced"],
["uu", "ul", "su", "sl"] or ["new", "old"], etc. Defaults to None.
splicing_total_layers: whether to also normalize spliced / unspliced layers by size factor from total RNA.
Defaults to False.
X_total_layers: whether to also normalize adata.X by size factor from total RNA. Defaults to False.
locfunc: the function to normalize the data. Defaults to np.nanmean.
round_exprs: whether the gene expression should be rounded into integers. Defaults to False.
method: the method used to calculate the expected total reads / UMI used in size factor calculation. Only
`mean-geometric-mean-total` / `geometric` and `median` are supported. When `median` is used, `locfunc` will
be replaced with `np.nanmedian`. Defaults to "median".
scale_to: the final total expression for each cell that will be scaled to. Defaults to None.
use_all_genes_cells: whether all cells and genes should be used for the size factor calculation. Defaults to
True.
genes_use_for_norm: a list of gene names that will be used to calculate total RNA for each cell and then the
size factor for normalization. This is often very useful when you want to use only the host genes to
normalize the dataset in a virus infection experiment (i.e. CMV or SARS-CoV-2 infection). Defaults to None.
Returns:
An updated anndata object that are updated with the `Size_Factor` (`layer_` + `Size_Factor`) column(s) in the
obs attribute.
"""
if use_all_genes_cells:
# let us ignore the `inplace` parameter in pandas.Categorical.remove_unused_categories warning.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
adata = adata_ori if genes_use_for_norm is None else adata_ori[:, genes_use_for_norm]
else:
cell_inds = adata_ori.obs.use_for_pca if "use_for_pca" in adata_ori.obs.columns else adata_ori.obs.index
filter_list = ["use_for_pca", "pass_basic_filter"]
filter_checker = [i in adata_ori.var.columns for i in filter_list]
which_filter = np.where(filter_checker)[0]
gene_inds = adata_ori.var[filter_list[which_filter[0]]] if len(which_filter) > 0 else adata_ori.var.index
adata = adata_ori[cell_inds, :][:, gene_inds]
if genes_use_for_norm is not None:
# let us ignore the `inplace` parameter in pandas.Categorical.remove_unused_categories warning.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
adata = adata[:, adata.var_names.intersection(genes_use_for_norm)]
if total_layers is not None:
if not isinstance(total_layers, list):
total_layers = [total_layers]
if len(set(total_layers).difference(adata.layers.keys())) == 0:
total = None
for t_key in total_layers:
total = adata.layers[t_key] if total is None else total + adata.layers[t_key]
adata.layers["_total_"] = total
if type(layers) is str:
layers = [layers]
layers.extend(["_total_"])
layers = DynamoAdataKeyManager.get_available_layer_keys(adata, layers)
if "raw" in layers and adata.raw is None:
adata.raw = adata.copy()
excluded_layers = []
if not X_total_layers:
excluded_layers.extend(["X"])
if not splicing_total_layers:
excluded_layers.extend(["spliced", "unspliced"])
for layer in layers:
if layer in excluded_layers:
sfs, cell_total = sz_util(
adata,
layer,
round_exprs,
method,
locfunc,
total_layers=None,
scale_to=scale_to,
)
else:
sfs, cell_total = sz_util(
adata,
layer,
round_exprs,
method,
locfunc,
total_layers=total_layers,
scale_to=scale_to,
)
sfs[~np.isfinite(sfs)] = 1
if layer == "raw":
adata.obs[layer + "_Size_Factor"] = sfs
adata.obs["Size_Factor"] = sfs
adata.obs["initial_cell_size"] = cell_total
elif layer == "X":
adata.obs["Size_Factor"] = sfs
adata.obs["initial_cell_size"] = cell_total
elif layer == "_total_":
adata.obs["total_Size_Factor"] = sfs
adata.obs["initial" + layer + "cell_size"] = cell_total
del adata.layers["_total_"]
else:
adata.obs[layer + "_Size_Factor"] = sfs
adata.obs["initial_" + layer + "_cell_size"] = cell_total
adata_ori = merge_adata_attrs(adata_ori, adata, attr="obs")
return adata_ori
@deprecated
def normalize_cell_expr_by_size_factors(*args, **kwargs):
return _normalize_cell_expr_by_size_factors_legacy(*args, **kwargs)
def _normalize_cell_expr_by_size_factors_legacy(
adata: anndata.AnnData,
layers: str = "all",
total_szfactor: str = "total_Size_Factor",
splicing_total_layers: bool = False,
X_total_layers: bool = False,
norm_method: Union[Callable, Literal["clr"], None] = None,
pseudo_expr: int = 1,
relative_expr: bool = True,
keep_filtered: bool = True,
recalc_sz: bool = False,
sz_method: str = "median",
scale_to: Union[float, None] = None,
) -> anndata.AnnData:
"""Normalize the gene expression value for the AnnData object
This function is partly based on Monocle R package (https://github.com/cole-trapnell-lab/monocle3).
Args:
adata: an AnnData object
layers: the layer(s) to be normalized. Default is all, including RNA (X, raw) or spliced, unspliced, protein,
etc. Defaults to "all".
total_szfactor: the column name in the .obs attribute that corresponds to the size factor for the total mRNA.
Defaults to "total_Size_Factor".
splicing_total_layers: whether to also normalize spliced / unspliced layers by size factor from total RNA.
Defaults to False.
X_total_layers: whether to also normalize adata.X by size factor from total RNA. Defaults to False.
norm_method: the method used to normalize data. Can be either function `np.log1p`, `np.log2` or any other
functions or string `clr`. By default, only .X will be size normalized and log1p transformed while data in
other layers will only be size normalized. Defaults to None.
pseudo_expr: a pseudocount added to the gene expression value before log/log2 normalization. Defaults to 1.
relative_expr: a logic flag to determine whether we need to divide gene expression values first by size factor
before normalization. Defaults to True.
keep_filtered: a logic flag to determine whether we will only store feature genes in the adata object. If it is
False, size factor will be recalculated only for the selected feature genes. Defaults to True.
recalc_sz: a logic flag to determine whether we need to recalculate size factor based on selected genes before
normalization. Defaults to False.
sz_method: the method used to calculate the expected total reads / UMI used in size factor calculation. Only
`mean-geometric-mean-total` / `geometric` and `median` are supported. When `median` is used, `locfunc` will
be replaced with `np.nanmedian`. Defaults to "median".
scale_to: the final total expression for each cell that will be scaled to. Defaults to None.
Returns:
An updated anndata object that are updated with normalized expression values for different layers.
"""
if recalc_sz:
if "use_for_pca" in adata.var.columns and keep_filtered is False:
adata = adata[:, adata.var.loc[:, "use_for_pca"]]
adata.obs = adata.obs.loc[:, ~adata.obs.columns.str.contains("Size_Factor")]
layers = DynamoAdataKeyManager.get_available_layer_keys(adata, layers)
layer_sz_column_names = [i + "_Size_Factor" for i in set(layers).difference("X")]
layer_sz_column_names.extend(["Size_Factor"])
layers_to_sz = list(set(layer_sz_column_names).difference(adata.obs.keys()))
if len(layers_to_sz) > 0:
layers = pd.Series(layers_to_sz).str.split("_Size_Factor", expand=True).iloc[:, 0].tolist()
if "Size_Factor" in layers:
layers[np.where(np.array(layers) == "Size_Factor")[0][0]] = "X"
calc_sz_factor_legacy(
adata,
layers=layers,
locfunc=np.nanmean,
round_exprs=True,
method=sz_method,
scale_to=scale_to,
)
excluded_layers = []
if not X_total_layers:
excluded_layers.extend(["X"])
if not splicing_total_layers:
excluded_layers.extend(["spliced", "unspliced"])
for layer in layers:
if layer in excluded_layers:
szfactors, CM = get_sz_exprs(adata, layer, total_szfactor=None)
else:
szfactors, CM = get_sz_exprs(adata, layer, total_szfactor=total_szfactor)
if norm_method is None and layer == "X":
CM = normalize_mat_monocle(CM, szfactors, relative_expr, pseudo_expr, np.log1p)
elif norm_method in [np.log1p, np.log, np.log2, _Freeman_Tukey, None] and layer != "protein":
CM = normalize_mat_monocle(CM, szfactors, relative_expr, pseudo_expr, norm_method)
elif layer == "protein": # norm_method == 'clr':
if norm_method != "clr":
main_warning(
"For protein data, log transformation is not recommended. Using clr normalization by default."
)
"""This normalization implements the centered log-ratio (CLR) normalization from Seurat which is computed
for each gene (M Stoeckius, 2017).
"""
CM = CM.T
n_feature = CM.shape[1]
for i in range(CM.shape[0]):
x = CM[i].A if issparse(CM) else CM[i]
res = np.log1p(x / (np.exp(np.nansum(np.log1p(x[x > 0])) / n_feature)))
res[np.isnan(res)] = 0
# res[res > 100] = 100
# no .A is required # https://stackoverflow.com/questions/28427236/set-row-of-csr-matrix
CM[i] = res
CM = CM.T
else:
main_warning(norm_method + " is not implemented yet")
if layer in ["raw", "X"]:
main_info("Set <adata.X> to normalized data")
adata.X = CM
elif layer == "protein" and "protein" in adata.obsm_keys():
main_info_insert_adata_obsm("X_protein")
adata.obsm["X_protein"] = CM
else:
adata.layers["X_" + layer] = CM
norm_method_key = "X_norm_method" if layer == DKM.X_LAYER else "layers_norm_method"
adata.uns["pp"][norm_method_key] = norm_method.__name__ if callable(norm_method) else norm_method
return adata
@deprecated
def filter_cells_legacy(*args, **kwargs):
return _filter_cells_legacy(*args, **kwargs)
def _filter_cells_legacy(
adata: anndata.AnnData,
filter_bool: Union[np.ndarray, None] = None,
layer: str = "all",
keep_filtered: bool = False,
min_expr_genes_s: int = 50,
min_expr_genes_u: int = 25,
min_expr_genes_p: int = 1,
max_expr_genes_s: float = np.inf,
max_expr_genes_u: float = np.inf,
max_expr_genes_p: float = np.inf,
shared_count: Union[int, None] = None,
) -> anndata.AnnData:
"""Select valid cells based on a collection of filters.
Args:
adata: an AnnData object
filter_bool: a boolean array from the user to select cells for downstream analysis. Defaults to None.
layer: the data from a particular layer (include X) used for feature selection. Defaults to "all".
keep_filtered: whether to keep cells that don't pass the filtering in the adata object. Defaults to False.
min_expr_genes_s: minimal number of genes with expression for a cell in the data from the spliced layer (also
used for X). Defaults to 50.
min_expr_genes_u: minimal number of genes with expression for a cell in the data from the unspliced layer.
Defaults to 25.
min_expr_genes_p: minimal number of genes with expression for a cell in the data from the protein layer.
Defaults to 1.
max_expr_genes_s: maximal number of genes with expression for a cell in the data from the spliced layer (also
used for X). Defaults to np.inf.
max_expr_genes_u: maximal number of genes with expression for a cell in the data from the unspliced layer.
Defaults to np.inf.
max_expr_genes_p: maximal number of protein with expression for a cell in the data from the protein layer.
Defaults to np.inf.
shared_count: the minimal shared number of counts for each cell across genes between layers. Defaults to None.
Returns:
An updated AnnData object with `pass_basic_filter` as a new column in .var attribute to indicate the selection
of cells for downstream analysis. adata will be subsetted with only the cells pass filtering if keep_filtered is
set to be False.
"""
detected_bool = np.ones(adata.X.shape[0], dtype=bool)
detected_bool = (detected_bool) & (
((adata.X > 0).sum(1) >= min_expr_genes_s) & ((adata.X > 0).sum(1) <= max_expr_genes_s)
).flatten()
if ("spliced" in adata.layers.keys()) & (layer == "spliced" or layer == "all"):
detected_bool = (
detected_bool
& (
((adata.layers["spliced"] > 0).sum(1) >= min_expr_genes_s)
& ((adata.layers["spliced"] > 0).sum(1) <= max_expr_genes_s)
).flatten()
)
if ("unspliced" in adata.layers.keys()) & (layer == "unspliced" or layer == "all"):
detected_bool = (
detected_bool
& (
((adata.layers["unspliced"] > 0).sum(1) >= min_expr_genes_u)
& ((adata.layers["unspliced"] > 0).sum(1) <= max_expr_genes_u)
).flatten()
)
if ("protein" in adata.obsm.keys()) & (layer == "protein" or layer == "all"):
detected_bool = (
detected_bool
& (
((adata.obsm["protein"] > 0).sum(1) >= min_expr_genes_p)
& ((adata.obsm["protein"] > 0).sum(1) <= max_expr_genes_p)
).flatten()
)
if shared_count is not None:
layers = DynamoAdataKeyManager.get_available_layer_keys(adata, layer, False)
detected_bool = detected_bool & get_inrange_shared_counts_mask(adata, layers, shared_count, "cell")
filter_bool = filter_bool & detected_bool if filter_bool is not None else detected_bool
filter_bool = np.array(filter_bool).flatten()
if keep_filtered:
adata.obs["pass_basic_filter"] = filter_bool
else:
adata._inplace_subset_obs(filter_bool)
adata.obs["pass_basic_filter"] = True
return adata
@deprecated
def filter_genes_by_outliers_legacy(*args, **kwargs):
return _filter_genes_by_outliers_legacy(*args, **kwargs)
def _filter_genes_by_outliers_legacy(
adata: anndata.AnnData,
filter_bool: Union[np.ndarray, None] = None,
layer: str = "all",
min_cell_s: int = 1,
min_cell_u: int = 1,
min_cell_p: int = 1,
min_avg_exp_s: float = 1e-10,
min_avg_exp_u: float = 0,
min_avg_exp_p: float = 0,
max_avg_exp: float = np.inf,
min_count_s: int = 0,
min_count_u: int = 0,
min_count_p: int = 0,
shared_count: int = 30,
) -> anndata.AnnData:
"""Basic filter of genes based a collection of expression filters.
Args:
adata: an Anndata object
filter_bool: a boolean array from the user to select genes for downstream analysis. Defaults to None.
layer: the data from a particular layer (include X) used for feature selection. Defaults to "all".
min_cell_s: minimal number of cells with expression for the data in the spliced layer (also used for X).
Defaults to 1.
min_cell_u: minimal number of cells with expression for the data in the unspliced layer. Defaults to 1.
min_cell_p: minimal number of cells with expression for the data in the protein layer. Defaults to 1.
min_avg_exp_s: minimal average expression across cells for the data in the spliced layer (also used for X).
Defaults to 1e-10.
min_avg_exp_u: minimal average expression across cells for the data in the unspliced layer. Defaults to 0.
min_avg_exp_p: minimal average expression across cells for the data in the protein layer. Defaults to 0.
max_avg_exp: maximal average expression across cells for the data in all layers (also used for X). Defaults to
np.inf.
min_count_s: minimal number of counts (UMI/expression) for the data in the spliced layer (also used for X).
Defaults to 0.
min_count_u: minimal number of counts (UMI/expression) for the data in the unspliced layer. Defaults to 0.
min_count_p: minimal number of counts (UMI/expression) for the data in the protein layer. Defaults to 0.
shared_count: the minimal shared number of counts for each genes across cell between layers. Defaults to 30.
Returns:
An updated AnnData object with use_for_pca as a new column in .var attributes to indicate the selection of genes
for downstream analysis. adata will be subsetted with only the genes pass filter if keep_unflitered is set to be
False.
"""
detected_bool = np.ones(adata.shape[1], dtype=bool)
detected_bool = (detected_bool) & np.array(
((adata.X > 0).sum(0) >= min_cell_s)
& (adata.X.mean(0) >= min_avg_exp_s)
& (adata.X.mean(0) <= max_avg_exp)
& (adata.X.sum(0) >= min_count_s)
).flatten()
# add our filtering for labeling data below
if "spliced" in adata.layers.keys() and (layer == "spliced" or layer == "all"):
detected_bool = (
detected_bool
& np.array(
((adata.layers["spliced"] > 0).sum(0) >= min_cell_s)
& (adata.layers["spliced"].mean(0) >= min_avg_exp_s)
& (adata.layers["spliced"].mean(0) <= max_avg_exp)
& (adata.layers["spliced"].sum(0) >= min_count_s)
).flatten()
)
if "unspliced" in adata.layers.keys() and (layer == "unspliced" or layer == "all"):
detected_bool = (
detected_bool
& np.array(
((adata.layers["unspliced"] > 0).sum(0) >= min_cell_u)
& (adata.layers["unspliced"].mean(0) >= min_avg_exp_u)
& (adata.layers["unspliced"].mean(0) <= max_avg_exp)
& (adata.layers["unspliced"].sum(0) >= min_count_u)
).flatten()
)
if shared_count is not None:
layers = DynamoAdataKeyManager.get_available_layer_keys(adata, "all", False)
tmp = get_inrange_shared_counts_mask(adata, layers, shared_count, "gene")
if tmp.sum() > 2000:
detected_bool &= tmp
else:
# in case the labeling time is very short for pulse experiment or
# chase time is very long for degradation experiment.
tmp = get_inrange_shared_counts_mask(
adata,
list(set(layers).difference(["new", "labelled", "labeled"])),
shared_count,
"gene",
)
detected_bool &= tmp
# The following code need to be updated
# just remove genes that are not following the protein criteria
if "protein" in adata.obsm.keys() and layer == "protein":
detected_bool = (
detected_bool
& np.array(
((adata.obsm["protein"] > 0).sum(0) >= min_cell_p)
& (adata.obsm["protein"].mean(0) >= min_avg_exp_p)
& (adata.obsm["protein"].mean(0) <= max_avg_exp)
& (adata.layers["protein"].sum(0) >= min_count_p) # TODO potential bug confirmation: obsm?
).flatten()
)
filter_bool = filter_bool & detected_bool if filter_bool is not None else detected_bool
adata.var["pass_basic_filter"] = np.array(filter_bool).flatten()
return adata
@deprecated
def recipe_monocle(*args, **kwargs):
return _recipe_monocle_legacy(*args, **kwargs)
def _recipe_monocle_legacy(
adata: anndata.AnnData,
reset_X: bool = False,
tkey: Union[str, None] = None,
t_label_keys: Union[str, List[str], None] = None,