Skip to content

Commit fe2cf79

Browse files
authored
Refactoring coloc and cluster into different steps, adding to analysis Rmd scripts (#167)
1 parent 8a7fede commit fe2cf79

37 files changed

Lines changed: 4526 additions & 1223 deletions

‎.github/workflows/main.yml‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,12 @@ jobs:
1414
- uses: actions/checkout@v2
1515
- uses: r-lib/actions/setup-r@v2
1616
- name: Install lintr
17-
run: Rscript -e 'install.packages("lintr", repos = "https://cloud.r-project.org")'
17+
# Pin to the same version as docker://mrcieu/genotype-phenotype-map:1.0.0
18+
# so CI lint rules match `make lint` inside Apptainer.
19+
run: |
20+
Rscript -e 'install.packages("remotes", repos = "https://cloud.r-project.org")'
21+
Rscript -e 'remotes::install_version("lintr", version = "3.3.0.1", repos = "https://cloud.r-project.org")'
22+
Rscript -e 'cat("lintr ", as.character(packageVersion("lintr")), "\n")'
1823
- name: Run linter
1924
run: make lint
2025
- name: Check that tests have been run successfully

‎.lintr‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@ linters: linters_with_defaults(
33
line_length_linter = line_length_linter(120),
44
object_length_linter(length = 60L),
55
return_linter = return_linter(return_style = "explicit"),
6+
assignment_linter = assignment_linter(operator = c("<-", "<<-")),
67
object_name_linter = NULL,
78
object_usage_linter = NULL,
89
T_and_F_symbol_linter = NULL,
910
commented_code_linter = NULL,
1011
pipe_consistency_linter = NULL
1112
)
12-
encoding: "UTF-8"
13+
encoding: "UTF-8"

‎DOCUMENTATION.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,9 @@ Pre-existing (you must provide):
113113
| File(s) | Script |
114114
|---------|--------|
115115
| `studies_processed.tsv.gz`, `traits_processed.tsv.gz`, `study_extractions.tsv.gz` | `compile_results.R` |
116-
| `coloc_clustered_results.tsv.gz`, `coloc_pairwise_results.tsv.gz` | `compile_results.R` (aggregates from `coloc_and_cluster_studies_in_ld_block.R` per LD block) |
116+
| `coloc_pairwise_results.tsv.gz` | `compile_results.R` (aggregates per-LD-block results from `coloc_studies_in_ld_block.R`, then annotated by `cluster_studies_in_ld_block.R`) |
117+
| `coloc_clustered_results.tsv.gz` | `compile_results.R` (aggregates per-LD-block clustering from `cluster_studies_in_ld_block.R`, using the global threshold from `calculate_global_bfdr.R`) |
118+
| `pipeline_metadata/global_bfdr.tsv` | `calculate_global_bfdr.R` (synced to worker servers for GWAS upload clustering) |
117119
| `rare_results.tsv.gz` | `compile_results.R` (aggregates from `compare_rare_studies_in_ld_block.R` per LD block) |
118120
| `studies.db`, `associations.db`, `associations_full.db`, `coloc_pairs.db`, `coloc_pairs_full.db`, `ld.db`, `gwas_upload.db` | `create_db_from_results.R` |
119121
| `static_web/opengwas_ids.json`, `phenotype_id_map.json`, `robots.txt`, `sitemap.xml`, `pipeline_summary.html` | `create_static_web_files.R` |

‎Snakefile‎

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ standardisation_pattern = LD_BLOCK_DATA_DIR + '{ld_block}/standardisation_comple
4646
imputation_pattern = LD_BLOCK_DATA_DIR + '{ld_block}/imputation_complete'
4747
finemapping_pattern = LD_BLOCK_DATA_DIR + '{ld_block}/finemapping_complete'
4848
coloc_pattern = LD_BLOCK_DATA_DIR + '{ld_block}/coloc_complete'
49+
clustering_pattern = LD_BLOCK_DATA_DIR + '{ld_block}/clustering_complete'
4950
compare_rare_pattern = LD_BLOCK_DATA_DIR + '{ld_block}/compare_rare_complete'
5051

5152
### OUTPUT DATA FILES
@@ -84,6 +85,7 @@ rule all:
8485
expand(imputation_pattern, ld_block=ld_blocks),
8586
expand(finemapping_pattern, ld_block=ld_blocks),
8687
expand(coloc_pattern, ld_block=ld_blocks),
88+
expand(clustering_pattern, ld_block=ld_blocks),
8789
expand(compare_rare_pattern, ld_block=ld_blocks),
8890
coloc_pairwise_results,
8991
coloc_clustered_results,
@@ -155,7 +157,8 @@ rule standardise_rule:
155157
ld_block = params.ld_dir.replace(LD_BLOCK_DATA_DIR, '')
156158
command = f"Rscript standardise_studies_in_ld_block.R \
157159
--ld_block {ld_block} \
158-
--completed_output_file {output}"
160+
--completed_output_file {output} \
161+
{block_list_arg}"
159162
subprocess.run(command, shell=True)
160163

161164

@@ -177,7 +180,8 @@ rule:
177180
ld_block = params.ld_dir.replace(LD_BLOCK_DATA_DIR, '')
178181
command = f"Rscript impute_studies_in_ld_block.R \
179182
--ld_block {ld_block} \
180-
--completed_output_file {output}"
183+
--completed_output_file {output} \
184+
{block_list_arg}"
181185
subprocess.run(command, shell=True)
182186

183187
rule finemap_rule:
@@ -198,7 +202,8 @@ rule finemap_rule:
198202
ld_block = params.ld_dir.replace(LD_BLOCK_DATA_DIR, '')
199203
command = f"Rscript finemap_studies_in_ld_block.R \
200204
--ld_block {ld_block} \
201-
--completed_output_file {output}"
205+
--completed_output_file {output} \
206+
{block_list_arg}"
202207
subprocess.run(command, shell=True)
203208

204209
rule coloc_rule:
@@ -218,7 +223,47 @@ rule coloc_rule:
218223
command = f"mkdir -p $(dirname {output}) && touch {output}"
219224
else:
220225
ld_block = params.ld_dir.replace(LD_BLOCK_DATA_DIR, '')
221-
command = f"Rscript coloc_and_cluster_studies_in_ld_block.R \
226+
command = f"Rscript coloc_studies_in_ld_block.R \
227+
--ld_block {ld_block} \
228+
--completed_output_file {output} \
229+
{block_list_arg}"
230+
subprocess.run(command, shell=True)
231+
232+
# rule calculate_global_bfdr:
233+
# name: 'calculate_global_bfdr'
234+
# input: expand(coloc_pattern, ld_block=ld_blocks)
235+
# output:
236+
# global_bfdr_tsv=global_bfdr_file,
237+
# global_bfdr_complete=temporary(global_bfdr_complete_file)
238+
# threads: 1
239+
# params:
240+
# block_list_arg=block_list_arg,
241+
# shell:
242+
# """
243+
# Rscript calculate_global_bfdr.R \
244+
# --output_file {output.global_bfdr_tsv} \
245+
# --completed_output_file {output.global_bfdr_complete} \
246+
# {params.block_list_arg}
247+
# """
248+
249+
rule clustering_rule:
250+
name: f'cluster_per_ld_block'
251+
retries: 1
252+
threads: 2
253+
input:
254+
coloc = coloc_pattern
255+
output: temporary(clustering_pattern)
256+
params:
257+
ld_dir=lambda wildcards, output: os.path.dirname(output[0])
258+
run:
259+
ld_blocks = pd.read_csv(ld_blocks_to_process, sep='\t')
260+
skip_block = len(ld_blocks[ld_blocks.data_dir == params.ld_dir]) == 0
261+
262+
if skip_block:
263+
command = f"mkdir -p $(dirname {output}) && touch {output}"
264+
else:
265+
ld_block = params.ld_dir.replace(LD_BLOCK_DATA_DIR, '')
266+
command = f"Rscript cluster_studies_in_ld_block.R \
222267
--ld_block {ld_block} \
223268
--completed_output_file {output} \
224269
{block_list_arg}"
@@ -247,7 +292,7 @@ rule compare_rare_rule:
247292
subprocess.run(command, shell=True)
248293

249294
rule compile_results:
250-
input: expand(coloc_pattern, ld_block=ld_blocks), expand(compare_rare_pattern, ld_block=ld_blocks)
295+
input: expand(clustering_pattern, ld_block=ld_blocks), expand(compare_rare_pattern, ld_block=ld_blocks)
251296
threads: 1
252297
params:
253298
block_list_arg=block_list_arg,

‎docker/requirements.R‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,13 @@ install.packages(c("remotes", "devtools"))
88

99
cran_install <- c(
1010
"testthat", "susieR", "Rfast", "duckdb", "validate", "redux", "sendmailR", "igraph", "svglite", "readxl",
11-
"janitor", "lintr", "styler"
11+
"janitor", "styler"
1212
)
1313
install.packages(cran_install)
1414

15+
# Pin lintr to match CI (.github/workflows/main.yml) and local make lint behaviour.
16+
remotes::install_version("lintr", version = "3.3.0.1")
17+
1518
# Install packages from GitHub and specific versions
1619
remotes::install_version("RcppEigen", version = "0.3.3.9.3")
1720
devtools::install_github("jrs95/hyprcoloc", upgrade = "never")
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
source("constants.R")
2+
3+
# Calculate a single global Bayesian FDR (BFDR) threshold across the pairwise coloc
4+
# results of every LD block, and store it in the pipeline_metadata directory so the
5+
# downstream clustering step can apply one consistent H4 threshold everywhere.
6+
7+
parser <- argparser::arg_parser("Calculate the global Bayesian FDR threshold across all LD blocks")
8+
parser <- argparser::add_argument(
9+
parser,
10+
"--output_file",
11+
help = "File to write the global BFDR threshold and metadata to",
12+
type = "character",
13+
default = NA
14+
)
15+
parser <- argparser::add_argument(
16+
parser,
17+
"--target_bfdr",
18+
help = "Target Bayesian FDR",
19+
type = "numeric",
20+
default = target_global_bfdr
21+
)
22+
parser <- argparser::add_argument(
23+
parser,
24+
"--block_list",
25+
help = "CSV of studies to exclude from the global BFDR calculation (columns: id_pattern, cis_trans)",
26+
type = "character",
27+
default = NA
28+
)
29+
parser <- argparser::add_argument(
30+
parser,
31+
"--completed_output_file",
32+
help = "Sentinel file to write once the global BFDR threshold has been calculated",
33+
type = "character",
34+
default = NA
35+
)
36+
37+
args <- argparser::parse_args(parser)
38+
39+
main <- function() {
40+
start_time <- Sys.time()
41+
42+
output_file <- args$output_file
43+
if (is.null(output_file) || is.na(output_file)) {
44+
output_file <- global_bfdr_file_path(args$block_list)
45+
}
46+
47+
48+
pairwise_files <- Sys.glob(
49+
glue::glue("{ld_block_data_dir}*/*/*/{ld_block_file_basenames()$coloc_pairwise}")
50+
)
51+
message(glue::glue("Found {length(pairwise_files)} LD blocks with pairwise coloc results"))
52+
53+
block_list <- NULL
54+
if (!is.null(args$block_list) && !is.na(args$block_list) && file.exists(args$block_list)) {
55+
block_list <- vroom::vroom(args$block_list, show_col_types = FALSE)
56+
}
57+
58+
h4_values <- unlist(lapply(pairwise_files, read_block_h4, block_list = block_list), use.names = FALSE)
59+
message(glue::glue(
60+
"Collected {length(h4_values)} pairwise H4 values in {diff_time_taken(start_time)}"
61+
))
62+
63+
64+
bfdr <- calculate_global_bfdr_threshold(
65+
posterior_probs = h4_values,
66+
target_bfdr = args$target_bfdr,
67+
minimum_threshold = posterior_prob_h4_threshold
68+
)
69+
70+
global_bfdr <- data.frame(
71+
threshold = bfdr$threshold,
72+
estimated_bfdr = bfdr$estimated_bfdr,
73+
n_discoveries = bfdr$n_discoveries,
74+
target_bfdr = args$target_bfdr,
75+
minimum_threshold = posterior_prob_h4_threshold,
76+
n_pairs = length(h4_values),
77+
n_blocks = length(pairwise_files),
78+
default_threshold = posterior_prob_h4_threshold
79+
)
80+
81+
message(glue::glue(
82+
"Global BFDR threshold: {signif(bfdr$threshold, 3)} ",
83+
"(default {signif(posterior_prob_h4_threshold, 3)}, target BFDR={args$target_bfdr}, ",
84+
"discoveries={bfdr$n_discoveries}, estimated BFDR={signif(bfdr$estimated_bfdr, 3)})"
85+
))
86+
87+
dir.create(dirname(output_file), showWarnings = FALSE, recursive = TRUE)
88+
vroom::vroom_write(global_bfdr, output_file)
89+
message(glue::glue("Wrote global BFDR threshold to {output_file}"))
90+
91+
completed_output_file <- args$completed_output_file
92+
if (!is.null(completed_output_file) && !is.na(completed_output_file)) {
93+
dir.create(dirname(completed_output_file), showWarnings = FALSE, recursive = TRUE)
94+
vroom::vroom_write(data.frame(), completed_output_file)
95+
message(glue::glue("Wrote completion sentinel to {completed_output_file}"))
96+
}
97+
98+
return()
99+
}
100+
101+
calculate_global_bfdr_threshold <- function(posterior_probs, target_bfdr = 0.05, minimum_threshold = 0.8) {
102+
valid_probs <- posterior_probs[is.finite(posterior_probs)]
103+
valid_probs <- valid_probs[!is.na(valid_probs)]
104+
if (length(valid_probs) == 0) {
105+
return(list(
106+
threshold = 1,
107+
estimated_bfdr = NA_real_,
108+
n_discoveries = 0
109+
))
110+
}
111+
112+
ordered_probs <- sort(valid_probs, decreasing = TRUE)
113+
cumulative_bfdr <- cumsum(1 - ordered_probs) / seq_along(ordered_probs)
114+
passing_indices <- which(cumulative_bfdr <= target_bfdr)
115+
116+
if (length(passing_indices) == 0) {
117+
return(list(
118+
threshold = 1,
119+
estimated_bfdr = NA_real_,
120+
n_discoveries = 0
121+
))
122+
}
123+
124+
threshold <- ordered_probs[max(passing_indices)]
125+
threshold <- max(threshold, minimum_threshold)
126+
discoveries <- valid_probs[valid_probs >= threshold]
127+
estimated_bfdr <- if (length(discoveries) == 0) NA_real_ else sum(1 - discoveries) / length(discoveries)
128+
129+
return(list(
130+
threshold = threshold,
131+
estimated_bfdr = estimated_bfdr,
132+
n_discoveries = length(discoveries)
133+
))
134+
}
135+
136+
#' Read the eligible H4 values from a block's pairwise coloc results.
137+
#' Self-pairs (study_a == study_b) and ignored pairs are excluded from the global pool,
138+
#' since self-colocs are ~1 by construction and would bias the FDR threshold downward.
139+
read_block_h4 <- function(pairwise_file, block_list = NULL) {
140+
if (!file.exists(pairwise_file) || file.size(pairwise_file) == 0) {
141+
return(numeric(0))
142+
}
143+
144+
header <- tryCatch(
145+
names(data.table::fread(pairwise_file, nrows = 0, showProgress = FALSE)),
146+
error = function(e) character(0)
147+
)
148+
h4_column <- if ("h4" %in% header) "h4" else if ("PP.H4.abf" %in% header) "PP.H4.abf" else NA_character_
149+
if (is.na(h4_column)) {
150+
return(numeric(0))
151+
}
152+
153+
select_columns <- intersect(c(h4_column, "study_a", "study_b", "ignore"), header)
154+
pairs <- tryCatch(
155+
data.table::fread(
156+
pairwise_file,
157+
select = select_columns,
158+
showProgress = FALSE,
159+
verbose = FALSE
160+
),
161+
error = function(e) {
162+
message(glue::glue("Could not read {pairwise_file}: {e$message}"))
163+
return(NULL)
164+
}
165+
)
166+
if (is.null(pairs) || nrow(pairs) == 0) {
167+
return(numeric(0))
168+
}
169+
170+
keep <- rep(TRUE, nrow(pairs))
171+
if (all(c("study_a", "study_b") %in% names(pairs))) {
172+
keep <- keep & !(!is.na(pairs$study_a) & !is.na(pairs$study_b) & pairs$study_a == pairs$study_b)
173+
}
174+
if ("ignore" %in% names(pairs)) {
175+
keep <- keep & !(pairs$ignore %in% TRUE)
176+
}
177+
178+
if (!is.null(block_list) && nrow(block_list) > 0) {
179+
finemapped_file <- file.path(
180+
dirname(pairwise_file),
181+
ld_block_file_basenames()$finemapped_studies
182+
)
183+
finemapped_studies <- if (file.exists(finemapped_file)) {
184+
vroom::vroom(finemapped_file, show_col_types = FALSE)
185+
} else {
186+
data.frame()
187+
}
188+
cis_trans_a <- finemapped_studies$cis_trans[match(pairs$study_a, finemapped_studies$study)]
189+
cis_trans_b <- finemapped_studies$cis_trans[match(pairs$study_b, finemapped_studies$study)]
190+
blocked_pair <- is_study_blocked(block_list, pairs$study_a, cis_trans_a) |
191+
is_study_blocked(block_list, pairs$study_b, cis_trans_b)
192+
keep <- keep & !blocked_pair
193+
}
194+
195+
return(as.numeric(pairs[[h4_column]][keep]))
196+
}
197+
198+
invisible(main())

0 commit comments

Comments
 (0)