Files
AMR/R/interpretive_rules.R
T
Matthijs BerendsandClaude Opus 5.5 0ca43df459 Update taxonomy of microorganisms (2026-10) (#312)
* Update taxonomy of microorganisms (2026-10)

Rebuild of the microorganisms data set from COL 2026-04-18 XR, LPSN and BacDive of October 2026
and MycoBank of January 2026, with v3.0.1 as the previous data set: 111,103 records (v3.0.1:
78,679), 0 changed MO codes of existing names, 522 released codes retired (275 to be reviewed).

Script fixes (data-raw/_reproduction_scripts/reproduction_of_microorganisms.R):
- previous data set from the last release; COL read as COL Data Package (NameUsage.tsv)
- keep COL records without authors (a filter on NA dropped them, e.g. Balamuthia mandrillaris)
- genus homonyms: unclassified MycoBank entries are not authoritative; the released domain of a
  genus wins if a source supports it (e.g. Moorella, Serpula, Pirella stay Bacteria)
- protect current names of relevant species instead of whole current genera (data set tripled)
- current names and synonyms only within the same domain and for known names (Brugia -> Lycoperdon)
- MycoBank names in Latin script only; old records outside their source's scope become manually added
- Graphium butterflies of v3.0.1 are not carried over, re-added or restored
- restore released taxa by name and rank; retire older cross-domain homonyms for review
- fill empty families from COL and a commented override list (Ascaris, Balamuthia)
- add Brugia malayi and B. timori; remove Salmonella species synonyms that are serovars
- BacDive: a minority of facultative strain records no longer decides (C. difficile)
- translate codes of other data sets with the development version; review unmatched codes
- scope decisions: COL XR names only if relevant or released; Protozoa follow the Fungi rules

Also: all checkpoints (data-raw/taxonomy*.rds), updated data sets, Bartlett et al. list, accessed
dates in TAXONOMY_VERSION, NEWS, two staphylococci added to CoNS, tests updated for real taxonomic
changes, known defects file removed (all solved), and the findings report with all review files in
data-raw/taxonomy_review/2026-10/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Taxonomy review report: note on the .dta export and the single commit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fix as.mo() for Salmonella serovars written with the species; add S. xeri to CoNS

- "Salmonella enterica (subsp. enterica) serovar Typhi" returned S. bongori, and
  "S. enterica Typhimurium" S. enterica diarizonae; "Paratyphi A/B/C" became serogroups
- Staphylococcus xeri and S. parequorum confirmed as coagulase-negative

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Taxonomy build: remove lichens (decision of 5 October 2026)

Fungi in the lichen-forming classes and the order Verrucariales are removed unless their genus is
clinically relevant, with the synonyms that point to them (4,155 records); released lichens are
restored. microorganisms now has 107,126 records (Fungi 45,739); all tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Taxonomy review decisions: microsporidia in Fungi, accepted names, missing protozoa

- all microsporidia in the Fungi (1,394 names of v3.0.1 from P_ to F_, old codes translated by name)
- Enterocytozoon bieneusi and Encephalitozoon cuniculi as accepted names (accepted_name_override)
- Balantidium and Isospora added to MO_RELEVANT_GENERA; Cystoisospora belli as synonym of Isospora belli
- synonym cycles decided: Capillidium and Scolecobasidium are the current genera
- removed the stale data-raw/taxonomy_lpsn0.rds
- microorganisms now has 107,253 records; all tests pass

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Taxonomy review report: all items reviewed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rule matching by accepted taxon; Erysipelatoclostridium as synonym of Thomasclavelia

- interpretive_rules(): species named in a rule (literal names, genus_species/fullname) now also match all other
  names of the same accepted taxon, e.g. 'Clostridium ramosum' for Thomasclavelia ramosa; not for genera or regex rules
- Erysipelatoclostridium and its species are synonyms of Thomasclavelia (accepted_name_override); E. merdavium is
  retired by decision of 6 October 2026, and the build removes taxa retired by a human decision
- microorganisms patched with the same logic as the build script (no full rebuild): 107,252 records
- intrinsic_resistant regenerated with the new taxonomy and rule matching: 308,646 rows
- clinical_breakpoints: EUCAST workbook rows merged again, 24 EUCAST 2026 rows moved from C. ramosum to T. ramosa

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Taxonomy: correct records for names listed twice, no synonyms without a current name, strict data tests

- one record per name keeps the accepted record (e.g. Eggerthella lenta, Gordonia amarae, Anisakis simplex and
  Enterobius vermicularis were synonyms without a current name), links to dropped records are moved
- LPSN lookup reads the taxonomic status and correct name; validly published synonyms are no longer 'accepted'
- synonyms without a current name: linked via LPSN or removed, released codes retired (3,668); records with kept
  children become 'unknown'; the M. tuberculosis complex is protected (decisions of 7 October 2026)
- subspecies codes reserved, current names of synonyms kept when pruning, missing parent records added or moved,
  higher taxonomy harmonised, shared identifiers resolved per domain and rank, pointers and parent links cleaned
- data sets refer only to current names (except intrinsic_resistant); group members only from current names;
  internal CoNS/CoPS/streptococcal lists keep a synonym only with its current name
- intrinsic_resistant, clinical_breakpoints (EUCAST workbooks) and microorganisms.groups regenerated
- 28 new tests in test-data.R; devtools::test(): 1,581 expectations, 0 failures
- open decisions listed in data-raw/taxonomy_review/2026-10/REPORT.md, section 6

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Taxonomy: protect WHO priority genera, follow LPSN for the M. tuberculosis complex, place protist groups in one domain

- all taxa of the genera in MO_WHO_PRIORITY_GENERA are protected, also names that are not validly published
  (replaces the hard-coded M. tuberculosis complex; keeps e.g. Klebsiella quasivariicola, M. canettii, M. orygis)
- LPSN is followed for the M. tuberculosis complex: M. bovis, M. africanum, M. caprae, M. microti and M. pinnipedii
  are heterotypic synonyms of M. tuberculosis (Riojas et al. 2018); a test enforces this
- labyrinthulids in the Chromista (Aplanochytrium), Dictydiaethalium in the Protozoa (genus_domain_move), and the
  rank suffix also between domains ('Acantharia {class}' next to the fungal genus Acantharia)
- devtools::test(): 1,582 expectations, 0 failures

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Taxonomy build no longer depends on the previous build

- intrinsic_resistant is no input of the microorganisms build anymore (it is computed from it); the genera named in
  the interpretive rules are read from the rules instead
- the previous data set no longer makes genera relevant; Debaryomyces added to MO_RELEVANT_GENERA
- new run_after_microorganisms_build.R recreates microorganisms.groups, the EUCAST breakpoints and
  intrinsic_resistant in the right order, and the build runs it at its end
- reproduction_of_intrinsic_resistant.R uses devtools::load_all() instead of the installed package
- effect: 24 never released, not relevant COL records less; devtools::test(): 1,582 expectations, 0 failures

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Taxonomy review report: summary updated to the second round

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* MO code retirements: mark the 265 reviewed retirements as reviewed

The Graphium and v2.x Protozoa retirements were reviewed and accepted on 6 October 2026 (see the taxonomy review
report, section 5); 'NEEDS REVIEW' is replaced by 'reviewed by Matthijs S. Berends on 2026-10-06'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 12:55:12 +02:00

1354 lines
59 KiB
R
Executable File

# ==================================================================== #
# TITLE: #
# AMR: An R Package for Working with Antimicrobial Resistance Data #
# #
# SOURCE CODE: #
# https://github.com/msberends/AMR #
# #
# PLEASE CITE THIS SOFTWARE AS: #
# Berends MS, Luz CF, Friedrich AW, et al. (2022). #
# AMR: An R Package for Working with Antimicrobial Resistance Data. #
# Journal of Statistical Software, 104(3), 1-31. #
# https://doi.org/10.18637/jss.v104.i03 #
# #
# Developed at the University of Groningen and the University Medical #
# Center Groningen in the Netherlands, in collaboration with many #
# colleagues from around the world, see our website. #
# #
# This R package is free software; you can freely use and distribute #
# it for both personal and commercial purposes under the terms of the #
# GNU General Public License version 2.0 (GNU GPL-2), as published by #
# the Free Software Foundation. #
# We created this package for both routine data analysis and academic #
# research and it was publicly released in the hope that it will be #
# useful, but it comes WITHOUT ANY WARRANTY OR LIABILITY. #
# #
# Visit our website for the full manual and a complete tutorial about #
# how to conduct AMR data analysis: https://amr-for-r.org #
# ==================================================================== #
# ====================================================== #
# || Change the EUCAST version numbers in R/globals.R || #
# ====================================================== #
format_eucast_version_nr <- function(version, markdown = TRUE) {
# for documentation - adds title, version number, year and url in markdown language
lst <- c(EUCAST_VERSION_BREAKPOINTS, EUCAST_VERSION_EXPECTED_PHENOTYPES, EUCAST_VERSION_EXPERT_RULES)
version <- format(unique(version), nsmall = 1)
txt <- character(0)
for (i in seq_len(length(version))) {
v <- version[i]
if (markdown == TRUE) {
txt <- c(txt, paste0(
"[", lst[[v]]$title, " ", lst[[v]]$version_txt, "](", lst[[v]]$url, ")",
" (", lst[[v]]$year, ")"
))
} else {
txt <- c(txt, paste0(
lst[[version]]$title, " ", lst[[v]]$version_txt,
" (", lst[[v]]$year, ")"
))
}
}
vector_and(txt, quotes = FALSE)
}
#' Apply Interpretive Rules
#'
#' @description
#' Apply rules from clinical breakpoints notes and expected resistant phenotypes as defined by e.g. the European Committee on Antimicrobial Susceptibility Testing (EUCAST, <https://www.eucast.org>), see *Source*. Use [eucast_dosage()] to get a [data.frame] with advised dosages of a certain bug-drug combination, which is based on the [dosage] data set.
#'
#' To improve the interpretation of the antibiogram before CLSI/EUCAST interpretive rules are applied, some AMR-specific rules can be applied at default, see *Details*.
#' @param x A data set with antimicrobials columns, such as `amox`, `AMX` and `AMC`.
#' @param info A [logical] to indicate whether progress should be printed to the console - the default is only print while in interactive sessions.
#' @param guideline A guideline name, either "EUCAST" (default) or "CLSI". This can be set with the package option [`AMR_guideline`][AMR-options].
#' @param rules A [character] vector that specifies which rules should be applied. Must be one or more of `"breakpoints"`, `"expected_phenotypes"`, `"expert"`, `"other"`, `"custom"`, `"all"`, and defaults to `c("breakpoints", "expected_phenotypes")`. The default value can be set to another value using the package option [`AMR_interpretive_rules`][AMR-options]: `options(AMR_interpretive_rules = "all")`. If using `"custom"`, be sure to fill in argument `custom_rules` too. Custom rules can be created with [custom_interpretive_rules()].
#' @param verbose A [logical] to turn Verbose mode on and off (default is off). In Verbose mode, the function does not apply rules to the data, but instead returns a data set in logbook form with extensive info about which rows and columns would be effected and in which way. Using Verbose mode takes a lot more time.
#' @param version_breakpoints The version number to use for the EUCAST Clinical Breakpoints guideline. Can be `r vector_or(names(EUCAST_VERSION_BREAKPOINTS), documentation = TRUE, reverse = TRUE)`.
#' @param version_expected_phenotypes The version number to use for the EUCAST Expected Phenotypes. Can be `r vector_or(names(EUCAST_VERSION_EXPECTED_PHENOTYPES), documentation = TRUE, reverse = TRUE)`.
#' @param version_expertrules The version number to use for the EUCAST Expert Rules and Intrinsic Resistance guideline. Can be `r vector_or(names(EUCAST_VERSION_EXPERT_RULES), documentation = TRUE, reverse = TRUE)`.
#' @param ampc_cephalosporin_resistance (only applies when `rules` contains `"expert"` or `"all"`) a [character] value that should be applied to cefotaxime, ceftriaxone and ceftazidime for AmpC de-repressed cephalosporin-resistant mutants - the default is `NA`. Currently only works when `version_expertrules` is `3.2` and higher; these versions of '*EUCAST Expert Rules on Enterobacterales*' state that results of cefotaxime, ceftriaxone and ceftazidime should be reported with a note, or results should be suppressed (emptied) for these three drugs. A value of `NA` (the default) for this argument will remove results for these three drugs, while e.g. a value of `"R"` will make the results for these drugs resistant. Use `NULL` or `FALSE` to not alter results for these three drugs of AmpC de-repressed cephalosporin-resistant mutants. Using `TRUE` is equal to using `"R"`. \cr For *EUCAST Expert Rules* v3.2, this rule applies to: `r vector_and(gsub("[^a-zA-Z ]+", "", unlist(strsplit(INTERPRETIVE_RULES_DF[which(INTERPRETIVE_RULES_DF$reference.version %in% c(3.2, 3.3) & INTERPRETIVE_RULES_DF$reference.rule %like% "ampc"), "this_value"][1], "|", fixed = TRUE))), quotes = "*")`.
#' @param ... Column names of antimicrobials. To automatically detect antimicrobial column names, do not provide any named arguments; [guess_ab_col()] will then be used for detection. To manually specify a column, provide its name (case-insensitive) as an argument, e.g. `AMX = "amoxicillin"`. To skip a specific antimicrobial, set it to `NULL`, e.g. `TIC = NULL` to exclude ticarcillin. If a manually defined column does not exist in the data, it will be skipped with a warning.
#' @param ab Any (vector of) text that can be coerced to a valid antimicrobial drug code with [as.ab()].
#' @param administration Route of administration, either `r vector_or(dosage$administration, documentation = TRUE)`.
#' @param only_sir_columns A [logical] to indicate whether only antimicrobial columns must be included that were transformed to class [sir][as.sir()] on beforehand. Defaults to `FALSE` if no columns of `x` have a class [sir][as.sir()].
#' @param custom_rules Custom rules to apply, created with [custom_interpretive_rules()].
#' @param overwrite A [logical] indicating whether to overwrite existing SIR values (default: `FALSE`). When `FALSE`, only non-SIR values are modified (i.e., any value that is not already S, I or R). To ensure compliance with EUCAST guidelines, **this should remain** `FALSE`, as EUCAST notes often state that an organism "should be tested for susceptibility to individual agents or be reported resistant".
#' @param add_if_missing A [logical] indicating whether rules should also be applied to missing (`NA`) values (default: `TRUE`). When `FALSE`, rules are only applied to cells that already contain an SIR value; cells with `NA` are left untouched. This is particularly useful when using `overwrite = TRUE` with custom rules and you want to update reported results without imputing values for untested drugs.
#' @inheritParams first_isolate
#' @details
#' **Note:** This function does not translate MIC or disk values to SIR values. Use [as.sir()] for that. \cr
#' **Note:** When ampicillin (AMP, J01CA01) is not available but amoxicillin (AMX, J01CA04) is, the latter will be used for all rules where there is a dependency on ampicillin. These drugs are interchangeable when it comes to expression of antimicrobial resistance. \cr
#'
#' The file containing all interpretive rules is located here: <https://github.com/msberends/AMR/blob/main/data-raw/interpretive_rules.tsv>. **Note:** Old taxonomic names are replaced with the current taxonomy where applicable. For example, *Ochrobactrum anthropi* was renamed to *Brucella anthropi* in 2020; older interpretive rules may not yet contain this new taxonomic name. The `AMR` package contains the full microbial taxonomy updated until `r documentation_date(max(TAXONOMY_VERSION$GBIF$accessed_date, TAXONOMY_VERSION$LPSN$accessed_date))`, see [microorganisms].
#'
#' ### Custom Rules
#'
#' Custom rules can be created using [custom_interpretive_rules()], e.g.:
#'
#' ```r
#' x <- custom_interpretive_rules(AMC == "R" & genus == "Klebsiella" ~ aminopenicillins == "R",
#' AMC == "I" & genus == "Klebsiella" ~ aminopenicillins == "I")
#'
#' interpretive_rules(example_isolates, rules = "custom", custom_rules = x)
#' ```
#'
#' ### 'Other' Rules
#'
#' Before further processing, two non-EUCAST rules about drug combinations can be applied to improve the efficacy of the EUCAST rules, and the reliability of your data (analysis). These rules are:
#'
#' 1. A drug **with** enzyme inhibitor will be set to S if the same drug **without** enzyme inhibitor is S
#' 2. A drug **without** enzyme inhibitor will be set to R if the same drug **with** enzyme inhibitor is R
#'
#' Important examples include amoxicillin and amoxicillin/clavulanic acid, and trimethoprim and trimethoprim/sulfamethoxazole. Needless to say, for these rules to work, both drugs must be available in the data set.
#'
#' Since these rules are not officially approved by EUCAST, they are not applied at default. To use these rules, include `"other"` to the `rules` argument, or use `interpretive_rules(..., rules = "all")`. You can also set the package option [`AMR_interpretive_rules`][AMR-options], i.e. run `options(AMR_interpretive_rules = "all")`.
#' @aliases EUCAST
#' @rdname interpretive_rules
#' @export
#' @return The input of `x`, possibly with edited values of antimicrobials. Or, if `verbose = TRUE`, a [data.frame] with all original and new values of the affected bug-drug combinations.
#' @references
#' - EUCAST Expert Rules. Version 2.0, 2012.\cr
#' Leclercq et al. **EUCAST expert rules in antimicrobial susceptibility testing.** *Clin Microbiol Infect.* 2013;19(2):141-60; \doi{https://doi.org/10.1111/j.1469-0691.2011.03703.x}
#' - EUCAST Expected Phenotypes. [(link)](https://www.eucast.org/bacteria/important-additional-information/expected-phenotypes/)
#' - EUCAST Breakpoint tables for interpretation of MICs and zone diameters. [(link)](https://www.eucast.org/bacteria/clinical-breakpoints-and-interpretation/clinical-breakpoint-tables/)
#' @inheritSection AMR Download Our Reference Data
#' @examples
#' \donttest{
#' a <- data.frame(
#' mo = c(
#' "Staphylococcus aureus",
#' "Enterococcus faecalis",
#' "Escherichia coli",
#' "Klebsiella pneumoniae",
#' "Pseudomonas aeruginosa"
#' ),
#' VAN = "-", # Vancomycin
#' AMX = "-", # Amoxicillin
#' COL = "-", # Colistin
#' CAZ = "-", # Ceftazidime
#' CXM = "-", # Cefuroxime
#' PEN = "S", # Benzylpenicillin
#' FOX = "S", # Cefoxitin
#' stringsAsFactors = FALSE
#' )
#'
#' head(a)
#'
#'
#' # apply EUCAST rules: some results wil be changed
#' b <- eucast_rules(a, overwrite = TRUE)
#'
#' head(b)
#'
#'
#' # do not apply EUCAST rules, but rather get a data.frame
#' # containing all details about the transformations:
#' c <- eucast_rules(a, overwrite = TRUE, verbose = TRUE)
#' head(c)
#' }
#'
#' # Dosage guidelines:
#'
#' eucast_dosage(c("tobra", "genta", "cipro"), "iv")
#'
#' eucast_dosage(c("tobra", "genta", "cipro"), "iv", version_breakpoints = 10)
interpretive_rules <- function(x,
col_mo = NULL,
info = interactive(),
rules = getOption("AMR_interpretive_rules", default = c("breakpoints", "expected_phenotypes")),
guideline = getOption("AMR_guideline", "EUCAST"),
verbose = FALSE,
version_breakpoints = 16.0,
version_expected_phenotypes = 1.2,
version_expertrules = 3.3,
ampc_cephalosporin_resistance = NA,
only_sir_columns = any(is.sir(x)),
custom_rules = NULL,
overwrite = FALSE,
add_if_missing = TRUE,
...) {
meet_criteria(x, allow_class = "data.frame")
meet_criteria(col_mo, allow_class = "character", has_length = 1, is_in = colnames(x), allow_NULL = TRUE)
if (guideline %like% "EUCAST") {
guideline <- "EUCAST"
} else if (guideline %like% "CLSI") {
guideline <- "CLSI"
}
meet_criteria(guideline, allow_class = "character", has_length = 1, is_in = c("EUCAST", "CLSI"))
meet_criteria(info, allow_class = "logical", has_length = 1)
meet_criteria(rules, allow_class = "character", has_length = c(1, 2, 3, 4, 5, 6), is_in = c("breakpoints", "expected_phenotypes", "expert", "other", "all", "custom"))
meet_criteria(verbose, allow_class = "logical", has_length = 1)
meet_criteria(version_breakpoints, allow_class = c("numeric", "integer"), has_length = 1, is_in = as.double(names(EUCAST_VERSION_BREAKPOINTS)))
meet_criteria(version_expected_phenotypes, allow_class = c("numeric", "integer"), has_length = 1, is_in = as.double(names(EUCAST_VERSION_EXPECTED_PHENOTYPES)))
meet_criteria(version_expertrules, allow_class = c("numeric", "integer"), has_length = 1, is_in = as.double(names(EUCAST_VERSION_EXPERT_RULES)))
meet_criteria(ampc_cephalosporin_resistance, allow_class = c("logical", "character", "sir"), has_length = 1, allow_NA = TRUE, allow_NULL = TRUE)
meet_criteria(only_sir_columns, allow_class = "logical", has_length = 1)
meet_criteria(custom_rules, allow_class = c("custom_interpretive_rules", "custom_eucast_rules"), allow_NULL = TRUE)
meet_criteria(overwrite, allow_class = "logical", has_length = 1)
meet_criteria(add_if_missing, allow_class = "logical", has_length = 1)
stop_if(
!overwrite && !add_if_missing,
"Either set {.arg overwrite} or {.arg add_if_missing} to {.code TRUE}, or both."
)
stop_if(
!is.na(ampc_cephalosporin_resistance) && !any(c("expert", "all") %in% rules),
"For the {.arg ampc_cephalosporin_resistance} argument to work, the {.arg rules} argument must contain {.code \"expert\"} or {.code \"all\"}."
)
add_MO_lookup_to_AMR_env()
if ("custom" %in% rules && is.null(custom_rules)) {
warning_("in {.help [{.fun interpretive_rules}](AMR::interpretive_rules)}: no custom rules were set with the {.arg custom_rules} argument",
immediate = TRUE
)
rules <- rules[rules != "custom"]
if (length(rules) == 0) {
if (isTRUE(info)) {
message_("No other rules were set, returning original data", as_note = FALSE)
}
return(x)
}
}
x_deparsed <- deparse(substitute(x))
if (length(x_deparsed) > 1 || any(x_deparsed %unlike% "[a-z]+")) {
x_deparsed <- "your_data"
}
breakpoints_info <- EUCAST_VERSION_BREAKPOINTS[[which(as.double(names(EUCAST_VERSION_BREAKPOINTS)) == version_breakpoints)]]
expected_phenotypes_info <- EUCAST_VERSION_EXPECTED_PHENOTYPES[[which(as.double(names(EUCAST_VERSION_EXPECTED_PHENOTYPES)) == version_expected_phenotypes)]]
expertrules_info <- EUCAST_VERSION_EXPERT_RULES[[which(as.double(names(EUCAST_VERSION_EXPERT_RULES)) == version_expertrules)]]
if (interactive() && isTRUE(verbose) && isTRUE(info)) {
txt <- paste0(
"WARNING: In Verbose mode, the interpretive_rules() function does not apply rules to the data, but instead returns a data set in logbook form with comprehensive info about which rows and columns would be effected and in which way.",
"\n\nThis may overwrite your existing data if you use e.g.:",
"\ndata <- interpretive_rules(data, verbose = TRUE)\n\nDo you want to continue?"
)
showQuestion <- import_fn("showQuestion", "rstudioapi", error_on_fail = FALSE)
if (!is.null(showQuestion)) {
q_continue <- showQuestion("Using verbose = TRUE with interpretive_rules()", txt)
} else {
q_continue <- utils::menu(choices = c("OK", "Cancel"), graphics = FALSE, title = txt)
}
if (q_continue %in% c(FALSE, 2)) {
message_("Cancelled, returning original data", as_note = FALSE)
return(x)
}
}
# try to find columns based on type
# -- mo
if (is.null(col_mo)) {
col_mo <- search_type_in_df(x = x, type = "mo", info = info)
stop_if(is.null(col_mo), "{.arg col_mo} must be set")
}
decimal.mark <- getOption("OutDec")
big.mark <- ifelse(decimal.mark != ",", ",", " ")
formatnr <- function(x, big = big.mark, dec = decimal.mark) {
trimws(format(x, big.mark = big, decimal.mark = dec))
}
warned <- FALSE
warn_lacking_sir_class <- character(0)
txt_ok <- function(n_added, n_changed, warned = FALSE) {
if (warned == FALSE) {
if (n_added + n_changed == 0) {
cat(font_subtle(" (no changes)\n"))
} else {
# opening
if (n_added > 0 && n_changed == 0) {
cat(font_bold(font_green(" (")))
} else if (n_added == 0 && n_changed > 0) {
cat(font_bold(font_blue(" (")))
} else {
cat(font_grey(" ("))
}
# additions
if (n_added > 0) {
if (n_added == 1) {
cat(font_bold(font_green("1 value added")))
} else {
cat(font_bold(font_green(formatnr(n_added), "values added")))
}
}
# separator
if (n_added > 0 && n_changed > 0) {
cat(font_grey(", "))
}
# changes
if (n_changed > 0) {
if (n_changed == 1) {
cat(font_bold(font_blue("1 value changed")))
} else {
cat(font_bold(font_blue(formatnr(n_changed), "values changed")))
}
}
# closing
if (n_added > 0 && n_changed == 0) {
cat(font_bold(font_green(")\n")))
} else if (n_added == 0 && n_changed > 0) {
cat(font_bold(font_blue(")\n")))
} else {
cat(font_grey(")\n"))
}
}
warned <<- FALSE
}
}
cols_ab <- get_column_abx(
x = x,
soft_dependencies = c(
"AMC",
"AMP",
"AMX",
"CIP",
"ERY",
"FOX-S",
"GEN",
"MFX",
"NAL-S",
"NOR-S",
"OXA-S",
"PEN-S",
"PIP",
"TCY",
"TIC",
"TOB"
),
hard_dependencies = NULL,
verbose = verbose,
info = info,
only_sir_columns = only_sir_columns,
fn = "interpretive_rules",
...
)
if (!"AMP" %in% names(cols_ab) && "AMX" %in% names(cols_ab)) {
# ampicillin column is missing, but amoxicillin is available
if (isTRUE(info)) {
message_("Using column {.field ", font_bold(cols_ab[names(cols_ab) == "AMX"]), "} as input for ampicillin since many EUCAST rules depend on it.")
}
cols_ab <- c(cols_ab, c(AMP = unname(cols_ab[names(cols_ab) == "AMX"])))
}
# data preparation ----
if (isTRUE(info) && NROW(x) > 10000) {
message_("Preparing data...", appendLF = FALSE, as_note = FALSE)
}
# Some helper functions ---------------------------------------------------
get_antibiotic_names <- function(x) {
x <- x %pm>%
strsplit(",") %pm>%
unlist() %pm>%
trimws2() %pm>%
vapply(FUN.VALUE = character(1), function(x) if (x %in% AMR::antimicrobials$ab) ab_name(x, language = NULL, tolower = TRUE, fast_mode = TRUE) else x) %pm>%
sort() %pm>%
paste(collapse = ", ")
x <- gsub("_", " ", x, fixed = TRUE)
x <- gsub("except CAZ", paste("except", ab_name("CAZ", language = NULL, tolower = TRUE)), x, fixed = TRUE)
x <- gsub("except TGC", paste("except", ab_name("TGC", language = NULL, tolower = TRUE)), x, fixed = TRUE)
x <- gsub("cephalosporins (1st|2nd|3rd|4th|5th)", "cephalosporins (\\1 gen.)", x)
x
}
format_antibiotic_names <- function(ab_names, ab_results) {
ab_names <- trimws2(unlist(strsplit(ab_names, ",")))
ab_results <- trimws2(unlist(strsplit(ab_results, ",")))
if (length(ab_results) == 1) {
if (length(ab_names) == 1) {
# like FOX S
x <- paste(ab_names, "is")
} else if (length(ab_names) == 2) {
# like PEN,FOX S
x <- paste(paste0(ab_names, collapse = " and "), "are both")
} else {
# like PEN,FOX,GEN S
x <- paste(paste0(ab_names, collapse = " and "), "are all")
}
return(paste0(x, " '", ab_results, "'"))
} else {
if (length(ab_names) == 2) {
# like PEN,FOX S,R
paste0(
ab_names[1], " is '", ab_results[1], "' and ",
ab_names[2], " is '", ab_results[2], "'"
)
} else {
# like PEN,FOX,GEN S,R,R
paste0(
ab_names[1], " is '", ab_results[1], "' and ",
ab_names[2], " is '", ab_results[2], "' and ",
ab_names[3], " is '", ab_results[3], "'"
)
}
}
}
as.sir_no_warning <- function(x) {
if (is.sir(x)) {
return(x)
}
suppressWarnings(as.sir(x))
}
expand_groups <- function(entry) {
parts <- trimws(strsplit(entry, ",")[[1]])
group_names <- tolower(AMR::microorganisms.groups$mo_group_name)
mo_names <- AMR::microorganisms.groups$mo_name
group_names_lc <- tolower(group_names)
result <- unlist(lapply(parts, function(part) {
match_idx <- which(group_names_lc == tolower(part))
if (length(match_idx) > 0) {
mo_names[match_idx]
} else {
part
}
}))
# only the ones with genus or genus/species, not subspecies (as genus_species will be matched)
spaces <- vapply(FUN.VALUE = integer(1), strsplit(result, " "), length)
result <- result[spaces < 3]
return(paste0(unique(result), collapse = ", "))
}
# the accepted taxa of literal organism names in a rule, e.g. Thomasclavelia ramosa for 'Clostridium ramosum'
add_MO_lookup_to_AMR_env()
fullnames_lower <- tolower(AMR_env$MO_lookup$fullname)
names_to_accepted_mo <- function(mo_names) {
mo <- AMR_env$MO_lookup$mo[which(fullnames_lower %in% tolower(mo_names))]
synonym_mo_to_accepted_mo(mo, fill_in_accepted = TRUE)
}
# Preparing the data ------------------------------------------------------
verbose_info <- data.frame(
rowid = character(0),
col = character(0),
mo_fullname = character(0),
old = as.sir(character(0)),
new = as.sir(character(0)),
rule = character(0),
rule_group = character(0),
rule_name = character(0),
rule_source = character(0),
stringsAsFactors = FALSE
)
old_cols <- colnames(x)
old_attributes <- attributes(x)
x <- as.data.frame(x, stringsAsFactors = FALSE) # no tibbles, data.tables, etc.
rownames(x) <- NULL # will later be restored with old_attributes
# create unique row IDs - combination of the MO and all ABx columns (so they will only run once per unique combination)
x$`.rowid` <- vapply(
FUN.VALUE = character(1),
as.list(as.data.frame(t(x[, c(col_mo, cols_ab), drop = FALSE]),
stringsAsFactors = FALSE
)),
function(x) {
x[is.na(x)] <- "."
paste0(x, collapse = "")
}
)
# save original table, with the new .rowid column
x.bak <- x
# keep only unique rows for MO and ABx
x <- x %pm>%
pm_arrange(`.rowid`) %pm>%
# big speed gain! only analyse unique rows:
pm_distinct(`.rowid`, .keep_all = TRUE) %pm>%
as.data.frame(stringsAsFactors = FALSE)
x[, col_mo] <- as.mo(as.character(x[, col_mo, drop = TRUE]), info = FALSE)
# rename col_mo to prevent interference with joined columns
colnames(x)[colnames(x) == col_mo] <- ".col_mo"
col_mo <- ".col_mo"
# join to microorganisms data set
x <- left_join_microorganisms(x, by = col_mo, suffix = c("_oldcols", ""))
x$gramstain <- mo_gramstain(x[, col_mo, drop = TRUE], language = NULL, info = FALSE)
x$genus_species <- trimws(paste(x$genus, x$species))
# the accepted name of each organism, so that a rule can name it by any of its synonyms (see 'Get rule from file')
x$`.mo_accepted` <- synonym_mo_to_accepted_mo(as.character(x[, col_mo, drop = TRUE]), fill_in_accepted = TRUE)
if (isTRUE(info) && NROW(x.bak) > 10000) {
message_("OK.", as_note = FALSE)
}
n_added <- 0
n_changed <- 0
rule_current <- ""
rule_group_current <- ""
rule_group_previous <- ""
rule_next <- ""
rule_previous <- ""
rule_text <- ""
# >>> Apply Other rules: enzyme inhibitors <<< ------------------------------------------
if (any(c("all", "other") %in% rules)) {
if (isTRUE(info)) {
cat(paste0("\n", font_grey(strrep("-", 0.95 * getOption("width", 100))), "\n"))
message_(
"Rules by the ",
font_bold(paste0("AMR package v", utils::packageDescription("AMR")$Version)),
" (", format(as.Date(utils::packageDescription("AMR")$Date), format = "%Y"),
"), see {.help [{.fun interpretive_rules}](AMR::interpretive_rules)}",
as_note = FALSE
)
cat("\n\n")
}
ab_enzyme <- subset(AMR::antimicrobials, name %like% "/")[, c("ab", "name"), drop = FALSE]
colnames(ab_enzyme) <- c("enzyme_ab", "enzyme_name")
ab_enzyme$base_name <- gsub("^([a-zA-Z0-9]+).*", "\\1", ab_enzyme$enzyme_name)
ab_enzyme$base_ab <- AMR::antimicrobials[match(ab_enzyme$base_name, AMR::antimicrobials$name), "ab", drop = TRUE]
ab_enzyme <- subset(ab_enzyme, !is.na(base_ab))
# make ampicillin and amoxicillin interchangable
ampi <- subset(ab_enzyme, base_ab == "AMX")
ampi$base_ab <- "AMP"
ampi$base_name <- ab_name("AMP", language = NULL)
amox <- subset(ab_enzyme, base_ab == "AMP")
amox$base_ab <- "AMX"
amox$base_name <- ab_name("AMX", language = NULL)
# merge and sort
ab_enzyme <- rbind_AMR(ab_enzyme, ampi, amox)
ab_enzyme <- ab_enzyme[order(ab_enzyme$enzyme_name), , drop = FALSE]
for (i in seq_len(nrow(ab_enzyme))) {
# check if both base and base + enzyme inhibitor are part of the data set
if (all(c(ab_enzyme$base_ab[i], ab_enzyme$enzyme_ab[i]) %in% names(cols_ab), na.rm = TRUE)) {
col_base <- unname(cols_ab[ab_enzyme$base_ab[i]])
col_enzyme <- unname(cols_ab[ab_enzyme$enzyme_ab[i]])
## Set base to R where base + enzyme inhibitor is R ----
rule_current <- paste0(
ab_enzyme$base_name[i], " ({.field ", font_bold(col_base), "}) = R if ",
tolower(ab_enzyme$enzyme_name[i]), " ({.field ", font_bold(col_enzyme), "}) = R"
)
if (isTRUE(info)) {
message_(rule_current,
as_note = FALSE,
appendLF = FALSE,
extra_indent = 6
)
}
run_changes <- edit_sir(
x = x,
to = "R",
rule = c(
rule_current, "Other rules", "",
paste0("Non-EUCAST: AMR package v", utils::packageDescription("AMR")$Version)
),
rows = which(as.sir_no_warning(x[, col_enzyme, drop = TRUE]) == "R"),
cols = col_base,
last_verbose_info = verbose_info,
original_data = x.bak,
warned = warned,
info = info,
verbose = verbose,
overwrite = overwrite,
add_if_missing = add_if_missing
)
n_added <- n_added + run_changes$added
n_changed <- n_changed + run_changes$changed
verbose_info <- run_changes$verbose_info
x <- run_changes$output
warn_lacking_sir_class <- c(warn_lacking_sir_class, run_changes$sir_warn)
# Print number of new changes
if (isTRUE(info)) {
# print only on last one of rules in this group
txt_ok(n_added = n_added, n_changed = n_changed, warned = warned)
# and reset counters
n_added <- 0
n_changed <- 0
}
## Set base + enzyme inhibitor to S where base is S ----
rule_current <- paste0(
ab_enzyme$enzyme_name[i], " ({.field ", font_bold(col_enzyme), "}) = S if ",
tolower(ab_enzyme$base_name[i]), " ({.field ", font_bold(col_base), "}) = S"
)
if (isTRUE(info)) {
cat(word_wrap(rule_current,
width = getOption("width") - 30,
extra_indent = 6
))
}
run_changes <- edit_sir(
x = x,
to = "S",
rule = c(
rule_current, "Other rules", "",
paste0("Non-EUCAST: AMR package v", utils::packageDescription("AMR")$Version)
),
rows = which(as.sir_no_warning(x[, col_base, drop = TRUE]) == "S"),
cols = col_enzyme,
last_verbose_info = verbose_info,
original_data = x.bak,
warned = warned,
info = info,
verbose = verbose,
overwrite = overwrite,
add_if_missing = add_if_missing
)
n_added <- n_added + run_changes$added
n_changed <- n_changed + run_changes$changed
verbose_info <- run_changes$verbose_info
x <- run_changes$output
warn_lacking_sir_class <- c(warn_lacking_sir_class, run_changes$sir_warn)
# Print number of new changes
if (isTRUE(info)) {
# print only on last one of rules in this group
txt_ok(n_added = n_added, n_changed = n_changed, warned = warned)
# and reset counters
n_added <- 0
n_changed <- 0
}
}
}
} else {
if (isTRUE(info)) {
cat("\n")
message_("Skipping inhibitor-inheritance rules defined by this AMR package: setting S to drug+inhibitor where drug is S, and setting R to drug where drug+inhibitor is R. Add {.val other} or {.val all} to the {.arg rules} argument to apply those rules.")
}
}
if (!any(c("all", "custom") %in% rules) && !is.null(custom_rules)) {
if (isTRUE(info)) {
message_("Skipping custom interpretive rules, since the {.arg rules} argument does not contain {.code \"custom\"}.")
}
custom_rules <- NULL
}
# >>> Apply Official interpretive rules <<< ---------------------------------------------------
eucast_notification_shown <- FALSE
if (!is.null(list(...)$interpretive_rules_df)) {
# this allows: interpretive_rules(x, interpretive_rules_df = AMR:::INTERPRETIVE_RULES_DF |> filter(is.na(have_these_values)))
interpretive_rules_df_total <- list(...)$interpretive_rules_df
} else if (!is.null(list(...)$eucast_rules_df)) {
# deprecated parameter name kept for backward compatibility
interpretive_rules_df_total <- list(...)$eucast_rules_df
warning("Used interpretive_rules(x, eucast_rules_df = ...) - Do use newer argument interpretive_rules_df now.")
} else {
# internal data file, created in data-raw/_pre_commit_checks.R
interpretive_rules_df_total <- INTERPRETIVE_RULES_DF
}
## filter on guideline provider and user-set guideline versions ----
interpretive_rules_df <- data.frame()
if (any(c("all", "breakpoints") %in% rules)) {
interpretive_rules_df <- interpretive_rules_df %pm>%
rbind_AMR(interpretive_rules_df_total %pm>%
subset(rule.provider == guideline & reference.rule_group %like% "breakpoint" & reference.version == version_breakpoints))
}
if (any(c("all", "expected_phenotypes") %in% rules)) {
interpretive_rules_df <- interpretive_rules_df %pm>%
rbind_AMR(interpretive_rules_df_total %pm>%
subset(rule.provider == guideline & reference.rule_group %like% "expected" & reference.version == version_expected_phenotypes))
}
if (any(c("all", "expert") %in% rules)) {
interpretive_rules_df <- interpretive_rules_df %pm>%
rbind_AMR(interpretive_rules_df_total %pm>%
subset(rule.provider == guideline & reference.rule_group %like% "expert" & reference.version == version_expertrules))
}
## filter out AmpC de-repressed cephalosporin-resistant mutants ----
# no need to filter on version number here - the rules contain these version number, so are inherently filtered
# cefotaxime, ceftriaxone, ceftazidime
if (is.null(ampc_cephalosporin_resistance) || isFALSE(ampc_cephalosporin_resistance)) {
interpretive_rules_df <- subset(
interpretive_rules_df,
reference.rule %unlike% "ampc"
)
} else {
if (isTRUE(ampc_cephalosporin_resistance)) {
ampc_cephalosporin_resistance <- "R"
}
if (!is.null(interpretive_rules_df$reference.rule)) {
interpretive_rules_df[which(interpretive_rules_df$reference.rule %like% "ampc"), "to_value"] <- as.character(ampc_cephalosporin_resistance)
}
}
# sometimes, the screenings are missing but the names are actually available
# we only hints on remaining rows in `interpretive_rules_df`
screening_abx <- as.character(AMR::antimicrobials$ab[which(AMR::antimicrobials$ab %like% "-S$")])
screening_abx <- screening_abx[screening_abx %in% unique(unlist(strsplit(interpretive_rules_df_total$and_these_antibiotics[!is.na(interpretive_rules_df_total$and_these_antibiotics)], ", *")))]
if (isTRUE(info)) {
cat("\n")
}
for (ab_s in screening_abx) {
ab <- gsub("-S$", "", ab_s)
if (ab %in% names(cols_ab) && !ab_s %in% names(cols_ab)) {
if (isTRUE(info)) {
message_(
"Using column {.field ", font_bold(cols_ab[names(cols_ab) == ab]),
"} as ", ab_name(ab_s, language = NULL, tolower = TRUE),
" since a column {.code ", ab_s, "} is missing but required for the chosen rules"
)
}
cols_ab <- c(cols_ab, stats::setNames(unname(cols_ab[names(cols_ab) == ab]), ab_s))
}
}
## Go over all rules and apply them ----
for (i in seq_len(nrow(interpretive_rules_df))) {
rule_previous <- interpretive_rules_df[max(1, i - 1), "reference.rule", drop = TRUE]
rule_current <- interpretive_rules_df[i, "reference.rule", drop = TRUE]
rule_next <- interpretive_rules_df[min(nrow(interpretive_rules_df), i + 1), "reference.rule", drop = TRUE]
rule_group_previous <- interpretive_rules_df[max(1, i - 1), "reference.rule_group", drop = TRUE]
rule_group_current <- interpretive_rules_df[i, "reference.rule_group", drop = TRUE]
# don't apply rules if user doesn't want to apply them
if (rule_group_current %like% "breakpoint" && !any(c("all", "breakpoints") %in% rules)) {
next
}
if (rule_group_current %like% "expected" && !any(c("all", "expected_phenotypes") %in% rules)) {
next
}
if (rule_group_current %like% "expert" && !any(c("all", "expert") %in% rules)) {
next
}
if (isFALSE(info) || isFALSE(verbose)) {
rule_text <- ""
} else {
if (is.na(interpretive_rules_df[i, "and_these_antibiotics", drop = TRUE])) {
rule_text <- paste0("always report as '", interpretive_rules_df[i, "to_value", drop = TRUE], "': ", get_antibiotic_names(interpretive_rules_df[i, "then_change_these_antibiotics", drop = TRUE]))
} else {
rule_text <- paste0(
"report as '", interpretive_rules_df[i, "to_value", drop = TRUE], "' when ",
format_antibiotic_names(
ab_names = get_antibiotic_names(interpretive_rules_df[i, "and_these_antibiotics", drop = TRUE]),
ab_results = interpretive_rules_df[i, "have_these_values", drop = TRUE]
), ": ",
get_antibiotic_names(interpretive_rules_df[i, "then_change_these_antibiotics", drop = TRUE])
)
}
}
if (i == 1) {
rule_previous <- ""
rule_group_previous <- ""
}
if (i == nrow(interpretive_rules_df)) {
rule_next <- ""
}
if (isTRUE(info)) {
## Print EUCAST intro ------------------------------------------------------
if (rule_group_current %unlike% "other" && eucast_notification_shown == FALSE) {
cat(
paste0(
"\n", font_grey(strrep("-", 0.95 * getOption("width", 100))), "\n",
word_wrap("Rules by the ", font_bold("European Committee on Antimicrobial Susceptibility Testing (EUCAST)")), "\n",
font_blue(font_url("https://eucast.org/")), "\n"
)
)
eucast_notification_shown <- TRUE
}
## Print rule (group) ------------------------------------------------------
if (rule_group_current != rule_group_previous) {
# is new rule group, one of Breakpoints, Expert Rules and Other
cat(font_bold(
ifelse(
rule_group_current %like% "breakpoint",
paste0(
"\n",
word_wrap(
breakpoints_info$title, " (",
font_red(paste0(breakpoints_info$version_txt, ", ", breakpoints_info$year)), ")\n"
)
),
ifelse(
rule_group_current %like% "expected",
paste0(
"\n",
word_wrap(
expected_phenotypes_info$title, " (",
font_red(paste0(expected_phenotypes_info$version_txt, ", ", expected_phenotypes_info$year)), ")\n"
)
),
ifelse(
rule_group_current %like% "expert",
paste0(
"\n",
word_wrap(
expertrules_info$title, " (",
font_red(paste0(expertrules_info$version_txt, ", ", expertrules_info$year)), ")\n"
)
),
"" # Default empty string if none of the conditions are met
)
)
)
), "\n")
}
## Print rule -------------------------------------------------------------
if (rule_current != rule_previous) {
# is new rule within group, print its name
cat(italicise_taxonomy(
word_wrap(rule_current,
width = getOption("width") - 30,
extra_indent = 6
),
type = "ansi"
))
warned <- FALSE
}
}
## Get rule from file ------------------------------------------------------
if_mo_property <- trimws(interpretive_rules_df[i, "if_mo_property", drop = TRUE])
like_is_one_of <- trimws(interpretive_rules_df[i, "like.is.one_of", drop = TRUE])
mo_value <- trimws(interpretive_rules_df[i, "this_value", drop = TRUE])
source_antibiotics <- interpretive_rules_df[i, "and_these_antibiotics", drop = TRUE]
source_value <- trimws(unlist(strsplit(interpretive_rules_df[i, "have_these_values", drop = TRUE], ",", fixed = TRUE)))
target_antibiotics <- interpretive_rules_df[i, "then_change_these_antibiotics", drop = TRUE]
target_value <- interpretive_rules_df[i, "to_value", drop = TRUE]
# if amo_value contains a group name, expand that name with all species in it
if (any(trimws(strsplit(mo_value, ",")[[1]]) %in% AMR::microorganisms.groups$mo_group_name, na.rm = TRUE)) {
like_is_one_of <- "one_of"
mo_value <- expand_groups(mo_value)
}
# Organisms match by the names in the data. Species-level rules with literal names also match by the accepted
# taxon, so that the rule and the data may use different names of it (e.g. 'Clostridium ramosum' in a rule, while
# its accepted name is Thomasclavelia ramosa). Not for genera, as a former genus also contains species that now
# belong to other genera (e.g. Pseudomonas maltophilia), and not for regular expressions, as these would then also
# match synonyms they were written to exclude (e.g. Klebsiella mobilis for '^Klebsiella(?! aerogenes)').
accepted_mo_of_rule <- NULL
if (like_is_one_of %in% c("is", "one_of") && if_mo_property %in% c("genus_species", "fullname")) {
accepted_mo_of_rule <- names_to_accepted_mo(trimws(strsplit(mo_value, ",", fixed = TRUE)[[1]]))
}
if (like_is_one_of == "is") {
# so e.g. 'Enterococcus' will turn into '^Enterococcus$'
mo_value <- paste0("^", mo_value, "$")
} else if (like_is_one_of == "one_of") {
# so 'Clostridium, Actinomyces, ...' will turn into '^(Clostridium|Actinomyces|...)$'
mo_value <- paste0(
"^(",
paste(trimws(unlist(strsplit(mo_value, ",", fixed = TRUE))),
collapse = "|"
),
")$"
)
} else if (like_is_one_of != "like") {
stop("invalid value for column {.field like.is.one_of}", call. = FALSE)
}
mo_match <- tryCatch(
x[, if_mo_property, drop = TRUE] %like% mo_value | x$fullname %like% mo_value,
error = function(e) rep(FALSE, nrow(x))
)
if (!is.null(accepted_mo_of_rule)) {
mo_match <- mo_match | x$`.mo_accepted` %in% accepted_mo_of_rule
}
if (is.na(source_antibiotics)) {
rows <- which(mo_match)
} else {
source_antibiotics <- get_ab_from_namespace(source_antibiotics, cols_ab)
if (length(source_value) == 1 && length(source_antibiotics) > 1) {
source_value <- rep(source_value, length(source_antibiotics))
}
if (length(source_antibiotics) == 0) {
rows <- integer(0)
} else if (length(source_antibiotics) == 1) {
rows <- tryCatch(
which(mo_match &
as.sir_no_warning(x[, source_antibiotics[1L]]) == source_value[1L]),
error = function(e) integer(0)
)
} else if (length(source_antibiotics) == 2) {
rows <- tryCatch(
which(mo_match &
as.sir_no_warning(x[, source_antibiotics[1L]]) == source_value[1L] &
as.sir_no_warning(x[, source_antibiotics[2L]]) == source_value[2L]),
error = function(e) integer(0)
)
} else {
stop_("only 2 antimicrobials supported for source_antibiotics")
}
}
cols <- get_ab_from_namespace(target_antibiotics, cols_ab)
## Apply rule on data ------------------------------------------------------
# this will return the unique number of changes
run_changes <- edit_sir(
x = x,
to = target_value,
rule = c(
rule_text, rule_group_current, rule_current,
ifelse(rule_group_current %like% "breakpoint",
paste0(breakpoints_info$title, " ", breakpoints_info$version_txt, ", ", breakpoints_info$year),
ifelse(rule_group_current %like% "expected",
paste0(expected_phenotypes_info$title, " ", expected_phenotypes_info$version_txt, ", ", expected_phenotypes_info$year),
paste0(expertrules_info$title, " ", expertrules_info$version_txt, ", ", expertrules_info$year)
)
)
),
rows = rows,
cols = cols,
last_verbose_info = verbose_info,
original_data = x.bak,
warned = warned,
info = info,
verbose = verbose,
overwrite = overwrite,
add_if_missing = add_if_missing
)
n_added <- n_added + run_changes$added
n_changed <- n_changed + run_changes$changed
verbose_info <- run_changes$verbose_info
x <- run_changes$output
warn_lacking_sir_class <- c(warn_lacking_sir_class, run_changes$sir_warn)
## Print number of new changes ---------------------------------------------
if (isTRUE(info) && rule_next != rule_current) {
# print only on last one of rules in this group
txt_ok(n_added = n_added, n_changed = n_changed, warned = warned)
# and reset counters
n_added <- 0
n_changed <- 0
}
} # end of going over all rules
# >>> Apply custom rules <<< ----
if (!is.null(custom_rules)) {
if (isTRUE(info)) {
cat("\n")
cat(font_bold("Custom interpretive rules, set by user"), "\n")
}
for (i in seq_len(length(custom_rules))) {
rule <- custom_rules[[i]]
rows <- tryCatch(which(eval(parse(text = rule$query), envir = x)),
error = function(e) stop_(conditionMessage(e), " (check available data and compare with the custom rules set)", call = FALSE)
)
cols <- as.character(rule$result_group)
cols <- c(
cols[cols %in% colnames(x)], # direct column names
unname(cols_ab[names(cols_ab) %in% cols])
) # based on previous cols_ab finding
cols <- unique(cols)
target_value <- as.character(rule$result_value)
rule_text <- paste0(
"report as '", target_value, "' when ",
format_custom_query_rule(rule$query, colours = FALSE), ": ",
get_antibiotic_names(cols)
)
if (isTRUE(info)) {
cat(italicise_taxonomy(
word_wrap(rule_text,
width = getOption("width") - 30,
extra_indent = 6
),
type = "ansi"
))
cat("\n")
warned <- FALSE
}
run_changes <- edit_sir(
x = x,
to = target_value,
rule = c(
rule_text,
"Custom interpretive rules",
paste0("Custom interpretive rule ", i),
paste0(
"Object '", deparse(substitute(custom_rules)),
"' consisting of ", length(custom_rules), " custom rules"
)
),
rows = rows,
cols = cols,
last_verbose_info = verbose_info,
original_data = x.bak,
warned = warned,
info = info,
verbose = verbose,
overwrite = overwrite,
add_if_missing = add_if_missing
)
n_added <- n_added + run_changes$added
n_changed <- n_changed + run_changes$changed
verbose_info <- run_changes$verbose_info
x <- run_changes$output
warn_lacking_sir_class <- c(warn_lacking_sir_class, run_changes$sir_warn)
## Print number of new changes ---------------------------------------------
if (isTRUE(info) && rule_next != rule_current) {
# print only on last one of rules in this group
txt_ok(n_added = n_added, n_changed = n_changed, warned = warned)
# and reset counters
n_added <- 0
n_changed <- 0
}
}
}
# Print overview ----------------------------------------------------------
if (isTRUE(info) || isTRUE(verbose)) {
verbose_info <- x.bak %pm>%
pm_mutate(row = pm_row_number()) %pm>%
pm_select(`.rowid`, row) %pm>%
pm_right_join(verbose_info,
by = c(".rowid" = "rowid")
) %pm>%
pm_select(-`.rowid`) %pm>%
pm_select(row, pm_everything()) %pm>%
pm_filter(!is.na(new) | is.na(new) & !is.na(old)) %pm>%
pm_arrange(row, rule_group, rule_name, col)
if (isFALSE(overwrite)) {
verbose_info <- verbose_info %pm>%
pm_filter(!old %in% levels(NA_sir_))
}
rownames(verbose_info) <- NULL
}
if (isTRUE(info)) {
if (isTRUE(verbose)) {
wouldve <- "would have "
} else {
wouldve <- ""
}
cat(paste0("\n", font_grey(strrep("-", 0.95 * getOption("width", 100))), "\n"))
cat(word_wrap(paste0(
"The rules ", paste0(wouldve, "affected "),
font_bold(
formatnr(pm_n_distinct(verbose_info$row)),
"out of", formatnr(nrow(x.bak)),
"rows"
),
", making a total of ",
font_bold(formatnr(nrow(verbose_info)), "edits\n")
)))
total_n_added <- verbose_info %pm>% pm_filter(is.na(old)) %pm>% nrow()
total_n_changed <- verbose_info %pm>% pm_filter(!is.na(old)) %pm>% nrow()
# print added values
if (total_n_added == 0) {
colour <- cat # is function
} else {
colour <- font_green # is function
}
cat(colour(paste0(
"=> ", wouldve, "added ",
font_bold(formatnr(verbose_info %pm>%
pm_filter(is.na(old)) %pm>%
nrow()), "test results"),
"\n"
)))
if (total_n_added > 0) {
added_summary <- verbose_info %pm>%
pm_filter(is.na(old)) %pm>%
pm_count(new, name = "n")
cat(paste(" -",
paste0(
formatnr(added_summary$n), " test result", ifelse(added_summary$n > 1, "s", ""),
" added as ", paste0('"', added_summary$new, '"')
),
collapse = "\n"
))
}
# print changed values
if (total_n_changed == 0) {
colour <- cat # is function
} else {
colour <- font_blue # is function
}
if (total_n_added + total_n_changed > 0) {
cat("\n")
}
cat(colour(paste0(
"=> ", wouldve, "changed ",
font_bold(formatnr(verbose_info %pm>%
pm_filter(!is.na(old)) %pm>%
nrow()), "test results"),
"\n"
)))
if (total_n_changed > 0) {
changed_summary <- verbose_info %pm>%
pm_filter(!is.na(old)) %pm>%
pm_mutate(new = ifelse(is.na(new), "NA", new)) %pm>%
pm_count(old, new, name = "n")
cat(paste(" -",
paste0(
formatnr(changed_summary$n), " test result", ifelse(changed_summary$n > 1, "s", ""), " changed from ",
paste0('"', changed_summary$old, '"'), " to ", paste0('"', changed_summary$new, '"')
),
collapse = "\n"
))
cat("\n")
}
cat(paste0(font_grey(strrep("-", 0.95 * getOption("width", 100))), "\n"))
if (isFALSE(verbose) && total_n_added + total_n_changed > 0) {
cat("\n", word_wrap("Use ", highlight_code("eucast_rules(..., verbose = TRUE)"), " (on your original data) to get a data.frame with all specified edits instead."), "\n\n", sep = "")
} else if (isTRUE(verbose)) {
cat("\n", word_wrap("Used 'Verbose mode' ({.code verbose = TRUE}), which returns a data.frame with all specified edits.\nUse {.code verbose = FALSE} to apply the rules on your data."), "\n\n", sep = "")
}
}
if (length(warn_lacking_sir_class) > 0) {
warn_lacking_sir_class <- unique(warn_lacking_sir_class)
# take order from original data set
warn_lacking_sir_class <- warn_lacking_sir_class[order(colnames(x.bak))]
warn_lacking_sir_class <- warn_lacking_sir_class[!is.na(warn_lacking_sir_class)]
warning_(
"in {.help [{.fun interpretive_rules}](AMR::interpretive_rules)}: not all columns with antimicrobial results are of class {.cls sir}. Transform them on beforehand, e.g.:\n\n",
"\u00a0\u00a0", AMR_env$bullet_icon, " ", highlight_code(paste0(x_deparsed, " |> as.sir(", ifelse(length(warn_lacking_sir_class) == 1,
warn_lacking_sir_class,
paste0(warn_lacking_sir_class[1], ":", warn_lacking_sir_class[length(warn_lacking_sir_class)])
), ")")), "\n\n",
"\u00a0\u00a0", AMR_env$bullet_icon, " ", highlight_code(paste0(x_deparsed, " |> mutate_if(is_sir_eligible, as.sir)")), "\n\n",
"\u00a0\u00a0", AMR_env$bullet_icon, " ", highlight_code(paste0(x_deparsed, " |> mutate(across(where(is_sir_eligible), as.sir))"))
)
}
# Return data set ---------------------------------------------------------
if (isTRUE(verbose)) {
as_original_data_class(verbose_info, old_attributes$class) # will remove tibble groups
} else {
# x was analysed with only unique rows, so join everything together again
x <- x[, c(cols_ab, ".rowid"), drop = FALSE]
x.bak <- x.bak[, setdiff(colnames(x.bak), cols_ab), drop = FALSE]
x.bak <- x.bak %pm>%
pm_left_join(x, by = ".rowid")
x.bak <- x.bak[, old_cols, drop = FALSE]
# reset original attributes
attributes(x.bak) <- old_attributes
x.bak <- as_original_data_class(x.bak, old_class = class(x.bak)) # will remove tibble groups
x.bak
}
}
#' @rdname interpretive_rules
#' @export
eucast_rules <- function(x,
col_mo = NULL,
info = interactive(),
rules = getOption("AMR_interpretive_rules", default = c("breakpoints", "expected_phenotypes")),
...) {
if (!is.null(getOption("AMR_eucastrules", default = NULL))) {
warning_("The global option {.code AMR_eucastrules} that you have set is now invalid was ignored - set {.code AMR_interpretive_rules} instead. See {.topic [AMR-options](AMR::AMR-options)}.")
}
interpretive_rules(x = x, col_mo = col_mo, info = info, rules = rules, guideline = "EUCAST", ...)
}
#' @rdname interpretive_rules
#' @export
clsi_rules <- function(x,
col_mo = NULL,
info = interactive(),
rules = getOption("AMR_interpretive_rules", default = c("breakpoints", "expected_phenotypes")),
...) {
interpretive_rules(x = x, col_mo = col_mo, info = info, rules = rules, guideline = "CLSI", ...)
}
# helper function for editing the table ----
edit_sir <- function(x,
to,
rule,
rows,
cols,
last_verbose_info,
original_data,
warned,
info,
verbose,
overwrite,
add_if_missing) {
cols <- unique(cols[!is.na(cols) & !is.null(cols)])
rows <- unique(rows)
# for Verbose Mode, keep track of all changes and return them
track_changes <- list(
added = 0,
changed = 0,
output = x,
verbose_info = last_verbose_info,
sir_warn = character(0)
)
txt_error <- function() {
if (isTRUE(info)) cat("", font_red_bg(" ERROR "), "\n\n")
}
txt_warning <- function() {
if (warned == FALSE) {
if (isTRUE(info)) cat(" ", font_orange_bg(" WARNING "), sep = "")
}
warned <<- TRUE
}
if (length(rows) > 0 && length(cols) > 0) {
new_edits <- x
if (any(!vapply(FUN.VALUE = logical(1), x[, cols, drop = FALSE], is.sir), na.rm = TRUE)) {
track_changes$sir_warn <- cols[!vapply(FUN.VALUE = logical(1), x[, cols, drop = FALSE], is.sir)]
}
isNA <- is.na(new_edits[rows, cols])
isSIR <- !isNA &
(new_edits[rows, cols] == "S" |
new_edits[rows, cols] == "I" |
new_edits[rows, cols] == "R" |
new_edits[rows, cols] == "SDD" |
new_edits[rows, cols] == "NI" |
new_edits[rows, cols] == "WT" |
new_edits[rows, cols] == "NWT" |
new_edits[rows, cols] == "NS")
non_SIR <- !isSIR
if (isFALSE(overwrite) && any(isSIR) && message_not_thrown_before("edit_sir.warning_overwrite")) {
warning_("in {.help [{.fun interpretive_rules}](AMR::interpretive_rules)}: some columns had SIR values which were not overwritten, since {.code overwrite = FALSE}.")
}
# determine which cells to modify based on overwrite and add_if_missing
if (isTRUE(overwrite)) {
if (isTRUE(add_if_missing)) {
apply_mask <- rep(TRUE, length(isSIR))
} else {
apply_mask <- isSIR
}
} else {
# overwrite = FALSE, add_if_missing = TRUE: fill missing and placeholder cells only
apply_mask <- !isSIR
}
do_assign <- function() {
subset <- new_edits[rows, cols, drop = FALSE]
mask <- matrix(apply_mask, nrow = nrow(subset), ncol = ncol(subset))
subset[mask] <- to
new_edits[rows, cols] <<- subset
}
tryCatch(
do_assign(),
warning = function(w) {
if (w$message %like% "invalid factor level") {
vapply(FUN.VALUE = logical(1), cols, function(col) {
new_edits[, col] <<- factor(
x = as.character(pm_pull(new_edits, col)),
levels = unique(c(to, levels(pm_pull(new_edits, col))))
)
TRUE
})
suppressWarnings(do_assign())
warning_(
"in {.help [{.fun interpretive_rules}](AMR::interpretive_rules)}: value \"", to, "\" added to the factor levels of column",
ifelse(length(cols) == 1, "", "s"),
" ", vector_and(cols, quotes = "`", sort = FALSE),
" because this value was not an existing factor level."
)
txt_warning()
warned <<- FALSE
} else {
warning_("in {.help [{.fun interpretive_rules}](AMR::interpretive_rules)}: ", w$message)
txt_warning()
}
},
error = function(e) {
txt_error()
stop(
paste0(
"In row(s) ", paste(rows[seq_len(min(length(rows), 10))], collapse = ","),
ifelse(length(rows) > 10, "...", ""),
" while writing value '", to,
"' to column(s) `", paste(cols, collapse = "`, `"),
"`:\n", conditionMessage(e)
),
call. = FALSE
)
}
)
track_changes$output <- new_edits
if ((isTRUE(info) || isTRUE(verbose)) && !isTRUE(all.equal(x, track_changes$output))) {
get_original_rows <- function(rowids) {
as.integer(rownames(original_data[which(original_data$.rowid %in% rowids), , drop = FALSE]))
}
for (i in seq_len(length(cols))) {
verbose_new <- data.frame(
rowid = new_edits[rows, ".rowid", drop = TRUE],
col = cols[i],
mo_fullname = new_edits[rows, "fullname", drop = TRUE],
old = x[rows, cols[i], drop = TRUE],
new = to,
rule = font_stripstyle(rule[1]),
rule_group = font_stripstyle(rule[2]),
rule_name = font_stripstyle(rule[3]),
rule_source = font_stripstyle(rule[4]),
stringsAsFactors = FALSE
)
colnames(verbose_new) <- c(
"rowid", "col", "mo_fullname", "old", "new",
"rule", "rule_group", "rule_name", "rule_source"
)
verbose_new <- verbose_new %pm>% pm_filter(old != new | is.na(old) | is.na(new) & !is.na(old))
# save changes to data set 'verbose_info'
track_changes$verbose_info <- rbind_AMR(
track_changes$verbose_info,
verbose_new
)
# count adds and changes
track_changes$added <- track_changes$added + verbose_new %pm>%
pm_filter(is.na(old)) %pm>%
pm_pull(rowid) %pm>%
get_original_rows() %pm>%
length()
track_changes$changed <- track_changes$changed + verbose_new %pm>%
pm_filter(!is.na(old)) %pm>%
pm_pull(rowid) %pm>%
get_original_rows() %pm>%
length()
}
}
}
return(track_changes)
}
#' @rdname interpretive_rules
#' @export
eucast_dosage <- function(ab, administration = "iv", version_breakpoints = 15) {
meet_criteria(ab, allow_class = c("character", "numeric", "integer", "factor"))
meet_criteria(administration, allow_class = "character", is_in = dosage$administration[!is.na(dosage$administration)], has_length = 1)
meet_criteria(version_breakpoints, allow_class = c("numeric", "integer"), has_length = 1, is_in = as.double(names(EUCAST_VERSION_BREAKPOINTS)))
# show used version_breakpoints number once per session (AMR_env will reload every session)
if (missing(version_breakpoints) && message_not_thrown_before("eucast_dosage", "v", gsub("[^0-9]", "", version_breakpoints), entire_session = TRUE)) {
message_(
"Dosages for antimicrobial drugs, as meant for ",
format_eucast_version_nr(version_breakpoints, markdown = FALSE), ". ",
font_red("This note will be shown once per session.")
)
}
ab <- as.ab(ab)
lst <- vector("list", length = length(ab))
for (i in seq_len(length(ab))) {
df <- AMR::dosage[which(AMR::dosage$eucast_version == version_breakpoints & AMR::dosage$ab == ab[i] & AMR::dosage$administration == administration), , drop = FALSE]
lst[[i]] <- list(
ab = "",
name = "",
standard_dosage = ifelse("standard_dosage" %in% df$type,
trimws2(df[which(df$type == "standard_dosage"), "original_txt", drop = TRUE]),
NA_character_
),
high_dosage = ifelse("high_dosage" %in% df$type,
trimws2(df[which(df$type == "high_dosage"), "original_txt", drop = TRUE]),
NA_character_
),
eucast_version = df$eucast_version[1]
)
}
out <- do.call(rbind_AMR, lapply(lst, as.data.frame, stringsAsFactors = FALSE))
rownames(out) <- NULL
out$ab <- ab
out$name <- ab_name(ab, language = NULL)
if (pkg_is_available("tibble")) {
import_fn("as_tibble", "tibble")(out)
} else {
out
}
}