-
Notifications
You must be signed in to change notification settings - Fork 10
/
singlecell.py
1571 lines (1336 loc) · 58.8 KB
/
singlecell.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 os
import warnings
from copy import deepcopy
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests
import scipy.stats as st
import seaborn as sns
from IPython.display import display
from ipywidgets import (HTML, Accordion, Button, Dropdown, FloatProgress,
FloatRangeSlider, HBox, IntRangeSlider, IntSlider,
Layout, Output, SelectionSlider, Tab, Text, VBox,
interactive_output)
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.ticker import MaxNLocator
from statsmodels.sandbox.stats.multicomp import multipletests
import subprocess
import plotly.offline as py
import plotly.tools as tls
import scanpy.api as sc
#from beakerx import TableDisplay, TableDisplayCellHighlighter
#import qgrid
py.init_notebook_mode()
warnings.simplefilter('ignore', UserWarning)
# -------------------- HELPERS --------------------
_CLUSTERS_CMAP = 'tab20'
_EXPRESSION_CMAP = LinearSegmentedColormap.from_list(
'name', ['lightgrey', 'orangered', 'red'])
_LINE_HEIGHT = '20px'
def _create_progress_bar():
style = '''
<style>
@-webkit-keyframes container-rotate {
to {
-webkit-transform: rotate(360deg)
}
}
@keyframes container-rotate {
to {
-webkit-transform: rotate(360deg);
transform: rotate(360deg)
}
}
@-webkit-keyframes fill-unfill-rotate {
12.5% {
-webkit-transform: rotate(135deg)
}
25% {
-webkit-transform: rotate(270deg)
}
37.5% {
-webkit-transform: rotate(405deg)
}
50% {
-webkit-transform: rotate(540deg)
}
62.5% {
-webkit-transform: rotate(675deg)
}
75% {
-webkit-transform: rotate(810deg)
}
87.5% {
-webkit-transform: rotate(945deg)
}
to {
-webkit-transform: rotate(1080deg)
}
}
@keyframes fill-unfill-rotate {
12.5% {
-webkit-transform: rotate(135deg);
transform: rotate(135deg)
}
25% {
-webkit-transform: rotate(270deg);
transform: rotate(270deg)
}
37.5% {
-webkit-transform: rotate(405deg);
transform: rotate(405deg)
}
50% {
-webkit-transform: rotate(540deg);
transform: rotate(540deg)
}
62.5% {
-webkit-transform: rotate(675deg);
transform: rotate(675deg)
}
75% {
-webkit-transform: rotate(810deg);
transform: rotate(810deg)
}
87.5% {
-webkit-transform: rotate(945deg);
transform: rotate(945deg)
}
to {
-webkit-transform: rotate(1080deg);
transform: rotate(1080deg)
}
}
.preloader-wrapper.active {
-webkit-animation: container-rotate 1568ms linear infinite;
animation: container-rotate 1568ms linear infinite;
} .preloader-wrapper {
display: inline-block;
position: relative;
width: 50px;
height: 50px;
}
.spinner-layer {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
border-color: #26a69a;
}
.active .spinner-layer {
border-color: #4285f4;
opacity: 1;
-webkit-animation: fill-unfill-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both;
animation: fill-unfill-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both;
}
.circle-clipper {
display: inline-block;
position: relative;
width: 50%;
height: 100%;
overflow: hidden;
border-color: inherit;
}
.circle-clipper.left {
float: left !important;
}
.active .circle-clipper.left .circle {
-webkit-animation: left-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both;
animation: left-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both;
}
.circle-clipper.left .circle {
left: 0;
border-right-color: transparent !important;
-webkit-transform: rotate(129deg);
transform: rotate(129deg);
}
.circle-clipper .circle {
width: 200%;
height: 100%;
border-width: 3px;
border-style: solid;
border-color: inherit;
border-bottom-color: transparent !important;
border-radius: 50%;
-webkit-animation: none;
animation: none;
position: absolute;
top: 0;
right: 0;
bottom: 0;
}
.circle {
border-radius: 50%;
}
.gap-patch {
position: absolute;
top: 0;
left: 45%;
width: 10%;
height: 100%;
overflow: hidden;
border-color: inherit;
}
.gap-patch .circle {
width: 1000%;
left: -450%;
}
.circle-clipper {
display: inline-block;
position: relative;
width: 50%;
height: 100%;
overflow: hidden;
border-color: inherit;
}
.circle-clipper.right {
float: right !important;
}
.active .circle-clipper.right .circle {
-webkit-animation: right-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both;
animation: right-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both;
}
.circle-clipper.right .circle {
left: -100%;
border-left-color: transparent !important;
-webkit-transform: rotate(-129deg);
transform: rotate(-129deg);
}
@-webkit-keyframes left-spin {
from {
-webkit-transform: rotate(130deg)
}
50% {
-webkit-transform: rotate(-5deg)
}
to {
-webkit-transform: rotate(130deg)
}
}
@keyframes left-spin {
from {
-webkit-transform: rotate(130deg);
transform: rotate(130deg)
}
50% {
-webkit-transform: rotate(-5deg);
transform: rotate(-5deg)
}
to {
-webkit-transform: rotate(130deg);
transform: rotate(130deg)
}
}
@-webkit-keyframes right-spin {
from {
-webkit-transform: rotate(-130deg)
}
50% {
-webkit-transform: rotate(5deg)
}
to {
-webkit-transform: rotate(-130deg)
}
}
@keyframes right-spin {
from {
-webkit-transform: rotate(-130deg);
transform: rotate(-130deg)
}
50% {
-webkit-transform: rotate(5deg);
transform: rotate(5deg)
}
to {
-webkit-transform: rotate(-130deg);
transform: rotate(-130deg)
}
}
</style>
'''
progress_bar = HTML(
'''{}
<div class="preloader-wrapper active">
<div class="spinner-layer spinner-blue-only">
<div class="circle-clipper left">
<div class="circle"></div>
</div><div class="gap-patch">
<div class="circle"></div>
</div><div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>
'''.format(style),
layout=Layout(height='150px', width='100%'))
return progress_bar
def _create_placeholder(kind):
if kind == 'plot':
word = 'Plot'
elif kind == 'table':
word = 'Table'
placeholder_html = '<p>{} will display here.</p>'.format(word)
return HTML(placeholder_html, layout=Layout(padding='28px'))
def _info_message(message):
return HTML(
'<div class="alert alert-info" style="font-size:14px; line-height:20px;"><p><b>NOTE:</b> {}</p></div>'.
format(message))
def _output_message(message):
return HTML(
'<div class="well well-sm" style="font-size:14px; line-height:20px; padding: 15px;">{}</div>'.
format(message))
def _output_message_txt(message):
return '<div class="well well-sm" style="font-size:14px; line-height:20px; padding: 15px;">{}</div>'.format(message)
def _warning_message(message):
return HTML(
'<div class="alert alert-warning" style="font-size:14px; line-height:20px;">{}</div>'.
format(message))
def _error_message(message):
return HTML(
'<div class="alert alert-danger" style="font-size:14px; line-height:20px;">{}</div>'.
format(message))
"""
These functions generate and update HTML objects to
display notebook progress status
"""
def _get_new_status(message):
return _output_message('<h3>Progress: </h3>'+message)
def _update_status(stat, message):
stat.value = _output_message_txt('<h3>Progress: </h3>'+message)
def _create_export_button(figure, fname):
# Default png
filetype_dropdown = Dropdown(
options=['png', 'svg', 'pdf'],
value='png',
layout=Layout(width='75px'))
if not os.path.isdir('figures'):
os.mkdir('figures')
# Default filename value
filename = 'figures/{}.{}'.format(fname, filetype_dropdown.value)
figure.savefig(
filename, bbox_inches='tight', format=filetype_dropdown.value)
# HTML button opens local link on click
a_style = '''text-decoration: none;
color: black;
border: 0px white solid !important;
'''
button_style = "width:100px; height:28px; margin:0px;"
button_classes = "p-Widget jupyter-widgets jupyter-button widget-button"
button_html = '<button class="{}" style="{}"><a href="{}" target="_blank" style="{}">Save Plot</a>'.format(
button_classes, button_style, filename, a_style)
export_button = HTML(button_html)
# Download file locally
def save_fig(value_info):
if not os.path.isdir('figures'):
os.mkdir('figures')
filename = 'figures/{}.{}'.format(fname, value_info['new'])
# Disable button until file is properly saved
export_button.value = '<button class="{}" style="{}" disabled><a href="{}" target="_blank" style="{}">Wait...</a>'.format(
button_classes, button_style, filename, a_style)
figure.savefig(filename, bbox_inches='tight', format=value_info['new'])
export_button.value = '<button class="{}" style="{}"><a href="{}" target="_blank" style="{}">Save Plot</a>'.format(
button_classes, button_style, filename, a_style)
filetype_dropdown.observe(save_fig, names='value')
return HBox(
[filetype_dropdown, export_button], justify_content='flex-start')
def _download_text_file(url):
'''
Downloads file assuming simple text file. Returns name of file.
'''
filename = url.split('/')[-1]
r = requests.get(url, stream=True)
file_size = int(r.headers['Content-Length'])
chunk_size = int(file_size / 50)
if chunk_size == 0:
chunk_size = int(file_size)
progress_bar = FloatProgress(
value=0,
min=0,
max=50,
step=1,
description='Loading...',
bar_style='info',
orientation='horizontal')
display(progress_bar)
f = open(filename, 'wb')
for chunk in r.iter_content(chunk_size=chunk_size):
f.write(chunk)
progress_bar.value += 1
f.close()
progress_bar.close()
#display(HTML('<p>Downloaded file: <code>{}</code>.</p>'.format(filename)))
return filename
class SingleCellAnalysis:
"""docstring for SingleCellAnalysis."""
def __init__(self, verbose=False):
self.data = ''
self.verbose = verbose
mpl.rcParams['figure.dpi'] = 80
# -------------------- SETUP ANALYSIS --------------------
def setup_analysis(self, csv_filepath=None, gene_x_cell=True, mtx_filepath=None,
gene_filepath=None, bc_filepath=None):
'''
Load a raw count matrix for a single-cell RNA-seq experiment.
If data is a single matrix file, csv_filepath should be used
and the other three variable names should be None. If data is in
10x format (mtx, gene, barcode), csv_filepath should be None
and the other three variables should be used correspondingly
'''
# Hide FutureWarnings.
warnings.simplefilter('ignore',
FutureWarning) if self.verbose else None
stat = _get_new_status("Preparing your files...")
display(stat)
if not self._setup_analysis(csv_filepath, gene_x_cell, mtx_filepath,
gene_filepath, bc_filepath, stat):
return
_update_status(stat, "Building QC metric plots...")
self._setup_analysis_ui()
_update_status(stat, "Done! QC for your data is displayed below")
# Revert to default settings to show FutureWarnings.
warnings.simplefilter('default',
FutureWarning) if self.verbose else None
def _setup_analysis(self, csv_filepath, gene_x_cell, mtx_filepath, gene_filepath,
bc_filepath, stat):
# Check for either one matrix file or all populated 10x fields, make
# sure user did not choose both or neither
paths_10x = [mtx_filepath, gene_filepath, bc_filepath]
use_csv = (csv_filepath != [])
use_10x = (paths_10x != [[], [], []])
if use_csv and use_10x:
display(_error_message("Can't use both single matrix file and 10X"))
return False
elif not use_csv and not use_10x:
display(_error_message("Must supply single matrix file or 10X files"))
return False
if use_csv:
local_csv_filepath = csv_filepath
if local_csv_filepath.startswith('http'):
_update_status(stat, "Downloading "+local_csv_filepath+"...")
display(stat)
local_csv_filepath = _download_text_file(csv_filepath)
if local_csv_filepath.endswith('.zip'):
subprocess.call('unzip -o '+local_csv_filepath, shell=True)
local_csv_filepath = '.'.join(local_csv_filepath.split('.')[:-1])
data = sc.read(local_csv_filepath, cache=False)
if gene_x_cell:
data = data.transpose()
elif use_10x:
local_mtx_filepath = mtx_filepath
local_gene_filepath = gene_filepath
local_bc_filepath = bc_filepath
if mtx_filepath.startswith('http'):
_update_status(stat, "Downloading "+mtx_filepath+"...")
local_mtx_filepath = _download_text_file(mtx_filepath)
if gene_filepath.startswith('http'):
_update_status(stat, "Downloading "+gene_filepath+"...")
local_gene_filepath = _download_text_file(gene_filepath)
if bc_filepath.startswith('http'):
_update_status(stat, "Downloading "+bc_filepath+"...")
local_bc_filepath = _download_text_file(bc_filepath)
if local_mtx_filepath.endswith('.zip'):
_update_status(stat, "Unpacking "+local_mtx_filepath+"...")
subprocess.call('unzip -o '+local_mtx_filepath, shell=True)
local_mtx_filepath = '.'.join(local_mtx_filepath.split('.')[:-1])
if local_gene_filepath.endswith('.zip'):
_update_status(stat, "Unpacking "+local_gene_filepath+"...")
subprocess.call('unzip -o '+local_gene_filepath, shell=True)
local_gene_filepath = '.'.join(local_gene_filepath.split('.')[:-1])
if local_bc_filepath.endswith('.zip'):
_update_status(stat, "Unpacking "+local_bc_filepath+"...")
subprocess.call('unzip -o '+local_bc_filepath, shell=True)
local_bc_filepath = '.'.join(local_bc_filepath.split('.')[:-1])
_update_status(stat, "Loading "+local_mtx_filepath+"...")
data = sc.read(local_mtx_filepath, cache=False).transpose()
_update_status(stat, "Loading "+local_bc_filepath+"...")
data.obs_names = np.genfromtxt(local_bc_filepath, dtype=str)
_update_status(stat, "Loading "+local_gene_filepath+"...")
data.var_names = np.genfromtxt(local_gene_filepath, dtype=str)[:,1]
# This is needed to setup the "n_genes" column in data.obs.
sc.pp.filter_cells(data, min_genes=0)
# Plot some information about mitochondrial genes, important for quality control
_update_status(stat, "Calculating mitochondrial DNA QC metrics...")
mito_genes = [
name for name in data.var_names if name.startswith('MT-')
]
data.obs['percent_mito'] = np.sum(
data[:, mito_genes].X, axis=1) / np.sum(
data.X, axis=1)
# add the total counts per cell as observations-annotation to data
_update_status(stat, "Calculating gene counts QC metrics...")
data.obs['n_counts'] = np.sum(data.X, axis=1)
data.is_log = False
self.data = data
return True
def _setup_analysis_ui(self):
measures = pd.DataFrame([
self.data.obs['n_genes'], self.data.obs['n_counts'],
self.data.obs['percent_mito'] * 100
]).T
measure_names = {
'n_genes': '# of Genes',
'n_counts': 'Total Counts',
'percent_mito': '% Mitochondrial Genes'
}
def plot_fig1(a, b, c):
with sns.axes_style('ticks'):
fig1 = plt.figure(figsize=(18, 4))
gs = mpl.gridspec.GridSpec(2, 3, wspace=0.1, hspace=0.05, height_ratios=[20, 1])
selected_info = HBox(layout=Layout( width='1012px', margin='0 0 0 10px'))
selected_info_children = []
is_selected = [True] * measures.shape[0]
for measure, ax_col, color, w in zip(measures.columns, list(range(len(measures.columns))), sns.color_palette('Set1')[:3], [a, b, c]):
values = measures[measure]
# Draw density plots
ax = plt.subplot(gs[0, ax_col])
if sum(values) > 0:
sns.kdeplot(values, shade=True, ax=ax, color=color, legend=False)
ax.set_xlim(0)
plt.setp(ax.get_xticklabels(), visible=False)
plt.setp(ax.get_yticklabels(), visible=False)
plt.setp(ax.get_yticklines(), visible=False)
ax.set_xlabel('')
sns.despine(ax=ax)
# Draw mean
ax.plot(len(ax.get_ylim()) * [values.mean()], ax.get_ylim(), color=color)
ax.text(values.mean(), ax.get_ylim()[1], 'x̅', fontsize=13)
# Draw SD lines
for i in range(3, 5):
ycoords = list(ax.get_ylim())
ycoords[1] *= (1-0.16 * (i-2))
if values.mean()+(i*values.std()) > values.max():
continue
ax.plot(len(ax.get_ylim()) * [values.mean() + i * values.std()],
ycoords, linestyle=':', color=color)
ax.text(values.mean() + i * values.std(), ax.get_ylim()
[1] * (1-0.16 * (i-2)), 'x̅ + {}σ'.format(i), fontsize=13)
# Draw selected area
selected_area = patches.Rectangle((w[0], 0), w[1], len(ax.get_ylim()),
linewidth=0, facecolor='black', alpha=0.1)
ax.add_patch(selected_area)
# Calculate # of cells selected using all filters
is_selected = is_selected & (measures[measure] >= w[0]) & (measures[measure] <= w[1])
# Draw points on bottom
ax_1 = plt.subplot(gs[1, ax_col], sharex=ax)
sns.stripplot(values, ax=ax_1, color=color, orient='horizontal', size=3, jitter=True, alpha=0.3)
ax_1.set_xlim(0)
ax_1.set_xlabel(measure_names[ax_1.get_xlabel()], fontsize=16)
ax_1.tick_params(labelsize=14)
if max(values) >= 1000:
ax_1.tick_params(labelrotation=-45)
plt.setp(ax_1.get_xticklines(), visible=False)
plt.setp(ax_1.get_yticklines(), visible=False)
sns.despine(ax=ax_1, left=True, bottom=True)
# Update selected info
w_info = HTML(value='<font size=4>Range: <code>{:.2f} - {:.2f}</code></font>'.format(w[0], w[1]),
layout=Layout(width='370px', padding='0', margin='0 0px 0 25px'))
selected_info_children.append(w_info)
plt.close()
selected_info.children = selected_info_children
is_selected_info = HTML('<font size=4><code><b>{:.2f}% ({} / {})</b></code> of total cells will be selected.</font>'.format(sum(is_selected) /
len(is_selected) * 100,
sum(is_selected),
len(is_selected)),
layout=Layout(margin='0 0 0 200px'))
display(is_selected_info, fig1, selected_info)
slider_box = HBox(layout=Layout(width='1012px', margin='0 0 0 0'))
slider_box_children = []
for measure in measures:
values = measures[measure]
slider = FloatRangeSlider(value=[0, values.mean() + 3 * values.std()],
min=0,
max=values.max(),
step=0.01,
continuous_update=False,
readout=False,
layout=Layout(margin='0 10px 0 13px'))
slider_box_children.append(slider)
slider_box.children = slider_box_children
slider_box_children.append(slider)
fig1_out = Output()
with fig1_out:
interactive_fig1 = interactive_output(plot_fig1, dict(zip(['a', 'b', 'c'], slider_box.children)))
display(interactive_fig1, slider_box)
# Descriptive text
header = _output_message('''<h3>Results</h3>
<p>Loaded <code>{}</code> cells and <code>{}</code> total genes.</p>
<h3>QC Metrics</h3>
<p>Visually inspect the quality metric distributions to visually identify thresholds for
filtering unwanted cell. Filtering is performed in
<b>Step 2</b>.<br><br>
There are 3 metrics including:
<ol>
<li>the number of genes detected in each cell</li>
<li>the total read counts in each cell</li>
<li>the percentage of counts mapped to mitochondrial genes</li>
</ol>
A high percentage of reads mapped to mitochondrial genes indicates the cell may have lysed before isolation,
losing cytoplasmic RNA and retaining RNA enclosed in the mitochondria. An abnormally high number of genes
or counts in a cell suggests a higher probability of a doublet.
<br><br>
Inspect the quality metric distribution plots below to filter appropriately.
</p>'''.format(measures.shape[0], len(self.data.var_names)))
display(header, fig1_out)
# -------------------- PREPROCESS COUNTS --------------------
def preprocess_counts(self,
min_n_cells=0,
min_n_genes=0,
max_n_genes='inf',
min_n_counts=0,
max_n_counts='inf',
min_percent_mito=0,
max_percent_mito='inf',
normalization_method='LogNormalize',
do_regression=True):
'''
Perform cell quality control by evaluating quality metrics, normalizing counts, scaling, and correcting for effects of total counts per cell and the percentage of mitochondrial genes expressed. Also detect highly variable genes and perform linear dimensional reduction (PCA).
'''
# Hide FutureWarnings.
stat = _get_new_status("Preparing to preprocess data...")
display(stat)
warnings.simplefilter('ignore',
FutureWarning) if self.verbose else None
if min_n_cells == '':
min_n_cells = 0
if min_n_genes == '':
min_n_genes = 0
if max_n_genes == '':
max_n_genes = 'inf'
if min_n_counts == '':
min_n_counts = 0
if max_n_counts == '':
max_n_counts = 'inf'
if min_percent_mito == '':
min_percent_mito = 0
if max_percent_mito == '':
max_percent_mito = 'inf'
# Sanitize input
min_n_cells = float(min_n_cells)
n_genes_range = [float(min_n_genes), float(max_n_genes)]
n_counts_range = [float(min_n_counts), float(max_n_counts)]
percent_mito_range = [float(min_percent_mito), float(max_percent_mito)]
orig_n_cells = len(self.data.obs_names)
orig_n_genes = len(self.data.var_names)
# Perform filtering on genes and cells
success_run = self._preprocess_counts(
min_n_cells, n_genes_range, n_counts_range, percent_mito_range,
normalization_method, stat, do_regression)
# Build UI output
if success_run:
_update_status(stat, "Preparing preprocessing results visualizations...")
self._preprocess_counts_ui(orig_n_cells, orig_n_genes)
_update_status(stat, "Done! See the results of preprocessing below")
# Revert to default settings to show FutureWarnings.
warnings.simplefilter('default',
FutureWarning) if self.verbose else None
def _preprocess_counts(self, min_n_cells, n_genes_range, n_counts_range,
percent_mito_range, normalization_method, stat,
do_regression):
if self.data.raw:
display(
_warning_message(
'This data has already been preprocessed. Please run <a href="#Step-1:-Setup-Analysis">Step 1: Setup Analysis</a> again if you would like to perform preprocessing again.</div>'
))
return False
_update_status(stat, "Filtering cells by #genes and #counts...")
# Gene filtering
sc.pp.filter_genes(self.data, min_cells=min_n_cells)
# Filter cells within a range of # of genes and # of counts.
sc.pp.filter_cells(self.data, min_genes=n_genes_range[0])
sc.pp.filter_cells(self.data, max_genes=n_genes_range[1])
sc.pp.filter_cells(self.data, min_counts=n_counts_range[0])
sc.pp.filter_cells(self.data, max_counts=n_counts_range[1])
# Remove cells that have too many mitochondrial genes expressed.
_update_status(stat, "Removing cells high in mitochondrial genes...")
percent_mito_filter = (
self.data.obs['percent_mito'] * 100 >= percent_mito_range[0]) & (
self.data.obs['percent_mito'] * 100 < percent_mito_range[1])
if not percent_mito_filter.any():
self.data = self.data[percent_mito_filter, :]
# Set the `.raw` attribute of AnnData object to the logarithmized raw gene expression for later use in
# differential testing and visualizations of gene expression. This simply freezes the state of the data stored
# in `data_raw`.
if normalization_method == 'LogNormalize' and self.data.is_log is False:
data_raw = sc.pp.log1p(self.data, copy=True)
self.data.raw = data_raw
# Per-cell scaling.
_update_status(stat, "Performing per-cell normalization...")
sc.pp.normalize_per_cell(self.data, counts_per_cell_after=1e4)
# Identify highly-variable genes.
_update_status(stat, "Identifying highly-variable genes...")
sc.pp.filter_genes_dispersion(
self.data, min_mean=0.0125, max_mean=3, min_disp=0.5)
# Logarithmize the data.
if normalization_method == 'LogNormalize' and self.data.is_log is False:
_update_status(stat, "Log-normalizing data...")
sc.pp.log1p(self.data)
self.data.is_log = True
# Regress out effects of total counts per cell and the percentage of mitochondrial genes expressed.
if do_regression:
_update_status(stat, "Performing regression based on counts per cell and percent mitochondrial genes expressed...")
sc.pp.regress_out(self.data, ['n_counts', 'percent_mito'])
# Scale the data to unit variance and zero mean. Clips to max of 10.
_update_status(stat, "Scaling data to have unit variance and zero mean...")
sc.pp.scale(self.data, max_value=10)
# Calculate PCA
_update_status(stat, "Performing principle component analysis (PCA)...")
try:
sc.tl.pca(self.data, n_comps=30)
except ValueError:
print("Less than 30 features available for PCA, trying 25")
try:
sc.tl.pca(self.data, n_comps=25)
except ValueError:
print("Less than 25 features available for PCA, trying 20")
try:
sc.tl.pca(self.data, n_comps=20)
except ValueError:
print("Less than 20 features available for PCA, trying 10")
try:
sc.tl.pca(self.data, n_comps=10)
except ValueError:
print("Less than 10 features available for PCA, trying 5")
sc.tl.pca(self.data, n_comps=10)
# Successfully ran
return True
def _preprocess_counts_ui(self, orig_n_cells, orig_n_genes):
cell_text = '<p>Number of cells passed filtering: <code>{} / {}</code></p>'.format(
len(self.data.obs_names), orig_n_cells)
genes_text = '<p>Number of genes passed filtering: <code>{} / {}</code></p>'.format(
len(self.data.raw.var_names), orig_n_genes)
v_genes_text = '<p>Number of genes detected as variable genes: <code>{} / {}</code></p>'.format(
len(self.data.var_names), len(self.data.raw.var_names))
if self.data.is_log:
log_text = '<p>Data is log normalized.</p>'
else:
log_text = '<p>Data is not normalized.</p>'
regress_text = '''<p>Performed linear regression to remove unwanted sources of variation including:<br>
<ol><li># of detected molecules per cell</li>
<li>% mitochondrial gene content</li>
</ol></p>'''
pca_help_text = '''<h3>Dimensional Reduction: Principal Components</h3>
<p>Use the following plot showing the standard deviations of the principal components to determine the number of relevant components to use downstream.</p>'''
output_div = _output_message(
'''<h3 style="position: relative; top: -10px">Preprocess Counts Results</h3>{}{}{}{}{}{}'''.
format(cell_text, genes_text, v_genes_text, log_text, regress_text,
pca_help_text))
display(output_div)
display(_info_message('Hover over the plot to interact.'))
pca_fig, pca_py_fig = self._plot_pca()
pca_plot_box = Output(layout=Layout(
display='flex',
align_items='center',
justify_content='center',
margin='0 0 0 -50px'))
display(pca_plot_box)
with pca_plot_box:
py.iplot(pca_py_fig, show_link=False)
def _plot_pca(self):
# mpl figure
fig_elbow_plot = plt.figure(figsize=(7, 6))
pc_var = self.data.uns['pca_variance_ratio']
#pc_var = self.data.uns['pca']['variance_ratio']
pc_var = pc_var[:min(len(pc_var), 30)]
# Calculate percent variance explained
pc_var = [v / sum(pc_var) * 100 for v in pc_var]
pc_var = pd.Series(pc_var, index=[x + 1 for x in range(len(pc_var))])
plt.plot(pc_var, 'o')
ax = fig_elbow_plot.gca()
ax.set_xlim(left=0)
ax.get_xaxis().set_major_locator(MaxNLocator(integer=True))
ax.get_xaxis().set_minor_locator(MaxNLocator(integer=True))
ax.set_xlabel('Principal Component', size=16)
ax.set_ylabel('% Variance Explained', size=16)
ax.tick_params(labelsize=14)
plt.close()
# plot interactive
py_fig = tls.mpl_to_plotly(fig_elbow_plot)
py_fig['layout']['margin'] = {'l': 75, 'r': 14, 't': 10, 'b': 45}
return fig_elbow_plot, py_fig
# -------------------- Cluster Cells --------------------
def cluster_cells(self):
# Hide FutureWarnings.
warnings.simplefilter('ignore',
FutureWarning) if self.verbose else None
# -------------------- tSNE PLOT --------------------
pc_sdev = pd.Series(np.std(self.data.obsm['X_pca'], axis=0))
pc_sdev.index = pc_sdev.index + 1
# Parameter values
pc_range = range(2, 31)
res_range = [
float('{:0.1f}'.format(x)) for x in list(np.arange(.5, 2.1, 0.1))
]
perp_range = range(5, min(51, len(self.data.obs_names)))
# Default parameter values
pcs = 10
resolution = 1.2
#perplexity = 30
perplexity = min(30, len(self.data.obs_names)-1)
# Parameter slider widgets
pc_slider = SelectionSlider(
options=pc_range,
value=pcs,
description="# of PCs",
continuous_update=False)
res_slider = SelectionSlider(
options=res_range,
value=resolution,
description="Resolution",
continuous_update=False)
perp_slider = SelectionSlider(
options=perp_range,
value=perplexity,
description="Perplexity",
continuous_update=False)
# Output widget
plot_output = Output(layout=Layout(
height='800px',
display='flex',
align_items='center',
justify_content='center'))
with plot_output:
display(_create_placeholder('plot'))
# "Go" button to plot on click
def plot_tsne_callback(button=None):
plot_output.clear_output()
progress_bar = _create_progress_bar()
with plot_output:
# show progress bar
display(progress_bar)
# perform tSNE calculation and plot
self._run_tsne(pc_slider.value, res_slider.value,
perp_slider.value)
tsne_fig, py_tsne_fig = self._plot_tsne(figsize=(10, 9))
py.iplot(py_tsne_fig, show_link=False)
# close progress bar
progress_bar.close()
# Button widget
go_button = Button(description='Plot', button_style='info')
go_button.on_click(plot_tsne_callback)
# Parameter descriptions
param_info = _output_message('''
<h3 style="position: relative; top: -10px">Clustering Parameters</h3>
<p>
<h4>Number of PCs (Principal Components)</h4>The number of principal components (PCs) to use in clustering.
It is important to note that the fewer PCs we choose to use, the less noise we have when clustering,
but at the risk of excluding relevant biological variance. Look at the plot in <b>Step 2</b> showing the
percent varianced explained by each principle components and choose a cutoff where there is a clear elbow
in the graph.<br><br>
<h4>Resolution</h4>Higher resolution means more and smaller clusters. We find that values 0.6-1.2 typically
returns good results for single cell datasets of around 3K cells. Optimal resolution often increases for
larger datasets.<br><br>
<h4>Perplexity</h4>The perplexity parameter loosely models the number of close neighbors each point has.
<a href="https://distill.pub/2016/misread-tsne/">More info on how perplexity matters here</a>.
</p>''')
help_message = '''Hover over the plot to interact. Click and drag to zoom. Click on the legend to hide or show
specific clusters; single-click hides/shows the cluster while double-click isolates the cluster.'''
sliders = HBox([pc_slider, res_slider, perp_slider])
ui = VBox(
[param_info, _info_message(help_message), sliders, go_button])
plot_box = VBox([ui, plot_output])
display(plot_box)
plot_tsne_callback()
# Revert to default settings to show FutureWarnings.
warnings.simplefilter('default',
FutureWarning) if self.verbose else None
def _run_tsne(self, pcs, resolution, perplexity):
sc.tl.tsne(
self.data,
n_pcs=pcs,
perplexity=perplexity,
learning_rate=1000,
n_jobs=8)
#sc.pp.neighbors(
# self.data,
# n_neighbors=10)
sc.tl.louvain(
self.data,
n_neighbors=10,
resolution=resolution,
recompute_graph=True
)
self.data.obs['louvain_groups']
def _plot_tsne(self, figsize):
# Clusters
#cell_clusters = self.data.obs['louvain'].astype(int)
cell_clusters = self.data.obs['louvain_groups'].astype(int)
cluster_names = np.unique(cell_clusters).tolist()
num_clusters = len(cluster_names)
# Coordinates with cluster assignments
tsne_coordinates = pd.DataFrame(