Chase Mateusiak
revising dto scripts to add harbison
77a595c
Raw
History Blame Contribute Delete
17 kB
# SQL generators for DTO input preparation.
#
# Every function here returns a SQL string and has no side effects, so a query
# can be printed and inspected before it is run. Only io.R and the driver
# execute anything.
#
# The work for one (binding, perturbation) pair is staged through two temp
# tables so the expensive scans and the perturbation dedup happen once per pair
# rather than once per output file. Both temp tables hold *unfiltered* rows plus
# a `sig_ok` flag; the significance filter is applied at ranking time. That
# ordering matters: the pre-refactor script computed the binding/perturbation
# cross-restriction against the unfiltered frames and only then applied the
# p-value cutoffs.
library(glue)
.DTO_BIND_TBL <- "_dto_bind"
.DTO_PERT_TBL <- "_dto_pert"
# SQL literal for a double, or NULL-safe passthrough.
.sql_num <- function(x) format(x, scientific = FALSE, trim = TRUE)
# Single-quoted SQL string literal.
.sql_str <- function(x) paste0("'", gsub("'", "''", x, fixed = TRUE), "'")
.dir_sql <- function(asc) if (isTRUE(asc)) "ASC NULLS LAST" else "DESC NULLS LAST"
# The expression part of an ORDER BY term, so a term already named in a spec's
# dedup_by is not appended to it a second time.
.order_expr <- function(x) {
trimws(sub("[[:space:]]+(ASC|DESC)([[:space:]]+NULLS[[:space:]]+(FIRST|LAST))?$", "",
trimws(x),
ignore.case = TRUE
))
}
#' Standardised perturbation expressions
#'
#' @param spec A `pert_spec()`.
#' @return List with `effect` and `pvalue` SQL expressions.
.pert_exprs <- function(spec) {
effect <- if (is.null(spec$effect_na_fill)) {
spec$effect_col
} else {
glue("COALESCE({spec$effect_col}, {.sql_num(spec$effect_na_fill)})")
}
# No p-value column means every row clears the significance gate, which is
# what the original `mutate(pvalue = 0)` achieved.
pvalue <- if (is.null(spec$pvalue_col)) {
"0.0"
} else if (is.null(spec$pvalue_na_fill)) {
spec$pvalue_col
} else {
glue("COALESCE({spec$pvalue_col}, {.sql_num(spec$pvalue_na_fill)})")
}
list(effect = as.character(effect), pvalue = as.character(pvalue))
}
#' SQL building the perturbation temp table for one dataset
#'
#' Applies the target universe, the self-target removal, the optional WT
#' exclusion and NA fills, and the max-|effect| dedup that collapses multiple
#' probes mapping to the same locus.
#'
#' @param pert_db db_name of the perturbation dataset.
#' @param spec A `pert_spec()`.
#' @return A `CREATE OR REPLACE TEMP TABLE` statement.
dto_pert_table_sql <- function(pert_db, spec) {
e <- .pert_exprs(spec)
wt_clause <- if (isTRUE(spec$exclude_wt)) {
# str_detect(regulator_locus_tag, "WT-", negate = TRUE) is a substring
# test, not a prefix test.
"AND regulator_locus_tag NOT LIKE '%WT-%'"
} else {
""
}
# The tiebreaks after abs(effect) are load-bearing, not cosmetic. Multiple
# probes for one locus routinely report the *same* effect with different
# p-values -- 18,893 such groups in kemmeren alone -- and abs(effect) alone
# leaves the winner up to whatever order the scan produced. Since the
# surviving row then faces the `pvalue <= 0.1` gate, an arbitrary winner
# means the target itself appears or disappears between runs of the same
# command. Preferring the more significant probe is both deterministic and
# the right reading of "keep the strongest evidence for this locus"; signed
# effect is the last discriminator, after which the rows are identical in
# every column carried forward and the choice cannot matter.
dedup_col <- if (isTRUE(spec$dedup)) {
glue(
" , row_number() OVER (
PARTITION BY sample_id, target_locus_tag
ORDER BY abs({e$effect}) DESC NULLS LAST,
{e$pvalue} ASC NULLS LAST,
{e$effect} DESC NULLS LAST
) AS _rn"
)
} else {
""
}
dedup_where <- if (isTRUE(spec$dedup)) "WHERE _rn = 1" else ""
sig_ok <- if (is.null(spec$sig_filter)) "TRUE" else spec$sig_filter
glue("
CREATE OR REPLACE TEMP TABLE {.DTO_PERT_TBL} AS
SELECT
CAST(sample_id AS VARCHAR) AS sample_id,
regulator_locus_tag,
target_locus_tag,
effect,
pvalue,
({sig_ok}) AS sig_ok
FROM (
SELECT
sample_id,
regulator_locus_tag,
target_locus_tag,
{e$effect} AS effect,
{e$pvalue} AS pvalue
{dedup_col}
FROM {pert_db}
WHERE target_locus_tag IN (SELECT locus_tag FROM dto_universe)
AND regulator_locus_tag IS NOT NULL
AND regulator_locus_tag <> target_locus_tag
{wt_clause}
) _std
{dedup_where}
")
}
#' SQL building the binding temp table for one dataset
#'
#' Most binding datasets already report one row per (sample, target). Where a
#' dataset does not -- harbison_2004 carries two rows for 7,744 sample/target
#' pairs -- `spec$dedup_by` names the order that decides which row survives, and
#' the rest are dropped here, before anything is ranked. Deduplicating at this
#' point rather than at ranking time matters: `_dto_bind` also donates the
#' regulator/target scope to the perturbation side, and a target must count once.
#'
#' @param binding_db db_name of the binding dataset.
#' @param spec A `binding_spec()`.
#' @return A `CREATE OR REPLACE TEMP TABLE` statement.
dto_bind_table_sql <- function(binding_db, spec) {
blacklist_clause <- if (length(spec$target_blacklist)) {
vals <- paste(vapply(spec$target_blacklist, .sql_str, character(1)), collapse = ", ")
glue("AND target_locus_tag NOT IN ({vals})")
} else {
""
}
# Falling back to target_locus_tag keeps output byte-identical across runs
# when a dataset has no natural secondary sort.
tiebreak_expr <- spec$tiebreak_col %||% "target_locus_tag"
sig_ok <- if (is.null(spec$sig_filter)) "TRUE" else spec$sig_filter
# The spec's own rank and tiebreak orders are appended to whatever dedup_by
# asks for. Once those are exhausted the surviving candidates are identical
# in every column this table carries forward, so "keep the first" is a real
# answer rather than whatever the scan happened to emit first.
dedup_col <- ""
dedup_where <- ""
if (length(spec$dedup_by)) {
appended <- c(
glue("{spec$rank_col} {.dir_sql(spec$rank_asc)}"),
glue("{tiebreak_expr} {.dir_sql(spec$tiebreak_asc)}")
)
appended <- appended[!.order_expr(appended) %in% .order_expr(spec$dedup_by)]
order_by <- paste(
c(spec$dedup_by, appended),
collapse = ",\n "
)
dedup_col <- glue("
, row_number() OVER (
PARTITION BY sample_id, target_locus_tag
ORDER BY {order_by}
) AS _rn")
dedup_where <- "WHERE _rn = 1"
}
# Self-targets are deliberately NOT removed here. The pre-refactor script
# donated the binding side's regulator/target scope to the perturbation side
# from the *raw* binding frame, and only dropped self-targets when building
# the ranked lists. Removing them at this point would shrink the scope the
# perturbation side is filtered against.
glue("
CREATE OR REPLACE TEMP TABLE {.DTO_BIND_TBL} AS
SELECT
sample_id,
regulator_locus_tag,
target_locus_tag,
rank_value_raw,
tiebreak_value,
sig_ok
FROM (
SELECT
CAST(sample_id AS VARCHAR) AS sample_id,
regulator_locus_tag,
target_locus_tag,
{spec$rank_col} AS rank_value_raw,
{tiebreak_expr} AS tiebreak_value,
({sig_ok}) AS sig_ok
{dedup_col}
FROM {binding_db}
WHERE target_locus_tag IN (SELECT locus_tag FROM dto_universe)
AND regulator_locus_tag IS NOT NULL
{blacklist_clause}
) _std
{dedup_where}
")
}
# The cross-restriction: binding rows are kept only for regulators and targets
# the paired perturbation dataset also measured, and vice versa. Computed
# against the unfiltered temp tables.
.bind_scope_where <- glue(
"regulator_locus_tag IN (SELECT DISTINCT regulator_locus_tag FROM {.DTO_PERT_TBL})
AND target_locus_tag IN (SELECT DISTINCT target_locus_tag FROM {.DTO_PERT_TBL})"
)
.pert_scope_where <- glue(
"regulator_locus_tag IN (SELECT DISTINCT regulator_locus_tag FROM {.DTO_BIND_TBL})
AND target_locus_tag IN (SELECT DISTINCT target_locus_tag FROM {.DTO_BIND_TBL})"
)
#' List truncation applied after ranking
#'
#' DTO's cost grows with the square of the number of distinct ranks in a list,
#' so capping list length is the cheapest lever on runtime. Either cap is
#' applied in the *outer* query -- after the significance filter, the pair scope
#' and the ranking -- so the rank values that survive are the true ranks the
#' untruncated list would have had, not a renumbering of the top slice.
#'
#' Two policies:
#'
#' * `"rank"` (default) keeps whole rank blocks: `rank_value <= max_rows`. A
#' list is cut to at most `max_rows` *distinct ranks*, and every row tied at
#' the last surviving rank is kept, so the cut never depends on the arbitrary
#' order of equals. Because `RANK()` assigns min-ranks, a list can come out
#' longer than `max_rows` rows -- but the quantity DTO's runtime keys on is
#' bounded at `max_rows` either way. A list with no real ordering would defeat
#' the policy entirely -- every row tied at rank 1 survives whole -- so
#' `dto_pert_list_sql()` never ranks on a constant column.
#' * `"row"` is a hard row cap: `sort_key <= max_rows`. Never longer than
#' `max_rows` rows, but the boundary can fall inside a block of tied ranks and
#' keep an arbitrary subset of equals. `dto_tie_split_report()` in audit.R
#' measures how often that happens for a given cap.
#'
#' The background is deliberately not capped under either policy: it is the
#' population the test draws against and must stay the size it would be if
#' nothing were truncated.
#'
#' @param max_rows Cap per sample, or `NULL` for no cap.
#' @param truncate_by `"rank"` for whole rank blocks, `"row"` for a hard row cap.
#' @return A `WHERE` clause, or `""`.
.limit_where <- function(max_rows, truncate_by = c("rank", "row")) {
truncate_by <- match.arg(truncate_by)
if (is.null(max_rows) || !is.finite(max_rows)) {
return("")
}
if (max_rows < 1) cli::cli_abort("{.arg max_rows} must be at least 1.")
col <- if (truncate_by == "rank") "rank_value" else "sort_key"
glue("WHERE {col} <= {as.integer(max_rows)}")
}
#' SELECT producing the binding ranked lists
#'
#' Ranks *after* filtering, matching the original `filter() |> mutate(rank())`
#' order.
#'
#' Emits `sample_id, target_locus_tag, rank_value, sort_key`. `sort_key` is a
#' per-sample sequence number carrying the full intended row order, including
#' the tiebreak. Writers order by it rather than relying on the order rows
#' happen to come out of a table, so a file's contents never depend on DuckDB's
#' scan-order behaviour.
#'
#' The tiebreak reproduces a subtlety of the pre-refactor script: it sorted by
#' descending enrichment before sorting by rank, and because `dplyr::arrange()`
#' is stable, enrichment ended up breaking ties. Making that explicit also makes
#' it reproducible.
#'
#' @param spec A `binding_spec()`.
#' @param max_rows Cap per sample; see `.limit_where()`.
#' @param truncate_by Truncation policy; see `.limit_where()`.
#' @return A SELECT statement.
dto_binding_list_sql <- function(spec, max_rows = NULL, truncate_by = c("rank", "row")) {
rank_dir <- .dir_sql(spec$rank_asc)
tiebreak_dir <- .dir_sql(spec$tiebreak_asc)
limit_where <- .limit_where(max_rows, truncate_by)
glue("
SELECT sample_id, target_locus_tag, rank_value, sort_key
FROM (
SELECT
sample_id,
target_locus_tag,
RANK() OVER (
PARTITION BY sample_id ORDER BY rank_value_raw {rank_dir}
) AS rank_value,
ROW_NUMBER() OVER (
PARTITION BY sample_id
ORDER BY rank_value_raw {rank_dir},
tiebreak_value {tiebreak_dir},
target_locus_tag
) AS sort_key
FROM {.DTO_BIND_TBL}
WHERE sig_ok
AND regulator_locus_tag <> target_locus_tag
AND {.bind_scope_where}
) _ranked
{limit_where}
ORDER BY sample_id, sort_key
")
}
#' SELECT producing a perturbation ranked list
#'
#' One query shape serves both output directories. `pr/effect/` ranks by
#' descending |effect|, `pr/pvalue/` by ascending p-value; each uses the other
#' quantity as its tiebreak so the row order is deterministic.
#'
#' Asking for `"pvalue"` on a dataset with no p-value column is an error, not a
#' fallback. Its `pvalue` is a constant filled in so the significance gate
#' passes; ranking on it would put every target in a single rank-1 block, which
#' carries no ordering at all. Such datasets get `pr/effect/` and nothing else --
#' see `pert_has_pvalue()`.
#'
#' @param spec A `pert_spec()`.
#' @param ranking Either `"effect"` or `"pvalue"`.
#' @param max_rows Cap per sample; see `.limit_where()`.
#' @param truncate_by Truncation policy; see `.limit_where()`.
#' @return A SELECT statement.
dto_pert_list_sql <- function(spec, ranking = c("effect", "pvalue"), max_rows = NULL,
truncate_by = c("rank", "row")) {
ranking <- match.arg(ranking)
limit_where <- .limit_where(max_rows, truncate_by)
if (ranking == "pvalue" && !pert_has_pvalue(spec)) {
cli::cli_abort(c(
"This dataset reports no p-value, so it has no p-value-ranked list.",
i = "Its {.field pvalue} column is a constant placeholder for the significance gate.",
i = "Rank by {.val effect}, or test with {.fun pert_has_pvalue} first."
))
}
rank_expr <- switch(ranking,
effect = "abs(effect) DESC NULLS LAST",
pvalue = "pvalue ASC NULLS LAST"
)
tiebreak <- switch(ranking,
effect = "pvalue ASC NULLS LAST",
pvalue = "abs(effect) DESC NULLS LAST"
)
glue("
SELECT sample_id, target_locus_tag, rank_value, sort_key
FROM (
SELECT
sample_id,
target_locus_tag,
RANK() OVER (PARTITION BY sample_id ORDER BY {rank_expr}) AS rank_value,
ROW_NUMBER() OVER (
PARTITION BY sample_id
ORDER BY {rank_expr}, {tiebreak}, target_locus_tag
) AS sort_key
FROM {.DTO_PERT_TBL}
WHERE sig_ok
AND {.pert_scope_where}
) _ranked
{limit_where}
ORDER BY sample_id, sort_key
")
}
#' SELECT counting the rows of each written ranked list
#'
#' Wraps a list SELECT to give one row per sample. Used to drop lookup entries
#' whose perturbation list is too short to produce a meaningful DTO result --
#' counting here rather than stat-ing the written files keeps the decision on the
#' same query that produced them.
#'
#' @param list_sql A SELECT from `dto_binding_list_sql()` or `dto_pert_list_sql()`.
#' @return A SELECT emitting `sample_id`, `n_targets`.
dto_list_sizes_sql <- function(list_sql) {
glue("
SELECT sample_id, COUNT(*) AS n_targets
FROM ({list_sql}) _l
GROUP BY sample_id
")
}
#' SELECT producing the shared background
#'
#' The background is every perturbation target inside the pair's scope, with no
#' significance filter applied -- the population the DTO test draws against.
#' It is unaffected by the ranked-list cap, by design: truncating the lists is a
#' runtime optimisation and must not change the population they are scored
#' against.
#'
#' @return A SELECT statement.
dto_background_sql <- function() {
glue("
SELECT DISTINCT target_locus_tag
FROM {.DTO_PERT_TBL}
WHERE {.pert_scope_where}
ORDER BY target_locus_tag
")
}
#' SELECT mapping sample_id to regulator for one side of a pair
#'
#' Restricted to the same rows that produced ranked-list files, so the lookup
#' never references a file that was not written.
#'
#' @param side Either `"binding"` or `"perturbation"`.
#' @return A SELECT statement.
dto_sample_map_sql <- function(side = c("binding", "perturbation")) {
side <- match.arg(side)
tbl <- if (side == "binding") .DTO_BIND_TBL else .DTO_PERT_TBL
scope <- if (side == "binding") .bind_scope_where else .pert_scope_where
# _dto_pert drops self-targets when it is built; _dto_bind keeps them so it
# can donate an unreduced scope, so the binding side filters them here to
# match the rows that produced ranked-list files.
self_clause <- if (side == "binding") "AND regulator_locus_tag <> target_locus_tag" else ""
glue("
SELECT DISTINCT sample_id, regulator_locus_tag
FROM {tbl}
WHERE sig_ok
{self_clause}
AND {scope}
ORDER BY sample_id
")
}
#' SQL dropping the per-pair temp tables
#'
#' @return A statement dropping both temp tables.
dto_drop_pair_tables_sql <- function() {
glue("DROP TABLE IF EXISTS {.DTO_BIND_TBL}; DROP TABLE IF EXISTS {.DTO_PERT_TBL};")
}