-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanalyze_cut.py
2088 lines (1391 loc) · 62.5 KB
/
analyze_cut.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
# coding: utf-8
# Based on: Per-cut analysis.ipynb
# <h1>Table of Contents<span class="tocSkip"></span></h1>
# <div class="toc" style="margin-top: 1em;"><ul class="toc-item"><li><span><a href="#Load-cibersort-results" data-toc-modified-id="Load-cibersort-results-1"><span class="toc-item-num">1 </span>Load cibersort results</a></span></li><li><span><a href="#Convergence-checks." data-toc-modified-id="Convergence-checks.-2"><span class="toc-item-num">2 </span>Convergence checks.</a></span></li><li><span><a href="#Load-traces" data-toc-modified-id="Load-traces-3"><span class="toc-item-num">3 </span>Load traces</a></span></li><li><span><a href="#Plot" data-toc-modified-id="Plot-4"><span class="toc-item-num">4 </span>Plot</a></span><ul class="toc-item"><li><span><a href="#Make-these-plots-for-every-mixture." data-toc-modified-id="Make-these-plots-for-every-mixture.-4.1"><span class="toc-item-num">4.1 </span>Make these plots for every mixture.</a></span></li></ul></li><li><span><a href="#Traceplots" data-toc-modified-id="Traceplots-5"><span class="toc-item-num">5 </span>Traceplots</a></span></li><li><span><a href="#correlation-matrix" data-toc-modified-id="correlation-matrix-6"><span class="toc-item-num">6 </span>correlation matrix</a></span></li><li><span><a href="#Percentiles" data-toc-modified-id="Percentiles-7"><span class="toc-item-num">7 </span>Percentiles</a></span></li><li><span><a href="#Output-summary-csv" data-toc-modified-id="Output-summary-csv-8"><span class="toc-item-num">8 </span>Output summary csv</a></span></li><li><span><a href="#brief-validation" data-toc-modified-id="brief-validation-9"><span class="toc-item-num">9 </span>brief validation</a></span></li></ul></div>
# In[1]:
import numpy as np
import matplotlib as mpl
import pandas as pd
mpl.use("Agg")
import matplotlib.pyplot as plt
#get_ipython().run_line_magic('matplotlib', 'inline')
import seaborn as sns
import pystan
from time import time
from datetime import timedelta
import pickle
import dill
# import sys
# sys.path.append('..')
# import models
# In[2]:
# verify kernel won't crash due to MKL issue from future imports
import sklearn.linear_model.tests.test_randomized_l1
# In[10]:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--cohort_name', required=True)
parser.add_argument('--cohort_name_cib', required=True)
parser.add_argument('--slug', required=True)
parser.add_argument('--metric', required=True)
parser.add_argument('--processing', required=True)
parser.add_argument('--cutname', required=True)
parser.add_argument('--stansummary', required=True)
parser.add_argument('--trace', action='append', required=True)
parser.add_argument('--noplots', action='store_false', dest='make_all_plots', help="add this to turn off plotting (takes a long time)")
args = parser.parse_args()
# test interactively with python -i, then parser.parse_args('--trace a --trace b --trace c'.split())
import os
assert 'infino-rcc' in os.getcwd()
cohort_name = args.cohort_name # 'bladder'
cohort_name_cib = args.cohort_name_cib # 'newbladder'
slug = args.slug # 'bladder_counts_raw'
metric = args.metric # 'counts'
processing=args.processing # 'raw'
cutname = args.cutname # 'cut1'
metric_processing = '%s_%s' % (args.metric, args.processing) #'counts_raw'
#data_col = 'est_counts'
PLOT_DIR = 'plots/{slug}/'.format(slug=slug)
if not os.path.exists(PLOT_DIR):
os.makedirs(PLOT_DIR)
# In[75]:
#make_all_plots = False # set to true for prod
make_all_plots = args.make_all_plots
# In[11]:
# stan_summary_loc = 'logs/{slug}/stansummary.{slug}.csv'.format(slug=slug)
# trace_fnames = [
# 'logs/{slug}/sampling_log.cohort.{slug}.txt_{num}.csv'.format(
# slug=slug, num=i) for i in range(4)
# ]
# # bladder custom
# stan_summary_loc = '/modelcache/experiments/{cohort_name}/stansummary.{cohort_name}.{metric_processing}.csv'.format(
# slug=slug, cohort_name=cohort_name, metric_processing=metric_processing)
# trace_fnames = [
# '/modelcache/experiments/{cohort_name}/sampling_log.{cohort_name}.cut{slug}.txt_{num}.csv'.format(
# slug=slug, num=i, cohort_name=cohort_name, metric_processing=metric_processing) for i in range(4)
# ]
stan_summary_loc = args.stansummary
trace_fnames = args.trace
cohort_name, cohort_name_cib, metric, processing, metric_processing, cutname, slug, stan_summary_loc, PLOT_DIR, trace_fnames
# In[5]:
sns.set_style('darkgrid')
# # Load cibersort results
# In[117]:
cibersort_results = pd.read_csv('all_cohorts.cibersort_results.tsv', sep='\t') #, index_col=0)
cibersort_results.drop('Unnamed: 0', axis=1, inplace=True) # this is index from sub-dfs. not monotonically increasing
cibersort_results.head()
# In[118]:
cibersort_results[['cohort', 'metric', 'processing', 'cutname']].drop_duplicates()
# In[119]:
print(cibersort_results.shape)
cibersort_results = cibersort_results.loc[((cibersort_results['cohort'] == cohort_name_cib) & (cibersort_results['metric'] == metric) & (cibersort_results['processing'] == processing) & (cibersort_results['cutname'] == cutname))]
print(cibersort_results.shape)
# In[124]:
# rough confirmation that we did that right
#assert all(cibersort_results['cohort_sample_id'] == cibersort_results['Column'] + 1)
assert cibersort_results['incut_sample_id'].max() == cibersort_results.shape[0]
# In[127]:
# reindex 0,1,2...
cibersort_results.reset_index(drop=True, inplace=True)
# In[128]:
cibersort_results.index
# In[130]:
# should be same for all -- just want to get the column names
cibersort_classes = pd.read_csv('cohort_newbladder.cibersort.input.classes.datatype_est_counts.txt', sep='\t', header=None)
cibersort_classes.head()
# In[131]:
#colnames = cibersort_results.columns[(cibersort_results.columns.str.startswith('B_') | cibersort_results.columns.str.startswith('CD4_') | cibersort_results.columns.str.startswith('CD8_'))]
colnames = cibersort_classes[0].values
assert len(colnames) == 13
colnames
# In[132]:
rollups = {
'B': [c for c in colnames if c.startswith('B_')],
'CD4 T': [c for c in colnames if c.startswith('CD4_')],
'CD8 T': [c for c in colnames if c.startswith('CD8_')]
}
rollups
# In[133]:
# process cibersort
# for each mixture, compute the rollup sums
rollupsums = {}
for key in rollups:
rollupsums[key] = cibersort_results[rollups[key]].sum(axis=1)
rollupsums_df = pd.DataFrame(rollupsums)
print(rollupsums_df.shape)
rollupsums_df.head()
# In[134]:
# sanity check
assert np.allclose(rollupsums_df.sum(axis=1), 1.0)
# # Convergence checks.
# In[18]:
stan_summary = pd.read_csv(stan_summary_loc, comment='#')
stan_summary.head()
# In[19]:
stan_summary[stan_summary.name.str.startswith('sample2_x')].name.nunique()
# In[22]:
# confirm we filtered properly
assert stan_summary[stan_summary.name.str.startswith('sample2_x')].name.nunique() / len(colnames) == cibersort_results.shape[0]
print(stan_summary[stan_summary.name.str.startswith('sample2_x')].name.nunique() / len(colnames),
cibersort_results.shape[0])
# In[23]:
def savefig(fig, *args, **kwargs):
"""
Wrap figure.savefig defaulting to tight bounding box.
From https://github.com/mwaskom/seaborn/blob/dfdd1126626f7ed0fe3737528edecb71346e9eb0/seaborn/axisgrid.py#L1840
"""
kwargs.setdefault("bbox_inches", "tight")
fig.savefig(*args, **kwargs)
# In[24]:
# if this isn't true, stansummary failed (perhaps we ran it twice and appended)
assert stan_summary[stan_summary.name.str.startswith('sample2_x')]['R_hat'].dtype == 'float64'
# In[25]:
# convergence rhats
with sns.plotting_context('paper'):
#f2 = plt.figure(figsize=(6,4))
f2 = plt.figure()
sns.distplot(stan_summary[stan_summary.name.str.startswith('sample2_x')]['R_hat'])
#plt.title('Unknown mixture fraction estimates -- Rhat distribution')
plt.title('$\hat{R}$ metric of convergence (%s)' % slug)
plt.ylabel('Frequency')
plt.xlabel('$\hat{R}$')
#f2 = plt.gcf()
savefig(f2, PLOT_DIR+'Rhat_sample2-x_dist.pdf', dpi=300)
savefig(f2, PLOT_DIR+'Rhat_sample2-x_dist.png', dpi=300)
# In[26]:
stan_summary[stan_summary.name.str.startswith('sample2_x')]['R_hat'].astype(float).describe()
# In[27]:
# convergence - N_eff
with sns.plotting_context('paper'):
#f2 = plt.figure(figsize=(6,4)) # 8,6
f2 = plt.figure()
sns.distplot(stan_summary[stan_summary.name.str.startswith('sample2_x')]['N_Eff'])
# Unknown mixture fraction estimates: effective sample size distribution
plt.title('Effective sample size: is it sufficiently high for unknown mixture estimates?')
print('median', stan_summary[stan_summary.name.str.startswith('sample2_x')]['N_Eff'].median())
print('mean', stan_summary[stan_summary.name.str.startswith('sample2_x')]['N_Eff'].mean())
print('min', stan_summary[stan_summary.name.str.startswith('sample2_x')]['N_Eff'].min())
plt.ylabel('Frequency')
#f2 = plt.gcf()
savefig(f2, PLOT_DIR+'Neff_sample2-x_dist.pdf', dpi=300)
savefig(f2, PLOT_DIR+'Neff_sample2-x_dist.png', dpi=300)
# In[28]:
current_palette = sns.color_palette()
sns.palplot(current_palette)
# In[29]:
# convergence -- MCSE
with sns.plotting_context('paper'):
#f2 = plt.figure(figsize=(6,4))
f2 = plt.figure()
sns.distplot(stan_summary[stan_summary.name.str.startswith('sample2_x')]['MCSE'],
#kde_kws={'color':sns.color_palette()[2]}
)
#plt.axvline(x=stan_summary[stan_summary.name.str.startswith('sample2_x')]['MCSE'].median(),
# linestyle='dotted', lw=2.5, color=sns.color_palette()[2])
print('median', stan_summary[stan_summary.name.str.startswith('sample2_x')]['MCSE'].median())
print('mean', stan_summary[stan_summary.name.str.startswith('sample2_x')]['MCSE'].mean())
#plt.title('Unknown mixture fraction estimates: Monte Carlo error distribution')
plt.title('Monte Carlo simulation error for unknown mixture estimates')
plt.ylabel('Frequency')
#f2 = plt.gcf()
savefig(f2, PLOT_DIR+'MCSE_sample2-x_dist.pdf', dpi=300)
savefig(f2, PLOT_DIR+'MCSE_sample2-x_dist.png', dpi=300)
# In[30]:
# convergence -- standard deviation
with sns.plotting_context('paper'):
#f2 = plt.figure(figsize=(6,4))
f2 = plt.figure()
sns.distplot(stan_summary[stan_summary.name.str.startswith('sample2_x')]['StdDev'])
# plt.axvline(x=stan_summary[stan_summary.name.str.startswith('sample2_x')]['StdDev'].median(),
# linestyle='dotted', lw=2.5, color=sns.color_palette()[2])
print('median', stan_summary[stan_summary.name.str.startswith('sample2_x')]['StdDev'].median())
print('mean', stan_summary[stan_summary.name.str.startswith('sample2_x')]['StdDev'].mean())
plt.title('Posterior standard deviation for unknown mixture estimates')
plt.ylabel('Frequency')
#f2 = plt.gcf()
savefig(f2, PLOT_DIR+'StdDev_sample2-x_dist.pdf', dpi=300)
savefig(f2, PLOT_DIR+'StdDev_sample2-x_dist.png', dpi=300)
# In[31]:
stan_summary[stan_summary.name.str.startswith('sample2_x')]['StdDev'].describe()
# In[32]:
summary_ranges = stan_summary[stan_summary.name.str.startswith('sample2_x')][[
'R_hat', 'StdDev', 'MCSE', 'N_Eff'
]].astype(float).describe()
summary_ranges.to_csv(PLOT_DIR + "summarystats.{slug}.tsv".format(slug=slug), sep='\t')
summary_ranges
# # Load traces
# In[33]:
# have to load in the full traces
cols_we_want = stan_summary[stan_summary.name.str.startswith('sample2_x')].name.values
cols_we_want
# In[34]:
cols_we_want_renamed = [c.replace('[', '.').replace(']', '').replace(',', '.') for c in cols_we_want]
cols_we_want_renamed
# In[35]:
all_traces = []
for (i, fname) in zip(range(4), trace_fnames):
print('loading:', i, fname)
trace_i = pd.read_csv(fname, comment='#', usecols=cols_we_want_renamed)
trace_i['trace_id'] = i
trace_i['iter'] = trace_i.index
all_traces.append(trace_i)
# In[36]:
all_traces_df = pd.concat(all_traces)
print(all_traces_df.shape)
all_traces_df.head()
# In[37]:
all_traces_df2 = pd.melt(all_traces_df, id_vars=['iter','trace_id'], value_name='estimate', var_name='variable')
all_traces_df2.head()
# In[38]:
var_ids = all_traces_df2.variable.str.extract('sample2_x.(?P<sample_id>\d+).(?P<subset_id>\d+)')
var_ids.head()
# In[39]:
all_traces_df3= pd.concat([all_traces_df2, var_ids], axis=1)
all_traces_df3.head()
# In[40]:
all_traces_df3['subset_id'] = all_traces_df3['subset_id'].astype(int)
all_traces_df3['sample_id'] = all_traces_df3['sample_id'].astype(int)
# In[41]:
all_traces_df3.sample_id.max(), all_traces_df3.subset_id.max()
# In[42]:
sample2_xs = stan_summary[stan_summary.name.str.startswith('sample2_x')]['Mean'].values.reshape(all_traces_df3.sample_id.max(), all_traces_df3.subset_id.max()) # (10,13) before
sample2_xs.shape
# In[43]:
mixture_estimates = pd.DataFrame(sample2_xs, columns=colnames)
mixture_estimates
# In[44]:
import re
subset_names = [re.sub(string=x, pattern='(.*)\[(.*)\]', repl='\\2') for x in mixture_estimates.columns]
subset_names
# In[45]:
# switch to names from stansummary
all_traces_df3['subset_name'] = all_traces_df3.subset_id.apply(lambda i: subset_names[i-1])
all_traces_df3.head()
# In[46]:
# IMPORTANT: drop the warmup samples!!!!!
warmup = 1000
# this should show a wide range
#all_traces_df3.iter.hist()
all_traces_df3.iter.describe()[['min', 'max']]
# In[47]:
# drop warmups
all_traces_df3 = all_traces_df3.loc[all_traces_df3['iter']>=1000,]
all_traces_df3['iter'] -= 1000
# this should be better now
#all_traces_df3.iter.hist()
all_traces_df3.iter.describe()[['min', 'max']]
# In[48]:
# combine iteration numbers across traces -- i.e. line them up from 0 to 4000, not 4 versions of 0 to 1000
#(all_traces_df3['trace_id']*1000 + all_traces_df3['iter']).hist()
(all_traces_df3['trace_id']*1000 + all_traces_df3['iter']).describe()[['min', 'max']]
# In[49]:
assert (all_traces_df3['trace_id']*1000 + all_traces_df3['iter']).describe()['max'] == (len(trace_fnames) * 1000 - 1)
# In[50]:
all_traces_df3['combined_iter_number'] = (all_traces_df3['trace_id']*1000 + all_traces_df3['iter'])
# In[51]:
#assert all_traces_df3.shape[0] / 10 / 13 / 4 == 1000.
assert all_traces_df3.shape[0] / all_traces_df3.sample_id.max() / all_traces_df3.subset_id.max() / len(trace_fnames) == 1000.
# # Plot
# In[52]:
current_palette = sns.color_palette()
sns.palplot(current_palette)
# In[53]:
subset_names, colnames
# In[54]:
rollups
# In[55]:
def label_rollup(rollups, x):
for key in rollups.keys():
if x in rollups[key]:
return key
return None
# In[56]:
all_traces_df3['rollup'] = all_traces_df3.subset_name.apply(lambda x: label_rollup(rollups, x))
all_traces_df3.rollup.value_counts()
# In[57]:
samples_rolledup = all_traces_df3.groupby(['sample_id', 'combined_iter_number', 'rollup']).estimate.sum().reset_index()
samples_rolledup.head()
# In[58]:
# cibersort results
rollupsums_df.head()
# In[59]:
cleaner_traces = all_traces_df3.copy()
cleaner_traces['subset_name'] = cleaner_traces['subset_name'].str.replace(
'_', ' ')
cleaner_traces['subset_name'].value_counts()
# In[60]:
cleaner_traces.head()
# In[61]:
samples_rolledup.head()
# In[62]:
merged_samples_1 = cleaner_traces[['sample_id', 'combined_iter_number', 'subset_name', 'estimate']].copy()
merged_samples_1['type'] = 'subset'
merged_samples_2 = samples_rolledup.copy()
merged_samples_2.columns = [c.replace('rollup', 'subset_name') for c in merged_samples_2.columns]
merged_samples_2['type'] = 'rollup'
merged_samples = pd.concat([merged_samples_1, merged_samples_2])
merged_samples.type.value_counts()
# In[63]:
#sns.set_context('paper')
sns.set_style("darkgrid")
# In[64]:
def extract_values_for_mixture_by_id(key):
"""
key: 1-indexed, meaning mixture 1 to mixture 10
based on:
for (key, grp), \
(_, groundtruth_base), \
friendly_title, \
(_, cib_vals_base), \
(mixID_rolledup, groundtruth_rolledup), \
(_, cib_vals_rolledup) in zip(merged_samples.groupby('sample_id'),
cleaner_gt.iterrows(),
#friendly_mixture_descriptions2,
friendly_mixture_descriptions,
example_result[cib_class_names].iterrows(),
rollup_groundtruth.groupby('mixID'),
rollupsums_df.iterrows()
"""
grp = merged_samples[merged_samples['sample_id'] == key]
#groundtruth_base = cleaner_gt.iloc[key-1]
cib_vals_base = cibersort_results[colnames].iloc[key - 1]
#groundtruth_rolledup = rollup_groundtruth[rollup_groundtruth['mixID'] == key-1]
cib_vals_rolledup = rollupsums_df.iloc[key - 1]
return (key,
grp,
#groundtruth_base,
cib_vals_base,
#groundtruth_rolledup,
cib_vals_rolledup)
# In[65]:
col_order = [[cat] + rollups[cat] for cat in rollups]
col_order = [item for sublist in col_order for item in sublist] # flatten: https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
col_order = [c.replace('_', ' ') for c in col_order]
col_order
# In[66]:
def plot_single_mixture_results(mixture_info, friendly_title):
#flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"] # http://seaborn.pydata.org/tutorial/color_palettes.html
#sns.palplot(flatui)
paired_colors = sns.color_palette("Paired_r", 12)
#sns.palplot(paired_colors)
(key,
grp,
#groundtruth_base,
cib_vals_base,
#groundtruth_rolledup,
cib_vals_rolledup
) = mixture_info
with sns.plotting_context('paper'):
f, ax = plt.subplots( figsize=(12,8))
g = sns.boxplot(data = grp,
y='subset_name',
x='estimate',
ax=ax,
hue='type',
order=col_order,
# some additional parameters that we think may help:
saturation=1,
linewidth=1, # not sure about this one
dodge=False, # avoid hue nesting
#palette=[flatui[0], flatui[1]]
palette=paired_colors[0:2]
)
g.set_title(friendly_title)
# # ground truth
# gt1 = pd.DataFrame(groundtruth_base).reset_index()
# gt1.columns = ['rollup', 'estimate']
# gt1['type'] = 'subset'
# gt2 = groundtruth_rolledup[['rollup', 'estimate']].copy()
# gt2['type'] = 'rollup'
# gt = pd.concat([gt1, gt2])
# sns.stripplot(
# x="estimate",
# y="rollup",
# data=gt,
# hue='type',
# order=col_order,
# linewidth=0,
# size=15,
# alpha=.9,
# marker=(5, 1),
# #palette=[flatui[5], flatui[3]],
# palette=paired_colors[2:4],
# zorder=5,
# jitter=False,
# label='Ground Truth' # https://github.com/mwaskom/seaborn/issues/940 -- without this line, the stars aren't shown in legend entries made by "hue" param; instead you get a ton of dupe Ground Truth star labels
# )
# add cibersort points
cb_base = pd.DataFrame(cib_vals_base).reset_index()
cb_base.columns = ['SubSet', 'estimate']
cb_base['type'] = 'subset'
cb_rolledup = pd.DataFrame(cib_vals_rolledup).reset_index()
cb_rolledup.columns = ['SubSet', 'estimate']
cb_rolledup['type'] = 'rollup'
cb = pd.concat([cb_base, cb_rolledup])
cb.SubSet = cb.SubSet.str.replace('_', ' ') # normalize names
sns.stripplot(
x="estimate",
y="SubSet",
data=cb,
hue='type',
order=col_order,
linewidth=0,
size=15,
alpha=.9,
marker=(3, 0),
#palette=[flatui[2], flatui[4]],
palette=paired_colors[4:6],
zorder=6,
jitter=False,
label='Cibersort' # see above again re this label parameter
)
g.set_xlabel('Mixture proportion')
g.set_ylabel('Cell type')
g.set_xbound(0, 1)
# show legend, and subselect because stripplot adds one legend item per point it appears
handles, labels = ax.get_legend_handles_labels()
"""
want legend items:
* infino samples: items 0, 1
* ground truth stars: items 2, 3
* cibersort triangles: items 2+len(col_order)+2, 2+len(col_order)+2+1
"""
chosen_idx = [1,
0,
2,3,
#2+len(col_order)+2, 2+len(col_order)+2+1
]
chosen_handles = [handles[i] for i in chosen_idx]
#chosen_labels = [labels[i] for i in chosen_idx]
chosen_labels = ['Infino (sums)',
'Infino',
#'Ground Truth (sums)',
#'Ground Truth',
'Cibersort (sums)',
'Cibersort']
legend = ax.legend(
chosen_handles,
chosen_labels,
loc='lower right',
frameon=True)
frame = legend.get_frame()
frame.set_edgecolor('red')
frame.set_facecolor('white')
# shade background
#fill1 = plt.axhspan('B', 'CD4 T', facecolor='0.5', alpha=0.5)
fill1 = plt.axhspan(-0.5, 3.5, facecolor='0.8', alpha=0.3)
fill3 = plt.axhspan(11.5, 15.5, facecolor='0.8', alpha=0.3)
# improve label format
# https://stackoverflow.com/a/34426167/130164
for label in ax.get_yticklabels():
if label.get_text() in rollups.keys():
label.set_size(15)
label.set_backgroundcolor("yellow")
label.set_weight("bold")
label.set_color("red")
else:
label.set_fontstyle("italic")
label.set_weight("bold")
return f,ax
# In[67]:
f,ax = plot_single_mixture_results(extract_values_for_mixture_by_id(7),
'Text mixture')
# savefig(f, PLOT_DIR+'fig1b.png', dpi=300)
# savefig(f, PLOT_DIR+'fig1b.pdf', dpi=300)
# Also bringing in new plots from `2.1.2.1 MCMC figure plotting`
# In[68]:
# set up order and colors
paired_colors = sns.color_palette("Paired_r", 12)
# colors for ground truth and cibersort overlays
sns.palplot([paired_colors[4], paired_colors[6]])
hue_order = []
built_palette = []
for r, start in zip(list(rollups), range(0,3)):
hue_order.extend(rollups[r])
hue_order.append(r)
full_pal = sns.cubehelix_palette(len(rollups[r]) + 3,
start=start,
rot=-.25,
light=.7)
# first #subtypes colors
built_palette.extend(full_pal[:len(rollups[r])])
# then a darker color (but not the darkest)
built_palette.append(full_pal[-2])
hue_order = [h.replace('_', ' ') for h in hue_order]
sns.palplot(built_palette)
print(hue_order)
color_lightening_coeff = 1.2
built_pal_lighter2 = [(np.array(i) * color_lightening_coeff).clip(0,1) for i in built_palette]
sns.palplot(built_pal_lighter2)
# In[69]:
def merge_datasets_for_plots(mixID):
mymix = extract_values_for_mixture_by_id(mixID)
(key,
grp,
#groundtruth_base,
cib_vals_base,
#groundtruth_rolledup,
cib_vals_rolledup
) = mymix
grp=grp.copy() # because going to modify
grp['supertype'] = grp['subset_name'].apply(lambda x: 'CD4 T' if 'CD4' in x else 'CD8 T' if 'CD8' in x else 'B')
map_row_to_ylevel = {}
for k in rollups:
map_row_to_ylevel[k] = 0
for v,s in zip(rollups[k], range(1, len(rollups[k]) + 1)):
map_row_to_ylevel[v.replace('_', ' ')] = s
grp['ylevel'] = grp['subset_name'].apply(lambda x: map_row_to_ylevel[x])
# # add ground truth
# gt1 = pd.DataFrame(groundtruth_base).reset_index()
# gt1.columns = ['rollup', 'estimate']
# gt1['type'] = 'subset'
# gt2 = groundtruth_rolledup[['rollup', 'estimate']].copy()
# gt2['type'] = 'rollup'
# gt = pd.concat([gt1, gt2])
# gt['gt'] = gt['estimate']
# del gt['estimate']
# merged_grp = pd.merge(grp, gt, left_on='subset_name', right_on='rollup', how='left')
merged_grp = grp
# add cibersort points
cb_base = pd.DataFrame(cib_vals_base).reset_index()
cb_base.columns = ['SubSet', 'estimate']
cb_base['type'] = 'subset'
cb_rolledup = pd.DataFrame(cib_vals_rolledup).reset_index()
cb_rolledup.columns = ['SubSet', 'estimate']
cb_rolledup['type'] = 'rollup'
cb = pd.concat([cb_base, cb_rolledup])
cb.SubSet = cb.SubSet.str.replace('_', ' ') # normalize names
cb = cb.rename(columns={'estimate': 'cb'})
merged_grp2 = pd.merge(merged_grp, cb, left_on='subset_name', right_on='SubSet', how='left')
# # compute infino, cibersort, groundtruth relative to ground truth (i.e. 0 is gt)
# merged_grp2['estimate_rel_gt'] = merged_grp2['estimate'] - merged_grp2['gt']
# merged_grp2['cb_rel_gt'] = merged_grp2['cb'] - merged_grp2['gt']
# merged_grp2['gt_rel_gt'] = 0.0
# turn ylevel into a categorical variable so that violinplot knows what to do with it
merged_grp2['ylevel_str'] = merged_grp2['ylevel'].apply(lambda x: chr(65+x))
merged_grp2['ylevel_str'].unique()
return merged_grp2 # has everything for plots
# In[70]:
merge_datasets_for_plots(1).head()
# In[71]:
def plot_mcmc_areas(merged_dataset, relative_to_groundtruth=False):
"""
plot MCMC areas, perhaps relative_to_groundtruth if flag enabled
feed in output of merge_datasets_for_plots(mixID)
"""
# HERE THERE'S NO GT
assert not relative_to_groundtruth
estimate_var = 'estimate_rel_gt' if relative_to_groundtruth else 'estimate'
gt_var = 'gt_rel_gt' if relative_to_groundtruth else 'gt'
cb_var = 'cb_rel_gt' if relative_to_groundtruth else 'cb'
label_cut_point = 0 if relative_to_groundtruth else .5
with sns.plotting_context("talk"):
with sns.axes_style("white", rc={"axes.facecolor": (0, 0, 0, 0)}):
g = sns.FacetGrid(merged_dataset,
row="ylevel",
hue="subset_name",
col="supertype",
row_order=reversed(list(range(merged_dataset.ylevel.values.max()+1))),
hue_order=hue_order,
aspect=15,
size=.5,
palette=built_palette,
sharey=False # important -- they don't share y ranges.
)
## Draw the densities in a few steps
# this is the shaded area
g.map(sns.kdeplot,
estimate_var,
clip_on=False,
shade=True,
alpha=.8,
lw=2,
)
# this is the dividing horizontal line
g.map(plt.axhline, y=0, lw=2, clip_on=False, ls='dashed')
### Add label for each facet.
def label(type_series, estimates, cut_point=.5, **kwargs):
"""
type_series is a Series that corresponds to this facet. it will have values "subset" or "rollup"
kwargs is e.g.: {'color': (0.4918017777777778, 0.25275644444444445, 0.3333333333333333), 'label': 'CD4 Treg'}
use estimates to find median. put rollup label on left/right based on that
"""
type_of_label = type_series.values[0]
color = kwargs['color']
label = kwargs['label']
estimate_median = estimates.median()
ax = plt.gca() # map() changes current axis repeatedly
if type_of_label == 'rollup':
plot_on_right = (estimate_median <= cut_point)
ax.text(
1 if plot_on_right else 0,
.2,
label + " (sum)", #label,
fontweight="bold",
color=color,
ha="right" if plot_on_right else "left",
va="center", transform=ax.transAxes,
fontsize='x-large', #15,
bbox=dict(facecolor='yellow', alpha=0.3)
)
else:
ax.text(1, .2,
label,
fontweight="bold",
color=color,
ha="right", va="center", transform=ax.transAxes
)
g.map(label, "type_x", estimate_var, cut_point=label_cut_point)
### Overlay Cibersort and Ground Truth points at the right heights.
def get_kde_intersection_yval(x0, kde_x, kde_y):
"""
we want to find y value at which kde line
(defined by [kde_x, kde_y] point collection)
intersects x=x0
(kde_x, kde_y are numpy ndarrays)
"""
if x0 in kde_x:
# the point actually is in the kde point definition!
return kde_y[np.where(kde_x == x0)][0]