File size: 4,824 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
# VirtualDB access for DTO input preparation.
#
# labretriever is a Python package. It is reached through reticulate rather than
# being reimplemented in R, so that the binding/perturbation views, the
# sample_id normalisation, and the measurement-to-metadata join all come from
# the same code that backs tfbpshiny.
#
# The venv defaults to the tfbpshiny one because labretriever is not installed
# on the system python. Override with the LABRETRIEVER_VENV environment
# variable.

library(cli)
library(here)

# Cache of the VirtualDB handle, keyed by config path. VirtualDB registers every
# view on construction, so building it repeatedly is expensive.
.dto_vdb_cache <- new.env(parent = emptyenv())

#' Return a labretriever VirtualDB handle
#'
#' @param config_path Path to the VirtualDB YAML collection config.
#' @param venv Path to a virtualenv with labretriever installed.
#' @param token HuggingFace token. Falls back to the HF_TOKEN env var, then NULL.
#' @param local_files_only Skip HuggingFace network checks and use only what is
#'   already cached locally. Much faster on warm restarts.
#' @param refresh Rebuild the handle even if one is cached.
#' @return A python VirtualDB object.
dto_vdb <- function(config_path = here("brentlab_yeast_collection.yaml"),
                    venv = Sys.getenv("LABRETRIEVER_VENV", "~/projects/tfbpshiny/.venv"),
                    token = Sys.getenv("HF_TOKEN", ""),
                    local_files_only = FALSE,
                    refresh = FALSE) {
    config_path <- normalizePath(config_path, mustWork = TRUE)
    key <- config_path

    if (!refresh && !is.null(.dto_vdb_cache[[key]])) {
        return(.dto_vdb_cache[[key]])
    }

    reticulate::use_virtualenv(path.expand(venv), required = TRUE)
    labretriever <- reticulate::import("labretriever")

    cli_alert_info("Initializing VirtualDB from {.file {config_path}} ...")
    vdb <- labretriever$VirtualDB(
        config_path,
        token = if (nzchar(token)) token else NULL,
        local_files_only = local_files_only
    )
    cli_alert_success("VirtualDB ready ({length(vdb$get_datasets())} datasets).")

    .dto_vdb_cache[[key]] <- vdb
    vdb
}

#' Run SQL against the VirtualDB connection, discarding the result
#'
#' `vdb$query()` always calls `fetchdf()`, which is fine for DDL and COPY but
#' returns a throwaway frame. This wrapper makes the intent explicit at the call
#' site.
#'
#' @param vdb A VirtualDB handle.
#' @param sql SQL to execute.
#' @return `invisible(NULL)`.
dto_execute <- function(vdb, sql) {
    vdb$query(sql)
    invisible(NULL)
}

#' Register the target universe as a temp table
#'
#' The universe is the set of protein-coding, non-dubious loci that both the
#' binding and perturbation sides are restricted to. It is read directly from a
#' parquet rather than through a VirtualDB view because the features table is
#' not registered as a dataset in the collection YAML.
#'
#' @param vdb A VirtualDB handle.
#' @param features_path Parquet with a `locus_tag` column.
#' @param locus_col Name of the locus tag column in that parquet.
#' @return `invisible(n)`, the number of loci registered.
dto_register_universe <- function(vdb,
                                  features_path = "~/projects/huggingface/mahendrawada_2025/features_mahendrawada_2025.parquet",
                                  locus_col = "locus_tag") {
    features_path <- normalizePath(path.expand(features_path), mustWork = TRUE)

    dto_execute(vdb, glue::glue(
        "CREATE OR REPLACE TEMP TABLE dto_universe AS
         SELECT DISTINCT {locus_col} AS locus_tag
         FROM read_parquet('{features_path}')
         WHERE {locus_col} IS NOT NULL"
    ))

    n <- vdb$query("SELECT COUNT(*) AS n FROM dto_universe")$n[[1]]
    cli_alert_info("Target universe: {n} loci from {.file {basename(features_path)}}.")
    invisible(n)
}

#' Map db_name -> (hf_repo, hf_config)
#'
#' `vdb$db_name_map` is the same mapping that produces the `repo;config;sample_id`
#' composite IDs used downstream, so nothing needs to hard-code those prefixes.
#'
#' @param vdb A VirtualDB handle.
#' @param db_names db_names to look up. Defaults to every dataset in the config.
#' @return A tibble with `db_name`, `hf_repo`, `hf_config`.
dto_hf_coords <- function(vdb, db_names = NULL) {
    name_map <- reticulate::py_to_r(vdb$db_name_map)
    if (is.null(db_names)) db_names <- names(name_map)

    missing <- setdiff(db_names, names(name_map))
    if (length(missing)) {
        cli_abort("db_name{?s} not present in the collection: {.val {missing}}")
    }

    tibble::tibble(
        db_name = db_names,
        hf_repo = vapply(db_names, function(x) as.character(name_map[[x]][[1]]), character(1)),
        hf_config = vapply(db_names, function(x) as.character(name_map[[x]][[2]]), character(1))
    )
}