diff --git a/.Rbuildignore b/.Rbuildignore index ab4f42a..afda15a 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,6 +1,7 @@ ^.*\.Rproj$ ^\.Rproj\.user$ ^README\.Rmd$ +^CONTRIBUTING\.md$ ^LICENSE\.md$ ^pkgdown$ ^_pkgdown\.yml$ diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index a56afce..e793cea 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -23,7 +23,12 @@ jobs: config: - {os: macos-latest, r: 'release'} - {os: windows-latest, r: 'release'} - - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} + # Pinned to 24.04: ubuntu-latest moved to 26.04 (resolute) on + # 2026-10-26, and RSPM does not yet serve R-devel binaries for + # duckdb there, forcing a ~1h source build that fails to install. + # R-release/oldrel-1 binaries on resolute are fine; revisit the + # pin once RSPM's resolute R-devel coverage matures. + - {os: ubuntu-24.04, r: 'devel', http-user-agent: 'release'} - {os: ubuntu-latest, r: 'release'} - {os: ubuntu-latest, r: 'oldrel-1'} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d9d956d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,34 @@ +# Contributing to geokit + +Thanks for considering a contribution! + +## Development setup + +geokit uses a Rust backend for URL resolution and SOFT parsing. To build from +source you need the Rust toolchain (`cargo` and `rustc`, see the +`SystemRequirements` field in DESCRIPTION) in addition to R. + +```sh +git clone https://github.com/WangLabCSU/geokit.git +Rscript -e 'pkgload::load_all(".")' +``` + +## Pull requests + +- Work on a feature branch and keep pull requests focused on one change. +- Add or update tests in `tests/testthat/` for behavior changes. Tests that + hit NCBI should use `skip_if_download_fail()` (download layer) so they skip + gracefully when the network is unavailable. +- Keep roxygen documentation in `R/*.R` in sync with the code and regenerate + the `man/` pages with `roxygen2::roxygenise()` when docs change. +- Record user-visible changes in `NEWS.md` under the development-version + section. +- CI runs `R CMD check` on Linux, macOS, and Windows plus test coverage; + please keep it green. + +## Reporting issues + +Include your R version, geokit version (`packageVersion("geokit")`), and a +minimal reproducible example. For download problems, mention whether an NCBI +API key (`ENTREZ_KEY`) is set and whether your environment can reach +`ftp.ncbi.nlm.nih.gov`. diff --git a/DESCRIPTION b/DESCRIPTION index 2807462..7870afa 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -19,12 +19,12 @@ Imports: data.table (>= 1.14.9), curl (>= 6.0.0), rentrez, + stats, xml2, utils Suggests: BiocGenerics, Biobase, - stats, dplyr, ggplot2, stringr, @@ -39,6 +39,6 @@ ByteCompile: true Config/testthat/edition: 3 Encoding: UTF-8 Roxygen: list(markdown = TRUE) -RoxygenNote: 8.0.0 SystemRequirements: Cargo (Rust's package manager), rustc >= 1.87.0 VignetteBuilder: knitr +Config/roxygen2/version: 8.1.1 diff --git a/NAMESPACE b/NAMESPACE index 3ee1244..26105de 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -62,12 +62,14 @@ exportMethods(rcd_name) exportMethods(rcd_type) exportMethods(show) importFrom(methods,show) -importFrom(rlang,abort) -importFrom(rlang,caller_arg) -importFrom(rlang,caller_env) -importFrom(rlang,ffi_standalone_check_number_1.0.7) -importFrom(rlang,ffi_standalone_is_bool_1.0.7) -importFrom(rlang,is_missing) -importFrom(rlang,is_string) -importFrom(rlang,is_vector) +importFrom(rlang, + abort, + caller_arg, + caller_env, + ffi_standalone_check_number_1.0.7, + ffi_standalone_is_bool_1.0.7, + is_missing, + is_string, + is_vector +) useDynLib(geokit, .registration = TRUE) diff --git a/NEWS.md b/NEWS.md index 500614b..7ae2ba8 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,8 +1,22 @@ # geokit (development version) -* Added a public Agent Skills file for AI agents, published once with the - pkgdown site at - . +* Added three vignettes: case studies for diabetic nephropathy and + urothelial cancer meta-analysis workflows, and a `geo_chat()` guide for + LLM-assisted exploration of GEO metadata. +* Added a public Agent Skills file for AI agents, published with the pkgdown + site at . +* Fixed `parse_sample_data()` ignoring its `sep` argument when parsing + characteristic key-value pairs, silently skipping non-contiguous + `characteristics_ch` columns, and crashing on custom `fields` names + without a `ch` suffix (they now prefix parsed columns with the field + name). +* Fixed plain-FTP downloads (`ftp_over_https = FALSE`) being deleted and + reported as failures after a success-detection regression. +* Fixed a guaranteed crash in `geo_matrix()` when a platform annotation + download fails, and clarified the error when sample metadata lacks + `platform_id`. +* CI resolves `querychat` from the posit-dev R-universe after its CRAN + archive; workflows and the skill file keep working unchanged. # geokit 0.0.2 diff --git a/R/class.R b/R/class.R index 78faa09..2ed55cb 100644 --- a/R/class.R +++ b/R/class.R @@ -2,6 +2,14 @@ #' #' @param object A [GEOSoft][GEOSoft-class] Class Object. #' @param value A R object with the same class of corresponding slots. +#' @return +#' The accessor generics return the value of the corresponding slot: +#' `accession()`, `rcd_name()`, `rcd_type()` and `metadata()` return the +#' record accession, name, type, and header metadata list; `columns()` and +#' `datatable()` return the column descriptions and the data table as +#' data.frames; `gsm()`, `gse()` and `gpl()` return lists of related +#' `GEOSoft` objects where applicable. The replacement forms return the +#' modified object. #' @name GEOSoft-class #' @docType class #' @keywords internal @@ -75,6 +83,7 @@ methods::setValidity("GEOSoft", function(object) { methods::setMethod("show", "GEOSoft", function(object) print(object)) #' @export +#' @rdname GEOSoft-class print.GEOSoft <- function(x, ...) { soft_print_header(x, ...) soft_print_data(x, ...) @@ -321,7 +330,7 @@ methods::setValidity("GEOPlatform", function(object) { if (!all(vapply(object@gse, function(x) { methods::is(x, "GEOSoft") }, logical(1L), USE.NAMES = FALSE))) { - return("the element of slot @gpl list should only contain Class `GEOSoft` object.") + return("the element of slot @gse list should only contain Class `GEOSoft` object.") } TRUE }) diff --git a/R/download.R b/R/download.R index 843b6c6..910701d 100644 --- a/R/download.R +++ b/R/download.R @@ -80,10 +80,18 @@ list_directory_url <- function(accession, format, ftp_over_https, urls } -#' Download utils function with good message. -#' @return If fail is `TRUE`, always return a character path if downloading -#' succeed, otherwise, stop with error message. If fail is `FALSE`, always -#' return a list. +#' Download files with informative messages. +#' +#' Download `urls` into `ofiles`, remove partially downloaded files on +#' failure, and optionally raise an error when any download fails. +#' +#' @param urls Character of URLs to download. +#' @param ofiles Character of local destination paths, aligned with `urls`. +#' @param handle_opts Options passed to [curl::multi_download()]. +#' @param error If `TRUE` (default), raise `geokit_download_error` when any +#' download fails. +#' @return A list with elements `urls`, `paths`, and `success` (a logical +#' vector aligned with `urls`). #' @noRd download_inform <- function(urls, ofiles, handle_opts, error = TRUE) { out <- list( @@ -111,10 +119,9 @@ download_inform <- function(urls, ofiles, handle_opts, error = TRUE) { urls = urls, destfiles = ofiles, resume = FALSE, !!!handle_opts )) - # FTP: 200L, 206L, 416L, 226L - # ADB: 200L, 206L, 416L + # success codes: HTTP 200/206/416 and FTP 226 (transfer complete) success <- !is.na(status$success) & status$success & - status$status_code == 200L + status$status_code %in% c(200L, 206L, 416L, 226L) removed <- !success & file.exists(ofiles) if (any(removed)) file.remove(ofiles[removed]) if (!all(success) && error) { @@ -132,10 +139,10 @@ download_inform <- function(urls, ofiles, handle_opts, error = TRUE) { } setup_handle_opts <- function(handle_opts) { + # the empty Expect header disables curl's default `Expect: 100-continue`, + # which otherwise stalls FTP transfers handle_opts$httpheader <- handle_opts$httpheader %||% - utils::getFromNamespace("format_request_headers", "curl")( - list("User-Agent" = "geokit") - ) + c("User-Agent: geokit", "Expect: ") handle_opts$followlocation <- handle_opts$followlocation %||% TRUE handle_opts$connecttimeout <- handle_opts$connecttimeout %||% 60L # this is recommended by GEO FTP site diff --git a/R/geo-matrix.R b/R/geo-matrix.R index 0297911..a9fdeb3 100644 --- a/R/geo-matrix.R +++ b/R/geo-matrix.R @@ -45,8 +45,8 @@ geo_matrix <- function(accession, add_gpl = NULL, pdata_from_soft = FALSE, return_object_or_list(matrix_list, accession) } -geo_matrix_impl <- function(accession, pdata_from_soft = TRUE, - add_gpl = NULL, ftp_over_https = TRUE, +geo_matrix_impl <- function(accession, pdata_from_soft = FALSE, + add_gpl = NULL, ftp_over_https = NULL, handle_opts = list(), odir = getwd()) { collected <- list( ftp_over_https = ftp_over_https, @@ -92,6 +92,8 @@ geo_matrix_impl <- function(accession, pdata_from_soft = TRUE, parse_gse_matrix <- function(path, gse_soft = NULL, add_gpl = NULL, ftp_over_https = TRUE, handle_opts = list(), odir = getwd()) { + # series matrix files are named "_series_matrix.txt[.gz]" + accession <- sub("_series_matrix.*$", "", basename(path)) entity_list <- parse_soft_rust(path, "matrix") gse_matrix <- parse_entity_list(.subset2(entity_list, 1L)) @@ -159,7 +161,17 @@ parse_gse_matrix <- function(path, gse_soft = NULL, add_gpl = NULL, "platform_id", colnames(metadata$Sample), ignore.case = TRUE ) - annotation <- .subset(.subset2(metadata$Sample, gpl_column[1L]), 1L) + annotation <- if (length(gpl_column)) { + .subset(.subset2(metadata$Sample, gpl_column[1L]), 1L) + } else { + NULL + } + if (is.null(annotation) || all(is.na(annotation))) { + cli::cli_abort(c( + "No {.field platform_id} found in the sample metadata of {.val {accession}}.", + "i" = "Cannot resolve platform annotation for the series matrix." + )) + } if (is.null(add_gpl) || !add_gpl) { bioc_pkg <- gpl_map(annotation)$bioc_pkg @@ -210,8 +222,8 @@ parse_gse_matrix <- function(path, gse_soft = NULL, add_gpl = NULL, ) } } else { - cli::cli_alert_info(paste( - "Failed to download annotation file for {.val {accession[!downloaded$success]}},", + cli::cli_alert_info(c( + "Failed to download annotation file for {.val {accession}},", "Platform information will not be added." )) } diff --git a/R/geo-search.R b/R/geo-search.R index a91c56b..99dd967 100644 --- a/R/geo-search.R +++ b/R/geo-search.R @@ -33,19 +33,22 @@ #' } #' @export geo_search <- function(query, step = 500L, interval = NULL) { + assert_string(query) assert_number_whole(step, min = 1) assert_number_decimal(interval, min = 0, allow_null = TRUE) interval <- interval %||% 0 - records_num <- rentrez::entrez_search("gds", query, retmax = 0L)$count + # one search call provides both the total count and the web history used + # by the paged fetches below + search_res <- rentrez::entrez_search( + "gds", query, + use_history = TRUE, retmax = 0L + ) + records_num <- search_res$count if (records_num == 0L) { cli::cli_abort("No items found.") } retstarts <- seq.int(0L, records_num - 1L, by = step) records <- character(length(retstarts)) - search_res <- rentrez::entrez_search( - "gds", query, - use_history = TRUE, retmax = 0L - ) bar <- cli::cli_progress_bar( name = "NCBI", format = "{cli::pb_bar} {cli::pb_current}/{cli::pb_total} [{cli::pb_rate}] | {cli::pb_eta_str}", diff --git a/R/geo-soft.R b/R/geo-soft.R index efd149e..f24f34b 100644 --- a/R/geo-soft.R +++ b/R/geo-soft.R @@ -8,7 +8,9 @@ #' [`multi_download`][curl::multi_download]. #' @param odir Destination directory for downloads. Defaults to the current #' working directory. -#' @return A [GEOSoft][GEOSoft-class] object +#' @return A [GEOSoft][GEOSoft-class] object (or a list of them when +#' multiple accessions are provided; subclasses `GEOPlatform` and +#' `GEOSeries` are returned for GPL and GSE accessions respectively). #' #' @details #' diff --git a/R/geo-suppl.R b/R/geo-suppl.R index 86b35b0..2216c61 100644 --- a/R/geo-suppl.R +++ b/R/geo-suppl.R @@ -9,14 +9,14 @@ #' @param pattern character string containing a #' [regular expression][base::regex] to be matched in the supplementary file #' names. -#' @return A list (or a character atomic verctor if only one `accession` is +#' @return A list (or a character atomic vector if only one `accession` is #' provided) of the full file paths of the resulting downloaded files. #' @examples #' \donttest{ #' geo_suppl("GSM1137", odir = tempdir()) #' } #' @export -geo_suppl <- function(accession, pattern = NULL, ftp_over_https = TRUE, +geo_suppl <- function(accession, pattern = NULL, ftp_over_https = NULL, handle_opts = list(), odir = getwd()) { odir <- dir_create(odir, recursive = TRUE) file_paths <- download_url_directory( diff --git a/R/phenodata.R b/R/phenodata.R index 185218d..2231b73 100644 --- a/R/phenodata.R +++ b/R/phenodata.R @@ -44,7 +44,7 @@ parse_sample_data.data.frame <- function(x, ..., fields = NULL, sep = ":") { }, logical(1L), USE.NAMES = FALSE) mean(have_sep, na.rm = TRUE) >= 0.5 }, logical(1L), USE.NAMES = FALSE) - fields <- colnames(x)[cols[column_with_sep]] + fields <- colnames(x)[which(cols)[column_with_sep]] } if (length(fields) == 0L) { return(set_rownames(x, "geo_accession")) @@ -121,20 +121,21 @@ parse_characteristics <- function(data, characteristic_cols, sep = ":") { )) } characteristics <- lapply(characteristic_cols, function(col) { - data <- parse_key_value_elements(.subset2(data, col), sep = ":") + data <- parse_key_value_elements(.subset2(data, col), sep = sep) if (nrow(data) && ncol(data)) { # we extract the last "ch\\d*" pattern as the column # name, which is the first group defined by parentheses. # This is just the second column of `str_match`. - # Sometimes there may be a "\\.\\d*" tail - new_names <- paste0( - str_match(col, "(ch\\d*)(\\.\\d*)?(_\\d*)?$")[ - , 2L, - drop = TRUE - ], - "_", - colnames(data) - ) + # Sometimes there may be a "\\.\\d*" tail. + # Columns without a "ch\\d*" suffix (custom `fields`) have no + # match group; fall back to the column name itself as the prefix. + matched <- str_match(col, "(ch\\d*)(\\.\\d*)?(_\\d*)?$") + prefix <- if (ncol(matched) >= 2L) { + matched[, 2L, drop = TRUE] + } else { + col + } + new_names <- paste0(prefix, "_", colnames(data)) colnames(data) <- new_names data } else { diff --git a/R/utils-str.R b/R/utils-str.R index cc38ac3..e53d975 100644 --- a/R/utils-str.R +++ b/R/utils-str.R @@ -1,16 +1,4 @@ -# stingr from base R --------------------------------- -str_which <- function(string, pattern, ..., fixed = FALSE) { - grep( - pattern = pattern, x = string, ..., - perl = !fixed, value = FALSE, - fixed = fixed - ) -} - -str_detect <- function(string, pattern, ..., fixed = FALSE) { - grepl(pattern = pattern, x = string, ..., perl = !fixed, fixed = fixed) -} - +# base R equivalents of stringr helpers used internally ---- str_subset <- function(string, pattern, ..., fixed = FALSE) { grep( pattern = pattern, x = string, ..., @@ -33,14 +21,6 @@ str_replace_all <- function(string, pattern, replacement, ..., fixed = FALSE) { ) } -str_extract <- function(string, pattern, ..., fixed = FALSE) { - matches <- regexpr(pattern, string, perl = !fixed, ..., fixed = fixed) - start <- as.vector(matches) - end <- start + attr(matches, "match.length") - 1L - start[start == -1L] <- NA_integer_ - substr(string, start, end) -} - str_extract_all <- function(string, pattern, ..., fixed = FALSE) { regmatches( string, @@ -51,47 +31,36 @@ str_extract_all <- function(string, pattern, ..., fixed = FALSE) { ) } -# split string based on pattern, Only split once, Return a list of character, -# the length of every element is two -str_split_fixed <- function(string, pattern, ..., fixed = FALSE) { - regmatches( - string, - regexpr( - pattern = pattern, text = string, - perl = !fixed, ..., fixed = fixed - ), - invert = TRUE - ) -} - str_split <- function(string, pattern, fixed = FALSE) { strsplit(x = string, split = pattern, fixed = fixed, perl = !fixed) } str_match <- function(string, pattern, ..., fixed = FALSE) { - out <- regmatches( - string, - regexec( - pattern = pattern, text = string, - perl = !fixed, ..., fixed = fixed - ), - invert = FALSE + matches <- regexec( + pattern = pattern, text = string, + perl = !fixed, ..., fixed = fixed ) + out <- regmatches(string, matches, invert = FALSE) + # a non-matching element yields character(0); pad it with an all-NA row so + # the result always keeps one row per input element, like + # stringr::str_match(). the column count (full match + capture groups) + # must come from an element that actually matched: a non-match reports a + # single -1 position and carries no group information, so when nothing + # matches the result degrades to one all-NA column + n_cols <- 1L + for (m in matches) { + if (m[[1L]] != -1L) { + n_cols <- length(attr(m, "match.length")) + break + } + } out <- lapply(out, function(x) { - if (!length(x)) "" else x + if (!length(x)) rep(NA_character_, n_cols) else x }) out <- do.call("rbind", out) + if (is.null(out)) { + return(out) + } out[out == ""] <- NA_character_ out } - -str_match_all <- function(string, pattern, ..., fixed = FALSE) { - regmatches( - string, - gregexec( - pattern = pattern, text = string, - perl = !fixed, ..., fixed = fixed - ), - invert = FALSE - ) -} diff --git a/data-raw/gpl2bioc.R b/data-raw/gpl2bioc.R index 0b0db5f..5f32890 100644 --- a/data-raw/gpl2bioc.R +++ b/data-raw/gpl2bioc.R @@ -13,7 +13,7 @@ if (length(new_gpl2bioc)) { gpl_soft <- geo_soft(names(new_gpl2bioc), odir = tempdir()) if (is(gpl_soft, "GEOSoft")) gpl_soft <- list(gpl_soft) gpl2bioc_list <- lapply(gpl_soft, function(gpl) { - res <- meta(gpl)[ + res <- metadata(gpl)[ intersect( c( "Platform_geo_accession", "Platform_title", @@ -22,7 +22,7 @@ if (length(new_gpl2bioc)) { "Platform_submission_date", "Platform_technology", "Platform_web_link" ), - names(meta(gpl)) + names(metadata(gpl)) ) ] res <- c(res, bioc_pkg = new_gpl2bioc[[res$Platform_geo_accession]]) diff --git a/man/GEOSoft-class.Rd b/man/GEOSoft-class.Rd index 3db2ce3..14194cf 100644 --- a/man/GEOSoft-class.Rd +++ b/man/GEOSoft-class.Rd @@ -4,6 +4,7 @@ \name{GEOSoft-class} \alias{GEOSoft-class} \alias{show,GEOSoft-method} +\alias{print.GEOSoft} \alias{metadata} \alias{metadata<-} \alias{metadata,GEOSoft-method} @@ -48,6 +49,8 @@ \usage{ \S4method{show}{GEOSoft}(object) +\method{print}{GEOSoft}(x, ...) + metadata(object) metadata(object) <- value @@ -129,6 +132,15 @@ gpl(object) <- value \item{value}{A R object with the same class of corresponding slots.} } +\value{ +The accessor generics return the value of the corresponding slot: +\code{accession()}, \code{rcd_name()}, \code{rcd_type()} and \code{metadata()} return the +record accession, name, type, and header metadata list; \code{columns()} and +\code{datatable()} return the column descriptions and the data table as +data.frames; \code{gsm()}, \code{gse()} and \code{gpl()} return lists of related +\code{GEOSoft} objects where applicable. The replacement forms return the +modified object. +} \description{ Virtual class for holding GEO series, samples, platforms, and datasets. } diff --git a/man/geo_soft.Rd b/man/geo_soft.Rd index 3395ff4..566a800 100644 --- a/man/geo_soft.Rd +++ b/man/geo_soft.Rd @@ -52,7 +52,9 @@ access.} working directory.} } \value{ -A \link[=GEOSoft-class]{GEOSoft} object +A \link[=GEOSoft-class]{GEOSoft} object (or a list of them when +multiple accessions are provided; subclasses \code{GEOPlatform} and +\code{GEOSeries} are returned for GPL and GSE accessions respectively). } \description{ By default, this function uses the \code{soft} format for GDS and GSE entities, diff --git a/man/geo_suppl.Rd b/man/geo_suppl.Rd index f9b1c4e..ac2707b 100644 --- a/man/geo_suppl.Rd +++ b/man/geo_suppl.Rd @@ -7,7 +7,7 @@ geo_suppl( accession, pattern = NULL, - ftp_over_https = TRUE, + ftp_over_https = NULL, handle_opts = list(), odir = getwd() ) @@ -37,7 +37,7 @@ access.} working directory.} } \value{ -A list (or a character atomic verctor if only one \code{accession} is +A list (or a character atomic vector if only one \code{accession} is provided) of the full file paths of the resulting downloaded files. } \description{ diff --git a/pkgdown/assets/skills/geokit/SKILL.md b/pkgdown/assets/skills/geokit/SKILL.md index 8dc1ab5..5192b12 100644 --- a/pkgdown/assets/skills/geokit/SKILL.md +++ b/pkgdown/assets/skills/geokit/SKILL.md @@ -10,7 +10,7 @@ license: MIT compatibility: > Requires R >= 3.5 with package geokit. Network access to NCBI GEO/Entrez is required for live queries and downloads. Biobase is required for geo_matrix() - ExpressionSet output. querychat and duckdb are required for geo_chat family. + ExpressionSet output. querychat plus a local SQL engine (duckdb or RSQLite) are required for the geo_chat family. Optional NCBI ENTREZ_KEY improves search rate limits. metadata: author: WangLabCSU diff --git a/src/rust/src/r/mod.rs b/src/rust/src/r/mod.rs index c867427..5c9c767 100644 --- a/src/rust/src/r/mod.rs +++ b/src/rust/src/r/mod.rs @@ -16,6 +16,15 @@ use rayon::{ ThreadPoolBuilder, }; + +/// Flatten an error chain into a single-line message for R conditions. +fn fmt_error(err: &anyhow::Error) -> String { + err.chain() + .map(ToString::to_string) + .collect::>() + .join(": ") +} + #[cfg(not(feature = "isal"))] use flate2::bufread::GzDecoder as GzipDecoder; #[cfg(feature = "isal")] @@ -36,7 +45,7 @@ fn geo_gtype(accession: Robj, abbre: bool) -> Result, String> { .as_str_vector() .ok_or_else(|| anyhow!("Expected a character vector")) .with_context(|| "Invalid 'accession'".to_string()) - .map_err(|e| format!("{:?}", e))? + .map_err(|e| fmt_error(&e))? .iter() .map(|acc| { GEOEntity::try_from(*acc) @@ -48,7 +57,7 @@ fn geo_gtype(accession: Robj, abbre: bool) -> Result, String> { } }) .with_context(|| format!("Invalid 'accession': {}", acc)) - .map_err(|e| format!("{:?}", e)) + .map_err(|e| fmt_error(&e)) }) .collect::, String>>() } @@ -72,7 +81,7 @@ fn geo_url( GEOType::Samples => "text", }, ) - .map_err(|e| format!("{:?}", e)) + .map_err(|e| fmt_error(&e)) .map(|resolvers| { resolvers .into_iter() @@ -96,7 +105,7 @@ fn geo_landing_page( |_| "brief", "html", ) - .map_err(|e| format!("{:?}", e)) + .map_err(|e| fmt_error(&e)) .map(|resolvers| { resolvers .into_iter() @@ -124,7 +133,7 @@ fn geo_file_url_and_fname( "text", ) .map_or_else( - |e| Err(format!("Failed to initialize the resolvers: {:?}", e)), + |e| Err(format!("Failed to initialize the resolvers: {}", fmt_error(&e))), |resolvers| { resolvers .into_iter() @@ -158,13 +167,13 @@ fn geo_parse_soft( .as_str_vector() .ok_or_else(|| anyhow!("Expected a character vector")) .with_context(|| "Invalid 'path'".to_string()) - .map_err(|err| format!("{:?}", err))?; + .map_err(|err| fmt_error(&err))?; let format = helper::robj_to_vec_str(&format, path.len()) .with_context(|| "Invalid 'format'".to_string()) - .map_err(|err| format!("{:?}", err))?; + .map_err(|err| fmt_error(&err))?; let use_lines = helper::robj_to_option_vec_str(&use_lines, path.len()) .with_context(|| "Invalid 'use_lines'".to_string()) - .map_err(|err| format!("{:?}", err))?; + .map_err(|err| fmt_error(&err))?; // use rayon to implement parallel let mut pool_builder = ThreadPoolBuilder::new(); @@ -174,7 +183,7 @@ fn geo_parse_soft( let record_res = pool_builder .build() .with_context(|| "Failed to create rayon thread pool".to_string()) - .map_err(|err| format!("{:?}", err))? + .map_err(|err| fmt_error(&err))? .install(|| { // for each path, we parse the soft file, each file has multiple records let style = ProgressStyle::with_template( @@ -193,12 +202,12 @@ fn geo_parse_soft( }) .collect::>, _>>() }) - .map_err(|err| format!("{:?}", err))?; + .map_err(|err| fmt_error(&err))?; // Building the result into R object let style = ProgressStyle::with_template( "{prefix:.bold.cyan/blue} {human_pos}/{human_len} {spinner:.green} [{elapsed_precise}] {per_sec} (ETA {eta})", - ).with_context(|| "Invalid progress style".to_string()).map_err(|err| format!("{:?}", err))?; + ).with_context(|| "Invalid progress style".to_string()).map_err(|err| fmt_error(&err))?; let pb = ProgressBar::new(record_res.len() as u64) .with_prefix("Building R object") .with_style(style) @@ -217,7 +226,8 @@ fn geo_parse_soft( out }) .collect::>() - .map_err(|err| format!("{:?}", err)) + // extendr_api::Error has no chain; its Display is already concise + .map_err(|err| err.to_string()) } fn geo_parse_soft_impl( @@ -285,18 +295,18 @@ fn pprof_geo_parse_soft( .frequency(2000) .build() .with_context(|| format!("Failed to create pprof profile guard")) - .map_err(|e| format!("{:?}", e))?; + .map_err(|e| fmt_error(&e))?; let out = geo_parse_soft(path, format, use_lines, threads); if let Ok(report) = guard.report().build() { let file = std::fs::File::create(pprof_file) .with_context(|| format!("Failed to create file {}", pprof_file)) - .map_err(|e| format!("{:?}", e))?; + .map_err(|e| fmt_error(&e))?; let mut options = pprof::flamegraph::Options::default(); options.image_width = Some(2500); report .flamegraph_with_options(file, &mut options) .with_context(|| format!("Failed to write flamegraph to {}", pprof_file)) - .map_err(|e| format!("{:?}", e))?; + .map_err(|e| fmt_error(&e))?; }; out } diff --git a/tests/testthat/test-geo-accessors.R b/tests/testthat/test-geo-accessors.R new file mode 100644 index 0000000..2dbd2d9 --- /dev/null +++ b/tests/testthat/test-geo-accessors.R @@ -0,0 +1,31 @@ +testthat::test_that("record accessors read and write GEOSoft slots", { + obj <- methods::new( + "GEOSoft", + rcd_type = "Sample", + rcd_name = "GSM1", + accession = "GSM1" + ) + + testthat::expect_identical(rcd_type(obj), "Sample") + testthat::expect_identical(rcd_name(obj), "GSM1") + testthat::expect_identical(accession(obj), "GSM1") + testthat::expect_type(metadata(obj), "list") + + rcd_type(obj) <- "Platform" + rcd_name(obj) <- "GPL1" + testthat::expect_identical(rcd_type(obj), "Platform") + testthat::expect_identical(rcd_name(obj), "GPL1") +}) + +testthat::test_that("GEOSoft validity enforces scalar record identity", { + testthat::expect_error(methods::new("GEOSoft", rcd_type = c("a", "b"))) + testthat::expect_error(methods::new("GEOSoft", rcd_name = character())) +}) + +testthat::test_that("accessors stay consistent on parsed SOFT records", { + gsm <- skip_if_download_fail(geo_soft("GSM11805", odir = tempdir())) + + testthat::expect_identical(rcd_name(gsm), accession(gsm)) + testthat::expect_type(rcd_type(gsm), "character") + testthat::expect_false(is.na(rcd_type(gsm))) +}) diff --git a/tests/testthat/test-geo-meta.R b/tests/testthat/test-geo-meta.R new file mode 100644 index 0000000..489f5f5 --- /dev/null +++ b/tests/testthat/test-geo-meta.R @@ -0,0 +1,21 @@ +testthat::test_that("geo_meta returns collapsed series metadata", { + meta <- skip_if_download_fail(geo_meta("GSE10", odir = tempdir())) + + testthat::expect_s3_class(meta, "data.frame") + testthat::expect_gte(nrow(meta), 1L) + for (col in c("Series_geo_accession", "Series_title")) { + testthat::expect_true(col %in% colnames(meta), info = col) + } + testthat::expect_true("GSE10" %in% meta$Series_geo_accession) +}) + +testthat::test_that("geo_meta is vectorized over accessions", { + meta <- skip_if_download_fail( + geo_meta(c("GSE10", "GSE1563"), odir = tempdir()) + ) + + testthat::expect_s3_class(meta, "data.frame") + testthat::expect_true( + all(c("GSE10", "GSE1563") %in% meta$Series_geo_accession) + ) +}) diff --git a/tests/testthat/test-geo-search.R b/tests/testthat/test-geo-search.R new file mode 100644 index 0000000..2085b47 --- /dev/null +++ b/tests/testthat/test-geo-search.R @@ -0,0 +1,48 @@ +# geo_search() goes through rentrez/curl instead of the download layer, so +# `skip_if_download_fail()` cannot catch its network errors. Skip when the +# failure looks like a network problem, but let real bugs surface. +skip_if_search_unreachable <- function(expr) { + deparsed <- deparse(substitute(expr)) + tryCatch( + expr, + error = function(cnd) { + msg <- conditionMessage(cnd) + if (grepl( + "Timeout|timed out|resolve|SSL|TLS|connection|status code|Failed", + msg, + ignore.case = TRUE + )) { + testthat::skip(sprintf( + "NCBI unreachable during '%s': %s", + deparsed, msg + )) + } + stop(cnd) + } + ) +} + +testthat::test_that("geo_search returns parsed summary records", { + hits <- skip_if_search_unreachable( + geo_search( + "diabetic nephropathy[ALL] AND Homo sapiens[ORGN] AND GSE[ETYP]", + step = 50L + ) + ) + + testthat::expect_s3_class(hits, "data.frame") + testthat::expect_gt(nrow(hits), 0L) + for (col in c("Title", "Contains")) { + testthat::expect_true(col %in% colnames(hits), info = col) + } + # accession columns are moved to the tail of the data frame + testthat::expect_true(grepl("Accession$", tail(colnames(hits), 1L))) +}) + +testthat::test_that("geo_search errors informatively on empty results", { + testthat::expect_error( + skip_if_search_unreachable( + geo_search("qqno-such-term-xyzzy[ALL] AND GDS[ETYP]", step = 5L) + ) + ) +}) diff --git a/tests/testthat/test-geo-url.R b/tests/testthat/test-geo-url.R new file mode 100644 index 0000000..ddaa24a --- /dev/null +++ b/tests/testthat/test-geo-url.R @@ -0,0 +1,38 @@ +testthat::test_that("geo_gtype classifies accessions with and without abbreviation", { + out <- geo_gtype(c("GSE10", "gpl98", "GSM1", "GDS505")) + testthat::expect_identical( + out, c("Series", "Platforms", "Samples", "Datasets") + ) + + abbre <- geo_gtype(c("GSE10", "gpl98", "GSM1", "GDS505"), TRUE) + testthat::expect_identical(abbre, c("GSE", "GPL", "GSM", "GDS")) +}) + +testthat::test_that("geo_gtype rejects non-character input", { + testthat::expect_error(geo_gtype(list("GSE10")), "character vector") +}) + +testthat::test_that("geo_url builds FTP and display URLs", { + # GSE defaults to the SOFT family file over HTTPS + testthat::expect_identical( + geo_url("GSE10"), + "https://ftp.ncbi.nlm.nih.gov/geo/series/GSEnnn/GSE10/soft/GSE10_family.soft.gz" # nolint + ) + + testthat::expect_identical( + geo_url("GSE10", "matrix"), + "https://ftp.ncbi.nlm.nih.gov/geo/series/GSEnnn/GSE10/matrix" + ) + + # plain FTP when https fronting is disabled + testthat::expect_identical( + geo_url("GSE10", ftp_over_https = FALSE), + "ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSEnnn/GSE10/soft/GSE10_family.soft.gz" # nolint + ) + + # Accession Display Bar URL for a GSM with full text view + testthat::expect_identical( + geo_url("GSM1", "text", "full", "self"), + "https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM1&targ=self&view=full&form=text" # nolint + ) +}) diff --git a/tests/testthat/test-log-trans.R b/tests/testthat/test-log-trans.R new file mode 100644 index 0000000..ee3e608 --- /dev/null +++ b/tests/testthat/test-log-trans.R @@ -0,0 +1,42 @@ +testthat::test_that("log_trans transforms linear matrices with pseudo offset", { + mat <- matrix(c(1, 8, 27, 64), nrow = 2) + out <- NULL + testthat::expect_message( + out <- log_trans(mat), + "Applying log2 transformation" + ) + testthat::expect_equal(out, log2(mat + 1)) + + out2 <- NULL + testthat::expect_message( + out2 <- log_trans(mat, pseudo = 2), + "pseudo count" + ) + testthat::expect_equal(out2, log2(mat + 2)) +}) + +testthat::test_that("log_trans keeps already log-scale data untouched", { + mat <- log2(outer(1:10, c(1, 10, 100, 1000))) + 5 + out <- NULL + testthat::expect_message( + out <- log_trans(mat), + "already log-transformed" + ) + testthat::expect_identical(out, mat) +}) + +testthat::test_that("log_trans handles ExpressionSet objects", { + testthat::skip_if_not_installed("Biobase") + mat <- matrix(c(1, 8, 27, 64, 125, 216), nrow = 2) + eset <- Biobase::ExpressionSet( + assayData = Biobase::assayDataNew(exprs = mat) + ) + out <- NULL + testthat::expect_message(out <- log_trans(eset)) + testthat::expect_s4_class(out, "ExpressionSet") + testthat::expect_equal( + Biobase::exprs(out), log2(mat + 1), + ignore_attr = "dimnames" + ) + testthat::expect_identical(dim(out), dim(eset)) +}) diff --git a/tests/testthat/test-phenodata.R b/tests/testthat/test-phenodata.R new file mode 100644 index 0000000..369c202 --- /dev/null +++ b/tests/testthat/test-phenodata.R @@ -0,0 +1,87 @@ +testthat::test_that("parse_sample_data expands characteristics columns", { + df <- data.frame( + geo_accession = c("GSM1", "GSM2"), + characteristics_ch1 = c("disease: yes", "disease: no"), + characteristics_ch1.1 = c("cell line: HeLa", "cell line: 293T"), + strain = c("C57BL/6", "C57BL/6"), + stringsAsFactors = FALSE + ) + out <- parse_sample_data(df) + + testthat::expect_identical(colnames(out), c( + "geo_accession", "characteristics_ch1", "ch1_disease", + "characteristics_ch1.1", "ch1_cell line", "strain" + )) + testthat::expect_identical(out$ch1_disease, c("yes", "no")) + testthat::expect_identical(out$`ch1_cell line`, c("HeLa", "293T")) + testthat::expect_identical(rownames(out), c("GSM1", "GSM2")) + # original characteristics columns are preserved + testthat::expect_identical(out$characteristics_ch1, df$characteristics_ch1) +}) + +testthat::test_that("parse_sample_data honors fields and sep arguments", { + df <- data.frame( + geo_accession = c("GSM1", "GSM2"), + characteristics_ch1 = c("disease=yes", "disease=no"), + stringsAsFactors = FALSE + ) + out <- parse_sample_data( + df, + fields = "characteristics_ch1", + sep = "=" + ) + testthat::expect_identical(colnames(out), c( + "geo_accession", "characteristics_ch1", "ch1_disease" + )) + testthat::expect_identical(out$ch1_disease, c("yes", "no")) +}) + +testthat::test_that("parse_sample_data skips low-quality characteristic columns", { + # only 1 of 3 values contains the separator -> below the 50% threshold + df <- data.frame( + geo_accession = c("GSM1", "GSM2", "GSM3"), + characteristics_ch1 = c("trait: yes", "no separator", "no separator"), + stringsAsFactors = FALSE + ) + out <- parse_sample_data(df) + testthat::expect_identical(colnames(out), c( + "geo_accession", "characteristics_ch1" + )) + testthat::expect_identical(rownames(out), c("GSM1", "GSM2", "GSM3")) +}) + +testthat::test_that("parse_sample_data expands non-contiguous characteristic columns", { + df <- data.frame( + geo_accession = c("GSM1", "GSM2"), + characteristics_ch1 = c("disease: yes", "disease: no"), + tissue = c("kidney", "kidney"), + characteristics_ch1.1 = c("cell line: HeLa", "cell line: 293T"), + strain = c("C57BL/6", "C57BL/6"), + stringsAsFactors = FALSE + ) + out <- parse_sample_data(df) + testthat::expect_identical(out$ch1_disease, c("yes", "no")) + testthat::expect_identical(out$`ch1_cell line`, c("HeLa", "293T")) +}) + +testthat::test_that("parse_sample_data returns input unchanged when no characteristics", { + df <- data.frame(geo_accession = "GSM1", trait = "x") + out <- parse_sample_data(df) + testthat::expect_identical(colnames(out), c("geo_accession", "trait")) + testthat::expect_identical(rownames(out), "GSM1") +}) + +testthat::test_that("parse_sample_data prefixes custom fields with the column name", { + # a field name without a "ch" suffix has no match group; it must not + # crash and should prefix parsed columns with the field name itself + df <- data.frame( + geo_accession = c("GSM1", "GSM2"), + custom_col = c("treatment: A", "treatment: B"), + stringsAsFactors = FALSE + ) + out <- parse_sample_data(df, fields = "custom_col") + testthat::expect_identical(colnames(out), c( + "geo_accession", "custom_col", "custom_col_treatment" + )) + testthat::expect_identical(out$custom_col_treatment, c("A", "B")) +}) diff --git a/tests/testthat/test-utils-str.R b/tests/testthat/test-utils-str.R new file mode 100644 index 0000000..73cd456 --- /dev/null +++ b/tests/testthat/test-utils-str.R @@ -0,0 +1,33 @@ +# str_match() is an internal base-R reimplementation of stringr::str_match(); +# lock down the semantics the package relies on, especially for non-matches +testthat::test_that("str_match returns one column per capture group on match", { + matched <- str_match("characteristics_ch1.2_3", "(ch\\d*)(\\.\\d*)?(_\\d*)?$") + testthat::expect_identical( + matched, + matrix(c("ch1.2_3", "ch1", ".2", "_3"), nrow = 1L) + ) +}) + +testthat::test_that("str_match pads non-matching input with all-NA rows", { + pattern <- "(ch\\d*)(\\.\\d*)?(_\\d*)?$" + + # a single non-match keeps one row; the width comes from any matching + # element, so here it degrades to a single all-NA column + no_match <- str_match("custom_col", pattern) + testthat::expect_identical(dim(no_match), c(1L, 1L)) + testthat::expect_true(all(is.na(no_match))) + + # in mixed input the width is taken from the matching element + mixed <- str_match(c("custom_col", "characteristics_ch1"), pattern) + testthat::expect_identical(dim(mixed), c(2L, 4L)) + testthat::expect_true(all(is.na(mixed[1L, ]))) + testthat::expect_identical(mixed[2L, ], c("ch1", "ch1", NA, NA)) +}) + +testthat::test_that("str_match handles groupless patterns and empty input", { + plain <- str_match(c("abc", "xyz"), "a") + testthat::expect_identical(dim(plain), c(2L, 1L)) + testthat::expect_identical(plain[, 1L], c("a", NA)) + + testthat::expect_null(str_match(character(0), "a")) +})