File size: 13,473 Bytes
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bfd1d6
 
 
 
 
163eea8
77a595c
 
 
 
 
 
 
163eea8
 
 
 
 
 
77a595c
 
163eea8
 
77a595c
163eea8
 
 
 
 
 
 
77a595c
 
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77a595c
163eea8
 
 
77a595c
163eea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bfd1d6
 
 
 
 
 
 
 
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
# Per-dataset DTO configuration.
#
# Everything that differs between datasets lives here: which column ranks the
# targets, which direction is "better", how ties break, and what counts as a
# significant call. Adding a promoter set to the collection means adding one
# entry to BINDING_DTO_REGISTRY -- no new code.
#
# Registration is opt-in: a dataset in brentlab_yeast_collection.yaml that has
# no entry here is not run. dto_check_registry() reports those so they are not
# forgotten.

library(cli)

# Calling cards targets that tfbpshiny's top-N analysis excludes
# (materialize/comparison/topn.py::CC_TARGET_BLACKLIST).
#
# NOT applied by default: the pre-refactor DTO prep did not exclude them, and
# turning it on here would make new DTO results incomparable with published
# ones. To adopt it, pass `target_blacklist = CC_TARGET_BLACKLIST` to the
# calling cards entries below.
CC_TARGET_BLACKLIST <- c("YOR201C", "YOR202W", "YOR203W", "YCL018W", "YEL021W")

#' Describe how a binding dataset is ranked for DTO
#'
#' @param rank_col Column the targets are ranked by.
#' @param rank_asc `TRUE` when lower values rank better (p-values), `FALSE` when
#'   higher values rank better (enrichment, peak scores).
#' @param tiebreak_col Column that orders rows sharing a rank. Reproduces the
#'   stable-sort behaviour of the original `arrange(desc(enrichment))` before
#'   `arrange(pvalue_rank)`. `NULL` falls back to `target_locus_tag`, which keeps
#'   output reproducible across runs.
#' @param tiebreak_asc Direction of `tiebreak_col`.
#' @param sig_filter SQL predicate applied before ranking. `NULL` means no
#'   pre-rank filter, which is the correct handling for peak datasets where a
#'   called peak is itself the significance criterion. Note that a `NULL`
#'   `rank_col` is always dropped regardless, when the pair's temp table is built
#'   rather than at ranking time -- see `dto_bind_table_sql()`. That is what makes
#'   `sig_filter = NULL` right for the peak sets even though they report every
#'   promoter: "a peak was called here" is expressed as a non-NULL `rank_col`.
#' @param target_blacklist Target locus tags dropped before ranking.
#' @param dedup_by SQL `ORDER BY` terms, best row first, collapsing multiple
#'   rows for one (`sample_id`, `target_locus_tag`) to one row. `NULL` (the
#'   default) means the dataset already reports one row per sample and target,
#'   which is true of every dataset here except harbison. Written against the
#'   source view's own columns, and applied before ranking and before the
#'   significance filter. `rank_col` and `tiebreak_col` are appended
#'   automatically, so only the terms that come *first* belong here.
#' @return A list carrying the above.
binding_spec <- function(rank_col,
                         rank_asc,
                         tiebreak_col = NULL,
                         tiebreak_asc = FALSE,
                         sig_filter = NULL,
                         target_blacklist = character(),
                         dedup_by = NULL) {
    stopifnot(is.character(rank_col), length(rank_col) == 1)
    stopifnot(is.logical(rank_asc), length(rank_asc) == 1)
    stopifnot(is.null(dedup_by) || is.character(dedup_by))

    list(
        rank_col = rank_col,
        rank_asc = rank_asc,
        tiebreak_col = tiebreak_col,
        tiebreak_asc = tiebreak_asc,
        sig_filter = sig_filter,
        target_blacklist = target_blacklist,
        dedup_by = dedup_by
    )
}

#' Does this perturbation dataset support a p-value-ranked list?
#'
#' The single place that question is asked. A dataset with no p-value column
#' gets `pr/effect/` and nothing else.
#'
#' @param spec A `pert_spec()`.
#' @return `TRUE` if a `pr/pvalue/` list can be built.
pert_has_pvalue <- function(spec) !is.null(spec$pvalue_col)

#' Describe how a perturbation dataset is standardised for DTO
#'
#' @param effect_col Column holding the perturbation effect size.
#' @param pvalue_col Column holding the p-value. `NULL` emits a constant `0.0`,
#'   matching the original script's `mutate(pvalue = 0)`, so every row of a
#'   dataset that reports no p-value clears the significance gate. Nothing is
#'   ever *ranked* on that constant: a dataset with `pvalue_col = NULL` gets no
#'   `pr/pvalue/` directory and no `pr_pvalue` column in `lookup.txt`, because
#'   there is no p-value to order targets by. Its targets are ranked by
#'   descending |effect| in `pr/effect/` only.
#' @param dedup Keep only the max-|effect| row per (sample_id, target_locus_tag).
#'   Needed where multiple probes map to one locus.
#' @param exclude_wt Drop regulators whose locus tag starts with `WT-`.
#' @param effect_na_fill Value substituted for a NULL effect. `NULL` leaves it.
#' @param pvalue_na_fill Value substituted for a NULL p-value. `NULL` leaves it.
#' @param sig_filter SQL predicate applied before ranking, written against the
#'   standardised `effect` / `pvalue` columns.
#' @return A list carrying the above.
pert_spec <- function(effect_col,
                      pvalue_col = NULL,
                      dedup = TRUE,
                      exclude_wt = FALSE,
                      effect_na_fill = NULL,
                      pvalue_na_fill = NULL,
                      sig_filter = "pvalue <= 0.1") {
    stopifnot(is.character(effect_col), length(effect_col) == 1)

    list(
        effect_col = effect_col,
        pvalue_col = pvalue_col,
        dedup = dedup,
        exclude_wt = exclude_wt,
        effect_na_fill = effect_na_fill,
        pvalue_na_fill = pvalue_na_fill,
        sig_filter = sig_filter
    )
}

# ---------------------------------------------------------------------------
# Binding datasets
# ---------------------------------------------------------------------------
#
# Four shapes:
#   * calling cards       -- rank on poisson_pval, tiebreak on enrichment
#   * promoter enrichment -- rank on log_poisson_pval, tiebreak on enrichment
#   * peak calls          -- rank on a score, no p-value, so no sig_filter
#   * ChIP-chip           -- rank on pvalue, tiebreak on effect, plus a dedup

.cc_spec <- function() {
    binding_spec(
        rank_col = "poisson_pval", rank_asc = TRUE,
        tiebreak_col = "callingcards_enrichment", tiebreak_asc = FALSE,
        sig_filter = "poisson_pval <= 0.1"
    )
}

.promoter_enrichment_spec <- function() {
    binding_spec(
        rank_col = "log_poisson_pval", rank_asc = TRUE,
        tiebreak_col = "enrichment", tiebreak_asc = FALSE,
        sig_filter = "log_poisson_pval <= ln(0.1)"
    )
}

# The re-called peak sets report every promoter their set defines, scoring only
# the ones a peak was called in: `max_score` is NULL elsewhere, and `n_peaks` is 0
# for a promoter with no peak at all. "A peak was called here" is therefore the
# significance criterion and needs no `sig_filter` -- a NULL `rank_col` is dropped
# when the pair's temp table is built. For the HOMER (ChEC) sets a promoter whose
# only peak appeared in a single replicate also carries a NULL `max_score` while
# keeping `n_peaks > 0`, so it is excluded too, which is the intended reading of
# the authors' two-replicate requirement.
.homer_macs_peak_spec <- function() {
    binding_spec(
        rank_col = "max_score", rank_asc = FALSE,
        tiebreak_col = "n_peaks", tiebreak_asc = FALSE,
        sig_filter = NULL
    )
}

BINDING_DTO_REGISTRY <- list(
    # Calling cards, one entry per promoter set.
    callingcards_kang = .cc_spec(),
    callingcards_mindel = .cc_spec(),
    callingcards_500bp = .cc_spec(),
    callingcards_intergenic = .cc_spec(),

    # ChIP-chip (Harbison 2004).
    #
    # No condition filter. Each of the 352 sample_ids carries exactly one of the
    # 14 conditions (204 are YPD), so ranking per sample already keeps conditions
    # apart -- a stress-condition sample becomes its own ranked list rather than
    # contaminating the YPD one. This is where tfbpshiny's top-N analysis differs:
    # it aggregates across samples, so it has to restrict to YPD first
    # (topn.py::_HARBISON_DEDUP_CTE).
    #
    # 7,744 (sample, target) pairs carry two rows, so dedup_by is needed. The
    # most significant row wins; where p-values tie -- 5,157 of those pairs --
    # the larger |effect| wins. NaN is how this dataset spells missing (2.1% of
    # rows), and DuckDB sorts NaN above every number: harmless under `pvalue ASC`
    # where it lands last on its own, but it would win an `abs(effect) DESC`, so
    # isnan() demotes it explicitly. That matches the pre-refactor script, which
    # filled a missing effect with 0 before taking the max.
    harbison = binding_spec(
        rank_col = "pvalue", rank_asc = TRUE,
        tiebreak_col = "effect", tiebreak_asc = FALSE,
        sig_filter = "pvalue <= 0.1",
        dedup_by = c(
            "pvalue ASC NULLS LAST",
            "isnan(effect) ASC NULLS LAST",
            "abs(effect) DESC NULLS LAST"
        )
    ),

    # ChIP-exo promoter enrichment (Rossi 2021).
    rossi = .promoter_enrichment_spec(),
    rossi_mindel = .promoter_enrichment_spec(),
    rossi_500bp = .promoter_enrichment_spec(),
    rossi_intergenic = .promoter_enrichment_spec(),

    # ChEC-seq promoter enrichment (Mahendrawada 2025).
    chec_m2025 = .promoter_enrichment_spec(),
    chec_m2025_mindel = .promoter_enrichment_spec(),
    chec_m2025_500bp = .promoter_enrichment_spec(),
    chec_m2025_intergenic = .promoter_enrichment_spec(),

    # Peaks as published by the original authors.
    rossi_peaks = binding_spec(
        rank_col = "peak_score", rank_asc = FALSE,
        tiebreak_col = "n_peaks", tiebreak_asc = FALSE,
        sig_filter = NULL
    ),
    # chec_m2025_peaks carries peak_score only -- no peak count to break ties on.
    chec_m2025_peaks = binding_spec(
        rank_col = "peak_score", rank_asc = FALSE,
        sig_filter = NULL
    ),

    # Peaks re-called against each promoter set (MACS for Rossi, HOMER for ChEC).
    rossi_peaks_kang = .homer_macs_peak_spec(),
    rossi_peaks_mindel = .homer_macs_peak_spec(),
    rossi_peaks_500bp = .homer_macs_peak_spec(),
    rossi_peaks_intergenic = .homer_macs_peak_spec(),
    chec_m2025_peaks_kang = .homer_macs_peak_spec(),
    chec_m2025_peaks_mindel = .homer_macs_peak_spec(),
    chec_m2025_peaks_500bp = .homer_macs_peak_spec(),
    chec_m2025_peaks_intergenic = .homer_macs_peak_spec()
)

# ---------------------------------------------------------------------------
# Perturbation datasets
# ---------------------------------------------------------------------------
# These reproduce the handling in the pre-refactor dto_preparation2.R exactly.

PERTURBATION_DTO_REGISTRY <- list(
    kemmeren = pert_spec(
        effect_col = "Madj", pvalue_col = "pval",
        dedup = TRUE, exclude_wt = TRUE
    ),
    hackett = pert_spec(
        effect_col = "log2_shrunken_timecourses", pvalue_col = NULL,
        dedup = TRUE, exclude_wt = TRUE
    ),
    degron = pert_spec(
        effect_col = "log2FoldChange", pvalue_col = "padj",
        dedup = FALSE,
        effect_na_fill = 0, pvalue_na_fill = 1
    ),
    hu_reimand = pert_spec(
        effect_col = "effect", pvalue_col = "pval",
        dedup = TRUE
    ),
    hughes_knockout = pert_spec(
        effect_col = "mean_norm_log2fc", pvalue_col = NULL,
        dedup = TRUE
    ),
    hughes_overexpression = pert_spec(
        effect_col = "mean_norm_log2fc", pvalue_col = NULL,
        dedup = TRUE
    )
)

#' Reconcile the registries against the collection config
#'
#' Errors when a registry entry names a dataset the collection does not have.
#' Informs -- but does not error -- when the collection has a binding or
#' perturbation dataset with no registry entry, which is the nudge to add one
#' after a new promoter set lands in the YAML.
#'
#' @param vdb A VirtualDB handle.
#' @param quiet Suppress the "not registered" report.
#' @return `invisible(TRUE)`.
dto_check_registry <- function(vdb, quiet = FALSE) {
    available <- vdb$get_datasets()
    registered <- c(names(BINDING_DTO_REGISTRY), names(PERTURBATION_DTO_REGISTRY))

    unknown <- setdiff(registered, available)
    if (length(unknown)) {
        cli_abort(c(
            "Registry names {length(unknown)} dataset{?s} absent from the collection.",
            "x" = "{.val {unknown}}",
            "i" = "Check the {.field db_name} values in {.file brentlab_yeast_collection.yaml}."
        ))
    }

    if (quiet) {
        return(invisible(TRUE))
    }

    tagged <- function(role) {
        keep <- vapply(available, function(db) {
            tags <- reticulate::py_to_r(vdb$get_tags(db))
            identical(tags[["data_type"]], role)
        }, logical(1))
        available[keep]
    }

    unregistered_binding <- setdiff(tagged("binding"), names(BINDING_DTO_REGISTRY))
    unregistered_pert <- setdiff(tagged("perturbation"), names(PERTURBATION_DTO_REGISTRY))

    if (length(unregistered_binding)) {
        cli_alert_warning(
            "Binding dataset{?s} in the collection with no registry entry: {.val {unregistered_binding}}"
        )
    }
    if (length(unregistered_pert)) {
        cli_alert_warning(
            "Perturbation dataset{?s} in the collection with no registry entry: {.val {unregistered_pert}}"
        )
    }
    if (!length(unregistered_binding) && !length(unregistered_pert)) {
        cli_alert_success("Registry covers every binding and perturbation dataset in the collection.")
    }

    invisible(TRUE)
}