File size: 12,248 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
# Interactive spot-checking of one (binding, perturbation) pair.
#
# dto_prepare_pair() drops its temp tables when it returns, which is right for a
# batch run and useless at the console. These helpers stage the same two temp
# tables and leave them up, then query them with the *same* SQL generators the
# writers use -- so what you see here is what lands in the CSV, not a
# reimplementation that can drift from it.
#
# Typical session:
#
#   source("R/yeast_comparative_analysis/dto_prep/spot_check.R")   # after the others
#   vdb <- dto_vdb(); dto_register_universe(vdb)
#   dto_stage_pair(vdb, "rossi_mindel", "degron")
#
#   dto_regulator(vdb, "YLR451W")        # which samples does this TF have?
#   dto_ranked(vdb, "binding", "180")    # the file that would be written
#   dto_binding_rows(vdb, "180", "YAL038W")   # why that target got that rank
#   dto_source_rows(vdb, "rossi_mindel", "180", "YAL038W")  # untouched source row
#   dto_overlap(vdb, "180", "119_261", n = 100)
#
#   dto_unstage(vdb)

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

# What dto_stage_pair() last set up, so the other helpers need only the ids.
.dto_stage <- new.env(parent = emptyenv())

# vdb$query() hands back a reticulate-converted pandas frame, which drags a
# RangeIndex and its attributes along. Strip them so a console `identical()`
# against a frame read off disk compares data and not provenance.
.as_tbl <- function(df) {
    df <- as.data.frame(df)
    attributes(df) <- attributes(df)[c("names", "class", "row.names")]
    rownames(df) <- NULL
    tibble::as_tibble(df)
}

#' Stage the two per-pair temp tables and leave them in place
#'
#' @param vdb A VirtualDB handle with `dto_universe` already registered.
#' @param binding_db,pert_db db_names, both of which must be in the registries.
#' @return `invisible(list(binding_db, pert_db, binding_spec, pert_spec))`.
dto_stage_pair <- function(vdb, binding_db, pert_db) {
    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}}.")

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

    .dto_stage$binding_db <- binding_db
    .dto_stage$pert_db <- pert_db
    .dto_stage$b_spec <- b_spec
    .dto_stage$p_spec <- p_spec

    nb <- vdb$query(glue("SELECT COUNT(*) n, COUNT(DISTINCT sample_id) s FROM {.DTO_BIND_TBL}"))
    np <- vdb$query(glue("SELECT COUNT(*) n, COUNT(DISTINCT sample_id) s FROM {.DTO_PERT_TBL}"))
    cli_alert_success(
        "Staged {binding_db} ({nb$n} rows / {nb$s} samples) x \\
         {pert_db} ({np$n} rows / {np$s} samples). \\
         Tables {.code { .DTO_BIND_TBL }} and {.code { .DTO_PERT_TBL }} are live."
    )

    invisible(as.list(.dto_stage))
}

#' Drop the staged temp tables
#'
#' @param vdb A VirtualDB handle.
#' @return `invisible(NULL)`.
dto_unstage <- function(vdb) {
    dto_execute(vdb, dto_drop_pair_tables_sql())
    rm(list = ls(.dto_stage), envir = .dto_stage)
    invisible(NULL)
}

.stage_or_abort <- function() {
    if (is.null(.dto_stage$binding_db)) {
        cli_abort("Nothing staged. Call {.code dto_stage_pair(vdb, binding_db, pert_db)} first.")
    }
}

#' Samples for one regulator on both sides of the staged pair
#'
#' Uses the same sample-map queries that build `lookup.txt`, so a regulator that
#' shows up here with samples on both sides is exactly a regulator the pipeline
#' will test, and one missing a side is a row in `incomplete.csv`.
#'
#' @param vdb A VirtualDB handle.
#' @param regulator A regulator locus tag.
#' @param max_rows The cap the run used, so `n_rows` matches the file.
#' @param truncate_by The truncation policy the run used.
#' @return A tibble of `side`, `sample_id`, `n_rows` (rows that pass the
#'   significance gate and the pair scope -- the length of the written file).
dto_regulator <- function(vdb, regulator, max_rows = NULL,
                          truncate_by = c("rank", "row")) {
    .stage_or_abort()
    truncate_by <- match.arg(truncate_by)

    one_side <- function(side) {
        map <- .as_tbl(vdb$query(dto_sample_map_sql(side)))
        map <- map[map$regulator_locus_tag == regulator, , drop = FALSE]
        if (!nrow(map)) return(tibble(side = character(), sample_id = character(), n_rows = integer()))

        list_sql <- if (side == "binding") {
            dto_binding_list_sql(.dto_stage$b_spec, max_rows, truncate_by)
        } else {
            dto_pert_list_sql(.dto_stage$p_spec, "effect", max_rows, truncate_by)
        }
        counts <- vdb$query(glue(
            "SELECT sample_id, COUNT(*) AS n_rows FROM ({list_sql}) _l GROUP BY sample_id"
        ))
        merged <- merge(
            data.frame(side = side, sample_id = map$sample_id, stringsAsFactors = FALSE),
            counts,
            by = "sample_id", all.x = TRUE
        )
        .as_tbl(merged[order(merged$sample_id), c("side", "sample_id", "n_rows")])
    }

    out <- rbind(one_side("binding"), one_side("perturbation"))
    if (!nrow(out)) {
        bdb <- .dto_stage$binding_db
        pdb <- .dto_stage$pert_db
        cli_alert_warning(
            "{.val {regulator}} has no in-scope samples in either \\
             {.val {bdb}} or {.val {pdb}}."
        )
    }
    out
}

#' The ranked list for one sample, exactly as written to disk
#'
#' Runs the writer's own SELECT and pulls out one sample. The two columns the
#' CSV holds are `target_locus_tag` and `rank_value`; `sort_key` is the row order
#' and is shown here because tie blocks are easiest to read with it visible.
#'
#' @param vdb A VirtualDB handle.
#' @param side `"binding"` or `"perturbation"`.
#' @param sample_id The sample to pull.
#' @param n Rows to return. `Inf` for all.
#' @param ranking Perturbation side only: `"effect"` or `"pvalue"`.
#' @param max_rows The cap the run used. Set it to match the run you are
#'   checking, or the console will show rows the file does not have.
#' @param truncate_by The truncation policy the run used.
#' @return A tibble of `target_locus_tag`, `rank_value`, `sort_key`.
dto_ranked <- function(vdb, side = c("binding", "perturbation"), sample_id,
                       n = 20, ranking = c("effect", "pvalue"),
                       max_rows = NULL, truncate_by = c("rank", "row")) {
    .stage_or_abort()
    side <- match.arg(side)
    ranking <- match.arg(ranking)
    truncate_by <- match.arg(truncate_by)

    list_sql <- if (side == "binding") {
        dto_binding_list_sql(.dto_stage$b_spec, max_rows, truncate_by)
    } else {
        dto_pert_list_sql(.dto_stage$p_spec, ranking, max_rows, truncate_by)
    }
    limit <- if (is.finite(n)) glue("LIMIT {as.integer(n)}") else ""

    .as_tbl(vdb$query(glue("
SELECT target_locus_tag, rank_value, sort_key
FROM ({list_sql}) _l
WHERE sample_id = {.sql_str(as.character(sample_id))}
ORDER BY sort_key
{limit}
")))
}

# Shared body of dto_binding_rows() / dto_pert_rows(): the staged row plus the
# two flags that decide whether it reaches a file at all.
.staged_rows <- function(vdb, tbl, extra_cols, scope, self_clause, sample_id, targets, n) {
    target_clause <- if (is.null(targets)) {
        ""
    } else {
        vals <- paste(vapply(targets, .sql_str, character(1)), collapse = ", ")
        glue("AND target_locus_tag IN ({vals})")
    }
    limit <- if (is.finite(n)) glue("LIMIT {as.integer(n)}") else ""

    .as_tbl(vdb$query(glue("
SELECT
    target_locus_tag,
    {extra_cols},
    sig_ok,
    ({scope}) AS in_scope,
    ({self_clause}) AS not_self
FROM {tbl}
WHERE sample_id = {.sql_str(as.character(sample_id))}
  {target_clause}
{limit}
")))
}

#' Staged binding rows for one sample, with the gate flags
#'
#' `sig_ok`, `in_scope` and `not_self` are the three conditions
#' `dto_binding_list_sql()` requires; a target present here but absent from
#' `dto_ranked()` will have a FALSE among them.
#'
#' @param vdb A VirtualDB handle.
#' @param sample_id Binding sample.
#' @param targets Target locus tags to restrict to. `NULL` for all.
#' @param n Row cap.
#' @return A tibble.
dto_binding_rows <- function(vdb, sample_id, targets = NULL, n = 50) {
    .stage_or_abort()
    # The staged columns are named generically so one query shape serves every
    # dataset; alias them back to the registry's column names so the output
    # reads like the source. A spec with no tiebreak_col falls back to
    # target_locus_tag, which is already the first column -- don't repeat it.
    b_spec <- .dto_stage$b_spec
    cols <- c("regulator_locus_tag", glue("rank_value_raw AS \"{b_spec$rank_col}\""))
    if (!is.null(b_spec$tiebreak_col)) {
        cols <- c(cols, glue("tiebreak_value AS \"{b_spec$tiebreak_col}\""))
    }

    .staged_rows(
        vdb, .DTO_BIND_TBL,
        extra_cols = paste(cols, collapse = ", "),
        scope = .bind_scope_where,
        self_clause = "regulator_locus_tag <> target_locus_tag",
        sample_id = sample_id, targets = targets, n = n
    )
}

#' Staged perturbation rows for one sample, with the gate flags
#'
#' `not_self` is always TRUE here: `_dto_pert` drops self-targets when it is
#' built, because the binding side donates its scope from unfiltered rows.
#'
#' @inheritParams dto_binding_rows
#' @return A tibble.
dto_pert_rows <- function(vdb, sample_id, targets = NULL, n = 50) {
    .stage_or_abort()
    .staged_rows(
        vdb, .DTO_PERT_TBL,
        extra_cols = "regulator_locus_tag, effect, pvalue",
        scope = .pert_scope_where,
        self_clause = "TRUE",
        sample_id = sample_id, targets = targets, n = n
    )
}

#' Untouched source rows behind a staged row
#'
#' Every column of the VirtualDB view, before the universe filter, the NA fills
#' and the dedup. This is where to look when a staged value is not what you
#' expected -- e.g. to see the several probes a dedup collapsed.
#'
#' @param vdb A VirtualDB handle.
#' @param db_name The dataset view to read.
#' @param sample_id Sample to restrict to. `NULL` for none.
#' @param targets Target locus tags to restrict to. `NULL` for all.
#' @param n Row cap.
#' @return A tibble.
dto_source_rows <- function(vdb, db_name, sample_id = NULL, targets = NULL, n = 50) {
    clauses <- "TRUE"
    if (!is.null(sample_id)) {
        clauses <- c(clauses, glue("CAST(sample_id AS VARCHAR) = {.sql_str(as.character(sample_id))}"))
    }
    if (!is.null(targets)) {
        vals <- paste(vapply(targets, .sql_str, character(1)), collapse = ", ")
        clauses <- c(clauses, glue("target_locus_tag IN ({vals})"))
    }

    .as_tbl(vdb$query(glue(
        "SELECT * FROM {db_name} WHERE {paste(clauses, collapse = ' AND ')} LIMIT {as.integer(n)}"
    )))
}

#' Top-n overlap between a binding and a perturbation sample
#'
#' The quantity DTO scores, computed here without the permutation test: how many
#' of the top `n` binding targets are in the top `n` perturbation targets, and
#' which ones. Useful for sanity-checking a surprising DTO p-value against the
#' inputs that produced it.
#'
#' @param vdb A VirtualDB handle.
#' @param binding_sample,pert_sample Sample ids from each side.
#' @param n Rank threshold, applied to `sort_key` on both sides.
#' @param ranking Perturbation ranking to use.
#' @return A list with `n_binding`, `n_pert`, `n_overlap`, `background_size` and
#'   the overlapping `targets`.
dto_overlap <- function(vdb, binding_sample, pert_sample, n = 100,
                        ranking = c("effect", "pvalue")) {
    .stage_or_abort()
    ranking <- match.arg(ranking)

    b <- dto_ranked(vdb, "binding", binding_sample, n = n)
    p <- dto_ranked(vdb, "perturbation", pert_sample, n = n, ranking = ranking)
    bg <- vdb$query(dto_background_sql())

    shared <- intersect(b$target_locus_tag, p$target_locus_tag)
    cli_alert_info(
        "top-{n}: {nrow(b)} binding, {nrow(p)} perturbation ({ranking}), \\
         {length(shared)} shared, background {nrow(bg)}."
    )

    list(
        n_binding = nrow(b),
        n_pert = nrow(p),
        n_overlap = length(shared),
        background_size = nrow(bg),
        targets = shared
    )
}