-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreproduceData.qmd
More file actions
1355 lines (1056 loc) · 53.9 KB
/
reproduceData.qmd
File metadata and controls
1355 lines (1056 loc) · 53.9 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
---
title: "Reproducing the Enpact data and results"
author: "Temi"
description: "This notebook contains steps and codes to reproduce, as much as possible, the Enpact paper results"
date: 'Wed Sep 11 2024'
html:
self-contained: true
code-background: true
fig-format: png
---
```{r}
knitr::opts_chunk$set(eval = F, echo = TRUE, message = TRUE, warning = TRUE, cache = TRUE)
```
```{r}
setwd('/beagle3/haky/users/temi/projects/TFXcan/notebooks') # to this repository
```
```{r}
library(data.table)
library(glue)
library(dplyr)
library(RSQLite)
library(rtracklayer)
library(GenomicRanges)
library(magrittr)
library(yaml)
# library(fpeek)
library(purrr)
```
```{r}
# tdate <- '2023-08-17' # modified
tdate <- '2024-04-17'
base_dir <- '/project2/haky/temi/projects/TFXcan/baca_cwas'
project_dir <- '/beagle3/haky/users/temi/projects/TFXcan'
data_dir <- glue('{project_dir}/data')
files_dir <- glue('{project_dir}/files')
if(!(dir.exists(files_dir))){
dir.create(files_dir, recursive = T)
}
if(!(dir.exists(data_dir))){
dir.create(data_dir, recursive = T)
}
```
# Introduction
In this notebook, I detail steps to re-create some of the data/results in the Enpact paper. I have set this notebook not to run when rendering. So, it will show you the code and markdown text, but not run the code.
# Train DL-based Enpact models from scratch
Use [this](https://github.com/hakyimlab/TFPred-snakemake/tree/main) repository to train the DL-based Enpact models from scratch.
To train all 700+ TF-tissue binding predictors,
```{bash}
snakemake -s snakefile.smk --configfile minimal/pipeline.734.yaml --profile profiles/simple/ -np > dryrun.out
```
Steps required to train Enpact models are [here](https://github.com/hakyimlab/TFPred-snakemake). There is a minimal example to follow, as well as the config needed to train all 734 TF-tissue binding predictors.
# Train DL-based Enpact models using prepared matrix
Alternatively, you may also train the AR-Prostate Enpact model, as well as the others, using the prepared train and test data here:
-- Train AR_Prostate model
```{r}
train_script <- file.path(project_dir, 'src', 'trainEnpactModel.R')
evaluate_script <- file.path(project_dir, 'src', 'evaluateEnpactModel.R')
train_data <- file.path(project_dir, 'data', 'enpact/training', 'AR_Prostate.train_epigenome.csv.gz')
eval_data <- file.path(project_dir, 'data', 'enpact/training', 'AR_Prostate.test_epigenome.csv.gz')
model_rds <- file.path(project_dir, 'models', 'enpact', 'AR_Prostate_logistic.enpact.rds')
basename_eval_output <- file.path(project_dir, 'data', 'enpact/evaluations', 'AR_Prostate_logistic.enpact.eval_output')
```
```{r}
cmd <- glue('sbatch {project_dir}/src/trainAndEvaluateEnpactModel.sbatch {train_script} {evaluate_script} {train_data} {eval_data} {model_rds} {basename_eval_output}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
-- Train FOXA1_Prostate model
```{r}
train_script <- file.path(project_dir, 'src', 'trainEnpactModel.R')
evaluate_script <- file.path(project_dir, 'src', 'evaluateEnpactModel.R')
train_data <- file.path(project_dir, 'data', 'enpact/training', 'FOXA1_Prostate.train_epigenome.csv.gz')
eval_data <- file.path(project_dir, 'data', 'enpact/training', 'FOXA1_Prostate.test_epigenome.csv.gz')
model_rds <- file.path(project_dir, 'models', 'enpact', 'FOXA1_Prostate_logistic.enpact.rds')
basename_eval_output <- file.path(project_dir, 'data', 'enpact/evaluations', 'FOXA1_Prostate_logistic.enpact.eval_output')
```
```{r}
cmd <- glue('sbatch {project_dir}/src/trainAndEvaluateEnpactModel.sbatch {train_script} {evaluate_script} {train_data} {eval_data} {model_rds} {basename_eval_output}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
-- Train GATA2_Prostate model
```{r}
train_script <- file.path(project_dir, 'src', 'trainEnpactModel.R')
evaluate_script <- file.path(project_dir, 'src', 'evaluateEnpactModel.R')
train_data <- file.path(project_dir, 'data', 'enpact/training', 'GATA2_Prostate.train_epigenome.csv.gz')
eval_data <- file.path(project_dir, 'data', 'enpact/training', 'GATA2_Prostate.test_epigenome.csv.gz')
model_rds <- file.path(project_dir, 'models', 'enpact', 'GATA2_Prostate_logistic.enpact.rds')
basename_eval_output <- file.path(project_dir, 'data', 'enpact/evaluations', 'GATA2_Prostate_logistic.enpact.eval_output')
```
```{r}
cmd <- glue('sbatch {project_dir}/src/trainAndEvaluateEnpactModel.sbatch {train_script} {evaluate_script} {train_data} {eval_data} {model_rds} {basename_eval_output}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
-- Train HOXB13_Prostate model
```{r}
train_script <- file.path(project_dir, 'src', 'trainEnpactModel.R')
evaluate_script <- file.path(project_dir, 'src', 'evaluateEnpactModel.R')
train_data <- file.path(project_dir, 'data', 'enpact/training', 'HOXB13_Prostate.train_epigenome.csv.gz')
eval_data <- file.path(project_dir, 'data', 'enpact/training', 'HOXB13_Prostate.test_epigenome.csv.gz')
model_rds <- file.path(project_dir, 'models', 'enpact', 'HOXB13_Prostate_logistic.enpact.rds')
basename_eval_output <- file.path(project_dir, 'data', 'enpact/evaluations', 'HOXB13_Prostate_logistic.enpact.eval_output')
```
```{r}
cmd <- glue('sbatch {project_dir}/src/trainAndEvaluateEnpactModel.sbatch {train_script} {evaluate_script} {train_data} {eval_data} {model_rds} {basename_eval_output}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
# Prepare Baca's CWAS models in sqlite and create the necessary databases
The AR weights in the CWAS paper were trained using the Fusion pipeline in mind. Here, we prepared the AR weights such that they are compatible with the PredictDB pipeline.
These weights were shared by our collaborators. So, you can either find them online yourself through the [CWAS paper](https://www.nature.com/articles/s41588-022-01168-y) or you can ask the authors for the weights.
-- the CWAS weights for AR
```{r}
transcription_factor <- 'AR'
ar_zip <- '/project2/haky/Data/baca_cwas/cwas_weights/AR.zip' # use the weights zip file here.
output_dir <- '/beagle3/haky/users/temi/projects/TFXcan/data/baca_cwas_weights'
print(file.exists(ar_zip))
```
-- First unzip the file
```{r}
if(!dir.exists(glue('{output_dir}/{transcription_factor}'))){
file_names <- unzip(ar_zip, list=T)$Name
files_to_read <- grep(pattern='^\\bAR\\b.*\\bRDat\\b$', x=file_names, value=T)
#files_to_read[1:5]
# unzip the file
zip::unzip(ar_zip, files=files_to_read, exdir=output_dir)
}
ar_files <- list.files(glue('{output_dir}/{transcription_factor}'))
ar_files_locus <- sapply(strsplit(x=ar_files, split='\\.'), getElement, 1)
ar_files_locus[1:5]
```
```{r}
length(ar_files_locus)
```
```{r}
hsq.out <- purrr::map(.x=seq_along(ar_files_locus), .f=function(i){
locus <- ar_files_locus[i]
#print(file.exists(glue('{output_dir}/{transcription_factor}/{locus}.wgt.RDat')))
rdt <- new.env(parent = emptyenv())
load(glue('{output_dir}/{transcription_factor}/{locus}.wgt.RDat'), envir=rdt)
hsqs <- data.frame(rdt$hsq, rdt$hsq.as, rdt$hsq.qtl, rdt$hsq.pv) %>%
dplyr::mutate(locus=locus)
return(hsqs)
}, .progress=T)
hsq.dt <- do.call('rbind', hsq.out)
# dim(cwas_db) ; cwas_db[1:5, ]
```
```{r}
range(hsq.dt[, 1])
```
-- read weights; Next, read the files `.wgt` files
```{r}
out <- purrr::map(.x=seq_along(ar_files_locus), .f=function(i){
locus <- ar_files_locus[i]
#print(file.exists(glue('{output_dir}/{transcription_factor}/{locus}.wgt.RDat')))
rdt <- new.env(parent = emptyenv())
load(glue('{output_dir}/{transcription_factor}/{locus}.wgt.RDat'), envir=rdt)
wgts <- as.data.frame(rdt$wgt.matrix) %>%
tibble::rownames_to_column('snp_id') %>%
dplyr::mutate(locus=locus)
snp_info <- rdt$snps %>%
as.data.frame() %>%
dplyr::select(all_of(c('V1', 'V3', 'V2', 'V4', 'V5')))
colnames(snp_info) <- c('chr', 'snp_id', 'position', 'a1', 'a2')
dt <- base::merge(wgts, snp_info, by='snp_id') %>%
dplyr::relocate(all_of(c('locus', 'chr', 'position', 'a1', 'a2')), .after=snp_id)
return(dt)
}, .progress=T)
cwas_db <- do.call('rbind', out)
dim(cwas_db) ; cwas_db[1:5, ]
```
-- write out the weights
```{r}
data.table::fwrite(cwas_db, file=glue('{files_dir}/{transcription_factor}_baca_cwas_weights.hg19.{tdate}.txt.gz'), col.names=T, row.names=F, quote=F, compress='gzip',sep = '\t')
```
```{r}
cwas_db <- data.table::fread(glue('{files_dir}/{transcription_factor}_baca_cwas_weights.hg19.{tdate}.txt.gz'))
cwas_db$locus |> unique() |> length()
```
-- read and write out the extras
```{r}
out <- purrr::map(.x=seq_along(ar_files_locus), .f=function(i){
locus <- ar_files_locus[i]
#print(file.exists(glue('{output_dir}/{transcription_factor}/{locus}.wgt.RDat')))
rdt <- new.env(parent = emptyenv())
load(glue('{output_dir}/{transcription_factor}/{locus}.wgt.RDat'), envir=rdt)
cv_perf <- rbind(rdt$cv.performance['pval', ], rdt$cv.performance['rsq', ]) %>%
as.data.frame() %>%
dplyr::mutate(measure = c('pval', 'rsq'), locus) %>%
dplyr::relocate(locus, measure) %>%
dplyr::mutate(locus = locus, transcription_factor = transcription_factor, n_snps_in_window = rdt$N.tot, n.snps.in.model = rdt$N.as)
return(cv_perf)
}, .progress=T)
cvperf_dt <- do.call('rbind', out)
dim(cvperf_dt) ; cvperf_dt[1:5, ]
```
```{r}
data.table::fwrite(cvperf_dt, file=glue('{files_dir}/{transcription_factor}_baca_cwas_extras.hg19.{tdate}.txt.gz'), col.names=T, row.names=F, quote=F, compress='gzip',sep = '\t')
```
```{r}
cvperf_dt <- data.table::fread(glue('{files_dir}/{transcription_factor}_baca_cwas_extras.hg19.{tdate}.txt.gz'))
cvperf_dt$locus |> unique() |> length()
```
```{r}
emptyperf <- setdiff(cvperf_dt$locus |> unique(), cwas_db$locus |> unique())
sapply(emptyperf, function(locus){
rdt <- new.env(parent = emptyenv())
load(glue('{output_dir}/{transcription_factor}/{locus}.wgt.RDat'), envir=rdt)
if(all(is.na(rdt$cv.performance))){
return(NA)
} else {
return(1)
}
})
```
-- map the loci to hg38 from hg19
### Bed mappings i.e. liftover the arbs' coordinates from hg19 to hg38
```{r}
cvperf_dt <- data.table::fread(glue('{files_dir}/{transcription_factor}_baca_cwas_extras.hg19.{tdate}.txt.gz'))
```
```{r}
cvperf_dt$locus |> unique() |> length()
```
```{r}
#write out the bed files
# make sure to remove the empty ones
cvperf_dt %>%
dplyr::filter(!locus %in% emptyperf) %>%
tidyr::separate_wider_delim(col = locus, names = c('chr', 'start', 'end'), delim = stringr::regex(':|-')) %>%
dplyr::mutate(across(c(start, end), as.numeric)) %>%
dplyr::select(chr, start, end) %>%
dplyr::distinct() %>%
dplyr::mutate(id = 1:nrow(.)) %>%
data.table::fwrite(file=glue('{project_dir}/files/baca_cwas_loci_hg19.bed'), col.names=F, row.names=F, quote=F, sep='\t')
```
```{r}
# lift over these files
# download the liftover command : https://hgdownload.cse.ucsc.edu/admin/exe/linux.x86_64/liftOver
if(!file.exists(file.path(project_dir, 'software', 'liftOver'))){
download.file('https://hgdownload.cse.ucsc.edu/admin/exe/linux.x86_64/liftOver', destfile = file.path(project_dir, 'software', 'liftOver'))
}
```
```{r}
liftover_sh <- file.path(project_dir, 'src', 'liftoverSingleBed.sbatch')
liftover_exe <- file.path(project_dir, 'software', 'liftOver')
input_bed <- glue('{project_dir}/files/baca_cwas_loci_hg19.bed')
chain_file <- file.path(project_dir, 'helpers', 'hg19ToHg38.over.chain.gz')
output_bed <- glue('{project_dir}/files/baca_cwas_loci_hg38.bed')
unmapped_bed <- glue('{project_dir}/files/baca_cwas_loci_hg19.unmapped.bed')
file.exists(liftover_sh) ; file.exists(liftover_exe) ; file.exists(chain_file) ; file.exists(input_bed)
```
```{r}
cmd <- glue('sbatch {liftover_sh} {liftover_exe} {chain_file} {input_bed} {output_bed} {unmapped_bed}')
cmd
```
```{r}
system(cmd)
```
- read in, merge and save
```{r}
hg19_bed <- data.table::fread(input_bed, col.names=c('chr', 'start.hg19', 'end.19', 'id'))
hg38_bed <- data.table::fread(output_bed, col.names=c('chr', 'start.hg38', 'end.hg39', 'id'))
bed_mappings <- dplyr::inner_join(hg19_bed, hg38_bed, by=c('chr' = 'chr', 'id' = 'id')) %>%
dplyr::select(-id) %>%
dplyr::rename(chrom = chr)
data.table::fwrite(bed_mappings, file=glue('{project_dir}/files/baca_cwas_arbs_mappings.txt'), col.names=T, row.names=F, quote=F, sep='\t')
```
```{r}
dim(bed_mappings)
```
### SNP mappings i.e. liftover the snps' coordinates from hg19 to hg38
```{r}
# write out the cwas database snps
cwas_db %>%
dplyr::select(chrom = chr, start = position, locus, rsid=snp_id, a1, a2) %>%
dplyr::mutate(chrom = paste0('chr', chrom, sep=''), end = start + 1) %>%
dplyr::relocate(end, .after = start) %>%
data.table::fwrite(file=glue('{project_dir}/files/baca_cwas_snps_hg19.bed'), col.names=F, row.names=F, quote=F, sep='\t')
```
```{r}
liftover_sh <- file.path(project_dir, 'src', 'liftoverSingleBed.sbatch')
liftover_exe <- file.path(project_dir, 'software', 'liftOver')
input_bed <- glue('{project_dir}/files/baca_cwas_snps_hg19.bed')
chain_file <- file.path(project_dir, 'helpers', 'hg19ToHg38.over.chain.gz')
output_bed <- glue('{project_dir}/files/baca_cwas_snps_hg38.bed')
unmapped_bed <- glue('{project_dir}/files/baca_cwas_snps_hg19.unmapped.bed')
file.exists(liftover_sh) ; file.exists(liftover_exe) ; file.exists(chain_file) ; file.exists(input_bed)
```
```{r}
cmd <- glue('sbatch {liftover_sh} {liftover_exe} {chain_file} {input_bed} {output_bed} {unmapped_bed}')
cmd
```
```{r}
system(cmd)
```
- read in, merge and save
```{r}
hg19_bed <- data.table::fread(input_bed, col.names=c('chrom', 'start.hg19', 'end.19', 'arbs.hg19', 'rsid', 'a1', 'a2'))
hg38_bed <- data.table::fread(output_bed, col.names=c('chr', 'start.hg38', 'end.hg39', 'arbs.hg19', 'rsid', 'a1', 'a2'))
snp_mappings <- dplyr::inner_join(hg19_bed, hg38_bed, by = c('arbs.hg19' = 'arbs.hg19', 'rsid' = 'rsid', 'a1' = 'a1', 'a2' = 'a2'))
data.table::fwrite(snp_mappings, file=glue('{project_dir}/files/baca_cwas_snp_mappings.txt'), col.names=T, row.names=F, quote=F, sep='\t')
```
-- Now, you can write out the db and save
```{r}
baca_models <- c('lasso', 'lasso.as', 'lasso.plasma', 'top1.as', 'top1.qtl', 'top1')
db_folder <- glue('{project_dir}/models/cwas/db_folder')
if(!dir.exists(db_folder)){dir.create(db_folder)}
db_folder_chr <- glue('{project_dir}/models/cwas/db_folder_chr')
if(!dir.exists(db_folder_chr)){dir.create(db_folder_chr)}
```
```{r}
snp_mappings <- data.table::fread(glue('{project_dir}/files/baca_cwas_snp_mappings.txt'))
weights_dt <- data.table::fread(file.path(project_dir, 'files', 'AR_baca_cwas_weights.hg19.2024-04-17.txt.gz'))
weights_dt <- dplyr::inner_join(weights_dt, snp_mappings, by=c('locus' = 'arbs.hg19', 'snp_id' = 'rsid', 'a1' = 'a1', 'a2' = 'a2')) %>%
dplyr::select(rsid = snp_id, locus, chrom, position = start.hg38, a1, a2, all_of(baca_models))
head(weights_dt)
```
```{r}
# next, map the locus to hg38
bed_mappings <- data.table::fread(glue('{project_dir}/files/baca_cwas_arbs_mappings.txt')) %>%
dplyr::mutate(locus.hg19 = paste0(chrom, ':', start.hg19, '-', end.19),
locus.hg38 = paste0(chrom, '_', start.hg38, '_', end.hg39)) %>%
dplyr::select(locus.hg19, locus.hg38)
weights_dt <- dplyr::inner_join(weights_dt, bed_mappings, by=c('locus' = 'locus.hg19')) %>%
dplyr::select(-locus) %>%
dplyr::rename(locus = locus.hg38) %>%
dplyr::relocate(locus, .before = rsid)
head(weights_dt)
```
```{r}
# read in and map the extras
baca_extra <- data.table::fread(glue('{files_dir}/{transcription_factor}_baca_cwas_extras.hg19.{tdate}.txt.gz'))
baca_extra <- dplyr::inner_join(baca_extra, bed_mappings, by=c('locus' = 'locus.hg19')) %>%
dplyr::select(-locus) %>%
dplyr::rename(locus = locus.hg38) %>%
dplyr::relocate(locus, .before = measure)
baca_extra$pred.perf.qval <- NA
baca_extra[1:5, ]
```
```{r}
baca_extra %>% dplyr::select(locus, measure, transcription_factor, n_snps_in_window, n.snps.in.model, pred.perf.qval, as.symbol('lasso')) %>%
tidyr::pivot_wider(names_from = 'measure', values_from = 'lasso') %>%
dplyr::relocate(c(pval, rsq), .after = locus)
```
```{r}
weights_dt %>%
dplyr::mutate(varID = paste0(chrom, '_', position, '_', a1, '_', a2, sep=''), gene = locus) %>%
dplyr::select(gene, rsid, varID, ref_allele=a1, eff_allele=a2, weight=all_of('lasso')) %>%
dplyr::mutate(varID = gsub("chr", '', varID))
```
```{r}
baca_weights_list <- purrr::map(.x=baca_models, function(each_m){
model_weights <- weights_dt %>%
dplyr::mutate(varID = paste0(chrom, '_', position, '_', a1, '_', a2, sep=''), gene = locus) %>%
dplyr::select(gene, rsid, varID, ref_allele=a1, eff_allele=a2, weight=all_of(each_m)) %>%
dplyr::mutate(varID = gsub("chr", '', varID))
## hg38
edt <- baca_extra %>%
dplyr::select(locus, measure, transcription_factor, n_snps_in_window, n.snps.in.model, pred.perf.qval, all_of(each_m)) %>%
tidyr::pivot_wider(names_from = 'measure', values_from = each_m) %>%
dplyr::relocate(c(pval, rsq), .after = locus) %>%
dplyr::filter(locus %in% weights_dt$locus) %>%
dplyr::rename(gene = locus, genename = transcription_factor, pred.perf.R2 = rsq, pred.perf.pval = pval)
each_db <- DBI::dbConnect(RSQLite::SQLite(), glue('{db_folder}/baca_cwas_{each_m}.hg38.db'))
dbWriteTable(each_db, "extra", edt, overwrite=T)
dbWriteTable(each_db, "weights", model_weights, overwrite=T)
dbDisconnect(each_db)
return(0)
})
# names(baca_weights_list) <- baca_models
```
-- see an example
```{r}
# '/project2/haky/temi/projects/TFXcan/baca_cwas/db_folder/baca_cwas_lasso.db'
mydb <- dbConnect(SQLite(), glue('{db_folder}/baca_cwas_lasso.hg38.db'))
ex <- dbGetQuery(mydb, 'SELECT * FROM extra')
wt <- dbGetQuery(mydb, 'SELECT * FROM weights')
ex |> head(); wt |> head()
dbDisconnect(mydb)
```
# Predict CWAS scores in Baca individuals using the CWAS models
Above, we prepared the CWAS models for AR. We can now predict CWAS scores using these models.
```{r}
db_folder <- '/project/haky/users/temi/projects/Enpact/models/cwas/db_folder'
txt_genotypes <- '/project2/haky/Data/baca_cwas/vcfs/hg38/formatted_geno/all_chrs.text_dosages.txt.gz'
txt_samples <- '/project2/haky/Data/baca_cwas/vcfs/hg38/formatted_geno/samples.text_dosages.txt'
exec_file <- '/beagle3/haky/users/temi/software/MetaXcan/software/Predict.py'
output_folder <- "/project/haky/users/temi/projects/Enpact/data/baca_cwas/output"
if(!dir.exists(output_folder)){dir.create(output_folder, recursive = T)}
```
```{r}
# if needed, you should edit the sbatch file: {project_dir}/src/predictCWASscores.sbatch
cmd <- glue('sbatch {project_dir}/src/predictCWASscores.sbatch {db_folder} {txt_genotypes} {txt_samples} {exec_file} {output_folder}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
- prepare the file in a simple matrix
```{r}
# read in the individual mappings
samples_metadata <- data.table::fread(file.path(project_dir, 'metadata', 'baca_samples_mappings.metadata.txt'))
cwas_scores <- data.table::fread(glue('{output_folder}/top1.hg38/baca_cwas_predict.txt')) %>%
dplyr::select(-FID) %>%
tibble::column_to_rownames('IID') %>%
t() %>% as.data.frame()
cwas_mat <- cwas_scores[,]
colnames(cwas_mat) <- gsub('UW_PDX_172', 'UW_PDX_170_2', colnames(cwas_mat))
colnames(cwas_mat) <- gsub('UW_PDX_173', 'UW_PDX_170_3', colnames(cwas_mat))
colnames(cwas_mat) <- samples_metadata[match(colnames(cwas_mat), samples_metadata$vcf), ]$id
cwas_mat <- cwas_mat %>% tibble::rownames_to_column('locus')
```
```{r}
data.table::fwrite(cwas_mat, file=glue('{project_dir}/files/baca_cwas_scores.hg38.txt.gz'), col.names=T, row.names=F, quote=F, compress='gzip', sep='\t')
```
# Predict Enpact scores using the DL-based Enpact model
Here, I just need the AR_Prostate model tbf
The steps here are involved.
1. Get epigenomic features for all Baca individuals with Enformer. In this paper, we used [this pipeline]().
2. With the DL-based Enpact model, predict the Enpact scores using [this pipeline](https://github.com/hakyimlab/enpact-predict-snakemake)
## For the 521 1KG EUR individuals at the 18,000 ARBS
```{r}
exec_file <- '/beagle3/haky/users/temi/projects/TFXcan/src/calculateEnpactScores.sbatch'
data_directory <- '/beagle3/haky/users/temi/data/1KG_AR_prostate'
individuals_list <- '/beagle3/haky/users/temi/projects/TFXcan-snakemake/metadata/EUR_individuals.1KG.txt'
enpact_weights <- '/beagle3/haky/users/temi/projects/Enpact/data/enpact/weights/ENPACT_734_2025-04-24.compiled_weights.with_intercept.lambda.1se.txt.gz'
output_file <-'/beagle3/haky/users/temi/projects/TFXcan/data/enpact_scores/AR_Prostate.1KG.CWAS_ARBS.predictions.2025-10-16.rds.gz'
files_pattern <- '_aggByCollect_AR_Prostate.csv'
md <- 'AR_Prostate'
```
```{r}
cmd <- glue('sbatch {exec_file} {data_directory} {individuals_list} {enpact_weights} {output_file} {files_pattern} {md}')
cmd
```
## For the 131 samples in Baca
```{r}
exec_file <- '/beagle3/haky/users/temi/projects/TFXcan/src/calculateEnpactScores.sbatch'
data_directory <- '/beagle3/haky/users/temi/data/baca_AR_prostate'
individuals_list <- '/project2/haky/temi/projects/enpact-predict-snakemake/metadata/cwas_individuals.txt'
enpact_weights <- '/beagle3/haky/users/temi/projects/Enpact/data/enpact/weights/ENPACT_734_2025-04-24.compiled_weights.with_intercept.lambda.1se.txt.gz'
output_file <- '/beagle3/haky/users/temi/projects/TFXcan/data/enpact_scores/AR_Prostate.BACA.CWAS_ARBS.predictions.2025-10-16.rds.gz'
files_pattern <- '_aggByMeanCenter_AR_Prostate.csv'
md <- 'AR_Prostate'
```
```{r}
cmd <- glue('sbatch {exec_file} {data_directory} {individuals_list} {enpact_weights} {output_file} {files_pattern} {md}')
cmd
```
# Train a SNP-based Enpact model
1. Get epigenomic features across 521 EUR individuals with Enformer; In this paper, we used [this pipeline]().
Alternatively, these features can be downloaded from here: [epigenomic features](https://zenodo.org/record/5520737/files/epigenomic_features.tar.gz)
2. With the DL-based Enpact model, predict the Enpact scores using [this pipeline](https://github.com/hakyimlab/enpact-predict-snakemake)
3. Prepare the matrix and data for the SNP-based Enpact model such that they are compatible with predictDB format
## Format 1KG predictions
```{r}
output_directory <- '/scratch/beagle3/temi/enpact_scores/cwas_arbs_1000G'
model <- 'AR_Prostate'
exec_file <- '/beagle3/haky/users/temi/projects/Enpact/src/formatForPredictDB.R' #file.path(project_dir, "src", 'formatForPredictDB.R')
enpact_scores <- file.path(output_directory, glue("1KG.{model}.enpact_scores.txt"))
enpact_annot <- file.path(output_directory, glue("1KG.{model}.enpact_annot.txt"))
# enpact_scores <- file.path(output_directory, "lenpact", glue("1KG_logistic.{model}.enpact_scores.txt"))
# enpact_annot <- file.path(output_directory, "lenpact", glue("1KG_logistic.{model}.enpact_annot.txt"))
rds_file <- '/beagle3/haky/users/temi/projects/TFXcan/data/enpact_scores/AR_Prostate.1KG.CWAS_ARBS.predictions.2025-10-16.rds.gz'
#'/beagle3/haky/users/temi/projects/TFXcan/data/enpact_scores/AR_Prostate.1KG.CWAS_ARBS.predictions.2025-10-16.rds.gz'
#'/beagle3/haky/users/temi/projects/TFXcan/misc/reruns/enpact_predictions/ENPACT_48.1KG.CWAS_ARBS.predictions.2025-04-28.rds.gz'
#endregion"/project2/haky/temi/projects/enpact-predict-snakemake/output/1KG_linear_2025-02-11/1KG_linear_2025-02-11.enpact_scores.array.rds.gz"
# if(!dir.exists(output_folder)){dir.create(output_folder, recursive = T)}
```
```{r}
# if needed, you should edit the sbatch file: {project_dir}/src/predictCWASscores.sbatch
cmd <- glue('sbatch {project_dir}/src/formatForPredictDB.sbatch {exec_file} {rds_file} {enpact_scores} {enpact_annot} {model}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
## Train the SNP-based Enpact model
```{r}
phenotype <- 'AR_Prostate.EUR.CWAS_ARBS'
outputpath <- "/scratch/beagle3/temi/lEnpact/AR_Prostate.2025-10-23"
annotfile <- file.path(output_directory, glue("1KG.{model}.enpact_annot.txt")) #file.path(data_dir, "lenpact", "1KG.enpact_annot.txt")
enpactfile <- file.path(output_directory, glue("1KG.{model}.enpact_scores.txt")) #file.path(data_dir, "lenpact", "1KG.enpact_scores.txt")
geno_dir <- "/project2/haky/Data/1000G/population_data/EUR/annot_files"
conda_env <- "/beagle3/haky/users/temi/software/conda_envs/predictdb-env"
nextflow_command <- "/beagle3/haky/users/temi/projects/TFXcan-snakemake/workflow/PredictDb-nextflow/main.nf"
```
```{r}
# if needed, you should edit the sbatch file: {project_dir}/src/predictCWASscores.sbatch
cmd <- glue('sbatch {project_dir}/src/generateLinearModels.sbatch {phenotype} {outputpath} {annotfile} {enpactfile} {geno_dir} {conda_env} {nextflow_command}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
```{bash}
# format the covariances
gzip -dk predict_db_AR_Prostate_filtered.txt.gz
sed -e 's/:/_/g' predict_db_AR_Prostate_filtered.txt > predict_db_AR_Prostate_filtered.formatted.txt
# or
#unpigz -ck predict_db_AR_Prostate.logistic_filtered.txt.gz | sed -e 's/:/_/g' | pigz > predict_db_AR_Prostate.logistic_filtered.formatted.txt.gz
unpigz -ck predict_db_AR_Prostate.EUR.CWAS_ARBS_filtered.txt.gz | sed -e 's/:/_/g' | pigz > predict_db_AR_Prostate.EUR.CWAS_ARBS_filtered.formatted.txt.gz
```
# Predict Enpact scores on Baca individuals using the SNP-based Enpact model
## Format Baca predictions
```{r}
output_directory <- '/scratch/beagle3/temi/enpact_scores/cwas_arbs_baca'
model <- 'AR_Prostate'
exec_file <- '/beagle3/haky/users/temi/projects/Enpact/src/formatForPredictDB.R'
enpact_scores <- file.path(output_directory, glue("Baca.{model}.enpact_scores.txt"))
enpact_annot <- file.path(output_directory, glue("Baca.{model}.enpact_annot.txt"))
rds_file <- '/beagle3/haky/users/temi/projects/TFXcan/data/enpact_scores/AR_Prostate.BACA.CWAS_ARBS.predictions.2025-10-16.rds.gz'
#"/project2/haky/temi/projects/enpact-predict-snakemake/output/baca_2024-11-15/baca_2024-11-15.enpact_scores.array.rds.gz"
# if(!dir.exists(output_folder)){dir.create(output_folder, recursive = T)}
```
```{r}
# if needed, you should edit the sbatch file: {project_dir}/src/predictCWASscores.sbatch
cmd <- glue('sbatch {project_dir}/src/formatForPredictDB.sbatch {exec_file} {rds_file} {enpact_scores} {enpact_annot} {model}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
## Predict on Baca individuals
```{r}
db_name <- 'AR_Prostate.EUR.CWAS_ARBS'
model_db <- '/scratch/beagle3/temi/lEnpact/AR_Prostate.2025-10-23/AR_Prostate.EUR.CWAS_ARBS/models/filtered_db/predict_db_AR_Prostate.EUR.CWAS_ARBS_filtered.db'
# '/beagle3/haky/users/temi/projects/TFXcan/models/lenpact/AR_Prostate.2025-04-28/AR_Prostate.logistic/models/filtered_db/predict_db_AR_Prostate.logistic_filtered.db'
txt_genotypes <- '/project2/haky/Data/baca_cwas/vcfs/hg38/formatted_geno/all_chrs.text_dosages.txt.gz'
txt_samples <- '/project2/haky/Data/baca_cwas/vcfs/hg38/formatted_geno/samples.text_dosages.txt'
exec_file <- '/beagle3/haky/users/temi/software/MetaXcan/software/Predict.py'
output_folder <- "/beagle3/haky/users/temi/projects/TFXcan/data/lenpact_scores" #"/beagle3/haky/users/temi/projects/TFXcan/data/baca_lenpact/output"
output_basename <- "baca"
if(!dir.exists(output_folder)){dir.create(output_folder, recursive = T)}
```
```{r}
# if needed, you should edit the sbatch file: {project_dir}/src/predictCWASscores.sbatch
cmd <- glue('sbatch {project_dir}/src/predictENPACTscores.sbatch {db_name} {model_db} {txt_genotypes} {txt_samples} {exec_file} {output_folder} {output_basename}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
# Running TFXcan on prostate cancer data (GWAS summary statistics)
You can download the GWAS summary statistic from the CWAS paper repo [here](https://github.com/scbaca/cwas/blob/master/gwas_data/ProstateCancer_Meta_Schumacher2018.nodup.sumstats.gz) or, better still, from the [GWAS catalog](https://www.ebi.ac.uk/gwas/publications/29892016). This is [the direct link](https://ftp.ebi.ac.uk/pub/databases/gwas/summary_statistics/GCST006001-GCST007000/GCST006085/harmonised/29892016-GCST006085-EFO_0001663.h.tsv.gz)
-- If you have/want to download from the GWAS catalog, this following scripts should help with processing
```{r}
gwas_data <- file.path(project_dir, 'data', 'sumstats', '29892016-GCST006085-EFO_0001663.h.tsv.gz')
dir.create(dirname(gwas_data), recursive = F)
if(!file.exists(gwas_data)){
download.file('https://ftp.ebi.ac.uk/pub/databases/gwas/summary_statistics/GCST006001-GCST007000/GCST006085/harmonised/29892016-GCST006085-EFO_0001663.h.tsv.gz', destfile = gwas_data)
}
```
-- process the downloaded file. I have processed this file in accordance with the weights data from the SNP-based Enpact model. So, you will need to read in the models and use the data to filter for compatible SNPs.
```{r}
pcr_sumstat <- data.table::fread(gwas_data)
dim(pcr_sumstat); pcr_sumstat[1:5, 1:10]
```
-- read in the lEnpact weights
```{r}
# model_db <- file.path(project_dir, 'models', 'lenpact', 'predict_db_EUR_AR_Prostate_logistic_filtered.db')
enpactdb <- dbConnect(SQLite(), model_db)
weights <- dbGetQuery(enpactdb, 'SELECT * FROM weights')
dbDisconnect(enpactdb)
```
reformat the file and filter for only those with variant Id in the weights data
```{r}
pcgss <- pcr_sumstat %>%
dplyr::select(chrom=hm_chrom, variant_id=hm_variant_id, rsid=hm_rsid, pos=hm_pos, A2=hm_other_allele, A1=hm_effect_allele, beta=hm_beta, p_value=p_value, se=standard_error, maf=hm_effect_allele_frequency) %>%
dplyr::filter(!(is.na(variant_id) | is.na(rsid) | is.na(pos))) %>%
dplyr::mutate(zscore=beta/se) %>%
dplyr::filter(variant_id %in% weights$varID)
pcgss[1:5, 1:5]; dim(pcgss)
```
```{r}
output_folder <- file.path(project_dir, 'data', 'sumstats')
if(!dir.exists(output_folder)){
dir.create(output_folder, recursive=T)
}
pcgss %>% split(.$chrom) %>% imap(~data.table::fwrite(.x, glue('{output_folder}/chr{.y}_Schumacher.gwas_ss.txt.gz'), compress='gzip', row.names=F, quote=F, sep = '\t'))
```
-- Now, you can run TFXcan on the prostate cancer data
```{r}
db_name <- 'AR_Prostate.EUR.CWAS_ARBS'
model_db <- "/scratch/beagle3/temi/lEnpact/AR_Prostate.2025-10-23/AR_Prostate.EUR.CWAS_ARBS/models/filtered_db/predict_db_AR_Prostate.EUR.CWAS_ARBS_filtered.db"
#file.path(project_dir, 'models/lenpact/AR_Prostate.2025-04-28/AR_Prostate.logistic/models/filtered_db/predict_db_AR_Prostate.logistic_filtered.db')
covariances <- "/scratch/beagle3/temi/lEnpact/AR_Prostate.2025-10-23/AR_Prostate.EUR.CWAS_ARBS/models/filtered_db/predict_db_AR_Prostate.EUR.CWAS_ARBS_filtered.formatted.txt.gz"
#file.path(project_dir, 'models/lenpact/AR_Prostate.2025-04-28/AR_Prostate.logistic/models/filtered_db/predict_db_AR_Prostate.logistic_filtered.formatted.txt.gz')
gwas_folder <- "/beagle3/haky/users/temi/projects/Enpact/data/sumstats" #file.path(project_dir, 'data/sumstats')
gwas_file_pattern <- ".*_Schumacher.gwas_ss.txt.gz"
exec_file <- '/beagle3/haky/users/temi/software/MetaXcan/software/SPrediXcan.py'
output_file <- file.path(project_dir, 'data', 'tfxcan', 'AR_Prostate.EUR.CWAS_ARBS.TFXcan.prostate_cancer_risk.csv')
if(!dir.exists(dirname(output_file))){dir.create(dirname(output_file), recursive = T)}
```
```{r}
cmd <- glue('sbatch {project_dir}/src/sTFXcan.sbatch {db_name} {model_db} {covariances} {gwas_folder} {gwas_file_pattern} {exec_file} {output_file}')
cmd
```
```{r}
system(cmd) ; system('squeue -u temi')
```
# Running TWAS on prostate cancer data
This is very similar to using the PrediXcan pipeline. You will need to download the TWAS weights from the [PrediXcan website](https://predictdb.org/). You can use the [GTEx v8 weights](https://predictdb.org/download/weights/GTEx_V8_HapMap-2017-11-29.tar.gz) or the [GTEx v7 weights](https://predictdb.org/download/weights/GTEx_V7_HapMap-2017-11-29.tar.gz).
# Consensus matrix factorization
```{r warning=F, message=F}
devtools::source_gist('https://gist.github.com/TemiPete/250d9922b9516691f83bb1fd999a3ccc')
devtools::source_gist('https://gist.github.com/hakyim/38431b74c6c0bf90c12f')
devtools::source_gist('https://gist.github.com/hakyim/5d2251ea1a86009499e4ffdf47fe2735')
devtools::source_gist('https://gist.github.com/TemiPete/e7214eb308c4116e2f10ee96401be0c2')
devtools::source_gist('https://gist.github.com/TemiPete/b309a46e25ecec93127fb6756e68fb14')
# analyze tenerife
devtools::source_gist("https://gist.github.com/TemiPete/d303781c7ddd9b6d8b4d0163804e80c2")
```
### Step 1: First prepare the z-ratio matrices
We want to remove some tissues
```{r}
# these weird tissues should be removed
weird_tissues <- c("endometrioidadenocarcinoma", "HCT116", "HeLacontaminant", "Headandneck", "LNCaPcells", 'PeritonealEffusion')
#performance_file <- '/beagle3/haky/users/temi/projects/TFPred-snakemake/data/ENPACT_734_2024-07-26/statistics/ENPACT_734_2024-07-26.compiled_stats.txt'
performance_file <- '/beagle3/haky/users/temi/projects/Enpact/data/enpact/weights/ENPACT_734_2025-04-24.compiled_stats.with_auprc.tsv'
#'/beagle3/haky/users/temi/projects/Enpact/data/enpact/weights/ENPACT_734_2025-04-24.compiled_stats.txt'
performance <- data.table::fread(performance_file) %>%
dplyr::filter(type == 'test') %>%
dplyr::filter((!is.na(auroc) & auroc >= 0.7) & !context %in% weird_tissues)
dim(performance)
```
You need the summary statistics
```{r}
# GWAS information
ss <- data.table::fread("/beagle3/haky/users/temi/projects/TFXcan-snakemake/data/prostate_cancer_risk_2024-09-30/collection/prostate_cancer_risk.filteredGWAS.topSNPs.txt.gz") %>%
dplyr::mutate(loci = paste('chr', chr, sep='') %>% paste(., pos, sep = ':'))
# %>%
# dplyr::mutate(locus = paste('chr', chr, sep = '') %>% paste(., pos, pos + 1, sep='_'))
```
You need the TFXcan results
```{r}
dt <- data.table::fread("/beagle3/haky/users/temi/projects/Enpact/misc/reruns/prca_tfxcan/prostate_cancer_risk.enpactScores.2025-10-21.complete.spredixcan.tsv") %>%
dplyr::filter(!is.na(pvalue), !is.na(zscore)) %>%
tidyr::separate_wider_delim(tfbs, delim = "_", names = c("tf", 'tissue', 'chrom', 'start', 'end')) %>%
dplyr::mutate(locus = paste(chrom, start, end, sep = "_"), tf_tissue = paste(tf, tissue, sep = "_")) %>%
dplyr::filter(tf_tissue %in% performance$model) %>%
dplyr::select(locus, tf, tissue, tf_tissue, chrom, start, end, zscore, pvalue) %>%
dplyr::filter(!grepl("HCT116|HeLacontaminant|PeritonealEffusion|LNCaPcells|endometrioidadenocarcinoma|Headandneck", tissue)) %>%
dplyr::mutate(snp = paste(chrom, start, sep = ':'))
```
```{r}
process_tfxcan_results <- function(summary_results, gwas_summary_stats, combine_at, retain_at, aggregate_on = c('tf', 'tissue', 'tf_tissue'), how = 'weights'){
# analysis_factor <- switch(analysis_level,
# 'tf' = 'tf',
# 'tissue' = 'tissue',
# 'tf_tissue' = 'tf_tissue'
# )
aggregate_on <- switch(aggregate_on,
'tf' = 'tf',
'tissue' = 'tissue',
'tf_tissue' = 'tf_tissue'
)
# process the sumstats to make it easier to work with
res_sumstats <- gwas_summary_stats %>%
dplyr::rename(locus = loci, zscore = zscore, pvalue = pval) %>%
dplyr::filter(nchar(a0) == 1) %>%
dplyr::mutate(bind_level = 'GWAS') %>%
dplyr::select(locus, bind_level, zscore, pvalue) %>%
dplyr::filter(locus %in% summary_results$snp)
print(head(res_sumstats))
if(aggregate_on %in% c('tf', 'tissue')){
dt_gwas <- res_sumstats %>%
dplyr::select(locus, bind_level, zscore, pvalue)
dt_tfxcan <- summary_results %>%
dplyr::select(locus, all_of(c(combine_at, aggregate_on)), zscore, pvalue)
mtx <- dt_tfxcan %>%
tidyr::separate(locus, c('chrom', 'start'), sep = ':', remove = FALSE) %>%
dplyr::mutate(start = as.numeric(start), end = as.numeric(start + 1))
if(how == 'weights'){
mtx <- mtx %>%
dplyr::group_split(!!rlang::sym(retain_at), chrom, start, end) %>%
purrr::map_dfr(merge_zscores, level = retain_at, how = 'weights') %>%
do.call(cbind, .) %>% as.data.table() %>%
dplyr::mutate(locus = paste0(chrom, ":", start), zscore = as.numeric(zscore)) %>%
dplyr::arrange(desc(zscore)) %>%
dplyr::select(locus, all_of(c('level', 'zscore'))) %>%
dplyr::rename(bind_level = 'level')
} else if (how == 'acat'){
# sum and convert to zscores
# dplyr::group_by(!!rlang::sym(retain_at))
mtx <- mtx %>%
dplyr::group_by(!!rlang::sym(aggregate_on), chrom, start, end) %>%
dplyr::summarize(nv = acat(pvalue) + 2.2e-16) %>%
dplyr::mutate(locus = paste0(chrom, ":", start), zscore = qnorm(nv, lower.tail = FALSE)) %>%
dplyr::ungroup() %>%
dplyr::group_by(!!rlang::sym(aggregate_on)) %>%
dplyr::arrange(desc(zscore)) %>%
dplyr::select(locus, all_of(c(aggregate_on, 'zscore'))) %>%
dplyr::rename(bind_level = aggregate_on)
}
} else if (aggregate_on %in% c('tf_tissue')) {
# gg <- res_sumstats %>%
# dplyr::select(locus, bind_level, zscore, pvalue)
mtx <- summary_results %>%
dplyr::select(locus = snp, bind_level = !!rlang::sym(aggregate_on), zscore, pvalue)
dt_gwas <- res_sumstats %>%
dplyr::select(locus, bind_level, zscore, pvalue)
# mtx <- dplyr::bind_rows(gg, xx)
}
print(head(mtx))
print("===")
print(head(dt_gwas))
mat_tfxcan <- dplyr::bind_rows(mtx, dt_gwas) %>%
dplyr::select(locus, bind_level, zscore) %>%
tidyr::pivot_wider(id_cols = 'locus', values_from = zscore, names_from = bind_level) %>%
tibble::column_to_rownames('locus') %>%
as.matrix() %>%
t()
print(mat_tfxcan[1:3, 1:3])
#mat_tfxcan <- mat_tfxcan[complete.cases(mat_tfxcan), ]
return(mat_tfxcan)
}
```
```{r}
# ss %>%
# dplyr::rename(locus = loci, zscore = zscore, pvalue = pval) %>%
# dplyr::filter(nchar(a0) == 1) %>%
# dplyr::mutate(bind_level = 'GWAS') %>%
# dplyr::select(locus, bind_level, zscore, pvalue) %>% head()
# dplyr::filter(locus %in% summary_results$locus) %>% head()
```
```{r}
# collect the Z-scores into a matrix of loci x TF/tissue pairs
tf_tissue_processed <- process_tfxcan_results(dt, ss, combine_at = 'tf', retain_at = 'tissue', aggregate_on = 'tf_tissue')
# collect the Z-scores into two matrices for TFXcan and GWAS results
data_list <- list()
data_list[['zratios']] <- collect_matrices(tf_tissue_processed)
# divide or get eh Z-ratios
zratio_matdev <- (data_list[["zratios"]][["tfxcan"]])^2/(data_list[["zratios"]][["gwas"]][,,drop = TRUE])^2
# there are missing values because I removed associations with pvalue at fdr < 0.05
dim(zratio_matdev); zratio_matdev[1:5, 1:5]
```
```{r}
saveRDS(data_list, '/beagle3/haky/users/temi/projects/TFXcan/data/tenerife/PrCa.tfxcan.zscores.matrices.rds')
saveRDS(zratio_matdev, '/beagle3/haky/users/temi/projects/TFXcan/data/tenerife/PrCa.tfxcan.zratios.matrix.rds')
```
```{r}
sum(complete.cases(zratio_matdev))
```
### Step 2: Split the z-ratio matrix into random subsets
```{r}
X <- readRDS('/beagle3/haky/users/temi/projects/TFXcan/data/tenerife/PrCa.tfxcan.zratios.matrix.rds') # loci by TF_tissues
```
```{r}
# subsets directory
consensus_subsets_dir <- file.path(project_dir, 'data', 'tenerife', 'repeat_flash', 'prca_risk')
dir.create(consensus_subsets_dir, recursive = TRUE)
```
```{r}
# create random subsets; here I use 1000 random subsets, each with 80% of the loci
set.seed(2025)
random_loci <- purrr::map(1:1000, function(k){
jj <- sample(nrow(X), round(nrow(X) * 0.8))
return(jj)
})
# confirm length
lapply(random_loci, length) %>% unlist() %>% unique()
# split into 100 batches
batches_loci <- purrr::map(1:100, function(k){
jj <- random_loci[seq(k, 1000, by = 100) ] #|> unlist() #seq(k, 1, 1)
return(jj)
})
names(batches_loci) <- paste0('batch', 1:100)
lapply(batches_loci, length) |> unlist() %>% sum()
# save these as a list
lapply(names(batches_loci), function(ni) {
saveRDS(batches_loci[ni], glue::glue('{consensus_subsets_dir}/prca_risk.random_subsets.{ni}.rds'))
})
# save this as a list
# saveRDS(random_loci, '/beagle3/haky/users/temi/projects/Enpact/data/tenerife/prca_risk.random_subsets_1000.rds')
```
```{r}
write(names(batches_loci), file = glue::glue('{consensus_subsets_dir}/prca_risk.random_subsets.txt'))
```
### Step 3: Run Flashier on the random subsets
```{r}
script <- file.path(project_dir, 'src/repeat_flash.sbatch')
datafile <- file.path(project_dir, 'data/tenerife/PrCa.tfxcan.zratios.matrix.rds')
output_basename <- file.path('/beagle3/haky/users/temi/projects/TFXcan/data/tenerife/flash_results', 'prca_risk') # not a directory but a prefix for the output files
priorL <- 'ebnm_point_exponential'
priorF <- 'ebnm_point_exponential'
greedy_Kmax <- 40L
batch_list <- glue::glue('{consensus_subsets_dir}/prca_risk.random_subsets.txt')
splits_directory <- consensus_subsets_dir
merged_output_basename <- '/beagle3/haky/users/temi/projects/TFXcan/data/tenerife/prca_risk'
```
```{r}
glue::glue("sbatch {script} {datafile} {output_basename} {priorL} {priorF} {greedy_Kmax} {batch_list} {splits_directory} {merged_output_basename}")
```
### Step 4: Run consensus factor analysis on the outputs