-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
executable file
·1852 lines (1484 loc) · 64.3 KB
/
utils.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
#!/usr/bin/env python3
from bokeh.palettes import Set1, Set2, Set3
from sklearn.gaussian_process.kernels import *
from pathlib import Path
from collections import Iterable
import anndata
import pandas as pd
import numpy as np
import scanpy.api as sc
import matplotlib.pyplot as plt
import re
import os
import scvelo as scv
import scanpy as sc
import pickle
import traceback
import warnings
"""
This contains functions for:
* scoring cell cycle genes
* matching DE genes with known marker genes
* plotting marker genes with support for regular expressions
"""
_inter_hist_js_code="""
// here is where original data is stored
var x = orig.data['values'];
x = x.sort((a, b) => a - b);
var n_bins = bins.value;
var bin_size = (x[x.length - 1] - x[0]) / n_bins;
var hist = new Array(n_bins).fill().map((_, i) => { return 0; });
var l_edges = new Array(n_bins).fill().map((_, i) => { return x[0] + bin_size * i; });
var r_edges = new Array(n_bins).fill().map((_, i) => { return x[0] + bin_size * (i + 1); });
// create the histogram
for (var i = 0; i < x.length; i++) {
for (var j = 0; j < r_edges.length; j++) {
if (x[i] <= r_edges[j]) {
hist[j] += 1;
break;
}
}
}
// make it a density
var sum = hist.reduce((a, b) => a + b, 0);
var deltas = r_edges.map((c, i) => { return c - l_edges[i]; });
// just like in numpy
hist = hist.map((c, i) => { return c / deltas[i] / sum; });
source.data['hist'] = hist;
source.data['l_edges'] = l_edges;
source.data['r_edges'] = r_edges;
source.change.emit();
"""
class Cache():
def __init__(self, cache_dir, ext='.pickle', make_dir=True):
if make_dir and not os.path.exists(cache_dir):
os.makedirs(cache_dir)
self.cache_dir = cache_dir
self._ext = ext
setattr(self, 'pca', self.cache(dict(obsm='X_pca',
varm='PCs',
uns=['pca', 'variance_ratio'],
uns_cache1=['pca', 'variance']),
default_fname='pca',
default_fn=sc.pp.pca))
setattr(self, 'neighbors', self.cache(dict(uns='neighbors'),
default_fname='neighs',
default_fn=sc.pp.neighbors))
setattr(self, 'louvain', self.cache(dict(obs='louvain'),
default_fname='louvain',
default_fn=sc.tl.louvain))
setattr(self, 'umap', self.cache(dict(obsm='X_umap'),
default_fname='umap',
default_fn=sc.tl.umap))
setattr(self, 'diffmap', self.cache(dict(obsm='X_diffmap', uns='diffmap_evals', uns_cache1='iroot'),
default_fname='diffmap',
default_fn=sc.tl.diffmap))
setattr(self, 'expression', self.cache(dict(X=None), default_fname='expression'))
setattr(self, 'pcarr', self._wrap_as_adata(self.cache(dict(obsm='X_pca'),
default_fname='pca_arr',
default_fn=sc.pp.pca),
ret_attr=dict(obsm='X_pca')))
setattr(self, 'paga', self.cache(dict(uns=['paga', 'connectivities'],
uns_cache1=['paga','connectivities_tree'],
uns_cache2=['paga', 'groups'],
uns_cache3=['paga', 'pos']),
default_fn=sc.tl.paga,
default_fname='paga'))
setattr(self, 'moments', self.cache(dict(uns='pca',
uns_cache1='neighbors',
obsm='X_pca',
varm='PCs',
layers='Ms',
layers_cache1='Mu'),
default_fn=scv.pp.moments,
default_fname='moments'))
setattr(self, 'velocity', self.cache(dict(var='velocity_gamma',
var_cache1='velocity_r2',
var_cache2='velocity_genes',
layers='velocity'),
default_fn=scv.tl.velocity,
default_fname='velo'))
setattr(self, 'velocity_graph', self.cache(dict(uns=re.compile(r'(.+)_graph$'),
uns_cache1=re.compile('(.+)_graph_neg$')),
default_fn=scv.tl.velocity_graph,
default_fname='velo_graph'))
setattr(self, 'draw_graph', self.cache(dict(obsm=re.compile(r'^X_draw_graph_(.+)$'),
uns='draw_graph'),
default_fn=sc.tl.draw_graph,
default_fname='draw_graph'))
def __repr__(self):
return f"{self.__class__.__name__}(dir='{self._cache_dir}', ext='{self._ext}')"
def _wrap_as_adata(self, fn, *, ret_attr):
def wrapper(*args, **kwargs):
if len(args) > 0:
adata = args[0] if isinstance(args[0], np.ndarray) else kwargs.get('adata')
else:
adata = kwargs.get('adata')
assert isinstance(adata, np.ndarray), f'Expected `{adata}` to be of type `np.ndarray`.'
# wrap the np.ndarray in AnnData
adata = anndata.AnnData(adata)
if isinstance(args[0], np.ndarray):
# can't assing to tuple
args = list(args)
args[0] = adata
args = tuple(args)
else:
kwargs['adata'] = adata
res = fn(*args, **kwargs)
# if copy was specified, operate on that object
# other use the original (inplace modification)
res = res if res is not None else adata
out = []
# currently, only 1 key supported
for attr, k in ret_attr.items():
out.append(getattr(res, attr)[k])
if len(ret_attr) == 1:
return out[0]
return tuple(out)
return wrapper
@property
def cache_dir(self):
return self._cache_dir
@cache_dir.setter
def cache_dir(self, value):
if not isinstance(value, Path):
value = Path(value)
if not value.exists():
warnings.warn(f'Path `{value}` does not exist.')
elif not value.is_dir():
warnings.warn(f'`{value}` is not a directory.')
self._cache_dir = value
def _create_cache_fn(self, *args, default_fname=None):
def helper(adata, fname=None, recache=False, verbose=True, *args, **kwargs):
def _get_val(obj, keys):
if keys is None:
return obj
if isinstance(keys, str) or not isinstance(keys, Iterable):
keys = (keys, )
for k in keys:
obj = obj[k]
return obj
def _convert_key(attr, key):
if key is None or isinstance(key, str):
return key
if isinstance(key, re._pattern_type):
km = {key.match(k).groups()[0]:k for k in getattr(adata, attr).keys() if key.match(k) is not None}
res = set(km.keys()) & possible_vals
if len(res) == 0:
# default value was not specified during the call
assert len(km) == 1, f'Found ambiguous matches for `{key}` in attribute `{attr}`: `{set(km.keys())}`.'
return tuple(km.values())[0]
assert len(res) == 1, f'Found ambiguous matches for `{key}` in attribute `{attr}`: `{res}`.'
return km[res.pop()]
assert isinstance(key, Iterable)
# converting to tuple because it's hashable
return tuple(key)
possible_vals = set(args) | set(kwargs.values())
try:
if fname is None:
fname = default_fname
if not fname.endswith(self._ext):
fname += self._ext
if recache:
if verbose:
print(f'Caching data to: `{fname}`.')
data = [((attr, (key, ) if key is None or isinstance(key, str) else key),
_get_val(getattr(adata, attr), key)) for attr, key in map(lambda a_k: (a_k[0], _convert_key(*a_k)), zip(attrs, keys))]
with open(self.cache_dir / fname, 'wb') as fout:
pickle.dump(data, fout)
return True
if (self.cache_dir / fname).is_file():
if verbose:
print(f'Loading data from: `{fname}`.')
with open(self.cache_dir / fname, 'rb') as fin:
attrs_keys, vals = zip(*pickle.load(fin))
for (attr, key), val in zip(attrs_keys, vals):
if key is None or isinstance(key, str):
key = (key, )
if not hasattr(adata, attr):
if attr == 'obsm': shape = (adata.n_obs, )
elif attr == 'varm': shape = (adata.n_vars, )
else: raise AttributeError('Support only for `.varm` and `.obsm` attributes.')
assert len(keys) == 1, 'Multiple keys not allowed in this case.'
setattr(adata, attr, np.empty(shape))
if key[0] is not None:
at = getattr(adata, attr)
msg = [f'adata.{attr}']
for k in key[:-1]:
if k not in at.keys():
at[k] = dict()
at = at[k]
msg.append(f'[{k}]')
if verbose and key[-1] in at.keys():
print(f'Warning: `{"".join(msg)}` already contains key: `{key[-1]}`.')
at[key[-1]] = val
else:
if verbose and hasattr(adata, attr):
print(f'Warning: `adata.{attr}` already exists.')
setattr(adata, attr, val)
return True
return False
except Exception as e:
if not isinstance(e, FileNotFoundError):
if recache:
print(traceback.format_exc())
else:
print(f'No cache found in `{self._cache_dir / fname}`.')
return False
if len(args) == 1:
collection = args[0]
if isinstance(collection, dict):
attrs = tuple(collection.keys())
keys = tuple(collection.values())
pat = re.compile(r'_cache\d+$')
attrs = tuple(pat.sub('', a) for a in attrs)
return helper
if isinstance(collection, Iterable) and len(next(iter(collection))) == 2:
attrs, keys = tuple(zip(*collection))
return helper
assert len(args) == 2
attrs, keys = args
if isinstance(attrs, str):
attrs = (attrs, )
if isinstance(keys, str):
keys = (keys, )
return helper
def cache(self, *args, **kwargs):
"""
Create a caching function.
:param: keys_attributes (dict, list(tuple))
:param: default_fname
"""
default_fn = kwargs.pop('default_fn', None)
def _run(*args, **kwargs):
"""
:param: *args
:param: **kwargs (fname, force, verbose)
"""
fname = kwargs.pop('fname', None)
force = kwargs.pop('force', False)
verbose = kwargs.pop('verbose', True)
copy = kwargs.get('copy', False)
callback = None
if len(args) > 1:
callback, *args = args
if len(args) > 0:
adata = args[0] if isinstance(args[0], anndata.AnnData) else kwargs.get('adata')
else:
adata = kwargs.get('adata')
assert isinstance(adata, anndata.AnnData), f'Expected `{adata}` to be of type `anndata.AnnData`.'
if callback is None:
callback = (lambda *_x, **_y: None) if default_fn is None else default_fn
assert callable(callback), f'`{callblack}` is not callable.'
if force:
if verbose:
print('Recomputing values.')
res = callback(*args, **kwargs)
cache_fn(res if copy else adata, fname, True, verbose, *args, **kwargs)
return res
# when loading to cache and copy is true, modify the copy
if copy:
adata = adata.copy()
# we need to pass the *args and **kwargs in order to
# get the right field when using regexes
if not cache_fn(adata, fname, False, verbose, *args, **kwargs):
if verbose:
print('Computing values.')
res = callback(*args, **kwargs)
ret = cache_fn(res if copy else adata, fname, True, False, *args, **kwargs)
assert ret, 'Caching failed.'
return res
# if cache was found and not modifying inplace
return adata if copy else None
cache_fn = self._create_cache_fn(*args, **kwargs)
return _run
def score_cell_cycle(adata, path, gene_symbols = 'none'):
"""
Computes cell cycle scores. This is usually done on batch corrected data.
adata - anndata object
path - path to a file containing cell cycle genes
gene_symbols - annotation key from adata.var
"""
# import the gene file
cc_genes = pd.read_table(path, delimiter='\t')
# sort by s and g2m genes
s_genes = cc_genes['S'].dropna() # s phase genes
g2m_genes = cc_genes['G2.M'].dropna() # g2 phase genes
# change the capitalisasion, to get from human genes to mouse genes
s_genes_mm = [gene.lower().capitalize() for gene in s_genes]
g2m_genes_mm = [gene.lower().capitalize() for gene in g2m_genes]
# which of those are also in our set of genes? in1d is a good way to check wether something
# is contained in something else
if gene_symbols is not None:
s_genes_mm_ens = adata.var_names[np.in1d(adata.var[gene_symbols], s_genes_mm)]
g2m_genes_mm_ens = adata.var_names[np.in1d(adata.var[gene_symbols], g2m_genes_mm)]
else:
s_genes_mm_ens = adata.var_names[np.in1d(adata.var_names, s_genes_mm)]
g2m_genes_mm_ens = adata.var_names[np.in1d(adata.var_names, g2m_genes_mm)]
# call the scoring function
sc.tl.score_genes_cell_cycle(adata, s_genes=s_genes_mm_ens,
g2m_genes=g2m_genes_mm_ens)
def check_markers(de_genes, marker_genes):
"""
This function compares a set of marker genes obtained from a differential expression test
to a set of reference marker genes provided by a data base or your local biologist
Parameters
--------
de_genes: pd.dataFrame
A data frame of differentially expressed genes per cluster
marker_genes: dict
A dict of known marker genes, e.g. for a specific cell type, each with a key
Output
--------
matches: dict
Genes from the DE list which were found in the marker_genes dict, for a specific key
"""
# create a dict for the results
matches = dict()
# loop over clusters
for group in de_genes.columns:
# add a new entry in the results dict
matches[group] = dict()
# extract the de genes for that cluster
de_genes_group = de_genes[group].values
# loop over cell types
for key in marker_genes:
genes_found = list()
# loop over the markers for this key
for gene in marker_genes[key]:
regex = re.compile('^' + gene + '$', re.IGNORECASE)
result = [l for l in de_genes_group for m in [regex.search(l)] if m]
if result: genes_found.append(result[0])
# save the matches in the dict
if genes_found: matches[group][key] = genes_found
return(matches)
def plot_markers(adata, key, markers = None, basis = 'umap', n_max = 10,
use_raw = True, multi_line = True, ignore_case = True,
protein= False, min_cutoff = None, max_cutoff = None, clustering = 'louvain',
colorbar = False, prot_key = 'prot', prot_names_key = 'prot_names', **kwags):
"""
This function plots a gridspec which visualises marker genes and a clustering in a given embedding.
Parameters
--------
adata: AnnData Object
Must contain the basis in adata.obsm
key: str
Can be either of var annotation, reg. expression or key from the markers dict (if given)
markers: dict or None
containing keys like cell types and marker genes as values
basis: str
any embedding from adata.obsm is valid
n_max: int
max number of genes to plot
use_raw: boolean
use adata.raw
multi_line: boolean
plot a grid
protein: boolean
Indicates wether this key should be interpreted as a protein name. Relevant
for cite-seq data.
min_cutoff, max_cutoff: str
string to indicate quantiles used for cutoffs, e.g. q05 for the 5% quantile
colorbar: boolean
wether a colorbar shall be plotted
prot_key : `str`, optional (default: `"prot"`)
Key to the proteins in adata.obsm
prot_names_key : `str`, optional (default: `"prot_names"`)
Key to the protein names in adata.uns
**kwags: keywod arguments for plt.scatter
"""
# check wether this basis exists
if 'X_' + basis not in adata.obsm.keys():
raise ValueError('You have not computed the basis ' + basis + ' yet. ')
X_em = adata.obsm['X_' + basis]
if basis == 'diffmap': X_em = X_em[:, 1:]
# give some feedback
print('Current key: {}'.format(key))
print('Basis: {}'.format(basis))
# get the gene names
if use_raw:
try:
print('Using the rawdata')
var_names = adata.raw.var_names
except:
var_names = adata.var_names
use_raw = False
print('adata.raw does not seem to exist')
else:
var_names = adata.var_names
# obtain the subset of genes we would like to plot
if markers is not None and protein is False:
if key not in markers.keys():
print('Key not in the markers dict. Searching in the var names.')
if ignore_case:
reg_ex = re.compile(key, re.IGNORECASE)
else:
reg_ex = re.compile(key, re.IGNORECASE)
genes = [l for l in var_names \
for m in [reg_ex.search(l)] if m]
else:
print('Key found in the markers dict.')
genes_pre = markers[key]
genes = list()
not_found = list()
# search through the list of genes
for gene in genes_pre:
if ignore_case:
reg_ex = re.compile('^' + gene + '$', re.IGNORECASE)
else:
reg_ex = re.compile('^' + gene + '$')
result = [l for l in var_names \
for m in [reg_ex.search(l)] if m]
if len(result)> 0:
genes.append(result[0])
else:
not_found.append(gene)
if len(not_found)> 0:
print('Could not find the following genes: ' + str(not_found))
elif protein is False:
print('No markers dict given. Searching in the var names.')
genes = []
for gene in key:
if ignore_case:
reg_ex = re.compile(gene, re.IGNORECASE)
else:
reg_ex = re.compile(gene)
genes_ = [l for l in var_names \
for m in [reg_ex.search(l)] if m]
genes.append(*genes_)
elif protein is True:
# we will internally refer to the proteins as genes
print('Looking for a protein with this name.')
if (prot_names_key not in adata.uns.keys()) or (prot_key not in adata.obsm.keys()):
raise ValueError('Requires a filed \'{}\' in adata.uns and a field \'{}\' in adata.obsm'.format(prot_names_key, prot_key))
proteins = adata.obsm[prot_key]
protein_names = adata.uns[prot_names_key]
# combine to a dataframe
proteins = pd.DataFrame(data = proteins, columns=protein_names)
if ignore_case:
reg_ex = re.compile(key, re.IGNORECASE)
else:
reg_ex = re.compile(key)
genes = [l for l in protein_names \
for m in [reg_ex.search(l)] if m]
if len(genes) == 0:
raise ValueError('Could not find any gene or protein to plot.')
# make sure it is not too many genes
if len(genes) > n_max:
print('Found ' + str(len(genes)) + ' matches.')
genes = genes[:n_max]
if not protein:
print('Plotting the following genes:' + str(genes))
else:
print('Plotting the following proteins:' + str(genes))
# create a gridspec
n_genes = len(genes)
if multi_line:
n_col = 3
n_row = int(np.ceil(n_genes+1/n_col))
else:
n_col = n_genes + 1
n_row = 1
gs = plt.GridSpec(n_row, n_col, figure = plt.figure(None, (12, n_row*12/(n_col+1) ), dpi = 150))
# plot the genes
plt.title(key)
for i in range(n_genes+ 2):
plt.subplot(gs[i])
# genes
if i < n_genes:
# get the color vector for this gene
if not protein:
if use_raw:
color = adata.raw[:, genes[i]].X
else:
color = adata[:, genes[i]].X
plt.title('Gene: ' + genes[i])
else:
color = proteins[genes[i]]
plt.title('Protein: ' + genes[i])
# quantile normalisation
if min_cutoff is not None:
color_min = np.quantile(color, np.float(min_cutoff[1:])/100)
else:
color_min = np.min(color)
if max_cutoff is not None:
color_max = np.quantile(color, np.float(max_cutoff[1:])/100)
else:
color_max = np.max(color)
color = np.clip(color, color_min, color_max)
plt.scatter(X_em[:, 0], X_em[:, 1], marker = '.', c = color, **kwags)
# add a colorbar
if colorbar: plt.colorbar()
elif i == n_genes: #louvain
ax = sc.pl.scatter(adata, basis = basis, color = clustering,
show = False, ax = plt.subplot(gs[i]),
legend_loc = 'right margin')
elif i > n_genes: #condition
if 'color' in adata.obs.keys():
print('found key')
ax = sc.pl.scatter(adata, basis = basis, color = 'color',
show = False, ax = plt.subplot(gs[i]),
legend_loc = 'right margin')
plt.axis("off")
plt.plot()
def map_to_mgi(adata, copy = False):
"""Utility funciton which maps gene names from ensembl names to mgi names.
Queries the biomart servers for the mapping
Parameters
--------
adata: AnnData object
"""
from pybiomart import Server
# connest to the biomart server
server = Server(host='http://www.ensembl.org')
# retrieve the mouse data set we need
dataset = (server.marts['ENSEMBL_MART_ENSEMBL']
.datasets['mmusculus_gene_ensembl'])
# recieve the mapping from ensembl to MGI
conv_table = dataset.query(attributes=['ensembl_gene_id', 'external_gene_name'])
# we first drop duplicates in the first column
conv_table = conv_table.drop_duplicates(conv_table.columns.values[0])
# convert the gene names from the adata object to a data frame
adata_table = pd.DataFrame(adata.var_names)
# give the first column a name
adata_table.columns = ['Gene stable ID']
# change the gene table so that the ensembl names are now the index
conv_table = conv_table.set_index('Gene stable ID')
# project the names from the conversion table on the corr. names in the
# adata var names table
mapping = adata_table.join(conv_table, on='Gene stable ID')
# how many could we not map
not_found_mgi = sum(pd.isnull(mapping).iloc[:,1])
# how many ensg symbols did we map several times?
rep_ensg = len(mapping.iloc[:, 0]) - len(set(mapping.iloc[:, 0]))
# how many mgi symbols did we map several times?
rep_mgi = len(mapping.iloc[:, 1]) - len(set(mapping.iloc[:, 1]))
# print this information
print('Genes where no MGI annotations where found: {}\nENSG repetition: {}\nMGI repetition: {}'.\
format(not_found_mgi, rep_ensg, rep_mgi))
# fill nans in mgi column with corresponding ensembl annotations
mapping['Gene name'].fillna(mapping['Gene stable ID'], inplace = True)
# add the new gene names to the adata object
adata.var['mgi_symbols'] = mapping['Gene name'].tolist()
def compare_distr(adata, key, groupby = 'batch', **kwags):
"""
Utility function that lets you compare quality measures among batches.
Parameters:
--------
adata : :class: '~anndata.AnnData`
Annotated data matrix
key : `str`
Observation annotation to use for comparing
groupby: `str`, optional (default: `"batch"`)
Levels used for grouping
**kwags: dict
Keyword arguments for plt.hist()
Returns:
--------
Nothing but it produces nice plots
"""
plt.figure(None, (8, 6), 70)
levels = adata.obs[groupby].cat.categories
for level in levels:
plt.hist(adata[adata.obs[groupby] == level].obs[key], alpha = 0.5,
label = level, density = True , **kwags)
plt.legend()
plt.title(key)
plt.show()
def print_numbers(adata, groupby=None, return_numbers=False, save_numbers=None):
"""
Utility function to print cell numbers per batch
Useful when filtering to check at intermediate steps how many cells and genes are left
Parameters:
--------
adata : AnnData object
Annotated data matrix
groupby : `str`, optional (defalut: `None`)
Key to categorical annotation in adata.obs
return_numbers: bool, optional (default: `False`)
Whether to return cell and gene numbers
save_numbers: None or str, optional (default: `None`)
if not None, saved the numbers in the adata object in uns
"""
adata_numbers = dict()
adata_numbers['groupby'] = groupby
adata_numbers['n_cells_total'] = adata.n_obs
# check wether batch key exists
if groupby is not None:
if groupby not in adata.obs.keys():
raise ValueError('Cannot find the key {!r} in adata.obs'.format(groupby))
else:
adata_numbers['by_group'] = dict()
# get the levels
groups = adata.obs[groupby]
groups = pd.Series(groups, dtype='category')
levels = groups.cat.categories
# print number of cell per batch
for level in levels:
n_cells = adata[adata.obs[groupby] == level].n_obs
print('{} cells in {} {}'.format(n_cells, groupby, level))
adata_numbers['by_group'][level] = n_cells
# In total
print('Total: {} cells, {} genes'.\
format(adata.n_obs, adata.n_vars))
if save_numbers is not None:
adata.uns[save_numbers] = adata_numbers
if return_numbers:
return adata_numbers
def print_filtering(adata, key='original_numbers'):
"""
:param adata: AnnData Object
Annotated Data Matrix
:param key: str, optional (default: `"original_numbers"`)
Where to find the original cell numbers in the
adata.uns field
:return: Nothing, just prints
"""
# check whether the original number have been saved
if key not in adata.uns.keys():
raise ValueError('Key {!r} not found in adata.uns'.format(key))
else:
original_numbers = adata.uns[key]
# print results for total numbers
print('In total: ')
n_cells = adata.n_obs
n_cells_orig = original_numbers['n_cells_total']
print('Filtered out {} cells or {:2.2f} %.\n'.format(
n_cells_orig - n_cells,
100 * (n_cells_orig - n_cells) / n_cells_orig))
# print results for group specific numbers
group_key = original_numbers['groupby']
if group_key is not None:
print('By {}'.format(group_key))
groups = adata.obs[group_key]
groups = pd.Series(groups, dtype='category')
groups = groups.cat.categories
for group in groups:
n_cells = adata[adata.obs[group_key] == group].n_obs
n_cells_orig = original_numbers['by_group'][group]
print('Filtered out {} cells or {:2.2f} % of {} {}.'.format(
n_cells_orig - n_cells,
100 * (n_cells_orig - n_cells) / n_cells_orig,
group_key,
group))
def batch_quantification(adata, scale=False,
regress_out=None,
n_neighbors=15, n_pcs=10,
keys=['n_counts', 'n_genes'],
batch_quant_key='batch',
bases=['pca', 'umap'],
components=[1, 2],
random_state=0, copy=True):
"""
adata : AnnData object
Annotated data matrix
scale: bool (default: `False`)
Scale cells to have 0 mean and 1 variance
regress_out: list[str], optional (default: `None`)
Keys from adata.obs to regress out
n_neighbors : int (default: `15`)
Number of neighbors to consider during clustering
n_pcs : int (default: `10`)
Number of principal components to use for clustering
keys : list[str], optional (default: `['n_counts', 'n_genes']`
Keys which are used in corr_ann
batch_quant_key: str, optional (default: `'batch'`)
Labels to use to compute silhouette coefficient
bases : list[str], optional (default: `['pca']`)
Bases to use
components : list[int], optional (default: `[1, 2]`)
Components of bases which are being passed to corr_ann
random_state : int, optional (default: `0`)
Random state to use
copy : bool, optional (default: `False`)
Operate on adata's copy rather than in-place
Returns
-------
None
"""
if copy:
adata = adata.copy()
if regress_out is not None:
sc.pp.regress_out(adata, regress_out)
if scale:
sc.pp.scale(adata)
sc.pp.pca(adata, svd_solver='arpack', random_state=random_state)
sc.pp.neighbors(adata, n_neighbors=n_neighbors,
n_pcs=n_pcs,
random_state=random_state)
sc.tl.umap(adata, random_state=random_state)
for basis in bases:
corr_ann(adata, obs_keys=keys, basis=basis, components=components)
quant_batch(adata, key=batch_quant_key, basis=basis, components=components)
return adata if copy else None
def create_dir(dir_type, base_path):
"""Utility function that manages scanpy directories
:param dir_type: str
Usually 'write', 'data' or 'figures'
:param base_path: str
Base path that is joined with the dir_type
:return: str
The joined path
"""
path = os.path.join(base_path, dir_type)
if not os.path.exists(path):
os.mkdir(path)
print('Created directory {!r}'.format(path))
else:
print('Found directory {!r}'.format(path))
if dir_type.find('figure') != -1:
sc.settings.figdir = path
scv.settings.figdir = path
return path
def corr_ann(adata, obs_keys=['n_counts', 'n_genes'], basis='pca', components=[1, 2]):
"""
Utility function to correlate continuous annotations against embedding
Can be used to see how large the linear influence of a measure like the count depth is on a
given component of any embedding, like PCA
Parameters
--------
adata : AnnData object
Annotated data matrix
obs_keys : `str`, optional (default: `[n_counts, n_genes]`)
Key for the continious annotation to use
basis : `str`, optional (default: `"pca"`)
Key to the basis stored in adata.obsm
components : `int`, optional (default: `[1, 2]`)
Component of the embedding to use
Returns
--------
Nothing, but prints the correlation
"""
# check input
if 'X_' + basis not in adata.obsm.keys():
raise ValueError('You have not computed this basis yet')
for key in obs_keys:
if key not in adata.obs.keys():
raise ValueError('The key {!r} does not exist in adata.obs'.format(obs_key))
# get the embedding coordinate
X_em = adata.obsm['X_' + basis]
for key in obs_keys:
for comp in components:
coordinates = X_em[:, comp - 1]
# get the continious annotation
ann = adata.obs[key]
# compute the correlation coefficient
corr = np.corrcoef(coordinates, ann)[0, 1]
print('Correlation between {!r} and component {!r} of basis {!r} is {:.2f}.'.format(key,
comp, basis, corr))
# quantify the batch effect quickly using the silhouette coefficient
def quant_batch(adata, key = 'batch', basis = 'pca', components=[1, 2]):
"""
Utility funciton to quantify batch effects
This is just a very simple approach, kBET by Maren will be much better and more sensitive
at fulfilling the same task.
Parameters
--------
adata : AnnData object
Annotated data matrix
key : `str`, optional (default: `"batch"`)
Labels to use to compute silhouette coefficient
basis : `str`, optional (default: `"pca"`)
Basis to compute the silhouette coefficient in. First two components used.
components : list[str], optional (default: `[1, 2]`)
Which components to use
Returns
--------
Nothing, prints the silhouette coefficient.
"""
from sklearn.metrics import silhouette_score
# check input
if 'X_' + basis not in adata.obsm.keys():
raise ValueError('You have not computd this basis yet')
if key not in adata.obs.keys():