Fitting emission lines

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4,
  out.width = "100%",
  dpi = 96
)

A typical LIBS analysis goes through four stages, each covered by a vignette:

  1. Fitting emission lines (this vignette): identify the lines, correct the wavelength axis and measure line areas.
  2. Preprocessing with recipe steps: vignette("preprocessing").
  3. Calibration and figures of merit: vignette("calibration").
  4. Plasma diagnostics: vignette("plasma-diagnostics").

All four use forageLIBS: 368 spectra of dried forage samples, with laboratory concentrations of 12 elements.

if (!requireNamespace("purrr", quietly = TRUE)) {
  knitr::knit_exit("This vignette needs the purrr package, which is not installed.")
}
library(specProc)
library(dplyr)
library(purrr)
library(ggplot2)

data("forageLIBS")
spectra_id <- forageLIBS |> select(1:2) |> names()
minerals <- forageLIBS |> select(3:14) |> names()
spectra <- forageLIBS |> select(-all_of(c(spectra_id, minerals)))
wl <- as.numeric(names(spectra))

Each row of spectra is one spectrum, the mean of 8 laser shots, and the column names are the wavelengths (nm):

forageLIBS |>
  slice(1:3) |>
  select(-Sample, -all_of(minerals)) |>
  plot_spectra(id = Measurement, wavelength = c(400, 460), offset = 10000) +
  scale_x_continuous(breaks = seq(400, 460, 5))

Identifying the lines

libs_lines() lists the strongest lines of given species in a wavelength range, from the NIST Atomic Spectra Database, and plot_lines() marks them on a spectrum. line_finder() opens an interactive app that does both. In the app, the lines of a species picked on the spectrum also build a Boltzmann plot, from which outlying lines can be left out, and Done returns its fit to R (see vignette("plasma-diagnostics")). These functions need an internet connection:

candidates <- libs_lines(c("K I", "Ca I", "Fe I", "Mn I"), wavelength = c(400, 410))
plot_lines(colMeans(spectra), candidates)
fit <- line_finder(spectra)

Molecules formed in the plasma emit bands. molecular_bands() lists the heads of the bands of diatomic molecules common in LIBS (CN, C2, CH, OH, N2, AlO, CaF, TiO, ...), computed from spectroscopic constants without a download. The organic matrix of the forage samples, ablated in air, emits the violet system of CN, whose bands are degraded to the violet: each rises sharply at its head and fades toward shorter wavelengths. Its strongest sequence, the bands with $v' = v''$, has heads from 388.3 to 385.0 nm:

cn <- molecular_bands("CN", wavelength = c(383, 390))
cn |>
  select(v_upper, v_lower, wavelength, degraded, fcf, relative_intensity) |>
  mutate(across(where(is.double), \(x) round(x, 3))) |>
  as.data.frame()
plot_lines(colMeans(spectra), bands = cn, wavelength = c(383, 390), interactive = FALSE)

The measured heads lie about 0.07 nm short of the markers: the wavelength axis needs a correction (next section). molecular_spectrum() simulates the full rotational structure of the bands from a line list of the ExoMol database, downloaded on demand:

cn_model <- molecular_spectrum("CN", temperature = 6000, wavelength = c(383, 390),
                               resolution = 0.1)

Correcting the wavelength axis

The measured lines are shifted from their tabulated wavelengths. wavelength_calibration() locates known lines in the mean spectrum and fits a correction of the axis. The instrument joins several detectors (the wavelengths step back at 766 nm), and each detector has its own calibration: we correct the first one, from 199 to 766 nm, which holds the lines used below.

first_detector <- spectra[seq_len(which(diff(wl) < 0)[1])]

reference <- c(`C I` = 247.856, `Mg I` = 285.213, `Ca II` = 317.933, `Ca II` = 370.603,
               `Ca II` = 373.690, `K I` = 404.414, `Ca I` = 430.253, `Ca I` = 445.478,
               `Mg I` = 516.732, `Mg I` = 517.268, `Mg I` = 518.360, `Na I` = 588.995,
               `Na I` = 589.592, `Ca I` = 616.217, `Ca I` = 643.907)
wavecal <- wavelength_calibration(first_detector, reference)
wavecal$segments
plot_wavelength_calibration(wavecal)

The offset grows from 0.05 nm in the UV to 0.12 nm in the red, about one channel, and the residuals of the linear correction are close to 0.01 nm. apply_calibration() relabels the columns with the corrected wavelengths. We also remove the continuum with baseline_arpls(), and average the spectra for a clean example:

calibrated <- apply_calibration(first_detector, wavecal)
corrected <- baseline_arpls(calibrated, lambda = 1e5, max_iter = 20)$correction
wl_corrected <- as.numeric(names(corrected))
mean_spectrum <- colMeans(corrected)

# The channels between two wavelengths, as a one-row table
window <- function(from, to, x = mean_spectrum) {
  keep <- wl_corrected > from & wl_corrected < to
  if (is.null(dim(x))) as_tibble(as.list(x[keep])) else x[keep]
}

Line profiles

An emission line of a laser-induced plasma is broadened by several mechanisms: the instrument and the Doppler effect give a Gaussian profile, the Stark effect a Lorentzian one, and both together a Voigt profile. specProc provides the four profiles, parametrized by their full widths at half maximum:

| Function | Profile | Widths | |---|---|---| | gaussian_profile() | Gaussian | wG | | lorentzian_profile() | Lorentzian | wL | | voigt_profile() | exact Voigt (Faddeeva function, C++) | wG, wL | | pseudo_voigt_profile() | Thompson–Cox–Hastings pseudo-Voigt | wG, wL |

Fitting a single line

peak_fit() fits (y = y_0 + A \cdot f(x; x_c, w)) to each spectrum (one per row, wavelengths as column names) by nonlinear least squares, with starting values estimated from the data. The hydrogen H(\alpha) line at 656.28 nm comes from the water of the samples. Its width is dominated by the Stark effect, and the choice of profile matters:

halpha <- window(653.5, 659.5)
fits <- c("gaussian", "lorentzian", "pseudo_voigt", "voigt") |>
  set_names() |>
  map(\(p) peak_fit(halpha, profile = p))

tibble(
  profile = names(fits),
  AIC = map_dbl(fits, \(f) AIC(f$fit[[1]])),
  area = map_dbl(fits, \(f) coef(f$fit[[1]])[["A"]])
) |>
  mutate(across(c(AIC, area), round))

The Gaussian misses the wings of the line: its AIC is 80 units higher, and its area 40% smaller. The Lorentzian, pseudo-Voigt and Voigt profiles fit equally well. tidied holds the parameters, with their standard errors:

fits$voigt$tidied[[1]]

The Gaussian width of the Voigt fit is close to zero, with a standard error far larger than its value: the line is purely Lorentzian, and the Voigt profile has one parameter too many. plot_fit() shows the Lorentzian fit and its residuals:

plot_fit(fits$lorentzian, title = "H-alpha 656.28 nm, Lorentzian profile")

The width of H(\alpha) gives the electron density of the plasma (see vignette("plasma-diagnostics")); for a Voigt fit, voigt_fwhm() combines the two widths into the total width.

Overlapping lines

The potassium doublet at 404.41 and 404.72 nm is weak and its lines overlap. multipeak_fit() fits them together, on a common baseline; the parameters of line (i) carry the suffix _i:

doublet <- window(404.1, 405.0)
k_voigt <- multipeak_fit(doublet, peaks = c(404.414, 404.721), profiles = "voigt")
k_voigt$tidied[[1]]

With about ten channels for 9 parameters, the Gaussian and Lorentzian widths of each line cannot be separated: their standard errors are larger than the estimates, and the areas are poorly determined. A Gaussian profile, with one width per line, is enough for lines only a few channels wide:

k_gauss <- multipeak_fit(doublet, peaks = c(404.414, 404.721), profiles = "gaussian")
k_gauss$tidied[[1]]
c(voigt = AIC(k_voigt$fit[[1]]), gaussian = AIC(k_gauss$fit[[1]]))
plot_fit(k_gauss, title = "K I 404.41 and 404.72 nm, Gaussian profiles")

The areas are now determined, and the AIC is lower: prefer the simplest profile that describes the data.

The two lines come from the fine-structure levels of the same 5p configuration of K I: their separation is known (0.307 nm, from the NIST database), and their instrumental and Stark widths are nearly the same. lock_centers = TRUE keeps the separation of peaks, with one shift of both lines, and share_widths = TRUE gives them one width:

k_locked <- multipeak_fit(doublet, peaks = c(404.414, 404.721), profiles = "gaussian",
                          lock_centers = TRUE, share_widths = TRUE)
k_locked$tidied[[1]]
term_of <- \(fit, term, column = "estimate") {
  t <- fit$tidied[[1]]
  t[[column]][t$term == term]
}
free_separation <- term_of(k_gauss, "xc_2") - term_of(k_gauss, "xc_1")
locked_ratio <- term_of(k_locked, "A_1") / term_of(k_locked, "A_2")
thin_ratio <- (4 * 1.15e6 / 404.414) / (2 * 1.07e6 / 404.721)

The free fit placed the lines r round(free_separation, 3) nm apart, with widths of r round(term_of(k_gauss, "wG_1"), 3) and r round(term_of(k_gauss, "wG_2"), 3) nm; with two parameters fewer, the standard error of the area of the weaker line drops from r round(term_of(k_gauss, "A_2", "std.error")) to r round(term_of(k_locked, "A_2", "std.error")). The common shift, r round(term_of(k_locked, "shift"), 3) ± r round(term_of(k_locked, "shift", "std.error"), 3) nm, is zero within its standard error, since the wavelength axis was corrected above; on raw spectra, it absorbs the offset of the axis.

area_ratios would also fix the ratio of the areas. In an optically thin plasma, the ratio of these lines is that of their (g_k A_{ki} / \lambda), r round(thin_ratio, 2) (their upper levels are 2 meV apart). The fitted ratio is r round(locked_ratio, 2): the 404.41 nm line, which ends on the ground state, is self-absorbed (see vignette("plasma-diagnostics")), so fixing the ratio would bias the areas. Fix ratios only for optically thin lines.

Instrumental and Doppler widths

The Gaussian width of a line is the instrumental width combined with the Doppler width, (w_G = \sqrt{w_{inst}^2 + w_D^2}). The instrumental width is the width of a line of a low-pressure lamp (mercury, argon), whose Stark and Doppler widths are negligible, fitted with a Gaussian profile; doppler_width() gives the Doppler width from the temperature and the mass of the emitter. With the Gaussian width known, fixed = "wG" holds it in the fit, and only the Lorentzian (Stark) width is fitted. The instrumental width of the forage spectrometers is not known, so here is a simulated Al I line, with an instrumental width of 0.08 nm and a Stark width of 0.04 nm:

x <- seq(395.5, 396.5, by = 0.02)
set.seed(1)
y <- voigt_profile(x, y0 = 50, xc = 396.15, wG = 0.08, wL = 0.04, A = 100) +
  rnorm(length(x), sd = 5)
al_line <- as_tibble(as.list(set_names(y, x)))
w_gauss <- sqrt(0.08^2 + doppler_width(396.15, temperature = 9000, mass = "Al")^2)
w_gauss

free <- peak_fit(al_line, profile = "voigt")$tidied[[1]]
fixed <- peak_fit(al_line, profile = "voigt", wG = w_gauss, fixed = "wG")$tidied[[1]]
bind_rows(free = free, fixed = fixed, .id = "fit") |>
  filter(term %in% c("wG", "wL")) |>
  select(fit, term, estimate, std.error)

The Doppler width of Al at 9000 K is only r round(doppler_width(396.15, 9000, "Al"), 4) nm, so the Gaussian width is the instrumental width. With both widths free, they trade off against each other: the standard error of the Lorentzian width is r round(free$std.error[free$term == "wL"] / fixed$std.error[fixed$term == "wL"], 1) times larger than with the Gaussian width fixed. The fixed width is listed without standard error.

Fitting every spectrum

With an id column, peak_fit() and multipeak_fit() fit each row, so the same line is measured in every spectrum. A fit that fails (here on a few spectra where the doublet is lost in the noise) gives NULL with a warning, and the others continue:

doublets <- bind_cols(
  select(forageLIBS, Measurement),
  window(404.1, 405.0, x = corrected)
)
k_fits <- multipeak_fit(doublets, peaks = c(404.414, 404.721), profiles = "gaussian",
                        id = "Measurement")

k_areas <- k_fits |>
  mutate(area = map_dbl(tidied, \(t) if (is.null(t)) NA else t$estimate[t$term == "A_1"])) |>
  select(Measurement, area) |>
  left_join(select(forageLIBS, Measurement, K), by = "Measurement")
sum(is.na(k_areas$area))
ggplot(k_areas, aes(K, area)) +
  geom_point(alpha = 0.5) +
  labs(x = "K (%)", y = "Area of K I 404.41 nm") +
  theme_bw()

The area follows the potassium content, with much scatter: the intensity of a line also depends on the ablated mass and the plasma, which the next vignettes correct by normalization and calibration.

Integrating instead of fitting

line_intensities() measures many lines at once: it finds the peak of each line near its tabulated wavelength (search) and integrates it over a window (half_width), or fits a Voigt profile with method = "voigt". It needs no starting values and is fast, but it does not separate overlapping lines:

lines <- c(`K I 404.41` = 404.414, `Mg I 518.36` = 518.360, `Fe II 259.94` = 259.940)
line_intensities(corrected[1:2, ], lines, half_width = 0.1)

The recipe step step_line_intensities() does the same within a preprocessing pipeline (vignette("preprocessing")).

Summary



Try the specProc package in your browser

Any scripts or data that you put into this service are public.

specProc documentation built on Nov. 20, 2026, 5:11 p.m.