Working range and linearity¶
Question: is the calibration a straight line over the working range, and is an ordinary least-squares fit the right way to use it?
Two separate things can go wrong with a calibration line:
- Shape: the response is not linear (it curves at the top, for example).
- Weighting: the line is straight, but the scatter grows with concentration, so an ordinary fit lets the top standards decide where the line goes at the bottom.
The correlation coefficient detects neither. This notebook checks both, on the calibration used in the LOD/LOQ notebook.
Data and assumptions. All data are synthetic, made by
scripts/make_data.py: Cu standards at 0, 10, 25, 50, 100 and 200 µg/L, three independent preparations of each, measured by ICP-OES as intensity in counts per second (cps). The true response is linear; the noise is a constant floor plus 1 % of the signal. No real laboratory data are used.
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
from labqc.validation import linearity
DATA = Path("..") / "data" / "synthetic"
if not DATA.exists(): # run from the repository root
DATA = Path("data") / "synthetic"
cal = pd.read_csv(DATA / "calibration.csv")
x = cal["cu_ug_L"].to_numpy()
y = cal["intensity_cps"].to_numpy()
# One quiet chart style for the handbook. Two series: blue, then orange.
BLUE, ORANGE, GREY, INK = "#2a78d6", "#eb6834", "#8a8984", "#52514e"
plt.rcParams.update({
"figure.facecolor": "#fcfcfb",
"axes.facecolor": "#fcfcfb",
"axes.spines.top": False,
"axes.spines.right": False,
"axes.edgecolor": GREY,
"axes.labelcolor": INK,
"xtick.color": INK,
"ytick.color": INK,
"axes.grid": True,
"axes.grid.axis": "y",
"axes.axisbelow": True,
"grid.color": "#e6e5e0",
"grid.linewidth": 0.8,
"font.size": 10,
"axes.titlesize": 11,
"axes.titleweight": "bold",
"axes.titlelocation": "left",
"legend.frameon": False,
})
print(f"{cal['cu_ug_L'].nunique()} levels x 3 replicates, "
f"{x.min():.0f} to {x.max():.0f} µg/L")
6 levels x 3 replicates, 0 to 200 µg/L
Step 1: the ordinary fit, and why r² is not the test¶
ols = linearity(x, y)
print(f"slope = {ols.slope:.1f} cps per µg/L, intercept = {ols.intercept:.0f} cps")
print(f"r² = {ols.r_squared:.4f}")
slope = 1203.9 cps per µg/L, intercept = 106 cps r² = 0.9997
An r² of 0.9997 looks perfect, and it would look almost as good for a line with a clear curve or with badly misplaced low standards. r² measures how much of the signal's spread the line explains; over a range from 0 to 200 µg/L that is always nearly all of it. It says nothing about whether a straight line is the right shape, or how well the line is known at the low end, where most samples are.
Step 2: is a straight line the right shape? (lack-of-fit test)¶
With replicate standards, the scatter about the line splits into two parts:
- pure error: replicates scattering about their own level mean, which no line can remove;
- lack of fit: level means missing the line, which a better shape would remove.
$$ F = \frac{\text{SS}_\text{lack of fit} / (m - 2)}{\text{SS}_\text{pure error} / (N - m)} $$
for m levels and N solutions. A large F (small p) means the level means are further from the line than the replicates are from each other: the line is the wrong shape.
lof = ols.lack_of_fit
print(f"F = {lof.f:.2f} on ({lof.dof_lack_of_fit}, {lof.dof_pure_error}) dof, "
f"p = {lof.p_value:.2f}")
if lof.significant:
print("Straight line rejected")
else:
print("No evidence against a straight line")
F = 0.32 on (4, 12) dof, p = 0.86 No evidence against a straight line
The straight line is adequate. This test needs genuine replicates: three readings of one solution measure only instrument noise and make almost any curve look significant. Here each replicate is a separate preparation.
Step 3: does the scatter grow with concentration?¶
Ordinary least squares assumes every standard has the same scatter. The residuals and the replicate standard deviations say otherwise:
level_sd = cal.groupby("cu_ug_L")["intensity_cps"].std(ddof=1)
sd_model = np.polyfit(level_sd.index, level_sd.to_numpy(), 1) # s(x) = a + b x
print(level_sd.round(0).to_string())
print(f"Variance model: s(x) = {sd_model[1]:.1f} + {sd_model[0]:.2f} x (cps)")
fig, ax = plt.subplots(figsize=(7, 3.4))
ax.scatter(level_sd.index, level_sd, s=30, color=BLUE, zorder=3,
label="SD of 3 replicates")
grid = np.linspace(0, x.max(), 50)
ax.plot(grid, np.polyval(sd_model, grid), color=GREY, lw=1.5,
label="model s(x) = a + b x")
ax.set_xlabel("Standard, Cu (µg/L)")
ax.set_ylabel("SD of signal (cps)")
ax.set_title("Replicate scatter grows about 150-fold from 0 to 200 µg/L")
ax.legend(loc="upper left")
plt.tight_layout()
plt.show()
cu_ug_L 0.0 20.0 10.0 146.0 25.0 56.0 50.0 645.0 100.0 2620.0 200.0 2892.0 Variance model: s(x) = 14.3 + 16.35 x (cps)
The SD of three replicates is itself rough (the 10 µg/L level happens to scatter more than the 25 µg/L level), so a smooth model, here a straight line s(x) = a + b·x, is a better basis for weights than the raw level SDs.
Step 4: the weighted fit¶
Each standard gets a weight w = 1 / s(x)², so precise low standards count more and
noisy high standards less. labqc.validation.linearity takes explicit weights;
statsmodels' WLS checks the result.
weights = 1 / np.polyval(sd_model, x) ** 2
wls = linearity(x, y, weights=weights)
print(f"weighted: slope = {wls.slope:.1f} cps per µg/L, "
f"intercept = {wls.intercept:.0f} cps")
check = sm.WLS(y, sm.add_constant(x), weights=weights).fit()
assert np.allclose([check.params[1], check.params[0]], [wls.slope, wls.intercept])
print("labqc and statsmodels agree on slope and intercept.")
ci = pd.DataFrame(
{"ordinary": [*ols.intercept_ci95], "weighted": [*wls.intercept_ci95]},
index=["intercept, 95 % CI low (cps)", "intercept, 95 % CI high (cps)"],
)
display(ci.round(0))
weighted: slope = 1202.7 cps per µg/L, intercept = 136 cps labqc and statsmodels agree on slope and intercept.
| ordinary | weighted | |
|---|---|---|
| intercept, 95 % CI low (cps) | -899.0 | 118.0 |
| intercept, 95 % CI high (cps) | 1111.0 | 154.0 |
The slopes are nearly identical, so results at mid and high concentrations hardly change. The intercept is a different story: the ordinary fit knows it only to within about ±1000 cps, roughly ±0.8 µg/L, because the 100 and 200 µg/L standards swing it around. The weighted fit pins it to within about ±18 cps. (Because the data are synthetic, the true intercept is known: 150 cps. It lies inside the weighted interval.)
The residuals, each divided by the scatter the fit assumes, show which fit matches the data:
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4), sharey=True)
panels = [
(axes[0], ols.residuals / ols.residual_sd, "Ordinary fit: fans out"),
(axes[1], wls.residuals / np.polyval(sd_model, x), "Weighted fit: even band"),
]
for ax, z, title in panels:
ax.scatter(x, z, s=22, color=BLUE, zorder=3)
ax.axhline(0, color=INK, lw=0.8)
for edge in (-2, 2):
ax.axhline(edge, color=GREY, ls=":", lw=1)
ax.set_title(title)
ax.set_xlabel("Standard, Cu (µg/L)")
axes[0].set_ylabel("Residual / assumed SD")
plt.tight_layout()
plt.show()
Step 5: what it changes for a sample¶
The question that matters is how well each line pins down a sample's concentration. The 95 % confidence band of the line, converted to µg/L, shows it:
X = sm.add_constant(x)
conc = np.linspace(0, 200, 201)
fits = {"ordinary": sm.OLS(y, X).fit(), "weighted": check}
half_width = {
name: (fit.get_prediction(sm.add_constant(conc, has_constant="add"))
.summary_frame(alpha=0.05)["mean_ci_upper"].to_numpy()
- fit.predict(sm.add_constant(conc, has_constant="add"))) / fit.params[1]
for name, fit in fits.items()
}
fig, ax = plt.subplots(figsize=(8, 3.6))
for (name, hw), colour in zip(half_width.items(), (BLUE, ORANGE)):
ax.plot(conc, hw, color=colour, lw=2, label=f"{name} fit")
ax.annotate(f"{name}", (conc[-1], hw[-1]), xytext=(6, 0),
textcoords="offset points", va="center", fontsize=9, color=INK)
ax.set_xlabel("Concentration, Cu (µg/L)")
ax.set_ylabel("± half-width (µg/L)")
ax.set_title("95 % confidence band of the calibration line")
ax.legend(loc="upper center")
plt.tight_layout()
plt.show()
loq = 2.6 # from the LOD/LOQ notebook
at = np.array([loq, 10, 50, 200])
table = pd.DataFrame(
{name: np.interp(at, conc, hw) for name, hw in half_width.items()},
index=pd.Index(at, name="Cu (µg/L)"),
)
table["ordinary (%)"] = 100 * table["ordinary"] / table.index
table["weighted (%)"] = 100 * table["weighted"] / table.index
display(table.round(3))
| ordinary | weighted | ordinary (%) | weighted (%) | |
|---|---|---|---|---|
| Cu (µg/L) | ||||
| 2.6 | 0.819 | 0.025 | 31.515 | 0.951 |
| 10.0 | 0.777 | 0.079 | 7.772 | 0.794 |
| 50.0 | 0.624 | 0.394 | 1.248 | 0.788 |
| 200.0 | 1.350 | 1.577 | 0.675 | 0.789 |
At the LOQ of 2.6 µg/L, the ordinary line is uncertain by about ±0.8 µg/L, a third of the result, from the calibration alone. The weighted line is uncertain by about ±0.03 µg/L. Above about 80 µg/L the weighted band is somewhat wider, the price of giving the top standards less say, but it stays under 1 % of the result.
The back-calculated standards look almost the same with either line (both within about 3 %), which is why the problem is easy to miss. Weighting is not about the standards fitting better; it is about how well the line is known where the samples are.
What this shows¶
- Do not judge a calibration by r². Look at the residual plot, and with genuine replicates use the lack-of-fit test for shape.
- This line is straight (lack of fit p ≈ 0.86) but heteroscedastic: the scatter grows about 150-fold over the range.
- Weight it, with w = 1/s(x)² from a smooth model of the replicate SDs. The common shortcut w = 1/x² assumes the SD is proportional to concentration and cannot use a zero standard. Narrowing the working range is the other remedy.
- Results near the LOQ depend on this choice far more than results mid-range.
From the lab. [To write: how calibration ranges and weighting were decided for an ICP-OES or other instrumental method you validated, and what assessors looked at.]
References¶
- ISO 8466-1, calibration and evaluation of analytical methods: linear calibration function.
- Eurachem, The Fitness for Purpose of Analytical Methods, section on working range and linearity.
- J. N. Miller and J. C. Miller, Statistics and Chemometrics for Analytical Chemistry, chapter on calibration methods (weighted regression).
labqc.validation.linearity: API documentation.