P03.18 · Lesson 18 of 18

Verification & Validation

Verification asks "did I solve the equations right?"; validation asks "did I solve the right equations?". The first is mathematics and has an exact answer; the second is physics and has only evidence. Confusing them is how a beautifully converged solution of the wrong model gets certified.

computational Time unmeasured

Build it Method of manufactured solutions

Learning outcomes
  1. Define verification, validation and credibility as NASA-STD-7009 uses them, and write a verifiable requirement for a simulation.
  2. Derive the truncation error of the Crank–Nicolson / central-difference heat solver, construct an exact discrete solution and a manufactured solution with its source term, and derive the observed order, Richardson extrapolation and grid convergence index from the error expansion f_h = f + C hᵖ.
  3. Implement code verification (manufactured solutions, planted bugs, backward error of the linear solve), solution verification (observed order, Richardson, GCI, required refinement) and validation (comparison error against data with a combined uncertainty, and the difference between calibration and validation) from scratch on a heat-conduction solver.
  4. Judge a simulation result: say what was verified, to what order, what the numerical uncertainty is, what the model was compared against, and what the comparison does and does not prove.
Prerequisites

P03.11 (finite differences for the 1D heat equation, stability, Crank–Nicolson), P03.08 (direct linear solvers; the Thomas algorithm is LU on a tridiagonal matrix), P03.01 (floating-point error, backward stability), P03.17 (combining uncertainties, chi-square), P02.02 (Taylor expansion). Skill check: you can write the central-difference formula for u_xx with its O(Δx²) error term and solve a tridiagonal system by hand for n = 3.

Engineering question

A 0.5 m aluminium bar, clamped to heat sinks at both ends and heated by a strip heater, is instrumented with four thermocouples for a thermal test of an avionics mounting rail. The design office has a Crank–Nicolson conduction model and wants to know: is the code right (does it solve the heat equation to second order, with no bugs), how far is the 100-cell answer from the converged one (numerical uncertainty), and does the model agree with the thermocouple data within the measurement uncertainty of 0.3 K? When it does not, is the disagreement a numerical error, a measurement error, or a missing physical term, and what is the honest thing to report?

Full lesson specification (11 more items)
Assumptions and limits

The bar is one-dimensional (10 mm square section, Biot number ≪ 1), its properties are constant, the heat sinks hold the ends at ambient exactly, the heater is a Gaussian strip of known power. The "measurements" are synthetic: generated by the same solver with a convective loss term the model under test omits, plus seeded Gaussian noise; they stand in for data nobody in this course has taken, and every table says so. The Richardson and GCI formulas assume the grids are in the asymptotic range of the error expansion, which the lesson shows how to test and how it fails.

Analytical work

Truncation error of the θ-method with central differences (second order in Δx; second order in Δt for θ = ½, first otherwise); a polynomial that is an exact solution of the discrete equations; the manufactured source q = u_t − α u_xx + βu for a chosen u; the observed order p = ln(e₁/e₂)/ln r; Richardson extrapolation f_ex = f₁ + (f₁ − f₂)/(rᵖ − 1), the GCI with safety factor 1.25, the asymptotic-range ratio and the refinement needed for a target GCI; the backward error of a linear solve and why a backward-stable solver can return a large forward error; the validation uncertainty u_val² = u_data² + u_num² and the comparison error E; the steady-state energy balance of the heated bar as a hand check.

Computational deliverable

starter/main.py: thomas_solve, backward_error, heat_theta (θ-method with Dirichlet ends, a loss term and two planted-bug flags), manufactured_source (SymPy builds the source), l2_error, observed_order, convergence_study, richardson, required_refinement, validation_comparison, fit_loss_coefficient (the setup dataclass, heater_source, separable_solution, sample_solution, synthetic_measurements and main are given). Tests prove: the Thomas solver matches scipy.linalg.solve_banded to 10⁻¹² and has a backward error below 20 machine epsilons on a system with condition number 1.6 × 10⁴; a constant and a quadratic-in-x, linear-in-t solution are reproduced to rounding; the separable analytical solution converges at order 2.00 ± 0.05; the manufactured source matches the hand formula; the observed order on the manufactured solution is 2.0 ± 0.1 for Crank–Nicolson and 1.0 ± 0.1 for backward Euler; the planted source-time bug drops the order to one and the planted diffusivity bug gives an error plateau of order zero; the time order is recovered by Richardson on point values without an exact solution; observed_order and richardson are exact on synthetic error laws and raise on oscillatory convergence; on the heater functional the observed order is 2.03, the extrapolated value beats the fine grid by a factor 5 and the GCI bounds the true error; the validation metric flags the model without the loss term (5 of 24 points within 2u_val, reduced χ² 61) and passes the true model (χ² ≈ 1); the calibration recovers the loss coefficient within 10 %.

Practical activity

computational experiment: the planted-bug hunt, the grid-convergence study of two functionals (one smooth, one not), and the validation-versus-calibration experiment on the synthetic thermocouple data.

Equipment

None. A computer with the environment from P00.01.

Safety

None beyond normal computer use.

Evidence

Completed main.py, passing tests, heat_vv.png, the truncation-error derivation, the exact-discrete-solution proof, the Richardson derivation, the three experiment tables, and a one-page V&V report in the NASA-STD-7009 reporting spirit: what was verified and how (orders, errors, backward error), the numerical uncertainty of the reported quantity (GCI), what the model was validated against (synthetic data, labelled), the comparison error with its uncertainty, the limits of validity, and what remains assumed.

Assessment

assessments/phase-03/grading-rubric.md; competencies 1–4. Pass: the truncation-error and Richardson derivations are correct; all public tests pass; the observed orders are measured and the planted bugs found; the report distinguishes verification from validation and calibration from validation, with numbers.

References

@nasa-std-7009b "Standard for Models and Simulations" (V&V definitions, credibility assessment factors, reporting requirements; required-free). @nasa-seh-rev2 "5.0 Product Realization" (verification and validation sections) and Appendix C "How to Write a Good Requirement" (required-free: the requirement-writing checklist as the basis for test oracles). @ocw-18-335j Week 2 "Lecture 3: Floating-Point Summation and Backwards Stability" (required-free: code verification by backward error). @nasa-nparc-cfd-vv-tutorial "Verification Assessment" (steps "4. Examine Spatial (Grid) Convergence", "5. Examine Temporal Convergence", "6. Compare CFD Results to Highly Accurate Solutions") and "Examining Spatial (Grid) Convergence" (sections "Order of Grid Convergence", "Asymptotic Range of Convergence", "Richardson Extrapolation", "Grid Convergence Index (GCI)", "Required Grid Resolution", "Example Grid Convergence Study") (required-free). @langtangen-linge-fd-computing-pdes Chapter 2 "2.2 Verification" (2.2.3 Manufactured Solution and Estimation of Convergence Rates, 2.2.4 Constructing an Exact Solution of the Discrete Equations), "2.3.4 Verification: Convergence Rates"; Chapter 1 "1.2.2 Verification" (required-free). @langtangen-fd-computing-exponential-decay Chapter 3 "3.1.4 Verifying a Constant Solution", "3.1.5 Verification via Manufactured Solutions", "3.1.6 Computing Convergence Rates" (required-free).

Extensions

★ Add a Neumann (insulated) end with a second-order ghost-point treatment and show, with a manufactured solution, that a first-order one-sided boundary difference drops the global order to one. ★ Replace the Gaussian noise of the synthetic data by a 0.5 K thermocouple bias and show that the validation metric cannot distinguish bias from model-form error without a second instrument. ★ Run the solver with a temperature-dependent diffusivity α(u) and verify it by manufactured solution (the source then depends on u).

Time

unmeasured

1. The engineering problem

Every lesson in this phase ended with "compare with SciPy". That was verification: an independent code solving the same equations. Real engineering codes have no SciPy to compare with, and the aircraft or spacecraft they size gets certified on their output, so the question "is this number right?" needs a procedure. NASA-STD-7009 (@nasa-std-7009b), written after the Columbia accident board found that a debris-impact prediction had been trusted beyond its evidence, defines the terms: verification is the process of determining that a model implementation accurately represents the developer's conceptual description (the equations are solved correctly); validation is the process of determining the degree to which a model is an accurate representation of the real world from the perspective of its intended use (the right equations are solved); and the standard requires that the uncertainty of the result, the verification and validation evidence, and the limits of the model's applicability be reported with every result that supports a critical decision.

This lesson does the whole procedure on a problem small enough to see every step: a transient one-dimensional heat-conduction solver for a strip-heated aluminium rail, u_t = α u_xx − βu + q(x, t) with the ends held at ambient. Code verification first: the solver must reproduce solutions whose exact form is known, and the method of manufactured solutions (@langtangen-fd-computing-exponential-decay 3.1.5, @langtangen-linge-fd-computing-pdes 2.2.3) supplies as many as we like; its observed order of convergence must equal the formal order, and we check that it catches two bugs planted in the solver. Solution verification next: on the real problem, which has no exact solution, three grids and Richardson extrapolation estimate the converged answer and the grid convergence index gives the numerical uncertainty of the 100-cell result (@nasa-nparc-cfd-vv-tutorial). Validation last: the model is compared with thermocouple data — synthetic data in this lesson, generated with a physical term (convective loss) the model omits, so the comparison fails in the way real comparisons fail, and we learn what the failure looks like, how calibrating one parameter hides it, and what should be reported.

Success criteria, written first: Thomas solver backward error below 20 ε; constant and polynomial solutions reproduced to 10⁻¹¹ K; observed order 2.00 ± 0.05 on two exact solutions; both planted bugs detected by the order test; Richardson extrapolation of the heater temperature within 10⁻⁴ K of an 800-cell reference, and the GCI of the 100-cell grid bounding its actual error; the validation metric rejects the lossless model and accepts the true one with reduced χ² between 0.5 and 2.

2. Understand and derive

2.1 Three words with precise meanings

NASA-STD-7009 separates code verification (the software solves the discrete equations without bugs: exact solutions, order tests, backward error), solution verification (how far the discrete solution on the grid actually used is from the exact solution of the continuous equations: grid convergence, iterative convergence), and validation (comparison with referent data from the real world, with uncertainties on both sides). Its credibility assessment adds input pedigree, results uncertainty, results robustness and the qualifications of the people; the reporting requirement is that a result be accompanied by its uncertainty, the assumptions and the V&V evidence. Appendix C of the Systems Engineering Handbook (@nasa-seh-rev2) teaches how to write a requirement that can be verified: a single statement with a measurable criterion and a method. "The solver shall be accurate" is not one. "The solver shall exhibit an observed spatial order of 2.0 ± 0.1 on the manufactured solution of §2.4 over grids of 25 to 200 cells, verified by test" is, and it is exactly what a pytest test encodes. Every test in this lesson is a requirement in that form.

2.2 The scheme and its truncation error

On a grid x_i = iΔx, i = 0 … nx, with time step Δt, the θ-method with central differences reads

(u_i^{n+1} − u_iⁿ)/Δt = θ[α D₂u^{n+1} − βu^{n+1} + q^{n+1}]i + (1 − θ)[α D₂uⁿ − βuⁿ + qⁿ]i, D₂u_i = (u{i−1} − 2u_i + u{i+1})/Δx², (1)

with θ = ½ Crank–Nicolson and θ = 1 backward Euler. Taylor-expand the exact solution about (x_i, t_{n+½}) (P02.02). The time difference equals u_t + (Δt²/24)u_ttt + …; the θ-average of a quantity at n and n + 1 equals its midpoint value plus (θ − ½)Δt ∂_t(·) + (Δt²/8)∂_tt(·) + …; and D₂u = u_xx + (Δx²/12)u_xxxx + …. The scheme's truncation error is therefore

τ = (θ − ½)Δt (αu_xx − βu + q)_t + O(Δt²) + (Δx²/12) α u_xxxx + O(Δx⁴): (2)

second order in Δx for every θ, second order in Δt only for θ = ½. The scheme is unconditionally stable for θ ≥ ½ (P03.11), so the error of the solution is O(Δx²) + O(Δt^{p_t}) with p_t = 2 or 1. With Δt ∝ Δx, both terms shrink by 4 per halving for Crank–Nicolson and the observed order must be 2; for backward Euler the Δt term shrinks by 2 and dominates, so the observed order falls to 1. Formula (2) is what we test; it also predicts the planted bug of §2.5.

Each time step is a tridiagonal solve: interior rows have diagonal 1 + θ(2r + βΔt) with r = αΔt/Δx², off-diagonals −θr, right-hand side from the known level plus the boundary values at t_{n+1}. The Thomas algorithm is Gaussian elimination without pivoting in O(n); the matrix is strictly diagonally dominant (diagonal exceeds the sum of the off-diagonals by 1 + θβΔt), so no pivot can vanish and the algorithm is backward stable.

2.3 Exact solutions of the discrete equations

Before any convergence study, test things that must hold exactly (@langtangen-fd-computing-exponential-decay 3.1.4, @langtangen-linge-fd-computing-pdes 2.2.4, 1.2.2). A constant u = c with q = 0 and both ends at c satisfies (1) identically: D₂c = 0, and the time difference is zero. A solver that does not return exactly c (to rounding) has a wrong boundary row or a sign error, and no order study is needed to find it. Stronger: u = 2t x(L − x) with source q = 2x(L − x) + 4αt. The central difference of a quadratic is exact (u_xxxx = 0 kills the Δx² term in (2)), the Crank–Nicolson average of a quantity linear in t is exact (u_ttt = 0 and q_tt = 0 kill the Δt² terms), so this polynomial is an exact solution of the discrete equations on any grid and any step. The code reproduces it to 7 × 10⁻¹⁵ K after ten steps on 40 cells: that is the rounding error of a few hundred floating-point operations, and the test demands 10⁻¹¹. The classic separable solution u = T₀ sin(πx/L) e^{−α(π/L)²t} of the homogeneous problem is the "analytical solution of physical significance" of @langtangen-linge-fd-computing-pdes 2.2.2: with T₀ = 50 K the L2 errors on 25, 50, 100, 200 cells (Δt = 300 s/nx) are 1.04 × 10⁻², 2.59 × 10⁻³, 6.47 × 10⁻⁴, 1.62 × 10⁻⁴ K, orders 2.0007, 2.0002, 2.0000.

2.4 Manufactured solutions and the observed order

Analytical solutions exist only for simple cases (no source, no loss, separable data), which is exactly where bugs do not hide. The method of manufactured solutions reverses the problem: choose any smooth u_m(x, t), compute the source q_m = ∂_t u_m − α ∂_xx u_m + βu_m that makes it a solution, take the initial and boundary data from u_m itself, run the solver with q_m and compare with u_m. The function is arbitrary, so pick one that exercises everything: time dependence that is not linear (so Δt² terms exist), space dependence with u_xxxx ≠ 0, nonzero values wherever a sign could be wrong. The lesson's choice,

u_m = 40 sin(πx/L)(1 − e^{−t/τ}) + 10 sin(2πx/L) e^{−t/τ}, τ = 200 s, (3)

has q_m = (40/τ) sin(πx/L) e^{−t/τ} + 40α(π/L)² sin(πx/L)(1 − e^{−t/τ}) − (10/τ) sin(2πx/L) e^{−t/τ} + 10α(2π/L)² sin(2πx/L) e^{−t/τ}; manufactured_source lets SymPy differentiate so that the learner's hand algebra is not the weakest link (the test checks SymPy's output against a hand formula on a simpler case). Note that q_m has no physical meaning; a heater that produces (3) does not exist, and that does not matter: verification is about the equations, not the physics.

With Δt = 300 s/nx the discrete L2 errors √(Δx Σ(u − u_m)²) are

nx 25 50 100 200 400
error [K] 1.480 × 10⁻² 3.696 × 10⁻³ 9.238 × 10⁻⁴ 2.309 × 10⁻⁴ 5.773 × 10⁻⁵
observed order 2.002 2.000 2.000 2.000

where the observed order between two grids refined by r is p = ln(e_coarse/e_fine)/ln r (@langtangen-fd-computing-exponential-decay 3.1.6, "Estimating r"). The sequence of p's converging to the formal order 2 from above is the signature of a correct code in its asymptotic range: the error is C Δx² + higher-order terms whose share shrinks. Backward Euler on the same problem gives errors 0.23, 0.12, 0.06, 0.03, 0.015 K and orders 0.96, 0.98, 0.99, 0.99: the Δt term of (2) dominates and the order is one, as predicted.

Order in time without an exact solution. Fix a fine grid (400 cells) and halve Δt: compared against u_m the errors are 1.51 × 10⁻², 3.79 × 10⁻³, 9.76 × 10⁻⁴, 2.74 × 10⁻⁴ K for 10, 20, 40, 80 steps and the orders 1.99, 1.96, 1.84 fall, because the spatial error (5.8 × 10⁻⁵ K) is becoming a floor. The remedy is to compare the solutions with each other rather than with the exact one: the point value u(0.15 m, 300 s) is 27.2847, 27.2679, 27.2637, 27.2626 K, and p = ln((f₃ − f₂)/(f₂ − f₁))/ln 2 from each triplet is 2.002 and 2.0005: the floor cancels in the differences. That is the Richardson idea of §2.6, used for verification; it needs no exact solution at all, which is why it works on the real problem.

2.5 Planted bugs: does the test catch what it is for?

A verification test is only as good as the bugs it can catch, so plant some. heat_theta(..., bug="source_time") evaluates the source at t_n instead of the θ-weighted level. By (2) this adds (Δt/2) q_t to the truncation error: the scheme still converges, but at first order. Observed: errors 0.080, 0.040, 0.020, 0.010, 0.005 K and orders 1.14, 1.08, 1.04, 1.02. The solution at 400 cells is still only 0.005 K wrong, which a plot would never show, and a comparison with the exact solution at a single resolution would call "accurate"; the order test exposes it at once. bug="diffusivity" uses 1.02α: the code converges perfectly, to the solution of the wrong equation. Errors 0.14, 0.15, 0.15, 0.15, 0.15 K, observed order ≈ 0: an error plateau, the signature of a converged solution of the wrong problem (a wrong constant, a wrong sign in a term that happens to be small, a boundary condition applied to the wrong node). Both bugs would pass the constant-solution test; only the first would pass a plot; neither passes the manufactured-solution order test. This is the content of "testing" in @langtangen-linge-fd-computing-pdes 2.2.3: the test oracle is the rate, not the error.

Backward error of the solve (@ocw-18-335j Lecture 3). For the linear-algebra piece the right oracle is not "does x agree with SciPy to 10⁻¹²" but "is x the exact solution of a nearby problem": the normwise relative backward error ‖Ax − b‖/(‖A‖‖x‖ + ‖b‖). A backward-stable algorithm returns a few machine epsilons whatever the conditioning; the forward error may still be as large as κ(A) times that, and that is the problem's fault, not the algorithm's. For the θ-method matrices (κ ≈ 1 + 4θr ≈ 50 at r = 12) the Thomas solver returns a backward error of 3.7 × 10⁻¹⁷; on a deliberately ill-conditioned tridiagonal (diagonal 2 − 10⁻⁶, κ = 1.6 × 10⁴) still 1.0 × 10⁻¹⁶, and the forward difference from a dense LU is 6.5 × 10⁻¹⁶: the algorithm is doing its job and the conditioning is benign here.

2.6 Solution verification: Richardson extrapolation and the GCI

The heater problem (Gaussian strip, q = Q e^{−(x−x₀)²/2w²}, Q = 0.5 K/s, w = 30 mm, x₀ = 0.2 m) has no closed-form solution. How far is the 100-cell answer from the converged one? Write the error expansion for a functional f (a temperature at a point, a heat flux, a maximum): on grid spacing h in the asymptotic range,

f_h = f_exact + C hᵖ + higher-order terms. (4)

Three grids with constant refinement ratio r (h, rh, r²h: fine f₁, medium f₂, coarse f₃) give three equations for f_exact, C and p. Subtracting pairs eliminates f_exact: f₂ − f₁ = C hᵖ(rᵖ − 1), f₃ − f₂ = C hᵖ rᵖ(rᵖ − 1), so

p = ln((f₃ − f₂)/(f₂ − f₁))/ln r, f_exact ≈ f₁ + (f₁ − f₂)/(rᵖ − 1) (5)

(the second is Richardson extrapolation; @nasa-nparc-cfd-vv-tutorial "Order of Grid Convergence" and "Richardson Extrapolation"). The grid convergence index turns the fine-grid change into an error band: GCI_fine = F_s |ε₂₁|/(rᵖ − 1) with ε₂₁ = (f₂ − f₁)/f₁ and a safety factor F_s = 1.25 when three grids are available (3 with two): it is the Richardson error estimate with 25 % margin, and reads "the fine-grid value is within GCI (relative) of the converged value, with the confidence that experience with many codes has earned the factor 1.25" ("Grid Convergence Index (GCI)"). Two further tools follow from (4): the grids are in the asymptotic range if GCI₃₂/(rᵖ GCI₂₁) ≈ 1 ("Asymptotic Range of Convergence"), and the refinement needed to bring the GCI to a target is (GCI/target)^{1/p} ("Required Grid Resolution"). One caution that the formulas hide: if p is computed from the same three values, the asymptotic ratio equals f₁/f₂ by construction and tests nothing; the check has teeth only when p is the scheme's formal order, which richardson(..., p_formal=2.0) allows. With four grids one can compute p from two triplets instead.

For the temperature rise at the heater centre, x = 0.2 m (a node of every grid used), after 600 s:

nx 25 50 100 800 (reference)
f [K] 38.3781 38.2531 38.2226 38.2126

Observed p = 2.034, Richardson f_exact ≈ 38.2127 K (the 800-cell reference is 38.2126 and its own extrapolation 38.21245), GCI_fine = 0.0323 %, actual |f₁ − f_ref|/f₁ = 0.0261 % (inside the GCI, as the factor 1.25 intends), asymptotic ratio with p = 2 equal to 1.023. To bring the GCI to 0.01 % the fine grid must be refined by (0.0323/0.01)^{1/2.03} = 1.78. In absolute terms the numerical uncertainty of the 100-cell model is u_num = 0.0323 % × 38.2 K = 0.012 K, forty times smaller than the thermocouple uncertainty: numerics will not be what limits the validation.

A functional that is not in the asymptotic range. Take instead the maximum over the nodes at t = 600 s: 38.3781, 38.3188, 38.3178 K on 25, 50, 100 cells. The formulas return p = 5.93 and an asymptotic ratio with p = 2 of 15.3; the next triplet (50, 100, 200) has differences of opposite sign and richardson raises. The functional is not a smooth function of the grid: the node under the peak moves as the grid changes, which adds an O(Δx) wobble that is not of the form (4). The lesson: Richardson applies to quantities that converge smoothly (point values at common nodes, integrals), and a p far from the formal order is a warning, not a result (@nasa-nparc-cfd-vv-tutorial "Example Grid Convergence Study" discusses the same symptom).

2.7 Validation: comparison error and its uncertainty

Validation compares the model with measurements of the real system. The data in this lesson are synthetic, generated by synthetic_measurements: the same solver with the true convective loss β_true = hP/(ρcA) = 8.2 × 10⁻⁴ s⁻¹ (h = 5 W/m²K on a 10 mm square section), on a fine grid, sampled at four thermocouples (x = 0.1, 0.2, 0.3, 0.4 m) at six times (100 to 600 s), plus Gaussian noise of standard deviation σ = 0.3 K (seed 18; the realised noise has an RMS of 0.307 K). The model under test has β = 0: the designer forgot that the rail loses heat to the air. The procedure would be identical with real data.

Define the comparison error E = model − data at each point and the validation uncertainty u_val = √(u_data² + u_num²), here √(0.3² + 0.012²) = 0.300 K. A model is validated at the level u_val if |E| is consistent with u_val: a reduced chi-square Σ(E/u_val)²/N near 1, almost all |E| < 2u_val. The lossless model gives

t [s] E at 0.1 m 0.2 m 0.3 m 0.4 m
100 0.45 0.88 0.14 0.44
300 1.06 1.57 2.34 0.77
600 2.90 4.60 4.46 2.38

(in K): 5 of 24 points within 2u_val, reduced χ² = 61, E/u_val up to 15, and a pattern: the error is positive everywhere, grows with time and is largest where the temperature is highest. That is not noise (noise has no pattern) and not numerics (u_num = 0.012 K); it is model-form error, and its shape says what is missing: a loss proportional to temperature. A hand estimate of the missing term, βu·t ≈ 8 × 10⁻⁴ × 35 K × 600 s ≈ 17 K if nothing else happened, bounded by conduction to about a quarter of that, matches the 4.6 K seen.

Calibration is not validation. fit_loss_coefficient minimises χ² over β: β̂ = 7.92 × 10⁻⁴ s⁻¹ in ten model runs, with a standard uncertainty of 0.23 × 10⁻⁴ from the curvature of χ² (the true 8.20 is 1.2σ away), reduced χ² = 0.98, 23 of 24 points within 2u_val. The calibrated model now "agrees with the data"; it also agreed before anybody knew the physics, because one free parameter can absorb one pattern. Whether β̂ = 7.9 × 10⁻⁴ s⁻¹ (equivalent h = 4.8 W/m²K) is a physical loss coefficient or a fudge that also hides a heater-power error, a contact resistance at the sinks or a thermocouple bias can only be learned from data not used in the fit (a different heater power, a longer time, a fifth sensor), which is why NASA-STD-7009 asks for validation on the intended use and not on the fitting set. Problem 5 does the hold-out test.

2.8 Where the model stops being valid

  • One-dimensional. The Biot number hw/k ≈ 5 × 0.01/237 = 2 × 10⁻⁴ justifies it here; a 100 mm block would not be.
  • Linear. Aluminium's k and c change by about 10 % between 20 and 200 °C; a 40 K rise is at the edge.
  • Ideal sinks. A contact resistance at the clamps raises the end temperature; its signature in E would be an offset that grows toward the ends, distinguishable from the loss term's shape, if the sensors resolve it.
  • The synthetic data. They contain exactly one unmodelled effect and Gaussian noise. Real thermocouples have bias, time lag and position error, and the real bar has all of the above at once. The procedure is the same; the diagnosis is harder.

3. Build the computational model

Open starter/main.py. HeatSetup, tridiagonal_matvec, heater_source, separable_solution, sample_solution, synthetic_measurements and main are given.

Step 1: the linear solver and its backward error

def thomas_solve(lower, diag, upper, rhs):
    n = diag.size
    c, d = diag.astype(float).copy(), rhs.astype(float).copy()
    for i in range(1, n):                       # forward elimination
        m = lower[i] / c[i - 1]
        c[i] -= m * upper[i - 1]
        d[i] -= m * d[i - 1]
    x = np.empty(n)
    x[-1] = d[-1] / c[-1]
    for i in range(n - 2, -1, -1):              # back substitution
        x[i] = (d[i] - upper[i] * x[i + 1]) / c[i]
    return x

Raise ValueError on a zero pivot. backward_error uses the given tridiagonal_matvec for the residual and the maximum row sum for ‖A‖_∞.

Step 2: the θ-method

Build the three constant diagonals once (diagonal 1 + θ(2r + βΔt), off-diagonals −θr), then per step: the explicit part u + (1 − θ)Δt(αD₂u − βu), plus Δt times the θ-weighted source, plus θr times the new boundary values in the first and last rows; solve; write the boundary values into the new level. Implement the two bug flags exactly as documented in the docstring (the tests plant them) and raise on an unknown flag. Return the full history (nt + 1, nx + 1).

Step 3: manufactured solutions and orders

def manufactured_source(u_expr, x_sym, t_sym, alpha, beta=0.0):
    import sympy as sp
    q_expr = sp.diff(u_expr, t_sym) - alpha * sp.diff(u_expr, x_sym, 2) + beta * u_expr
    u_l, q_l = sp.lambdify((x_sym, t_sym), u_expr, "numpy"), sp.lambdify((x_sym, t_sym), q_expr, "numpy")
    ...  # wrap both so that (x_array, t) -> array of x's shape, even when the expression is constant in x

l2_error is √(Δx Σ(u − u_e)²); observed_order is the vector of ln(e_k/e_{k+1})/ln r; convergence_study just maps a run(n) callable over the resolutions (keep it, it makes every study a one-liner and a test).

Step 4: Richardson, GCI, validation

richardson(f1, f2, f3, r, Fs, p_formal) implements (5) and the GCI, returns a dict with p, p_used, f_extrap, eps21, eps32, gci_fine, gci_medium, asymptotic_ratio, and raises ValueError when the differences are zero or of opposite sign. required_refinement is (GCI/target)^{1/p}. validation_comparison returns E, u_val, z = E/u_val, the count within 2, the reduced χ² and the largest |z|. fit_loss_coefficient wraps scipy.optimize.minimize_scalar(method="bounded") around χ²(β) and counts model runs.

Running main() prints

exact discrete (polynomial) solution reproduced to 7.1e-15 K; Thomas backward error 3.7e-17 (machine epsilon 2.2e-16)
manufactured solution, Crank-Nicolson, dt = t_end/nx:
  nx =   25: L2 error 1.480e-02 K
  ...
  observed orders [2.002 2.    2.    2.   ]
  planted bug 'source_time': errors [0.08 0.04 0.02 0.01 0.  ], orders [1.14 1.08 1.04 1.02]
  planted bug 'diffusivity': errors [0.14 0.15 0.15 0.15 0.15], orders [-0.1  -0.02 -0.01 -0.  ]
  backward Euler (theta = 1):  errors [0.23 0.12 0.06 0.03 0.01], orders [0.96 0.98 0.99 0.99]
temperature rise at the heater, t = 600 s: nx = 25/50/100 -> 38.3781/38.2531/38.2226 K; observed p = 2.034, Richardson 38.2127 K (nx = 800 gives 38.2126), GCI_fine = 0.0323 %, actual |f1 - f_ref|/f1 = 0.0261 %, asymptotic ratio with p = 2: 1.023
  the same with the nodal maximum: 38.3781/38.3188/38.3178 K -> observed p = 5.93, asymptotic ratio with p = 2: 15.3 (not asymptotic: the node under the peak moves)
validation against SYNTHETIC data (seed 18, 24 points, u_data = 0.3 K, u_num = 0.012 K):
  model without loss: 5/24 points within 2 u_val, reduced chi2 61.3, max |E|/u_val 15.3, worst E = 4.60 K
  calibrated beta = 7.919e-04 1/s (truth 8.200e-04, 10 model runs): 23/24 within 2 u_val, reduced chi2 0.98

and heat_vv.png: the convergence plot with the two bugs, the temperature profiles against the synthetic data at 600 s, and E/u_val per sensor against time.

Verify

  • Exact cases: constant solution; the quadratic-linear polynomial; the separable solution; the hand formula for the manufactured source; observed_order and richardson on exact error laws (p = 1.7 and 2 recovered to 10⁻¹², f_exact recovered, GCI formula).
  • Orders: 2.0 ± 0.1 for Crank–Nicolson, 1.0 ± 0.1 for backward Euler, both from the manufactured solution; the time order by Richardson on point values.
  • Failure cases: the two planted bugs (order 1 and order 0); an unknown flag raises; oscillatory convergence raises; a zero pivot raises.
  • Oracles: scipy.linalg.solve_banded for the solve; the backward error against machine epsilon; the 400-cell reference for the extrapolation and the GCI bound.
  • Validation logic: the lossless model is rejected (≤ 10 of 24 within 2u_val, χ² > 10, every late error positive), the true model is accepted (≥ 20 of 24, 0.5 < χ² < 2), the fit recovers β within 10 %, and the data dict is labelled "synthetic".

Compare

scipy.linalg.solve_banded is the production tridiagonal solver (LAPACK gtsv, with pivoting, which Thomas lacks and which matters for matrices that are not diagonally dominant); scipy.sparse.linalg and scipy.integrate.solve_ivp with the method-of-lines would solve the same PDE; and the structure of the verification (exact solutions, manufactured solutions, rate tests as pytest oracles) is the one @langtangen-fd-computing-exponential-decay 3.1.6 recommends ("Why convergence rates are important"): a rate test is an absolute criterion, while "the error is small" is relative to an unstated expectation. What writing it bought is the habit of treating every claim about a simulation as a requirement with a method of verification, and the knowledge that "the code agrees with the experiment" can mean the code is right, or that one parameter was tuned until it did.

4. Experiment at home, or investigate real data

Mode: computational experiment; write each prediction first.

  1. Bug hunt. Run the manufactured-solution study with bug=None, "source_time", "diffusivity" and with θ = 1. Predict the observed orders (2, 1, 0, 1) from (2) and §2.5 before running, and predict which of the four a single-resolution comparison at 400 cells with a 0.01 K tolerance would pass (three of them).
  2. Two functionals. Repeat the Richardson study for the heater temperature at x = 0.2 m and for the nodal maximum on grids 25–50–100 and 50–100–200, with the observed and the formal order. Predict p ≈ 2 and a ratio ≈ 1 for the first, garbage for the second, and say beforehand what feature of the second functional breaks (4).
  3. Validation versus calibration. Compute E and χ² for β = 0, β = β̂ and β = β_true. Then refit β on the first five sampling times only and evaluate E at t = 600 s (hold-out). Predict that the hold-out row stays within 2u_val if the model form is now right, and predict the sign of E if it were not.
  4. Noise and sensitivity. Regenerate the synthetic data with seeds 1–10 and record β̂ for each; compare the scatter with the 0.23 × 10⁻⁴ s⁻¹ from the χ² curvature. Predict agreement within a factor 1.5.

Raw data format: CSV (nx, error_none, error_source_time, error_diffusivity, error_backward_euler; functional, grids, f1, f2, f3, p, f_extrap, gci_fine, ratio_p2; beta, chi2_reduced, n_within_2; seed, beta_hat), every file headed "SYNTHETIC data, seed N, sigma 0.3 K", and heat_vv.png.

What you should find: orders 2.00, 1.0–1.1, ≈ 0, 0.96–0.99, and a 400-cell comparison at 0.01 K passing everything except the diffusivity bug (0.15 K); point functional p = 2.03 then 2.01 with ratio 1.02 and 1.00, maximum functional p = 5.9 then a ValueError; χ² = 61, 0.98, 0.99 for the three β's; the hold-out row of E within [−0.3, 0.6] K with β̂ fitted on five rows (7.6 × 10⁻⁴ s⁻¹ for seed 15); ten seeds giving β̂ with a standard deviation near 0.25 × 10⁻⁴ s⁻¹.

5. Validate and improve

quantity hand (§2) code difference cause
constant and polynomial solutions exact 7 × 10⁻¹⁵ K rounding —
Thomas backward error O(ε) 3.7 × 10⁻¹⁷; 1.0 × 10⁻¹⁶ at κ = 1.6 × 10⁴ — backward stable
CN order on manufactured solution 2 from (2) 2.002, 2.000, 2.000, 2.000 — —
backward Euler order 1 from (2) 0.96–0.99 <0.04 O(Δt²) remainder
planted bug orders 1 and 0 1.14→1.02; −0.1→0.0 — caught
heater temperature, extrapolated — 38.2127 vs 38.2126 (800 cells) 10⁻⁴ K within GCI
GCI vs actual error, 100 cells GCI ≥ actual 0.0323 % vs 0.0261 % covered F_s = 1.25
steady-state heater temperature 46.3 K (energy balance, point-source limit) 38.2 K at 600 s, 2.3 time constants 83 % of steady transient, as expected
lossless model vs synthetic data fails χ² = 61, 5/24 within 2u_val — missing βu term
calibrated β̂ 8.2 × 10⁻⁴ s⁻¹ (truth) 7.92 ± 0.23 × 10⁻⁴ 1.2σ noise

The steady-state hand check: with no loss, the total heating ∫q dx = Qw√(2π) = 0.0376 K m/s must leave through the ends; treating the heater as a point source at x₀, u(x₀) = (∫q dx/α)·x₀(L − x₀)/L = 46.3 K at steady state, and the slowest mode decays with time constant L²/(π²α) = 260 s, so 38 K after 600 s is the right size. Every row of the table is a verification row except the last two: those are what validation against synthetic data can teach, which is the method and its failure modes, not whether an aluminium rail loses 5 W/m²K to the air. The report (part 6) must say so.

What to improve: the Neumann boundary and its order (extension 1) is the most common real bug class not covered here; a bias term in the synthetic data (extension 2) shows the limit of a single data set; and if this were a real test, the next step is not more cells (u_num is already 0.012 K) but a second heater power and a longer run to test the calibrated β̂ on data it was not fitted to.

6. Defend your work

Submit: the completed main.py with passing tests; the derivations of (2), of the exact discrete polynomial solution and of (5); heat_vv.png; the four experiment tables; and a one-page V&V report (template in projects/_template/report-template.md, sections 1, 5, 6 and 7) with the headings Code verification (which exact solutions, which orders, which planted bugs, backward error), Solution verification (grids, observed order, extrapolated value, GCI, u_num), Validation (what data — labelled synthetic — with what uncertainty, E and χ² before and after calibration, what the calibration can and cannot claim), Limits of validity and Assumptions. Every number in it must come from your own run.

Adversarial self-checks

  • What if a reviewer swaps α for 1.02α in the released code? The manufactured-solution test fails with an error plateau at 0.15 K; the separable-solution order test also fails (plateau); the constant-solution and polynomial tests pass (the polynomial has u_xxxx = 0 but its source contains 4αt, so check: it fails too, because q was built with the true α). Run it and see which tests are the useful ones.
  • What if the data had been real? The pattern of E (positive, growing in time, largest at the hottest point) would still point to a loss term, but a thermocouple bias of +0.5 K at one sensor would masquerade as a local model error, and a heater-power error of 5 % would be absorbed into β̂ along with the loss. One parameter fitted to one data set proves nothing about either.
  • Which assumption fails first? The ideal heat sinks: a clamp contact resistance of 10⁻⁴ m²K/W under a flux of 0.0376 × ρc/2 ≈ 46 kW/m² raises each end by 4.6 K, as large as the whole model-form error found here, and with a different spatial signature. A fifth sensor on the sink would resolve it.
  • What measurement would falsify the calibrated model? A run at double heater power: a true convective loss predicts the same β̂ (linear in u), whereas an absorbed heater-power error predicts a β̂ that changes with power. That is the hold-out test every calibration owes.
  • Does the result survive a change of grid, step or seed? Orders within ±0.1, extrapolated temperature within 10⁻⁴ K, β̂ within its 0.23 × 10⁻⁴ s⁻¹ over seeds; a departure outside these bands is a bug, not a feature.
  • Which decision changes if the uncertainty doubles? If u_data were 0.6 K the lossless model would still fail (χ² = 15) but β̂ would be known only to 0.5 × 10⁻⁴ s⁻¹ (6 %), and a design margin based on the rail temperature at 1200 s (35.4 K with β̂, 35.2 with the truth, 41.3 without loss) would carry ±0.4 K from the calibration alone. The decision to add a fan or not hinges on 6 K of model-form error, not on 0.012 K of numerics: spend on sensors, not cells.

Check yourself

  1. Define verification and validation in one sentence each, and give an example of a result that passes the first and fails the second.
  2. From the truncation error (2), state the observed order you expect for Crank–Nicolson and for backward Euler when Δt ∝ Δx, and why.
  3. Why is u = 2t x(L − x) with q = 2x(L − x) + 4αt reproduced to rounding, while sin(πx/L) e^{−α(π/L)²t} is not?
  4. Write the manufactured source for u_m = A sin(πx/L) e^{−t/τ} with a loss term β.
  5. Derive the observed order and the Richardson extrapolation from f_h = f + Chᵖ on three grids with ratio r.
  6. What does an observed order near zero on a manufactured solution indicate? And an order of 1 where 2 is expected?
  7. A GCI of 0.03 % was computed with the observed order; the asymptotic ratio came out 1.00. What has been tested and what has not?
  8. State the difference between calibration and validation in terms of the data used, and name the test that distinguishes a physical loss coefficient from a fudge factor.

Problem set

Attempt every problem before opening solutions/. Record what you tried. State units on every numerical answer, give every error with the resolution it belongs to, and label every data set you use as measured or synthetic.

Several problems use your personal seed s: the day of the month you were born (1–31).

1. (Warm-up: grid convergence by hand)

A drag coefficient is computed on three grids refined by r = 2: C_D = 0.0200 + 1 × 10⁻⁵ s on the fine grid, 0.0200 + 4 × 10⁻⁵ s on the medium grid and 0.0200 + 17 × 10⁻⁵ s on the coarse grid.

(a) Compute the observed order p, the Richardson-extrapolated C_D and the GCI of the fine grid (F_s = 1.25) by hand. (b) Recompute the extrapolated value and the GCI with the formal order 2 and compare; compute the asymptotic-range ratio with p = 2 and say whether the grids are in the asymptotic range. (c) By what factor must the fine grid be refined for a GCI of 0.1 %?

Answer form: p, two extrapolated values, two GCIs in %, one ratio, one factor.

2. (Derivation: truncation error, exact discrete solution, Richardson, planted bug)

(a) Derive the truncation error (2) of the θ-method with central differences by Taylor expansion about (x_i, t_{n+½}). Show that the O(Δt) term vanishes only for θ = ½. (b) Show that u = 2t x(L − x) with q = 2x(L − x) + 4αt satisfies the Crank–Nicolson discrete equations (1) exactly for any Δx and Δt with zero Dirichlet ends. (c) From f_h = f + Chᵖ on grids h, rh, r²h derive p and the Richardson extrapolation (5). Show that the asymptotic ratio GCI₃₂/(rᵖGCI₂₁) equals f₁/f₂ when p is the observed order. (d) Show that evaluating the source at t_n instead of the θ-weighted level adds (½ − 0)Δt q_t + O(Δt²) to the truncation error for θ = ½, and hence that the observed order with Δt ∝ Δx becomes 1.

Answer form: four derivations; (b) ends with an identity, (c) with formulas (5).

3. (Unfamiliar scenario: verifying an ODE integrator by manufactured solution)

A probe cools by radiation in vacuum: dT/dt = −k(T⁴ − T_a⁴), k = 2 × 10⁻¹¹ K⁻³ s⁻¹, T_a = 250 K, T(0) = (350 + s) K. You have written Heun's method (RK2: k₁ = f(T, t), k₂ = f(T + hk₁, t + h), T ← T + ½h(k₁ + k₂)) and want to verify it without an exact solution of the nonlinear equation.

(a) Manufacture the solution T_m(t) = T_a + (T(0) − T_a)e^{−t/τ}, τ = 500 s: write the source q_m(t) that makes dT/dt = −k(T⁴ − T_a⁴) + q_m(t) have T_m as its solution, and evaluate q_m(0) by hand. (b) Implement the modified ODE and Heun's method, integrate to t = 1000 s with n = 10, 20, 40, 80, 160 steps, tabulate |T_n − T_m| and the observed orders. (c) Plant a bug: evaluate k₂ at time t instead of t + h. Repeat (b). Explain the result with the truncation error of the stage. (d) Why does the test in (b) also verify the integrator for the unmodified cooling equation?

Answer form: one formula and one number, two tables, two short paragraphs.

4. (Numerical, uses your code: your own manufactured solution)

Build the manufactured solution u_m = (20 + s) sin(πx/L)(1 − e^{−t/τ}) + s·x(L − x)/L²·sin(2πt/τ), τ = 200 s, with a loss coefficient β = s × 10⁻⁴ s⁻¹ and the lesson's α and L.

(a) Let manufactured_source build q_m; check one value of q_m by hand (at x = 0.1 m, t = 50 s). (b) Run the Crank–Nicolson convergence study on 25–400 cells with Δt = 300 s/nx; report the errors and observed orders. Repeat with bug="source_time". (c) Run the heater problem with your β on 25, 50, 100 cells, report the temperature at the heater at 600 s, the observed order, the extrapolated value and the GCI, check against an 800-cell run, and compute the refinement needed for a GCI of 0.01 %.

Answer form: one hand value, two convergence tables, one Richardson table with a check.

5. (Numerical, uses your code: validation with your own data set)

Generate synthetic data with synthetic_measurements(HeatSetup(), seed=s) (label it synthetic in everything you write).

(a) Evaluate the lossless model on 200 cells with Δt = 1 s at the sensors and report the validation metrics (points within 2u_val, reduced χ², largest |E|/u_val, E at t = 600 s). Take u_num from the lesson's GCI. (b) Fit β on the first five sampling times only (hold out t = 600 s). Report β̂ and the hold-out row of E/u_val. Then fit on all six and report β̂ with its standard uncertainty from the curvature of χ² (σ_β = √(2/χ²'')). How many standard uncertainties is the truth away? (c) Convert β̂ to a convective coefficient h for a 10 mm square aluminium section (ρ = 2700 kg/m³, c = 900 J/kg K). Then predict the heater temperature at 1200 s with β̂, with β_true and with β = 0. Which of the three numbers would you put in a design report, with what uncertainty, and what sentence must accompany it?

Answer form: one metrics table, two fits with uncertainties, three predictions and two sentences.

6. (Judgment: a vendor says "validated")

A CFD vendor states that its code is "validated for internal flows" and shows a plot in which its pressure-drop prediction for a duct lies within 3 % of a textbook correlation. Your project needs the heat-transfer coefficient in a cooling channel with a 90° bend to ±10 % for a thermal margin that decides whether a battery pack needs a second fan.

(a) Using the NASA-STD-7009 vocabulary, say what the vendor's plot does and does not demonstrate, and list the three pieces of verification evidence you would ask for first. (b) Write three verifiable requirements (Appendix C style: one statement, a measurable criterion, a method) for the simulation you would run. (c) The vendor's grid study on your geometry gives heat-transfer coefficients of 412, 395 and 390 W/m²K on grids refined by r = 1.5. Compute the observed order and the GCI; is the fine grid adequate for ±10 %? For ±2 %? (d) The computed coefficient agrees with a single test point to 4 %, but the test's own uncertainty is 8 %. Write the two-sentence statement for the design review, including what the agreement proves and what it does not.

Answer form: four short paragraphs, each with at least one number.

Get the code

Clone the repository once, write your code in starter/main.py, then run the tests from the repository root.

pytest curriculum/phase-03/lesson-18-verification-and-validation

To run the same tests against the reference solution instead:

AEFS_IMPL=solution pytest curriculum/phase-03/lesson-18-verification-and-validation

Found a mistake? Every page is built from the Markdown in the repository; edit it on GitHub.