File size: 13,002 Bytes
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77a595c
 
 
 
 
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77a595c
163eea8
 
 
 
 
 
 
 
 
 
77a595c
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77a595c
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77a595c
 
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77a595c
 
 
 
 
 
163eea8
 
 
 
 
 
77a595c
 
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77a595c
 
 
 
 
163eea8
 
 
 
 
 
 
 
 
77a595c
 
 
 
 
 
 
 
 
 
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
# Auditing the registry against the data.
#
# Two levels, because the questions are different:
#
#   dto_registry_table()  -- what the registry *says*. No database, instant.
#                            Answers "which column, which direction, what
#                            cutoff, any blacklist" for every dataset at once.
#   dto_registry_audit()  -- whether the data *agrees*. One scan per dataset.
#                            Catches a column that does not exist, a cutoff that
#                            keeps everything or nothing, and -- the failure that
#                            is otherwise invisible -- a rank direction that is
#                            backwards.
#
# The direction check works by correlating the rank column against the tiebreak
# column, which is always a corroborating measure of the same binding event
# (enrichment beside a p-value, peak count beside a peak score). If the spec
# calls low p-values best and high enrichment best, the two must be negatively
# correlated. A sign that comes back the other way means one of the two
# directions is wrong.

library(cli)
library(dplyr)
library(glue)
library(tibble)

.DTO_NUMERIC_TYPES <- c(
    "TINYINT", "SMALLINT", "INTEGER", "BIGINT", "HUGEINT",
    "UTINYINT", "USMALLINT", "UINTEGER", "UBIGINT",
    "FLOAT", "DOUBLE", "REAL", "DECIMAL"
)

.is_numeric_type <- function(x) {
    any(vapply(.DTO_NUMERIC_TYPES, function(t) startsWith(toupper(x), t), logical(1)))
}

#' The registry as a table
#'
#' Every knob for every registered dataset, side by side. This is the fast way
#' to answer "what is dataset X ranked on and which way round" -- it reads the
#' registry only, so it needs no VirtualDB and no data.
#'
#' @param which `"binding"`, `"perturbation"` or `"both"`.
#' @return A tibble, one row per registered dataset.
dto_registry_table <- function(which = c("binding", "perturbation", "both")) {
    which <- match.arg(which)

    binding <- NULL
    if (which %in% c("binding", "both")) {
        binding <- bind_rows(lapply(names(BINDING_DTO_REGISTRY), function(db) {
            s <- BINDING_DTO_REGISTRY[[db]]
            tibble(
                side = "binding",
                db_name = db,
                rank_col = s$rank_col,
                direction = if (s$rank_asc) "asc (low = best)" else "desc (high = best)",
                tiebreak = s$tiebreak_col %||% "(target_locus_tag)",
                tiebreak_dir = if (s$tiebreak_asc) "asc" else "desc",
                sig_filter = s$sig_filter %||% "(none)",
                dedup_by = if (length(s$dedup_by)) {
                    paste(s$dedup_by, collapse = ", ")
                } else {
                    "(one row per sample/target)"
                },
                blacklist = if (length(s$target_blacklist)) {
                    paste(s$target_blacklist, collapse = " ")
                } else {
                    "(none)"
                }
            )
        }))
    }

    perturbation <- NULL
    if (which %in% c("perturbation", "both")) {
        # Two rows per dataset: one per output directory, so the table states
        # what each written file is ranked on -- and which datasets get no
        # pr/pvalue directory at all.
        perturbation <- bind_rows(lapply(names(PERTURBATION_DTO_REGISTRY), function(db) {
            s <- PERTURBATION_DTO_REGISTRY[[db]]
            has_p <- !is.null(s$pvalue_col)
            opts <- paste0(
                if (s$dedup) "dedup " else "",
                if (s$exclude_wt) "exclude_wt " else "",
                if (!is.null(s$effect_na_fill)) glue("effect_na={s$effect_na_fill} ") else "",
                if (!is.null(s$pvalue_na_fill)) glue("pvalue_na={s$pvalue_na_fill}") else ""
            )
            bind_rows(
                tibble(
                    side = "pert: pr/effect",
                    db_name = db,
                    rank_col = s$effect_col,
                    direction = "desc (high |effect| = best)",
                    tiebreak = s$pvalue_col %||% "(constant 0.0)",
                    tiebreak_dir = "asc",
                    sig_filter = s$sig_filter %||% "(none)",
                    dedup_by = "",
                    blacklist = opts
                ),
                tibble(
                    side = "pert: pr/pvalue",
                    db_name = db,
                    rank_col = if (has_p) s$pvalue_col else "(not written: no p-value column)",
                    direction = if (has_p) "asc (low = best)" else "",
                    tiebreak = if (has_p) s$effect_col else "",
                    tiebreak_dir = if (has_p) "desc" else "",
                    sig_filter = if (has_p) s$sig_filter %||% "(none)" else "",
                    dedup_by = "",
                    blacklist = if (has_p) opts else ""
                )
            )
        }))
    }

    bind_rows(binding, perturbation)
}

# One dataset's worth of data-backed checks. Single scan, aggregates only.
.audit_one <- function(vdb, db, spec, blacklist_probe) {
    schema <- vdb$query(glue("DESCRIBE {db}"))
    cols <- schema$column_name
    types <- setNames(schema$column_type, cols)

    base <- tibble(
        db_name = db,
        rank_col = spec$rank_col,
        direction = if (spec$rank_asc) "asc" else "desc"
    )

    if (!spec$rank_col %in% cols) {
        return(bind_cols(base, tibble(
            status = "rank_col MISSING",
            n_rows = NA_real_, n_samples = NA_real_,
            rank_min = NA_real_, rank_med = NA_real_, rank_max = NA_real_,
            frac_sig = NA_real_, med_sig_per_sample = NA_real_,
            corr_rank_tiebreak = NA_real_, direction_ok = NA,
            n_probe_rows = NA_real_, n_dup_rows = NA_real_, dedup_declared = NA
        )))
    }

    tb <- spec$tiebreak_col
    use_corr <- !is.null(tb) && tb %in% cols &&
        .is_numeric_type(types[[tb]]) && .is_numeric_type(types[[spec$rank_col]])

    tb_select <- if (use_corr) glue(", {tb}") else ""
    corr_expr <- if (use_corr) glue("corr({spec$rank_col}, {tb})") else "CAST(NULL AS DOUBLE)"
    sig <- spec$sig_filter %||% "TRUE"
    probe <- paste(vapply(blacklist_probe, .sql_str, character(1)), collapse = ", ")

    res <- vdb$query(glue("
WITH src AS (
    SELECT CAST(sample_id AS VARCHAR) AS sample_id,
           target_locus_tag,
           {spec$rank_col}{tb_select}
    FROM {db}
    WHERE target_locus_tag IN (SELECT locus_tag FROM dto_universe)
      AND regulator_locus_tag IS NOT NULL
),
agg AS (
    SELECT COUNT(*) AS n_rows,
           MIN({spec$rank_col}) AS rank_min,
           MEDIAN({spec$rank_col}) AS rank_med,
           MAX({spec$rank_col}) AS rank_max,
           COUNT(*) FILTER (WHERE {sig}) / NULLIF(COUNT(*), 0)::DOUBLE AS frac_sig,
           COUNT(*) FILTER (WHERE target_locus_tag IN ({probe})) AS n_probe_rows,
           COUNT(*) - COUNT(DISTINCT sample_id || '|' || target_locus_tag)
               AS n_dup_rows,
           {corr_expr} AS corr_rank_tiebreak
    FROM src
),
per_sample AS (
    SELECT sample_id, COUNT(*) FILTER (WHERE {sig}) AS n_sig
    FROM src GROUP BY sample_id
),
samp AS (
    SELECT COUNT(*) AS n_samples, MEDIAN(n_sig) AS med_sig_per_sample FROM per_sample
)
SELECT * FROM agg, samp
"))

    # Better-is-low for the rank column iff rank_asc; same for the tiebreak.
    # Agreeing directions must correlate positively, opposing ones negatively.
    expect_positive <- identical(spec$rank_asc, spec$tiebreak_asc)
    corr <- res$corr_rank_tiebreak[[1]]
    direction_ok <- if (is.na(corr)) NA else (corr > 0) == expect_positive

    bind_cols(base, tibble(status = "ok"), as_tibble(res[, c(
        "n_rows", "n_samples", "rank_min", "rank_med", "rank_max",
        "frac_sig", "med_sig_per_sample", "corr_rank_tiebreak", "n_probe_rows",
        "n_dup_rows"
    )]), tibble(
        direction_ok = direction_ok,
        dedup_declared = length(spec$dedup_by) > 0
    ))
}

#' Check every registered binding dataset against its data
#'
#' `n_probe_rows` is not a blacklist that is applied -- it counts rows matching
#' `blacklist_probe` so the cost of switching one on is visible before you do.
#' `n_dup_rows` counts rows a `dedup_by` would collapse: how far the dataset is
#' from one row per (`sample_id`, `target_locus_tag`).
#' No dataset currently sets `target_blacklist`; see the comment on
#' `CC_TARGET_BLACKLIST` in registry.R for why.
#'
#' @param vdb A VirtualDB handle with `dto_universe` registered.
#' @param dbs Binding db_names to audit. Defaults to the whole registry.
#' @param blacklist_probe Locus tags to count occurrences of.
#' @return A tibble, one row per dataset.
dto_registry_audit <- function(vdb,
                               dbs = names(BINDING_DTO_REGISTRY),
                               blacklist_probe = CC_TARGET_BLACKLIST) {
    out <- bind_rows(lapply(dbs, function(db) {
        spec <- BINDING_DTO_REGISTRY[[db]]
        if (is.null(spec)) cli_abort("No BINDING_DTO_REGISTRY entry for {.val {db}}.")
        cli_alert_info("auditing {db} ...")
        .audit_one(vdb, db, spec, blacklist_probe)
    }))

    bad <- out$db_name[!is.na(out$direction_ok) & !out$direction_ok]
    missing <- out$db_name[out$status != "ok"]
    # Duplicate (sample, target) rows with no dedup_by are the silent failure:
    # the target appears twice in its ranked list and twice in the scope the
    # perturbation side is filtered against.
    undeduped <- out$db_name[!is.na(out$n_dup_rows) & out$n_dup_rows > 0 &
        !is.na(out$dedup_declared) & !out$dedup_declared]

    if (length(missing)) {
        cli_alert_danger("rank_col does not exist in: {.val {missing}}")
    }
    if (length(bad)) {
        cli_alert_danger(
            "rank direction disagrees with the tiebreak column in: {.val {bad}}"
        )
    }
    if (length(undeduped)) {
        cli_alert_danger(c(
            "Repeated (sample_id, target_locus_tag) rows and no {.arg dedup_by}: ",
            "{.val {undeduped}}"
        ))
    }
    if (!length(bad) && !length(missing) && !length(undeduped)) {
        cli_alert_success(
            "All {nrow(out)} binding datasets: column exists, direction consistent, one row per sample/target."
        )
    }

    out
}

#' What truncation costs the staged pair
#'
#' Compares the two policies on the *uncapped* lists for the staged pair:
#'
#' * `"rank"` -- `rank_value <= max_rows`. Keeps whole rank blocks, so no tie is
#'   ever split, but a list can come out longer than `max_rows` rows.
#' * `"row"` -- `sort_key <= max_rows`. Never longer than `max_rows` rows, but
#'   the boundary can land inside a block of tied ranks and keep an arbitrary
#'   subset of equals; `n_samples_tie_split` and `max_tied_rows_lost` count that.
#'
#' Both bound the thing the cap is actually for: DTO scales with the square of
#' the number of *distinct* ranks, so `med_ranks_full / med_ranks_kept` squared
#' is the rough speedup, and it is the same for either policy.
#'
#' Requires a pair staged with `dto_stage_pair()`.
#'
#' @param vdb A VirtualDB handle.
#' @param max_rows The cap to evaluate.
#' @param ranking Perturbation ranking to evaluate.
#' @return A tibble, one row per side.
dto_tie_split_report <- function(vdb, max_rows = 300, ranking = c("effect", "pvalue")) {
    if (is.null(.dto_stage$binding_db)) {
        cli_abort("Nothing staged. Call {.code dto_stage_pair(vdb, binding_db, pert_db)} first.")
    }
    ranking <- match.arg(ranking)
    n <- as.integer(max_rows)

    one <- function(side, list_sql) {
        res <- vdb$query(glue("
WITH l AS ({list_sql}),
marked AS (
    SELECT sample_id, rank_value, sort_key,
           MAX(CASE WHEN sort_key = {n} THEN rank_value END)
               OVER (PARTITION BY sample_id) AS boundary
    FROM l
),
per_sample AS (
    SELECT sample_id,
           COUNT(*) AS rows_full,
           COUNT(DISTINCT rank_value) AS ranks_full,
           COUNT(*) FILTER (WHERE rank_value <= {n}) AS rows_rank,
           COUNT(DISTINCT rank_value) FILTER (WHERE rank_value <= {n}) AS ranks_rank,
           COUNT(*) FILTER (WHERE sort_key <= {n}) AS rows_row,
           COUNT(*) FILTER (WHERE sort_key > {n} AND rank_value = boundary) AS split_lost
    FROM marked GROUP BY sample_id
)
SELECT COUNT(*) AS n_samples,
       MEDIAN(rows_full) AS med_rows_full,
       MEDIAN(ranks_full) AS med_ranks_full,
       MEDIAN(rows_rank) AS med_rows_kept_rank,
       MAX(rows_rank) AS max_rows_kept_rank,
       MEDIAN(ranks_rank) AS med_ranks_kept,
       MEDIAN(rows_row) AS med_rows_kept_row,
       COUNT(*) FILTER (WHERE split_lost > 0) AS n_samples_tie_split,
       MAX(split_lost) AS max_tied_rows_lost
FROM per_sample
"))
        bind_cols(tibble(side = side), .as_tbl(res))
    }

    out <- bind_rows(
        one("binding", dto_binding_list_sql(.dto_stage$b_spec)),
        one(paste0("perturbation (", ranking, ")"), dto_pert_list_sql(.dto_stage$p_spec, ranking))
    )
    out$approx_speedup <- round((out$med_ranks_full / out$med_ranks_kept)^2, 1)
    out
}