1
0
mirror of https://github.com/msberends/AMR.git synced 2025-01-30 06:24:36 +01:00

(v2.1.1.9129) unit test fix

This commit is contained in:
dr. M.S. (Matthijs) Berends 2025-01-27 16:17:03 +01:00
parent 6efa317a81
commit 1149360b27
No known key found for this signature in database
66 changed files with 94 additions and 80 deletions

View File

@ -1,5 +1,5 @@
Package: AMR
Version: 2.1.1.9128
Version: 2.1.1.9129
Date: 2025-01-27
Title: Antimicrobial Resistance Data Analysis
Description: Functions to simplify and standardise antimicrobial resistance (AMR)
@ -46,6 +46,7 @@ Suggests:
rmarkdown,
rvest,
skimr,
testthat,
tibble,
tidymodels,
tidyselect,

View File

@ -1,4 +1,4 @@
# AMR 2.1.1.9128
# AMR 2.1.1.9129
*(this beta version will eventually become v3.0. We're happy to reach a new major milestone soon, which will be all about the new One Health support! Install this beta using [the instructions here](https://msberends.github.io/AMR/#latest-development-version).)*

View File

@ -1,6 +1,6 @@
Metadata-Version: 2.2
Name: AMR
Version: 2.1.1.9128
Version: 2.1.1.9129
Summary: A Python wrapper for the AMR R package
Home-page: https://github.com/msberends/AMR
Author: Matthijs Berends

View File

@ -1,7 +1,3 @@
BLUE = '\033[94m'
GREEN = '\033[32m'
RESET = '\033[0m'
import os
import sys
from rpy2 import robjects
@ -17,18 +13,22 @@ venv_path = sys.prefix
r_lib_path = os.path.join(venv_path, "R_libs")
# Ensure the R library path exists
os.makedirs(r_lib_path, exist_ok=True)
# Set the R library path in .libPaths
base = importr('base')
# Turn off warnings
base.options(warn = -1)
base._libPaths(r_lib_path)
# Import base and utils
base = importr('base')
utils = importr('utils')
# Override R library paths globally for the session
robjects.r(f'.Library <- "{r_lib_path}"') # Replace default library
robjects.r(f'.Library.site <- "{r_lib_path}"') # Replace site-specific library
base._libPaths(r_lib_path) # Override .libPaths() as well
# Get the effective library path
r_amr_lib_path = base._libPaths()[0]
# Check if the AMR package is installed in R
if not isinstalled('AMR', lib_loc = r_amr_lib_path):
utils = importr('utils')
print(f"{BLUE}AMR:{RESET} Installing AMR package to {BLUE}{r_amr_lib_path}/{RESET}...", flush=True)
if not isinstalled('AMR', lib_loc=r_amr_lib_path):
print(f"AMR: Installing latest AMR R package to {r_amr_lib_path}...", flush=True)
utils.install_packages('AMR', repos='https://msberends.r-universe.dev', quiet=True)
# Python package version of AMR
@ -43,16 +43,12 @@ r_amr_version = robjects.r(f'as.character(packageVersion("AMR", lib.loc = "{r_li
# Compare R and Python package versions
if r_amr_version != python_amr_version:
try:
print(f"{BLUE}AMR:{RESET} Updating AMR package in {BLUE}{r_amr_lib_path}/{RESET}...", flush=True)
utils = importr('utils')
print(f"AMR: Updating AMR package in {r_amr_lib_path}...", flush=True)
utils.install_packages('AMR', repos='https://msberends.r-universe.dev', quiet=True)
except Exception as e:
print(f"{BLUE}AMR:{RESET} Could not update: {e}{RESET}", flush=True)
print(f"AMR: Could not update: {e}", flush=True)
# Restore warnings to default
base.options(warn = 0)
print(f"{BLUE}AMR:{RESET} Setting up R environment and AMR datasets...", flush=True)
print(f"AMR: Setting up R environment and AMR datasets...", flush=True)
# Activate the automatic conversion between R and pandas DataFrames
pandas2ri.activate()
@ -77,4 +73,4 @@ microorganisms = pandas2ri.rpy2py(robjects.r('AMR::microorganisms[, !sapply(AMR:
antibiotics = pandas2ri.rpy2py(robjects.r('AMR::antibiotics[, !sapply(AMR::antibiotics, is.list)]'))
clinical_breakpoints = pandas2ri.rpy2py(robjects.r('AMR::clinical_breakpoints[, !sapply(AMR::clinical_breakpoints, is.list)]'))
print(f"{BLUE}AMR:{RESET} {GREEN}Done.{RESET}", flush=True)
print(f"AMR: Done.", flush=True)

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -2,7 +2,7 @@ from setuptools import setup, find_packages
setup(
name='AMR',
version='2.1.1.9128',
version='2.1.1.9129',
packages=find_packages(),
install_requires=[
'rpy2',

View File

@ -165,6 +165,7 @@ globalVariables(c(
"lang",
"language",
"lookup",
"lower",
"method",
"mic ",
"mic",
@ -198,6 +199,7 @@ globalVariables(c(
"total",
"txt",
"type",
"upper",
"uti_index",
"value",
"varname",

View File

@ -60,7 +60,7 @@
#'
#' For estimating antimicrobial coverage, especially when creating a WISCA, the outcome might become more reliable by only including the top *n* species encountered in the data. You can filter on this top *n* using [top_n_microorganisms()]. For example, use `top_n_microorganisms(your_data, n = 10)` as a pre-processing step to only include the top 10 species in the data.
#'
#' The numeric values of an antibiogram are stored in a long format as the [attribute] `long_numeric`. You can retrieve them using `attributes(x)$long_numeric`, where `x` is the outcome of [antibiogram()] or [wisca()]. This is ideal for e.g. advanced plotting.
#' The numeric values of an antibiogram are stored in a long format as the [attribute][attributes()] `long_numeric`. You can retrieve them using `attributes(x)$long_numeric`, where `x` is the outcome of [antibiogram()] or [wisca()]. This is ideal for e.g. advanced plotting.
#'
#' ### Formatting Type
#'

View File

@ -36,6 +36,7 @@
#' @param remove_intrinsic_resistant [logical] to indicate that rows and columns with 100% resistance for all tested antimicrobials must be removed from the table
#' @param FUN the function to call on the `mo` column to transform the microorganism codes - the default is [mo_shortname()]
#' @param translate_ab a [character] of length 1 containing column names of the [antibiotics] data set
#' @param include_n_rows a [logical] to indicate if the total number of rows must be included in the output
#' @param ... arguments passed on to `FUN`
#' @inheritParams sir_df
#' @inheritParams base::formatC
@ -182,8 +183,8 @@ bug_drug_combinations <- function(x,
out <- out[, colnames(out)[colnames(out) != "total_rows"], drop = FALSE]
}
out <- out %pm>% pm_arrange(mo, ab)
out <- as_original_data_class(out, class(x.bak)) # will remove tibble groups
out <- out %pm>% pm_arrange(mo, ab)
rownames(out) <- NULL
structure(out, class = c("bug_drug_combinations", if(data_has_groups) "grouped" else NULL, class(out)))
}

View File

@ -261,7 +261,7 @@ ggplot_pca <- function(x,
type = "open"
),
colour = arrows_colour,
size = arrows_size,
linewidth = arrows_size,
alpha = arrows_alpha
)
if (arrows_textangled == TRUE) {

View File

@ -36,7 +36,7 @@
#' @param n_for_each an optional integer specifying the maximum number of rows to retain for each value of the selected property. If `NULL`, all rows within the top *n* groups will be included.
#' @param col_mo A character string indicating the column in `x` that contains microorganism names or codes. Defaults to the first column of class [`mo`]. Values will be coerced using [as.mo()].
#' @param ... Additional arguments passed on to [mo_property()] when `property` is not `NULL`.
#' @details This function is useful for preprocessing data before creating [antibiograms][antibiograms()] or other analyses that require focused subsets of microbial data. For example, it can filter a data set to only include isolates from the top 10 species.
#' @details This function is useful for preprocessing data before creating [antibiograms][antibiogram()] or other analyses that require focused subsets of microbial data. For example, it can filter a data set to only include isolates from the top 10 species.
#' @export
#' @seealso [mo_property()], [as.mo()], [antibiogram()]
#' @examples

View File

@ -42,10 +42,6 @@ description_file="../DESCRIPTION"
# Write header to the datasets Python file, including the convert_to_python function
cat <<EOL > "$datasets_file"
BLUE = '\033[94m'
GREEN = '\033[32m'
RESET = '\033[0m'
import os
import sys
from rpy2 import robjects
@ -61,18 +57,22 @@ venv_path = sys.prefix
r_lib_path = os.path.join(venv_path, "R_libs")
# Ensure the R library path exists
os.makedirs(r_lib_path, exist_ok=True)
# Set the R library path in .libPaths
base = importr('base')
# Turn off warnings
base.options(warn = -1)
base._libPaths(r_lib_path)
# Import base and utils
base = importr('base')
utils = importr('utils')
# Override R library paths globally for the session
robjects.r(f'.Library <- "{r_lib_path}"') # Replace default library
robjects.r(f'.Library.site <- "{r_lib_path}"') # Replace site-specific library
base._libPaths(r_lib_path) # Override .libPaths() as well
# Get the effective library path
r_amr_lib_path = base._libPaths()[0]
# Check if the AMR package is installed in R
if not isinstalled('AMR', lib_loc = r_amr_lib_path):
utils = importr('utils')
print(f"{BLUE}AMR:{RESET} Installing AMR package to {BLUE}{r_amr_lib_path}/{RESET}...", flush=True)
if not isinstalled('AMR', lib_loc=r_amr_lib_path):
print(f"AMR: Installing latest AMR R package to {r_amr_lib_path}...", flush=True)
utils.install_packages('AMR', repos='https://msberends.r-universe.dev', quiet=True)
# Python package version of AMR
@ -87,16 +87,12 @@ r_amr_version = robjects.r(f'as.character(packageVersion("AMR", lib.loc = "{r_li
# Compare R and Python package versions
if r_amr_version != python_amr_version:
try:
print(f"{BLUE}AMR:{RESET} Updating AMR package in {BLUE}{r_amr_lib_path}/{RESET}...", flush=True)
utils = importr('utils')
print(f"AMR: Updating AMR package in {r_amr_lib_path}...", flush=True)
utils.install_packages('AMR', repos='https://msberends.r-universe.dev', quiet=True)
except Exception as e:
print(f"{BLUE}AMR:{RESET} Could not update: {e}{RESET}", flush=True)
print(f"AMR: Could not update: {e}", flush=True)
# Restore warnings to default
base.options(warn = 0)
print(f"{BLUE}AMR:{RESET} Setting up R environment and AMR datasets...", flush=True)
print(f"AMR: Setting up R environment and AMR datasets...", flush=True)
# Activate the automatic conversion between R and pandas DataFrames
pandas2ri.activate()
@ -121,7 +117,7 @@ microorganisms = pandas2ri.rpy2py(robjects.r('AMR::microorganisms[, !sapply(AMR:
antibiotics = pandas2ri.rpy2py(robjects.r('AMR::antibiotics[, !sapply(AMR::antibiotics, is.list)]'))
clinical_breakpoints = pandas2ri.rpy2py(robjects.r('AMR::clinical_breakpoints[, !sapply(AMR::clinical_breakpoints, is.list)]'))
print(f"{BLUE}AMR:{RESET} {GREEN}Done.{RESET}", flush=True)
print(f"AMR: Done.", flush=True)
EOL
echo "from .datasets import example_isolates" >> $init_file

View File

@ -1,5 +1,5 @@
This files contains all context you must know about the AMR package for R.
First and foremost, you are trained on version 2.1.1.9128. Remember this whenever someone asks which AMR package version youre at.
First and foremost, you are trained on version 2.1.1.9129. Remember this whenever someone asks which AMR package version youre at.
--------------------------------
THE PART HEREAFTER CONTAINS CONTENTS FROM FILE 'NAMESPACE':
@ -1705,7 +1705,7 @@ This function returns a table with values between 0 and 100 for \emph{susceptibi
For estimating antimicrobial coverage, especially when creating a WISCA, the outcome might become more reliable by only including the top \emph{n} species encountered in the data. You can filter on this top \emph{n} using \code{\link[=top_n_microorganisms]{top_n_microorganisms()}}. For example, use \code{top_n_microorganisms(your_data, n = 10)} as a pre-processing step to only include the top 10 species in the data.
The numeric values of an antibiogram are stored in a long format as the \link{attribute} \code{long_numeric}. You can retrieve them using \code{attributes(x)$long_numeric}, where \code{x} is the outcome of \code{\link[=antibiogram]{antibiogram()}} or \code{\link[=wisca]{wisca()}}. This is ideal for e.g. advanced plotting.
The numeric values of an antibiogram are stored in a long format as the \link[=attributes]{attribute} \code{long_numeric}. You can retrieve them using \code{attributes(x)$long_numeric}, where \code{x} is the outcome of \code{\link[=antibiogram]{antibiogram()}} or \code{\link[=wisca]{wisca()}}. This is ideal for e.g. advanced plotting.
\subsection{Formatting Type}{
The formatting of the 'cells' of the table can be set with the argument \code{formatting_type}. In these examples, \code{5} is the susceptibility percentage (for WISCA: \code{4-6} indicates the confidence level), \code{15} the numerator, and \code{300} the denominator:
@ -3900,6 +3900,8 @@ bug_drug_combinations(x, col_mo = NULL, FUN = mo_shortname,
\item{FUN}{the function to call on the \code{mo} column to transform the microorganism codes - the default is \code{\link[=mo_shortname]{mo_shortname()}}}
\item{include_n_rows}{a \link{logical} to indicate if the total number of rows must be included in the output}
\item{...}{arguments passed on to \code{FUN}}
\item{translate_ab}{a \link{character} of length 1 containing column names of the \link{antibiotics} data set}
@ -8027,7 +8029,7 @@ top_n_microorganisms(x, n, property = "fullname", n_for_each = NULL,
This function filters a data set to include only the top \emph{n} microorganisms based on a specified property, such as taxonomic family or genus. For example, it can filter a data set to the top 3 species, or to any species in the top 5 genera, or to the top 3 species in each of the top 5 genera.
}
\details{
This function is useful for preprocessing data before creating \link[=antibiograms]{antibiograms} or other analyses that require focused subsets of microbial data. For example, it can filter a data set to only include isolates from the top 10 species.
This function is useful for preprocessing data before creating \link[=antibiogram]{antibiograms} or other analyses that require focused subsets of microbial data. For example, it can filter a data set to only include isolates from the top 10 species.
}
\examples{
# filter to the top 3 species:

View File

@ -2210,6 +2210,6 @@ devtools::load_all(".")
# run the unit tests
Sys.setenv(NOT_CRAN = "true")
testthat::test_file("inst/tinytest/test-data.R")
testthat::test_file("inst/tinytest/test-mo.R")
testthat::test_file("inst/tinytest/test-mo_property.R")
testthat::test_file("inst/tests/testthat/test-data.R")
testthat::test_file("inst/tests/testthat/test-mo.R")
testthat::test_file("inst/tests/testthat/test-mo_property.R")

View File

@ -27,6 +27,15 @@
# how to conduct AMR data analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
tryCatch(!is.function(expect_stout), error = function(e) TRUE) {
expect_stout <<- testthat::expect_output
}
tryCatch(!is.function(expect_inherits), error = function(e) TRUE) {
expect_inherits <<- function(x, y, ...) testthat::expect(inherits(x, y),
failure_message = paste0("Expected class ", paste(y, collapse = "/"),
", got class ", paste(class(x), collapse = "/")))
}
expect_equal(AMR:::percentage(0.25), "25%")
expect_equal(AMR:::percentage(0.5), "50%")
expect_equal(AMR:::percentage(0.500, digits = 1), "50.0%")

View File

@ -37,7 +37,7 @@ suppressMessages(
species = "asburiae/cloacae")
)
)
expect_identical(as.character(as.mo("ENT_ASB_CLO")), "ENT_ASB_CLO")
expect_identical(mo_name("ENT_ASB_CLO"), "Enterobacter asburiae/cloacae")
expect_identical(mo_gramstain("ENT_ASB_CLO", language = NULL), "Gram-negative")

View File

@ -43,13 +43,15 @@ if (AMR:::pkg_is_available("dplyr", min_version = "1.0.0", also_load = TRUE) &&
summarise_all(resistance) %>%
as.double()
)
expect_stdout(print(example_isolates %>%
select(AMC, CIP) %>%
ggplot_sir(x = "interpretation", facet = "antibiotic")))
expect_stdout(print(example_isolates %>%
select(AMC, CIP) %>%
ggplot_sir(x = "antibiotic", facet = "interpretation")))
expect_inherits(example_isolates %>%
select(AMC, CIP) %>%
ggplot_sir(x = "interpretation", facet = "antibiotic"),
"gg")
expect_inherits(example_isolates %>%
select(AMC, CIP) %>%
ggplot_sir(x = "antibiotic", facet = "interpretation"),
"gg")
expect_equal(
(example_isolates %>%

View File

@ -100,7 +100,7 @@ This function returns a table with values between 0 and 100 for \emph{susceptibi
For estimating antimicrobial coverage, especially when creating a WISCA, the outcome might become more reliable by only including the top \emph{n} species encountered in the data. You can filter on this top \emph{n} using \code{\link[=top_n_microorganisms]{top_n_microorganisms()}}. For example, use \code{top_n_microorganisms(your_data, n = 10)} as a pre-processing step to only include the top 10 species in the data.
The numeric values of an antibiogram are stored in a long format as the \link{attribute} \code{long_numeric}. You can retrieve them using \code{attributes(x)$long_numeric}, where \code{x} is the outcome of \code{\link[=antibiogram]{antibiogram()}} or \code{\link[=wisca]{wisca()}}. This is ideal for e.g. advanced plotting.
The numeric values of an antibiogram are stored in a long format as the \link[=attributes]{attribute} \code{long_numeric}. You can retrieve them using \code{attributes(x)$long_numeric}, where \code{x} is the outcome of \code{\link[=antibiogram]{antibiogram()}} or \code{\link[=wisca]{wisca()}}. This is ideal for e.g. advanced plotting.
\subsection{Formatting Type}{
The formatting of the 'cells' of the table can be set with the argument \code{formatting_type}. In these examples, \code{5} is the susceptibility percentage (for WISCA: \code{4-6} indicates the confidence level), \code{15} the numerator, and \code{300} the denominator:

View File

@ -21,6 +21,8 @@ bug_drug_combinations(x, col_mo = NULL, FUN = mo_shortname,
\item{FUN}{the function to call on the \code{mo} column to transform the microorganism codes - the default is \code{\link[=mo_shortname]{mo_shortname()}}}
\item{include_n_rows}{a \link{logical} to indicate if the total number of rows must be included in the output}
\item{...}{arguments passed on to \code{FUN}}
\item{translate_ab}{a \link{character} of length 1 containing column names of the \link{antibiotics} data set}

View File

@ -24,7 +24,7 @@ top_n_microorganisms(x, n, property = "fullname", n_for_each = NULL,
This function filters a data set to include only the top \emph{n} microorganisms based on a specified property, such as taxonomic family or genus. For example, it can filter a data set to the top 3 species, or to any species in the top 5 genera, or to the top 3 species in each of the top 5 genera.
}
\details{
This function is useful for preprocessing data before creating \link[=antibiograms]{antibiograms} or other analyses that require focused subsets of microbial data. For example, it can filter a data set to only include isolates from the top 10 species.
This function is useful for preprocessing data before creating \link[=antibiogram]{antibiograms} or other analyses that require focused subsets of microbial data. For example, it can filter a data set to only include isolates from the top 10 species.
}
\examples{
# filter to the top 3 species:

View File

@ -27,21 +27,25 @@
# how to conduct AMR data analysis: https://msberends.github.io/AMR/ #
# ==================================================================== #
# we use {tinytest} instead of {testthat} because it does not rely on recent R versions - we want to test on R >= 3.0.
# we use {tinytest} for older R versions to allow unit testing in R >= 3.0.0.
# Run them in RStudio using:
# rstudioapi::jobRunScript("tests/tinytest.R", name = "AMR Unit Tests", workingDir = getwd(), exportEnv = "tinytest_results")
# use this to quickly use testtthat for more informative errors:
# testthat::test_dir("inst/tests")
# test only on GitHub Actions and at using RStudio jobs - not on CRAN as tests are lengthy
if (tryCatch(isTRUE(AMR:::import_fn("isJob", "rstudioapi")()), error = function(e) FALSE) ||
identical(Sys.getenv("R_RUN_TINYTEST"), "true")) {
# env var 'R_LIBS_USER' got overwritten during 'R CMD check' in GitHub Actions, so:
# test only on GitHub Actions - not on CRAN as tests are lengthy
if (identical(Sys.getenv("R_RUN_TINYTEST"), "true")) {
# env var 'R_LIBS_USER' gets overwritten during 'R CMD check' in GitHub Actions, so:
.libPaths(c(Sys.getenv("R_LIBS_USER_GH_ACTIONS"), .libPaths()))
if (AMR:::pkg_is_available("tinytest", also_load = TRUE)) {
# load the package
library(AMR)
# set language
set_AMR_locale("English")
# set some functions if on old R
# set some functions for older R versions
if (getRversion() < "3.2.0") {
anyNA <- AMR:::anyNA
dir.exists <- AMR:::dir.exists
@ -64,16 +68,15 @@ if (tryCatch(isTRUE(AMR:::import_fn("isJob", "rstudioapi")()), error = function(
if (getRversion() < "4.0.0") {
deparse1 <- AMR:::deparse1
}
# start the unit tests
suppressMessages(
out <- test_package("AMR",
testdir = ifelse(dir.exists("inst/tinytest"),
"inst/tinytest",
"tinytest"
),
verbose = FALSE,
color = FALSE
testdir = ifelse(dir.exists("inst/tests"),
"inst/tests",
"tests"
),
verbose = FALSE,
color = FALSE
)
)
cat("\n\nSUMMARY:\n")