| Title: | A Comprehensive Package for Sediment Source Unmixing |
|---|---|
| Description: | Source apportionment toolkit for fluvial catchments and river sediment provenance. It estimates how much each source contributes to a sediment mixture, using frequentist, Bayesian, and machine-learning models on the same dataset. The software includes tools to check which tracer is causing an unrealistic result, plus built-in validation against artificial mixtures with known, true source proportions. |
| Authors: | Margarita Villalonga [aut, cre], Esther Cepeda [aut], Maarten Wynants [aut], Ivan Lizaga [aut, ths, ldr], Samuel Bodé [ctb], Pascal Boeckx [ctb], William Blake [ctb], Jan Vanaverbeke [ctb], Ulrike Braeckman [ctb], Aiming Lian [ctb], Borja Latorre [ctb], Yuri Jacques Agra Bezerra da Silva [ctb], Leticia Gaspar [ctb], Jorge Crespo [ctb], Ana Navas [ctb], Maziar Mohammadi [ctb], Vince Q Vu [ctb] |
| Maintainer: | Margarita Villalonga <[email protected]> |
| License: | GPL (>= 2) |
| Version: | 1.0.0 |
| Built: | 2026-11-12 13:11:22 UTC |
| Source: | https://github.com/cran/FluvialTracer |
A function that calculates and visualizes the percentage deviation between an experimental artificial mixture and a theoretical virtual mixture calculated from user-defined source proportions. Source proportions should be defined as described in Option A: manual list or Option B: CSV file
checking_diff_mult_mix( data, proportions = props_table, sample_col = 1, source_col = 2 )checking_diff_mult_mix( data, proportions = props_table, sample_col = 1, source_col = 2 )
data |
Data frame. Contains source and mixture data in the standard format. |
proportions |
Data.frame. With one row per mixture and one column per source. Can be created in two ways: Option A - manually:
Option B - from a CSV file (one row per mixture, one column per source):
|
sample_col |
Character. Defines which column of the data contains the sample names. |
source_col |
Character. Defines which column of the data contains the source names. Indicate the column number in which the sources are defined independently from the sample number. |
No return value, called for side effects (draws one plot per mixture showing the deviation between the virtual and artificial mixture).
A function that calculates and visualizes the percentage deviation between an experimental artificial mixture and a theoretical virtual mixture calculated from user-defined source proportions.
checking_diff_single_mix( data, proportions = c(1, 0, 0, 0), sample_col = 1, source_col = 2, subtitle_extra = NULL )checking_diff_single_mix( data, proportions = c(1, 0, 0, 0), sample_col = 1, source_col = 2, subtitle_extra = NULL )
data |
Data frame. Contains source and mixture data in the standard format. |
proportions |
Numeric vector. Defines the proportions of each source in the mixture. Required to calculate virtual mixture. |
sample_col |
Character. Defines which column of the data contains the sample names. |
source_col |
Character. Defines which column of the data contains the source names. Indicate the column number in which the sources are defined independently from the sample number. |
subtitle_extra |
Character. Custom subtitle for the plot; overrides the automatic one if provided. Default NULL. |
Invisibly returns a gtable object with the combined plot
(both panels, title, legend and caption). The plot is also drawn on the
current graphics device.
Quantifies how consistently each tracer constrains the mixture apportionment when paired with randomly chosen complementary tracers. For each tracer of interest, the function solves a large number of minimal determined systems and records the spread of the resulting source contributions. A narrow spread indicates that the tracer is conservative and highly informative, regardless of which other tracers accompany it.
CI_Method( data, points = 2000, Means = NULL, triangles = "virtual", seed = 123456L )CI_Method( data, points = 2000, Means = NULL, triangles = "virtual", seed = 123456L )
data |
Data frame in the standard FluvialTracer format (sources + mixture). Raw and averaged formats are both accepted. |
points |
Integer. Number of Monte Carlo draws per tracer. |
Means |
Logical or |
triangles |
Logical. If |
seed |
Integer. Random seed for reproducibility. |
Two strategies are available for selecting the accompanying tracers:
Virtual method: remaining tracers are replaced by values
drawn uniformly from , isolating the tracer of interest
from correlations with other measured properties.
Dataset method: remaining tracers are sampled at random from the measured dataset, reflecting realistic geochemical combinations.
A list with one data frame per tracer containing the predicted
source contributions across all iterations, followed by two named
elements: DB, the input data, and CI, a data frame with
the CI score, normalized score, category and status for each tracer.
Lizaga, I., Latorre, B., Bodé, S., Gaspar, L., Boeckx, P., & Navas, A. (2024). Combining isotopic and elemental tracers for enhanced sediment source partitioning in complex catchments. Journal of Hydrology*, 631 , 130768.doi:10.1016/j.jhydrol.2024.130768
Lizaga, I., Latorre, B., Gaspar, L., & Navas, A. (2020). Consensus ranking as a method to identify non-conservative and dissenting tracers in fingerprinting studies. Science of The Total Environment, 720, 137537. doi:10.1016/j.scitotenv.2020.137537
Takes the output of CTS_n_sources and groups the tracer
combinations into clusters of similar source contributions (w1, w2, ...).
This helps identify the dominant apportionment solutions and how many
individual tracers support each one.
cluster_solutions( cts_result, top_n = 50L, k = NULL, max_k = 6L, interactive = FALSE, seed = NULL )cluster_solutions( cts_result, top_n = 50L, k = NULL, max_k = 6L, interactive = FALSE, seed = NULL )
cts_result |
Data frame returned by |
top_n |
Integer. Number of top rows to use for clustering. Default 50. |
k |
Integer or |
max_k |
Integer. Maximum k to evaluate when |
interactive |
Boolean. If |
seed |
Integer or |
Hierarchical clustering with Ward.D2 linkage is used because contribution
clusters are rarely spherical or equal-sized. The optimal number of clusters
is selected automatically via the average silhouette width criterion, but
can be overridden with the k argument.
Visualisation adapts to the number of sources:
2 sources: single 2D panel (w1 vs w2).
3 sources: two 2D panels (w1~w2, w1~w3) plus optional interactive 3D plotly scatter.
4+ sources: all pairwise 2D panels as a grid. Interactive 3D is not available (dimensionality reduction would obscure interpretation).
The physically feasible region (0-100 shaded white; everything outside it (negative or >100 i.e. not physically possible) is shaded grey.
A named list:
summaryData frame: one row per cluster with mean/SD of each contribution, n_pairs, n_unique_tracers, avg_silhouette.
tracersNamed list. Each element has $pairs (character
vector) and $individual_tracers (data frame ranked by frequency).
plotggplot2 or plotly visualisation.
Wynants, M., Verboom, C., Lizaga, I., de Boer, H., van der Perk, M., Bennett, W., Boeckx, P., & Brooks, A. Sediment and phosphorus source hysteresis and tracing during an extreme flood in a subtropical Australian river.
Transforms isotopic ratio and elemental content data into virtual scalar tracers that can be directly used in classical unmixing models.
Conservative_Balance(data, error_propagation = "ratio", impute_nas = FALSE) CB_Method(data, ...) cb_method(...)Conservative_Balance(data, error_propagation = "ratio", impute_nas = FALSE) CB_Method(data, ...) cb_method(...)
data |
Data frame. Contains the isotopic tracer characteristics of sediment sources and one mixture. Both averaged and raw formats are supported. |
error_propagation |
Character. Error propagation method for averaged data: "ratio" (default) or "full". |
impute_nas |
Logical. If TRUE, automatically imputes missing values (NAs) in source samples using their respective group means. Default FALSE. |
... |
Additional arguments passed to other methods. |
A data frame with isotopic tracers replaced by their CB-transformed scalar equivalents.
Assesses the mathematical consistency of a tracer selection by computing the normalized error between the predicted and observed tracer concentrations in the mixture. A low error (typically below 0.05) for all tracers indicates a consistent selection. High errors point to non-conservative tracers or multiple partial solutions in the dataset.
consistency_error(data, solution) CTS_error(data, solution) cts_error(data, solution)consistency_error(data, solution) CTS_error(data, solution) cts_error(data, solution)
data |
A data frame containing the characteristics of sediment sources and one mixture, in the standard fingerprinting format. |
solution |
Either a numeric vector of apportionment weights (one per
source, in the same order as they appear in |
The error for each tracer is the absolute difference between the observed mixture concentration and the virtual mixture reconstructed from the apportionment solution, after normalizing by the range of the source confidence intervals.
A data frame with columns tracer and consistency_error,
one row per tracer.
Latorre, B., Lizaga, I., Gaspar, L., & Navas, A. (2021). A novel method for analysing consistency and unravelling multiple solutions in sediment fingerprinting. Science of The Total Environment, 789, 147804.
Generates a correlation matrix scatterplot of dataset properties, grouped by source, to aid in collinearity diagnosis and optimal tracer selection.
Correlation_Chart( data, tracers = 1:(ncol(data) - 2), mixtures = TRUE, nmixtures = 2, colors = NULL, seed = NULL ) correlationPlot( data, tracers = 1:(ncol(data) - 2), mixtures = TRUE, nmixtures = 2, colors = NULL, seed = NULL ) correlation_plot( data, tracers = 1:(ncol(data) - 2), mixtures = TRUE, nmixtures = 2, colors = NULL, seed = NULL )Correlation_Chart( data, tracers = 1:(ncol(data) - 2), mixtures = TRUE, nmixtures = 2, colors = NULL, seed = NULL ) correlationPlot( data, tracers = 1:(ncol(data) - 2), mixtures = TRUE, nmixtures = 2, colors = NULL, seed = NULL ) correlation_plot( data, tracers = 1:(ncol(data) - 2), mixtures = TRUE, nmixtures = 2, colors = NULL, seed = NULL )
data |
Data frame. Contains source and mixture data in the standard FluvialTracer format. |
tracers |
Numeric vector. Indices of the tracers to include in the matrix. Default 1:(ncol(data) - 2). |
mixtures |
Logical. If TRUE, includes mixture samples in the correlation plots. Default TRUE. |
nmixtures |
Integer. Number of mixture samples present in the dataset. Default 2. |
colors |
Character vector. Custom colors for the scatterplot groups. If NULL (default), colors are pulled automatically from fluvial_palette: the first N-1 Source colors, plus one Mixture color if mixtures = TRUE. |
seed |
Integer. Random seed for reproducibility. Default NULL. |
A GGally::ggpairs object.
Computes the Consensus Ranking (CR) method, an ensemble technique to identify non-conservative and dissenting tracers. The method combines predictions from single-tracer models and is based on a scoring function derived from a series of random "debates" between tracers, utilizing advanced thresholding logic for extreme datasets.
CR_Method( data, debates = 1000, completion_quantile = 1, apportionment_threshold = 0, seed = 123456 ) CR( data, debates = 1000, completion_quantile = 1, apportionment_threshold = 0, seed = 123456 ) cr_ns( data, debates = 1000, completion_quantile = 1, apportionment_threshold = 0, seed = 123456 )CR_Method( data, debates = 1000, completion_quantile = 1, apportionment_threshold = 0, seed = 123456 ) CR( data, debates = 1000, completion_quantile = 1, apportionment_threshold = 0, seed = 123456 ) cr_ns( data, debates = 1000, completion_quantile = 1, apportionment_threshold = 0, seed = 123456 )
data |
Data frame. Contains source and mixture data in the standard FluvialTracer format. |
debates |
Integer. Target number of random debates per tracer. Default 1000. |
completion_quantile |
Numeric. Value between 0-1. Quantile threshold for debate completion. For example, 0.5 stops the simulation once half the tracers hit the debates target. Default 1. |
apportionment_threshold |
Numeric. Tolerance boundary for valid debate apportionments (e.g., defining valid as -threshold to 1 + threshold). Default 0. |
seed |
Integer. Random seed for reproducibility. Default 123456. |
A data frame containing the CR score, debates won, and debates lost per tracer.
Lizaga, I., Latorre, B., Gaspar, L., & Navas, A. (2020). Consensus ranking as a method to identify non-conservative and dissenting tracers in fingerprinting studies. *Science of The Total Environment*, *720*, 137537. https://doi.org/10.1016/j.scitotenv.2020.137537
Solves determined systems for 1 tracer and 2 sources to assess solution dispersion and discriminant capacity.
CTS_2_sources(source, mixture, iter = 1000, seed = 123456) singles(source, mixture, iter = 1000, seed = 123456) CTS_seeds_singles(source, mixture, iter = 1000, seed = 123456)CTS_2_sources(source, mixture, iter = 1000, seed = 123456) singles(source, mixture, iter = 1000, seed = 123456) CTS_seeds_singles(source, mixture, iter = 1000, seed = 123456)
source |
Data frame of sediment sources. |
mixture |
Data frame of mixture samples. |
iter |
Number of Monte Carlo iterations. |
seed |
Integer for reproducibility. |
A data frame with one row per tracer, sorted by max_dw
(most discriminant first), with columns: id (tracer name),
w1, w2 (source contributions from mean values),
dw1, dw2 (dispersion of each contribution, half the
16-84% quantile range), cons (proportion of physically
feasible solutions) and max_dw (maximum dispersion).
Solves determined systems for 2 tracers and 3 sources to assess solution dispersion and discriminant capacity.
CTS_3_sources(source, mixture, iter = 1000, seed = 123456) pairs(source, mixture, iter = 1000, seed = 123456) CTS_seeds_pairs(source, mixture, iter = 1000, seed = 123456)CTS_3_sources(source, mixture, iter = 1000, seed = 123456) pairs(source, mixture, iter = 1000, seed = 123456) CTS_seeds_pairs(source, mixture, iter = 1000, seed = 123456)
source |
Data frame of sediment sources. |
mixture |
Data frame of mixture samples. |
iter |
Number of Monte Carlo iterations. |
seed |
Integer for reproducibility. |
A data frame with one row per tracer pair, sorted by max_dw
(most discriminant first), with columns: id (tracer pair),
w1, w2, w3 (source contributions from mean values),
dw1, dw2, dw3 (dispersion of each contribution, half
the 16-84% quantile range), cons (proportion of physically
feasible solutions) and max_dw (maximum dispersion).
Solves determined systems for 3 tracers and 4 sources to assess solution dispersion and discriminant capacity.
CTS_4_sources(source, mixture, iter = 1000, seed = 123456) triplets(source, mixture, iter = 1000, seed = 123456) CTS_seeds_triplets(source, mixture, iter = 1000, seed = 123456)CTS_4_sources(source, mixture, iter = 1000, seed = 123456) triplets(source, mixture, iter = 1000, seed = 123456) CTS_seeds_triplets(source, mixture, iter = 1000, seed = 123456)
source |
Data frame of sediment sources. |
mixture |
Data frame of mixture samples. |
iter |
Number of Monte Carlo iterations. |
seed |
Integer for reproducibility. |
A data frame with one row per tracer triplet, sorted by
max_dw (most discriminant first), with columns: id
(tracer triplet), w1 to w4 (source contributions from
mean values), dw1 to dw4 (dispersion of each contribution,
half the 16-84% quantile range), cons (proportion of physically
feasible solutions) and max_dw (maximum dispersion).
Solves determined systems for 4 tracers and 5 sources to assess solution dispersion and discriminant capacity.
CTS_5_sources(source, mixture, iter = 1000, seed = 123456) quartets(source, mixture, iter = 1000, seed = 123456) CTS_seeds_quartets(source, mixture, iter = 1000, seed = 123456)CTS_5_sources(source, mixture, iter = 1000, seed = 123456) quartets(source, mixture, iter = 1000, seed = 123456) CTS_seeds_quartets(source, mixture, iter = 1000, seed = 123456)
source |
Data frame of sediment sources. |
mixture |
Data frame of mixture samples. |
iter |
Number of Monte Carlo iterations. |
seed |
Integer for reproducibility. |
A data frame with one row per tracer quartet, sorted by
max_dw (most discriminant first), with columns: id
(tracer quartet), w1 to w5 (source contributions from
mean values), dw1 to dw5 (dispersion of each contribution,
half the 16-84% quantile range), cons (proportion of physically
feasible solutions) and max_dw (maximum dispersion).
Identifies the most discriminant minimal tracer combinations (n-1) by solving determined systems and assessing solution dispersion. Lower dispersion indicates higher discriminant capacity.
CTS_n_sources(data, iter = 1000, seed = 123456) CTS_seeds(data, iter = 1000, seed = 123456)CTS_n_sources(data, iter = 1000, seed = 123456) CTS_seeds(data, iter = 1000, seed = 123456)
data |
Data frame containing sediment source and mixture data. |
iter |
Number of Monte Carlo iterations for variability analysis. |
seed |
Integer for reproducibility. |
A data frame with one row per tracer combination, sorted by
max_dw (lowest dispersion first), with columns: id
(tracer combination), w1, w2, ... (source apportionments),
dw1, dw2, ... (solution dispersion), % in sources range
(percentage of physically feasible solutions) and max_dw
(maximum dispersion).
Latorre, B., Lizaga, I., Gaspar, L., & Navas, A. (2021). A novel method for analysing consistency and unravelling multiple solutions in sediment fingerprinting.
Performs stepwise forward variable selection using the Wilks Lambda criterion. Tracers are added one at a time when they improve inter-source discrimination beyond the specified significance threshold.
DFATest(data, niveau = 0.1)DFATest(data, niveau = 0.1)
data |
Data frame in the standard FluvialTracer format (sources + mixture). |
niveau |
Numeric. Significance level for the F-test at each step. Default 0.1.. |
A list with two elements: (1) a data frame retaining only the tracer
columns selected by the stepwise procedure, and (2) the object returned by
klaR::greedy.wilks with the details of the selection.
A named vector of hex color codes used as the default palette across
FluvialTracer's plotting functions (e.g. plot_apportionment,
LDA_Chart). Designed to remain visually distinct for up to
five sources plus the mixture.
fluvial_palettefluvial_palette
A named character vector of length 20.
Custom palette defined by the FluvialTracer authors.
Virtual dataset in the standard FluvialTracer format, used in the package examples.
fluvialdata_examplefluvialdata_example
A data frame with one row per sample: sample ID, source/mixture group, and one column per tracer.
head(fluvialdata_example)head(fluvialdata_example)
Estimates the fractional contribution of each sediment source to a mixture by solving an overdetermined mass-balance system with least-squares minimisation. Source variability is propagated by Monte Carlo resampling: at each iteration, synthetic source signatures are drawn from a normal distribution defined by the measured mean and standard deviation, and the system is solved independently for each draw.
frequentist_unconstrained( data, variability = "SEM", iter = 1000, means = FALSE, seed = 123456L )frequentist_unconstrained( data, variability = "SEM", iter = 1000, means = FALSE, seed = 123456L )
data |
Data frame in the standard FluvialTracer format (sources + mixture). |
variability |
Character. |
iter |
Integer. Number of Monte Carlo iterations. |
means |
Logical. |
seed |
Integer. Random seed for reproducibility. |
This function is the computational back-end called by unmixing.
For most users, calling unmixing directly is recommended.
A data frame with one row per iteration containing the mixture ID, goodness-of-fit (GOF), and one column per source with the estimated fractional contribution.
Estimates the fractional contribution of each sediment source to a mixture by solving an overdetermined mass-balance system with least-squares minimisation. Unlike classical Monte Carlo propagation, uncertainty is handled analytically through Linear Variability Propagation (LVP): the Jacobian of the least-squares solution propagates source covariances directly into the apportionment uncertainty, avoiding assumptions of independent normally distributed errors.
frequentist_unconstrained_lvp( data, variability = "SEM", iter = 1000, means = FALSE, seed = 123456L )frequentist_unconstrained_lvp( data, variability = "SEM", iter = 1000, means = FALSE, seed = 123456L )
data |
Data frame in the standard FluvialTracer format (sources + mixture). |
variability |
Character. |
iter |
Integer. Number of iterations. |
means |
Logical. |
seed |
Integer. Random seed for reproducibility. |
LVP is recommended when source variability is high or when apportionments are near the physical boundaries (0 or 1), where Monte Carlo resampling tends to underestimate uncertainty.
This function is the computational back-end called by unmixing
when lvp = TRUE. For most users, calling unmixing directly
is recommended.
A data frame with one row per iteration containing the mixture ID, goodness-of-fit (GOF), and one column per source with the estimated fractional contribution.
Latorre, B., Lizaga, I., Gaspar, L., & Navas, A. (2025). Evaluating the impact of high source variability and extreme contributing sources on sediment fingerprinting models. Water Resources Management. doi:10.1007/s11269-025-04169-8
Biplot for Principal Components using ggplot2
ggbiplot( pcobj, choices = 1:2, scale = 1, pc.biplot = TRUE, obs.scale = 1 - scale, var.scale = scale, groups = NULL, ellipse = FALSE, ellipse.prob = 0.68, labels = NULL, labels.size = 3, alpha = 1, var.axes = TRUE, circle = FALSE, circle.prob = 0.69, varname.size = 3, varname.adjust = 1.5, varname.abbrev = FALSE, ... )ggbiplot( pcobj, choices = 1:2, scale = 1, pc.biplot = TRUE, obs.scale = 1 - scale, var.scale = scale, groups = NULL, ellipse = FALSE, ellipse.prob = 0.68, labels = NULL, labels.size = 3, alpha = 1, var.axes = TRUE, circle = FALSE, circle.prob = 0.69, varname.size = 3, varname.adjust = 1.5, varname.abbrev = FALSE, ... )
pcobj |
Object. A PCA object returned by prcomp(), princomp(), PCA(), or lda(). |
choices |
Numeric vector. Indices of the principal components to plot. Default c(1,2). |
scale |
Numeric. Scale factor (0 or 1). Covariance biplot (scale = 1), form biplot (scale = 0). Default 1. |
pc.biplot |
Logical. If TRUE, ensures compatibility with biplot.princomp() scaling. Default TRUE. |
obs.scale |
Numeric. Scale factor applied to observations. Default 1 - scale. |
var.scale |
Numeric. Scale factor applied to variables. Default scale. |
groups |
Factor. Optional grouping variable to color-code observations. Default NULL. |
ellipse |
Logical. If TRUE, draws a normal data ellipse for each group. Default FALSE. |
ellipse.prob |
Numeric. Size of the ellipse in Normal probability. Default 0.68. |
labels |
Character vector. Optional custom labels for observations. Default NULL. |
labels.size |
Numeric. Text size used for observation labels. Default 3. |
alpha |
Numeric. Alpha transparency for points (0 = transparent, 1 = opaque). Default 1. |
var.axes |
Logical. If TRUE, renders variable loading arrows. Default TRUE. |
circle |
Logical. If TRUE, draws a correlation circle (only valid if scale = TRUE and var.scale = 1). Default FALSE. |
circle.prob |
Numeric. Size of the circle in Normal probability. Default 0.69. |
varname.size |
Numeric. Text size for variable names. Default 3. |
varname.adjust |
Numeric. Adjustment factor for variable name placement (>= 1 moves text further from arrow). Default 1.5. |
varname.abbrev |
Logical. If TRUE, abbreviates variable names. Default FALSE. |
... |
Currently not used. Kept for compatibility with the original
|
A ggplot2 plot.
Visualizes the distribution of continuous tracer variables across sources and mixtures. It compactly displays five summary statistics (the median, two hinges, and two whiskers), alongside individual outliers.
Graph_boxplots( data, tracers = 1:(ncol(data) - 2), ncol = 3, colors = NULL, seed = NULL, max_per_page = 16, label_size = 3 ) boxPlot( data, tracers = 1:(ncol(data) - 2), ncol = 3, colors = NULL, seed = NULL, max_per_page = 16, label_size = 3 ) box_plot( data, tracers = 1:(ncol(data) - 2), ncol = 3, colors = NULL, seed = NULL, max_per_page = 16, label_size = 3 )Graph_boxplots( data, tracers = 1:(ncol(data) - 2), ncol = 3, colors = NULL, seed = NULL, max_per_page = 16, label_size = 3 ) boxPlot( data, tracers = 1:(ncol(data) - 2), ncol = 3, colors = NULL, seed = NULL, max_per_page = 16, label_size = 3 ) box_plot( data, tracers = 1:(ncol(data) - 2), ncol = 3, colors = NULL, seed = NULL, max_per_page = 16, label_size = 3 )
data |
Data frame. Contains source and mixture data in the standard FluvialTracer format. |
tracers |
Numeric vector. Indices of the tracers to plot (column 1 refers to the first tracer variable). Default 1:(ncol(data) - 2). |
ncol |
Integer. Number of plots per row in the grid layout. Default 3. |
colors |
Character vector. Optional hex codes or names for custom boxplot colors, one per group (sources + mixture). If NULL (default), colors are pulled automatically from fluvial_palette: the first N-1 Source colors, plus one Mixture color for the last group. |
seed |
Integer. Random seed for reproducible jittering or sampling. Default NULL. |
max_per_page |
Integer. Maximum number of tracer panels to draw per page/device call. If the number of requested tracers exceeds this, the plots are split across multiple pages, drawn sequentially (each replacing the previous on-screen, or as successive pages if called inside a pdf()/dev device). Default 16. |
label_size |
Numeric. Font size for the n= and mean annotation labels inside each panel. Lower this if labels overlap when many panels are shown. Default 3. |
Invisibly returns a list of gtable objects, one per page.
The plots are also drawn on the current graphics device.
Identifies and returns the rows corresponding to the sediment mixture(s)
in a combined source-mixture data frame. The mixture is assumed to be the
last unique group in the second column of data. Both raw and
averaged (Mean_/SD_) formats are supported.
inputSample(data) inputMixture(data)inputSample(data) inputMixture(data)
data |
Data frame in the standard FluvialTracer format, where the second column encodes the group identity (sources and mixture). |
A data frame containing only the mixture rows, with column names standardised to the FluvialTracer convention.
inputSource for extracting source rows.
Selects and extracts the source samples from the dataset, computing mean,
SD and n when the input is in raw format. When a different format dataset
is detected, column names are normalised to Mean_/SD_ in the
output so that all downstream functions work correctly.
inputSource(data, na.omit = TRUE)inputSource(data, na.omit = TRUE)
data |
Data frame containing source and mixture data. |
na.omit |
Boolean. If |
A data frame with one row per source, containing the source
identifier (id), the mean of each tracer (Mean_ columns),
the standard deviation of each tracer (SD_ columns) and the
number of samples (n).
Retains only tracer properties that show statistically significant differences across source groups according to the non-parametric Kruskal-Wallis rank-sum test. Tracers with no discriminant power add noise to the unmixing model and should be removed before unmixing.
KWTest(data, pvalue = 0.05)KWTest(data, pvalue = 0.05)
data |
Data frame in the standard FluvialTracer format (sources + mixture). |
pvalue |
Numeric. Significance threshold. Default 0.05. |
A data frame retaining only tracer columns with p-value below pvalue.
Performs a linear discriminant analysis (LDA) to project data into maximum-separation dimensions. Includes a comprehensive discrimination summary detailing variance explained, a leave-one-out cross-validation confusion matrix, and misclassification rates to rigorously assess source separability.
LDA_Chart( data, Plot3D = FALSE, text = FALSE, colors = NULL, interactive = FALSE, seed = NULL ) LDA_plot( data, Plot3D = FALSE, text = FALSE, colors = NULL, interactive = FALSE, seed = NULL ) LDAPlot( data, Plot3D = FALSE, text = FALSE, colors = NULL, interactive = FALSE, seed = NULL )LDA_Chart( data, Plot3D = FALSE, text = FALSE, colors = NULL, interactive = FALSE, seed = NULL ) LDA_plot( data, Plot3D = FALSE, text = FALSE, colors = NULL, interactive = FALSE, seed = NULL ) LDAPlot( data, Plot3D = FALSE, text = FALSE, colors = NULL, interactive = FALSE, seed = NULL )
data |
Data frame. Contains source and mixture data in the standard FluvialTracer format. |
Plot3D |
Logical. If TRUE, renders a 3D scatter plot instead of a 2D projection. Default FALSE. |
text |
Logical. If TRUE, overlays the sample identification numbers on the plot. Default FALSE. |
colors |
Character vector. Custom colors for the source groups. If NULL (default), the first N Source colors from fluvial_palette are used automatically, where N is the number of source groups detected in data. |
interactive |
Logical. If TRUE, renders an interactive HTML widget for 3D plots. Default FALSE. |
seed |
Integer. Random seed for reproducibility. Default NULL. |
Invisibly returns a list with: lda (the fitted
MASS::lda object), confusion (leave-one-out confusion
matrix), prop_var (percentage of variance explained by each
discriminant axis) and plot (the plot object).
Displays the relative contribution of sediment sources to each mixture as density or violin plots. Designed to take the output of the unmixing functions directly.
plot_apportionment( data, violin = FALSE, bounds = c(0, 1), scaled = TRUE, y_high = 1, colors = NULL, vlines = NULL, title = NULL, bw = "nrd" ) plotResults( data, violin = FALSE, bounds = c(0, 1), scaled = TRUE, y_high = 1, colors = NULL, vlines = NULL, title = NULL, bw = "nrd" ) plot_results( data, violin = FALSE, bounds = c(0, 1), scaled = TRUE, y_high = 1, colors = NULL, vlines = NULL, title = NULL, bw = "nrd" )plot_apportionment( data, violin = FALSE, bounds = c(0, 1), scaled = TRUE, y_high = 1, colors = NULL, vlines = NULL, title = NULL, bw = "nrd" ) plotResults( data, violin = FALSE, bounds = c(0, 1), scaled = TRUE, y_high = 1, colors = NULL, vlines = NULL, title = NULL, bw = "nrd" ) plot_results( data, violin = FALSE, bounds = c(0, 1), scaled = TRUE, y_high = 1, colors = NULL, vlines = NULL, title = NULL, bw = "nrd" )
data |
A data frame, typically the output from |
violin |
Logical. If |
bounds |
A numeric vector of length 2 specifying the lower and upper
display bounds (the camera window). Default |
scaled |
Logical. If |
y_high |
Maximum value for the y-axis. Only used when
|
colors |
An optional named character vector of colors, one per source.
If |
vlines |
An optional named numeric vector specifying true/expected values
for specific sources. Draws a dashed vertical line to allow visual validation
of the model's accuracy (e.g., |
title |
Optional character string to add a main title to the plot. |
bw |
The smoothing bandwidth to be used. Can be a numeric value (e.g., 0.06) or a character string like "nrd" (the default automatic method). |
A ggplot2 object.
Performs a PCA on the tracer data and displays a biplot with source group
ellipses. Averaged datasets (with Mean_/SD_ or
mean_/sd_ columns) are automatically expanded to individual
observations by sampling from a normal distribution before the PCA is
computed, so all formats are accepted.
plot_pca(data, components = c(1L, 2L), colors = NULL, seed = NULL) PCAPlot(data, components = c(1L, 2L), colors = NULL, seed = NULL) PCA_plot(data, components = c(1L, 2L), colors = NULL, seed = NULL)plot_pca(data, components = c(1L, 2L), colors = NULL, seed = NULL) PCAPlot(data, components = c(1L, 2L), colors = NULL, seed = NULL) PCA_plot(data, components = c(1L, 2L), colors = NULL, seed = NULL)
data |
A data frame containing source and mixture data in the standard fingerprinting format (raw or averaged). |
components |
A numeric vector of length 2 indicating which principal
components to display. Default |
colors |
An optional character vector of colors, one per group. If
|
seed |
An integer value used to initialize the random number generator. |
A ggplot object.
Removes tracer properties whose mixture value falls outside the envelope defined by the minimum and maximum values observed across all source groups. Tracers failing this test cannot be explained by any linear combination of the measured sources and should be excluded before unmixing.
rangeTest(data)rangeTest(data)
data |
Data frame in the standard FluvialTracer format (sources + mixture). |
A data frame retaining only tracer columns that pass the range test.
Visualizes Conservativeness Index (CI) predictions using ternary diagrams. Incorporates advanced hierarchical clustering to automatically group and color-code structurally similar apportionment solutions.
Ternary_Plot( data, tracers = 1:(length(data) - 2), n_row = 4, n_col = 5, Means = FALSE, cluster = FALSE, dendro_lvls = 5, vrtl_sol = FALSE, vrtl = c(1, 0, 0), seed = NULL ) Ternary_diagram( data, tracers = 1:(length(data) - 2), n_row = 4, n_col = 5, Means = FALSE, cluster = FALSE, dendro_lvls = 5, vrtl_sol = FALSE, vrtl = c(1, 0, 0), seed = NULL ) ternary_diagram( data, tracers = 1:(length(data) - 2), n_row = 4, n_col = 5, Means = FALSE, cluster = FALSE, dendro_lvls = 5, vrtl_sol = FALSE, vrtl = c(1, 0, 0), seed = NULL )Ternary_Plot( data, tracers = 1:(length(data) - 2), n_row = 4, n_col = 5, Means = FALSE, cluster = FALSE, dendro_lvls = 5, vrtl_sol = FALSE, vrtl = c(1, 0, 0), seed = NULL ) Ternary_diagram( data, tracers = 1:(length(data) - 2), n_row = 4, n_col = 5, Means = FALSE, cluster = FALSE, dendro_lvls = 5, vrtl_sol = FALSE, vrtl = c(1, 0, 0), seed = NULL ) ternary_diagram( data, tracers = 1:(length(data) - 2), n_row = 4, n_col = 5, Means = FALSE, cluster = FALSE, dendro_lvls = 5, vrtl_sol = FALSE, vrtl = c(1, 0, 0), seed = NULL )
data |
List. The output generated by the CI_Method function. |
tracers |
Numeric vector. Indices of the tracers to display. Default 1:4. |
n_row |
Integer. Number of rows in the output grid layout. Default 1. |
n_col |
Integer. Number of columns in the output grid layout. Default 2. |
Means |
Logical. If TRUE, indicates the input utilizes mean and SD formats rather than raw observations. Default FALSE. |
cluster |
Logical. If TRUE, applies hierarchical clustering to group structurally similar ternary solutions. Default FALSE. |
dendro_lvls |
Integer. Number of branch levels to cut the clustering dendrogram. Default 5. |
vrtl_sol |
Logical. If TRUE, overlays a theoretical or target virtual solution on the plot. Default FALSE. |
vrtl |
Numeric vector. Apportionment values for the theoretical solution. Default c(0.05, 0.9, 0.05). |
seed |
Integer. Random seed for reproducible cluster ordering when cluster = TRUE. Default NULL. |
No return value, called for side effects (draws ternary diagrams of the individual tracer predictions on the current graphics device).
Evaluates the directional bias introduced by individual tracers within Consistent Tracer Selection (CTS) subset models. This function unpacks the unconstrained source apportionments to reveal if specific tracers are systematically pulling source contributions into physically impossible spaces (e.g., >1 or <0).
tracer_pull_analysis(cts_result)tracer_pull_analysis(cts_result)
cts_result |
A data frame containing the output from a CTS run. It must contain an
|
Global unmixing models (using all tracers simultaneously) can suffer from "tracer compensation," where extreme mathematical contradictions between non-conservative tracers cancel each other out, resulting in a misleadingly plausible central solution.
This function exposes that illusion. By taking the output of a CTS run (e.g., CTS_n_sources),
it isolates every debate a specific tracer participated in. It then calculates the marginal effect
(median, mean, and SD) that the tracer has on the fractional weight of each source.
Visualizations are automatically generated to aid interpretation:
Boxplots: Display the distribution of calculated weights for each source, grouped by tracer. Red dashed lines denote the physical boundaries of 0 and 1.
Heatmap: Displays the median weight pull. Deep red indicates a strong positive pull (overestimation), while deep blue indicates a negative pull (pushing the source into negative mass space).
A named list containing four elements:
summaryA tibble containing the Mean, Median, and SD of the weights forced by each tracer on each source.
boxplotA ggplot object showing the distribution of source weights grouped by tracer.
heatmapA ggplot object visualizing the median tracer bias across all sources.
raw_expandedA tibble of the raw, pivoted data used for calculations and plotting.
For each tracer of interest, solves a series of minimal determined linear systems to assess how consistently that tracer constrains the source apportionment. In each iteration the tracer under evaluation is kept fixed while the remaining tracers needed to complete the system are drawn at random from the other measured tracers in the dataset (dataset approach). Because the companion tracers are real geochemical measurements, this strategy reflects realistic co-variation patterns among tracers and produces a less conservative — but more ecologically meaningful — estimate of tracer informativeness compared to the virtual approach.
triangles_dataset( sources, mixtures, tracer = 0L, iter = 100L, seed = 69512L, pb = NULL, pb_offset = 0L, tracer_current = NULL, tracer_total = NULL )triangles_dataset( sources, mixtures, tracer = 0L, iter = 100L, seed = 69512L, pb = NULL, pb_offset = 0L, tracer_current = NULL, tracer_total = NULL )
sources |
Data frame of source statistics: ID, one mean column per
tracer, one SD column per tracer, and sample size |
mixtures |
Data frame of mixture samples with the same tracer columns. |
tracer |
Integer (0-based). Index of the tracer under evaluation. |
iter |
Integer. Number of Monte Carlo iterations per mixture sample. |
seed |
Integer. Random seed for reproducibility. Default |
pb |
An optional |
pb_offset |
Integer. Starting offset for the external progress bar.
Default |
tracer_current |
Integer. Position of this tracer in the outer loop,
used to print a progress message. Default |
tracer_total |
Integer. Total number of tracers in the outer loop.
Default |
This function is called internally by CI_Method() and is not usually
invoked directly by the user.
A data frame with nrow(mixtures) * iter rows. Columns are
ID (mixture index), GOF (set to 1 for all rows), and one
weight column per source (w.S1, w.S2, ...).
For each tracer of interest, solves a series of minimal determined linear
systems to assess how consistently that tracer constrains the source
apportionment. In each iteration the tracer under evaluation is kept fixed
while the remaining tracers needed to complete the system are replaced by
uniformly random values in (virtual approach). The mixture
value for each virtual tracer is drawn inside the range spanned by the
virtual source values, ensuring the system is geometrically solvable.
Because the companion tracers carry no real geochemical information, any
consistency in the resulting source weights is attributable solely to the
tracer under evaluation, making this a conservative (worst-case) estimator
of tracer informativeness.
triangles_virtual( sources, mixtures, tracer = 0L, iter = 100L, seed = 69512L, pb = NULL, pb_offset = 0L, tracer_current = NULL, tracer_total = NULL )triangles_virtual( sources, mixtures, tracer = 0L, iter = 100L, seed = 69512L, pb = NULL, pb_offset = 0L, tracer_current = NULL, tracer_total = NULL )
sources |
Data frame of source statistics: ID, one mean column per
tracer, one SD column per tracer, and sample size |
mixtures |
Data frame of mixture samples with the same tracer columns. |
tracer |
Integer (0-based). Index of the tracer under evaluation. |
iter |
Integer. Number of Monte Carlo iterations per mixture sample. |
seed |
Integer. Random seed for reproducibility. Default |
pb |
An optional |
pb_offset |
Integer. Starting offset for the external progress bar.
Default |
tracer_current |
Integer. Position of this tracer in the outer loop,
used to print a progress message. Default |
tracer_total |
Integer. Total number of tracers in the outer loop.
Default |
This function is called internally by CI_Method() and is not usually
invoked directly by the user.
A data frame with nrow(mixtures) * iter rows. Columns are
ID (mixture index), GOF (set to 1 for all rows), and one
weight column per source (w.S1, w.S2, ...).
A wrapper function that seamlessly formats an 'FluvialTracer' dataset (raw or averaged) and passes it to the 'MixSIAR' Bayesian unmixing engine.
unmix_mixsiar( data, tracers, prior_type = "uninformative", prior_values = NULL, run = "normal", process_err = FALSE, resid_err = TRUE )unmix_mixsiar( data, tracers, prior_type = "uninformative", prior_values = NULL, run = "normal", process_err = FALSE, resid_err = TRUE )
data |
Data frame. Contains source and mixture data in the standard FluvialTracer format. |
tracers |
Character vector. Names of the tracers to include in the model. |
prior_type |
Character. "uninformative" (default, alpha=1) or "informative". |
prior_values |
Numeric vector. Required if 'prior_type = "informative"'. Must match the number of sources. |
run |
Character. MCMC run length. Options: "test", "very short", "short", "normal" (default), "long", "very long", "extreme". |
process_err |
Logical. Include process error in the JAGS model? Default FALSE. |
resid_err |
Logical. Include residual error in the JAGS model? Default TRUE. |
A list with three elements:
apportionmentData frame with the posterior draws of the
global source proportions, in the FluvialTracer format (ID,
GOF and one column per source), compatible with
plot_apportionment.
bayesian_summaryData frame with the summary statistics of all model parameters returned by JAGS.
jags_modelThe full JAGS model object returned by
MixSIAR::run_model.
Trains a Random Forest model on simulated virtual mixtures. Features a 'stretch_bounds' parameter to expand training data beyond the 0-1 limits, effectively eliminating the boundary bias typically seen in pure Machine Learning and Bayesian unmixing of extreme sources.
unmix_rf( data, n_sim = 10000L, n_trees = 500L, stretch_bounds = 1.2, seed = 123456L )unmix_rf( data, n_sim = 10000L, n_trees = 500L, stretch_bounds = 1.2, seed = 123456L )
data |
Data frame. Contains source and mixture data in the standard FluvialTracer format. |
n_sim |
Integer. Number of virtual mixtures to simulate for training. Default 10000. |
n_trees |
Integer. Number of trees for the Random Forest model. Default 500. |
stretch_bounds |
Numeric. Factor to expand training boundaries to avoid 0/1 bias. Default 1.2. |
seed |
Integer. Random seed for reproducibility. Default 123456. |
A list containing the apportionment data frame (one row per tree) and a summary.
Trains an ensemble of XGBoost models on simulated virtual mixtures. Uses bootstrapping to generate uncertainty distributions (density curves).
unmix_xgboost( data, n_sim = 5000L, n_boot = 100L, stretch_bounds = 1.2, seed = 123456L )unmix_xgboost( data, n_sim = 5000L, n_boot = 100L, stretch_bounds = 1.2, seed = 123456L )
data |
Data frame. Contains source and mixture data. |
n_sim |
Integer. Number of virtual mixtures for the base training set. Default 5000. |
n_boot |
Integer. Number of XGBoost models to train (iterations for uncertainty). Default 100. |
stretch_bounds |
Numeric. Expansion factor for training boundaries. Default 1.2. |
seed |
Integer. Random seed. Default 123456.. |
Invisibly returns a list with two elements: apportionment,
a data frame with one row per bootstrapped model (ID, GOF
and one column per source), compatible with
plot_apportionment; and xgb_summary, a data frame
with the mean, SD, median and 95% interval of each source contribution.
Estimates the fractional contribution of each potential source to one or more mixtures. Users can seamlessly switch between a lightning-fast Frequentist least-squares approach (with optional Linear Variability Propagation), a standard Bayesian MCMC approach, or a Machine Learning approach.
unmixing( data, model = "frequentist", iter = 1000L, variability = "SEM", lvp = TRUE, seed = 123456L, ml_type = "RandomForest", ... )unmixing( data, model = "frequentist", iter = 1000L, variability = "SEM", lvp = TRUE, seed = 123456L, ml_type = "RandomForest", ... )
data |
Data frame in the standard FluvialTracer format. |
model |
Character. |
iter |
Integer. Number of iterations for frequentist Monte Carlo/LVP.
Default |
variability |
Character. Uncertainty metric: |
lvp |
Logical. |
seed |
Integer. Random seed for reproducibility. Default |
ml_type |
Character. Only used if |
... |
Additional arguments passed to the Bayesian or ML engines (e.g., |
Both raw (individual observations) and averaged (Mean_/SD_
columns) input formats are accepted. When multiple mixture samples are
present, the model processes each independently.
For the "frequentist" model, a data frame with one row per iteration
and mixture. For the "bayesian" model, a named list containing the
formatted apportionment data frame, the MixSIAR summary statistics, and the
raw JAGS model object. For the "machine_learning" model, a named list
containing the apportionment predictions and a statistical summary (rf_summary or xgb_summary).
Latorre, B., Lizaga, I., Gaspar, L., & Navas, A. (2025). Evaluating the impact of high source variability and extreme contributing sources on sediment fingerprinting models. Water Resources Management. doi:10.1007/s11269-025-04169-8