Chase Mateusiak
using current run of dto to replace old results
163eea8
Raw History Blame Contribute Delete
4.82 kB
# 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))
)
}