From 5758ad993fa2b80cba9297a83786a4a59556e544 Mon Sep 17 00:00:00 2001 From: Awa Synthia Date: Tue, 8 Oct 2024 00:29:13 +0300 Subject: [PATCH 01/24] add error handling in tree.R Signed-off-by: Awa Synthia --- R/tree.R | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/R/tree.R b/R/tree.R index 01e9ead5..9386bbfe 100755 --- a/R/tree.R +++ b/R/tree.R @@ -51,6 +51,30 @@ convert_fa2tre <- function(fa_path = here("data/alns/pspa_snf7.fa"), # fa_path=here("data/alns/pspa_snf7.fa") # tre_path=here("data/alns/pspa_snf7.tre") # fasttree_path=here("src/FastTree") + + # Check if the FASTA file exists + if (!file.exists(fa_path)) { + stop(paste("Error: The FASTA file does not exist at:", fa_path)) + } + + # Check if the FastTree executable exists + if (!file.exists(fasttree_path)) { + stop(paste("Error: The FastTree executable does not exist at:", + fasttree_path)) + } + + # Check if the output directory exists + tre_dir <- dirname(tre_path) + if (!dir.exists(tre_dir)) { + stop(paste("Error: The output directory does not exist:", tre_dir)) + } + + # Check if the output file already exists + if (file.exists(tre_path)) { + cat("Warning: The output file already exists and will be overwritten:", + tre_path, "\n") + } + print(fa_path) system2( command = fasttree_path, @@ -83,8 +107,18 @@ convert_fa2tre <- function(fa_path = here("data/alns/pspa_snf7.fa"), #' #' @examples generate_trees <- function(aln_path = here("data/alns/")) { + + # Check if the alignment directory exists + if (!dir.exists(aln_path)) { + stop(paste("Error: The alignment directory does not exist:", aln_path)) + } # finding all fasta alignment files fa_filenames <- list.files(path = aln_path, pattern = "*.fa") + # Check if any FASTA files were found + if (length(fa_filenames) == 0) { + stop("Error: No FASTA files found in the specified directory.") + } + fa_paths <- paste0(aln_path, fa_filenames) variable <- str_replace_all(basename(fa_filenames), pattern = ".fa", replacement = "" @@ -139,6 +173,23 @@ generate_fa2tre <- function(fa_file = "data/alns/pspa_snf7.fa", ## SAMPLE ARGS # fa_file="data/alns/pspa_snf7.fa" # out_file="data/alns/pspa_snf7.tre" + + # Check if the FASTA file exists + if (!file.exists(fa_file)) { + stop(paste("Error: The FASTA file does not exist at:", fa_file)) + } + + # Check if the output directory exists + out_dir <- dirname(out_file) + if (!dir.exists(out_dir)) { + stop(paste("Error: The output directory does not exist:", out_dir)) + } + + # Check if the output file already exists + if (file.exists(out_file)) { + cat("Warning: The output file already exists and will be overwritten:", + out_file, "\n") + } ########################### ## Approach 1 From bf40f2da6cb35beb466a92dadf5e39c943b35d5d Mon Sep 17 00:00:00 2001 From: Awa Synthia Date: Tue, 8 Oct 2024 00:45:02 +0300 Subject: [PATCH 02/24] add error handling Signed-off-by: Awa Synthia --- R/summarize.R | 149 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) diff --git a/R/summarize.R b/R/summarize.R index a9b13e43..4b0eaa55 100644 --- a/R/summarize.R +++ b/R/summarize.R @@ -41,6 +41,23 @@ filter_by_doms <- function(prot, column = "DomArch", doms_keep = c(), doms_remov # Any row containing a domain in doms_remove will be removed # ^word$|(?<=\+)word$|(?<=\+)word(?=\+)|word(?=\+) + + # Check if prot is a data frame + if (!is.data.frame(prot)) { + stop("Error: 'prot' must be a data frame.") + } + + # Check if the specified column exists in the data frame + if (!column %in% names(prot)) { + stop(paste("Error: The specified column '", column, "' does not exist + in the data frame.", sep = "")) + } + + # If doms_keep or doms_remove are not provided, inform the user + if (length(doms_keep) == 0 && length(doms_remove) == 0) { + warning("Warning: No domains specified to keep or remove. Returning the + original data frame.") + } # Make regex safe doms_keep <- str_replace_all(string = doms_keep, pattern = "\\(", replacement = "\\\\(") @@ -105,6 +122,23 @@ filter_by_doms <- function(prot, column = "DomArch", doms_keep = c(), doms_remov #' count_bycol() #' } count_bycol <- function(prot = prot, column = "DomArch", min.freq = 1) { + + # Check if 'prot' is a data frame + if (!is.data.frame(prot)) { + stop("Error: 'prot' must be a data frame.") + } + + # Check if the specified column exists in the data frame + if (!column %in% names(prot)) { + stop(paste("Error: The specified column '", column, "' does not exist in + the data frame.", sep = "")) + } + + # Check if min.freq is a positive integer + if (!is.numeric(min.freq) || length(min.freq) != 1 || min.freq < 1 || + floor(min.freq) != min.freq) { + stop("Error: 'min.freq' must be a positive integer.") + } counts <- prot %>% select(column) %>% table() %>% @@ -139,6 +173,24 @@ count_bycol <- function(prot = prot, column = "DomArch", min.freq = 1) { #' } #' elements2words <- function(prot, column = "DomArch", conversion_type = "da2doms") { + # Check if 'prot' is a data frame + if (!is.data.frame(prot)) { + stop("Error: 'prot' must be a data frame.") + } + + # Check if the specified column exists in the data frame + if (!column %in% names(prot)) { + stop(paste("Error: The specified column '", column, "' does not exist in + the data frame.", sep = "")) + } + + # Check for valid conversion_type values + valid_types <- c("da2doms", "doms2da") + if (!conversion_type %in% valid_types) { + stop(paste("Error: Invalid 'conversion_type'. Must be one of:", + paste(valid_types, collapse = ", "))) + } + z1 <- prot %>% dplyr::pull(column) %>% str_replace_all("\\,", " ") %>% @@ -189,6 +241,11 @@ elements2words <- function(prot, column = "DomArch", conversion_type = "da2doms" #' } #' words2wc <- function(string) { + # Check if 'string' is a character vector of length 1 + if (!is.character(string) || length(string) != 1) { + stop("Error: 'string' must be a single character vector.") + } + df_word_count <- string %>% # reduce spaces with length 2 or greater to a single space str_replace_all("\\s{2,}", " ") %>% @@ -230,6 +287,22 @@ words2wc <- function(string) { #' filter_freq() #' } filter_freq <- function(x, min.freq) { + + # Check if 'x' is a data frame + if (!is.data.frame(x)) { + stop("Error: 'x' must be a data frame.") + } + + # Check if 'min.freq' is a positive integer + if (!is.numeric(min.freq) || length(min.freq) != 1 || min.freq < 1 || + floor(min.freq) != min.freq) { + stop("Error: 'min.freq' must be a positive integer.") + } + + # Check if the 'freq' column exists in the data frame + if (!"freq" %in% names(x)) { + stop("Error: The data frame must contain a 'freq' column.") + } x %>% filter(freq >= min.freq) } @@ -259,6 +332,23 @@ filter_freq <- function(x, min.freq) { #' summarize_bylin <- function(prot = "prot", column = "DomArch", by = "Lineage", query) { + # Check if 'prot' is a data frame + if (!is.data.frame(prot)) { + stop("Error: 'prot' must be a data frame.") + } + + # Check if the specified column exists in the data frame + if (!column %in% names(prot)) { + stop(paste("Error: The specified column '", column, "' does not exist in + the data frame.", sep = "")) + } + + # Check if the 'by' column exists in the data frame + if (!by %in% names(prot)) { + stop(paste("Error: The specified 'by' column '", by, "' does not exist + n the data frame.", sep = "")) + } + column <- sym(column) by <- sym(by) if (query == "all") { @@ -295,6 +385,19 @@ summarize_bylin <- function(prot = "prot", column = "DomArch", by = "Lineage", #' summ.DA.byLin() #' } summ.DA.byLin <- function(x) { + # Check if 'x' is a data frame + if (!is.data.frame(x)) { + stop("Error: 'x' must be a data frame.") + } + + # Check if required columns exist in the data frame + required_columns <- c("DomArch", "Lineage") + missing_columns <- setdiff(required_columns, names(x)) + + if (length(missing_columns) > 0) { + stop(paste("Error: The following required columns are + missing:", paste(missing_columns, collapse = ", "))) + } ## Note: it is better to reserve dots for S3 Objects. Consider replacing '.' with '_' x %>% filter(!grepl("^-$", DomArch)) %>% @@ -321,6 +424,10 @@ summ.DA.byLin <- function(x) { #' summ.DA() #' } summ.DA <- function(x) { + # Check if 'x' is a data frame + if (!is.data.frame(x)) { + stop("Error: 'x' must be a data frame.") + } ## Note: it is better to reserve dots for S3 Objects. Consider replacing '.' with '_' x %>% group_by(DomArch) %>% @@ -344,6 +451,10 @@ summ.DA <- function(x) { #' summ.GC.byDALin #' } summ.GC.byDALin <- function(x) { + # Check if 'x' is a data frame + if (!is.data.frame(x)) { + stop("Error: 'x' must be a data frame.") + } ## Note: it is better to reserve dots for S3 Objects. Consider replacing '.' with '_' x %>% filter(!grepl("^-$", GenContext)) %>% @@ -369,6 +480,10 @@ summ.GC.byDALin <- function(x) { #' summ.GC.byLin() #' } summ.GC.byLin <- function(x) { + # Check if 'x' is a data frame + if (!is.data.frame(x)) { + stop("Error: 'x' must be a data frame.") + } ## Note: it is better to reserve dots for S3 Objects. Consider replacing '.' with '_' x %>% filter(!grepl("^-$", GenContext)) %>% @@ -394,6 +509,10 @@ summ.GC.byLin <- function(x) { #' summ.GC() #' } summ.GC <- function(x) { + # Check if 'x' is a data frame + if (!is.data.frame(x)) { + stop("Error: 'x' must be a data frame.") + } ## Note: it is better to reserve dots for S3 Objects. Consider replacing '.' with '_' x %>% group_by(GenContext) %>% @@ -442,6 +561,31 @@ total_counts <- function(prot, column = "DomArch", lineage_col = "Lineage", cutoff = 90, RowsCutoff = FALSE, digits = 2 # type = "GC" ) { + # Check if 'prot' is a data frame + if (!is.data.frame(prot)) { + stop("Error: 'prot' must be a data frame.") + } + + # Check if the specified columns exist in the data frame + required_columns <- c(column, lineage_col) + missing_columns <- setdiff(required_columns, names(prot)) + + if (length(missing_columns) > 0) { + stop(paste("Error: The following required columns are missing:", + paste(missing_columns, collapse = ", "))) + } + + # Check that cutoff is a numeric value between 0 and 100 + if (!is.numeric(cutoff) || length(cutoff) != 1 || cutoff < 0 || cutoff > 100) { + stop("Error: 'cutoff' must be a numeric value between 0 and 100.") + } + + # Check that digits is a non-negative integer + if (!is.numeric(digits) || length(digits) != 1 || digits < 0 || + floor(digits) != digits) { + stop("Error: 'digits' must be a non-negative integer.") + } + column <- sym(column) prot <- select(prot, {{ column }}, {{ lineage_col }}) %>% @@ -601,6 +745,11 @@ total_counts <- function(prot, column = "DomArch", lineage_col = "Lineage", #' find_paralogs(pspa) #' } find_paralogs <- function(prot) { + # Check if 'prot' is a data frame + if (!is.data.frame(prot)) { + stop("Error: 'prot' must be a data frame.") + } + # Remove eukaryotes prot <- prot %>% filter(!grepl("^eukaryota", Lineage)) paralogTable <- prot %>% From ca1ac21d2c29e95f8da688c677526d281d98aa36 Mon Sep 17 00:00:00 2001 From: Awa Synthia Date: Tue, 8 Oct 2024 00:53:35 +0300 Subject: [PATCH 03/24] add error handling in reverse_operons Signed-off-by: Awa Synthia --- R/reverse_operons.R | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/R/reverse_operons.R b/R/reverse_operons.R index e4bbd50e..4b1fb934 100755 --- a/R/reverse_operons.R +++ b/R/reverse_operons.R @@ -12,6 +12,10 @@ #' #' @examples reveql <- function(prot) { + # Check if 'prot' is a data frame + if (!is.data.frame(prot)) { + stop("Error: 'prot' must be a data frame.") + } w <- prot # $GenContext.orig # was 'x' y <- rep(NA, length(w)) @@ -66,6 +70,10 @@ reveql <- function(prot) { #' #' @examples reverse_operon <- function(prot) { + # Check if 'prot' is a data frame + if (!is.data.frame(prot)) { + stop("Error: 'prot' must be a data frame.") + } gencontext <- prot$GenContext gencontext <- gsub(pattern = ">", replacement = ">|", x = gencontext) From a683ac05238e30e3df6b249d7c73e3e53e4f3ee8 Mon Sep 17 00:00:00 2001 From: Awa Synthia Date: Tue, 8 Oct 2024 01:16:35 +0300 Subject: [PATCH 04/24] add input checks in pre-msa-tree Signed-off-by: Awa Synthia --- R/pre-msa-tree.R | 145 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 145 insertions(+) diff --git a/R/pre-msa-tree.R b/R/pre-msa-tree.R index 44979c3c..cdfd222d 100644 --- a/R/pre-msa-tree.R +++ b/R/pre-msa-tree.R @@ -50,6 +50,11 @@ api_key <- Sys.getenv("ENTREZ_API_KEY", unset = "YOUR_KEY_HERE") #' #' @examples to_titlecase <- function(x, y = " ") { + # Check if the input is NULL or not a character + if (is.null(x) || !is.character(x)) { + stop("Error: Input must be a non-null character string.") + } + s <- strsplit(x, y)[[1]] paste(toupper(substring(s, 1, 1)), substring(s, 2), sep = "", collapse = y @@ -101,6 +106,25 @@ add_leaves <- function(aln_file = "", lin_file = "data/rawdata_tsv/all_semiclean.txt", # !! finally change to all_clean.txt!! # lin_file="data/rawdata_tsv/PspA.txt", reduced = FALSE) { + + #Check if the alignment file is provided and exists + if (nchar(aln_file) == 0) { + stop("Error: Alignment file path must be provided.") + } + + if (!file.exists(aln_file)) { + stop(paste("Error: The alignment file '", aln_file, "' does not exist.")) + } + + # Check if the lineage file exists + if (!file.exists(lin_file)) { + stop(paste("Error: The lineage file '", lin_file, "' does not exist.")) + } + + # Check that the 'reduced' parameter is logical + if (!is.logical(reduced) || length(reduced) != 1) { + stop("Error: 'reduced' must be a single logical value (TRUE or FALSE).") + } ## SAMPLE ARGS # aln_file <- "data/rawdata_aln/pspc.gismo.aln" # lin_file <- "data/rawdata_tsv/all_semiclean.txt" @@ -212,6 +236,19 @@ add_leaves <- function(aln_file = "", add_name <- function(data, accnum_col = "AccNum", spec_col = "Species", lin_col = "Lineage", lin_sep = ">", out_col = "Name") { + # Check if the data is a data fram + if (!is.data.frame(data)) { + stop("Error: The input 'data' must be a data frame") + } + + # Check that the specified columns exist in the data + required_cols <- c(accnum_col, spec_col, lin_col) + missing_cols <- setdiff(required_cols, names(data)) + if (length(missing_cols) > 0) { + stop(paste("Error: The following columns are missing from the data:", + paste(missing_cols, collapse = ", "))) + } + cols <- c(accnum_col, "Kingdom", "Phylum", "Genus", "Spp") split_data <- data %>% separate( @@ -294,6 +331,24 @@ convert_aln2fa <- function(aln_file = "", lin_file = "data/rawdata_tsv/all_semiclean.txt", # !! finally change to all_clean.txt!! fa_outpath = "", reduced = FALSE) { + #Check if the alignment file is provided and exists + if (nchar(aln_file) == 0) { + stop("Error: Alignment file path must be provided.") + } + + if (!file.exists(aln_file)) { + stop(paste("Error: The alignment file '", aln_file, "' does not exist.")) + } + + # Check if the lineage file exists + if (!file.exists(lin_file)) { + stop(paste("Error: The lineage file '", lin_file, "' does not exist.")) + } + + # Check that the 'reduced' parameter is logical + if (!is.logical(reduced) || length(reduced) != 1) { + stop("Error: 'reduced' must be a single logical value (TRUE or FALSE).") + } ## SAMPLE ARGS # aln_file <- "data/rawdata_aln/pspc.gismo.aln" # lin_file <- "data/rawdata_tsv/all_semiclean.txt" @@ -341,6 +396,20 @@ convert_aln2fa <- function(aln_file = "", #' #' @examples map_acc2name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") { + # Check if acc2name is a data frame + if (!is.data.frame(acc2name)) { + stop("Error: acc2name must be a data frame.") + } + + # Check if the specified columns exist in the data frame + if (!(acc_col %in% colnames(acc2name))) { + stop("Error: The specified acc_col '", acc_col, "' does not exist in + acc2name.") + } + if (!(name_col %in% colnames(acc2name))) { + stop("Error: The specified name_col '", name_col, "' does not exist in + acc2name.") + } # change to be the name equivalent to an add_names column # Find the first ' ' end_acc <- str_locate(line, " ")[[1]] @@ -371,6 +440,17 @@ map_acc2name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") #' @examples rename_fasta <- function(fa_path, outpath, replacement_function = map_acc2name, ...) { + # Check if the input FASTA file exists + if (!file.exists(fa_path)) { + stop("Error: The input FASTA file does not exist at the specified + path: ", fa_path) + } + + # Check if the output path is writable + outdir <- dirname(outpath) + if (!dir.exists(outdir)) { + stop("Error: The output directory does not exist: ", outdir) + } lines <- read_lines(fa_path) res <- map(lines, function(x) { if (strtrim(x, 1) == ">") { @@ -419,6 +499,24 @@ generate_all_aln2fa <- function(aln_path = here("data/rawdata_aln/"), fa_outpath = here("data/alns/"), lin_file = here("data/rawdata_tsv/all_semiclean.txt"), reduced = F) { + # Check if the alignment path exists + if (!dir.exists(aln_path)) { + stop("Error: The alignment directory does not exist at the specified + path: ", aln_path) + } + + # Check if the output path exists; if not, attempt to create it + if (!dir.exists(fa_outpath)) { + dir.create(fa_outpath, recursive = TRUE) + message("Note: The output directory did not exist and has been created: ", + fa_outpath) + } + + # Check if the linear file exists + if (!file.exists(lin_file)) { + stop("Error: The linear file does not exist at the specified path: ", + lin_file) + } # library(here) # library(tidyverse) # aln_path <- here("data/rawdata_aln/") @@ -476,6 +574,13 @@ generate_all_aln2fa <- function(aln_path = here("data/rawdata_aln/"), #' EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> acc2fa(outpath = "ebi.fa") #' } acc2fa <- function(accessions, outpath, plan = "sequential") { + if (!is.character(accessions) || length(accessions) == 0) { + stop("Error: 'accessions' must be a non-empty character vector.") + } + + if (!dir.exists(dirname(outpath))) { + stop("Error: The output directory does not exist: ", dirname(outpath)) + } # validation stopifnot(length(accessions) > 0) @@ -569,6 +674,23 @@ acc2fa <- function(accessions, outpath, plan = "sequential") { RepresentativeAccNums <- function(prot_data, reduced = "Lineage", accnum_col = "AccNum") { + + # Validate input + if (!is.data.frame(prot_data)) { + stop("Error: 'prot_data' must be a data frame.") + } + + # Check if the reduced column exists in prot_data + if (!(reduced %in% colnames(prot_data))) { + stop("Error: The specified reduced column '", reduced, "' does not + exist in the data frame.") + } + + # Check if the accnum_col exists in prot_data + if (!(accnum_col %in% colnames(prot_data))) { + stop("Error: The specified accession number column '", accnum_col, "' + does not exist in the data frame.") + } # Get Unique reduced column and then bind the AccNums back to get one AccNum per reduced column reduced_sym <- sym(reduced) accnum_sym <- sym(accnum_col) @@ -614,6 +736,14 @@ RepresentativeAccNums <- function(prot_data, #' #' @examples alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { + # Validate the input FASTA file + if (!file.exists(fasta_file)) { + stop("Error: The FASTA file does not exist: ", fasta_file) + } + + if (file_ext(fasta_file) != "fasta" && file_ext(fasta_file) != "fa") { + stop("Error: The specified file is not a valid FASTA file: ", fasta_file) + } fasta <- readAAStringSet(fasta_file) aligned <- switch(tool, @@ -648,6 +778,21 @@ alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { #' #' @examples write.MsaAAMultipleAlignment <- function(alignment, outpath) { + # Validate input alignment + if (!inherits(alignment, "AAMultipleAlignment")) { + stop("Error: The alignment must be of type 'AAMultipleAlignment'.") + } + + # Check the output path is a character string + if (!is.character(outpath) || nchar(outpath) == 0) { + stop("Error: Invalid output path specified.") + } + + # Check if the output directory exists + outdir <- dirname(outpath) + if (!dir.exists(outdir)) { + stop("Error: The output directory does not exist: ", outdir) + } l <- length(rownames(alignment)) fasta <- "" for (i in 1:l) From ae9e737616acc95e03ee4b7f4ca997e68675cc0d Mon Sep 17 00:00:00 2001 From: teddyCodex Date: Tue, 8 Oct 2024 22:20:07 +0100 Subject: [PATCH 05/24] refactor: externalize internal functions for global use --- .gitignore | 1 + R/plotting.R | 87 +++++++++++++++++++++++++++++----------------------- 2 files changed, 49 insertions(+), 39 deletions(-) diff --git a/.gitignore b/.gitignore index 50d1aa13..ef11006e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .Rproj.user docs .Rhistory +.DS_Store \ No newline at end of file diff --git a/R/plotting.R b/R/plotting.R index da95ea5f..5d949cd5 100644 --- a/R/plotting.R +++ b/R/plotting.R @@ -18,6 +18,47 @@ # suppressPackageStartupMessages(library(d3r)) # suppressPackageStartupMessages(library(viridis)) +######################## +## Internal Functions ## +######################## +#' +#' +.LevelReduction <- function(lin, level) { + if (level == 1) { + gt_loc <- str_locate(lin, ">")[[1]] + if (is.na(gt_loc)) { + # No '>' in lineage + return(lin) + } else { + lin <- substring(lin, first = 0, last = (gt_loc - 1)) + return(lin) + } + } + # Out of bounds guard + gt_loc <- str_locate_all(lin, ">")[[1]] + l <- length(gt_loc) / 2 + if (level > l) { + # Not enough '>' in lineage + return(lin) + } else { + gt_loc <- gt_loc[level, ][1] %>% as.numeric() + lin <- substring(lin, first = 0, last = (gt_loc - 1)) + return(lin) + } +} + +.GetKingdom <- function(lin) { + gt_loc <- str_locate(lin, ">")[, "start"] + if (is.na(gt_loc)) { + # No '>' in lineage + return(lin) + } else { + kingdom <- substring(lin, first = 0, last = (gt_loc - 1)) + return(kingdom) + } +} + + #' Shorten Lineage #' #' @param data @@ -665,30 +706,6 @@ plotLineageDomainRepeats <- function(query_data, colname) { #' } #' plotLineageHeatmap <- function(prot, domains_of_interest, level = 3, label.size = 8) { - .LevelReduction <- function(lin) { - if (level == 1) { - gt_loc <- str_locate(lin, ">")[[1]] - if (is.na(gt_loc)) { - # No '>' in lineage - return(lin) - } else { - lin <- substring(lin, first = 0, last = (gt_loc - 1)) - return(lin) - } - } - #### Add guard here to protect from out of bounds - gt_loc <- str_locate_all(lin, ">")[[1]] # [(level-1),][1] - l <- length(gt_loc) / 2 - if (level > l) { - # Not enough '>' in lineage - return(lin) - } else { - gt_loc <- gt_loc[level, ][1] %>% as.numeric() - lin <- substring(lin, first = 0, last = (gt_loc - 1)) - return(lin) - } - } - all_grouped <- data.frame("Query" = character(0), "Lineage" = character(0), "count" = integer()) for (dom in domains_of_interest) { @@ -703,19 +720,7 @@ plotLineageHeatmap <- function(prot, domains_of_interest, level = 3, label.size all_grouped <- dplyr::union(all_grouped, domSub) } - .GetKingdom <- function(lin) { - gt_loc <- str_locate(lin, ">")[, "start"] - - if (is.na(gt_loc)) { - # No '>' in lineage - return(lin) - } else { - kingdom <- substring(lin, first = 0, last = (gt_loc - 1)) - return(kingdom) - } - } - - all_grouped <- all_grouped %>% mutate(ReducedLin = unlist(purrr::map(Lineage, .LevelReduction))) + all_grouped <- all_grouped %>% mutate(ReducedLin = unlist(purrr::map(Lineage, ~.LevelReduction(.x, level)))) all_grouped_reduced <- all_grouped %>% group_by(Query, ReducedLin) %>% @@ -739,6 +744,10 @@ plotLineageHeatmap <- function(prot, domains_of_interest, level = 3, label.size append(eukaryota_colors) %>% append(virus_colors) + if (length(colors) < length(unique(all_grouped_reduced$ReducedLin))) { + colors <- rep("black", length(unique(all_grouped_reduced$ReducedLin))) # Fallback to black + } + all_grouped_reduced$ReducedLin <- map( all_grouped_reduced$ReducedLin, function(lin) { @@ -766,7 +775,7 @@ plotLineageHeatmap <- function(prot, domains_of_interest, level = 3, label.size ) ggplot( data = all_grouped_reduced, - aes_string(x = "ReducedLin", y = "Query") + aes(x = "ReducedLin", y = "Query") ) + geom_tile( data = subset( @@ -774,7 +783,7 @@ plotLineageHeatmap <- function(prot, domains_of_interest, level = 3, label.size !is.na(count) ), aes(fill = count), - colour = "darkred", size = 0.3 + colour = "darkred", linewidth = 0.3 ) + # , width=0.7, height=0.7), scale_fill_gradient(low = "white", high = "darkred") + # scale_x_discrete(position="top") + From 823af96d484a1ec075548ce181f52147cff54af5 Mon Sep 17 00:00:00 2001 From: David Mayer Date: Thu, 10 Oct 2024 09:13:26 -0600 Subject: [PATCH 06/24] - remove old .Rd leftovers and update with new docs - let R-CMD sort NAMESPACE --- NAMESPACE | 1 - man/IPG2Lineage.Rd | 3 ++- man/acc2Lineage.Rd | 3 ++- man/acc2lin.Rd | 0 man/efetchIPG.Rd | 3 ++- man/efetch_ipg.Rd | 0 man/ipg2lin.Rd | 0 man/sink.reset.Rd | 0 man/sinkReset.Rd | 1 + 9 files changed, 7 insertions(+), 4 deletions(-) delete mode 100644 man/acc2lin.Rd delete mode 100644 man/efetch_ipg.Rd delete mode 100644 man/ipg2lin.Rd delete mode 100644 man/sink.reset.Rd diff --git a/NAMESPACE b/NAMESPACE index 50af36df..078f971b 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -77,7 +77,6 @@ export(prepareColumnParams) export(prepareSingleColumnParams) export(proteinAcc2TaxID) export(proteinAcc2TaxID_old) -export(prot2tax_old) export(removeAsterisks) export(removeEmptyRows) export(removeTails) diff --git a/man/IPG2Lineage.Rd b/man/IPG2Lineage.Rd index e24ab617..f8434c7f 100644 --- a/man/IPG2Lineage.Rd +++ b/man/IPG2Lineage.Rd @@ -38,7 +38,8 @@ This file can be generated using the \link[MolEvolvR]{downloadAssemblySummary} f Describe return, in detail } \description{ -Takes the resulting file of an efetch run on the ipg database and +Takes the resulting file +of an efetch run on the ipg database and Takes the resulting file of an efetch run on the ipg database and append lineage, and taxid columns diff --git a/man/acc2Lineage.Rd b/man/acc2Lineage.Rd index a24bdc9a..836a677f 100644 --- a/man/acc2Lineage.Rd +++ b/man/acc2Lineage.Rd @@ -38,7 +38,8 @@ on the ipg database. If NULL, the file will not be written. Defaults to NULL} Describe return, in detail } \description{ -This function combines 'efetchIPG()' and 'IPG2Lineage()' to map a set +This function combines 'efetchIPG()' +and 'IPG2Lineage()' to map a set of protein accessions to their assembly (GCA_ID), tax ID, and lineage. Function to map protein accession numbers to lineage diff --git a/man/acc2lin.Rd b/man/acc2lin.Rd deleted file mode 100644 index e69de29b..00000000 diff --git a/man/efetchIPG.Rd b/man/efetchIPG.Rd index 6a5d85a4..5d2e8372 100644 --- a/man/efetchIPG.Rd +++ b/man/efetchIPG.Rd @@ -23,7 +23,8 @@ the ipg database} Describe return, in detail } \description{ -Perform efetch on the ipg database and write the results to out_path +Perform efetch on the ipg database +and write the results to out_path Perform efetch on the ipg database and write the results to out_path } diff --git a/man/efetch_ipg.Rd b/man/efetch_ipg.Rd deleted file mode 100644 index e69de29b..00000000 diff --git a/man/ipg2lin.Rd b/man/ipg2lin.Rd deleted file mode 100644 index e69de29b..00000000 diff --git a/man/sink.reset.Rd b/man/sink.reset.Rd deleted file mode 100644 index e69de29b..00000000 diff --git a/man/sinkReset.Rd b/man/sinkReset.Rd index 0285c0b2..e3fc7ce4 100644 --- a/man/sinkReset.Rd +++ b/man/sinkReset.Rd @@ -8,6 +8,7 @@ sinkReset() } \value{ No return, but run to close all outstanding \code{sink()}s +and handles any errors or warnings that occur during the process. } \description{ Sink Reset From b116442be77ea2dc267b638f4ecd604a090a9ede Mon Sep 17 00:00:00 2001 From: Awa Synthia Date: Fri, 11 Oct 2024 01:40:21 +0300 Subject: [PATCH 07/24] document functions Signed-off-by: Awa Synthia --- NAMESPACE | 1 + R/CHANGED-pre-msa-tree.R | 108 ++++++-- R/blastWrappers.R | 51 ++-- R/cleanup.R | 81 +++--- R/combine_analysis.R | 28 ++- R/combine_files.R | 24 +- R/create_lineage_lookup.R | 17 +- R/fa2domain.R | 21 +- R/ipr2viz.R | 121 ++++++--- R/lineage.R | 155 +++++++++--- R/msa.R | 20 +- R/networks_domarch.R | 39 +-- R/networks_gencontext.R | 36 ++- R/plotme.R | 43 ++-- R/plotting.R | 230 ++++++++++++------ R/pre-msa-tree.R | 114 ++++++--- R/reverse_operons.R | 38 ++- man/BinaryDomainNetwork.Rd | 24 +- man/GCA2Lineage.Rd | 15 +- man/GenContextNetwork.Rd | 11 +- man/IPG2Lineage.Rd | 16 ++ man/RepresentativeAccNums.Rd | 23 +- man/acc2FA.Rd | 39 +++ man/acc2Lineage.Rd | 15 +- man/acc2fa.Rd | 16 +- man/addLeaves2Alignment.Rd | 4 + man/addLineage.Rd | 32 ++- man/addName.Rd | 10 + man/addTaxID.Rd | 20 +- man/add_leaves.Rd | 4 + man/add_name.Rd | 9 +- man/alignFasta.Rd | 18 +- man/cleanDomainArchitecture.Rd | 27 +- man/cleanFAHeaders.Rd | 4 +- man/cleanGeneDescription.Rd | 5 +- man/cleanLineage.Rd | 9 +- man/cleanSpecies.Rd | 2 +- man/combine_files.Rd | 26 +- man/combine_full.Rd | 16 +- man/combine_ipr.Rd | 16 +- man/condenseRepeatedDomains.Rd | 2 +- man/convert2TitleCase.Rd | 8 + man/convertAlignment2FA.Rd | 5 + man/convert_aln2fa.Rd | 9 +- man/{countbycolumn.Rd => countByColumn.Rd} | 0 man/createWordCloud2Element.Rd | 13 +- man/createWordCloudElement.Rd | 13 +- man/create_lineage_lookup.Rd | 19 +- man/domain_network.Rd | 17 +- man/downloadAssemblySummary.Rd | 16 +- man/efetchIPG.Rd | 12 +- man/extractAccNum.Rd | 3 +- ...{filterbydomains.Rd => filterByDomains.Rd} | 0 ...terbyfrequency.Rd => filterByFrequency.Rd} | 0 man/{findparalogs.Rd => findParalogs.Rd} | 0 man/find_top_acc.Rd | 26 +- man/gc_undirected_network.Rd | 27 +- man/generateAllAlignments2FA.Rd | 19 +- man/generate_all_aln2fa.Rd | 18 +- man/generate_msa.Rd | 15 +- man/get_accnums_from_fasta_file.Rd | 19 +- man/ipr2viz.Rd | 45 +++- man/ipr2viz_web.Rd | 46 +++- man/mapAcc2Name.Rd | 15 +- man/map_acc2name.Rd | 15 +- man/msa_pdf.Rd | 8 +- man/plotLineageDA.Rd | 8 + man/plotLineageDomainRepeats.Rd | 11 +- man/plotLineageHeatmap.Rd | 5 + man/plotLineageNeighbors.Rd | 5 + man/plotLineageQuery.Rd | 20 +- man/plotLineageSunburst.Rd | 31 ++- man/plotStackedLineage.Rd | 39 ++- man/plotSunburst.Rd | 6 +- man/plotUpSet.Rd | 19 +- man/prepareColumnParams.Rd | 17 +- man/prepareSingleColumnParams.Rd | 18 +- man/proteinAcc2TaxID.Rd | 26 +- man/proteinAcc2TaxID_old.Rd | 20 +- man/removeAsterisks.Rd | 10 +- man/removeEmptyRows.Rd | 3 +- man/removeTails.Rd | 3 +- man/renameFA.Rd | 9 + man/rename_fasta.Rd | 9 + man/replaceQuestionMarks.Rd | 4 +- man/reveql.Rd | 19 +- man/reverse_operon.Rd | 21 +- man/runIPRScan.Rd | 24 +- man/run_deltablast.Rd | 29 ++- man/run_rpsblast.Rd | 27 +- man/selectLongestDuplicate.Rd | 9 +- man/shortenLineage.Rd | 24 +- ...rizebylineage.Rd => summarizeByLineage.Rd} | 0 man/theme_genes2.Rd | 13 + man/to_titlecase.Rd | 7 + ...s.Rd => totalGenContextOrDomArchCounts.Rd} | 0 man/validateCountDF.Rd | 10 +- man/wordcloud3.Rd | 54 +++- ...ords2wordcounts.Rd => words2WordCounts.Rd} | 0 man/write.MsaAAMultipleAlignment.Rd | 16 ++ 100 files changed, 1913 insertions(+), 461 deletions(-) create mode 100644 man/acc2FA.Rd rename man/{countbycolumn.Rd => countByColumn.Rd} (100%) rename man/{filterbydomains.Rd => filterByDomains.Rd} (100%) rename man/{filterbyfrequency.Rd => filterByFrequency.Rd} (100%) rename man/{findparalogs.Rd => findParalogs.Rd} (100%) rename man/{summarizebylineage.Rd => summarizeByLineage.Rd} (100%) rename man/{totalgencontextordomarchcounts.Rd => totalGenContextOrDomArchCounts.Rd} (100%) rename man/{words2wordcounts.Rd => words2WordCounts.Rd} (100%) diff --git a/NAMESPACE b/NAMESPACE index 078f971b..50943690 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -230,6 +230,7 @@ importFrom(purrr,map2) importFrom(purrr,map_chr) importFrom(purrr,pmap) importFrom(purrr,pmap_dfr) +importFrom(rMSA,kalign) importFrom(readr,cols) importFrom(readr,read_delim) importFrom(readr,read_file) diff --git a/R/CHANGED-pre-msa-tree.R b/R/CHANGED-pre-msa-tree.R index c4a97589..76c13859 100644 --- a/R/CHANGED-pre-msa-tree.R +++ b/R/CHANGED-pre-msa-tree.R @@ -40,10 +40,14 @@ api_key <- Sys.getenv("ENTREZ_API_KEY", unset = "YOUR_KEY_HERE") #' @param y Delimitter. Default is space (" "). #' @seealso chartr, toupper, and tolower. #' -#' @return +#' @return Character vector with the input strings converted to title case. +#' #' @export #' #' @examples +#' # Convert a single string to title case +#' convert2TitleCase("hello world") # Returns "Hello World" +#' convert2TitleCase <- function(x, y = " ") { s <- strsplit(x, y)[[1]] paste(toupper(substring(s, 1, 1)), substring(s, 2), @@ -76,7 +80,8 @@ convert2TitleCase <- function(x, y = " ") { #' @importFrom stringr str_sub #' @importFrom tidyr replace_na separate #' -#' @return +#' @return A data frame containing the enriched alignment data with lineage +#' information. #' #' @details The alignment file would need two columns: 1. accession + #' number and 2. alignment. The protein homolog accession to lineage mapping + @@ -203,6 +208,14 @@ addLeaves2Alignment <- function(aln_file = "", #' @export #' #' @examples +#' # Example usage of the addName function +#' data <- data.frame( +#' AccNum = c("ACC123", "ACC456"), +#' Species = c("Homo sapiens", "Mus musculus"), +#' Lineage = c("Eukaryota>Chordata", "Eukaryota>Chordata") +#' ) +#' enriched_data <- addName(data) +#' print(enriched_data) addName <- function(data, accnum_col = "AccNum", spec_col = "Species", lin_col = "Lineage", lin_sep = ">", out_col = "Name") { @@ -278,7 +291,9 @@ addName <- function(data, #' @note Please refer to the source code if you have alternate + #' file formats and/or column names. #' -#' @return +#' @return A character string representing the FASTA formatted sequences. +#' If `fa_outpath` is provided, the FASTA will also be saved to the specified +#' file. #' @export #' #' @examples @@ -323,18 +338,24 @@ convertAlignment2FA <- function(aln_file = "", #' Default renameFA() replacement function. Maps an accession number to its name #' #' @param line The line of a fasta file starting with '>' -#' @param acc2name Data Table containing a column of accession numbers and a name column +#' @param acc2name Data Table containing a column of accession numbers and a +#' name column #' @param acc_col Name of the column containing Accession numbers -#' @param name_col Name of the column containing the names that the accession numbers +#' @param name_col Name of the column containing the names that the accession +#' numbers #' are mapped to #' #' @importFrom dplyr filter pull #' @importFrom rlang sym #' -#' @return +#' @return A character string representing the updated FASTA line, where the +#' accession number is replaced with its corresponding name. #' @export #' #' @examples +#' \dontrun{ +#' mapAcc2Name(">P12345 some description", acc2name, "AccNum", "Name") +#' } mapAcc2Name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") { # change to be the name equivalent to an addNames column # Find the first ' ' @@ -360,10 +381,14 @@ mapAcc2Name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") { #' @importFrom purrr map #' @importFrom readr read_lines write_lines #' -#' @return +#' @return A character vector of the modified lines in the FASTA file. #' @export #' #' @examples +#' \dontrun{ +#' renameFA("path/to/input.fasta", +#' "path/to/output.fasta", mapAcc2Name, acc2name) +#' } renameFA <- function(fa_path, outpath, replacement_function = mapAcc2Name, ...) { lines <- read_lines(fa_path) @@ -389,20 +414,26 @@ renameFA <- function(fa_path, outpath, #' #' @param aln_path Character. Path to alignment files. #' Default is 'here("data/rawdata_aln/")' -#' @param fa_outpath Character. Path to file. Master protein file with AccNum & lineages. +#' @param fa_outpath Character. Path to file. Master protein file with AccNum & +#' lineages. #' Default is 'here("data/rawdata_tsv/all_semiclean.txt")' #' @param lin_file Character. Path to the written fasta file. #' Default is 'here("data/alns/")'. -#' @param reduced Boolean. If TRUE, the fasta file will contain only one sequence per lineage. +#' @param reduced Boolean. If TRUE, the fasta file will contain only one +#' sequence per lineage. #' Default is 'FALSE'. #' #' @importFrom purrr pmap #' @importFrom stringr str_replace_all #' -#' @return +#' @return NULL. The function saves the output FASTA files to the specified +#' directory. #' -#' @details The alignment files would need two columns separated by spaces: 1. AccNum and 2. alignment. The protein homolog file should have AccNum, Species, Lineages. -#' @note Please refer to the source code if you have alternate + file formats and/or column names. +#' @details The alignment files would need two columns separated by spaces: +#' 1. AccNum and 2. alignment. The protein homolog file should have AccNum, +#' Species, Lineages. +#' @note Please refer to the source code if you have alternate + file formats +#' and/or column names. #' #' @export #' @@ -449,24 +480,29 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), #' @author Samuel Chen, Janani Ravi #' @keywords accnum, fasta #' -#' @param accessions Character vector containing protein accession numbers to generate fasta sequences for. +#' @param accessions Character vector containing protein accession numbers to +#' generate fasta sequences for. #' Function may not work for vectors of length > 10,000 #' @param outpath [str] Location where fasta file should be written to. -#' @param plan +#' @param plan Character string specifying the parallel processing strategy to +#' use with the `future` package. Default is "sequential". #' #' @importFrom Biostrings readAAStringSet #' @importFrom future future plan value #' @importFrom purrr map #' @importFrom rentrez entrez_fetch #' -#' @return +#' @return A logical value indicating whether the retrieval and conversion were +#' successful. Returns `TRUE` if successful and `FALSE` otherwise. #' @export #' #' @examples #' \dontrun{ -#' acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), outpath = "my_proteins.fasta") +#' acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), +#' outpath = "my_proteins.fasta") #' Entrez:accessions <- rep("ANY95992.1", 201) |> acc2FA(outpath = "entrez.fa") -#' EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> acc2FA(outpath = "ebi.fa") +#' EBI:accessions <- c("P12345", "Q9UHC1", +#' "O15530", "Q14624", "P0DTD1") |> acc2FA(outpath = "ebi.fa") #' } acc2FA <- function(accessions, outpath, plan = "sequential") { # validation @@ -539,7 +575,8 @@ acc2FA <- function(accessions, outpath, plan = "sequential") { return(result) } -#' Function to generate a vector of one Accession number per distinct observation from 'reduced' column +#' Function to generate a vector of one Accession number per distinct +#' observation from 'reduced' column #' #' @author Samuel Chen, Janani Ravi #' @@ -552,14 +589,20 @@ acc2FA <- function(accessions, outpath, plan = "sequential") { #' @importFrom dplyr filter pull #' @importFrom rlang sym #' -#' @return +#' @return A character vector containing one Accession number per distinct +#' observation from the specified reduced column. #' @export #' #' @examples +#' \dontrun{ +#' representative_accessions <- RepresentativeAccNums(prot_data, +#' reduced = "Lineage", accnum_col = "AccNum") +#' } RepresentativeAccNums <- function(prot_data, reduced = "Lineage", accnum_col = "AccNum") { - # Get Unique reduced column and then bind the AccNums back to get one AccNum per reduced column + # Get Unique reduced column and then bind the AccNums back to get one + # AccNum per reduced column reduced_sym <- sym(reduced) accnum_sym <- sym(accnum_col) @@ -590,8 +633,10 @@ RepresentativeAccNums <- function(prot_data, #' @author Samuel Chen, Janani Ravi #' #' @param fasta_file Path to the FASTA file to be aligned -#' @param tool Type of alignment tool to use. One of three options: "Muscle", "ClustalO", or "ClustalW" -#' @param outpath Path to write the resulting alignment to as a FASTA file. If NULL, no file is written +#' @param tool Type of alignment tool to use. One of three options: "Muscle", +#' "ClustalO", or "ClustalW" +#' @param outpath Path to write the resulting alignment to as a FASTA file. +#' If NULL, no file is written #' #' @importFrom Biostrings readAAStringSet #' @importFrom msa msaClustalOmega msaMuscle msaClustalW @@ -600,6 +645,10 @@ RepresentativeAccNums <- function(prot_data, #' @export #' #' @examples +#' \dontrun{ +#' aligned_sequences <- alignFasta("my_sequences.fasta", +#' tool = "Muscle", outpath = "aligned_output.fasta") +#' } alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { fasta <- readAAStringSet(fasta_file) @@ -628,10 +677,14 @@ alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { #' @importFrom Biostrings toString unmasked #' @importFrom readr write_file #' -#' @return +#' @return Character string representing the content of the written FASTA file. #' @export #' #' @examples +#' \dontrun{ +#' alignment <- msaMuscle("my_sequences.fasta") +#' write.MsaAAMultipleAlignment(alignment, "aligned_sequences.fasta") +#' } write.MsaAAMultipleAlignment <- function(alignment, outpath) { l <- length(rownames(alignment)) fasta <- "" @@ -647,14 +700,19 @@ write.MsaAAMultipleAlignment <- function(alignment, outpath) { #' Get accnums from fasta file #' -#' @param fasta_file +#' @param fasta_file Character. The path to the FASTA file from which +#' accession numbers will be extracted. #' #' @importFrom stringi stri_extract_all_regex #' -#' @return +#' @return A character vector containing the extracted accession numbers. #' @export #' #' @examples +#' \dontrun{ +#' accnums <- get_accnums_from_fasta_file("my_sequences.fasta") +#' print(accnums) +#' } get_accnums_from_fasta_file <- function(fasta_file) { txt <- read_file(fasta_file) accnums <- stringi::stri_extract_all_regex(fasta_file, "(?<=>)[\\w,.]+")[[1]] diff --git a/R/blastWrappers.R b/R/blastWrappers.R index 552b1ff6..2a0325ca 100755 --- a/R/blastWrappers.R +++ b/R/blastWrappers.R @@ -3,20 +3,28 @@ #' Run DELTABLAST to find homologs for proteins of interest #' #' @author Samuel Chen, Janani Ravi +#' @description +#' This function executes a Delta-BLAST search using the specified parameters +#' and database. It sets the BLAST database path, runs the Delta-BLAST command +#' with the given query, and outputs the results. #' -#' @param deltablast_path -#' @param db_search_path Path to the BLAST databases -#' @param db -#' @param query -#' @param evalue -#' @param out -#' @param num_alignments -#' @param num_threads +#' @param deltablast_path Path to the Delta-BLAST executable. +#' @param db_search_path Path to the BLAST databases. +#' @param db Name of the BLAST database to search against (default is "refseq"). +#' @param query Path to the input query file. +#' @param evalue E-value threshold for reporting matches (default is "1e-5"). +#' @param out Path to the output file where results will be saved. +#' @param num_alignments Number of alignments to report. +#' @param num_threads Number of threads to use for the search (default is 1). #' -#' @return +#' @return This function does not return a value; it outputs results to the +#' specified file. #' @export #' #' @examples +#' \dontrun{ +#' run_deltablast(deltablast_path, db_search_path, query, out, num_alignments) +#' } run_deltablast <- function(deltablast_path, db_search_path, db = "refseq", query, evalue = "1e-5", out, num_alignments, num_threads = 1) { @@ -42,18 +50,27 @@ run_deltablast <- function(deltablast_path, db_search_path, #' Run RPSBLAST to generate domain architectures for proteins of interest #' -#' @param rpsblast_path -#' @param db_search_path Path to the BLAST databases -#' @param db -#' @param query -#' @param evalue -#' @param out -#' @param num_threads +#' @description +#' This function executes an RPS-BLAST search to generate domain architectures +#' for specified proteins. It sets the BLAST database path, runs the RPS-BLAST +#' command with the provided query, and outputs the results. #' -#' @return +#' @param rpsblast_path Path to the RPS-BLAST executable. +#' @param db_search_path Path to the BLAST databases. +#' @param db Name of the BLAST database to search against (default is "refseq"). +#' @param query Path to the input query file. +#' @param evalue E-value threshold for reporting matches (default is "1e-5"). +#' @param out Path to the output file where results will be saved. +#' @param num_threads Number of threads to use for the search (default is 1). +#' +#' @return This function does not return a value; it outputs results to the +#' specified file. #' @export #' #' @examples +#' \dontrun{ +#' run_rpsblast(rpsblast_path, db_search_path, query, out) +#' } run_rpsblast <- function(rpsblast_path, db_search_path, db = "refseq", query, evalue = "1e-5", out, num_threads = 1) { diff --git a/R/cleanup.R b/R/cleanup.R index 4fe074ee..a8e79e33 100755 --- a/R/cleanup.R +++ b/R/cleanup.R @@ -46,7 +46,8 @@ cleanString <- function(string) { # get_sequences() function to extract accession numbers #' extractAccNum #' -#' @param string +#' @param string A string from which to extract the accession number. +#' The string may contain accession information delimited by `|` or spaces. #' #' @return Describe return, in detail #' @export @@ -103,7 +104,9 @@ ensureUniqAccNum <- function(accnums) { #' Parse accesion numbers from fasta and add a #' suffix of the ith occurence to handle duplicates #' -#' @param fasta +#' @param fasta An [XStringSet] object representing the sequences from a +#' FASTA file. The sequence names (headers) will be adjusted for uniqueness +#' and sanitized. #' #' @importFrom purrr map_chr #' @importFrom fs path_sanitize @@ -148,7 +151,8 @@ cleanFAHeaders <- function(fasta) { #' #' @importFrom dplyr as_tibble filter #' -#' @return Describe return, in detail +#' @return A tibble with rows removed where the specified column contains +#' `"-"`, `"NA"`, or an empty string. #' @export #' #' @examples @@ -183,7 +187,7 @@ removeEmptyRows <- function(prot, by_column = "DomArch") { #' @param by_column Column in which repeats are condensed to domain+domain -> domain(s). #' @param excluded_prots Vector of strings that condenseRepeatedDomains should not reduce to (s). Defaults to c() #' -#' @return Describe return, in detail +#' @return A data frame with condensed repeated domains in the specified column. #' @export #' #' @importFrom dplyr pull @@ -244,7 +248,9 @@ condenseRepeatedDomains <- function(prot, by_column = "DomArch", excluded_prots #' @param prot DataTable to operate on #' @param by_column Column to operate on #' -#' @return Describe return, in detail +#' @return The original data frame with the specified column updated. All +#' consecutive '?' characters will be replaced with 'X(s)', and individual '?' +#' characters will be replaced with 'X'. #' @export #' #' @importFrom dplyr pull @@ -273,19 +279,21 @@ replaceQuestionMarks <- function(prot, by_column = "GenContext") { } -#' Remove Astrk +#' Remove Asterisk #' #' @description #' Remove the asterisks from a column of data #' Used for removing * from GenContext columns #' -#' @param query_data -#' @param colname +#' @param query_data A data frame containing the data to be processed. +#' @param colname The name of the column from which asterisks should be removed. +#' Defaults to "GenContext". #' #' @importFrom purrr map #' @importFrom stringr str_remove_all #' -#' @return Describe return, in detail +#' @return The original data frame with asterisks removed from the specified +#' column. #' @export #' #' @examples @@ -315,7 +323,8 @@ removeAsterisks <- function(query_data, colname = "GenContext") { #' @param by_column Default column is 'DomArch'. Can also take 'ClustName', 'GenContext' as input. #' @param keep_domains Default is False Keeps tail entries that contain the query domains. #' -#' @return Describe return, in detail +#' @return The original data frame with singletons removed from the specified +#' column. #' @export #' #' @importFrom dplyr count filter group_by pull n summarize @@ -374,7 +383,7 @@ removeTails <- function(prot, by_column = "DomArch", #' #' @importFrom stringr coll str_replace_all #' -#' @return Describe return, in detail +#' @return The original data frame with Species cleaned. #' @export #' #' @examples @@ -504,25 +513,34 @@ cleanClusters <- function(prot, #' The original data frame is returned with the clean DomArchs column and the old domains in the DomArchs.old column. #' #' @param prot A data frame containing a 'DomArch' column -#' @param old -#' @param new +#' @param old The name of the original column containing domain architecture. +#' Defaults to "DomArch.orig". +#' @param new The name of the cleaned column to be created. Defaults to +#' "DomArch". #' @param domains_keep A data frame containing the domain names to be retained. -#' @param domains_rename A data frame containing the domain names to be replaced in a column 'old' and the +#' @param domains_rename A data frame containing the domain names to be replaced +#' in a column 'old' and the #' corresponding replacement values in a column 'new'. -#' @param condenseRepeatedDomains Boolean. If TRUE, repeated domains in 'DomArch' are condensed. Default is TRUE. -#' @param removeTails Boolean. If TRUE, 'ClustName' will be filtered based on domains to keep/remove. Default is FALSE. -#' @param removeEmptyRows Boolean. If TRUE, rows with empty/unnecessary values in 'DomArch' are removed. Default is FALSE. -#' @param domains_ignore A data frame containing the domain names to be removed in a column called 'domains' +#' @param condenseRepeatedDomains Boolean. If TRUE, repeated domains in +#' 'DomArch' are condensed. Default is TRUE. +#' @param removeTails Boolean. If TRUE, 'ClustName' will be filtered based on +#' domains to keep/remove. Default is FALSE. +#' @param removeEmptyRows Boolean. If TRUE, rows with empty/unnecessary values +#' in 'DomArch' are removed. Default is FALSE. +#' @param domains_ignore A data frame containing the domain names to be removed +#' in a column called 'domains' #' #' @importFrom dplyr pull #' @importFrom stringr coll str_replace_all #' -#' @return The original data frame is returned with the clean DomArchs column and the old domains in the DomArchs.old column. +#' @return The original data frame is returned with the clean DomArchs column +#' and the old domains in the DomArchs.old column. #' @export #' #' @examples #' \dontrun{ -#' cleanDomainArchitecture(prot, TRUE, FALSE, domains_keep, domains_rename, domains_ignore = NULL) +#' cleanDomainArchitecture(prot, TRUE, FALSE, +#' omains_keep, domains_rename, domains_ignore = NULL) #' } cleanDomainArchitecture <- function(prot, old = "DomArch.orig", new = "DomArch", domains_keep, domains_rename, @@ -658,8 +676,9 @@ cleanGenomicContext <- function(prot, domains_rename = data.frame("old" = charac #' Cleanup GeneDesc #' -#' @param prot -#' @param column +#' @param prot A data frame containing the gene descriptions. +#' @param column The name of the column from which gene descriptions are pulled +#' for cleanup. #' #' @return Return trailing period that occurs in GeneDesc column #' @export @@ -677,13 +696,16 @@ cleanGeneDescription <- function(prot, column) { #' Pick Longer Duplicate #' -#' @param prot -#' @param column +#' @param prot A data frame containing the data, with at least one column +#' named 'AccNum' for identification of duplicates. +#' @param column The name of the column from which the longest entry among +#' duplicates will be selected. #' #' @importFrom dplyr arrange filter group_by pull n select summarize #' @importFrom rlang sym #' -#' @return Describe return, in detail +#' @return A data frame containing only the longest entries among duplicates +#' based on the specified column. #' @export #' #' @examples @@ -728,10 +750,13 @@ selectLongestDuplicate <- function(prot, column) { #' Cleanup Lineage #' -#' @param prot -#' @param lins_rename +#' @param prot A data frame containing a 'Lineage' column that needs to be +#' cleaned up. +#' @param lins_rename A data frame with two columns: 'old' containing terms +#' to be replaced and 'new' containing the corresponding replacement terms. #' -#' @return Describe return, in detail +#' @return The original data frame with the 'Lineage' column updated based on +#' the provided replacements. #' @export #' #' @examples diff --git a/R/combine_analysis.R b/R/combine_analysis.R index bb3b3ce2..2361c213 100755 --- a/R/combine_analysis.R +++ b/R/combine_analysis.R @@ -8,15 +8,23 @@ #' Combining full_analysis files #' -#' @param inpath -#' @param ret +#' @param inpath Character. The path to the directory containing the +#' `.full_analysis.tsv` files to be combined. +#' @param ret Logical. If TRUE, the function will return the combined data frame. +#' Default is FALSE, meaning it will only write the file and not return the data. #' #' @importFrom readr write_tsv #' -#' @return +#' @return If `ret` is TRUE, a data frame containing the combined data from all +#' input files. If `ret` is FALSE, the function writes the combined data to a +#' TSV file named `cln_combined.tsv` in the specified directory and returns NULL. +#' #' @export #' #' @examples +#' \dontrun{ +#' combined_data <- combine_full("path/to/full_analysis/files", ret = TRUE) +#' } combine_full <- function(inpath, ret = FALSE) { ## Combining full_analysis files full_combnd <- combine_files(inpath, @@ -35,15 +43,23 @@ combine_full <- function(inpath, ret = FALSE) { #' Combining clean ipr files #' -#' @param inpath -#' @param ret +#' @param inpath Character. The path to the directory containing the +#' `.iprscan_cln.tsv` files to be combined. +#' @param ret Logical. If TRUE, the function will return the combined data frame. +#' Default is FALSE, meaning it will only write the file and not return the data. #' #' @importFrom readr write_tsv #' -#' @return +#' @return If `ret` is TRUE, a data frame containing the combined data from all +#' input files. If `ret` is FALSE, the function writes the combined data to a +#' TSV file named `ipr_combined.tsv` in the specified directory and returns NULL. +#' #' @export #' #' @examples +#' \dontrun{ +#' combined_ipr_data <- combine_ipr("path/to/ipr/files", ret = TRUE) +#' } combine_ipr <- function(inpath, ret = FALSE) { ## Combining clean ipr files ipr_combnd <- combine_files(inpath, diff --git a/R/combine_files.R b/R/combine_files.R index 76c5fa09..088f2d7b 100755 --- a/R/combine_files.R +++ b/R/combine_files.R @@ -24,20 +24,30 @@ #' #' @author Janani Ravi #' -#' @param inpath String of 'master' path where the files reside (recursive=T) -#' @param pattern Character vector containing search pattern for files -#' @param delim -#' @param skip -#' @param col_names Takes logical T/F arguments OR column names vector; -#' usage similar to col_names parameter in `readr::read_delim` +#' @param inpath Character. The master directory path where the files reside. +#' The search is recursive (i.e., it will look in subdirectories as well). +#' @param pattern Character. A search pattern to identify files to be combined. +#' Default is "*full_analysis.tsv". +#' @param delim Character. The delimiter used in the input files. +#' Default is tab ("\t"). +#' @param skip Integer. The number of lines to skip at the beginning of each file. +#' Default is 0. +#' @param col_names Logical or character vector. If TRUE, the first row of each file +#' is treated as column names. Alternatively, a character vector can +#' be provided to specify custom column names. #' #' @importFrom purrr pmap_dfr #' @importFrom readr cols #' -#' @return +#' @return A data frame containing the combined contents of all matched files. +#' Each row will include a new column "ByFile" indicating the source file of the data. +#' #' @export #' #' @examples +#' \dontrun{ +#' combined_data <- combine_files(inpath = "../molevol_data/project_data/phage_defense/") +#' } combine_files <- function(inpath = c("../molevol_data/project_data/phage_defense/"), pattern = "*full_analysis.tsv", delim = "\t", skip = 0, diff --git a/R/create_lineage_lookup.R b/R/create_lineage_lookup.R index e7374df3..7c581d2e 100644 --- a/R/create_lineage_lookup.R +++ b/R/create_lineage_lookup.R @@ -7,12 +7,12 @@ #' #' @author Samuel Chen #' -#' @param lineage_file Path to the rankedlineage.dmp file containing taxid's and their -#' corresponding taxonomic rank. rankedlineage.dmp can be downloaded at +#' @param lineage_file Path to the rankedlineage.dmp file containing taxid's +#' and their corresponding taxonomic rank. rankedlineage.dmp can be downloaded at #' https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/new_taxdump/ #' @param outfile File the resulting lineage lookup table should be written to -#' @param taxonomic_rank The upperbound of taxonomic rank that the lineage includes. The lineaege will -#' include superkingdom>...>taxonomic_rank. +#' @param taxonomic_rank The upperbound of taxonomic rank that the lineage +#' includes. The lineaege will include superkingdom>...>taxonomic_rank. #' Choices include: "supperkingdom", "phylum", "class","order", "family", #' "genus", and "species" #' @@ -22,10 +22,17 @@ #' @importFrom stringr str_locate str_replace_all #' @importFrom tidyr unite #' -#' @return +#' @return A tibble containing the tax IDs and their respective lineages up to +#' the specified taxonomic rank, saved as a tab-separated file. +#' #' @export #' #' @examples +#' \dontrun{ +#' create_lineage_lookup(lineage_file = "data/rankedlineage.dmp", +#' outfile = "data/lineage_lookup.tsv", +#' taxonomic_rank = "family") +#' } create_lineage_lookup <- function(lineage_file = here("data/rankedlineage.dmp"), outfile, taxonomic_rank = "phylum") { shorten_NA <- function(Lineage) { diff --git a/R/fa2domain.R b/R/fa2domain.R index 6dc6f622..29803b85 100644 --- a/R/fa2domain.R +++ b/R/fa2domain.R @@ -5,16 +5,29 @@ # interproscan CLI will return a completely empty file (0Bytes) #' runIPRScan +#' +#' Run InterProScan on a given FASTA file and save the results to an +#' output file. #' -#' @param filepath_fasta -#' @param filepath_out -#' @param appl +#' @param filepath_fasta A string representing the path to the input FASTA file. +#' @param filepath_out A string representing the base path for the output file. +#' @param appl A character vector specifying the InterProScan applications to +#' use (e.g., "Pfam", "Gene3D"). Default is `c("Pfam", "Gene3D")`. #' #' @importFrom stringr str_glue #' -#' @return +#' @return A data frame containing the results from the InterProScan output +#' TSV file. #' #' @examples +#' \dontrun{ +#' results <- runIPRScan( +#' filepath_fasta = "path/to/your_fasta_file.fasta", +#' filepath_out = "path/to/output_file", +#' appl = c("Pfam", "Gene3D") +#' ) +#' print(results) +#' } runIPRScan <- function( filepath_fasta, filepath_out, # do not inlucde file extension since ipr handles this diff --git a/R/ipr2viz.R b/R/ipr2viz.R index 0d417be0..c4006e51 100644 --- a/R/ipr2viz.R +++ b/R/ipr2viz.R @@ -19,10 +19,17 @@ #' #' @importFrom ggplot2 element_blank element_line theme theme_grey #' -#' @return +#' @return A ggplot2 theme object. #' @export -#' #' @examples +#' library(ggplot2) +#' +#' # Create a sample plot using the custom theme +#' ggplot(mtcars, aes(x = wt, y = mpg)) + +#' geom_point() + +#' theme_genes2() + +#' labs(title = "Car Weight vs MPG") +#' theme_genes2 <- function() { ggplot2::theme_grey() + ggplot2::theme( panel.background = ggplot2::element_blank(), @@ -43,11 +50,16 @@ theme_genes2 <- function() { ################################## #' Group by lineage + DA then take top 20 #' -#' @param infile_full -#' @param DA_col -#' @param lin_col -#' @param n -#' @param query +#' @param infile_full A data frame containing the full dataset with lineage and +#' domain architecture information. +#' @param DA_col A string representing the name of the domain architecture +#' column. Default is "DomArch.Pfam". +#' @param lin_col A string representing the name of the lineage column. +#' Default is "Lineage_short". +#' @param n An integer specifying the number of top accession numbers to return. +#' Default is 20. +#' @param query A string for filtering a specific query name. If it is not +#' "All", only the data matching this query will be processed. #' #' @importFrom dplyr arrange filter group_by select summarise #' @importFrom shiny showNotification @@ -55,10 +67,16 @@ theme_genes2 <- function() { #' @importFrom rlang sym #' @importFrom rlang .data #' -#' @return +#' @return A vector of the top N accession numbers (`AccNum`) based on counts +#' grouped by lineage and domain architecture. #' @export #' #' @examples +#' \dontrun{ +#' top_accessions <- find_top_acc(infile_full = my_data, +#' DA_col = "DomArch.Pfam", lin_col = "Lineage_short", +#' n = 20, query = "specific_query_name") +#' } find_top_acc <- function(infile_full, DA_col = "DomArch.Pfam", lin_col = "Lineage_short", @@ -94,16 +112,26 @@ find_top_acc <- function(infile_full, ############################################# #' IPR2Viz #' -#' @param infile_ipr -#' @param infile_full -#' @param accessions -#' @param analysis -#' @param group_by -#' @param topn -#' @param name -#' @param text_size -#' @param query -#' +#' @param infile_ipr A path to the input IPR file (TSV format) containing +#' domain information. +#' @param infile_full A path to the full input file (TSV format) containing +#' lineage and accession information. +#' @param accessions A character vector of accession numbers to filter the +#' analysis. Default is an empty vector. +#' @param analysis A character vector specifying the types of analysis to +#' include (e.g., "Pfam", "Phobius", "TMHMM", "Gene3D"). Default is a +#' vector of these analyses. +#' @param group_by A string specifying how to group the visualization. +#' Default is "Analysis". Options include "Analysis" or "Query". +#' @param topn An integer specifying the number of top accessions to visualize. +#' Default is 20. +#' @param name A string representing the name to use for y-axis labels. +#' Default is "Name". +#' @param text_size An integer specifying the text size for the plot. +#' Default is 15. +#' @param query A string for filtering a specific query name. If it is not +#' "All", only the data matching this query will be processed. +#' #' @importFrom dplyr distinct filter select #' @importFrom gggenes geom_gene_arrow geom_subgene_arrow #' @importFrom ggplot2 aes aes_string as_labeller element_text facet_wrap ggplot guides margin scale_fill_manual theme theme_minimal unit ylab @@ -111,10 +139,22 @@ find_top_acc <- function(infile_full, #' @importFrom tidyr pivot_wider #' @importFrom stats as.formula #' -#' @return +#' @return A ggplot object representing the domain architecture visualization. #' @export #' #' @examples +#' \dontrun{ +#' plot <- ipr2viz(infile_ipr = "path/to/ipr_file.tsv", +#' infile_full = "path/to/full_file.tsv", +#' accessions = c("ACC123", "ACC456"), +#' analysis = c("Pfam", "TMHMM"), +#' group_by = "Analysis", +#' topn = 20, +#' name = "Gene Name", +#' text_size = 15, +#' query = "All") +#' print(plot) +#' } ipr2viz <- function(infile_ipr = NULL, infile_full = NULL, accessions = c(), analysis = c("Pfam", "Phobius", "TMHMM", "Gene3D"), group_by = "Analysis", # "Analysis" @@ -250,15 +290,25 @@ ipr2viz <- function(infile_ipr = NULL, infile_full = NULL, accessions = c(), #' IPR2Viz Web #' -#' @param infile_ipr -#' @param accessions -#' @param analysis -#' @param group_by -#' @param name -#' @param text_size -#' @param legend_name -#' @param cols -#' @param rows +#' @param infile_ipr A path to the input IPR file (TSV format) containing +#' domain information. +#' @param accessions A character vector of accession numbers to filter the +#' analysis. +#' @param analysis A character vector specifying the types of analysis to +#' include (e.g., "Pfam", "Phobius", "TMHMM", "Gene3D"). Default is a vector +#' of these analyses. +#' @param group_by A string specifying how to group the visualization. +#' Default is "Analysis". Options include "Analysis" or "Query". +#' @param name A string representing the name to use for y-axis labels. +#' Default is "Name". +#' @param text_size An integer specifying the text size for the plot. +#' Default is 15. +#' @param legend_name A string representing the column to use for legend labels. +#' Default is "ShortName". +#' @param cols An integer specifying the number of columns in the facet wrap. +#' Default is 5. +#' @param rows An integer specifying the number of rows in the legend. +#' Default is 10. #' #' @importFrom dplyr arrange distinct filter select #' @importFrom gggenes geom_gene_arrow geom_subgene_arrow @@ -266,10 +316,23 @@ ipr2viz <- function(infile_ipr = NULL, infile_full = NULL, accessions = c(), #' @importFrom readr read_tsv #' @importFrom tidyr pivot_wider #' -#' @return +#' @return A ggplot object representing the domain architecture visualization +#' for web display. #' @export #' #' @examples +#' \dontrun{ +#' plot <- ipr2viz_web(infile_ipr = "path/to/ipr_file.tsv", +#' accessions = c("ACC123", "ACC456"), +#' analysis = c("Pfam", "TMHMM"), +#' group_by = "Analysis", +#' name = "Gene Name", +#' text_size = 15, +#' legend_name = "ShortName", +#' cols = 5, +#' rows = 10) +#' print(plot) +#' } ipr2viz_web <- function(infile_ipr, accessions, analysis = c("Pfam", "Phobius", "TMHMM", "Gene3D"), diff --git a/R/lineage.R b/R/lineage.R index d14246d7..ea1cd13a 100644 --- a/R/lineage.R +++ b/R/lineage.R @@ -11,17 +11,24 @@ #' #' @author Samuel Chen, Janani Ravi #' -#' @param outpath String of path where the assembly summary file should be written -#' @param keep Character vector containing which columns should be retained and downloaded +#' @param outpath String of path where the assembly summary file should be +#' written +#' @param keep Character vector containing which columns should be retained and +#' downloaded #' #' @importFrom data.table fwrite setnames #' @importFrom dplyr bind_rows select #' @importFrom biomartr getKingdomAssemblySummary #' -#' @return +#' @return A tab-separated file containing the assembly summary. The function +#' does notreturn any value but writes the output directly to the specified file. #' @export #' #' @examples +#' \dontrun{ +#' downloadAssemblySummary(outpath = "assembly_summary.tsv", +#' keep = c("assembly_accession", "taxid", "organism_name")) +#' } downloadAssemblySummary <- function(outpath, keep = c( "assembly_accession", "taxid", @@ -78,15 +85,24 @@ downloadAssemblySummary <- function(outpath, #' @param lineagelookup_path String of the path to the lineage lookup file #' (taxid to lineage mapping). This file can be generated using the #' "create_lineage_lookup()" function -#' @param acc_col +#' @param acc_col Character. The name of the column in `prot_data` containing +#' accession numbers. Default is "AccNum". #' #' @importFrom dplyr pull #' @importFrom data.table fread setnames #' -#' @return +#' @return A dataframe containing the merged information of GCA_IDs, TaxIDs, +#' and their corresponding lineage up to the phylum level. The dataframe +#' will include information from the input `prot_data` and lineage data. +#' #' @export #' #' @examples +#' \dontrun{ +#' result <- GCA2Lineage(prot_data = my_prot_data, +#' assembly_path = "path/to/assembly_summary.txt", +#' lineagelookup_path = "path/to/lineage_lookup.tsv") +#' } GCA2Lineage <- function(prot_data, assembly_path = "/data/research/jravilab/common_data/assembly_summary_genbank.txt", lineagelookup_path = "/data/research/jravilab/common_data/lineage_lookup.tsv", @@ -135,20 +151,34 @@ GCA2Lineage <- function(prot_data, ################################### #' addLineage #' -#' @param df -#' @param acc_col -#' @param assembly_path -#' @param lineagelookup_path -#' @param ipgout_path -#' @param plan +#' @param df Dataframe containing accession numbers. The dataframe should +#' have a column specified by `acc_col` that contains these accession numbers. +#' @param acc_col Character. The name of the column in `df` containing +#' accession numbers. Default is "AccNum". +#' @param assembly_path String. The path to the assembly summary file generated +#' using the `downloadAssemblySummary()` function. +#' @param lineagelookup_path String. The path to the lineage lookup file (taxid +#' to lineage mapping) generated using the `create_lineage_lookup()` function. +#' @param ipgout_path String. Optional path to save intermediate output files. +#' Default is NULL. +#' @param plan Character. Specifies the execution plan for parallel processing. +#' Default is "multicore". #' #' @importFrom dplyr pull #' @importFrom rlang sym #' -#' @return +#' @return A dataframe that combines the original dataframe `df` with lineage +#' information retrieved based on the provided accession numbers. +#' #' @export #' #' @examples +#' \dontrun{ +#' enriched_df <- addLineage(df = my_data, +#' acc_col = "AccNum", +#' assembly_path = "path/to/assembly_summary.txt", +#' lineagelookup_path = "path/to/lineage_lookup.tsv") +#' } addLineage <- function(df, acc_col = "AccNum", assembly_path, lineagelookup_path, ipgout_path = NULL, plan = "multicore") { acc_sym <- sym(acc_col) @@ -194,12 +224,23 @@ addLineage <- function(df, acc_col = "AccNum", assembly_path, #' (taxid to lineage mapping). This file can be generated using the #' @param ipgout_path Path to write the results of the efetch run of the accessions #' on the ipg database. If NULL, the file will not be written. Defaults to NULL -#' @param plan +#' @param plan Character. Specifies the execution plan for parallel processing. +#' Default is "multicore". #' -#' @return +#' @return A dataframe containing lineage information mapped to the given protein +#' accessions. The dataframe includes relevant columns such as TaxID, GCA_ID, +#' Protein, Protein Name, Species, and Lineage. #' @export #' #' @examples +#' \dontrun{ +#' lineage_data <- acc2Lineage( +#' accessions = c("P12345", "Q67890"), +#' assembly_path = "path/to/assembly_summary.txt", +#' lineagelookup_path = "path/to/lineage_lookup.tsv", +#' ipgout_path = "path/to/output.txt" +#' ) +#' } acc2Lineage <- function(accessions, assembly_path, lineagelookup_path, ipgout_path = NULL, plan = "multicore") { tmp_ipg <- F @@ -235,16 +276,25 @@ acc2Lineage <- function(accessions, assembly_path, lineagelookup_path, #' @param accessions Character vector containing the accession numbers to query on #' the ipg database #' @param out_path Path to write the efetch results to -#' @param plan +#' @param plan Character. Specifies the execution plan for parallel processing. +#' Default is "multicore". #' #' @importFrom future future plan #' @importFrom purrr map #' @importFrom rentrez entrez_fetch #' -#' @return +#' @return The function does not return a value but writes the efetch results +#' directly to the specified `out_path`. +#' #' @export #' #' @examples +#' \dontrun{ +#' efetchIPG( +#' accessions = c("P12345", "Q67890", "A12345"), +#' out_path = "path/to/efetch_results.xml" +#' ) +#' } efetchIPG <- function(accessions, out_path, plan = "multicore") { if (length(accessions) > 0) { partition <- function(v, groups) { @@ -305,18 +355,28 @@ efetchIPG <- function(accessions, out_path, plan = "multicore") { #' @param ipg_file Path to the file containing results of an efetch run on the #' ipg database. The protein accession in 'accessions' should be contained in this #' file -#' @param refseq_assembly_path -#' @param genbank_assembly_path +#' @param refseq_assembly_path String. Path to the RefSeq assembly summary file. +#' @param genbank_assembly_path String. Path to the GenBank assembly summary file. #' @param lineagelookup_path String of the path to the lineage lookup file #' (taxid to lineage mapping). This file can be generated using the #' "create_lineage_lookup()" function #' #' @importFrom data.table fread setnames #' -#' @return +#' @return A data table containing protein accessions along with their +#' corresponding TaxIDs and lineage information. #' @export #' #' @examples +#' \dontrun{ +#' lins <- IPG2Lineage( +#' accessions = c("P12345", "Q67890"), +#' ipg_file = "path/to/ipg_results.txt", +#' refseq_assembly_path = "path/to/refseq_assembly_summary.txt", +#' genbank_assembly_path = "path/to/genbank_assembly_summary.txt", +#' lineagelookup_path = "path/to/lineage_lookup.tsv" +#' ) +#' } IPG2Lineage <- function(accessions, ipg_file, refseq_assembly_path, genbank_assembly_path, lineagelookup_path) { @@ -383,16 +443,25 @@ IPG2Lineage <- function(accessions, ipg_file, ######################################### #' addTaxID #' -#' @param data -#' @param acc_col -#' @param version +#' @param data A data frame or data table containing protein accession numbers. +#' @param acc_col A string specifying the column name in `data` that contains +#' the accession numbers. Defaults to "AccNum". +#' @param version A logical indicating whether to remove the last two characters +#' from the accession numbers for TaxID retrieval. Defaults to TRUE. #' #' @importFrom data.table as.data.table #' -#' @return +#' @return A data table that includes the original data along with a new column +#' containing the corresponding TaxIDs. #' @export #' #' @examples +#' \dontrun{ +#' # Create a sample data table with accession numbers +#' sample_data <- data.table(AccNum = c("ABC123.1", "XYZ456.1", "LMN789.2")) +#' enriched_data <- addTaxID(sample_data, acc_col = "AccNum", version = TRUE) +#' print(enriched_data) +#' } addTaxID <- function(data, acc_col = "AccNum", version = T) { if (!is.data.table(data)) { data <- as.data.table(data) @@ -421,17 +490,30 @@ addTaxID <- function(data, acc_col = "AccNum", version = T) { ################################## #' proteinAcc2TaxID #' -#' @param accnums -#' @param suffix -#' @param out_path -#' @param return_dt +#' @param accnums A character vector of protein accession numbers to be mapped +#' to TaxIDs. +#' @param suffix A string suffix used to name the output file generated by the +#' script. +#' @param out_path A string specifying the directory where the output file will +#' be saved. +#' @param return_dt A logical indicating whether to return the result as a data +#' table. Defaults to FALSE. If TRUE, the output file is read into a data table +#' and returned. #' #' @importFrom data.table fread #' -#' @return +#' @return If `return_dt` is TRUE, a data table containing the mapping of protein +#' accession numbers to TaxIDs. If FALSE, the function returns NULL. #' @export #' #' @examples +#' \dontrun{ +#' # Example accession numbers +#' accessions <- c("ABC123", "XYZ456", "LMN789") +#' tax_data <- proteinAcc2TaxID(accessions, suffix = "example", +#' out_path = "/path/to/output", return_dt = TRUE) +#' print(tax_data) +#' } proteinAcc2TaxID <- function(accnums, suffix, out_path, return_dt = FALSE) { # Write accnums to a file acc_file <- tempfile() @@ -456,18 +538,25 @@ proteinAcc2TaxID <- function(accnums, suffix, out_path, return_dt = FALSE) { #' @description Perform elink to go from protein database to taxonomy database #' and write the resulting file of taxid and lineage to out_path #' -#' @param accessions Character vector containing the accession numbers to query on -#' the ipg database -#' @param out_path Path to write the efetch results to -#' @param plan +#' @param accessions A character vector containing the accession numbers to query +#' in the protein database. +#' @param out_path A string specifying the path where the results of the query +#' will be written. If set to NULL, a temporary directory will be used. +#' @param plan A character string that specifies the execution plan for parallel +#' processing. The default is "multicore". #' #' @importFrom future plan #' @importFrom purrr map #' -#' @return +#' @return This function does not return a value. It writes the results to the +#' specified output path. #' @export #' #' @examples +#' \dontrun{ +#' accessions <- c("ABC123", "XYZ456", "LMN789") +#' proteinAcc2TaxID_old(accessions, out_path = "/path/to/output") +#' } proteinAcc2TaxID_old <- function(accessions, out_path, plan = "multicore") { if (length(accessions) > 0) { partition <- function(v, groups) { diff --git a/R/msa.R b/R/msa.R index e56cc32c..20089dba 100644 --- a/R/msa.R +++ b/R/msa.R @@ -50,12 +50,15 @@ #' @importFrom msa msa msaPrettyPrint #' @importFrom stringr str_replace #' -#' @return +#' @return A PDF file containing the multiple sequence alignment. #' @export #' #' @examples #' \dontrun{ -#' msa_pdf() +#' msa_pdf(fasta_path = "path/to/your/file.fasta", +#' out_path = "path/to/output/alignment.pdf", +#' lowerbound = 10, +#' upperbound = 200) #' } msa_pdf <- function(fasta_path, out_path = NULL, lowerbound = NULL, upperbound = NULL) { @@ -187,15 +190,22 @@ msa_pdf <- function(fasta_path, out_path = NULL, ## https://github.com/mhahsler/rMSA #' Function to generate MSA using kalign #' -#' @param fa_file -#' @param outfile +#' @param fa_file Character. The path to the input FASTA file containing protein +#' sequences. +#' @param outfile Character. The path to the output file where the alignment +#' will be saved. #' #' @importFrom Biostrings readAAStringSet +#' @importFrom rMSA kalign #' -#' @return +#' @return A list containing the alignment object and the output file path. #' @export #' #' @examples +#' \dontrun{ +#' generate_msa(fa_file = "path/to/sequences.fasta", +#' outfile = "path/to/alignment.txt") +#' } generate_msa <- function(fa_file = "", outfile = "") { prot_aa <- readAAStringSet( path = fa_file, diff --git a/R/networks_domarch.R b/R/networks_domarch.R index fea0a195..65090fa4 100755 --- a/R/networks_domarch.R +++ b/R/networks_domarch.R @@ -24,13 +24,17 @@ #' A network of domains is returned based on shared domain architectures. #' #' @param prot A data frame that contains the column 'DomArch'. -#' @param column Name of column containing Domain architecture from which nodes and edges are generated. -#' @param domains_of_interest -#' @param cutoff Integer. Only use domains that occur at or above the cutoff for total counts if cutoff_type is "Total Count". -#' Only use domains that appear in cutoff or greater lineages if cutoff_type is Lineage. +#' @param column Name of column containing Domain architecture from which nodes +#' and edges are generated. +#' @param domains_of_interest Character vector specifying domains of interest. +#' @param cutoff Integer. Only use domains that occur at or above the cutoff for +#' total counts if cutoff_type is "Total Count". +#' Only use domains that appear in cutoff or greater lineages if cutoff_type is +#' Lineage. #' @param layout Character. Layout type to be used for the network. Options are: #' \itemize{\item "grid" \item "circle" \item "random" \item "auto"} -#' @param query_color +#' @param query_color Character. Color to represent the queried domain in the +#' network. #' #' @importFrom dplyr across add_row all_of distinct filter mutate pull select #' @importFrom igraph delete_vertices graph_from_edgelist vertex @@ -41,7 +45,7 @@ #' @importFrom tidyr pivot_wider #' @importFrom visNetwork visIgraph visIgraphLayout visNetwork visOptions #' -#' @return +#' @return A network visualization of domain architectures. #' @export #' #' @examples @@ -227,15 +231,20 @@ domain_network <- function(prot, column = "DomArch", domains_of_interest, cutoff #' #' #' @param prot A data frame that contains the column 'DomArch'. -#' @param column Name of column containing Domain architecture from which nodes and edges are generated. -#' @param domains_of_interest -#' @param cutoff Integer. Only use domains that occur at or above the cutoff for total counts if cutoff_type is "Total Count". -#' Only use domains that appear in cutoff or greater lineages if cutoff_type is Lineage. +#' @param column Name of column containing Domain architecture from which nodes +#' and edges are generated. +#' @param domains_of_interest Character vector specifying the domains of interest. +#' @param cutoff Integer. Only use domains that occur at or above the cutoff for +#' total counts if cutoff_type is "Total Count". +#' Only use domains that appear in cutoff or greater lineages if cutoff_type is +#' Lineage. #' @param layout Character. Layout type to be used for the network. Options are: #' \itemize{\item "grid" \item "circle" \item "random" \item "auto"} -#' @param query_color Color that the nodes of the domains in the domains_of_interest vector are colored -#' @param partner_color Color that the nodes that are not part of the domains_of_interest vector are colored -#' @param border_color +#' @param query_color Color that the nodes of the domains in the +#' domains_of_interest vector are colored +#' @param partner_color Color that the nodes that are not part of the +#' domains_of_interest vector are colored +#' @param border_color Color for the borders of the nodes. #' @param IsDirected Is the network directed? Set to false to eliminate arrows #' #' @importFrom dplyr distinct filter group_by mutate pull select summarize @@ -245,12 +254,12 @@ domain_network <- function(prot, column = "DomArch", domains_of_interest, cutoff #' @importFrom stringr str_replace_all str_split #' @importFrom visNetwork visEdges visGroups visIgraphLayout visLegend visNetwork visOptions #' -#' @return +#' @return A network visualization of domain architectures. #' @export #' #' @examples #' \dontrun{ -#' domain_network(pspa) +#' BinaryDomainNetwork(pspa) #' } BinaryDomainNetwork <- function(prot, column = "DomArch", domains_of_interest, cutoff = 70, layout = "nice", query_color = adjustcolor("yellow", alpha.f = .5), diff --git a/R/networks_gencontext.R b/R/networks_gencontext.R index e0dd63da..02733cdf 100755 --- a/R/networks_gencontext.R +++ b/R/networks_gencontext.R @@ -17,13 +17,19 @@ #' #' #' @param prot A data frame that contains the column 'DomArch'. -#' @param column Name of column containing Domain architecture from which nodes and edges are generated. -#' @param domains_of_interest -#' @param cutoff_type Character. Used to determine how data should be filtered. Either -#' \itemize{\item "Lineage" to filter domains based off how many lineages the Domain architecture appears in -#' \item "Total Count" to filter off the total amount of times a domain architecture occurs } -#' @param cutoff Integer. Only use domains that occur at or above the cutoff for total counts if cutoff_type is "Total Count". -#' Only use domains that appear in cutoff or greater lineages if cutoff_type is Lineage. +#' @param column Name of column containing Domain architecture from which nodes +#' and edges are generated. +#' @param domains_of_interest Character vector specifying the domains of interest. +#' @param cutoff_type Character. Used to determine how data should be filtered. +#' Either +#' \itemize{\item "Lineage" to filter domains based off how many lineages the +#' Domain architecture appears in +#' \item "Total Count" to filter off the total amount of times a +#' domain architecture occurs } +#' @param cutoff Integer. Only use domains that occur at or above the cutoff +#' for total counts if cutoff_type is "Total Count". +#' Only use domains that appear in cutoff or greater lineages if cutoff_type is +#' Lineage. #' @param layout Character. Layout type to be used for the network. Options are: #' \itemize{\item "grid" \item "circle" \item "random" \item "auto"} #' @@ -32,12 +38,14 @@ #' @importFrom igraph E graph_from_edgelist layout.auto layout.circle layout_on_grid layout_randomly plot.igraph V #' @importFrom stringr str_replace_all str_split #' -#' @return +#' @return A plot of the domain architecture network. #' @export #' #' @examples #' \dontrun{ -#' domain_network(pspa) +#' domain_network(pspa, column = "DomArch", +#' domains_of_interest = c("Domain1", "Domain2"), +#' cutoff_type = "Total Count", cutoff = 10) #' } gc_undirected_network <- function(prot, column = "GenContext", domains_of_interest, cutoff_type = "Lineage", cutoff = 1, layout = "grid") { # by domain networks or all, as required. @@ -127,8 +135,10 @@ gc_undirected_network <- function(prot, column = "GenContext", domains_of_intere #' #' @param prot A data frame that contains the column 'GenContext'. #' @param domains_of_interest Character vector of domains of interest. -#' @param column Name of column containing Genomic Context from which nodes and edges are generated. -#' @param cutoff Integer. Only use GenContexts that occur at or above the cutoff percentage for total count +#' @param column Name of column containing Genomic Context from which nodes and +#' edges are generated. +#' @param cutoff Integer. Only use GenContexts that occur at or above the cutoff +#' percentage for total count #' @param layout Character. Layout type to be used for the network. Options are: #' \itemize{\item "grid" \item "circle" \item "random" \item "auto" \item "nice"} #' @param directed Is the network directed? @@ -139,12 +149,12 @@ gc_undirected_network <- function(prot, column = "GenContext", domains_of_intere #' @importFrom stringr str_replace_all #' @importFrom visNetwork visIgraphLayout visLegend visNetwork visOptions #' -#' @return +#' @return A plot of the genomic context network. #' @export #' #' @examples #' \dontrun{ -#' gc_directed_network(pspa, column = "GenContex", cutoff = 55) +#' gc_directed_network(pspa, column = "GenContext", cutoff = 55) #' } GenContextNetwork <- function(prot, domains_of_interest, column = "GenContext", cutoff = 40, diff --git a/R/plotme.R b/R/plotme.R index 906e85ec..3527f170 100644 --- a/R/plotme.R +++ b/R/plotme.R @@ -44,10 +44,9 @@ plotSunburst <- function(count_data, fill_by_n = FALSE, sort_by_n = FALSE, maxde } -#' @param count_data -#' -#' @param fill_by_n -#' @param sort_by_n +#' @param count_data A data frame containing the data. +#' @param fill_by_n Logical indicating if fill color is based on counts. +#' @param sort_by_n Logical indicating if data should be sorted by counts. #' #' @importFrom plotly plot_ly #' @importFrom purrr exec @@ -68,18 +67,24 @@ plotTreemap <- function(count_data, fill_by_n = FALSE, sort_by_n = FALSE) { #' prepareColumnParams #' -#' @param count_data -#' @param fill_by_n -#' @param sort_by_n +#' @param count_data A data frame containing the data. +#' @param fill_by_n Logical indicating if fill color is based on counts. +#' @param sort_by_n Logical indicating if data should be sorted by counts. #' #' @importFrom assertthat assert_that #' @importFrom dplyr bind_rows mutate #' @importFrom purrr map #' -#' @return +#' @return A data frame of parameters for treemap visualization. #' @export #' #' @examples +#' \dontrun{ +#' count_data <- data.frame(Category = c("A", "B", "C"), +#' n = c(10, 20, 15)) +#' params <- prepareColumnParams(count_data, fill_by_n = TRUE, sort_by_n = FALSE) +#' print(params) +#' } prepareColumnParams <- function(count_data, fill_by_n, sort_by_n) { validateCountDF(count_data) assertthat::assert_that(is.logical(fill_by_n), @@ -116,17 +121,24 @@ prepareColumnParams <- function(count_data, fill_by_n, sort_by_n) { #' prepareSingleColumnParams #' -#' @param df -#' @param col_num -#' @param root +#' @param df A data frame containing the data to be processed. +#' @param col_num An integer representing the column number to process. +#' @param root A string representing the root node for the treemap. #' #' @importFrom dplyr c_across group_by mutate rowwise select summarise ungroup #' @importFrom stringr str_glue #' -#' @return +#' @return A data frame containing parameters for the specified column for +#' treemap visualization. #' @export #' #' @examples +#' \dontrun{ +#' df <- data.frame(Category = c("A", "A", "B", "B", "C"), +#' n = c(10, 20, 30, 40, 50)) +#' params <- prepareSingleColumnParams(df, col_num = 1, root = "Root") +#' print(params) +#' } prepareSingleColumnParams <- function(df, col_num, root) { @@ -158,15 +170,18 @@ prepareSingleColumnParams <- function(df, } #' validateCountDF #' -#' @param var +#' @param var A data frame whose columns are to be converted. #' #' @importFrom assertthat assert_that has_name #' @importFrom dplyr across mutate #' -#' @return +#' @return A data frame with non-'n' columns converted to character type. #' @export #' #' @examples +#' \dontrun{ +#' new_df <- .all_non_n_cols_to_char(my_data) +#' } validateCountDF <- function(var) { msg <- paste(substitute(var), "must be a count dataframe (output of dplyr::count)") assertthat::assert_that(is.data.frame(var), diff --git a/R/plotting.R b/R/plotting.R index 7191eace..b9a2758a 100644 --- a/R/plotting.R +++ b/R/plotting.R @@ -18,20 +18,34 @@ # suppressPackageStartupMessages(library(d3r)) # suppressPackageStartupMessages(library(viridis)) -#' Shorten Lineage +#' Shorten Lineage Names #' -#' @param data -#' @param colname -#' @param abr_len +#' @description +#' This function abbreviates lineage names by shortening the first part of the +#' string (up to a given delimiter). +#' +#' @param data A data frame that contains a column with lineage names to be +#' shortened. +#' @param colname Character. The name of the column in the data frame containing +#' the lineage strings to be shortened. Default is `"Lineage"`. +#' @param abr_len Integer. The number of characters to retain after the first +#' letter. If set to 1, only the first letter of each segment before the +#' delimiter (`>`) is retained. Default is 1. #' #' @importFrom stringr str_locate +#' @importFrom purrr pmap +#' +#' @return A modified data frame where the specified lineage column has been +#' shortened. #' -#' @return #' @export #' #' @examples #' \dontrun{ -#' shortenLineage() +#' df <- data.frame(Lineage = c("Bacteria>Firmicutes>Clostridia", +#' "Archaea>Euryarchaeota>Thermococci")) +#' shortened_df <- shortenLineage(df, colname = "Lineage", abr_len = 1) +#' print(shortened_df) #' } shortenLineage <- function(data, colname = "Lineage", abr_len = 1) { abbrv <- function(x) { @@ -65,23 +79,29 @@ shortenLineage <- function(data, colname = "Lineage", abr_len = 1) { #' #' @param query_data Data frame of protein homologs with the usual 11 columns + #' additional word columns (0/1 format). Default is toast_rack.sub -#' @param colname +#' @param colname Column name from query_data: "DomArch.norep", "GenContext.norep", +#' "DomArch.PFAM.norep" or "DomArch.LADB.norep". Default is "DomArch.norep". #' @param cutoff Numeric. Cutoff for word frequency. Default is 90. -#' @param RowsCutoff -#' @param text.scale Allows scaling of axis title, tick lables, and numbers above the intersection size bars. +#' @param RowsCutoff Boolean. If TRUE, applies a row cutoff to remove data rows +#' based on a certain condition. Default is FALSE. +#' @param text.scale Allows scaling of axis title, tick lables, and numbers +#' above the intersection size bars. #' text.scale can either take a universal scale in the form of an integer, #' or a vector of specific scales in the format: c(intersection size title, #' intersection size tick labels, set size title, set size tick labels, set names, #' numbers above bars) -#' @param point.size -#' @param line.size +#' @param point.size Numeric. Sets the size of points in the UpSet plot. +#' Default is 2.2. +#' @param line.size Numeric. Sets the line width in the UpSet plot. +#' Default is 0.8. #' #' @importFrom dplyr across distinct filter if_else mutate pull select where #' @importFrom rlang sym #' @importFrom stringr str_detect str_replace_all str_split #' @importFrom UpSetR upset #' -#' @return +#' @return An UpSet plot object. The plot visualizes intersections of sets based +#' on the provided colname in query_data. #' @export #' #' @note Please refer to the source code if you have alternate file formats and/or @@ -230,8 +250,9 @@ plotUpSet <- function(query_data = "toast_rack.sub", #' Default is prot (variable w/ protein data). #' @param colname Column name from query_data: "DomArch.norep", "GenContext.norep", #' "DomArch.PFAM.norep" or "DomArch.LADB.norep". Default is "DomArch.norep". -#' @param cutoff -#' @param RowsCutoff +#' @param cutoff Numeric. Cutoff for word frequency. Default is 90. +#' @param RowsCutoff Boolean. If TRUE, applies a row cutoff to remove data rows +#' based on a certain condition. Default is FALSE. #' @param color Color for the heatmap. One of six options: "default", "magma", "inferno", #' "plasma", "viridis", or "cividis" #' @@ -243,7 +264,7 @@ plotUpSet <- function(query_data = "toast_rack.sub", #' @importFrom viridis scale_fill_viridis #' @importFrom rlang sym #' -#' @return +#' @return A LineageDA plot object. #' @export #' #' @details @@ -325,7 +346,7 @@ plotLineageDA <- function(query_data = "prot", #' Lineage Plot: Heatmap of Queries vs Lineages #' -#' @authors Janani Ravi, Samuel Chen +#' @author Janani Ravi, Samuel Chen #' @keywords Lineages, Domains, Domain Architectures, GenomicContexts #' @description #' Lineage plot for queries. Heatmap. @@ -333,10 +354,14 @@ plotLineageDA <- function(query_data = "prot", #' @param query_data Data frame of protein homologs with the usual 11 columns + #' additional word columns (0/1 format). #' Default is prot (variable w/ protein data). -#' @param queries Character Vector containing the queries that will be used for the categories -#' @param colname -#' @param cutoff -#' @param color +#' @param queries Character Vector containing the queries that will be used for +#' the categories. +#' @param colname Character. The column used for filtering based on the `queries`. +#' Default is "ClustName". +#' @param cutoff Numeric. The cutoff value for filtering rows based on their +#' total count. Rows with values below this cutoff are excluded. +#' @param color Character. Defines the color palette used for the heatmap. +#' Default is a red gradient. #' #' @importFrom dplyr arrange desc filter group_by select summarise union #' @importFrom ggplot2 aes aes_string element_rect element_text geom_tile ggplot scale_fill_gradient scale_x_discrete theme theme_minimal @@ -346,7 +371,9 @@ plotLineageDA <- function(query_data = "prot", #' @importFrom tidyr drop_na #' @importFrom viridis scale_fill_viridis #' -#' @return +#' @return A ggplot object representing a heatmap (tile plot) showing the +#' relationship between queries and lineages, with the intensity of color +#' representing the count of matching records. #' @export #' #' @note @@ -476,7 +503,9 @@ plotLineageQuery <- function(query_data = all, #' @importFrom stringr str_replace_all #' @importFrom tidyr gather #' -#' @return +#' @return A ggplot object representing a heatmap (tile plot) of lineage versus +#' the top neighboring domain architectures, with color intensity representing +#' the frequency of occurrences. #' @export #' #' @details @@ -554,15 +583,19 @@ plotLineageNeighbors <- function(query_data = "prot", query = "pspa", #' Lineage Domain Repeats Plot #' -#' @param query_data -#' @param colname +#' @param query_data Data frame containing protein homolog data, including +#' relevant domain architectures and lineages. +#' @param colname Character. The name of the column in query_data that contains +#' domain architectures or other structural information. #' #' @importFrom dplyr across mutate select where #' @importFrom ggplot2 aes element_text geom_tile ggplot scale_fill_gradient scale_x_discrete theme theme_minimal #' @importFrom stringr str_count str_replace_all #' @importFrom tidyr gather #' -#' @return +#' @return A ggplot object representing a heatmap (tile plot) of domain repeat +#' counts across different lineages, with color intensity representing the +#' occurrence of domains. #' @export #' #' @examples @@ -646,7 +679,9 @@ plotLineageDomainRepeats <- function(query_data, colname) { #' @importFrom purrr map #' @importFrom stringr str_locate str_locate_all #' -#' @return +#' @return A ggplot object representing a heatmap (tile plot) of domain repeat +#' counts across different lineages, with color intensity representing the +#' occurrence of domains. #' @export #' #' @examples @@ -791,25 +826,35 @@ plotLineageHeatmap <- function(prot, domains_of_interest, level = 3, label.size #' Stacked Lineage Plot #' -#' @param prot -#' @param column -#' @param cutoff -#' @param Lineage_col -#' @param xlabel -#' @param reduce_lineage -#' @param label.size -#' @param legend.position -#' @param legend.text.size -#' @param legend.cols -#' @param legend.size -#' @param coord_flip -#' @param legend +#' @param prot Data frame containing protein data including domain architecture +#' and lineage information. +#' @param column Character. The name of the column in prot representing domain +#' architectures (default is "DomArch"). +#' @param cutoff Numeric. A threshold value for filtering domain architectures +#' or protein counts. +#' @param Lineage_col Character. The name of the column representing lineage +#' data (default is "Lineage"). +#' @param xlabel Character. Label for the x-axis +#' (default is "Domain Architecture"). +#' @param reduce_lineage Logical. Whether to shorten lineage names +#' (default is TRUE). +#' @param label.size Numeric. The size of axis text labels (default is 8). +#' @param legend.position Numeric vector. Coordinates for placing the legend +#' (default is c(0.7, 0.4)). +#' @param legend.text.size Numeric. Size of the text in the legend +#' (default is 10). +#' @param legend.cols Numeric. Number of columns in the legend (default is 2). +#' @param legend.size Numeric. Size of the legend keys (default is 0.7). +#' @param coord_flip Logical. Whether to flip the coordinates of the plot +#' (default is TRUE). +#' @param legend Logical. Whether to display the legend (default is TRUE). #' #' @importFrom dplyr pull select #' @importFrom ggplot2 aes_string coord_flip element_blank element_line element_rect element_text geom_bar ggplot guides guide_legend scale_fill_manual xlab ylab theme theme_minimal #' @importFrom purrr map #' -#' @return +#' @return A ggplot object representing a stacked bar plot showing the +#' distribution of protein domain architectures across lineages. #' @export #' #' @examples @@ -937,31 +982,46 @@ plotStackedLineage <- function(prot, column = "DomArch", cutoff, Lineage_col = " #' plotWordCloud3 #' -#' @param data -#' @param size -#' @param minSize -#' @param gridSize -#' @param fontFamily -#' @param fontWeight -#' @param color -#' @param backgroundColor -#' @param minRotation -#' @param maxRotation -#' @param shuffle -#' @param rotateRatio -#' @param shape -#' @param ellipticity -#' @param widgetsize -#' @param figPath -#' @param hoverFunction +#' @param data Data frame or table containing words and their frequencies for +#' the word cloud. +#' @param size Numeric. Scaling factor for word sizes (default is 1). +#' @param minSize Numeric. Minimum font size for the smallest word +#' (default is 0). +#' @param gridSize Numeric. Size of the grid for placing words (default is 0). +#' @param fontFamily Character. Font family to use for the words +#' (default is "Segoe UI"). +#' @param fontWeight Character. Font weight for the words (default is "bold"). +#' @param color Character or vector. Color of the words. Use "random-dark" for +#' random dark colors (default) or specify a color. +#' @param backgroundColor Character. Background color of the word cloud +#' (default is "white"). +#' @param minRotation Numeric. Minimum rotation angle of words in radians +#' (default is -π/4). +#' @param maxRotation Numeric. Maximum rotation angle of words in radians +#' (default is π/4). +#' @param shuffle Logical. Whether to shuffle the words (default is TRUE). +#' @param rotateRatio Numeric. Proportion of words that are rotated +#' (default is 0.4). +#' @param shape Character. Shape of the word cloud ("circle" is default, but +#' you can use "cardioid", "star", "triangle", etc.). +#' @param ellipticity Numeric. Degree of ellipticity (default is 0.65). +#' @param widgetsize Numeric vector. Width and height of the widget +#' (default is NULL, which uses default size). +#' @param figPath Character. Path to an image file to use as a mask for the +#' word cloud (optional). +#' @param hoverFunction JS function. JavaScript function to run when hovering +#' over words (optional). #' #' @importFrom base64enc base64encode #' @importFrom htmlwidgets createWidget JS sizingPolicy #' -#' @return +#' @return An HTML widget object displaying a word cloud. #' @export #' #' @examples +#' \dontrun{ +#' wordcloud3(data = your_data, size = 1.5, color = "random-light") +#' } wordcloud3 <- function(data, size = 1, minSize = 0, gridSize = 0, fontFamily = "Segoe UI", fontWeight = "bold", color = "random-dark", backgroundColor = "white", minRotation = -pi / 4, maxRotation = pi / 4, shuffle = TRUE, @@ -1022,16 +1082,20 @@ wordcloud3 <- function(data, size = 1, minSize = 0, gridSize = 0, fontFamily = " #' #' @param query_data Data frame of protein homologs with the usual 11 columns + #' additional word columns (0/1 format). Default is "prot". -#' @param colname -#' @param cutoff -#' @param UsingRowsCutoff +#' @param colname Character. The name of the column in `query_data` to generate +#' the word cloud from. Default is "DomArch". +#' @param cutoff Numeric. The cutoff value for filtering elements based on their +#' frequency. Default is 70. +#' @param UsingRowsCutoff Logical. Whether to use a row-based cutoff instead of +#' a frequency cutoff. Default is FALSE. #' #' @importFrom dplyr filter pull #' @importFrom RColorBrewer brewer.pal #' @importFrom rlang sym #' @importFrom wordcloud wordcloud #' -#' @return +#' @return A word cloud plot showing the frequency of elements from the selected +#' column. #' @export #' #' @details @@ -1102,14 +1166,18 @@ createWordCloudElement <- function(query_data = "prot", #' #' @param query_data Data frame of protein homologs with the usual 11 columns + #' additional word columns (0/1 format). Default is "prot". -#' @param colname -#' @param cutoff -#' @param UsingRowsCutoff +#' @param colname Character. The name of the column in `query_data` to generate +#' the word cloud from. Default is "DomArch". +#' @param cutoff Numeric. The cutoff value for filtering elements based on their +#' frequency. Default is 70. +#' @param UsingRowsCutoff Logical. Whether to use a row-based cutoff instead of +#' a frequency cutoff. Default is FALSE. #' #' @importFrom dplyr filter pull #' @importFrom rlang sym #' -#' @return +#' @return A word cloud plot showing the frequency of elements from the selected +#' column. #' @export #' #' @details @@ -1172,16 +1240,23 @@ createWordCloud2Element <- function(query_data = "prot", #### Sunburst ##### #' Lineage Sunburst #' -#' @param prot Data frame containing a lineage column that the sunburst plot will be generated for -#' @param lineage_column String. Name of the lineage column within the data frame. Defaults to "Lineage" -#' @param type String, either "sunburst" or "sund2b". If type is "sunburst", a sunburst plot of the lineage +#' @param prot Data frame containing a lineage column that the sunburst plot +#' will be generated for +#' @param lineage_column String. Name of the lineage column within the +#' data frame. Defaults to "Lineage" +#' @param type String, either "sunburst" or "sund2b". If type is "sunburst", +#' a sunburst plot of the lineage #' @param levels Integer. Number of levels the sunburst will have. -#' @param colors -#' @param legendOrder String vector. The order of the legend. If legendOrder is NULL, -#' @param showLegend Boolean. If TRUE, the legend will be enabled when the component first renders. -#' @param maxLevels Integer, the maximum number of levels to display in the sunburst; 5 by default, NULL to disable -#' then the legend will be in the descending order of the top level hierarchy. -#' will be rendered. If the type is sund2b, a sund2b plot will be rendered. +#' @param colors A vector of colors for the sunburst plot. +#' If NULL, default colors are used. +#' @param legendOrder String vector. The order of the legend. If legendOrder +#' is NULL, +#' @param showLegend Boolean. If TRUE, the legend will be enabled when the +#' component first renders. +#' @param maxLevels Integer, the maximum number of levels to display in the +#' sunburst; 5 by default, NULL to disable then the legend will be in the +#' descending order of the top level hierarchy. will be rendered. If the type is +#' sund2b, a sund2b plot will be rendered. #' #' @importFrom d3r d3_nest #' @importFrom dplyr arrange desc group_by_at select summarise @@ -1190,12 +1265,13 @@ createWordCloud2Element <- function(query_data = "prot", #' @importFrom sunburstR sunburst sund2b #' @importFrom tidyr drop_na separate #' -#' @return +#' @return A sunburst or sund2b plot based on the input lineage data. #' @export #' #' @examples #' \dontrun{ -#' plotLineageSunburst() +#' plotLineageSunburst(prot, lineage_column = "Lineage", +#' type = "sunburst", levels = 3) #' } plotLineageSunburst <- function(prot, lineage_column = "Lineage", type = "sunburst", diff --git a/R/pre-msa-tree.R b/R/pre-msa-tree.R index 44979c3c..5904a522 100644 --- a/R/pre-msa-tree.R +++ b/R/pre-msa-tree.R @@ -45,10 +45,12 @@ api_key <- Sys.getenv("ENTREZ_API_KEY", unset = "YOUR_KEY_HERE") #' @param x Character vector. #' @param y Delimitter. Default is space (" "). #' -#' @return +#' @return A character vector in title case. #' @export #' #' @examples +#' to_titlecase("hello world") +#' to_titlecase("this is a test", "_") to_titlecase <- function(x, y = " ") { s <- strsplit(x, y)[[1]] paste(toupper(substring(s, 1, 1)), substring(s, 2), @@ -87,7 +89,8 @@ to_titlecase <- function(x, y = " ") { #' @importFrom stringr str_sub #' @importFrom tidyr replace_na separate #' -#' @return +#' @return A data frame containing the combined alignment and lineage +#' information. #' @export #' #' @note Please refer to the source code if you have alternate + @@ -188,8 +191,8 @@ add_leaves <- function(aln_file = "", #' #' @author Samuel Chen, Janani Ravi #' -#' @description This function adds a new 'Name' column that is comprised of components from -#' Kingdom, Phylum, Genus, and species, as well as the accession +#' @description This function adds a new 'Name' column that is comprised of +#' components from Kingdom, Phylum, Genus, and species, as well as the accession #' #' @param data Data to add name column to #' @param accnum_col Column containing accession numbers @@ -209,6 +212,9 @@ add_leaves <- function(aln_file = "", #' @export #' #' @examples +#' \dontrun{ +#' add_name(data_frame) +#' } add_name <- function(data, accnum_col = "AccNum", spec_col = "Species", lin_col = "Lineage", lin_sep = ">", out_col = "Name") { @@ -272,8 +278,8 @@ add_name <- function(data, #' Default is 'pspa.txt' #' @param fa_outpath Character. Path to the written fasta file. #' Default is 'NULL' -#' @param reduced Boolean. If TRUE, the fasta file will contain only one sequence per lineage. -#' Default is 'FALSE' +#' @param reduced Boolean. If TRUE, the fasta file will contain only one +#' sequence per lineage. Default is 'FALSE' #' #' @details The alignment file would need two columns: 1. accession + #' number and 2. alignment. The protein homolog accession to lineage mapping + @@ -283,7 +289,9 @@ add_name <- function(data, #' #' @importFrom readr write_file #' -#' @return +#' @return Character string containing the Fasta formatted sequences. +#' If `fa_outpath` is specified, the function also writes the sequences to the +#' Fasta file. #' @export #' #' @examples @@ -326,7 +334,7 @@ convert_aln2fa <- function(aln_file = "", #' Default rename_fasta() replacement function. Maps an accession number to its name #' -#' @param line he line of a fasta file starting with '>' +#' @param line The line of a fasta file starting with '>' #' @param acc2name Data Table containing a column of accession numbers and a name column #' @param acc_col Name of the column containing Accession numbers #' @param name_col Name of the column containing the names that the accession numbers @@ -336,10 +344,18 @@ convert_aln2fa <- function(aln_file = "", #' @importFrom stringr str_locate #' @importFrom rlang sym #' -#' @return +#' @return Character string. The modified line from the Fasta file header with +#' the name instead of the accession number. #' @export #' #' @examples +#' \dontrun{ +#' acc2name_table <- data.table(AccNum = c("ACC001", "ACC002"), +#' Name = c("Species A", "Species B")) +#' line <- ">ACC001 some additional info" +#' mapped_line <- map_acc2name(line, acc2name_table) +#' print(mapped_line) # Expected output: ">Species A" +#' } map_acc2name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") { # change to be the name equivalent to an add_names column # Find the first ' ' @@ -365,10 +381,14 @@ map_acc2name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") #' @importFrom purrr map #' @importFrom readr read_lines write_lines #' -#' @return +#' @return Character vector containing the modified lines of the Fasta file. #' @export #' #' @examples +#' \dontrun{ +#' rename_fasta("input.fasta", "output.fasta", +#' replacement_function = map_acc2name, acc2name = acc2name_table) +#' } rename_fasta <- function(fa_path, outpath, replacement_function = map_acc2name, ...) { lines <- read_lines(fa_path) @@ -397,18 +417,21 @@ rename_fasta <- function(fa_path, outpath, #' Default is 'here("data/rawdata_aln/")' #' @param fa_outpath Character. Path to the written fasta file. #' Default is 'here("data/alns/")'. -#' @param lin_file Character. Path to file. Master protein file with AccNum & lineages. -#' Default is 'here("data/rawdata_tsv/all_semiclean.txt")' -#' @param reduced Boolean. If TRUE, the fasta file will contain only one sequence per lineage. -#' Default is 'FALSE'. +#' @param lin_file Character. Path to file. Master protein file with AccNum & +#' lineages. Default is 'here("data/rawdata_tsv/all_semiclean.txt")' +#' @param reduced Boolean. If TRUE, the fasta file will contain only one +#' sequence per lineage. Default is 'FALSE'. #' -#' @details The alignment files would need two columns separated by spaces: 1. AccNum and 2. alignment. The protein homolog file should have AccNum, Species, Lineages. -#' @note Please refer to the source code if you have alternate + file formats and/or column names. +#' @details The alignment files would need two columns separated by spaces: 1. +#' AccNum and 2. alignment. The protein homolog file should have AccNum, +#' Species, Lineages. +#' @note Please refer to the source code if you have alternate + file +#' formats and/or column names. #' #' @importFrom purrr pmap #' @importFrom stringr str_replace_all #' -#' @return +#' @return A list of paths to the generated Fasta files. #' @export #' #' @examples @@ -456,24 +479,27 @@ generate_all_aln2fa <- function(aln_path = here("data/rawdata_aln/"), #' Resulting fasta file is written to the outpath. #' #' -#' @param accessions Character vector containing protein accession numbers to generate fasta sequences for. -#' Function may not work for vectors of length > 10,000 +#' @param accessions Character vector containing protein accession numbers to +#' generate fasta sequences for. Function may not work for vectors of +#' length > 10,000 #' @param outpath [str]. Location where fasta file should be written to. -#' @param plan +#' @param plan Character. The plan to use for processing. Default is "sequential". #' #' @importFrom Biostrings readAAStringSet #' @importFrom future future plan #' @importFrom purrr map #' @importFrom rentrez entrez_fetch #' -#' @return +#' @return A Fasta file is written to the specified `outpath`. #' @export #' #' @examples #' \dontrun{ -#' acc2fa(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), outpath = "my_proteins.fasta") +#' acc2fa(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), +#' outpath = "my_proteins.fasta") #' Entrez:accessions <- rep("ANY95992.1", 201) |> acc2fa(outpath = "entrez.fa") -#' EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> acc2fa(outpath = "ebi.fa") +#' EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> +#' acc2fa(outpath = "ebi.fa") #' } acc2fa <- function(accessions, outpath, plan = "sequential") { # validation @@ -562,14 +588,23 @@ acc2fa <- function(accessions, outpath, plan = "sequential") { #' @importFrom dplyr filter pull #' @importFrom rlang sym #' -#' @return +#' @return A character vector containing representative accession numbers, +#' one for each distinct observation in the specified 'reduced' column. #' @export #' #' @examples +#' \dontrun{ +#' # Example usage with a data frame called `protein_data` +#' representative_accessions <- RepresentativeAccNums(prot_data = protein_data, +#' reduced = "Lineage", +#' accnum_col = "AccNum") +#' print(representative_accessions) +#' } RepresentativeAccNums <- function(prot_data, reduced = "Lineage", accnum_col = "AccNum") { - # Get Unique reduced column and then bind the AccNums back to get one AccNum per reduced column + # Get Unique reduced column and then bind the AccNums back to get one + # AccNum per reduced column reduced_sym <- sym(reduced) accnum_sym <- sym(accnum_col) @@ -603,8 +638,10 @@ RepresentativeAccNums <- function(prot_data, #' @author Samuel Chen, Janani Ravi #' #' @param fasta_file Path to the FASTA file to be aligned -#' @param tool Type of alignment tool to use. One of three options: "Muscle", "ClustalO", or "ClustalW" -#' @param outpath Path to write the resulting alignment to as a FASTA file. If NULL, no file is written +#' @param tool Type of alignment tool to use. One of three options: "Muscle", +#' "ClustalO", or "ClustalW" +#' @param outpath Path to write the resulting alignment to as a FASTA file. If +#' NULL, no file is written #' #' @importFrom Biostrings readAAStringSet #' @importFrom msa msaMuscle msaClustalOmega msaClustalW @@ -613,6 +650,12 @@ RepresentativeAccNums <- function(prot_data, #' @export #' #' @examples +#' \dontrun{ +#' # Example usage +#' aligned_sequences <- alignFasta("path/to/sequences.fasta", +#' tool = "ClustalO", outpath = "path/to/aligned_sequences.fasta") +#' print(aligned_sequences) +#' } alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { fasta <- readAAStringSet(fasta_file) @@ -643,10 +686,15 @@ alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { #' @importFrom Biostrings unmasked #' @importFrom readr write_file #' -#' @return +#' @return Character string of the FASTA content that was written to the file. #' @export #' #' @examples +#' \dontrun{ +#' # Example usage +#' alignment <- alignFasta("path/to/sequences.fasta") +#' write.MsaAAMultipleAlignment(alignment, "path/to/aligned_sequences.fasta") +#' } write.MsaAAMultipleAlignment <- function(alignment, outpath) { l <- length(rownames(alignment)) fasta <- "" @@ -662,15 +710,21 @@ write.MsaAAMultipleAlignment <- function(alignment, outpath) { #' get_accnums_from_fasta_file #' -#' @param fasta_file +#' @param fasta_file Character. Path to the FASTA file from which +#' accession numbers will be extracted. #' #' @importFrom readr read_file #' @importFrom stringi stri_extract_all_regex #' -#' @return +#' @return A character vector containing the extracted accession numbers. #' @export #' #' @examples +#' \dontrun{ +#' # Example usage +#' accnums <- get_accnums_from_fasta_file("path/to/sequences.fasta") +#' print(accnums) +#' } get_accnums_from_fasta_file <- function(fasta_file) { txt <- read_file(fasta_file) accnums <- stringi::stri_extract_all_regex(fasta_file, "(?<=>)[\\w,.]+")[[1]] diff --git a/R/reverse_operons.R b/R/reverse_operons.R index e4bbd50e..b165ef72 100755 --- a/R/reverse_operons.R +++ b/R/reverse_operons.R @@ -3,14 +3,26 @@ # Modified by Janani Ravi and Samuel Chen -#' reveql +#' reveql: Reverse Equalities in Genomic Context #' -#' @param prot +#' @description +#' This function processes the genomic context strings (GenContext) and reverses +#' directional signs based on the presence of an equal sign ("="). +#' +#' @param prot [vector] A vector of genomic context strings to be processed. +#' +#' @return [vector] A vector of the same length as the input, where each genomic +#' element is annotated with either a forward ("->") or reverse ("<-") direction, +#' depending on its position relative to the "=" symbols. #' -#' @return #' @export #' #' @examples +#' # Example input: Genomic context with directional symbols and an asterisk +#' genomic_context <- c("A", "B", "*", "C", "D", "=", "E", "F") +#' reveql(genomic_context) +#' +#' # Output: "A->", "B->", "*", "<-C", "<-D", "=", "E->", "F->" reveql <- function(prot) { w <- prot # $GenContext.orig # was 'x' @@ -57,14 +69,28 @@ reveql <- function(prot) { ## The function to reverse operons -#' reverse_operon +#' reverse_operon: Reverse the Direction of Operons in Genomic Context +#' +#' @description +#' This function processes a genomic context data frame to reverse the direction +#' of operons based on specific patterns in the GenContext column. It handles +#' elements represented by ">" and "<" and restructures the genomic context by +#' flipping the direction of operons while preserving the relationships +#' indicated by "=". +#' +#' @param prot [data.frame] A data frame containing at least a column named +#' 'GenContext', which represents the genomic contexts that need to be reversed. #' -#' @param prot +#' @return [data.frame] The input data frame with the 'GenContext' column updated t +#' o reflect the reversed operons. #' -#' @return #' @export #' #' @examples +#' # Example genomic context data frame +#' prot <- data.frame(GenContext = c("A>B", "CI")) +#' reversed_prot <- reverse_operon(prot) +#' print(reversed_prot) reverse_operon <- function(prot) { gencontext <- prot$GenContext diff --git a/man/BinaryDomainNetwork.Rd b/man/BinaryDomainNetwork.Rd index bb7e2353..5c35be0f 100644 --- a/man/BinaryDomainNetwork.Rd +++ b/man/BinaryDomainNetwork.Rd @@ -19,20 +19,32 @@ BinaryDomainNetwork( \arguments{ \item{prot}{A data frame that contains the column 'DomArch'.} -\item{column}{Name of column containing Domain architecture from which nodes and edges are generated.} +\item{column}{Name of column containing Domain architecture from which nodes +and edges are generated.} -\item{cutoff}{Integer. Only use domains that occur at or above the cutoff for total counts if cutoff_type is "Total Count". -Only use domains that appear in cutoff or greater lineages if cutoff_type is Lineage.} +\item{domains_of_interest}{Character vector specifying the domains of interest.} + +\item{cutoff}{Integer. Only use domains that occur at or above the cutoff for +total counts if cutoff_type is "Total Count". +Only use domains that appear in cutoff or greater lineages if cutoff_type is +Lineage.} \item{layout}{Character. Layout type to be used for the network. Options are: \itemize{\item "grid" \item "circle" \item "random" \item "auto"}} -\item{query_color}{Color that the nodes of the domains in the domains_of_interest vector are colored} +\item{query_color}{Color that the nodes of the domains in the +domains_of_interest vector are colored} + +\item{partner_color}{Color that the nodes that are not part of the +domains_of_interest vector are colored} -\item{partner_color}{Color that the nodes that are not part of the domains_of_interest vector are colored} +\item{border_color}{Color for the borders of the nodes.} \item{IsDirected}{Is the network directed? Set to false to eliminate arrows} } +\value{ +A network visualization of domain architectures. +} \description{ This function creates a domain network from the 'DomArch' column. @@ -42,6 +54,6 @@ A network of domains is returned based on shared domain architectures. } \examples{ \dontrun{ -domain_network(pspa) +BinaryDomainNetwork(pspa) } } diff --git a/man/GCA2Lineage.Rd b/man/GCA2Lineage.Rd index 9ec0ce56..796c2efb 100644 --- a/man/GCA2Lineage.Rd +++ b/man/GCA2Lineage.Rd @@ -21,7 +21,13 @@ This file can be generated using the "downloadAssemblySummary()" function} (taxid to lineage mapping). This file can be generated using the "create_lineage_lookup()" function} -\item{acc_col}{} +\item{acc_col}{Character. The name of the column in \code{prot_data} containing +accession numbers. Default is "AccNum".} +} +\value{ +A dataframe containing the merged information of GCA_IDs, TaxIDs, +and their corresponding lineage up to the phylum level. The dataframe +will include information from the input \code{prot_data} and lineage data. } \description{ Function to map GCA_ID to TaxID, and TaxID to Lineage @@ -29,6 +35,13 @@ Function to map GCA_ID to TaxID, and TaxID to Lineage \note{ Currently configured to have at most kingdom and phylum } +\examples{ +\dontrun{ +result <- GCA2Lineage(prot_data = my_prot_data, + assembly_path = "path/to/assembly_summary.txt", + lineagelookup_path = "path/to/lineage_lookup.tsv") +} +} \author{ Samuel Chen, Janani Ravi } diff --git a/man/GenContextNetwork.Rd b/man/GenContextNetwork.Rd index 2eeebbc5..08d4f476 100644 --- a/man/GenContextNetwork.Rd +++ b/man/GenContextNetwork.Rd @@ -18,15 +18,20 @@ GenContextNetwork( \item{domains_of_interest}{Character vector of domains of interest.} -\item{column}{Name of column containing Genomic Context from which nodes and edges are generated.} +\item{column}{Name of column containing Genomic Context from which nodes and +edges are generated.} -\item{cutoff}{Integer. Only use GenContexts that occur at or above the cutoff percentage for total count} +\item{cutoff}{Integer. Only use GenContexts that occur at or above the cutoff +percentage for total count} \item{layout}{Character. Layout type to be used for the network. Options are: \itemize{\item "grid" \item "circle" \item "random" \item "auto" \item "nice"}} \item{directed}{Is the network directed?} } +\value{ +A plot of the genomic context network. +} \description{ This function creates a Genomic Context network from the 'GenContext' column. @@ -34,6 +39,6 @@ A network of Genomic Context is returned. } \examples{ \dontrun{ -gc_directed_network(pspa, column = "GenContex", cutoff = 55) +gc_directed_network(pspa, column = "GenContext", cutoff = 55) } } diff --git a/man/IPG2Lineage.Rd b/man/IPG2Lineage.Rd index 282d5cbf..42b9b943 100644 --- a/man/IPG2Lineage.Rd +++ b/man/IPG2Lineage.Rd @@ -27,6 +27,10 @@ IPG2Lineage( ipg database. The protein accession in 'accessions' should be contained in this file} +\item{refseq_assembly_path}{String. Path to the RefSeq assembly summary file.} + +\item{genbank_assembly_path}{String. Path to the GenBank assembly summary file.} + \item{lineagelookup_path}{String of the path to the lineage lookup file (taxid to lineage mapping). This file can be generated using the "create_lineage_lookup()" function} @@ -37,6 +41,9 @@ This file can be generated using the \link[MolEvolvR]{downloadAssemblySummary} f \value{ A \code{data.table} with the lineage information for the provided protein accessions. + +A data table containing protein accessions along with their +corresponding TaxIDs and lineage information. } \description{ Takes the resulting file of an efetch run on the ipg database and @@ -49,6 +56,15 @@ append lineage, and taxid columns IPG2Lineage() } +\dontrun{ +lins <- IPG2Lineage( + accessions = c("P12345", "Q67890"), + ipg_file = "path/to/ipg_results.txt", + refseq_assembly_path = "path/to/refseq_assembly_summary.txt", + genbank_assembly_path = "path/to/genbank_assembly_summary.txt", + lineagelookup_path = "path/to/lineage_lookup.tsv" +) +} } \author{ Samuel Chen, Janani Ravi diff --git a/man/RepresentativeAccNums.Rd b/man/RepresentativeAccNums.Rd index f617cde4..49192f8e 100644 --- a/man/RepresentativeAccNums.Rd +++ b/man/RepresentativeAccNums.Rd @@ -2,7 +2,8 @@ % Please edit documentation in R/CHANGED-pre-msa-tree.R, R/pre-msa-tree.R \name{RepresentativeAccNums} \alias{RepresentativeAccNums} -\title{Function to generate a vector of one Accession number per distinct observation from 'reduced' column} +\title{Function to generate a vector of one Accession number per distinct +observation from 'reduced' column} \usage{ RepresentativeAccNums(prot_data, reduced = "Lineage", accnum_col = "AccNum") @@ -17,9 +18,29 @@ One accession number will be assigned for each of these observations} \item{accnum_col}{Column from prot_data that contains Accession Numbers} } +\value{ +A character vector containing one Accession number per distinct +observation from the specified reduced column. + +A character vector containing representative accession numbers, +one for each distinct observation in the specified 'reduced' column. +} \description{ Function to generate a vector of one Accession number per distinct observation from 'reduced' column } +\examples{ +\dontrun{ +representative_accessions <- RepresentativeAccNums(prot_data, +reduced = "Lineage", accnum_col = "AccNum") +} +\dontrun{ +# Example usage with a data frame called `protein_data` +representative_accessions <- RepresentativeAccNums(prot_data = protein_data, + reduced = "Lineage", + accnum_col = "AccNum") +print(representative_accessions) +} +} \author{ Samuel Chen, Janani Ravi } diff --git a/man/acc2FA.Rd b/man/acc2FA.Rd new file mode 100644 index 00000000..6c6ea43c --- /dev/null +++ b/man/acc2FA.Rd @@ -0,0 +1,39 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/CHANGED-pre-msa-tree.R +\name{acc2FA} +\alias{acc2FA} +\title{acc2FA converts protein accession numbers to a fasta format.} +\usage{ +acc2FA(accessions, outpath, plan = "sequential") +} +\arguments{ +\item{accessions}{Character vector containing protein accession numbers to +generate fasta sequences for. +Function may not work for vectors of length > 10,000} + +\item{outpath}{\link{str} Location where fasta file should be written to.} + +\item{plan}{Character string specifying the parallel processing strategy to +use with the \code{future} package. Default is "sequential".} +} +\value{ +A logical value indicating whether the retrieval and conversion were +successful. Returns \code{TRUE} if successful and \code{FALSE} otherwise. +} +\description{ +Resulting fasta file is written to the outpath. +} +\examples{ +\dontrun{ +acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), +outpath = "my_proteins.fasta") +Entrez:accessions <- rep("ANY95992.1", 201) |> acc2FA(outpath = "entrez.fa") +EBI:accessions <- c("P12345", "Q9UHC1", +"O15530", "Q14624", "P0DTD1") |> acc2FA(outpath = "ebi.fa") +} +} +\author{ +Samuel Chen, Janani Ravi +} +\keyword{accnum,} +\keyword{fasta} diff --git a/man/acc2Lineage.Rd b/man/acc2Lineage.Rd index a46b6f20..ce499592 100644 --- a/man/acc2Lineage.Rd +++ b/man/acc2Lineage.Rd @@ -32,11 +32,16 @@ This file can be generated using the "downloadAssemblySummary()" function} \item{ipgout_path}{Path to write the results of the efetch run of the accessions on the ipg database. If NULL, the file will not be written. Defaults to NULL} -\item{plan}{} +\item{plan}{Character. Specifies the execution plan for parallel processing. +Default is "multicore".} } \value{ A \code{data.table} that contains the lineage information, mapping protein accessions to their tax IDs and lineages. + +A dataframe containing lineage information mapped to the given protein +accessions. The dataframe includes relevant columns such as TaxID, GCA_ID, +Protein, Protein Name, Species, and Lineage. } \description{ This function combines 'efetchIPG()' and 'IPG2Lineage()' to map a set @@ -51,6 +56,14 @@ of protein accessions to their assembly (GCA_ID), tax ID, and lineage. \dontrun{ acc2Lineage() } +\dontrun{ +lineage_data <- acc2Lineage( + accessions = c("P12345", "Q67890"), + assembly_path = "path/to/assembly_summary.txt", + lineagelookup_path = "path/to/lineage_lookup.tsv", + ipgout_path = "path/to/output.txt" +) +} } \author{ Samuel Chen, Janani Ravi diff --git a/man/acc2fa.Rd b/man/acc2fa.Rd index 158b2d51..517ee3d6 100644 --- a/man/acc2fa.Rd +++ b/man/acc2fa.Rd @@ -7,12 +7,16 @@ acc2fa(accessions, outpath, plan = "sequential") } \arguments{ -\item{accessions}{Character vector containing protein accession numbers to generate fasta sequences for. -Function may not work for vectors of length > 10,000} +\item{accessions}{Character vector containing protein accession numbers to +generate fasta sequences for. Function may not work for vectors of +length > 10,000} \item{outpath}{\link{str}. Location where fasta file should be written to.} -\item{plan}{} +\item{plan}{Character. The plan to use for processing. Default is "sequential".} +} +\value{ +A Fasta file is written to the specified \code{outpath}. } \description{ acc2fa converts protein accession numbers to a fasta format. @@ -20,9 +24,11 @@ Resulting fasta file is written to the outpath. } \examples{ \dontrun{ -acc2fa(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), outpath = "my_proteins.fasta") +acc2fa(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), +outpath = "my_proteins.fasta") Entrez:accessions <- rep("ANY95992.1", 201) |> acc2fa(outpath = "entrez.fa") -EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> acc2fa(outpath = "ebi.fa") +EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> +acc2fa(outpath = "ebi.fa") } } \author{ diff --git a/man/addLeaves2Alignment.Rd b/man/addLeaves2Alignment.Rd index a758ebd5..d7055fbf 100644 --- a/man/addLeaves2Alignment.Rd +++ b/man/addLeaves2Alignment.Rd @@ -22,6 +22,10 @@ Default is 'pspa.txt'} \item{reduced}{Boolean. If TRUE, a reduced data frame will be generated with only one sequence per lineage. Default is FALSE.} } +\value{ +A data frame containing the enriched alignment data with lineage +information. +} \description{ Adding Leaves to an alignment file w/ accessions Genomic Contexts vs Domain Architectures. diff --git a/man/addLineage.Rd b/man/addLineage.Rd index ab02a5ab..e2363463 100644 --- a/man/addLineage.Rd +++ b/man/addLineage.Rd @@ -23,26 +23,30 @@ addLineage( ) } \arguments{ -\item{df}{A \code{data.frame} containing the input data. One column must contain -the accession numbers.} +\item{df}{Dataframe containing accession numbers. The dataframe should +have a column specified by \code{acc_col} that contains these accession numbers.} -\item{acc_col}{A string specifying the column name in \code{df} that holds the -accession numbers. Defaults to \code{"AccNum"}.} +\item{acc_col}{Character. The name of the column in \code{df} containing +accession numbers. Default is "AccNum".} -\item{assembly_path}{A string specifying the path to the \code{assembly_summary.txt} -file. This file contains metadata about assemblies.} +\item{assembly_path}{String. The path to the assembly summary file generated +using the \code{downloadAssemblySummary()} function.} -\item{lineagelookup_path}{A string specifying the path to the lineage lookup -file, which contains a mapping from tax IDs to their corresponding lineages.} +\item{lineagelookup_path}{String. The path to the lineage lookup file (taxid +to lineage mapping) generated using the \code{create_lineage_lookup()} function.} -\item{ipgout_path}{(Optional) A string specifying the path where IPG database -fetch results will be saved. If \code{NULL}, the results are not written to a file.} +\item{ipgout_path}{String. Optional path to save intermediate output files. +Default is NULL.} -\item{plan}{} +\item{plan}{Character. Specifies the execution plan for parallel processing. +Default is "multicore".} } \value{ A \code{data.frame} that combines the original \code{df} with the lineage information. + +A dataframe that combines the original dataframe \code{df} with lineage +information retrieved based on the provided accession numbers. } \description{ addLineage @@ -53,4 +57,10 @@ addLineage \dontrun{ addLineage() } +\dontrun{ +enriched_df <- addLineage(df = my_data, + acc_col = "AccNum", + assembly_path = "path/to/assembly_summary.txt", + lineagelookup_path = "path/to/lineage_lookup.tsv") +} } diff --git a/man/addName.Rd b/man/addName.Rd index e04f9849..5bf400b4 100644 --- a/man/addName.Rd +++ b/man/addName.Rd @@ -34,6 +34,16 @@ Original data with a 'Name' column This function adds a new 'Name' column that is comprised of components from Kingdom, Phylum, Genus, and species, as well as the accession } +\examples{ +# Example usage of the addName function +data <- data.frame( + AccNum = c("ACC123", "ACC456"), + Species = c("Homo sapiens", "Mus musculus"), + Lineage = c("Eukaryota>Chordata", "Eukaryota>Chordata") +) +enriched_data <- addName(data) +print(enriched_data) +} \author{ Samuel Chen, Janani Ravi } diff --git a/man/addTaxID.Rd b/man/addTaxID.Rd index d2fe139d..e960769b 100644 --- a/man/addTaxID.Rd +++ b/man/addTaxID.Rd @@ -7,8 +7,26 @@ addTaxID(data, acc_col = "AccNum", version = T) } \arguments{ -\item{version}{} +\item{data}{A data frame or data table containing protein accession numbers.} + +\item{acc_col}{A string specifying the column name in \code{data} that contains +the accession numbers. Defaults to "AccNum".} + +\item{version}{A logical indicating whether to remove the last two characters +from the accession numbers for TaxID retrieval. Defaults to TRUE.} +} +\value{ +A data table that includes the original data along with a new column +containing the corresponding TaxIDs. } \description{ addTaxID } +\examples{ +\dontrun{ +# Create a sample data table with accession numbers +sample_data <- data.table(AccNum = c("ABC123.1", "XYZ456.1", "LMN789.2")) +enriched_data <- addTaxID(sample_data, acc_col = "AccNum", version = TRUE) +print(enriched_data) +} +} diff --git a/man/add_leaves.Rd b/man/add_leaves.Rd index f1eeed10..5e462a2b 100644 --- a/man/add_leaves.Rd +++ b/man/add_leaves.Rd @@ -22,6 +22,10 @@ Default is 'pspa.txt'} \item{reduced}{Boolean. If TRUE, a reduced data frame will be generated with only one sequence per lineage. Default is FALSE.} } +\value{ +A data frame containing the combined alignment and lineage +information. +} \description{ Adding Leaves to an alignment file w/ accessions Genomic Contexts vs Domain Architectures. diff --git a/man/add_name.Rd b/man/add_name.Rd index f19139e1..db7b7339 100644 --- a/man/add_name.Rd +++ b/man/add_name.Rd @@ -31,8 +31,13 @@ Lineage, and AccNum info} Original data with a 'Name' column } \description{ -This function adds a new 'Name' column that is comprised of components from -Kingdom, Phylum, Genus, and species, as well as the accession +This function adds a new 'Name' column that is comprised of +components from Kingdom, Phylum, Genus, and species, as well as the accession +} +\examples{ +\dontrun{ +add_name(data_frame) +} } \author{ Samuel Chen, Janani Ravi diff --git a/man/alignFasta.Rd b/man/alignFasta.Rd index 21b020cf..54678d0a 100644 --- a/man/alignFasta.Rd +++ b/man/alignFasta.Rd @@ -11,9 +11,11 @@ alignFasta(fasta_file, tool = "Muscle", outpath = NULL) \arguments{ \item{fasta_file}{Path to the FASTA file to be aligned} -\item{tool}{Type of alignment tool to use. One of three options: "Muscle", "ClustalO", or "ClustalW"} +\item{tool}{Type of alignment tool to use. One of three options: "Muscle", +"ClustalO", or "ClustalW"} -\item{outpath}{Path to write the resulting alignment to as a FASTA file. If NULL, no file is written} +\item{outpath}{Path to write the resulting alignment to as a FASTA file. If +NULL, no file is written} } \value{ aligned fasta sequence as a MsaAAMultipleAlignment object @@ -23,6 +25,18 @@ aligned fasta sequence as a MsaAAMultipleAlignment object \description{ Perform a Multiple Sequence Alignment on a FASTA file. } +\examples{ +\dontrun{ +aligned_sequences <- alignFasta("my_sequences.fasta", +tool = "Muscle", outpath = "aligned_output.fasta") +} +\dontrun{ +# Example usage +aligned_sequences <- alignFasta("path/to/sequences.fasta", +tool = "ClustalO", outpath = "path/to/aligned_sequences.fasta") +print(aligned_sequences) +} +} \author{ Samuel Chen, Janani Ravi } diff --git a/man/cleanDomainArchitecture.Rd b/man/cleanDomainArchitecture.Rd index 887b5388..f12f1083 100644 --- a/man/cleanDomainArchitecture.Rd +++ b/man/cleanDomainArchitecture.Rd @@ -19,21 +19,33 @@ cleanDomainArchitecture( \arguments{ \item{prot}{A data frame containing a 'DomArch' column} +\item{old}{The name of the original column containing domain architecture. +Defaults to "DomArch.orig".} + +\item{new}{The name of the cleaned column to be created. Defaults to +"DomArch".} + \item{domains_keep}{A data frame containing the domain names to be retained.} -\item{domains_rename}{A data frame containing the domain names to be replaced in a column 'old' and the +\item{domains_rename}{A data frame containing the domain names to be replaced +in a column 'old' and the corresponding replacement values in a column 'new'.} -\item{condenseRepeatedDomains}{Boolean. If TRUE, repeated domains in 'DomArch' are condensed. Default is TRUE.} +\item{condenseRepeatedDomains}{Boolean. If TRUE, repeated domains in +'DomArch' are condensed. Default is TRUE.} -\item{removeTails}{Boolean. If TRUE, 'ClustName' will be filtered based on domains to keep/remove. Default is FALSE.} +\item{removeTails}{Boolean. If TRUE, 'ClustName' will be filtered based on +domains to keep/remove. Default is FALSE.} -\item{removeEmptyRows}{Boolean. If TRUE, rows with empty/unnecessary values in 'DomArch' are removed. Default is FALSE.} +\item{removeEmptyRows}{Boolean. If TRUE, rows with empty/unnecessary values +in 'DomArch' are removed. Default is FALSE.} -\item{domains_ignore}{A data frame containing the domain names to be removed in a column called 'domains'} +\item{domains_ignore}{A data frame containing the domain names to be removed +in a column called 'domains'} } \value{ -The original data frame is returned with the clean DomArchs column and the old domains in the DomArchs.old column. +The original data frame is returned with the clean DomArchs column +and the old domains in the DomArchs.old column. } \description{ Cleanup Domain Architectures @@ -46,6 +58,7 @@ The original data frame is returned with the clean DomArchs column and the old d } \examples{ \dontrun{ -cleanDomainArchitecture(prot, TRUE, FALSE, domains_keep, domains_rename, domains_ignore = NULL) +cleanDomainArchitecture(prot, TRUE, FALSE, +omains_keep, domains_rename, domains_ignore = NULL) } } diff --git a/man/cleanFAHeaders.Rd b/man/cleanFAHeaders.Rd index e9ad9b30..e93d0ca3 100644 --- a/man/cleanFAHeaders.Rd +++ b/man/cleanFAHeaders.Rd @@ -7,7 +7,9 @@ cleanFAHeaders(fasta) } \arguments{ -\item{fasta}{} +\item{fasta}{An \link{XStringSet} object representing the sequences from a +FASTA file. The sequence names (headers) will be adjusted for uniqueness +and sanitized.} } \value{ \link{XStringSet} fasta with adjusted names (headers) diff --git a/man/cleanGeneDescription.Rd b/man/cleanGeneDescription.Rd index f98a25d4..3d106ae6 100644 --- a/man/cleanGeneDescription.Rd +++ b/man/cleanGeneDescription.Rd @@ -7,7 +7,10 @@ cleanGeneDescription(prot, column) } \arguments{ -\item{column}{} +\item{prot}{A data frame containing the gene descriptions.} + +\item{column}{The name of the column from which gene descriptions are pulled +for cleanup.} } \value{ Return trailing period that occurs in GeneDesc column diff --git a/man/cleanLineage.Rd b/man/cleanLineage.Rd index adcea312..071b37d2 100644 --- a/man/cleanLineage.Rd +++ b/man/cleanLineage.Rd @@ -7,10 +7,15 @@ cleanLineage(prot, lins_rename) } \arguments{ -\item{lins_rename}{} +\item{prot}{A data frame containing a 'Lineage' column that needs to be +cleaned up.} + +\item{lins_rename}{A data frame with two columns: 'old' containing terms +to be replaced and 'new' containing the corresponding replacement terms.} } \value{ -Describe return, in detail +The original data frame with the 'Lineage' column updated based on +the provided replacements. } \description{ Cleanup Lineage diff --git a/man/cleanSpecies.Rd b/man/cleanSpecies.Rd index 82b5444c..93fc2e05 100644 --- a/man/cleanSpecies.Rd +++ b/man/cleanSpecies.Rd @@ -13,7 +13,7 @@ cleanSpecies(prot, removeEmptyRows = FALSE) Default is false.} } \value{ -Describe return, in detail +The original data frame with Species cleaned. } \description{ Cleanup Species diff --git a/man/combine_files.Rd b/man/combine_files.Rd index 4126eb9e..432513d6 100644 --- a/man/combine_files.Rd +++ b/man/combine_files.Rd @@ -13,16 +13,34 @@ combine_files( ) } \arguments{ -\item{inpath}{String of 'master' path where the files reside (recursive=T)} +\item{inpath}{Character. The master directory path where the files reside. +The search is recursive (i.e., it will look in subdirectories as well).} -\item{pattern}{Character vector containing search pattern for files} +\item{pattern}{Character. A search pattern to identify files to be combined. +Default is "*full_analysis.tsv".} -\item{col_names}{Takes logical T/F arguments OR column names vector; -usage similar to col_names parameter in \code{readr::read_delim}} +\item{delim}{Character. The delimiter used in the input files. +Default is tab ("\t").} + +\item{skip}{Integer. The number of lines to skip at the beginning of each file. +Default is 0.} + +\item{col_names}{Logical or character vector. If TRUE, the first row of each file +is treated as column names. Alternatively, a character vector can +be provided to specify custom column names.} +} +\value{ +A data frame containing the combined contents of all matched files. +Each row will include a new column "ByFile" indicating the source file of the data. } \description{ Download the combined assembly summaries of genbank and refseq } +\examples{ +\dontrun{ +combined_data <- combine_files(inpath = "../molevol_data/project_data/phage_defense/") +} +} \author{ Janani Ravi } diff --git a/man/combine_full.Rd b/man/combine_full.Rd index f4e6597b..563a5450 100644 --- a/man/combine_full.Rd +++ b/man/combine_full.Rd @@ -7,8 +7,22 @@ combine_full(inpath, ret = FALSE) } \arguments{ -\item{ret}{} +\item{inpath}{Character. The path to the directory containing the +\code{.full_analysis.tsv} files to be combined.} + +\item{ret}{Logical. If TRUE, the function will return the combined data frame. +Default is FALSE, meaning it will only write the file and not return the data.} +} +\value{ +If \code{ret} is TRUE, a data frame containing the combined data from all +input files. If \code{ret} is FALSE, the function writes the combined data to a +TSV file named \code{cln_combined.tsv} in the specified directory and returns NULL. } \description{ Combining full_analysis files } +\examples{ +\dontrun{ +combined_data <- combine_full("path/to/full_analysis/files", ret = TRUE) +} +} diff --git a/man/combine_ipr.Rd b/man/combine_ipr.Rd index 52aa3057..ddb3e6af 100644 --- a/man/combine_ipr.Rd +++ b/man/combine_ipr.Rd @@ -7,8 +7,22 @@ combine_ipr(inpath, ret = FALSE) } \arguments{ -\item{ret}{} +\item{inpath}{Character. The path to the directory containing the +\code{.iprscan_cln.tsv} files to be combined.} + +\item{ret}{Logical. If TRUE, the function will return the combined data frame. +Default is FALSE, meaning it will only write the file and not return the data.} +} +\value{ +If \code{ret} is TRUE, a data frame containing the combined data from all +input files. If \code{ret} is FALSE, the function writes the combined data to a +TSV file named \code{ipr_combined.tsv} in the specified directory and returns NULL. } \description{ Combining clean ipr files } +\examples{ +\dontrun{ +combined_ipr_data <- combine_ipr("path/to/ipr/files", ret = TRUE) +} +} diff --git a/man/condenseRepeatedDomains.Rd b/man/condenseRepeatedDomains.Rd index 3b239129..ee51a544 100644 --- a/man/condenseRepeatedDomains.Rd +++ b/man/condenseRepeatedDomains.Rd @@ -14,7 +14,7 @@ condenseRepeatedDomains(prot, by_column = "DomArch", excluded_prots = c()) \item{excluded_prots}{Vector of strings that condenseRepeatedDomains should not reduce to (s). Defaults to c()} } \value{ -Describe return, in detail +A data frame with condensed repeated domains in the specified column. } \description{ Condense repeated domains diff --git a/man/convert2TitleCase.Rd b/man/convert2TitleCase.Rd index 84e7fa00..cd8634ef 100644 --- a/man/convert2TitleCase.Rd +++ b/man/convert2TitleCase.Rd @@ -13,8 +13,16 @@ convert2TitleCase(text, delimitter) \item{y}{Delimitter. Default is space (" ").} } +\value{ +Character vector with the input strings converted to title case. +} \description{ Translate string to Title Case w/ delimitter. +} +\examples{ +# Convert a single string to title case +convert2TitleCase("hello world") # Returns "Hello World" + } \seealso{ chartr, toupper, and tolower. diff --git a/man/convertAlignment2FA.Rd b/man/convertAlignment2FA.Rd index d6b4dc56..027267ad 100644 --- a/man/convertAlignment2FA.Rd +++ b/man/convertAlignment2FA.Rd @@ -26,6 +26,11 @@ Default is 'NULL'} \item{reduced}{Boolean. If TRUE, the fasta file will contain only one sequence per lineage. Default is 'FALSE'} } +\value{ +A character string representing the FASTA formatted sequences. +If \code{fa_outpath} is provided, the FASTA will also be saved to the specified +file. +} \description{ Adding Leaves to an alignment file w/ accessions Genomic Contexts vs Domain Architectures. diff --git a/man/convert_aln2fa.Rd b/man/convert_aln2fa.Rd index 8bebe31d..8ca9a3a0 100644 --- a/man/convert_aln2fa.Rd +++ b/man/convert_aln2fa.Rd @@ -23,8 +23,13 @@ Default is 'pspa.txt'} \item{fa_outpath}{Character. Path to the written fasta file. Default is 'NULL'} -\item{reduced}{Boolean. If TRUE, the fasta file will contain only one sequence per lineage. -Default is 'FALSE'} +\item{reduced}{Boolean. If TRUE, the fasta file will contain only one +sequence per lineage. Default is 'FALSE'} +} +\value{ +Character string containing the Fasta formatted sequences. +If \code{fa_outpath} is specified, the function also writes the sequences to the +Fasta file. } \description{ Adding Leaves to an alignment file w/ accessions diff --git a/man/countbycolumn.Rd b/man/countByColumn.Rd similarity index 100% rename from man/countbycolumn.Rd rename to man/countByColumn.Rd diff --git a/man/createWordCloud2Element.Rd b/man/createWordCloud2Element.Rd index a6279e2f..b1fd827f 100644 --- a/man/createWordCloud2Element.Rd +++ b/man/createWordCloud2Element.Rd @@ -15,7 +15,18 @@ createWordCloud2Element( \item{query_data}{Data frame of protein homologs with the usual 11 columns + additional word columns (0/1 format). Default is "prot".} -\item{UsingRowsCutoff}{} +\item{colname}{Character. The name of the column in \code{query_data} to generate +the word cloud from. Default is "DomArch".} + +\item{cutoff}{Numeric. The cutoff value for filtering elements based on their +frequency. Default is 70.} + +\item{UsingRowsCutoff}{Logical. Whether to use a row-based cutoff instead of +a frequency cutoff. Default is FALSE.} +} +\value{ +A word cloud plot showing the frequency of elements from the selected +column. } \description{ Wordclouds for the predominant domains (from DAs) and DAs (from GC) diff --git a/man/createWordCloudElement.Rd b/man/createWordCloudElement.Rd index 7f27ef41..42b32da0 100644 --- a/man/createWordCloudElement.Rd +++ b/man/createWordCloudElement.Rd @@ -15,7 +15,18 @@ createWordCloudElement( \item{query_data}{Data frame of protein homologs with the usual 11 columns + additional word columns (0/1 format). Default is "prot".} -\item{UsingRowsCutoff}{} +\item{colname}{Character. The name of the column in \code{query_data} to generate +the word cloud from. Default is "DomArch".} + +\item{cutoff}{Numeric. The cutoff value for filtering elements based on their +frequency. Default is 70.} + +\item{UsingRowsCutoff}{Logical. Whether to use a row-based cutoff instead of +a frequency cutoff. Default is FALSE.} +} +\value{ +A word cloud plot showing the frequency of elements from the selected +column. } \description{ Wordclouds for the predominant domains (from DAs) and DAs (from GC) diff --git a/man/create_lineage_lookup.Rd b/man/create_lineage_lookup.Rd index 51670f35..869db71a 100644 --- a/man/create_lineage_lookup.Rd +++ b/man/create_lineage_lookup.Rd @@ -11,20 +11,31 @@ create_lineage_lookup( ) } \arguments{ -\item{lineage_file}{Path to the rankedlineage.dmp file containing taxid's and their -corresponding taxonomic rank. rankedlineage.dmp can be downloaded at +\item{lineage_file}{Path to the rankedlineage.dmp file containing taxid's +and their corresponding taxonomic rank. rankedlineage.dmp can be downloaded at https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/new_taxdump/} \item{outfile}{File the resulting lineage lookup table should be written to} -\item{taxonomic_rank}{The upperbound of taxonomic rank that the lineage includes. The lineaege will -include superkingdom>...>taxonomic_rank. +\item{taxonomic_rank}{The upperbound of taxonomic rank that the lineage +includes. The lineaege will include superkingdom>...>taxonomic_rank. Choices include: "supperkingdom", "phylum", "class","order", "family", "genus", and "species"} } +\value{ +A tibble containing the tax IDs and their respective lineages up to +the specified taxonomic rank, saved as a tab-separated file. +} \description{ Create a look up table that goes from TaxID, to Lineage } +\examples{ +\dontrun{ +create_lineage_lookup(lineage_file = "data/rankedlineage.dmp", + outfile = "data/lineage_lookup.tsv", + taxonomic_rank = "family") +} +} \author{ Samuel Chen } diff --git a/man/domain_network.Rd b/man/domain_network.Rd index 528e4924..0580b4d2 100644 --- a/man/domain_network.Rd +++ b/man/domain_network.Rd @@ -16,15 +16,24 @@ domain_network( \arguments{ \item{prot}{A data frame that contains the column 'DomArch'.} -\item{column}{Name of column containing Domain architecture from which nodes and edges are generated.} +\item{column}{Name of column containing Domain architecture from which nodes +and edges are generated.} -\item{cutoff}{Integer. Only use domains that occur at or above the cutoff for total counts if cutoff_type is "Total Count". -Only use domains that appear in cutoff or greater lineages if cutoff_type is Lineage.} +\item{domains_of_interest}{Character vector specifying domains of interest.} + +\item{cutoff}{Integer. Only use domains that occur at or above the cutoff for +total counts if cutoff_type is "Total Count". +Only use domains that appear in cutoff or greater lineages if cutoff_type is +Lineage.} \item{layout}{Character. Layout type to be used for the network. Options are: \itemize{\item "grid" \item "circle" \item "random" \item "auto"}} -\item{query_color}{} +\item{query_color}{Character. Color to represent the queried domain in the +network.} +} +\value{ +A network visualization of domain architectures. } \description{ This function creates a domain network from the 'DomArch' column. diff --git a/man/downloadAssemblySummary.Rd b/man/downloadAssemblySummary.Rd index 636af878..bad2b603 100644 --- a/man/downloadAssemblySummary.Rd +++ b/man/downloadAssemblySummary.Rd @@ -10,13 +10,25 @@ downloadAssemblySummary( ) } \arguments{ -\item{outpath}{String of path where the assembly summary file should be written} +\item{outpath}{String of path where the assembly summary file should be +written} -\item{keep}{Character vector containing which columns should be retained and downloaded} +\item{keep}{Character vector containing which columns should be retained and +downloaded} +} +\value{ +A tab-separated file containing the assembly summary. The function +does notreturn any value but writes the output directly to the specified file. } \description{ Download the combined assembly summaries of genbank and refseq } +\examples{ +\dontrun{ +downloadAssemblySummary(outpath = "assembly_summary.tsv", + keep = c("assembly_accession", "taxid", "organism_name")) +} +} \author{ Samuel Chen, Janani Ravi } diff --git a/man/efetchIPG.Rd b/man/efetchIPG.Rd index 047e2652..e55c342a 100644 --- a/man/efetchIPG.Rd +++ b/man/efetchIPG.Rd @@ -14,13 +14,17 @@ the ipg database} \item{out_path}{Path to write the efetch results to} -\item{plan}{} +\item{plan}{Character. Specifies the execution plan for parallel processing. +Default is "multicore".} \item{accnums}{Character vector containing the accession numbers to query on the ipg database} } \value{ No return value. The function writes the fetched results to \code{out_path}. + +The function does not return a value but writes the efetch results +directly to the specified \code{out_path}. } \description{ Perform efetch on the ipg database and write the results to out_path @@ -31,6 +35,12 @@ Perform efetch on the ipg database and write the results to out_path \dontrun{ efetchIPG() } +\dontrun{ +efetchIPG( + accessions = c("P12345", "Q67890", "A12345"), + out_path = "path/to/efetch_results.xml" +) +} } \author{ Samuel Chen, Janani Ravi diff --git a/man/extractAccNum.Rd b/man/extractAccNum.Rd index 15870f3f..caf9e5db 100644 --- a/man/extractAccNum.Rd +++ b/man/extractAccNum.Rd @@ -7,7 +7,8 @@ extractAccNum(string) } \arguments{ -\item{string}{} +\item{string}{A string from which to extract the accession number. +The string may contain accession information delimited by \code{|} or spaces.} } \value{ Describe return, in detail diff --git a/man/filterbydomains.Rd b/man/filterByDomains.Rd similarity index 100% rename from man/filterbydomains.Rd rename to man/filterByDomains.Rd diff --git a/man/filterbyfrequency.Rd b/man/filterByFrequency.Rd similarity index 100% rename from man/filterbyfrequency.Rd rename to man/filterByFrequency.Rd diff --git a/man/findparalogs.Rd b/man/findParalogs.Rd similarity index 100% rename from man/findparalogs.Rd rename to man/findParalogs.Rd diff --git a/man/find_top_acc.Rd b/man/find_top_acc.Rd index 780cde11..ffce1640 100644 --- a/man/find_top_acc.Rd +++ b/man/find_top_acc.Rd @@ -13,8 +13,32 @@ find_top_acc( ) } \arguments{ -\item{query}{} +\item{infile_full}{A data frame containing the full dataset with lineage and +domain architecture information.} + +\item{DA_col}{A string representing the name of the domain architecture +column. Default is "DomArch.Pfam".} + +\item{lin_col}{A string representing the name of the lineage column. +Default is "Lineage_short".} + +\item{n}{An integer specifying the number of top accession numbers to return. +Default is 20.} + +\item{query}{A string for filtering a specific query name. If it is not +"All", only the data matching this query will be processed.} +} +\value{ +A vector of the top N accession numbers (\code{AccNum}) based on counts +grouped by lineage and domain architecture. } \description{ Group by lineage + DA then take top 20 } +\examples{ +\dontrun{ +top_accessions <- find_top_acc(infile_full = my_data, +DA_col = "DomArch.Pfam", lin_col = "Lineage_short", +n = 20, query = "specific_query_name") +} +} diff --git a/man/gc_undirected_network.Rd b/man/gc_undirected_network.Rd index 28cf1abb..5dab8a70 100644 --- a/man/gc_undirected_network.Rd +++ b/man/gc_undirected_network.Rd @@ -16,18 +16,29 @@ gc_undirected_network( \arguments{ \item{prot}{A data frame that contains the column 'DomArch'.} -\item{column}{Name of column containing Domain architecture from which nodes and edges are generated.} +\item{column}{Name of column containing Domain architecture from which nodes +and edges are generated.} -\item{cutoff_type}{Character. Used to determine how data should be filtered. Either -\itemize{\item "Lineage" to filter domains based off how many lineages the Domain architecture appears in -\item "Total Count" to filter off the total amount of times a domain architecture occurs }} +\item{domains_of_interest}{Character vector specifying the domains of interest.} -\item{cutoff}{Integer. Only use domains that occur at or above the cutoff for total counts if cutoff_type is "Total Count". -Only use domains that appear in cutoff or greater lineages if cutoff_type is Lineage.} +\item{cutoff_type}{Character. Used to determine how data should be filtered. +Either +\itemize{\item "Lineage" to filter domains based off how many lineages the +Domain architecture appears in +\item "Total Count" to filter off the total amount of times a +domain architecture occurs }} + +\item{cutoff}{Integer. Only use domains that occur at or above the cutoff +for total counts if cutoff_type is "Total Count". +Only use domains that appear in cutoff or greater lineages if cutoff_type is +Lineage.} \item{layout}{Character. Layout type to be used for the network. Options are: \itemize{\item "grid" \item "circle" \item "random" \item "auto"}} } +\value{ +A plot of the domain architecture network. +} \description{ This function creates a domain network from the 'DomArch' column. @@ -35,6 +46,8 @@ A network of domains is returned based on shared domain architectures. } \examples{ \dontrun{ -domain_network(pspa) +domain_network(pspa, column = "DomArch", +domains_of_interest = c("Domain1", "Domain2"), +cutoff_type = "Total Count", cutoff = 10) } } diff --git a/man/generateAllAlignments2FA.Rd b/man/generateAllAlignments2FA.Rd index 3bf9938a..1100f241 100644 --- a/man/generateAllAlignments2FA.Rd +++ b/man/generateAllAlignments2FA.Rd @@ -15,23 +15,34 @@ generateAllAlignments2FA( \item{aln_path}{Character. Path to alignment files. Default is 'here("data/rawdata_aln/")'} -\item{fa_outpath}{Character. Path to file. Master protein file with AccNum & lineages. +\item{fa_outpath}{Character. Path to file. Master protein file with AccNum & +lineages. Default is 'here("data/rawdata_tsv/all_semiclean.txt")'} \item{lin_file}{Character. Path to the written fasta file. Default is 'here("data/alns/")'.} -\item{reduced}{Boolean. If TRUE, the fasta file will contain only one sequence per lineage. +\item{reduced}{Boolean. If TRUE, the fasta file will contain only one +sequence per lineage. Default is 'FALSE'.} } +\value{ +NULL. The function saves the output FASTA files to the specified +directory. +} \description{ Adding Leaves to all alignment files w/ accessions & DAs? } \details{ -The alignment files would need two columns separated by spaces: 1. AccNum and 2. alignment. The protein homolog file should have AccNum, Species, Lineages. +The alignment files would need two columns separated by spaces: +\enumerate{ +\item AccNum and 2. alignment. The protein homolog file should have AccNum, +Species, Lineages. +} } \note{ -Please refer to the source code if you have alternate + file formats and/or column names. +Please refer to the source code if you have alternate + file formats +and/or column names. } \examples{ \dontrun{ diff --git a/man/generate_all_aln2fa.Rd b/man/generate_all_aln2fa.Rd index ad6b7136..0a9b7e0f 100644 --- a/man/generate_all_aln2fa.Rd +++ b/man/generate_all_aln2fa.Rd @@ -18,20 +18,26 @@ Default is 'here("data/rawdata_aln/")'} \item{fa_outpath}{Character. Path to the written fasta file. Default is 'here("data/alns/")'.} -\item{lin_file}{Character. Path to file. Master protein file with AccNum & lineages. -Default is 'here("data/rawdata_tsv/all_semiclean.txt")'} +\item{lin_file}{Character. Path to file. Master protein file with AccNum & +lineages. Default is 'here("data/rawdata_tsv/all_semiclean.txt")'} -\item{reduced}{Boolean. If TRUE, the fasta file will contain only one sequence per lineage. -Default is 'FALSE'.} +\item{reduced}{Boolean. If TRUE, the fasta file will contain only one +sequence per lineage. Default is 'FALSE'.} +} +\value{ +A list of paths to the generated Fasta files. } \description{ Adding Leaves to all alignment files w/ accessions & DAs? } \details{ -The alignment files would need two columns separated by spaces: 1. AccNum and 2. alignment. The protein homolog file should have AccNum, Species, Lineages. +The alignment files would need two columns separated by spaces: 1. +AccNum and 2. alignment. The protein homolog file should have AccNum, +Species, Lineages. } \note{ -Please refer to the source code if you have alternate + file formats and/or column names. +Please refer to the source code if you have alternate + file +formats and/or column names. } \examples{ \dontrun{ diff --git a/man/generate_msa.Rd b/man/generate_msa.Rd index a68eb8b4..90f2ca91 100644 --- a/man/generate_msa.Rd +++ b/man/generate_msa.Rd @@ -7,8 +7,21 @@ generate_msa(fa_file = "", outfile = "") } \arguments{ -\item{outfile}{} +\item{fa_file}{Character. The path to the input FASTA file containing protein +sequences.} + +\item{outfile}{Character. The path to the output file where the alignment +will be saved.} +} +\value{ +A list containing the alignment object and the output file path. } \description{ Function to generate MSA using kalign } +\examples{ +\dontrun{ +generate_msa(fa_file = "path/to/sequences.fasta", +outfile = "path/to/alignment.txt") +} +} diff --git a/man/get_accnums_from_fasta_file.Rd b/man/get_accnums_from_fasta_file.Rd index 84c163cc..3a3c1784 100644 --- a/man/get_accnums_from_fasta_file.Rd +++ b/man/get_accnums_from_fasta_file.Rd @@ -9,10 +9,27 @@ get_accnums_from_fasta_file(fasta_file) get_accnums_from_fasta_file(fasta_file) } \arguments{ -\item{fasta_file}{} +\item{fasta_file}{Character. Path to the FASTA file from which +accession numbers will be extracted.} +} +\value{ +A character vector containing the extracted accession numbers. + +A character vector containing the extracted accession numbers. } \description{ Get accnums from fasta file get_accnums_from_fasta_file } +\examples{ +\dontrun{ +accnums <- get_accnums_from_fasta_file("my_sequences.fasta") +print(accnums) +} +\dontrun{ +# Example usage +accnums <- get_accnums_from_fasta_file("path/to/sequences.fasta") +print(accnums) +} +} diff --git a/man/ipr2viz.Rd b/man/ipr2viz.Rd index 79063497..728c188c 100644 --- a/man/ipr2viz.Rd +++ b/man/ipr2viz.Rd @@ -17,8 +17,51 @@ ipr2viz( ) } \arguments{ -\item{query}{} +\item{infile_ipr}{A path to the input IPR file (TSV format) containing +domain information.} + +\item{infile_full}{A path to the full input file (TSV format) containing +lineage and accession information.} + +\item{accessions}{A character vector of accession numbers to filter the +analysis. Default is an empty vector.} + +\item{analysis}{A character vector specifying the types of analysis to +include (e.g., "Pfam", "Phobius", "TMHMM", "Gene3D"). Default is a +vector of these analyses.} + +\item{group_by}{A string specifying how to group the visualization. +Default is "Analysis". Options include "Analysis" or "Query".} + +\item{topn}{An integer specifying the number of top accessions to visualize. +Default is 20.} + +\item{name}{A string representing the name to use for y-axis labels. +Default is "Name".} + +\item{text_size}{An integer specifying the text size for the plot. +Default is 15.} + +\item{query}{A string for filtering a specific query name. If it is not +"All", only the data matching this query will be processed.} +} +\value{ +A ggplot object representing the domain architecture visualization. } \description{ IPR2Viz } +\examples{ +\dontrun{ +plot <- ipr2viz(infile_ipr = "path/to/ipr_file.tsv", + infile_full = "path/to/full_file.tsv", + accessions = c("ACC123", "ACC456"), + analysis = c("Pfam", "TMHMM"), + group_by = "Analysis", + topn = 20, + name = "Gene Name", + text_size = 15, + query = "All") +print(plot) +} +} diff --git a/man/ipr2viz_web.Rd b/man/ipr2viz_web.Rd index 896445bd..defa5b2d 100644 --- a/man/ipr2viz_web.Rd +++ b/man/ipr2viz_web.Rd @@ -17,8 +17,52 @@ ipr2viz_web( ) } \arguments{ -\item{rows}{} +\item{infile_ipr}{A path to the input IPR file (TSV format) containing +domain information.} + +\item{accessions}{A character vector of accession numbers to filter the +analysis.} + +\item{analysis}{A character vector specifying the types of analysis to +include (e.g., "Pfam", "Phobius", "TMHMM", "Gene3D"). Default is a vector +of these analyses.} + +\item{group_by}{A string specifying how to group the visualization. +Default is "Analysis". Options include "Analysis" or "Query".} + +\item{name}{A string representing the name to use for y-axis labels. +Default is "Name".} + +\item{text_size}{An integer specifying the text size for the plot. +Default is 15.} + +\item{legend_name}{A string representing the column to use for legend labels. +Default is "ShortName".} + +\item{cols}{An integer specifying the number of columns in the facet wrap. +Default is 5.} + +\item{rows}{An integer specifying the number of rows in the legend. +Default is 10.} +} +\value{ +A ggplot object representing the domain architecture visualization +for web display. } \description{ IPR2Viz Web } +\examples{ +\dontrun{ +plot <- ipr2viz_web(infile_ipr = "path/to/ipr_file.tsv", + accessions = c("ACC123", "ACC456"), + analysis = c("Pfam", "TMHMM"), + group_by = "Analysis", + name = "Gene Name", + text_size = 15, + legend_name = "ShortName", + cols = 5, + rows = 10) +print(plot) +} +} diff --git a/man/mapAcc2Name.Rd b/man/mapAcc2Name.Rd index 0f5d447d..a59c8760 100644 --- a/man/mapAcc2Name.Rd +++ b/man/mapAcc2Name.Rd @@ -9,13 +9,24 @@ mapAcc2Name(line, acc2name, acc_col = "AccNum", name_col = "Name") \arguments{ \item{line}{The line of a fasta file starting with '>'} -\item{acc2name}{Data Table containing a column of accession numbers and a name column} +\item{acc2name}{Data Table containing a column of accession numbers and a +name column} \item{acc_col}{Name of the column containing Accession numbers} -\item{name_col}{Name of the column containing the names that the accession numbers +\item{name_col}{Name of the column containing the names that the accession +numbers are mapped to} } +\value{ +A character string representing the updated FASTA line, where the +accession number is replaced with its corresponding name. +} \description{ Default renameFA() replacement function. Maps an accession number to its name } +\examples{ +\dontrun{ +mapAcc2Name(">P12345 some description", acc2name, "AccNum", "Name") +} +} diff --git a/man/map_acc2name.Rd b/man/map_acc2name.Rd index fcdb3023..88377eea 100644 --- a/man/map_acc2name.Rd +++ b/man/map_acc2name.Rd @@ -7,7 +7,7 @@ map_acc2name(line, acc2name, acc_col = "AccNum", name_col = "Name") } \arguments{ -\item{line}{he line of a fasta file starting with '>'} +\item{line}{The line of a fasta file starting with '>'} \item{acc2name}{Data Table containing a column of accession numbers and a name column} @@ -16,6 +16,19 @@ map_acc2name(line, acc2name, acc_col = "AccNum", name_col = "Name") \item{name_col}{Name of the column containing the names that the accession numbers are mapped to} } +\value{ +Character string. The modified line from the Fasta file header with +the name instead of the accession number. +} \description{ Default rename_fasta() replacement function. Maps an accession number to its name } +\examples{ +\dontrun{ +acc2name_table <- data.table(AccNum = c("ACC001", "ACC002"), +Name = c("Species A", "Species B")) +line <- ">ACC001 some additional info" +mapped_line <- map_acc2name(line, acc2name_table) +print(mapped_line) # Expected output: ">Species A" +} +} diff --git a/man/msa_pdf.Rd b/man/msa_pdf.Rd index 4d5fed17..0f42eb9f 100644 --- a/man/msa_pdf.Rd +++ b/man/msa_pdf.Rd @@ -18,6 +18,9 @@ Default is NULL. If value is NULL, the entire multiple sequence alignment is pri \item{upperbound}{Numeric. The column that determines the ending location of the MSA. Default is NULL. If value is NULL, the entire multiple sequence alignment is printed.} } +\value{ +A PDF file containing the multiple sequence alignment. +} \description{ Generates a multiple sequence alignment from a fasta file @@ -26,6 +29,9 @@ a pdf } \examples{ \dontrun{ -msa_pdf() +msa_pdf(fasta_path = "path/to/your/file.fasta", + out_path = "path/to/output/alignment.pdf", + lowerbound = 10, + upperbound = 200) } } diff --git a/man/plotLineageDA.Rd b/man/plotLineageDA.Rd index 7e84bcfd..a752eb9b 100644 --- a/man/plotLineageDA.Rd +++ b/man/plotLineageDA.Rd @@ -20,9 +20,17 @@ Default is prot (variable w/ protein data).} \item{colname}{Column name from query_data: "DomArch.norep", "GenContext.norep", "DomArch.PFAM.norep" or "DomArch.LADB.norep". Default is "DomArch.norep".} +\item{cutoff}{Numeric. Cutoff for word frequency. Default is 90.} + +\item{RowsCutoff}{Boolean. If TRUE, applies a row cutoff to remove data rows +based on a certain condition. Default is FALSE.} + \item{color}{Color for the heatmap. One of six options: "default", "magma", "inferno", "plasma", "viridis", or "cividis"} } +\value{ +A LineageDA plot object. +} \description{ Lineage plot for Domains, Domain Architectures and Genomic Contexts. Heatmap. diff --git a/man/plotLineageDomainRepeats.Rd b/man/plotLineageDomainRepeats.Rd index 8ccfba41..45d31d68 100644 --- a/man/plotLineageDomainRepeats.Rd +++ b/man/plotLineageDomainRepeats.Rd @@ -7,7 +7,16 @@ plotLineageDomainRepeats(query_data, colname) } \arguments{ -\item{colname}{} +\item{query_data}{Data frame containing protein homolog data, including +relevant domain architectures and lineages.} + +\item{colname}{Character. The name of the column in query_data that contains +domain architectures or other structural information.} +} +\value{ +A ggplot object representing a heatmap (tile plot) of domain repeat +counts across different lineages, with color intensity representing the +occurrence of domains. } \description{ Lineage Domain Repeats Plot diff --git a/man/plotLineageHeatmap.Rd b/man/plotLineageHeatmap.Rd index 5449f8ec..e6870edb 100644 --- a/man/plotLineageHeatmap.Rd +++ b/man/plotLineageHeatmap.Rd @@ -15,6 +15,11 @@ plotLineageHeatmap(prot, domains_of_interest, level = 3, label.size = 8) \item{label.size}{Size of the text labels} } +\value{ +A ggplot object representing a heatmap (tile plot) of domain repeat +counts across different lineages, with color intensity representing the +occurrence of domains. +} \description{ Generate a lineage plot } diff --git a/man/plotLineageNeighbors.Rd b/man/plotLineageNeighbors.Rd index 85adf175..2c7ca448 100644 --- a/man/plotLineageNeighbors.Rd +++ b/man/plotLineageNeighbors.Rd @@ -18,6 +18,11 @@ additional word columns (0/1 format). Default is pspa_data.} \item{colname}{Column name from query_data. Default is "GenContext.norep".} } +\value{ +A ggplot object representing a heatmap (tile plot) of lineage versus +the top neighboring domain architectures, with color intensity representing +the frequency of occurrences. +} \description{ Lineage plot for top neighbors obtained from DAs of Genomic Contexts. diff --git a/man/plotLineageQuery.Rd b/man/plotLineageQuery.Rd index ad52a4d2..aa3793b7 100644 --- a/man/plotLineageQuery.Rd +++ b/man/plotLineageQuery.Rd @@ -17,9 +17,22 @@ plotLineageQuery( additional word columns (0/1 format). Default is prot (variable w/ protein data).} -\item{queries}{Character Vector containing the queries that will be used for the categories} +\item{queries}{Character Vector containing the queries that will be used for +the categories.} -\item{color}{} +\item{colname}{Character. The column used for filtering based on the \code{queries}. +Default is "ClustName".} + +\item{cutoff}{Numeric. The cutoff value for filtering rows based on their +total count. Rows with values below this cutoff are excluded.} + +\item{color}{Character. Defines the color palette used for the heatmap. +Default is a red gradient.} +} +\value{ +A ggplot object representing a heatmap (tile plot) showing the +relationship between queries and lineages, with the intensity of color +representing the count of matching records. } \description{ Lineage plot for queries. Heatmap. @@ -33,6 +46,9 @@ column names. plotLineageQuery(prot, c("PspA", "PspB", "PspC", "PspM", "PspN"), 95) } } +\author{ +Janani Ravi, Samuel Chen +} \keyword{Architectures,} \keyword{Domain} \keyword{Domains,} diff --git a/man/plotLineageSunburst.Rd b/man/plotLineageSunburst.Rd index 972bbe5d..3240d77d 100644 --- a/man/plotLineageSunburst.Rd +++ b/man/plotLineageSunburst.Rd @@ -16,27 +16,40 @@ plotLineageSunburst( ) } \arguments{ -\item{prot}{Data frame containing a lineage column that the sunburst plot will be generated for} +\item{prot}{Data frame containing a lineage column that the sunburst plot +will be generated for} -\item{lineage_column}{String. Name of the lineage column within the data frame. Defaults to "Lineage"} +\item{lineage_column}{String. Name of the lineage column within the +data frame. Defaults to "Lineage"} -\item{type}{String, either "sunburst" or "sund2b". If type is "sunburst", a sunburst plot of the lineage} +\item{type}{String, either "sunburst" or "sund2b". If type is "sunburst", +a sunburst plot of the lineage} \item{levels}{Integer. Number of levels the sunburst will have.} -\item{legendOrder}{String vector. The order of the legend. If legendOrder is NULL,} +\item{colors}{A vector of colors for the sunburst plot. +If NULL, default colors are used.} -\item{showLegend}{Boolean. If TRUE, the legend will be enabled when the component first renders.} +\item{legendOrder}{String vector. The order of the legend. If legendOrder +is NULL,} -\item{maxLevels}{Integer, the maximum number of levels to display in the sunburst; 5 by default, NULL to disable -then the legend will be in the descending order of the top level hierarchy. -will be rendered. If the type is sund2b, a sund2b plot will be rendered.} +\item{showLegend}{Boolean. If TRUE, the legend will be enabled when the +component first renders.} + +\item{maxLevels}{Integer, the maximum number of levels to display in the +sunburst; 5 by default, NULL to disable then the legend will be in the +descending order of the top level hierarchy. will be rendered. If the type is +sund2b, a sund2b plot will be rendered.} +} +\value{ +A sunburst or sund2b plot based on the input lineage data. } \description{ Lineage Sunburst } \examples{ \dontrun{ -plotLineageSunburst() +plotLineageSunburst(prot, lineage_column = "Lineage", +type = "sunburst", levels = 3) } } diff --git a/man/plotStackedLineage.Rd b/man/plotStackedLineage.Rd index 9d1cde6d..63ae9b66 100644 --- a/man/plotStackedLineage.Rd +++ b/man/plotStackedLineage.Rd @@ -21,7 +21,44 @@ plotStackedLineage( ) } \arguments{ -\item{legend}{} +\item{prot}{Data frame containing protein data including domain architecture +and lineage information.} + +\item{column}{Character. The name of the column in prot representing domain +architectures (default is "DomArch").} + +\item{cutoff}{Numeric. A threshold value for filtering domain architectures +or protein counts.} + +\item{Lineage_col}{Character. The name of the column representing lineage +data (default is "Lineage").} + +\item{xlabel}{Character. Label for the x-axis +(default is "Domain Architecture").} + +\item{reduce_lineage}{Logical. Whether to shorten lineage names +(default is TRUE).} + +\item{label.size}{Numeric. The size of axis text labels (default is 8).} + +\item{legend.position}{Numeric vector. Coordinates for placing the legend +(default is c(0.7, 0.4)).} + +\item{legend.text.size}{Numeric. Size of the text in the legend +(default is 10).} + +\item{legend.cols}{Numeric. Number of columns in the legend (default is 2).} + +\item{legend.size}{Numeric. Size of the legend keys (default is 0.7).} + +\item{coord_flip}{Logical. Whether to flip the coordinates of the plot +(default is TRUE).} + +\item{legend}{Logical. Whether to display the legend (default is TRUE).} +} +\value{ +A ggplot object representing a stacked bar plot showing the +distribution of protein domain architectures across lineages. } \description{ Stacked Lineage Plot diff --git a/man/plotSunburst.Rd b/man/plotSunburst.Rd index 5ee465a6..37da9df5 100644 --- a/man/plotSunburst.Rd +++ b/man/plotSunburst.Rd @@ -10,11 +10,11 @@ plotSunburst(count_data, fill_by_n = FALSE, sort_by_n = FALSE, maxdepth = 2) plotTreemap(count_data, fill_by_n = FALSE, sort_by_n = FALSE) } \arguments{ -\item{count_data}{} +\item{count_data}{A data frame containing the data.} -\item{fill_by_n}{If TRUE, uses a continuous scale to fill plot by group size} +\item{fill_by_n}{Logical indicating if fill color is based on counts.} -\item{sort_by_n}{} +\item{sort_by_n}{Logical indicating if data should be sorted by counts.} } \description{ These functions help you quickly create interactive hierarchical plots diff --git a/man/plotUpSet.Rd b/man/plotUpSet.Rd index 84169987..47dd12e1 100644 --- a/man/plotUpSet.Rd +++ b/man/plotUpSet.Rd @@ -18,15 +18,30 @@ plotUpSet( \item{query_data}{Data frame of protein homologs with the usual 11 columns + additional word columns (0/1 format). Default is toast_rack.sub} +\item{colname}{Column name from query_data: "DomArch.norep", "GenContext.norep", +"DomArch.PFAM.norep" or "DomArch.LADB.norep". Default is "DomArch.norep".} + \item{cutoff}{Numeric. Cutoff for word frequency. Default is 90.} -\item{text.scale}{Allows scaling of axis title, tick lables, and numbers above the intersection size bars. +\item{RowsCutoff}{Boolean. If TRUE, applies a row cutoff to remove data rows +based on a certain condition. Default is FALSE.} + +\item{text.scale}{Allows scaling of axis title, tick lables, and numbers +above the intersection size bars. text.scale can either take a universal scale in the form of an integer, or a vector of specific scales in the format: c(intersection size title, intersection size tick labels, set size title, set size tick labels, set names, numbers above bars)} -\item{line.size}{} +\item{point.size}{Numeric. Sets the size of points in the UpSet plot. +Default is 2.2.} + +\item{line.size}{Numeric. Sets the line width in the UpSet plot. +Default is 0.8.} +} +\value{ +An UpSet plot object. The plot visualizes intersections of sets based +on the provided colname in query_data. } \description{ UpSet plot for Domain Architectures vs Domains and diff --git a/man/prepareColumnParams.Rd b/man/prepareColumnParams.Rd index bb0b9a29..8a9f566b 100644 --- a/man/prepareColumnParams.Rd +++ b/man/prepareColumnParams.Rd @@ -7,8 +7,23 @@ prepareColumnParams(count_data, fill_by_n, sort_by_n) } \arguments{ -\item{sort_by_n}{} +\item{count_data}{A data frame containing the data.} + +\item{fill_by_n}{Logical indicating if fill color is based on counts.} + +\item{sort_by_n}{Logical indicating if data should be sorted by counts.} +} +\value{ +A data frame of parameters for treemap visualization. } \description{ prepareColumnParams } +\examples{ +\dontrun{ +count_data <- data.frame(Category = c("A", "B", "C"), + n = c(10, 20, 15)) +params <- prepareColumnParams(count_data, fill_by_n = TRUE, sort_by_n = FALSE) +print(params) +} +} diff --git a/man/prepareSingleColumnParams.Rd b/man/prepareSingleColumnParams.Rd index d823852b..0070497e 100644 --- a/man/prepareSingleColumnParams.Rd +++ b/man/prepareSingleColumnParams.Rd @@ -7,8 +7,24 @@ prepareSingleColumnParams(df, col_num, root) } \arguments{ -\item{root}{} +\item{df}{A data frame containing the data to be processed.} + +\item{col_num}{An integer representing the column number to process.} + +\item{root}{A string representing the root node for the treemap.} +} +\value{ +A data frame containing parameters for the specified column for +treemap visualization. } \description{ prepareSingleColumnParams } +\examples{ +\dontrun{ +df <- data.frame(Category = c("A", "A", "B", "B", "C"), + n = c(10, 20, 30, 40, 50)) +params <- prepareSingleColumnParams(df, col_num = 1, root = "Root") +print(params) +} +} diff --git a/man/proteinAcc2TaxID.Rd b/man/proteinAcc2TaxID.Rd index c0317bba..9be09d53 100644 --- a/man/proteinAcc2TaxID.Rd +++ b/man/proteinAcc2TaxID.Rd @@ -7,8 +7,32 @@ proteinAcc2TaxID(accnums, suffix, out_path, return_dt = FALSE) } \arguments{ -\item{return_dt}{} +\item{accnums}{A character vector of protein accession numbers to be mapped +to TaxIDs.} + +\item{suffix}{A string suffix used to name the output file generated by the +script.} + +\item{out_path}{A string specifying the directory where the output file will +be saved.} + +\item{return_dt}{A logical indicating whether to return the result as a data +table. Defaults to FALSE. If TRUE, the output file is read into a data table +and returned.} +} +\value{ +If \code{return_dt} is TRUE, a data table containing the mapping of protein +accession numbers to TaxIDs. If FALSE, the function returns NULL. } \description{ proteinAcc2TaxID } +\examples{ +\dontrun{ +# Example accession numbers +accessions <- c("ABC123", "XYZ456", "LMN789") +tax_data <- proteinAcc2TaxID(accessions, suffix = "example", +out_path = "/path/to/output", return_dt = TRUE) +print(tax_data) +} +} diff --git a/man/proteinAcc2TaxID_old.Rd b/man/proteinAcc2TaxID_old.Rd index 0c2a85ba..fb6cd5a0 100644 --- a/man/proteinAcc2TaxID_old.Rd +++ b/man/proteinAcc2TaxID_old.Rd @@ -7,17 +7,29 @@ proteinAcc2TaxID_old(accessions, out_path, plan = "multicore") } \arguments{ -\item{accessions}{Character vector containing the accession numbers to query on -the ipg database} +\item{accessions}{A character vector containing the accession numbers to query +in the protein database.} -\item{out_path}{Path to write the efetch results to} +\item{out_path}{A string specifying the path where the results of the query +will be written. If set to NULL, a temporary directory will be used.} -\item{plan}{} +\item{plan}{A character string that specifies the execution plan for parallel +processing. The default is "multicore".} +} +\value{ +This function does not return a value. It writes the results to the +specified output path. } \description{ Perform elink to go from protein database to taxonomy database and write the resulting file of taxid and lineage to out_path } +\examples{ +\dontrun{ +accessions <- c("ABC123", "XYZ456", "LMN789") +proteinAcc2TaxID_old(accessions, out_path = "/path/to/output") +} +} \author{ Samuel Chen, Janani Ravi } diff --git a/man/removeAsterisks.Rd b/man/removeAsterisks.Rd index 691a7adf..c62b7651 100644 --- a/man/removeAsterisks.Rd +++ b/man/removeAsterisks.Rd @@ -2,15 +2,19 @@ % Please edit documentation in R/cleanup.R \name{removeAsterisks} \alias{removeAsterisks} -\title{Remove Astrk} +\title{Remove Asterisk} \usage{ removeAsterisks(query_data, colname = "GenContext") } \arguments{ -\item{colname}{} +\item{query_data}{A data frame containing the data to be processed.} + +\item{colname}{The name of the column from which asterisks should be removed. +Defaults to "GenContext".} } \value{ -Describe return, in detail +The original data frame with asterisks removed from the specified +column. } \description{ Remove the asterisks from a column of data diff --git a/man/removeEmptyRows.Rd b/man/removeEmptyRows.Rd index 66551810..4e52cc99 100644 --- a/man/removeEmptyRows.Rd +++ b/man/removeEmptyRows.Rd @@ -13,7 +13,8 @@ removeEmptyRows(prot, by_column = "DomArch") Default column is 'DomArch'. Can also take the following as input, 'Species', 'GenContext', 'ClustName'.} } \value{ -Describe return, in detail +A tibble with rows removed where the specified column contains +\code{"-"}, \code{"NA"}, or an empty string. } \description{ Remove empty rows by column diff --git a/man/removeTails.Rd b/man/removeTails.Rd index 76d1e18a..0c63e89d 100644 --- a/man/removeTails.Rd +++ b/man/removeTails.Rd @@ -14,7 +14,8 @@ removeTails(prot, by_column = "DomArch", keep_domains = FALSE) \item{keep_domains}{Default is False Keeps tail entries that contain the query domains.} } \value{ -Describe return, in detail +The original data frame with singletons removed from the specified +column. } \description{ Remove tails/singletons diff --git a/man/renameFA.Rd b/man/renameFA.Rd index 7b6fd579..da7d339b 100644 --- a/man/renameFA.Rd +++ b/man/renameFA.Rd @@ -15,6 +15,15 @@ renameFA(fa_path, outpath, replacement_function = mapAcc2Name, ...) \item{...}{Additional arguments to pass to replacement_function} } +\value{ +A character vector of the modified lines in the FASTA file. +} \description{ Rename the labels of fasta files } +\examples{ +\dontrun{ +renameFA("path/to/input.fasta", +"path/to/output.fasta", mapAcc2Name, acc2name) +} +} diff --git a/man/rename_fasta.Rd b/man/rename_fasta.Rd index 6b4e5dd7..3089d530 100644 --- a/man/rename_fasta.Rd +++ b/man/rename_fasta.Rd @@ -15,6 +15,15 @@ rename_fasta(fa_path, outpath, replacement_function = map_acc2name, ...) \item{...}{Additional arguments to pass to replacement_function} } +\value{ +Character vector containing the modified lines of the Fasta file. +} \description{ Rename the labels of fasta files } +\examples{ +\dontrun{ +rename_fasta("input.fasta", "output.fasta", +replacement_function = map_acc2name, acc2name = acc2name_table) +} +} diff --git a/man/replaceQuestionMarks.Rd b/man/replaceQuestionMarks.Rd index 0949568f..8b16992a 100644 --- a/man/replaceQuestionMarks.Rd +++ b/man/replaceQuestionMarks.Rd @@ -12,7 +12,9 @@ replaceQuestionMarks(prot, by_column = "GenContext") \item{by_column}{Column to operate on} } \value{ -Describe return, in detail +The original data frame with the specified column updated. All +consecutive '?' characters will be replaced with 'X(s)', and individual '?' +characters will be replaced with 'X'. } \description{ Replace consecutive '?' separated by '->', '<-' or '||' with 'X(s)' diff --git a/man/reveql.Rd b/man/reveql.Rd index 9dc2bcb8..b16ed7be 100644 --- a/man/reveql.Rd +++ b/man/reveql.Rd @@ -2,13 +2,26 @@ % Please edit documentation in R/reverse_operons.R \name{reveql} \alias{reveql} -\title{reveql} +\title{reveql: Reverse Equalities in Genomic Context} \usage{ reveql(prot) } \arguments{ -\item{prot}{} +\item{prot}{\link{vector} A vector of genomic context strings to be processed.} +} +\value{ +\link{vector} A vector of the same length as the input, where each genomic +element is annotated with either a forward ("->") or reverse ("<-") direction, +depending on its position relative to the "=" symbols. } \description{ -reveql +This function processes the genomic context strings (GenContext) and reverses +directional signs based on the presence of an equal sign ("="). +} +\examples{ +# Example input: Genomic context with directional symbols and an asterisk +genomic_context <- c("A", "B", "*", "C", "D", "=", "E", "F") +reveql(genomic_context) + +# Output: "A->", "B->", "*", "<-C", "<-D", "=", "E->", "F->" } diff --git a/man/reverse_operon.Rd b/man/reverse_operon.Rd index 270e2a62..1c27aecc 100644 --- a/man/reverse_operon.Rd +++ b/man/reverse_operon.Rd @@ -2,13 +2,28 @@ % Please edit documentation in R/reverse_operons.R \name{reverse_operon} \alias{reverse_operon} -\title{reverse_operon} +\title{reverse_operon: Reverse the Direction of Operons in Genomic Context} \usage{ reverse_operon(prot) } \arguments{ -\item{prot}{} +\item{prot}{\link{data.frame} A data frame containing at least a column named +'GenContext', which represents the genomic contexts that need to be reversed.} +} +\value{ +\link{data.frame} The input data frame with the 'GenContext' column updated t +o reflect the reversed operons. } \description{ -reverse_operon +This function processes a genomic context data frame to reverse the direction +of operons based on specific patterns in the GenContext column. It handles +elements represented by ">" and "<" and restructures the genomic context by +flipping the direction of operons while preserving the relationships +indicated by "=". +} +\examples{ +# Example genomic context data frame +prot <- data.frame(GenContext = c("A>B", "CI")) +reversed_prot <- reverse_operon(prot) +print(reversed_prot) } diff --git a/man/runIPRScan.Rd b/man/runIPRScan.Rd index 678d8652..8431efb4 100644 --- a/man/runIPRScan.Rd +++ b/man/runIPRScan.Rd @@ -7,8 +7,28 @@ runIPRScan(filepath_fasta, filepath_out, appl = c("Pfam", "Gene3D")) } \arguments{ -\item{appl}{} +\item{filepath_fasta}{A string representing the path to the input FASTA file.} + +\item{filepath_out}{A string representing the base path for the output file.} + +\item{appl}{A character vector specifying the InterProScan applications to +use (e.g., "Pfam", "Gene3D"). Default is \code{c("Pfam", "Gene3D")}.} +} +\value{ +A data frame containing the results from the InterProScan output +TSV file. } \description{ -runIPRScan +Run InterProScan on a given FASTA file and save the results to an +output file. +} +\examples{ +\dontrun{ +results <- runIPRScan( + filepath_fasta = "path/to/your_fasta_file.fasta", + filepath_out = "path/to/output_file", + appl = c("Pfam", "Gene3D") +) +print(results) +} } diff --git a/man/run_deltablast.Rd b/man/run_deltablast.Rd index 3c934d77..2a9f01b0 100644 --- a/man/run_deltablast.Rd +++ b/man/run_deltablast.Rd @@ -16,12 +16,35 @@ run_deltablast( ) } \arguments{ -\item{db_search_path}{Path to the BLAST databases} +\item{deltablast_path}{Path to the Delta-BLAST executable.} -\item{num_threads}{} +\item{db_search_path}{Path to the BLAST databases.} + +\item{db}{Name of the BLAST database to search against (default is "refseq").} + +\item{query}{Path to the input query file.} + +\item{evalue}{E-value threshold for reporting matches (default is "1e-5").} + +\item{out}{Path to the output file where results will be saved.} + +\item{num_alignments}{Number of alignments to report.} + +\item{num_threads}{Number of threads to use for the search (default is 1).} +} +\value{ +This function does not return a value; it outputs results to the +specified file. } \description{ -Run DELTABLAST to find homologs for proteins of interest +This function executes a Delta-BLAST search using the specified parameters +and database. It sets the BLAST database path, runs the Delta-BLAST command +with the given query, and outputs the results. +} +\examples{ +\dontrun{ +run_deltablast(deltablast_path, db_search_path, query, out, num_alignments) +} } \author{ Samuel Chen, Janani Ravi diff --git a/man/run_rpsblast.Rd b/man/run_rpsblast.Rd index bc4474f1..4b638a72 100644 --- a/man/run_rpsblast.Rd +++ b/man/run_rpsblast.Rd @@ -15,10 +15,31 @@ run_rpsblast( ) } \arguments{ -\item{db_search_path}{Path to the BLAST databases} +\item{rpsblast_path}{Path to the RPS-BLAST executable.} -\item{num_threads}{} +\item{db_search_path}{Path to the BLAST databases.} + +\item{db}{Name of the BLAST database to search against (default is "refseq").} + +\item{query}{Path to the input query file.} + +\item{evalue}{E-value threshold for reporting matches (default is "1e-5").} + +\item{out}{Path to the output file where results will be saved.} + +\item{num_threads}{Number of threads to use for the search (default is 1).} +} +\value{ +This function does not return a value; it outputs results to the +specified file. } \description{ -Run RPSBLAST to generate domain architectures for proteins of interest +This function executes an RPS-BLAST search to generate domain architectures +for specified proteins. It sets the BLAST database path, runs the RPS-BLAST +command with the provided query, and outputs the results. +} +\examples{ +\dontrun{ +run_rpsblast(rpsblast_path, db_search_path, query, out) +} } diff --git a/man/selectLongestDuplicate.Rd b/man/selectLongestDuplicate.Rd index c177d289..bd535455 100644 --- a/man/selectLongestDuplicate.Rd +++ b/man/selectLongestDuplicate.Rd @@ -7,10 +7,15 @@ selectLongestDuplicate(prot, column) } \arguments{ -\item{column}{} +\item{prot}{A data frame containing the data, with at least one column +named 'AccNum' for identification of duplicates.} + +\item{column}{The name of the column from which the longest entry among +duplicates will be selected.} } \value{ -Describe return, in detail +A data frame containing only the longest entries among duplicates +based on the specified column. } \description{ Pick Longer Duplicate diff --git a/man/shortenLineage.Rd b/man/shortenLineage.Rd index f495fb32..00200f96 100644 --- a/man/shortenLineage.Rd +++ b/man/shortenLineage.Rd @@ -2,18 +2,34 @@ % Please edit documentation in R/plotting.R \name{shortenLineage} \alias{shortenLineage} -\title{Shorten Lineage} +\title{Shorten Lineage Names} \usage{ shortenLineage(data, colname = "Lineage", abr_len = 1) } \arguments{ -\item{abr_len}{} +\item{data}{A data frame that contains a column with lineage names to be +shortened.} + +\item{colname}{Character. The name of the column in the data frame containing +the lineage strings to be shortened. Default is \code{"Lineage"}.} + +\item{abr_len}{Integer. The number of characters to retain after the first +letter. If set to 1, only the first letter of each segment before the +delimiter (\code{>}) is retained. Default is 1.} +} +\value{ +A modified data frame where the specified lineage column has been +shortened. } \description{ -Shorten Lineage +This function abbreviates lineage names by shortening the first part of the +string (up to a given delimiter). } \examples{ \dontrun{ -shortenLineage() +df <- data.frame(Lineage = c("Bacteria>Firmicutes>Clostridia", +"Archaea>Euryarchaeota>Thermococci")) +shortened_df <- shortenLineage(df, colname = "Lineage", abr_len = 1) +print(shortened_df) } } diff --git a/man/summarizebylineage.Rd b/man/summarizeByLineage.Rd similarity index 100% rename from man/summarizebylineage.Rd rename to man/summarizeByLineage.Rd diff --git a/man/theme_genes2.Rd b/man/theme_genes2.Rd index 29f79673..d1420067 100644 --- a/man/theme_genes2.Rd +++ b/man/theme_genes2.Rd @@ -6,6 +6,19 @@ \usage{ theme_genes2() } +\value{ +A ggplot2 theme object. +} \description{ Theme Genes2 } +\examples{ +library(ggplot2) + +# Create a sample plot using the custom theme +ggplot(mtcars, aes(x = wt, y = mpg)) + + geom_point() + + theme_genes2() + + labs(title = "Car Weight vs MPG") + +} diff --git a/man/to_titlecase.Rd b/man/to_titlecase.Rd index 45139d3b..1b142875 100644 --- a/man/to_titlecase.Rd +++ b/man/to_titlecase.Rd @@ -13,10 +13,17 @@ to_titlecase(text, delimitter) \item{y}{Delimitter. Default is space (" ").} } +\value{ +A character vector in title case. +} \description{ Translate string to Title Case w/ delimitter. Changing case to 'Title Case' } +\examples{ +to_titlecase("hello world") +to_titlecase("this is a test", "_") +} \seealso{ chartr, toupper, and tolower. } diff --git a/man/totalgencontextordomarchcounts.Rd b/man/totalGenContextOrDomArchCounts.Rd similarity index 100% rename from man/totalgencontextordomarchcounts.Rd rename to man/totalGenContextOrDomArchCounts.Rd diff --git a/man/validateCountDF.Rd b/man/validateCountDF.Rd index fc4aefa2..5943723e 100644 --- a/man/validateCountDF.Rd +++ b/man/validateCountDF.Rd @@ -7,8 +7,16 @@ validateCountDF(var) } \arguments{ -\item{var}{} +\item{var}{A data frame whose columns are to be converted.} +} +\value{ +A data frame with non-'n' columns converted to character type. } \description{ validateCountDF } +\examples{ +\dontrun{ +new_df <- .all_non_n_cols_to_char(my_data) +} +} diff --git a/man/wordcloud3.Rd b/man/wordcloud3.Rd index cce07a82..1406ea0d 100644 --- a/man/wordcloud3.Rd +++ b/man/wordcloud3.Rd @@ -25,8 +25,60 @@ wordcloud3( ) } \arguments{ -\item{hoverFunction}{} +\item{data}{Data frame or table containing words and their frequencies for +the word cloud.} + +\item{size}{Numeric. Scaling factor for word sizes (default is 1).} + +\item{minSize}{Numeric. Minimum font size for the smallest word +(default is 0).} + +\item{gridSize}{Numeric. Size of the grid for placing words (default is 0).} + +\item{fontFamily}{Character. Font family to use for the words +(default is "Segoe UI").} + +\item{fontWeight}{Character. Font weight for the words (default is "bold").} + +\item{color}{Character or vector. Color of the words. Use "random-dark" for +random dark colors (default) or specify a color.} + +\item{backgroundColor}{Character. Background color of the word cloud +(default is "white").} + +\item{minRotation}{Numeric. Minimum rotation angle of words in radians +(default is -π/4).} + +\item{maxRotation}{Numeric. Maximum rotation angle of words in radians +(default is π/4).} + +\item{shuffle}{Logical. Whether to shuffle the words (default is TRUE).} + +\item{rotateRatio}{Numeric. Proportion of words that are rotated +(default is 0.4).} + +\item{shape}{Character. Shape of the word cloud ("circle" is default, but +you can use "cardioid", "star", "triangle", etc.).} + +\item{ellipticity}{Numeric. Degree of ellipticity (default is 0.65).} + +\item{widgetsize}{Numeric vector. Width and height of the widget +(default is NULL, which uses default size).} + +\item{figPath}{Character. Path to an image file to use as a mask for the +word cloud (optional).} + +\item{hoverFunction}{JS function. JavaScript function to run when hovering +over words (optional).} +} +\value{ +An HTML widget object displaying a word cloud. } \description{ plotWordCloud3 } +\examples{ +\dontrun{ +wordcloud3(data = your_data, size = 1.5, color = "random-light") +} +} diff --git a/man/words2wordcounts.Rd b/man/words2WordCounts.Rd similarity index 100% rename from man/words2wordcounts.Rd rename to man/words2WordCounts.Rd diff --git a/man/write.MsaAAMultipleAlignment.Rd b/man/write.MsaAAMultipleAlignment.Rd index 17a05f50..6d660b9e 100644 --- a/man/write.MsaAAMultipleAlignment.Rd +++ b/man/write.MsaAAMultipleAlignment.Rd @@ -13,6 +13,11 @@ write.MsaAAMultipleAlignment(alignment, outpath) \item{outpath}{Where the resulting FASTA file should be written to} } +\value{ +Character string representing the content of the written FASTA file. + +Character string of the FASTA content that was written to the file. +} \description{ MsaAAMultipleAlignment Objects are generated from calls to msaClustalOmega and msaMuscle from the 'msa' package @@ -21,6 +26,17 @@ Write MsaAAMultpleAlignment Objects as algined fasta sequence MsaAAMultipleAlignment Objects are generated from calls to msaClustalOmega and msaMuscle from the 'msa' package } +\examples{ +\dontrun{ +alignment <- msaMuscle("my_sequences.fasta") +write.MsaAAMultipleAlignment(alignment, "aligned_sequences.fasta") +} +\dontrun{ +# Example usage +alignment <- alignFasta("path/to/sequences.fasta") +write.MsaAAMultipleAlignment(alignment, "path/to/aligned_sequences.fasta") +} +} \author{ Samuel Chen, Janani Ravi } From 74b83ab58bbd3463217f211b861918f5daa2b6dd Mon Sep 17 00:00:00 2001 From: Awa Synthia Date: Fri, 11 Oct 2024 01:59:14 +0300 Subject: [PATCH 08/24] remove import Signed-off-by: Awa Synthia --- NAMESPACE | 1 - R/msa.R | 1 - 2 files changed, 2 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 50943690..078f971b 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -230,7 +230,6 @@ importFrom(purrr,map2) importFrom(purrr,map_chr) importFrom(purrr,pmap) importFrom(purrr,pmap_dfr) -importFrom(rMSA,kalign) importFrom(readr,cols) importFrom(readr,read_delim) importFrom(readr,read_file) diff --git a/R/msa.R b/R/msa.R index 20089dba..7d0d9be5 100644 --- a/R/msa.R +++ b/R/msa.R @@ -196,7 +196,6 @@ msa_pdf <- function(fasta_path, out_path = NULL, #' will be saved. #' #' @importFrom Biostrings readAAStringSet -#' @importFrom rMSA kalign #' #' @return A list containing the alignment object and the output file path. #' @export From 48b7fd697b6c6cac7826ae3f09d315025db1a438 Mon Sep 17 00:00:00 2001 From: Seyi Kuforiji Date: Sun, 13 Oct 2024 18:02:36 +0100 Subject: [PATCH 09/24] Update error handling to use rlang functions in acc2lin.R file - Replaced base R error handling with rlang functions: `abort()`, `warn()`, and `inform()`. - Improved clarity and consistency in error and warning messages. - Enhanced robustness with detailed context for errors and warnings. --- R/acc2lin.R | 209 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 141 insertions(+), 68 deletions(-) diff --git a/R/acc2lin.R b/R/acc2lin.R index 08cb7d76..bd5cc289 100644 --- a/R/acc2lin.R +++ b/R/acc2lin.R @@ -5,6 +5,7 @@ # suppressPackageStartupMessages(library(data.table)) # suppressPackageStartupMessages(library(tidyverse)) # suppressPackageStartupMessages(library(biomartr)) +suppressPackageStartupMessages(library(rlang)) # https://stackoverflow.com/questions/18730491/sink-does-not-release-file #' Sink Reset @@ -24,13 +25,18 @@ sinkReset <- function() { for (i in seq_len(sink.number())) { sink(NULL) } - print("All sinks closed") + inform("All sinks closed", class = "sink_reset_info") }, error = function(e) { - print(paste("Error: ", e$message)) + abort(paste("Error: ", e$message), class = "sink_reset_error") }, warning = function(w) { - print(paste("Warning: ", w$message)) + warn(paste("Warning: ", w$message), class = "sink_reset_warning") }, finally = { - print("resetSink function execution completed.") + # If any additional cleanup is needed, it can be done here + if (sink.number() > 0) { + # Additional cleanup if sinks are still open + inform("Some sinks remain open, ensure proper cleanup.", + class = "sink_cleanup_warning") + } }) } @@ -56,60 +62,64 @@ sinkReset <- function() { #' addLineage() #' } addLineage <- function(df, acc_col = "AccNum", assembly_path, - lineagelookup_path, ipgout_path = NULL, - plan = "sequential", ...) { + lineagelookup_path, ipgout_path = NULL, + plan = "sequential", ...) { # check for validate inputs if (!is.data.frame(df)) { - stop("Input 'df' must be a data frame.") + abort("Input 'df' must be a data frame.", class = "input_error") } if (!acc_col %in% colnames(df)) { - stop(paste("Column", acc_col, "not found in data frame.")) + abort(paste("Column", acc_col, + "not found in data frame."), class = "column_error") } # Ensure paths are character strings if (!is.character(assembly_path) || !is.character(lineagelookup_path)) { - stop("Both 'assembly_path' and - 'lineagelookup_path' must be character strings.") + abort("Both 'assembly_path' and + 'lineagelookup_path' must be character strings.", + class = "path_type_error") } # Ensure paths exist if (!file.exists(assembly_path)) { - stop(paste("Assembly file not found at:", assembly_path)) + abort(paste("Assembly file not found at:", + assembly_path), class = "file_not_found_error") } if (!file.exists(lineagelookup_path)) { - stop(paste("Lineage lookup file not found at:", lineagelookup_path)) + abort(paste("Lineage lookup file not found at:", + lineagelookup_path), class = "file_not_found_error") } - tryCatch({ - # Attempt to add lineages - acc_col <- sym(acc_col) - accessions <- df %>% pull(acc_col) - lins <- acc2Lineage( - accessions, assembly_path, lineagelookup_path, ipgout_path, plan - ) - - # Drop a lot of the unimportant columns for now? - # will make merging much easier - lins <- lins[, c( - "Strand", "Start", "Stop", "Nucleotide Accession", "Source", - "Id", "Strain" - ) := NULL] - lins <- unique(lins) - - # dup <- lins %>% group_by(Protein) %>% - # summarize(count = n()) %>% filter(count > 1) %>% - # pull(Protein) - - merged <- merge(df, lins, by.x = acc_col, by.y = "Protein", all.x = TRUE) - return(merged) - }, error = function(e) { - print(paste("Error: ", e$message)) - }, warning = function(w) { - print(paste("Warning: ", w$message)) - }, finally = { - print("addLineages function execution completed.") - }) + tryCatch({ + # Attempt to add lineages + acc_col <- sym(acc_col) + accessions <- df %>% pull(acc_col) + lins <- acc2Lineage( + accessions, assembly_path, lineagelookup_path, ipgout_path, plan + ) + + # Drop a lot of the unimportant columns for now? + # will make merging much easier + lins <- lins[, c( + "Strand", "Start", "Stop", "Nucleotide Accession", "Source", + "Id", "Strain" + ) := NULL] + lins <- unique(lins) + + # dup <- lins %>% group_by(Protein) %>% + # summarize(count = n()) %>% filter(count > 1) %>% + # pull(Protein) + + merged <- merge(df, lins, by.x = acc_col, by.y = "Protein", all.x = TRUE) + return(merged) + }, error = function(e) { + abort(paste("Error during lineage addition:", e$message), + class = "lineage_addition_error") + }, warning = function(w) { + warn(paste("Warning during lineage addition:", w$message), + class = "lineage_addition_warning") + }) } @@ -140,11 +150,11 @@ addLineage <- function(df, acc_col = "AccNum", assembly_path, #' acc2Lineage() #' } acc2Lineage <- function(accessions, assembly_path, - lineagelookup_path, ipgout_path = NULL, - plan = "sequential", ...) { + lineagelookup_path, ipgout_path = NULL, + plan = "sequential", ...) { tmp_ipg <- F if (is.null(ipgout_path)) { - tmp_ipg <- T + tmp_ipg <- TRUE ipgout_path <- tempfile("ipg", fileext = ".txt") } @@ -154,18 +164,41 @@ acc2Lineage <- function(accessions, assembly_path, efetchIPG(accessions, out_path = ipgout_path, plan) # Attempt to process IPG to lineages - lins <- IPG2Lineage(accessions, ipgout_path, assembly_path, lineagelookup_path) + lins <- IPG2Lineage(accessions, ipgout_path, + assembly_path, lineagelookup_path) }, error = function(e) { - print(paste("An error occurred: ", e$message)) + abort( + message = paste("An error occurred during IPG fetching + or lineage processing:", e$message), + class = "lineage_processing_error", + # capturing the call stack + call = sys.call(), + # adding additional context + accessions = accessions, + assembly_path = assembly_path, + lineagelookup_path = lineagelookup_path, + ipgout_path = ipgout_path, + plan = plan + ) }, warning = function(w) { - print(paste("Warning: ", w$message)) + warn( + message = paste("Warning during IPG fetching + or lineage processing:", w$message), + class = "lineage_processing_warning", + call = sys.call(), # capturing the call stack + accessions = accessions, + assembly_path = assembly_path, + lineagelookup_path = lineagelookup_path, + ipgout_path = ipgout_path, + plan = plan + ) }, finally = { - print("acc2lin function execution completed.") + # Cleanup: delete temporary IPG file if it was created + if (tmp_ipg && file.exists(ipgout_path)) { + unlink(ipgout_path) + } }) - if (tmp_ipg) { - unlink(tempdir(), recursive = T) - } return(lins) } @@ -196,15 +229,18 @@ acc2Lineage <- function(accessions, assembly_path, efetchIPG <- function(accnums, out_path, plan = "sequential", ...) { # Argument validation if (!is.character(accnums) || length(accnums) == 0) { - stop("Error: 'accnums' must be a non-empty character vector.") + abort("Error: 'accnums' must be a non-empty character vector.", + class = "validation_error") } if (!is.character(out_path) || nchar(out_path) == 0) { - stop("Error: 'out_path' must be a non-empty string.") + abort("Error: 'out_path' must be a non-empty string.", + class = "validation_error") } if (!is.function(plan)) { - stop("Error: 'plan' must be a valid plan function.") + abort("Error: 'plan' must be a valid plan function.", + class = "validation_error") } if (length(accnums) > 0) { partition <- function(in_data, groups) { @@ -249,11 +285,26 @@ efetchIPG <- function(accnums, out_path, plan = "sequential", ...) { }) sink(NULL) }, error = function(e) { - print(paste("An error occurred: ", e$message)) + abort( + message = paste("An error occurred: ", e$message), + class = "fetch_error", + call = sys.call(), + accnums = accnums, + out_path = out_path, + plan = plan + ) }, warning = function(w) { - print(paste("Warning: ", w$message)) + warn( + message = paste("Warning: ", w$message), + class = "fetch_warning", + call = sys.call(), + accnums = accnums, + out_path = out_path, + plan = plan + ) }, finally = { - print("efetch_ipg function execution completed.") + # Ensure the sink is closed in case of errors + if (sink.number() > 0) sink(NULL) }) } } @@ -289,31 +340,38 @@ efetchIPG <- function(accnums, out_path, plan = "sequential", ...) { #' IPG2Lineage() #' } #' -IPG2Lineage <- function(accessions, ipg_file, assembly_path, lineagelookup_path, ...) { +IPG2Lineage <- function(accessions, ipg_file, + assembly_path, lineagelookup_path, ...) { # Argument validation for accessions if (!is.character(accessions) || length(accessions) == 0) { - stop("Input 'accessions' must be a non-empty character vector.") + abort("Input 'accessions' must be a non-empty + character vector.", class = "validation_error") } # check for validate inputs if (!is.character(ipg_file)) { - stop("Input 'ipg_file' must be a character string.") + abort("Input 'ipg_file' must be a + character string.", class = "validation_error") } + # Ensure paths are character strings if (!is.character(assembly_path) || !is.character(lineagelookup_path)) { - stop("Both 'assembly_path' and - 'lineagelookup_path' must be character strings.") + abort("Both 'assembly_path' and 'lineagelookup_path' + must be character strings.", class = "validation_error") } # Ensure paths exist if (!file.exists(assembly_path)) { - stop(paste("Assembly file not found at:", assembly_path)) + abort(paste("Assembly file not found at:", assembly_path), + class = "file_error") } if (!file.exists(lineagelookup_path)) { - stop(paste("Lineage lookup file not found at:", lineagelookup_path)) + abort(paste("Lineage lookup file not found at:", lineagelookup_path), + class = "file_error") } + # Process the IPG file try({ # Attempt to read the IPG file ipg_dt <- fread(ipg_file, sep = "\t", fill = T) @@ -332,12 +390,27 @@ IPG2Lineage <- function(accessions, ipg_file, assembly_path, lineagelookup_path, return(lins) }, error = function(e) { - print(paste("An error occurred: ", e$message)) + abort( + message = paste("An error occurred: ", e$message), + class = "processing_error", + call = sys.call(), + accessions = accessions, + ipg_file = ipg_file, + assembly_path = assembly_path, + lineagelookup_path = lineagelookup_path + ) }, warning = function(w) { - print(paste("Warning: ", w$message)) - }, finally = { - print("ipg2lin function execution completed.") + warn( + message = paste("Warning: ", w$message), + class = "processing_warning", + call = sys.call(), + accessions = accessions, + ipg_file = ipg_file, + assembly_path = assembly_path, + lineagelookup_path = lineagelookup_path + ) }) + } From 6babffe95d2729857b921c9305f25dcbc0c0ed49 Mon Sep 17 00:00:00 2001 From: Seyi Kuforiji Date: Tue, 15 Oct 2024 11:57:15 +0100 Subject: [PATCH 10/24] Update error handling to use rlang functions in R/assign_job_queue.R file - Replaced base R error handling with rlang functions: `abort()`, `warn()`, and `inform()`. - Improved clarity and consistency in error and warning messages. - Enhanced robustness with detailed context for errors and warnings. --- R/assign_job_queue.R | 227 +++++++++++++++++++++++++++++++------------ 1 file changed, 166 insertions(+), 61 deletions(-) diff --git a/R/assign_job_queue.R b/R/assign_job_queue.R index c531fb09..df4f97e7 100644 --- a/R/assign_job_queue.R +++ b/R/assign_job_queue.R @@ -1,3 +1,4 @@ +suppressPackageStartupMessages(library(rlang)) # for now, we're using an env var, COMMON_SRC_ROOT, to specify this folder since # the working directory is changed in many parts of the current molevolvr # pipeline. @@ -22,11 +23,9 @@ make_opts2procs <- function() { ) return(opts2processes) }, error = function(e) { - message(paste("Encountered an error: ", e$message)) + abort(paste("Error: ", e$message), class = "Opts_to_process_error") }, warning = function(w) { - message(paste("Warning: ", w$message)) - }, finally = { - message("make_opts2procs function execution completed.") + warn(paste("Warning: ", w$message), class = "Opts_to_process_warning") }) } @@ -44,7 +43,7 @@ make_opts2procs <- function() { #' @export map_advanced_opts2procs <- function(advanced_opts) { if (!is.character(advanced_opts)) { - stop("Argument must be a character vector!") + abort("Argument must be a character vector!", class = "validation_error") } tryCatch({ # append 'always' to add procs that always run @@ -56,11 +55,19 @@ map_advanced_opts2procs <- function(advanced_opts) { procs <- opts2proc[idx] |> unlist() return(procs) }, error = function(e) { - message(paste("Encountered an error: ", e$message)) + abort( + message = paste("Encountered an error: ", e$message), + class = "map_advanced_opts2procs_error", + call = sys.call(), + advanced_opts = advanced_opts + ) }, warning = function(w) { - message(paste("Warning: ", w$message)) - }, finally = { - message("make_opts2procs function execution completed.") + warn( + message = paste("Warning: ", w$message), + class = "map_advanced_opts2procs_warning", + call = sys.call(), + advanced_opts = advanced_opts + ) }) } @@ -91,12 +98,14 @@ get_proc_medians <- function(dir_job_results) { tryCatch({ # Check if dir_job_results is a character string if (!is.character(dir_job_results) || length(dir_job_results) != 1) { - stop("Input 'dir_job_results' must be a single character string.") + abort("Input 'dir_job_results' must be a single character string.", + class = "validation_error") } # Check if dir_job_results exists if (!dir.exists(dir_job_results)) { - stop(paste("The directory", dir_job_results, "does not exist.")) + abort(paste("The directory", dir_job_results, "does not exist."), + class = "file_error") } source(file.path(common_root, "molevol_scripts", "R", "metrics.R")) @@ -135,11 +144,10 @@ get_proc_medians <- function(dir_job_results) { as.list() return(list_proc_medians) }, error = function(e) { - message(paste("Encountered an error: ", e$message)) + abort(paste("Encountered an error: ", e$message), + class = "processing_error") }, warning = function(w) { - message(paste("Warning: ", w$message)) - }, finally = { - message("get_proc_medians function execution completed.") + warn(paste("Warning: ", w$message), class = "processing_warning") }) } @@ -165,15 +173,18 @@ write_proc_medians_table <- function(dir_job_results, filepath) { tryCatch({ # Error handling for input arguments if (!is.character(dir_job_results) || length(dir_job_results) != 1) { - stop("Input 'dir_job_results' must be a single character string.") + abort("Input 'dir_job_results' must be a single character string.", + class = "validation_error") } if (!dir.exists(dir_job_results)) { - stop(paste("The directory", dir_job_results, "does not exist.")) + abort(paste("The directory", dir_job_results, "does not exist."), + class = "file_error") } if (!is.character(filepath) || length(filepath) != 1) { - stop("Input 'filepath' must be a single character string.") + abort("Input 'filepath' must be a single character string.", + class = "validation_error") } df_proc_medians <- get_proc_medians(dir_job_results) |> tibble::as_tibble() |> @@ -188,11 +199,21 @@ write_proc_medians_table <- function(dir_job_results, filepath) { readr::write_tsv(df_proc_medians, file = filepath) return(df_proc_medians) }, error = function(e) { - message(paste("Encountered an error: ", e$message)) + abort( + message = paste("Encountered an error: ", e$message), + class = "processing_error", + call = sys.call(), + dir_job_results = dir_job_results, + filepath = filepath + ) }, warning = function(w) { - message(paste("Warning: ", w$message)) - }, finally = { - message("write_proc_medians_table function execution completed.") + warn( + message = paste("Warning: ", w$message), + class = "processing_warning", + call = sys.call(), + dir_job_results = dir_job_results, + filepath = filepath + ) }) } @@ -222,12 +243,21 @@ write_proc_medians_yml <- function(dir_job_results, filepath = NULL) { tryCatch({ # Error handling for dir_job_results arguments if (!is.character(dir_job_results) || length(dir_job_results) != 1) { - stop("Input 'dir_job_results' must be a single character string.") + abort( + message = "Input 'dir_job_results' must be a single character string.", + class = "validation_error", + dir_job_results = dir_job_results + ) } if (!dir.exists(dir_job_results)) { - stop(paste("The directory", dir_job_results, "does not exist.")) + abort( + message = paste("The directory", dir_job_results, "does not exist."), + class = "file_error", + dir_job_results = dir_job_results + ) } + if (is.null(filepath)) { filepath <- file.path(common_root, "molevol_scripts", @@ -235,20 +265,32 @@ write_proc_medians_yml <- function(dir_job_results, filepath = NULL) { "job_proc_weights.yml") } if (!is.character(filepath) || length(filepath) != 1) { - stop("Input 'filepath' must be a single character string.") + abort( + message = "Input 'filepath' must be a single character string.", + class = "validation_error", + filepath = filepath + ) } medians <- get_proc_medians(dir_job_results) yaml::write_yaml(medians, filepath) }, error = function(e) { - message(paste("Encountered an error: "), e$message) + abort( + message = paste("Encountered an error: ", e$message), + class = "processing_error", + call = sys.call(), + dir_job_results = dir_job_results, + filepath = filepath + ) }, warning = function(w) { - message(paste("Warning: "), w$message) - }, finally = { - message("write_proc_medians_table function execution completed.") - } - ) - + warn( + message = paste("Warning: ", w$message), + class = "processing_warning", + call = sys.call(), + dir_job_results = dir_job_results, + filepath = filepath + ) + }) } #' Quickly get the runtime weights for MolEvolvR backend processes @@ -275,13 +317,24 @@ get_proc_weights <- function(medians_yml_path = NULL) { # attempt to read the weights from the YAML file produced by # write_proc_medians_yml() if (stringr::str_trim(medians_yml_path) == "") { - stop( - stringr::str_glue("medians_yml_path is empty - ({medians_yml_path}), returning default weights") + abort( + message = stringr::str_glue("medians_yml_path is empty + ({medians_yml_path}), returning default weights"), + class = "input_error", + medians_yml_path = medians_yml_path ) } proc_weights <- yaml::read_yaml(medians_yml_path) + + if (!is.list(proc_weights) || length(proc_weights) == 0) { + abort( + message = "The loaded YAML file does not + contain valid process weights.", + class = "file_error", + medians_yml_path = medians_yml_path + ) + } }, # to avoid fatal errors in reading the proc weights yaml, # some median process runtimes have been hardcoded based on @@ -318,10 +371,9 @@ get_proc_weights <- function(medians_yml_path = NULL) { #' "domain_architecture"), #' n_inputs = 3, n_hits = 50L) #' @export -advanced_opts2est_walltime <- function(advanced_opts, - n_inputs = 1L, - n_hits = NULL, - verbose = FALSE) { +advanced_opts2est_walltime <- function(advanced_opts, n_inputs = 1L, + n_hits = NULL, + verbose = FALSE) { tryCatch({ # to calculate est walltime for a homology search job, the number of hits @@ -331,26 +383,42 @@ advanced_opts2est_walltime <- function(advanced_opts, # Validate advanced_opts if (!is.character(advanced_opts)) { - stop("Argument 'advanced_opts' must be a character vector.") + abort( + message = "Argument 'advanced_opts' must be a character vector.", + class = "validation_error", + advanced_opts = advanced_opts + ) } # Validate n_inputs if (!is.numeric(n_inputs) || length(n_inputs) != 1 || n_inputs <= 0) { - stop("Argument 'n_inputs' must be a single positive numeric value.") + abort( + message = "Argument 'n_inputs' + must be a single positive numeric value.", + class = "validation_error", + n_inputs = n_inputs + ) } # Validate n_hits if homology_search is in advanced_opts if ("homology_search" %in% advanced_opts && - (is.null(n_hits)|| !is.numeric(n_hits) - || length(n_hits) != 1 || n_hits < 0)) { - stop("Argument 'n_hits' must be a single non-negative numeric value when - 'homology_search' is in 'advanced_opts'.") + (is.null(n_hits) || !is.numeric(n_hits) || + length(n_hits) != 1 || n_hits < 0)) { + abort( + message = "Argument 'n_hits' must be a single non-negative numeric + value when 'homology_search' is in 'advanced_opts'.", + class = "validation_error", + n_hits = n_hits + ) } # Get process weights proc_weights <- write_proc_medians_yml() if (!is.list(proc_weights)) { - stop("Process weights could not be retrieved correctly.") + abort( + message = "Process weights could not be retrieved correctly.", + class = "processing_error" + ) } # sort process weights by names and convert to vec @@ -389,12 +457,23 @@ advanced_opts2est_walltime <- function(advanced_opts, } return(est_walltime) }, error = function(e) { - message(paste("Encountered an error: ", e$message)) + abort( + message = paste("Encountered an error: ", e$message), + class = "processing_error", + call = sys.call(), + advanced_opts = advanced_opts, + n_inputs = n_inputs, + n_hits = n_hits + ) }, warning = function(w) { - message(paste("Warning: ", w$message)) - }, finally = { - message("advanced_opts2est_walltime - function execution completed.") + warn( + message = paste("Warning: ", w$message), + class = "processing_warning", + call = sys.call(), + advanced_opts = advanced_opts, + n_inputs = n_inputs, + n_hits = n_hits + ) }) } @@ -419,22 +498,44 @@ assign_job_queue <- function( t_cutoff = 21600 # 6 hours ) { tryCatch({ + # Validate t_sec_estimate if (!is.numeric(t_sec_estimate) || length(t_sec_estimate) != 1) { - stop("Argument 't_sec_estimate' must be a single numeric value.") + abort( + message = "Argument 't_sec_estimate' must be a single numeric value.", + class = "validation_error", + t_sec_estimate = t_sec_estimate + ) } + # Validate t_cutoff if (!is.numeric(t_cutoff) || length(t_cutoff) != 1 || t_cutoff < 0) { - stop("Argument 't_cutoff' must be a single non-negative numeric value.") + abort( + message = "Argument 't_cutoff' must be a + single non-negative numeric value.", + class = "validation_error", + t_cutoff = t_cutoff + ) } + queue <- ifelse(t_sec_estimate > t_cutoff, "long", "short") return(queue) }, error = function(e) { - message(paste("Encountered an error: ", e$message)) + abort( + message = paste("Encountered an error: ", e$message), + class = "processing_error", + call = sys.call(), + t_sec_estimate = t_sec_estimate, + t_cutoff = t_cutoff + ) }, warning = function(w) { - message(paste("Warning: ", w$message)) - }, finally = { - message("assign_job_queue function execution completed.") + warn( + message = paste("Warning: ", w$message), + class = "processing_warning", + call = sys.call(), + t_sec_estimate = t_sec_estimate, + t_cutoff = t_cutoff + ) }) } @@ -537,11 +638,15 @@ plot_estimated_walltimes <- function() { ) return(p) }, error = function(e) { - message(paste("Encountered an error: ", e$message)) + abort( + message = paste("Encountered an error:", e$message), + .internal = TRUE + ) }, warning = function(w) { - message(paste("Warning: ", w$message)) - }, finally = { - message("plot_estimated_walltimes function execution completed.") + warn( + message = paste("Warning:", w$message), + .internal = TRUE + ) }) } From 57a635671795984f5ace17076ef0029c6ff0336c Mon Sep 17 00:00:00 2001 From: Seyi Kuforiji Date: Sun, 20 Oct 2024 12:01:02 +0100 Subject: [PATCH 11/24] Enhance error handling and validation across functions - Added robust error handling in run_deltablast and run_rpsblast functions. - Updated Roxygen documentation to import rlang::abort, rlang::warn and rlang::inform for better error management. - Refactored code for clarity and consistency based on the suggestion from the last review. --- NAMESPACE | 3 + R/acc2lin.R | 105 ++++++++++++++++++----------------- R/assign_job_queue.R | 128 ++++++++++++++++++++++--------------------- R/blastWrappers.R | 84 +++++++++++++++++++++------- 4 files changed, 184 insertions(+), 136 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index 078f971b..9449e14b 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -240,8 +240,11 @@ importFrom(readr,write_lines) importFrom(readr,write_tsv) importFrom(rentrez,entrez_fetch) importFrom(rlang,.data) +importFrom(rlang,abort) importFrom(rlang,as_string) +importFrom(rlang,inform) importFrom(rlang,sym) +importFrom(rlang,warn) importFrom(sendmailR,mime_part) importFrom(sendmailR,sendmail) importFrom(seqinr,dist.alignment) diff --git a/R/acc2lin.R b/R/acc2lin.R index bd5cc289..c1f3b34e 100644 --- a/R/acc2lin.R +++ b/R/acc2lin.R @@ -5,11 +5,13 @@ # suppressPackageStartupMessages(library(data.table)) # suppressPackageStartupMessages(library(tidyverse)) # suppressPackageStartupMessages(library(biomartr)) -suppressPackageStartupMessages(library(rlang)) + # https://stackoverflow.com/questions/18730491/sink-does-not-release-file #' Sink Reset #' +#' @importFrom rlang warn abort inform +#' #' @return No return, but run to close all outstanding `sink()`s #' and handles any errors or warnings that occur during the process. #' @@ -25,17 +27,17 @@ sinkReset <- function() { for (i in seq_len(sink.number())) { sink(NULL) } - inform("All sinks closed", class = "sink_reset_info") + rlang::inform("All sinks closed", class = "sink_reset_info") }, error = function(e) { - abort(paste("Error: ", e$message), class = "sink_reset_error") + rlang::abort(paste("Error: ", e$message), class = "sink_reset_error") }, warning = function(w) { - warn(paste("Warning: ", w$message), class = "sink_reset_warning") + rlang::warn(paste("Warning: ", w$message), class = "sink_reset_warning") }, finally = { # If any additional cleanup is needed, it can be done here if (sink.number() > 0) { # Additional cleanup if sinks are still open - inform("Some sinks remain open, ensure proper cleanup.", - class = "sink_cleanup_warning") + rlang::inform("Some sinks remain open, ensure proper cleanup.", + class = "sink_cleanup_warning") } }) } @@ -52,7 +54,7 @@ sinkReset <- function() { #' #' @importFrom dplyr pull #' @importFrom magrittr %>% -#' @importFrom rlang sym +#' @importFrom rlang sym warn abort inform #' #' @return Describe return, in detail #' @export @@ -66,30 +68,30 @@ addLineage <- function(df, acc_col = "AccNum", assembly_path, plan = "sequential", ...) { # check for validate inputs if (!is.data.frame(df)) { - abort("Input 'df' must be a data frame.", class = "input_error") + rlang::abort("Input 'df' must be a data frame.", class = "input_error") } if (!acc_col %in% colnames(df)) { - abort(paste("Column", acc_col, - "not found in data frame."), class = "column_error") + rlang::abort(paste("Column", acc_col, + "not found in data frame."), class = "column_error") } # Ensure paths are character strings if (!is.character(assembly_path) || !is.character(lineagelookup_path)) { - abort("Both 'assembly_path' and - 'lineagelookup_path' must be character strings.", - class = "path_type_error") + rlang::abort("Both 'assembly_path' and + 'lineagelookup_path' must be character strings.", + class = "path_type_error") } # Ensure paths exist if (!file.exists(assembly_path)) { - abort(paste("Assembly file not found at:", - assembly_path), class = "file_not_found_error") + rlang::abort(paste("Assembly file not found at:", + assembly_path), class = "file_not_found_error") } if (!file.exists(lineagelookup_path)) { - abort(paste("Lineage lookup file not found at:", - lineagelookup_path), class = "file_not_found_error") + rlang::abort(paste("Lineage lookup file not found at:", + lineagelookup_path), class = "file_not_found_error") } tryCatch({ # Attempt to add lineages @@ -99,7 +101,7 @@ addLineage <- function(df, acc_col = "AccNum", assembly_path, accessions, assembly_path, lineagelookup_path, ipgout_path, plan ) - # Drop a lot of the unimportant columns for now? + # Drop a lot of the unimportant columns for now? # will make merging much easier lins <- lins[, c( "Strand", "Start", "Stop", "Nucleotide Accession", "Source", @@ -107,18 +109,18 @@ addLineage <- function(df, acc_col = "AccNum", assembly_path, ) := NULL] lins <- unique(lins) - # dup <- lins %>% group_by(Protein) %>% + # dup <- lins %>% group_by(Protein) %>% # summarize(count = n()) %>% filter(count > 1) %>% # pull(Protein) merged <- merge(df, lins, by.x = acc_col, by.y = "Protein", all.x = TRUE) return(merged) }, error = function(e) { - abort(paste("Error during lineage addition:", e$message), - class = "lineage_addition_error") + rlang::abort(paste("Error during lineage addition:", e$message), + class = "lineage_addition_error") }, warning = function(w) { - warn(paste("Warning during lineage addition:", w$message), - class = "lineage_addition_warning") + rlang::warn(paste("Warning during lineage addition:", w$message), + class = "lineage_addition_warning") }) } @@ -137,11 +139,13 @@ addLineage <- function(df, acc_col = "AccNum", assembly_path, #' This file can be generated using the \link[MolEvolvR]{downloadAssemblySummary} function #' @param lineagelookup_path String of the path to the lineage lookup file #' (taxid to lineage mapping). This file can be generated using the -#' @param ipgout_path Path to write the results +#' @param ipgout_path Path to write the results #' of the efetch run of the accessions #' on the ipg database. If NULL, the file will not be written. Defaults to NULL #' @param plan #' +#' @importFrom rlang warn abort inform +#' #' @return Describe return, in detail #' @export #' @@ -149,8 +153,8 @@ addLineage <- function(df, acc_col = "AccNum", assembly_path, #' \dontrun{ #' acc2Lineage() #' } -acc2Lineage <- function(accessions, assembly_path, - lineagelookup_path, ipgout_path = NULL, +acc2Lineage <- function(accessions, assembly_path, + lineagelookup_path, ipgout_path = NULL, plan = "sequential", ...) { tmp_ipg <- F if (is.null(ipgout_path)) { @@ -167,12 +171,10 @@ acc2Lineage <- function(accessions, assembly_path, lins <- IPG2Lineage(accessions, ipgout_path, assembly_path, lineagelookup_path) }, error = function(e) { - abort( + rlang::abort( message = paste("An error occurred during IPG fetching or lineage processing:", e$message), class = "lineage_processing_error", - # capturing the call stack - call = sys.call(), # adding additional context accessions = accessions, assembly_path = assembly_path, @@ -181,11 +183,10 @@ acc2Lineage <- function(accessions, assembly_path, plan = plan ) }, warning = function(w) { - warn( + rlang::warn( message = paste("Warning during IPG fetching or lineage processing:", w$message), class = "lineage_processing_warning", - call = sys.call(), # capturing the call stack accessions = accessions, assembly_path = assembly_path, lineagelookup_path = lineagelookup_path, @@ -218,6 +219,7 @@ acc2Lineage <- function(accessions, assembly_path, #' @importFrom furrr future_map #' @importFrom future plan #' @importFrom rentrez entrez_fetch +#' @importFrom rlang warn abort inform #' #' @return Describe return, in detail #' @export @@ -229,18 +231,18 @@ acc2Lineage <- function(accessions, assembly_path, efetchIPG <- function(accnums, out_path, plan = "sequential", ...) { # Argument validation if (!is.character(accnums) || length(accnums) == 0) { - abort("Error: 'accnums' must be a non-empty character vector.", - class = "validation_error") + rlang::abort("Error: 'accnums' must be a non-empty character vector.", + class = "validation_error") } if (!is.character(out_path) || nchar(out_path) == 0) { - abort("Error: 'out_path' must be a non-empty string.", - class = "validation_error") + rlang::abort("Error: 'out_path' must be a non-empty string.", + class = "validation_error") } if (!is.function(plan)) { - abort("Error: 'plan' must be a valid plan function.", - class = "validation_error") + rlang::abort("Error: 'plan' must be a valid plan function.", + class = "validation_error") } if (length(accnums) > 0) { partition <- function(in_data, groups) { @@ -285,19 +287,17 @@ efetchIPG <- function(accnums, out_path, plan = "sequential", ...) { }) sink(NULL) }, error = function(e) { - abort( + rlang::abort( message = paste("An error occurred: ", e$message), class = "fetch_error", - call = sys.call(), accnums = accnums, out_path = out_path, plan = plan ) }, warning = function(w) { - warn( + rlang::warn( message = paste("Warning: ", w$message), class = "fetch_warning", - call = sys.call(), accnums = accnums, out_path = out_path, plan = plan @@ -331,6 +331,7 @@ efetchIPG <- function(accnums, out_path, plan = "sequential", ...) { #' "create_lineage_lookup()" function #' #' @importFrom data.table fread +#' @importFrom rlang warn abort inform #' #' @return Describe return, in detail #' @export @@ -344,31 +345,31 @@ IPG2Lineage <- function(accessions, ipg_file, assembly_path, lineagelookup_path, ...) { # Argument validation for accessions if (!is.character(accessions) || length(accessions) == 0) { - abort("Input 'accessions' must be a non-empty + rlang::abort("Input 'accessions' must be a non-empty character vector.", class = "validation_error") } # check for validate inputs if (!is.character(ipg_file)) { - abort("Input 'ipg_file' must be a + rlang::abort("Input 'ipg_file' must be a character string.", class = "validation_error") } # Ensure paths are character strings if (!is.character(assembly_path) || !is.character(lineagelookup_path)) { - abort("Both 'assembly_path' and 'lineagelookup_path' - must be character strings.", class = "validation_error") + rlang::abort("Both 'assembly_path' and 'lineagelookup_path' + must be character strings.", class = "validation_error") } # Ensure paths exist if (!file.exists(assembly_path)) { - abort(paste("Assembly file not found at:", assembly_path), - class = "file_error") + rlang::abort(paste("Assembly file not found at:", assembly_path), + class = "file_error") } if (!file.exists(lineagelookup_path)) { - abort(paste("Lineage lookup file not found at:", lineagelookup_path), - class = "file_error") + rlang::abort(paste("Lineage lookup file not found at:", lineagelookup_path), + class = "file_error") } # Process the IPG file @@ -390,20 +391,18 @@ IPG2Lineage <- function(accessions, ipg_file, return(lins) }, error = function(e) { - abort( + rlang::abort( message = paste("An error occurred: ", e$message), class = "processing_error", - call = sys.call(), accessions = accessions, ipg_file = ipg_file, assembly_path = assembly_path, lineagelookup_path = lineagelookup_path ) }, warning = function(w) { - warn( + rlang::warn( message = paste("Warning: ", w$message), class = "processing_warning", - call = sys.call(), accessions = accessions, ipg_file = ipg_file, assembly_path = assembly_path, diff --git a/R/assign_job_queue.R b/R/assign_job_queue.R index df4f97e7..8b227979 100644 --- a/R/assign_job_queue.R +++ b/R/assign_job_queue.R @@ -1,4 +1,4 @@ -suppressPackageStartupMessages(library(rlang)) + # for now, we're using an env var, COMMON_SRC_ROOT, to specify this folder since # the working directory is changed in many parts of the current molevolvr # pipeline. @@ -9,6 +9,8 @@ common_root <- Sys.getenv("COMMON_SRC_ROOT") #' Construct list where names (MolEvolvR advanced options) point to processes #' +#' @importFrom rlang warn abort inform +#' #' @return list where names (MolEvolvR advanced options) point to processes #' #' example: list_opts2procs <- make_opts2procs @@ -23,9 +25,10 @@ make_opts2procs <- function() { ) return(opts2processes) }, error = function(e) { - abort(paste("Error: ", e$message), class = "Opts_to_process_error") + rlang::abort(paste("Error: ", e$message), class = "Opts_to_process_error") }, warning = function(w) { - warn(paste("Warning: ", w$message), class = "Opts_to_process_warning") + rlang::warn(paste("Warning: ", w$message), + class = "Opts_to_process_warning") }) } @@ -34,6 +37,8 @@ make_opts2procs <- function() { #' #' @param advanced_opts character vector of MolEvolvR advanced options #' +#' @importFrom rlang warn abort inform +#' #' @return character vector of process names that will execute given #' the advanced options #' @@ -43,7 +48,8 @@ make_opts2procs <- function() { #' @export map_advanced_opts2procs <- function(advanced_opts) { if (!is.character(advanced_opts)) { - abort("Argument must be a character vector!", class = "validation_error") + rlang::abort("Argument must be a character vector!", + class = "validation_error") } tryCatch({ # append 'always' to add procs that always run @@ -55,17 +61,15 @@ map_advanced_opts2procs <- function(advanced_opts) { procs <- opts2proc[idx] |> unlist() return(procs) }, error = function(e) { - abort( + rlang::abort( message = paste("Encountered an error: ", e$message), class = "map_advanced_opts2procs_error", - call = sys.call(), advanced_opts = advanced_opts ) }, warning = function(w) { - warn( + rlang::warn( message = paste("Warning: ", w$message), class = "map_advanced_opts2procs_warning", - call = sys.call(), advanced_opts = advanced_opts ) }) @@ -78,6 +82,7 @@ map_advanced_opts2procs <- function(advanced_opts) { #' directory #' #' @importFrom dplyr across everything select summarise +#' @importFrom rlang warn abort inform #' #' @return [list] names: processes; values: median runtime (seconds) #' @@ -98,14 +103,14 @@ get_proc_medians <- function(dir_job_results) { tryCatch({ # Check if dir_job_results is a character string if (!is.character(dir_job_results) || length(dir_job_results) != 1) { - abort("Input 'dir_job_results' must be a single character string.", - class = "validation_error") + rlang::abort("Input 'dir_job_results' must be a single character string.", + class = "validation_error") } # Check if dir_job_results exists if (!dir.exists(dir_job_results)) { - abort(paste("The directory", dir_job_results, "does not exist."), - class = "file_error") + rlang::abort(paste("The directory", dir_job_results, "does not exist."), + class = "file_error") } source(file.path(common_root, "molevol_scripts", "R", "metrics.R")) @@ -144,10 +149,10 @@ get_proc_medians <- function(dir_job_results) { as.list() return(list_proc_medians) }, error = function(e) { - abort(paste("Encountered an error: ", e$message), - class = "processing_error") + rlang::abort(paste("Encountered an error: ", e$message), + class = "processing_error") }, warning = function(w) { - warn(paste("Warning: ", w$message), class = "processing_warning") + rlang::warn(paste("Warning: ", w$message), class = "processing_warning") }) } @@ -161,6 +166,7 @@ get_proc_medians <- function(dir_job_results) { #' @importFrom tibble as_tibble #' @importFrom readr write_tsv #' @importFrom tidyr pivot_longer +#' @importFrom rlang warn abort inform #' #' @return [tbl_df] 2 columns: 1) process and 2) median seconds #' @@ -173,18 +179,18 @@ write_proc_medians_table <- function(dir_job_results, filepath) { tryCatch({ # Error handling for input arguments if (!is.character(dir_job_results) || length(dir_job_results) != 1) { - abort("Input 'dir_job_results' must be a single character string.", - class = "validation_error") + rlang::abort("Input 'dir_job_results' must be a single character string.", + class = "validation_error") } if (!dir.exists(dir_job_results)) { - abort(paste("The directory", dir_job_results, "does not exist."), - class = "file_error") + rlang::abort(paste("The directory", dir_job_results, "does not exist."), + class = "file_error") } if (!is.character(filepath) || length(filepath) != 1) { - abort("Input 'filepath' must be a single character string.", - class = "validation_error") + rlang::abort("Input 'filepath' must be a single character string.", + class = "validation_error") } df_proc_medians <- get_proc_medians(dir_job_results) |> tibble::as_tibble() |> @@ -199,18 +205,16 @@ write_proc_medians_table <- function(dir_job_results, filepath) { readr::write_tsv(df_proc_medians, file = filepath) return(df_proc_medians) }, error = function(e) { - abort( + rlang::abort( message = paste("Encountered an error: ", e$message), class = "processing_error", - call = sys.call(), dir_job_results = dir_job_results, filepath = filepath ) }, warning = function(w) { - warn( + rlang::warn( message = paste("Warning: ", w$message), class = "processing_warning", - call = sys.call(), dir_job_results = dir_job_results, filepath = filepath ) @@ -226,10 +230,11 @@ write_proc_medians_table <- function(dir_job_results, filepath) { #' read location. #' #' @param dir_job_results [chr] path to MolEvolvR job_results directory -#' @param filepath [chr] path to save YAML file; if NULL, +#' @param filepath [chr] path to save YAML file; if NULL, #' uses ./molevol_scripts/log_data/job_proc_weights.yml #' #' @importFrom yaml write_yaml +#' @importFrom rlang warn abort inform #' #' @examples #' \dontrun{ @@ -243,7 +248,7 @@ write_proc_medians_yml <- function(dir_job_results, filepath = NULL) { tryCatch({ # Error handling for dir_job_results arguments if (!is.character(dir_job_results) || length(dir_job_results) != 1) { - abort( + rlang::abort( message = "Input 'dir_job_results' must be a single character string.", class = "validation_error", dir_job_results = dir_job_results @@ -251,7 +256,7 @@ write_proc_medians_yml <- function(dir_job_results, filepath = NULL) { } if (!dir.exists(dir_job_results)) { - abort( + rlang::abort( message = paste("The directory", dir_job_results, "does not exist."), class = "file_error", dir_job_results = dir_job_results @@ -265,7 +270,7 @@ write_proc_medians_yml <- function(dir_job_results, filepath = NULL) { "job_proc_weights.yml") } if (!is.character(filepath) || length(filepath) != 1) { - abort( + rlang::abort( message = "Input 'filepath' must be a single character string.", class = "validation_error", filepath = filepath @@ -275,18 +280,16 @@ write_proc_medians_yml <- function(dir_job_results, filepath = NULL) { medians <- get_proc_medians(dir_job_results) yaml::write_yaml(medians, filepath) }, error = function(e) { - abort( + rlang::abort( message = paste("Encountered an error: ", e$message), class = "processing_error", - call = sys.call(), dir_job_results = dir_job_results, filepath = filepath ) }, warning = function(w) { - warn( + rlang::warn( message = paste("Warning: ", w$message), class = "processing_warning", - call = sys.call(), dir_job_results = dir_job_results, filepath = filepath ) @@ -300,6 +303,7 @@ write_proc_medians_yml <- function(dir_job_results, filepath = NULL) { #' #' @importFrom stringr str_glue str_trim #' @importFrom yaml read_yaml +#' @importFrom rlang warn abort inform #' #' @return [list] names: processes; values: median runtime (seconds) #' @@ -317,9 +321,9 @@ get_proc_weights <- function(medians_yml_path = NULL) { # attempt to read the weights from the YAML file produced by # write_proc_medians_yml() if (stringr::str_trim(medians_yml_path) == "") { - abort( - message = stringr::str_glue("medians_yml_path is empty - ({medians_yml_path}), returning default weights"), + rlang::abort( + message = stringr::str_glue("medians_yml_path is empty + ({medians_yml_path}), returning default weights"), class = "input_error", medians_yml_path = medians_yml_path ) @@ -328,7 +332,7 @@ get_proc_weights <- function(medians_yml_path = NULL) { proc_weights <- yaml::read_yaml(medians_yml_path) if (!is.list(proc_weights) || length(proc_weights) == 0) { - abort( + rlang::abort( message = "The loaded YAML file does not contain valid process weights.", class = "file_error", @@ -364,6 +368,7 @@ get_proc_weights <- function(medians_yml_path = NULL) { #' #' @importFrom dplyr if_else #' @importFrom stringr str_glue +#' @importFrom rlang warn abort inform #' #' @return total estimated number of seconds a job will process (walltime) #' @@ -383,7 +388,7 @@ advanced_opts2est_walltime <- function(advanced_opts, n_inputs = 1L, # Validate advanced_opts if (!is.character(advanced_opts)) { - abort( + rlang::abort( message = "Argument 'advanced_opts' must be a character vector.", class = "validation_error", advanced_opts = advanced_opts @@ -392,8 +397,8 @@ advanced_opts2est_walltime <- function(advanced_opts, n_inputs = 1L, # Validate n_inputs if (!is.numeric(n_inputs) || length(n_inputs) != 1 || n_inputs <= 0) { - abort( - message = "Argument 'n_inputs' + rlang::abort( + message = "Argument 'n_inputs' must be a single positive numeric value.", class = "validation_error", n_inputs = n_inputs @@ -404,8 +409,8 @@ advanced_opts2est_walltime <- function(advanced_opts, n_inputs = 1L, if ("homology_search" %in% advanced_opts && (is.null(n_hits) || !is.numeric(n_hits) || length(n_hits) != 1 || n_hits < 0)) { - abort( - message = "Argument 'n_hits' must be a single non-negative numeric + rlang::abort( + message = "Argument 'n_hits' must be a single non-negative numeric value when 'homology_search' is in 'advanced_opts'.", class = "validation_error", n_hits = n_hits @@ -415,7 +420,7 @@ advanced_opts2est_walltime <- function(advanced_opts, n_inputs = 1L, # Get process weights proc_weights <- write_proc_medians_yml() if (!is.list(proc_weights)) { - abort( + rlang::abort( message = "Process weights could not be retrieved correctly.", class = "processing_error" ) @@ -437,9 +442,9 @@ advanced_opts2est_walltime <- function(advanced_opts, n_inputs = 1L, opts2procs <- make_opts2procs() # exclude the homology search processes for the homologous hits procs2exclude_for_homologs <- opts2procs[["homology_search"]] - procs_homologs <- procs_from_opts[!(procs_from_opts + procs_homologs <- procs_from_opts[!(procs_from_opts %in% procs2exclude_for_homologs)] - binary_proc_vec_homolog <- dplyr::if_else(all_procs + binary_proc_vec_homolog <- dplyr::if_else(all_procs %in% procs_homologs, 1L, 0L) # add the estimated walltime for processes run on the homologous hits est_walltime <- est_walltime + @@ -457,19 +462,17 @@ advanced_opts2est_walltime <- function(advanced_opts, n_inputs = 1L, } return(est_walltime) }, error = function(e) { - abort( + rlang::abort( message = paste("Encountered an error: ", e$message), class = "processing_error", - call = sys.call(), advanced_opts = advanced_opts, n_inputs = n_inputs, n_hits = n_hits ) }, warning = function(w) { - warn( + rlang::warn( message = paste("Warning: ", w$message), class = "processing_warning", - call = sys.call(), advanced_opts = advanced_opts, n_inputs = n_inputs, n_hits = n_hits @@ -486,6 +489,8 @@ advanced_opts2est_walltime <- function(advanced_opts, n_inputs = 1L, #' @param t_long threshold value that defines the lower bound for assigning a #' job to the "long queue" #' +#' @importFrom rlang warn abort inform +#' #' @return a string of "short" or "long" #' #' example: @@ -500,7 +505,7 @@ assign_job_queue <- function( tryCatch({ # Validate t_sec_estimate if (!is.numeric(t_sec_estimate) || length(t_sec_estimate) != 1) { - abort( + rlang::abort( message = "Argument 't_sec_estimate' must be a single numeric value.", class = "validation_error", t_sec_estimate = t_sec_estimate @@ -509,8 +514,8 @@ assign_job_queue <- function( # Validate t_cutoff if (!is.numeric(t_cutoff) || length(t_cutoff) != 1 || t_cutoff < 0) { - abort( - message = "Argument 't_cutoff' must be a + rlang::abort( + message = "Argument 't_cutoff' must be a single non-negative numeric value.", class = "validation_error", t_cutoff = t_cutoff @@ -521,18 +526,16 @@ assign_job_queue <- function( queue <- ifelse(t_sec_estimate > t_cutoff, "long", "short") return(queue) }, error = function(e) { - abort( + rlang::abort( message = paste("Encountered an error: ", e$message), class = "processing_error", - call = sys.call(), t_sec_estimate = t_sec_estimate, t_cutoff = t_cutoff ) }, warning = function(w) { - warn( + rlang::warn( message = paste("Warning: ", w$message), class = "processing_warning", - call = sys.call(), t_sec_estimate = t_sec_estimate, t_cutoff = t_cutoff ) @@ -548,6 +551,7 @@ assign_job_queue <- function( #' @importFrom dplyr mutate select #' @importFrom ggplot2 aes geom_line ggplot labs #' @importFrom tibble as_tibble +#' @importFrom rlang warn abort inform #' #' @return line plot object #' @@ -581,8 +585,8 @@ plot_estimated_walltimes <- function() { n_hits <- if ("homology_search" %in% advanced_opts) { 100 } else { - NULL - } + NULL + } est_walltime <- advanced_opts2est_walltime ( advanced_opts, n_inputs = i, @@ -627,8 +631,8 @@ plot_estimated_walltimes <- function() { # sec to hrs df_walltimes <- df_walltimes |> dplyr::mutate(est_walltime = est_walltime / 3600) - p <- ggplot2::ggplot(df_walltimes, ggplot2::aes(x = n_inputs, - y = est_walltime, + p <- ggplot2::ggplot(df_walltimes, ggplot2::aes(x = n_inputs, + y = est_walltime, color = advanced_opts)) + ggplot2::geom_line() + ggplot2::labs( @@ -638,12 +642,12 @@ plot_estimated_walltimes <- function() { ) return(p) }, error = function(e) { - abort( + rlang::abort( message = paste("Encountered an error:", e$message), .internal = TRUE ) }, warning = function(w) { - warn( + rlang::warn( message = paste("Warning:", w$message), .internal = TRUE ) diff --git a/R/blastWrappers.R b/R/blastWrappers.R index 15484a1b..95643e24 100755 --- a/R/blastWrappers.R +++ b/R/blastWrappers.R @@ -13,6 +13,8 @@ #' @param num_alignments #' @param num_threads #' +#' @importFrom rlang warn abort inform +#' #' @return #' @export #' @@ -23,23 +25,25 @@ run_deltablast <- function(deltablast_path, db_search_path, # Argument validation if (!file.exists(deltablast_path)) { - stop("The DELTABLAST executable path is invalid: ", deltablast_path) + rlang::abort(paste("The DELTABLAST executable path is invalid:", + deltablast_path)) } if (!dir.exists(db_search_path)) { - stop("The database search path is invalid: ", db_search_path) + rlang::abort(paste("The database search path is invalid:", db_search_path)) } if (!file.exists(query)) { - stop("The query file path is invalid: ", query) + rlang::abort(paste("The query file path is invalid:", query)) } if (!is.numeric(as.numeric(evalue)) || as.numeric(evalue) <= 0) { - stop("The evalue must be a positive number: ", evalue) + rlang::abort(paste("The evalue must be a positive number:", evalue)) } if (!is.numeric(num_alignments) || num_alignments <= 0) { - stop("The number of alignments must be a - positive integer: ", num_alignments) + rlang::abort(paste("The number of alignments must be a positive integer:", + num_alignments)) } if (!is.numeric(num_threads) || num_threads <= 0) { - stop("The number of threads must be a positive integer: ", num_threads) + rlang::abort(paste("The number of threads must be a positive integer:", + num_threads)) } start <- Sys.time() @@ -61,13 +65,28 @@ run_deltablast <- function(deltablast_path, db_search_path, ) print(Sys.time() - start) }, error = function(e) { - message(paste("Error in run_deltablast: ", e)) + rlang::abort( + message = paste("Error in run_deltablast:", e$message), + class = "processing_error", + deltablast_path = deltablast_path, + db_search_path = db_search_path, + query = query, + out = out, + num_alignments = num_alignments, + num_threads = num_threads + ) }, warning = function(w) { - message(paste("Warning in run_deltablast: ", w)) - }, finally = { - message("run_deltablast completed") + rlang::warn( + message = paste("Warning in run_deltablast:", w$message), + class = "processing_warning", + deltablast_path = deltablast_path, + db_search_path = db_search_path, + query = query, + out = out, + num_alignments = num_alignments, + num_threads = num_threads + ) }) - } @@ -81,6 +100,8 @@ run_deltablast <- function(deltablast_path, db_search_path, #' @param out #' @param num_threads #' +#' @importFrom rlang warn abort inform +#' #' @return #' @export #' @@ -90,19 +111,26 @@ run_rpsblast <- function(rpsblast_path, db_search_path, out, num_threads = 1) { # Argument validation if (!file.exists(rpsblast_path)) { - stop("The RPSBLAST executable path is invalid: ", rpsblast_path) + rlang::abort(paste("The RPSBLAST executable path is invalid:", + rpsblast_path), + class = "file_error") } if (!dir.exists(db_search_path)) { - stop("The database search path is invalid: ", db_search_path) + rlang::abort(paste("The database search path is invalid:", db_search_path), + class = "file_error") } if (!file.exists(query)) { - stop("The query file path is invalid: ", query) + rlang::abort(paste("The query file path is invalid:", query), + class = "file_error") } if (!is.numeric(as.numeric(evalue)) || as.numeric(evalue) <= 0) { - stop("The evalue must be a positive number: ", evalue) + rlang::abort(paste("The evalue must be a positive number:", evalue), + class = "validation_error") } if (!is.numeric(num_threads) || num_threads <= 0) { - stop("The number of threads must be a positive integer: ", num_threads) + rlang::abort(paste("The number of threads must be a positive integer:", + num_threads), + class = "validation_error") } start <- Sys.time() @@ -123,11 +151,25 @@ run_rpsblast <- function(rpsblast_path, db_search_path, ) print(Sys.time() - start) }, error = function(e) { - message(paste("Error in run_rpsblast: ", e)) + rlang::abort( + message = paste("Error in run_rpsblast:", e$message), + class = "processing_error", + rpsblast_path = rpsblast_path, + db_search_path = db_search_path, + query = query, + out = out, + num_threads = num_threads + ) }, warning = function(w) { - message(paste("Warning in run_rpsblast: ", w)) - }, finally = { - message("run_rpsblast completed") + rlang::warn( + message = paste("Warning in run_rpsblast:", w$message), + class = "processing_warning", + rpsblast_path = rpsblast_path, + db_search_path = db_search_path, + query = query, + out = out, + num_threads = num_threads + ) }) } From 6632fe4cc4a26451c17831ef25a5a03fa182bb81 Mon Sep 17 00:00:00 2001 From: David Mayer Date: Tue, 22 Oct 2024 16:01:06 -0600 Subject: [PATCH 12/24] replace rd --- man/acc2FA.Rd | 31 +++++++++++++++---------------- man/acc2fa.Rd | 38 -------------------------------------- 2 files changed, 15 insertions(+), 54 deletions(-) delete mode 100644 man/acc2fa.Rd diff --git a/man/acc2FA.Rd b/man/acc2FA.Rd index 6c6ea43c..517ee3d6 100644 --- a/man/acc2FA.Rd +++ b/man/acc2FA.Rd @@ -1,35 +1,34 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/CHANGED-pre-msa-tree.R -\name{acc2FA} -\alias{acc2FA} -\title{acc2FA converts protein accession numbers to a fasta format.} +% Please edit documentation in R/pre-msa-tree.R +\name{acc2fa} +\alias{acc2fa} +\title{acc2fa} \usage{ -acc2FA(accessions, outpath, plan = "sequential") +acc2fa(accessions, outpath, plan = "sequential") } \arguments{ \item{accessions}{Character vector containing protein accession numbers to -generate fasta sequences for. -Function may not work for vectors of length > 10,000} +generate fasta sequences for. Function may not work for vectors of +length > 10,000} -\item{outpath}{\link{str} Location where fasta file should be written to.} +\item{outpath}{\link{str}. Location where fasta file should be written to.} -\item{plan}{Character string specifying the parallel processing strategy to -use with the \code{future} package. Default is "sequential".} +\item{plan}{Character. The plan to use for processing. Default is "sequential".} } \value{ -A logical value indicating whether the retrieval and conversion were -successful. Returns \code{TRUE} if successful and \code{FALSE} otherwise. +A Fasta file is written to the specified \code{outpath}. } \description{ +acc2fa converts protein accession numbers to a fasta format. Resulting fasta file is written to the outpath. } \examples{ \dontrun{ -acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), +acc2fa(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), outpath = "my_proteins.fasta") -Entrez:accessions <- rep("ANY95992.1", 201) |> acc2FA(outpath = "entrez.fa") -EBI:accessions <- c("P12345", "Q9UHC1", -"O15530", "Q14624", "P0DTD1") |> acc2FA(outpath = "ebi.fa") +Entrez:accessions <- rep("ANY95992.1", 201) |> acc2fa(outpath = "entrez.fa") +EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> +acc2fa(outpath = "ebi.fa") } } \author{ diff --git a/man/acc2fa.Rd b/man/acc2fa.Rd deleted file mode 100644 index 517ee3d6..00000000 --- a/man/acc2fa.Rd +++ /dev/null @@ -1,38 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/pre-msa-tree.R -\name{acc2fa} -\alias{acc2fa} -\title{acc2fa} -\usage{ -acc2fa(accessions, outpath, plan = "sequential") -} -\arguments{ -\item{accessions}{Character vector containing protein accession numbers to -generate fasta sequences for. Function may not work for vectors of -length > 10,000} - -\item{outpath}{\link{str}. Location where fasta file should be written to.} - -\item{plan}{Character. The plan to use for processing. Default is "sequential".} -} -\value{ -A Fasta file is written to the specified \code{outpath}. -} -\description{ -acc2fa converts protein accession numbers to a fasta format. -Resulting fasta file is written to the outpath. -} -\examples{ -\dontrun{ -acc2fa(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), -outpath = "my_proteins.fasta") -Entrez:accessions <- rep("ANY95992.1", 201) |> acc2fa(outpath = "entrez.fa") -EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> -acc2fa(outpath = "ebi.fa") -} -} -\author{ -Samuel Chen, Janani Ravi -} -\keyword{accnum,} -\keyword{fasta} From 5bedeee27a7fbd20eb17847bc1e4833d09f9d439 Mon Sep 17 00:00:00 2001 From: David Mayer Date: Thu, 24 Oct 2024 13:45:02 -0600 Subject: [PATCH 13/24] update .Rd --- man/generateAllAlignments2FA.Rd | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/man/generateAllAlignments2FA.Rd b/man/generateAllAlignments2FA.Rd index 5babd22d..421d8cf7 100644 --- a/man/generateAllAlignments2FA.Rd +++ b/man/generateAllAlignments2FA.Rd @@ -22,18 +22,21 @@ generateAllAlignments2FA( \item{aln_path}{Character. Path to alignment files. Default is 'here("data/rawdata_aln/")'} -\item{fa_outpath}{Character. Path to the written fasta file. -Default is 'here("data/alns/")'.} - -\item{lin_file}{Character. Path to file. Master protein file with AccNum & +\item{fa_outpath}{Character. Path to file. Master protein file with AccNum & lineages. Default is 'here("data/rawdata_tsv/all_semiclean.txt")'} +\item{lin_file}{Character. Path to the written fasta file. +Default is 'here("data/alns/")'.} + \item{reduced}{Boolean. If TRUE, the fasta file will contain only one sequence per lineage. Default is 'FALSE'.} } \value{ +NULL. The function saves the output FASTA files to the specified +directory. + NULL. The function saves the output FASTA files to the specified directory. } @@ -47,6 +50,12 @@ Adding Leaves to an alignment file w/ accessions Adding Leaves to all alignment files w/ accessions & DAs? } \details{ +The alignment files would need two columns separated by spaces: +\enumerate{ +\item AccNum and 2. alignment. The protein homolog file should have AccNum, +Species, Lineages. +} + The alignment files would need two columns separated by spaces: \enumerate{ \item AccNum and 2. alignment. The protein homolog file should have AccNum, @@ -54,6 +63,9 @@ Species, Lineages. } } \note{ +Please refer to the source code if you have alternate + file formats +and/or column names. + Please refer to the source code if you have alternate + file formats and/or column names. } @@ -64,12 +76,6 @@ generateAllAlignments2FA() \dontrun{ generateAllAlignments2FA() } -\dontrun{ -generateAllAlignments2FA() -} -} -\author{ -Janani Ravi } \keyword{accnum,} \keyword{alignment,} From cb76c69eba5586c255834a370bc7ffa035700b8c Mon Sep 17 00:00:00 2001 From: Awa Synthia Date: Sat, 26 Oct 2024 12:40:34 +0300 Subject: [PATCH 14/24] change 'print(results)' to 'results' for brevity and to avoid potential issues Signed-off-by: Awa Synthia --- R/CHANGED-pre-msa-tree.R | 77 +++++++++-------- R/blastWrappers.R | 17 ++-- R/fa2domain.R | 10 +-- R/ipr2viz.R | 98 ++++++++++----------- R/lineage.R | 78 ++++++++--------- R/plotme.R | 6 +- R/plotting.R | 138 +++++++++++++++--------------- R/pre-msa-tree.R | 74 ++++++++-------- R/reverse_operons.R | 16 ++-- man/acc2FA.Rd | 8 +- man/addName.Rd | 2 +- man/addTaxID.Rd | 2 +- man/alignFasta.Rd | 6 +- man/convert2TitleCase.Rd | 4 +- man/createRepresentativeAccNum.Rd | 9 +- man/downloadAssemblySummary.Rd | 2 +- man/getAccNumFromFA.Rd | 5 +- man/getTopAccByLinDomArch.Rd | 4 +- man/mapAcc2Name.Rd | 4 +- man/plotIPR2Viz.Rd | 18 ++-- man/plotIPR2VizWeb.Rd | 18 ++-- man/plotLineageSunburst.Rd | 2 +- man/prepareColumnParams.Rd | 2 +- man/prepareSingleColumnParams.Rd | 2 +- man/proteinAcc2TaxID.Rd | 4 +- man/renameFA.Rd | 2 +- man/rename_fasta.Rd | 2 +- man/reverseOperonSeq.Rd | 2 +- man/runDeltaBlast.Rd | 11 ++- man/runIPRScan.Rd | 2 +- man/shortenLineage.Rd | 4 +- man/writeMSA_AA2FA.Rd | 3 + 32 files changed, 329 insertions(+), 303 deletions(-) diff --git a/R/CHANGED-pre-msa-tree.R b/R/CHANGED-pre-msa-tree.R index 40bd672e..48d1abf9 100644 --- a/R/CHANGED-pre-msa-tree.R +++ b/R/CHANGED-pre-msa-tree.R @@ -47,7 +47,7 @@ api_key <- Sys.getenv("ENTREZ_API_KEY", unset = "YOUR_KEY_HERE") #' @examples #' # Convert a single string to title case #' convert2TitleCase("hello world") # Returns "Hello World" -#' +#' convert2TitleCase <- function(x, y = " ") { s <- strsplit(x, y)[[1]] paste(toupper(substring(s, 1, 1)), substring(s, 2), @@ -80,7 +80,7 @@ convert2TitleCase <- function(x, y = " ") { #' @importFrom stringr str_sub #' @importFrom tidyr replace_na separate #' -#' @return A data frame containing the enriched alignment data with lineage +#' @return A data frame containing the enriched alignment data with lineage #' information. #' #' @details The alignment file would need two columns: 1. accession + @@ -215,7 +215,7 @@ addLeaves2Alignment <- function(aln_file = "", #' Lineage = c("Eukaryota>Chordata", "Eukaryota>Chordata") #' ) #' enriched_data <- addName(data) -#' print(enriched_data) +#' enriched_data addName <- function(data, accnum_col = "AccNum", spec_col = "Species", lin_col = "Lineage", lin_sep = ">", out_col = "Name") { @@ -292,7 +292,7 @@ addName <- function(data, #' file formats and/or column names. #' #' @return A character string representing the FASTA formatted sequences. -#' If `fa_outpath` is provided, the FASTA will also be saved to the specified +#' If `fa_outpath` is provided, the FASTA will also be saved to the specified #' file. #' @export #' @@ -336,22 +336,22 @@ convertAlignment2FA <- function(aln_file = "", } #' mapAcc2Name -#' +#' #' @description #' Default renameFA() replacement function. Maps an accession number to its name #' #' @param line The line of a fasta file starting with '>' -#' @param acc2name Data Table containing a column of accession numbers and a +#' @param acc2name Data Table containing a column of accession numbers and a #' name column #' @param acc_col Name of the column containing Accession numbers -#' @param name_col Name of the column containing the names that the accession +#' @param name_col Name of the column containing the names that the accession #' numbers #' are mapped to #' #' @importFrom dplyr filter pull #' @importFrom rlang sym #' -#' @return A character string representing the updated FASTA line, where the +#' @return A character string representing the updated FASTA line, where the #' accession number is replaced with its corresponding name. #' @export #' @@ -389,7 +389,7 @@ mapAcc2Name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") { #' #' @examples #' \dontrun{ -#' renameFA("path/to/input.fasta", +#' renameFA("path/to/input.fasta", #' "path/to/output.fasta", mapAcc2Name, acc2name) #' } renameFA <- function(fa_path, outpath, @@ -411,8 +411,8 @@ renameFA <- function(fa_path, outpath, ################################ ## generateAllAlignments2FA #' generateAllAlignments2FA -#' -#' @description +#' +#' @description #' Adding Leaves to an alignment file w/ accessions #' #' @keywords alignment, accnum, leaves, lineage, species @@ -420,25 +420,25 @@ renameFA <- function(fa_path, outpath, #' #' @param aln_path Character. Path to alignment files. #' Default is 'here("data/rawdata_aln/")' -#' @param fa_outpath Character. Path to file. Master protein file with AccNum & +#' @param fa_outpath Character. Path to file. Master protein file with AccNum & #' lineages. #' Default is 'here("data/rawdata_tsv/all_semiclean.txt")' #' @param lin_file Character. Path to the written fasta file. #' Default is 'here("data/alns/")'. -#' @param reduced Boolean. If TRUE, the fasta file will contain only one +#' @param reduced Boolean. If TRUE, the fasta file will contain only one #' sequence per lineage. #' Default is 'FALSE'. #' #' @importFrom purrr pmap #' @importFrom stringr str_replace_all #' -#' @return NULL. The function saves the output FASTA files to the specified +#' @return NULL. The function saves the output FASTA files to the specified #' directory. #' -#' @details The alignment files would need two columns separated by spaces: -#' 1. AccNum and 2. alignment. The protein homolog file should have AccNum, +#' @details The alignment files would need two columns separated by spaces: +#' 1. AccNum and 2. alignment. The protein homolog file should have AccNum, #' Species, Lineages. -#' @note Please refer to the source code if you have alternate + file formats +#' @note Please refer to the source code if you have alternate + file formats #' and/or column names. #' #' @export @@ -478,20 +478,20 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), # accessions <- c("P12345","Q9UHC1","O15530","Q14624","P0DTD1") # accessions <- rep("ANY95992.1", 201) -#' acc2FA +#' acc2FA #' #' @description -#' converts protein accession numbers to a fasta format. Resulting +#' converts protein accession numbers to a fasta format. Resulting #' fasta file is written to the outpath. #' #' @author Samuel Chen, Janani Ravi #' @keywords accnum, fasta #' -#' @param accessions Character vector containing protein accession numbers to +#' @param accessions Character vector containing protein accession numbers to #' generate fasta sequences for. #' Function may not work for vectors of length > 10,000 #' @param outpath [str] Location where fasta file should be written to. -#' @param plan Character string specifying the parallel processing strategy to +#' @param plan Character string specifying the parallel processing strategy to #' use with the `future` package. Default is "sequential". #' #' @importFrom Biostrings readAAStringSet @@ -499,16 +499,16 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), #' @importFrom purrr map #' @importFrom rentrez entrez_fetch #' -#' @return A logical value indicating whether the retrieval and conversion were +#' @return A logical value indicating whether the retrieval and conversion were #' successful. Returns `TRUE` if successful and `FALSE` otherwise. #' @export #' #' @examples #' \dontrun{ -#' acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), +#' acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), #' outpath = "my_proteins.fasta") #' Entrez:accessions <- rep("ANY95992.1", 201) |> acc2FA(outpath = "entrez.fa") -#' EBI:accessions <- c("P12345", "Q9UHC1", +#' EBI:accessions <- c("P12345", "Q9UHC1", #' "O15530", "Q14624", "P0DTD1") |> acc2FA(outpath = "ebi.fa") #' } acc2FA <- function(accessions, outpath, plan = "sequential") { @@ -583,9 +583,9 @@ acc2FA <- function(accessions, outpath, plan = "sequential") { } #' createRepresentativeAccNum -#' +#' #' @description -#' Function to generate a vector of one Accession number per distinct +#' Function to generate a vector of one Accession number per distinct #' observation from 'reduced' column #' #' @author Samuel Chen, Janani Ravi @@ -599,15 +599,18 @@ acc2FA <- function(accessions, outpath, plan = "sequential") { #' @importFrom dplyr filter pull #' @importFrom rlang sym #' -#' @return A character vector containing one Accession number per distinct +#' @return A character vector containing one Accession number per distinct #' observation from the specified reduced column. #' @export #' #' @examples +#' \dontrun{ +#' createRepresentativeAccNum(prot) +#' } createRepresentativeAccNum <- function(prot_data, reduced = "Lineage", accnum_col = "AccNum") { - # Get Unique reduced column and then bind the AccNums back to get one + # Get Unique reduced column and then bind the AccNums back to get one # AccNum per reduced column reduced_sym <- sym(reduced) accnum_sym <- sym(accnum_col) @@ -635,16 +638,16 @@ createRepresentativeAccNum <- function(prot_data, } #' alignFasta -#' +#' #' @description #' Perform a Multiple Sequence Alignment on a FASTA file. #' #' @author Samuel Chen, Janani Ravi #' #' @param fasta_file Path to the FASTA file to be aligned -#' @param tool Type of alignment tool to use. One of three options: "Muscle", +#' @param tool Type of alignment tool to use. One of three options: "Muscle", #' "ClustalO", or "ClustalW" -#' @param outpath Path to write the resulting alignment to as a FASTA file. +#' @param outpath Path to write the resulting alignment to as a FASTA file. #' If NULL, no file is written #' #' @importFrom Biostrings readAAStringSet @@ -655,7 +658,7 @@ createRepresentativeAccNum <- function(prot_data, #' #' @examples #' \dontrun{ -#' aligned_sequences <- alignFasta("my_sequences.fasta", +#' aligned_sequences <- alignFasta("my_sequences.fasta", #' tool = "Muscle", outpath = "aligned_output.fasta") #' } alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { @@ -690,7 +693,10 @@ alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { #' @export #' #' @examples -writeMSA_AA2FA <- function(alignment, outpath) { +#' \dontrun{ +#' writeMSA_AA2FA("my_sequences.fasta", outpath = "aligned_output.fasta") +#' } +writeMSA_AA2FA <- function(writeMSA_AA2FA, outpath) { l <- length(rownames(alignment)) fasta <- "" for (i in 1:l) @@ -705,7 +711,7 @@ writeMSA_AA2FA <- function(alignment, outpath) { #' getAccNumFromFA #' -#' @param fasta_file Character. The path to the FASTA file from which +#' @param fasta_file Character. The path to the FASTA file from which #' accession numbers will be extracted. #' #' @importFrom stringi stri_extract_all_regex @@ -714,6 +720,9 @@ writeMSA_AA2FA <- function(alignment, outpath) { #' @export #' #' @examples +#' \dontrun{ +#' getAccNumFromFA("my_sequences.fasta") +#' } getAccNumFromFA <- function(fasta_file) { txt <- read_file(fasta_file) accnums <- stringi::stri_extract_all_regex(fasta_file, "(?<=>)[\\w,.]+")[[1]] diff --git a/R/blastWrappers.R b/R/blastWrappers.R index d89f9b95..3c9c4192 100755 --- a/R/blastWrappers.R +++ b/R/blastWrappers.R @@ -4,8 +4,8 @@ #' #' @author Samuel Chen, Janani Ravi #' @description -#' This function executes a Delta-BLAST search using the specified parameters -#' and database. It sets the BLAST database path, runs the Delta-BLAST command +#' This function executes a Delta-BLAST search using the specified parameters +#' and database. It sets the BLAST database path, runs the Delta-BLAST command #' with the given query, and outputs the results. #' #' @param deltablast_path Path to the Delta-BLAST executable. @@ -17,12 +17,15 @@ #' @param num_alignments Number of alignments to report. #' @param num_threads Number of threads to use for the search (default is 1). #' -#' @return This function does not return a value; it outputs results to the +#' @return This function does not return a value; it outputs results to the #' specified file. #' @export #' #' @examples -runDeltaBlast <- function(deltablast_path, db_search_path, +#' \dontrun{ +#' runDeltaBlast(runDeltaBlast, db_search_path) +#' } +runDeltaBlast <- function(runDeltaBlast, db_search_path, db = "refseq", query, evalue = "1e-5", out, num_alignments, num_threads = 1) { start <- Sys.time() @@ -49,8 +52,8 @@ runDeltaBlast <- function(deltablast_path, db_search_path, #' Run RPSBLAST to generate domain architectures for proteins of interest #' #' @description -#' This function executes an RPS-BLAST search to generate domain architectures -#' for specified proteins. It sets the BLAST database path, runs the RPS-BLAST +#' This function executes an RPS-BLAST search to generate domain architectures +#' for specified proteins. It sets the BLAST database path, runs the RPS-BLAST #' command with the provided query, and outputs the results. #' #' @param rpsblast_path Path to the RPS-BLAST executable. @@ -61,7 +64,7 @@ runDeltaBlast <- function(deltablast_path, db_search_path, #' @param out Path to the output file where results will be saved. #' @param num_threads Number of threads to use for the search (default is 1). #' -#' @return This function does not return a value; it outputs results to the +#' @return This function does not return a value; it outputs results to the #' specified file. #' @export #' diff --git a/R/fa2domain.R b/R/fa2domain.R index 29803b85..f53322ca 100644 --- a/R/fa2domain.R +++ b/R/fa2domain.R @@ -5,18 +5,18 @@ # interproscan CLI will return a completely empty file (0Bytes) #' runIPRScan -#' -#' Run InterProScan on a given FASTA file and save the results to an +#' +#' Run InterProScan on a given FASTA file and save the results to an #' output file. #' #' @param filepath_fasta A string representing the path to the input FASTA file. #' @param filepath_out A string representing the base path for the output file. -#' @param appl A character vector specifying the InterProScan applications to +#' @param appl A character vector specifying the InterProScan applications to #' use (e.g., "Pfam", "Gene3D"). Default is `c("Pfam", "Gene3D")`. #' #' @importFrom stringr str_glue #' -#' @return A data frame containing the results from the InterProScan output +#' @return A data frame containing the results from the InterProScan output #' TSV file. #' #' @examples @@ -26,7 +26,7 @@ #' filepath_out = "path/to/output_file", #' appl = c("Pfam", "Gene3D") #' ) -#' print(results) +#' results #' } runIPRScan <- function( filepath_fasta, diff --git a/R/ipr2viz.R b/R/ipr2viz.R index c976276d..e582ab09 100644 --- a/R/ipr2viz.R +++ b/R/ipr2viz.R @@ -23,7 +23,7 @@ #' @export #' @examples #' library(ggplot2) -#' +#' #' # Create a sample plot using the custom theme #' ggplot(mtcars, aes(x = wt, y = mpg)) + #' geom_point() + @@ -51,15 +51,15 @@ themeGenes2 <- function() { #' getTopAccByLinDomArch #' @description Group by lineage + DA then take top 20 #' -#' @param infile_full A data frame containing the full dataset with lineage and +#' @param infile_full A data frame containing the full dataset with lineage and #' domain architecture information. -#' @param DA_col A string representing the name of the domain architecture +#' @param DA_col A string representing the name of the domain architecture #' column. Default is "DomArch.Pfam". -#' @param lin_col A string representing the name of the lineage column. +#' @param lin_col A string representing the name of the lineage column. #' Default is "Lineage_short". -#' @param n An integer specifying the number of top accession numbers to return. +#' @param n An integer specifying the number of top accession numbers to return. #' Default is 20. -#' @param query A string for filtering a specific query name. If it is not +#' @param query A string for filtering a specific query name. If it is not #' "All", only the data matching this query will be processed. #' #' @importFrom dplyr arrange filter group_by select summarise @@ -68,14 +68,14 @@ themeGenes2 <- function() { #' @importFrom rlang sym #' @importFrom rlang .data #' -#' @return A vector of the top N accession numbers (`AccNum`) based on counts +#' @return A vector of the top N accession numbers (`AccNum`) based on counts #' grouped by lineage and domain architecture. #' @export #' #' @examples #' \dontrun{ -#' top_accessions <- getTopAccByLinDomArch(infile_full = my_data, -#' DA_col = "DomArch.Pfam", lin_col = "Lineage_short", +#' top_accessions <- getTopAccByLinDomArch(infile_full = my_data, +#' DA_col = "DomArch.Pfam", lin_col = "Lineage_short", #' n = 20, query = "specific_query_name") #' } getTopAccByLinDomArch <- function(infile_full, @@ -113,26 +113,26 @@ getTopAccByLinDomArch <- function(infile_full, ############################################# #' plotIPR2Viz #' -#' @param infile_ipr A path to the input IPR file (TSV format) containing +#' @param infile_ipr A path to the input IPR file (TSV format) containing #' domain information. -#' @param infile_full A path to the full input file (TSV format) containing +#' @param infile_full A path to the full input file (TSV format) containing #' lineage and accession information. -#' @param accessions A character vector of accession numbers to filter the +#' @param accessions A character vector of accession numbers to filter the #' analysis. Default is an empty vector. -#' @param analysis A character vector specifying the types of analysis to -#' include (e.g., "Pfam", "Phobius", "TMHMM", "Gene3D"). Default is a +#' @param analysis A character vector specifying the types of analysis to +#' include (e.g., "Pfam", "Phobius", "TMHMM", "Gene3D"). Default is a #' vector of these analyses. -#' @param group_by A string specifying how to group the visualization. +#' @param group_by A string specifying how to group the visualization. #' Default is "Analysis". Options include "Analysis" or "Query". -#' @param topn An integer specifying the number of top accessions to visualize. +#' @param topn An integer specifying the number of top accessions to visualize. #' Default is 20. -#' @param name A string representing the name to use for y-axis labels. +#' @param name A string representing the name to use for y-axis labels. #' Default is "Name". -#' @param text_size An integer specifying the text size for the plot. +#' @param text_size An integer specifying the text size for the plot. #' Default is 15. -#' @param query A string for filtering a specific query name. If it is not +#' @param query A string for filtering a specific query name. If it is not #' "All", only the data matching this query will be processed. -#' +#' #' @importFrom dplyr distinct filter select #' @importFrom gggenes geom_gene_arrow geom_subgene_arrow #' @importFrom ggplot2 aes aes_string as_labeller element_text facet_wrap ggplot guides margin scale_fill_manual theme theme_minimal unit ylab @@ -145,16 +145,16 @@ getTopAccByLinDomArch <- function(infile_full, #' #' @examples #' \dontrun{ -#' plot <- plotIPR2Viz(infile_ipr = "path/to/ipr_file.tsv", -#' infile_full = "path/to/full_file.tsv", -#' accessions = c("ACC123", "ACC456"), -#' analysis = c("Pfam", "TMHMM"), -#' group_by = "Analysis", -#' topn = 20, -#' name = "Gene Name", -#' text_size = 15, +#' plot <- plotIPR2Viz(infile_ipr = "path/to/ipr_file.tsv", +#' infile_full = "path/to/full_file.tsv", +#' accessions = c("ACC123", "ACC456"), +#' analysis = c("Pfam", "TMHMM"), +#' group_by = "Analysis", +#' topn = 20, +#' name = "Gene Name", +#' text_size = 15, #' query = "All") -#' print(plot) +#' plot #' } plotIPR2Viz <- function(infile_ipr = NULL, infile_full = NULL, accessions = c(), analysis = c("Pfam", "Phobius", "TMHMM", "Gene3D"), @@ -291,24 +291,24 @@ plotIPR2Viz <- function(infile_ipr = NULL, infile_full = NULL, accessions = c(), #' plotIPR2VizWeb #' -#' @param infile_ipr A path to the input IPR file (TSV format) containing +#' @param infile_ipr A path to the input IPR file (TSV format) containing #' domain information. -#' @param accessions A character vector of accession numbers to filter the +#' @param accessions A character vector of accession numbers to filter the #' analysis. -#' @param analysis A character vector specifying the types of analysis to -#' include (e.g., "Pfam", "Phobius", "TMHMM", "Gene3D"). Default is a vector +#' @param analysis A character vector specifying the types of analysis to +#' include (e.g., "Pfam", "Phobius", "TMHMM", "Gene3D"). Default is a vector #' of these analyses. -#' @param group_by A string specifying how to group the visualization. +#' @param group_by A string specifying how to group the visualization. #' Default is "Analysis". Options include "Analysis" or "Query". -#' @param name A string representing the name to use for y-axis labels. +#' @param name A string representing the name to use for y-axis labels. #' Default is "Name". -#' @param text_size An integer specifying the text size for the plot. +#' @param text_size An integer specifying the text size for the plot. #' Default is 15. -#' @param legend_name A string representing the column to use for legend labels. +#' @param legend_name A string representing the column to use for legend labels. #' Default is "ShortName". -#' @param cols An integer specifying the number of columns in the facet wrap. +#' @param cols An integer specifying the number of columns in the facet wrap. #' Default is 5. -#' @param rows An integer specifying the number of rows in the legend. +#' @param rows An integer specifying the number of rows in the legend. #' Default is 10. #' #' @importFrom dplyr arrange distinct filter select @@ -317,22 +317,22 @@ plotIPR2Viz <- function(infile_ipr = NULL, infile_full = NULL, accessions = c(), #' @importFrom readr read_tsv #' @importFrom tidyr pivot_wider #' -#' @return A ggplot object representing the domain architecture visualization +#' @return A ggplot object representing the domain architecture visualization #' for web display. #' @export #' #' @examples #' \dontrun{ -#' plot <- plotIPR2VizWeb(infile_ipr = "path/to/ipr_file.tsv", -#' accessions = c("ACC123", "ACC456"), -#' analysis = c("Pfam", "TMHMM"), -#' group_by = "Analysis", -#' name = "Gene Name", -#' text_size = 15, -#' legend_name = "ShortName", -#' cols = 5, +#' plot <- plotIPR2VizWeb(infile_ipr = "path/to/ipr_file.tsv", +#' accessions = c("ACC123", "ACC456"), +#' analysis = c("Pfam", "TMHMM"), +#' group_by = "Analysis", +#' name = "Gene Name", +#' text_size = 15, +#' legend_name = "ShortName", +#' cols = 5, #' rows = 10) -#' print(plot) +#' plot #' } plotIPR2VizWeb <- function(infile_ipr, accessions, diff --git a/R/lineage.R b/R/lineage.R index 73fa008a..46249c91 100644 --- a/R/lineage.R +++ b/R/lineage.R @@ -11,22 +11,22 @@ #' #' @author Samuel Chen, Janani Ravi #' -#' @param outpath String of path where the assembly summary file should be +#' @param outpath String of path where the assembly summary file should be #' written -#' @param keep Character vector containing which columns should be retained and +#' @param keep Character vector containing which columns should be retained and #' downloaded #' #' @importFrom data.table fwrite setnames #' @importFrom dplyr bind_rows select #' @importFrom biomartr getKingdomAssemblySummary #' -#' @return A tab-separated file containing the assembly summary. The function +#' @return A tab-separated file containing the assembly summary. The function #' does notreturn any value but writes the output directly to the specified file. #' @export #' #' @examples #' \dontrun{ -#' downloadAssemblySummary(outpath = "assembly_summary.tsv", +#' downloadAssemblySummary(outpath = "assembly_summary.tsv", #' keep = c("assembly_accession", "taxid", "organism_name")) #' } downloadAssemblySummary <- function(outpath, @@ -85,16 +85,16 @@ downloadAssemblySummary <- function(outpath, #' @param lineagelookup_path String of the path to the lineage lookup file #' (taxid to lineage mapping). This file can be generated using the #' "createLineageLookup()" function -#' @param acc_col Character. The name of the column in `prot_data` containing +#' @param acc_col Character. The name of the column in `prot_data` containing #' accession numbers. Default is "AccNum". #' #' @importFrom dplyr pull #' @importFrom data.table fread setnames #' -#' @return A dataframe containing the merged information of GCA_IDs, TaxIDs, -#' and their corresponding lineage up to the phylum level. The dataframe +#' @return A dataframe containing the merged information of GCA_IDs, TaxIDs, +#' and their corresponding lineage up to the phylum level. The dataframe #' will include information from the input `prot_data` and lineage data. -#' +#' #' @export #' #' @examples @@ -151,25 +151,25 @@ GCA2Lineage <- function(prot_data, ################################### #' addLineage #' -#' @param df Dataframe containing accession numbers. The dataframe should +#' @param df Dataframe containing accession numbers. The dataframe should #' have a column specified by `acc_col` that contains these accession numbers. -#' @param acc_col Character. The name of the column in `df` containing +#' @param acc_col Character. The name of the column in `df` containing #' accession numbers. Default is "AccNum". -#' @param assembly_path String. The path to the assembly summary file generated +#' @param assembly_path String. The path to the assembly summary file generated #' using the `downloadAssemblySummary()` function. -#' @param lineagelookup_path String. The path to the lineage lookup file (taxid +#' @param lineagelookup_path String. The path to the lineage lookup file (taxid #' to lineage mapping) generated using the `create_lineage_lookup()` function. -#' @param ipgout_path String. Optional path to save intermediate output files. +#' @param ipgout_path String. Optional path to save intermediate output files. #' Default is NULL. -#' @param plan Character. Specifies the execution plan for parallel processing. +#' @param plan Character. Specifies the execution plan for parallel processing. #' Default is "multicore". #' #' @importFrom dplyr pull #' @importFrom rlang sym #' -#' @return A dataframe that combines the original dataframe `df` with lineage +#' @return A dataframe that combines the original dataframe `df` with lineage #' information retrieved based on the provided accession numbers. -#' +#' #' @export #' #' @examples @@ -224,11 +224,11 @@ addLineage <- function(df, acc_col = "AccNum", assembly_path, #' (taxid to lineage mapping). This file can be generated using the #' @param ipgout_path Path to write the results of the efetch run of the accessions #' on the ipg database. If NULL, the file will not be written. Defaults to NULL -#' @param plan Character. Specifies the execution plan for parallel processing. +#' @param plan Character. Specifies the execution plan for parallel processing. #' Default is "multicore". #' -#' @return A dataframe containing lineage information mapped to the given protein -#' accessions. The dataframe includes relevant columns such as TaxID, GCA_ID, +#' @return A dataframe containing lineage information mapped to the given protein +#' accessions. The dataframe includes relevant columns such as TaxID, GCA_ID, #' Protein, Protein Name, Species, and Lineage. #' @export #' @@ -276,16 +276,16 @@ acc2Lineage <- function(accessions, assembly_path, lineagelookup_path, #' @param accessions Character vector containing the accession numbers to query on #' the ipg database #' @param out_path Path to write the efetch results to -#' @param plan Character. Specifies the execution plan for parallel processing. +#' @param plan Character. Specifies the execution plan for parallel processing. #' Default is "multicore". #' #' @importFrom future future plan #' @importFrom purrr map #' @importFrom rentrez entrez_fetch #' -#' @return The function does not return a value but writes the efetch results +#' @return The function does not return a value but writes the efetch results #' directly to the specified `out_path`. -#' +#' #' @export #' #' @examples @@ -363,7 +363,7 @@ efetchIPG <- function(accessions, out_path, plan = "multicore") { #' #' @importFrom data.table fread setnames #' -#' @return A data table containing protein accessions along with their +#' @return A data table containing protein accessions along with their #' corresponding TaxIDs and lineage information. #' @export #' @@ -444,14 +444,14 @@ IPG2Lineage <- function(accessions, ipg_file, #' addTaxID #' #' @param data A data frame or data table containing protein accession numbers. -#' @param acc_col A string specifying the column name in `data` that contains +#' @param acc_col A string specifying the column name in `data` that contains #' the accession numbers. Defaults to "AccNum". -#' @param version A logical indicating whether to remove the last two characters +#' @param version A logical indicating whether to remove the last two characters #' from the accession numbers for TaxID retrieval. Defaults to TRUE. #' #' @importFrom data.table as.data.table #' -#' @return A data table that includes the original data along with a new column +#' @return A data table that includes the original data along with a new column #' containing the corresponding TaxIDs. #' @export #' @@ -460,7 +460,7 @@ IPG2Lineage <- function(accessions, ipg_file, #' # Create a sample data table with accession numbers #' sample_data <- data.table(AccNum = c("ABC123.1", "XYZ456.1", "LMN789.2")) #' enriched_data <- addTaxID(sample_data, acc_col = "AccNum", version = TRUE) -#' print(enriched_data) +#' enriched_data #' } addTaxID <- function(data, acc_col = "AccNum", version = T) { if (!is.data.table(data)) { @@ -490,19 +490,19 @@ addTaxID <- function(data, acc_col = "AccNum", version = T) { ################################## #' proteinAcc2TaxID #' -#' @param accnums A character vector of protein accession numbers to be mapped +#' @param accnums A character vector of protein accession numbers to be mapped #' to TaxIDs. -#' @param suffix A string suffix used to name the output file generated by the +#' @param suffix A string suffix used to name the output file generated by the #' script. -#' @param out_path A string specifying the directory where the output file will +#' @param out_path A string specifying the directory where the output file will #' be saved. -#' @param return_dt A logical indicating whether to return the result as a data -#' table. Defaults to FALSE. If TRUE, the output file is read into a data table +#' @param return_dt A logical indicating whether to return the result as a data +#' table. Defaults to FALSE. If TRUE, the output file is read into a data table #' and returned. #' #' @importFrom data.table fread #' -#' @return If `return_dt` is TRUE, a data table containing the mapping of protein +#' @return If `return_dt` is TRUE, a data table containing the mapping of protein #' accession numbers to TaxIDs. If FALSE, the function returns NULL. #' @export #' @@ -510,9 +510,9 @@ addTaxID <- function(data, acc_col = "AccNum", version = T) { #' \dontrun{ #' # Example accession numbers #' accessions <- c("ABC123", "XYZ456", "LMN789") -#' tax_data <- proteinAcc2TaxID(accessions, suffix = "example", +#' tax_data <- proteinAcc2TaxID(accessions, suffix = "example", #' out_path = "/path/to/output", return_dt = TRUE) -#' print(tax_data) +#' tax_data #' } proteinAcc2TaxID <- function(accnums, suffix, out_path, return_dt = FALSE) { # Write accnums to a file @@ -538,17 +538,17 @@ proteinAcc2TaxID <- function(accnums, suffix, out_path, return_dt = FALSE) { #' @description Perform elink to go from protein database to taxonomy database #' and write the resulting file of taxid and lineage to out_path #' -#' @param accessions A character vector containing the accession numbers to query +#' @param accessions A character vector containing the accession numbers to query #' in the protein database. -#' @param out_path A string specifying the path where the results of the query +#' @param out_path A string specifying the path where the results of the query #' will be written. If set to NULL, a temporary directory will be used. -#' @param plan A character string that specifies the execution plan for parallel +#' @param plan A character string that specifies the execution plan for parallel #' processing. The default is "multicore". #' #' @importFrom future plan #' @importFrom purrr map #' -#' @return This function does not return a value. It writes the results to the +#' @return This function does not return a value. It writes the results to the #' specified output path. #' @export #' diff --git a/R/plotme.R b/R/plotme.R index 3527f170..3cfd54f8 100644 --- a/R/plotme.R +++ b/R/plotme.R @@ -83,7 +83,7 @@ plotTreemap <- function(count_data, fill_by_n = FALSE, sort_by_n = FALSE) { #' count_data <- data.frame(Category = c("A", "B", "C"), #' n = c(10, 20, 15)) #' params <- prepareColumnParams(count_data, fill_by_n = TRUE, sort_by_n = FALSE) -#' print(params) +#' params #' } prepareColumnParams <- function(count_data, fill_by_n, sort_by_n) { validateCountDF(count_data) @@ -128,7 +128,7 @@ prepareColumnParams <- function(count_data, fill_by_n, sort_by_n) { #' @importFrom dplyr c_across group_by mutate rowwise select summarise ungroup #' @importFrom stringr str_glue #' -#' @return A data frame containing parameters for the specified column for +#' @return A data frame containing parameters for the specified column for #' treemap visualization. #' @export #' @@ -137,7 +137,7 @@ prepareColumnParams <- function(count_data, fill_by_n, sort_by_n) { #' df <- data.frame(Category = c("A", "A", "B", "B", "C"), #' n = c(10, 20, 30, 40, 50)) #' params <- prepareSingleColumnParams(df, col_num = 1, root = "Root") -#' print(params) +#' params #' } prepareSingleColumnParams <- function(df, col_num, diff --git a/R/plotting.R b/R/plotting.R index b9a2758a..102ab6af 100644 --- a/R/plotting.R +++ b/R/plotting.R @@ -21,31 +21,31 @@ #' Shorten Lineage Names #' #' @description -#' This function abbreviates lineage names by shortening the first part of the -#' string (up to a given delimiter). +#' This function abbreviates lineage names by shortening the first part of the +#' string (up to a given delimiter). #' -#' @param data A data frame that contains a column with lineage names to be +#' @param data A data frame that contains a column with lineage names to be #' shortened. -#' @param colname Character. The name of the column in the data frame containing +#' @param colname Character. The name of the column in the data frame containing #' the lineage strings to be shortened. Default is `"Lineage"`. -#' @param abr_len Integer. The number of characters to retain after the first -#' letter. If set to 1, only the first letter of each segment before the +#' @param abr_len Integer. The number of characters to retain after the first +#' letter. If set to 1, only the first letter of each segment before the #' delimiter (`>`) is retained. Default is 1. #' #' @importFrom stringr str_locate #' @importFrom purrr pmap #' -#' @return A modified data frame where the specified lineage column has been +#' @return A modified data frame where the specified lineage column has been #' shortened. #' #' @export #' #' @examples #' \dontrun{ -#' df <- data.frame(Lineage = c("Bacteria>Firmicutes>Clostridia", +#' df <- data.frame(Lineage = c("Bacteria>Firmicutes>Clostridia", #' "Archaea>Euryarchaeota>Thermococci")) #' shortened_df <- shortenLineage(df, colname = "Lineage", abr_len = 1) -#' print(shortened_df) +#' shortened_df #' } shortenLineage <- function(data, colname = "Lineage", abr_len = 1) { abbrv <- function(x) { @@ -82,17 +82,17 @@ shortenLineage <- function(data, colname = "Lineage", abr_len = 1) { #' @param colname Column name from query_data: "DomArch.norep", "GenContext.norep", #' "DomArch.PFAM.norep" or "DomArch.LADB.norep". Default is "DomArch.norep". #' @param cutoff Numeric. Cutoff for word frequency. Default is 90. -#' @param RowsCutoff Boolean. If TRUE, applies a row cutoff to remove data rows +#' @param RowsCutoff Boolean. If TRUE, applies a row cutoff to remove data rows #' based on a certain condition. Default is FALSE. -#' @param text.scale Allows scaling of axis title, tick lables, and numbers +#' @param text.scale Allows scaling of axis title, tick lables, and numbers #' above the intersection size bars. #' text.scale can either take a universal scale in the form of an integer, #' or a vector of specific scales in the format: c(intersection size title, #' intersection size tick labels, set size title, set size tick labels, set names, #' numbers above bars) -#' @param point.size Numeric. Sets the size of points in the UpSet plot. +#' @param point.size Numeric. Sets the size of points in the UpSet plot. #' Default is 2.2. -#' @param line.size Numeric. Sets the line width in the UpSet plot. +#' @param line.size Numeric. Sets the line width in the UpSet plot. #' Default is 0.8. #' #' @importFrom dplyr across distinct filter if_else mutate pull select where @@ -100,7 +100,7 @@ shortenLineage <- function(data, colname = "Lineage", abr_len = 1) { #' @importFrom stringr str_detect str_replace_all str_split #' @importFrom UpSetR upset #' -#' @return An UpSet plot object. The plot visualizes intersections of sets based +#' @return An UpSet plot object. The plot visualizes intersections of sets based #' on the provided colname in query_data. #' @export #' @@ -251,7 +251,7 @@ plotUpSet <- function(query_data = "toast_rack.sub", #' @param colname Column name from query_data: "DomArch.norep", "GenContext.norep", #' "DomArch.PFAM.norep" or "DomArch.LADB.norep". Default is "DomArch.norep". #' @param cutoff Numeric. Cutoff for word frequency. Default is 90. -#' @param RowsCutoff Boolean. If TRUE, applies a row cutoff to remove data rows +#' @param RowsCutoff Boolean. If TRUE, applies a row cutoff to remove data rows #' based on a certain condition. Default is FALSE. #' @param color Color for the heatmap. One of six options: "default", "magma", "inferno", #' "plasma", "viridis", or "cividis" @@ -354,13 +354,13 @@ plotLineageDA <- function(query_data = "prot", #' @param query_data Data frame of protein homologs with the usual 11 columns + #' additional word columns (0/1 format). #' Default is prot (variable w/ protein data). -#' @param queries Character Vector containing the queries that will be used for +#' @param queries Character Vector containing the queries that will be used for #' the categories. -#' @param colname Character. The column used for filtering based on the `queries`. +#' @param colname Character. The column used for filtering based on the `queries`. #' Default is "ClustName". -#' @param cutoff Numeric. The cutoff value for filtering rows based on their +#' @param cutoff Numeric. The cutoff value for filtering rows based on their #' total count. Rows with values below this cutoff are excluded. -#' @param color Character. Defines the color palette used for the heatmap. +#' @param color Character. Defines the color palette used for the heatmap. #' Default is a red gradient. #' #' @importFrom dplyr arrange desc filter group_by select summarise union @@ -371,8 +371,8 @@ plotLineageDA <- function(query_data = "prot", #' @importFrom tidyr drop_na #' @importFrom viridis scale_fill_viridis #' -#' @return A ggplot object representing a heatmap (tile plot) showing the -#' relationship between queries and lineages, with the intensity of color +#' @return A ggplot object representing a heatmap (tile plot) showing the +#' relationship between queries and lineages, with the intensity of color #' representing the count of matching records. #' @export #' @@ -503,8 +503,8 @@ plotLineageQuery <- function(query_data = all, #' @importFrom stringr str_replace_all #' @importFrom tidyr gather #' -#' @return A ggplot object representing a heatmap (tile plot) of lineage versus -#' the top neighboring domain architectures, with color intensity representing +#' @return A ggplot object representing a heatmap (tile plot) of lineage versus +#' the top neighboring domain architectures, with color intensity representing #' the frequency of occurrences. #' @export #' @@ -583,9 +583,9 @@ plotLineageNeighbors <- function(query_data = "prot", query = "pspa", #' Lineage Domain Repeats Plot #' -#' @param query_data Data frame containing protein homolog data, including +#' @param query_data Data frame containing protein homolog data, including #' relevant domain architectures and lineages. -#' @param colname Character. The name of the column in query_data that contains +#' @param colname Character. The name of the column in query_data that contains #' domain architectures or other structural information. #' #' @importFrom dplyr across mutate select where @@ -593,8 +593,8 @@ plotLineageNeighbors <- function(query_data = "prot", query = "pspa", #' @importFrom stringr str_count str_replace_all #' @importFrom tidyr gather #' -#' @return A ggplot object representing a heatmap (tile plot) of domain repeat -#' counts across different lineages, with color intensity representing the +#' @return A ggplot object representing a heatmap (tile plot) of domain repeat +#' counts across different lineages, with color intensity representing the #' occurrence of domains. #' @export #' @@ -679,8 +679,8 @@ plotLineageDomainRepeats <- function(query_data, colname) { #' @importFrom purrr map #' @importFrom stringr str_locate str_locate_all #' -#' @return A ggplot object representing a heatmap (tile plot) of domain repeat -#' counts across different lineages, with color intensity representing the +#' @return A ggplot object representing a heatmap (tile plot) of domain repeat +#' counts across different lineages, with color intensity representing the #' occurrence of domains. #' @export #' @@ -826,26 +826,26 @@ plotLineageHeatmap <- function(prot, domains_of_interest, level = 3, label.size #' Stacked Lineage Plot #' -#' @param prot Data frame containing protein data including domain architecture +#' @param prot Data frame containing protein data including domain architecture #' and lineage information. -#' @param column Character. The name of the column in prot representing domain +#' @param column Character. The name of the column in prot representing domain #' architectures (default is "DomArch"). -#' @param cutoff Numeric. A threshold value for filtering domain architectures +#' @param cutoff Numeric. A threshold value for filtering domain architectures #' or protein counts. -#' @param Lineage_col Character. The name of the column representing lineage +#' @param Lineage_col Character. The name of the column representing lineage #' data (default is "Lineage"). -#' @param xlabel Character. Label for the x-axis +#' @param xlabel Character. Label for the x-axis #' (default is "Domain Architecture"). -#' @param reduce_lineage Logical. Whether to shorten lineage names +#' @param reduce_lineage Logical. Whether to shorten lineage names #' (default is TRUE). #' @param label.size Numeric. The size of axis text labels (default is 8). -#' @param legend.position Numeric vector. Coordinates for placing the legend +#' @param legend.position Numeric vector. Coordinates for placing the legend #' (default is c(0.7, 0.4)). -#' @param legend.text.size Numeric. Size of the text in the legend +#' @param legend.text.size Numeric. Size of the text in the legend #' (default is 10). #' @param legend.cols Numeric. Number of columns in the legend (default is 2). #' @param legend.size Numeric. Size of the legend keys (default is 0.7). -#' @param coord_flip Logical. Whether to flip the coordinates of the plot +#' @param coord_flip Logical. Whether to flip the coordinates of the plot #' (default is TRUE). #' @param legend Logical. Whether to display the legend (default is TRUE). #' @@ -853,7 +853,7 @@ plotLineageHeatmap <- function(prot, domains_of_interest, level = 3, label.size #' @importFrom ggplot2 aes_string coord_flip element_blank element_line element_rect element_text geom_bar ggplot guides guide_legend scale_fill_manual xlab ylab theme theme_minimal #' @importFrom purrr map #' -#' @return A ggplot object representing a stacked bar plot showing the +#' @return A ggplot object representing a stacked bar plot showing the #' distribution of protein domain architectures across lineages. #' @export #' @@ -982,34 +982,34 @@ plotStackedLineage <- function(prot, column = "DomArch", cutoff, Lineage_col = " #' plotWordCloud3 #' -#' @param data Data frame or table containing words and their frequencies for +#' @param data Data frame or table containing words and their frequencies for #' the word cloud. #' @param size Numeric. Scaling factor for word sizes (default is 1). -#' @param minSize Numeric. Minimum font size for the smallest word +#' @param minSize Numeric. Minimum font size for the smallest word #' (default is 0). #' @param gridSize Numeric. Size of the grid for placing words (default is 0). -#' @param fontFamily Character. Font family to use for the words +#' @param fontFamily Character. Font family to use for the words #' (default is "Segoe UI"). #' @param fontWeight Character. Font weight for the words (default is "bold"). -#' @param color Character or vector. Color of the words. Use "random-dark" for +#' @param color Character or vector. Color of the words. Use "random-dark" for #' random dark colors (default) or specify a color. -#' @param backgroundColor Character. Background color of the word cloud +#' @param backgroundColor Character. Background color of the word cloud #' (default is "white"). -#' @param minRotation Numeric. Minimum rotation angle of words in radians +#' @param minRotation Numeric. Minimum rotation angle of words in radians #' (default is -π/4). -#' @param maxRotation Numeric. Maximum rotation angle of words in radians +#' @param maxRotation Numeric. Maximum rotation angle of words in radians #' (default is π/4). #' @param shuffle Logical. Whether to shuffle the words (default is TRUE). -#' @param rotateRatio Numeric. Proportion of words that are rotated +#' @param rotateRatio Numeric. Proportion of words that are rotated #' (default is 0.4). -#' @param shape Character. Shape of the word cloud ("circle" is default, but +#' @param shape Character. Shape of the word cloud ("circle" is default, but #' you can use "cardioid", "star", "triangle", etc.). #' @param ellipticity Numeric. Degree of ellipticity (default is 0.65). -#' @param widgetsize Numeric vector. Width and height of the widget +#' @param widgetsize Numeric vector. Width and height of the widget #' (default is NULL, which uses default size). -#' @param figPath Character. Path to an image file to use as a mask for the +#' @param figPath Character. Path to an image file to use as a mask for the #' word cloud (optional). -#' @param hoverFunction JS function. JavaScript function to run when hovering +#' @param hoverFunction JS function. JavaScript function to run when hovering #' over words (optional). #' #' @importFrom base64enc base64encode @@ -1082,11 +1082,11 @@ wordcloud3 <- function(data, size = 1, minSize = 0, gridSize = 0, fontFamily = " #' #' @param query_data Data frame of protein homologs with the usual 11 columns + #' additional word columns (0/1 format). Default is "prot". -#' @param colname Character. The name of the column in `query_data` to generate +#' @param colname Character. The name of the column in `query_data` to generate #' the word cloud from. Default is "DomArch". -#' @param cutoff Numeric. The cutoff value for filtering elements based on their +#' @param cutoff Numeric. The cutoff value for filtering elements based on their #' frequency. Default is 70. -#' @param UsingRowsCutoff Logical. Whether to use a row-based cutoff instead of +#' @param UsingRowsCutoff Logical. Whether to use a row-based cutoff instead of #' a frequency cutoff. Default is FALSE. #' #' @importFrom dplyr filter pull @@ -1094,7 +1094,7 @@ wordcloud3 <- function(data, size = 1, minSize = 0, gridSize = 0, fontFamily = " #' @importFrom rlang sym #' @importFrom wordcloud wordcloud #' -#' @return A word cloud plot showing the frequency of elements from the selected +#' @return A word cloud plot showing the frequency of elements from the selected #' column. #' @export #' @@ -1166,17 +1166,17 @@ createWordCloudElement <- function(query_data = "prot", #' #' @param query_data Data frame of protein homologs with the usual 11 columns + #' additional word columns (0/1 format). Default is "prot". -#' @param colname Character. The name of the column in `query_data` to generate +#' @param colname Character. The name of the column in `query_data` to generate #' the word cloud from. Default is "DomArch". -#' @param cutoff Numeric. The cutoff value for filtering elements based on their +#' @param cutoff Numeric. The cutoff value for filtering elements based on their #' frequency. Default is 70. -#' @param UsingRowsCutoff Logical. Whether to use a row-based cutoff instead of +#' @param UsingRowsCutoff Logical. Whether to use a row-based cutoff instead of #' a frequency cutoff. Default is FALSE. #' #' @importFrom dplyr filter pull #' @importFrom rlang sym #' -#' @return A word cloud plot showing the frequency of elements from the selected +#' @return A word cloud plot showing the frequency of elements from the selected #' column. #' @export #' @@ -1240,22 +1240,22 @@ createWordCloud2Element <- function(query_data = "prot", #### Sunburst ##### #' Lineage Sunburst #' -#' @param prot Data frame containing a lineage column that the sunburst plot +#' @param prot Data frame containing a lineage column that the sunburst plot #' will be generated for -#' @param lineage_column String. Name of the lineage column within the +#' @param lineage_column String. Name of the lineage column within the #' data frame. Defaults to "Lineage" -#' @param type String, either "sunburst" or "sund2b". If type is "sunburst", +#' @param type String, either "sunburst" or "sund2b". If type is "sunburst", #' a sunburst plot of the lineage #' @param levels Integer. Number of levels the sunburst will have. -#' @param colors A vector of colors for the sunburst plot. +#' @param colors A vector of colors for the sunburst plot. #' If NULL, default colors are used. -#' @param legendOrder String vector. The order of the legend. If legendOrder +#' @param legendOrder String vector. The order of the legend. If legendOrder #' is NULL, -#' @param showLegend Boolean. If TRUE, the legend will be enabled when the +#' @param showLegend Boolean. If TRUE, the legend will be enabled when the #' component first renders. -#' @param maxLevels Integer, the maximum number of levels to display in the -#' sunburst; 5 by default, NULL to disable then the legend will be in the -#' descending order of the top level hierarchy. will be rendered. If the type is +#' @param maxLevels Integer, the maximum number of levels to display in the +#' sunburst; 5 by default, NULL to disable then the legend will be in the +#' descending order of the top level hierarchy. will be rendered. If the type is #' sund2b, a sund2b plot will be rendered. #' #' @importFrom d3r d3_nest @@ -1270,7 +1270,7 @@ createWordCloud2Element <- function(query_data = "prot", #' #' @examples #' \dontrun{ -#' plotLineageSunburst(prot, lineage_column = "Lineage", +#' plotLineageSunburst(prot, lineage_column = "Lineage", #' type = "sunburst", levels = 3) #' } plotLineageSunburst <- function(prot, lineage_column = "Lineage", diff --git a/R/pre-msa-tree.R b/R/pre-msa-tree.R index 2f9c7832..e2a8a39c 100644 --- a/R/pre-msa-tree.R +++ b/R/pre-msa-tree.R @@ -49,8 +49,8 @@ api_key <- Sys.getenv("ENTREZ_API_KEY", unset = "YOUR_KEY_HERE") #' @export #' #' @examples -#' convert2TitleCase("hello world") -#' convert2TitleCase("this is a test", "_") +#' convert2TitleCase("hello world") +#' convert2TitleCase("this is a test", "_") convert2TitleCase <- function(x, y = " ") { s <- strsplit(x, y)[[1]] paste(toupper(substring(s, 1, 1)), substring(s, 2), @@ -89,7 +89,7 @@ convert2TitleCase <- function(x, y = " ") { #' @importFrom stringr str_sub #' @importFrom tidyr replace_na separate #' -#' @return A data frame containing the combined alignment and lineage +#' @return A data frame containing the combined alignment and lineage #' information. #' @export #' @@ -191,7 +191,7 @@ addLeaves2Alignment <- function(aln_file = "", #' #' @author Samuel Chen, Janani Ravi #' -#' @description This function adds a new 'Name' column that is comprised of +#' @description This function adds a new 'Name' column that is comprised of #' components from Kingdom, Phylum, Genus, and species, as well as the accession #' #' @param data Data to add name column to @@ -278,7 +278,7 @@ addName <- function(data, #' Default is 'pspa.txt' #' @param fa_outpath Character. Path to the written fasta file. #' Default is 'NULL' -#' @param reduced Boolean. If TRUE, the fasta file will contain only one +#' @param reduced Boolean. If TRUE, the fasta file will contain only one #' sequence per lineage. Default is 'FALSE' #' #' @details The alignment file would need two columns: 1. accession + @@ -289,8 +289,8 @@ addName <- function(data, #' #' @importFrom readr write_file #' -#' @return Character string containing the Fasta formatted sequences. -#' If `fa_outpath` is specified, the function also writes the sequences to the +#' @return Character string containing the Fasta formatted sequences. +#' If `fa_outpath` is specified, the function also writes the sequences to the #' Fasta file. #' @export #' @@ -333,7 +333,7 @@ convertAlignment2FA <- function(aln_file = "", } #' mapAcc2Name -#' +#' #' @description #' Default rename_fasta() replacement function. Maps an accession number to its name #' @@ -347,17 +347,17 @@ convertAlignment2FA <- function(aln_file = "", #' @importFrom stringr str_locate #' @importFrom rlang sym #' -#' @return Character string. The modified line from the Fasta file header with +#' @return Character string. The modified line from the Fasta file header with #' the name instead of the accession number. #' @export #' #' @examples #' \dontrun{ -#' acc2name_table <- data.table(AccNum = c("ACC001", "ACC002"), +#' acc2name_table <- data.table(AccNum = c("ACC001", "ACC002"), #' Name = c("Species A", "Species B")) #' line <- ">ACC001 some additional info" #' mapped_line <- mapAcc2Name(line, acc2name_table) -#' print(mapped_line) # Expected output: ">Species A" +#' mapped_line # Expected output: ">Species A" #' } mapAcc2Name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") { # change to be the name equivalent to an add_names column @@ -389,7 +389,7 @@ mapAcc2Name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") { #' #' @examples #' \dontrun{ -#' rename_fasta("input.fasta", "output.fasta", +#' rename_fasta("input.fasta", "output.fasta", #' replacement_function = map_acc2name, acc2name = acc2name_table) #' } rename_fasta <- function(fa_path, outpath, @@ -411,8 +411,8 @@ rename_fasta <- function(fa_path, outpath, ################################ ## generateAllAlignments2FA #' generateAllAlignments2FA -#' -#' @description +#' +#' @description #' Adding Leaves to an alignment file w/ accessions #' #' @keywords alignment, accnum, leaves, lineage, species @@ -420,25 +420,25 @@ rename_fasta <- function(fa_path, outpath, #' #' @param aln_path Character. Path to alignment files. #' Default is 'here("data/rawdata_aln/")' -#' @param fa_outpath Character. Path to file. Master protein file with AccNum & +#' @param fa_outpath Character. Path to file. Master protein file with AccNum & #' lineages. #' Default is 'here("data/rawdata_tsv/all_semiclean.txt")' #' @param lin_file Character. Path to the written fasta file. #' Default is 'here("data/alns/")'. -#' @param reduced Boolean. If TRUE, the fasta file will contain only one +#' @param reduced Boolean. If TRUE, the fasta file will contain only one #' sequence per lineage. #' Default is 'FALSE'. #' #' @importFrom purrr pmap #' @importFrom stringr str_replace_all #' -#' @return NULL. The function saves the output FASTA files to the specified +#' @return NULL. The function saves the output FASTA files to the specified #' directory. #' -#' @details The alignment files would need two columns separated by spaces: -#' 1. AccNum and 2. alignment. The protein homolog file should have AccNum, +#' @details The alignment files would need two columns separated by spaces: +#' 1. AccNum and 2. alignment. The protein homolog file should have AccNum, #' Species, Lineages. -#' @note Please refer to the source code if you have alternate + file formats +#' @note Please refer to the source code if you have alternate + file formats #' and/or column names. #' #' @export @@ -481,9 +481,9 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), #' acc2FA #' #' @description -#' converts protein accession numbers to a fasta format. Resulting +#' converts protein accession numbers to a fasta format. Resulting #' fasta file is written to the outpath. -#' +#' #' @author Samuel Chen, Janani Ravi #' @keywords accnum, fasta #' @@ -492,8 +492,8 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), #' Resulting fasta file is written to the outpath. #' #' -#' @param accessions Character vector containing protein accession numbers to -#' generate fasta sequences for. Function may not work for vectors of +#' @param accessions Character vector containing protein accession numbers to +#' generate fasta sequences for. Function may not work for vectors of #' length > 10,000 #' @param outpath [str]. Location where fasta file should be written to. #' @param plan Character. The plan to use for processing. Default is "sequential". @@ -508,10 +508,10 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), #' #' @examples #' \dontrun{ -#' acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), +#' acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), #' outpath = "my_proteins.fasta") #' Entrez:accessions <- rep("ANY95992.1", 201) |> acc2FA(outpath = "entrez.fa") -#' EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> +#' EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> #' acc2FA(outpath = "ebi.fa") #' } acc2FA <- function(accessions, outpath, plan = "sequential") { @@ -601,22 +601,22 @@ acc2FA <- function(accessions, outpath, plan = "sequential") { #' @importFrom dplyr filter pull #' @importFrom rlang sym #' -#' @return A character vector containing representative accession numbers, +#' @return A character vector containing representative accession numbers, #' one for each distinct observation in the specified 'reduced' column. #' @export #' #' @examples #' \dontrun{ #' # Example usage with a data frame called `protein_data` -#' createRepresentativeAccNum <- RepresentativeAccNums(prot_data = protein_data, -#' reduced = "Lineage", +#' createRepresentativeAccNum <- RepresentativeAccNums(prot_data = protein_data, +#' reduced = "Lineage", #' accnum_col = "AccNum") -#' print(representative_accessions) +#' representative_accessions #' } createRepresentativeAccNum <- function(prot_data, reduced = "Lineage", accnum_col = "AccNum") { - # Get Unique reduced column and then bind the AccNums back to get one + # Get Unique reduced column and then bind the AccNums back to get one # AccNum per reduced column reduced_sym <- sym(reduced) accnum_sym <- sym(accnum_col) @@ -651,9 +651,9 @@ createRepresentativeAccNum <- function(prot_data, #' @author Samuel Chen, Janani Ravi #' #' @param fasta_file Path to the FASTA file to be aligned -#' @param tool Type of alignment tool to use. One of three options: "Muscle", +#' @param tool Type of alignment tool to use. One of three options: "Muscle", #' "ClustalO", or "ClustalW" -#' @param outpath Path to write the resulting alignment to as a FASTA file. If +#' @param outpath Path to write the resulting alignment to as a FASTA file. If #' NULL, no file is written #' #' @importFrom Biostrings readAAStringSet @@ -665,9 +665,9 @@ createRepresentativeAccNum <- function(prot_data, #' @examples #' \dontrun{ #' # Example usage -#' aligned_sequences <- alignFasta("path/to/sequences.fasta", +#' aligned_sequences <- alignFasta("path/to/sequences.fasta", #' tool = "ClustalO", outpath = "path/to/aligned_sequences.fasta") -#' print(aligned_sequences) +#' aligned_sequences #' } alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { fasta <- readAAStringSet(fasta_file) @@ -723,7 +723,7 @@ writeMSA_AA2FA <- function(alignment, outpath) { #' getAccNumFromFA #' -#' @param fasta_file Character. Path to the FASTA file from which +#' @param fasta_file Character. Path to the FASTA file from which #' accession numbers will be extracted. #' #' @importFrom readr read_file @@ -736,7 +736,7 @@ writeMSA_AA2FA <- function(alignment, outpath) { #' \dontrun{ #' # Example usage #' accnums <- getAccNumFromFA("path/to/sequences.fasta") -#' print(accnums) +#' accnums #' } getAccNumFromFA <- function(fasta_file) { txt <- read_file(fasta_file) diff --git a/R/reverse_operons.R b/R/reverse_operons.R index 5e1cb423..9094598b 100755 --- a/R/reverse_operons.R +++ b/R/reverse_operons.R @@ -7,12 +7,12 @@ #' #' @description #' This function processes the genomic context strings (GenContext) and reverses -#' directional signs based on the presence of an equal sign ("="). +#' directional signs based on the presence of an equal sign ("="). #' #' @param prot [vector] A vector of genomic context strings to be processed. #' -#' @return [vector] A vector of the same length as the input, where each genomic -#' element is annotated with either a forward ("->") or reverse ("<-") direction, +#' @return [vector] A vector of the same length as the input, where each genomic +#' element is annotated with either a forward ("->") or reverse ("<-") direction, #' depending on its position relative to the "=" symbols. #' #' @export @@ -73,12 +73,12 @@ straightenOperonSeq <- function(prot) { #' #' @description #' This function processes a genomic context data frame to reverse the direction -#' of operons based on specific patterns in the GenContext column. It handles -#' elements represented by ">" and "<" and restructures the genomic context by -#' flipping the direction of operons while preserving the relationships +#' of operons based on specific patterns in the GenContext column. It handles +#' elements represented by ">" and "<" and restructures the genomic context by +#' flipping the direction of operons while preserving the relationships #' indicated by "=". #' -#' @param prot [data.frame] A data frame containing at least a column named +#' @param prot [data.frame] A data frame containing at least a column named #' 'GenContext', which represents the genomic contexts that need to be reversed. #' #' @return [data.frame] The input data frame with the 'GenContext' column updated t @@ -90,7 +90,7 @@ straightenOperonSeq <- function(prot) { #' # Example genomic context data frame #' prot <- data.frame(GenContext = c("A>B", "CI")) #' reversed_prot <- reverseOperonSeq(prot) -#' print(reversed_prot) +#' reversed_prot reverseOperonSeq <- function(prot) { gencontext <- prot$GenContext diff --git a/man/acc2FA.Rd b/man/acc2FA.Rd index c878403b..ae7101d7 100644 --- a/man/acc2FA.Rd +++ b/man/acc2FA.Rd @@ -35,17 +35,17 @@ Resulting fasta file is written to the outpath. } \examples{ \dontrun{ -acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), +acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), outpath = "my_proteins.fasta") Entrez:accessions <- rep("ANY95992.1", 201) |> acc2FA(outpath = "entrez.fa") -EBI:accessions <- c("P12345", "Q9UHC1", +EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> acc2FA(outpath = "ebi.fa") } \dontrun{ -acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), +acc2FA(accessions = c("ACU53894.1", "APJ14606.1", "ABK37082.1"), outpath = "my_proteins.fasta") Entrez:accessions <- rep("ANY95992.1", 201) |> acc2FA(outpath = "entrez.fa") -EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> +EBI:accessions <- c("P12345", "Q9UHC1", "O15530", "Q14624", "P0DTD1") |> acc2FA(outpath = "ebi.fa") } } diff --git a/man/addName.Rd b/man/addName.Rd index e4a745c5..b681f349 100644 --- a/man/addName.Rd +++ b/man/addName.Rd @@ -56,7 +56,7 @@ data <- data.frame( Lineage = c("Eukaryota>Chordata", "Eukaryota>Chordata") ) enriched_data <- addName(data) -print(enriched_data) +enriched_data \dontrun{ addName(data_frame) } diff --git a/man/addTaxID.Rd b/man/addTaxID.Rd index e960769b..9e68321c 100644 --- a/man/addTaxID.Rd +++ b/man/addTaxID.Rd @@ -27,6 +27,6 @@ addTaxID # Create a sample data table with accession numbers sample_data <- data.table(AccNum = c("ABC123.1", "XYZ456.1", "LMN789.2")) enriched_data <- addTaxID(sample_data, acc_col = "AccNum", version = TRUE) -print(enriched_data) +enriched_data } } diff --git a/man/alignFasta.Rd b/man/alignFasta.Rd index e9bd22d7..61e880ab 100644 --- a/man/alignFasta.Rd +++ b/man/alignFasta.Rd @@ -29,14 +29,14 @@ Perform a Multiple Sequence Alignment on a FASTA file. } \examples{ \dontrun{ -aligned_sequences <- alignFasta("my_sequences.fasta", +aligned_sequences <- alignFasta("my_sequences.fasta", tool = "Muscle", outpath = "aligned_output.fasta") } \dontrun{ # Example usage -aligned_sequences <- alignFasta("path/to/sequences.fasta", +aligned_sequences <- alignFasta("path/to/sequences.fasta", tool = "ClustalO", outpath = "path/to/aligned_sequences.fasta") -print(aligned_sequences) +aligned_sequences } } \author{ diff --git a/man/convert2TitleCase.Rd b/man/convert2TitleCase.Rd index a4078141..4769efea 100644 --- a/man/convert2TitleCase.Rd +++ b/man/convert2TitleCase.Rd @@ -30,8 +30,8 @@ Changing case to 'Title Case' # Convert a single string to title case convert2TitleCase("hello world") # Returns "Hello World" -convert2TitleCase("hello world") -convert2TitleCase("this is a test", "_") +convert2TitleCase("hello world") +convert2TitleCase("this is a test", "_") } \seealso{ chartr, toupper, and tolower. diff --git a/man/createRepresentativeAccNum.Rd b/man/createRepresentativeAccNum.Rd index 639a36d4..53902940 100644 --- a/man/createRepresentativeAccNum.Rd +++ b/man/createRepresentativeAccNum.Rd @@ -40,11 +40,14 @@ Function to generate a vector of one Accession number per distinct observation f } \examples{ \dontrun{ +createRepresentativeAccNum(prot) +} +\dontrun{ # Example usage with a data frame called `protein_data` -createRepresentativeAccNum <- RepresentativeAccNums(prot_data = protein_data, - reduced = "Lineage", +createRepresentativeAccNum <- RepresentativeAccNums(prot_data = protein_data, + reduced = "Lineage", accnum_col = "AccNum") -print(representative_accessions) +representative_accessions } } \author{ diff --git a/man/downloadAssemblySummary.Rd b/man/downloadAssemblySummary.Rd index bad2b603..e67aba70 100644 --- a/man/downloadAssemblySummary.Rd +++ b/man/downloadAssemblySummary.Rd @@ -25,7 +25,7 @@ Download the combined assembly summaries of genbank and refseq } \examples{ \dontrun{ -downloadAssemblySummary(outpath = "assembly_summary.tsv", +downloadAssemblySummary(outpath = "assembly_summary.tsv", keep = c("assembly_accession", "taxid", "organism_name")) } } diff --git a/man/getAccNumFromFA.Rd b/man/getAccNumFromFA.Rd index d2d9216a..4c6179a1 100644 --- a/man/getAccNumFromFA.Rd +++ b/man/getAccNumFromFA.Rd @@ -24,8 +24,11 @@ getAccNumFromFA } \examples{ \dontrun{ +getAccNumFromFA("my_sequences.fasta") +} +\dontrun{ # Example usage accnums <- getAccNumFromFA("path/to/sequences.fasta") -print(accnums) +accnums } } diff --git a/man/getTopAccByLinDomArch.Rd b/man/getTopAccByLinDomArch.Rd index c76931f1..0eeb0610 100644 --- a/man/getTopAccByLinDomArch.Rd +++ b/man/getTopAccByLinDomArch.Rd @@ -37,8 +37,8 @@ Group by lineage + DA then take top 20 } \examples{ \dontrun{ -top_accessions <- getTopAccByLinDomArch(infile_full = my_data, -DA_col = "DomArch.Pfam", lin_col = "Lineage_short", +top_accessions <- getTopAccByLinDomArch(infile_full = my_data, +DA_col = "DomArch.Pfam", lin_col = "Lineage_short", n = 20, query = "specific_query_name") } } diff --git a/man/mapAcc2Name.Rd b/man/mapAcc2Name.Rd index 7ef04955..3213201a 100644 --- a/man/mapAcc2Name.Rd +++ b/man/mapAcc2Name.Rd @@ -35,10 +35,10 @@ Default rename_fasta() replacement function. Maps an accession number to its nam mapAcc2Name(">P12345 some description", acc2name, "AccNum", "Name") } \dontrun{ -acc2name_table <- data.table(AccNum = c("ACC001", "ACC002"), +acc2name_table <- data.table(AccNum = c("ACC001", "ACC002"), Name = c("Species A", "Species B")) line <- ">ACC001 some additional info" mapped_line <- mapAcc2Name(line, acc2name_table) -print(mapped_line) # Expected output: ">Species A" +mapped_line # Expected output: ">Species A" } } diff --git a/man/plotIPR2Viz.Rd b/man/plotIPR2Viz.Rd index 8d06eae1..13ac06c1 100644 --- a/man/plotIPR2Viz.Rd +++ b/man/plotIPR2Viz.Rd @@ -53,15 +53,15 @@ plotIPR2Viz } \examples{ \dontrun{ -plot <- plotIPR2Viz(infile_ipr = "path/to/ipr_file.tsv", - infile_full = "path/to/full_file.tsv", - accessions = c("ACC123", "ACC456"), - analysis = c("Pfam", "TMHMM"), - group_by = "Analysis", - topn = 20, - name = "Gene Name", - text_size = 15, +plot <- plotIPR2Viz(infile_ipr = "path/to/ipr_file.tsv", + infile_full = "path/to/full_file.tsv", + accessions = c("ACC123", "ACC456"), + analysis = c("Pfam", "TMHMM"), + group_by = "Analysis", + topn = 20, + name = "Gene Name", + text_size = 15, query = "All") -print(plot) +plot } } diff --git a/man/plotIPR2VizWeb.Rd b/man/plotIPR2VizWeb.Rd index 9de7413f..e56d917e 100644 --- a/man/plotIPR2VizWeb.Rd +++ b/man/plotIPR2VizWeb.Rd @@ -54,15 +54,15 @@ plotIPR2VizWeb } \examples{ \dontrun{ -plot <- plotIPR2VizWeb(infile_ipr = "path/to/ipr_file.tsv", - accessions = c("ACC123", "ACC456"), - analysis = c("Pfam", "TMHMM"), - group_by = "Analysis", - name = "Gene Name", - text_size = 15, - legend_name = "ShortName", - cols = 5, +plot <- plotIPR2VizWeb(infile_ipr = "path/to/ipr_file.tsv", + accessions = c("ACC123", "ACC456"), + analysis = c("Pfam", "TMHMM"), + group_by = "Analysis", + name = "Gene Name", + text_size = 15, + legend_name = "ShortName", + cols = 5, rows = 10) -print(plot) +plot } } diff --git a/man/plotLineageSunburst.Rd b/man/plotLineageSunburst.Rd index 3240d77d..363e8c27 100644 --- a/man/plotLineageSunburst.Rd +++ b/man/plotLineageSunburst.Rd @@ -49,7 +49,7 @@ Lineage Sunburst } \examples{ \dontrun{ -plotLineageSunburst(prot, lineage_column = "Lineage", +plotLineageSunburst(prot, lineage_column = "Lineage", type = "sunburst", levels = 3) } } diff --git a/man/prepareColumnParams.Rd b/man/prepareColumnParams.Rd index 8a9f566b..f685624e 100644 --- a/man/prepareColumnParams.Rd +++ b/man/prepareColumnParams.Rd @@ -24,6 +24,6 @@ prepareColumnParams count_data <- data.frame(Category = c("A", "B", "C"), n = c(10, 20, 15)) params <- prepareColumnParams(count_data, fill_by_n = TRUE, sort_by_n = FALSE) -print(params) +params } } diff --git a/man/prepareSingleColumnParams.Rd b/man/prepareSingleColumnParams.Rd index 0070497e..0261f9c1 100644 --- a/man/prepareSingleColumnParams.Rd +++ b/man/prepareSingleColumnParams.Rd @@ -25,6 +25,6 @@ prepareSingleColumnParams df <- data.frame(Category = c("A", "A", "B", "B", "C"), n = c(10, 20, 30, 40, 50)) params <- prepareSingleColumnParams(df, col_num = 1, root = "Root") -print(params) +params } } diff --git a/man/proteinAcc2TaxID.Rd b/man/proteinAcc2TaxID.Rd index 9be09d53..1ccafe4f 100644 --- a/man/proteinAcc2TaxID.Rd +++ b/man/proteinAcc2TaxID.Rd @@ -31,8 +31,8 @@ proteinAcc2TaxID \dontrun{ # Example accession numbers accessions <- c("ABC123", "XYZ456", "LMN789") -tax_data <- proteinAcc2TaxID(accessions, suffix = "example", +tax_data <- proteinAcc2TaxID(accessions, suffix = "example", out_path = "/path/to/output", return_dt = TRUE) -print(tax_data) +tax_data } } diff --git a/man/renameFA.Rd b/man/renameFA.Rd index da7d339b..18eca8b9 100644 --- a/man/renameFA.Rd +++ b/man/renameFA.Rd @@ -23,7 +23,7 @@ Rename the labels of fasta files } \examples{ \dontrun{ -renameFA("path/to/input.fasta", +renameFA("path/to/input.fasta", "path/to/output.fasta", mapAcc2Name, acc2name) } } diff --git a/man/rename_fasta.Rd b/man/rename_fasta.Rd index 3089d530..35658437 100644 --- a/man/rename_fasta.Rd +++ b/man/rename_fasta.Rd @@ -23,7 +23,7 @@ Rename the labels of fasta files } \examples{ \dontrun{ -rename_fasta("input.fasta", "output.fasta", +rename_fasta("input.fasta", "output.fasta", replacement_function = map_acc2name, acc2name = acc2name_table) } } diff --git a/man/reverseOperonSeq.Rd b/man/reverseOperonSeq.Rd index 3709bbe1..03e68a94 100644 --- a/man/reverseOperonSeq.Rd +++ b/man/reverseOperonSeq.Rd @@ -25,5 +25,5 @@ indicated by "=". # Example genomic context data frame prot <- data.frame(GenContext = c("A>B", "CI")) reversed_prot <- reverseOperonSeq(prot) -print(reversed_prot) +reversed_prot } diff --git a/man/runDeltaBlast.Rd b/man/runDeltaBlast.Rd index fc9cd09e..c3384d12 100644 --- a/man/runDeltaBlast.Rd +++ b/man/runDeltaBlast.Rd @@ -5,7 +5,7 @@ \title{Run DELTABLAST to find homologs for proteins of interest} \usage{ runDeltaBlast( - deltablast_path, + runDeltaBlast, db_search_path, db = "refseq", query, @@ -16,8 +16,6 @@ runDeltaBlast( ) } \arguments{ -\item{deltablast_path}{Path to the Delta-BLAST executable.} - \item{db_search_path}{Path to the BLAST databases.} \item{db}{Name of the BLAST database to search against (default is "refseq").} @@ -31,6 +29,8 @@ runDeltaBlast( \item{num_alignments}{Number of alignments to report.} \item{num_threads}{Number of threads to use for the search (default is 1).} + +\item{deltablast_path}{Path to the Delta-BLAST executable.} } \value{ This function does not return a value; it outputs results to the @@ -41,6 +41,11 @@ This function executes a Delta-BLAST search using the specified parameters and database. It sets the BLAST database path, runs the Delta-BLAST command with the given query, and outputs the results. } +\examples{ +\dontrun{ +runDeltaBlast(runDeltaBlast, db_search_path) +} +} \author{ Samuel Chen, Janani Ravi } diff --git a/man/runIPRScan.Rd b/man/runIPRScan.Rd index 8431efb4..f675314d 100644 --- a/man/runIPRScan.Rd +++ b/man/runIPRScan.Rd @@ -29,6 +29,6 @@ results <- runIPRScan( filepath_out = "path/to/output_file", appl = c("Pfam", "Gene3D") ) -print(results) +results } } diff --git a/man/shortenLineage.Rd b/man/shortenLineage.Rd index 00200f96..161d0260 100644 --- a/man/shortenLineage.Rd +++ b/man/shortenLineage.Rd @@ -27,9 +27,9 @@ string (up to a given delimiter). } \examples{ \dontrun{ -df <- data.frame(Lineage = c("Bacteria>Firmicutes>Clostridia", +df <- data.frame(Lineage = c("Bacteria>Firmicutes>Clostridia", "Archaea>Euryarchaeota>Thermococci")) shortened_df <- shortenLineage(df, colname = "Lineage", abr_len = 1) -print(shortened_df) +shortened_df } } diff --git a/man/writeMSA_AA2FA.Rd b/man/writeMSA_AA2FA.Rd index c9551102..d0d5d305 100644 --- a/man/writeMSA_AA2FA.Rd +++ b/man/writeMSA_AA2FA.Rd @@ -28,6 +28,9 @@ and msaMuscle from the 'msa' package } \examples{ \dontrun{ +writeMSA_AA2FA("my_sequences.fasta", outpath = "aligned_output.fasta") +} +\dontrun{ # Example usage alignment <- alignFasta("path/to/sequences.fasta") writeMSA_AA2FA(alignment, "path/to/aligned_sequences.fasta") From ecdd69e27f422c4c0e13dc9ce4ef9818ccdfb828 Mon Sep 17 00:00:00 2001 From: teddyCodex Date: Sun, 27 Oct 2024 16:34:58 +0100 Subject: [PATCH 15/24] added boundary guard and error handling to .LevelReduction --- R/plotting.R | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/R/plotting.R b/R/plotting.R index 5d949cd5..853b377f 100644 --- a/R/plotting.R +++ b/R/plotting.R @@ -23,22 +23,12 @@ ######################## #' #' -.LevelReduction <- function(lin, level) { - if (level == 1) { - gt_loc <- str_locate(lin, ">")[[1]] - if (is.na(gt_loc)) { - # No '>' in lineage - return(lin) - } else { - lin <- substring(lin, first = 0, last = (gt_loc - 1)) - return(lin) - } - } - # Out of bounds guard - gt_loc <- str_locate_all(lin, ">")[[1]] - l <- length(gt_loc) / 2 - if (level > l) { - # Not enough '>' in lineage +.LevelReduction <- function(lin, level) { + gt_loc <- str_locate_all(lin, ">")[[1]] + available_levels <- length(gt_loc) / 2 # Since `str_locate_all` returns a matrix + + # Guard against out-of-bounds level requests + if (level > available_levels || level < 1) { return(lin) } else { gt_loc <- gt_loc[level, ][1] %>% as.numeric() @@ -47,6 +37,8 @@ } } + + .GetKingdom <- function(lin) { gt_loc <- str_locate(lin, ">")[, "start"] if (is.na(gt_loc)) { @@ -1359,4 +1351,4 @@ plotLineageSunburst <- function(prot, lineage_column = "Lineage", # # theme(axis.text.x=element_text(angle=90,hjust=1,vjust=0.5), # # axis.text.y=element_text(angle=90,hjust=1,vjust=0.5)) # -# } +# } \ No newline at end of file From 64d16bec64a607c9cfb427b01acad378dd064ab0 Mon Sep 17 00:00:00 2001 From: David Mayer Date: Tue, 29 Oct 2024 09:20:49 -0600 Subject: [PATCH 16/24] Rd consistency --- man/shortenLineage.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/man/shortenLineage.Rd b/man/shortenLineage.Rd index 161d0260..7390b254 100644 --- a/man/shortenLineage.Rd +++ b/man/shortenLineage.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/plotting.R \name{shortenLineage} \alias{shortenLineage} -\title{Shorten Lineage Names} +\title{shortenLineage} \usage{ shortenLineage(data, colname = "Lineage", abr_len = 1) } From 32418b39ba9b40550ef425c771d4c857741a8446 Mon Sep 17 00:00:00 2001 From: David Mayer Date: Tue, 29 Oct 2024 09:21:11 -0600 Subject: [PATCH 17/24] disable example code for reverseOperonSeq() - see https://github.com/JRaviLab/MolEvolvR/issues/118 --- R/reverse_operons.R | 5 ++++- man/reverseOperonSeq.Rd | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/R/reverse_operons.R b/R/reverse_operons.R index 9094598b..f250e8c0 100755 --- a/R/reverse_operons.R +++ b/R/reverse_operons.R @@ -87,10 +87,13 @@ straightenOperonSeq <- function(prot) { #' @export #' #' @examples +#' \dontrun{ #' # Example genomic context data frame -#' prot <- data.frame(GenContext = c("A>B", "CI")) +#' ## Rework example data, does not pass R-CMD Check +#' prot <- data.frame(GenContext = c("A>B", "CI")) #' reversed_prot <- reverseOperonSeq(prot) #' reversed_prot +#' } reverseOperonSeq <- function(prot) { gencontext <- prot$GenContext diff --git a/man/reverseOperonSeq.Rd b/man/reverseOperonSeq.Rd index 03e68a94..812d0e89 100644 --- a/man/reverseOperonSeq.Rd +++ b/man/reverseOperonSeq.Rd @@ -22,8 +22,11 @@ flipping the direction of operons while preserving the relationships indicated by "=". } \examples{ +\dontrun{ # Example genomic context data frame -prot <- data.frame(GenContext = c("A>B", "CI")) +## Rework example data, does not pass R-CMD Check +prot <- data.frame(GenContext = c("A>B", "CI")) reversed_prot <- reverseOperonSeq(prot) reversed_prot } +} From f4b50f4c387f7a797e630eb2b00c06d473ee75da Mon Sep 17 00:00:00 2001 From: David Mayer Date: Tue, 29 Oct 2024 20:39:13 -0600 Subject: [PATCH 18/24] fix error introduced by merge --- R/assign_job_queue.R | 28 +--------------------------- 1 file changed, 1 insertion(+), 27 deletions(-) diff --git a/R/assign_job_queue.R b/R/assign_job_queue.R index 6f3dde17..e0c22ec6 100644 --- a/R/assign_job_queue.R +++ b/R/assign_job_queue.R @@ -127,33 +127,6 @@ calculateProcessRuntime <- function(dir_job_results) { dir.create(dirname(path_log_data), recursive = TRUE, showWarnings = FALSE) } - - # attempt to load pre-generated logdata - if (!file.exists(path_log_data)) { - logs <- aggregate_logs(dir_job_results, latest_date = Sys.Date() - 60) - save(logs, file = path_log_data) - } else { - load(path_log_data) # loads the logs object - } - df_log <- logs$df_log - procs <- c( - "dblast", "dblast_cleanup", "iprscan", - "ipr2lineage", "ipr2da", "blast_clust", - "clust2table" - ) - list_proc_medians <- df_log |> - dplyr::select(dplyr::all_of(procs)) |> - dplyr::summarise( - dplyr::across( - dplyr::everything(), - \(x) median(x, na.rm = TRUE) - ) - ) |> - as.list() - return(list_proc_medians) -} - - # attempt to load pre-generated logdata if (!file.exists(path_log_data)) { logs <- aggregate_logs(dir_job_results, latest_date = Sys.Date() - 60) @@ -600,6 +573,7 @@ assignJobQueue <- function( #' dev/molevol_scripts/docs/estimate_walltimes.png", plot = p) #' @export plotEstimatedWallTimes <- function() { + tryCatch({ opts <- mapOption2Process() |> names() # get all possible submission permutations (powerset) get_powerset <- function(vec) { From dd86b3ce04e68345297ee2f0f095f2999ff286f1 Mon Sep 17 00:00:00 2001 From: David Mayer Date: Tue, 29 Oct 2024 20:45:29 -0600 Subject: [PATCH 19/24] fix .Rd --- R/assign_job_queue.R | 18 ++++++++++++++++++ man/acc2Lineage.Rd | 3 +-- man/efetchIPG.Rd | 3 +-- man/sinkReset.Rd | 1 - 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/R/assign_job_queue.R b/R/assign_job_queue.R index e0c22ec6..52af46bf 100644 --- a/R/assign_job_queue.R +++ b/R/assign_job_queue.R @@ -36,6 +36,9 @@ mapOption2Process <- function() { } +#' mapAdvOption2Process +#' +#' @description #' Use MolEvolvR advanced options to get associated processes #' #' @param advanced_opts character vector of MolEvolvR advanced options @@ -79,6 +82,9 @@ mapAdvOption2Process <- function(advanced_opts) { } +#' calculateProcessRuntime +#' +#' @description #' Scrape MolEvolvR logs and calculate median processes #' #' @param dir_job_results [chr] path to MolEvolvR job_results @@ -227,6 +233,9 @@ writeProcessRuntime2TSV <- function(dir_job_results, filepath) { } +#' writeProcessRuntime2YML +#' +#' @description #' Compute median process runtimes, then write a YAML list of the processes and #' their median runtimes in seconds to the path specified by 'filepath'. #' @@ -304,6 +313,9 @@ writeProcessRuntime2YML <- function(dir_job_results, filepath = NULL) { }) } +#' getProcessRuntimeWeights +#' +#' @description #' Quickly get the runtime weights for MolEvolvR backend processes #' #' @param dir_job_results [chr] path to MolEvolvR job_results @@ -494,6 +506,9 @@ calculateEstimatedWallTimeFromOpts <- function(advanced_opts, } +#' assignJobQueue +#' +#' @description #' Decision function to assign job queue #' #' @param t_sec_estimate estimated number of seconds a job will process @@ -555,6 +570,9 @@ assignJobQueue <- function( } +#' plotEstimatedWallTimes +#' +#' @description #' Plot the estimated runtimes for different advanced options and number #' of inputs #' diff --git a/man/acc2Lineage.Rd b/man/acc2Lineage.Rd index fd4eeceb..ce499592 100644 --- a/man/acc2Lineage.Rd +++ b/man/acc2Lineage.Rd @@ -44,8 +44,7 @@ accessions. The dataframe includes relevant columns such as TaxID, GCA_ID, Protein, Protein Name, Species, and Lineage. } \description{ -This function combines 'efetchIPG()' -and 'IPG2Lineage()' to map a set +This function combines 'efetchIPG()' and 'IPG2Lineage()' to map a set of protein accessions to their assembly (GCA_ID), tax ID, and lineage. Function to map protein accession numbers to lineage diff --git a/man/efetchIPG.Rd b/man/efetchIPG.Rd index eb5ca678..e55c342a 100644 --- a/man/efetchIPG.Rd +++ b/man/efetchIPG.Rd @@ -27,8 +27,7 @@ The function does not return a value but writes the efetch results directly to the specified \code{out_path}. } \description{ -Perform efetch on the ipg database -and write the results to out_path +Perform efetch on the ipg database and write the results to out_path Perform efetch on the ipg database and write the results to out_path } diff --git a/man/sinkReset.Rd b/man/sinkReset.Rd index e3fc7ce4..0285c0b2 100644 --- a/man/sinkReset.Rd +++ b/man/sinkReset.Rd @@ -8,7 +8,6 @@ sinkReset() } \value{ No return, but run to close all outstanding \code{sink()}s -and handles any errors or warnings that occur during the process. } \description{ Sink Reset From f6c8188c9eb27df33bbb74a5c1b0febff549153a Mon Sep 17 00:00:00 2001 From: David Mayer Date: Tue, 29 Oct 2024 21:17:23 -0600 Subject: [PATCH 20/24] swap rlang::abort() for base::stop() - allows for additional metadata to be added to error - pkg consistency, abort is used elsewhere print -> message --- R/tree.R | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/R/tree.R b/R/tree.R index 82eb11db..ddbf9d61 100755 --- a/R/tree.R +++ b/R/tree.R @@ -43,6 +43,8 @@ #' be saved. Default is the path to "data/alns/pspa_snf7.tre". #' @param fasttree_path Path to the FastTree executable, which is used to #' generate the phylogenetic tree. Default is "src/FastTree". +#' +#' @importFrom rlang abort #' #' @return No return value. The function generates a tree file (.tre) from the #' input FASTA file. @@ -63,19 +65,19 @@ convertFA2Tree <- function(fa_path = here("data/alns/pspa_snf7.fa"), # Check if the FASTA file exists if (!file.exists(fa_path)) { - stop(paste("Error: The FASTA file does not exist at:", fa_path)) + abort(paste("Error: The FASTA file does not exist at:", fa_path)) } # Check if the FastTree executable exists if (!file.exists(fasttree_path)) { - stop(paste("Error: The FastTree executable does not exist at:", + abort(paste("Error: The FastTree executable does not exist at:", fasttree_path)) } # Check if the output directory exists tre_dir <- dirname(tre_path) if (!dir.exists(tre_dir)) { - stop(paste("Error: The output directory does not exist:", tre_dir)) + abort(paste("Error: The output directory does not exist:", tre_dir)) } # Check if the output file already exists @@ -84,7 +86,7 @@ convertFA2Tree <- function(fa_path = here("data/alns/pspa_snf7.fa"), tre_path, "\n") } - print(fa_path) + message(fa_path) system2( command = fasttree_path, args = paste(c(fa_path, ">", tre_path), @@ -125,13 +127,13 @@ convertAlignment2Trees <- function(aln_path = here("data/alns/")) { # Check if the alignment directory exists if (!dir.exists(aln_path)) { - stop(paste("Error: The alignment directory does not exist:", aln_path)) + abort(paste("Error: The alignment directory does not exist:", aln_path)) } # finding all fasta alignment files fa_filenames <- list.files(path = aln_path, pattern = "*.fa") # Check if any FASTA files were found if (length(fa_filenames) == 0) { - stop("Error: No FASTA files found in the specified directory.") + abort("Error: No FASTA files found in the specified directory.") } fa_paths <- paste0(aln_path, fa_filenames) @@ -194,13 +196,13 @@ createFA2Tree <- function(fa_file = "data/alns/pspa_snf7.fa", # Check if the FASTA file exists if (!file.exists(fa_file)) { - stop(paste("Error: The FASTA file does not exist at:", fa_file)) + abort(paste("Error: The FASTA file does not exist at:", fa_file)) } # Check if the output directory exists out_dir <- dirname(out_file) if (!dir.exists(out_dir)) { - stop(paste("Error: The output directory does not exist:", out_dir)) + abort(paste("Error: The output directory does not exist:", out_dir)) } # Check if the output file already exists @@ -233,7 +235,7 @@ createFA2Tree <- function(fa_file = "data/alns/pspa_snf7.fa", ## Model Testing & Distance Matrices ## Comparison of different nucleotide or amino acid substitution models mt <- modelTest(prot10, model = "all") - print(mt) + message(mt) # estimate a distance matrix using a Jules-Cantor Model dna_dist <- dist.ml(prot10, model = "JC69") @@ -254,7 +256,7 @@ createFA2Tree <- function(fa_file = "data/alns/pspa_snf7.fa", ## Maximum likelihood and Bootstrapping # ml estimation w/ distance matrix fit <- pml(prot_NJ, prot10) - print(fit) + message(fit) fitJC <- optim.pml(fit, model = "JC", rearrangement = "stochastic") logLik(fitJC) bs <- bootstrap.pml(fitJC, @@ -267,7 +269,7 @@ createFA2Tree <- function(fa_file = "data/alns/pspa_snf7.fa", prot10_dm <- dist.ml(prot10) prot10_NJ <- NJ(prot10_dm) fit2 <- pml(prot10_NJ, data = prot10) - print(fit2) + message(fit2) fitJC2 <- optim.pml(fit2, model = "JC", rearrangement = "stochastic") logLik(fitJC2) bs_subset <- bootstrap.pml(fitJC2, From 01ac8b233f75df76d12320dbbfc0fe09441b1910 Mon Sep 17 00:00:00 2001 From: David Mayer Date: Tue, 29 Oct 2024 21:34:12 -0600 Subject: [PATCH 21/24] use rlang::abort() --- R/summarize.R | 54 +++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/R/summarize.R b/R/summarize.R index 504da767..e76a86da 100644 --- a/R/summarize.R +++ b/R/summarize.R @@ -25,7 +25,7 @@ #' #' @importFrom dplyr filter #' @importFrom stringr str_replace_all -#' @importFrom rlang sym +#' @importFrom rlang abort sym #' #' @return Filtered data frame #' @note There is no need to make the domains 'regex safe', that will be handled by this function @@ -44,12 +44,12 @@ filterByDomains <- function(prot, column = "DomArch", doms_keep = c(), doms_remo # Check if prot is a data frame if (!is.data.frame(prot)) { - stop("Error: 'prot' must be a data frame.") + abort("Error: 'prot' must be a data frame.") } # Check if the specified column exists in the data frame if (!column %in% names(prot)) { - stop(paste("Error: The specified column '", column, "' does not exist + abort(paste("Error: The specified column '", column, "' does not exist in the data frame.", sep = "")) } @@ -139,19 +139,19 @@ countByColumn <- function(prot = prot, column = "DomArch", min.freq = 1) { # Check if 'prot' is a data frame if (!is.data.frame(prot)) { - stop("Error: 'prot' must be a data frame.") + abort("Error: 'prot' must be a data frame.") } # Check if the specified column exists in the data frame if (!column %in% names(prot)) { - stop(paste("Error: The specified column '", column, "' does not exist in + abort(paste("Error: The specified column '", column, "' does not exist in the data frame.", sep = "")) } # Check if min.freq is a positive integer if (!is.numeric(min.freq) || length(min.freq) != 1 || min.freq < 1 || floor(min.freq) != min.freq) { - stop("Error: 'min.freq' must be a positive integer.") + abort("Error: 'min.freq' must be a positive integer.") } counts <- prot %>% select(column) %>% @@ -200,19 +200,19 @@ countByColumn <- function(prot = prot, column = "DomArch", min.freq = 1) { elements2Words <- function(prot, column = "DomArch", conversion_type = "da2doms") { # Check if 'prot' is a data frame if (!is.data.frame(prot)) { - stop("Error: 'prot' must be a data frame.") + abort("Error: 'prot' must be a data frame.") } # Check if the specified column exists in the data frame if (!column %in% names(prot)) { - stop(paste("Error: The specified column '", column, "' does not exist in + abort(paste("Error: The specified column '", column, "' does not exist in the data frame.", sep = "")) } # Check for valid conversion_type values valid_types <- c("da2doms", "doms2da") if (!conversion_type %in% valid_types) { - stop(paste("Error: Invalid 'conversion_type'. Must be one of:", + abort(paste("Error: Invalid 'conversion_type'. Must be one of:", paste(valid_types, collapse = ", "))) } @@ -277,7 +277,7 @@ elements2Words <- function(prot, column = "DomArch", conversion_type = "da2doms" words2WordCounts <- function(string) { # Check if 'string' is a character vector of length 1 if (!is.character(string) || length(string) != 1) { - stop("Error: 'string' must be a single character vector.") + abort("Error: 'string' must be a single character vector.") } df_word_count <- string %>% @@ -331,18 +331,18 @@ filterByFrequency <- function(x, min.freq) { # Check if 'x' is a data frame if (!is.data.frame(x)) { - stop("Error: 'x' must be a data frame.") + abort("Error: 'x' must be a data frame.") } # Check if 'min.freq' is a positive integer if (!is.numeric(min.freq) || length(min.freq) != 1 || min.freq < 1 || floor(min.freq) != min.freq) { - stop("Error: 'min.freq' must be a positive integer.") + abort("Error: 'min.freq' must be a positive integer.") } # Check if the 'freq' column exists in the data frame if (!"freq" %in% names(x)) { - stop("Error: The data frame must contain a 'freq' column.") + abort("Error: The data frame must contain a 'freq' column.") } x %>% filter(freq >= min.freq) @@ -388,18 +388,18 @@ summarizeByLineage <- function(prot = "prot", column = "DomArch", by = "Lineage" query) { # Check if 'prot' is a data frame if (!is.data.frame(prot)) { - stop("Error: 'prot' must be a data frame.") + abort("Error: 'prot' must be a data frame.") } # Check if the specified column exists in the data frame if (!column %in% names(prot)) { - stop(paste("Error: The specified column '", column, "' does not exist in + abort(paste("Error: The specified column '", column, "' does not exist in the data frame.", sep = "")) } # Check if the 'by' column exists in the data frame if (!by %in% names(prot)) { - stop(paste("Error: The specified 'by' column '", by, "' does not exist + abort(paste("Error: The specified 'by' column '", by, "' does not exist n the data frame.", sep = "")) } @@ -448,7 +448,7 @@ summarizeByLineage <- function(prot = "prot", column = "DomArch", by = "Lineage" summarizeDomArch_ByLineage <- function(x) { # Check if 'x' is a data frame if (!is.data.frame(x)) { - stop("Error: 'x' must be a data frame.") + abort("Error: 'x' must be a data frame.") } # Check if required columns exist in the data frame @@ -456,7 +456,7 @@ summarizeDomArch_ByLineage <- function(x) { missing_columns <- setdiff(required_columns, names(x)) if (length(missing_columns) > 0) { - stop(paste("Error: The following required columns are + abort(paste("Error: The following required columns are missing:", paste(missing_columns, collapse = ", "))) } x %>% @@ -494,7 +494,7 @@ summarizeDomArch_ByLineage <- function(x) { summarizeDomArch <- function(x) { # Check if 'x' is a data frame if (!is.data.frame(x)) { - stop("Error: 'x' must be a data frame.") + abort("Error: 'x' must be a data frame.") } x %>% group_by(DomArch) %>% @@ -530,7 +530,7 @@ summarizeDomArch <- function(x) { summarizeGenContext_ByDomArchLineage <- function(x) { # Check if 'x' is a data frame if (!is.data.frame(x)) { - stop("Error: 'x' must be a data frame.") + abort("Error: 'x' must be a data frame.") } x %>% filter(!grepl("^-$", GenContext)) %>% @@ -559,7 +559,7 @@ summarizeGenContext_ByDomArchLineage <- function(x) { summarizeGenContext_ByLineage <- function(x) { # Check if 'x' is a data frame if (!is.data.frame(x)) { - stop("Error: 'x' must be a data frame.") + abort("Error: 'x' must be a data frame.") } x %>% filter(!grepl("^-$", GenContext)) %>% @@ -596,7 +596,7 @@ summarizeGenContext_ByLineage <- function(x) { summarizeGenContext <- function(x) { # Check if 'x' is a data frame if (!is.data.frame(x)) { - stop("Error: 'x' must be a data frame.") + abort("Error: 'x' must be a data frame.") } x %>% group_by(GenContext) %>% @@ -659,7 +659,7 @@ totalGenContextOrDomArchCounts <- function(prot, column = "DomArch", lineage_col ) { # Check if 'prot' is a data frame if (!is.data.frame(prot)) { - stop("Error: 'prot' must be a data frame.") + abort("Error: 'prot' must be a data frame.") } # Check if the specified columns exist in the data frame @@ -667,19 +667,19 @@ totalGenContextOrDomArchCounts <- function(prot, column = "DomArch", lineage_col missing_columns <- setdiff(required_columns, names(prot)) if (length(missing_columns) > 0) { - stop(paste("Error: The following required columns are missing:", + abort(paste("Error: The following required columns are missing:", paste(missing_columns, collapse = ", "))) } # Check that cutoff is a numeric value between 0 and 100 if (!is.numeric(cutoff) || length(cutoff) != 1 || cutoff < 0 || cutoff > 100) { - stop("Error: 'cutoff' must be a numeric value between 0 and 100.") + abort("Error: 'cutoff' must be a numeric value between 0 and 100.") } # Check that digits is a non-negative integer if (!is.numeric(digits) || length(digits) != 1 || digits < 0 || floor(digits) != digits) { - stop("Error: 'digits' must be a non-negative integer.") + abort("Error: 'digits' must be a non-negative integer.") } column <- sym(column) @@ -843,7 +843,7 @@ totalGenContextOrDomArchCounts <- function(prot, column = "DomArch", lineage_col findParalogs <- function(prot) { # Check if 'prot' is a data frame if (!is.data.frame(prot)) { - stop("Error: 'prot' must be a data frame.") + abort("Error: 'prot' must be a data frame.") } # Remove eukaryotes From f74e7cfbdfa04f83c3cc13ac2c4534c56a3d9e44 Mon Sep 17 00:00:00 2001 From: David Mayer Date: Tue, 29 Oct 2024 21:44:50 -0600 Subject: [PATCH 22/24] use Tidyverse equivalent rlang::abort() --- R/reverse_operons.R | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/R/reverse_operons.R b/R/reverse_operons.R index 05e08580..7283566e 100755 --- a/R/reverse_operons.R +++ b/R/reverse_operons.R @@ -10,6 +10,8 @@ #' directional signs based on the presence of an equal sign ("="). #' #' @param prot [vector] A vector of genomic context strings to be processed. +#' +#' @importFrom rlang abort #' #' @return [vector] A vector of the same length as the input, where each genomic #' element is annotated with either a forward ("->") or reverse ("<-") direction, @@ -27,7 +29,7 @@ straightenOperonSeq <- function(prot) { # Check if 'prot' is a data frame if (!is.data.frame(prot)) { - stop("Error: 'prot' must be a data frame.") + abort("Error: 'prot' must be a data frame.") } w <- prot # $GenContext.orig # was 'x' @@ -86,6 +88,8 @@ straightenOperonSeq <- function(prot) { #' #' @param prot [data.frame] A data frame containing at least a column named #' 'GenContext', which represents the genomic contexts that need to be reversed. +#' +#' @importFrom rlang abort #' #' @return [data.frame] The input data frame with the 'GenContext' column updated t #' o reflect the reversed operons. @@ -104,7 +108,7 @@ straightenOperonSeq <- function(prot) { reverseOperonSeq <- function(prot) { # Check if 'prot' is a data frame if (!is.data.frame(prot)) { - stop("Error: 'prot' must be a data frame.") + abort("Error: 'prot' must be a data frame.") } gencontext <- prot$GenContext From 9b300144135528409e954bd89cf88e3b5601b269 Mon Sep 17 00:00:00 2001 From: David Mayer Date: Tue, 29 Oct 2024 21:54:43 -0600 Subject: [PATCH 23/24] fix input validation --- R/reverse_operons.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/R/reverse_operons.R b/R/reverse_operons.R index 7283566e..59a8fdea 100755 --- a/R/reverse_operons.R +++ b/R/reverse_operons.R @@ -28,8 +28,8 @@ straightenOperonSeq <- function(prot) { # Check if 'prot' is a data frame - if (!is.data.frame(prot)) { - abort("Error: 'prot' must be a data frame.") + if (!is.vector(prot)) { + abort("Error: 'prot' must be a vector.") } w <- prot # $GenContext.orig # was 'x' From 6949a68f019a8807a8467be94b99dca1bb8334aa Mon Sep 17 00:00:00 2001 From: David Mayer Date: Wed, 30 Oct 2024 11:21:43 -0600 Subject: [PATCH 24/24] swap rlang::abort() for stop() --- R/pre-msa-tree.R | 71 +++++++++++++++++++++++++++--------------------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/R/pre-msa-tree.R b/R/pre-msa-tree.R index b1246c9a..75cc375d 100644 --- a/R/pre-msa-tree.R +++ b/R/pre-msa-tree.R @@ -45,6 +45,8 @@ api_key <- Sys.getenv("ENTREZ_API_KEY", unset = "YOUR_KEY_HERE") #' @param x Character vector. #' @param y Delimitter. Default is space (" "). #' +#' @importFrom rlang abort +#' #' @return A character vector in title case. #' @export #' @@ -55,7 +57,7 @@ api_key <- Sys.getenv("ENTREZ_API_KEY", unset = "YOUR_KEY_HERE") convert2TitleCase <- function(x, y = " ") { # Check if the input is NULL or not a character if (is.null(x) || !is.character(x)) { - stop("Error: Input must be a non-null character string.") + abort("Error: Input must be a non-null character string.") } s <- strsplit(x, y)[[1]] paste(toupper(substring(s, 1, 1)), substring(s, 2), @@ -93,6 +95,7 @@ convert2TitleCase <- function(x, y = " ") { #' @importFrom stats complete.cases #' @importFrom stringr str_sub #' @importFrom tidyr replace_na separate +#' @importFrom rlang abort #' #' @return A data frame containing the combined alignment and lineage #' information. @@ -112,21 +115,21 @@ addLeaves2Alignment <- function(aln_file = "", #Check if the alignment file is provided and exists if (nchar(aln_file) == 0) { - stop("Error: Alignment file path must be provided.") + abort("Error: Alignment file path must be provided.") } if (!file.exists(aln_file)) { - stop(paste("Error: The alignment file '", aln_file, "' does not exist.")) + abort(paste("Error: The alignment file '", aln_file, "' does not exist.")) } # Check if the lineage file exists if (!file.exists(lin_file)) { - stop(paste("Error: The lineage file '", lin_file, "' does not exist.")) + abort(paste("Error: The lineage file '", lin_file, "' does not exist.")) } # Check that the 'reduced' parameter is logical if (!is.logical(reduced) || length(reduced) != 1) { - stop("Error: 'reduced' must be a single logical value (TRUE or FALSE).") + abort("Error: 'reduced' must be a single logical value (TRUE or FALSE).") } ## SAMPLE ARGS # aln_file <- "data/rawdata_aln/pspc.gismo.aln" @@ -230,7 +233,7 @@ addLeaves2Alignment <- function(aln_file = "", #' @importFrom dplyr mutate pull select #' @importFrom stringi stri_replace_all_regex #' @importFrom tidyr separate -#' @importFrom rlang sym +#' @importFrom rlang abort sym #' #' @return Original data with a 'Name' column #' @export @@ -244,14 +247,14 @@ addName <- function(data, lin_sep = ">", out_col = "Name") { # Check if the data is a data fram if (!is.data.frame(data)) { - stop("Error: The input 'data' must be a data frame") + abort("Error: The input 'data' must be a data frame") } # Check that the specified columns exist in the data required_cols <- c(accnum_col, spec_col, lin_col) missing_cols <- setdiff(required_cols, names(data)) if (length(missing_cols) > 0) { - stop(paste("Error: The following columns are missing from the data:", + abort(paste("Error: The following columns are missing from the data:", paste(missing_cols, collapse = ", "))) } @@ -325,6 +328,7 @@ addName <- function(data, #' file formats and/or column names. #' #' @importFrom readr write_file +#' @importFrom rlang abort #' #' @return Character string containing the Fasta formatted sequences. #' If `fa_outpath` is specified, the function also writes the sequences to the @@ -341,21 +345,21 @@ convertAlignment2FA <- function(aln_file = "", reduced = FALSE) { #Check if the alignment file is provided and exists if (nchar(aln_file) == 0) { - stop("Error: Alignment file path must be provided.") + abort("Error: Alignment file path must be provided.") } if (!file.exists(aln_file)) { - stop(paste("Error: The alignment file '", aln_file, "' does not exist.")) + abort(paste("Error: The alignment file '", aln_file, "' does not exist.")) } # Check if the lineage file exists if (!file.exists(lin_file)) { - stop(paste("Error: The lineage file '", lin_file, "' does not exist.")) + abort(paste("Error: The lineage file '", lin_file, "' does not exist.")) } # Check that the 'reduced' parameter is logical if (!is.logical(reduced) || length(reduced) != 1) { - stop("Error: 'reduced' must be a single logical value (TRUE or FALSE).") + abort("Error: 'reduced' must be a single logical value (TRUE or FALSE).") } ## SAMPLE ARGS # aln_file <- "data/rawdata_aln/pspc.gismo.aln" @@ -400,7 +404,7 @@ convertAlignment2FA <- function(aln_file = "", #' #' @importFrom dplyr filter pull #' @importFrom stringr str_locate -#' @importFrom rlang sym +#' @importFrom rlang abort sym #' #' @return Character string. The modified line from the Fasta file header with #' the name instead of the accession number. @@ -418,16 +422,16 @@ convertAlignment2FA <- function(aln_file = "", mapAcc2Name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") { # Check if acc2name is a data frame if (!is.data.frame(acc2name)) { - stop("Error: acc2name must be a data frame.") + abort("Error: acc2name must be a data frame.") } # Check if the specified columns exist in the data frame if (!(acc_col %in% colnames(acc2name))) { - stop("Error: The specified acc_col '", acc_col, "' does not exist in + abort("Error: The specified acc_col '", acc_col, "' does not exist in acc2name.") } if (!(name_col %in% colnames(acc2name))) { - stop("Error: The specified name_col '", name_col, "' does not exist in + abort("Error: The specified name_col '", name_col, "' does not exist in acc2name.") } @@ -454,6 +458,7 @@ mapAcc2Name <- function(line, acc2name, acc_col = "AccNum", name_col = "Name") { #' #' @importFrom purrr map #' @importFrom readr read_lines write_lines +#' @importFrom rlang abort #' #' @return Character vector containing the modified lines of the Fasta file. #' @export @@ -467,14 +472,14 @@ rename_fasta <- function(fa_path, outpath, replacement_function = map_acc2name, ...) { # Check if the input FASTA file exists if (!file.exists(fa_path)) { - stop("Error: The input FASTA file does not exist at the specified + abort("Error: The input FASTA file does not exist at the specified path: ", fa_path) } # Check if the output path is writable outdir <- dirname(outpath) if (!dir.exists(outdir)) { - stop("Error: The output directory does not exist: ", outdir) + abort("Error: The output directory does not exist: ", outdir) } lines <- read_lines(fa_path) res <- map(lines, function(x) { @@ -513,6 +518,7 @@ rename_fasta <- function(fa_path, outpath, #' #' @importFrom purrr pmap #' @importFrom stringr str_replace_all +#' @importFrom rlang abort #' #' @return NULL. The function saves the output FASTA files to the specified #' directory. @@ -535,7 +541,7 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), reduced = F) { # Check if the alignment path exists if (!dir.exists(aln_path)) { - stop("Error: The alignment directory does not exist at the specified + abort("Error: The alignment directory does not exist at the specified path: ", aln_path) } @@ -548,7 +554,7 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), # Check if the linear file exists if (!file.exists(lin_file)) { - stop("Error: The linear file does not exist at the specified path: ", + abort("Error: The linear file does not exist at the specified path: ", lin_file) } # library(here) @@ -602,6 +608,7 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), #' @importFrom future future plan #' @importFrom purrr map #' @importFrom rentrez entrez_fetch +#' @importFrom rlang abort #' #' @return A Fasta file is written to the specified `outpath`. #' @export @@ -617,11 +624,11 @@ generateAllAlignments2FA <- function(aln_path = here("data/rawdata_aln/"), acc2FA <- function(accessions, outpath, plan = "sequential") { if (!is.character(accessions) || length(accessions) == 0) { - stop("Error: 'accessions' must be a non-empty character vector.") + abort("Error: 'accessions' must be a non-empty character vector.") } if (!dir.exists(dirname(outpath))) { - stop("Error: The output directory does not exist: ", dirname(outpath)) + abort("Error: The output directory does not exist: ", dirname(outpath)) } # validation @@ -708,7 +715,7 @@ acc2FA <- function(accessions, outpath, plan = "sequential") { #' @param accnum_col Column from prot_data that contains Accession Numbers #' #' @importFrom dplyr filter pull -#' @importFrom rlang sym +#' @importFrom rlang abort sym #' #' @return A character vector containing representative accession numbers, #' one for each distinct observation in the specified 'reduced' column. @@ -728,18 +735,18 @@ createRepresentativeAccNum <- function(prot_data, # Validate input if (!is.data.frame(prot_data)) { - stop("Error: 'prot_data' must be a data frame.") + abort("Error: 'prot_data' must be a data frame.") } # Check if the reduced column exists in prot_data if (!(reduced %in% colnames(prot_data))) { - stop("Error: The specified reduced column '", reduced, "' does not + abort("Error: The specified reduced column '", reduced, "' does not exist in the data frame.") } # Check if the accnum_col exists in prot_data if (!(accnum_col %in% colnames(prot_data))) { - stop("Error: The specified accession number column '", accnum_col, "' + abort("Error: The specified accession number column '", accnum_col, "' does not exist in the data frame.") } # Get Unique reduced column and then bind the AccNums back to get one AccNum per reduced column @@ -784,6 +791,7 @@ createRepresentativeAccNum <- function(prot_data, #' #' @importFrom Biostrings readAAStringSet #' @importFrom msa msaMuscle msaClustalOmega msaClustalW +#' @importFrom rlang abort #' #' @return aligned fasta sequence as a MsaAAMultipleAlignment object #' @export @@ -798,11 +806,11 @@ createRepresentativeAccNum <- function(prot_data, alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { # Validate the input FASTA file if (!file.exists(fasta_file)) { - stop("Error: The FASTA file does not exist: ", fasta_file) + abort("Error: The FASTA file does not exist: ", fasta_file) } if (file_ext(fasta_file) != "fasta" && file_ext(fasta_file) != "fa") { - stop("Error: The specified file is not a valid FASTA file: ", fasta_file) + abort("Error: The specified file is not a valid FASTA file: ", fasta_file) } fasta <- readAAStringSet(fasta_file) @@ -832,6 +840,7 @@ alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { #' #' @importFrom Biostrings unmasked #' @importFrom readr write_file +#' @importFrom rlang abort #' #' @return Character string of the FASTA content that was written to the file. #' @export @@ -846,18 +855,18 @@ alignFasta <- function(fasta_file, tool = "Muscle", outpath = NULL) { writeMSA_AA2FA <- function(alignment, outpath) { # Validate input alignment if (!inherits(alignment, "AAMultipleAlignment")) { - stop("Error: The alignment must be of type 'AAMultipleAlignment'.") + abort("Error: The alignment must be of type 'AAMultipleAlignment'.") } # Check the output path is a character string if (!is.character(outpath) || nchar(outpath) == 0) { - stop("Error: Invalid output path specified.") + abort("Error: Invalid output path specified.") } # Check if the output directory exists outdir <- dirname(outpath) if (!dir.exists(outdir)) { - stop("Error: The output directory does not exist: ", outdir) + abort("Error: The output directory does not exist: ", outdir) } l <- length(rownames(alignment))