| Title: | Analysis and Visualization of Laser-Induced Breakdown Spectroscopy Data |
|---|---|
| Description: | Provides a vendor-agnostic pipeline for importing, preprocessing, calibrating, and visualizing Laser-Induced Breakdown Spectroscopy (LIBS) spectral data. Supports baseline correction, peak identification against user-supplied atomic emission line references, univariate and multivariate calibration, relative elemental amounts under an explicitly specified two-stage Saha-Boltzmann model, and calibration-based detection-limit estimates. Includes exploratory chemometric analysis (principal component analysis, partial least squares discriminant analysis, clustering), heuristic tissue classification, and spatial elemental mapping. Includes an interactive 'shiny' application for spectral exploration. Designed for biomedical tissue analysis, environmental monitoring, and materials characterization workflows. |
| Authors: | R. Heller [aut, cre] (ORCID: <https://orcid.org/0000-0001-8006-9742>) |
| Maintainer: | R. Heller <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.0.9001 |
| Built: | 2026-11-03 18:13:47 UTC |
| Source: | https://github.com/CTTIR/libscanR |
Subset a LIBS Dataset
## S3 method for class 'libs_dataset' x[i]## S3 method for class 'libs_dataset' x[i]
x |
A |
i |
Integer or logical index of spectra to keep. |
A new libs_dataset.
Returns a new libs_spectrum with channels whose wavelengths fall in the
supplied numeric vector's range.
## S3 method for class 'libs_spectrum' x[i]## S3 method for class 'libs_spectrum' x[i]
x |
A |
i |
Numeric vector. Wavelengths are kept if they fall in
|
A new libs_spectrum object.
Concatenates shots from multiple spectra. All spectra must share the same
wavelength axis. Shared metadata are retained; source metadata are stored
in combined_metadata. If every input has a baseline, the output stores
its shot-weighted mean; otherwise the aggregate baseline is unknown.
## S3 method for class 'libs_spectrum' c(...)## S3 method for class 'libs_spectrum' c(...)
... |
Two or more |
A new libs_spectrum with combined shots.
Dimensions of a Dataset (spectra x channels)
## S3 method for class 'libs_dataset' dim(x)## S3 method for class 'libs_dataset' dim(x)
x |
A |
Integer vector of length 2.
Dimensions of a LIBS Spectrum (shots x channels)
## S3 method for class 'libs_spectrum' dim(x)## S3 method for class 'libs_spectrum' dim(x)
x |
A |
Integer vector of length 2.
Test whether an object is a libs_calibration
is_libs_calibration(x)is_libs_calibration(x)
x |
Object to test. |
Logical scalar.
Test whether an object is a libs_dataset
is_libs_dataset(x)is_libs_dataset(x)
x |
Object to test. |
Logical scalar.
Test whether an object is a libs_spectrum
is_libs_spectrum(x)is_libs_spectrum(x)
x |
Object to test. |
Logical scalar.
Number of Spectra in a Dataset
## S3 method for class 'libs_dataset' length(x)## S3 method for class 'libs_dataset' length(x)
x |
A |
Integer scalar.
Number of Channels in a LIBS Spectrum
## S3 method for class 'libs_spectrum' length(x)## S3 method for class 'libs_spectrum' length(x)
x |
A |
Integer scalar.
Averages shots within a ls_spectrum().
ls_average_shots(x, method = "mean", trim = 0, remove_outliers = FALSE)ls_average_shots(x, method = "mean", trim = 0, remove_outliers = FALSE)
x |
A |
method |
Character. |
trim |
Numeric. Fraction trimmed from each end for trimmed mean. Default 0. |
remove_outliers |
Logical. Remove shots with deviation > 3 SD from
the per-channel mean. Default |
A libs_spectrum with a single averaged shot.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), n_shots = 10, seed = 1) ls_average_shots(spec, remove_outliers = TRUE)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), n_shots = 10, seed = 1) ls_average_shots(spec, remove_outliers = TRUE)
Removes continuum/baseline drift from LIBS spectra. Supported methods:
"snip" (Statistics-sensitive Non-linear Iterative Peak-clipping,
Morhac/Ryan), "als" (Asymmetric Least Squares smoothing, Eilers &
Boelens), "rolling_ball" (morphological), "linear" (two-endpoint
interpolation), or "polynomial" (low-order polynomial fit of
baseline-only regions).
ls_baseline( x, method = "snip", iterations = 100, order = 3, lambda = 1e+05, p = 0.01, radius = 50, ... )ls_baseline( x, method = "snip", iterations = 100, order = 3, lambda = 1e+05, p = 0.01, radius = 50, ... )
x |
A |
method |
Character. One of |
iterations |
Integer. Iterations for iterative methods (SNIP, ALS). Default 100. |
order |
Integer. Polynomial order for |
lambda |
Numeric. Smoothness parameter for ALS. Default |
p |
Numeric. Asymmetry parameter for ALS (0 < p < 1). Default 0.01. |
radius |
Integer. Rolling-ball radius in channels. Default 50. |
... |
Reserved for future use. |
Same class as input with baseline-corrected intensities; the
estimated baseline is stored in the baseline element for inspection.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) corr <- ls_baseline(spec, method = "snip") is.null(corr$baseline)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) corr <- ls_baseline(spec, method = "snip") is.null(corr$baseline)
Constructs a spatial map from LIBS line-scan or raster-scan data. The
dataset's sample_info must include x_pos and y_pos columns.
Coordinates must be finite numeric values and each pair must be unique;
aggregate replicate positions explicitly before mapping them.
ls_build_map(dataset, element, line_nm, calibration = NULL, window_nm = NULL)ls_build_map(dataset, element, line_nm, calibration = NULL, window_nm = NULL)
dataset |
A |
element |
Character. Element label (for metadata). |
line_nm |
Numeric. Emission line wavelength (nm). |
calibration |
Optional |
window_nm |
Optional integration window. |
A list with S3 class libs_map containing x, y, values,
element, line_nm, unit, and a rasterized grid matrix when the
points form a regular grid.
ds <- ls_example_data("spatial") m <- ls_build_map(ds, "Ca", 393.37) dim(m$grid)ds <- ls_example_data("spatial") m <- ls_build_map(ds, "Ca", 393.37) dim(m$grid)
Constructs a calibration model from standards with known concentrations.
ls_calibrate( dataset, element, line_nm, concentrations, method = "univariate", internal_std_nm = NULL, window_nm = 1, pls_window_nm = NULL, n_components = 5, unit = "ppm", verbose = TRUE )ls_calibrate( dataset, element, line_nm, concentrations, method = "univariate", internal_std_nm = NULL, window_nm = 1, pls_window_nm = NULL, n_components = 5, unit = "ppm", verbose = TRUE )
dataset |
A |
element |
Character. Target element symbol. |
line_nm |
Numeric. Emission line wavelength (nm). |
concentrations |
Numeric vector of known concentrations, one per
spectrum in |
method |
Character. |
internal_std_nm |
Numeric. Internal standard line wavelength,
required for |
window_nm |
Numeric. Peak integration window. Default 1. |
pls_window_nm |
Numeric vector of length 2. Spectral window for PLS.
Default |
n_components |
Integer. Number of PLS components. Default 5. |
unit |
Character. Concentration unit. Default |
verbose |
Logical. Default |
Prediction preserves the fitted wavelength axis, ordered preprocessing,
integration window and internal-standard ratio or PLS columns. Univariate
predictions retain inverse concentration-on-response regression. Estimated
3-sigma LOD and 10-sigma LOQ use the residual standard deviation of a separate
response-on-concentration fit divided by its absolute slope. These estimates
require independent verification near the limits; they are not validated
instrument limits. PLS reports training RMSE separately and leaves LOD/LOQ
unavailable (NA); residual prediction error alone is not a detection limit.
A ls_calibration() object.
ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) print(cal)ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) print(cal)
Constructs a libs_calibration S3 object holding a fitted calibration
model plus the underlying training data and figures of merit.
ls_calibration( element, wavelength_nm, concentrations, intensities, model, method = "univariate", lod = NULL, loq = NULL, r_squared = NULL, unit = "ppm", feature_contract = NULL, response_model = NULL, lod_basis = NULL, training_rmse = NULL )ls_calibration( element, wavelength_nm, concentrations, intensities, model, method = "univariate", lod = NULL, loq = NULL, r_squared = NULL, unit = "ppm", feature_contract = NULL, response_model = NULL, lod_basis = NULL, training_rmse = NULL )
element |
Character. Element symbol (e.g. "Ca", "Fe"). |
wavelength_nm |
Numeric. Emission line wavelength used. |
concentrations |
Numeric vector. Known concentrations of standards. |
intensities |
Numeric vector. Measured peak intensities or areas
(or ratios for |
model |
Fitted model object ( |
method |
Character. One of |
lod |
Numeric. Limit of detection (3-sigma). Default |
loq |
Numeric. Limit of quantification (10-sigma). Default |
r_squared |
Numeric. Coefficient of determination. Default |
unit |
Character. Concentration unit, e.g. |
feature_contract |
Optional fitted wavelength/preprocessing and extraction
contract, normally populated by |
response_model |
Optional response-on-concentration regression used to estimate univariate detection limits. |
lod_basis |
Character description of the limit estimate, or |
training_rmse |
Numeric training prediction error, or |
A libs_calibration S3 object.
conc <- c(100, 500, 1000, 2500, 5000) ints <- conc * 0.12 + stats::rnorm(5, 0, 5) m <- stats::lm(conc ~ ints) cal <- ls_calibration("Ca", 393.37, conc, ints, model = m, r_squared = summary(m)$r.squared) print(cal)conc <- c(100, 500, 1000, 2500, 5000) ints <- conc * 0.12 + stats::rnorm(5, 0, 5) m <- stats::lm(conc ~ ints) cal <- ls_calibration("Ca", 393.37, conc, ints, model = m, r_squared = summary(m)$r.squared) print(cal)
Applies a trained classifier (from ls_plsda() or ls_train_classifier())
to new spectra.
ls_classify(model, new_data)ls_classify(model, new_data)
model |
A |
new_data |
A |
A tibble::tibble() with columns sample_id, predicted_class,
and score for PLS-DA (an unbounded discriminant score, not a
probability), or probability for SVM/RF. The wavelength axis and ordered
preprocessing must match the fitted contract. Legacy models without this
contract must be refitted before prediction.
ds <- ls_example_data("tissue") if (requireNamespace("e1071", quietly = TRUE)) { clf <- ls_train_classifier(ds[1:30], "tissue", method = "svm") ls_classify(clf, ds[31:50]) }ds <- ls_example_data("tissue") if (requireNamespace("e1071", quietly = TRUE)) { clf <- ls_train_classifier(ds[1:30], "tissue", method = "svm") ls_classify(clf, ds[31:50]) }
Unsupervised clustering via k-means, hierarchical, or DBSCAN (DBSCAN
requires the dbscan package in Suggests).
ls_cluster(dataset, method = "kmeans", k = 3, ...)ls_cluster(dataset, method = "kmeans", k = 3, ...)
dataset |
A |
method |
Character. |
k |
Integer. Number of clusters for kmeans/hclust. Default 3. |
... |
Additional arguments passed to the underlying clustering function. |
An S3 object of class libs_clusters with elements cluster,
method, k, silhouette (mean score excluding DBSCAN noise;
singleton clusters contribute zero; NA when not computable),
sample_info.
ds <- ls_example_data("tissue") cl <- ls_cluster(ds, method = "kmeans", k = 5) cl$clusterds <- ls_example_data("tissue") cl <- ls_cluster(ds, method = "kmeans", k = 5) cl$cluster
Subsets a spectrum or dataset to a wavelength range.
ls_crop(x, min_nm = NULL, max_nm = NULL)ls_crop(x, min_nm = NULL, max_nm = NULL)
x |
A |
min_nm |
Numeric. Minimum wavelength (nm). Default |
max_nm |
Numeric. Maximum wavelength (nm). Default |
Same class as input, cropped.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) ls_crop(spec, 380, 450)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) ls_crop(spec, 380, 450)
Constructs a libs_dataset: a collection of ls_spectrum() objects
sharing a common wavelength axis, plus a sample-info table.
ls_dataset(spectra, sample_info = NULL)ls_dataset(spectra, sample_info = NULL)
spectra |
List of |
sample_info |
Optional data.frame or tibble with one row per spectrum.
Must contain column |
A libs_dataset S3 object.
specs <- lapply(1:3, function(i) { ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 1000 * i, Na = 500), seed = i) }) specs <- Map(function(s, id) { s$metadata$sample_id <- paste0("s", id) s }, specs, seq_along(specs)) ds <- ls_dataset(specs) print(ds)specs <- lapply(1:3, function(i) { ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 1000 * i, Na = 500), seed = i) }) specs <- Map(function(s, id) { s$metadata$sample_id <- paste0("s", id) s }, specs, seq_along(specs)) ds <- ls_dataset(specs) print(ds)
Returns invented peak strengths at the package's existing teaching and heuristic integration windows. Component names are labels used by the example scenarios, not validated elemental identifications. This table is not derived from an atomic database: it contains no transition rates, energy levels or statistical weights, and must not be used as a reference for experimental spectra. It is accepted only as explicit simulation input.
ls_demo_peaks()ls_demo_peaks()
A tibble with component, wavelength_nm and relative_strength.
Every strength is the arbitrary multiplier 0.001.
peaks <- ls_demo_peaks() spec <- ls_simulate_spectrum(seed = 1, line_data = peaks) ls_plot_spectrum(spec)peaks <- ls_demo_peaks() spec <- ls_simulate_spectrum(seed = 1, line_data = peaks) ls_plot_spectrum(spec)
Reads a local CSV or RDS table supplied by the user. No atomic reference
compilation is bundled and this function does not access the network.
Configure a file with options(libscanR.element_db = "/path/lines.csv")
or the environment variable LIBSCANR_ELEMENT_DB. An explicit path
takes precedence over the option, which takes precedence over the variable.
ls_element_db( elements = NULL, range_nm = c(190, 900), min_aki = 0, ionization = c(1L, 2L), persistent_only = FALSE, path = NULL )ls_element_db( elements = NULL, range_nm = c(190, 900), min_aki = 0, ionization = c(1L, 2L), persistent_only = FALSE, path = NULL )
elements |
Character vector of element symbols, or |
range_nm |
Two ordered finite wavelength limits, or |
min_aki |
Minimum transition probability in units of 10^8 s^-1. Missing rates are excluded only when this is positive. |
ionization |
Ionization states: 1 = neutral, 2 = singly ionized,
or |
persistent_only |
Keep only rows explicitly marked |
path |
Local CSV/RDS file. Default |
The table must contain element, ionization, wavelength_nm, aki
(transition probability in units of 10^8 s^-1), wavelength_medium
("air" or "vacuum") and a nonempty source attribution per row.
Missing transition rates remain missing. Optional ei_ev, ek_ev and
persistent columns default to missing energies and FALSE; no persistent
line designation is inferred. Other columns and provenance are retained.
The installed package provides scripts/import_nist.py for converting a
separately downloaded NIST ASD CSV; see the README for exact settings.
A tibble::tibble() retaining the reference columns. Physical fields
required by ls_saha_boltzmann() must be supplied and independently checked;
loading a reference does not establish its scientific validity or reuse rights.
# After downloading and importing a reference as described in the README: # options(libscanR.element_db = "local-data/atomic-lines.csv") # ls_element_db(elements = "Ca")# After downloading and importing a reference as described in the README: # options(libscanR.element_db = "local-data/atomic-lines.csv") # ls_element_db(elements = "Ca")
Creates a synthetic libs_dataset suitable for demonstrating package
features without an atomic reference download. All scenarios use explicit
fictional peaks from ls_demo_peaks(); component names and tissue labels
are teaching labels, not measured concentrations or biological ground truth.
Scenarios:
ls_example_data( scenario = c("tissue", "calibration", "spatial", "all"), seed = 42, n_channels = 1024 )ls_example_data( scenario = c("tissue", "calibration", "spatial", "all"), seed = 42, n_channels = 1024 )
scenario |
Character. One of |
seed |
Integer. Random seed. Default 42. |
n_channels |
Integer. Number of spectral channels. Default 1024 (reduced from 2048 for faster examples). |
"tissue" — 50 spectra from 5 tissue types (bone, liver, kidney,
muscle, fat), 10 per type, with deliberately different synthetic profiles.
"calibration" — 27 spectra of Ca standards (9 concentrations x 3
replicates) with constant matrix (Na, K, Mg).
"spatial" — 400 spectra on a 20x20 grid simulating a tissue
cross-section with Ca/Fe gradients and a Zn-enriched hotspot.
"all" — named list of the above.
A libs_dataset object (or named list for "all").
ds <- ls_example_data("tissue") print(ds)ds <- ls_example_data("tissue") print(ds)
Writes each spectrum in a dataset as a separate CSV file, plus a
sample_info.csv metadata table. IDs must be unique portable filenames.
Existing output is left intact if overwrite = FALSE; if any target exists,
the whole export is skipped. All files are staged before replacement, with
rollback on ordinary write failures. Concurrent writers and power-loss
recovery are not supported.
ls_export_spectra(dataset, dir, overwrite = FALSE)ls_export_spectra(dataset, dir, overwrite = FALSE)
dataset |
A |
dir |
Character. Output directory (created if missing). |
overwrite |
Logical. Overwrite existing files. Default |
Invisibly returns dir.
ds <- ls_example_data("tissue")[1:3] tmp <- tempfile() ls_export_spectra(ds, tmp) list.files(tmp) unlink(tmp, recursive = TRUE)ds <- ls_example_data("tissue")[1:3] tmp <- tempfile() ls_export_spectra(ds, tmp) list.files(tmp) unlink(tmp, recursive = TRUE)
Detects peaks in a LIBS spectrum using local maxima detection with prominence and signal-to-noise filtering.
ls_find_peaks( x, snr_threshold = 3, min_prominence = 0.01, min_distance_nm = 0.5 )ls_find_peaks( x, snr_threshold = 3, min_prominence = 0.01, min_distance_nm = 0.5 )
x |
A |
snr_threshold |
Numeric. Minimum signal-to-noise ratio. Default 3. |
min_prominence |
Numeric. Minimum peak prominence as a fraction of maximum intensity (0-1). Default 0.01. |
min_distance_nm |
Numeric. Minimum distance between peaks (nm). Default 0.5. |
A tibble::tibble() with columns wavelength_nm, intensity,
snr, prominence, fwhm_nm, area, sorted by intensity descending.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 5000, Na = 1000), seed = 1) peaks <- ls_find_peaks(spec, snr_threshold = 5) head(peaks)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 5000, Na = 1000), seed = 1) peaks <- ls_find_peaks(spec, snr_threshold = 5) head(peaks)
Analyzes SNR and signal-to-background ratios across spectra acquired at different gate delays to recommend optimal timing for a target line.
ls_gate_optimize(spectra, element, line_nm, window_nm = 1)ls_gate_optimize(spectra, element, line_nm, window_nm = 1)
spectra |
List of |
element |
Character. Target element symbol. |
line_nm |
Numeric. Target emission line wavelength (nm). |
window_nm |
Numeric. Window around the line. Default 1. |
A tibble::tibble() with columns gate_delay_us, snr, sbr,
peak_intensity, with attribute "recommended" giving the row index
of the highest SNR.
specs <- lapply(c(0.5, 1, 2, 5, 10), function(g) { s <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = round(g * 10)) s$metadata$gate_delay_us <- g s }) ls_gate_optimize(specs, "Ca", 393.37)specs <- lapply(c(0.5, 1, 2, 5, 10), function(g) { s <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = round(g * 10)) s$metadata$gate_delay_us <- g s }) ls_gate_optimize(specs, "Ca", 393.37)
Matches detected peaks to known atomic emission lines. Each peak is
assigned its nearest wavelength candidate from the user-configured reference.
No atomic reference is bundled; configure ls_element_db() first.
This is a candidate identification, not proof of elemental presence or
resolution of blended transitions. Check the measured air/vacuum convention.
ls_identify_peaks( peaks, elements = NULL, tolerance_nm = 0.2, ionization = c(1L, 2L) )ls_identify_peaks( peaks, elements = NULL, tolerance_nm = 0.2, ionization = c(1L, 2L) )
peaks |
A tibble from |
elements |
Character vector. Restrict search. Default |
tolerance_nm |
Numeric. Maximum wavelength deviation. Default 0.2. |
ionization |
Integer vector of ionization states. Default |
A tibble with all peak columns plus: element, ionization,
nist_wavelength_nm, nist_aki, deviation_nm, confidence (0-1),
n_candidates, and wavelength_medium. The legacy confidence name
denotes only 1 - abs(deviation_nm) / tolerance_nm, not a probability.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 5000, Na = 1000), seed = 1) pk <- ls_find_peaks(spec, snr_threshold = 5) id <- ls_identify_peaks(pk, elements = c("Ca", "Na")) head(id)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 5000, Na = 1000), seed = 1) pk <- ls_find_peaks(spec, snr_threshold = 5) id <- ls_identify_peaks(pk, elements = c("Ca", "Na")) head(id)
Calculates LOD using the 3-sigma criterion.
ls_lod(calibration, blank = NULL, window_nm = NULL)ls_lod(calibration, blank = NULL, window_nm = NULL)
calibration |
A |
blank |
Optional |
window_nm |
Optional window; |
Estimated numeric LOD in the calibration's concentration unit; NA
for PLS. This 3-sigma estimate requires independent confirmation near the
detection limit and is not an instrument qualification.
ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_lod(cal)ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_lod(cal)
Calculates LOQ using the 10-sigma criterion.
ls_loq(calibration, blank = NULL, window_nm = NULL)ls_loq(calibration, blank = NULL, window_nm = NULL)
calibration |
A |
blank |
Optional |
window_nm |
Optional window; |
Numeric LOQ in the calibration's concentration unit.
ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_loq(cal)ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_loq(cal)
Build Maps for Multiple Elements
ls_map_elements( dataset, elements, lines_nm, calibrations = NULL, window_nm = NULL )ls_map_elements( dataset, elements, lines_nm, calibrations = NULL, window_nm = NULL )
dataset |
A |
elements |
Character vector. Elements to map. |
lines_nm |
Named numeric vector: wavelength per element (e.g.
|
calibrations |
Named list of |
window_nm |
Optional integration window. |
A named list of libs_map objects.
ds <- ls_example_data("spatial") ls_map_elements(ds, c("Ca", "Fe"), c(Ca = 393.37, Fe = 371.99))ds <- ls_example_data("spatial") ls_map_elements(ds, c("Ca", "Fe"), c(Ca = 393.37, Fe = 371.99))
Normalizes intensity values. Methods:
"total" — divide each shot by total intensity
"max" — divide by per-shot maximum
"snv" — Standard Normal Variate: (x - mean) / sd
"internal_std" — divide by intensity at a reference line
"area" — divide by integrated (trapezoidal) area
ls_normalize(x, method = "total", ref_wavelength = NULL, ref_window = 1)ls_normalize(x, method = "total", ref_wavelength = NULL, ref_window = 1)
x |
A |
method |
Character. Normalization method. Default |
ref_wavelength |
Numeric. Required for |
ref_window |
Numeric. Window width (nm) around |
Same class as input with normalized intensities. A zero or non-finite
divisor is an error; a constant SNV shot becomes zero. Previous removed
baselines are retained in metadata$baseline_history and cleared from
baseline, because per-shot scaling changes their units.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) spec_n <- ls_normalize(spec, method = "total") sum(spec_n$intensity[1, ]) # ~1spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) spec_n <- ls_normalize(spec, method = "total") sum(spec_n$intensity[1, ]) # ~1
Performs PCA on the intensity matrix of a ls_dataset().
ls_pca(dataset, n_components = 10, scale = TRUE, center = TRUE)ls_pca(dataset, n_components = 10, scale = TRUE, center = TRUE)
dataset |
A |
n_components |
Integer. Number of PCs to retain. Default 10. |
scale |
Logical. Scale variables to unit variance. Default |
center |
Logical. Center variables. Default |
A list with S3 class libs_pca containing:
scores (matrix: spectra x PCs), loadings (matrix: channels x PCs),
sdev, variance_explained (fraction), cumulative_variance,
wavelength, sample_info, pca_obj.
ds <- ls_example_data("tissue") pca <- ls_pca(ds, n_components = 5) pca$variance_explainedds <- ls_example_data("tissue") pca <- ls_pca(ds, n_components = 5) pca$variance_explained
Integrates peak area at a given emission line, with a local baseline subtracted (linear interpolation between window edges).
ls_peak_area(x, center_nm, window_nm = 1, method = "trapezoidal")ls_peak_area(x, center_nm, window_nm = 1, method = "trapezoidal")
x |
A |
center_nm |
Numeric. Peak center wavelength (nm). |
window_nm |
Numeric. Integration window width. Default 1. To support coarsely sampled input, the effective window is at least five median channel spacings, with up to five nearest channels used at edges. This does not resolve overlapping lines; inspect instrument resolution and the integration region before interpreting an area as an element. |
method |
Character. |
Numeric. Baseline-subtracted integrated peak area.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 5000), seed = 1) ls_peak_area(spec, 393.37)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 5000), seed = 1) ls_peak_area(spec, 393.37)
Plot a Calibration Curve
ls_plot_calibration( calibration, show_lod = TRUE, show_loq = TRUE, show_prediction_interval = TRUE )ls_plot_calibration( calibration, show_lod = TRUE, show_loq = TRUE, show_prediction_interval = TRUE )
calibration |
A |
show_lod |
Logical. Show LOD as a horizontal dashed line. Default |
show_loq |
Logical. Show LOQ as a horizontal dashed line. Default |
show_prediction_interval |
Logical. Show 95% prediction band.
Default |
A ggplot2 object.
ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_plot_calibration(cal)ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_plot_calibration(cal)
Convenience alias for ls_plot_map().
ls_plot_element_map(map, ...)ls_plot_element_map(map, ...)
map |
A |
... |
Passed to |
A ggplot2 object.
ds <- ls_example_data("spatial") ls_plot_element_map(ls_build_map(ds, "Ca", 393.37))ds <- ls_example_data("spatial") ls_plot_element_map(ls_build_map(ds, "Ca", 393.37))
Plots the loadings for a selected principal component across the full wavelength axis, optionally annotating the top contributing channels.
ls_plot_loadings(pca, pc = 1, n_top = 10)ls_plot_loadings(pca, pc = 1, n_top = 10)
pca |
A |
pc |
Integer. Which PC's loadings to show. Default 1. |
n_top |
Integer. Number of top-absolute contributors to annotate. Default 10. |
A ggplot2 object.
ds <- ls_example_data("tissue") pca <- ls_pca(ds, n_components = 4) ls_plot_loadings(pca, pc = 1, n_top = 5)ds <- ls_example_data("tissue") pca <- ls_pca(ds, n_components = 4) ls_plot_loadings(pca, pc = 1, n_top = 5)
Plot an Elemental Map
ls_plot_map(map, color_scale = "viridis", title = NULL)ls_plot_map(map, color_scale = "viridis", title = NULL)
map |
A |
color_scale |
Character. |
title |
Character. Plot title. Default: element symbol. |
A ggplot2 object.
ds <- ls_example_data("spatial") m <- ls_build_map(ds, "Ca", 393.37) ls_plot_map(m)ds <- ls_example_data("spatial") m <- ls_build_map(ds, "Ca", 393.37) ls_plot_map(m)
Plots multiple elemental maps as a faceted panel.
ls_plot_map_panel(maps, ncol = 3)ls_plot_map_panel(maps, ncol = 3)
maps |
Named list of |
ncol |
Integer. Facet columns. Default 3. |
A ggplot2 object.
ds <- ls_example_data("spatial") ms <- ls_map_elements(ds, c("Ca", "Fe", "Zn"), c(Ca = 393.37, Fe = 371.99, Zn = 213.86)) ls_plot_map_panel(ms)ds <- ls_example_data("spatial") ms <- ls_map_elements(ds, c("Ca", "Fe", "Zn"), c(Ca = 393.37, Fe = 371.99, Zn = 213.86)) ls_plot_map_panel(ms)
Plots multiple spectra on the same axes, optionally colored by a grouping variable.
ls_plot_overlay(dataset, color_by = NULL, normalize = FALSE, alpha = 0.5)ls_plot_overlay(dataset, color_by = NULL, normalize = FALSE, alpha = 0.5)
dataset |
A |
color_by |
Character. Column in |
normalize |
Logical. Divide each spectrum by its positive maximum. Default |
alpha |
Numeric. Line alpha. Default 0.5. |
A ggplot2 object.
ds <- ls_example_data("tissue") ls_plot_overlay(ds[1:10], color_by = "tissue")ds <- ls_example_data("tissue") ls_plot_overlay(ds[1:10], color_by = "tissue")
Plot PCA Scores
ls_plot_pca(pca, pc_x = 1, pc_y = 2, color_by = NULL, ellipses = TRUE)ls_plot_pca(pca, pc_x = 1, pc_y = 2, color_by = NULL, ellipses = TRUE)
pca |
A |
pc_x |
Integer. PC for x-axis. Default 1. |
pc_y |
Integer. PC for y-axis. Default 2. |
color_by |
Character. Sample-info column. Numeric values use a continuous
colour scale; other values define discrete groups. Default |
ellipses |
Logical. Draw nominal 95% normal-theory data ellipses for
discrete groups with at least four non-collinear points. They describe score
dispersion, not confidence intervals for a group mean. Default |
A ggplot2 object.
ds <- ls_example_data("tissue") pca <- ls_pca(ds, n_components = 4) ls_plot_pca(pca, color_by = "tissue")ds <- ls_example_data("tissue") pca <- ls_pca(ds, n_components = 4) ls_plot_pca(pca, color_by = "tissue")
Plot PLS-DA Results
ls_plot_plsda(plsda, type = "scores")ls_plot_plsda(plsda, type = "scores")
plsda |
A |
type |
Character. |
A ggplot2 object.
ds <- ls_example_data("tissue") if (requireNamespace("pls", quietly = TRUE)) { plsda <- ls_plsda(ds, "tissue", n_components = 3, validation = "none") ls_plot_plsda(plsda, type = "scores") }ds <- ls_example_data("tissue") if (requireNamespace("pls", quietly = TRUE)) { plsda <- ls_plsda(ds, "tissue", n_components = 3, validation = "none") ls_plot_plsda(plsda, type = "scores") }
Zooms into a specified wavelength range and annotates peaks when a user
reference is configured. With default elements = NULL and no reference,
the spectrum remains visible and a subtitle reports unavailable annotations.
Explicitly requesting element labels requires a configured reference.
ls_plot_region(x, min_nm, max_nm, elements = NULL, snr_threshold = 5)ls_plot_region(x, min_nm, max_nm, elements = NULL, snr_threshold = 5)
x |
A |
min_nm |
Numeric. Minimum wavelength (nm). |
max_nm |
Numeric. Maximum wavelength (nm). |
elements |
Optional character vector. Element symbols to annotate.
Default |
snr_threshold |
Numeric. SNR threshold for peak detection. Default 5. |
A ggplot2 object.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) ls_plot_region(spec, 380, 410)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) ls_plot_region(spec, 380, 410)
Standard regression diagnostic: residuals vs fitted.
ls_plot_residuals(calibration)ls_plot_residuals(calibration)
calibration |
A |
A ggplot2 object.
ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_plot_residuals(cal)ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_plot_residuals(cal)
Plot PCA Variance (Scree Plot)
ls_plot_scree(pca)ls_plot_scree(pca)
pca |
A |
A ggplot2 object.
ds <- ls_example_data("tissue") pca <- ls_pca(ds, n_components = 6) ls_plot_scree(pca)ds <- ls_example_data("tissue") pca <- ls_pca(ds, n_components = 6) ls_plot_scree(pca)
Generic spectrum plotter. Returns a ggplot2 object.
ls_plot_spectrum( x, show_peaks = FALSE, show_elements = NULL, normalize = FALSE, snr_threshold = 5, ... )ls_plot_spectrum( x, show_peaks = FALSE, show_elements = NULL, normalize = FALSE, snr_threshold = 5, ... )
x |
A |
show_peaks |
Logical. Annotate detected peaks. Default |
show_elements |
Character vector of element symbols to highlight
as dashed vertical lines from the configured reference. All matching rows
in the displayed range are used; no persistent-line status is inferred.
Default |
normalize |
Logical. Divide intensity by its positive maximum before plotting.
Default |
snr_threshold |
Numeric. SNR threshold for peak annotation when
|
... |
Additional arguments (currently unused). |
A ggplot2 object.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) ls_plot_spectrum(spec) # Element overlays require a configured reference; see ls_element_db().spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) ls_plot_spectrum(spec) # Element overlays require a configured reference; see ls_element_db().
Partial Least Squares Discriminant Analysis for class prediction.
ls_plsda(dataset, grouping, n_components = 5, validation = "CV")ls_plsda(dataset, grouping, n_components = 5, validation = "CV")
dataset |
A |
grouping |
Character. Column name in |
n_components |
Integer. Number of PLS latent variables. Default 5. |
validation |
Character. |
An S3 object of class libs_plsda with elements model,
predictions (tibble with predicted/observed class), confusion_matrix,
accuracy, class_labels, n_components, sample_info,
feature_contract, and evaluation_basis ("cross_validation",
"leave_one_out", or "training").
ds <- ls_example_data("tissue") if (requireNamespace("pls", quietly = TRUE)) { plsda <- ls_plsda(ds, "tissue", n_components = 3, validation = "none") plsda$accuracy }ds <- ls_example_data("tissue") if (requireNamespace("pls", quietly = TRUE)) { plsda <- ls_plsda(ds, "tissue", n_components = 3, validation = "none") plsda$accuracy }
Applies a calibration model using its saved wavelength axis, preprocessing and
extraction contract. Legacy models without this contract must be refitted.
Unavailable detection-limit flags are NA, not FALSE.
ls_quantify(calibration, x, window_nm = NULL)ls_quantify(calibration, x, window_nm = NULL)
calibration |
A |
x |
A |
window_nm |
Optional numeric integration window. |
A tibble::tibble() with columns sample_id, element,
concentration, unit, below_lod, below_loq.
ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_quantify(cal, ds)ds <- ls_example_data("calibration") conc <- ds$sample_info$concentration cal <- ls_calibrate(ds, "Ca", 393.37, conc, verbose = FALSE) ls_quantify(cal, ds)
Parses output from Applied Spectra J200 and Aurora LIBS systems. Applied Spectra files commonly have wavelength in the first column and shots in subsequent columns, optionally with a few header lines.
ls_read_aurora(path, verbose = TRUE)ls_read_aurora(path, verbose = TRUE)
path |
Character. Path to export file (.csv or .asc). |
verbose |
Logical. Default |
A libs_spectrum object.
tmp <- tempfile(fileext = ".csv") writeLines(c( "Applied Spectra J200", "Model,J200", "wl,shot1,shot2", "200.0,50,52", "200.5,55,58", "201.0,52,50" ), tmp) spec <- ls_read_aurora(tmp, verbose = FALSE) unlink(tmp)tmp <- tempfile(fileext = ".csv") writeLines(c( "Applied Spectra J200", "Model,J200", "wl,shot1,shot2", "200.0,50,52", "200.5,55,58", "201.0,52,50" ), tmp) spec <- ls_read_aurora(tmp, verbose = FALSE) unlink(tmp)
Attempts to identify the file format (generic CSV, SciAps, Applied Spectra)
and dispatches to the correct reader. When path is a directory, delegates
to ls_read_dir().
ls_read_auto(path, verbose = TRUE)ls_read_auto(path, verbose = TRUE)
path |
Character. Path to spectrum file or directory. |
verbose |
Logical. Default |
A libs_spectrum or libs_dataset object.
tmp <- tempfile(fileext = ".csv") utils::write.csv(data.frame(wavelength = seq(200, 300, 1), intensity = 1:101), tmp, row.names = FALSE) spec <- ls_read_auto(tmp, verbose = FALSE) unlink(tmp)tmp <- tempfile(fileext = ".csv") utils::write.csv(data.frame(wavelength = seq(200, 300, 1), intensity = 1:101), tmp, row.names = FALSE) spec <- ls_read_auto(tmp, verbose = FALSE) unlink(tmp)
Read a LIBS Spectrum from CSV (Convenience Wrapper)
ls_read_csv(path, ...)ls_read_csv(path, ...)
path |
Character. Path to CSV file. |
... |
Additional arguments passed to |
A libs_spectrum object.
Batch-imports spectrum files from a directory into a libs_dataset.
ls_read_dir( dir, pattern = "\\.(csv|tsv|txt)$", recursive = FALSE, sample_info = NULL, ... )ls_read_dir( dir, pattern = "\\.(csv|tsv|txt)$", recursive = FALSE, sample_info = NULL, ... )
dir |
Character. Directory path. |
pattern |
Character. File pattern (regex). Default |
recursive |
Logical. Recurse into subdirectories. Default |
sample_info |
data.frame/tibble. Optional sample metadata table.
Must have a |
... |
Additional arguments passed to |
A libs_dataset object.
dir <- tempfile() dir.create(dir) for (i in 1:3) { wl <- seq(200, 900, length.out = 100) int <- exp(-((wl - 393)^2) / 2) + stats::rnorm(100, 0, 0.01) utils::write.csv(data.frame(w = wl, i = int), file.path(dir, paste0("s", i, ".csv")), row.names = FALSE) } ds <- ls_read_dir(dir, verbose = FALSE) unlink(dir, recursive = TRUE)dir <- tempfile() dir.create(dir) for (i in 1:3) { wl <- seq(200, 900, length.out = 100) int <- exp(-((wl - 393)^2) / 2) + stats::rnorm(100, 0, 0.01) utils::write.csv(data.frame(w = wl, i = int), file.path(dir, paste0("s", i, ".csv")), row.names = FALSE) } ds <- ls_read_dir(dir, verbose = FALSE) unlink(dir, recursive = TRUE)
Parses output files from SciAps handheld LIBS analyzers (Z-series).
The SciAps export format typically includes metadata lines preceded by
# or a keyword header, followed by a wavelength/intensity table.
ls_read_sciaps(path, verbose = TRUE)ls_read_sciaps(path, verbose = TRUE)
path |
Character. Path to SciAps export file. |
verbose |
Logical. Emit messages. Default |
A libs_spectrum object with SciAps-specific metadata.
# See vignette("getting-started") for realistic usage; this parser # is best exercised against actual SciAps export files. tmp <- tempfile(fileext = ".csv") writeLines(c( "# SciAps Z-903", "# Serial: 12345", "# Gate Delay (us): 2.5", "wavelength,intensity", "200.0,50", "200.5,55", "201.0,52" ), tmp) spec <- ls_read_sciaps(tmp, verbose = FALSE) unlink(tmp)# See vignette("getting-started") for realistic usage; this parser # is best exercised against actual SciAps export files. tmp <- tempfile(fileext = ".csv") writeLines(c( "# SciAps Z-903", "# Serial: 12345", "# Gate Delay (us): 2.5", "wavelength,intensity", "200.0,50", "200.5,55", "201.0,52" ), tmp) spec <- ls_read_sciaps(tmp, verbose = FALSE) unlink(tmp)
Reads a single spectrum file. Supports CSV, TSV, and TXT formats where columns represent wavelength and intensity.
ls_read_spectrum( path, format = "auto", wavelength_col = 1, intensity_col = 2, skip = 0, metadata = list(), verbose = TRUE )ls_read_spectrum( path, format = "auto", wavelength_col = 1, intensity_col = 2, skip = 0, metadata = list(), verbose = TRUE )
path |
Character. Path to spectrum file. |
format |
Character. One of |
wavelength_col |
Column index or name for wavelength values. Default 1. |
intensity_col |
Column index/indices or name(s) for intensity values. Multiple columns are interpreted as multiple shots. Default 2. |
skip |
Integer. Header lines to skip before the data table. Default 0. |
metadata |
Named list of additional metadata. Default |
verbose |
Logical. Emit import messages. Default |
A libs_spectrum object.
tmp <- tempfile(fileext = ".csv") wl <- seq(200, 900, length.out = 100) int <- exp(-((wl - 393)^2) / 2) utils::write.csv(data.frame(wavelength = wl, intensity = int), tmp, row.names = FALSE) spec <- ls_read_spectrum(tmp, verbose = FALSE) unlink(tmp)tmp <- tempfile(fileext = ".csv") wl <- seq(200, 900, length.out = 100) int <- exp(-((wl - 393)^2) / 2) utils::write.csv(data.frame(wavelength = wl, intensity = int), tmp, row.names = FALSE) spec <- ls_read_spectrum(tmp, verbose = FALSE) unlink(tmp)
Starts an interactive Shiny application for exploring, preprocessing, and analyzing LIBS spectral data. The app provides six tabs: Import, Preprocessing, Peaks, Calibration, Chemometrics, and Export.
ls_run_app(data = NULL, port = NULL, launch.browser = TRUE)ls_run_app(data = NULL, port = NULL, launch.browser = TRUE)
data |
Optional. A |
port |
Integer. Port for the app. Default |
launch.browser |
Logical. Open browser on launch. Default |
Upload batches are admitted together: invalid files leave the previously loaded data intact. Original upload names identify their source. New data and successful preprocessing invalidate downstream analysis results. Preprocessing controls take effect only after Apply; a failed operation retains the last successful data, and Reset restores raw data.
The complete ZIP download contains one CSV per spectrum and, for a dataset,
sample_info.csv. Spectrum CSV files retain all shots, baseline and
supported metadata through ls_write_csv(). ZIP creation requires an
external zip command on PATH (or configured through R_ZIPCMD),
including on Windows. The separate wide dataset CSV
contains mean intensities only. Calibration CSV files summarize figures of
merit rather than storing reusable prediction models. Load a labelled
ls_dataset() through data for analyses requiring concentration or class
columns in sample_info.
Example datasets use explicitly fictional teaching peaks and concentrations,
not an atomic reference or experimental measurements. Peak detection and
raw plots work without a reference. Optional element annotations require
a user-supplied file configured for ls_element_db(); missing or invalid
references leave raw detections available and report the annotation error.
Peak and calibration CSVs carry data_origin = "explicit_synthetic_peaks"
for wholly fictional inputs; mixed calibration inputs carry
"includes_explicit_synthetic_peaks". Peak exports follow the first
spectrum actually used for detection.
The previous application data option is restored when the app stops or startup fails. Each browser session keeps its own working data and results.
Invisible NULL. Launches a Shiny application as a side effect.
if (interactive()) { ls_run_app() }if (interactive()) { ls_run_app() }
Estimates a common Boltzmann temperature and relative elemental number fractions using explicit atomic and instrumental inputs. The Saha equation accounts for the neutral/singly-ionized balance. This research calculation requires optically thin emission, local thermodynamic equilibrium (LTE), a common sampled plasma, stoichiometric ablation and corrected spectral response. It does not establish those assumptions from an observed spectrum.
ls_saha_boltzmann( x, elements, lines_nm, electron_density = NULL, window_nm = 0.5, verbose = TRUE, atomic_data = NULL, partition_functions = NULL, ionization_energies_ev = NULL, temperature_k = NULL, intensity_scale = c("energy", "photon"), wavelength_medium = NULL, tolerance_nm = 0.01 )ls_saha_boltzmann( x, elements, lines_nm, electron_density = NULL, window_nm = 0.5, verbose = TRUE, atomic_data = NULL, partition_functions = NULL, ionization_energies_ev = NULL, temperature_k = NULL, intensity_scale = c("energy", "photon"), wavelength_medium = NULL, tolerance_nm = 0.01 )
x |
A |
elements |
Unique character vector of elements to include. |
lines_nm |
Named list of measured line wavelengths per element. |
electron_density |
Independently estimated electron density in cm^-3. Required; no density is assumed. |
window_nm |
Integration width in nm. Default 0.5. Effective integration
windows, including the coarse-channel expansion of |
verbose |
Logical. Report the temperature and scope of the result. |
atomic_data |
A data.frame with one unambiguous record per selected
transition: |
partition_functions |
Named list, one entry per element. Each entry is
a list with |
ionization_energies_ev |
Named positive numeric vector of first ionization energies in eV, one per element. |
temperature_k |
Optional independently estimated common temperature in kelvin. If NULL, estimate it from a shared slope with a separate intercept per element/ion stage. Estimation requires a full-rank fit and positive residual degrees of freedom. Non-negative slopes are rejected. |
intensity_scale |
|
wavelength_medium |
Medium of the measured axis. If NULL, read
|
tolerance_nm |
Maximum difference between requested and reference wavelengths. Default 0.01. Multiple possible transitions are an error. |
Earlier versions silently used unit statistical weights, omitted partition functions and ignored electron density. Those outputs cannot be reused as quantitative reference results. Supply verified physical inputs and refit. A low residual does not verify LTE, optical thinness, absence of self-absorption, spectral resolution, detector response or matrix-independent ablation.
A tibble with element, temperature_k, concentration_rel,
electron_density, n_lines, r_squared and log_population_sd.
Fractions are normalized only over the supplied elements, under a model
that excludes molecules and charge states above +1; they are neither mass
fractions nor absolute sample concentrations. log_population_sd measures
line/stage disagreement on the log population scale, not calibrated
uncertainty. Attributes line_diagnostics, assumptions, and
temperature_source retain the calculation's inputs and limitations.
NIST Atomic Spectra Database, spectral lines and Saha/LTE documentation: https://physics.nist.gov/PhysRefData/ASD/Html/lineshelp.html.
# A complete, explicitly synthetic forward-model example: system.file("examples", "saha-boltzmann-synthetic.R", package = "libscanR")# A complete, explicitly synthetic forward-model example: system.file("examples", "saha-boltzmann-synthetic.R", package = "libscanR")
Generates a demonstration LIBS spectrum with configurable elemental
composition, noise, and continuum background. Emission lines are drawn
from the user-configured atomic reference (ls_element_db()) and modelled as
Gaussian peaks. Peak widths are at least 2.5 channel spacings so coarse
demonstrations remain visible; this is not an instrument response model
or validation of quantitative elemental concentrations or tissue identity.
ls_simulate_spectrum( elements = c(Ca = 5000, Fe = 200, Na = 1000), wavelength_range = c(200, 900), n_channels = 2048, n_shots = 10, noise_level = 0.02, continuum_level = 100, shot_rsd = 0.1, fwhm_nm = 0.1, seed = NULL, line_data = NULL )ls_simulate_spectrum( elements = c(Ca = 5000, Fe = 200, Na = 1000), wavelength_range = c(200, 900), n_channels = 2048, n_shots = 10, noise_level = 0.02, continuum_level = 100, shot_rsd = 0.1, fwhm_nm = 0.1, seed = NULL, line_data = NULL )
elements |
Named numeric vector. Element concentrations (arbitrary
units, interpreted as relative intensity scaling). Default
|
wavelength_range |
Numeric vector of length 2. Range in nm.
Default |
n_channels |
Integer. Number of spectral channels. Default 2048. |
n_shots |
Integer. Number of replicate shots. Default 10. |
noise_level |
Numeric. Relative noise level (fraction of max intensity). Default 0.02. |
continuum_level |
Numeric. Continuum background level. Default 100. |
shot_rsd |
Numeric. Relative standard deviation of shot-to-shot intensity variation (0-1). Default 0.1. |
fwhm_nm |
Numeric. Typical line FWHM in nm. Default 0.1. |
seed |
Optional integer random seed for reproducibility. |
line_data |
Optional explicit teaching peak table, with |
A ls_spectrum() object.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 1000, Na = 500), seed = 1) print(spec)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), elements = c(Ca = 1000, Na = 500), seed = 1) print(spec)
Applies spectral smoothing. Methods: "savgol" (Savitzky-Golay, needs
the signal package when available, otherwise uses local polynomial least
squares with an intercept), "moving_avg", "gaussian", "median".
ls_smooth(x, method = "savgol", window = 11, poly_order = 3)ls_smooth(x, method = "savgol", window = 11, poly_order = 3)
x |
A |
method |
Character. Default |
window |
Integer. Window size in channels (odd preferred). Default 11. |
poly_order |
Integer. Polynomial order for Savitzky-Golay. Default 3. |
Same class as input with smoothed intensities.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) sm <- ls_smooth(spec, method = "moving_avg", window = 9)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) sm <- ls_smooth(spec, method = "moving_avg", window = 9)
Constructs a libs_spectrum S3 object from a wavelength axis and one or
more intensity vectors (shots).
ls_spectrum(wavelength, intensity, metadata = list(), baseline = NULL)ls_spectrum(wavelength, intensity, metadata = list(), baseline = NULL)
wavelength |
Numeric vector of wavelengths in nanometers. Must be contain at least two distinct, finite, positive values. Channels and the optional baseline are sorted together in ascending wavelength order. |
intensity |
Numeric vector (single shot) or matrix (multiple shots)
of emission intensities. If matrix: rows = shots, columns = wavelength
channels, |
metadata |
Named list of metadata (e.g. |
baseline |
Optional numeric vector of baseline values corresponding
to each wavelength channel (populated by |
An object of class libs_spectrum: a named list with elements
wavelength, intensity (matrix: shots x channels), metadata,
baseline, n_shots, n_channels, and range_nm.
wl <- seq(200, 900, length.out = 512) int <- exp(-((wl - 393)^2) / 2) + stats::rnorm(512, 0, 0.05) spec <- ls_spectrum(wl, int, metadata = list(sample_id = "demo")) print(spec)wl <- seq(200, 900, length.out = 512) int <- exp(-((wl - 393)^2) / 2) + stats::rnorm(512, 0, 0.05) spec <- ls_spectrum(wl, int, metadata = list(sample_id = "demo")) print(spec)
Classifies tissue types based on LIBS spectral signatures. Implements three methods:
"ratio" — an unvalidated heuristic based on integrated Ca, Na, K, Fe
and C line responses. It is a research illustration, not a calibrated tissue
probability or clinical classifier. All required lines must be covered and
the response denominators must be positive; otherwise the row is unclassified.
"plsda" — fits a PLS-DA model on the supplied labelled reference
dataset and predicts class for x.
"svm" — fits an SVM on reference and predicts class.
ls_tissue_classify( x, method = "ratio", reference = NULL, group_col = "tissue", verbose = TRUE )ls_tissue_classify( x, method = "ratio", reference = NULL, group_col = "tissue", verbose = TRUE )
x |
A |
method |
Character. |
reference |
A |
group_col |
Character. Column in reference |
verbose |
Logical. Default |
A tibble::tibble() with columns sample_id, predicted_tissue,
score, score_type, and status. The former confidence column is
replaced to distinguish relative heuristic scores, unrestricted PLS-DA
scores and SVM probability estimates. None establishes tissue validity.
ds <- ls_example_data("tissue") ls_tissue_classify(ds[1:3])ds <- ls_example_data("tissue") ls_tissue_classify(ds[1:3])
Identifies emission channels that best discriminate two tissue types via
per-wavelength t-tests with Benjamini-Hochberg FDR correction, plus log2
fold-change. Element annotations are nearest wavelength candidates, not
established elemental identities; candidate_count records ambiguity.
Without a configured atomic reference, statistical results remain available,
with missing element annotations and annotation_status = "reference_unavailable".
A configured but unreadable or invalid reference raises an error.
ls_tissue_discriminate( dataset, group_col, group_a, group_b, method = "t_test", tolerance_nm = 0.2 )ls_tissue_discriminate( dataset, group_col, group_a, group_b, method = "t_test", tolerance_nm = 0.2 )
dataset |
A |
group_col |
Character. Label column in |
group_a |
Character. First group label. |
group_b |
Character. Second group label. |
method |
Character. |
tolerance_nm |
Numeric. Matching tolerance when annotating elements. Default 0.2. |
A tibble::tibble() with columns wavelength_nm, mean_a,
mean_b, p_value, fold_change, fdr, significant, element.
ds <- ls_example_data("tissue") head(ls_tissue_discriminate(ds, "tissue", "bone", "muscle"))ds <- ls_example_data("tissue") head(ls_tissue_discriminate(ds, "tissue", "bone", "muscle"))
Trains SVM or Random Forest on spectral intensity features.
ls_train_classifier(dataset, grouping, method = "svm", ...)ls_train_classifier(dataset, grouping, method = "svm", ...)
dataset |
A |
grouping |
Character. Column name in |
method |
Character. |
... |
Additional arguments passed to the underlying trainer. |
An S3 object of class libs_classifier, including predictions,
a square confusion matrix, the fitted feature_contract, and
evaluation_basis: "training" for SVM or "out_of_bag" for RF.
SVM evaluation uses the same probability-based class decision as
ls_classify(). Training accuracy is not an independent estimate of
generalization.
ds <- ls_example_data("tissue") if (requireNamespace("e1071", quietly = TRUE)) { clf <- ls_train_classifier(ds, "tissue", method = "svm") clf$accuracy }ds <- ls_example_data("tissue") if (requireNamespace("e1071", quietly = TRUE)) { clf <- ls_train_classifier(ds, "tissue", method = "svm") clf$accuracy }
Exports a libs_spectrum to a CSV file with a wavelength_nm column plus
one column per shot.
ls_write_csv(x, path, include_metadata = TRUE)ls_write_csv(x, path, include_metadata = TRUE)
x |
A |
path |
Character. Output file path. |
include_metadata |
Logical. Prepend metadata as comment lines.
Default |
Invisibly returns path.
spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) tmp <- tempfile(fileext = ".csv") ls_write_csv(spec, tmp) unlink(tmp)spec <- ls_simulate_spectrum(line_data = ls_demo_peaks(), seed = 1) tmp <- tempfile(fileext = ".csv") ls_write_csv(spec, tmp) unlink(tmp)
Plot a LIBS Dataset
## S3 method for class 'libs_dataset' plot(x, y, ...)## S3 method for class 'libs_dataset' plot(x, y, ...)
x |
A |
y |
Ignored. |
... |
Passed to |
A ggplot object.
Plot a LIBS Spectrum
## S3 method for class 'libs_spectrum' plot(x, y, ...)## S3 method for class 'libs_spectrum' plot(x, y, ...)
x |
A |
y |
Ignored. |
... |
Arguments passed to |
A ggplot object.
Predict Concentrations from a Calibration Model
## S3 method for class 'libs_calibration' predict(object, newdata, ...)## S3 method for class 'libs_calibration' predict(object, newdata, ...)
object |
A |
newdata |
A finite numeric vector of already integrated responses (ratios
for internal-standard calibration), or a matrix with the fitted PLS columns
in their trained order. This low-level method cannot verify wavelength labels;
use |
... |
Unused. |
Numeric vector of predicted concentrations.
Print a LIBS Calibration
## S3 method for class 'libs_calibration' print(x, ...)## S3 method for class 'libs_calibration' print(x, ...)
x |
A |
... |
Unused. |
Invisibly x.
Print a LIBS Dataset
## S3 method for class 'libs_dataset' print(x, ...)## S3 method for class 'libs_dataset' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Print a LIBS Spectrum
## S3 method for class 'libs_spectrum' print(x, ...)## S3 method for class 'libs_spectrum' print(x, ...)
x |
A |
... |
Unused. |
Invisibly returns x.
Maps wavelength values (nm) to approximate visible-light colors for intuitive spectral visualization. Below 380 nm: UV purple; above 780 nm: deep red.
scale_color_wavelength(name = "Wavelength (nm)", ...)scale_color_wavelength(name = "Wavelength (nm)", ...)
name |
Character. Legend title. Default |
... |
Additional arguments passed to
|
A ggplot2 scale object.
df <- data.frame(x = 1:5, y = 1:5, wl = c(200, 400, 550, 700, 850)) ggplot2::ggplot(df, ggplot2::aes(x, y, colour = wl)) + ggplot2::geom_point(size = 5) + scale_color_wavelength()df <- data.frame(x = 1:5, y = 1:5, wl = c(200, 400, 550, 700, 850)) ggplot2::ggplot(df, ggplot2::aes(x, y, colour = wl)) + ggplot2::geom_point(size = 5) + scale_color_wavelength()
Summary of a LIBS Calibration
## S3 method for class 'libs_calibration' summary(object, ...)## S3 method for class 'libs_calibration' summary(object, ...)
object |
A |
... |
Unused. |
Invisibly a list of key figures of merit.
Summary of a LIBS Dataset
## S3 method for class 'libs_dataset' summary(object, ...)## S3 method for class 'libs_dataset' summary(object, ...)
object |
A |
... |
Unused. |
Invisibly returns a list with per-group statistics.
Summary of a LIBS Spectrum
## S3 method for class 'libs_spectrum' summary(object, n_peaks = 5, ...)## S3 method for class 'libs_spectrum' summary(object, n_peaks = 5, ...)
object |
A |
n_peaks |
Integer. Number of top peaks to show. Default 5. |
... |
Unused. |
Invisibly returns a list with summary statistics.
A clean publication-ready theme for LIBS spectral plots.
theme_libs(base_size = 12)theme_libs(base_size = 12)
base_size |
Numeric. Base font size in points. Default 12. |
A ggplot2 theme object.
ggplot2::ggplot(mtcars, ggplot2::aes(mpg, wt)) + ggplot2::geom_point() + theme_libs()ggplot2::ggplot(mtcars, ggplot2::aes(mpg, wt)) + ggplot2::geom_point() + theme_libs()