/
analysis.py
2470 lines (2204 loc) · 118 KB
/
analysis.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 copy import deepcopy
import warnings
import logging
import numpy as np
from scipy.spatial.distance import pdist, squareform
from scipy.stats import norm as normal
import scipy.stats
from scipy import sparse
import matplotlib
import matplotlib.pyplot as plt
from sklearn.svm import SVR
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.neighbors import NearestNeighbors
from numba import jit
import loompy
from .neighbors import knn_distance_matrix, connectivity_to_weights, convolve_by_sparse_weights, BalancedKNN
from .estimation import fit_slope, fit_slope_offset, fit_slope_weighted, fit_slope_weighted_offset
from .estimation import clusters_stats
from .estimation import colDeltaCor, colDeltaCorSqrt, colDeltaCorLog10, colDeltaCorpartial, colDeltaCorSqrtpartial, colDeltaCorLog10partial
from .diffusion import Diffusion
from .serialization import dump_hdf5, load_hdf5
from typing import *
class VelocytoLoom:
"""A convenient object to store the data of a velocyto loom file.
Data will be stored in memory
Examples
--------
For usage examples consult the documentation
Attributes
----------
S: np.ndarray
Expressed spliced molecules
U: np.ndarray
Unspliced molecule count
A: np.ndarray
Ambiguous molecule count
ca: dict
Column attributes of the loom file
ra: dict
Row attributes of the loom file
loom_filepath: str
The original path the loom files has been read from
initial_cell_size: int
The sum of spliced molecules
initial_Ucell_size: int
The sum of unspliced molecules
"""
def __init__(self, loom_filepath: str) -> None:
self.loom_filepath = loom_filepath
ds = loompy.connect(self.loom_filepath)
self.S = ds.layer["spliced"][:, :]
self.U = ds.layer["unspliced"][:, :]
self.A = ds.layer["ambiguous"][:, :]
self.ca = dict(ds.col_attrs.items())
self.ra = dict(ds.row_attrs.items())
ds.close()
self.initial_cell_size = self.S.sum(0)
self.initial_Ucell_size = self.U.sum(0)
try:
if np.mean(self.ca["_Valid"]) < 1:
logging.warn(f"fraction of _Valid cells is {np.mean(self.ca['_Valid'])} but all will be taken in consideration")
except KeyError:
pass
# logging.debug("The file did not specify the _Valid column attribute")
def to_hdf5(self, filename: str, **kwargs: Dict[str, Any]) -> None:
"""Serialize the VelocytoLoom object in its current state
Arguments
---------
filename:
The name of the file that will be generated (the suffix hdf5 is suggested but not enforced)
**kwargs:
The function accepts the arguments of `dump_hdf5`
Returns
-------
Nothing. It saves a file that can be used to recreate the object in another session.
Note
----
The object can be reloaded calling ``load_velocyto_hdf5(filename)``
"""
dump_hdf5(self, filename, **kwargs)
def plot_fractions(self, save2file: str=None) -> None:
"""Plots a barplot showing the abundance of spliced/unspliced molecules in the dataset
Arguments
---------
save2file: str (default: None)
If not None specifies the file path to which plots get saved
Returns
-------
Nothing, it plots a barplot
"""
plt.figure(figsize=(3.2, 5))
try:
chips, chip_ix = np.unique(self.ca["SampleID"], return_inverse=1)
except KeyError:
chips, chip_ix = np.unique([i.split(":")[0] for i in self.ca["CellID"]], return_inverse=1)
n = len(chips)
for i in np.unique(chip_ix):
tot_mol_cell_submatrixes = [X[:, chip_ix == i].sum(0) for X in [self.S, self.A, self.U]]
total = np.sum(tot_mol_cell_submatrixes, 0)
_mean = [np.mean(j / total) for j in tot_mol_cell_submatrixes]
_std = [np.std(j / total) for j in tot_mol_cell_submatrixes]
plt.ylabel("Fraction")
plt.bar(np.linspace(-0.2, 0.2, n)[i] + np.arange(3), _mean, 0.5 / (n * 1.05), label=chips[i])
plt.errorbar(np.linspace(-0.2, 0.2, n)[i] + np.arange(3), _mean, _std, c="k", fmt="none", lw=1, capsize=2)
# Hide the right and top spines
plt.gca().spines['right'].set_visible(False)
plt.gca().spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
plt.gca().yaxis.set_ticks_position('left')
plt.gca().xaxis.set_ticks_position('bottom')
plt.gca().spines['left'].set_bounds(0, 0.8)
plt.legend()
plt.xticks(np.arange(3), ["spliced", "ambiguous", "unspliced"])
plt.tight_layout()
if save2file:
plt.savefig(save2file, bbox_inches="tight")
def filter_cells(self, bool_array: np.ndarray) -> None:
"""Filter cells using a boolean array.
Arguments
---------
bool_array: np.ndarray (size )
array describing the cells to keep (True).
Return
------
Nothing but it removes some cells from S and U.
"""
self.S, self.U, self.A = (X[:, bool_array] for X in (self.S, self.U, self.A))
self.initial_cell_size = self.initial_cell_size[bool_array]
self.initial_Ucell_size = self.initial_Ucell_size[bool_array]
try:
self.ts = self.ts[bool_array] # type: np.ndarray
except:
pass
try:
self.size_factor = self.size_factor[bool_array] # type: np.ndarray
except:
pass
self.ca = {k: v[bool_array] for k, v in self.ca.items()}
try:
self.cluster_labels = self.cluster_labels[bool_array] # type: np.ndarray
self.colorandum = self.colorandum[bool_array, :] # type: np.ndarray
except AttributeError:
pass
def set_clusters(self, cluster_labels: np.ndarray, cluster_colors_dict: Dict[str, List[float]]=None, colormap: Any=None) -> None:
"""Utility function to set cluster labels, names and colormap
Arguments
---------
cluster_labels: np.ndarray
A vector of strings containing the name of the cluster for each cells
cluster_colors_dict: dict[str, List[float]]
A mapping cluster_name -> rgb_color_triplet for example "StemCell":[0.65,0.1,0.4]
colormap:
(optional)
In alternative to cluster_colors_dict a colormap object (e.g. from matplotlib or similar callable) can be passed
Returns
-------
Nothing, the attributes `cluster_labels, colorandum, cluster_ix, cluster_uid` are created.
"""
self.cluster_labels = np.array(cluster_labels)
if self.cluster_labels.dtype == "O": # Fixes a bug when importing from pandas
self.cluster_labels = self.cluster_labels.astype(np.string_)
if cluster_colors_dict:
self.colorandum = np.array([cluster_colors_dict[i] for i in cluster_labels])
self.cluster_colors_dict = cluster_colors_dict
self.colormap = None
else:
if colormap is None:
self.colorandum = colormap_fun(self.cluster_ix)
cluster_uid = self.cluster_uid
self.cluster_colors_dict = {cluster_uid[i]: colormap_fun(i) for i in range(len(cluster_uid))}
else:
self.colormap = colormap
self.colorandum = self.colormap(self.cluster_ix)
cluster_uid = self.cluster_uid
self.cluster_colors_dict = {cluster_uid[i]: self.colormap(i) for i in range(len(cluster_uid))}
@property
def cluster_uid(self) -> np.ndarray:
clusters_uid = np.unique(self.cluster_labels)
return clusters_uid
@property
def cluster_ix(self) -> np.ndarray:
_, cluster_ix = np.unique(self.cluster_labels, return_inverse=True)
return cluster_ix
def score_cv_vs_mean(self, N: int=3000, min_expr_cells: int=2, max_expr_avg: float=20, min_expr_avg: int=0, svr_gamma: float=None,
winsorize: bool=False, winsor_perc: Tuple[float, float]=(1, 99.5), sort_inverse: bool=False, which: str="S",
plot: bool=False) -> np.ndarray:
"""Rank genes on the basis of a CV vs mean fit, it uses a nonparametric fit (Support Vector Regression)
Arguments
---------
N: int
the number to select
min_expr_cells: int, (default=2)
minimum number of cells that express that gene for it to be considered in the fit
min_expr_avg: int, (default=0)
The minimum average accepted before discarding from the the gene as not expressed
max_expr_avg: float, (default=20)
The maximum average accepted before discarding from the the gene as house-keeping/outlier
svr_gamma: float
the gamma hyper-parameter of the SVR
winsorize: bool
Wether to winsorize the data for the cv vs mean model
winsor_perc: tuple, default=(1, 99.5)
the up and lower bound of the winsorization
sort_inverse: bool, (default=False)
if True it sorts genes from less noisy to more noisy (to use for size estimation not for feature selection)
which: bool, (default="S")
it performs the same cv_vs mean procedure on spliced "S" or unspliced "U" count
"both" is NOT supported here because most often S the two procedure would have different parameters
(notice that default parameters are good heuristics only for S)
plot: bool, default=False
whether to show a plot
Returns
-------
Nothing but it creates the attributes
cv_mean_score: np.ndarray
How much the observed CV is higher than the one predicted by a noise model fit to the data
cv_mean_selected: np.ndarray bool
on the basis of the N parameter
Note: genes excluded from the fit will have in the output the same score as the lowest scoring gene in the dataset.
To perform the filtering use the method `filter_genes`
"""
if which == "S":
if winsorize:
if min_expr_cells <= ((100 - winsor_perc[1]) * self.S.shape[1] * 0.01):
min_expr_cells = int(np.ceil((100 - winsor_perc[1]) * self.S.shape[0] * 0.01)) + 2
logging.debug(f"min_expr_cells is too low for winsorization with upper_perc ={winsor_perc[1]}, upgrading to min_expr_cells ={min_expr_cells}")
detected_bool = ((self.S > 0).sum(1) > min_expr_cells) & (self.S.mean(1) < max_expr_avg) & (self.S.mean(1) > min_expr_avg)
Sf = self.S[detected_bool, :]
if winsorize:
down, up = np.percentile(Sf, winsor_perc, 1)
Sfw = np.clip(Sf, down[:, None], up[:, None])
mu = Sfw.mean(1)
sigma = Sfw.std(1, ddof=1)
else:
mu = Sf.mean(1)
sigma = Sf.std(1, ddof=1)
cv = sigma / mu
log_m = np.log2(mu)
log_cv = np.log2(cv)
if svr_gamma is None:
svr_gamma = 150. / len(mu)
logging.debug(f"svr_gamma set to {svr_gamma}")
# Fit the Support Vector Regression
clf = SVR(gamma=svr_gamma)
clf.fit(log_m[:, None], log_cv)
fitted_fun = clf.predict
ff = fitted_fun(log_m[:, None])
score = log_cv - ff
if sort_inverse:
score = - score
nth_score = np.sort(score)[::-1][N]
if plot:
scatter_viz(log_m[score > nth_score], log_cv[score > nth_score], s=3, alpha=0.4, c="tab:red")
scatter_viz(log_m[score <= nth_score], log_cv[score <= nth_score], s=3, alpha=0.4, c="tab:blue")
mu_linspace = np.linspace(np.min(log_m), np.max(log_m))
plt.plot(mu_linspace, fitted_fun(mu_linspace[:, None]), c="k")
plt.xlabel("log2 mean S")
plt.ylabel("log2 CV S")
self.cv_mean_score = np.zeros(detected_bool.shape)
self.cv_mean_score[~detected_bool] = np.min(score) - 1e-16
self.cv_mean_score[detected_bool] = score
self.cv_mean_selected = self.cv_mean_score >= nth_score
else:
if winsorize:
if min_expr_cells <= ((100 - winsor_perc[1]) * self.U.shape[1] * 0.01):
min_expr_cells = int(np.ceil((100 - winsor_perc[1]) * self.U.shape[0] * 0.01)) + 2
logging.debug(f"min_expr_cells is too low for winsorization with upper_perc ={winsor_perc[1]}, upgrading to min_expr_cells ={min_expr_cells}")
detected_bool = ((self.U > 0).sum(1) > min_expr_cells) & (self.U.mean(1) < max_expr_avg) & (self.U.mean(1) > min_expr_avg)
Uf = self.U[detected_bool, :]
if winsorize:
down, up = np.percentile(Uf, winsor_perc, 1)
Ufw = np.clip(Uf, down[:, None], up[:, None])
mu = Ufw.mean(1)
sigma = Ufw.std(1, ddof=1)
else:
mu = Uf.mean(1)
sigma = Uf.std(1, ddof=1)
cv = sigma / mu
log_m = np.log2(mu)
log_cv = np.log2(cv)
if svr_gamma is None:
svr_gamma = 150. / len(mu)
logging.debug(f"svr_gamma set to {svr_gamma}")
# Fit the Support Vector Regression
clf = SVR(gamma=svr_gamma)
clf.fit(log_m[:, None], log_cv)
fitted_fun = clf.predict
ff = fitted_fun(log_m[:, None])
score = log_cv - ff
if sort_inverse:
score = - score
nth_score = np.sort(score)[::-1][N]
if plot:
scatter_viz(log_m[score > nth_score], log_cv[score > nth_score], s=3, alpha=0.4, c="tab:red")
scatter_viz(log_m[score <= nth_score], log_cv[score <= nth_score], s=3, alpha=0.4, c="tab:blue")
mu_linspace = np.linspace(np.min(log_m), np.max(log_m))
plt.plot(mu_linspace, fitted_fun(mu_linspace[:, None]), c="k")
plt.xlabel("log2 mean U")
plt.ylabel("log2 CV U")
self.Ucv_mean_score = np.zeros(detected_bool.shape)
self.Ucv_mean_score[~detected_bool] = np.min(score) - 1e-16
self.Ucv_mean_score[detected_bool] = score
self.Ucv_mean_selected = self.Ucv_mean_score >= nth_score
def robust_size_factor(self, pc: float=0.1, which: str="both") -> None:
"""Calculates a size factor in a similar way of Anders and Huber 2010
Arguments
--------
pc: float, default=0.1
The pseudocount to add to the expression before taking the log for the purpose of the size factor calculation
which: str, default="both"
For which counts estimate the normalization size factor. It can be "both", "S" or "U"
Returns
-------
Nothing but it creates the attribute `self.size_factor` and `self.Usize_factor`
normalization is self.S / self.size_factor and is performed by using `self.normalize(relative_size=self.size_factor)`
Note
----
Before running this method `score_cv_vs_mean` need to be run with sort_inverse=True, since only lowly variable genes are used for this size estimation
"""
if which == "both":
Y = np.log2(self.S[self.cv_mean_selected, :] + pc)
Y_avg = Y.mean(1)
self.size_factor: np.ndarray = np.median(2**(Y - Y_avg[:, None]), axis=0)
self.size_factor = self.size_factor / np.mean(self.size_factor)
Y = np.log2(self.U[self.Ucv_mean_selected, :] + pc)
Y_avg = Y.mean(1)
self.Usize_factor: np.ndarray = np.median(2**(Y - Y_avg[:, None]), axis=0)
self.Usize_factor = self.Usize_factor / np.mean(self.Usize_factor)
elif which == "S":
Y = np.log2(self.S[self.cv_mean_selected, :] + pc)
Y_avg = Y.mean(1)
self.size_factor: np.ndarray = np.median(2**(Y - Y_avg[:, None]), axis=0)
self.size_factor = self.size_factor / np.mean(self.size_factor)
elif which == "U":
Y = np.log2(self.U[self.Ucv_mean_selected, :] + pc)
Y_avg = Y.mean(1)
self.Usize_factor: np.ndarray = np.median(2**(Y - Y_avg[:, None]), axis=0)
self.Usize_factor = self.Usize_factor / np.mean(self.Usize_factor)
def score_cluster_expression(self, min_avg_U: float=0.02, min_avg_S: float=0.08) -> np.ndarray:
"""Prepare filtering genes on the basis of cluster-wise expression threshold
Arguments
---------
min_avg_U: float
Include genes that have unspliced average bigger than `min_avg_U` in at least one of the clusters
min_avg_S: float
Include genes that have spliced average bigger than `min_avg_U` in at least one of the clusters
Note: the two conditions are combined by and "&" logical operator
Returns
-------
Nothing but it creates the attribute
clu_avg_selected: np.ndarray bool
The gene cluster that is selected
To perform the filtering use the method `filter_genes`
"""
self.U_avgs, self.S_avgs = clusters_stats(self.U, self.S, self.cluster_uid, self.cluster_ix, size_limit=40)
self.clu_avg_selected = (self.U_avgs.max(1) > min_avg_U) & (self.S_avgs.max(1) > min_avg_S)
def score_detection_levels(self, min_expr_counts: int= 50, min_cells_express: int= 20,
min_expr_counts_U: int= 0, min_cells_express_U: int= 0) -> np.ndarray:
"""Prepare basic filtering of genes on the basis of their detection levels
Arguments
---------
min_expr_counts: float
The minimum number of spliced molecules detected considering all the cells
min_cells_express: float
The minimum number of cells that express spliced molecules of a gene
min_expr_counts_U: float
The minimum number of unspliced molecules detected considering all the cells
min_cells_express_U: float
The minimum number of cells that express unspliced molecules of a gene
Note: the conditions are combined by and "&" logical operator
Returns
-------
Nothing but an attribute self.detection_level_selected is created
To perform the filtering by detection levels use the method `filter_genes`
"""
# Some basic filtering
S_sum = self.S.sum(1)
S_ncells_express = (self.S > 0).sum(1)
U_sum = self.U.sum(1)
U_ncells_express = (self.U > 0).sum(1)
filter_bool = (S_sum >= min_expr_counts) & (S_ncells_express >= min_cells_express) & (U_sum >= min_expr_counts_U) & (U_ncells_express >= min_cells_express_U)
self.detection_level_selected = filter_bool
def filter_genes(self, by_detection_levels: bool=False, by_cluster_expression: bool=False,
by_cv_vs_mean: bool=False, by_custom_array: Any=None, keep_unfiltered: bool=False) -> None:
"""Filter genes taking care that all the matrixes and all the connected annotation get filtered accordingly
Attributes affected: .U, .S, .ra
Arguments
---------
by_detection_levels: bool, default=False
filter genes by the score_detection_levels result
by_cluster_expression: bool, default=False
filter genes by the score_cluster_expression result
by_cv_vs_mean: bool, default=False
filter genes by the score_cluster_expression result
by_custom_array, np.ndarray, default=None
provide a boolean or index array
keep_unfiltered: bool, default=False
whether to create attributes self.S_prefilter, self.U_prefilter, self.ra_prefilter,
(array will be made sparse to minimize memory footprint)
or just overwrite the previous arrays
Returns
-------
Nothing but it updates the self.S, self.U, self.ra attributes
"""
assert np.any([by_detection_levels, by_cluster_expression,
by_cv_vs_mean, (type(by_custom_array) is np.ndarray)]), "At least one of the filtering methods needs to be True"
tmp_filter = np.ones(self.S.shape[0], dtype=bool)
if by_cluster_expression:
assert hasattr(self, "clu_avg_selected"), "clu_avg_selected was not found"
logging.debug("Filtering by cluster expression")
tmp_filter = tmp_filter & self.clu_avg_selected
if by_cv_vs_mean:
assert hasattr(self, "cv_mean_selected"), "cv_mean_selected was not found"
logging.debug("Filtering by cv vs mean")
tmp_filter = tmp_filter & self.cv_mean_selected
if by_detection_levels:
assert hasattr(self, "detection_level_selected"), "detection_level_selected was not found"
logging.debug("Filtering by detection level")
tmp_filter = tmp_filter & self.detection_level_selected
if type(by_custom_array) is np.ndarray:
if by_custom_array.dtype == bool:
logging.debug("Filtering by custom boolean array")
tmp_filter = tmp_filter & by_custom_array
elif by_custom_array.dtype == int:
logging.debug("Filtering by custom index array")
bool_negative = ~np.in1d(np.arange(len(tmp_filter)), by_custom_array)
tmp_filter[bool_negative] = False
if keep_unfiltered:
if hasattr(self, "U_prefilter"):
logging.debug("Attributes *_prefilter are already present and were overwritten")
self.U_prefilter = sparse.csr_matrix(self.U)
self.S_prefilter = sparse.csr_matrix(self.S)
self.ra_prefilter = deepcopy(self.ra)
self.U = self.U[tmp_filter, :]
self.S = self.S[tmp_filter, :]
self.ra = {k: v[tmp_filter] for k, v in self.ra.items()}
def custom_filter_attributes(self, attr_names: List[str], bool_filter: np.ndarray) -> None:
"""Filter attributes given a boolean array. attr_names can be dictionaries or numpy arrays
Arguments
---------
attr_names: List[str]
a list of the attributes to be modified. The can be
1d arrays, dictionary of 1d arrays, ndarrays, will be filtered by axis=0
if .T is specified by axis=-1
bool_filter:
the boolean filter to be applied
Returns
-------
Nothing it filters the specified attributes
"""
transpose_flag = False
for attr in attr_names:
if attr[-2:] == ".T":
obj = getattr(self, attr[:-2])
transpose_flag = True
else:
obj = getattr(self, attr)
transpose_flag = False
if type(obj) is dict:
setattr(self, attr, {k: v[bool_filter] for k, v in obj.items()})
elif type(obj) is np.ndarray:
if len(obj.shape) > 1:
if transpose_flag:
setattr(self, attr, obj[..., bool_filter])
else:
setattr(self, attr, obj[bool_filter, :])
else:
setattr(self, attr, obj[bool_filter])
else:
raise NotImplementedError(f"The filtering of an object of type {type(obj)} is not defined")
def _normalize_S(self, size: bool=True, log: bool=True, pcount: float=1, relative_size: Any=None, target_size: Any=None) -> np.ndarray:
"""Internal function for the spliced molecule filtering. The `normalize` method should be used as a standard interface"""
if size:
if type(relative_size) is np.ndarray:
self.cell_size = relative_size
else:
self.cell_size = self.S.sum(0)
if target_size is None:
self.avg_size = self.cell_size.mean()
else:
self.avg_size = target_size
self.norm_factor = self.avg_size / self.cell_size
else:
self.norm_factor = 1
self.S_sz = self.norm_factor * self.S
if log:
self.S_norm = np.log2(self.S_sz + pcount) # np.sqrt(S_sz )# np.log2(S_sz + 1)
def _normalize_U(self, size: bool=True, log: bool=True, pcount: float=1, use_S_size: bool=False, relative_size: np.ndarray=None, target_size: Any=None) -> np.ndarray:
"""Internal function for the unspliced molecule filtering. The `normalize` method should be used as a standard interface"""
if size:
if use_S_size:
if hasattr(self, "cell_size"):
cell_size = self.cell_size
else:
cell_size = self.S.sum(0)
elif type(relative_size) is np.ndarray:
cell_size = relative_size
else:
cell_size = self.U.sum(0)
self.Ucell_size = cell_size
if target_size is None:
avg_size = cell_size.mean()
else:
avg_size = target_size
self.Uavg_size = avg_size
with warnings.catch_warnings():
warnings.simplefilter("ignore")
norm_factor = avg_size / cell_size
else:
norm_factor = 1
self.Unorm_factor = norm_factor
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.U_sz = norm_factor * self.U
self.U_sz[~np.isfinite(self.U_sz)] = 0 # it happened only once but it is here as a precaution
if log:
self.U_norm = np.log2(self.U_sz + pcount) # np.sqrt(S_sz )# np.log2(S_sz + 1)
def _normalize_Sx(self, size: bool=True, log: bool=True, pcount: float=1, relative_size: Any=None, target_size: Any=None) -> np.ndarray:
"""Internal function for the smoothed spliced molecule filtering. The `normalize` method should be used as a standard interface"""
if size:
if relative_size:
self.xcell_size = relative_size
else:
self.xcell_size = self.Sx.sum(0)
if target_size is None:
self.xavg_size = self.xcell_size.mean()
else:
self.xavg_size = target_size
self.xnorm_factor = self.xavg_size / self.xcell_size
else:
self.xnorm_factor = 1
self.Sx_sz = self.xnorm_factor * self.Sx
if log:
self.Sx_norm = np.log2(self.Sx_sz + pcount) # np.sqrt(S_sz )# np.log2(S_sz + 1)
def _normalize_Ux(self, size: bool=True, log: bool=True, pcount: float=1, use_Sx_size: bool=False, relative_size: Any=None, target_size: Any=None) -> np.ndarray:
"""Internal function for the smoothed unspliced molecule filtering. The `normalize` method should be used as a standard interface"""
if size:
if use_Sx_size:
if hasattr(self, "cell_size"):
cell_size = self.xcell_size
else:
cell_size = self.Sx.sum(0)
elif type(relative_size) is np.ndarray:
cell_size = relative_size
else:
cell_size = self.Ux.sum(0)
self.xUcell_size = cell_size
if target_size is None:
avg_size = cell_size.mean()
else:
avg_size = target_size
self.xUavg_size = avg_size
with warnings.catch_warnings():
warnings.simplefilter("ignore")
norm_factor = avg_size / cell_size
else:
norm_factor = 1
self.xUnorm_factor = norm_factor
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.Ux_sz = norm_factor * self.Ux
self.Ux_sz[~np.isfinite(self.Ux_sz)] = 0 # it happened only once but it is here as a precaution
if log:
self.Ux_norm = np.log2(self.Ux_sz + pcount) # np.sqrt(S_sz )# np.log2(S_sz + 1)
def normalize(self, which: str="both", size: bool=True, log: bool=True, pcount: float=1,
relative_size: np.ndarray=None, use_S_size_for_U: bool=False, target_size: Tuple[float, float]=(None, None)) -> None:
"""Normalization interface
Arguments
---------
which: either 'both', 'S', 'U', "imputed", "Sx", "Ux"
which attributes to normalize.
"both" corresponds to "S" and "U"
"imputed" corresponds to "Sx" and "Ux"
size: bool
perform size normalization
log: bool
perform log normalization (if size==True, this comes after the size normalization)
pcount: int, default: 1
The extra count added when logging (log2)
relative_size: np.ndarray, default=None
if None it calculate the sums the molecules per cell (self.S.sum(0))
if an array is provided it is used for the normalization
use_S_size_for_U: bool
U is size normalized using the sum of molecules of S
target_size: float or Tuple[float, float] (depending if the which parameter implies 1 or more normalizations)
the size of the cells after normalization will be set to.
If tuple the order is (S, U) or (Sx, Ux)
If None the target size is the average of the cell sizes
Returns
-------
Nothing but creates the attributes `U_norm`, `U_sz` and `S_norm`, "S_sz"
or `Ux_norm`, `Ux_sz` and `Sx_norm`, "Sx_sz"
"""
if which == "both":
self._normalize_S(size=size, log=log, pcount=pcount, relative_size=relative_size, target_size=target_size[0])
self._normalize_U(size=size, log=log, pcount=pcount, use_S_size=use_S_size_for_U, relative_size=relative_size, target_size=target_size[1])
if "S" == which:
self._normalize_S(size=size, log=log, pcount=pcount, relative_size=relative_size, target_size=target_size[0])
if "U" == which:
self._normalize_U(size=size, log=log, pcount=pcount, use_S_size=use_S_size_for_U, relative_size=relative_size, target_size=target_size[1])
if which == "imputed":
self._normalize_Sx(size=size, log=log, pcount=pcount, relative_size=relative_size, target_size=target_size[0])
self._normalize_Ux(size=size, log=log, pcount=pcount, use_Sx_size=use_S_size_for_U, relative_size=relative_size, target_size=target_size[1])
if "Sx" == which:
self._normalize_Sx(size=size, log=log, pcount=pcount, relative_size=relative_size, target_size=target_size[0])
if "Ux" == which:
self._normalize_Ux(size=size, log=log, pcount=pcount, use_Sx_size=use_S_size_for_U, relative_size=relative_size, target_size=target_size[1])
def perform_PCA(self, which: str="S_norm", n_components: int=None, div_by_std: bool=False) -> None:
"""Perform PCA (cells as samples)
Arguments
---------
which: str, default="S_norm"
The name of the attribute to use for the calculation (e.g. S_norm or Sx_norm)
n_components: int, default=None
Number of components to keep. If None all the components will be kept.
div_by_std: bool, default=False
Wether to divide by standard deviation
Returns
-------
Returns nothing but it creates the attributes:
pca: np.ndarray
a numpy array of shape (cells, npcs)
"""
X = getattr(self, which)
self.pca = PCA(n_components=n_components)
if div_by_std:
self.pcs = self.pca.fit_transform(X.T / X.std(0))
else:
self.pcs = self.pca.fit_transform(X.T)
def normalize_by_total(self, min_perc_U: float=0.5, plot: bool=False, skip_low_U_pop: bool=True, same_size_UnS: bool=False) -> None:
"""Normalize the cells using the (initial) total molecules as size estimate
Arguments
---------
min_perc_U: float
the percentile to use as a minimum value allowed for the size normalization
plot: bool, default=False
whether
skip_low_U_pop: bool, default=True
population with very low unspliced will not be multiplied by the scaling factor to avoid predicting very strong
velocity just as a consequence of low detection
same_size_UnS: bool, default=False
Each cell is set tot have the same total number of spliced and unspliced molecules
Returns
-------
Returns nothing but it creates the attributes:
small_U_pop: np.ndarray
Cells with extremely low unspliced count
"""
target_cell_size = np.median(self.initial_cell_size)
min_Ucell_size = np.percentile(self.initial_Ucell_size, min_perc_U)
if min_Ucell_size < 2:
raise ValueError(f"min_perc_U={min_perc_U} corresponds to total Unspliced of 1 molecule of less. Please choose higher value or filter our these cell")
bool_f = self.initial_Ucell_size < min_Ucell_size
self.small_U_pop = bool_f
if same_size_UnS:
target_Ucell_size = target_cell_size # 0.15 * target_cell_size
else:
target_Ucell_size = np.median(self.initial_Ucell_size[~self.small_U_pop]) # 0.15 * target_cell_size
if plot:
plt.figure(None, (12, 6))
plt.subplot(121)
plt.scatter(self.initial_cell_size, self.initial_Ucell_size, s=3, alpha=0.1)
plt.xlabel("total spliced")
plt.ylabel("total unspliced")
plt.scatter(self.initial_cell_size[bool_f], self.initial_Ucell_size[bool_f], s=3, alpha=0.1)
plt.subplot(122)
plt.scatter(np.log2(self.initial_cell_size), np.log2(self.initial_Ucell_size), s=7, alpha=0.3)
plt.scatter(np.log2(self.initial_cell_size)[bool_f], np.log2(self.initial_Ucell_size)[bool_f], s=7, alpha=0.3)
plt.xlabel("log total spliced")
plt.ylabel("log total unspliced")
self._normalize_S(relative_size=self.initial_cell_size,
target_size=target_cell_size)
if skip_low_U_pop:
self._normalize_U(relative_size=np.clip(self.initial_Ucell_size, min_Ucell_size, None),
target_size=target_Ucell_size)
else:
self._normalize_U(relative_size=self.initial_Ucell_size,
target_size=target_Ucell_size)
def normalize_by_size_factor(self, min_perc_U: float=0.5, plot: bool=False, skip_low_U_pop: bool=True, same_size_UnS: bool=False) -> None:
"""Normalize the cells using the (initial) size_factor
Arguments
---------
min_perc_U: float
the percentile to use as a minimum value allowed for the size normalization
plot: bool, default=False
whether
skip_low_U_pop: bool, default=True
population with very low unspliced will not be multiplied by the scaling factor to avoid predicting very strong
velocity just as a consequence of low detection
same_size_UnS: bool, default=False
Each cell is set tot have the same total number of spliced and unspliced molecules
Returns
-------
Returns nothing but it creates the attributes:
small_U_pop: np.ndarray
Cells with extremely low unspliced count
"""
cell_size = self.S.sum(0)
Ucell_size = self.U.sum(0)
target_cell_size = np.median(cell_size)
min_Ucell_size = np.percentile(Ucell_size, min_perc_U)
if min_Ucell_size < 2:
raise ValueError(f"min_perc_U={min_perc_U} corresponds to total Unspliced of 1 molecule of less. Please choose higher value or filter our these cell")
bool_f = Ucell_size < min_Ucell_size
self.small_U_pop = bool_f
if same_size_UnS:
target_Ucell_size = target_cell_size # 0.15 * target_cell_size
else:
target_Ucell_size = np.median(Ucell_size[~self.small_U_pop])
if plot:
plt.figure(None, (12, 6))
plt.subplot(121)
plt.scatter(cell_size, Ucell_size, s=3, alpha=0.1)
plt.xlabel("S cell_size")
plt.ylabel("U cell_size")
plt.scatter(cell_size[bool_f], Ucell_size[bool_f], s=3, alpha=0.1)
plt.subplot(122)
plt.scatter(np.log2(cell_size), np.log2(Ucell_size), s=7, alpha=0.3)
plt.scatter(np.log2(cell_size)[bool_f], np.log2(Ucell_size)[bool_f], s=7, alpha=0.3)
plt.xlabel("log S cell_size")
plt.ylabel("log U cell_size")
self._normalize_S(relative_size=self.size_factor,
target_size=target_cell_size)
if skip_low_U_pop:
self._normalize_U(relative_size=np.clip(self.initial_Ucell_size, min_Ucell_size, None),
target_size=target_Ucell_size)
else:
self._normalize_U(relative_size=self.initial_Ucell_size,
target_size=target_Ucell_size)
def adjust_totS_totU(self, skip_low_U_pop: bool=True, normalize_total: bool=False,
fit_with_low_U: bool=True,
svr_C: float=100, svr_gamma: float=1e-6, plot: bool=False) -> None:
"""Adjust the spliced count on the base of the relation S_sz_tot and U_sz_tot
Arguments
---------
skip_low_U_pop: bool, default=True
Do not normalize the low unspliced molecules cell population to avoid overinflated values
normalize_total: bool, default=False
If this is True the function results in a normalization by median of both U and S.
NOTE: Legacy compatibility, I might want to split this into a different function.
fit_with_low_U: bool, default=True
Wether to consider the low_U population for the fit
svr_C: float
The C parameter of scikit-learn Support Vector Regression
svr_gamma: float
The gamma parameter of scikit-learn Support Vector Regression
plot: bool
Whether to plot the results of the fit
Returns
-------
Nothing but it modifies the attributes:
U_sz: np.ndarray
"""
svr = SVR(C=svr_C, kernel="rbf", gamma=svr_gamma)
X, y = self.S_sz.sum(0), self.U_sz.sum(0)
if fit_with_low_U:
svr.fit(X[:, None], y)
predicted = svr.predict(X[:, None])
else:
svr.fit(X[~self.small_U_pop, None], y[~self.small_U_pop])
predicted = np.copy(y)
predicted[~self.small_U_pop] = svr.predict(X[~self.small_U_pop, None])
adj_factor = predicted / y
adj_factor[~np.isfinite(adj_factor)] = 1
if skip_low_U_pop:
self.U_sz[:, ~self.small_U_pop] = self.U_sz[:, ~self.small_U_pop] * adj_factor[~self.small_U_pop]
else:
self.U_sz = self.U_sz * adj_factor
if normalize_total:
self.normalize_median(which="renormalize", skip_low_U_pop=skip_low_U_pop)
if plot:
plt.figure(None, (8, 8))
plt.scatter(X, y, s=3, alpha=0.1)
plt.scatter(X, predicted, c="k", s=5, alpha=0.1)
def normalize_median(self, which: str="imputed", skip_low_U_pop: bool=True) -> None:
"""Normalize cell size to the median, for both S and U.
Arguments
---------
which: str, default="imputed"
"imputed" or "renormalized"
skip_low_U_pop: bool=True
Whether to skip the low U population defined in normalize_by_total
Returns
-------
Nothing but it modifies the attributes:
S_sz: np.ndarray
U_sz: np.ndarray
or
Sx_sz: np.ndarray
Ux_sz: np.ndarray
"""
if not hasattr(self, "small_U_pop") and skip_low_U_pop:
self.small_U_pop = np.zeros(self.U_sz.shape[1], dtype=bool)
logging.warning("object does not have the attribute `small_U_pop`, so all the unspliced will be normalized by relative size, this might cause the overinflation the unspliced counts of cells where only few unspliced molecules were detected")
if which == "renormalize":
self.S_sz = self.S_sz * (np.median(self.S_sz.sum(0)) / self.S_sz.sum(0))
if skip_low_U_pop:
self.U_sz[:, ~self.small_U_pop] = self.U_sz[:, ~self.small_U_pop] * (np.median(self.U_sz[:, ~self.small_U_pop].sum(0)) / self.U_sz[:, ~self.small_U_pop].sum(0))
else:
self.U_sz = self.U_sz * (np.median(self.U_sz.sum(0)) / self.U_sz.sum(0))
elif which == "imputed":
self.Sx_sz = self.Sx * (np.median(self.Sx.sum(0)) / self.Sx.sum(0))
if skip_low_U_pop:
self.Ux_sz = np.copy(self.Ux)
self.Ux_sz[:, ~self.small_U_pop] = self.Ux[:, ~self.small_U_pop] * (np.median(self.Ux[:, ~self.small_U_pop].sum(0)) / self.Ux[:, ~self.small_U_pop].sum(0))
else:
self.Ux_sz = self.Ux * (np.median(self.Ux.sum(0)) / self.Ux.sum(0))
def plot_pca(self, dim: List[int]=[0, 1, 2], elev: float=60, azim: float=-140) -> None:
"""Plot 3d PCA
"""
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(self.pcs[:, dim[0]],
self.pcs[:, dim[1]],
self.pcs[:, dim[2]],
c=self.colorandum)
ax.view_init(elev=elev, azim=azim)
def _perform_PCA_imputed(self, n_components: int=None) -> None:
"""Simply performs PCA of `Sx_norm` and save the result as `pcax`"""
self.pcax = PCA(n_components=n_components)
self.pcsx = self.pcax.fit_transform(self.Sx_norm.T)
def _plot_pca_imputed(self, dim: List[int]=[0, 1, 2], elev: float=60, azim: float=-140) -> None:
"""Plot 3d PCA of the smoothed data
"""
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(self.pcsx[:, dim[0]],
self.pcsx[:, dim[1]],
self.pcsx[:, dim[2]],
c=self.colorandum)
ax.view_init(elev=elev, azim=azim)
def knn_imputation(self, k: int=None, pca_space: float=True, metric: str="euclidean", diag: float=1,
n_pca_dims: int=None, maximum: bool=False, size_norm: bool=True,
balanced: bool=False, b_sight: int=None, b_maxl: int=None,
group_constraint: Union[str, np.ndarray]=None, n_jobs: int=8) -> None:
"""Performs k-nn smoothing of the data matrix
Arguments
---------
k: int
number of neighbors. If None the default it is chosen to be `0.025 * Ncells`
pca_space: bool, default=True
if True the knn will be performed in PCA space (`pcs`)
otherwise it will use log2 size normalized data (`S_norm`)
metric: str
"euclidean" or "correlation"
diag: int, default=1
before smoothing this value is substituted in the diagonal of the knn contiguity matrix
Resulting in a reduction of the smoothing effect.
E.g. if diag=8 and k=10 value of Si = (8 * S_i + sum(S_n, with n in 5nn of i)) / (8+5)
maximum: bool, default=False
If True the maximum value of the smoothing and the original matrix entry is taken.
n_pca_dims: int, default=None
number of pca to use for the knn distance metric. If None all pcs will be used. (used only if pca_space == True)
balanced: bool
whether to use BalancedKNN version
b_sight: int
the sight parameter of BalancedKNN (used only if balanced == True)
b_maxl: int
the maxl parameter of BalancedKNN (used only if balanced == True)
group_constraint: str or np.ndarray[int]:
currently implemented only for balanced = True
if "clusters" the the clusters will be used as a constraint so that cells of different clusters cannot be neighbors
if an array of integers of shape vlm.S.shape[1] it will be interpreted as labels of the groups
n_jobs: int, default 8
number of parallel jobs in knn calculation
Returns
-------
Nothing but it creates the attributes:
knn: scipy.sparse.csr_matrix
knn contiguity matrix
knn_smoothing_w: scipy.sparse.lil_matrix
the weights used for the smoothing
Sx: np.ndarray
smoothed spliced
Ux: np.ndarray
smoothed unspliced
"""
N = self.S.shape[1]
if k is None:
k = int(N * 0.025)
if b_sight is None and balanced:
b_sight = np.maximum(int(k * 8), N - 1)
if b_maxl is None and balanced:
b_maxl = np.maximum(int(k * 4), N - 1)
if pca_space:
space = self.pcs[:, :n_pca_dims]
else:
space = self.S_norm.T
if balanced:
if group_constraint is not None:
if isinstance(group_constraint, str) and group_constraint == "clusters":
constraint = np.array(self.cluster_ix)
bknn = BalancedKNN(k=k, sight_k=b_sight, maxl=b_maxl, metric=metric, constraint=constraint, mode="distance", n_jobs=n_jobs)
else:
bknn = BalancedKNN(k=k, sight_k=b_sight, maxl=b_maxl, metric=metric, mode="distance", n_jobs=n_jobs)
bknn.fit(space)