| Title: | Automated Deep-Time Phylogenetic Tree Collapsing and Visualization |
| Version: | 1.1.5 |
| Author: | Zeng Zichao [aut, cre] |
| Maintainer: | Zeng Zichao <zengzichao@sjtu.edu.cn> |
| Description: | Provides a single-function pipeline for automated collapsing and visualization of large phylogenetic trees with geological timescales. Automatically parses taxonomic labels from multiple formats (GTDB, Silva, NCBI, embedded, custom), identifies Most Recent Common Ancestors (MRCAs), assigns color-blind-safe palettes, executes batch collapsing with automatic nesting-aware ordering, integrates 'deeptime' geologic time scales with adaptive time breaks and unit switching, and manages smart legend layout. Supports special ancestral node identifiers (LUCA, LACA, LBCA) for highlighting key nodes in the tree of life. Provides external taxonomy file support for trees with incomplete or missing taxonomic labels. Features real-time logging with timestamps, step tracking, and multiple log levels. Includes comprehensive input validation for tree and sequence file formats. Reduces a 60-line manual workflow to a single function call while preserving full compatibility with the 'ggtree'/'deeptime' ecosystem. The visualization pipeline builds on 'ggtree' Yu et al. (2017) <doi:10.1111/2041-210X.12628>, 'deeptime' Gearty (2025) <doi:10.1080/20964471.2025.2537516>, and 'ape' Paradis and Schliep (2019) <doi:10.1093/bioinformatics/bty633>. |
| License: | MIT + file LICENSE |
| Depends: | R (≥ 4.1.0) |
| Imports: | ape (≥ 5.0), ggtree (≥ 4.0.0), deeptime (≥ 1.0), ggplot2 (≥ 3.5.0), rlang, stringr (≥ 1.5), tidytree (≥ 0.4), viridisLite |
| Suggests: | treeio (≥ 1.0), phangorn (≥ 2.0), RColorBrewer, cowplot (≥ 1.1), patchwork (≥ 1.1), shiny (≥ 1.7), optparse (≥ 1.7), yaml, vdiffr (≥ 1.0), testthat (≥ 3.0), knitr, rmarkdown, covr, filelock, withr |
| Encoding: | UTF-8 |
| VignetteBuilder: | knitr |
| Config/roxygen2/version: | 8.0.0 |
| Config/testthat/edition: | 3 |
| URL: | https://github.com/zengzichao/Rclade, https://zengzichao.github.io/Rclade/ |
| BugReports: | https://github.com/zengzichao/Rclade/issues |
| NeedsCompilation: | no |
| Packaged: | 2026-09-15 16:09:30 UTC; zengzichao |
| Repository: | CRAN |
| Date/Publication: | 2026-09-26 16:40:32 UTC |
Acquire an advisory file lock for the active log file (L-C5)
Description
Uses the filelock package when available; otherwise it is a silent
no-op and parallel safety relies on the documented per-process log-file
convention. Lock acquisition is non-blocking (timeout = 0).
Usage
.acquire_log_lock()
Extract –config path from raw args (pre-parse)
Description
Scans the raw argument vector for --config <path> or --config=<path>
so the config can be loaded before optparse parsing fills in defaults.
Usage
.rclade_extract_config(args)
Release the advisory log file lock acquired by .acquire_log_lock()
Description
Release the advisory log file lock acquired by .acquire_log_lock()
Usage
.release_log_lock()
End of the Hadean eon / start of the Archean eon (Ma, ICS 2023/02)
Description
End of the Hadean eon / start of the Archean eon (Ma, ICS 2023/02)
Usage
RCLADE_HADEAN_END
Default margin factor for x-axis range extension
Description
Extends the x-axis range by 5% beyond the tree depth to prevent tip labels from being clipped at the plot boundary. Source: ICS chronostratigraphic chart convention for visual padding.
Usage
RCLADE_X_MARGIN_FACTOR
Minimum x-axis value used when the tree root reaches into the Hadean (4567–4031 Ma), so the full Hadean eon is visible in that case
Description
Minimum x-axis value used when the tree root reaches into the Hadean (4567–4031 Ma), so the full Hadean eon is visible in that case
Usage
RCLADE_X_MIN_FLOOR
Supported tree file extensions
Description
Supported tree file extensions
Usage
SUPPORTED_TREE_EXTENSIONS
Apply coordinate-system clip="off" (the only clip application point)
Description
Collapsed-triangle vertices (especially the MRCA apex) often extend beyond
the tip-based y-axis range, so the plot panel must NOT clip them. This
helper is the single, sanctioned place to add clip = "off":
rectangular ->
coord_cartesian(clip = "off")circular/fan ->
coord_polar(theta = "y", clip = "off")
Usage
add_clip_off(p, layout = "rectangular")
Arguments
p |
A ggplot object. |
layout |
"rectangular" or "circular". |
Details
A utils::packageVersion("ggplot2") guard protects against ggplot2
< 3.5.0 (which does not support clip = "off"): in that case we
log_warning and skip clip rather than silently mis-rendering.
Value
The ggplot object with the appropriate clip-off coordinate added.
Add geological event bands (e.g., GOE, NOE) to a tree plot
Description
Events are drawn as semi-transparent vertical bands covering the full vertical extent of the tree (but not the geological timescale panels).
Usage
add_geo_events(p, tree, events = NULL)
Arguments
p |
ggplot object |
tree |
phylo object (edge lengths in Ma) |
events |
Event specification. Can be:
If only |
Value
ggplot object
Add geological timescale to a tree plot
Description
Add geological timescale to a tree plot
Usage
add_geo_timescale(
p,
tree,
levels,
layout,
version = "ICS 2023/02",
actual_ntips = NULL,
timescale_mode = "radial",
timescale_position = "right",
angle = 360,
tree_start_position = "right"
)
Arguments
p |
ggplot object |
tree |
phylo object (edge lengths in Ma) |
levels |
Timescale levels vector, e.g., c("eras", "eons") |
layout |
Layout type |
version |
Geological timescale version. Default: "ICS 2023/02". |
Value
ggplot object
Add HPD (Highest Posterior Density) range to a tree plot
Description
Uses ggtree::geom_range() to display horizontal uncertainty bars
on internal nodes. Requires a node.data data frame attached to the
tree with a HPD column (list column of c(lower, upper) vectors).
Usage
add_hpd_range(p, tree, color = "firebrick")
Arguments
p |
ggplot object |
tree |
phylo object (with node.data containing HPD annotations) |
color |
Color for HPD bars. Default: "firebrick". |
Value
ggplot object
Add smart legend to a tree plot
Description
Add smart legend to a tree plot
Usage
add_smart_legend(p, colors, rank_name, position, nrow, ncol)
Arguments
p |
ggplot object |
colors |
Named color vector |
rank_name |
Display name for the rank |
position |
Position: cardinal direction or length-2 numeric vector |
nrow |
User-specified rows |
ncol |
User-specified columns |
Value
ggplot object
Add node support labels to a tree plot
Description
Add node support labels to a tree plot
Usage
add_support_labels(p, tree, threshold)
Arguments
p |
ggplot object |
tree |
phylo object (with node.data if from treedata) |
threshold |
Minimum support value to display |
Value
ggplot object
Add clade labels next to collapsed triangles
Description
Supports both rectangular and circular (fan) layouts. For rectangular: labels are at the tips' x-position, extending rightward. For circular: labels are at the tips' x-position (outer radius), angled along the MRCA's angular position, extending outward.
Usage
annotate_clade(
p,
tree,
mrca_map,
colors,
show_count = TRUE,
offset = 0,
fontsize = 3,
singleton_map = NULL
)
Arguments
p |
ggplot object |
tree |
phylo object |
mrca_map |
Output of compute_mrca_map() |
colors |
Named color vector |
show_count |
Whether to show species count |
offset |
Offset from the tree's right edge (tips). Default 0 places labels right at the tip line. |
fontsize |
Font size for labels (default 3) |
singleton_map |
Optional named list mapping single-species group names to their tip label. When provided, these tips are also labeled. |
Value
ggplot object
Batch plot timetrees from a directory of tree files
Description
Batch plot timetrees from a directory of tree files
Usage
batch_plot(
input_dir,
output_dir,
pattern = "*.tre",
format = "pdf",
width = 14,
height = 10,
overwrite = "ask",
ignore_malformed = FALSE,
...
)
Arguments
input_dir |
Input directory containing tree files |
output_dir |
Output directory for plots |
pattern |
File matching pattern (glob format, e.g., "*.tre") |
format |
Output format: "pdf", "png", "tiff", "svg", "eps" (default "pdf") |
width |
Output width in inches (default 14) |
height |
Output height in inches (default 10) |
overwrite |
Overwrite mode: "ask" (default), "force", or "no-clobber" |
ignore_malformed |
Logical. If |
... |
Additional arguments passed to plot_timetree() |
Value
Invisibly returns list of success/failure status
Execute batch operation with interrupt handling and progress
Description
Processes a list of items with progress tracking and graceful interrupt handling. If interrupted, reports how many items were completed before stopping.
Usage
batch_with_interrupt(items, fun, label_fun = NULL)
Arguments
items |
List or vector of items to process. |
fun |
Function to apply to each item. Receives (item, index). |
label_fun |
Optional function to generate label for each item. |
Value
List of results (NULL for items not processed due to interrupt).
Create base tree plot based on layout type
Description
Create base tree plot based on layout type
Usage
build_base_tree(
tree,
layout,
angle,
line_width,
branch.length = "branch.length"
)
Arguments
tree |
phylo object |
layout |
Layout type: "rectangular" or "circular" |
angle |
Fan angle for circular layout |
line_width |
Branch line width |
branch.length |
Branch length mode passed to ggtree. Use "none" to draw a cladogram where all tips are aligned (ignoring original branch lengths). Default: "branch.length" (use original edge lengths). |
Value
ggplot object
Build a full-rank taxonomy data.frame in a single pass (M-D4 helper)
Description
Used by clade-specific collapsing to avoid re-parsing every rank (and
re-reading any taxonomy file) once per search rank. Produces one
label-based full parse (format-specific parsers already compute all ranks
at once) supplemented/overridden by a single taxonomy-file read when
taxonomy_file is supplied.
Usage
build_full_taxa_df(
labels,
format = "auto",
custom_patterns = NULL,
taxonomy_file = NULL,
file_sep = "auto",
file_header = FALSE,
file_priority = TRUE,
table_sep = ";",
delimiter_mode = "reverse",
taxonomy_levels = NULL
)
Arguments
labels |
Character vector of tip labels. |
format |
Format: "auto", "GTDB", "Silva", "NCBI", "custom_rank", "custom_regex", "embedded". |
custom_patterns |
Custom regex patterns (for "custom_regex" format). |
taxonomy_file |
Character. Path to external taxonomy file. Default: NULL. |
file_sep |
Character. Column separator for taxonomy file. Default: "auto". |
file_header |
Logical. Whether taxonomy file has header row. Default: FALSE. |
file_priority |
Logical. If TRUE, file taxonomy takes priority over label-based parsing. Default: TRUE. |
table_sep |
Character. Separator between taxonomy ranks. Default: ";". |
delimiter_mode |
Character. Embedded parsing strategy. |
taxonomy_levels |
Custom taxonomy level configuration. Default: NULL. |
Value
data.frame with a label column plus one column per rank.
Build a group vector from custom groups
Description
Converts a named list of tip vectors into the named-vector format used
by compute_mrca_map().
Usage
build_group_vec(groups, tip_labels)
Arguments
groups |
Named list of character vectors (tip labels per group). |
tip_labels |
Character vector of all tip labels in the tree. |
Value
Named character vector: names = tip labels, values = group names,
NA for ungrouped tips.
Build file path safely (cross-platform)
Description
Wrapper around file.path() to ensure consistent path construction. Never use paste() or sprintf() for path construction.
Usage
build_path(...)
Arguments
... |
Path components. |
Value
Character. Constructed path.
Build plot_timetree parameter list from CLI options
Description
Build plot_timetree parameter list from CLI options
Usage
build_plot_timetree_params(
opt,
color_palette,
color_mapping = NULL,
taxonomy_levels = NULL
)
Build taxonomy lookup from file
Description
Creates a lookup table from a taxonomy file that can be used to supplement or override label-based taxonomy parsing.
Usage
build_taxonomy_lookup(file, sep = "auto", header = FALSE, table_sep = ";")
Arguments
file |
Character. Path to the taxonomy table file. |
sep |
Character. Column separator. Default: |
header |
Logical. Whether the file has a header row. Default: |
table_sep |
Character. Separator between taxonomy ranks in the second
column. Default: |
Value
A named list where names are tip labels and values are data.frame rows with taxonomy information.
Check a single dependency
Description
Check a single dependency
Usage
check_dependency(name, min_version, required, verbose = TRUE)
Arguments
verbose |
Logical. Report progress when TRUE. |
Check example tree loading and structure
Description
Check example tree loading and structure
Usage
check_example_tree(verbose = TRUE)
Arguments
verbose |
Logical. Report progress when TRUE. |
Check input validation functions
Description
Check input validation functions
Usage
check_input_validation(verbose = TRUE)
Arguments
verbose |
Logical. Report progress when TRUE. |
Check for malicious characters in node names
Description
Detects control characters and Unicode bidirectional text markers that could be used for display spoofing.
Usage
check_malicious_chars(names, filepath = "<unknown>")
Arguments
names |
Character vector of node names to check. |
filepath |
Character. Source file for error messages. |
Value
Invisibly returns TRUE if clean. Stops on detection.
Check if a taxonomic group is monophyletic
Description
Tests whether all tips belonging to a specified taxonomic group form a monophyletic clade in the tree.
Usage
check_monophyly(
tree,
group,
rank,
format = "auto",
custom_patterns = NULL,
quiet = FALSE,
delimiter_mode = "reverse",
taxonomy_levels = NULL
)
Arguments
tree |
A |
group |
Character. The name of the taxonomic group to check
(e.g., |
rank |
Character. Taxonomic rank of the group. One of |
format |
Character. Taxonomy label format. One of |
custom_patterns |
Named list of regex patterns for custom format.
Required when |
quiet |
Logical. If |
delimiter_mode |
Character. Embedded (Format A) parsing strategy:
|
taxonomy_levels |
Custom taxonomy level configuration (list with codes and names).
Default: |
Value
A list with components:
- is_monophyletic
Logical. Whether the group is monophyletic.
- group
Character. The group name.
- n_tips
Integer. Number of tips belonging to the group.
- mrca_node
Integer or NULL. The MRCA node number, or NULL if the group has fewer than 2 tips.
- outsiders
Character vector. Tips in the MRCA clade that do not belong to the group (empty if monophyletic).
Case sensitivity (L-A2)
Group matching is case-insensitive. The query group and every
parsed Group label are lower-cased with tolower() at
comparison time (not during parsing) before matching, so
"Proteobacteria" and "proteobacteria" match the same clade.
parse_taxonomy itself preserves the original case of parsed
labels; the lower-casing applied here is local to this comparison and keeps
the two modules consistent about what a group name refers to.
Examples
data(example_tree)
# Check if phylum P1 is monophyletic
result <- check_monophyly(example_tree, "P1",
rank = "phylum", format = "GTDB")
if (result$is_monophyletic) {
message("P1 is monophyletic!")
} else {
message("P1 is NOT monophyletic.")
}
Check monophyly logic with known cases
Description
Check monophyly logic with known cases
Usage
check_monophyly_logic(verbose = TRUE)
Arguments
verbose |
Logical. Report progress when TRUE. |
Check if a special identifier corresponds to a monophyletic group
Description
Tests whether the MRCA of the specified domains (identified by LUCA/LACA/LBCA) contains only tips from those domains (i.e., is monophyletic with respect to the target domains).
Usage
check_special_monophyly(
tree,
identifier,
format = "auto",
quiet = FALSE,
delimiter_mode = "reverse",
taxonomy_levels = NULL
)
Arguments
tree |
A |
identifier |
Character. One of |
format |
Character. Taxonomy label format. Default: |
quiet |
Logical. If TRUE, suppress informational messages. Default: FALSE. |
delimiter_mode |
Character. Embedded parsing strategy: |
taxonomy_levels |
Custom taxonomy level configuration (list with codes and names).
Default: |
Value
A list with components:
- is_monophyletic
Logical. Whether the group is monophyletic.
- identifier
Character. The identifier name.
- node
Integer or NULL. The MRCA node number.
- n_tips
Integer. Number of tips in the target domains.
- n_outsiders
Integer. Number of outsider tips in the MRCA clade.
- outsider_domains
Character vector. Domains of outsider tips.
Examples
data(example_tree)
result <- check_special_monophyly(example_tree, "LBCA")
if (result$is_monophyletic) {
message("LBCA is monophyletic!")
}
Check taxonomy extraction from example tree
Description
Check taxonomy extraction from example tree
Usage
check_taxonomy_extraction(verbose = TRUE)
Arguments
verbose |
Logical. Report progress when TRUE. |
Clean up resources on interruption
Description
Closes open connections, removes incomplete temp files.
Usage
cleanup_on_interrupt()
Compute legend row/column layout
Description
Compute legend row/column layout
Usage
compute_legend_layout(n_groups, position, nrow, ncol)
Arguments
n_groups |
Number of groups |
position |
Position ("right", "left", "top", "bottom", "inside") |
nrow |
User-specified rows (can be NULL) |
ncol |
User-specified columns (can be NULL) |
Value
list(nrow = integer, ncol = integer)
Compute MRCA node mapping for each taxonomic group
Description
Compute MRCA node mapping for each taxonomic group
Usage
compute_mrca_map(tree, group_vec, check_monophyly = TRUE, strict = FALSE)
Arguments
tree |
phylo object |
group_vec |
Named vector (names = tip labels, values = group names, NA = ungrouped) |
check_monophyly |
Logical. If TRUE (default), check if each group is monophyletic before adding to collapse plan. Non-monophyletic groups will be skipped with a warning. |
strict |
Logical. If TRUE, non-monophyletic groups cause an error instead of a warning. Default: FALSE. |
Value
Named list: each element is list(node = integer, tip_count = integer)
Compute adaptive time breaks for x-axis
Description
Compute adaptive time breaks for x-axis
Usage
compute_time_breaks(x_min, x_max)
Arguments
x_min |
Minimum x value (negative, in Ma) |
x_max |
Maximum x value (usually 0) |
Value
List with breaks, labels, unit_label
Compute x-axis minimum from tree depth
Description
Calculates the leftmost x-axis value by finding the maximum tree depth and applying a 5% margin extension for visual clarity. The axis range is adaptive: for trees whose root is younger than the end of the Hadean eon (4031 Ma), the axis starts slightly beyond the root so the tree occupies the full panel width. Only when the root reaches into the Hadean is the axis floored at -4567 Ma, so the entire Hadean eon is shown exactly when it is relevant.
Usage
compute_x_min(tree)
Arguments
tree |
phylo object with edge lengths |
Value
Negative x_min value (in same units as edge lengths, typically Ma)
Convert time units (Ga -> Ma)
Description
Convert time units (Ga -> Ma)
Usage
convert_unit(tree, unit)
Arguments
tree |
phylo object |
unit |
Time unit "Ga" or "Ma" |
Value
Modified phylo object (copy, original unchanged)
Detect sequence alphabet from characters
Description
Detect sequence alphabet from characters
Usage
detect_alphabet(chars)
Arguments
chars |
Character vector of individual sequence characters. |
Value
Character. One of "DNA", "RNA", "protein", "unknown".
Detect file encoding
Description
Detect file encoding
Usage
detect_encoding(filepath, n_lines = 10)
Arguments
filepath |
Character. Path to file. |
n_lines |
Integer. Number of initial lines sampled for UTF-8 validity (in addition to a fixed 10 KB raw-byte prefix used for BOM / endianness detection). Sampling the head is sufficient because BOM and byte-order markers appear at file start, and U+FFFD substitution surfaces early. |
Value
Character. Detected encoding name.
Detect sequence file format
Description
Detect sequence file format
Usage
detect_sequence_format(filepath)
Detect taxonomy format from tip labels
Description
Detects Format A (embedded: _d_Bacteria_p_...) or
Format B (semicolon-delimited: d__Bacteria;p__...).
Usage
detect_taxonomy_format(labels)
Arguments
labels |
Character vector of tip labels |
Value
Format name: "embedded", "GTDB", "Silva", "NCBI", or "unknown"
Regex heuristic boundaries (L-C3)
Detection and parsing here are heuristic regex passes, not a strict grammar. Known boundaries the caller must respect:
-
Underscores in names: under
delimiter_mode = "reverse"the pattern uses[^_]+?, so an underscore inside a taxon name (e.g._g_Clostridium_sensu_stricto_s_X) can be mis-read as a rank separator. Names that contain underscores should usedelimiter_mode = "segment"(delimiter-to-delimiter extraction), which preserves embedded underscores. For Format B (;-delimited) underscores are safe. -
Custom regex backtracking: caller-supplied
custom_patternsare inserted verbatim into the parser. Unbounded repeating groups (e.g.(.+)+) can cause catastrophic backtracking on adversarial labels. Patterns are rejected above the 200-character limit, but keep sub-patterns bounded and anchored. -
Detection is content-based:
detect_taxonomy_formatsamples labels; a mixed or malformed corpus may return"unknown", in which case the caller must fall back to an explicitformat=. -
GTDB requires a semicolon majority (M-B3): the GTDB rule additionally requires that more than half of sampled labels contain a semicolon. Accession-prefixed embedded labels with double-underscore rank separators (e.g.
GCA_xxx_d__Archaea_p__Nanoarchaeota) satisfy the[dpcofgsk]__pattern but contain no semicolons; they are detected as"embedded"rather than misclassified as GTDB. The embedded parsers also tolerate double-underscore separators.
Detect and validate tree file format
Description
Detect and validate tree file format
Usage
detect_tree_format(filepath)
Arguments
filepath |
Character. Path to tree file. |
Value
Character. Detected format: "newick", "nexus", "beast", "unknown".
Ensure directory exists, create if needed
Description
Ensure directory exists, create if needed
Usage
ensure_dir(dirpath)
Arguments
dirpath |
Character. Directory path. |
Value
Invisibly returns the path.
Escape a string for safe use inside a regular expression
Description
Wraps every regex-metacharacter in a backslash so the resulting string can
be embedded literally in a pattern. Used by the semicolon-delimited parser
(and any other code that turns a user separator into a regex) so that a
separator such as "." or "+" is matched as a literal character
rather than as a metacharacter.
Usage
escape_regex(x)
Arguments
x |
Character scalar to escape. |
Value
Escaped character scalar.
Example phylogenetic tree with GTDB-style labels
Description
A phylo object with 50 tips containing GTDB-format taxonomic labels
spanning 5 coded phyla (P1, P2, P3, P4, P5) and 10 coded classes (C1, ..., C10)
for demonstration and testing purposes. Branch lengths are in Ma (mega-annum).
This tree is fully bifurcating with proper monophyletic groups at all
taxonomic levels. All labels are artificial codes, not real taxon names.
Usage
data(example_tree)
Format
A phylo object with 50 tips and 49 internal nodes.
Source
Simulated data for package demonstration.
Find circular dependencies between two rank columns
Description
Find circular dependencies between two rank columns
Usage
find_rank_cycles(taxa_df, rank_high, rank_low)
Arguments
taxa_df |
data.frame with taxonomy columns. |
rank_high |
Character. Higher rank column name. |
rank_low |
Character. Lower rank column name. |
Value
Character vector of cycle descriptions (empty if none).
Format elapsed time
Description
Format elapsed time
Usage
format_elapsed()
Format step counter
Description
Format step counter
Usage
format_step()
Format timestamp in ISO 8601 with milliseconds and timezone offset
Description
Format timestamp in ISO 8601 with milliseconds and timezone offset
Usage
format_timestamp()
Generate color mapping for taxonomic groups
Description
Generate color mapping for taxonomic groups
Usage
generate_colors(groups, palette = "viridis", color_mapping = NULL)
Arguments
groups |
Character vector of group names |
palette |
Palette name (e.g., "viridis", "Set1", "rainbow") or color vector |
color_mapping |
Named vector of specific color assignments (highest priority) |
Value
Named color vector (names = groups)
Get dependency versions
Description
Get dependency versions
Usage
get_dependency_versions()
Get the current git short hash of the installed package source
Description
Consolidates the previously duplicated git-hash detection found in
cli.R::get_version_string() and logo.R::rclade_logo().
Returns "unknown" when not running from a git working tree or when
git is unavailable / errors.
Usage
get_git_hash()
Value
Character: short git hash (7 chars) or "unknown".
Get level prefix
Description
Get level prefix
Usage
get_level_prefix(level)
Get current progress summary
Description
Get current progress summary
Usage
get_progress_summary()
Value
Character string with progress info.
Get display name for a taxonomic rank
Description
Get display name for a taxonomic rank
Usage
get_rank_name(rank)
Arguments
rank |
Taxonomic rank (abbreviation or full name) |
Value
Display name string
Get supported file extensions
Description
Get supported file extensions
Usage
get_supported_extensions()
Value
Named list of supported extensions by category.
Get taxonomy level configuration
Description
Returns the current taxonomy level mapping. Can be customized via
--taxonomy-levels option.
Usage
get_taxonomy_levels(custom_levels = NULL)
Arguments
custom_levels |
Named list or NULL. If NULL, uses defaults. |
Value
List with codes and names vectors.
Get package version with git hash if available
Description
Get package version with git hash if available
Usage
get_version_string()
Highlight monophyletic clades on a tree plot
Description
Adds colored highlighting for specified taxonomic groups. Only monophyletic groups are highlighted; non-monophyletic groups trigger a warning. Supports special identifiers LUCA, LACA, LBCA for ancestral nodes.
Usage
highlight_clades(
p,
tree,
groups,
rank,
format = "auto",
colors = NULL,
alpha = 0.2,
custom_patterns = NULL,
delimiter_mode = "reverse",
taxonomy_levels = NULL
)
Arguments
p |
A |
tree |
A |
groups |
Character vector of group names to highlight.
Can include special identifiers: |
rank |
Character. Taxonomic rank of the groups (ignored for special identifiers). |
format |
Character. Taxonomy label format. Default: |
colors |
Named character vector of colors for each group.
If |
alpha |
Numeric. Transparency of the highlight. Default: |
custom_patterns |
Named list of regex patterns for custom format. |
taxonomy_levels |
Custom taxonomy level configuration (list with codes and names).
Default: |
Value
A ggplot object with highlights added.
Initialize progress tracking for a batch operation
Description
Initialize progress tracking for a batch operation
Usage
init_progress_tracking(total = 0, preserve_temp_files = FALSE)
Arguments
total |
Integer. Total number of items to process. |
preserve_temp_files |
Logical. If TRUE, do not reset temp_files list (used when nesting inside an already-active interrupt context). |
Initialize step counter for progress tracking
Description
Initialize step counter for progress tracking
Usage
init_steps(total)
Arguments
total |
Integer. Total number of steps. |
Get numeric value for log level
Description
Get numeric value for log level
Usage
level_to_num(level)
Log a CRITICAL message
Description
Log a CRITICAL message
Usage
log_critical(..., .module = NULL)
Arguments
... |
Message components (passed to sprintf if multiple). |
.module |
Character. Optional module/function tag (§15). Default: NULL. |
Log a DEBUG message
Description
Log a DEBUG message
Usage
log_debug(..., .module = NULL)
Arguments
... |
Message components (passed to sprintf if multiple). |
.module |
Character. Optional module/function tag (§15). Default: NULL. |
Log an ERROR message
Description
Log an ERROR message
Usage
log_error(..., .module = NULL)
Arguments
... |
Message components (passed to sprintf if multiple). |
.module |
Character. Optional module/function tag (§15). Default: NULL. |
Log an INFO message
Description
Log an INFO message
Usage
log_info(..., .module = NULL)
Arguments
... |
Message components (passed to sprintf if multiple). |
.module |
Character. Optional module/function tag (§15). Default: NULL. |
Log a key-value pair
Description
Log a key-value pair
Usage
log_keyvalue(key, value, level = "INFO")
Arguments
key |
Character. Key name. |
value |
Any. Value to display. |
level |
Character. Log level. Default: "INFO". |
Log current memory usage at DEBUG level
Description
Attempts to report memory usage. Uses gc() for R memory stats.
Usage
log_memory(label = "")
Arguments
label |
Character. Label for the memory checkpoint. |
Log a message with real-time flush
Description
Log a message with real-time flush
Usage
log_message(level, ..., .flush = TRUE, .module = NULL)
Arguments
level |
Character. Log level. |
... |
Message components. |
.flush |
Logical. Whether to flush immediately. Default: TRUE. |
.module |
Character. Optional module/function tag for §15 error message
format. When non-empty, inserted as |
Log a progress indicator
Description
Log a progress indicator
Usage
log_progress(current, total, item = "")
Arguments
current |
Integer. Current progress. |
total |
Integer. Total items. |
item |
Character. Description of current item. |
Print a formatted section header
Description
Print a formatted section header
Usage
log_section(title)
Arguments
title |
Character. Section title. |
Print summary statistics
Description
Print summary statistics
Usage
log_stats(stats)
Arguments
stats |
Named list of statistics. |
Print a formatted subsection header
Description
Print a formatted subsection header
Usage
log_subsection(title)
Arguments
title |
Character. Subsection title. |
Print a formatted table
Description
Print a formatted table
Usage
log_table(data, title = NULL)
Arguments
data |
Named list or data.frame to display. |
title |
Character. Optional table title. |
Log a WARNING message
Description
Log a WARNING message
Usage
log_warning(..., .module = NULL)
Arguments
... |
Message components (passed to sprintf if multiple). |
.module |
Character. Optional module/function tag (§15). Default: NULL. |
Create and manage temporary directory with automatic cleanup
Description
Create and manage temporary directory with automatic cleanup
Usage
managed_tempdir(pattern = "rclade_")
Arguments
pattern |
Character. Directory name pattern. |
Value
List with path and cleanup function.
Create and manage temporary file with automatic cleanup
Description
Creates a temporary file and registers cleanup via on.exit().
Usage
managed_tempfile(pattern = "rclade_", fileext = ".tmp", tmpdir = tempdir())
Arguments
pattern |
Character. File name pattern. |
fileext |
Character. File extension. |
tmpdir |
Character. Temporary directory. Default: tempdir(). |
Value
List with path and cleanup function.
Increment step counter
Description
Increment step counter
Usage
next_step(step_name = NULL)
Arguments
step_name |
Character. Description of the step. |
Normalize line endings in a file
Description
Reads a file, normalizes line endings, and writes it back.
Usage
normalize_file_newlines(filepath)
Arguments
filepath |
Character. Path to file. |
Value
Invisibly returns the filepath.
Normalize line endings in text
Description
Converts all line endings to Unix style (LF).
Usage
normalize_newlines(text)
Arguments
text |
Character vector or single string. |
Value
Character with normalized line endings.
Normalize rank abbreviation to full name
Description
Normalize rank abbreviation to full name
Usage
normalize_rank(rank)
Arguments
rank |
Rank code or full name ("k","d","p","c","o","f","g","s","ss" or "kingdom","domain","phylum",...) |
Value
Standardized full name string
Parse custom rank format labels (Format A wrapper)
Description
Parse custom rank format labels (Format A wrapper)
Usage
parse_custom_rank(labels, levels = NULL, delimiter_mode = "reverse")
Arguments
labels |
Character vector of tip labels |
levels |
List with codes and names vectors. |
delimiter_mode |
Character. Embedded parsing strategy. |
Value
data.frame with taxonomy columns
Parse custom regex format labels
Description
Parse custom regex format labels
Usage
parse_custom_regex(labels, rank_patterns)
Arguments
labels |
Character vector of tip labels |
rank_patterns |
Named list of regex patterns |
Value
data.frame
Parse Format A: Embedded taxonomy labels
Description
Parses labels like GB_GCA_000252485.1_d_Bacteria_p_Cyanobacteriota_c_...
using delimiters _d_, _p_, _c_, _o_, _f_, _g_, _s_.
Usage
parse_embedded(labels, levels = NULL, delimiter_mode = "reverse")
Arguments
labels |
Character vector of tip labels |
levels |
List with codes and names vectors for taxonomy levels. |
delimiter_mode |
Character. One of |
Details
Supports three delimiter matching strategies:
-
"reverse"(default): match ranks from right-to-left to reduce ambiguity when taxonomy names contain underscores. -
"greedy": match ranks left-to-right using a character-class boundary (faster but less robust to underscores in names). -
"segment": extract the segment between each rank delimiter and the next rank delimiter, preserving underscores within values.
All three strategies tolerate double-underscore rank separators
(e.g. _p__Nanoarchaeota, common in accession-prefixed embedded
labels); leading underscores left over from such schemes are trimmed from
parsed values.
Value
data.frame with taxonomy columns
Parse GTDB format labels (wrapper for parse_semicolon_delimited)
Description
Parse GTDB format labels (wrapper for parse_semicolon_delimited)
Usage
parse_gtdb(labels, levels = NULL, sep = ";")
Arguments
labels |
Character vector of tip labels |
levels |
List with codes and names vectors. |
sep |
Character. Separator between taxonomy ranks. Default: |
Value
data.frame with taxonomy columns
Parse NCBI format labels
Description
Parse NCBI format labels
Usage
parse_ncbi(labels, quiet = FALSE)
Arguments
labels |
Character vector of tip labels |
quiet |
Logical. If TRUE, suppress the positional mapping warning. |
Value
data.frame with columns: domain, phylum, class, order, family, genus, species
Parse raw UI / CLI strings into structured plot parameters
Description
This is the ONLY place that converts raw UI strings (comma-separated
highlight lists, "A:#FF0000,B:#00FF00" color mappings, "k:k,ss:ss"
taxonomy level specs, "auto"/"tab"/"comma" separators) into the
structured R objects expected by plot_timetree().
Usage
parse_plot_params(
color_mapping = NULL,
taxonomy_levels = NULL,
highlight = NULL,
taxonomy_file_sep = "auto"
)
Arguments
color_mapping |
Character string "GroupA:#FF0000,GroupB:#00FF00", or an
already-structured named vector/list. A single bare hex ("#FF0000") is
returned as a length-1 color vector (M-E2 / L-D7). |
taxonomy_levels |
Character string "k:k,ss:ss", or a pre-built
|
highlight |
Character string "LUCA, LACA", or a character vector.
|
taxonomy_file_sep |
One of "auto", "tab", "comma", or an already-resolved separator (a literal tab, ",", or "auto"). |
Details
Both the CLI (build_plot_timetree_params) and the Shiny
server() must route their raw inputs through this function so that
parsing logic lives in exactly one location.
Value
A named list with components:
color_mapping |
named character vector or |
taxonomy_levels |
list(codes, names) or |
highlight |
character vector or |
taxonomy_file_sep |
character scalar |
Parse Format B: Semicolon-delimited taxonomy (GTDB-style)
Description
Parses labels like d__Bacteria;p__Cyanobacteriota;c__Cyanobacteriia;...
where empty values like s__ are parsed as NA.
Usage
parse_semicolon_delimited(labels, levels = NULL, sep = ";")
Arguments
labels |
Character vector of tip labels |
levels |
List with codes and names vectors for taxonomy levels. |
sep |
Character. Separator between taxonomy ranks. Default: |
Value
data.frame with taxonomy columns
Parse Silva format labels
Description
Parse Silva format labels
Usage
parse_silva(labels)
Arguments
labels |
Character vector of tip labels |
Value
data.frame with columns: domain, phylum, class, order, family, genus, species
Unified taxonomy parsing entry point
Description
Parses taxonomic information from tip labels using the specified format and returns a data.frame of group assignments. Intended for use as a stable library API by external workflows (e.g., Snakemake/Nextflow).
Usage
parse_taxonomy(
labels,
rank,
format = "auto",
custom_patterns = NULL,
taxonomy_levels = NULL,
delimiter_mode = "reverse"
)
Arguments
labels |
Character vector of tip labels |
rank |
Taxonomic rank (abbreviation or full name) |
format |
Format: "auto", "embedded", "GTDB", "Silva", "NCBI", "custom_rank", "custom_regex" |
custom_patterns |
Custom regex patterns (required when format = "custom_regex") |
taxonomy_levels |
Custom taxonomy level configuration (list with codes and names) |
delimiter_mode |
Character. Embedded parsing strategy: "reverse", "greedy", "segment". |
Value
data.frame with columns: label, Group
Parse taxonomy with external file support
Description
Extended taxonomy parsing that can use an external taxonomy file to supplement or override label-based parsing. Useful when:
Tip labels lack taxonomy information
Only some tips have taxonomy in their labels
External taxonomy data is more complete or accurate
Usage
parse_taxonomy_with_file(
labels,
rank,
format = "auto",
custom_patterns = NULL,
taxonomy_file = NULL,
file_sep = "auto",
file_header = FALSE,
file_priority = TRUE,
table_sep = ";",
delimiter_mode = "reverse",
taxonomy_levels = NULL
)
Arguments
labels |
Character vector of tip labels. |
rank |
Taxonomic rank (abbreviation or full name). |
format |
Format: "auto", "GTDB", "Silva", "NCBI", "custom_rank", "custom_regex". |
custom_patterns |
Custom regex patterns (for "custom_regex" format). |
taxonomy_file |
Character. Path to external taxonomy file. Default: |
file_sep |
Character. Column separator for taxonomy file. Default: |
file_header |
Logical. Whether taxonomy file has header row. Default: |
file_priority |
Logical. If |
table_sep |
Character. Separator between taxonomy ranks in the second
column of the taxonomy file. Default: |
delimiter_mode |
Character. Embedded parsing strategy: "reverse", "greedy", "segment". |
taxonomy_levels |
Custom taxonomy level configuration (list with codes and names).
Used to extend or override default rank handling. Default: |
Value
data.frame with columns: label, Group.
Plot a phylogenetic tree with geological timescale and taxonomic collapsing
Description
The main entry point of Rclade. Takes a phylogenetic tree object or file path and produces a publication-ready visualization with automatic taxonomic collapsing, geological timescale integration, and smart legend layout.
Usage
plot_timetree(
tree,
tree_index = NULL,
multi_tree_mode = "error",
rank = "none",
triangle_mode = "mixed",
space_mode = "proportional",
layout = "rectangular",
angle = 360,
color_palette = "viridis",
color_mapping = NULL,
line_width = 1,
show_tip_labels = FALSE,
tip_label_size = 2,
add_timescale = TRUE,
timescale_levels = c("eras", "eons"),
unit = NULL,
taxonomy_format = "auto",
custom_patterns = NULL,
taxonomy_file = NULL,
taxonomy_file_sep = "auto",
taxonomy_file_header = FALSE,
taxonomy_file_priority = TRUE,
taxonomy_source_priority = NULL,
taxonomy_table_sep = ";",
taxonomy_delimiter_mode = "reverse",
legend_position = "bottom",
legend_nrow = NULL,
legend_ncol = NULL,
legend_title = NULL,
clade = NULL,
strict = FALSE,
groups = NULL,
show_clade_label = FALSE,
show_clade_count = TRUE,
clade_label_offset = 50,
clade_label_fontsize = 3,
show_support = FALSE,
support_threshold = 0.95,
show_hpd = FALSE,
hpd_color = "firebrick",
geo_events = FALSE,
timescale_version = "ICS 2023/02",
main_title = NULL,
sub_title = NULL,
highlight = NULL,
highlight_alpha = 0.2,
theme_fun = theme_timetree,
output = NULL,
overwrite = "ask",
width = 14,
height = 10,
taxonomy_levels = NULL,
low_memory = FALSE,
ignore_malformed = FALSE,
ignore_branch_length = FALSE,
color_rank = NULL,
timescale_mode = "radial",
timescale_position = "right",
tree_start_position = "right",
opts = NULL
)
Arguments
tree |
A |
tree_index |
Integer. Index of tree to use from multiPhylo objects (e.g., BEAST posterior).
Only used when |
multi_tree_mode |
Character. How to handle multiple trees in a file.
Options: |
rank |
Taxonomic rank to collapse at. One of:
|
triangle_mode |
Collapse triangle visualization mode.
|
space_mode |
Space allocation strategy for collapsed clades.
|
layout |
Tree layout. |
angle |
Fan angle in degrees for circular layout (0-360).
Only used when |
color_palette |
Color palette specification. Can be:
|
color_mapping |
Named character vector of specific color assignments.
Takes highest priority over |
line_width |
Branch line width (passed to ggtree). Default: |
show_tip_labels |
Logical. Whether to display tip labels.
Default: |
tip_label_size |
Numeric. Tip label font size. Default: |
add_timescale |
Logical. Whether to add a geological timescale to the x-axis.
Requires rectangular layout and valid edge lengths. Default: |
timescale_levels |
Character vector of timescale levels to display.
Options: |
unit |
Time unit of input tree edge lengths: |
taxonomy_format |
Taxonomy label format. |
custom_patterns |
Named list of regex patterns for custom format parsing.
Required when |
taxonomy_file |
Character. Path to an external taxonomy file. The file
should have two columns: (1) tip labels and (2) taxonomy strings in GTDB
format (e.g., |
taxonomy_file_sep |
Character. Column separator for taxonomy file.
|
taxonomy_file_header |
Logical. Whether taxonomy file has a header row.
Default: |
taxonomy_file_priority |
Logical. If |
taxonomy_source_priority |
Character. Which taxonomy source takes priority
when both embedded (label-based) and table (file-based) taxonomy are available:
|
taxonomy_table_sep |
Character. Separator between taxonomy ranks in the
second column of an external taxonomy file. Default: |
taxonomy_delimiter_mode |
Character. Embedded (Format A) parsing strategy:
|
legend_position |
Legend placement. Can be a cardinal direction
( |
legend_nrow |
Integer. Number of rows in legend grid. Auto-computed if NULL. |
legend_ncol |
Integer. Number of columns in legend grid. Auto-computed if NULL. |
legend_title |
Character. Custom legend title. If |
clade |
Character. Specific clade name to collapse (e.g., "Cyanobacteriota").
When provided, only this clade is checked for monophyly and collapsed if valid.
Mutually exclusive with |
strict |
Logical. If |
groups |
Named list of custom tip groups for collapsing. Each element
is a character vector of tip labels belonging to that group. Groups must be
monophyletic; non-monophyletic groups will raise an error. When |
show_clade_label |
Logical. Whether to add clade labels next to collapsed
triangles showing group name and species count. Default: |
show_clade_count |
Logical. Whether to show species count in clade labels
(e.g., "Proteobacteria (n=42)"). Only used when |
clade_label_offset |
Numeric. Horizontal offset for clade labels from the
right edge of the collapsed triangle in Ma units (0-5000). Default: |
clade_label_fontsize |
Numeric. Font size for clade labels (1-20).
Default: |
show_support |
Logical. Whether to display node support values.
Requires treedata input with posterior/bootstrap annotations.
Default: |
support_threshold |
Numeric. Minimum support value to display (0-1).
Default: |
show_hpd |
Logical. Whether to display HPD (Highest Posterior Density)
intervals. Requires node data with HPD annotations. Default: |
hpd_color |
Color for HPD bars. Default: |
geo_events |
Data frame of geological events to annotate, with columns
|
timescale_version |
Geological timescale version string. Currently only
|
main_title |
Character. Main title for the plot. Default: |
sub_title |
Character. Subtitle for the plot. Default: |
highlight |
Character vector of group names to highlight with colored
backgrounds. Only monophyletic groups are highlighted; non-monophyletic
groups trigger a warning. Supports special identifiers:
|
highlight_alpha |
Numeric. Transparency of highlight color (0-1).
Default: |
theme_fun |
Theme function or NULL. Default: |
output |
Optional output file path. If provided, the plot is saved
immediately (backward compatibility). Default: |
overwrite |
Character. Overwrite mode when |
width |
Output width in inches. Default: |
height |
Output height in inches. Default: |
taxonomy_levels |
Optional list for custom taxonomy rank codes and
names, e.g. |
low_memory |
Logical. If |
ignore_malformed |
Logical. If |
ignore_branch_length |
Logical. If |
color_rank |
Character. Taxonomic rank for coloring, independent of
|
timescale_mode |
Character. Timescale display mode for circular layout:
|
timescale_position |
Character. Clock position of the timescale axis
when |
tree_start_position |
Character. Clock position where the tree starts
expanding (the gap between the last and first tip). One of |
opts |
A |
Details
This function orchestrates the complete Rclade pipeline:
Input validation and reading (format detection, unit conversion)
Taxonomy parsing (GTDB/Silva/NCBI/custom, clade/groups/rank modes)
MRCA computation and monophyly check (with nesting conflict detection)
Color generation (color-blind-safe palette)
Tree rendering and batch clade collapsing (ggtree + depth-first collapse)
Timescale integration and annotations (deeptime, support, HPD, labels, highlight)
Plot finalization (legend, theme, title, save, metadata)
Value
A ggplot object with an rclade_info attribute containing
metadata (tip count, group count, taxonomy format, etc.).
Can be further customized with + layers.
Label length guard
When tree is a file path, Newick labels longer than 500 characters
are truncated to 400 characters plus a _RCLADE_TRUNC suffix (with a
warning) before parsing, because ape's Newick parser aborts the whole R
process on labels longer than ~512 characters on Linux. Truncated labels
may no longer match external taxonomy files or sequence IDs; shorten
labels upstream if exact matching is required. See read_tree_auto().
Parameter grouping
For complex configurations, consider organizing parameters by category:
-
Tree input:
tree -
Collapsing:
rank,triangle_mode,space_mode -
Layout:
layout,angle,line_width -
Colors:
color_palette,color_mapping -
Labels:
show_tip_labels,tip_label_size,show_clade_label,clade_label_offset -
Timescale:
add_timescale,timescale_levels,unit -
Taxonomy:
taxonomy_format,custom_patterns -
Annotations:
show_support,support_threshold,show_hpd -
Legend:
legend_position,legend_nrow,legend_ncol -
Output:
output,width,height
References
Yu G, Smith DK, Zhu H, Guan Y, Lam TT-Y (2017). "ggtree: an R package for visualization and annotation of phylogenetic trees with their covariates and other associated data." Methods in Ecology and Evolution, 8(1), 28-36. doi:10.1111/2041-210X.12628
Gearty W (2025). "deeptime: an R package that facilitates highly customizable and reproducible visualizations of data over geological time intervals." Big Earth Data. doi:10.1080/20964471.2025.2537516
Paradis E, Schliep K (2019). "ape 5.0: an environment for modern phylogenetics and evolutionary analyses in R." Bioinformatics, 35(3), 526-528. doi:10.1093/bioinformatics/bty633
Examples
# Quick start with the bundled example tree (no timescale)
data(example_tree)
p <- plot_timetree(example_tree, rank = "phylum",
taxonomy_format = "GTDB", add_timescale = FALSE)
Example phylogenetic tree with polytomies
Description
A phylo object with 9 tips containing intentional polytomies
(multifurcations) for testing polytomy handling. This tree has a structure
of ((A,B,C),(D,E),(F,G,H,I)) with three multifurcating clades.
Usage
data(polytomy_tree)
Format
A phylo object with 9 tips.
Source
Simulated data for testing polytomy handling.
Load internal geological timescale data
Description
Tries deeptime::get_scale_data() first, falls back to internal sysdata. Ensures Hadean eon is included.
Usage
prepare_geo_timescales(version = "ICS 2023/02")
Arguments
version |
Geological timescale version string. Currently supported:
|
Value
List with eons, eras, periods data frames
Print method for rclade_options
Description
Print method for rclade_options
Usage
## S3 method for class 'rclade_options'
print(x, ...)
Arguments
x |
A |
... |
Ignored. |
Value
Returns the input object x invisibly, after printing its
key-value pairs to the console.
Print version information
Description
Print version information
Usage
print_version()
Single-tree plotting pipeline
Description
Orchestrates all pipeline steps for a single phylo object.
This is the internal counterpart to plot_timetree() that handles
one tree after batch / file-path resolution has already occurred.
Usage
pt_single_tree(
tree,
rank,
clade,
strict,
groups,
triangle_mode,
space_mode,
layout,
angle,
color_palette,
color_mapping,
line_width,
show_tip_labels,
tip_label_size,
add_timescale,
timescale_levels,
unit,
taxonomy_format,
custom_patterns,
taxonomy_file,
taxonomy_file_sep,
taxonomy_file_header,
taxonomy_file_priority,
taxonomy_source_priority,
taxonomy_table_sep,
taxonomy_delimiter_mode,
legend_position,
legend_nrow,
legend_ncol,
legend_title,
show_clade_label,
show_clade_count,
clade_label_offset,
clade_label_fontsize,
show_support,
support_threshold,
show_hpd,
hpd_color,
geo_events,
timescale_version,
main_title,
sub_title,
highlight,
highlight_alpha,
theme_fun,
output,
overwrite,
width,
height,
taxonomy_levels,
low_memory,
ignore_malformed,
ignore_branch_length,
color_rank = NULL,
timescale_mode = "radial",
timescale_position = "right",
tree_start_position = "right"
)
Value
A ggplot object with rclade_info attribute.
Step 1: Prepare and validate inputs
Description
Reads tree from file (if path), validates structure, converts units, checks for large trees, and handles cladogram mode.
Usage
pt_step1_prepare_inputs(
tree,
tree_index,
multi_tree_mode,
rank,
unit,
layout,
triangle_mode,
space_mode,
add_timescale,
groups,
clade,
overwrite,
ignore_branch_length,
low_memory
)
Value
A named list with:
tree |
validated phylo object |
unit |
resolved time unit |
branch_length_mode |
"branch.length" or "none" |
add_timescale |
possibly modified |
Step 2: Resolve taxonomy / collapsing mode
Description
Determines whether we are in clade-specific, custom-groups, or rank-based mode and parses the taxonomy accordingly.
Usage
pt_step2_resolve_taxonomy(
tree,
clade,
strict,
groups,
rank,
taxonomy_format,
custom_patterns,
taxonomy_file,
taxonomy_file_sep,
taxonomy_file_header,
taxonomy_file_priority,
taxonomy_table_sep,
taxonomy_delimiter_mode,
taxonomy_levels,
low_memory
)
Value
A named list with:
group_vec |
named vector mapping tip labels to groups |
detected_format |
resolved taxonomy format string |
Step 3: Compute MRCA and check monophyly
Description
Computes MRCA map for each group, checks monophyly, and detects nesting conflicts.
Usage
pt_step3_compute_mrca(tree, group_vec, clade, strict, low_memory)
Value
A named list with:
mrca_map |
list of MRCA nodes per group |
singleton_map |
singleton group map (attr from compute_mrca_map) |
all_group_names |
union of mrca and singleton names |
Step 4: Generate colors
Description
Generates color palette for all identified groups.
Usage
pt_step4_generate_colors(all_group_names, color_palette, color_mapping)
Value
Named character vector of colors (group -> hex color).
Step 5: Render base tree and collapse clades
Description
Builds the ggplot tree, binds taxonomy data, collapses clades, handles circular layout rescaling, and colors collapse branches.
Usage
pt_step5_render_and_collapse(
tree,
group_vec,
mrca_map,
colors,
layout,
angle,
line_width,
branch_length_mode,
triangle_mode,
space_mode,
low_memory,
color_group_vec = NULL
)
Value
A named list with:
p |
ggplot object |
actual_ntips |
displayed tip count after collapse (or NULL) |
Step 6: Add annotations (tip labels, timescale, support, HPD, clade labels, highlight)
Description
Step 6: Add annotations (tip labels, timescale, support, HPD, clade labels, highlight)
Usage
pt_step6_add_annotations(
p,
tree,
layout,
add_timescale,
timescale_levels,
actual_ntips,
timescale_version,
show_tip_labels,
tip_label_size,
show_support,
support_threshold,
show_hpd,
hpd_color,
geo_events,
show_clade_label,
show_clade_count,
clade_label_offset,
clade_label_fontsize,
mrca_map,
singleton_map,
highlight,
highlight_alpha,
rank,
taxonomy_format,
custom_patterns,
taxonomy_delimiter_mode,
taxonomy_levels,
ignore_branch_length,
colors,
timescale_mode = "radial",
timescale_position = "right",
angle = 360,
tree_start_position = "right"
)
Value
Updated ggplot object.
Step 7: Finalize plot (legend, theme, title, save, metadata)
Description
Step 7: Finalize plot (legend, theme, title, save, metadata)
Usage
pt_step7_finalize_plot(
p,
colors,
groups,
rank,
legend_position,
legend_nrow,
legend_ncol,
legend_title,
theme_fun,
add_timescale,
layout,
main_title,
sub_title,
output,
width,
height,
overwrite,
tree,
mrca_map,
all_group_names,
actual_ntips,
detected_format,
color_palette
)
Value
Final ggplot object with rclade_info attribute.
Rclade Logger
Description
A real-time logging system with flush support, timestamps, and log levels. Messages are printed immediately (not buffered) with formatted output.
Details
Thread safety: The logger uses a package-global environment and is not thread-safe. In concurrent contexts (e.g., multiple Shiny sessions or parallel Snakemake/Nextflow rule executions), multiple Rclade instances writing to the same log file will produce interleaved or corrupted log output.
Best practices for parallel execution:
-
Each process MUST use an independent log file (mandatory). Never point two concurrent Rclade processes at the same
--log_file. Sharing one log file is only safe when thefilelockpackage is installed (it provides an advisory lock on each write); otherwise concurrent writes will interleave/corrupt output. Assign each Rclade instance a unique log file via
--log_file(e.g.,--log_file logs/task_\$SLURM_JOB_ID.log)In Snakemake/Nextflow pipelines, use wildcards to generate per-rule or per-sample log paths
For Shiny deployments, disable file logging with
enable_file_logging(FALSE)before launching the appThe console output (via
message()) is process-local and does not suffer from interleaving issues
Limitation: The current design does not support a shared log file across concurrent Rclade processes. This is a known limitation tracked for a future release. For now, use per-instance log files as described above.
Log Levels
-
DEBUG: Detailed debug information
-
INFO: Normal operation information
-
WARNING: Warning messages
-
ERROR: Error messages
-
CRITICAL: Critical errors
Display Rclade ASCII art logo
Description
Prints a stylized ASCII art logo for Rclade to the console.
Usage
rclade_logo(show_version = TRUE, show_tagline = TRUE)
Arguments
show_version |
Logical. Whether to show version number. Default: TRUE |
show_tagline |
Logical. Whether to show tagline. Default: TRUE |
Value
Invisible NULL
Examples
rclade_logo()
Construct a validated options list for plot_timetree()
Description
rclade_options() returns a named list of commonly used rendering
parameters that can be passed to plot_timetree(opts = ...) as a
single object. Explicit arguments supplied directly to
plot_timetree() always take precedence over values in opts.
Usage
rclade_options(
rank = "none",
layout = "rectangular",
color_palette = "viridis",
taxonomy_format = "auto",
add_timescale = TRUE,
timescale_mode = "radial",
unit = NULL,
legend_position = "bottom",
line_width = 1,
show_tip_labels = FALSE,
width = 14,
height = 10,
...
)
Arguments
rank |
Character. Collapsing rank (e.g. "phylum", "class", "none"). |
layout |
Character. "rectangular" or "circular". |
color_palette |
Character. Palette name (e.g. "viridis", "plasma", "Set1"). |
taxonomy_format |
Character. One of "auto", "GTDB", "Silva", "NCBI", "embedded", "custom_regex". |
add_timescale |
Logical. Whether to add a geological timescale. |
timescale_mode |
Character. "radial", "linear", "none". |
unit |
Character or NULL. "Ma", "Ga", or NULL. Required when add_timescale = TRUE (the pipeline aborts for NULL); NULL leaves native units untouched and is only valid with add_timescale = FALSE. |
legend_position |
Character. Legend placement (e.g. "bottom", "right", "none"). |
line_width |
Numeric. Branch line width. |
show_tip_labels |
Logical. Whether to display tip labels. |
width |
Numeric. Output width in inches. |
height |
Numeric. Output height in inches. |
... |
Additional named parameters to include in the options list. These are passed through without validation. |
Details
This constructor is the first step toward parameter-surface convergence:
it provides a single validated source of truth for parameter defaults,
reducing the risk of drift between the plot_timetree() signature,
internal forwarding lists, and documentation.
Value
A named list of class "rclade_options" suitable for the
opts argument of plot_timetree().
Examples
# Create a reusable options object
opts <- rclade_options(rank = "phylum", layout = "circular",
color_palette = "plasma", add_timescale = TRUE)
Read file with explicit UTF-8 encoding
Description
Attempts UTF-8 first, falls back to a byte-level read (utf-8-sig equivalent)
on failure. Any occurrence of the Unicode replacement character U+FFFD
(a sign of mojibake / invalid bytes silently substituted by the reader) is
reported via log_warning, or aborts when strict = TRUE (M-C3).
Usage
read_file_utf8(filepath, warn = TRUE, strict = FALSE)
Arguments
filepath |
Character. Path to file. |
warn |
Logical. Whether to warn on encoding fallback. |
strict |
Logical. If |
Value
Character vector of file lines.
Read taxonomy information from a table file
Description
Reads taxonomy information from a two-column table file where:
Column 1: Tip labels (must match tree tip labels)
Column 2: Taxonomy strings in GTDB format (e.g.,
d__Archaea;p__Thermoproteota;c__Korarchaeia)
Usage
read_taxonomy_file(file, sep = "auto", header = FALSE, table_sep = ";")
Arguments
file |
Character. Path to the taxonomy table file. |
sep |
Character. Column separator. |
header |
Logical. Whether the file has a header row. Default: |
table_sep |
Character. Separator between taxonomy ranks in the
second column (the taxonomy string). Default: |
Details
Supports tab-delimited or comma-delimited files. Missing ranks are indicated
by empty values after the rank prefix (e.g., s__ for missing species).
Value
A data.frame with columns:
- label
Character. Tip labels from column 1.
- domain
Character. Domain (d__).
- phylum
Character. Phylum (p__).
- class
Character. Class (c__).
- order
Character. Order (o__).
- family
Character. Family (f__).
- genus
Character. Genus (g__).
- species
Character. Species (s__).
Missing ranks are NA.
Read tree from file with automatic format detection
Description
Intended for use as a stable library API by external workflows (e.g., Snakemake/Nextflow).
Usage
read_tree_auto(filepath, tree_index = NULL, multi_tree_mode = "error")
Arguments
filepath |
Path to tree file (.tre, .nwk, .newick, .nexus, .nex, .treefile, .xml) |
tree_index |
Integer. Index of tree to use from multiPhylo objects (e.g., BEAST posterior). Default: NULL (will use multi_tree_mode to determine behavior). |
multi_tree_mode |
Character. How to handle multiple trees in a file. Options:
|
Details
Newick labels longer than 500 characters are automatically truncated to
400 characters plus a _RCLADE_TRUNC suffix (with a warning), because
ape's Newick parser aborts the whole R process on labels longer than
~512 characters on Linux. Truncated labels may no longer match external
taxonomy files or sequence IDs; shorten labels upstream if exact matching
is required.
Value
phylo object (or multiPhylo if multi_tree_mode = "all" or "split")
Resolve group name or special identifier to MRCA node
Description
Unified function that handles both regular group names and special identifiers (LUCA, LACA, LBCA).
Usage
resolve_group(
tree,
group,
rank = "domain",
format = "auto",
quiet = FALSE,
delimiter_mode = "reverse",
custom_patterns = NULL,
taxonomy_levels = NULL
)
Arguments
tree |
A |
group |
Character. Group name or special identifier. |
rank |
Character. Taxonomic rank (ignored for special identifiers). |
format |
Character. Taxonomy label format. Default: |
quiet |
Logical. If TRUE, suppress messages. Default: FALSE. |
delimiter_mode |
Character. Embedded parsing strategy: |
custom_patterns |
Named list of regex patterns for custom format.
Required when |
taxonomy_levels |
Custom taxonomy level configuration (list with codes and names).
Default: |
Value
A list with components:
- is_monophyletic
Logical. Whether the group is monophyletic.
- group
Character. The group name or identifier.
- is_special
Logical. Whether this is a special identifier.
- node
Integer or NULL. The MRCA node number.
- n_tips
Integer. Number of tips in the group.
- outsiders
Character vector. Tips in MRCA not belonging to group.
Resolve special ancestral node identifiers
Description
Handles special identifiers for key ancestral nodes in the tree of life:
-
LUCA: Last Universal Common Ancestor - MRCA of all Bacteria and Archaea
-
LACA: Last Archaeal Common Ancestor - MRCA of all Archaea
-
LBCA: Last Bacterial Common Ancestor - MRCA of all Bacteria
Usage
resolve_special_identifier(
tree,
identifier,
format = "auto",
quiet = FALSE,
delimiter_mode = "reverse",
taxonomy_levels = NULL
)
Arguments
tree |
A |
identifier |
Character. One of
|
format |
Character. Taxonomy label format. Default: |
quiet |
Logical. If TRUE, suppress informational messages. Default: FALSE. |
delimiter_mode |
Character. Embedded parsing strategy: |
taxonomy_levels |
Custom taxonomy level configuration (list with codes and names).
Default: |
Value
A list with components:
- node
Integer. The node number of the MRCA, or NULL if not found.
- identifier
Character. The identifier name.
- description
Character. Human-readable description.
- n_tips
Integer. Number of descendant tips.
- tip_labels
Character vector. Labels of descendant tips.
Resolve the target/expected taxonomy domains for a special ancestral identifier.
Description
Single source of truth for which taxonomy domains a special identifier maps
to. Shared by resolve_special_identifier() (to find the tips belonging
to the identifier) and check_special_monophyly() (to decide which
domains are "inside" the clade), so the two call sites cannot drift apart.
Usage
resolve_target_domains(identifier, all_domains)
Arguments
identifier |
Character, one of |
all_domains |
Character vector of domain names present in the relevant tip set (full tree for resolution, MRCA clade for monophyly checking). |
Value
Character vector of target domains.
Resolve taxonomy source priority (embedded vs table)
Description
Unifies the no_taxonomy_file_priority flag (CLI) and the explicit
taxonomy_source_priority value (CLI / Shiny) into a single canonical
"embedded" / "table" string. Replaces the inline if
previously duplicated in cli.R and plot_timetree().
Usage
resolve_taxonomy_source_priority(
no_taxonomy_file_priority = FALSE,
taxonomy_source_priority = "table"
)
Arguments
no_taxonomy_file_priority |
Logical. When |
taxonomy_source_priority |
Character "embedded" or "table". Ignored when
|
Value
Character: "embedded" or "table".
Run Rclade from the command line
Description
Provides a command-line interface for Rclade. Requires the optparse package.
Usage
run_rclade_cli(args = commandArgs(trailingOnly = TRUE))
Arguments
args |
Character vector of command-line arguments (default: commandArgs(trailingOnly = TRUE)) |
Value
An invisible integer exit code following standard Unix conventions:
0L (success), 1L (runtime error), 2L (parameter error),
3L (input-data error), 130L (user interrupt / SIGINT).
The caller MUST pass this value to q(status = ...) or
quit(status = ...) for the exit code to propagate to the operating
system; simply calling run_rclade_cli() without forwarding the
return value will always exit with code 0 regardless of errors.
Config-file override trap (L-E3 — READ BEFORE USING --config)
A --config YAML file supplies defaults for any option, with
precedence CLI explicit argument > config file > built-in default.
Because optparse does not expose "was this flag passed?", the override
is applied by comparing each option against its built-in default:
any option the user left at its default value is eligible to be
overridden by the config file — even if the user explicitly typed a
value identical to the default. Concretely:
-
plot_timetree --rank phylum(where"phylum"is the default) will be overridden byrank: classin the config. -
plot_timetree --rank species(non-default) is preserved.
This is an optparse limitation, not a bug, and is intentional
but surprising. To make an option immune to config, pass a non-default value,
or avoid relying on config for options you care about. Unknown config keys are
warned and ignored.
Run Rclade self-test
Description
Performs comprehensive self-check:
Required package availability and versions
Example tree parsing and taxonomy extraction
Monophyly logic validation
Usage
run_rclade_selftest(verbose = TRUE)
Arguments
verbose |
Logical. If TRUE (default), progress and results are
reported via |
Value
Integer. Exit code (0 = all passed, 1 = failures).
Launch Rclade Shiny app
Description
Provides an interactive web interface for Rclade. Requires the shiny package.
Usage
run_rclade_shiny()
Value
No return value, called for side effects (launches a Shiny web app).
Concurrency
The logger, step-progress, and interrupt subsystems use package-level global
environments (.logger_env, .interrupt_env). Within a single R
process, multiple concurrent Shiny sessions will share (and may corrupt) this
state — log messages, step counters, and interrupt flags can cross between
sessions. For production multi-user deployment, run one Shiny instance per R
process (e.g., behind a load balancer), or assign a dedicated log file per
task via --log_file. A session-scoped state refactor is on the
roadmap.
Save sessionInfo() for reproducibility
Description
Save sessionInfo() for reproducibility
Usage
save_session_info(file = "session_info.txt")
Arguments
file |
Output file path (default "session_info.txt") |
Value
Invisibly returns sessionInfo
Save a timetree plot to file
Description
Save a timetree plot to file
Usage
save_timetree(p, file, width = 14, height = 10, dpi = 300, overwrite = "ask")
Arguments
p |
ggplot object |
file |
Output file path |
width |
Width in inches |
height |
Height in inches |
dpi |
Resolution (for PNG/TIFF only) |
overwrite |
Character. Overwrite mode: "ask" (default), "force", "no-clobber". |
Value
Invisibly returns the ggplot object
Report a self-test progress line
Description
All self-test reporting goes through message (stderr) so
that it can be suppressed with suppressMessages; plain
cat() output cannot be suppressed by the user (CRAN policy on
console output).
Usage
selftest_report(verbose, ...)
Arguments
verbose |
Logical. Output only when TRUE. |
... |
Passed to |
Enable or disable logging
Description
Enable or disable logging
Usage
set_log_enabled(enabled)
Arguments
enabled |
Logical. |
Value
No return value, called for side effects (toggles the package-level logging enabled flag).
Set log file for dual output
Description
Set log file for dual output
Usage
set_log_file(filepath)
Arguments
filepath |
Character. Path to log file. NULL to disable. |
Value
No return value, called for side effects (opens or closes a log file connection for dual console + file logging).
Set log level
Description
Set log level
Usage
set_log_level(level)
Arguments
level |
Character. One of "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL". |
Value
No return value, called for side effects (sets the package-level log threshold).
Sort groups by MRCA node depth (deepest first)
Description
Sort groups by MRCA node depth (deepest first)
Usage
sort_by_depth(groups, mrca_map, tree)
Arguments
groups |
Character vector of group names |
mrca_map |
Output of compute_mrca_map() |
tree |
phylo object |
Value
Sorted character vector
Extract legend as separate grob and combine with patchwork
Description
Extract legend as separate grob and combine with patchwork
Usage
split_legend(p, ncol_split = 2)
Arguments
p |
ggplot object |
ncol_split |
Number of columns for legend splitting (used for reflow) |
Value
patchwork object. Note: This returns a patchwork object, not a ggplot object.
You cannot add ggplot2 layers with + after calling split_legend().
Use patchwork operators like | and / for layout composition.
Strip node annotations from a tree (§9.1.1 –strip_annotations)
Description
Removes bootstrap/support node labels and NHX comment metadata from a tree
so they are not carried into the rendered output. Works on both phylo
and treedata objects. For treedata objects, data columns whose
names match common annotation patterns (support values, rates, heights,
HPD intervals, comments, NHX/taxid metadata) are dropped; the exact matched
column names are logged at INFO level.
Usage
strip_tree_annotations(tree)
Arguments
tree |
A phylo or treedata object. |
Value
The same tree class with annotation fields cleared.
Summarize multiple trees in a file
Description
Prints a summary of each tree in a multiPhylo object before raising the multi-tree error.
Usage
summarize_multi_trees(trees, filepath)
Arguments
trees |
multiPhylo object. |
filepath |
Character. Source file path. |
Report taxonomy label parsing quality
Description
Provides a detailed report on how well taxonomic labels can be parsed, including per-rank parse rates and failed labels.
Usage
summarize_taxonomy_quality(
labels,
format = "auto",
custom_patterns = NULL,
taxonomy_levels = NULL,
delimiter_mode = "reverse"
)
Arguments
labels |
Character vector of tip labels |
format |
Format: "auto", "embedded", "GTDB", "Silva", "NCBI", "custom_rank", "custom_regex" |
custom_patterns |
Custom regex patterns (for "custom_regex" format) |
taxonomy_levels |
Custom taxonomy level configuration |
delimiter_mode |
Character. Embedded parsing strategy: "reverse", "greedy", "segment". |
Value
Invisibly returns a list with parsing statistics
Summarize taxonomy quality with external file support
Description
Extended version of summarize_taxonomy_quality() that can use an
external taxonomy file.
Usage
summarize_taxonomy_quality_with_file(
labels,
format = "auto",
custom_patterns = NULL,
taxonomy_file = NULL,
file_sep = "auto",
file_header = FALSE,
file_priority = TRUE,
table_sep = ";",
delimiter_mode = "reverse",
taxonomy_levels = NULL
)
Arguments
labels |
Character vector of tip labels. |
format |
Format: "auto", "GTDB", "Silva", "NCBI", "custom_rank", "custom_regex". |
custom_patterns |
Custom regex patterns (for "custom_regex" format). |
taxonomy_file |
Character. Path to external taxonomy file. Default: |
file_sep |
Character. Column separator for taxonomy file. Default: |
file_header |
Logical. Whether taxonomy file has header row. Default: |
file_priority |
Logical. If |
table_sep |
Character. Separator between taxonomy ranks in the second
column of the taxonomy file. Default: |
delimiter_mode |
Character. Embedded parsing strategy: "reverse", "greedy", "segment". |
taxonomy_levels |
Custom taxonomy level configuration (list with codes and names).
Default: |
Value
Invisibly returns a list with parsing statistics.
Print a summary of a Rclade timetree plot
Description
Print a summary of a Rclade timetree plot
Usage
summarize_timetree(p)
Arguments
p |
ggplot object returned by plot_timetree() (with rclade_info attribute) |
Value
Invisibly returns the info list
Publication-ready theme for timetree plots
Description
Based on ggtree::theme_tree2(), customized for publication quality.
Includes coord_cartesian(clip = "off") to prevent collapsed clade
triangles from being clipped at the plot panel boundary — triangle vertices
(especially the MRCA node apex) often extend beyond the tip-based y-axis range.
Usage
theme_timetree(base_size = 12)
Arguments
base_size |
Base font size |
Value
A list with components theme (ggplot2 theme) and
coord (coord_cartesian(clip = "off")). Callers should apply
both via p + result$theme + result$coord.
Start a timer for performance measurement
Description
Start a timer for performance measurement
Usage
timer_start(name)
Arguments
name |
Character. Timer name. |
Stop a timer and log elapsed time
Description
Stop a timer and log elapsed time
Usage
timer_stop(name, level = "INFO")
Arguments
name |
Character. Timer name. |
level |
Character. Log level. Default: "INFO". |
Value
Numeric. Elapsed seconds.
Update progress counter
Description
Update progress counter
Usage
update_progress(processed = NULL, current = NULL)
Arguments
processed |
Integer. Number processed so far. |
current |
Character. Description of current item. |
Validate input parameters
Description
Validate input parameters
Usage
validate_cli_params(opt)
Detect nesting conflicts in a collapse plan
Description
Detect nesting conflicts in a collapse plan
Usage
validate_collapse_plan(mrca_map, tree)
Arguments
mrca_map |
Output of compute_mrca_map() |
tree |
phylo object |
Value
Invisibly returns warning message vector
Validate user-defined custom groups for tree collapsing
Description
Checks that every group is monophyletic and that tips do not overlap between groups.
Usage
validate_custom_groups(tree, groups)
Arguments
tree |
A |
groups |
A named |
Value
Invisibly returns TRUE if all checks pass. Otherwise stops
with an informative error.
Validate FASTA content
Description
Validate FASTA content
Usage
validate_fasta_content(lines, filepath, result, check_alignment = FALSE)
Arguments
lines |
Character vector of file lines. |
filepath |
Character. File path for messages. |
result |
List to populate. |
check_alignment |
Logical. Whether to check sequence length consistency. |
Validate FASTQ content
Description
Validate FASTQ content
Usage
validate_fastq_content(lines, filepath, result)
Validate file existence and readability
Description
Validate file existence and readability
Usage
validate_file_exists(filepath, file_type = "input", must_exist = TRUE)
Arguments
filepath |
Character. Path to file. |
file_type |
Character. Description of file type for error messages. |
must_exist |
Logical. Whether file must exist. Default: TRUE. |
Value
Logical. TRUE if valid.
Validate file is not empty
Description
Checks file size and raises CRITICAL if empty.
Usage
validate_file_not_empty(filepath, file_type = "input")
Arguments
filepath |
Character. Path to file. |
file_type |
Character. Description for error messages. |
Value
Invisibly returns TRUE if not empty. Stops on empty file.
Validate and preprocess tree input
Description
Checks tree object validity, converts treedata to phylo, validates parameters, and performs unit sanity checks.
Usage
validate_inputs(
tree,
rank,
unit,
layout,
triangle_mode,
space_mode,
add_timescale = TRUE,
groups = NULL,
clade = NULL,
overwrite = "ask"
)
Arguments
tree |
phylo or treedata object |
rank |
Taxonomic rank |
unit |
Time unit |
layout |
Layout type |
triangle_mode |
Triangle mode |
space_mode |
Space mode |
Value
Validated phylo object (with node.data attribute if treedata input)
Validate Newick string syntax
Description
Performs deep syntax validation on a raw Newick string before parsing. Checks bracket balance, negative branch lengths, empty node names, duplicate node names, and self-loops.
Usage
validate_newick_syntax(text, filepath = "<string>")
Arguments
text |
Character. Raw Newick string. |
filepath |
Character. File path for error messages. |
Value
Invisibly returns TRUE if valid. Stops on CRITICAL errors.
Heuristics & error contract (L-C3 / L-E3)
The syntax checks are regex heuristics over the raw string and may occasionally false-positive or false-negative on exotic input (e.g. unusual quoting, deeply nested labels). They are a fast pre-filter; the authoritative correctness check is the structural validation that runs after the tree is parsed. Do not treat a clean heuristic pass as a full guarantee.
On failure these validators raise via rlang::abort(message, class = "Rclade_validate_error")
(or "Rclade_read_error" for I/O problems). Callers must
branch on the condition class, never grep the message text —
this is the supported contract and prevents brittle tests when wording changes.
Deep validation of sequence files
Description
Validates FASTA/FASTQ files: format detection, duplicate IDs, alphabet detection, and alignment length consistency.
Usage
validate_sequence_deep(
filepath,
expected_alphabet = NULL,
check_alignment = FALSE
)
Arguments
filepath |
Character. Path to sequence file. |
expected_alphabet |
Character or NULL. Expected alphabet: "DNA", "RNA", "protein", or NULL for auto-detect. |
check_alignment |
Logical. If TRUE, check all sequences have equal length. |
Value
List with validation results.
Validate sequence file format
Description
Validate sequence file format
Usage
validate_sequence_file(filepath)
Arguments
filepath |
Character. Path to sequence file. |
Value
Character. Detected format: "fasta", "fastq", "unknown".
Detect circular dependencies in taxonomy table
Description
Validates full taxonomy consistency by checking for cyclical relationships between every pair of adjacent ranks (coarsest to finest), not just the canonical domain/phylum/class/order chain. For example:
domain <-> phylum, phylum <-> class, class <-> order,
order <-> family, family <-> genus, genus <-> species
A circular dependency means a value appears as both a high-rank and a
low-rank member forming a loop (e.g. Row 1: d__A;p__B,
Row 2: d__B;p__A).
Usage
validate_taxonomy_no_cycles(taxa_df, filepath = "<taxonomy>")
Arguments
taxa_df |
data.frame with taxonomy columns (domain, phylum, class, etc.). |
filepath |
Character. Source file for error messages. |
Value
Invisibly returns TRUE if no cycles. Aborts on detection
(class Rclade_validate_error).
Deep tree validation after parsing
Description
Validates a parsed phylo object for structural integrity including self-loops, multi-root, negative branch lengths, and node consistency.
Usage
validate_tree_deep(tree, filepath = "<object>")
Arguments
tree |
phylo object. |
filepath |
Character. Source file path for messages. |
Value
Invisibly returns TRUE if valid.
Cross-validate tree tip labels against sequence IDs
Description
Checks that all tree tips have corresponding sequences and vice versa.
Usage
validate_tree_sequence_match(
tree,
sequence_file,
quiet = FALSE,
mol_type = NULL,
skip_length_check = FALSE,
multi_tree_mode = "error"
)
Arguments
tree |
phylo object or path to tree file. |
sequence_file |
Character. Path to sequence file (FASTA/FASTQ). |
quiet |
Logical. If TRUE, suppress messages. |
mol_type |
Character. Molecule type for sequence validation: "DNA",
"RNA", "protein", or "auto" (NULL). Default: |
skip_length_check |
Logical. If TRUE, skip alignment length consistency
check. Default: |
multi_tree_mode |
Character. How to handle multiple trees in a file when
|
Value
List with match status and differences.
Validate tree object structure
Description
Validate tree object structure
Usage
validate_tree_structure(tree)
Arguments
tree |
phylo object to validate. |
Value
Logical. TRUE if valid.
Execute expression with graceful interrupt handling
Description
Wraps an expression so that SIGINT (Ctrl+C) is caught gracefully: progress is reported, resources are cleaned up, and the function returns NULL instead of throwing an error.
Usage
with_graceful_interrupt(expr, total = 0)
Arguments
expr |
Expression to evaluate. |
total |
Integer. Total items for progress tracking (batch mode). |
Value
Result of expr, or NULL if interrupted.
Write file with explicit UTF-8 encoding and Unix line endings
Description
Write file with explicit UTF-8 encoding and Unix line endings
Usage
write_file_utf8(filepath, content, append = FALSE)
Arguments
filepath |
Character. Path to file. |
content |
Character vector. Lines to write. |
append |
Logical. Whether to append to existing file. |