# Writing the DTO input tree. # # The tree is split in two at the top level, by how each file is consumed on the # cluster: # # /lists/// # binding/.csv target_locus_tag,rank (no header) # pr/effect/.csv # pr/pvalue/.csv only when the dataset reports p-values # # /index/// # background.csv # lookup.txt TSV: binding, pr_effect[, pr_pvalue] # incomplete.csv # /index/manifest.csv # /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 /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 `/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 #' `/.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 )) }