-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgensup_analysis.R
More file actions
4657 lines (3918 loc) · 216 KB
/
gensup_analysis.R
File metadata and controls
4657 lines (3918 loc) · 216 KB
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
overall_start_time = Sys.time()
cat(file=stderr(), 'Loading dependencies...')
options(stringsAsFactors=F)
suppressMessages(library(tidyverse))
suppressMessages(library(janitor))
suppressMessages(library(binom))
suppressMessages(library(glue))
suppressMessages(library(lawstat))
suppressMessages(library(weights))
suppressMessages(library(epitools))
suppressMessages(library(DescTools))
suppressMessages(library(openxlsx))
suppressMessages(library(optparse))
suppressMessages(library(MASS)); summarize=dplyr::summarize; select=dplyr::select;
if(interactive()) {
setwd('~/d/sci/src/genetic_support')
}
option_list = list(
make_option(c("-o", "--oto"), action="store_true", default=FALSE,
help="limit to drugs with one target only (oto mode) [default %default]")
);
opt = parse_args(OptionParser(option_list=option_list))
output_path = ifelse(opt$oto, 'oto/', 'display_items/')
##############
# OUTPUT FILE
##############
cat(file=stderr(), 'done.\nCreating output streams...'); flush.console()
text_stats_path = paste0(output_path,'stats_for_text.txt')
write(paste('Last updated: ',Sys.Date(),'\n',sep=''),text_stats_path,append=F) # start anew - but all subsequent writings will be append=T
supplement_path = paste0(output_path, 'supplement.xlsx')
supplement = createWorkbook()
supplement_directory = tibble(name=character(0), title=character(0))
unnumbered_tables = 2 # abbrevs and notes
write_supp_table = function(tbl, title='', numbered=T, tblname=NULL) {
# write Excel sheet for supplement
if (numbered) {
table_number = length(names(supplement)) + 1 - unnumbered_tables
table_name = paste0('s',formatC(table_number,'d',digits=0,width=2,flag='0'))
} else {
table_name = tblname
}
addWorksheet(supplement,table_name)
bold_style = createStyle(textDecoration = "Bold")
writeData(supplement,table_name,tbl,headerStyle=bold_style,withFilter=T)
freezePane(supplement,table_name,firstRow=T)
saveWorkbook(supplement,supplement_path,overwrite = TRUE)
# also write tab-sep version for GitHub repo
write_tsv(tbl,paste0(output_path,'table_',table_name,'.tsv'), na='')
# and save the title in the directory tibble for later
assign('supplement_directory',
supplement_directory %>% add_row(name=table_name, title=title),
envir = .GlobalEnv)
}
##############
# DATA INPUTS
##############
cat(file=stderr(), 'done.\nReading in data...')
merge2 = read_tsv('data/merge2.tsv.gz', col_types=cols())
pp = read_tsv('data/pp.tsv', col_types=cols())
drug_phase_summary = read_tsv('data/drug_phase_summary.tsv', col_types=cols())
assoc = read_tsv('data/assoc.tsv.gz', col_types=cols())
indic = read_tsv("data/indic.tsv", col_types=cols())
indic_topl_match = read_tsv('data/indic_topl_match.tsv', col_types=cols())
universe = read_tsv('data/universe.tsv', col_types=cols())
meta_hcat = read_tsv('data/meta_hcat.tsv', col_types=cols())
meta_acat = read_tsv('data/meta_acat.tsv', col_types=cols())
meta_ccat = read_tsv('data/meta_ccat.tsv', col_types=cols())
mesh_best_names = read_tsv('data/mesh_best_names.tsv.gz', col_types=cols())
sim = read_tsv('data/sim.tsv.gz', col_types=cols())
if (opt$oto) {
pp$hcat = pp$oto_hcat
pp$acat = pp$oto_acat
pp$ccat = pp$oto_ccat
pp$hcatnum = meta_hcat$num[match(pp$hcat, meta_hcat$cat)]
pp$acatnum = meta_acat$num[match(pp$acat, meta_hcat$cat)]
pp$ccatnum = meta_ccat$num[match(pp$ccat, meta_hcat$cat)]
merge2$hcat = pp$oto_hcat[match(merge2$ti_uid, pp$ti_uid)]
merge2$acat = pp$oto_acat[match(merge2$ti_uid, pp$ti_uid)]
merge2$ccat = pp$oto_ccat[match(merge2$ti_uid, pp$ti_uid)]
pp = pp[!is.na(pp$ccat),]
merge2 = merge2[!is.na(merge2$ccat),]
}
# constants
active_clinical = tibble(cat=c('Phase I','Phase II','Phase III'))
####
# Functions
####
percent = function(x, digits=0, signed=F) gsub(' ','',paste0(ifelse(x < 0, '-', ifelse(signed, '+', '')),formatC(100*x,format='f',digits=digits),'%'))
upper = function(x, ci=0.95) {
alpha = 1 - ci
sds = qnorm(1-alpha/2)
mean(x) + sds*sd(x)/sqrt(sum(!is.na(x)))
}
lower = function(x, ci=0.95) {
alpha = 1 - ci
sds = qnorm(1-alpha/2)
mean(x) - sds*sd(x)/sqrt(sum(!is.na(x)))
}
alpha = function(rgb_hexcolor, proportion) {
hex_proportion = sprintf("%02x",round(proportion*255))
rgba = paste(rgb_hexcolor,hex_proportion,sep='')
return (rgba)
}
ci_alpha = 0.35 # degree of transparency for shading confidence intervals in plot
clipdist = function(x, minx, maxx) {
return (pmin(maxx,pmax(minx,x)))
}
abs_or = function(odds_ratio) {
abs_odds_ratio = odds_ratio
flip_indices = odds_ratio < 1 & !is.na(odds_ratio)
abs_odds_ratio[flip_indices] = 1/odds_ratio[flip_indices]
return (abs_odds_ratio)
}
pipeline_best = function(merged_table,
basis='ti',
phase='combined',
require_insight=TRUE,
share_mode='L2G', # other option is V2G
min_share=0.5,
max_share=1,
worst_rank=Inf, # set to Inf if you want to include all
min_h4 = 0.9,
include_missing=FALSE,
associations=c('OMIM','GWAS'),
otg_subcat=c(''),
genebass_subcat=NULL,
mendelian_mechanism='',
min_year=2005,
max_year=2022,
firstyear=F,
minusomim=F,
lacking=NULL, # association sources required to be lacked by the T-I
andalso=NULL, # association sources required to *also* endorse the T-I
minusothersubcat=F,
mingenecount=0,
maxgenecount=Inf,
mapping_basis='all',
min_beta=0,
max_beta=Inf,
min_or=1,
max_or=Inf,
min_maf=0,
max_maf=1,
threshold=0.8,
network_list=NA,
verbose=T) {
start_time = Sys.time()
mtable = merged_table
if (verbose) {
cat(file=stderr(),'Starting row count: ',nrow(mtable),'\n')
flush.console()
}
# add & select unique ID
if (basis %in% c('di_mesh','drug-indication')) {
mtable$di_uid = paste0(mtable$drugid,'-',mtable$indication_mesh_id)
mtable$uid = mtable$di_uid
} else if (basis %in% c('ti','target-indication')) {
mtable$ti_uid = paste0(mtable$gene,'-',mtable$indication_mesh_id)
mtable$uid = mtable$ti_uid
} else if (basis=='drug') {
mtable$uid = mtable$drugid
}
# assign highest level of advancement depending on phase specified
if (phase == 'active') {
meta = meta_acat
mtable$cat = mtable$acat
} else if (phase == 'historical') {
meta = meta_hcat
mtable$cat = mtable$hcat
} else if (phase == 'combined') {
meta = meta_ccat
mtable$cat = mtable$ccat
}
mtable$catnum = meta$num[match(mtable$cat, meta$cat)]
# remove "Other"
mtable = mtable[mtable$cat != 'Other' ,]
# map L2G share
mtable$assoc_share = mtable$l2g_share
mtable$assoc_rank = mtable$l2g_rank
if (verbose) {
cat(file=stderr(),'Selecting user-specified filters...')
flush.console()
}
# by default, require non-missing target & indication
if (!include_missing) {
mtable = mtable[mtable$gene != '' & mtable$indication_mesh_id != '' & !is.na(mtable$gene) & !is.na(mtable$indication_mesh_id),]
}
# genetic insight requirement
if (require_insight) {
mtable = mtable[mtable$indication_mesh_id %in% indic$indication_mesh_id[indic$genetic_insight != 'none'],]
} else {
# otherwise simply require the indication be present in the indic table
mtable = mtable[mtable$indication_mesh_id %in% indic$indication_mesh_id,]
}
# remove omim-supported associations if desired. only works in T-I mode
# note that order of operations is important - this must come before associations filter
if (minusomim) {
# look for first year in which a target-*indication* pair was genetically supported
mtable %>%
filter(comb_norm >= threshold) %>%
filter(assoc_source %in% c('OMIM')) %>%
select(ti_uid) -> omim_supported_ti
# retain the null rows (i.e. no association) or those where hte T-I is not in OMIM
# what gets removed? e.g. OTG associations that were already established by OMIM
mtable %>%
filter(is.na(assoc_source) | !(ti_uid %in% omim_supported_ti$ti_uid)) -> mtable
}
# remove any association sources required to be lacked
if (!is.null(lacking)) {
mtable %>%
filter(comb_norm >= threshold) %>%
filter(assoc_source %in% lacking) %>%
filter(!(assoc_source %in% 'OTG' & l2g_share >= min_share)) %>%
select(ti_uid) -> lackable_supported_ti
mtable %>%
filter(is.na(assoc_source) | !(ti_uid %in% lackable_supported_ti$ti_uid)) -> mtable
}
if (!is.null(andalso)) {
mtable %>%
filter(comb_norm >= threshold) %>%
filter(assoc_source %in% andalso) %>%
filter(!(assoc_source %in% 'OTG' & l2g_share < min_share)) %>%
select(ti_uid) -> andalso_supported_ti
mtable %>%
filter(is.na(assoc_source) | (ti_uid %in% andalso_supported_ti$ti_uid)) -> mtable
}
# user-specified sources of genetic associations
# allow user to specify either grouping terms like "GWAS", or specific sources
source_map = tibble(source=c("OTG", "PICCOLO", "Genebass", "OMIM", "intOGen"),
source_name=c('GWAS','GWAS','GWAS','OMIM','Somatic'))
if (!(identical(associations, c('OMIM','GWAS','Somatic'))) ) {
mtable %>%
left_join(source_map, by=c('assoc_source'='source')) %>%
filter(is.na(source_name) | source_name %in% associations | assoc_source %in% associations) -> mtable
}
# further filter of subtype of OTG association
if (otg_subcat != '') {
# first subset to just OTG
mtable %>%
filter(is.na(assoc_source) | assoc_source %in% 'OTG') -> mtable
# now pick the types
mtable %>%
mutate(gwas_source = case_when(grepl('GCST', original_link) ~ 'GWAS Catalog',
grepl('FINNGEN', original_link) ~ 'FinnGen',
grepl('NEALE',original_link) ~ 'Neale UKBB',
TRUE ~ 'Other')) %>%
filter(is.na(assoc_source) | gwas_source %in% otg_subcat) -> mtable
}
# further filter of annotation & test in Genebass
if (!is.null(genebass_subcat)) {
grepstring = paste(genebass_subcat, collapse='|')
# mtable %>%
# filter(!is.na(assoc_source) & assoc_source %in% 'Genebass') %>%
# filter(grepl(grepstring, assoc_info)) -> genebass_hits
mtable %>%
filter(is.na(assoc_source) | !(assoc_source %in% 'Genebass') | grepl(grepstring, assoc_info)) -> mtable
}
# apply user-specified filter of OMIM disease mechanism
if (mendelian_mechanism != '') {
mtable %>%
filter(!(mtable$assoc_source %in% 'OMIM') | is.na(mtable$assoc_info) | grepl(mendelian_mechanism,mtable$assoc_info)) -> mtable
}
# apply user-specified OTG gene mapping share & rank minimum/maximum
if (share_mode == 'V2G') {
mtable$assoc_share = mtable$v2g_share
mtable$assoc_rank = mtable$v2g_rank
assoc$assoc_share = assoc$v2g_share # needed in assoc table too for genecount section below
} else if (share_mode == 'L2G') {
mtable$assoc_share = mtable$l2g_share
mtable$assoc_rank = mtable$l2g_rank
assoc$assoc_share = assoc$l2g_share
}
# worst rank
if (worst_rank < Inf) {
mtable %>%
filter(!(assoc_source %in% 'OTG') | mtable$assoc_rank <= worst_rank) -> mtable
}
# note that among OTG associations, throw out any with NA share, as these would be zeroes (does not occur in Dec 2021 dataset anyway)
# and note that with L2G a significant number of associations actually have 100% share, so only delete > max_share and not >= max_share
mtable %>%
filter(!(assoc_source %in% 'OTG') | (!is.na(assoc_share) & assoc_share >= min_share & assoc_share <= max_share)) -> mtable
# apply user-specified H4 minimum / maximum
if (min_h4 > .9) {
mtable %>%
filter(!(assoc_source %in% 'PICCOLO') | (!is.na(mtable$pic_h4) & mtable$pic_h4 >= min_h4)) -> mtable
}
# apply user-specified genecount minimum/maximum
if (mingenecount > 0 | maxgenecount < Inf) {
assoc %>%
filter(source %in% associations) %>%
filter(source!='OTG' | (assoc_share >= min_share & assoc_share <= max_share)) %>%
group_by(mesh_id) %>%
summarize(.groups='keep', n_genes=length(unique(gene))) -> gene_counts
mtable$gene_count = gene_counts$n_genes[match(mtable$assoc_mesh_id, gene_counts$mesh_id)]
mtable %>%
filter(is.na(gene_count) | gene_count >= mingenecount & gene_count <= maxgenecount) -> mtable
}
# apply "first year" criteria if applicable
if (firstyear) {
# look for first year in which a target-*indication* pair was genetically supported
# only works in T-I mode
mtable %>%
filter(comb_norm >= threshold) %>%
group_by(ti_uid) %>%
summarize(.groups='keep', min_assoc_year=min(assoc_year)) -> ti_first_sup
mtable$min_assoc_year = ti_first_sup$min_assoc_year[match(mtable$ti_uid, ti_first_sup$ti_uid)]
# keep entries with no assoc year (the null rows), or where assoc year = the min assoc year, i.e. this is
# the first report of this genetic association (or tied for first)
mtable %>%
filter(is.na(assoc_year) | assoc_year == min_assoc_year) -> mtable
}
# avoid -Inf values in comparisons by hard coding in case of all missing values:
if (sum(!is.na(mtable$assoc_year)) == 0) {
mtable_intrinsic_max_year = 2021
mtable_intrinsic_min_year = 2000
} else {
mtable_intrinsic_max_year = max(mtable$assoc_year, na.rm=T)
mtable_intrinsic_min_year = min(mtable$assoc_year, na.rm=T)
}
# apply user-specified filter of association years - for OTG only
if (min_year > mtable_intrinsic_min_year | max_year < mtable_intrinsic_max_year) {
mtable %>%
filter(is.na(assoc_source) | assoc_source != 'OTG' | assoc_year >= min_year & assoc_year <= max_year) -> mtable
}
# join back in beta
mtable$abs_beta = abs(assoc$beta[match(mtable$arow, assoc$arow)])
if (min_beta > 0 | max_beta < Inf) {
stopifnot(associations=='OTG') # only supported for OTG-only mode
mtable %>%
filter(is.na(assoc_source) | (!is.na(mtable$abs_beta) & mtable$abs_beta >= min_beta & mtable$abs_beta <= max_beta)) -> mtable
}
# same as beta but for OR
mtable$abs_or = abs_or(assoc$odds_ratio[match(mtable$arow, assoc$arow)])
if (min_or > 1 | max_or < Inf) {
stopifnot(associations=='OTG') # only supported for OTG-only mode
# leave null rows (with no association source) but delete all those mapped to OTG that do not have or, or have or outside range
mtable %>%
filter(is.na(assoc_source) | (!is.na(mtable$abs_or) & mtable$abs_or >= min_or & mtable$abs_or < max_or)) -> mtable
}
# lead SNP maf
if (min_maf > 0 | max_maf < 1) {
mtable$lead_maf = pmin(mtable$af_gnomad_nfe, 1-mtable$af_gnomad_nfe)
mtable$lead_maf[!is.na(mtable$lead_maf) & mtable$lead_maf < 0] = NA
# lead_maf >= min_maf & lead_maf < max_maf
# >= and < gets you "[, )" logic
# also remove those that are GWAS where lead_maf is NA - likely in non-European populations so af_gnomad_nfe is not relevant
mtable %>%
filter(is.na(assoc_source) | !(assoc_source %in% c('OTG','PICCOLO','Genebass')) | (!is.na(lead_maf) & (lead_maf >= min_maf & lead_maf < max_maf))) -> mtable
}
if (verbose) {
cat(file=stderr(),'Selecting highest phase reached and best genetic similarity...')
flush.console()
}
suppressWarnings(mtable %>% group_by(uid) %>% summarize(maxsim = max(comb_norm, na.rm=T), maxcat=max(catnum, na.rm=T)) -> step1)
if (verbose) {
cat(file=stderr(),nrow(step1),'rows remain.\n')
flush.console()
}
if (verbose) {
cat(file=stderr(),'Joining back in program details...')
flush.console()
}
# add a filter first - only slightly reduces row count
mtable %>%
filter(uid %in% step1$uid & comb_norm %in% unique(step1$maxsim) & catnum %in% unique(step1$maxcat)) -> mtable
# use tidy to left join
step1 %>%
left_join(mtable, by = c("uid" = "uid", "maxsim" = "comb_norm", "maxcat" = "catnum")) %>%
rename(similarity=maxsim, catnum=maxcat) -> step2
if (verbose) {
cat(file=stderr(),nrow(step2),'rows found after join.\n')
flush.console()
}
if (verbose) {
cat(file=stderr(),'Removing duplicates resulting from ties...')
flush.console()
}
# prioritize rows with known outcome at most advanced phase, then de-dup
step2 %>%
mutate(highest_phase_with_known_outcome = case_when(!is.na(succ_3_a) ~ 3,
!is.na(succ_2_3) ~ 2,
!is.na(succ_1_2) ~ 1,
!is.na(succ_p_1) ~ 0)) %>%
arrange(uid, desc(highest_phase_with_known_outcome)) %>%
group_by(uid) %>%
slice(1) %>%
ungroup() -> step2 # row count should drop back to ~ that of step1
if (verbose) {
cat(file=stderr(),nrow(step2),'rows remain.\n')
flush.console()
}
# annotate in additional info:
step2$areas = indic$areas[match(step2$indication_mesh_id, indic$indication_mesh_id)]
step2$genetic_insight = replace_na(indic$genetic_insight[match(step2$indication_mesh_id, indic$indication_mesh_id)],'none')
step2$target_status = ''
step2$target_status[step2$similarity >= threshold] = 'genetically supported target'
step2$target_status[step2$similarity < threshold] = 'unsupported target'
step2$target_status[require_insight & step2$genetic_insight == 'none'] = 'indication lacks genetic insight'
step2$target_status[is.na(step2$gene) | step2$gene == ''] = 'no target annotated'
step2$target_status[is.na(step2$indication_mesh_id) | step2$indication_mesh_id == ''] = 'no indication annotated'
if (verbose) {
cat(file=stderr(),paste0('Using sim threshold ',threshold,', "genetically supported target" rows: ',sum(step2$target_status=='genetically supported target'),'....\n'))
time_elapsed = (Sys.time() - start_time)
cat(file=stderr(),'pipeline_best completed in',round(time_elapsed,1),units(time_elapsed),'.\n')
flush.console()
}
return (step2)
}
advancement_forest = function(best_table, phase='combined') {
if (phase == 'active') {
meta = meta_acat
} else if (phase == 'historical') {
meta = meta_hcat
} else if (phase == 'combined') {
meta = meta_ccat
}
meta %>%
left_join(best_table, by=c('num'='catnum', 'cat'='cat')) %>%
filter(cat != 'Other') %>%
filter(!(target_status %in% c('indication lacks genetic insight','no indication annotated','no target annotated'))) %>%
group_by(catnum=num, cat) %>%
summarize(.groups='keep',
n_total = sum(!is.na(target_status)),
n_gensup = sum(target_status=='genetically supported target', na.rm=T)) -> forest_data
bconf_obj = binom.confint(x=forest_data$n_gensup, n=forest_data$n_total, method='wilson', conf.level = .95)
forest_data$proportion = bconf_obj$mean
forest_data$l95 = bconf_obj$lower
forest_data$u95 = bconf_obj$upper
forest_data$y = max(forest_data$catnum) - forest_data$catnum + 1
colnames(forest_data) = c('num','label','denominator','numerator','mean','l95','u95','y')
return (forest_data)
}
advancement_rr = function(best, alpha = 0.05, threshold = NA) {
phase_map = tibble(phase=factor(c('Preclinical','I','II','III','I-Launch'),ordered=T,levels=c('Preclinical','I','II','III','I-Launch')),
phorder = 0:4,
varname=c('succ_p_1','succ_1_2','succ_2_3','succ_3_a','succ_1_a'))
# determine whether operating on a pipeline_best output that required genetic insight
require_insight = 'indication lacks genetic insight' %in% best$target_status
if (is.na(threshold)) {
best$gensup = best$target_status=='genetically supported target'
} else {
best$gensup = !is.na(best$similarity) & best$similarity >= threshold
}
best %>%
filter(genetic_insight != 'none' | (!require_insight)) %>%
select(ti_uid, gensup, succ_p_1:succ_3_a) %>%
pivot_longer(succ_p_1:succ_3_a) %>%
inner_join(phase_map, by=c('name'='varname')) %>%
filter(!is.na(value)) %>%
rename(success=value) %>%
mutate(gs = ifelse(gensup,'yes','no')) %>%
select(ti_uid, gs, phase, success) -> long
denoms_structure = tibble(gs=c('no','yes'))
long %>%
mutate(gs = as.character(gs)) %>%
filter(phase != 'Preclinical') %>%
group_by(gs) %>%
summarize(.groups='keep',
denom = length(unique(ti_uid))) %>%
ungroup() %>%
right_join(denoms_structure, by='gs') %>%
mutate(denom = replace_na(denom, 0)) -> denoms
rr_long_structure = crossing(gs=c('yes','no'),phase=c('Preclinical','I','II','III'))
# Wilson CI for single phases
long %>%
mutate(gs = as.character(gs)) %>%
group_by(gs, phase) %>%
summarize(.groups='keep',
x = sum(success),
n = sum(!is.na(success))) %>%
ungroup() %>%
right_join(rr_long_structure, by=c('gs','phase')) %>%
mutate(x=replace_na(x, 0),
n=replace_na(n, 0)) %>%
mutate(binom = binom.confint(x, n, 1-alpha, method='wilson')[,c('mean','lower','upper')]) %>%
mutate(mean = binom$mean, l=binom$lower, u=binom$upper) %>%
select(gs, phase, x, n, mean, l, u) -> rs_long
# Wald CI for product of P(S) across I-Launch
rs_long %>%
filter(phase != 'Preclinical' & phase != 'I-Launch') %>%
group_by(gs) %>%
summarize(.groups='keep',
x = x[phase=='III'],
m = prod(mean),
l = prod(mean) - qnorm(1 - (alpha)/2) * sqrt(prod(mean * (1 - mean) / n + mean^2) - prod(mean)^2),
u = prod(mean) + qnorm(1 - (alpha)/2) * sqrt(prod(mean * (1 - mean) / n + mean^2) - prod(mean)^2)) %>%
rename(mean=m) %>%
ungroup() %>%
left_join(denoms, by='gs') %>%
mutate(n = denom) %>%
mutate(phase='I-Launch') %>%
select(gs, phase, x, n, mean, l, u) -> ilrows
rs_long %>%
bind_rows(ilrows) %>%
pivot_wider(id_cols=phase, names_from = gs, names_sep='_', values_from=c(x,n,mean,l,u)) %>%
inner_join(select(phase_map, phase, phorder), by='phase') %>%
arrange(phorder) %>%
select(-phorder) %>%
ungroup() %>%
mutate(
binratio = suppressWarnings(binom_ratio(x_yes, n_yes, x_no, n_no, mean_yes, mean_no, alpha = 0.05))) %>%
mutate(
rs_mean = binratio$rs_mean,
rs_l = binratio$rs_l,
rs_u = binratio$rs_u,
fraction = glue("{x_yes}/{n_yes}")
) %>%
select(phase, x_yes, n_yes, x_no, n_no, mean_yes, l_yes, u_yes, mean_no, l_no, u_no, rs_mean, rs_l, rs_u, fraction) -> rr
return (rr)
}
always_katz = T
binom_ratio_atomic = function(x_yes, n_yes, x_no, n_no, mean_yes=NA, mean_no=NA, alpha = 0.05) {
# Wald by default
if (!always_katz & x_yes >= 3 & x_no >=3) {
mean = mean_yes / mean_no
#mean = (x_yes/n_yes) / (x_no/n_no)
lower = mean - qnorm(1 - alpha/2) * sqrt(1/(n_yes + n_no) * mean^2 * (1/mean_yes + 1/mean_no))
upper = mean + qnorm(1 - alpha/2) * sqrt(1/(n_yes + n_no) * mean^2 * (1/mean_yes + 1/mean_no))
} else { # Katz for small N
# for the I-Launch row, mean_yes or mean_no may be NA because a phase had no data
# important to leave that NA - don't use the filled-in total denominator
if (is.na(mean_yes) | is.na(mean_no)) {
mean = lower = upper = as.numeric(NA)
} else {
binom_obj = BinomRatioCI(x_yes, n_yes, x_no, n_no, conf=1-alpha)
mean = binom_obj[1,'est']
lower = binom_obj[1,'lwr.ci']
upper = binom_obj[1,'upr.ci']
}
}
return (cbind(mean=mean,lower=lower,upper=upper))
}
binom_ratio = function(x_yes, n_yes, x_no, n_no, mean_yes, mean_no, alpha = 0.05) {
setNames(as_tibble(t(mapply(binom_ratio_atomic, x_yes, n_yes, x_no, n_no, mean_yes, mean_no, alpha))), c('rs_mean','rs_l','rs_u'))
}
# For Figure ED6, we need to be able to calculate RS based solely on columns ccat, ccatnum, and gensup (example: p13_g13)
adv_rr_simple = function(ptbl, alpha=0.05) {
phase_map = tibble(phase=factor(c('Preclinical','I','II','III','I-Launch'),ordered=T,levels=c('Preclinical','I','II','III','I-Launch')),
phorder = 0:4,
varname=c('succ_p_1','succ_1_2','succ_2_3','succ_3_a','succ_1_a'))
rr_long_structure = crossing(gs=c('yes','no'),phase=c('Preclinical','I','II','III'))
ptbl %>%
mutate(ti_uid = paste0(gene,'-',mesh_id_indication)) %>%
filter(ccat %in% c('Preclinical','Phase I','Phase II','Phase III','Launched')) %>%
mutate(succ_p_1 = case_when(ccat %in% c('Phase I','Phase II','Phase III','Launched') ~ TRUE,
ccat %in% c('Preclinical') ~ FALSE)) %>%
mutate(succ_1_2 = case_when(ccat %in% c('Phase II','Phase III','Launched') ~ TRUE,
ccat %in% c('Phase I') ~ FALSE,
TRUE ~ NA)) %>%
mutate(succ_2_3 = case_when(ccat %in% c('Phase III','Launched') ~ TRUE,
ccat %in% c('Phase II') ~ FALSE,
TRUE ~ NA)) %>%
mutate(succ_3_a = case_when(ccat %in% c('Launched') ~ TRUE,
ccat %in% c('Phase III') ~ FALSE,
TRUE ~ NA)) %>%
mutate(gs = ifelse(gensup,'yes','no')) %>%
select(gs, ti_uid, ccatnum, ccat, succ_p_1, succ_1_2, succ_2_3, succ_3_a) %>%
pivot_longer(succ_p_1:succ_3_a) %>%
rename(success=value) %>%
filter(!is.na(success)) %>%
inner_join(phase_map, by=c('name'='varname')) %>%
select(ti_uid, gs, phase, success) -> long
long %>%
group_by(gs, phase) %>%
summarize(.groups='keep',
x = sum(success),
n = sum(!is.na(success))) %>%
ungroup() %>%
right_join(rr_long_structure, by=c('gs','phase')) %>%
mutate(x=replace_na(x, 0),
n=replace_na(n, 0)) %>%
mutate(binom = binom.confint(x, n, 1-alpha, method='wilson')[,c('mean','lower','upper')]) %>%
mutate(mean = binom$mean, l=binom$lower, u=binom$upper) %>%
select(gs, phase, x, n, mean, l, u) -> rs_long
denoms_structure = tibble(gs=c('no','yes'))
long %>%
mutate(gs = as.character(gs)) %>%
filter(phase != 'Preclinical') %>%
group_by(gs) %>%
summarize(.groups='keep',
denom = length(unique(ti_uid))) %>%
ungroup() %>%
right_join(denoms_structure, by='gs') %>%
mutate(denom = replace_na(denom, 0)) -> denoms
rs_long %>%
filter(phase != 'Preclinical' & phase != 'I-Launch') %>%
group_by(gs) %>%
summarize(.groups='keep',
x = x[phase=='III'],
m = prod(mean),
l = prod(mean) - qnorm(1 - (alpha)/2) * sqrt(prod(mean * (1 - mean) / n + mean^2) - prod(mean)^2),
u = prod(mean) + qnorm(1 - (alpha)/2) * sqrt(prod(mean * (1 - mean) / n + mean^2) - prod(mean)^2)) %>%
rename(mean=m) %>%
ungroup() %>%
left_join(denoms, by='gs') %>%
mutate(n = denom) %>%
mutate(phase='I-Launch') %>%
select(gs, phase, x, n, mean, l, u) -> ilrows
rs_long %>%
bind_rows(ilrows) %>%
pivot_wider(id_cols=phase, names_from = gs, names_sep='_', values_from=c(x,n,mean,l,u)) %>%
inner_join(select(phase_map, phase, phorder), by='phase') %>%
arrange(phorder) %>%
select(-phorder) %>%
ungroup() %>%
mutate(
binratio = suppressWarnings(binom_ratio(x_yes, n_yes, x_no, n_no, mean_yes, mean_no, alpha = 0.05))) %>%
mutate(
rs_mean = binratio$rs_mean,
rs_l = binratio$rs_l,
rs_u = binratio$rs_u,
fraction = glue("{x_yes}/{n_yes}")
) %>%
select(phase, x_yes, n_yes, x_no, n_no, mean_yes, l_yes, u_yes, mean_no, l_no, u_no, rs_mean, rs_l, rs_u, fraction) -> rr
return(rr)
}
plot_forest = function(forestdf, xlims=c(0,1), xstyle='percent', mar=c(3,8,3,8), xlab='', title='', col='#000000', showvals=F, right_text=NA, xlab_line=1.6, yaxcex=0.75) {
ylims = range(forestdf$y) + c(-0.5, 0.5)
par(mar=mar)
plot(NA, NA, xlim=xlims, ylim=ylims, axes=F, ann=F, xaxs='i', yaxs='i')
axis(side=1, at=xlims, labels=NA, lwd.ticks=0)
if (xstyle == 'percent') {
axis(side=1, at=0:100/100, labels=NA, tck=-0.025)
if (max(xlims) > .5) {
axis(side=1, at=0:10/10, labels=NA, tck=-0.05)
axis(side=1, at=0:2/2, labels=percent(0:2/2), lwd=0, line=-0.5)
} else {
axis(side=1, at=0:20/20, labels=NA, tck=-0.05)
axis(side=1, at=0:20/20, labels=percent(0:20/20,digits=0), lwd=0, line=-0.5)
}
} else if (xstyle == 'ratio') {
axis(side=1, at=seq(0,max(xlims),0.1), labels=NA, tck=-0.025)
axis(side=1, at=seq(0,max(xlims),1), labels=NA, tck=-0.05)
axis(side=1, at=seq(0,max(xlims),1), lwd=0, line=-0.5)
abline(v=1, lwd=0.25, lty=3)
}
mtext(side=1, line=xlab_line, cex=0.75, text=xlab)
axis(side=2, at=ylims, labels=NA, lwd.ticks=0)
mtext(side=2, at=forestdf$y, text=forestdf$label, cex=yaxcex, line=0.5, las=2, col=col)
mtext(side=4, at=forestdf$y, text=paste0(formatC(forestdf$numerator,big.mark=','),'/',formatC(forestdf$denominator,big.mark=',')), cex=yaxcex, las=2, line=0.25)
par(xpd=T)
if (is.na(right_text)) {
if (xstyle=='ratio') {
right_text = 'Approved/\nSupported'
} else if (xstyle == 'percent') {
right_text = 'Supported/\nTotal'
}
}
mtext(side=4, las=2, at=max(forestdf$y)+1, font=2, text=right_text, cex=0.7, padj=0)
par(xpd=F)
points(forestdf$mean, forestdf$y, pch=19, col=col) # means
segments(x0=forestdf$l95, x1=pmin(forestdf$u95,max(xlims)), y0=forestdf$y, lwd=2, col=col) # 95%CIs
mtext(side=3, line=0, text=title, col=col, font=1, cex=0.7)
if (showvals) {
text(x=forestdf$u95, y=forestdf$y, pos=4, labels=formatC(forestdf$mean, format='f', digits=1), font=3, cex=.75, col=col)
}
}
subset_by_area = function(best_table, topl, filter='only', orphan='any') {
btable = best_table
if (orphan=='any') {
btable = btable
} else if (orphan=='yes') {
btable = btable[btable$orphan==1,]
} else if (orphan=='non') {
btable = btable[btable$orphan==0,]
}
if (topl == 'all' | topl == 'ALL') {
btable = btable
} else if (filter == 'only') {
btable = btable[btable$indication_mesh_id %in% indic_topl_match$indication_mesh_id[indic_topl_match$topl==topl],]
} else if (filter == 'non') {
btable = btable[!(btable$indication_mesh_id %in% indic_topl_match$indication_mesh_id[indic_topl_match$topl==topl]),]
}
return (btable)
}
add_genelist_cols = function(tbl, genelistdf) {
for (i in 1:nrow(genelistdf)) {
if (substr(genelistdf$list[i],1,3)=='all') {
tbl[,genelists$list[i]] = TRUE
} else {
genes = read.table(paste0('data/gene_lists/',genelists$list[i],'.tsv'),sep='\t',header=F)$V1
tbl[,genelists$list[i]] = tbl$gene %in% genes
}
}
return (tbl)
}
########
# Staging
########
cat(file=stderr(), 'done.\nGenerating pipeline tables: hist_ti...')
hist_ti = pipeline_best(merge2, phase='historical', basis='ti', verbose = F)
cat(file=stderr(), '\rGenerating pipeline tables: hist_ti_all...')
hist_ti_all = pipeline_best(merge2, phase='historical', basis='ti', require_insight=F, include_missing=F, verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: active_ti...')
active_ti = pipeline_best(merge2, phase='active', basis='ti', verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti...')
combined_ti = pipeline_best(merge2, phase='combined', basis='ti', verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_unfiltered...')
combined_ti_unfiltered = pipeline_best(merge2, phase='combined', basis='ti', require_insight=F, verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_all...')
combined_ti_all = pipeline_best(merge2, phase='combined', basis='ti', require_insight=F, include_missing=F, verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_omim...')
combined_ti_omim = pipeline_best(merge2, phase='combined', basis='ti', associations=c('OMIM'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_gwas...')
combined_ti_gwas = pipeline_best(merge2, phase='combined', basis='ti', associations=c('OTG','PICCOLO','Genebass'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_everything...')
combined_ti_everything = pipeline_best(merge2, phase='combined', basis='ti', associations = c('OMIM','GWAS','intOGen'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_germline...')
combined_ti_germline = combined_ti
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_omim...')
combined_ti_omim = pipeline_best(merge2, phase='combined', basis='ti', associations=c('OMIM'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_genebass...')
combined_ti_genebass = pipeline_best(merge2, phase='combined', basis='ti', associations=c('Genebass'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_otg...')
combined_ti_otg = pipeline_best(merge2, phase='combined', basis='ti', associations=c('OTG'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_piccolo...')
combined_ti_pic = pipeline_best(merge2, phase='combined', basis='ti', associations=c('PICCOLO'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_gwas...')
combined_ti_gwas = pipeline_best(merge2, phase='combined', basis='ti', associations=c('PICCOLO','OTG','Genebass'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_soma...')
combined_ti_soma = pipeline_best(merge2, phase='combined', basis='ti', associations=c('Somatic'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_intogen...')
combined_ti_intogen = pipeline_best(merge2, phase='combined', basis='ti', associations=c('intOGen'), verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_gwascat...')
combined_ti_gwascat = pipeline_best(merge2, phase='combined', basis='ti', otg_subcat='GWAS Catalog', verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_ukbb...')
combined_ti_ukbb = pipeline_best(merge2, phase='combined', basis='ti', otg_subcat='Neale UKBB', verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables: combined_ti_finngen...')
combined_ti_finngen = pipeline_best(merge2, phase='combined', basis='ti', otg_subcat='FinnGen', verbose=F)
cat(file=stderr(), '\rGenerating pipeline tables... done. \n')
# combined_ti %>%
# select(ti_uid, gene, indication_mesh_id, indication_mesh_term, ccatnum, ccat, orphan,
# assoc_mesh_id, assoc_mesh_term, assoc_source, assoc_info, original_trait, original_link,
# assoc_year, pic_qtl_pval, pic_h4)
#########
# Figure ED1
#########
# Things I can't generate based on my limited dataset:
# Unique drugs - total
# Unique drugs - monotherapy, phase assigned, human target
merge2$tia = paste(merge2$gene, merge2$indication_mesh_id, merge2$assoc_mesh_id, sep='-')
merge2$tia[is.na(merge2$gene) | is.na(merge2$indication_mesh_id) | is.na(merge2$assoc_mesh_id)] = NA
write(paste('Unique indications: ',nrow(indic),'\n',sep=''),text_stats_path,append=T)
write(paste('Unique indications - of which genetic insight: ',sum(indic$genetic_insight!='none'),'\n',sep=''),text_stats_path,append=T)
write(paste('Unique targets: ',length(unique(pp$gene)),'\n',sep=''),text_stats_path,append=T)
write(paste('Unique T-I: ',nrow(pp),'\n',sep=''),text_stats_path,append=T)
write(paste('Unique D-T-I: ',nrow(drug_phase_summary),'\n',sep=''),text_stats_path,append=T)
write(paste('Approved | Unique targets: ',length(unique(pp$gene[pp$ccat=='Launched'])),'\n',sep=''),text_stats_path,append=T)
write(paste('Approved | Unique indications: ',length(unique(pp$indication_mesh_id[pp$ccat=='Launched'])),'\n',sep=''),text_stats_path,append=T)
write(paste('Approved | Unique T-I: ',sum(pp$ccat=='Launched'),'\n',sep=''),text_stats_path,append=T)
write(paste('Historical | Unique targets: ',length(unique(pp$gene[pp$hcat!='Launched' & !is.na(pp$hcat)])),'\n',sep=''),text_stats_path,append=T)
write(paste('Historical | Unique indications: ',length(unique(pp$indication_mesh_id[pp$hcat!='Launched' & !is.na(pp$hcat)])),'\n',sep=''),text_stats_path,append=T)
write(paste('Historical | Unique T-I: ',sum(pp$hcat!='Launched' & !is.na(pp$hcat)),'\n',sep=''),text_stats_path,append=T)
write(paste('Active | Unique targets: ',length(unique(pp$gene[pp$acat!='Launched' & !is.na(pp$acat)])),'\n',sep=''),text_stats_path,append=T)
write(paste('Active | Unique indications: ',length(unique(pp$indication_mesh_id[pp$acat!='Launched' & !is.na(pp$acat)])),'\n',sep=''),text_stats_path,append=T)
write(paste('Active | Unique T-I: ',sum(pp$acat!='Launched' & !is.na(pp$acat)),'\n',sep=''),text_stats_path,append=T)
merge2 %>%
filter(!is.na(comb_norm) & comb_norm >= 0.8) %>%
group_by(ti_uid) %>%
summarize(.groups='keep', max_ccatnum = max(ccatnum)) %>%
ungroup() %>%
group_by(max_ccatnum) %>%
summarize(.groups='keep', n_ti = length(unique(ti_uid))) %>%
pull(n_ti) %>%
sum() -> gs_ti_count_all
# replicate the number shown in roc_sim for threshold 0.8
merge2 %>%
filter(!is.na(comb_norm) & comb_norm >= 0.8) %>%
filter(assoc_source != 'intOGen' & (l2g_share >= 0.5 | assoc_source != 'OTG')) %>%
group_by(ti_uid) %>%
summarize(.groups='keep', max_ccatnum = max(ccatnum)) %>%
ungroup() %>%
group_by(max_ccatnum) %>%
summarize(.groups='keep', n_ti = length(unique(ti_uid))) %>%
ungroup() %>%
filter(max_ccatnum > 1) %>%
pull(n_ti) %>%
sum() -> gs_ti_count_default
write(paste('Merged sim ≥0.8 | Unique targets: ',length(unique(merge2$gene[merge2$comb_norm >= 0.8 & !is.na(merge2$comb_norm)])),'\n',sep=''),text_stats_path,append=T)
write(paste('Merged sim ≥0.8 | Unique indications: ',length(unique(merge2$indication_mesh_id[merge2$comb_norm >= 0.8 & !is.na(merge2$comb_norm)])),'\n',sep=''),text_stats_path,append=T)
write(paste('Merged sim ≥0.8 | Unique T-I (all): ',gs_ti_count_all,'\n',sep=''),text_stats_path,append=T)
write(paste('Merged sim ≥0.8 | Unique T-I (meeting default criteria): ',gs_ti_count_default,'\n',sep=''),text_stats_path,append=T)
write(paste('Merged sim ≥0.8 | Unique T-I-A: ',length(unique(merge2$tia[merge2$comb_norm >= 0.8 & !is.na(merge2$comb_norm)])),'\n',sep=''),text_stats_path,append=T)
assoc$ta_uid = paste0(assoc$gene, '-', assoc$mesh_id)
write(paste('Assocs | Unique T-A: ',length(unique(assoc$ta_uid[(assoc$l2g_share >= 0.5 | assoc$source != 'OTG')])),'\n',sep=''),text_stats_path,append=T)
write(paste('Assocs | OTG | Unique T-A (all): ',length(unique(assoc$ta_uid[(assoc$source == 'OTG')])),'\n',sep=''),text_stats_path,append=T)
write(paste('Assocs | OTG | Unique T-A (L2G >= 0.5): ',length(unique(assoc$ta_uid[(assoc$l2g_share >= 0.5 & assoc$source == 'OTG')])),'\n',sep=''),text_stats_path,append=T)
write(paste('Assocs | OMIM | Unique T-A: ',length(unique(assoc$ta_uid[(assoc$source == 'OMIM')])),'\n',sep=''),text_stats_path,append=T)
write(paste('Assocs | PICCOLO | Unique T-A: ',length(unique(assoc$ta_uid[(assoc$source == 'PICCOLO')])),'\n',sep=''),text_stats_path,append=T)
write(paste('Assocs | Genebass | Unique T-A: ',length(unique(assoc$ta_uid[(assoc$source == 'Genebass')])),'\n',sep=''),text_stats_path,append=T)
write(paste('Assocs | intOGen | Unique T-A: ',length(unique(assoc$ta_uid[(assoc$source == 'intOGen')])),'\n',sep=''),text_stats_path,append=T)
assoc %>%
filter(!is.na(source)) %>%
filter(!is.na(mesh_id)) %>%
distinct(mesh_id) %>%
mutate(in_sim = mesh_id %in% sim$meshcode_a) -> assoc_mesh_uq
pp %>%
distinct(indication_mesh_id) %>%
filter(!is.na(indication_mesh_id)) %>%
mutate(in_sim = indication_mesh_id %in% sim$meshcode_a) -> pp_mesh_uq
write(paste0('Pharmaprojects | MeSH missing from sim matrix: ',sum(!(pp_mesh_uq$indication_mesh_id %in% sim$meshcode_a)),'/',nrow(pp_mesh_uq),'\n',sep=''),text_stats_path,append=T)
write(paste0('Pharmaprojects | MeSH present in sim matrix: ',sum((pp_mesh_uq$indication_mesh_id %in% sim$meshcode_a)),'/',nrow(pp_mesh_uq),'\n',sep=''),text_stats_path,append=T)
write(paste0('Pharmaprojects | proportion of unique MeSH in sim matrix: ',percent(mean(pp_mesh_uq$indication_mesh_id %in% sim$meshcode_a), digits=3),'\n',sep=''),text_stats_path,append=T)
write(paste0('Pharmaprojects | proportion of rows in sim matrix: ',percent(mean(pp$indication_mesh_id[!is.na(pp$indication_mesh_id)] %in% sim$meshcode_a), digits=3),'\n',sep=''),text_stats_path,append=T)
write(paste0('Assocs | MeSH missing from sim matrix: ',sum(!(assoc_mesh_uq$mesh_id %in% sim$meshcode_a)),'/',nrow(assoc_mesh_uq),'\n',sep=''),text_stats_path,append=T)
write(paste0('Assocs | MeSH present in sim matrix: ',sum((assoc_mesh_uq$mesh_id %in% sim$meshcode_a)),'/',nrow(assoc_mesh_uq),'\n',sep=''),text_stats_path,append=T)
write(paste0('Assocs | proportion of unique MeSH in sim matrix: ',percent(mean(assoc_mesh_uq$mesh_id %in% sim$meshcode_a), digits=3),'\n',sep=''),text_stats_path,append=T)
write(paste0('Assocs | proportion assoc rows in sim matrix: ',percent(mean(assoc$mesh_id[!is.na(assoc$source)] %in% sim$meshcode_a), digits=3),'\n',sep=''),text_stats_path,append=T)
notes = tribble(
~table, ~notes,
'Table S1', 'Note that this table is already grouped by target-indication pair with just 1 supporting genetic association shown. This is provided for browsing purposes but is not sufficient to reproduce all analyses in the paper. To reproduce the full analysis, please visit the study GitHub repository.',
)
abbrevs = tribble(
~`abbreviation`, ~`description`,
'pg', 'P(G); proportion of programs with genetic support.',
'ps', 'P(S); probability of success.',
'rs', 'RS; relative success.',
'_l95', 'Lower bound of the 95% confidence interval',
'_u95', 'Upper bound of the 95% confidence interval',
'gensup', 'Genetically supported',
'nosup', 'Not genetically supported',
'_yes', 'Genetically supported',
'_no', 'Not genetically supported',
'x_', 'Number of successes (numerator)',
'n_', 'Total programs (denominator)'
)
write_supp_table(abbrevs, numbered=F, tblname='abbrevs')
write_supp_table(notes, numbered=F, tblname='notes')
genelists = tibble(list=c('ab_tractable','sm_tractable','rhodop_gpcr','nuclear_receptors','enzymes','ion_channels','kinases'),
disp=c('predicted Ab tractable','predicted SM tractable','rhodopsin-like GPCRs','nuclear receptors','enzymes','ion channels','kinases'))
combined_ti_out = add_genelist_cols(combined_ti, genelists)
combined_ti_out %>%
select(-uid) %>%
relocate(ti_uid) %>%
select(-catnum, -cat) %>%
rename(historical_max_phase = hcat) %>%
rename(active_max_phase = acat) %>%
rename(combined_max_phase = ccat) %>%
select(-hcatnum, -acatnum, -ccatnum, -highest_phase_with_known_outcome) %>%
select(-arow) %>%
rename(indication_association_similarity = similarity) %>%
rename(nuclear_receptor=nuclear_receptors,enzyme=enzymes,ion_channel=ion_channels,kinase=kinases) %>%
rename(target=gene) -> combined_ti_out
write_supp_table(combined_ti_out, 'Target-indication pairs, genetic associations, and maximum phase reached.')
assoc %>%
filter(source=='OTG' & l2g_share >= 0.5) %>%
group_by(original_link, gene) %>%
slice(1) %>%
ungroup() %>%
mutate(gwas_source = gsub('[0-9_].*','',gsub('https://genetics.opentargets.org/study/','',original_link))) %>%
group_by(gwas_source) %>%
summarize(.groups='keep', n=n()) %>%
ungroup() -> otg_source_breakdown
write_supp_table(otg_source_breakdown, 'Sources of GWAS hits within OTG.')
assoc %>%
filter(source=='PICCOLO') %>%
mutate(qtl_source = case_when(grepl('gtex',tolower(extra_info)) ~ 'GTEx',
TRUE ~ 'other')) %>%
group_by(qtl_source) %>%
summarize(.groups='keep', n=n()) %>%
ungroup() -> piccolo_qtl_breakdown
write_supp_table(piccolo_qtl_breakdown, 'Sources of QTL mappings within PICCOLO.')
#########
# Figure 1