File size: 15,910 Bytes
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Writing the DTO input tree.
#
# The tree is split in two at the top level, by how each file is consumed on the
# cluster:
#
#   <outdir>/lists/<pert_db>/<binding_db>/
#       binding/<sample_id>.csv        target_locus_tag,rank   (no header)
#       pr/effect/<sample_id>.csv
#       pr/pvalue/<sample_id>.csv      only when the dataset reports p-values
#
#   <outdir>/index/<pert_db>/<binding_db>/
#       background.csv
#       lookup.txt                     TSV: binding, pr_effect[, pr_pvalue]
#       incomplete.csv
#   <outdir>/index/manifest.csv
#   <outdir>/index/pair_summary.csv
#
# `lists/` is the bulk -- tens of thousands of files of a few KB each, of which
# a given array task reads exactly one or two. Unpacking that onto a parallel
# filesystem is metadata-bound and slow, so it is meant to be shipped as a
# single SquashFS image and read in place:
#
#   mksquashfs <outdir>/lists dto_lists.sqsh -comp zstd -b 1M -no-xattrs -noappend
#
# `index/` is the handful of files per pair that must stay loose and readable:
# the submit script globs `index/*/*/lookup.txt` to enumerate array jobs, and
# every task reads `background.csv`. Together they are a few hundred files, not
# tens of thousands.
#
# The paths written into lookup.txt are `<scratch_path>/lists/...`, mirroring
# this layout, so the same tree works unpacked on scratch or mounted from the
# image -- see DTO_INPUT_ROOT in dto_cluster/run_dto.sh.

library(cli)
library(dplyr)
library(readr)
library(tibble)

# Top-level split: bulk ranked lists vs the per-pair files the job scripts read.
.DTO_LISTS_SUBDIR <- "lists"
.DTO_INDEX_SUBDIR <- "index"

#' Write one ranked list per sample
#'
#' Two implementations of the same contract, both consuming a SELECT that emits
#' `sample_id, target_locus_tag, rank_value, sort_key` and both writing
#' `<dir>/<sample_id>.csv` holding `target_locus_tag,rank_value` with no header,
#' ordered by `sort_key`.
#'
#' The DuckDB path materialises the ranked result once, indexes it on
#' `sample_id`, and issues one small `COPY` per sample. On the worst pair in the
#' collection (hackett x rossi_mindel: 6.6M rows, 1260 samples) that is ~43s and
#' ~150MB of R memory; pulling the same frame into R took minutes and 4.4GB.
#'
#' `COPY ... PARTITION_BY (sample_id)` looks like the obvious way to do this in
#' one statement and is *not* used: it reorders rows within a partition, so the
#' ranked lists come out shuffled.
#'
#' The R path pulls the frame across and splits it. It is slower and much
#' hungrier, and exists as a cross-check on the DuckDB path.
#'
#' @param vdb A VirtualDB handle.
#' @param select_sql SELECT producing the four columns above.
#' @param dir Directory to write into. Cleared first.
#' @param use_duckdb_copy Use the DuckDB path.
#' @return Character vector of sample_ids written.
dto_write_ranked_lists <- function(vdb, select_sql, dir, use_duckdb_copy = TRUE) {
    if (dir.exists(dir)) unlink(dir, recursive = TRUE)
    dir.create(dir, recursive = TRUE, showWarnings = FALSE)

    if (use_duckdb_copy) {
        return(.dto_write_via_duckdb(vdb, select_sql, dir))
    }

    df <- vdb$query(select_sql)
    if (!nrow(df)) {
        return(character())
    }

    df <- df[order(df$sample_id, df$sort_key), ]
    by_sample <- split(df[, c("target_locus_tag", "rank_value")], df$sample_id)
    for (sid in names(by_sample)) {
        write_csv(by_sample[[sid]], file.path(dir, paste0(sid, ".csv")), col_names = FALSE)
    }
    names(by_sample)
}

.DTO_RANKED_TBL <- "_dto_ranked"

.dto_write_via_duckdb <- function(vdb, select_sql, dir) {
    dto_execute(vdb, glue::glue(
        "CREATE OR REPLACE TEMP TABLE {.DTO_RANKED_TBL} AS {select_sql}"
    ))
    on.exit(dto_execute(vdb, glue::glue("DROP TABLE IF EXISTS {.DTO_RANKED_TBL}")), add = TRUE)

    # Turns each per-sample COPY into a point lookup rather than a full scan.
    dto_execute(vdb, glue::glue(
        "CREATE INDEX {.DTO_RANKED_TBL}_sid ON {.DTO_RANKED_TBL}(sample_id)"
    ))

    ids <- vdb$query(glue::glue(
        "SELECT DISTINCT sample_id FROM {.DTO_RANKED_TBL} ORDER BY sample_id"
    ))$sample_id
    if (!length(ids)) {
        return(character())
    }

    for (sid in ids) {
        dest <- file.path(dir, paste0(sid, ".csv"))
        dto_execute(vdb, glue::glue(
            "COPY (
                 SELECT target_locus_tag, rank_value
                 FROM {.DTO_RANKED_TBL}
                 WHERE sample_id = {.sql_str(sid)}
                 ORDER BY sort_key
             ) TO {.sql_str(dest)} (FORMAT CSV, HEADER false)"
        ))
    }

    ids
}

#' Build the lookup and incomplete-case tables for one pair
#'
#' Full-joins the two sides on regulator so that samples present on only one
#' side surface as incomplete cases rather than silently vanishing. Carried over
#' from `create_pr_lookups()` in the pre-refactor script.
#'
#' @param binding_map Tibble of `sample_id`, `regulator_locus_tag`.
#' @param pert_map Same shape, perturbation side.
#' @param scratch_pair_dir Directory the cluster job will see, used to build the
#'   paths written into `lookup.txt`.
#' @param include_pvalue Emit the third (`pr_pvalue`) column. `FALSE` for
#'   datasets with no p-value column, which get no `pr/pvalue/` directory -- a
#'   column pointing at files that were never written would break the job.
#' @param pr_sizes Tibble of `sample_id`, `n_targets` from
#'   `dto_list_sizes_sql()`. Required for `min_pr_targets` to do anything.
#' @param min_pr_targets Drop lookup rows whose perturbation list holds fewer
#'   than this many targets. A handful of targets cannot produce a meaningful
#'   overlap: DTO returns intersection 0 and an empirical p-value of 1, having
#'   spent an array task and 1000 permutations to say so. Dropped rows are
#'   recorded in `incomplete.csv` as `pr_below_min` rather than vanishing. `0`
#'   disables the floor.
#' @return List with `lookup` and `incomplete` tibbles.
dto_build_lookup <- function(binding_map, pert_map, scratch_pair_dir,
                             include_pvalue = TRUE,
                             pr_sizes = NULL,
                             min_pr_targets = 0) {
    binding_samples <- binding_map %>%
        distinct(binding_id = sample_id, regulator_locus_tag)

    pr_samples <- pert_map %>%
        distinct(pr_id = sample_id, regulator_locus_tag)

    lookup_df <- binding_samples %>%
        full_join(pr_samples, by = "regulator_locus_tag", relationship = "many-to-many") %>%
        mutate(
            binding = if_else(
                !is.na(binding_id),
                file.path(scratch_pair_dir, "binding", paste0(binding_id, ".csv")),
                NA_character_
            ),
            pr_effect = if_else(
                !is.na(pr_id),
                file.path(scratch_pair_dir, "pr", "effect", paste0(pr_id, ".csv")),
                NA_character_
            ),
            pr_pvalue = if_else(
                !is.na(pr_id),
                file.path(scratch_pair_dir, "pr", "pvalue", paste0(pr_id, ".csv")),
                NA_character_
            )
        )

    lookup_cols <- if (include_pvalue) {
        c("binding", "pr_effect", "pr_pvalue")
    } else {
        c("binding", "pr_effect")
    }

    lookup_df <- if (!is.null(pr_sizes) && min_pr_targets > 0) {
        sizes <- pr_sizes %>%
            transmute(
                pr_id = as.character(sample_id),
                pr_n_targets = as.integer(n_targets)
            )
        lookup_df %>%
            left_join(sizes, by = "pr_id") %>%
            mutate(pr_below_min = !is.na(pr_id) & pr_n_targets < min_pr_targets)
    } else {
        lookup_df %>%
            mutate(pr_n_targets = NA_integer_, pr_below_min = FALSE)
    }

    list(
        lookup = lookup_df %>%
            filter(!is.na(binding_id), !is.na(pr_id), !pr_below_min) %>%
            select(all_of(lookup_cols)),
        incomplete = lookup_df %>%
            filter(is.na(binding_id) | is.na(pr_id) | pr_below_min) %>%
            mutate(missing_type = case_when(
                is.na(binding_id) & is.na(pr_id) ~ "both",
                is.na(binding_id) ~ "binding",
                is.na(pr_id) ~ "pr",
                pr_below_min ~ "pr_below_min",
                TRUE ~ "unknown"
            )) %>%
            select(regulator_locus_tag, binding_id, pr_id, pr_n_targets, missing_type) %>%
            distinct()
    )
}

#' Write the run manifest
#'
#' Records db_name -> HuggingFace repo/config so nothing downstream has to
#' hard-code the `repo;config;sample_id` composite ID prefixes.
#'
#' @param vdb A VirtualDB handle.
#' @param binding_dbs Binding db_names in the run.
#' @param pert_dbs Perturbation db_names in the run.
#' @param outdir Root of the DTO input tree. The manifest is written under
#'   `index/`, with the other files the cluster reads directly.
#' @return The manifest tibble, invisibly.
dto_write_manifest <- function(vdb, binding_dbs, pert_dbs, outdir) {
    manifest <- bind_rows(
        dto_hf_coords(vdb, binding_dbs) %>% mutate(role = "binding"),
        dto_hf_coords(vdb, pert_dbs) %>% mutate(role = "perturbation")
    )

    index_dir <- file.path(outdir, .DTO_INDEX_SUBDIR)
    dir.create(index_dir, recursive = TRUE, showWarnings = FALSE)
    write_csv(manifest, file.path(index_dir, "manifest.csv"))
    invisible(manifest)
}

#' Prepare every DTO input file for one (binding, perturbation) pair
#'
#' The unit of work: stage the two temp tables, write the three ranked-list
#' sets, the background, the lookup and the incomplete cases, then drop the temp
#' tables.
#'
#' @param vdb A VirtualDB handle, with `dto_universe` already registered.
#' @param binding_db db_name of the binding dataset.
#' @param pert_db db_name of the perturbation dataset.
#' @param outdir Root of the DTO input tree.
#' @param scratch_path Root the cluster job will see, used for `lookup.txt`.
#' @param max_rows Cap each ranked list at this many ranks (or rows -- see
#'   `truncate_by`), applied after every filter and after ranking, so surviving
#'   rank values are the untruncated ones. `NULL` writes full lists. DTO scales
#'   with the square of the number of distinct ranks, so this is the main
#'   runtime lever. `background.csv` is not capped -- it stays the size it would
#'   be with full lists.
#' @param truncate_by `"rank"` cuts at whole rank blocks, keeping every row tied
#'   at the last surviving rank; `"row"` is a hard row cap that can split a tie.
#'   See `.limit_where()`.
#' @param min_pr_targets Omit a regulator from `lookup.txt` when its
#'   perturbation list holds fewer targets than this. See `dto_build_lookup()`.
#' @param use_duckdb_copy Passed to `dto_write_ranked_lists()`.
#' @return A one-row tibble summarising the pair, invisibly.
dto_prepare_pair <- function(vdb,
                             binding_db,
                             pert_db,
                             outdir = here::here("results/dto"),
                             scratch_path = "/scratch/mblab/chasem/dto",
                             max_rows = 300,
                             truncate_by = c("rank", "row"),
                             min_pr_targets = 10,
                             use_duckdb_copy = TRUE) {
    truncate_by <- match.arg(truncate_by)
    b_spec <- BINDING_DTO_REGISTRY[[binding_db]]
    p_spec <- PERTURBATION_DTO_REGISTRY[[pert_db]]

    if (is.null(b_spec)) {
        cli_abort("No BINDING_DTO_REGISTRY entry for {.val {binding_db}}.")
    }
    if (is.null(p_spec)) {
        cli_abort("No PERTURBATION_DTO_REGISTRY entry for {.val {pert_db}}.")
    }

    t0 <- Sys.time()

    # Two roots per pair: the ranked lists, which get packed into an image, and
    # the files the job scripts read directly off the filesystem. The scratch
    # path written into lookup.txt points at the lists root, so a mounted image
    # and an unpacked tree are interchangeable.
    lists_pair_dir <- file.path(outdir, .DTO_LISTS_SUBDIR, pert_db, binding_db)
    index_pair_dir <- file.path(outdir, .DTO_INDEX_SUBDIR, pert_db, binding_db)
    scratch_pair_dir <- file.path(scratch_path, .DTO_LISTS_SUBDIR, pert_db, binding_db)
    dir.create(lists_pair_dir, recursive = TRUE, showWarnings = FALSE)
    dir.create(index_pair_dir, recursive = TRUE, showWarnings = FALSE)

    dto_execute(vdb, dto_pert_table_sql(pert_db, p_spec))
    dto_execute(vdb, dto_bind_table_sql(binding_db, b_spec))

    on.exit(dto_execute(vdb, dto_drop_pair_tables_sql()), add = TRUE)

    binding_ids <- dto_write_ranked_lists(
        vdb, dto_binding_list_sql(b_spec, max_rows, truncate_by),
        file.path(lists_pair_dir, "binding"), use_duckdb_copy
    )
    pr_effect_ids <- dto_write_ranked_lists(
        vdb, dto_pert_list_sql(p_spec, "effect", max_rows, truncate_by),
        file.path(lists_pair_dir, "pr", "effect"), use_duckdb_copy
    )
    # Datasets with no p-value column get no p-value-ranked list at all: their
    # `pvalue` is a constant placeholder, so the list would be one rank-1 block.
    has_pvalue <- pert_has_pvalue(p_spec)
    pvalue_dir <- file.path(lists_pair_dir, "pr", "pvalue")
    pr_pvalue_ids <- if (has_pvalue) {
        dto_write_ranked_lists(
            vdb, dto_pert_list_sql(p_spec, "pvalue", max_rows, truncate_by),
            pvalue_dir, use_duckdb_copy
        )
    } else {
        # Clear one left behind by an earlier run under different settings.
        if (dir.exists(pvalue_dir)) unlink(pvalue_dir, recursive = TRUE)
        character()
    }

    background <- vdb$query(dto_background_sql())
    write_csv(
        tibble(target_locus_tag = background$target_locus_tag),
        file.path(index_pair_dir, "background.csv"),
        col_names = FALSE
    )

    # Counted off the same SELECT that wrote pr/effect, so the floor is applied
    # to exactly the lists the job would have been handed.
    pr_sizes <- as_tibble(vdb$query(dto_list_sizes_sql(
        dto_pert_list_sql(p_spec, "effect", max_rows, truncate_by)
    )))

    lookups <- dto_build_lookup(
        binding_map = as_tibble(vdb$query(dto_sample_map_sql("binding"))),
        pert_map = as_tibble(vdb$query(dto_sample_map_sql("perturbation"))),
        scratch_pair_dir = scratch_pair_dir,
        include_pvalue = has_pvalue,
        pr_sizes = pr_sizes,
        min_pr_targets = min_pr_targets
    )

    write_tsv(lookups$lookup, file.path(index_pair_dir, "lookup.txt"), col_names = FALSE)
    if (nrow(lookups$incomplete)) {
        write_csv(lookups$incomplete, file.path(index_pair_dir, "incomplete.csv"))
    }

    elapsed <- as.numeric(difftime(Sys.time(), t0, units = "secs"))
    cap <- if (is.null(max_rows)) {
        "uncapped"
    } else {
        glue::glue("<={max_rows} {if (truncate_by == 'rank') 'ranks' else 'rows'}")
    }
    pv <- if (has_pvalue) "" else ", no pr/pvalue (no p-value column)"
    n_below_min <- sum(lookups$incomplete$missing_type == "pr_below_min")
    floor_msg <- if (n_below_min) {
        glue::glue(", {n_below_min} dropped (<{min_pr_targets} targets)")
    } else {
        ""
    }
    cli_alert_success(
        "{pert_db} x {binding_db}: {length(binding_ids)} binding, \\
         {length(pr_effect_ids)} pr, {nrow(lookups$lookup)} pairs, \\
         {nrow(background)} background, {cap}{pv}{floor_msg} ({round(elapsed, 1)}s)"
    )

    invisible(tibble(
        pert_db = pert_db,
        binding_db = binding_db,
        n_binding_samples = length(binding_ids),
        n_pr_samples = length(pr_effect_ids),
        n_pr_pvalue_samples = length(pr_pvalue_ids),
        n_lookup_rows = nrow(lookups$lookup),
        n_incomplete = nrow(lookups$incomplete),
        n_pr_below_min = n_below_min,
        n_background = nrow(background),
        min_pr_targets = min_pr_targets,
        max_rows = max_rows %||% NA_integer_,
        truncate_by = if (is.null(max_rows)) NA_character_ else truncate_by,
        elapsed_sec = elapsed
    ))
}