-
Notifications
You must be signed in to change notification settings - Fork 53
/
report.py
1893 lines (1617 loc) · 82 KB
/
report.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
"""Functions for creation of an HTML report that plots and explains output."""
from cellbender.remove_background.downstream import \
load_anndata_from_input, \
load_anndata_from_input_and_output, \
_load_anndata_from_input_and_decontx
from cellbender.base_cli import get_version
from cellbender.remove_background import consts
import matplotlib.pyplot as plt
import numpy as np
import torch
import scipy.sparse as sp
import scipy.stats
from IPython.display import display, Markdown, HTML
import subprocess
import datetime
import os
import shutil
import logging
from typing import Dict, Optional
logger = logging.getLogger('cellbender')
warnings = []
TIMEOUT = 1200 # twenty minutes should always be way more than enough
# counteract an error when I run locally
# https://stackoverflow.com/questions/53014306/error-15-initializing-libiomp5-dylib-but-found-libiomp5-dylib-already-initial
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
run_notebook_str = lambda file: \
f'jupyter nbconvert ' \
f'--ExecutePreprocessor.timeout={TIMEOUT} ' \
f'--to notebook ' \
f'--allow-errors ' \
f'--execute {file}'
to_html_str = lambda file, output: \
f'jupyter nbconvert ' \
f'--to html ' \
f'--TemplateExporter.exclude_input=True ' \
f'{file}'
def _run_notebook(file):
shutil.copy(file, 'tmp.report.ipynb')
subprocess.run(run_notebook_str(file='tmp.report.ipynb'), shell=True)
os.remove('tmp.report.ipynb')
return 'tmp.report.nbconvert.ipynb'
def _to_html(file, output) -> str:
subprocess.run(to_html_str(file=file, output=output), shell=True)
os.replace(file.replace(".ipynb", ".html"), output)
os.remove(file)
return output
def _postprocess_html(file: str, title: str):
try:
with open(file, mode='r', encoding="utf8", errors="surrogateescape") as f:
html = f.read()
html = html.replace('<title>tmp.report.nbconvert</title>',
f'<title>{title}</title>')
with open(file, mode='w', encoding="utf8", errors="surrogateescape") as f:
f.write(html)
except:
logger.warning('Failed to overwrite default HTML report title. '
'This is purely aesthetic and does not affect output.')
def run_notebook_make_html(file, output) -> str:
"""Run Jupyter notebook to populate report and then convert to HTML.
Args:
file: Notebook file
output: Output file. Should end in ".html"
Returns:
output: Output file
"""
assert output.endswith('.html'), 'Output HTML filename should end with .html'
html_file = _to_html(file=_run_notebook(file), output=output)
_postprocess_html(
file=html_file,
title=('CellBender: ' + os.path.basename(output).replace('_report.html', '')),
)
return html_file
def generate_summary_plots(input_file: str,
output_file: str,
truth_file: Optional[Dict] = None,
dev_mode: bool = consts.EXTENDED_REPORT):
"""Read in cellbender's output file and generate summary plots.
Args:
input_file: Raw CellRanger
"""
global warnings
warnings = []
display(Markdown(f'### CellBender version {get_version()}'))
display(Markdown(str(datetime.datetime.now()).split('.')[0]))
display(Markdown(f'# {os.path.basename(output_file)}'))
# load datasets, before and after CellBender
input_layer_key = 'raw'
if os.path.isdir(output_file):
adata = _load_anndata_from_input_and_decontx(input_file=input_file,
output_mtx_directory=output_file,
input_layer_key=input_layer_key,
truth_file=truth_file)
out_key = 'decontx'
else:
adata = load_anndata_from_input_and_output(input_file=input_file,
output_file=output_file,
analyzed_barcodes_only=True,
input_layer_key=input_layer_key,
truth_file=truth_file)
out_key = 'cellbender'
# need to make any duplicate var indices unique (for pandas manipulations)
adata.var_names_make_unique()
display(Markdown('## Loaded dataset'))
print(adata)
# bit of pre-compute
cells = (adata.obs['cell_probability'] > consts.CELL_PROB_CUTOFF)
adata.var['n_removed'] = adata.var[f'n_{input_layer_key}'] - adata.var[f'n_{out_key}']
adata.var['fraction_removed'] = adata.var['n_removed'] / (adata.var[f'n_{input_layer_key}'] + 1e-5)
adata.var['fraction_remaining'] = adata.var[f'n_{out_key}'] / (adata.var[f'n_{input_layer_key}'] + 1e-5)
adata.var[f'n_{input_layer_key}_cells'] = np.array(adata.layers[input_layer_key][cells].sum(axis=0)).squeeze()
adata.var[f'n_{out_key}_cells'] = np.array(adata.layers[out_key][cells].sum(axis=0)).squeeze()
adata.var['n_removed_cells'] = (adata.var[f'n_{input_layer_key}_cells']
- adata.var[f'n_{out_key}_cells'])
adata.var['fraction_removed_cells'] = (adata.var['n_removed_cells']
/ (adata.var[f'n_{input_layer_key}_cells'] + 1e-5))
adata.var['fraction_remaining_cells'] = (adata.var[f'n_{out_key}_cells']
/ (adata.var[f'n_{input_layer_key}_cells'] + 1e-5))
# this inline command is necessary after cellbender imports
plt.rcParams.update({'font.size': 12})
# input UMI curve
raw_full_adata = plot_input_umi_curve(input_file)
# prove that remove-background is only subtracting counts, never adding
if out_key == 'cellbender':
assert (adata.layers[input_layer_key] < adata.layers[out_key]).sum() == 0, \
"There is an entry in the output greater than the input"
else:
if (adata.layers[input_layer_key] < adata.layers[out_key]).sum() == 0:
display(Markdown('WARNING: There is an entry in the output greater than the input'))
display(Markdown('## Examine how many counts were removed in total'))
try:
assess_overall_count_removal(adata, raw_full_adata=raw_full_adata, out_key=out_key)
except ValueError:
display(Markdown('Skipping assessment over overall count removal. Presumably '
'this is due to including the whole dataset in '
'--total-droplets-included.'))
# plot learning curve
if out_key == 'cellbender':
try:
assess_learning_curve(adata)
except Exception:
pass
else:
display(Markdown('Skipping learning curve assessment.'))
# look at per-gene count removal
assess_count_removal_per_gene(adata, raw_full_adata=raw_full_adata, extended=dev_mode)
if dev_mode:
display(Markdown('## Histograms of counts per cell for several genes'))
plot_gene_removal_histograms(adata, out_layer_key=out_key)
display(Markdown('Typically we see that some of the low-count cells have '
'their counts removed, since they were background noise.'))
# plot UMI curve and cell probabilities
if out_key == 'cellbender':
display(Markdown('## Cell probabilities'))
display(Markdown('The inferred posterior probability '
'that each droplet is non-empty.'))
display(Markdown('*<span style="color:gray">We sometimes write "non-empty" '
'instead of "cell" because dead cells and other cellular '
'debris can still lead to a "non-empty" droplet, which will '
'have a high posterior cell probability. But these '
'kinds of low-quality droplets should be removed during '
'cell QC to retain only high-quality cells for downstream '
'analyses.</span>*'))
plot_counts_and_probs_per_cell(adata)
else:
display(Markdown('Skipping cell probability assessment.'))
# concordance of data before and after
display(Markdown('## Concordance of data before and after `remove-background`'))
plot_validation_plots(adata, output_layer_key=out_key, extended=dev_mode)
# PCA of gene expression
if out_key == 'cellbender':
display(Markdown('## PCA of encoded gene expression'))
plot_gene_expression_pca(adata, extended=dev_mode)
else:
display(Markdown('Skipping gene expression embedding assessment.'))
# "mixed species" plots
mixed_species_plots(adata, input_layer_key=input_layer_key, output_layer_key=out_key)
if dev_mode and (truth_file is not None):
# accuracy plots ==========================================
display(Markdown('# Comparison with truth data'))
display(Markdown('## Removal per gene'))
display(Markdown('Counts per gene are summed over cell-containing droplets'))
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.plot(adata.var['n_truth'].values, adata.var[f'n_{out_key}_cells'].values, '.', color='k')
plt.plot([0, adata.var['n_truth'].max()], [0, adata.var['n_truth'].max()],
color='lightgray', alpha=0.5)
plt.xlabel('True counts per gene')
plt.ylabel(f'{out_key} counts per gene')
plt.subplot(1, 2, 2)
logic = (adata.var['n_truth'].values > 0)
plt.plot(adata.var['n_truth'].values[logic],
((adata.var[f'n_{out_key}_cells'].values[logic] - adata.var['n_truth'].values[logic])
/ adata.var['n_truth'].values[logic]),
'.', color='k')
plt.plot([0, adata.var['n_truth'].max()], [0, 0],
color='lightgray', alpha=0.5)
plt.xlabel('True counts per gene')
plt.ylabel(f'{out_key}: residual count ratio per gene\n({out_key} - truth) / truth')
plt.tight_layout()
plt.show()
adata.var['fraction_remaining_cells_truth'] = (adata.var[f'n_truth']
/ (adata.var[f'n_{input_layer_key}_cells'] + 1e-5))
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.semilogx(adata.var[f'n_{input_layer_key}_cells'],
adata.var['fraction_remaining_cells'], 'k.', ms=1)
plt.ylim([-0.05, 1.05])
plt.xlabel('Number of counts in raw data')
plt.ylabel('Fraction of counts remaining')
plt.title('Genes: removal of counts\nfrom (inferred) cell-containing droplets')
plt.subplot(1, 2, 2)
plt.semilogx(adata.var[f'n_{input_layer_key}_cells'],
adata.var['fraction_remaining_cells_truth'], 'k.', ms=1)
plt.ylim([-0.05, 1.05])
plt.xlabel('Number of counts in raw data')
plt.ylabel('Truth: fraction of counts remaining')
plt.title('Genes: truth')
plt.tight_layout()
plt.show()
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.semilogx(adata.var[f'n_{input_layer_key}_cells'],
adata.var['fraction_remaining_cells'] - adata.var['fraction_remaining_cells_truth'],
'k.', ms=1)
plt.ylim([-1.05, 1.05])
plt.xlabel('Number of counts in raw data')
plt.ylabel('Residual fraction of counts remaining')
plt.title('Genes: residual')
plt.subplot(1, 2, 2)
plt.semilogx(adata.var[f'n_{input_layer_key}_cells'],
adata.var[f'n_{input_layer_key}_cells'] - adata.var['n_truth'],
'k.', ms=1, label='raw')
plt.semilogx(adata.var[f'n_{input_layer_key}_cells'],
adata.var[f'n_{out_key}_cells'] - adata.var['n_truth'],
'r.', ms=1, label=f'{out_key}')
plt.legend()
plt.xlabel('Number of counts in raw data')
plt.ylabel('Residual counts remaining')
plt.title('Genes: residual')
plt.tight_layout()
plt.show()
display(Markdown('## Revisiting histograms of counts per cell'))
display(Markdown('Now showing the truth in addition to the `remove-background` '
'output.'))
plot_gene_removal_histograms(adata, plot_truth=True, out_layer_key=out_key)
# plot z, and comparisons of learned to true gene expression
if out_key == 'cellbender':
cluster_and_compare_expression_to_truth(adata=adata)
else:
display(Markdown('Skipping gene expression embedding assessment.'))
# gene expression as images: visualize changes
display(Markdown('## Visualization just for fun'))
display(Markdown('This is a strange but somewhat fun way to visualize what '
'is going on with the data for each cell. We look at one '
'cell at a time, and visualize gene expression as an '
'image, where pixels are ordered by their true expression '
'in the ambient RNA, where upper left is most expressed '
'in ambient. We plot the output gene expression in '
'blue/yellow, and then we look at three residuals (in red):'
'\n\n1. (raw - truth): what was supposed to be removed'
'\n2. (raw - posterior): what was actually removed'
'\n3. (truth - posterior): the residual, '
'where red means too little was removed and blue means too '
'much was removed.'))
try:
show_gene_expression_before_and_after(adata=adata, num=5)
except:
display(Markdown('WARNING: skipped showing gene expression as images, due to an error'))
if dev_mode:
# inference of latents
if out_key == 'cellbender':
compare_latents(adata)
else:
display(Markdown('Skipping gene expression embedding assessment.'))
if truth_file is not None:
# ROC curves
display(Markdown('## Quantification of performance'))
display(Markdown('Here we take a look at removal of noise counts from cell '
'containing droplets only.'))
true_fpr = cell_roc_count_roc(
output_csr=adata.layers[out_key],
input_csr=adata.layers[input_layer_key],
truth_csr=adata.layers['truth'],
cell_calls=(adata.obs['cell_probability'] > 0.5),
truth_cell_labels=adata.obs['truth_cell_label'],
)
if type(adata.uns['target_false_positive_rate'][0]) == np.float64:
if true_fpr > adata.uns['target_false_positive_rate'][0]:
warnings.append('FPR exceeds target FPR.')
display(Markdown(f'WARNING: FPR of {true_fpr:.4f} exceeds target FPR of '
f'{adata.uns["target_false_positive_rate"]}. Keep '
f'in mind however that the target FPR is meant to '
f'target false positives over and above some '
f'basal level (dataset dependent), so the '
f'measured FPR should exceed the target by some '
f'amount.'))
display(Markdown('# Summary of warnings:'))
if len(warnings) == 0:
display(Markdown('None.'))
else:
for warning in warnings:
display(Markdown(warning))
def plot_input_umi_curve(inputfile):
adata = load_anndata_from_input(inputfile)
plt.loglog(sorted(np.array(adata.X.sum(axis=1)).squeeze(), reverse=True))
plt.xlabel('Ranked Barcode ID')
plt.ylabel('UMI counts')
plt.title(f'UMI curve\nRaw input data: {os.path.basename(inputfile)}')
plt.show()
return adata
def assess_overall_count_removal(adata, raw_full_adata, input_layer_key='raw', out_key='cellbender'):
global warnings
cells = (adata.obs['cell_probability'] > 0.5)
initial_counts = adata.layers[input_layer_key][cells].sum()
removed_counts = initial_counts - adata.layers[out_key][cells].sum()
removed_percentage = removed_counts / initial_counts * 100
print(f'removed {removed_counts:.0f} counts from non-empty droplets')
print(f'removed {removed_percentage:.2f}% of the counts in non-empty droplets')
from scipy.stats import norm
log_counts = np.log10(np.array(adata.layers[input_layer_key].sum(axis=1)).squeeze())
empty_log_counts = np.array(raw_full_adata.X[
[bc not in adata.obs_names
for bc in raw_full_adata.obs_names]
].sum(axis=1)).squeeze()
empty_log_counts = np.log10(empty_log_counts[empty_log_counts > consts.LOW_UMI_CUTOFF])
bins = np.linspace(empty_log_counts.min(), log_counts.max(), 100)
# binwidth = bins[1] - bins[0]
# def plot_normal_fit(x, loc, scale, n, label):
# plt.plot(x, n * binwidth * norm.pdf(x=x, loc=loc, scale=scale), label=label)
plt.hist(empty_log_counts.tolist() + log_counts[~cells].tolist(),
histtype='step', label='empty droplets', bins=bins)
plt.hist(log_counts[cells], histtype='step', label='non-empty droplets', bins=bins)
xx = np.linspace(plt.gca().get_xlim()[0], plt.gca().get_xlim()[-1], 100)
# if 'cell_size' in adata.obs.keys():
# plt.hist(np.log10(adata.obs['cell_size'][cells]),
# histtype='step', label='inferred cell sizes', bins=bins)
# plot_normal_fit(x=xx,
# loc=np.log10(adata.obs['cell_size'][cells]).mean(),
# scale=np.log10(adata.obs['cell_size'][cells]).std(),
# n=cells.sum(),
# label='inferred cell sizes')
# if (('empty_droplet_size_lognormal_loc' in adata.uns.keys())
# and ('empty_droplet_size_lognormal_scale' in adata.uns.keys())):
# plot_normal_fit(x=xx,
# loc=np.log10(np.exp(adata.uns['empty_droplet_size_lognormal_loc'])),
# scale=np.log10(np.exp(adata.uns['empty_droplet_size_lognormal_scale'])),
# n=(~cells).sum() + len(empty_log_counts),
# label='inferred empty sizes')
plt.ylabel('Number of droplets')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.ylim(bottom=1)
plt.yscale('log')
# x-axis log10 to regular number
plt.xticks(plt.gca().get_xticks(),
[f'{n:.0f}' for n in np.power(10, plt.gca().get_xticks())], rotation=90)
plt.xlim(left=empty_log_counts.min())
plt.xlabel('UMI counts per droplet')
plt.show()
estimated_ambient_per_droplet = np.exp(adata.uns['empty_droplet_size_lognormal_loc']).item()
expected_fraction_removed_from_cells = estimated_ambient_per_droplet * cells.sum() / initial_counts
fpr = adata.uns['target_false_positive_rate'].item() # this is an np.ndarray with one element
cohort_mode = False
if type(fpr) != float:
cohort_mode = True
print('Rough estimate of expectations based on nothing but the plot above:')
print(f'roughly {estimated_ambient_per_droplet * cells.sum():.0f} noise counts '
f'should be in non-empty droplets')
print(f'that is approximately {expected_fraction_removed_from_cells * 100:.2f}% of '
f'the counts in non-empty droplets')
if not cohort_mode:
expected_percentage = (expected_fraction_removed_from_cells + fpr) * 100
print(f'with a false positive rate [FPR] of {fpr * 100}%, we would expect to remove about '
f'{expected_percentage:.2f}% of the counts in non-empty droplets')
else:
expected_percentage = expected_fraction_removed_from_cells * 100
print(f'ran in cohort mode, so no false positive rate [FPR] target was set, '
f'but we would still expect to remove about '
f'{expected_percentage:.2f}% of the counts in non-empty droplets')
display(Markdown('\n'))
if np.abs(expected_percentage - removed_percentage) <= 0.5:
display(Markdown('It looks like the algorithm did a great job meeting that expectation.'))
elif np.abs(expected_percentage - removed_percentage) <= 1:
display(Markdown('It looks like the algorithm did a decent job meeting that expectation.'))
elif np.abs(expected_percentage - removed_percentage) <= 5:
if removed_percentage < expected_percentage:
display(Markdown('The algorithm removed a bit less than naive expectations '
'would indicate, but this is likely okay. If removal '
'seems insufficient, the FPR can be increased.'))
else:
display(Markdown('The algorithm removed a bit more than naive expectations '
'would indicate, but this is likely okay. Spot-check '
'removal of a few top-removed genes as a QC measure. '
'If less removal is desired, decrease the FPR.'))
elif removed_percentage - expected_percentage > 5:
display(Markdown('The algorithm seems to have removed more overall counts '
'than would be naively expected.'))
warnings.append('Algorithm removed more counts overall than naive expectations.', )
elif expected_percentage - removed_percentage > 5:
display(Markdown('The algorithm seems to have removed fewer overall counts '
'than would be naively expected.'))
warnings.append('Algorithm removed fewer counts overall than naive expectations.', )
def assess_learning_curve(adata,
spike_size: float = 0.5,
deviation_size: float = 0.25,
monotonicity_cutoff: float = 0.1):
global warnings
display(Markdown('## Assessing convergence of the algorithm'))
plot_learning_curve(adata)
if 'learning_curve_train_elbo' not in adata.uns.keys():
return
display(Markdown(
'*<span style="color:gray">The learning curve tells us about the progress of the algorithm in '
'inferring all the latent variables in our model. We want to see '
'the ELBO increasing as training epochs increase. Generally it is '
'desirable for the ELBO to converge at some high plateau, and be fairly '
'stable.</span>*'))
display(Markdown(
'*<span style="color:gray">What to watch out for:</span>*'
))
display(Markdown(
'*<span style="color:gray">1. large downward spikes in the ELBO (of value more than a few hundred)</span>*\n'
'*<span style="color:gray">2. the test ELBO can be smaller than the train ELBO, but generally we '
'want to see both curves increasing and reaching a stable plateau. We '
'do not want the test ELBO to dip way back down at the end.</span>*\n'
'*<span style="color:gray">3. lack of convergence, where it looks like the ELBO would change '
'quite a bit if training went on for more epochs.</span>*'
))
if adata.uns['learning_curve_train_epoch'][-1] < 50:
display(Markdown('Short run. Will not analyze the learning curve.'))
warnings.append(f'Short run of only {adata.uns["learning_curve_train_epoch"][-1]} epochs')
return
train_elbo_min_max = np.percentile(adata.uns['learning_curve_train_elbo'], q=[5, 95])
train_elbo_range = train_elbo_min_max.max() - train_elbo_min_max.min()
# look only from epoch 45 onward for spikes in train ELBO
large_spikes_in_train = np.any((adata.uns['learning_curve_train_elbo'][46:]
- adata.uns['learning_curve_train_elbo'][45:-1])
< -train_elbo_range * spike_size)
second_half_train_elbo = (adata.uns['learning_curve_train_elbo']
[(len(adata.uns['learning_curve_train_elbo']) // 2):])
large_deviation_in_train = np.any(second_half_train_elbo
< np.median(second_half_train_elbo)
- train_elbo_range * deviation_size)
half = len(adata.uns['learning_curve_train_elbo']) // 2
threequarter = len(adata.uns['learning_curve_train_elbo']) * 3 // 4
typical_end_variation = np.std(adata.uns['learning_curve_train_elbo'][half:threequarter])
low_end_in_train = (adata.uns['learning_curve_train_elbo'][-1]
< adata.uns['learning_curve_train_elbo'].max() - 5 * typical_end_variation)
# look only from epoch 45 onward for spikes in train ELBO
non_monotonicity = ((adata.uns['learning_curve_train_elbo'][46:]
- adata.uns['learning_curve_train_elbo'][45:-1])
< -3 * typical_end_variation).sum() / len(adata.uns['learning_curve_train_elbo'])
non_monotonic = (non_monotonicity > monotonicity_cutoff)
def windowed_cumsum(x, n=20):
return np.array([np.cumsum(x[i:(i + n)])[-1] for i in range(len(x) - n)])
windowsize = 20
tracking_trace = windowed_cumsum(adata.uns['learning_curve_train_elbo'][1:]
- adata.uns['learning_curve_train_elbo'][:-1],
n=windowsize)
big_dip = -1 * (adata.uns['learning_curve_train_elbo'][-1]
- adata.uns['learning_curve_train_elbo'][5]) / 10
backtracking = (tracking_trace.min() < big_dip)
backtracking_ind = np.argmin(tracking_trace) + windowsize
halftest = len(adata.uns['learning_curve_test_elbo']) // 2
threequartertest = len(adata.uns['learning_curve_test_elbo']) * 3 // 4
typical_end_variation_test = np.std(adata.uns['learning_curve_test_elbo'][halftest:threequartertest])
runaway_test = (adata.uns['learning_curve_test_elbo'][-1]
< adata.uns['learning_curve_test_elbo'].max() - 4 * typical_end_variation_test)
non_convergence = (np.mean([adata.uns['learning_curve_train_elbo'][-1]
- adata.uns['learning_curve_train_elbo'][-2],
adata.uns['learning_curve_train_elbo'][-2]
- adata.uns['learning_curve_train_elbo'][-3]])
> 2 * typical_end_variation)
display(Markdown('**Automated assessment** --------'))
if large_spikes_in_train:
warnings.append('Large spikes in training ELBO.')
display(Markdown('- *WARNING*: Large spikes detected in the training ELBO.'))
if large_deviation_in_train:
warnings.append('Large deviation in training ELBO from max value late in learning.')
display(Markdown('- *WARNING*: The training ELBO deviates quite a bit from '
'the max value during the second half of training.'))
if low_end_in_train:
warnings.append('Large deviation in training ELBO from max value at end.')
display(Markdown('- The training ELBO deviates quite a bit from '
'the max value at the last epoch.'))
if non_monotonic:
warnings.append('Non-monotonic training ELBO.')
display(Markdown('- We typically expect to see the training ELBO increase almost '
'monotonically. This curve seems to have a lot more downward '
'motion than we like to see.'))
if backtracking:
warnings.append('Back-tracking in training ELBO.')
display(Markdown('- We typically expect to see the training ELBO increase almost '
'monotonically. This curve seems to have a concerted '
f'period of motion in the wrong direction near epoch {backtracking_ind}. '
f'If this is early in training, this is probably okay.'))
if runaway_test:
warnings.append('Final test ELBO is much lower than the max test ELBO.')
display(Markdown('- We hope to see the test ELBO follow the training ELBO, '
'increasing almost monotonically (though there will be '
'deviations, and that is expected). There may be a large '
'gap, and that is okay. However, this curve '
'ends with a low test ELBO compared to the max test ELBO '
'value during training. The output could be suboptimal.'))
if non_convergence:
warnings.append('Non-convergence of training ELBO.')
display(Markdown('- We typically expect to see the training ELBO come to a '
'stable plateau value near the end of training. Here '
'the training ELBO is still moving quite a bit.'))
display(Markdown('**Summary**:'))
if large_spikes_in_train or large_deviation_in_train:
display(Markdown('This is unusual behavior, and a reduced --learning-rate '
'is indicated. Re-run with half the current learning '
'rate and compare the results.'))
elif low_end_in_train or non_monotonic or runaway_test:
display(Markdown('This is slightly unusual behavior, and a reduced '
'--learning-rate might be indicated. Consider re-running '
'with half the current learning rate to compare the results.'))
elif non_convergence:
display(Markdown('This is slightly unusual behavior, and more training '
'--epochs might be indicated. Consider re-running '
'for more epochs to compare the results.'))
else:
display(Markdown('This learning curve looks normal.'))
def plot_learning_curve(adata):
if 'learning_curve_train_elbo' not in adata.uns.keys():
print('No learning curve recorded!')
return
def _mkplot():
plt.plot(adata.uns['learning_curve_train_epoch'],
adata.uns['learning_curve_train_elbo'], label='train')
try:
plt.plot(adata.uns['learning_curve_test_epoch'],
adata.uns['learning_curve_test_elbo'], '.:', label='test')
plt.legend()
except Exception:
pass
plt.title('Learning curve')
plt.ylabel('ELBO')
plt.xlabel('Epoch')
if len(adata.uns['learning_curve_train_elbo']) > 20:
# two panels: zoom on the right-hand side
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
_mkplot()
plt.subplot(1, 2, 2)
_mkplot()
plt.title('Learning curve (zoomed in)')
low = np.percentile(adata.uns['learning_curve_train_elbo'], q=10)
if (len(adata.uns['learning_curve_train_elbo']) > 0) \
and (len(adata.uns['learning_curve_test_elbo']) > 0):
high = max(adata.uns['learning_curve_train_elbo'].max(),
adata.uns['learning_curve_test_elbo'].max())
else:
high = adata.uns['learning_curve_train_elbo'].max()
plt.ylim([low, high + (high - low) / 10])
plt.tight_layout()
plt.show()
else:
_mkplot()
plt.show()
def assess_count_removal_per_gene(adata,
raw_full_adata,
input_layer_key='raw',
r_squared_cutoff=0.5,
extended=True):
global warnings
display(Markdown('## Examine count removal per gene'))
# how well does it correlate with our expectation about the ambient RNA profile?
cells = (adata.obs['cell_probability'] > 0.5)
counts = np.array(raw_full_adata.X.sum(axis=1)).squeeze()
clims = [adata.obs[f'n_{input_layer_key}'][~cells].mean() / 2,
np.percentile(adata.obs[f'n_{input_layer_key}'][cells].values, q=2)]
# if all are called "cells" then clims[0] will be a nan
if np.isnan(clims[0]):
clims[0] = counts.min()
if 'approximate_ambient_profile' in adata.uns.keys():
approximate_ambient_profile = adata.uns['approximate_ambient_profile']
else:
empty_count_matrix = raw_full_adata[(counts > clims[0]) & (counts < clims[1])].X
if empty_count_matrix.shape[0] > 100:
approximate_ambient_profile = np.array(raw_full_adata[(counts > clims[0])
& (counts < clims[1])].X.mean(axis=0)).squeeze()
else:
# a very rare edge case I've seen once
display(Markdown('Having some trouble finding the empty droplets via heuristics. '
'The "approximate background estimated from empty droplets" may be inaccurate.'))
approximate_ambient_profile = np.array(raw_full_adata[counts < clims[1]].X.mean(axis=0)).squeeze()
approximate_ambient_profile = approximate_ambient_profile / approximate_ambient_profile.sum()
y = adata.var['n_removed'] / adata.var['n_removed'].sum()
maxval = (approximate_ambient_profile / approximate_ambient_profile.sum()).max()
def _plot_identity(maxval):
plt.plot([0, maxval], [0, maxval], 'lightgray')
if extended:
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(approximate_ambient_profile, adata.var['ambient_expression'], '.', ms=2)
_plot_identity(maxval)
plt.xlabel('Approximate background per gene\nestimated from empty droplets')
plt.ylabel('Inferred ambient profile')
plt.title('Genes: inferred ambient')
plt.subplot(1, 2, 2)
plt.plot(approximate_ambient_profile, y, '.', ms=2)
_plot_identity(maxval)
plt.xlabel('Approximate background per gene\nestimated from empty droplets')
plt.ylabel('Removal per gene')
plt.title('Genes: removal')
plt.tight_layout()
plt.show()
else:
plt.plot(approximate_ambient_profile, y, '.', ms=2)
_plot_identity(maxval)
plt.xlabel('Approximate background per gene\nestimated from empty droplets')
plt.ylabel('Removal per gene')
plt.title('Genes: removal')
plt.tight_layout()
plt.show()
cutoff = 1e-6
logic = np.logical_not((approximate_ambient_profile < cutoff) | (y < cutoff))
r_squared_result = scipy.stats.pearsonr(np.log(approximate_ambient_profile[logic]),
np.log(y[logic]))
if hasattr(r_squared_result, 'statistic'):
# scipy version 1.9.0+
r_squared = r_squared_result.statistic
else:
r_squared = r_squared_result[0]
display(Markdown(f'Pearson correlation coefficient for the above is {r_squared:.4f}'))
if r_squared > r_squared_cutoff:
display(Markdown('This meets expectations.'))
else:
warnings.append('Per-gene removal does not closely match a naive estimate '
'of ambient RNA from empty droplets. Does it look like '
'CellBender correctly identified the empty droplets?')
display(Markdown('WARNING: This deviates from expectations, and may '
'indicate that the run did not go well'))
percentile = 90
genecount_lowlim = int(np.percentile(adata.var[f'n_{input_layer_key}'], q=percentile))
display(Markdown('### Table of top genes removed\n\nRanked by fraction removed, '
f'and excluding genes with fewer than {genecount_lowlim} '
f'total raw counts ({percentile}th percentile)'))
df = adata.var[adata.var['cellbender_analyzed']] # exclude omitted features
df = df[[c for c in df.columns if (c != 'features_analyzed_inds')]]
display(HTML(df[df[f'n_{input_layer_key}'] > genecount_lowlim]
.sort_values(by='fraction_removed', ascending=False).head(10).to_html()))
for g in adata.var[(adata.var[f'n_{input_layer_key}_cells'] > genecount_lowlim)
& (adata.var['fraction_removed'] > 0.8)].index:
warnings.append(f'Expression of gene {g} decreases quite a bit')
display(Markdown(f'**WARNING**: The expression of the highly-expressed '
f'gene {g} decreases quite markedly after CellBender. '
f'Check to ensure this makes sense!'))
if extended:
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.semilogx(adata.var[f'n_{input_layer_key}'],
adata.var['fraction_remaining'], 'k.', ms=1)
plt.ylim([-0.05, 1.05])
plt.xlabel('Number of counts in raw data')
plt.ylabel('Fraction of counts remaining')
plt.title('Genes: removal of counts\nfrom the entire dataset')
plt.subplot(1, 2, 2)
plt.semilogx(adata.var[f'n_{input_layer_key}_cells'],
adata.var['fraction_remaining_cells'], 'k.', ms=1)
plt.ylim([-0.05, 1.05])
plt.xlabel('Number of counts in raw data')
plt.ylabel('Fraction of counts remaining')
plt.title('Genes: removal of counts\nfrom (inferred) cell-containing droplets')
plt.show()
def plot_counts_and_probs_per_cell(adata, input_layer_key='raw'):
limit_to_features_analyzed = True
if limit_to_features_analyzed:
var_logic = adata.var['cellbender_analyzed']
else:
var_logic = ...
in_counts = np.array(adata.layers[input_layer_key][:, var_logic].sum(axis=1)).squeeze()
# cellbender_counts = np.array(adata.layers['cellbender'][:, var_logic].sum(axis=1)).squeeze()
order = np.argsort(in_counts)[::-1]
# plt.semilogy(cellbender_counts[order], '.:', ms=3, color='lightgray', alpha=0.5, label='cellbender')
plt.semilogy(in_counts[order], 'k-', lw=1, label=input_layer_key)
plt.xlabel('Sorted barcode ID')
plt.ylabel('Unique UMI counts' + ('\n(for features analyzed by CellBender)'
if limit_to_features_analyzed else ''))
plt.legend(loc='lower left', title='UMI counts')
plt.gca().twinx()
plt.plot(adata.obs['cell_probability'][order].values, '.', ms=2, alpha=0.2, color='red')
plt.ylabel('Inferred cell probability', color='red')
plt.yticks([0, 0.25, 0.5, 0.75, 1.0], color='red')
plt.ylim([-0.05, 1.05])
plt.show()
def plot_validation_plots(adata, input_layer_key='raw',
output_layer_key='cellbender',
extended=True):
display(Markdown('*<span style="color:gray">The intent is to change the input '
'data as little as possible while achieving noise removal. '
'These plots show general summary statistics about similarity '
'of the input and output data. We expect to see the data '
'lying close to a straight line (gray). There may be '
'outlier genes/features, which are often those highest-'
'expressed in the ambient RNA.</span>*'))
display(Markdown('The plots here show data '
'for inferred cell-containing droplets, and exclude the '
'empty droplets.'))
cells = (adata.obs['cell_probability'] > 0.5)
# counts per barcode
plt.figure(figsize=(9, 4))
plt.subplot(1, 2, 1)
plt.loglog(adata.obs[f'n_{input_layer_key}'][cells].values,
adata.obs[f'n_{output_layer_key}'][cells].values,
'.', ms=3, alpha=0.8, rasterized=True)
minmax = [adata.obs[f'n_{input_layer_key}'][cells].min() / 10,
adata.obs[f'n_{input_layer_key}'][cells].max() * 10]
plt.loglog(minmax, minmax, lw=1, color='gray', alpha=0.5)
plt.xlabel('Input counts per barcode')
plt.ylabel(f'{output_layer_key} counts per barcode')
plt.title('Droplet count concordance\nin inferred cell-containing droplets')
plt.axis('equal')
# counts per gene
plt.subplot(1, 2, 2)
plt.loglog(adata.var[f'n_{input_layer_key}_cells'],
adata.var[f'n_{output_layer_key}_cells'],
'.', ms=3, alpha=0.8, rasterized=True)
minmax = [adata.var[f'n_{input_layer_key}_cells'].min() / 10,
adata.var[f'n_{input_layer_key}_cells'].max() * 10]
plt.loglog(minmax, minmax, lw=1, color='gray', alpha=0.5)
plt.xlabel('Input counts per gene')
plt.ylabel(f'{output_layer_key} counts per gene')
plt.title('Gene count concordance\nin inferred cell-containing droplets')
plt.axis('equal')
plt.tight_layout()
plt.show()
cells = (adata.obs['cell_probability'] >= 0.5)
if extended:
# Fano factor per barcode
plt.figure(figsize=(9, 4))
plt.subplot(1, 2, 1)
plt.loglog(fano(adata.layers[input_layer_key][cells], axis=1),
fano(adata.layers[output_layer_key][cells], axis=1), '.', ms=1)
plt.loglog([1e0, 1e3], [1e0, 1e3], lw=1, color='gray', alpha=0.5)
plt.xlabel('Input Fano factor per droplet')
plt.ylabel(f'{output_layer_key} Fano factor per droplet')
plt.title('Droplet count variance\nin inferred cell-containing droplets')
plt.axis('equal')
# Fano factor per gene
plt.subplot(1, 2, 2)
plt.loglog(fano(adata.layers[input_layer_key][cells], axis=0),
fano(adata.layers[output_layer_key][cells], axis=0), '.', ms=1)
plt.loglog([1e0, 1e3], [1e0, 1e3], lw=1, color='gray', alpha=0.5)
plt.xlabel('Input Fano factor per gene')
plt.ylabel(f'{output_layer_key} Fano factor per gene')
plt.title('Gene count variance\nin inferred cell-containing droplets')
plt.axis('equal')
plt.tight_layout()
plt.show()
# histogram of per-cell cosine distances
# cells_in_data = latents['barcodes_analyzed_inds'][latents['cell_probability'] >= 0.5]
cosine_dist = []
for bc in np.random.permutation(np.where(cells)[0])[:300]:
cosine_dist.append(cosine(np.array(adata.layers[input_layer_key][bc, :].todense()).squeeze(),
np.array(adata.layers[output_layer_key][bc, :].todense()).squeeze()))
cosine_dist = np.array(cosine_dist)
plt.hist(cosine_dist, bins=100)
plt.xlabel('Cosine distance between cell before and after')
plt.ylabel('Number of cells')
plt.title('Per-cell expression changes')
plt.show()
print(f'cosine_dist.mean = {cosine_dist.mean():.4f}')
display(Markdown('We want this cosine distance to be as small as it can be '
'(though it cannot be zero, since we are removing counts). '
'There is no specific threshold value above which we are '
'concerned, but typically we see values below 0.05.'))
def plot_gene_removal_histograms(adata, input_layer_key='raw', plot_truth=False, out_layer_key='cellbender'):
order_gene = np.argsort(np.array(adata.var[f'n_{input_layer_key}']))[::-1]
bins = np.arange(50) - 0.5
plt.figure(figsize=(14, 6))
for i, g_ind in enumerate([0, 5, 10, 20, 100, 1000]):
if g_ind >= len(order_gene):
break
plt.subplot(2, 3, i + 1)
plt.hist(np.array(adata.layers[input_layer_key][:, order_gene[g_ind]].todense()).squeeze(),
bins=bins, log=True, label=input_layer_key, histtype='step')
plt.hist(np.array(adata.layers[out_layer_key][:, order_gene[g_ind]].todense()).squeeze(),
bins=bins, log=True, label=out_layer_key, alpha=0.75, histtype='step')
if plot_truth:
plt.hist(np.array(adata.layers['truth'][:, order_gene[g_ind]].todense()).squeeze(),
bins=bins, log=True, label='truth', alpha=0.5, histtype='step')
plt.xlabel('counts per cell', fontsize=12)
plt.title(f'{adata.var_names[order_gene[g_ind]]}: rank {g_ind} in ambient', fontsize=12)
plt.ylabel('number of cells', fontsize=12)
plt.legend()
plt.tight_layout()
plt.show()
def show_gene_expression_before_and_after(adata,
input_layer_key: str = 'raw',
num: int = 10):
"""Display gene expression as an image.
Show what was removed.
Show what should have been removed.
Show residual.
"""
inds = np.where(adata.obs['cell_probability'] > 0.5)[0][:num]
# ambient sort order
order = np.argsort(adata.var['truth_ambient_expression'])[::-1]
for i in inds:
raw = np.array(adata.layers[input_layer_key][i, :].todense(), dtype=float).squeeze()
# size of images
nz_inds = np.where(raw[order] > 0)[0]
nrows = int(np.floor(np.sqrt(nz_inds.size)).item())
imsize = (nrows, int(np.ceil(nz_inds.size / max(1, nrows)).item()))
raw = np.resize(raw[order][nz_inds], imsize[0] * imsize[1]).reshape(imsize)
overflow = (imsize[0] * imsize[1]) - nz_inds.size + 1
raw[-1, -overflow:] = 0.
post = np.array(adata.layers['cellbender'][i, :].todense(), dtype=float).squeeze()
post = np.resize(post[order][nz_inds], imsize[0] * imsize[1]).reshape(imsize)
post[-1, -overflow:] = 0.
true_ambient = np.resize(adata.var['truth_ambient_expression'][order][nz_inds],
imsize[0] * imsize[1]).reshape(imsize)
true_ambient[-1, -overflow:] = 0.
true = np.array(adata.layers['truth'][i, :].todense(), dtype=float).squeeze()
true = np.resize(true[order][nz_inds], imsize[0] * imsize[1]).reshape(imsize)
true[-1, -overflow:] = 0.
lim = max(np.log1p(post).max(), np.log1p(true).max(), np.log1p(raw).max())
plt.figure(figsize=(14, 3))
# plt.subplot(1, 4, 1)
# plt.imshow(np.log1p(raw), vmin=1, vmax=lim)
# plt.title(f'log raw [{np.expm1(lim):.1f}]')
# plt.xticks([])
# plt.yticks([])
plt.subplot(1, 4, 1)
plt.imshow(np.log1p(post), vmin=1, vmax=lim)
plt.title(f'log posterior [{np.expm1(lim):.1f}]')
plt.xticks([])
plt.yticks([])
plt.subplot(1, 4, 2)
dat = (raw - true)
minmax = max(-1 * dat.min(), dat.max())
plt.imshow(dat, cmap='seismic', vmin=-1 * minmax, vmax=minmax)
plt.title(f'raw - truth [{minmax:.1f}]')
plt.xticks([])
plt.yticks([])
plt.subplot(1, 4, 3)
dat = (raw - post)
# minmax = max(-1*dat.min(), dat.max())
cmap = plt.get_cmap('seismic', 2 * minmax + 1)
plt.imshow(dat, cmap=cmap, vmin=-1 * minmax, vmax=minmax)
plt.title(f'raw - posterior [{minmax}]')
plt.xticks([])
plt.yticks([])
plt.subplot(1, 4, 4)
dat = (true - post)
thisminmax = max(-1 * dat.min(), dat.max())
minmax = max(thisminmax, minmax)
plt.imshow(-dat, cmap='seismic', vmin=-1 * minmax, vmax=minmax)
if minmax == dat.max():
plt.title(f'truth - posterior [- {minmax:.1f}]')
else:
plt.title(f'truth - posterior [{minmax:.1f}]')
plt.xticks([])
plt.yticks([])
plt.show()