Skip to content
Tech Interview Prep

Top 100 Simulation Engineer Interview Questions and Answers

The questions most likely to come up in your Simulation Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.

Curated: · Written: · Reviewed: —

Reviewed 0Review pending 100

100 questions · Flow follows Relevance until this set has a learning order.

Q&A-1A CFD run takes 10 minutes on a coarse mesh and 5 hours on a mesh twice as fine. How do you decide whether the finer mesh is worth it for ranking three designs?

The 90-second answer

I compare the two meshes on the quantity the decision uses, not on the mesh itself. If the three designs differ by 3% in drag and the coarse mesh already separates them by more than its own numerical error, the fine mesh buys nothing. If the coarse mesh error is the same size as the gap between designs, the ranking is noise and I need the finer mesh, or a cheaper way to reduce the error.

The mechanism is the exchange rate between cost and error. In 3D, halving the mesh spacing multiplies the cell count by about 8. For a steady solver the cost per run rises by roughly that factor. Error falls by 2^p, where p is the observed order of accuracy. For a nominally second-order scheme, p is near 2 in the asymptotic range, so error falls by about 4. That is the trade: about 8 times the compute for about 4 times less discretisation error. Whether that is worth it depends on the decision margin.

Worked example

Suppose the study ranks three winglet designs by drag coefficient Cd at cruise. The best and second best differ by 3%, about 0.0009 on a Cd of 0.0300. The coarse mesh runs in 10 minutes. The fine mesh, spacing halved, runs in about 80 minutes for a steady solve, and in this hypothetical case let us say 5 hours because the fine mesh also needs a smaller time step for unsteady shedding. I run three meshes and check convergence before I trust any of them.

MeshSpacing hRuntimeCdChange from previous
Coarse1.010 min0.0320-
Medium0.580 min0.0305-0.0015
Fine0.255 h0.0301-0.0004

The changes shrink by a factor of about 3.75, close to the factor of 4 expected for p = 2. That tells me the solutions are in the asymptotic range and the remaining error on the fine mesh is small. The Richardson extrapolated value is:

Python
# Python 3.11
import math

q1, q2, q3 = 0.0320, 0.0305, 0.0301  # Cd on coarse, medium, fine
r = 2.0
p = math.log((q1 - q2) / (q2 - q3)) / math.log(r)
q_ext = q3 + (q3 - q2) / (r**p - 1)
print(f"observed order p = {p:.2f}")
print(f"extrapolated Cd = {q_ext:.5f}")
print(f"fine mesh error estimate = {abs(q_ext - q3):.5f}")

This gives p = 1.91 and an extrapolated Cd of 0.03003, so the fine mesh error estimate is about 0.00007, or 0.2% of Cd. The medium mesh error estimate, from the same calculation, is about 0.0005, or 1.6%. Now the decision is arithmetic. The gap between designs is 0.0009. The medium mesh error of 0.0005 is more than half that gap, so ranking on the medium mesh alone is risky. The fine mesh error of 0.00007 is well below the gap, so the fine mesh can rank them. If the gap had been 5% instead of 3%, the medium mesh would have been enough and I would not spend 5 hours per run.

What I check before accepting the fine mesh

First, that p is positive and near the formal order. If p came out near zero, the change between meshes is not shrinking, which means something else dominates, such as an unconverged residual, a sensitive boundary condition, or a flow feature the mesh does not resolve at any of these spacings. Refining further then wastes compute. I would fix the cause, for example tightening the residual target or refining locally near the winglet tip where the vortex forms, rather than refining everywhere.

Second, that the error estimate applies to the quantity I rank on. Drag can converge while a derived quantity such as pitching moment converges more slowly, because it depends on the pressure distribution in a small region. I run the same three mesh calculation on every quantity that feeds the decision. If moment needs the fine mesh and drag does not, the requirement says that, and I run the sweep on the medium mesh for drag and reserve the fine mesh for the final design.

Third, that the bias is consistent across the three designs. If the medium mesh overpredicts drag for one design and underpredicts it for another, the errors do not cancel in the ranking even if each error looks small. I check the sign of the change from medium to fine for each design. Same sign and similar size means the ranking is stable. Mixed signs means I need the fine mesh for all three, or a finer medium mesh.

The line I hold in the interview is this: the finer mesh is worth it when its error estimate is comfortably below the gap between the options being ranked, and not before. Cost scaling sets the price, the convergence calculation sets the error, and the decision margin sets the requirement.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-2What is the global accuracy order of explicit Euler, and how does it compare with RK4?

The 90-second answer

Explicit Euler is first order. RK4 is fourth order. That means global error scales as h for Euler and as h⁴ for RK4, where h is the step size. Halving h roughly halves Euler's error and cuts RK4's error by about a factor of 16. RK4 pays for that with four derivative evaluations per step instead of one.

What the orders mean

Euler advances with the slope at the start of the step:

y_{n+1} = y_n + h f(t_n, y_n)

Its local truncation error is O(h²), which accumulates to a global error of O(h).

RK4 samples the slope four times, at the start, twice in the middle, and at the end, then takes a weighted average:

k1 = f(t_n, y_n) k2 = f(t_n + h/2, y_n + h k1/2) k3 = f(t_n + h/2, y_n + h k2/2) k4 = f(t_n + h, y_n + h k3) y_{n+1} = y_n + h (k1 + 2k2 + 2k3 + k4) / 6

Local error is O(h⁵), global error O(h⁴).

Worked trace

Take y' = -y, y(0) = 1, h = 0.5. The exact value after one step is e^{-0.5} = 0.60653.

Methody after 1 stepError
Euler0.500000.10653
RK40.606770.00024

One RK4 step lands about 400 times closer here, for four evaluations. That gap grows as h shrinks, which is why RK4 usually lets you take far larger steps for a target tolerance.

Python
# Python 3, checked against y' = -y, y0 = 1, h = 0.5
def euler(f, y, h):
    return y + h * f(y)

def rk4(f, y, h):
    k1 = f(y)
    k2 = f(y + 0.5 * h * k1)
    k3 = f(y + 0.5 * h * k2)
    k4 = f(y + h * k3)
    return y + h * (k1 + 2 * k2 + 2 * k3 + k4) / 6

f = lambda y: -y
print(euler(f, 1.0, 0.5))  # 0.5
print(rk4(f, 1.0, 0.5))    # 0.6067708333333334

Stability, and the stiff trap

PropertyExplicit EulerRK4
Global order14
Derivative evaluations per step14
Stable interval on real axis, z = λh-2 < z < 0-2.785 < z < 0
Stable interval on imaginary axisnone, except z = 0about -2.83i < z < 2.83i

Both are explicit, so both fail on stiff problems. If λ = -10,000 (a fast decaying mode), Euler needs h < 0.0002 and RK4 needs h < 0.0002785. RK4 buys you 39% more step size and charges you 300% more evaluations. When the step is dictated by a fast mode you do not care about, neither method is the answer. That is the case for an implicit method such as backward Euler or a BDF solver, where stability does not force h down to the fastest timescale.

The imaginary axis matters for oscillators. Euler amplifies a pure oscillation at every step, since |1 + iy| > 1 for any y ≠ 0, so energy grows steadily. RK4 keeps |R(iy)| ≤ 1 up to about 2.83, so it preserves oscillations far better over long runs.

When Euler still wins

Pick Euler when the step count is already fixed by something else, such as a fixed-rate sensor loop or a real-time budget where one evaluation per step is the only thing that fits. It also wins for quick prototyping and for checking signs and magnitudes before investing in a higher order scheme. If you are free to choose h for accuracy, RK4 almost always reaches a given tolerance with fewer total evaluations, despite the factor of four per step.

A common failure mode is running Euler with h chosen for accuracy on the slow dynamics and watching a fast mode blow up after a few hundred steps. The fix is to check z = λh for the fastest eigenvalue in the Jacobian, not just the error estimate.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-3Walk me through how you would design a mesh convergence study for a CFD quantity of interest and use Richardson extrapolation to estimate its continuum value and uncertainty?

The 90-second answer

I fix the quantity of interest (QoI) first, for example drag coefficient, peak stress, or outlet mass flow, and I refine systematically until that QoI, not the residual, stops changing in a predictable way. I use at least three meshes with a constant refinement ratio r = h_coarse / h_fine of 1.3 to 1.5, keep geometry, boundary conditions, physics models and solver settings identical, and tighten iterative convergence well below the expected discretisation error. Then I check whether the three QoI values are in the asymptotic range, estimate the observed order p, extrapolate to h = 0 with Richardson extrapolation, and report the extrapolated value with a Grid Convergence Index (GCI) band. If the sequence is oscillatory or diverging, I do not extrapolate. I refine further or fix the mesh quality problem that caused it.

Design choices that decide whether the numbers mean anything

Systematic refinement means each mesh is generated by the same procedure with a smaller target size, not three hand-tuned meshes. I keep element type, topology family and grading strategy consistent, and I check skewness, aspect ratio and y+ (for wall-bounded flow) on every level. A sudden jump in max skewness from 0.85 to 0.97 between levels can change the QoI more than refinement does.

Iterative error is the usual trap. If the solver stops at a residual of 1e-4 and the QoI is still drifting by 0.5% between iterations, a 0.3% mesh-to-mesh change is noise. I converge until the QoI monitor varies by less than about one tenth of the expected discretisation change, often 1e-6 relative residual for steady RANS, and I record iterations and final residual per mesh.

I also separate global from local refinement. Uniform refinement of a whole car body or turbine blade is expensive and slow to reach the asymptotic range. Local refinement around a separation point, shock or stress concentration reaches it sooner, but then r is not uniform and classical Richardson extrapolation on a single h is not strictly valid. In that case I refine the critical region systematically, keep the far field fixed, and treat the extrapolation as an estimate with a wider uncertainty band, or I run one globally refined family for the extrapolation and use the locally refined mesh for production.

Worked example (hypothetical figures)

Three meshes, r = 1.5, QoI = drag coefficient:

MeshCellsh (relative)QoI f
Coarse (3)0.8 M1.001.200
Medium (2)2.7 M0.6671.280
Fine (1)6.1 M0.4441.320

Monotonic ratio R = (f2 - f1) / (f3 - f2) = (-0.040) / (-0.080) = 0.5. Since 0 < R < 1, convergence is monotonic, a necessary condition for extrapolation.

Observed order:

p = ln(|f3 - f2| / |f2 - f1|) / ln(r) = ln(2.0) / ln(1.5) = 1.71

That is plausible for a nominally second-order scheme on an unstructured mesh, where the effective order is often below 2. If p came out at 0.4 or 3.5, I would suspect non-asymptotic behaviour or a mesh defect rather than celebrate a high order. Note that r^p = 2.0 here by construction, since p was derived from a ratio of 2.0.

Richardson extrapolation:

f_ext = f1 + (f1 - f2) / (r^p - 1) = 1.320 + 0.040 / (2.0 - 1) = 1.360

Fine-grid GCI with safety factor Fs = 1.25 for three grids:

GCI_fine = Fs * |(f1 - f2) / f1| / (r^p - 1) = 1.25 * 0.0303 / 1.0 = 3.8%

So I would report drag as 1.360 +/- 3.8%, with the fine mesh at 1.320 sitting about 2.9% below the extrapolated value. The medium-grid GCI is 1.25 * |(1.280 - 1.200) / 1.280| / 1.0 = 7.8%, and GCI_fine is close to GCI_medium / r^p = 3.9%, which is the consistency check that the grids are near the asymptotic range.

Python
import math

f1, f2, f3 = 1.320, 1.280, 1.200  # fine, medium, coarse
r = 1.5
p = math.log(abs(f3 - f2) / abs(f2 - f1)) / math.log(r)
f_ext = f1 + (f1 - f2) / (r**p - 1)
gci_fine = 1.25 * abs((f1 - f2) / f1) / (r**p - 1)
print(f"p={p:.2f}  f_ext={f_ext:.4f}  GCI_fine={gci_fine*100:.1f}%")
# p=1.71  f_ext=1.3600  GCI_fine=3.8%

Failure modes I check before trusting the extrapolation

Oscillatory convergence, where R < 0, means the QoI jumps around the limit. Extrapolation then amplifies noise. I add a fourth mesh and use the oscillatory GCI based on the spread of the last three values, or I find the cause, often a limiter, a contact patch, or a mesh that resolves a feature on one level only.

Divergence, R > 1, means refinement makes the answer worse. That points to a bad boundary condition, an unstable scheme, or a mesh quality collapse, not to a need for more cells.

A p far from the formal order with a small GCI is also a warning. It can happen when the QoI is dominated by a singularity, such as a sharp trailing edge, where convergence is genuinely slow. Then the honest answer is a larger uncertainty band and a note that the production mesh needs local refinement at that feature, not a claim of 0.2% accuracy.

Finally, I never extrapolate a QoI that is not smooth in h. Integrated forces and averaged fluxes usually behave well. A single point maximum stress at a re-entrant corner may not converge at all, and for that QoI I report the mesh trend and the location of the maximum instead of a Richardson value.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-4A bracket is bolted through four holes to a plate and loaded at its tip. How would you set the boundary conditions, and what changes if you fix all four holes instead of just one?

The 90-second answer

For a linear static model, constrain only what the hardware constrains. The bracket is held by four bolts, so the bolted face cannot translate away from the plate. It can still bend a little between bolts, and the holes can bear unevenly as the bracket tries to rotate under the tip load. Fixing one hole fully and guiding the others in the plane of the plate, or tying the whole face to a remote point, captures that. Fixing all four holes in every direction removes deformation between the bolts and gives the load a second, artificial path to ground.

How I set it up

I start with the load path. Tip load enters at the end, travels through the bracket arm, and leaves through the bolted face into the plate. The constraint should sit on that exit face and allow the motion the joint allows.

ApproachWhat is constrainedEffect on the model
One hole fixed, other holes guided in planeTranslation normal to plate held at all holes, in-plane motion held at one holeRemoves rigid body motion, lets the face bend between bolts
All four holes fully fixedAll translations and rotations zero at each holeFace cannot bend, each hole becomes a separate support
Remote point tied to bolted faceFace tied to one point, point fixedSpreads reaction over the face, face can still deform if the tie is RBE3 style

The first approach is usually the closest for a bolted bracket. The third is useful when the mating plate is stiff and the load is applied through a single bolt pattern. A rigid tie (RBE2 in many solvers) would stiffen the face, so I avoid it for a deformable bracket.

Tip load enters Arm carries bending to root Bolted face transfers load to plate Constraint only on bolted face Check reactions sum to tip load

What changes when all four holes are fixed

Take a simple case with real figures. Arm length 200 mm, tip load 5 kN, root section modulus 12,000 mm3. Root moment is 5 kN x 0.2 m = 1.0 kN m, so bending stress at the root fillet is about 83 MPa. A beam estimate for tip deflection, with E = 200 GPa and I = 2.4 x 10^-6 m4, gives roughly 1.0 mm.

ModelTip deflectionPeak stressWhere the peak sits
One hole fixed, others guided1.1 mm88 MPaRoot fillet, settles under refinement
All four holes fixed0.4 mm210 MPaEdge of a fixed hole, climbs under refinement

Deflection drops by more than half because the fixed holes act as four built-in ends. The bracket looks stiffer than the real part. Peak stress more than doubles and moves to the constraint. That peak does not converge: a fixed node forces displacement to zero at a point, so strain rises as elements shrink around it. The fillet stress, which controls fatigue in the real bracket, is hidden under that artefact.

Reactions tell the same story. In both models the vertical reactions sum to 5 kN, as equilibrium requires. With all holes fixed, the reaction splits unevenly, with the holes nearest the load path carrying most of it and the far holes carrying little. That split depends on mesh and hole stiffness in the model, not on bolt preload or plate flexibility in the hardware.

Checks before I trust either model

First, equilibrium. I sum reactions in Python after export and compare with applied loads.

Python
# reactions.csv: node, fx, fy, fz  (N), applied tip load = -5000 N in y
import csv
fy = sum(float(r["fy"]) for r in csv.DictReader(open("reactions.csv")))
print(fy)  # expect approx +5000 N; a large gap means a load was applied to a fixed node

Second, deflection against the beam estimate. A result of 0.4 mm against a 1.0 mm estimate is a flag that constraints are carrying load.

Third, refinement at the fillet. If fillet stress settles within a few percent while hole-edge stress keeps climbing, I report the fillet value and treat the hole edge as a modelling artefact. I then replace the four fixed holes with the guided-hole setup and rerun.

Fixing all four holes is not wrong because the solver complains. It solves cleanly and returns a stiffer part with a misleading peak. The guided setup costs a little more thought at setup and gives a deflection and stress I can defend against a hand calc.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-5For a 2 mm sheet-metal bracket loaded in bending with a bolt hole at the root, would you model it with shell or solid elements, and what does each choice miss?

The 90-second answer

Use shells for the global bracket and a solid submodel at the bolt hole. A 2 mm wall is thin relative to its in-plane size, so a shell captures membrane and bending stress through the thickness with one layer of elements and a fraction of the cost of a solid mesh. It does not capture the local bearing stress where the bolt bears on the hole, or the through-thickness stress at that contact. A solid mesh does capture those, but only if you put at least two or three elements through the 2 mm thickness and use quadratic elements. One layer of linear solids through a bending-dominated wall is stiffer than the real part and gives a misleading peak stress.

Beam elements are not in contention here. The bracket is a plate, not a slender member, and a beam would give you a section force with no stress distribution across the width or around the hole.

ChoiceWhat it captures wellWhat it misses or costsTypical element
ShellMembrane and bending stress, deflection, buckling mode shapeBolt bearing, through-thickness normal stress, contact pressure detailS4, or S8 for curved panels
Solid hexBearing, through-thickness stress, contact, local yieldingNeeds 2 to 3 layers through 2 mm, mesh quality matters, higher DOF countC3D20 preferred, C3D8 only with refinement
Solid tetSame local physics as hex, meshes the hole and fillets easilyC3D4 is too stiff in bending, C3D10 needed for accuracyC3D10

Why the shell works for most of the part

A shell element represents the wall by its mid-surface plus a thickness. Bending stress is recovered from the curvature and the distance from the mid-surface, which is exactly the physics that dominates a thin panel away from concentrated contact. With a 2 mm thickness and a panel roughly 80 mm by 60 mm, the thickness to span ratio is about 1 to 30. That is well inside shell territory. You can mesh the whole bracket with, say, 4,000 S8 elements and get a converged bending stress at the root fillet, provided the mesh is refined there and the mid-surface is placed correctly.

Placement matters. If you build the shell on the outer face instead of the mid-surface, the bending stiffness shifts and the stress at the outer fibre is offset by roughly half the thickness times the curvature. In a scripted workflow, build the geometry on the mid-surface or use the shell offset option deliberately, then check the section points reported by the solver against a simple plate bending estimate for one load case.

Where the shell stops being enough

At the bolt hole the load is not distributed bending. It is contact over a small arc, with bearing stress that varies through the thickness and a stress concentration around the hole edge. A shell with a rigid or coupled reference point will smear that load over the hole edge and under-report the peak. The error is local, which is why a submodel is the standard fix: cut the global shell model a few hole diameters away from the bolt, drive the cut boundary with the global displacements, and remesh that region with solids.

Python
# Abaqus 2024 Python, element assignment for the two-zone model
# Global: S8 shells. Submodel: C3D20 solids, 3 elements through 2 mm
bracket = model.parts["Bracket"]
bracket.setElementType(elemType="S8", secondOrder=True)

submodel = model.parts["BoltSubmodel"]
submodel.setElementType(elemType="C3D20", secondOrder=True)
# Seed the thickness direction with 3 elements (about 0.67 mm each)
submodel.seedPart(size=1.5, deviationFactor=0.1, minSizeFactor=0.1)

The arithmetic shows why you do not solid-mesh the whole bracket. A solid mesh with 3 layers through the thickness and a 1.5 mm in-plane seed on an 80 by 60 mm panel needs roughly 3,200 elements per layer times 3 layers, about 10,000 C3D20 elements and 60,000 nodes. The shell equivalent is about 2,500 S8 elements and 10,000 nodes. The solid model is not wrong, it is just expensive everywhere for a local effect that only exists near the bolt.

Global model: shell, S8 Check bending stress and deflection Cut submodel around bolt hole Solid submodel: C3D20, 3 through thickness Report bearing and hole-edge stress from submodel

Failure modes to check

A single layer of C3D4 or C3D8 through the wall will look converged on deflection while the stress stays low, because linear elements cannot represent the linear strain variation through the thickness in bending. If you must use solids globally, use quadratic elements and confirm with a mesh study on peak stress, not displacement. For shells, check element warpage and aspect ratio near the hole, and confirm the thickness and offset in the property definition, since a default thickness of 1 mm on a 2 mm part halves the bending stiffness. For the submodel, check that the cut boundary is far enough from the hole that the driven displacements do not artificially stiffen the contact zone, typically at least three hole diameters away.

The decision rule is simple to state and worth defending in the interview: shells for the load path, solids for the contact, and never a linear solid through a thin wall in bending.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-6In penalty-based contact, what happens to surface penetration as penalty stiffness increases?

The 90-second answer

Penetration falls as penalty stiffness rises. In a penalty formulation the contact surface is not a hard wall. It is a one sided spring. If the normal gap is $g_N$, negative when the surfaces overlap, the normal force is $F_N = k_p \langle -g_N \rangle$, where the brackets mean the force is zero after separation. Rearranged for a given contact force, penetration is $\delta = F_N / k_p$. Double $k_p$ and, for the same force, the overlap halves. That inverse relationship is the whole rule.

Friction follows from the same force. Coulomb friction caps the tangential force at $|F_T| \le \mu F_N$, so a stiffer penalty that produces the required $F_N$ at smaller penetration also produces the correct friction limit. A soft penalty underpredicts $F_N$ at a given overlap and therefore lets a joint slip too early.

Worked numbers

Take a contact force of 1,000 N, a plausible load for a bolted joint or a small impact contact in a structural model.

Penalty stiffness $k_p$ (N/m)Penetration $\delta = F_N/k_p$
$10^5$10 mm
$10^6$1 mm
$10^7$0.1 mm
$10^8$0.01 mm

If the local elements are 2 mm across, the first row means the surfaces have passed through each other by five element widths. The last row is geometrically negligible. The practical choice is the smallest $k_p$ that keeps penetration to a small fraction of the element size, commonly 1 to 5 percent, because raising $k_p$ further buys little geometry and costs solver effort.

Python
# Penalty contact force, checked against Python 3.12
def penalty_force(gap, k_p, mu):
    if gap >= 0.0:
        return 0.0, 0.0  # separated: no normal force, no friction
    f_n = k_p * (-gap)  # gap is negative in penetration
    f_t_max = mu * f_n  # Coulomb limit on tangential force
    return f_n, f_t_max

# Same 1,000 N force, two stiffnesses
for k_p in (1e6, 1e7):
    print(k_p, 1000.0 / k_p)  # 0.001 m, then 0.0001 m

Why not simply make it very large

The spring frequency scales as $\omega \approx \sqrt{k_p/m}$ for a nodal mass $m$. In an explicit solver the stable time step scales as $2/\omega$, so raising $k_p$ by a factor of 100 cuts the step by a factor of 10. In an implicit solver the same stiffness worsens conditioning and can cause contact nodes to chatter between open and closed states. Those are follow up costs, not a change to the rule above. Penetration still decreases monotonically with $k_p$; the question in practice is how much penetration your quantity of interest can tolerate before the extra stiffness stops paying for itself.

A quick check in a run is to plot maximum penetration against time and rerun with $k_p$ halved and doubled. If the force history or displacement changes by more than your tolerance, the penalty, not the material, is controlling the answer.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-7For a notched 6061-T6 bracket that yields locally under cyclic overload, how do you choose between von Mises with isotropic versus kinematic hardening, and calibrate it so the FEA does not overpredict shakedown?

The 90-second answer

For a ductile aluminium bracket I start with J2 (von Mises) flow theory with a combined hardening law, and I calibrate it from both monotonic and reversed loading. Isotropic hardening alone will make the model predict shakedown under cyclic overload when the real part ratchets, because it expands the yield surface symmetrically and erases the Bauschinger effect. Kinematic hardening alone misses cyclic hardening saturation. Combined hardening captures both, and that distinction decides whether the FEA is conservative or dangerously optimistic.

Yield criterion: why J2, and when to leave it

J2 assumes yielding starts when the deviatoric stress reaches a threshold, independent of hydrostatic pressure. For 6061-T6 that is a good first model: yield is shear driven and pressure has little effect in the range of a bracket (triaxiality roughly -0.3 to 0.6). Tresca gives a yield surface up to 15% smaller in pure shear, so it is conservative for a shear dominated fillet, but it has corners that cause numerical trouble in return mapping and it still assumes isotropy. I would switch only with evidence: Hill 1948 if the bracket is formed sheet with measured r-values and directional yield differences above about 5%, Drucker-Prager or a pressure modified criterion if the material is a polymer, cast iron or soil where hydrostatic stress shifts yield. Using Drucker-Prager for aluminium without that evidence adds a pressure term the tests do not support.

Hardening: the mechanism that matters under reversal

Write the yield function as f = sqrt(2/3 * (s - alpha):(s - alpha)) - (sigma_y + R), where s is deviatoric stress, alpha is the back stress and R is the isotropic hardening variable. Isotropic hardening grows R, so the surface expands. Kinematic hardening evolves alpha, so the surface translates. Combined hardening does both.

ModelMonotonic tensionReversed loadingCyclic loopsTypical failure in FEA
Isotropic onlyFits wellOverpredicts reverse yield by 30 to 50%Loops widen each cyclePredicts shakedown, misses ratcheting
Kinematic only (linear Prager)Fits initial slopeCaptures Bauschinger effectLoops stabilise too early, no saturationUnderpredicts cyclic hardening, overpredicts plastic strain range
Combined (Chaboche style, 2 to 3 back stresses)Fits with Voce termCaptures translation and expansionCaptures saturation and mean stress relaxationNeeds more calibration data, risk of overfitting

For the bracket I would use one isotropic Voce term plus two kinematic terms, a fast one for the initial transient and a slow one for long term ratcheting. That is the standard Chaboche structure and it needs only monotonic plus a few strain controlled cycles to identify.

Calibration with real numbers

Take a hypothetical but typical 6061-T6 calibration: sigma_y = 276 MPa, ultimate 310 MPa. Fit the monotonic curve with a Voce law, sigma = sigma_y + R * (1 - exp(-b * ep)). With R = 85 MPa and b = 18, at ep = 0.02 the flow stress is 276 + 85 * (1 - exp(-0.36)) = 276 + 85 * 0.302 = 302 MPa. That matches the measured curve near necking. Then fit the kinematic terms from tension compression tests at strain amplitude 0.004. The reverse yield drop of about 60 MPa after 2% prestrain fixes the first back stress modulus C1 and recovery rate gamma1. Without that reversed test, C1 is unidentifiable and any value the optimiser returns is a guess.

In the solver the update is a backward Euler radial return. For J2 the trial deviatoric stress is scaled back to the yield surface, which gives a closed form plastic multiplier and a consistent tangent. A minimal check in Python shows the logic:

Python
import numpy as np

def j2_return(s_trial, alpha, sigma_y, R, G):
    # s_trial, alpha: deviatoric tensors (3x3), G: shear modulus
    xi = s_trial - alpha
    xi_eq = np.sqrt(1.5 * np.sum(xi * xi))
    f_trial = xi_eq - (sigma_y + R)
    if f_trial <= 0:
        return s_trial, 0.0
    dgamma = f_trial / (3.0 * G)  # plastic multiplier for radial return
    s_new = s_trial - 2.0 * G * dgamma * (xi / xi_eq) * 1.5
    return s_new, dgamma

If the code returns a negative multiplier or the tangent stiffness is taken as elastic, Newton iterations stall at the fillet where plastic strain concentrates. That is a common failure mode I check by plotting equivalent plastic strain per increment, not just final displacement.

Failure modes I would name in the interview

First, mesh sensitivity at the notch. Local yielding is driven by the stress concentration, so a coarse mesh underpredicts peak stress and delays predicted yielding by one load cycle. I refine until the plastic zone size changes by less than 10% between meshes. Second, large rotation and necking. J2 with small strain formulation overpredicts load after about 5% local strain, so for a bracket that sees that level I move to a finite strain formulation or stop the analysis at necking onset. Third, ignoring anisotropy in a formed part. If the bracket is bent sheet, the isotropic model can be 8% high in one direction and 8% low in the transverse direction, which shifts the predicted crack initiation site. A quick directional tensile test settles that question before I add Hill parameters.

The decision rule I state out loud: monotonic data alone justifies isotropic hardening for a single overload check, reversed data is required before I claim anything about cyclic life, ratcheting or shakedown.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-8For steady drag ranking of a car with separation at the rear window, why does k-omega SST usually predict separation better than k-epsilon, and when would you switch to LES instead?

The 90-second answer

For steady drag ranking on a car with separation at the rear window, I would use RANS with k-omega SST. RANS solves for the mean flow and models the Reynolds stresses, so a steady drag value comes out in hours on a few million cells. k-epsilon is the cheaper classic, but it tends to keep the boundary layer attached too long in an adverse pressure gradient. That moves the predicted separation point downstream and can underpredict drag on a bluff rear end. SST usually places separation closer to experiment because its near-wall form handles deceleration better. I would switch to LES only if the question changes to the unsteady wake itself, such as shedding frequency or buffeting. LES resolves the large eddies and models only the small ones, so it captures that dynamics, at roughly 20 to 50 times the cost of RANS.

Why k-epsilon struggles at the rear window

Both k-epsilon and SST use the Boussinesq assumption. The modelled Reynolds stress is proportional to the mean strain rate through a scalar eddy viscosity. The difference is how that viscosity is built and how it behaves near the wall.

k-epsilon was built for high Reynolds number free shear flow. Near the wall it needs damping functions or wall functions, and the first cell height decides which regime the solver thinks it is in. In the decelerating flow over the rear window, the real boundary layer thickens and the turbulent stress no longer aligns cleanly with the mean strain. k-epsilon keeps the eddy viscosity high in that zone. A high eddy viscosity diffuses momentum toward the wall, which delays separation. The computed recirculation bubble then starts too far back, the wake is narrower, and drag comes out low.

SST blends two closures. Close to the wall it uses k-omega, which integrates to the wall without damping functions and responds more directly to the pressure gradient in the boundary layer. Away from the wall it blends to k-epsilon, which is more stable in the free stream and wake. The practical result is a separation point that moves less when the first cell height changes, provided y+ is below 1 and the boundary layer has 15 to 20 cells across it.

ModelNear-wall formSeparation behaviourCost for a car, estimateMain risk
RANS k-epsilonWall functions or damping functions, y+ 30 to 300 typicalOften delayed in adverse pressure gradient2 to 5 million cells, about 2 h on 256 coresDrag error of 10 to 20 percent on separated bluff bodies
RANS k-omega SSTk-omega to the wall, y+ below 1Usually closer to measured separation3 to 8 million cells, about 3 to 4 h on 256 coresStill gives only the mean, so unsteady wake content is missing
LESResolved eddies, y+ near 1Captures unsteady separation and shedding50 to 200 million cells, 40 to 100 hMean drag needs many flow-through times to converge

The LES trade-off in numbers

Take the SST baseline as 5 million cells and 2 hours. LES for the same car needs resolution in the wake as well as at the wall, so 100 million cells is a realistic planning figure. The cell count factor is 20. The timestep also shrinks because the Courant number for resolved eddies must stay near 1, while a steady RANS solver has no such limit. Multiplying by a further factor of 2.5 for the timestep gives about 100 hours, before any averaging.

Python
# Python 3.11, planning estimate only
rans_cells = 5e6
rans_hours = 2.0
les_cells = 100e6
les_hours = rans_hours * (les_cells / rans_cells) * 2.5
print(f"{les_hours:.0f} h")  # 100 h

That cost buys a different answer, not a better version of the same answer. If the design decision is which rear-window angle gives lower mean drag, SST on three meshes answers it and the mesh study shows whether drag has settled. If the decision depends on a 25 Hz wake oscillation exciting a panel, SST cannot produce that frequency at any mesh density, and LES becomes the right tool despite the cost.

What I would check before trusting either number

For SST, I would check y+ over the roof and rear window, then run three meshes and watch drag and separation location rather than residuals. If drag still moves by more than about 1 percent between the two finest meshes, I would not rank designs yet.

For LES, I would check that more than 80 percent of the turbulent kinetic energy in the wake is resolved, and that the mean drag stops drifting when the sample length is doubled. A smooth drag trace from only two or three shedding cycles can look converged and still be off. That check is what separates a usable LES mean from an expensive guess.

What is needed? Mean drag, design ranking Wake frequency or buffeting RANS k-omega SST LES Mesh study on drag and separation Resolved energy and sample length

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-9How do you size the first near-wall cell and choose y+ for a turbulent CFD run, and how does that choice change with wall functions versus a resolved boundary layer?

The 90-second answer

Size the first cell from the wall shear you expect, not from the bulk mesh. Define $y^+ = y u_\tau / \nu$, where $u_\tau = \sqrt{\tau_w/\rho}$ is the friction velocity, $y$ is the distance from the wall to the first cell centre, and $\nu$ is the kinematic viscosity. If you resolve the viscous sublayer, target $y^+ \approx 1$ (accept 0.5 to 2) and put 15 to 30 cells across the boundary layer. If you use wall functions, target $y^+$ between 30 and 300, ideally 50 to 100, and keep the first cell centre in the log layer. Avoid $y^+$ between about 5 and 30. That buffer layer is neither viscous nor logarithmic, so both treatments lose accuracy there.

The catch is that $\tau_w$ is an output, not an input. You estimate it from a correlation or a coarse run, size the mesh, run, then check the actual $y^+$ distribution and resize if it has drifted.

Worked sizing, flat plate in air

Take a 1 m plate, $U = 20$ m/s, $\rho = 1.2$ kg/m$^3$, $\nu = 1.46\times10^{-5}$ m$^2$/s. Then $Re_x = Ux/\nu = 1.37\times10^6$, turbulent over most of the plate.

Local skin friction coefficient, turbulent flat plate: $C_f \approx 0.0592,Re_x^{-1/5} = 0.0088$. So $\tau_w = (C_f/2)\rho U^2 = 0.0044 \times 1.2 \times 400 = 2.1$ Pa, and $u_\tau = \sqrt{2.1/1.2} = 1.33$ m/s.

First cell centre height for a target $y^+$:

$y = y^+ \nu / u_\tau$

Target$y$ (centre)First cell height (approx. $2y$)Layers to cover $\delta \approx 22$ mm at growth 1.2
$y^+ = 1$0.011 mm0.022 mmabout 33
$y^+ = 50$0.55 mm1.1 mmabout 12

Boundary layer thickness from $\delta \approx 0.37x/Re_x^{1/5} = 22$ mm. The resolved mesh needs roughly three times the near-wall layers, and each layer is far thinner, so cell count and stiffness both rise. That is the price for accurate skin friction, heat transfer and separation prediction.

Python
# Python 3, checked against the numbers above
def first_cell_height(y_plus, nu, u_tau):
    """Return first cell height (m) for a target y+ at the cell centre."""
    y_centre = y_plus * nu / u_tau
    return 2.0 * y_centre

nu, u_tau = 1.46e-5, 1.33
for yp in (1, 50):
    print(yp, first_cell_height(yp, nu, u_tau) * 1e3, "mm")
# 1  0.022 mm
# 50 1.1 mm

Choosing between the two treatments

Wall resolved, $y^+ \approx 1$Wall function, $y^+ \approx 30$ to 300
Near-wall modelViscous sublayer solved directlyLog law assumed, sublayer modelled
Skin friction and heat transferAccurate if mesh and turbulence model hold upTypically 5 to 15% error, worse under pressure gradient
Separation, adverse pressure gradientPreferred, wall functions assume local equilibriumCan delay or suppress separation
CostHigh, small cells, small time step if transient, stiffLow, coarse near-wall mesh
SensitivitySensitive to $y^+$ drift where $\tau_w$ is lowSensitive to $y^+$ falling into the buffer layer

Automatic wall treatment, as in Fluent and OpenFOAM nutLowReWallFunction style blending, interpolates between the two based on local $y^+$. It helps when $\tau_w$ varies strongly over the surface, but it does not rescue a mesh whose first cell is an order of magnitude off. Treat it as insurance, not as a sizing strategy.

Failure modes I check in post-processing

  1. Buffer layer trap. Area-averaged $y^+$ of 40 can hide patches at 10 on the suction side where $\tau_w$ drops. Plot $y^+$ as a surface histogram and report the fraction of wall area in 5 to 30, not just the mean. More than a few percent there means resize.

  2. Growth ratio too aggressive. Above about 1.2 to 1.3 per layer, the turbulence model sees a stretched grid it was not calibrated for and the velocity profile kinks. Keep 1.1 to 1.2 in the boundary layer, and check orthogonality and skewness in the first few layers, since wall shear is computed from the wall-normal gradient.

  3. Sizing from the wrong $\tau_w$. A correlation for a smooth flat plate underpredicts $\tau_w$ on a rough or strongly curved surface and overpredicts it near separation. If the run shows $y^+$ systematically above target in one region, that region needs a thinner first cell, not a global remesh.

  4. Low $y^+$ everywhere by habit. Running $y^+ \approx 1$ with a high-$y^+$ turbulence model, or with wall functions still active, wastes cells and can degrade the solution. The mesh, the near-wall model and the turbulence model have to be chosen together.

Practical loop: estimate $C_f$, size the first cell, run a coarse check, extract $y^+$ and $C_f$ from the solution, adjust the first cell height by the ratio of target to actual $y^+$, and rerun. One iteration usually lands within 20% of target, which is close enough for the log law or the sublayer to behave as intended.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-10State the 6-DOF rigid-body equations of motion and how the inertia tensor enters them?

The 90-second answer

Write Newton-Euler about the centre of mass (COM), with all vectors expressed in a body-fixed frame whose origin is the COM:

m * (dv/dt + omega x v) = F
I * domega/dt + omega x (I * omega) = tau

Here v and omega are the COM velocity and angular velocity, F and tau are the resultant force and torque about the COM, and I is the 3x3 inertia tensor about the COM in the body frame. The dv/dt and domega/dt terms are derivatives of the body-frame components. The omega x v term appears because the body frame rotates, so the inertial acceleration of the COM is the body-frame derivative plus omega x v. The omega x (I * omega) term is the gyroscopic term. It appears for the same reason: I is constant in the body frame, but the frame itself rotates. In an inertial frame the translational equation is simply m * dv/dt = F, with no omega x v term, because v there is already the inertial velocity.

The inertia tensor comes from the mass distribution:

I = integral over body of ((r . r) * Identity3 - r * r^T) dm

where r is position relative to the COM. It is symmetric, so it has six independent components: Ixx, Iyy, Izz, Ixy, Ixz, Iyz. In principal axes the products of inertia vanish and I is diagonal. A simulator stores mass, COM position, and those six components, with the frame and origin stated explicitly.

Worked numbers

Take a solid box, m = 2 kg, sides 0.4 x 0.3 x 0.2 m, axes along its faces through the COM. For a box:

Ixx = m/12 * (y^2 + z^2), and cyclically for the other diagonal terms.

ComponentCalculationValue (kg m^2)
Ixx2/12 * (0.3^2 + 0.2^2)0.0217
Iyy2/12 * (0.4^2 + 0.2^2)0.0333
Izz2/12 * (0.4^2 + 0.3^2)0.0417
Ixy, Ixz, Iyzsymmetry about COM0

If the same box is modelled about a corner instead, the parallel axis theorem moves the tensor: I_corner = I_com + m * ((d . d) * Identity3 - d * d^T), where d is the vector from the COM to the new origin. A simulator that integrates about a non-COM origin must also carry the coupling between force and angular acceleration. Writing the COM equations and then pretending the origin is the COM is the common bug, and it shows up as a body that drifts or tumbles incorrectly under a pure torque.

Computing it from geometry

For a mesh or a set of point masses, the same integral becomes a sum. This is checked against Python 3.11 with NumPy:

Python
import numpy as np

def inertia_tensor(masses, positions):
    # positions: (N, 3), relative to the COM, in metres
    I = np.zeros((3, 3))
    for m, r in zip(masses, positions):
        I += m * (np.dot(r, r) * np.eye(3) - np.outer(r, r))
    return I

masses = np.array([1.0, 1.0])
positions = np.array([[0.2, 0.0, 0.0], [-0.2, 0.0, 0.0]])
print(inertia_tensor(masses, positions))
# [[0. 0. 0.]
#  [0. 0.08 0.]
#  [0. 0. 0.08]]

Two point masses on the x-axis give Ixx = 0, which is correct in the point-mass idealisation, and Iyy = Izz = 2 * 1 * 0.2^2 = 0.08 kg m^2.

Frames and failure modes

ChoiceWhat stays constantWhat to watch
Body frame at COMITorque and force must be rotated into this frame each step, and omega x v stays in the translational equation
World framemass onlyI_world = R * I_body * R^T changes every step, and the gyroscopic term is absorbed into that rotation
Spatial (4x4) inertiamass, COM offset, I togetherConvenient for articulated bodies, harder to audit by hand

Three checks catch most errors. First, I must be symmetric and positive definite, with principal moments satisfying the triangle inequalities for a real mass distribution, for example Ixx + Iyy >= Izz. A tensor that fails this came from a sign error in a product of inertia. Second, units are kg m^2 and the tensor is about a named point in a named frame. A CAD export often gives inertia about the CAD origin, in kg mm^2, and silently using it as COM inertia in SI units is a factor of 10^6 error. Third, dropping omega x (I * omega) is only safe for slow rotation or near-spherical inertia. For a satellite or a tumbling vehicle at omega = 10 rad/s with Izz - Ixx = 0.02 kg m^2, that term is 0.02 * 100 = 2 N m, which is not a rounding error. The interview follow-up is usually to ask what changes if the body is not rigid, and the answer is that I becomes time-varying and the single tensor is replaced by a mass distribution that must be recomputed or modelled with flexible modes.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-11Walk me through forward kinematics for a 6-DOF serial manipulator using DH parameters, including how you assign frames and compute the end-effector pose for a given joint vector?

The 90-second answer

Forward kinematics maps a joint vector q to the end-effector pose by chaining one homogeneous transform per joint. With standard Denavit-Hartenberg parameters, each link i is described by four numbers: link length a_i, link twist alpha_i, link offset d_i, and joint angle theta_i. The transform from frame i-1 to frame i is:

A_i = RotZ(theta_i) TransZ(d_i) TransX(a_i) RotX(alpha_i)

In matrix form, with c = cos(theta_i) and s = sin(theta_i):

| c | -s cos(alpha) | s sin(alpha) | a c | | s | c cos(alpha) | -c sin(alpha) | a s | | 0 | sin(alpha) | cos(alpha) | d | | 0 | 0 | 0 | 1 |

The end-effector pose is T_0n = A_1 A_2 ... A_n. The upper left 3x3 block is orientation, the upper right column is position in the base frame. For a 6-DOF arm I compute that product at every simulation step, then reuse the intermediate frames for the Jacobian and for transforming link inertias into the base frame. That reuse is the point. Recomputing frames separately for kinematics, dynamics, and rendering is how a simulation drifts out of sync with itself.

Frame assignment, where most errors live

Standard DH assigns z_i along joint axis i+1. Frame i has x_i along the common normal from z_{i-1} to z_i, and y_i completes a right-handed triad. Two choices decide whether the table is usable. First, pick the zero position before you pick any numbers. Theta_i = 0 must be a pose you can physically set and measure, otherwise every downstream calibration inherits an arbitrary offset. Second, decide standard versus modified DH and write it at the top of the table. Modified DH (Craig convention) attaches the frame to the proximal link, so the transform order and the meaning of a_i and alpha_i shift by one link. Mixing the two conventions is the classic silent bug: the code runs, the arm moves, and the simulated tool point is off by one link length in a direction that rotates with the base.

Worked trace: planar 2R arm

Take a two-link arm in a vertical plane, a1 = 0.40 m, a2 = 0.35 m, d1 = d2 = 0, alpha1 = alpha2 = 0. Set theta1 = 30 degrees and theta2 = -50 degrees, where theta2 is relative to link 1. With alpha = 0, each A_i reduces to a planar rotation plus a translation along the link.

StepCumulative angleContribution to xContribution to y
Link 130 deg0.40 cos(30) = 0.346 m0.40 sin(30) = 0.200 m
Link 230 - 50 = -20 deg0.35 cos(-20) = 0.329 m0.35 sin(-20) = -0.120 m
End effectororientation -20 deg0.675 m0.080 m

So T_02 has position (0.675, 0.080, 0) m and yaw -20 degrees. I would assert exactly that in a unit test, plus the zero pose (0.750, 0) and the folded pose theta2 = 180 degrees giving (-0.05, 0) at theta1 = 0. Those three cases catch sign errors, degree versus radian errors, and a transposed a_i.

Code

Checked against Python 3.12 with NumPy 2.0. The same function takes a full 6-row DH table for a spatial arm.

Python
import numpy as np

def dh_transform(theta, d, a, alpha):
    ct, st = np.cos(theta), np.sin(theta)
    ca, sa = np.cos(alpha), np.sin(alpha)
    return np.array([
        [ct, -st * ca,  st * sa, a * ct],
        [st,  ct * ca, -ct * sa, a * st],
        [0.0,      sa,       ca,      d],
        [0.0,      0.0,      0.0,     1.0],
    ])

def forward_kinematics(q, dh_table):
    T = np.eye(4)
    for theta, (d, a, alpha) in zip(q, dh_table):
        T = T @ dh_transform(theta, d, a, alpha)
    return T

# Planar 2R example above, angles in radians
dh = [(0.0, 0.40, 0.0), (0.0, 0.35, 0.0)]
T = forward_kinematics(np.deg2rad([30.0, -50.0]), dh)
print(T[:3, 3])  # [0.675, 0.080, 0.0]

Standard versus modified DH

AspectStandard DHModified DH
Frame i sits ondistal linkproximal link
Transform orderRotZ TransZ TransX RotXRotX TransX RotZ TransZ
a_i, alpha_i describelink ilink i-1
Common intextbooks, older controllersCraig's textbook, some robotics libraries

Neither is more correct. The failure mode is importing a table from a vendor datasheet or a URDF export without checking which convention the source used, then feeding it to the other matrix. In simulation I cross-check the DH chain against the URDF or CAD model at five random joint vectors and require agreement to 1e-6 m before any dynamics work starts.

Failure modes an interviewer will probe

Parallel consecutive joint axes make the common normal ill-defined. Two nominally parallel axes in a wrist or a parallelogram linkage can produce large, unstable jumps in d_i and theta_i from tiny geometric changes, and the calibrated table becomes unusable even though the physical arm is fine. The fix is to choose a convention for that pair (for example, fix d_i = 0 and let the offset live in theta) and document it, or switch that segment to a product-of-exponentials description where each joint axis is a screw in the base frame and no common normal is needed.

DH also assumes perfect revolute joints with fixed axes. Real gear eccentricity, encoder mounting error, and link deflection under load violate that. If FK accuracy matters below about 0.5 mm at the tool point, DH alone will not get there. You calibrate the four parameters per link plus joint offsets against measured poses, typically with a laser tracker or a CMM, and you report the residual. A residual above 0.2 mm after calibration usually means a non-geometric effect such as compliance or backlash, and adding more DH parameters will fit the calibration data while predicting worse.

Finally, frame zero and the tool frame are part of the answer, not an afterthought. A simulation that reports the flange pose while the controller expects the tool center point will pass every FK test and fail the task. I define T_tool explicitly, include it as the last fixed transform in the chain, and test FK with a known tool offset, for example a 175 mm gripper, so a missing tool transform shows up as a constant 175 mm error rather than a mysterious rotation-dependent one.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-12For a redundant 7-DOF arm tracking a 6-DOF pose, how would you use the nullspace to avoid a joint limit, and what changes when the Jacobian approaches a singularity?

The 90-second answer

For a 7-DOF arm tracking a 6-DOF pose, the Jacobian J is 6x7, so there is a one-dimensional family of joint motions that leave the end-effector pose unchanged to first order. I use that freedom explicitly: solve the pose task with the pseudoinverse, then add a secondary joint-limit avoidance term projected into the nullspace of J. Near a singularity I add damping to the pseudoinverse, accepting a small pose lag so joint velocities stay bounded.

The combined command is:

qdot = J^+ xdot_desired + (I - J^+ J) qdot_secondary

The first term tracks the pose. The projector N = I - J^+ J maps any secondary command into the nullspace, so by construction N qdot_secondary does not move the end effector (to first order). That is the whole mechanism. Joint-limit avoidance, a preferred elbow posture, or obstacle repulsion all become choices of qdot_secondary.

Nullspace for a joint limit

Let q_i be a joint approaching its limit q_max. A simple secondary command is a gradient descent on a potential that grows near the limit, for example H(q) = sum over joints of ((q_i - q_mid) / (range_i/2))^4, and qdot_secondary = -k grad H(q). The quartic keeps the push small in mid-range and strong near the ends. Projected through N, it bends the elbow away from the limit while the pseudoinverse term holds the pose.

Python
import numpy as np

def step(J, xdot, q, q_mid, half_range, k=1.0):
    J_pinv = np.linalg.pinv(J)              # 7x6
    N = np.eye(7) - J_pinv @ J              # nullspace projector, 7x7
    u = (q - q_mid) / half_range            # normalised joint position
    grad_H = 4.0 * u**3 / half_range        # gradient of sum(u^4)
    qdot_secondary = -k * grad_H
    return J_pinv @ xdot + N @ qdot_secondary

In simulation I check the leak: compute J @ (N @ qdot_secondary) and confirm it is near zero relative to J @ qdot. If it is not, the pseudoinverse is inaccurate or J is badly scaled, and the secondary task is quietly fighting the primary one.

What breaks near a singularity

The pseudoinverse divides by the singular values of J. As the smallest singular value sigma_min falls toward zero, a modest xdot_desired demands a large joint velocity along the weak direction. On a 7-DOF arm the usual case is wrist alignment, where axes 5, 6 and 7 line up and one rotation is lost, or full elbow extension.

Damped least squares replaces J^+ with J^T (J J^T + lambda^2 I)^-1. Directions with sigma_i much larger than lambda pass through. Directions with sigma_i much smaller than lambda are attenuated, so the end effector lags the target instead of the joint spinning. That lag is the trade-off to state plainly: exact tracking is given up in the weak direction to keep the solution bounded and on the same IK branch.

sigma_min (scaled units)lambdaEffect
0.300.00Near-exact tracking
0.080.05Small lag in weak direction, velocities capped
0.010.10Pose held approximately, posture task still works

Hypothetical trace approaching wrist alignment, fixed target:

Stepsigma_minmax joint rate, undamped (rad/s)max joint rate, damped (rad/s)pose error, damped (mm)
10.300.80.80.2
20.083.51.21.1
30.0114.01.44.2

Without damping the simulated wrist hits its rate limit at step 3 and the pose error grows anyway, because the commanded motion cannot be realised. With damping the error grows to a few millimetres and the arm remains controllable, which is what lets the planner route around the singular region.

Failure modes I watch for

Drift: integrating qdot accumulates error, so I close the loop on measured pose error each step rather than integrating open-loop commands. Branch flip: near a singularity two IK solutions are close, and a large step can jump between them, so I cap the per-step joint change. Saturated secondary task: if the nullspace cannot keep a joint off its limit, sustained damping plus rising pose error is the signal to replan the path, not to raise the gains.

no yes Compute J and pose error Pseudoinverse pose step Project limit avoidance through nullspace Add damping if sigma_min is small Cap joint step and integrate Pose error falling? Slow down or replan path

The point to land in the room: redundancy does not give free accuracy. The nullspace chooses which solution you stay on, and damping decides how gracefully you lose tracking when the Jacobian cannot deliver it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-13How would an EKF-based digital twin assimilate 1 Hz bearing temperature and 10 Hz vibration features for a wind turbine gearbox, and what breaks if you update both at 10 Hz?

The 90-second answer

I would run one EKF for the gearbox, but feed it two measurement streams at their natural rates. Vibration features arrive at 10 Hz and correct the fast states, such as shaft speed error and mesh vibration amplitude. Temperature arrives at 1 Hz and corrects the slow thermal state. Between temperature samples the filter only predicts, so the thermal covariance grows slowly and the state follows the model. That is the whole point of data assimilation here: prediction carries the state forward, correction pulls it toward the measurement only when a measurement exists.

If I forced temperature into the filter at 10 Hz by repeating the last sample, I would be telling the filter I have ten independent temperature measurements per second. The Kalman gain would shrink, the covariance would collapse, and the twin would stop listening to the model. A real temperature rise would then be tracked late, and sensor noise would be treated as signal.

Vibration features 10 Hz EKF predict and correct Bearing temperature 1 Hz Reduced gearbox model Estimated states and covariance Fault score and remaining life

What the filter actually does

State vector for a small gearbox twin might be [speed_error, mesh_amplitude, bearing_temp, friction]. The model propagates those states with a torsional and thermal model. Each step computes a Jacobian F of the model and propagates covariance as P = F P F.T + Q, where Q is process noise. When a measurement arrives, the filter computes the innovation, the difference between measured and predicted output, and weights it by the Kalman gain K. Large R, the measurement noise covariance, means trust the model more. Small R means trust the sensor more.

Python
# Python 3.11, checked against numpy 1.26. One EKF step.
import numpy as np

def ekf_step(x, P, z, model, F, H, Q, R):
    x_pred = model(x)              # predict state
    P_pred = F @ P @ F.T + Q       # predict covariance
    if z is None:                  # no measurement this tick
        return x_pred, P_pred
    y = z - H @ x_pred             # innovation
    S = H @ P_pred @ H.T + R
    K = P_pred @ H.T @ np.linalg.inv(S)
    x_new = x_pred + K @ y         # correct state
    P_new = (np.eye(len(x)) - K @ H) @ P_pred
    return x_new, P_new

At 10 Hz the vibration branch calls the correction path every tick. At 1 Hz the temperature branch calls it once in ten ticks and returns early the other nine times. The code path is identical, only the call rate differs.

Rates, costs and the failure if both run at 10 Hz

StreamRateCorrectsTime constantR choice
---------------
Vibration band RMS10 HzMesh amplitude, speed error0.1 to 1 sSet from bench noise floor
Bearing temperature1 HzBearing temp, friction10 to 30 minSet from sensor spec, about 0.5 C
SCADA torque and speed1 HzLoad input to modelSecondsSet from SCADA resolution

The arithmetic is simple. A 15 state EKF with a dense covariance update costs roughly O(n^3) per correction, about 3,400 operations for the matrix inverse at this size, which is trivial at 10 Hz on an edge CPU. The problem with repeating temperature at 10 Hz is not compute. It is statistical. Ten repeats of the same 1 Hz sample make the filter believe the effective R is ten times smaller. After 10 seconds the thermal covariance can fall by an order of magnitude even though no new information arrived. I have seen this in bench tests: the estimate locks onto a drifting sensor and the innovation test stops firing, because the filter has already decided the sensor is right.

The opposite error also fails. If temperature only corrected at 0.01 Hz, the thermal state would drift with friction error. A friction error of 5 percent in the model produces a steady temperature error of several degrees over an hour, and the twin would call a healthy bearing hot or miss a real rise.

How I would detect trouble

I would plot the normalised innovation squared, y.T @ inv(S) @ y, for each stream separately. For a well tuned filter it averages near the measurement dimension. A sustained value above 3 for temperature means model mismatch or sensor drift, not a sudden bearing event. I would also keep a shadow open loop model with no corrections. If the corrected and open loop temperatures diverge by more than 5 C for a day, I would distrust the assimilation and flag the sensor before I flagged the bearing. That check costs almost nothing and catches the exact failure that a single rate, single R design hides.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-14What is the difference between verification and validation in simulation?

The 90-second answer

Verification checks that the numerical solution is accurate. Validation checks that the simulation predicts the physical system accurately enough for its intended use. In short, verification is solving the equations right, and validation is solving the right equations.

Verification evidence comes from the calculation itself. A manufactured solution or benchmark with a known answer checks the code. A mesh and time step refinement study checks the solution for the case being run. Validation evidence comes from outside the calculation. Simulation results are compared with experimental measurements, with both sides carrying stated uncertainties, over the range where the model will be applied.

VerificationValidation
Question askedHow large is the numerical error?How large is the error against reality?
Typical evidenceBenchmark case, refinement study, residual and monitor historyTest data not used for tuning, error metric, uncertainty budget
Typical resultContinuum estimate plus numerical uncertaintyValidation error plus combined uncertainty
Main riskCoarse mesh, large time step, unconverged solverWrong turbulence model, material law or boundary condition

Verification evidence

Take drag coefficient as the quantity of interest. Run the same case on three systematically refined meshes and record Cd each time. Hypothetical values that show clean convergence:

Mesh spacing hCdChange from previous mesh
0.040 m0.3180
0.020 m0.31300.0050
0.010 m0.31170.0013

The change shrinks by a factor of about 3.85 per halving of h, which corresponds to an observed order near 1.94. Richardson extrapolation then gives a continuum value:

Python
# Python 3.11
f_fine = 0.3117
f_medium = 0.3130
p = 1.94  # observed order from the table above
r = 2.0   # refinement ratio
f_continuum = f_fine + (f_fine - f_medium) / (r**p - 1)
print(f_continuum)  # 0.3113

The extrapolated value is 0.3113, and the remaining numerical uncertainty on the fine mesh is about 0.0004. That statement is verification. It bounds the error from discretisation for this setup. It does not say the turbulence model matches a real car.

Validation evidence

Compare 0.3113 with wind tunnel data at matched Reynolds number and ride height. Suppose the test reports Cd = 0.3150 with expanded uncertainty 0.0040 at k = 2. The validation error is 0.0037. Combine the experimental uncertainty with simulation uncertainty from the mesh study and from input parameters such as ride height and tyre pressure. If the combined interval covers 0.0037, the model is validated at that operating point for a tolerance of roughly 0.004 in Cd. If it does not cover it, the gap points to modelling choices, for example separation prediction or missing mirror geometry, and refining the mesh further will not close it.

That split is what an interviewer is listening for. Verification lets another engineer reproduce the number and bound its numerical error. Validation states where that number can be trusted for a design decision, and where it cannot.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-15Your simulated lidar range sensor shows white Gaussian noise on the bench but correlated drift on the vehicle. How do you model white, colored and Gaussian noise so the simulation reproduces both, and validate it?

The 90-second answer

White, colored and Gaussian describe different axes, and conflating them is the usual modeling error. White describes correlation: flat power spectral density and zero autocorrelation at nonzero lags. Colored describes correlation: PSD varies with frequency, so samples are correlated over a characteristic time. Gaussian describes the marginal distribution of amplitudes: a histogram that matches a normal distribution. A process can be white and non-Gaussian, for example uniform quantization noise, or colored and Gaussian, which is the common case for filtered sensor noise.

For a simulation I would start from measured data, not from a textbook sigma. Record the sensor stationary, compute its PSD and autocorrelation, and fit the simplest process that reproduces both. If the PSD is flat and the autocorrelation is a spike at lag zero, use white noise. If the PSD rolls off or rises at low frequency, use a filtered or autoregressive process. Then check the histogram and higher moments separately for Gaussianity. A bench test that looks white can become colored on a vehicle because temperature drift, vibration and multipath add low-frequency power that the bench setup does not excite.

Generating the processes

White Gaussian noise at fixed sample interval dt is one line, but the variance must be tied to the PSD level, not just copied between timesteps. If a continuous white process has two-sided PSD N0/2, sampling it gives per-sample variance N0/(2*dt). Halving dt without rescaling doubles the variance per sample and changes the integrated noise the downstream filter sees. In a discrete simulation where the sensor model is defined per sample, state sigma at that sample rate explicitly and rescale when the rate changes.

Colored Gaussian noise is most controllably made by filtering white Gaussian noise, or by an AR(1) process:

Python
import numpy as np

rng = np.random.default_rng(42)
dt = 0.01          # 100 Hz
N = 100_000
sigma_white = 0.05 # m, lidar range noise at 100 Hz

white = rng.normal(0.0, sigma_white, N)

# AR(1): x[k] = phi*x[k-1] + sqrt(1-phi^2)*sigma*e[k]
# Stationary variance stays sigma^2, correlation time tau = -dt/ln(phi)
phi = 0.98
ar1 = np.empty(N)
ar1[0] = rng.normal(0.0, sigma_white)
e = rng.normal(0.0, 1.0, N)
for k in range(1, N):
    ar1[k] = phi * ar1[k-1] + np.sqrt(1 - phi**2) * sigma_white * e[k]

With phi = 0.98 at 100 Hz, tau = -0.01 / ln(0.98) = 0.495 s. The lag-1 autocorrelation is 0.98, lag-10 is 0.98**10 = 0.82, and lag-100 is 0.13. That is a concrete, checkable claim against measured autocorrelation. A first-order low-pass filter applied to white noise gives the same shape, with cutoff fc = 1/(2*pi*tau) = 0.32 Hz in this example. For 1/f or pink noise, filter in the frequency domain: shape the FFT amplitudes by 1/sqrt(f), then inverse transform. Do not integrate white noise to make colored noise. That produces a random walk, which is nonstationary, its variance grows with time, and it will fail any long-run validation even if a short segment looks plausible.

ProcessPSDAutocorrelationAmplitude distributionTypical sensor source
White GaussianFlatSpike at lag 0 onlyNormalThermal noise in a receiver, shot noise averaged per sample
White non-GaussianFlatSpike at lag 0 onlyUniform, Laplace, quantizedADC quantization, dither
Colored GaussianRolls off or rises with fDecays over tauNormal at each sampleFiltered vibration, temperature drift, multipath fading
Colored non-GaussianVaries with fDecays over tauSkewed or heavy tailedDropouts, glitches, occasional outliers

Validation and failure modes

Validate in three domains, because passing one does not imply the others. Compare PSD by Welch's method over the same segment length and window as the measurement. Compare autocorrelation up to a few tau. Compare the histogram and kurtosis for Gaussianity. A process can match sigma exactly and still be wrong: white noise with sigma 0.05 m at 100 Hz has 100 effectively independent samples per second, while the AR(1) above has roughly 1/(2*tau) = 1 independent sample per second. A Kalman filter or detector tuned on the white version will be overconfident by about a factor of ten in sample count on the colored version, and its innovation sequence will show autocorrelation that the white model predicts should be absent.

Two failure modes recur. First, generating colored noise by filtering and then forgetting that the filter changed the variance. Always renormalize after filtering so the stationary sigma matches the measured sigma, as the sqrt(1-phi**2) term does above. Second, fitting only the PSD and ignoring non-Gaussian events. Lidar and radar dropouts produce heavy tails that a Gaussian model smooths away, so a tracker that never sees an outlier in simulation meets them first in the field. If the measured kurtosis is well above 3, add a separate outlier or dropout mechanism rather than inflating sigma, which would corrupt the nominal accuracy to cover rare events.

For reproducibility, fix the seed per sensor instance, not globally, so adding a sensor does not shift every other noise stream. Log the fitted parameters, sample rate, tau and seed with the simulation configuration. When the timestep changes, recompute phi from tau as phi = exp(-dt/tau) and rescale white noise variance as above, then rerun the PSD check. That keeps the physical noise the same even though the numerics changed.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-16How many Monte Carlo runs do you need to propagate material and thickness variation through an FEA and report the mean and 95th percentile of peak stress to a stated tolerance?

The 90-second answer

You do not pick N from a rule of thumb. You run a pilot, estimate the output spread, then size N from the tolerance on the statistic you actually report. For the mean, the standard error is sigma divided by sqrt(N), so a 95% interval half width of E needs N at least (1.96 sigma / E) squared. For a percentile the standard error is sqrt(p(1-p)/N) / f(x_p), where f is the output density at that percentile, so the 95% interval half width is 1.96 times that. The N that settles the mean will usually not settle the 95th percentile, especially if the tail is flat and f is small. I size for the percentile, check convergence with running estimates and split samples, and stop only when both are inside tolerance.

Assume the inputs are sampled independently from their measured distributions, the solver is deterministic for a given input set, and the quantity of interest (QoI) is peak von Mises stress in a bracket. Say a 40 run pilot gives mean 212 MPa, standard deviation sigma = 18 MPa, and 95th percentile 244 MPa. Those figures are hypothetical and only for sizing. From the pilot histogram, the density at the 95th percentile is about f = 0.005 per MPa, consistent with a roughly normal output with sigma 18 MPa.

For the mean, to get plus or minus 2 MPa at 95% confidence:

N >= (1.96 x 18 / 2)^2 = 311

For the 95th percentile, to get plus or minus 2 MPa at 95% confidence:

N >= 1.96^2 x 0.95 x 0.05 / (0.005 x 2)^2 = 0.1825 / 0.0001 = 1825

The percentile needs about six times as many runs for the same absolute tolerance. If you needed the 99th percentile to plus or minus 2 MPa, with f about 0.0015 per MPa in the far tail:

N >= 1.96^2 x 0.99 x 0.01 / (0.0015 x 2)^2 = 0.0380 / 0.000009 = 4226

That is the usual trap: reporting a high percentile from 200 runs. The count grows as 1/f squared, so a flatter tail punishes you quickly.

A worked trace from the pilot extended in batches shows why you watch both statistics:

NMean (MPa)95% CI half width, mean95th percentile (MPa)
502095.0238
1002113.5241
2002122.5243
4002121.8245
8002121.2247
16002120.9246
20002120.8246

The mean is inside plus or minus 2 MPa by about 400 runs. The percentile moves by 9 MPa between 50 and 800 runs, then stabilises near 246 MPa only after about 1800 runs, matching the sizing calculation. I would not report the percentile until the last two batches agree within tolerance and a split half check passes.

Python
# Python 3.11, numpy. Sequential batch check on stored QoI values.
import numpy as np

def converged(qoi, tol_mean, tol_pct, p=95, batch=100):
    qoi = np.asarray(qoi, dtype=float)
    prev_pct = None
    for n in range(batch, len(qoi) + 1, batch):
        s = qoi[:n]
        mean = s.mean()
        half = 1.96 * s.std(ddof=1) / np.sqrt(n)
        pct = np.percentile(s, p)
        h = n // 2
        drift_mean = abs(s[:h].mean() - s[h:].mean())
        drift_pct = abs(np.percentile(s[:h], p) - np.percentile(s[h:], p))
        stable_pct = prev_pct is not None and abs(pct - prev_pct) < tol_pct
        if half < tol_mean and drift_mean < tol_mean and drift_pct < tol_pct and stable_pct:
            return n, mean, pct, half
        prev_pct = pct
    return None

In practice I run in batches of 100, reuse the same seed sequence so results are reproducible, and store every input and QoI pair. Latin hypercube sampling helps for the mean and for main effect sensitivity at small N because it stratifies each input. It does not fix a tail percentile. It can even make the empirical percentile look smoother than the true tail if the extreme corner combinations are under sampled. For a percentile driven by a rare combination, such as low thickness plus high friction plus low yield, plain random sampling with a large N, or importance sampling around that corner, is more honest.

No Yes Define input distributions Pilot batch Estimate sigma and tail density Size N for mean and percentile Run batches, store QoI Running CI and split half inside tolerance? Report mean, percentile, N, seed

Failure modes I check before trusting the result: correlated inputs sampled as independent, which understates spread when thickness and yield come from the same batch of material; a bimodal QoI, where the mean sits between two failure modes and the percentile jumps between them; solver non convergence counted as a sample, which biases the tail; and reusing a fixed seed across design variants, which hides sampling error when you rank designs. For ranking, common random numbers across variants reduce the variance of the difference, but you still need absolute convergence for the reported percentile. If the required N is unaffordable, say 4000 FEA runs at 10 minutes each, I switch to a surrogate for propagation, validate the surrogate on held out runs including tail cases, and report the surrogate error alongside the sampling error. A percentile without its N, seed, and interval is not a result.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-17Your simulated DC motor actuator overshoots 25% and settles slowly after a step command. How do you tune the PID gains to fix that, and how do you verify the tuning is not just overfitting the simulation?

The 90-second answer

Treat overshoot and slow settling as a damping problem first, not a gain problem. For a simulated actuator, usually a DC motor or servo with inertia J, viscous damping b, torque constant Kt, voltage saturation and a one or two sample delay, a step that overshoots 25% and rings for a second is telling you the closed loop is underdamped and the integral term is probably winding up while the output is saturated. I would identify the plant from the simulation, place the loop to a damping ratio near 0.8, add derivative action on measurement with a filter, clamp the integrator, then retest across amplitude, load and time step. If I only tune Kp, Ki, Kd against one step in one model, I have fitted the test, not the actuator.

What the numbers say

Approximate the position loop as second order. Overshoot is set mainly by damping ratio zeta:

Mp = exp(-pi*zeta / sqrt(1 - zeta^2))

25% overshoot gives zeta about 0.40. 5% overshoot needs zeta about 0.69. Settling time to 2% is roughly 4 / (zeta * wn), where wn is the undamped natural frequency. So the fix is not simply lowering Kp. Lowering Kp alone reduces wn and can make settling worse. I want higher zeta at a wn that still meets rise time.

Worked example, labelled as such: J = 0.02 kg m^2, b = 0.10 N m s, Kt = 0.08 N m/A, supply limit 12 V. With proportional gain alone the loop is slow and, once integral action is added aggressively, underdamped. Raising derivative gain adds phase lead and effective damping. Raising integral gain removes steady state error faster but adds a pole near the origin and typically increases overshoot, especially after saturation. That trade off is the core of the tuning.

ChangeOvershootSettlingSteady state errorMain risk
Increase Kprisesfalls, then worsensfallssaturation, noise, delay instability
Increase Kirisesworsens if wound upfalls to zerowindup, slow recovery from saturation
Increase Kdfallsfallsunchangedamplifies measurement noise and quantisation
Add derivative filterslight rise vs unfilteredslight riseunchangedless noise amplification, less phase lead at high frequency
Clamp integrator (anti-windup)falls after large stepsfallsunchanged in linear regionnone in linear region, essential under saturation

How I tune it in the simulator

  1. Freeze the plant and log the open loop step. Estimate J, b and delay from the response, or read them from the model if they are known. Record the saturation limit and the solver step dt. If dt is not at least 20 times smaller than the desired settling time, the simulated overshoot may be a numerical artefact.
  2. Set targets before touching gains. For example: overshoot under 5%, settling under 0.5 s, no sustained oscillation, control effort under the voltage limit for a 0.5 rad step and a 1.0 rad step.
  3. Start with Ki = 0. Raise Kp until rise time is acceptable, then raise Kd until overshoot drops. Only then add Ki, starting small, to remove steady state error. Derivative on measurement, not on error, avoids a derivative kick when the setpoint changes.
  4. Add anti-windup by conditional integration or back calculation. When the output saturates, stop integrating in the direction that pushes it further into saturation.
Python
# Python 3.11, checked against a first order motor model
# J*ddtheta + b*dtheta = Kt * u, u saturated at +/-12 V
import math

def simulate(Kp, Ki, Kd, dt=0.001, T=2.0, setpoint=1.0, J=0.02, b=0.10, Kt=0.08):
    theta = dtheta = integral = prev_meas = 0.0
    N = 20.0  # derivative filter coefficient
    d_filt = 0.0
    out = []
    for i in range(int(T / dt)):
        err = setpoint - theta
        # derivative on measurement, filtered
        d_raw = -(theta - prev_meas) / dt
        d_filt += (dt / (dt + 1.0 / N)) * (d_raw - d_filt)
        prev_meas = theta
        u_unsat = Kp * err + Ki * integral + Kd * d_filt
        u = max(-12.0, min(12.0, u_unsat))
        if u == u_unsat or (u > 0 and err < 0) or (u < 0 and err > 0):
            integral += err * dt  # conditional integration
        ddtheta = (Kt * u - b * dtheta) / J
        dtheta += ddtheta * dt
        theta += dtheta * dt
        out.append(theta)
    return out

resp = simulate(Kp=6.0, Ki=2.0, Kd=0.35)
peak = max(resp)
print(f"peak={peak:.3f} overshoot={(peak-1)*100:.1f}%")

With those illustrative gains the peak is near 1.03 rad. The exact value depends on the plant parameters, which is the point. I would sweep Kd from 0.1 to 0.5 and Ki from 0.5 to 4.0 and plot overshoot against settling time, rather than report a single triple.

Verification, not just a good step

A tuning that only works for a 1 rad step at nominal J and b will fail in the real system. I retest at 0.2, 0.5 and 1.0 rad, with load torque added, with J and b varied by plus or minus 20%, with one extra sample of delay, and with dt halved. If overshoot returns when dt is halved, the original result was integration error, not control. If it returns with added delay, the derivative gain is too high for the loop delay and I lower the bandwidth. I also check the control signal itself. A loop that meets the position spec by slamming into saturation for 300 ms will overshoot as soon as the supply droops or the load changes.

Two failure modes I watch for specifically. First, integral windup: the step looks fine at small amplitude and badly overshoots at large amplitude because the integrator accumulated while saturated. The fix is anti-windup, not lower Ki alone. Second, derivative noise: in simulation with a clean encoder the derivative looks free, but with quantised feedback it chatters and excites the actuator. The filtered derivative in the code above, with N around 10 to 20, is the compromise. If the simulated sensor is ideal, I add quantisation and noise to the test before signing off the gains.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-18What assumption does a transfer function make about initial conditions, and how does state-space handle them differently?

The 90-second answer

A transfer function assumes all initial conditions are zero. State-space does not. It carries the state vector x explicitly, so you can start a simulation from any x(0) and integrate forward from there.

That one difference explains most of the practical split between the two forms. G(s) = Y(s)/U(s) is defined for a system at rest. If the mass is already displaced, or a controller integrator already holds a value, the transfer function has nowhere to put that information. State-space puts it in x(0).

Worked example: mass, spring, damper

Take m = 2 kg, k = 50 N/m, c = 4 N s/m, force input u, position output y. In state-space, with x = [position, velocity]:

Python
# Python 3.12, scipy 1.14
import numpy as np
from scipy import signal

m, k, c = 2.0, 50.0, 4.0
A = np.array([[0.0, 1.0], [-k/m, -c/m]])
B = np.array([[0.0], [1.0/m]])
C = np.array([[1.0, 0.0]])
D = np.array([[0.0]])

sys_ss = signal.StateSpace(A, B, C, D)
sys_tf = signal.ss2tf(A, B, C, D)
print(sys_tf)  # numerator [1], denominator [2, 4, 50]

The equivalent transfer function is G(s) = 1 / (2 s^2 + 4 s + 50). Its poles are -1 +/- j4.96, giving a natural frequency of 5 rad/s and a damping ratio of 0.2.

Now set x(0) = [0.1 m, 0 m/s] and apply no force. The state-space model integrates that initial displacement into a decaying oscillation at about 5 rad/s, with amplitude falling as exp(-t) because the real part of the poles is -1. The transfer function with U(s) = 0 returns zero output. It has no term for the stored energy in the spring.

Transfer functionState-space
---------
Initial conditionsAssumed zeroSet in x(0)
What is integratedInput to output map onlydx/dt = A x + B u
Internal variablesNot representedPosition, velocity, integrator states are explicit
Typical useFrequency response, Bode plotTime simulation, observers, MIMO control

Why this matters in a simulation

Real runs rarely start at rest. A vehicle model may start with a nonzero suspension deflection, a motor model with a spinning rotor, or a controller with a preloaded integrator. In state-space you set those values directly and the solver carries them forward. With a transfer function you would have to add a separate initial condition response, which means reconstructing state information the transfer function discarded.

The reverse direction has the mirror problem. Converting a transfer function back to state-space with tf2ss gives a realization that matches the input to output behaviour, but its states are a mathematical construction. They are not the physical position and velocity, so you cannot initialise them from a measurement or clamp one at a physical limit.

So the rule is simple. If the simulation starts from rest and you only need the forced response, a transfer function is enough. If it starts from a physical state, or you need to inspect and set that state during the run, use state-space.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-19Walk me through transforming a point from a rotating sensor frame to the world frame, composing successive rotations, and keeping the rotation matrix orthonormal over a long simulation run?

The 90-second answer

A point is not transformed by a rotation matrix alone. You carry a homogeneous transform, $T = [R ; t; 0 ; 1]$, where $R$ is $3 \times 3$ and $t$ is translation. For a point $p_S$ in the sensor frame, its world coordinates are $p_W = R_{WS} p_S + t_{WS}$. $R_{WS}$ maps vectors expressed in $S$ into $W$. Its columns are the $S$ axes written in $W$ coordinates, which is the check I use when a sign looks wrong.

Composition order is the usual failure. If a sensor is fixed in a body by $T_{BS}$ and the body moves in the world by $T_{WB}$, then $T_{WS} = T_{WB} T_{BS}$. The rightmost transform acts first on the point. Reversing that product is not a small error. It rotates about the wrong origin and the error grows with $|t|$.

Point in sensor frame p_S Apply T_BS: rotate and translate into body Apply T_WB: body pose in world Point in world p_W

Worked trace

Take a sensor mounted with a $+90^\circ$ yaw about $z$ in the body, at $t_{BS} = (0.5, 0, 0)$ m. The body is yawed $+90^\circ$ about $z$ in the world, at $t_{WB} = (1, 2, 0)$ m. A target at $p_S = (1, 0, 0)$ m:

StepCalculationResult (m)
Sensor to body$R_z(90^\circ)(1,0,0) + (0.5,0,0)$$(0.5, 1, 0)$
Body to world$R_z(90^\circ)(0.5,1,0) + (1,2,0)$$(0, 2.5, 0)$
Direct check$R_{WS} = R_z(90^\circ)R_z(90^\circ) = R_z(180^\circ)$, $t_{WS} = (1,2,0) + R_z(90^\circ)(0.5,0,0) = (1, 2.5, 0)$$(1,2.5,0) + (-1,0,0) = (0, 2.5, 0)$

The two routes agree. If you composed in the opposite order you would get $t = (0.5, 2, 0)$ and a final point off by about $0.7$ m, with no warning from the code.

Keeping $R$ a rotation over a long run

Repeated multiplication accumulates roundoff. Columns drift from unit length and from mutual orthogonality, so $R^T R \ne I$ and lengths change. At $10^5$ steps in double precision the drift is often $10^{-12}$ to $10^{-9}$, small but enough to bias a lidar ray or a contact normal after $10^7$ steps in a real time loop. I renormalise on a schedule, not every step, because the cost matters. A $3 \times 3$ SVD orthonormalisation costs roughly a few hundred flops, negligible at 1 kHz but wasteful at 1 MHz.

Python
import numpy as np

def orthonormalise(R: np.ndarray) -> np.ndarray:
    # Closest rotation matrix in Frobenius norm (Kabsch / SVD form).
    U, _, Vt = np.linalg.svd(R)
    Rn = U @ Vt
    if np.linalg.det(Rn) < 0:  # reflection crept in; flip last column
        U[:, -1] *= -1
        Rn = U @ Vt
    return Rn

# Integrate a body rate omega (rad/s) with an exact incremental rotation.
def step(R: np.ndarray, omega: np.ndarray, dt: float) -> np.ndarray:
    theta = np.linalg.norm(omega) * dt
    if theta < 1e-12:
        return R
    k = omega / np.linalg.norm(omega)
    K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
    dR = np.eye(3) + np.sin(theta) * K + (1 - np.cos(theta)) * (K @ K)  # Rodrigues
    return orthonormalise(R @ dR)  # body frame increment on the right

Note the increment side. $R \leftarrow R , dR$ applies $dR$ in the body frame. $R \leftarrow dR , R$ applies it in the world frame. Mixing those two in one integrator is a common source of a slow heading error that only shows in a closed loop test.

Representation choice

Euler angles are fine for display and for small angles near level flight. They fail near pitch of $\pm 90^\circ$, where yaw and roll become indistinguishable and the rate mapping loses rank. That is gimbal lock, and it is a property of the parameterisation, not of the rotation itself. Quaternions avoid the singularity and renormalise with one division, so I integrate orientation as a quaternion in the dynamics and convert to a matrix only where the geometry code needs one. The conversion is $R(q)$ with $q = (w, x, y, z)$, and I check $|q| = 1$ to $10^{-12}$ before conversion. If a legacy interface demands Euler angles, I extract them at the boundary and never feed them back into the integrator.

Detection in practice: log $|R^T R - I|_F$ and $\det(R)$ every $10^4$ steps. A healthy run stays below $10^{-10}$ between renormalisations. A jump in that metric usually means a reflection slipped in through a mirrored frame, for example a left handed sensor frame treated as right handed, which gives $\det(R) = -1$ and flips every cross product downstream.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-20Why do ZYX Euler angles lose a degree of freedom at 90 degrees pitch, and how does a unit quaternion represent the same attitude without that singularity?

The 90-second answer

Euler angles lose a degree of freedom at pitch = 90 degrees because the yaw and roll axes line up. A unit quaternion has no such alignment, because it stores an axis and a half-angle instead of three sequential rotations. For a flight sim, keep attitude as a unit quaternion q = [w, x, y, z] with w = cos(theta/2) and [x, y, z] = sin(theta/2) * axis, integrate it from body rates, and renormalize it each step. Derive Euler angles only for display if you need them.

What happens at vertical pitch

Take the common ZYX sequence: yaw about Z, then pitch about the new Y, then roll about the new X. The resulting rotation matrix has yaw and roll terms multiplied by cos(pitch). At pitch = 90 degrees, cos(pitch) = 0, so changing yaw and changing roll rotate the body in the same way. Two inputs now control one physical rotation.

That is gimbal lock. It is not a numerical accident. The mapping from Euler angle rates to body angular velocity becomes singular, so a controller or an integrator that tries to hold a small roll rate near vertical pitch will demand very large yaw and roll rates in opposite directions. In practice you see a sudden spin, jitter, or a division by cos(pitch) when code recovers angles from a matrix.

A worked check makes the loss concrete. With ZYX angles, the body X axis after yaw psi and pitch theta is:

Pitchcos(pitch)Effect of yaw vs roll
0 degrees1.0Yaw and roll act about distinct axes
45 degrees0.707Axes are distinct, but coupling is strong
89 degrees0.017Yaw and roll are nearly the same rotation
90 degrees0.0Yaw and roll are indistinguishable

At 89 degrees the sim may still run, but the conditioning is already poor. At 90 degrees the representation itself has collapsed.

How a quaternion avoids it

A quaternion encodes the same rotation as a single axis and angle. Composition is quaternion multiplication, and for a unit quaternion the inverse is its conjugate. There is no intermediate axis that can align with another, so no pitch value is special.

The price is one extra number and a constraint. Four components must satisfy w^2 + x^2 + y^2 + z^2 = 1. Also, q and -q describe the same attitude, which matters for interpolation and logging, where you enforce sign continuity by negating the new quaternion if its dot product with the previous one is negative.

Attitude kinematics in the body frame are:

q_dot = 0.5 * q ⊗ [0, wx, wy, wz]

A minimal integrator with renormalization looks like this:

Python
import numpy as np

def quat_mul(a, b):
    aw, ax, ay, az = a
    bw, bx, by, bz = b
    return np.array([
        aw*bw - ax*bx - ay*by - az*bz,
        aw*bx + ax*bw + ay*bz - az*by,
        aw*by - ax*bz + ay*bw + az*bx,
        aw*bz + ax*by - ay*bx + az*bw,
    ])

def step_attitude(q, omega_body, dt):
    q_dot = 0.5 * quat_mul(q, np.array([0.0, *omega_body]))
    q_new = q + dt * q_dot
    return q_new / np.linalg.norm(q_new)

Renormalization matters because numerical integration does not preserve unit length exactly. Without it, |q| drifts, the matrix derived from q is no longer a pure rotation, and thrust direction and sensor frames slowly skew. Normalizing every step is cheap compared with the dynamics solve and bounds that drift.

Choosing between them

RepresentationSizeSingularityWhere it fits
Euler angles, ZYX3Pitch at plus or minus 90 degreesPilot input, cockpit display, small-angle control laws
Unit quaternion4, constrainedNoneAttitude state and integration in the sim
Rotation matrix9, constrainedNoneApplying a known attitude to many vectors each step

Keep the state as a quaternion and build the rotation matrix from it when forces, sensors, or rendering need it. That avoids storing two attitude representations that can drift apart. If a HUD still shows Euler angles near vertical pitch, expect yaw and roll to swing even though the underlying quaternion state is correct. Treat that as a display limit, not a dynamics failure.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-21For an explicit CFD solver on a 2 mm mesh with 200 m/s flow, how do you derive the CFL limit and pick a time step that stays stable without wasting steps?

The 90-second answer

For an explicit update, information from a cell can only travel about one cell per step if the scheme is to stay stable. That gives a maximum step from the fastest wave in the domain. For compressible flow the wave speed is the fluid speed plus the speed of sound, so the convective CFL number is

CFL = (|u| + a) * dt / dx

and stability requires CFL at or below a scheme dependent limit, often 1 for a first order upwind finite volume update and lower for higher order or multidimensional schemes. I compute dt from the smallest cell and the largest local wave speed, apply a safety factor of 0.5 to 0.9, and then check the viscous and source limits separately. The smallest of those limits sets the global step.

LimitFormWhen it controls
Convective / acousticdt <= CFL_max * dx / (|u| + a)High speed compressible flow, shocks, rotating machinery
Viscous diffusiondt <= dx^2 / (2 * d * nu), so 0.25 * dx^2 / nu in 2D and (1/6) * dx^2 / nu in 3DFine near wall cells in an incompressible solver, low speed flow, explicit viscous terms
Turbulence / sourcedt <= C / (source rate), for example 1 / (2 * epsilon / k) in k-epsilonStiff turbulence production, chemistry, relaxation terms
Accuracydt small enough to resolve the timescale of interest, often 20 to 100 steps per periodVortex shedding, acoustics, transient loads where stability alone allows too large a step

Worked numbers

Take dx = 0.002 m, u = 200 m/s, a = 340 m/s. Then |u| + a = 540 m/s and dt at CFL = 1 is 0.002 / 540 = 3.7e-6 s. With a safety factor of 0.8 I would run dt = 3.0e-6 s. Simulating 0.1 s of physical time then needs about 33,000 steps. Halving dx to 0.001 m halves that dt to 1.5e-6 s and doubles the step count.

The smallest cell is the trap. A near wall cell with dx = 1e-5 m and local u = 5 m/s still sees the speed of sound, so its convective limit is 0.8 * 1e-5 / (5 + 340) = 2.3e-8 s. Its 3D diffusion limit, with nu = 1.5e-5 m2/s, is (1e-5)^2 / (6 * 1.5e-5) = 1.1e-6 s, about 50 times larger. In this compressible run the acoustic limit on that tiny cell controls the whole domain, even though the flow there is slow. That is why a global dt based on the mean mesh size fails in practice.

Remove the acoustic term, as an incompressible solver does, and the ordering flips near the wall. The same cell then has dt_conv = 0.8 * 1e-5 / 5 = 1.6e-6 s against dt_visc = 1.1e-6 s, so diffusion controls. In the bulk, dx = 0.002 m and u = 200 m/s, dt_conv = 8.0e-6 s against dt_visc = 0.044 s, so convection controls there. Which limit wins depends on the solver formulation, not just the mesh.

Python
# Python 3.11, checked against the numbers above
import numpy as np

dx = np.array([0.002, 0.001, 1e-5])  # m, smallest cells in the mesh
u = np.array([200.0, 200.0, 5.0])    # m/s, local speed per cell
a = 340.0                            # m/s, compressible case
nu = 1.5e-5                          # m2/s
cfl_max = 0.8

dt_conv = cfl_max * dx / (np.abs(u) + a)
dt_visc = dx**2 / (6 * nu)           # 3D explicit diffusion limit
dt = min(dt_conv.min(), dt_visc.min())
print(dt_conv, dt_visc, dt)
# dt_conv ~ [3.0e-6, 1.5e-6, 2.3e-8], dt_visc ~ [4.4e-2, 1.1e-2, 1.1e-6]
# dt = 2.3e-8 s, set by the acoustic limit on the near wall cell

What I do in a real solver

I use a local CFL field and take the global dt as the minimum over all cells, then log which cell and which limit set it. If one tiny cell forces dt down by an order of magnitude, I look at local time stepping for steady runs, subcycling or implicit treatment of diffusion for unsteady runs, or coarsening that cell if it carries no physics. Local time stepping accelerates convergence to steady state but destroys time accuracy, so I never use it for a transient quantity of interest.

Failure shows up as a sudden residual rise, checkerboard pressure, or NaNs that start at the cell with the highest local CFL and spread. I detect it by tracking max CFL, min dt, and the location of the limiting cell every few hundred steps. A run that is stable at CFL = 0.9 on a uniform mesh can go unstable on a stretched mesh because the effective dx in the diagonal direction is smaller than the nominal cell size, and because explicit Runge Kutta schemes have different stability regions for advection and diffusion. When the step count becomes prohibitive, the credible alternative is an implicit or semi implicit treatment, which removes the stability limit and leaves accuracy and nonlinear convergence to set dt, at the cost of a linear solve per step and more code complexity.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-22For a stiff system, why can an implicit solver take a large step that would make an explicit solver unstable?

The 90-second answer

A system is stiff when it contains fast modes that decay quickly and slow modes that evolve slowly, and the explicit stability limit is set by the fast modes long after they have died out. An implicit solver does not have that limit for decaying modes, so its step size is set by accuracy on the slow modes. That is the whole rule: stiffness means the step you want for accuracy is much larger than the step an explicit method can take without going unstable.

For the test equation y' = λy with λ negative, explicit Euler advances by y_{n+1} = (1 + hλ) y_n. Stability needs |1 + hλ| ≤ 1, so h ≤ 2/|λ|. Implicit Euler advances by y_{n+1} = y_n / (1 - hλ), which stays bounded for any h > 0 when λ < 0. The fast mode is damped in one implicit step instead of dictating h.

Take λ = -1000, y0 = 1, h = 0.1. The exact value after one step is e^{-100}, effectively zero.

MethodAmplification per stepy1y2Behaviour
Explicit Euler1 + hλ = -99-999801Grows in magnitude and flips sign
Implicit Euler1 / (1 - hλ) = 0.00990.00990.000098Decays toward the exact value

Explicit Euler needs h ≤ 0.002 for stability here. Covering 10 s would take at least 5000 steps, even though the solution is zero for practical purposes after 0.01 s. Implicit Euler takes 100 steps at h = 0.1, and the remaining error comes from resolving the slow dynamics you still care about.

Python
# Python 3, test equation y' = lam * y
lam = -1000.0
h = 0.1
y_exp, y_imp = 1.0, 1.0
for _ in range(3):
    y_exp *= (1 + h * lam)   # explicit Euler
    y_imp /= (1 - h * lam)   # implicit Euler, linear case
    print(f"{y_exp: .6g}  {y_imp: .6g}")

The cost shows up in the nonlinear case. An implicit step solves y_{n+1} - y_n - h f(y_{n+1}) = 0, typically by Newton iteration. Each iteration needs the Jacobian of f, and factorising it can dominate the run time for a large model. If Newton fails to converge, the usual response is to cut h and retry. So the trade is step size freedom against a Jacobian and a nonlinear solve per step.

No Yes Fast decaying mode present Accuracy step exceeds explicit stability limit? Explicit solver: cheap steps Implicit solver: solve at each step Step set by slow dynamics

In practice, chemical kinetics, stiff structural dynamics and some circuit models are the textbook cases. A prepared candidate should be able to state the stability limit, show the amplification factors above, and name the Jacobian cost without needing to derive a convergence proof.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-23Your CFD solver is 95% parallel on 1 core and you need 10x speedup: what core count does Amdahl predict, why does Gustafson give a different answer, and what breaks both at scale?

The 90-second answer

Assume a fixed serial fraction s = 0.05, meaning 5% of the single-core runtime cannot be parallelised. Amdahl's law answers the fixed-problem question: how much faster does the same mesh run on N cores? Gustafson's law answers the scaled-problem question: how much more work can we do in the same wall time on N cores? They disagree because they hold different things constant, and both fail when communication, load imbalance or memory bandwidth make s grow with N.

Amdahl: S(N) = 1 / (s + (1-s)/N). For a target S = 10: 0.10 = 0.05 + 0.95/N, so N = 19 cores. The ceiling is 1/s = 20x, however many cores you buy. Gustafson: S_scaled(N) = s + (1-s)N. At N = 19 that gives 0.05 + 0.95 x 19 = 18.1x more work in the same time, because the serial part stays at 5% of a larger job.

NAmdahl speedup (fixed mesh)Gustafson speedup (scaled mesh)Amdahl efficiency
11.01.0100%
85.97.774%
1910.018.153%
6415.460.924%
25618.6243.37%
infinity20.0unbounded0%

Which law to use in practice

Use Amdahl when the deliverable is fixed: the same 40M-cell mesh, the same 2,000 timesteps, a deadline tonight. It tells you when adding cores stops helping and you should instead cut the serial part, for example parallelising the I/O writer or the linear solver setup that currently runs on rank 0.

Use Gustafson when the deliverable scales with the machine: you refine the mesh or add physics until the job fills the allocation, which is how most HPC CFD and FEA campaigns actually run. It justifies a larger allocation, but only if the serial fraction really stays constant as the problem grows. In a real solver it often does not. Global reductions in the pressure solver, halo exchanges at partition boundaries, and checkpoint writes all grow with core count.

A useful check is to measure s at two core counts and see whether it is stable:

Python
# Python 3.11, checked against the formulas above
def amdahl(s, n):
    return 1.0 / (s + (1.0 - s) / n)

def gustafson(s, n):
    return s + (1.0 - s) * n

def cores_for_speedup(s, target):
    # Invert Amdahl: N = (1-s) / (1/target - s); impossible if target >= 1/s
    if target >= 1.0 / s:
        return float("inf")
    return (1.0 - s) / (1.0 / target - s)

print(cores_for_speedup(0.05, 10))  # 19.0
print(amdahl(0.05, 64), gustafson(0.05, 64))  # 15.4, 60.9

Where both laws break

Neither law includes overhead. Add a per-step communication term and the measured speedup bends below Amdahl, then falls. Concrete failure modes I look for in a profile:

  1. Serial fraction creep. Rank 0 writes restart files while other ranks idle. At 64 cores the write is 3% of runtime; at 512 cores, with the same file size, it can be 30% because the parallel compute per rank shrank. Detect it by timing the write separately, not by fitting s to total runtime.
  2. Load imbalance. An adaptive mesh with 10% of cells in a recirculation zone leaves some ranks with twice the work. Speedup is set by the slowest rank, so efficiency drops even with perfect communication. Detect it with per-rank timestep timers; the spread, not the mean, predicts the loss.
  3. Memory bandwidth saturation. Two ranks sharing a socket contend for the same memory controllers. The parallel part itself slows, which neither law models. Detect it by comparing a single-rank-per-socket run against two ranks per socket at the same total core count.
Yes No, s grows Measure runtime at N=1, 8, 64 Fit s from Amdahl at each N Is s stable? Use Amdahl for fixed mesh, Gustafson for scaled mesh Profile serial, imbalance and bandwidth terms Fix the growing term before buying more cores

The senior answer is therefore not a formula choice. It is a measurement plan: time the serial sections directly, check whether s is constant across two scales, and only then extrapolate. If s grows, the correct move is usually to parallelise the bottleneck or rebalance the decomposition, because no core count fixes a serial fraction that scales with the machine.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-24Your Python simulation runs a CPU-bound RK4 integrator in multiple threads and gets no speedup. Why, and how would you restructure it to use multiple cores?

The 90-second answer

In CPython, only one thread executes Python bytecode at a time. That lock is the GIL. It protects the interpreter state and reference counting, and the runtime switches threads every sys.getswitchinterval() (5 ms by default) or when a thread blocks on I/O. A pure-Python RK4 loop never blocks, so the threads take turns and total CPU work is unchanged. You get one core of throughput plus switching overhead.

Threading still helps when the work releases the GIL: waiting on sockets or files, sleeping, or calling a C extension that releases it around a long computation. NumPy releases the GIL for many array operations, which is why a NumPy-heavy solver can scale with threads while a scalar Python loop cannot.

For CPU-bound simulation code, the fixes are multiprocessing, vectorisation, or moving the hot loop out of the interpreter.

What the trace looks like

Assume four independent trajectories, each 10 s of single-thread CPU time on one core, run on a 4-core machine (hypothetical figures):

ApproachWall timeCPU usedWhy
1 thread40 s1 coresequential
4 threads, pure Python40 to 42 s1 coreGIL serialises bytecode, plus switch cost
4 threads, I/O boundabout 10 sunder 1 corethreads block and release the GIL
4 processesabout 10 s4 coresseparate interpreters, no shared GIL
1 thread, Numba-compiled loopoften 5 to 50 times faster per core1 coreloop compiled to native code, no bytecode lock

That last row matters in interviews. If the loop is the bottleneck, compiling it can beat adding cores, and it keeps the code single-process and deterministic.

Python
# Checked against CPython 3.12. The same structure runs on 3.11+.
from concurrent.futures import ProcessPoolExecutor
import numpy as np

def run_trajectory(seed: int, steps: int) -> np.ndarray:
    rng = np.random.default_rng(seed)  # one RNG per worker, no shared state
    y = rng.random(3)
    for _ in range(steps):
        y = rk4_step(y)  # your integrator, pure Python or Numba-compiled
    return y

if __name__ == "__main__":
    seeds = [0, 1, 2, 3]
    with ProcessPoolExecutor(max_workers=4) as pool:
        results = list(pool.map(run_trajectory, seeds, [200_000] * 4))
No, pure Python Yes, I/O or GIL-releasing C call Yes No, independent runs Hot loop in Python bytecode Does it release the GIL? Threads serialise on one core Threads overlap, keep threading Can you vectorise or compile it? NumPy, Numba njit, or Cython ProcessPoolExecutor, one process per core

Choosing between the alternatives

Multiprocessing is the default for independent runs such as Monte Carlo trajectories, parameter sweeps, or mesh cases. Each worker gets its own interpreter and memory, so there is no shared mutable state to corrupt. The costs are real: arguments and results are pickled, so passing a 200 MB mesh per task can dominate runtime, and on Windows and macOS the start method is spawn, which re-imports the module, so the if __name__ == "__main__": guard above is mandatory. Seed each worker explicitly, as shown, or parallel runs will produce correlated or duplicated random streams.

Vectorising with NumPy removes the Python loop entirely by operating on whole arrays. It is the best option when the state is a grid or a batch of trajectories, and it often releases the GIL, so threads can help. It fails when the algorithm is inherently sequential, such as an adaptive step-size controller with data-dependent branching per step.

Numba (@njit) or Cython moves a scalar loop to native code. That keeps one process, shared memory, and deterministic ordering, at the price of a restricted Python subset and a compile step. For a fixed-step integrator this is usually the highest-value change.

Failure modes and detection

If you add threads and see one core at 100% in top or htop while wall time barely moves, that is the GIL signature. py-spy top will show threads piling up in the same Python frame. If you switch to processes and get identical results across workers, check RNG seeding. If you get RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase on Windows, the entry point guard is missing.

One newer option deserves a mention with its limits stated. PEP 703 added an experimental free-threaded CPython build in 3.13 (python3.13t), where the GIL can be disabled. It removes the lock but requires extensions rebuilt for that build and typically costs single-thread performance. It is not the default interpreter, so do not design a production pipeline around it yet. For current mainstream CPython, assume the GIL is present and pick processes, vectorisation, or compilation accordingly.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-25Your simulation updates particle velocities with a Python for loop over 1 million particles. Why is a NumPy vectorized version usually faster, and what update would you leave as a loop?

The 90-second answer

A Python loop does work in the interpreter for every particle. It fetches the next bytecode, looks up names, boxes numbers into Python objects, and calls the operation. NumPy moves that loop into compiled C code. One call iterates over a whole contiguous array, reads values from memory, applies the arithmetic, and writes the result. The per-element interpreter cost disappears.

That is why the same formula runs much faster when it applies independently to each particle. It also explains the limit. If particle i needs the updated value from particle i-1, or the next timestep needs the current one, you cannot apply the formula to the whole array at once without changing the maths. That update stays as a loop, or needs a different algorithm.

Python
import numpy as np

# pos, vel: (N, 3) float64 arrays, mass: (N,)
# Python loop version
for i in range(N):
    vel[i] += (force[i] / mass[i]) * dt

# NumPy version, no Python loop over particles
vel += (force / mass[:, None]) * dt

The second version still runs the timestep loop in Python. It vectorizes the work inside one timestep, which is where the particle count lives.

Why the gap is so large

Illustrative figures for CPython 3.11 and NumPy 1.26 on a laptop, float64 data. Your machine will differ, the pattern will not.

NPython loopNumPySpeedup
1,0000.2 ms0.01 ms20x
100,00020 ms0.4 ms50x
1,000,000200 ms3 ms65x

At 1 million particles the array is 8 MB per component. At an effective memory bandwidth of 20 GB/s, one pass over it takes about 0.4 ms. The NumPy version makes a few passes for division, multiplication and addition, so a few milliseconds is expected. The loop version spends most of its time in the interpreter, not in the arithmetic.

Call overhead sets the other end. Each NumPy ufunc costs roughly 1 to 5 microseconds to dispatch. For 100 particles that overhead can exceed the work itself, and the loop and the vectorized version are both fast in absolute terms. Vectorization pays off once N is in the thousands and grows from there.

What to leave as a loop

UpdateVectorize?Reason
Velocity from force per particleYesSame formula, independent elements
Position from velocity per particleYesSame formula, independent elements
Time stepping, step n+1 from step nNoRecurrence across time
Chain where each particle follows the previous oneNoRecurrence across particles
Collision response with a different branch per particleUsually noData-dependent branching, irregular lists

For the branching case, a common fix is to group particles by type or state, then vectorize each group. That keeps arrays dense and avoids a branch per element. If grouping still leaves a messy inner loop, Numba can compile the loop itself. That is a later step. NumPy first, because it is portable and easy to check against the loop version.

Checks before I trust the rewrite

I compare outputs element by element on a small case, then time both versions on the real N with timeit. I also check dtype and layout. Float32 halves the memory traffic and can be faster, but it changes rounding in a long integration, so I keep state in float64 unless a float32 run validates against it. A (N, 3) C-contiguous array is fine for this update. If I transpose it or store x, y, z separately, I re-measure rather than assume.

The decision rule is simple. Independent, same formula, large N: vectorize. Sequential dependency or per-element branching: keep the loop or restructure the data first.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-26In calibrating a simulation model by least-squares regression, what are you minimizing, and what does the residual tell you?

The 90-second answer

Least-squares calibration chooses the parameters that make the simulation match the measurements as closely as possible in the squared-error sense. For measurements $y_i$ at conditions $x_i$ and a model $f(x_i;\theta)$, you minimize

$$J(\theta)=\sum_i \left(y_i - f(x_i;\theta)\right)^2$$

Each term is a residual, measured minus predicted. A small residual sum means the model reproduces the calibration data. It does not prove the model is physically correct, and it says nothing about behaviour outside the range of $x_i$ you calibrated on.

Worked example: stiffness from a bench test

Suppose a bracket is loaded in displacement control and you want its linear stiffness $k$ in $F = kx$. Hypothetical bench data:

$x$ (mm)$F_{meas}$ (N)$F_{pred}=10.02x$ (N)residual (N)
00.00.00.0
19.810.02-0.22
220.420.030.37
329.730.05-0.35
440.240.070.13

For a model linear in the parameter, the least-squares solution is closed form: $k = \sum x_iF_i / \sum x_i^2 = 300.5/30 = 10.02$ N/mm. The fit quality is $SSE = \sum r_i^2 = 0.33\ \text{N}^2$, so $RMSE = \sqrt{SSE/n} = 0.26$ N. That RMSE is the typical size of the mismatch on this data, in the same units as the measurement, which is what you compare against the sensor accuracy. If RMSE is well below sensor noise, you are probably fitting noise. If it is well above, the model form is wrong or a parameter is missing.

Python
import numpy as np

x = np.array([0.0, 1.0, 2.0, 3.0, 4.0])      # mm
F = np.array([0.0, 9.8, 20.4, 29.7, 40.2])  # N

k, *_ = np.linalg.lstsq(x[:, None], F, rcond=None)
resid = F - k[0] * x
rmse = np.sqrt(np.mean(resid**2))
print(f"k = {k[0]:.2f} N/mm, RMSE = {rmse:.2f} N")
# k = 10.02 N/mm, RMSE = 0.26 N

What to check before trusting the calibrated value

Plot residuals against $x$, not just the fit itself. Random scatter around zero is consistent with measurement noise. A curved pattern, residuals all positive at the ends and negative in the middle, means the model form is wrong, for example the bracket stiffens with load and a single $k$ cannot capture it. Adding a quadratic term would reduce SSE on this data while telling you nothing about whether that term is real.

Identifiability is the other trap. With two parameters, such as stiffness and damping fitted to a force trace, a higher $k$ with a lower $c$ can produce nearly the same SSE as the true pair. The minimum is then a valley, not a point. Check the sensitivity of the output to each parameter and the correlation between parameter estimates. If two parameters trade off almost perfectly, the calibration data cannot separate them, and you need a different test, such as a hold or a release phase, rather than more points of the same kind.

Weighting matters when noise is not uniform. Ordinary least squares assumes equal variance at every point. If force noise grows with load, the high-load points dominate SSE and pull the fit. Weighted least squares divides each residual by its expected standard deviation, which is the maximum-likelihood solution under Gaussian noise with known variances. For a model nonlinear in its parameters, such as a drag coefficient inside a CFD run, there is no closed form. You use nonlinear least squares, typically Gauss-Newton or Levenberg-Marquardt, and each iteration needs the Jacobian of the model output with respect to the parameters, often by finite differences on the simulation.

Finally, hold out data. Fit on part of the bench runs and check RMSE on runs the fit never saw, ideally at loads or temperatures outside the calibration set. A calibrated parameter that only works on its own training points has memorized the test, not learned the physics.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-27Your sensor model needs to represent measurement noise, manufacturing variation, and rare outliers in one simulation: how do you choose between Gaussian, lognormal, uniform and mixture distributions, and validate the tails?

The 90-second answer

I match the distribution to the generating process and to the quantity of interest, not to convenience of sampling. Additive sensor noise from many small independent errors is usually Gaussian by the central limit theorem. A dimension controlled to a hard tolerance with no process data is often modelled as uniform, but only as a stated assumption. A strictly positive quantity driven by multiplicative effects, such as fatigue life or a measured strength, is usually lognormal or Weibull. Rare glitches or a second operating regime need a mixture or a heavy-tailed distribution such as Student t, because a single Gaussian will understate the extremes that drive failure.

The tails decide the answer in most simulation work. Peak stress, missed detection and time to failure are tail events, so I validate exceedance rates, not just mean and variance.

QuantityFirst choiceWhyWhat it gets wrong if misused
Lidar or encoder noise, bench dataGaussian, truncated if the sensor saturatesAdditive, symmetric, many small sourcesUnbounded tails, no saturation pile-up
Sheet thickness, 2.00 mm nominal, tolerance +/-0.10 mmUniform only with no process data, otherwise fitted normal or lognormalHard limits, unknown shape inside limitsUniform overweights near-limit values for a centred process
Fatigue life, strength, positive wear rateLognormal or WeibullPositive support, multiplicative scatter, skewedGaussian gives negative life and understates early failures
Sensor with occasional dropouts or multipathMixture: 99% N(0, sigma), 1% wide componentTwo regimes in one channelSingle Gaussian inflates sigma and still misses the glitch rate
Correlated loads on two axesJoint distribution or copula, not independent marginalsCorrelation changes joint exceedanceIndependent sampling understates simultaneous extremes

Worked tail check

Take a sensor error modelled two ways, both with unit variance. Pure Gaussian: P(|x| > 3) = 0.0027. Mixture: 99% N(0, 1) plus 1% N(0, 5). Its variance is 0.99 x 1 + 0.01 x 25 = 1.24, and P(|x| > 3) = 0.99 x 0.0027 + 0.01 x 0.549 = 0.0082. That is three times the Gaussian rate at the same threshold, even though the standard deviations differ by only 11%. If the quantity of interest is a 99.9th percentile response, that factor propagates directly into the reported margin. Fitting only mean and standard deviation would hide it.

The same issue appears with thickness. A Gaussian with mean 2.00 mm and sigma 0.05 mm gives P(thickness < 1.85 mm) = 0.00135, a 3 sigma event, and also assigns probability to negative thickness, which is physically impossible. Clipping those samples at zero creates a pile-up at the clip value. A lognormal matched to the same mean and variance keeps support positive and gives a different lower tail. I would not choose between them from the tolerance drawing alone. I would ask for process data.

Sampling and validation

Python
# Python 3.11, NumPy 1.26. Hypothetical parameters for illustration.
import numpy as np
rng = np.random.default_rng(42)
n = 200_000
# Mixture sensor error: 99% nominal, 1% glitch component
glitch = rng.random(n) < 0.01
err = np.where(glitch, rng.normal(0, 5.0, n), rng.normal(0, 1.0, n))
# Positive thickness, lognormal matched to mean 2.00 mm, sigma 0.05 mm
mu = np.log(2.00) - 0.5 * np.log(1 + (0.05 / 2.00) ** 2)
s = np.sqrt(np.log(1 + (0.05 / 2.00) ** 2))
thickness = rng.lognormal(mu, s, n)
print("P(|err| > 3):", np.mean(np.abs(err) > 3))
print("P(thickness < 1.85):", np.mean(thickness < 1.85))

Validation starts with a QQ plot and a tail count on held-out data, not the data used for fitting. I compare empirical exceedance at the thresholds that matter, for example the 99th and 99.9th percentiles, and use Anderson-Darling rather than Kolmogorov-Smirnov when tail fit is the concern, since KS is most sensitive near the median. I also check autocorrelation of residuals. White Gaussian samples passed through a filter become coloured noise, and treating them as independent in a Monte Carlo run understates the chance of sustained drift. For correlated inputs I fit the marginals first, transform to uniform ranks, then fit a copula, and I check joint exceedance against data.

Failure modes I watch for: fitting a Gaussian to skewed life data and reporting a mean life that no specimen approaches, assuming uniform inside a tolerance when the process is centred and the true near-limit rate is far lower, and using a mixture with a wide component fitted to a handful of outliers so the glitch rate itself is uncertain by a factor of two. When the tail data are thin I report the sensitivity: run the quantity of interest under the Gaussian and under the mixture or lognormal alternative and state which assumption controls the margin. That sensitivity, with the exceedance table, is what an interviewer or a reviewer can actually check.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-28You have 8 CFD runs with mean drag bias +1.2% and standard deviation 2.4% against a plus or minus 4% acceptance margin. How would you test equivalence with TOST and estimate how many runs you need?

The 90-second answer

Use an equivalence test, not a standard difference test. A difference test asks whether the bias is detectably different from zero. With few runs it often fails to detect anything, and that non-result is not evidence the simulation is close enough. An equivalence test asks the acceptance question directly: is the bias inside a margin you set in advance?

For your numbers, set the margin at plus or minus 4 percent before looking at the result. The two one-sided tests procedure, TOST, then tests two null hypotheses: the bias is at or below minus 4 percent, and the bias is at or above plus 4 percent. Reject both at alpha = 0.05 and you have shown equivalence at that level. In practice this is equivalent to checking whether the 90 percent confidence interval for the mean bias lies entirely inside the margin.

Assume the eight runs are independent replicates, for example different inflow seeds or initialisations, and that run to run scatter is roughly normal. If the wind tunnel mean also has scatter, add its variance to the simulation variance when you size the study.

Worked trace with your figures

Mean bias = +1.2 percent, sample standard deviation s = 2.4 percent, n = 8.

Standard error = s / sqrt(n) = 2.4 / 2.828 = 0.85 percent.

For a 90 percent interval with 7 degrees of freedom, t = 1.895. The interval is 1.2 plus or minus 1.895 x 0.85, which gives -0.41 percent to +2.81 percent.

Both ends sit inside plus or minus 4 percent, so TOST rejects both one-sided nulls and the simulation passes at the 5 percent level. The corresponding TOST p-value is the larger of the two one-sided p-values, here about 0.004, driven by the upper bound.

QuantityValue
Mean bias+1.2%
Standard error0.85%
90% CI-0.41% to +2.81%
Margin-4% to +4%
VerdictPass, interval inside margin
Python
import numpy as np
from scipy import stats

# Replace with your 8 per-run biases, in percent
diffs = np.array([2.8, -0.5, 1.9, 0.6, 3.1, -1.2, 2.0, 0.9])
delta = 4.0  # acceptance margin, percent
alpha = 0.05

mean = diffs.mean()
se = diffs.std(ddof=1) / np.sqrt(len(diffs))
df = len(diffs) - 1

ci = stats.t.interval(1 - 2 * alpha, df, loc=mean, scale=se)
t_lower = (mean + delta) / se
t_upper = (delta - mean) / se
p_tost = max(1 - stats.t.cdf(t_lower, df), 1 - stats.t.cdf(t_upper, df))
print(f"mean={mean:.2f}%  90% CI={ci}  TOST p={p_tost:.3f}")

How many runs do you need

Invert the interval width. An approximate sizing formula for equivalence is n = ((z(1-alpha) + z(1-beta)) x sigma / (delta - |expected bias|))^2, where beta is the false-fail rate. With alpha = 0.05, power = 0.8 so beta = 0.2, sigma = 2.4 percent, delta = 4 percent and expected bias = 1.2 percent, n = ((1.645 + 0.842) x 2.4 / 2.8)^2 = 4.6, so 5 runs. Your 8 runs are therefore comfortably powered for this margin.

The formula shows why the margin matters more than the run count. Tighten delta to 2.5 percent with the same scatter and expected bias, and n becomes ((2.487) x 2.4 / 1.3)^2 = 21 runs. Halving the slack between margin and expected bias roughly quadruples the cost. That is the trade-off to put to whoever sets the acceptance criterion: a tighter margin is a request for many more expensive runs, or for lower scatter from a better mesh or setup.

Difference test versus equivalence test

ApproachNull hypothesisWhat p > 0.05 meansMain risk
Difference testBias = 0No difference detectedNoisy runs pass by default
Equivalence test (TOST)Bias outside marginEquivalence not provenGood model fails when n is small

The difference test rewards low power. The equivalence test penalises it, which is what you want for acceptance. Report the margin, the interval, n and the TOST p-value together. A p-value alone, without the margin it was tested against, does not tell a reviewer whether the simulation is fit for the decision it feeds.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-29Walk me through deriving the weak form of -∇·(k∇u)=f with Dirichlet and Neumann boundaries, and how it leads to the discrete system?

The 90-second answer

Start from the strong form on a domain Ω, for example steady diffusion or heat conduction:

$$-\nabla \cdot (k \nabla u) = f \quad \text{in } \Omega$$

with $u = g_D$ on $\Gamma_D$ and $-k \nabla u \cdot n = g_N$ on $\Gamma_N$. The weak form is the statement that this holds in an averaged sense against every admissible test function $v$ that vanishes on $\Gamma_D$:

$$\int_\Omega k \nabla u \cdot \nabla v , d\Omega = \int_\Omega f v , d\Omega - \int_{\Gamma_N} g_N v , d\Gamma \qquad \forall v \in H^1_{0,\Gamma_D}(\Omega)$$

That single equation is what the code assembles. Everything else is how you get there and what you do with the boundary terms.

Derivation. Multiply the strong form by $v$ and integrate over Ω:

$$\int_\Omega -\nabla \cdot (k \nabla u) , v , d\Omega = \int_\Omega f v , d\Omega$$

Integration by parts (the divergence theorem) moves one derivative from $u$ onto $v$:

$$\int_\Omega k \nabla u \cdot \nabla v , d\Omega - \int_{\partial\Omega} (k \nabla u \cdot n) v , d\Gamma = \int_\Omega f v , d\Omega$$

The boundary integral splits by type. On $\Gamma_D$, $v = 0$ by construction, so the term drops out regardless of the flux. On $\Gamma_N$, the flux is known data, $k \nabla u \cdot n = -g_N$, so the boundary term becomes $-\int_{\Gamma_N} (-g_N) v , d\Gamma = +\int_{\Gamma_N} g_N v , d\Gamma$ on the left hand side, and moving it to the right hand side gives the minus sign in the weak form above. That is why Dirichlet conditions are called essential (they constrain the trial space) and Neumann conditions are natural (they appear in the equations). If you flip the sign of $g_N$ here, you have applied the flux in the wrong direction, and the error shows up as a solution that satisfies the PDE inside but pushes heat or force the wrong way at the boundary.

Two things are gained. First, $u$ only needs to be in $H^1$, meaning its first derivative is square integrable, so a piecewise linear hat function is admissible even though its second derivative is a distribution at element boundaries. The strong form would demand $u \in H^2$, which finite element spaces do not provide. Second, the bilinear form $a(u,v) = \int k \nabla u \cdot \nabla v$ is symmetric and, for $k > 0$, coercive on the test space, which is what makes the discrete system solvable by standard sparse direct or conjugate gradient solvers.

Discretisation. Replace $u$ and $v$ by finite element functions $u_h = \sum_j U_j \phi_j$ and $v_h = \sum_i v_i \phi_i$ built from the same shape functions $\phi_i$. The weak form must hold for each basis test function, giving $K U = F$ with:

$$K_{ij} = \int_\Omega k \nabla \phi_j \cdot \nabla \phi_i , d\Omega, \qquad F_i = \int_\Omega f \phi_i , d\Omega - \int_{\Gamma_N} g_N \phi_i , d\Gamma$$

For a 1D element of length $h$ with linear hats and constant $k$, $K_e = \frac{k}{h} \begin{bmatrix} 1 & -1 \ -1 & 1 \end{bmatrix}$. With $k = 2$ and $h = 0.5$, that is $\begin{bmatrix} 4 & -4 \ -4 & 4 \end{bmatrix}$. Dirichlet nodes are then removed or penalised, which breaks the singularity of the pure Neumann problem, where $K$ has a constant nullspace and $F$ must satisfy a compatibility condition or no solution exists.

BoundaryCondition on $u$ or $v$Where it entersTypical mistake
Dirichlet $\Gamma_D$$u = g_D$, $v = 0$Trial space and rows of $K$Applying it only to the load vector
Neumann $\Gamma_N$flux $= g_N$Right hand side $F$, with a minus sign under the convention $-k\nabla u\cdot n = g_N$Wrong sign on $g_N$
Robinflux $+ \alpha u = g$Both $K$ (boundary mass term) and $F$Treating it as pure Neumann

Assembly in code. For 1D Poisson, $-u'' = f$ on $[0,1]$ with $u(0)=u(1)=0$, the element loop is short enough to check by hand:

Python
import numpy as np

n = 11                      # nodes, h = 0.1
x = np.linspace(0.0, 1.0, n)
h = x[1] - x[0]
K = np.zeros((n, n))
F = np.zeros(n)

for e in range(n - 1):
    Ke = np.array([[1.0, -1.0], [-1.0, 1.0]]) / h
    Fe = np.array([h / 2, h / 2]) * 1.0   # f = 1, exact integral of f*phi
    idx = [e, e + 1]
    K[np.ix_(idx, idx)] += Ke
    F[idx] += Fe

# Dirichlet: delete rows/cols 0 and n-1, solve the interior
U = np.zeros(n)
U[1:-1] = np.linalg.solve(K[1:-1, 1:-1], F[1:-1])

The exact solution is $u = x(1-x)/2$, so $u(0.5) = 0.125$. With $h = 0.1$ the nodal values match to machine precision for this problem because the exact solution is quadratic and linear elements reproduce it at nodes. That check catches sign errors and missing boundary terms faster than any residual plot.

Where it breaks. If $k$ varies sharply or the solution has a kink at a material interface, the weak form still holds but the mesh must align with the interface or convergence drops from $O(h^2)$ in $L^2$ to $O(h)$ or worse. If you use a test space that does not vanish on $\Gamma_D$, the boundary term you discarded reappears and the discrete system is inconsistent. And for convection dominated problems, the symmetric Galerkin form loses coercivity in practice, producing node to node oscillations unless you add stabilisation such as SUPG. The weak form is the right starting point, but it does not rescue a formulation whose bilinear form is unstable for the physics at hand.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-30Which of finite volume, finite difference, and finite element methods is built on integrating the PDE over control volumes so fluxes balance across cell faces?

The 90-second answer

Finite volume. It integrates the PDE over each control volume, or cell, and turns the volume integral into fluxes through the cell faces. The update for a cell is the net flux in minus the net flux out, plus any source term inside the cell.

That is the defining rule. Finite difference approximates derivatives at grid points with a stencil. Finite element approximates the solution with shape functions over elements and solves the weak form. Only finite volume starts from a balance over a volume.

MethodWhat is discretizedCore operation
Finite differenceDerivatives at a nodeStencil, for example $(u_{i+1} - 2u_i + u_{i-1}) / \Delta x^2$ for a second derivative
Finite volumeThe PDE integrated over a cellFace fluxes summed over the cell boundary
Finite elementThe solution over an elementWeak form assembled into a global system

Why the balance is automatic

For a conservation law in one dimension, $\partial u/\partial t + \partial F/\partial x = 0$, integrate over cell $i$ from $x_{i-1/2}$ to $x_{i+1/2}$:

$$ \frac{d}{dt} \bar{u}i = -\frac{F{i+1/2} - F_{i-1/2}}{\Delta x} $$

$\bar{u}i$ is the cell average. $F{i+1/2}$ is the flux through the right face and $F_{i-1/2}$ through the left face. The same face value is used as the outflow of cell $i$ and the inflow of cell $i+1$. Sum the update over all cells and every internal flux cancels. Total mass changes only through boundary fluxes and sources, to round-off.

Finite difference has no such telescoping step. It can be conservative on a uniform grid with constant coefficients, where the stencil happens to match the flux form, but that is a coincidence of the grid and the equation, not a property of the method.

Python
import numpy as np

# 1D advection with a simple upwind flux, dx = 1
# F[i] is the flux through the face between cell i-1 and cell i
# u_new[i] = u[i] - dt/dx * (F[i+1] - F[i])
u = np.zeros(100)
u[20:30] = 1.0
dt, dx, speed = 0.4, 1.0, 1.0

for _ in range(50):
    F = speed * u          # flux at each face, upwind value
    u = u - dt / dx * (np.roll(F, -1) - F)

print(u.sum())  # 10.0, up to round-off: the pulse moved, mass did not leak

Where you see it

Most production CFD codes are finite volume for this reason. A shock, a contact discontinuity, or a source term inside a cell is handled as a flux or a source in the balance, and the solver cannot create or destroy mass inside the domain. Finite difference codes remain common for simple problems on structured grids, and finite element codes dominate solid mechanics, where the geometry and the weak form matter more than a cell balance.

PDE Integrate over a cell Convert to face fluxes Update = net flux in minus net flux out Internal fluxes cancel when summed over all cells

So the one-step test is simple: if the method is described as integrating over control volumes and balancing fluxes across faces, it is finite volume.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-31When would you choose upwind over central differencing for convection in CFD, and how do you quantify and control the false diffusion it introduces on a skewed mesh?

The 90-second answer

For convection I start from the cell Peclet number, Pe = |u| dx / D, where D is the physical diffusion coefficient. If Pe is below about 2, central differencing is usually safe and gives second order accuracy with almost no numerical diffusion. If Pe is well above 2, central differencing produces unbounded oscillations, so I use upwind or a bounded higher order scheme. Upwind is first order and stable, but it adds numerical diffusion that can swamp the physics on a coarse or skewed mesh.

Take steady 1D advection-diffusion, u dphi/dx = D d2phi/dx2, discretised on a uniform mesh. Central differencing for the convective flux gives a coefficient for the downstream neighbour proportional to (D/dx - u/2). When u dx / D > 2 that coefficient changes sign. The discrete solution can then overshoot and undershoot the boundary values, even though the matrix may still solve. Upwind replaces the face value with the upstream cell value. The modified equation for pure advection is then dphi/dx + (u dx / 2) d2phi/dx2 = 0 for u > 0, so the scheme behaves as if the physical diffusion were D + u dx / 2.

That extra term is the cost. With u = 10 m/s, dx = 0.05 m and air with D = 1.5e-5 m2/s, the numerical diffusion is 0.25 m2/s, roughly 16,000 times the physical value. Pe based on the physical D is 33,000, so central differencing would be hopeless for a sharp scalar front, and first order upwind would smear that front over many cells. The fix is not to argue about schemes in the abstract. I refine until dx is small enough that u dx / 2 is a small fraction of the diffusion or transport scale I care about, or I move to a second order TVD limiter such as MUSCL with a van Leer or superbee limiter, which keeps boundedness while recovering near second order accuracy in smooth regions.

SchemeFace valueFormal orderBoundednessMain failure mode
Central(phi_P + phi_E) / 22Fails for Pe > 2Wiggles, overshoots at sharp fronts
First order upwindphi_P for u > 01BoundedNumerical diffusion, smeared gradients
Second order TVD upwindphi_P + limiter * gradient2 in smooth regionsBounded by limiterClipping at extrema, limiter dependent

False diffusion is the multidimensional version of the same problem. When flow crosses a structured mesh at an angle, donor cell upwinding in each coordinate direction diffuses scalar across streamlines. A common estimate for flow at angle theta to the grid is D_false approx (U dx / 4) * sin(2 theta) * (1 - Courant) for an explicit transient scheme, with the steady spatial part scaling as U dx sin(2 theta) / 4. The worst case is 45 degrees. With U = 10 m/s and dx = 0.1 m, that gives about 0.25 m2/s of cross stream diffusion, enough to widen a plume or a wake far faster than molecular diffusion ever would. Refining by a factor of two halves it, which is why false diffusion is a mesh alignment problem as much as a scheme problem.

Python
# Python 3.11, checked against the modified equation above
U, dx, D = 10.0, 0.05, 1.5e-5
Pe = abs(U) * dx / D
D_num = abs(U) * dx / 2.0
print(f"Pe = {Pe:.0f}, D_num/D = {D_num / D:.0f}")
# Pe = 33333, D_num/D = 16667
Yes No Yes No Yes No Compute Pe per face Pe below 2? Central or second order Sharp front or separation? TVD limiter, refine locally Upwind, check D_num Flow skewed to mesh? Align mesh or refine, estimate D_false Accept and verify by refinement

In practice I check three things before trusting a result. First, I plot the scalar field and look for overshoots beyond the physical bounds, which is the signature of central differencing at high Pe. Second, I compare a coarse and a refined mesh for a quantity that false diffusion attacks directly, such as plume width, peak concentration or wake deficit. If that quantity changes by more than the tolerance when dx halves, the numerical diffusion is still controlling the answer. Third, on a skewed mesh I rotate the geometry or the mesh so the dominant flow is closer to a grid line, because no limiter fully removes crosswind diffusion from a first order donor cell formulation. When the front must stay sharp and the mesh cannot be refined further, I switch the convection scheme rather than tightening the solver tolerance, since the error is in the discretisation, not in the iteration.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-32On a collocated grid, why can predicted velocities satisfy continuity yet still allow a checkerboard pressure, and how does one SIMPLE pressure-correction step remove that imbalance?

The 90-second answer

On a collocated grid, pressure and velocity are stored at the same cell centres. A face velocity is interpolated from its two neighbours, so continuity can be satisfied by a velocity field even when the pressure field is physically wrong. The classic failure is a checkerboard: pressure alternates high, low, high, low from cell to cell, the centred pressure gradient at each centre is almost zero, and the interpolated face flux barely changes. Momentum therefore sees no force that would remove the pattern.

SIMPLE breaks that link by not solving directly for the new pressure. It predicts velocity with the old pressure, measures the mass imbalance at each face, solves a pressure correction equation that would cancel that imbalance, and corrects the face fluxes first. Cell velocities and pressure are then corrected from the same correction. Under-relaxation on pressure, typically 0.3, keeps the sequential steps from overshooting.

Why the checkerboard survives a naive solve

Write steady momentum for a cell P as a_P u_P = sum(a_N u_N) + b_P - V_P (dp/dx)_P, where a_P collects neighbour coefficients. For the east face, linear interpolation gives u_e = (u_P + u_E)/2. If p_P is high and p_E is low by the same amount that p_E is high relative to its eastern neighbour, the centred gradients at P and E can cancel. The face flux, built only from centre velocities, does not contain the local pressure difference p_E - p_P. Continuity sum(rho u_f A_f) = 0 can then hold with a flux that ignores the pressure jump.

A staggered grid avoids this because velocity lives on the face and the face gradient is direct. On a collocated grid the standard fix is Rhie-Chow interpolation. The face velocity gets an extra term proportional to the difference between the face pressure gradient and the interpolated centre gradient, divided by a_P. That term makes the flux respond to p_E - p_P even when centre velocities are smooth.

One SIMPLE sweep

No Yes Solve momentum with current p Predict centre velocities Interpolate to faces with Rhie-Chow Compute mass imbalance per cell Solve pressure correction equation Correct face fluxes Correct velocities and pressure Imbalance below tolerance? Converged
Python
for it in range(max_iter):
    u_star = solve_momentum(p, alpha_u=0.7)
    u_face = rhie_chow(u_star, p)          # face flux sees dp/dx
    imbalance = continuity_residual(u_face)  # kg/s per cell
    p_corr = solve_pressure_correction(imbalance)
    u_face -= correction_flux(p_corr)      # now mass-conserving
    u_star -= grad(p_corr) / a_P
    p += 0.3 * p_corr
    if max(abs(imbalance)) < 1e-6:
        break

The correction follows from writing the velocity correction as u' = -grad(p')/a_P and inserting it into continuity. The result is a Poisson-like equation for p' with the imbalance as source. Treating a_P as frozen during the correction is an approximation, which is why SIMPLE needs many outer iterations and why under-relaxation is part of the method rather than a tuning extra.

Worked trace

Take one cell with face area 1 m2 and density 1 kg/m3. Predicted fluxes in and out are 1.20 and 1.05 kg/s, leaving 0.15 kg/s imbalance. The correction equation finds a p' field whose gradient removes 0.15 kg/s from the net flux. After correction both faces carry about 1.10 kg/s. Over a full solve the pattern looks like this for a hypothetical laminar pipe, residuals normalised by inlet mass flow:

Outer iterationMax imbalanceMomentum residualMax pressure correction
11.5e-18.0e-242 Pa
102.1e-21.1e-26.5 Pa
501.8e-39.0e-40.55 Pa
2004.0e-63.0e-60.012 Pa

The slow tail after iteration 50 is typical. SIMPLE converges linearly, so a decade of imbalance reduction can take 30 to 50 sweeps once the flow is close.

SIMPLE compared with PISO

MethodPer stepBest useMain cost
SIMPLEOne momentum solve, one correction, under-relaxedSteady incompressible flowMany outer iterations
PISOOne momentum solve, two correctors, no under-relaxationTransient flow where each step must conserve mass closelyExtra linear solve per step, poor for steady state

For a steady case I start with SIMPLE at alpha_u 0.7 and alpha_p 0.3. For a transient case with a fixed time step, PISO usually gives a cleaner mass balance per step. SIMPLEC, which replaces a_P by sum(a_N) in the correction, can cut iterations on some steady cases but is less forgiving of a poor mesh.

How you spot a stall

Check global mass balance, inlet minus outlet, rather than the normalised residual alone. A run can show a small residual while leaking 0.5 percent of the flow. Sample pressure along a line of cells. Alternating values with no physical gradient point to missing or incorrect Rhie-Chow interpolation. If halving alpha_p shortens the tail, the coupling is stiff. On a highly non-orthogonal mesh, the explicit non-orthogonal correction in the pressure equation is another common source of oscillation, and limiting that correction often restores convergence without changing the solver.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-33A cold plate channel bows 0.15 mm under thermal load, narrowing a 2 mm channel. How does that deformation feed back into flow and temperature, and would one-way coupling capture it?

The 90-second answer

One-way coupling would miss the effect in this case. The sequence is thermal load bows the plate, the bow narrows the channel, the narrower channel carries less flow, and the reduced flow raises the plate temperature further. That is a feedback loop, so the structural result changes the fluid result that produced it. A one-way run that stops after structural analysis keeps the original 2 mm gap in the fluid solve and therefore underpredicts peak temperature. A two-way run iterates fluid, thermal and structural solves until the gap and temperature stop changing.

Thermal: plate heats and bows Structural: gap falls from 2.00 to 1.85 mm Fluid: flow resistance rises, flow falls

The mechanism, with numbers

Assume laminar flow in a wide rectangular channel, which is a reasonable first model for a cold plate at typical coolant rates. For a channel of height h, pressure drop at fixed flow scales roughly as 1/h^3. The bow reduces h from 2.00 mm to 1.85 mm, a 7.5% reduction.

Resistance ratio = (2.00 / 1.85)^3 = 1.26

So that channel needs 26% more pressure drop for the same flow. In a pack with several channels in parallel on a common manifold, the pump and manifold set a common pressure drop, so the narrowed channel instead loses flow. If total flow is held by the pump, flow in the narrowed channel falls by roughly 1 - 1/1.26, about 21%, while neighbouring channels pick up the difference.

Lower flow lowers the heat transfer coefficient. For laminar flow with roughly constant Nusselt number, h depends mainly on thermal conductivity and hydraulic diameter, so the direct effect is modest. The larger effect is coolant heating. With 21% less mass flow through the channel, the coolant temperature rise along the channel rises by about 1/0.79, or 27%. If the original rise was 8 K, it becomes about 10.2 K. The downstream end of the plate, which already sees the warmest coolant, gets about 2 K hotter. That extra temperature drives more thermal expansion, which is why the loop needs iteration rather than a single correction.

StepGap (mm)Relative resistanceChannel flowCoolant rise (K)
Initial fluid solve2.001.001.008.0
After first structural solve1.851.260.7910.2
After second iteration, hotter plate bows a little more1.831.300.7710.4
Converged1.831.300.7710.4

The numbers in the last rows are illustrative, but the pattern is the point. Most of the change arrives in the first feedback pass. The second pass adds only about 0.2 K, which is a practical stopping point if the quantity of interest is peak temperature to within 0.5 K.

How I would run the two-way version

I would keep the solvers separate and exchange two fields on the plate interface: temperature from thermal to structural, and deformed gap from structural back to fluid. Each iteration I would under-relax the gap update, for example taking 70% of the new gap change, because a full update can oscillate between a narrow hot channel and a wide cool one. I would stop when peak temperature changes by less than 0.1 K and gap changes by less than 0.01 mm between iterations.

Python
# Staggered two-way coupling for the cold plate, steady state
T_old = T_init.copy()
gap_old = 2.00  # mm
for it in range(10):
    h, T_cool = fluid.solve(gap=gap_old)          # fluid sees current gap
    T_new = thermal.solve(h=h, T_cool=T_cool)     # thermal sees local h
    gap_new = structural.solve(T=T_new)           # structural sees T_new
    gap_old = gap_old + 0.7 * (gap_new - gap_old) # under-relaxation
    if abs(T_new.max() - T_old.max()) < 0.1:
        break
    T_old = T_new

When one-way would be enough

One-way is defensible when the feedback is small enough to bound. If the bow were 0.02 mm instead of 0.15 mm, the resistance ratio would be (2.00/1.98)^3 = 1.03, flow would fall by about 3%, and coolant rise would increase by about 0.25 K. For ranking three plate designs that differ by 5 K in peak temperature, that error is acceptable and I would state it. At 0.15 mm the error is about 2 K and it grows in the hot channel, so it can change the ranking. The decision comes from that sensitivity arithmetic, applied to the stated deflection, rather than from a preference for the more expensive method.

One check before trusting either run: the heat leaving the plate into the coolant in the thermal solve should match the heat picked up by the coolant in the fluid solve to within a few percent. If the interface mapping creates or destroys heat, the converged temperature is wrong even though the iteration converged.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-34What equation does modal analysis solve, and what do its natural frequencies and mode shapes actually describe?

The 90-second answer

Modal analysis solves the undamped, free-vibration eigenvalue problem for a linear structure:

(K - ω²M) φ = 0

K is the stiffness matrix, M the mass matrix, ω a natural frequency in rad/s, and φ the associated mode shape. Nontrivial solutions exist only when det(K - ω²M) = 0, which gives the eigenvalues λ = ω². Each eigenvalue gives one natural frequency, f = ω / (2π) in Hz, and its eigenvector gives the displacement pattern the structure vibrates in at that frequency. A mode shape is not a deformed shape under load. It is the relative displacement of every degree of freedom when the structure vibrates freely in that mode, with nodes where displacement stays near zero.

In FEA the same problem is solved after discretisation, usually as the generalised symmetric problem Kφ = λMφ. Solvers return frequencies and mass-normalised shapes, φᵀMφ = I, so modes are mass-orthogonal: φᵢᵀMφⱼ = 0 for i ≠ j. That orthogonality is what lets a later transient or random-vibration run expand the response in a few modes instead of solving every degree of freedom at every step.

Worked trace: two masses in series

Take two 1 kg masses. Mass 1 connects to the wall through a 100 N/m spring and to mass 2 through another 100 N/m spring. Mass 2 is otherwise free.

K = [[200, -100], [-100, 100]] N/m    M = [[1, 0], [0, 1]] kg

The eigenvalues of M⁻¹K are λ = 38.2 and 261.8 s⁻². Taking square roots and dividing by 2π:

Modeλ = ω² (s⁻²)ω (rad/s)f (Hz)Shape φ (mass 1, mass 2)Reading
138.26.180.98(1.00, 1.62)Both masses move the same way, mass 2 furthest
2261.816.182.58(1.00, -0.62)Masses move in opposite directions

Mode 1 is the low, in-phase mode. Mode 2 is higher because the coupling spring stretches, adding stiffness. If a shaker or motor excites the bracket near 0.98 Hz, mode 1 dominates the response. Near 2.58 Hz, mode 2 dominates and the two masses counter-move. That is the practical use: compare the first few f values against known excitation frequencies and check where the shape has large displacement at the component you care about.

Checking it in code

Python
import numpy as np
from scipy.linalg import eigh

K = np.array([[200.0, -100.0], [-100.0, 100.0]])
M = np.eye(2)

lam, phi = eigh(K, M)          # solves K phi = lam M phi
freq_hz = np.sqrt(lam) / (2 * np.pi)
print(freq_hz)                 # [0.98 2.58]
print(phi)                     # columns are the mode shapes

scipy.linalg.eigh is the right call here because both matrices are symmetric and M is positive definite. A general eigensolver would waste effort and could return complex values for a problem that has none.

What the result does not tell you

Undamped modal analysis assumes linear elasticity, small displacements, and no damping. Real damping shifts the frequency slightly and, for non-proportional damping, makes the mode shape complex, meaning different points peak at different times in the cycle. A standard real modal run will not show that. It also says nothing about stress magnitude. A mode shape scaled to 1 mm at the tip and the same shape scaled to 10 mm have the same frequency. Amplitude comes from the excitation and damping, not from the eigenvalue problem.

Two failure modes show up often in practice. A frequency near zero, say below 0.01 Hz, usually means a rigid-body mode or an unconstrained mechanism rather than a real vibration mode. Check the boundary conditions and any missing connection before reporting it. A mode shape that is large only at a single node with a lumped mass often means the mass is modelled but the stiffness path to it is missing or far too soft. In a vehicle or machine model, also watch for repeated frequencies from symmetry. Two identical modes at the same frequency can appear in any rotated combination, so comparing shapes node by node between runs needs care.

For a simulation engineer the deliverable is rarely the full list. It is the first three to six frequencies, a statement of which excitation bands they clear, and the shape of any mode that sits inside an operating band.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-35You need peak stress in a bracket under a 2 s impact load and also its steady deflection under sustained load: how do you set up transient and steady-state analyses differently, and how do you know the transient result has settled?

The 90-second answer

They are different problems, not the same run with a longer clock. A steady-state (static) analysis solves K u = F once, with inertia and damping absent. A transient analysis solves M a + C v + K u = F(t) at every step, so mass, damping, initial conditions and the load history all change the answer. For your bracket, I would run static first to get the sustained deflection and a baseline stress, then run transient only for the impact, because static cannot give peak stress during a 2 s pulse and transient cannot be trusted for the sustained case until you prove the response has settled.

Setup decides that before the solver starts.

ItemSteady-state staticTransient dynamics
Governing termsK u = FM a + C v + K u = F(t)
Material data neededE, nu, yieldplus density rho, damping ratio or Rayleigh alpha, beta
Loadconstant F, applied in one stepF(t) as a table or ramp, with rise time stated
Initial conditionsnoneu(0), v(0); zero is an assumption, not a default to forget
Time stepnonedt small enough to resolve the highest mode of interest, typically T/20 or finer
Output to reportu, von Mises stress at equilibriumtime history, peak and time of peak, settled value

Transient setup, with numbers. Take a bracket with first natural frequency f1 = 18 Hz, so T1 = 55 ms. For a 2 s impact I would use dt = 1 ms (T1/55) with an implicit integrator such as Newmark or HHT, and run at least 3 to 5 periods after the load ends. That is 2,000 to 3,000 steps, not the 20 steps a static solve needs. Damping matters as much as dt: with no damping the oscillation never decays and the "peak" is just the undamped overshoot. I would set modal damping from test if available, otherwise Rayleigh damping calibrated to zeta = 0.02 at f1 and at a higher mode, and state that assumption next to every peak value. Mass scaling, if the explicit solver forces it, must be reported, because it lowers f1 and inflates the transient peak.

Initial conditions are the usual trap. Starting from rest with u(0) = 0 under a load that is already applied at t = 0 creates a step response and a spurious oscillation at f1. If the real bracket was already carrying the sustained load before the impact, I would either pre-stress with a static step, then restart the transient from that deformed state, or ramp the load over about one period. The two choices give different peaks, and the difference is physical, not numerical.

How you know it has settled. Never judge by eye on a single trace. I check three things over a window of at least one period after the load becomes constant: the change in the quantity of interest, the kinetic energy relative to strain energy, and the residual of the equation of motion. A practical criterion for the settled value is max |q(t) - q(t - T1)| / |q(t)| < 0.01 over a full period, and kinetic energy below 1% of strain energy. Only then can the transient mean be compared with the static result. If they disagree by more than a few percent, something is inconsistent, usually damping, a different load magnitude, or a contact or plasticity state that the static run did not reproduce.

Worked trace, hypothetical but typical for this bracket after the pulse ends at 2.0 s:

t (s)Peak stress (MPa)Change over last T1Kinetic / strain energy
2.00412-0.31
2.063886.1%0.18
2.123714.4%0.09
2.183632.2%0.04
2.243591.1%0.015
2.303580.3%0.006

The peak to report is 412 MPa at 2.0 s. The settled value is about 358 MPa, which should match the static run under the same sustained load within tolerance. Reporting 412 MPa as the design stress for sustained loading, or 358 MPa as the impact peak, are both wrong.

In code, the settling check is a windowed test on the exported history, not a solver flag:

Python
# Python 3.11, checked against a CSV export: t, stress
import numpy as np

d = np.genfromtxt("history.csv", delimiter=",", names=True)
t, q = d["t"], d["stress"]
T1 = 0.055  # first period, s
settled = False
for i in range(len(t)):
    j = np.searchsorted(t, t[i] - T1)
    if j > 0 and abs(q[i] - q[j]) / max(abs(q[i]), 1e-9) < 0.01:
        settled = True
        print(f"settled at t={t[i]:.3f} s, q={q[i]:.1f} MPa")
        break

Failure modes I watch for. Too large dt filters the peak and can miss it entirely, so I halve dt and confirm the peak moves by less than 2%. Zero damping gives a peak that grows with run length. A static run with contact or plasticity can land on a different branch than the transient, so I compare deformed shape and plastic strain, not just stress. And a "steady" CFD or thermal run that is really a transient run stopped early shows the same symptom: residuals plateau but the quantity of interest still drifts. In that case the honest answer is that steady state was not reached, and the run needs a better initial field or a longer integration, not a tighter residual tolerance.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-36A linear buckling run on a column under a 500 kN reference load returns a first eigenvalue of 2.4. What does that eigenvalue mean, and how would you check it with Euler's formula?

The 90-second answer

The eigenvalue is the factor by which the reference load must be scaled to reach elastic bifurcation in the linearised model. With a 500 kN reference load and a first eigenvalue of 2.4, the predicted critical load is 2.4 x 500 kN = 1,200 kN. It is a load multiplier for that specific load pattern, not a safety factor and not a collapse load. I would check it by computing the Euler load for the same column and confirming the two are close, then inspect the mode shape to confirm it is global column buckling rather than a local plate mode.

What the solver solves

Linear buckling builds the elastic stiffness matrix K from the material and geometry, and a geometric stiffness matrix Kg that depends on the stress state from a preceding linear static run. It then solves:

(K + lambda * Kg) * phi = 0

Here lambda is the eigenvalue and phi is the buckling mode shape. The smallest positive lambda gives the first bifurcation. Larger eigenvalues correspond to higher modes. Because Kg comes from a linear stress state, the analysis assumes elastic behaviour, perfect geometry and small deflections up to bifurcation. It cannot capture yielding before buckling, contact changes or imperfection sensitivity.

Worked check against Euler

Take a pin-ended steel column with length L = 2.0 m, E = 200 GPa and second moment of area I = 2.43e-6 m^4. Euler gives:

Pcr = pi^2 * E * I / (K * L)^2, with K = 1.0 for pin ends Pcr = 9.87 * 200e9 * 2.43e-6 / 4.0 = 1.20e6 N = 1,200 kN lambda_Euler = 1,200 / 500 = 2.40

Agreement with the FEA value of 2.4 is what I expect for a prismatic column with matching end conditions. A small difference of 5 to 10% is normal from shear deformation and discretisation. A large difference points to a modelling error, such as the wrong end condition, a local mode being reported instead of the global mode, or Kg built from the wrong load case.

Python
import math

E = 200e9        # Pa, steel
I = 2.43e-6      # m^4
L = 2.0          # m
K = 1.0          # pin-ended
P_ref = 500e3    # N

P_cr = math.pi**2 * E * I / (K * L)**2
print(f"P_cr = {P_cr/1e3:.0f} kN")
print(f"lambda_Euler = {P_cr / P_ref:.2f}")
# P_cr = 1198 kN, lambda_Euler = 2.40

Eigenvalue versus nonlinear buckling

ApproachWhat it givesMain trade-off
---------
---------
---------
Eigenvalue bucklingElastic bifurcation load and mode shape from one linear runFast and good for screening, but misses plasticity and imperfection effects
Nonlinear buckling with imperfectionsLoad versus deflection path past bifurcation, including yielding and unstable post-bucklingMore realistic for thin shells, but needs an imperfection amplitude and a converged arc-length run

For this column, if the Euler stress Pcr / A is well below yield, the eigenvalue result is a reasonable estimate of the buckling load. If that stress approaches yield, the elastic eigenvalue will overpredict capacity and a nonlinear run or a code formula such as Johnson should replace it.

Apply 500 kN reference load Run linear static analysis Assemble geometric stiffness Kg Solve eigenvalue problem Report lambda = 2.4 and mode shape Compare Pcr = 1200 kN with Euler

I would always report the critical load in kN alongside lambda, because lambda changes if the reference load changes even though the structure does not. I would also state the mode shape and end conditions, so the result can be reproduced and compared with test or hand calculation.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-37A bracket root sees 5,000 cycles at 60 MPa and 50,000 cycles at 30 MPa per block. How would you use an S-N curve and Miner's rule to estimate blocks to failure, and why might ignoring the 30 MPa cycles be unsafe?

The 90-second answer

I would rainflow count the stress history at the bracket root, group the cycles into amplitude bins, read cycles to failure for each bin from the S-N curve, and add the damage fractions with Miner's rule. Damage per block is D = sum(n_i / N_i), and blocks to failure is 1 / D. The step that decides whether the answer is safe is not the arithmetic. It is whether the S-N curve I read from matches the detail, the mean stress and the amplitude range of the real cycles, especially the small cycles below the knee of the curve.

A constant amplitude S-N curve is usually fitted as Basquin's relation:

N = C * S_a^(-m)

S_a is stress amplitude, N is cycles to failure, m is the slope and C sets the level. On log-log axes it is a straight line. The curve comes from tests on a specific detail, often polished specimens or a standard welded joint, at a stated stress ratio R. If my bracket root has a notch, a different surface finish or a high mean stress, I need to correct the amplitude or use a curve for that detail class before I enter it. Otherwise the life can be off by an order of magnitude.

Worked example, labelled as hypothetical

Assume the detail curve is N = 1e12 * S_a^-4, with S_a in MPa, already corrected for notch and mean stress, and one duty block contains the two bins in the question:

S_a (MPa)Cycles per block nN = 1e12 * S_a^-4Damage n / N
605,0007.72e40.0648
3050,0001.23e60.0405

Total damage per block is 0.1053, so blocks to failure is 1 / 0.1053 = 9.5 blocks. The 30 MPa cycles look harmless on their own, yet they supply 38% of the damage in this block. If I dropped them as below an assumed endurance limit, I would predict 1 / 0.0648 = 15.4 blocks, an overprediction of about 60%.

Python
# Python 3.11, illustrative Miner calculation
def cycles_to_failure(sa, C=1e12, m=4.0):
    return C * sa ** (-m)

bins = [(60, 5000), (30, 50000)]
damage = sum(n / cycles_to_failure(sa) for sa, n in bins)
print(f"damage per block: {damage:.4f}")
print(f"blocks to failure: {1 / damage:.1f}")
# damage per block: 0.1053, blocks to failure: 9.5

Why ignoring small cycles is unsafe

Many textbook curves show a knee, sometimes called an endurance limit, below which life is treated as infinite. That knee is a feature of the test data and the fitting method, not a guarantee for a different detail. For welded joints, design codes such as BS 7608 and the IIW recommendations use a bilinear curve with a shallower slope below the knee, often m + 2, precisely because small cycles still propagate cracks once a crack has been initiated by larger cycles. In a variable amplitude spectrum the large cycles initiate damage and the small cycles then extend it. A single slope extrapolation below the knee can therefore be non-conservative, and deleting the small bins entirely is worse.

Mean stress is the other correction I would check before trusting the table above. The curve is normally for fully reversed loading, R = -1. A cycle at 30 MPa amplitude with a mean stress of 120 MPa is more damaging than the same amplitude at zero mean. A Goodman correction converts it to an equivalent fully reversed amplitude, S_ar = S_a / (1 - S_m / S_ut). With S_ut = 600 MPa, that 30 MPa cycle becomes 37.5 MPa, and its N falls from 1.23e6 to about 5.0e5. Damage from that bin more than doubles. Gerber's correction is less severe and fits some alloys better, so I would state which correction I used and, if the mean stress is high, check it against test data at a comparable R ratio.

I would also report the result as a range, not a single number. Fatigue scatter at a given stress is commonly a factor of 3 to 10 in life, and a 10% error in stress amplitude changes life by (1.1)^4, about 46% at this slope. For a design claim I would use a lower bound curve, such as mean minus two standard deviations in log life, and note that Miner summation assumes sequence does not matter. An overload that yields the notch root can retard later cycles, so the 9.5 blocks is a comparative estimate for ranking spectra or details, not a certified life without test correlation.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-38What does it mean to make a material property temperature-dependent in a simulation, and what does the solver do at a temperature between table entries?

The 90-second answer

A temperature-dependent property is not a single number. It is a function, usually a table of measured values at discrete temperatures, and the solver evaluates that function at the current temperature of each element or node. At a temperature between table entries the solver interpolates, most commonly linearly, between the two nearest values. That interpolated value is what enters the stiffness matrix, the yield check and the thermal strain for that step.

So for steel you might enter E as 210 GPa at 20 C, 195 GPa at 200 C, 180 GPa at 400 C and 150 GPa at 600 C. At 500 C the solver does not use 210 GPa and it does not round to the nearest entry. It interpolates to 165 GPa and uses that for the element stiffness at 500 C.

How the interpolation works

Linear interpolation between points (T1, P1) and (T2, P2) is:

P(T) = P1 + (P2 - P1) * (T - T1) / (T2 - T1)

For E at 500 C, between 400 C and 600 C:

E = 180 + (150 - 180) * (500 - 400) / (600 - 400) = 165 GPa

The same rule applies to yield strength, thermal conductivity, specific heat and expansion coefficient. Thermal strain also needs a reference temperature, T_ref, the temperature at which the part is stress free. The solver then accumulates alpha(T) * (T - T_ref), or the integral of alpha over that range when alpha varies with temperature. If T_ref is wrong, every thermal stress shifts by about E * alpha per kelvin of error, roughly 2.5 MPa/K for steel.

A short Python version of the same lookup, useful for checking a material card before it goes into the FEA tool:

Python
import numpy as np

T = np.array([20, 200, 400, 600])
E = np.array([210, 195, 180, 150])  # GPa

def E_at(temp_c):
    return float(np.interp(temp_c, T, E))

print(E_at(500))  # 165.0
print(E_at(20))   # 210.0

np.interp clamps outside the table range, which mirrors what many solvers do. That behaviour matters, as below.

What goes wrong in practice

The table defines the valid range. If the data stop at 400 C and a hot spot reaches 700 C, the solver will clamp to the 400 C value or extrapolate linearly, depending on the code and the card settings. Either way the result is no longer based on measurement. Strength in particular falls steeply above about 0.4 times the melting temperature, and creep and phase change can appear. A candidate should state the table range in the model notes and check the peak temperature in the results against it.

A second common error is making only one property temperature-dependent. Updating E(T) while leaving yield strength and alpha constant gives a deflection that moves with temperature and a yield onset that does not. For 6061-T6 aluminium, yield drops from about 276 MPa at 20 C to roughly 140 MPa at 250 C, so a constant yield at elevated temperature overstates the margin by about a factor of two.

T (C)E, steel (GPa)Yield, steel (MPa)Yield, 6061-T6 (MPa)
20210355276
200195320190
40018026090
600150150not applicable

Values are representative for illustration. Use the datasheet or test curve for the exact grade.

Use temperature-dependent tables whenever the part spans more than about 100 C or whenever yield, thermal stress or creep governs the design. Below that span a constant property set is acceptable if you state the temperature it was measured at.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-39A bracket CAD has a 0.5 mm chamfer, 1 mm rib fillets and 3 mm bolt holes, and you must mesh it at 2 mm. How do you decide what to remove, keep or idealize, and prove the result of interest has not moved?

The 90-second answer

I defeature against the quantity of interest (QoI), not against the CAD. Start from the target element size h and the QoI tolerance, then remove only features whose removal changes that QoI by less than the tolerance, and prove it by running the baseline and the defeatured model on the same mesh settings.

For a bracket meshed at h = 2 mm, a 0.5 mm chamfer and a 1 mm fillet are below h/2. They force tiny elements, slivers and poor aspect ratios without carrying load. A 3 mm bolt hole is not defeatured. It is a load path and a stress riser, so it stays even though it costs elements. A 0.3 mm cosmetic edge break on a non-structural face goes. The rule I apply in practice: remove a feature if its characteristic size is under 0.5h, it is not on the primary load or flow path, and the QoI shift on a paired run is under 1% for stiffness or 2% for peak stress. If any one of those fails, keep it or idealize it.

No Yes Import CAD, record volume and mass Set h from QoI and mesh study Classify each feature by size vs h Remove or idealize candidates Mesh both models, check quality Compare QoI on paired runs QoI shift within tolerance? Freeze defeatured geometry

How I classify and idealize

FeatureSize vs h = 2 mmActionWhy
0.5 mm chamfer0.25hRemove, extend facesBelow mesh resolution, creates slivers
1 mm fillet at rib root0.5hKeep, or replace with 2 mm idealized filletControls peak stress, removal raises stress 15 to 30% in my experience on similar brackets
3 mm bolt hole1.5hKeep, mesh with 4 to 6 elements across diameterLoad introduction, bearing stress
0.2 mm engraved logo0.1hRemoveNo structural or thermal function
Thin wall 1.2 mm0.6hKeep, use shell or mid-surface idealizationSolid meshing would need 2 elements through thickness and still be inaccurate

Idealization is not deletion. A rib that is 1.2 mm thick becomes a shell mid-surface tied to the solid faces. A boss with a hole becomes a rigid or elastic coupling node if the hole detail is not the QoI. A small fillet that matters becomes a larger, meshable fillet and I record the change so the stress is read as comparative, not absolute.

Worked check with real figures

Suppose the original CAD has volume 48,200 mm3 and mass 130 g in aluminium. After removing the chamfer, logo and two 0.8 mm edge fillets, volume is 47,900 mm3, a 0.6% change. That alone proves nothing. I mesh both at h = 2 mm with second order tetrahedra. Baseline: 412,000 elements, 3.1% elements with aspect ratio above 5, tip deflection 1.84 mm, peak von Mises 212 MPa at the rib root. Defeatured: 268,000 elements, 0.9% poor elements, deflection 1.86 mm, peak 218 MPa. Deflection moved 1.1%, peak moved 2.8%. Deflection passes, peak does not pass my 2% limit, so I restore the rib root fillet as a 2 mm idealized fillet. Rerun: peak 214 MPa, 0.9% shift, and the mesh is still 35% cheaper. That paired comparison is the evidence I keep in the model log.

A quick script flags candidates before I touch CAD:

Python
# Python 3.11, checked against a feature list exported from CAD
def classify(size_mm, h_mm, on_load_path):
    ratio = size_mm / h_mm
    if on_load_path:
        return "keep"
    if ratio < 0.5:
        return "remove_candidate"
    if ratio < 1.0:
        return "idealize_or_test"
    return "keep"

features = [("chamfer", 0.5, False), ("rib_fillet", 1.0, True),
            ("bolt_hole", 3.0, True), ("logo", 0.2, False)]
for name, size, load in features:
    print(name, classify(size, 2.0, load))

Failure modes I watch for

Removing a fillet at a re-entrant corner does not just raise peak stress. It can move the location of the peak to the next feature, which makes a mesh convergence study look converged on the wrong spot. Removing a small hole that acts as a stress relief can stiffen the part and shift a natural frequency by 5% or more, which matters if the QoI is modal. In CFD the same logic applies with a different threshold: a 1 mm gap on a 2 mm mesh can be removed for external aero, but a 1 mm cooling passage cannot, because the flow area changes by 50% and the pressure drop follows roughly with area squared.

Detection is concrete. I check volume and surface area change, element quality histograms before and after, and the QoI on two mesh densities. If the defeatured model needs a finer mesh to converge than the baseline, the simplification bought nothing. I also never defeature a feature that carries a boundary condition, a contact pair, or a weld line without replacing it with an equivalent coupling, because the solver will happily produce a clean mesh with the wrong physics.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-40A wake cell has aspect ratio 20, skewness 0.3 and orthogonal quality 0.4. How does each metric affect the CFD solution there, and would you accept or remesh this cell?

The 90-second answer

I would not accept that cell in the wake, even though two of the three metrics look good. Skewness 0.3 and orthogonal quality 0.4 mean the cell shape and face orientation are reasonable. Aspect ratio 20 means it is stretched 20 to 1, and in the wake that stretch is across the shear layer rather than along the flow. That smears the velocity gradient, moves the apparent separation and recirculation length, and adds false diffusion. The fix is to remesh that patch with more isotropic cells, not to refine the long direction.

The three metrics measure different things, so a good score on two cannot compensate for a bad score on the third.

What each metric does in the solver

Aspect ratio is longest dimension divided by shortest dimension. A square is 1. A 20 mm by 1 mm rectangle is 20. Finite volume diffusion and convection fluxes need gradients between cell centres. On a stretched cell the centre to centre distance in the long direction is large, so interpolation to the face is over a long distance and the gradient in the short direction is poorly resolved. In the wake the important gradient is cross stream, across the shear layer. If the short side is cross stream, the layer is under resolved. If the long side is cross stream, the solver averages across the layer. Either way the peak velocity deficit is smeared.

Skewness measures deviation from the ideal shape for that topology. Zero is an equilateral triangle or a cube. One is flat or degenerate. At 0.3 the cell is moderately distorted. Face values are interpolated from cell centres that are offset from the face centroid, so error grows with skewness, but 0.3 is well inside the usual production limit of 0.85. It would not by itself explain a wrong wake.

Orthogonal quality measures how aligned the vector between adjacent cell centres is with the shared face normal. On the Fluent scale used here, 1 is perfect and 0 is degenerate. At 0.4 the non orthogonal correction the solver adds to the flux is moderate. The implicit flux can still dominate, so pressure velocity coupling should remain stable. Below about 0.1 the correction starts to dominate and residuals often stall.

MetricThis cellIdealTypical limitEffect here
Aspect ratio201< 5 in core flowDominant problem. Gradient and interpolation error across shear layer.
Skewness0.30< 0.85Acceptable. Small extra interpolation error.
Orthogonal quality0.41> 0.1, aim > 0.2Acceptable. Correction term stays secondary.

Worked numbers

Take the cell as 20 mm long in the streamwise direction and 1 mm across the shear layer. The shear layer thickness behind a car at the rear window might be of order 10 mm, so a 1 mm cross stream spacing gives roughly 10 cells across the layer, which sounds fine. The problem is the 20 mm streamwise length. A vortex or separation bubble of length 50 mm is then represented by only two to three cells in the streamwise direction. Numerical diffusion acts over that 20 mm stencil, so the recirculation is shortened and the drag contribution from the wake is biased.

Contrast that with a boundary layer cell of aspect ratio 200, 20 mm long along the wall and 0.1 mm normal to it. There the long direction follows the flow, the quantity of interest varies slowly along the wall and rapidly normal to it, and the stretch is intentional. The same number in the wake has the opposite alignment to the physics.

Checking the numbers yourself

For a quadrilateral cell the aspect ratio and a skewness proxy can be recomputed in a few lines, which is useful when a mesh report only gives a combined quality score:

Python
import math

def quad_metrics(p):  # four (x, y) corners in order
    edges = [math.dist(p[i], p[(i + 1) % 4]) for i in range(4)]
    aspect_ratio = max(edges) / min(edges)
    angs = []
    for i in range(4):
        a, b, c = p[i - 1], p[i], p[(i + 1) % 4]
        v1 = (a[0] - b[0], a[1] - b[1])
        v2 = (c[0] - b[0], c[1] - b[1])
        cosang = (v1[0] * v2[0] + v1[1] * v2[1]) / (math.hypot(*v1) * math.hypot(*v2))
        angs.append(math.degrees(math.acos(max(-1.0, min(1.0, cosang)))))
    skewness = max(abs(a - 90.0) for a in angs) / 90.0  # 0 ideal, 1 degenerate
    return round(aspect_ratio, 2), round(skewness, 2), [round(a, 1) for a in angs]

print(quad_metrics([(0, 0), (20, 0), (20, 1), (0, 1)]))  # (20.0, 0.0, [90, 90, 90, 90])
print(quad_metrics([(0, 0), (20, 0), (17, 1), (3, 1)]))  # (20.0, 0.3, [73, 107, 73, 107])

The first case has perfect angles and skewness 0, yet aspect ratio 20 on its own is enough to reject it in the wake. That is the point of reporting the three metrics separately.

What I would do next

I would remesh the wake patch with a size function that limits aspect ratio to about 5 and keeps skewness below 0.85 and orthogonal quality above 0.1, then rerun and compare recirculation length and drag against the original mesh. If drag changes by more than the discretisation uncertainty from a mesh convergence study, the original cell was biasing the answer. Splitting the existing cell only in the short direction would make aspect ratio worse, so local isotropic remeshing is the correct fix.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-41For a transonic airfoil with a shock on the suction side, how does a gradient-based error indicator decide which cells to refine, and how does that differ from a residual-based indicator?

The 90-second answer

A gradient indicator refines where the solution changes fast. For a shock on the suction side of a transonic airfoil, that means cells with a large pressure gradient get split, cells in smooth freestream flow stay coarse. A residual indicator refines where the discrete equations are not satisfied, which includes shocks but also regions where the gradient looks modest yet the solution is still under-resolved. The trade-off is cost and reliability against sensitivity. Gradient indicators are cheap and easy to debug. Residual indicators catch more error sources but need the PDE residual and face fluxes from the solver.

The AMR loop is the same either way. Solve on the current mesh, compute an indicator per cell, mark cells above a rule, refine those cells, transfer the solution, and solve again.

No Yes Solve on current mesh Compute indicator per cell Mark cells above threshold Refine marked cells Transfer solution and resolve Indicator and drag converged? Accept mesh

How the gradient indicator works

For each cell, scale the pressure gradient by the cell size and a reference pressure:

Python
import numpy as np

def gradient_indicator(grad_p, p_ref, h):
    # grad_p: |grad p| in each cell, h: cell size, p_ref: freestream pressure
    return h * grad_p / p_ref

ind = gradient_indicator(grad_p, p_inf, h)
marked = ind > 0.05
print(f"marked {marked.mean():.1%} of cells")

A threshold of 0.05 means a cell is refined when the pressure change across it exceeds about 5 percent of freestream pressure. At a shock, pressure jumps by a large fraction of $p_\infty$ over one or two cells, so the indicator spikes there. In the freestream, gradients are near zero and the indicator stays below threshold. The result is a refined band around the shock and the boundary layer, with coarse cells elsewhere.

Refinement is usually octree subdivision in 3D, with neighbouring cells allowed to differ by at most one level. That limit keeps the transition gradual. Without it, interpolation across a jump from a fine cell to a very coarse neighbour creates oscillations, and the indicator then flags its own artefact.

Residual indicator, and the comparison

A residual indicator combines two terms. The first is the PDE residual inside the cell, how far the computed solution is from satisfying the equations. The second is the jump in flux across each face between neighbours. A large jump means the two cells disagree about what crosses their shared face, which happens at under-resolved shocks and also at poorly resolved shear layers.

PropertyGradient indicatorResidual indicator
Needs from solverPressure gradient onlyPDE residual and face fluxes
Cost per passLow, one gradient evaluationHigher, residual assembly each pass
DetectsSharp features such as shocksSharp features plus smooth but under-resolved regions
RiskCan miss error where gradients are smallMore sensitive to solver internals and scaling choices

For a first AMR setup on a shock problem, I would start with the gradient indicator. It is enough to capture the shock, and if the refined region looks wrong the cause is usually obvious. I would move to a residual indicator if drag keeps changing between passes while the gradient indicator marks fewer and fewer cells. That pattern means error is present where gradients are not large, for example in the wake.

Worked trace

Hypothetical numbers for a transonic airfoil, starting from 200,000 cells:

PassCellsCells markedDrag coefficientChange
1200,00018%0.02140baseline
2520,00012%0.02085-2.6%
3890,0009%0.02062-1.1%
41,240,0007%0.02054-0.4%

The marked fraction falls each pass because the shock is already resolved and fewer new cells cross the threshold. I would stop when the drag change drops below a stated tolerance, here 0.5 percent, rather than when the cell count reaches a target. Stopping on cell count alone can accept a mesh where drag is still moving.

One failure mode to watch is refining the wrong feature. A gradient indicator will refine a contact discontinuity or a wake shear layer even if neither affects drag much. Tracking drag at each pass exposes that. If drag is flat while refinement continues, the indicator is spending cells where the quantity of interest does not care, and a goal-oriented indicator that weights error by its effect on drag would be the next step.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-42What is the difference between residual-based and solution-change convergence criteria in an iterative solver, and why should you require both?

The 90-second answer

Residual convergence asks whether the discrete equations are satisfied. Solution-change convergence asks whether the answer has stopped moving. A solver is converged only when both are small, for several iterations in a row, and the quantity of interest has also stopped moving.

For a linear system A x = b, the residual at iterate k is r_k = b - A x_k. The usual test is the relative residual ||r_k|| / ||b||. The solution change is ||x_k - x_{k-1}|| / ||x_k||, or the maximum absolute change in a field. In the example below I use tol_r = 1e-5 for the relative residual and tol_x = 1e-5 for the relative solution change, and I require both to hold for three consecutive iterations.

Neither test alone is safe. A small residual does not guarantee a small error. The error satisfies ||x - x_k|| <= ||A^{-1}|| * ||r_k||, so an ill-conditioned A can turn a tiny residual into a large error in a sensitive mode. A small solution change does not guarantee a small residual either. A slowly converging iteration, or a heavily under-relaxed update, can creep by tiny amounts each step while still far from the solution.

Worked trace

Hypothetical trace from a steady solver, with tol_r = 1e-5 and tol_x = 1e-5:

IterRel. residualRel. solution changeVerdict
1002.0e-34.0e-4Both fail
2003.0e-58.0e-6Change passes, residual fails, continue
3008.0e-62.0e-6Both pass, first consecutive pass
4005.0e-61.0e-6Both pass, second consecutive pass
5004.0e-68.0e-7Both pass, third consecutive pass, stop

Stopping at iteration 200 on solution change alone would be premature, because the residual is still above tolerance and the equations are violated by 0.003 percent in relative terms. Stopping on a single pass at iteration 300 would also be premature, because one lucky iteration can dip below a threshold and then bounce back. The three-pass rule is what makes iteration 500 the stop point.

How I set it in code

Python
# Python 3.11, checked against NumPy 1.26 conventions
import numpy as np

def converged(residual_norm, b_norm, x, x_prev, tol_r=1e-5, tol_x=1e-5):
    rel_residual = residual_norm / max(b_norm, 1e-30)
    rel_change = np.linalg.norm(x - x_prev) / max(np.linalg.norm(x), 1e-30)
    return rel_residual < tol_r and rel_change < tol_x, rel_residual, rel_change

In production I count consecutive passes from that predicate, reset the count on any failure, and log both numbers every iteration. I stop only when the count reaches three.

CriterionWhat it detectsBlind spot
Relative residualEquations not yet satisfiedIll-conditioning can hide a large error behind a small residual
Relative solution changeIteration still moving the fieldSlow creep or under-relaxation can look still while far from the solution
Quantity of interest, for example drag or peak stressEngineering answer still driftingCan plateau by coincidence while local fields are still changing

Failure modes I watch for

Residual stalls at 1e-3 while solution change falls below 1e-5. That pattern usually means the iteration is stuck, the preconditioner is poor, or a limiter or clipping step is preventing further reduction. Tightening the solution-change tolerance will not fix it.

Residual falls steadily but solution change stays large. That is normal early in a run and also a sign of a stiff or ill-conditioned problem. Keep iterating, and check whether the quantity of interest is the sensitive mode.

Both pass but the quantity of interest keeps moving. That happens when the global norms are dominated by large regions and a small region, such as a separation zone or a stress concentration, is still evolving. I then tighten both tolerances by a factor of ten and rerun from the current state to see whether the quantity of interest moves by more than the reporting tolerance.

The practical rule: set the residual tolerance from the accuracy you need in the answer, set the solution-change tolerance at or tighter than that, require both for consecutive iterations, and never report a converged result without plotting both histories.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-43When does a linear solver suffice for a structural FEA, and when do you need Newton-Raphson, and how do you make that iteration converge for large rotations and contact?

The 90-second answer

A linear solver assumes stiffness does not change with displacement, so the whole problem is one system, K u = f, solved by one factorisation. That holds for small strains, small rotations, linear elasticity and fixed contact status. Superposition then works and you can reuse K for many load cases.

A nonlinear solver solves R(u) = 0, where R(u) = F_int(u) - F_ext. Newton-Raphson linearises that residual at the current guess and iterates:

K_T(u_k) * delta_u = -R(u_k), then u_{k+1} = u_k + delta_u, with K_T = dR/du the tangent stiffness.

Near a smooth solution it converges quadratically, so error roughly squares each iteration. Far from the solution, at a limit point, or with contact switching, it can diverge or stall. Load stepping, a consistent tangent, line search and, for snap-through, arc-length control are what make it converge in practice.

Worked trace: quadratic convergence

Solve f(u) = u^2 - 2 = 0 with Newton, u_{k+1} = u_k - f(u_k)/f'(u_k), starting at u_0 = 1.5. True root sqrt(2) = 1.41421356.

ku_kerrorerror ratio
01.500000008.58e-2-
11.416666672.45e-30.029
21.414215692.13e-68.7e-4
31.414213561.6e-127.5e-7

The error does not shrink by a constant factor. It shrinks by roughly the previous error, which is the signature of quadratic convergence. A fixed-point or secant method would show a steadier ratio and need more iterations.

Linear versus nonlinear in an FEA run

AspectLinearNonlinear (Newton)
---------
---------
---------
---------
---------
---------
---------
StiffnessConstant K, factorised onceK_T(u) rebuilt or updated each iteration
Load stepsOne step for proportional loadingMany increments, each with 2 to 10 Newton iterations
SuperpositionValidInvalid once geometry, material or contact changes
Typical triggerStress well below yield, rotations under a few degreesPlasticity, large rotation, buckling, contact, thermal bowing
Cost driverOne sparse factorisationFactorisations per iteration, plus line search evaluations

A bracket that stays elastic and rotates 0.5 degrees can be linear. The same bracket with a plastic hinge at the root, a bolted joint that opens, or a 0.15 mm thermal bow that changes the flow gap cannot. The stiffness in the second case depends on the answer you are solving for.

Making Newton converge

Python
import numpy as np

def newton(residual, jacobian, u0, tol=1e-8, max_iter=20):
    u = u0.copy()
    for k in range(max_iter):
        R = residual(u)
        rnorm = np.linalg.norm(R, ord=np.inf)
        if rnorm < tol:
            return u, k, True
        du = np.linalg.solve(jacobian(u), -R)
        # Backtracking line search: accept only a step that reduces ||R||
        alpha = 1.0
        while alpha > 1e-4:
            u_trial = u + alpha * du
            if np.linalg.norm(residual(u_trial), ord=np.inf) < (1 - 1e-4 * alpha) * rnorm:
                break
            alpha *= 0.5
        u = u + alpha * du
    return u, max_iter, False

Three choices decide most failures I see in production runs.

  1. Tangent quality. For plasticity, use the consistent (algorithmic) tangent from the return-mapping update, not the continuum elastoplastic tangent. The consistent form restores quadratic convergence for the discretised problem. With the wrong tangent you often get linear convergence, 15 iterations instead of 4, and a false conclusion that the model is ill conditioned.

  2. Step size and initial guess. Start each load increment from the previous converged state and keep increments small enough that the active set (yielded points, contact nodes) changes gradually. If the residual norm grows for two iterations, cut the increment in half rather than forcing more iterations at the same load. Modified Newton, which freezes K_T and its factorisation for several iterations, is cheaper per iteration but converges linearly. It pays off when factorisation dominates and the tangent changes slowly, for example elastic contact with a stable active set.

  3. Convergence test. Test the residual, not only the displacement increment. A common setting is ||R||_inf <= 1e-6 * ||F_ext||_inf together with a displacement check ||delta_u|| <= 1e-5 * ||u||. Displacement alone can pass while equilibrium is still off by a large force at a stiff contact node.

Failure modes that need a different scheme

At a snap-through or snap-back limit point, K_T becomes singular and Newton under load control has no nearby solution at the next load level. The iteration jumps, residual oscillates, and halving the step does not fix it because the branch itself turns back. Arc-length (Riks) control fixes this by constraining delta_u and delta_lambda together, so the solver follows the equilibrium path past the limit point.

Contact is non-smooth. A node either sticks, slips or separates, so the residual is only piecewise smooth and quadratic convergence is lost at the switching iteration. Chattering contact, where nodes toggle each iteration, usually means the penalty or augmented Lagrangian parameter is too stiff for the increment size, or the initial penetration is too large. Smaller increments and a consistent contact tangent help more than tightening the tolerance.

If Newton diverges from a poor first guess, for example starting a large-rotation truss from the undeformed shape under full load, the fix is continuation: ramp the load in 10 to 50 increments, or ramp a load factor lambda from 0 to 1 while holding the previous solution as the guess. That is slower per run and far cheaper than debugging a diverged one.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-44Walk me through Newmark-beta integration for M u'' + C u' + K u = F(t), and how you choose beta and gamma for a bracket impact run without damping high modes away?

The 90-second answer

Newmark-beta advances displacement, velocity and acceleration together using two parameters, gamma and beta, that weight the acceleration at the new step. For the linear system M u'' + C u' + K u = F(t), each step solves a modified static problem with effective stiffness K_hat = K + gamma/(beta*dt) * C + 1/(beta*dt^2) * M. That solve is the cost of the method. One factorisation of K_hat can be reused for every step when M, C, K and dt stay constant, which is why it is cheap for long transient runs.

Unconditional stability requires gamma >= 0.5 and beta >= (gamma + 0.5)^2 / 4. The common choice gamma = 0.5, beta = 0.25 (average acceleration) is second order and adds no algorithmic damping. Second order requires gamma = 0.5 exactly. Raising gamma above 0.5 drops the method to first order and adds numerical damping that grows with frequency, so high modes die faster than the physical ones. That helps when a mesh has spurious high frequency modes, and hurts when those modes carry real impact energy.

Python
import numpy as np

def newmark_step(M, C, K, F_new, u, v, a, dt, gamma=0.5, beta=0.25, K_hat=None):
    # Predictor from current state, then solve for u_new
    a0 = 1.0 / (beta * dt**2); a1 = gamma / (beta * dt)
    a2 = 1.0 / (beta * dt);   a3 = 1.0 / (2.0 * beta) - 1.0
    a4 = gamma / beta - 1.0;  a5 = dt * (gamma / (2.0 * beta) - 1.0)
    a6 = dt * (1.0 - gamma);  a7 = gamma * dt
    if K_hat is None:
        K_hat = K + a1 * C + a0 * M
    F_hat = (F_new + M @ (a0 * u + a2 * v + a3 * a)
             + C @ (a1 * u + a4 * v + a5 * a))
    u_new = np.linalg.solve(K_hat, F_hat)
    a_new = a0 * (u_new - u) - a2 * v - a3 * a
    v_new = v + a6 * a + a7 * a_new
    return u_new, v_new, a_new

The predictor uses u, v, a at t. The corrector enforces equilibrium at t + dt through F_hat. In a nonlinear run, K and the residual are updated inside a Newton loop and the same formulas apply with the tangent stiffness.

ChoiceOrderAlgorithmic dampingWhen I use it
gamma=0.5, beta=0.252noneDefault for impact and vibration where energy matters
gamma=0.5, beta=1/62none, but conditional stabilityLinear acceleration form, needs dt <= 0.551 * T_min for the highest mode kept
gamma=0.6, beta=0.30251strong, high modes firstMesh with noisy high modes, or a force history with step discontinuities, only if the loss below is acceptable
gamma=1.0, beta=0.251very strongOnly for quasi-static loading applied in steps, accuracy drops fast

Worked trace: period error and damping

Take an undamped bracket mode at 10 Hz, so T = 0.1 s, omega = 62.8 rad/s. With average acceleration, the numerical period ratio is approximately T_tilde/T = 1 + (pi^2/3)*(dt/T)^2 for small dt/T. The table shows what that means in practice. The gamma=0.6 column is the exact spectral radius per step for beta = 0.3025, raised to the number of steps in 10 cycles.

dtdt/TSteps per periodPeriod error, gamma=0.5Peak after 10 cycles, gamma=0.5Peak after 10 cycles, gamma=0.6
0.001 s0.011000.03%1.0000.82
0.005 s0.05200.8%1.0000.38
0.010 s0.10103.3%1.0000.17
0.020 s0.20512%1.0000.06

Two lessons fall out. First, stability is not accuracy. Average acceleration stays stable at dt = 0.02 s and still gives a period 12% long, so a 10 Hz mode looks like 8.9 Hz and phase lags accumulate over a 2 s impact. I keep dt <= T/20 for the highest mode that contributes to stress, and check with a halved step. Second, gamma=0.6 is not a mild filter. Even at dt/T = 0.01 it removes 18% of amplitude in 10 cycles, and at dt/T = 0.05 it removes 62%. If the impact excites a 200 Hz local mode, that mode is damped far more, which can hide a peak stress and also degrades the solution to first order.

not converged converged State u, v, a at t Build F_hat from F(t+dt) Solve K_hat u_new = F_hat Correct a_new, v_new Check equilibrium residual Advance to t+dt

Choosing parameters for an impact run

Start with average acceleration and physical damping from a Rayleigh model fitted to two measured modes, for example 2% at 10 Hz and 50 Hz. Run with dt = T_high/20, where T_high comes from the highest mode with meaningful modal mass, not the highest eigenvalue of the mesh. Then repeat at dt/2 and compare peak stress and time of peak. If peak stress moves by more than about 2%, the step is too large or gamma is eating the response.

Switch to gamma around 0.55 to 0.6 only when the force history has a discontinuity, such as a dropped mass or a contact strike, and the response shows ringing at the mesh frequency that does not change with dt. Expect first order accuracy and the losses in the table, document the extra damping as numerical, not physical, and report the average acceleration result alongside it. A reviewer can then see whether the design margin depends on a solver setting.

Failure modes I check first: a factorisation reused after dt changed, which silently uses the wrong K_hat; lumped mass with rotational inertia set to zero, which creates zero energy modes that Newmark will happily integrate; and a nonlinear run where the residual is checked on displacement increment alone while the force residual stays large. Energy balance over the run catches the last one. For an undamped linear run, total energy should stay within the period error band, and a drift of several percent in 10 cycles points at the parameters or the mass matrix, not at the physics.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-45Walk me through how broad-phase and narrow-phase collision detection work for 10,000 rigid bodies in a real-time simulation, and how you choose between sweep-and-prune, spatial hashing and BVH?

The 90-second answer

Collision detection is split because the exact test is too expensive to run on every pair. With 10,000 bodies, all-pairs is 10,000 x 9,999 / 2 = about 50 million pairs per step. The broad phase uses cheap bounding volumes to discard most of those pairs and emit a candidate list. The narrow phase runs an exact geometric test, such as SAT for convex polygons, GJK for convex shapes, or a triangle mesh test, only on candidates and, if they overlap, builds a contact manifold with penetration depth and normal for the solver.

The broad phase choice depends on motion coherence, size variance and density. Sweep-and-prune wins when bodies move a little per frame and sizes are similar. A spatial hash wins when bodies are roughly uniform in size and move a lot, or when you need predictable insertion. A BVH wins when sizes vary widely, when you have static geometry mixed with dynamic bodies, or when you need ray and overlap queries against the same structure.

Broad phase: sweep-and-prune

Give each body an axis-aligned bounding box, or AABB, fattened by a margin for expected motion. Sort box endpoints on one axis, usually x. Sweep in increasing order, maintain an active list of boxes whose x intervals overlap the current box, and test the remaining axes for those active boxes. If all three axes overlap, emit the pair.

Temporal coherence is the key optimisation. Between frames most bodies move less than their box size, so the sorted endpoint list barely changes. Insertion sort re-sorts it in close to O(n) per frame instead of O(n log n), and pairs persist until their intervals separate. That is why SAP is the default in many physics engines for scenes with many small, continuously moving bodies.

Worked trace, x intervals only, bodies A to E:

Sweep positionEventActive set after eventCandidate pairs emitted
0A startsAnone
2B startsA, BA-B
5A endsBnone
6C startsB, CB-C
7D startsB, C, DB-D, C-D
9B endsC, Dnone
11E startsC, D, EC-E, D-E

Only five x-overlap candidates reach the y and z test, even though five bodies allow ten pairs. In a dense pile the active set grows and SAP degrades toward O(n^2) in the worst case, which is the signal to switch structures.

C++
// SAP endpoints, re-sorted each frame with insertion sort.
// Endpoint { value, bodyId, isEnd } sorted by value.
for (int i = 1; i < endpoints.size(); ++i) {
    Endpoint key = endpoints[i];
    int j = i - 1;
    while (j >= 0 && endpoints[j].value > key.value) {
        endpoints[j + 1] = endpoints[j];
        --j;
    }
    endpoints[j + 1] = key;
}

Spatial hash and BVH

A spatial hash divides space into cells of size near the median body diameter. Each body is inserted into every cell its AABB touches, or into one cell by its centre with a neighbour search. Pairs are generated only within a cell and its neighbours. Average cost is O(n + k) for k candidates, with no sorting. It fails when cell size is wrong: cells much larger than bodies create many false candidates, cells much smaller split one large body across many cells and duplicate pairs. Hash collisions also need handling, usually by storing a small vector per cell rather than a single body.

A BVH builds a tree of AABBs by recursively splitting the body set, for example by longest axis median split. Querying one body traverses the tree and prunes whole subtrees whose AABB misses. Build is O(n log n), query is roughly O(log n + k) for sparse scenes, and the same tree serves ray casts and closest-point queries. The cost is memory and refitting: when bodies move, leaf boxes change and internal nodes must be refit bottom-up, or the tree is rebuilt periodically. A BVH handles a scene with a huge static ground mesh plus small dynamic debris far better than SAP, where the ground box would stay active for the entire sweep.

Yes No Integrate bodies Update AABBs Broad phase: SAP, hash or BVH Candidate pairs Narrow phase: SAT, GJK or mesh test Overlap? Build contact manifold Discard pair Contact solver

Narrow phase and failure modes

For convex rigid bodies, GJK tests overlap without building faces, and EPA or a SAT pass on the closest features gives penetration depth and normal. For concave meshes, engines decompose the mesh into convex hulls or test triangles against the other body, then clip the incident face to the reference face to get a manifold with up to four points. A single point contact lets a box rock on a corner, so the manifold matters as much as the boolean result.

Three failures show up in testing. First, tunnelling: a bullet at 60 m/s with a 0.02 s step moves 1.2 m per step and can pass through a 0.1 m wall without ever overlapping. The fix is a swept AABB in the broad phase or a continuous test in the narrow phase, at extra cost per fast body. Second, stale fat boxes: if the margin is too small, a fast body escapes its box and pairs are missed; if it is too large, candidate count explodes and the narrow phase dominates. Third, resting contact jitter: SAP pairs flicker as boxes slide past an endpoint, and the solver sees contacts appear and disappear. Persistent pair caching and a small separation tolerance in the narrow phase smooth that out.

Rule of thumb for the interview: start with SAP for a uniform, coherent dynamic scene, move to a spatial hash when teleporting or spawning breaks coherence, and move to a BVH when size variance or static geometry dominates. Measure candidate pairs per body, not just frame time. If candidates per body rises above roughly ten, the broad phase is no longer filtering and the structure, not the narrow phase, is the bottleneck.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-46For a serial kinematic chain, how does the Jacobian map joint velocities to end-effector velocity, and what does one column of the Jacobian represent?

The 90-second answer

For a serial chain the (geometric) Jacobian is the linear map from joint velocities to end-effector velocity:

$$ \dot{q} ;\mapsto; \begin{bmatrix} v_e \ \omega_e \end{bmatrix} = J(q),\dot{q} $$

$v_e$ is linear velocity of the end-effector origin, $\omega_e$ its angular velocity, both expressed in the same frame (usually base/world). $J$ is $6 \times n$ for $n$ joints. Its $i$-th column is the twist that joint $i$ alone produces when $\dot{q}_i = 1$ and every other joint rate is zero. That single fact gives the whole construction: build each column from the joint axis and the vector from that joint to the end effector, then velocity propagation is one matrix-vector product per step, no differentiation of the forward kinematics needed.

Column construction

For a revolute joint $i$ with unit axis $z_{i-1}$ (in world coordinates) and origin $p_{i-1}$:

$$ J_{v,i} = z_{i-1} \times (p_e - p_{i-1}), \qquad J_{\omega,i} = z_{i-1} $$

For a prismatic joint with unit axis $z_{i-1}$:

$$ J_{v,i} = z_{i-1}, \qquad J_{\omega,i} = 0 $$

So a revolute column is a lever arm: magnitude $|p_e-p_{i-1}|$ times the sine of the angle between axis and lever, direction perpendicular to both. A prismatic joint contributes translation only. Stack the columns in joint order and you have $J$. In a simulator you recompute $J$ from the current $q$ each step, because $z_{i-1}$ and $p_{i-1}$ rotate with the upstream joints.

Worked trace: planar 2-link arm

Take $L_1 = 0.4$ m, $L_2 = 0.3$ m, $q_1 = 0$, $q_2 = 90^\circ$. Then $p_1 = (0.4, 0)$ and $p_e = (0.4, 0.3)$ m. Both axes are $z = (0,0,1)$.

Column$p_e - p_{i-1}$ (m)$J_{v,i} = z \times (p_e-p_{i-1})$ (m)$J_{\omega,i}$
1$(0.4, 0.3)$$(-0.3, 0.4)$$(0,0,1)$
2$(0, 0.3)$$(-0.3, 0)$$(0,0,1)$

$$ J = \begin{bmatrix} -0.3 & -0.3 \ 0.4 & 0 \ 0 & 0 \ 0 & 0 \ 0 & 0 \ 1 & 1 \end{bmatrix} $$

Command $\dot{q} = [0.5, -0.2]^T$ rad/s. Then $v_e = J_v \dot{q} = (-0.3\cdot0.5 + -0.3\cdot(-0.2),; 0.4\cdot0.5 + 0) = (-0.09, 0.20)$ m/s, and $\omega_e = 0.5 - 0.2 = 0.3$ rad/s about $z$. You can check the first component by hand: joint 1 swings the whole arm, joint 2 only the forearm, and the signs follow from the lever arms above.

In code

Python
import numpy as np

def jacobian_revolute(axes, origins, p_e):
    # axes: (n,3) unit joint axes in world frame, origins: (n,3) joint origins
    n = len(axes)
    J = np.zeros((6, n))
    for i in range(n):
        J[0:3, i] = np.cross(axes[i], p_e - origins[i])
        J[3:6, i] = axes[i]
    return J

axes = np.array([[0, 0, 1], [0, 0, 1]], float)
origins = np.array([[0, 0, 0], [0.4, 0, 0]], float)
p_e = np.array([0.4, 0.3, 0.0])
J = jacobian_revolute(axes, origins, p_e)
print(J @ np.array([0.5, -0.2, 0, 0, 0, 0]))  # [-0.09  0.20  0.  0.  0.  0.30]

Replace the cross product with $J_{v,i} = z_{i-1}$ and $J_{\omega,i} = 0$ for a prismatic joint. The axes and origins come from the same forward kinematics pass that gives $p_e$, so in a loop you compute frames once and reuse them for both pose and Jacobian.

Where it bites

$J$ depends only on configuration, not on $\dot{q}$, which is why the same matrix serves for velocity propagation, for inverse velocity control ($\dot{q} = J^+ v_{desired}$), and for mapping end-effector forces to joint torques ($\tau = J^T F$). The failure mode to watch is rank loss: when columns become linearly dependent, $J$ is singular, some end-effector directions need infinite joint rates, and $J^+$ blows up. In the trace above, straightening the arm ($q_2 = 0$) makes both columns point the same way in the plane and the radial direction becomes unreachable. In simulation that shows up as a commanded Cartesian velocity producing a huge $\dot{q}$ spike for one step. Damping ($J^T(JJ^T + \lambda^2 I)^{-1}$) or a manipulability check on $\det(JJ^T)$ before inverting is the usual guard, and it is worth logging the smallest singular value of $J$ alongside the velocity so a near-singular pass is visible in the data rather than inferred from a jittery trajectory.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-47Your simulated actuator loop shows 6 dB gain margin but only 12 degrees phase margin at crossover, and a notch filter improves phase margin while worsening gain margin. How do you compute both margins from the open-loop response and decide which one limits robustness?

The 90-second answer

For open-loop L(jw), find two different crossovers. Gain margin is read where the phase is -180 degrees. Phase margin is read where the magnitude is 1 (0 dB). They answer different questions, so a healthy value for one does not rescue a poor value for the other.

GM = 1 / |L(jw_pc)|, reported as -20*log10|L(jw_pc)| dB, where angle(L(jw_pc)) = -180 degrees. PM = 180 + angle(L(jw_gc)), in degrees, where |L(jw_gc)| = 1.

In your case PM = 12 degrees is the limiter. A 6 dB GM tolerates a gain error of about a factor of 2 before the Nyquist plot reaches -1. A 12 degree PM tolerates very little extra phase lag. An 8 ms transport or computation delay at a gain crossover of 18 rad/s removes 18 * 0.008 = 0.144 rad, or 8.3 degrees, leaving under 4 degrees. That is the failure mode I would chase first, not the notch.

Worked trace

Hypothetical sweep from the simulated loop, interpolated between samples:

| w (rad/s) | |L| | angle(L) (deg) | Reading | | --- | --- | --- | --- | | 12 | 1.80 | -145 | | | 18 | 1.00 | -168 | gain crossover, PM = 180 - 168 = 12 deg | | 30 | 0.45 | -175 | | | 42 | 0.25 | -180 | phase crossover, GM = 1/0.25 = 4, or 12.0 dB | | 60 | 0.18 | -195 | |

Note the inconsistency to check in an interview: if the measured GM is only 6 dB, then |L| at the true phase crossover must be 0.50, not 0.25. Recompute from the interpolated crossing, not from the nearest sample. With coarse frequency spacing the nearest sample can move the reported margin by several dB or degrees.

Computing it from a simulation sweep

Python
import numpy as np

def margins(w, L):
    mag = np.abs(L)
    phase = np.degrees(np.unwrap(np.angle(L)))  # continuous, not wrapped to [-180, 180]
    # Gain crossover: interpolate where mag crosses 1
    i = np.where(np.diff(np.sign(mag - 1.0)))[0][0]
    f = (1.0 - mag[i]) / (mag[i + 1] - mag[i])
    phase_gc = phase[i] + f * (phase[i + 1] - phase[i])
    pm = 180.0 + phase_gc
    # Phase crossover: interpolate where phase crosses -180
    j = np.where(np.diff(np.sign(phase + 180.0)))[0][0]
    f = (-180.0 - phase[j]) / (phase[j + 1] - phase[j])
    mag_pc = mag[j] + f * (mag[j + 1] - mag[j])
    gm_db = -20.0 * np.log10(mag_pc)
    return gm_db, pm

Unwrapping matters. Wrapped phase jumps from +179 to -179 and a naive search finds a false crossover. In a discrete simulation, evaluate L at the sample rate actually used, including the zero-order hold and one-step computation delay. A continuous-time margin computed from the plant alone will overstate PM.

Why the notch trades one margin for the other

A notch placed near a flexible mode reduces |L| at high frequency, which can push the phase crossover out and raise GM. The same filter adds phase lag below its centre frequency. If that lag lands near w_gc, PM falls. Moving the notch up in frequency protects PM but leaves the flexible mode inside the loop, so GM falls. There is no free improvement: you are reshaping where the Nyquist curve passes near -1.

Open-loop sweep L jw Phase = -180 deg GM from magnitude there Magnitude = 1 PM from phase there Which margin is eroded by delay, sampling, gain error

Failure modes and limits

  1. Multiple crossovers. A flexible mode or a notch can create two phase crossovers. The smallest GM and the smallest PM govern, and conditional stability is possible: stable at nominal gain, unstable at lower gain. Check the full Nyquist encirclement count, not just the first crossing.
  2. Shallow gain crossover. If |L| crosses 0 dB with a shallow slope, a small gain change moves w_gc a long way and PM changes fast. PM alone then understates sensitivity. Look at the slope of phase versus frequency at w_gc.
  3. Non-minimum phase and delay. Right-half-plane zeros and pure delay add phase lag with no magnitude change. GM measured at the old phase crossover looks unchanged while the true crossover moves to lower frequency. Recompute both after adding the delay term exp(-s*tau).
  4. Nonlinearity. Margins are linear, small-signal results. Actuator saturation, rate limits and backlash in the simulation can produce limit cycles with margins that look acceptable on the Bode plot. Verify with a large-signal step and a describing-function check if saturation is present.
  5. MIMO coupling. For a multi-axis stage, SISO margins on each diagonal do not bound the coupled return difference. Use the smallest singular value of I + L as a check when axes interact.

Decision rule I would defend: fix PM first by reducing delay, raising w_gc only if the flexible mode allows it, or adding lead compensation centred at w_gc. Then recheck GM, because lead at w_gc usually raises high-frequency gain and can lower GM. Report both margins with the frequency at which each was measured, the sample rate, and the delay included in the model. A margin without its crossover frequency is not reproducible.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-48A simulated steering actuator saturates at ±30° and slews at 60°/s. How do you model both limits in the control loop, and what goes wrong if you only clamp the output?

The 90-second answer

Model saturation and rate limit as separate blocks in the actuator path, in physical order: controller output, then rate limiter, then position clamp, then the plant. Clamping only the final output hides the rate limit, so the controller thinks it can move the actuator in one step when the real hardware needs 0.5 s to slew 30 degrees. That mismatch is what creates windup, overshoot and limit cycles in simulation that never appear in a linear test.

Assume a steering actuator with position limit ±30°, slew limit 60°/s, simulated at dt = 0.01 s with a PID controller. The rate limit alone bounds the fastest possible move:

t_slew = Δθ / rate = 30° / 60°/s = 0.5 s

A 45° step command therefore cannot be tracked in one sample. The actuator can only reach the +30° clamp, so it needs 0.5 s of slewing to get there, plus settling. If the integrator keeps accumulating error during that 0.5 s, it will still be charged when the actuator arrives, and the loop overshoots when the reference later moves.

How to implement it

Apply the rate limit to the commanded increment per step, not as a post-hoc clamp on position. At dt = 0.01 s the maximum increment is 0.6° per step. Then clamp position. Then feed the actual applied actuator position back to the controller for anti-windup, not the requested position. Keep a separate state for the rate-limited command, because the plant position lags behind it.

Python
# Python 3.11, first-order steering plant with lag
import math

DT = 0.01
POS_LIM = math.radians(30.0)
RATE_LIM = math.radians(60.0)  # rad/s

def rate_limit(prev_cmd, cmd, dt=DT):
    max_step = RATE_LIM * dt
    return prev_cmd + max(-max_step, min(max_step, cmd - prev_cmd))

def saturate(x):
    return max(-POS_LIM, min(POS_LIM, x))

Kp, Ki, Kd = 2.0, 0.8, 0.05
Kt = 1.0  # back-calculation tracking gain, 1/s
integral = 0.0  # integral contribution to output, not raw error integral
prev_act = 0.0
limited_cmd = 0.0
act_pos = 0.0

for k in range(200):
    ref = math.radians(45.0)  # step beyond the limit
    err = ref - act_pos
    deriv = -(act_pos - prev_act) / DT  # derivative on measurement
    u_unsat = Kp * err + integral + Kd * deriv
    limited_cmd = rate_limit(limited_cmd, u_unsat)
    u_applied = saturate(limited_cmd)
    # plant: actuator follows applied command with 80 ms lag
    act_pos += (u_applied - act_pos) * DT / 0.08
    # back-calculation: bleed integral toward the applied output
    integral += Ki * err * DT + Kt * (u_applied - u_unsat) * DT
    prev_act = act_pos

Two details matter. First, the derivative term uses measured position, not error, so a step reference does not produce a derivative kick that the rate limiter then smears into a long transient. Second, substep the limiter if dt is large. At dt = 0.1 s the allowed step is 6°, and a single update can jump past the target and hunt around it. Keep dt at most one tenth of the slew time across the full range, here 0.05 s, or integrate the limiter analytically within the step.

What the trace looks like

Hypothetical run, 45° step, dt = 0.01 s, no anti-windup versus back-calculation:

t (s)Actuator (°)Integral contribution no AWIntegral contribution with AWError (°) with AW
0.000.00.00.045.0
0.2514.86.51.930.2
0.5029.612.22.515.4
0.7530.015.82.615.0
1.5030.021.12.615.0
2.5028.124.82.616.9

Without anti-windup the integral keeps growing while the actuator is pinned at 30°. When the reference later drops, that stored charge drives the actuator hard in the opposite direction and the loop overshoots by several degrees. With back-calculation the integral settles near 2.6, which is the value needed to hold the saturated position, and the response is a clean slew then hold.

Choosing the anti-windup method

MethodRuleStrengthFailure mode
Conditional integrationFreeze integral when saturated and error drives further saturationSimple, no extra gainCan stall if the freeze condition is checked on the wrong signal
ClampingStop integration when output saturatesEasy to auditIntegral still wrong if saturation is brief but repeated
Back-calculationAdd Kt·(u_applied − u_unsat) to the integralSmooth, handles rate and position limits togetherKt too large makes the loop sluggish, too small leaves windup

Back-calculation is the default when both limits are present, because it uses the actual applied output after both blocks. Conditional integration is fine for a single static clamp, but it needs care with a rate limiter: the output may not be saturated in position while it is still rate limited, and the integrator will wind up through that gap.

Failure modes to check in validation

A limit cycle appears when the controller gain is high enough that the rate limiter adds phase lag near crossover. The symptom is a sustained oscillation where the actuator repeatedly slews up and down at the rate limit, reversing direction each half cycle. Lowering Kd or adding a small deadband on the derivative fixes it, but the real check is a frequency sweep with the limiter active, not the linear Bode plot.

Hunting around the target appears when dt is too coarse relative to the plant lag. Each step can move the command by up to rate·dt, so at dt = 0.1 s the command can overshoot the target by up to 6° and then reverse. Halving dt should roughly halve that hunting band if discretisation is the cause. If it does not, the problem is in the controller gains, not the step size.

Finally, validate against hardware data with the same step sequence. Compare slew time, overshoot and steady state error, not just the final position. A model that matches the final value but slews in 0.2 s instead of 0.5 s will pass a static test and fail every transient test that follows.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-49A vibration sensor samples at 1 kHz but the bearing fault shows a 700 Hz tone. What will you see in the sampled data, and how would you choose a sampling rate to capture it correctly?

The 90-second answer

Sampling at $f_s$ can represent a bandlimited signal unambiguously only if $f_s > 2 f_{max}$, where $f_{max}$ is the highest frequency present, not just the one you care about. That is the Nyquist criterion. If a component sits above $f_s/2$, the Nyquist frequency, it does not disappear. It folds back into the band and appears as a lower frequency alias. A 700 Hz tone sampled at 1 kHz therefore looks like a 300 Hz tone, and no amount of post-processing on the sampled data alone can tell the two apart.

The alias frequency is $f_{alias} = |f - k f_s|$ for the integer $k$ that puts the result in $[0, f_s/2]$. For $f = 700$ Hz and $f_s = 1000$ Hz, $k = 1$ gives $|700 - 1000| = 300$ Hz. In a simulation this matters twice: the solver time step must resolve the physics, and the sensor model must then sample that solution at its own rate, with its own anti-alias behaviour. Conflating the two hides aliasing that the real sensor would produce.

Worked trace

Take $x(t) = \sin(2\pi \cdot 700 t)$, sampled every 1 ms. Compare it with a genuine 300 Hz sine at the same instants:

$t$ (ms)700 Hz sample300 Hz sample
00.0000.000
1-0.951-0.951
2-0.588-0.588
30.5880.588
40.9510.951
50.0000.000

The sequences are identical. An FFT of the sampled data peaks at 300 Hz with the same amplitude, so a fault classifier trained on it would report the wrong characteristic frequency and could miss the bearing defect entirely.

Python
import numpy as np

fs = 1000.0          # sensor sample rate, Hz
f_true = 700.0       # physical tone, Hz
t = np.arange(0, 0.05, 1.0 / fs)
x = np.sin(2 * np.pi * f_true * t)

spectrum = np.abs(np.fft.rfft(x))
freqs = np.fft.rfftfreq(len(x), 1.0 / fs)
print(freqs[np.argmax(spectrum)])  # 300.0, not 700.0

Choosing a rate in practice

Suppose the fault tone is 700 Hz and its third harmonic at 2100 Hz carries diagnostic energy. The highest frequency present is then 2100 Hz, so the bare minimum is $f_s > 4200$ Hz. Sampling at 5 kHz satisfies Nyquist on paper, but leaves almost no margin for filter roll-off and gives only about seven samples per cycle of the fundamental, which is poor for waveform shape, phase and amplitude estimates. A common working choice is 10 to 20 kHz here, roughly 5 to 10 times $f_{max}$, plus an analogue anti-alias low-pass filter ahead of the ADC with its cutoff below $f_s/2$.

Choice$f_s$Outcome for 700 Hz + 2100 Hz harmonic
1 kHzbelow Nyquist for both700 Hz folds to 300 Hz, 2100 Hz folds to 100 Hz
5 kHzjust above Nyquist for harmonicFrequencies correct, waveform and amplitude estimates noisy
20 kHz10x fundamental, ~10x harmonic marginClean spectrum, filter transition band is easy to place

The filter is the part candidates often skip. Nyquist assumes the signal is already bandlimited. Real vibration is not. Without an anti-alias filter, energy above $f_s/2$ folds in before digitisation and cannot be removed afterwards. In a simulation, model that filter explicitly, or at minimum apply a digital low-pass at the sensor rate before downsampling a high-rate solver output. Decimating a 100 kHz simulation result to 1 kHz by taking every 100th sample, with no filter, reproduces exactly the aliasing the hardware would show.

Two failure modes deserve a follow-up question. First, nonstationary signals such as impacts and chirps have broadband content, so a single $f_{max}$ is a poor description and the safe rate comes from the fastest transient, not the dominant tone. Second, sampling exactly at $2f$ or at a rational multiple of a tone can lock onto a fixed phase and hide amplitude changes. Offset the rate slightly from round multiples of expected tones, and validate the sensor model by injecting a known swept sine in simulation and checking that the recovered spectrum matches the input up to the stated cutoff.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-50In a simulated sensor fusion loop, what do the Kalman filter predict and update steps each do to the state estimate and its covariance?

The 90-second answer

The Kalman filter keeps two things for the state: the estimate itself, x, and its error covariance, P. Each cycle has a predict step, which propagates both through the motion model, and an update step, which corrects both with a measurement. The covariance is what decides how much to trust the model versus the sensor.

Predict, with state transition F and process noise covariance Q:

x_minus = F @ x
P_minus = F @ P @ F.T + Q

Update, for a measurement z with measurement matrix H and measurement noise covariance R:

K = P_minus @ H.T @ inv(H @ P_minus @ H.T + R)
x = x_minus + K @ (z - H @ x_minus)
P = (I - K @ H) @ P_minus

K is the Kalman gain. It is a matrix weighting, not a fixed tuning knob. If P_minus is large and R is small, K approaches the measurement. If the model is confident and the sensor is noisy, K stays small and the estimate barely moves.

Worked trace, 1D position

Hypothetical figures, checked by hand. Prior estimate x = 10.0 m, P = 4.0. A simulated lidar reports z = 10.6 m with R = 1.0. Here H = 1.

QuantityCalculationResult
---------
Kalman gain4.0 / (4.0 + 1.0)0.80
Innovation10.6 - 10.00.60 m
Posterior estimate10.0 + 0.80 * 0.6010.48 m
Posterior covariance(1 - 0.80) * 4.00.80

The estimate moves 80% of the way to the measurement because the prior variance is four times the measurement variance. After the update, P drops from 4.0 to 0.8. That drop is the fusion gain: two independent sources have been combined, so uncertainty falls.

Runnable core, NumPy

Python
import numpy as np

def predict(x, P, F, Q):
    return F @ x, F @ P @ F.T + Q

def update(x, P, z, H, R):
    S = H @ P @ H.T + R
    K = P @ H.T @ np.linalg.inv(S)
    x_new = x + K @ (z - H @ x)
    P_new = (np.eye(len(x)) - K @ H) @ P
    return x_new, P_new, K

In a simulation this runs per sensor tick. A 10 Hz lidar and a 100 Hz IMU do not share a step. You predict to each measurement timestamp, update with whichever sensor arrived, and keep Q tied to the elapsed dt. Feeding both sensors at the same timestamp without that propagation double counts the motion.

Where it breaks in practice

Q and R are the whole tuning problem. Set Q too low and the filter ignores real motion, lagging in turns. Set R too low and it chases sensor noise, which shows up as jitter in the fused pose even though each raw sensor looked acceptable on the bench. A common check is the innovation sequence, z - H @ x_minus. If it is white and roughly zero mean, the covariances are plausible. If it grows during maneuvers, Q is too small or the model is missing dynamics.

The linear form above assumes linear motion and measurement models. For a rotating sensor frame or a range bearing measurement you need the extended Kalman filter, which linearizes around the current estimate, or an unscented filter. Both keep the same predict and update structure. They differ only in how F and H are obtained.

Numerical care matters over long runs. P should stay symmetric and positive definite. Using the Joseph form, P = (I - KH) @ P @ (I - KH).T + K @ R @ K.T, preserves that better than the short form when K is computed in finite precision. If P collapses to near zero, the filter stops listening to new measurements entirely, and recovery takes a manual covariance reset.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-51You have input-output test data from a vibrating structure and must identify a model for simulation. How do you choose the model structure, excitation, and estimation method, and validate it without overfitting?

The 90-second answer

I would treat identification as three separate decisions: what model class can represent the physics, whether the test actually excites the parameters I need, and whether the fitted model predicts data it did not fit. I start from the intended use. A model for control design needs accurate frequency response near crossover. A model for loads needs accurate time histories and energy. That choice drives structure before any fitting.

For a linear system I would compare an ARX model, an output-error model, and a subspace model such as N4SID on the same data split. ARX is fast and convex, so it is a good baseline, but its noise model biases poles when measurement noise is coloured. Output-error matches the simulation use case, because it predicts output from input alone, but it is nonlinear in the parameters. Subspace methods give a state-space model and an order estimate without choosing poles in advance, which is useful when I do not know the order. I would not pick by training error. I would pick by prediction error on a held-out run, residual whiteness, and stability of the parameters across runs.

Excitation and identifiability

No estimator fixes a poor test. Inputs must be persistently exciting for the model order: a single sine sweep identifies a frequency response well but leaves time-domain parameters correlated, while a multisine or pseudo-random binary sequence excites many frequencies at once and exposes nonlinearities through intermodulation. I check the input spectrum and the condition number of the regression matrix before fitting. If two parameters move together, for example stiffness and mass in a narrow band test, the Fisher information matrix is near singular and the individual values are not identifiable even if the fit looks excellent.

Closed-loop data is the classic trap. If the input was generated by a controller reacting to the output, ordinary least squares can be biased because the input correlates with the noise. I would either use an instrumental variable or prediction-error method with a correct noise model, or add a small external dither to the loop and identify from that known excitation.

Python
import numpy as np

# ARX fit: y[k] = -a1*y[k-1] - a2*y[k-2] + b0*u[k-1] + b1*u[k-2]
# Checked with NumPy 1.26. Data columns are lagged outputs then lagged inputs.
Phi = np.column_stack([y[1:-1], y[:-2], u[1:-1], u[:-2]])
target = y[2:]
theta, residuals, rank, sv = np.linalg.lstsq(Phi, target, rcond=None)
cond = sv[0] / sv[-1]  # large cond means collinear regressors, weak identifiability

A condition number above roughly 1e4 on scaled regressors tells me to redesign the test or reparameterise, not to add regularisation and hope. Ridge regression can stabilise a fit, but it hides the fact that the test did not separate the effects.

Model selection with real numbers

Suppose I have n = 10,000 samples and compare two candidate orders on training data. I compute BIC = n * ln(RSS/n) + k * ln(n), where k is the parameter count. Lower is better, and the penalty grows with log(n), about 9.2 per parameter here.

CandidatekRSSBICHeld-out RMS error
ARX order 24812-24,9000.31
ARX order 612790-24,8300.34
Output-error order 24845-24,8600.29

The order 6 ARX wins on training RSS but loses on BIC and on held-out error. That pattern is overfitting: extra poles fit noise and a single run's disturbance. The output-error model has slightly worse training fit and the best held-out error, which is the behaviour I want for simulation. I would also plot residuals against input and check autocorrelation. Correlated residuals mean the noise model or structure is wrong, even if RMS looks small.

No Yes Define use and quantity of interest Design excitation and check spectrum Fit candidate structures Check identifiability and condition number Validate on held-out runs Residuals white and stable across runs? Freeze model and report uncertainty

Nonlinear and physical parameters

When the physics is known but parameters are not, for example damping ratios and stiffness in a modal model, I fit those physical parameters directly by nonlinear least squares on simulated output. That keeps the model extrapolatable outside the test amplitude range, unlike a black-box transfer function. I report parameter covariance from the Jacobian at the optimum, and I test sensitivity: if a 10% change in a parameter moves the quantity of interest by less than the measurement noise, I do not claim to have identified it.

The failure mode I watch for is a model that validates on the same rig, same amplitude, same temperature, and then fails in simulation at a different operating point. Held-out validation must therefore split by run and by condition, not by random samples from one run. Random splitting leaks correlated samples between train and test and flatters the result. Splitting by run, and ideally by amplitude or temperature, is what exposes extrapolation error before the model is used for design decisions.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-52You have a thermal model with eight uncertain inputs and a 10-minute FEA per run. How would you use Sobol indices to rank which inputs drive peak temperature, and what would you do if the total-effect indices sum to well over one?

The 90-second answer

Sobol indices decompose the variance of an output Y into contributions from each input and from interactions between inputs. For input Xi, the first-order index is S_i = Var(E[Y | Xi]) / Var(Y). It is the fraction of output variance you would remove on average if you fixed Xi to its true value. The total-effect index is ST_i = E[Var(Y | X_-i)] / Var(Y), where X_-i means every input except Xi. It includes the main effect of Xi plus every interaction involving Xi. Rank by ST_i, not S_i, when the goal is screening. An input with ST_i near zero can be fixed at a nominal value with little effect on the output distribution. An input with high S_i but low ST_i - S_i has a mostly independent effect. A large gap between ST_i and S_i means interactions matter and fixing inputs one at a time will mislead you.

With eight inputs and a 10-minute FEA, you cannot run a direct Saltelli design. The standard design needs N(k + 2) model evaluations for k inputs and base sample size N. Even N = 256 gives 256 x 10 = 2,560 runs, or 17.8 days on one core and about 13 hours on 32 cores if scaling were perfect. That budget is usually spent better on a surrogate.

How I would run it

No Yes Define ranges and distributions for 8 inputs Saltelli LHS design, N=256 Run FEA in parallel, store peak temperature Check bootstrap CI width on ST_i CI under 0.05? Fit surrogate on 300 runs, validate on 50 Compute Sobol indices on surrogate Fix inputs with ST_i below 0.02

In practice I would do two stages. First, run a coarse Saltelli design directly on the FEA with N = 128 to 256, in parallel, and bootstrap the indices. If the 95% confidence interval on ST_i is wider than about 0.05, the ranking is not stable and I would not report it. Second, train a surrogate on a few hundred FEA runs, for example a Gaussian process or polynomial chaos expansion, validate it on held-out runs, then compute Sobol indices from tens of thousands of surrogate evaluations. The surrogate step is where the ranking becomes cheap. The FEA step is where you prove the surrogate reproduces peak temperature within, say, 2 K on the validation set.

Python
import numpy as np

# A, B: (N, k) Saltelli matrices, AB_i: A with column i from B
# Y_A, Y_B, Y_AB: model outputs, shape (N, k) for Y_AB
def sobol_first_total(Y_A, Y_B, Y_AB):
    var_y = np.var(np.concatenate([Y_A, Y_B]), ddof=1)
    k = Y_AB.shape[1]
    S = np.empty(k)
    ST = np.empty(k)
    for i in range(k):
        S[i] = np.mean(Y_B * (Y_AB[:, i] - Y_A)) / var_y
        ST[i] = np.mean((Y_A - Y_AB[:, i]) ** 2) / (2 * var_y)
    return S, ST

That is the Jansen estimator form. SALib or UQLab implement the same calculation with bootstrap intervals, which I would use rather than hand-rolling the final numbers.

Reading the numbers

Hypothetical result for peak temperature, labelled as an example:

InputS_iST_iST_i - S_i
Contact resistance0.380.440.06
Coolant flow rate0.140.220.08
Ambient temperature0.070.090.02
Channel height0.020.310.29
Other four inputs combined0.010.320.31
Sum0.621.38

Sum of S_i below one is expected. The missing 0.38 is variance from interactions of order two and higher that no single input explains alone. Sum of ST_i above one is also expected and is not an error. Each interaction is counted once for every input involved in it, so ST_i values overlap. Channel height is the case to watch here. Its first-order index is small but its total index is large, which means it matters mainly through interaction, in this example with flow rate because a taller channel lowers velocity and changes the heat transfer coefficient. Fixing channel height at nominal and varying flow rate alone would understate its effect.

Failure modes I check before trusting a ranking

Correlated inputs break the standard decomposition. Sobol indices assume independent inputs. If contact resistance and interface thickness are sampled from a joint distribution with correlation 0.8, the variance split depends on the ordering and the indices can assign credit to the wrong variable. I would either decorrelate the inputs, group correlated inputs into one factor, or switch to Shapley-based effects that handle dependence differently.

Sampling noise is the second trap. With N = 128 and k = 8, bootstrap intervals on ST_i are often 0.1 or wider. A ranking that flips between runs is a sign to increase N or move to the surrogate, not to average the rankings.

The third trap is a surrogate that fits the mean well but misses the tails. Peak temperature is often driven by combinations in the corners of the input space. I check surrogate error specifically on the highest-temperature validation runs, not just overall RMSE, because those runs dominate the variance you are decomposing.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-53You have five design factors for a CFD study, each run takes four hours, and you can afford 16 runs. How do you choose a design of experiments that estimates main effects and two-factor interactions without confounding them?

The 90-second answer

Use a two-level fractional factorial, 2^(5-1), with generator E = ABCD. That gives 16 runs, resolution V. Every main effect is aliased only with a four-factor interaction, and every two-factor interaction is aliased only with a three-factor interaction. If three-factor interactions are negligible, as they usually are in a first screening study, all main effects and all two-factor interactions are estimable. A full 2^5 factorial would need 32 runs at four hours each, 128 core-hours, to estimate the three-, four- and five-factor interactions you do not need yet.

Randomize the run order, or block on machine and day if you cannot randomize fully. Add centre points in a second stage if curvature is plausible, because two levels alone cannot detect it.

The design

Code each factor as -1 (low) and +1 (high). With E = ABCD, the 16 runs are:

ABCDE=ABCD
-1-1-1-1+1
+1-1-1-1-1
-1+1-1-1-1
+1+1-1-1+1
-1-1+1-1-1
+1-1+1-1+1
-1+1+1-1+1
+1+1+1-1-1
-1-1-1+1-1
+1-1-1+1+1
-1+1-1+1+1
+1+1-1+1-1
-1-1+1+1+1
+1-1+1+1-1
-1+1+1+1-1
+1+1+1+1+1

Alias structure, written as pairs that cannot be separated in these 16 runs:

Effect estimatedAliased with
ABCDE
ABCDE
ABCDE
ABCDE

So the column labelled AB actually estimates AB + CDE. If you later find a large AB effect, you cannot claim it is AB until a follow-up run breaks the alias, for example by running the complementary fraction or a few targeted points where AB and CDE differ.

Python
# Python 3.11, standard library only
import itertools

runs = []
for a, b, c, d in itertools.product([-1, 1], repeat=4):
    e = a * b * c * d  # generator E = ABCD
    runs.append((a, b, c, d, e))

for i, run in enumerate(runs, 1):
    print(i, run)

Why this beats the alternatives at 16 runs

ApproachRuns for 5 factorsWhat you getMain weakness
One at a time from a baseline6 to 10Main effects at one setting of the othersMisses interactions, order effects confound drift
Full factorial 2^532Everything, including 5-way interactionTwice the budget, most terms are noise
Fractional 2^(5-1)16Main effects and 2-factor interactions2-factor effects aliased with 3-factor effects
Latin hypercube, 16 points16Good coverage of continuous rangesNo clean effect estimates, interactions need a fitted surrogate

One at a time is the common failure. If factor A only helps when B is high, changing A at low B shows nothing and you discard a factor that matters. The factorial design spreads each factor evenly across the levels of the others, so the A effect is averaged over both B settings.

Noise and arithmetic

For a stochastic simulation, the standard error of a main effect in a two-level design is roughly 2*sigma / sqrt(N), where sigma is the run-to-run standard deviation at fixed settings and N is the number of runs. With N = 16, that is sigma/2. If pilot runs give sigma = 0.4% on drag coefficient, the effect standard error is about 0.2%, so an effect below roughly 0.5% will be hard to distinguish from noise. Replication of the whole design halves that only if you double N. Common random numbers across runs can cut sigma for comparisons, but only if the same seed stream drives the same physical randomness in each run. That assumption fails if the solver changes the number of random draws with the design.

Centre points, all factors at 0, test curvature. Three centre runs cost 12 hours. If their mean differs from the factorial mean by more than about two standard errors, a linear model in the coded factors is inadequate and you move to a response-surface design, such as a central composite design, around the promising region.

yes no yes no Screen: 2^(5-1) fractional factorial, 16 runs Centre points show curvature? Response surface design near best corner Large 2-factor alias? Fold-over or targeted runs to break alias Fit linear model, confirm at predicted optimum

Failure modes to check before you trust the ranking

Aliasing is the first. A large AB column may be a real CDE interaction, unlikely but possible if the physics couples three inputs, for example mesh size, turbulence model and inlet profile. The fold-over in the diagram resolves it.

The second is a factor range that is too narrow. If the low and high levels differ by less than the manufacturing tolerance, the effect will be buried in noise and you will wrongly drop the factor. Set levels from the range you would actually consider for the product, not from a convenient CAD parameter sweep.

The third is non-random drift. Solver version changes, mesh regeneration failures, or a shared cluster queue that slows some runs can correlate with run order. Randomization plus a recorded run order lets you plot residuals against time and spot that pattern. If a run fails to converge, do not replace it with a convenient setting. Record it as a failed run at that design point, because dropping it biases the design toward the region that happens to converge.

Confirmation matters. Predict the response at the best corner from the fitted model, run that point, and compare. If the confirmation run misses by more than the effect standard error, the model is missing curvature or an interaction, and the ranking from the screening design should not be used for a design decision.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-54What is a surrogate model in simulation, and what does response surface methodology fit to the simulation results?

The 90-second answer

A surrogate model is a cheap mathematical approximation fitted to outputs from an expensive simulation, so you can evaluate thousands of designs in milliseconds instead of rerunning CFD or FEA for hours. Response surface methodology (RSM) is the classical way to build one: run the simulation at a planned set of design points, fit a low-order polynomial to the results, then use that polynomial to search for an optimum or to propagate uncertainty.

The fitted surface is usually quadratic in the input variables:

y_hat = b0 + sum(bi * xi) + sum(bij * xi * xj) + sum(bii * xi^2)

where xi are coded variables (scaled to -1 to +1) and y is the quantity of interest, for example drag coefficient or peak stress. The quadratic terms matter because they capture curvature and interaction between variables, which a linear model misses. A linear fit can tell you which variable matters. A quadratic fit can locate a minimum inside the design region.

RSM is sequential. First a screening design, often a fractional factorial, identifies the few variables that matter. Then a design that supports a quadratic fit, such as a central composite design, adds centre and axial points. You fit the surface, check it against held-out simulation runs, and move or shrink the region if the optimum sits on the boundary.

Worked example

Suppose drag depends on ride height, grille opening and wheel deflection. A central composite design for 3 factors needs 8 factorial points, 6 axial points and centre points, about 17 runs. At 5 hours per CFD run that is 85 hours of compute, after which the polynomial evaluates in about 2 ms. A candidate would check the surrogate before trusting it:

CheckFigure in this example
Training runs17 CFD runs
Held-out validation runs5 CFD runs not used in the fit
Mean absolute error on held-out runs0.8% of drag
Max error on held-out runs2.1% of drag
Surrogate evaluation time~2 ms vs 5 hours
Optimisation search20,000 surrogate evaluations in under a minute

If held-out error were 8%, the polynomial is the wrong form or the region is too wide. Shrinking the region or switching surrogate type is the fix, not adding more terms blindly.

Python
# Python 3.11, NumPy only. Fit a quadratic response surface.
import numpy as np

# X: (n_runs, 3) coded variables in [-1, 1]; y: (n_runs,) drag values
def design_matrix(X):
    x1, x2, x3 = X[:, 0], X[:, 1], X[:, 2]
    return np.column_stack([
        np.ones(len(X)), x1, x2, x3,
        x1 * x2, x1 * x3, x2 * x3,
        x1**2, x2**2, x3**2,
    ])

Phi = design_matrix(X)
coef, *_ = np.linalg.lstsq(Phi, y, rcond=None)
y_pred = Phi @ coef
rmse = float(np.sqrt(np.mean((y - y_pred) ** 2)))

Choosing the surrogate

SurrogateStrengthWeaknessTypical use
Polynomial RSMInterpretable coefficients, finds optimum analyticallyPoor outside the fitted region, struggles with sharp featuresSmooth drag, stress, thermal response over a bounded region
Kriging / Gaussian processGives an uncertainty estimate that grows away from dataCost grows roughly as n^3, so it stalls beyond a few hundred runsExpensive runs, 5 to 15 variables, uncertainty propagation
Radial basis functionHandles nonlinear, non-polynomial shapesNo built-in uncertainty, can oscillate between pointsShock-dominated or strongly nonlinear responses
Neural networkScales to many runs and high dimensionsNeeds far more data, opaque, easy to overfitLarge simulation databases, image or field outputs

Failure modes to name in an interview: extrapolating outside the design region, fitting a quadratic to a response with a discontinuity such as a shock moving across the design space, and reporting an optimum without confirming it with one real simulation run at the predicted optimum. The confirmation run is the step that separates a surrogate study from a curve-fitting exercise.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-55Walk me through building a POD reduced-order model for a CFD flow field to predict drag in real time, and how do you choose truncation rank and validate it outside training conditions?

The 90-second answer

POD is a data-driven compression of a high-dimensional field. You run the full CFD solver offline at a set of operating conditions, collect snapshots of the state (velocity, pressure, temperature on the mesh), subtract the mean field, and take the singular value decomposition of the snapshot matrix. The left singular vectors are the spatial modes, ordered by how much variance they explain. Keeping the first r modes gives a basis that reconstructs any training snapshot as mean plus a linear combination of r modes. For real-time drag prediction you either project the snapshots onto those modes and interpolate the coefficients (or drag directly) in parameter space, or you build a Galerkin system by projecting the governing equations onto the modes and integrate r ODEs instead of millions of cells.

The rank choice is not an energy percentage. It is the smallest r where the quantity of interest, drag in this case, stops moving within your tolerance on held-out snapshots, and where the online cost still beats the full model by the factor you need.

no yes Full CFD runs at sampled conditions Snapshot matrix X, mean subtracted SVD: modes U, coefficients S Vt Truncate to rank r Online: project or integrate r modes Reconstruct field, compute drag Held-out error within tolerance? Deploy ROM

Building it

Let the state be x in R^N, with N = 2,000,000 cells times variables, and m snapshots. Form X in R^(N x m), subtract the temporal mean xbar, and compute the economy SVD X = U S V^T. The columns of U are orthonormal modes. The energy in mode i is sigma_i^2 / sum_j sigma_j^2. A reconstruction with rank r is xhat = xbar + U_r U_r^T (x - xbar).

In Python, with snapshots already assembled as a float64 array of shape (N, m):

Python
import numpy as np

# X: (N, m) snapshots, checked against NumPy 1.26
xbar = X.mean(axis=1, keepdims=True)
Xc = X - xbar
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
energy = np.cumsum(s**2) / np.sum(s**2)
r = int(np.searchsorted(energy, 0.999) + 1)
Ur = U[:, :r]                       # (N, r) modes
coeffs = Ur.T @ Xc                  # (r, m) modal coefficients
# Reconstruct one snapshot and its drag proxy:
xhat = xbar[:, 0] + Ur @ coeffs[:, 0]

For N >> m, which is the usual CFD case, you never form U directly. You form the m x m Gram matrix Xc^T Xc, eigendecompose it, and recover modes as U = Xc V S^-1. That drops the cost from O(N^2 m) to O(N m^2 + m^3). With m = 200 snapshots and N = 2,000,000, the Gram route is the only tractable one.

Choosing rank with real figures

Energy alone misleads. A mode can carry 0.1% of field energy and still move drag by 2% if it sits in the wake. So I sweep r and score three things on snapshots the SVD never saw: field reconstruction error, drag error, and online latency. Hypothetical but representative numbers for a steady external flow case:

Rank rCumulative energyField RMS errorDrag error (held-out)Online time per query
598.2%4.1%3.8%0.4 ms
1299.9%1.2%0.9%0.9 ms
2599.99%0.5%0.4%1.8 ms
5099.999%0.2%0.2%3.5 ms

If the requirement is drag within 1% for design ranking, r = 12 is the knee. Going to 50 buys 0.7 points of drag accuracy and quadruples the projection cost, while the full CFD run at 5 hours makes even 3.5 ms a 5-million-fold speedup. The decision is driven by the drag tolerance, not by hitting 99.9% energy.

Where it breaks

Three failure modes show up in review and in production.

  1. Extrapolation. POD interpolates inside the convex hull of the training conditions. Train at Reynolds numbers 200k to 400k and query at 800k, and the modes have never seen that boundary layer state. Reconstruction error can look small while drag is off by 5% or more, because the error concentrates in a region the QoI weights heavily. Detection: hold out the corner conditions from training entirely, not random snapshots from the middle. If the corner fails, add snapshots there or refuse to answer outside the hull.

  2. Moving discontinuities. A shock that moves across the mesh is not low rank. Its snapshots need many modes, and a truncated reconstruction smears the shock over several cells, which corrupts pressure drag. The singular values decay slowly, which is your warning. If sigma decays like 1/i rather than exponentially, POD is the wrong tool. Options are to align snapshots before decomposition, split the domain, or switch to a nonlinear autoencoder or a local POD per flow regime.

  3. Galerkin instability. Projecting the Navier-Stokes equations onto POD modes gives a nonlinear ODE system in the coefficients. Truncation can make that system unstable even when reconstruction is accurate, because the discarded modes carried dissipation. The symptom is coefficients that grow over time in a free integration. Fixes are to add a closure term, such as a simple eddy-viscosity-like damping on higher modes calibrated on training data, or to avoid Galerkin entirely and use the cheaper interpolation approach: project each snapshot, then interpolate coefficients or drag in parameter space with radial basis functions or a Gaussian process. Interpolation is less elegant and cannot extrapolate in time, but it cannot blow up either.

Validation I would defend

Split snapshots by condition, not by index. Train on 80% of conditions, test on the remaining 20%, including at least one condition at each edge of the parameter range. Report drag error as a distribution, not a mean: mean bias, 95th percentile absolute error, and worst case. Check that the error does not grow systematically with Reynolds number or angle of attack, which would signal a missing mode rather than noise. Finally, time the online path end to end, including reconstruction if the user needs the field and not just drag. A ROM that returns drag in 1 ms but needs 200 ms to rebuild the field for visualisation has not met a real-time requirement.

The honest summary for an interviewer: POD gives you a linear basis that is optimal for reconstruction in the least-squares sense, by the Eckart-Young theorem. Optimal for reconstruction is not optimal for drag, for stability, or for extrapolation. Rank selection and validation on the quantity of interest are where the engineering judgement sits.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-56When would you couple a vehicle dynamics FMU to a distributed HLA federation instead of running both in one FMI co-simulation, and how do you keep time and causality consistent?

The 90-second answer

Use FMI when the coupling is inside one process or one controlled master, and HLA when the coupling crosses organisations, sites, or real-time hardware. An FMU is a self-contained model with a standard C interface. In FMI Co-Simulation the FMU contains its own solver and the master calls fmi2DoStep with a communication step. In FMI Model Exchange the FMU exposes derivatives and the master integrates them. HLA, IEEE 1516-2010, is a federation standard. Independent federates, each possibly containing one or more FMUs, join through a Runtime Infrastructure (RTI) and exchange published objects and interactions under a shared Federation Object Model (FOM).

The deciding question is who owns time. With FMI alone, your master owns it and can step, interpolate, and in some tools roll back. With HLA, no federate may advance past the logical time that another federate could still affect. That guarantee costs latency and lookahead, and it is the reason to accept HLA only when distribution or independent ownership forces it.

Event Grant Master or RTI time manager Set inputs for step Advance FMU or federate to t plus h Event or time grant? Handle event, restart step Read outputs, interpolate

FMI Co-Simulation, mechanism

The master picks a communication step h, writes inputs with fmi2SetReal, calls fmi2DoStep to advance the FMU from t to t+h, then reads outputs. Accuracy depends on h, on how inputs are interpolated inside the step, and on event detection. FMI 2.0 has no general rollback, so a master that needs to reject a step must either use a smaller h, restart from a saved state if the FMU supports it, or accept the error. FMI 3.0 adds clocks and partitions, which help with hybrid and multi-rate models, but the master still controls the sequence.

A typical master loop in Python, checked against FMI 2.0 via FMPy, looks like this:

Python
import fmpy

fmus = ["vehicle.fmu", "powertrain.fmu"]
# fmpy handles instantiation, input interpolation and fmiDoStep calls
result = fmpy.simulate(
    fmus,
    start_time=0.0,
    stop_time=10.0,
    step_size=0.005,  # communication step h, seconds
    input=[(0.0, "throttle", 0.3)],
    output=["vehicle.speed", "powertrain.torque"],
)

If the powertrain FMU has stiff dynamics at 1 ms and the vehicle body moves slowly, a single h of 5 ms can be stable for one and wasteful or inaccurate for the other. That is a signal to use Model Exchange for the stiff part, sub-step the master, or move to a partitioned FMI 3.0 setup, rather than shrinking h for everything.

HLA, mechanism

Each federate declares itself time regulating and time constrained, then requests time advance with requestTimeAdvance or nextEventRequest. The RTI grants time only up to the greatest available logical time (GALT), which is bounded by other federates' lookahead. Lookahead is a promise: a federate will not send a timestamped message earlier than its current logical time plus lookahead. Larger lookahead gives the RTI more freedom and reduces stalls, but delays the effect of local inputs.

AspectFMI Co-SimulationHLA federation
ScopeComponents in one master, usually one hostFederates across hosts, sites, vendors
Time controlMaster chooses step sizeRTI grants logical time, bounded by lookahead and GALT
Data exchangeDirect variable access via FMI APIPublish/subscribe of objects and interactions defined in FOM
Rollback and eventsLimited in FMI 2.0, better in 3.0 with clocksNo rollback of a federate, save/restore is coarse
Typical costLow overhead, deterministic in one processRTI latency, time management stalls
Use whenOne team, one solver schedule, offline or HIL with one masterIndependent simulators, live-virtual-constructive mixes, real-time federation

Worked trace, HLA time grant

Assume two federates, vehicle (V) and traffic (T), both with 10 ms lookahead. Logical time is in seconds.

StepV logical timeT logical timeRTI grantConsequence
10.0000.0000.010Both can send messages timestamped at or after 0.010
20.0100.0000.010V advances, T still at 0.000 cannot be overtaken
30.0100.0100.020T catches up, next grant moves to 0.020
40.0200.0100.020V waits if it needs T data stamped at 0.020

If V requests 0.100 in one jump while T needs to inject a cut-in at 0.015, the RTI will not grant 0.100. It grants only to the point where T could still send. Ignoring that and forcing a large step is the classic HLA failure: causality breaks, and the vehicle reacts to a traffic event after it should have.

Failure modes I check

Algebraic loops across FMUs, where A needs B output at the same instant B needs A output, cause the master to iterate or fail. HLA does not solve this, it only orders timestamped messages. A second failure is mismatched time units or wall-clock versus logical time in a real-time federation, which shows up as a federate running at 10x speed. A third is a FOM mismatch, where a federate publishes Vehicle.speed in km/h and another reads it as m/s. I validate with a recorded trace, compare FMU outputs against a monolithic reference for the first seconds, and test the federation with lookahead set to zero to expose hidden causality assumptions before raising it for performance.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-57Why does a hardware-in-the-loop plant model need a fixed time step, and how would you pick that step for a motor with a 2 ms electrical time constant running at a 1 kHz controller rate?

The 90-second answer

A hardware-in-the-loop rig replaces the physical motor with a model running on a real-time target, while the real controller stays connected through physical inputs and outputs. The model has to advance in lockstep with the controller clock. A variable step solver cannot do that reliably, because the step size changes with the state, the time spent in a step varies, and the I/O update no longer lands on a known tick. The controller then sees a plant that sometimes responds late and sometimes early, and a test result cannot be repeated exactly.

A fixed step solver takes the same step every tick, so latency is constant and measurable. The cost is accuracy. The step must be small enough for the fastest dynamics in the plant, and small enough steps cost compute on every tick, even when the motor is idle.

For the motor in the question, the electrical time constant is tau = L/R = 2 ms. A common starting rule is at least ten steps per time constant for a first order lag with RK4, so dt <= 0.2 ms. The controller tick is 1 ms, so one controller tick needs five plant substeps at 0.2 ms, or ten substeps at 0.1 ms if you want margin for current ripple. That arithmetic, not the controller rate, sets the plant step.

ApproachStep behaviourI/O timingMain risk
Variable step, for example adaptive RK45Step shrinks during transients, grows at steady stateSensor update time varies from tick to tickController tuned against a plant with variable delay
Fixed step RK4 at 0.1 msSame step every substep, 10 substeps per 1 ms tickSensor update lands on the same tick boundaryStep too large distorts current ripple, step too small overruns the CPU
Fixed step with precomputed discretisationSame step, matrix update per tickSame as above, less compute per tickFrequency warping above roughly one tenth of the sample rate

How I would set it up

I would run the plant at 10 kHz inside the 1 kHz I/O tick. The target reads the PWM command once per millisecond, advances the electrical and mechanical states ten times, then writes encoder counts and current measurements once. The loop is a simple counted loop with no allocation and no operating system calls inside it.

C
// Plant substep inside a 1 kHz I/O tick. Fixed step, no allocation.
void hil_tick(void) {
    read_pwm_command(&cmd);
    for (int k = 0; k < 10; ++k) {
        plant_step_rk4(0.0001);  // 0.1 ms, ten steps per time constant is 20 steps
    }
    write_encoder_and_current(&meas);
}

At 0.1 ms the step is tau/20. That gives margin over the tau/10 rule and keeps the current loop behaviour close to the bench motor. If the target cannot finish ten RK4 steps plus I/O inside 1 ms with headroom, I would move to a discretised state space update for the electrical states, which is one matrix multiply per substep, and check the error against the RK4 version offline.

How I would check the choice

First, I would run the same current step test in three places: the model on a desktop, the model in the loop, and the real motor on a dynamometer. Desktop and loop results should match to solver tolerance, for example peak current within 1 percent. If they do not, the discretisation differs between the two runs. If desktop and loop match but the dynamometer differs by more, the model parameters or the step size are wrong for the real plant.

Second, I would measure timing directly. I would log the worst case tick time over a long run and require it to stay below the 1 ms period with no overruns. I would also inject a known pulse from the controller and timestamp when the corresponding sensor change appears. With a fixed step that delay should be one or two ticks every time. With a variable step it would spread over several ticks, and that spread is the corruption I am trying to avoid.

The trade-off is therefore direct. Fixed step buys deterministic timing and repeatable tests, and it charges you compute on every tick. Variable step buys accuracy per compute on a desktop, and it charges you timing uncertainty in the loop. For HIL, timing uncertainty usually costs more, because a controller that passes against a late plant can fail on the real motor.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-58In software-in-the-loop testing, what runs on the host computer and what is simulated instead of real hardware?

The 90-second answer

Software-in-the-loop testing, or SIL, runs the production controller software on a host computer and replaces the physical plant with a simulation. The code under test is the real code, compiled for the host, with its control laws, state machines and message handling intact. The vehicle, motor, sensors and actuators it talks to are models.

That is the whole distinction. In model-in-the-loop testing the controller itself is still a model. In hardware-in-the-loop testing the controller runs on the target ECU and the plant runs in real time on dedicated hardware. SIL sits between them: real software, simulated world, ordinary workstation.

Production controller code compiled for host Simulated plant: dynamics, sensors, actuators Logged inputs and outputs for replay
ComponentIn SILIn HIL
ControllerProduction code on host PCProduction code on target ECU
Plant and sensorsSimulated modelsSimulated in real time, or real hardware
TimingFixed simulation step, deterministicReal-time deadlines and bus delays apply
Typical useEvery commit in CI, thousands of scenariosFinal timing and interface checks before vehicle tests

A minimal harness makes the split explicit. The plant model produces sensor values, the controller code consumes them and returns a command, and the plant model advances.

Python
# Python 3.11. controller is the production code exposed as step().
def run_scenario(controller, plant, dt=0.01, duration=10.0):
    state = plant.reset()
    controller.reset()
    for k in range(int(duration / dt)):
        sensor = plant.measure(state, k * dt)
        command = controller.step(sensor, k * dt)
        state = plant.step(state, command, dt)
    return state

Because the plant is simulated, the same scenario replays bit for bit. You can inject a sensor dropout, a frozen value or an out-of-range reading, and you can run hundreds of cases in parallel overnight. A failure points at the software logic, since no hardware is involved. If the controller misbehaves in SIL, the bug is in the code or in the plant model, and the log shows exactly which input caused it.

The limit follows from the definition. SIL cannot prove the code meets its deadline on the ECU, survives real bus latency, or handles electrical faults, because none of that hardware is present. Those checks belong to HIL. SIL proves the software logic is correct against the simulated plant, early enough that fixing it costs a rebuild rather than a rig booking.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-59Your CFD result changes after a solver upgrade and a mesh regeneration, but the input files look identical. How do you prove which change caused it and make the run reproducible six months later?

The 90-second answer

Identical input files do not make a run reproducible. A simulation result is a function of the code, the solver binary and its libraries, the mesh and material data as actually read, the environment, and the parallel execution. I capture all five in a manifest at launch, store inputs by content hash, and treat the manifest plus the container image as the version of the run. When a result moves, I replay the old manifest in the old container and change one factor at a time. That isolates a solver upgrade from a mesh regeneration in a way a folder of case files never will.

What the manifest must contain

Git commit and dirty flag for the pre-processor and solver wrapper, solver name and build, container digest, mesh file hash and mesh generator version and seed, material and boundary condition tables by hash, command line, RNG seed, MPI rank count and decomposition, and hardware class. Hash the files the solver opened, not the files you intended it to open. A symlink or a default table silently substituted at runtime is a common cause of a drift that looks like a physics change.

Python
# Python 3.11, run by the launcher before exec
import hashlib, json, subprocess, pathlib

def sha256(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()

manifest = {
    "code": subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip(),
    "code_dirty": bool(subprocess.check_output(["git", "status", "--porcelain"])),
    "inputs": {str(p): sha256(p) for p in ["mesh.msh", "materials.json", "bc.json"]},
    "solver": "openfoam-2312", "ranks": 256, "seed": 42,
}
pathlib.Path("manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True))

Store the manifest, inputs and outputs in content-addressable storage keyed by hash, for example with DVC or a simple object store layout sha256/ab/cd/.... A version tag such as case_v3_final is an alias that can be repointed. The hash cannot.

Isolating the change

Suppose drag was 0.3120 in March and 0.3181 now, a 1.9% shift, after both a solver upgrade and a mesh regeneration. I run a 2 by 2 replay:

RunSolverMeshDrag coefficient
Aoldold0.3120
Bnewold0.3124
Coldnew0.3178
Dnewnew0.3181

Run B moves drag by 0.13%, run C by 1.86%. The mesh regeneration caused the shift, and the solver upgrade is within run to run variation. Without the old container I could not have run A and C at all, which is why the container digest, not just a version string, goes in the manifest. A version string does not pin the MPI library, the compiler flags or the BLAS build.

Manifest: code, container, seed Inputs by sha256 Solver run Outputs plus QoI Provenance record Replay in old container One factor changed

Reproducibility is not bitwise identity

MPI reductions, dynamic load balancing and GPU atomics change summation order. The same manifest on 256 ranks can give a different last bit than on 128 ranks, and a rerun on the same rank count can still differ if the solver uses non-deterministic atomics. I therefore compare quantities of interest against a tolerance set from the verification study, for example drag within 0.2% and peak temperature within 0.5 K, and I record rank count as part of the provenance. If a regulator or a customer needs bitwise replay, I pin rank count, disable dynamic decomposition, and use deterministic reduction modes where the solver offers them, and I state that cost in the record.

Failure modes I check first

A material table edited in place without a hash change in the case folder, a mesh file overwritten by a regeneration script with the same name, an environment variable such as OMP_NUM_THREADS inherited from a login shell, and a post-processing script that reads a stale field file. Each one produces a plausible result and a false conclusion about the physics. The manifest catches the first three because the hash, the container and the environment are captured at launch. The fourth is caught by hashing the post-processor and its inputs in the same record as the output it produced.

Six months later, reproducibility means I can point to one manifest, pull the exact inputs and container by digest, rerun, and show the quantity of interest lands inside the stated tolerance, or show exactly which single change moved it outside that tolerance.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-60Your CFD solver scales poorly past 256 cores and wall time barely drops. How do you profile it to find whether the bottleneck is compute, memory, MPI communication or load imbalance?

The 90-second answer

Start with a flat profile on a representative run at the core count where scaling breaks, then check a timeline. The flat profile tells you which function consumes cycles. The timeline tells you whether ranks are waiting for each other, for the network, or for memory. I would run the same case at 64 and 256 cores and compare both views. If the same kernel dominates at both counts and its share grows, the problem is inside that kernel. If no kernel grows but MPI_Wait or MPI_Allreduce grows, the problem is communication or synchronisation. If ranks finish the kernel at different times, the problem is load imbalance.

For a CFD or FEA code I use perf stat for hardware counters, perf record for a sampling profile, and a tracing tool such as Nsight Systems, Score-P or HPCToolkit for MPI and OpenMP timelines. Sampling at 999 Hz on a 10 minute run gives roughly 600,000 samples, enough to rank hot functions without rebuilding with instrumentation.

Shell
# counters: IPC, cache misses, stalls
perf stat -e cycles,instructions,cache-misses,cache-references,branch-misses ./solver --case coarse

# sampling profile with call graph
perf record -F 999 -g --call-graph dwarf ./solver --case coarse
perf report

Worked trace: reading the numbers

Hypothetical but typical figures for a 256 core run that takes 1,000 s:

Signal64 cores256 coresReading
Wall time3,200 s1,000 sSpeedup 3.2x for 4x cores
Flux kernel share48%61%Kernel is the target
MPI_Wait share4%19%Ranks wait at halo exchange
IPC in flux kernel1.91.1Core stalls, likely memory
L3 miss rate12 per 1,000 instr31 per 1,000 instrCache behaviour worsens with rank placement
Rank finish spread2% of step14% of stepImbalance grows with core count

That pattern points to two faults at once. The flux kernel is memory bound and its cache miss rate rises when ranks are spread across sockets, which suggests NUMA placement. The growing MPI_Wait share with a 14% finish spread suggests some ranks own more cells in the refined region, so the others wait at the exchange.

Roofline check before optimising

Arithmetic makes the memory claim checkable. Work per node per flux evaluation: 20 GB of field data read and written, 4 GFLOP of work. Arithmetic intensity is 4 / 20 = 0.2 FLOP per byte. On a node with 1.5 TB/s sustained bandwidth, the bandwidth bound is 20 / 1500 = 13.3 ms. On a node with 32 cores at 40 GFLOP/s per core, peak compute is 1,280 GFLOP/s, so the compute bound is 4 / 1280 = 3.1 ms. Bandwidth is the tighter bound. If the measured time is 40 ms, the kernel runs at about 33% of bandwidth, so cache blocking, vectorisation width and data layout are worth more than adding flops. If it ran near 14 ms, I would stop tuning the kernel and look at the exchange.

C++
// OpenMP threads inside one MPI rank share cache lines. Padding the
// leading dimension stops adjacent threads writing into the same line
// when they fill halo rows. MPI ranks are separate processes and do
// not share a cache, so this does not fix inter-rank sharing.
constexpr int PAD = 64;
std::vector<double> halo((nx + PAD) * ny);
#pragma omp parallel for schedule(static)
for (int j = 0; j < ny; ++j) {
    double* row = &halo[j * (nx + PAD)];
    for (int i = 0; i < nx; ++i) row[i] = field[j * nx + i];
}

Fix order and verification

I fix in the order the evidence suggests. First, pin ranks and threads with OMP_PROC_BIND=close and OMP_PLACES=cores, then remeasure the miss rate. Second, rebalance the mesh partition so cell counts per rank differ by under 2%, using a space filling curve partitioner if the mesh is unstructured. Third, overlap the halo exchange with interior flux work by posting MPI_Irecv before the interior loop and waiting only before the boundary cells are used. Each change gets the same 64 and 256 core pair. A fix that helps at 256 cores but hurts at 64 cores usually traded compute for communication in a way that only pays at scale.

Yes No Yes Run at 64 and 256 cores perf stat counters perf record flat profile Timeline for MPI and OpenMP Kernel share grows? Roofline and cache tuning Wait time grows? Rebalance and overlap exchange Remeasure same pair

The common failure mode is profiling a tiny test case that fits in cache, then optimising a kernel that is irrelevant at production size. I profile the production mesh, with production I/O and restart enabled, because checkpoint writes often appear as a periodic stall that a short run never shows.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-61Why does a GPU speed up an explicit dynamics element update with millions of elements, and why does that speedup shrink on a small mesh?

The 90-second answer

An explicit element update does the same arithmetic on every element, with no dependency between elements in the same step. That maps directly to thousands of GPU threads, each handling one element. The kernel is usually limited by memory bandwidth, not by flops. It reads the element state, computes the internal force, and writes the new state. A GPU socket offers roughly 5 to 10 times the memory bandwidth of a CPU socket, so that streaming pattern runs several times faster on the GPU.

The speedup shrinks on a small mesh for two reasons. Kernel launch and synchronization cost about 5 to 10 microseconds regardless of mesh size. And if the state has to cross the PCIe bus to reach the GPU and back, that transfer can take longer than the compute it was meant to accelerate.

Worked arithmetic

Assume each element reads and writes 200 bytes per step and does 500 flops. Label these as hypothetical figures for a worked example.

MeshTraffic per stepCPU at 200 GB/sGPU at 1.5 TB/s
10,000,000 elements2.0 GB10 ms1.3 ms
200,000 elements40 MB0.20 ms0.03 ms

On the large mesh the GPU saves about 8.7 ms per step. Over 100,000 steps that is roughly 15 minutes saved per 1,000 steps, and the end to end speedup is often 4x to 6x after contact, output and launch overhead are included.

On the small mesh the saving is 0.17 ms per step. A 10 microsecond launch plus a PCIe transfer of the 40 MB state, about 1.6 ms at 25 GB/s, wipes that out completely. Keeping the state resident on the device across steps removes the transfer, but the launch overhead is still a third of the 30 microsecond kernel time. Batching several steps per launch, or running several independent cases concurrently on streams, recovers much of it.

C++
// CUDA, one thread per element, coalesced access
__global__ void update_kernel(float* __restrict__ u,
                              const float* __restrict__ f,
                              int n, float dt) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) u[i] += dt * f[i];
}

Coalescing matters here. Consecutive threads read consecutive addresses, so the memory system moves full cache lines. A gather pattern, where each thread reads a scattered node, wastes most of that bandwidth and the GPU advantage falls sharply.

Where the trade turns against the GPU

Precision is the first check. On some consumer GPUs double precision runs at 1/64 the rate of single precision. An update that was bandwidth bound in single precision becomes compute bound in double, and the speedup above disappears. Benchmark in the precision the production run will use.

Memory capacity is the second. Ten million elements with history variables can exceed device memory even when the mesh fits comfortably on the host. Spilling to host memory each step reintroduces the PCIe cost and can make the GPU version slower than the CPU version.

The practical test is end to end timing of a full step, including contact search, reductions and checkpoint output, with the state resident. If that is under about 3x faster, the extra code path, the second solver to maintain and the precision risk are usually not worth it. Spend the effort on a coarser mesh for ranking, or on a reduced order model, instead.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-62What does load balancing mean when a simulation domain is split across MPI ranks?

The 90-second answer

Load balancing means each MPI rank gets about the same amount of computational work from the split domain. Domain decomposition divides the mesh or grid into subdomains, one per rank. Each rank updates only its own cells, then exchanges boundary values with neighbours. If the subdomains hold equal work, all ranks finish a step at roughly the same time. If one rank holds much more work, every other rank waits for it at the next exchange or collective operation.

That waiting rank sets the step time for the whole job. Suppose four ranks each need 10 ms for their update, except one needs 20 ms because its subdomain has twice as many cells or a more expensive physics term. The step cannot complete in 10 ms. It completes in 20 ms, and the three fast ranks sit idle for 10 ms. Parallel efficiency from that imbalance alone is the average rank time divided by the slowest rank time, so 12.5 ms divided by 20 ms, or 62.5%. The fix is to rebalance the subdomains so the work per rank is even, not merely to add more ranks.

C
// C with MPI, checked against Open MPI 4.1. Timing the compute phase per rank.
#include <mpi.h>
#include <stdio.h>

double t0 = MPI_Wtime();
// ... update owned cells for this rank ...
double local = MPI_Wtime() - t0;

double slowest;
MPI_Reduce(&local, &slowest, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
if (rank == 0) {
    printf("slowest rank compute time: %.3f ms\n", slowest * 1000.0);
}

A large gap between the slowest rank and the average points to imbalance. A small gap means the split is balanced and the remaining cost is communication or the physics itself.

Worked trace

Take a 1D grid of 1,000 cells split across four ranks, with a halo of one cell exchanged on each side per step. A balanced split gives each rank 250 owned cells. An unbalanced split might give 400, 200, 200 and 200.

RankOwned cellsCompute time per stepIdle time per step
025010 ms0 ms
125010 ms0 ms
225010 ms0 ms
325010 ms0 ms
040016 ms0 ms
12008 ms8 ms
22008 ms8 ms
32008 ms8 ms

The balanced case finishes the step in 10 ms. The unbalanced case finishes in 16 ms even though the total work is identical. Over 10,000 steps that difference is 60 seconds of wall time spent waiting. Repartitioning back to 250 cells per rank removes it.

No, one rank still computing Yes Split domain into subdomains Each rank updates its cells Exchange halo values with neighbours All ranks finished? Other ranks wait Next step

Why equal cell counts are not always equal work

Load balancing is about work, not just cell count. A rank whose subdomain contains a shock, a contact zone or a dense particle cloud may run more iterations or process more particles per cell than a rank in smooth flow. In that case equal cell counts still leave one rank slowest. The practical check is measured time per rank, as in the snippet above, weighted by the actual cost per cell. Repartitioners such as ParMETIS or Zoltan accept those weights, so the heavy region gets fewer cells and the light region gets more. The rule stays the same: balance the work, because the slowest rank gates every step.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-63A 50M-cell FP64 explicit solver must step in 2 ms on one H100, but profiling shows 40% of DRAM bandwidth and 18% of peak FLOPS: how do you meet the deadline without losing accuracy, and what roofline numbers decide the fix?

The 90-second answer

I would not start by optimising either roof. I would first check whether the 2 ms deadline is reachable at all, because the profile you quote, 40% of bandwidth and 18% of FLOPS, is consistent with a kernel that is already wasting most of its traffic. On one H100 SXM, FP64 peak is about 34 TFLOP/s and HBM3 bandwidth is about 3.35 TB/s, so the ridge point is 34e12 / 3.35e12 = 10.1 FLOP/byte. Almost every explicit stencil sits far left of that ridge. The deadline therefore turns on bytes per cell per step, not on FLOPs, and the accuracy constraint rules out the easiest byte cut, which is dropping to FP32 storage.

Use labelled figures for a 50M-cell run: 120 FLOP/cell/step for a high-order flux plus limiter, and 160 byte/cell/step unfused, meaning several fields are read and written by separate kernels. Total work is 6.0 GFLOP and 8.0 GB per step. The bandwidth floor is 8.0 / 3.35 = 2.39 ms and the compute floor is 6.0e9 / 34e12 = 0.18 ms. The step cannot meet 2 ms as written, and no amount of vectorisation changes that. I need traffic below about 6.7 GB per step, a cut of at least 17%, with FP64 arithmetic retained.

Python
# Python 3.11, H100 SXM figures above
peak = 34e12
bw = 3.35e12
cells = 50e6
flops_per_cell = 120

def step_time(bytes_per_cell):
    flops = cells * flops_per_cell
    data = cells * bytes_per_cell
    intensity = flops_per_cell / bytes_per_cell
    attainable = min(peak, bw * intensity)
    return intensity, flops / attainable * 1e3  # ms

for b in (160, 96, 64, 80):
    print(b, step_time(b))

Options against both constraints

ChangeByte/cellIntensityPredicted stepVerdict
Baseline, unfused kernels1600.752.39 msMisses deadline
Fuse flux, update and limiter, tile in shared memory641.880.96 msMeets it if no spills
Same fusion, but register spills add 32 byte/cell of local traffic961.251.43 msStill meets it, margin is thin
FP32 storage, FP64 compute801.501.19 msMeets timing, fails accuracy case below
Raise order to cut error, wider halo2001.001.79 msWorse traffic, no deadline gain

The fused version is the only lever that attacks the binding roof. Tiling matters as much as fusion: a tile of, say, 8x8x8 cells loaded once into shared memory lets each interior face be reused across the stencil width instead of fetched from DRAM for every neighbour. SoA layout keeps those fetches coalesced. Keeping the limiter and flux in one pass also stops intermediate fields from being written and reread.

The subtle failure mode

Fusion is where experienced teams get caught. Packing three stages into one kernel raises register use. Past roughly 64 registers per thread on H100, occupancy falls and the compiler spills arrays to local memory, which is backed by DRAM. The source code looks fused, but measured bytes per cell climb back toward the unfused value and the kernel can end up slower than the baseline. I would check this before believing the roofline prediction: compile with register and spill reporting, for example nvcc -Xptxas -v, and confirm zero spill loads in the inner loop. If spills appear, I split the kernel at the limiter, keep the flux and update fused, and accept 96 byte/cell rather than chase 64 with spills. That split still passes at 1.43 ms and is more predictable.

FP32 storage looks attractive on the same table, halving traffic, but it is the wrong cut here. With FP64 required for the stiff source term and for accumulation over long integrations, FP32 field storage introduces roundoff of order 1e-7 relative per update. Over 1e5 to 1e6 steps that error is systematic in a conservative update, not random noise that averages out, and it shows up as drift in conserved totals and phase error in the wave part of the solution. Mixed precision is defensible for a short ranking run with a tolerance check against an FP64 reference. It is not defensible as the default fix for a production accuracy case.

Yes Yes No No Yes Profile DRAM bytes and FLOPs per step Bytes per cell above deadline budget? Fuse stages and tile for shared reuse Register spills in inner loop? Split at limiter, keep partial fusion Keep FP64, re-measure bytes per cell Step under 2 ms with margin? Reduce halo traffic or split domain, not precision Validate conserved totals against FP64 reference

So the decision is: fuse and tile to cut traffic from 160 to 64 to 96 byte/cell, verify there are no spills, keep FP64, and only then re-measure. If the fused kernel still misses, the next move is to cut halo and field traffic further, for example by not storing derived fields that can be recomputed from neighbours, rather than by trading precision for bytes.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-64For a simulation with 10,000 particles each storing position and velocity, when would you use a list of dataclass objects instead of separate NumPy arrays, and what is the main trade-off?

The 90-second answer

For 10,000 particles with identical fields, I would default to separate NumPy arrays, one for position and one for velocity. I would switch to a list of dataclass objects when the particles are not identical, for example when each one carries its own material, controller state, or optional sensor configuration, and the code needs to call a method on each particle. The trade-off is vectorized throughput against per-particle flexibility. Arrays let the integrator update all particles in one pass. Objects let each particle behave differently, at the cost of a Python loop and scattered memory.

A practical hybrid is common. Keep the numeric state in arrays and keep a list of small dataclasses for the heterogeneous metadata, indexed by the same particle id. That keeps the hot loop vectorized and the configuration readable.

The mechanism behind the gap

A NumPy array of shape (10000, 3) with dtype float64 stores 30,000 doubles contiguously. That is 240,000 bytes for position, the same for velocity, and the update vel += acc * dt touches each byte once in compiled code, with SIMD where the CPU supports it. A list of 10,000 dataclass instances stores each float as a Python object. A Python float is 24 bytes, and each instance and each list adds overhead on top. The same state easily exceeds 2 MB and is scattered across the heap, so the update loop pays for attribute lookup, float unboxing, and cache misses on every particle.

Separate NumPy arraysList of dataclass objects
Storage for pos + vel, 10,000 particles480 KB, contiguousTypically 2 to 4 MB, scattered
Update vel += acc * dtOne vectorized pass, usually under 1 ms for this sizePython loop, typically 10 to 30 ms
Heterogeneous fieldsAwkward. Every particle has the same fields.Natural. Each instance can hold different types or optional fields.
Per-particle behaviourNone. Behaviour lives in functions over arrays.Methods on the class, called per instance.
Adding a fieldAdd a new array, or rebuild a structured dtype.Add a field to the class, with a default.

Those timings are order of magnitude and machine dependent. The structural point holds at any size: contiguous arrays are cheaper to update, objects are cheaper to extend.

Code

Checked against Python 3.11 and NumPy 1.26. The array version is the integrator. The dataclass version is shown only for the case where particles differ.

Python
import numpy as np
from dataclasses import dataclass, field

# Hot state: same fields for every particle
n = 10_000
dt = 0.001
pos = np.zeros((n, 3), dtype=np.float64)
vel = np.zeros((n, 3), dtype=np.float64)
acc = np.zeros((n, 3), dtype=np.float64)

vel += acc * dt
pos += vel * dt

# Heterogeneous metadata: one object per particle
@dataclass
class Particle:
    material: str
    controller: object = None
    pos: tuple = (0.0, 0.0, 0.0)
    vel: tuple = (0.0, 0.0, 0.0)

If I use the dataclass form for the numeric state as well, I add slots=True to cut per-instance memory and prevent accidental attribute creation. I do not use a plain dict for state that the integrator touches every step. A dict adds a hash lookup per field access and hides typos until runtime, since state["vel"] and state["vle"] are both legal operations.

Failure modes to check

With arrays, the common bug is dtype drift. If acc is float32 and vel is float64, the in-place update can raise a casting error or silently truncate depending on the NumPy version. I keep the integrator in float64 and cast at the output boundary. The second bug is misalignment after filtering. Applying a boolean mask creates new arrays, so any neighbour list or id list stored elsewhere must be rebuilt in the same step. I assert len(pos) == len(vel) == n after any structural change.

With objects, the common bug is a shared mutable default. Writing pos: list = [] in a dataclass shares one list across all instances, so particles leak state into each other. The fix is field(default_factory=list). The other failure is silent growth in memory. Each new attribute on a non-slotted instance adds a dict entry, so a simulation that attaches diagnostic fields per particle can grow without bound. I detect both by checking instance count and total array size at checkpoint time, and by serializing particle ids alongside the arrays so a resumed run cannot misalign fields.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-65When would you choose asyncio over threading for IO-bound simulation tasks, and when would neither help?

The 90-second answer

For IO-bound simulation work, both asyncio and threading overlap waits instead of executing them in parallel. The choice is about where the waiting happens and who owns shared state. I pick asyncio when the tasks are mostly sockets, pipes, subprocesses or async file APIs and the code is mine end to end. One thread runs an event loop, each task yields at an await, and there is no preemption between awaits. That removes data races on shared simulation state and makes ordering easier to reason about. I pick threading when I must call blocking libraries I cannot rewrite, such as a vendor sensor SDK, a blocking requests call, or a solver launcher that only exposes a synchronous API. Threads let the OS block each caller independently while the GIL is released during the IO wait.

Neither helps for CPU-bound work. A Python RK4 step, a NumPy call that holds the GIL for long stretches, or a pure Python particle update will not speed up on threads in default CPython, and asyncio will stall the loop if that code runs inline. That case needs ProcessPoolExecutor, multiprocessing, or moving the hot loop to Numba, Cython or a compiled solver.

Worked arithmetic

Suppose a co-simulation step polls 200 sensor sockets, each reply takes 80 ms, and the step budget is 100 ms.

ApproachWall time per stepWhy
Sequential200 x 80 ms = 16,000 msWaits are serial
asyncioabout 80 ms plus scheduling overheadAll sockets are open at once, one thread
Threading, 32 workersabout 7 batches x 80 ms = 560 msPool size caps concurrency
Threading, 200 workersabout 80 ms plus thread overheadOne thread per socket, more memory and contention

The numbers are illustrative, but the shape is real. Asyncio gets high concurrency cheaply. Threading gets the same overlap only if the pool is sized for it, and each thread carries stack and scheduling cost.

Code shape

Python
import asyncio
import concurrent.futures

# asyncio: native async IO, one thread, no locks on shared state
async def poll_socket(sock):
    data = await sock.recv(4096)  # yields without blocking the loop
    return parse_frame(data)

async def run_async(sockets):
    return await asyncio.gather(*(poll_socket(s) for s in sockets))

# threading: wrap a blocking SDK call, GIL released while it waits
def poll_blocking(client):
    return parse_frame(client.read_frame())  # blocking call

def run_threaded(clients):
    with concurrent.futures.ThreadPoolExecutor(max_workers=32) as pool:
        return list(pool.map(poll_blocking, clients))

If an asyncio task calls poll_blocking directly, the loop freezes for the full 80 ms per call and every other socket misses its deadline. The fix is await loop.run_in_executor(None, poll_blocking, client), which moves that call to a thread pool. At that point the design is threading underneath, with asyncio only orchestrating it.

DimensionasyncioThreading
Concurrency unitCoroutine, cooperative at awaitOS thread, preemptive
Shared stateSafe between awaits, unsafe across themRacy anywhere, needs locks
Blocking libraryBreaks the loop unless sent to an executorNatural fit
CancellationTask.cancel() at the next await pointHard to interrupt a blocked call cleanly
DeterminismEasier to replay, single-threaded orderInterleaving varies run to run
Scaling limitOne core, loop lag if CPU work sneaks inPool size, GIL for CPU work

Failure modes I watch for

In asyncio, the classic failure is a hidden blocking call. A NumPy solve, a time.sleep, or a synchronous file read inside a coroutine adds its full duration to loop lag, and timestamps derived from loop time drift. I measure loop lag by scheduling a heartbeat coroutine every 10 ms and alerting if it slips past, say, 25 ms. In threading, the failures are pool exhaustion, where queued tasks wait longer than the step budget, and races on shared arrays, such as two threads updating particle positions in place. Both show up as nondeterministic results between identical runs. I detect the first with pool queue depth and per-task wait time, and the second by running the same seed twice and diffing the state hash.

My rule of thumb: start with asyncio for sockets and subprocesses I control, use threads only at the boundary with blocking code, and reach for processes the moment profiling shows CPU time, not wait time, dominating the step.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-66What does a large condition number of A mean when you solve Ax = b?

The 90-second answer

A large condition number means the solution of Ax = b is sensitive to small changes in b or in A. In the 2-norm, kappa(A) = sigma_max / sigma_min, the ratio of the largest to the smallest singular value of A. When that ratio is near 1, a small relative error in the data produces a comparably small relative error in x. When it is large, the same small error can be amplified by roughly that factor.

The bound candidates quote is:

||delta_x|| / ||x||  <=  kappa(A) * ||delta_b|| / ||b||

It is a worst case bound. Whether a particular perturbation reaches it depends on its direction. A perturbation aligned with the singular vector for sigma_min gets amplified by 1 / sigma_min. In simulation that alignment is not rare. Mesh distortion, noisy sensor data and truncated geometry tend to excite exactly those weak directions.

A concrete case

Take A = diag(1, 1e-8) and b = (1, 1e-8), so x = (1, 1). The singular values are 1 and 1e-8, so kappa(A) = 1e8. Change the second entry of b by 1e-8. That is a relative change of about 1e-8 in b, since ||b|| is about 1. The second entry of x changes by 1e-8 / 1e-8 = 1, so x becomes (1, 2). A tiny change in the data doubled one component of the answer.

kappa(A)Relative error in bWorst case relative error in x
101e-81e-7
1e41e-81e-4
1e81e-81
1e161e-81e8

Double precision has machine epsilon near 2.2e-16. Once kappa(A) approaches 1e16, roundoff alone can overwhelm the smallest singular direction, and no solver tolerance will rescue the result.

Checking it

Python
import numpy as np

A = np.diag([1.0, 1e-8])
b = np.array([1.0, 1e-8])
print(np.linalg.cond(A))  # 1e8, 2-norm by default
x = np.linalg.solve(A, b)  # [1. 1.]
x2 = np.linalg.solve(A, b + np.array([0.0, 1e-8]))  # [1. 2.]

For a large sparse stiffness matrix you would not form the inverse. Estimate the extreme singular values with an iterative eigensolver, or watch pivot growth during LU factorisation as a cheaper warning.

What to do about it

Refining the mesh or tightening the solver tolerance does not fix ill-conditioning. It often makes kappa worse, because a finer discretisation adds more small singular values. The useful fixes are to remove the near dependency, for example by constraining a rigid body mode instead of adding a tiny spring, to scale rows and columns so their magnitudes are comparable, or to regularise with a penalty term lambda^2 ||x||^2 and accept a small bias in exchange for a large drop in variance. If the weak direction does not affect the quantity of interest, project it out and say which result remains trustworthy.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-67Your FEA takes 10 minutes per run and you must optimize 12 parameters under a stress constraint with a 200-run budget. How do you choose and run the optimization?

The 90-second answer

State the budget before picking an algorithm. For an expensive simulator, the choice is driven by three numbers: cost per run, number of parameters, and noise in the objective. A 12-parameter FEA at 10 minutes per run makes a finite-difference gradient cost 13 runs, or 130 minutes, for one step. That rules out naive gradient descent unless you have an adjoint or a cheap surrogate gradient. My default for 8 to 20 parameters, a budget of 100 to 300 runs, and mild noise is a two-stage approach: a space-filling design to find the basin, then a local derivative-free optimizer such as Nelder-Mead, Powell, or CMA-ES from the best points. If runs are very expensive, under 100 total, Bayesian optimization with a Gaussian process surrogate usually beats both. If the simulator is cheap, under a second, differential evolution or CMA-ES from the start is simpler and harder to trap.

Why the naive choices fail here

Finite differences assume a smooth, deterministic objective. FEA and CFD objectives are often neither. Mesh adaptation, iterative solver tolerances, and contact chatter can add 0.5 to 2% noise to a quantity of interest. A central difference with step h then estimates a gradient dominated by noise when the true change over h is smaller than that band. You detect this by running the same design point five times with different seeds or solver settings. If the spread is comparable to the improvement you are chasing, no optimizer will save you. Fix the noise first: tighten solver tolerance by a factor of 10, freeze the mesh, or use common random numbers so comparisons share the same stochastic error.

Constraints are the second trap. A penalty term such as objective + 1000 * max(0, stress - limit)^2 creates a cliff that derivative-free methods handle poorly and gradient methods exploit. For a hard limit like peak stress below 250 MPa, I prefer to keep the constraint explicit. SLSQP and COBYLA accept inequality constraints directly. CMA-ES needs a repair or resampling rule: reject infeasible candidates and resample, or rank feasible points ahead of infeasible ones regardless of objective value.

Worked budget

Assume 12 parameters, 10 minutes per run, 8 cores available, and a 200-run budget.

StrategyRuns to first candidateTotal wall timeRisk
Finite-difference SLSQP13 per iteration, about 15 iterations = 19532.5 h serial, 4.1 h on 8 coresGradient noise, local minimum
Latin hypercube (40) + Nelder-Mead (160)40 before local search starts33.3 h serial, 4.2 h on 8 coresSimplex collapse in 12D
Bayesian optimization (GP, 200)Sequential, no batch until 2033.3 h serial, less if batchedGP struggles above about 20D

Nelder-Mead in 12 dimensions needs a simplex of 13 points and typically 300 to 500 evaluations to converge well. With only 160 left after screening, Powell's method, which does line searches along conjugate directions, often does better in that budget. CMA-ES is the stronger choice if you can afford 500 or more runs, because its population of about 10 to 14 per generation averages out noise.

Code: screening plus local search with constraints

Python
# Python 3.11, scipy 1.13. Checked against scipy.optimize.
import numpy as np
from scipy.optimize import differential_evolution, minimize

def simulate(x):
    """Replace with FEA call. Returns (objective, max_stress)."""
    return 0.0, 0.0

def objective(x):
    obj, stress = simulate(x)
    return obj if stress <= 250.0 else 1e6 + 100.0 * (stress - 250.0)

bounds = [(0.5, 2.0)] * 12  # thickness, stiffness, damping, etc.

# Stage 1: global screening, popsize 5 gives 60 points per generation.
result = differential_evolution(
    objective, bounds, maxiter=3, popsize=5, seed=1,
    polish=False, workers=8, updating="deferred",
)

# Stage 2: local polish from the best point with Powell.
local = minimize(objective, result.x, method="Powell",
                 bounds=bounds, options={"maxfev": 120, "xtol": 1e-3})

workers=8 with updating="deferred" evaluates a generation in parallel, which matters when one run is 10 minutes. Do not use polish=True inside differential evolution here, because its default L-BFGS-B polish will spend finite-difference runs on a noisy objective.

Overfitting to the simulator

An optimizer will exploit any systematic error in the model. If the mesh is coarse, it will push thickness to the lower bound in a region where the coarse mesh underpredicts stress. Guard against this in two ways. First, hold out validation points: reserve 20% of the budget for designs the optimizer never sees, and check that the predicted improvement holds there. Second, re-run the final candidate on a refined mesh and with a tighter solver tolerance. If peak stress moves by more than your acceptance margin, the optimum was a mesh artifact, not a design improvement. Report the optimum with that refined-mesh value, not the value the optimizer saw.

For multi-objective work, such as mass versus stiffness, do not collapse to a weighted sum unless you can defend the weight. Run the optimizer for two or three weights and report the Pareto points you actually evaluated. A single weighted answer hides the trade-off the design review needs to see.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-68For a CFD shape optimization with 8 continuous parameters, 2 hours per run and an adjoint solver available, how does gradient-based optimization compare with derivative-free on cost per iteration, and when would you still choose derivative-free?

The 90-second answer

With 8 continuous shape parameters and an adjoint available, I would use gradient-based optimization, typically L-BFGS-B, and I would expect it to reach a given drag reduction in far fewer solver runs than a derivative-free method. The deciding factor is cost per iteration. A forward finite-difference gradient needs 9 runs for 8 parameters. An adjoint needs about 2 to 3 run equivalents in total, and that cost stays roughly flat if the parameter count grows. A derivative-free method such as Nelder-Mead or CMA-ES evaluates one design at a time and usually needs hundreds of evaluations in 8 dimensions. If each run takes 2 hours, that difference is days against weeks.

I would still pick derivative-free if the objective were not smooth enough for a gradient to be meaningful, for example if adaptive remeshing made drag jump between nearby shapes, or if some parameters were discrete choices such as airfoil family or number of vortex generators. In those cases the gradient points in a random direction and a ranking based method is more honest.

How the gradient is obtained

Finite differences perturb one parameter at a time and divide the change in drag by the change in shape. The step size matters. A step that is too small produces a drag change below solver convergence noise. A step that is too large measures curvature rather than the local slope. With adaptive meshing the response can also be discontinuous, because the mesh topology changes between runs.

A discrete adjoint differentiates the solver code as written and returns the sensitivity of drag to every shape parameter from one additional solve. It is the main reason gradient-based optimization wins on cost here. Its weakness is implementation effort. The adjoint must cover the turbulence model, boundary conditions and moving mesh terms, and a missing term gives a wrong gradient that still looks plausible.

Automatic differentiation is a third route for codes written in a differentiable framework. It gives discrete gradients without hand derivation, but it is rarely available for a legacy implicit CFD solver with iterative linear algebra.

MethodRuns per gradient, 8 parametersScaling with parameter countHandles noisy or discontinuous dragMain risk
Forward finite difference9LinearPoorStep size dilemma and solver noise
Discrete adjointAbout 2 to 3 equivalentsRoughly constantPoorMissing or buggy term in the adjoint
Nelder-Mead or CMA-ES1 per trial, often 200 to 500 trials totalGrows quicklyBetter, based on ranking designsBudget spent before convergence

Worked budget

Assume 2 hours per run and 15 optimizer iterations. Finite-difference L-BFGS-B costs 15 x 9 x 2 = 270 hours before line search evaluations. The adjoint version costs about 15 x 5 = 75 hours. CMA-ES with a population of 12 needs 12 runs per generation, so 15 generations is 360 hours, and it typically needs more generations than L-BFGS-B to reach the same precision on a smooth problem.

Python
# Python 3.11, SciPy 1.14. Forward finite-difference gradient.
# Each call to drag(x) is one 2 h CFD run.
import numpy as np

def fd_gradient(drag, x, h=1e-3):
    f0 = drag(x)
    grad = np.empty_like(x)
    for i in range(len(x)):
        xp = x.copy()
        xp[i] += h * max(1.0, abs(x[i]))
        grad[i] = (drag(xp) - f0) / (xp[i] - x[i])
    return f0, grad  # 9 evaluations for 8 parameters

# Adjoint route replaces the loop with one call:
# f0, grad = drag_and_adjoint(x)  # about 2 to 3 run equivalents

Checks before trusting the result

I first check smoothness by repeating one design with a different mesh seed or tighter convergence. If drag varies by 0.4% between repeats while one optimizer step is expected to improve drag by 0.2%, a finite-difference gradient will mostly reflect noise. I would then fix the mesh during optimization, tighten convergence, or switch to derivative-free search.

I also verify the adjoint against finite differences on a coarse mesh for two or three parameters. Agreement within a few percent is the expected outcome. A large mismatch usually traces to a turbulence source term or a moving boundary contribution that the adjoint omitted.

Non-smooth physics is the other common failure. A shock crossing a cell or separation onset can make drag piecewise smooth, and L-BFGS-B will stall or oscillate near the kink. A practical fix is to optimize with the limiter frozen or the mesh fixed, then recheck the final design with the full model. If the kink is the design feature of interest, a small derivative-free search around it is safer than forcing a gradient through it.

The rule I apply is simple. Many continuous parameters, expensive runs and a smooth objective favour the adjoint. Few parameters, a black-box solver, discrete choices or a discontinuous response favour derivative-free, provided the evaluation budget can cover the trials it needs.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-69For laminar flow over a flat plate, how does Blasius theory give you delta and Cf, and how would you use those values to check the near-wall mesh in a CFD run?

The 90-second answer

Blasius theory gives you a laminar flat-plate solution you can compute on paper before you mesh. You compare the CFD skin friction and velocity profile against it at a station upstream of transition. If they disagree there, the near-wall mesh or the boundary condition is the problem, and arguing about the turbulence model downstream will not fix it.

The mechanism starts with no slip. Fluid at the wall has the wall velocity, fluid far from the wall has the free-stream velocity $U$. Viscosity forces that change to happen across a thin layer of thickness $\delta$. Inside the layer the velocity gradient is steep, so wall shear $\tau_w = \mu (\partial u/\partial y)_{wall}$ is large. Outside the layer the flow is close to inviscid and sets the pressure.

For steady, incompressible, laminar flow over a flat plate with zero pressure gradient, Blasius showed the Navier-Stokes equations collapse to a single ordinary differential equation by similarity. With $\eta = y\sqrt{U/(\nu x)}$, the profile $u/U = f'(\eta)$ has the same shape at every downstream distance $x$. Integrating that profile gives the standard results:

$\delta \approx 5x/\sqrt{Re_x}$, $\delta^* \approx 1.72x/\sqrt{Re_x}$, $\theta \approx 0.664x/\sqrt{Re_x}$, $C_f \approx 0.664/\sqrt{Re_x}$

Here $Re_x = Ux/\nu$, $\delta^$ is displacement thickness, $\theta$ is momentum thickness, and $C_f = \tau_w/(0.5\rho U^2)$ is the local skin friction coefficient. The ratio $H = \delta^/\theta$ is about 2.59 for this profile. Those numbers are the check.

Worked example

Take air with $\nu = 1.5\times10^{-5},\text{m}^2/\text{s}$ and $U = 10,\text{m/s}$. At $x = 0.30,\text{m}$, $Re_x = 2.0\times10^5$, safely laminar for a clean plate.

Quantity at $x = 0.30$ mBlasius value
$\delta$$5x/\sqrt{Re_x} \approx 3.4$ mm
$\delta^*$$\approx 1.2$ mm
$\theta$$\approx 0.45$ mm
$C_f$$0.664/\sqrt{Re_x} \approx 1.5\times10^{-3}$
Python
import math
U, nu, x = 10.0, 1.5e-5, 0.30
Re = U * x / nu
delta = 5 * x / math.sqrt(Re)
Cf = 0.664 / math.sqrt(Re)
print(f"Re_x={Re:.2e} delta={delta*1e3:.2f} mm Cf={Cf:.2e}")

That script is the pre-mesh estimate. It tells you the layer is only a few millimetres thick, so a mesh with 2 mm cells everywhere will put roughly one cell inside it. You need clustering toward the wall, with several cells inside $\delta$ and the smallest cell well below $\delta$, if you want the gradient at the wall resolved.

How you use it in the run

Probe the CFD solution at $x = 0.30$ m. Plot $u/U$ against $y/\delta$ and compare the shape with $f'(\eta)$. Read $C_f$ from the wall shear and compare it with $1.5\times10^{-3}$. A common failure is a first cell that is too tall. The solver then underpredicts the wall gradient, $C_f$ comes out low, and the profile looks smeared across the layer. Refining the whole mesh wastes cells in the outer flow. Refining only the wall-normal direction, keeping the streamwise spacing, fixes the check with far fewer cells.

The check has limits. It assumes a flat plate, zero pressure gradient, steady laminar flow, and no roughness or free-stream turbulence tripping the layer early. On a curved surface or under an adverse pressure gradient the profile changes and $H$ rises, so Blasius no longer predicts the numbers. Used inside its assumptions, it separates a mesh problem from a physics problem in one probe, which is why it is worth doing before any mesh convergence study on drag.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-70Which of conduction, convection and radiation can occur in a vacuum, and how does its heat flux depend on temperature?

The 90-second answer

Only radiation can occur in a vacuum. Conduction needs a material to conduct through and convection needs a fluid to carry the heat. Radiation travels as electromagnetic waves, so it needs neither.

Its flux from a small gray surface follows Stefan-Boltzmann:

q'' = eps sigma (Ts^4 - Tsurr^4)

where q'' is in W/m2, eps is emissivity between 0 and 1, sigma = 5.67e-8 W/m2K4, and both temperatures are absolute, in kelvin. The key point for a simulation is the fourth power. Heat flux does not scale with the temperature difference. It scales with the difference of the fourth powers.

Worked numbers

Take a surface with eps = 0.8 facing surroundings at 300 K.

At Ts = 400 K: 0.8 * 5.67e-8 * (400^4 - 300^4) = 793 W/m2.

At Ts = 600 K: 0.8 * 5.67e-8 * (600^4 - 300^4) = 5,500 W/m2.

At Ts = 900 K: 0.8 * 5.67e-8 * (900^4 - 300^4) = 29,400 W/m2.

Raising the surface from 400 K to 600 K is a 200 K rise and multiplies the flux by about 7. Raising it from 600 K to 900 K is a 300 K rise and multiplies the flux by about 5.3. A linear model fitted at 400 K would underpredict the 900 K flux by more than an order of magnitude.

Python
# Python 3
sigma = 5.67e-8

def radiation(eps, Ts, Tsurr):
    return eps * sigma * (Ts**4 - Tsurr**4)

for Ts in (400, 600, 900):
    print(Ts, round(radiation(0.8, Ts, 300)))
# 400 793
# 600 5500
# 900 29400

Why the other two stop in vacuum

ModeMedium requiredFlux lawIn vacuum
conductionsolid, liquid or gas with conductivity kq'' = -k dT/dxno conduction path, so no flux
convectionmoving fluid with coefficient hq'' = h (Ts - Tinf)no fluid, so h is effectively zero
radiationnoneq'' = eps sigma (Ts^4 - Tsurr^4)unchanged, waves cross empty space

That is why a satellite panel in orbit, with no air around it, still cools by radiation and why a thermos flask uses a vacuum gap to stop conduction and convection while a reflective coating cuts the radiation term through a low eps.

What this means in a model

In code I add radiation as a nonlinear boundary term evaluated at the current surface temperature each iteration, not as a fixed heat transfer coefficient. If I linearise it for speed, I write q'' = h_rad (Ts - Tsurr) with h_rad = eps sigma (Ts + Tsurr)(Ts^2 + Tsurr^2) and I recompute h_rad when temperature moves. Reusing a value calibrated at 350 K for a part that later reaches 800 K is the usual error. The conduction and convection terms can stay linear in the temperature difference for a given k and h. The radiation term cannot, because of the T^4 dependence.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-71For air at 300 K flowing over a wing at 250 m/s and water in a 10 mm pipe at 3 m/s, how do you decide whether to treat each as compressible or incompressible, and what fluid properties and equations change if you get it wrong?

The 90-second answer

I do not decide from the fluid name. I decide from the largest local Mach number and from how much density actually changes along the path, then I check whether temperature change alone forces variable density even at low Mach.

For a gas, $M = U/a$ with $a=\sqrt{\gamma R T}$. At $M<0.3$ the isentropic density change is under about 5%, so constant density is usually defensible for forces. Above that, and certainly near $M=1$, I solve the compressible equations with an equation of state. For a liquid, $M$ is almost always tiny because $a$ is large, so steady flow is incompressible even at high pressure. Transient liquid flow is the exception: water hammer and cavitation need compressibility or a cavitation model.

Worked check

Air at 300 K: $a=\sqrt{1.4 \times 287 \times 300}=347$ m/s. At 250 m/s, $M=0.72$. That is not a borderline case.

Water in a pipe at 3 m/s: $a \approx 1480$ m/s, so $M=0.002$. Density change from pressure is $\Delta\rho/\rho \approx \Delta p/K$ with bulk modulus $K \approx 2.2$ GPa. Even a 10 MPa swing gives 0.45%.

Python
import math

def density_ratio(M, gamma=1.4):
    return (1 + (gamma - 1) / 2 * M**2) ** (1 / (gamma - 1))

for M in (0.1, 0.3, 0.72, 1.0):
    print(M, round(density_ratio(M), 4))
# 0.1 -> 1.005, 0.3 -> 1.0456, 0.72 -> 1.2797, 1.0 -> 1.5774
Case$M_{max}$$\rho_0/\rho$Treatment
Air, 250 m/s, 300 K0.721.28Compressible, ideal gas EOS
Air, 80 m/s, 300 K0.231.03Incompressible acceptable for drag ranking
Water, 3 m/s pipe0.0021.000Incompressible, constant $\rho$
Water, valve slam, 1 m/s stoppage0.0007 steady, transient $\Delta p \approx \rho a \Delta U \approx 1.5$ MPa1.000 steady, compressible transientWater hammer needs $a$ and $K$

Use local $M_{max}$, not freestream. A wing at freestream $M=0.75$ can have $M>1$ over the suction peak and a shock near the trailing edge. An incompressible run there will miss the shock, the drag rise and the separation it triggers, and no mesh refinement fixes a missing term in the equations. At freestream $M=0.25$ a local peak of $M=0.6$ produces no shock, but the density ratio is already about 1.08, so forces and pressure distribution are still off by several percent.

What changes in the model

ItemIncompressibleCompressible
Continuity$\nabla \cdot \mathbf{u}=0$$\partial\rho/\partial t + \nabla \cdot (\rho\mathbf{u})=0$
DensityConstant, or Boussinesq $\rho=\rho_0[1-\beta(T-T_0)]$ for buoyancy$\rho=p/(RT)$ for ideal gas, or real gas table
EnergyOften dropped if isothermalRequired, $\rho E$ equation with $c_p$, $c_v$, $\gamma$
PressureLagrange multiplier enforcing continuity, no EOSState variable through EOS, sets $a$
Time stepConvective CFL, $\Delta t \sim \Delta x/U$Acoustic CFL, $\Delta t \sim \Delta x/(U+a)$, often 3 to 10 times smaller

Fluid properties follow the same split. Incompressible water at 20 C: $\rho=998$ kg/m3, $\mu=1.0\times10^{-3}$ Pa s, $c_p=4182$ J/kg K. Incompressible air at 300 K and 1 atm: $\rho=1.177$ kg/m3, $\mu=1.846\times10^{-5}$ Pa s from Sutherland's law, $c_p=1007$ J/kg K. Compressible air needs those as functions of $T$ and $p$, plus $\gamma$ and the EOS, because density, sound speed and viscosity all move with temperature across a shock or in a heated channel.

Yes No Yes No Yes Compute local Mmax and dT Mmax above 0.3 or shock possible Compressible with EOS and energy Density change from heating above 5 percent Variable density or Boussinesq Incompressible constant density Transient pressure wave in liquid Add bulk modulus or water hammer model

Failure modes I watch for

Running a compressible solver on steady water flow wastes effort and invites trouble. The acoustic CFL forces tiny steps, pressure waves reflect off boundaries, and a stiff EOS can produce ringing that looks like unsteadiness. Running incompressible on transonic air is worse: it converges cleanly to the wrong physics.

Two traps sit between those extremes. First, low Mach does not mean constant density if temperature swings are large. A heat exchanger with air heated from 300 K to 900 K changes density by a factor of three at constant pressure, so $\nabla \cdot \mathbf{u}=0$ fails even at $M=0.05$. Second, incompressible liquid flow can still fail through cavitation. When local pressure drops below vapour pressure, the flow creates vapour pockets, and a single phase constant density model cannot represent the load or the noise. I check the cavitation number $\sigma=(p-p_v)/(\frac{1}{2}\rho U^2)$ against the minimum pressure coefficient before trusting the run.

My rule in practice: report $M_{max}$, the density ratio from the formula above, and the temperature ratio for every run. If any of them moves density by more than about 5%, the incompressible assumption goes in the report as a stated limitation, not a silent default.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-72For a transonic airfoil CFD run, how do you capture a shock without spurious oscillations, and why does a conservative scheme get the shock speed right even when the shock is smeared over a few cells?

The 90-second answer

Use a conservative finite-volume scheme with a high-resolution reconstruction, typically MUSCL with a TVD limiter, and let the numerical flux supply the dissipation at the discontinuity. The shock will be smeared over two to four cells, but its speed will be correct because conservation plus consistency forces the discrete jump to satisfy the Rankine-Hugoniot condition in the limit. A non-conservative discretisation can look sharper and still move the shock at the wrong speed.

For a transonic airfoil I would start from a Godunov-type flux for the Euler equations, reconstruct left and right states at each face with a limiter, advance with an explicit Runge-Kutta method under a CFL number below one, and check the solution for overshoots in pressure and density near the shock foot.

Why conservation fixes the speed

Write the one-dimensional Euler equations as $U_t + F(U)x = 0$, with $U = (\rho, \rho u, E)$. A shock moving at speed $s$ must satisfy $s[U] = [F]$, where brackets denote the jump across the shock. That relation comes from integrating the PDE over a control volume that straddles the shock. If the scheme updates cell averages by differencing fluxes, $U_i^{n+1} = U_i^n - \lambda (\hat F{i+1/2} - \hat F_{i-1/2})$, then the total mass, momentum and energy in a large patch change only through the boundary fluxes. The Lax-Wendroff theorem says a conservative scheme that converges will converge to a weak solution, so the captured profile, however smeared, must travel at the speed implied by those integral balances. Smearing changes the internal structure of the profile. It does not change the jump between the far upstream and far downstream states, and that jump sets the speed.

A primitive-variable or non-conservative form, $U_t + A(U)U_x = 0$, discretises a different equation at the discontinuity. The product $A(U)U_x$ is not defined where $U_x$ is a delta function, and the discrete result depends on the path taken through state space. In practice the shock speed error can be several percent and does not vanish cleanly under refinement.

Worked numbers

Take a normal shock at Mach 2.0 in air, $\gamma = 1.4$, upstream pressure $p_1 = 101$ kPa and density $\rho_1 = 1.225$ kg/m$^3$. The normal-shock relations give $p_2/p_1 = 4.50$, $\rho_2/\rho_1 = 2.67$ and $s = 680$ m/s. A conservative solver on a coarse mesh might spread that jump over three cells, with intermediate pressures of, say, 180, 320 and 430 kPa. The cell averages are wrong inside the layer, but the flux difference across the layer still enforces the correct mass and momentum jump, so the layer position advances at close to 680 m/s. Refining the mesh narrows the layer. It does not need to, for the speed to be right.

How the limiter stops the oscillations

A second-order central reconstruction near a discontinuity produces Gibbs overshoots, then negative pressures and a failed run. The limiter blends the reconstruction back toward first order where the solution is not smooth. The minmod limiter is the simplest example:

Python
# Python 3, MUSCL reconstruction slope in one cell
def minmod(a, b):
    if a * b <= 0:
        return 0.0
    return a if abs(a) < abs(b) else b

def face_states(u_im1, u_i, u_ip1):
    slope = minmod(u_i - u_im1, u_ip1 - u_i)
    return u_i - 0.5 * slope, u_i + 0.5 * slope  # left, right face values

At a smooth extremum the differences change sign, the slope becomes zero, and the scheme locally drops to first order. At a monotone shock the slope is limited so the face values stay between neighbouring cell averages. That total-variation-diminishing property prevents new extrema from appearing. The cost is clipping of smooth peaks, which is why a minmod run underpredicts a suction peak slightly more than a less dissipative limiter such as van Leer or superbee.

A hypothetical Sod tube trace at a fixed time illustrates the effect. Values are cell-centred pressures in kPa across a shock near cell 6:

Cell456789
Central, no limiter16.215.119.831.430.230.0
MUSCL-minmod16.216.118.429.630.030.0
Exact far states16.216.216.230.030.030.0

The central column overshoots on both sides. The limited column is monotone and reaches the downstream state within two cells.

Choosing between schemes

SchemeShock widthSmooth-region accuracyMain risk
First-order Godunov4 to 8 cellsFirst order, very dissipativeSmears contact waves and shear layers, drag error on the airfoil
MUSCL with TVD limiter2 to 3 cellsSecond order away from extremaPeak clipping, needs an entropy fix at sonic points
WENO5 with Godunov flux2 to 3 cellsFifth order in smooth regionsHigher cost per step, more code to verify, still needs a positivity check

For a production airfoil run I would pick MUSCL with van Leer or minmod for the first pass, then move to WENO5 if the quantity of interest is lift or pitching moment and the mesh budget allows it. First-order Godunov is a useful sanity check because it is hard to make it oscillate, but its dissipation will move the shock foot and thicken the boundary layer interaction.

Failure modes to check

An expansion shock can appear at a sonic point if the numerical flux does not respect the entropy condition. The symptom is a stationary kink in Mach number near Mach 1 with no physical compression. An entropy fix, such as the Harten-Hyman correction to the Roe flux or an exact Godunov flux, removes it. A second failure is a carbuncle pattern when a strong shock sits almost aligned with grid lines on a structured mesh, visible as a sawtooth in pressure along the shock. Unstructured meshes, a small amount of dissipation, or rotating the mesh a few degrees usually suppress it. Finally, check positivity after every stage. A single cell with negative density or pressure will poison the flux calculation, and limiters alone do not guarantee positivity under a large CFL number.

Yes No Cell averages Reconstruct face states Apply TVD limiter Godunov flux at face Conservative update Negative p or rho? Cut CFL, add entropy fix

The practical test is a one-dimensional shock tube and a flat-plate case at the same Mach number before the airfoil run. If the shock speed and post-shock state match the normal-shock relations on a coarse mesh, the capturing machinery is doing its job. If they do not, refining the airfoil mesh will only produce a sharper wrong answer.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-73For a flat plate at Re_x = 2e6 with transition near 5e5, how would you model laminar-turbulent transition in RANS CFD, and when would a fully turbulent assumption mislead drag and separation predictions?

The 90-second answer

For a flat plate or airfoil at Re_x up to a few million, I would run RANS with a transition model coupled to SST, usually Langtry-Menter gamma-Re_theta, and I would check it against a fully turbulent run and, if the budget allows, a resolved run on a smaller domain. The transition model adds two transport equations to SST. One carries intermittency gamma, 0 in laminar flow and 1 in fully turbulent flow. The other carries Re_theta_t, the momentum thickness Reynolds number at transition onset, which sets where production of gamma starts. The solver blends laminar and turbulent viscosity and production terms by gamma, so skin friction rises through the transition zone instead of jumping at the leading edge.

A fully turbulent assumption fixes gamma at 1 from x = 0. That is defensible when transition is forced very early by roughness or high freestream turbulence, or when the quantity of interest is insensitive to the upstream boundary layer. It misleads when a laminar run, a separation bubble, or a long laminar stretch controls drag. It overpredicts skin friction over the laminar portion by roughly a factor of 5 to 7, thickens the boundary layer too early, and can move predicted separation and stall.

Worked numbers for a flat plate

Use the standard flat plate correlations as a sanity check, with Re_x = U x / nu.

x positionRe_xLaminar Cf, 0.664/sqrt(Re_x)Turbulent Cf, 0.074/Re_x^(1/5)Ratio
0.25 m at U = 30 m/s, nu = 1.5e-55.0e50.000940.005365.7
0.50 m1.0e60.000660.004677.0
1.00 m2.0e60.000470.004078.6

If transition is near Re_x = 5e5, a fully turbulent run applies about 0.0054 where the real flow is near 0.0009. Integrated over the first half metre that error dominates the drag difference between two airfoil sections, even if the turbulent part is modelled well. A transition model should reproduce a Cf rise over a finite length, often 0.1 to 0.3 m at this Reynolds number depending on freestream turbulence intensity Tu, pressure gradient, and surface roughness.

No, forced early Yes Estimate Re_x and Tu at inlet Transition expected before separation or drag rise? Fully turbulent SST, document assumption Gamma-Re_theta SST, y+ near 1 Check Cf(x) and gamma(x) against flat plate data Sensitivity to Tu and Re_theta_t correlation

How gamma-Re_theta behaves, and where it fails

Gamma is produced when the local momentum thickness Reynolds number Re_theta exceeds a critical value Re_theta_c. In the Langtry-Menter correlation, Re_theta_c = 1200 - 4000 / Re_theta_t, so a higher inlet Re_theta_t (higher Tu) lowers the threshold and moves onset upstream. Gamma is destroyed by a term proportional to gamma, so gamma relaxes back toward laminar values if local conditions become favourable again. Re_theta_t is transported from the inlet value computed from Tu and the local length scale. That inlet value is the main calibration knob. In OpenFOAM or Fluent style setups you set freestream turbulence intensity and viscosity ratio, and the correlation converts them to a transition onset Reynolds number.

Adverse pressure gradient and surface roughness both promote earlier transition in reality. The standard correlation captures the Tu effect through Re_theta_t, but it does not fully capture strong pressure gradient, roughness tripping, or crossflow effects, so those cases need extra checks rather than blind trust in the default constants.

Failure modes I check in practice:

  1. Wrong Tu at the inlet. A wind tunnel or flight condition with Tu = 0.1% transitions much later than Tu = 1%. If the inlet Tu is guessed, transition location can move by tens of percent in x. I run the case at Tu multiplied and divided by about 3 and report the spread in drag.
  2. Mesh and y+. Gamma production is sensitive to near wall resolution. With wall functions at y+ = 30 to 100 the model often transitions too early or not at all. I use y+ near 1 with at least 15 to 20 cells across the boundary layer in the transition region, and I check that gamma stays between 0 and 1 without overshoot.
  3. Roughness and crossflow. The standard correlation has no roughness trip model and no crossflow instability. A rough leading edge or a swept wing with crossflow transition will be mispredicted. For those I either trip the boundary layer in the geometry, use an e^N based onset from a stability solver, or move to LES.
  4. Unsteady separation. Steady RANS with a transition model can hold a laminar separation bubble that in reality flaps or bursts. If the bubble length changes with time step or with small changes in angle of attack, I treat the steady result as indicative only and run unsteady or LES.

Choosing between approaches

ApproachCostWhat it capturesWhen I use it
Fully turbulent SSTBaselineTurbulent drag and separation downstreamTransition forced early, or ranking designs where all transition at the same place
Gamma-Re_theta SSTAbout 20 to 40% more per iteration, two extra equationsFinite transition length, laminar drag saving, bubble effectsAirfoil or plate drag at Re_x 1e5 to 1e7 with smooth surfaces
e^N plus RANSExtra stability calculationOnset location from linear stabilitySetting Re_theta_t or checking onset, not a full flow solution
LES or DNS10 to 100 times RANS costNatural transition, bubble dynamicsLow Reynolds number airfoil, stall onset, or validation of the RANS model

For a design ranking I would keep the transition model fixed across candidates, compare Cf(x) and gamma(x) plots rather than drag alone, and flag any candidate where transition moves into a pressure gradient or separation zone. That movement, more than the absolute drag number, is usually what changes the ranking.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-74What does the large deformation option change in an FEA run compared with a linear run?

The 90-second answer

Large deformation changes where equilibrium is checked. A linear run checks equilibrium on the original, undeformed geometry and solves K u = F once with a constant stiffness matrix. A large deformation run checks equilibrium on the deformed geometry. At each Newton iteration it rebuilds the tangent stiffness from the current displaced shape, so stiffness can rise or fall as the part moves.

That is geometric nonlinearity. The material law can stay perfectly linear. The response becomes nonlinear because the geometry the load acts on keeps changing. A thin cantilever bending through a large angle is the standard example. Its tip moment arm changes as it deflects, so load and deflection no longer follow a straight line even though the stress stays below yield.

Linear runLarge deformation run
Geometry for equilibriumUndeformedDeformed, updated each iteration
StiffnessConstant KTangent stiffness rebuilt from current displacement and stress
StrainInfinitesimal strainFinite strain, such as Green-Lagrange strain
SolveOne linear solveNewton-Raphson iterations

Why the update matters

In the linear case the internal force is K u. In the large deformation case the solver works with the residual R(u) = F_int(u) - F_ext, where F_int is evaluated at the displaced positions. Newton-Raphson solves K_T delta_u = -R, updates u, and repeats until R is small. K_T includes a geometric term from the stress already present in the element. Tension stiffens a membrane. Compression softens a slender strut. A linear run omits that term entirely.

Finite strain is the matching strain measure. Under a rigid rotation the true strain is zero. Infinitesimal strain does not return zero once rotation is large, so it reports strain that is not physically there. Green-Lagrange strain, E = (F^T F - I)/2 where F is the deformation gradient, is unchanged by rigid rotation and does return zero. Python, checked against those definitions:

Python
import numpy as np

def green_lagrange(F):
    return 0.5 * (F.T @ F - np.eye(3))

def infinitesimal(F):
    grad_u = F - np.eye(3)
    return 0.5 * (grad_u + grad_u.T)

theta = np.deg2rad(30.0)  # rigid rotation about z
F = np.array([[np.cos(theta), -np.sin(theta), 0.0],
              [np.sin(theta),  np.cos(theta), 0.0],
              [0.0,             0.0,           1.0]])
print(np.linalg.norm(green_lagrange(F)))   # about 1e-16
print(np.linalg.norm(infinitesimal(F)))    # about 0.27, all spurious

When to switch it on

Use it when deflection is large relative to thickness, when rotations exceed roughly 5 to 10 degrees, or when the deformed shape changes the load path. A quick check is to run both settings on the same mesh. If peak displacement differs by more than a few percent, the linear result was based on the wrong geometry.

Large deformation alone does not add plasticity, contact, or a hyperelastic material law. Those are separate settings. It only updates the kinematics and the equilibrium check, which is why a rubber part can need both large deformation for its shape change and a hyperelastic law for its stress-strain behaviour.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-75How do you choose between Neo-Hookean, Mooney-Rivlin, Ogden and Yeoh for a rubber part that sees uniaxial, biaxial and shear strains, and calibrate it without extrapolating badly?

The 90-second answer

Start from the strain energy, not the stress strain curve. For an isotropic rubber the deformation is described by the principal stretches and the invariants I1 and I2 of the left Cauchy Green tensor. A hyperelastic model is a function W(I1, I2) whose derivatives give stress, and the choice of W decides how the material behaves in deformation modes you did not test. I would fit Neo-Hookean only for small to moderate strain and a first pass, Mooney-Rivlin when I have uniaxial plus planar or biaxial data and need a stable two parameter fit, Yeoh when I have mainly uniaxial data over a wide stretch range and need I1 softening and stiffening without I2 sensitivity, and Ogden when the response is strongly mode dependent or shows a sharp upturn and I can afford more parameters with strict stability constraints.

The practical decision is calibration range versus use range. If the part sees lambda = 2.5 in biaxial tension and I calibrated only to lambda = 1.8 in uniaxial tension, the model is extrapolating and the ranking of designs is not trustworthy, however good the fit looks inside the calibration box.

Worked check: incompressible uniaxial tension

For principal stretches lambda, lambda^-0.5, lambda^-0.5, I1 = lambda^2 + 2/lambda and I2 = 2 lambda + lambda^-2. Nominal stress P is dW/dlambda.

Neo-Hookean: W = C10 (I1 - 3), so P = 2 C10 (lambda - lambda^-2).

Mooney-Rivlin: W = C10 (I1 - 3) + C01 (I2 - 3), so P = 2 (lambda - lambda^-2) (C10 + C01/lambda).

Yeoh: W = sum Ci0 (I1 - 3)^i, so P = 2 (lambda - lambda^-2) sum i Ci0 (I1 - 3)^(i-1).

With C10 = 0.30 MPa and C01 = 0.05 MPa, hypothetical but typical for a filled elastomer at small strain:

lambdaNeo-Hookean P (MPa)Mooney-Rivlin P (MPa)
1.50.630.70
2.01.051.14
2.51.411.49

The two models agree closely in uniaxial tension. They diverge in biaxial tension and pure shear, which is why a uniaxial only fit cannot separate C10 from C01. In biaxial tension the I2 term contributes with the opposite sign pattern, so a fit that trades C10 against C01 to match uniaxial data can be badly wrong in biaxial loading.

Python
import numpy as np

def nominal_stress_uniaxial(lam, C10, C01=0.0):
    # Incompressible, Mooney-Rivlin reduces to Neo-Hookean when C01 = 0
    return 2.0 * (lam - lam**-2) * (C10 + C01 / lam)

for lam in [1.5, 2.0, 2.5]:
    print(lam, nominal_stress_uniaxial(lam, 0.30, 0.0),
          nominal_stress_uniaxial(lam, 0.30, 0.05))

Calibration and stability

Fit by least squares on nominal stress or Cauchy stress against stretch for at least two modes, for example uniaxial and planar, or uniaxial and equibiaxial. Hold out one mode as validation. If the held out mode is missed by more than the test scatter, the model form is wrong for the application, not the parameters.

Constrain the fit. For Mooney-Rivlin require C10 > 0, C01 > 0 and C10 + C01/lambda > 0 over the whole stretch range, which is the Drucker stability condition in this case. For Ogden, W = sum (mu_p/alpha_p)(lambda1^alpha_p + lambda2^alpha_p + lambda3^alpha_p - 3), require mu_p * alpha_p > 0 for each term. That condition is sufficient for Baker-Ericksen inequalities and prevents the solver from finding a non physical branch with negative stiffness in shear. Yeoh needs dW/dI1 > 0 over the range, so check the polynomial derivative at the maximum I1 in the part, not just at the calibration points.

Ogden with three terms has six parameters. It can fit uniaxial, biaxial and planar data at once, but it will also fit noise and produce wild extrapolation beyond the fitted stretches. I use it only when I have all three modes, I bound alpha_p, and I plot P versus lambda to lambda = 3 or 4 to confirm the upturn is monotone and not oscillatory.

What hyperelasticity does not capture

A hyperelastic model is path independent. It will not reproduce Mullins softening on unloading, hysteresis, creep or rate dependence, all common in filled rubber. If the test data show a large unload reload gap, adding Ogden terms will not fix it. That needs a Mullins damage variable or a viscoelastic Prony series on top of the hyperelastic base, calibrated from cyclic and relaxation tests.

Near incompressibility is a numerical issue as well as a physical one. Rubber has bulk modulus roughly 1000 times the shear modulus, Poisson ratio 0.49 to 0.499. Standard displacement elements lock in that regime. Use hybrid or mixed elements, or a compressible formulation with a measured bulk modulus, and check volumetric strain in the results. A model that predicts the right uniaxial stress but locks in a confined seal will underpredict deflection by a large factor.

In short: pick the simplest W that fits two deformation modes and validates on a third, enforce Drucker stability over the full strain range in the part, and treat any prediction outside the calibrated stretch and mode range as unvalidated.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-76A polymer mount creeps 0.8 mm in a week under constant load but its stress relaxes 30% in an hour at fixed displacement. How do you model both with a Prony series, and what test data do you need to fit it?

The 90-second answer

Use a generalized Maxwell model, also called a Prony series, with one equilibrium spring in parallel with several Maxwell branches. Each branch has a spring and a dashpot in series, with its own relaxation time tau_i = eta_i / E_i. Under a step strain the stress relaxes as a sum of exponentials. Under a step stress the same branches give bounded creep, but the creep compliance is not a sum of exponentials in the same tau_i. Its retardation times are different, and they come from the poles of the compliance in the Laplace domain. In practice I fit the Prony coefficients to a relaxation test, then check the prediction against an independent creep test, because a fit that only matches one loading history often fails on the other.

For a step strain epsilon_0 applied at t = 0:

sigma(t) = epsilon_0 * G(t), G(t) = E_inf + sum_i E_i * exp(-t / tau_i)

Here E_inf is the long term modulus, E_inf + sum_i E_i is the instantaneous modulus, and each tau_i is a relaxation time. For a step stress sigma_0, the strain is sigma_0 * J(t), where J(t) is the creep compliance. For the generalized Maxwell model J(0) = 1 / (E_inf + sum_i E_i) and J(infinity) = 1 / E_inf, and in between

J(t) = J_inf - sum_k A_k * exp(-t / tau_k^J)

The tau_k^J are retardation times, not the tau_i. They are obtained from the roots of the Laplace transform of the compliance. The relaxation modulus and creep compliance satisfy G*(s) * J*(s) = 1 / s^2 in the Laplace domain, equivalently s^2 * G*(s) * J*(s) = 1. That relation is why one set of Prony terms can describe both tests, and also why fitting both tests separately and getting inconsistent times is a warning sign. In a time stepping FEA code I do not evaluate J(t) from a closed form with the tau_i. I integrate the branch equations directly, which avoids the error of reusing relaxation times for creep.

Step strain or step stress Equilibrium spring E_inf Maxwell branch 1: E1, tau1 Maxwell branch 2: E2, tau2 Maxwell branch N: EN, tauN Total stress or strain

Worked example

Take a polymer mount with E_inf = 0.8 GPa, and three branches: E = [0.6, 0.4, 0.2] GPa with tau = [0.1, 10, 1000] s. Instantaneous modulus is 2.0 GPa. For a 1% step strain, sigma(0+) = 20 MPa and sigma(infinity) = 8 MPa.

Python
import numpy as np

E_inf = 0.8e9
E = np.array([0.6e9, 0.4e9, 0.2e9])
tau = np.array([0.1, 10.0, 1000.0])

def G(t):
    return E_inf + np.sum(E * np.exp(-t / tau))

for t in [0, 0.1, 1, 10, 100, 1000, 10000]:
    print(t, G(t) / 1e9, 0.01 * G(t) / 1e6)
t (s)G(t) (GPa)sigma at 1% strain (MPa)
02.0020.0
0.11.6216.2
11.3613.6
101.1511.5
1000.989.8
10000.878.7
100000.808.0

The fast branch explains the drop in the first second. The 1000 s branch is barely visible in a 10 s test, yet it controls the stress after a day. That is the main extrapolation risk. For creep at, say, 5 MPa, the same model gives an instantaneous strain of 5 MPa / 2.0 GPa = 0.25% and a long term strain of 5 MPa / 0.8 GPa = 0.625%. The path between those values follows the retardation times, which I get by integrating the branch ODEs or by inverting the Laplace relation numerically, not by inserting the tau_i into a Kelvin-Voigt form.

ModelStep strainStep stressUse it when
Single MaxwellStress decays to zeroUnbounded flow, strain grows as t / etaA melt or a fluid like polymer, rarely a solid mount
Kelvin-VoigtStress jumps, then relaxes in a delayed way with no instantaneous strain jump in the dual creep testNo instantaneous strain, strain approaches 1 / E with retardation time eta / ECreep with recovery and no instantaneous compliance, poor for relaxation
Generalized Maxwell (Prony)Sum of exponentials to E_infBounded creep to 1 / E_inf, with retardation times distinct from tau_iSolid polymer with both relaxation and creep
BurgersMaxwell plus Kelvin-Voigt in seriesCreep with a steady flow term after the delayed partCreep that never levels off in the test window

What data to collect

Run relaxation at fixed strain and creep at fixed stress, at the service temperature and at the service strain level. Cover at least three decades in time around the times that matter in service. If the mount must hold preload for a week, a 60 s relaxation test cannot identify a 1000 s branch. Fit log time data, not linear time, so the long tail is not ignored. Weight the fit by measurement uncertainty, and report tau values with the test window that supports them.

Temperature changes tau strongly in polymers. Above the glass transition, time-temperature superposition with a WLF shift can collapse curves at different temperatures onto one master curve. Below it, an Arrhenius shift is often used. I check whether shifted curves actually overlap before using a shift factor in FEA. A shift that works for relaxation may fail for creep if the mechanism changes.

FEA implementation and failure modes

In a commercial FEA code this enters as a viscoelastic material with a Prony series, or as a user material implementing the hereditary integral:

sigma(t) = integral_0^t G(t - s) * d epsilon / ds ds

The time step must resolve the shortest tau that carries significant modulus. With tau_min = 0.1 s, a 5 s step will miss the fast branch and overpredict stress early in the load. I set the step to tau_min / 5 or finer during the transient, then grow it once the fast branches have decayed.

Common failures I look for: fitting one tau to data that spans four decades, which gives a good fit in the test window and a wrong long term preload; assuming linear viscoelasticity at 5% strain when the test was at 0.5%, which hides strain dependent relaxation; and reusing relaxation times as retardation times in a hand coded creep formula, which can predict the wrong creep rate even when the relaxation fit looks good. A Burgers term, or a creep test that keeps rising linearly in log time, tells me the equilibrium spring is missing.

Validation is a blind prediction: fit on relaxation, predict creep at a stress not used in fitting, and compare the strain at the service time, not just the shape. If the prediction misses by more than the test scatter, the Prony series needs more branches or the material is nonlinear, and I would move to a nonlinear viscoelastic model such as a Schapery or Bergstrom-Boyce form rather than adding more linear terms.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-77A crack in a panel is expected to kink toward a bolt hole as it grows. How do cohesive-zone and XFEM models each represent that crack, and which would you choose for predicting its path and growth rate?

The 90-second answer

I would pick XFEM for this case, because the path is the unknown. A cohesive zone model needs the crack path decided before the run. You insert cohesive elements along a line, usually element faces, and the crack can only open where those elements exist. If the real crack kinks 20 degrees toward the bolt hole and your cohesive line goes straight, the model will either follow the wrong line or refuse to kink. XFEM enriches nodes inside elements crossed by the crack, so the discontinuity can cut through elements at an angle that is not aligned with the mesh. The path is carried by a level set field that is updated as the crack grows.

That choice trades a calibrated local law for path freedom. Cohesive zone gives me a direct traction separation law I can fit to a test. XFEM gives me a path I do not have to guess, at the cost of extra degrees of freedom, worse conditioning and a level set update I have to validate.

How each model represents the crack

In a cohesive zone model the material ahead of the tip is replaced by a surface that transmits traction until a separation is reached. A common bilinear law is:

Python
def cohesive_traction(delta, delta0, deltaf, sigma_max):
    # delta: current opening, delta0: opening at peak traction
    # deltaf: opening at complete separation, sigma_max: peak traction
    if delta <= delta0:
        return sigma_max * delta / delta0
    if delta < deltaf:
        return sigma_max * (deltaf - delta) / (deltaf - delta0)
    return 0.0

The area under that curve is the fracture energy Gc. I set sigma_max near the yield strength, about 275 MPa for 6061-T6 in a labelled hypothetical example, and choose deltaf so that Gc matches KIC squared divided by E prime. The mesh inside the cohesive band needs 5 to 10 elements across the zone length, otherwise the predicted peak load rises artificially with refinement.

XFEM does not insert a surface. Standard shape functions are supplemented, for nodes of crossed elements, with a ridge enrichment that allows a displacement jump inside the element. The crack geometry is stored as a signed distance level set, phi = 0 on the crack. At each growth step I advance phi at the tip by a length computed from a growth criterion, often Paris law da/dN = C (Delta K)^m evaluated from the J integral, then reinitialise phi. The crack can therefore turn toward the bolt hole because the stress field there raises K on the kinked plane.

AspectCohesive zoneXFEM
Crack pathPrescribed along cohesive elementsFree, crosses elements, updated by level set
Mesh requirementVery fine along the band, aligned with pathCan be coarser, but enrichment zone needs care
CalibrationTraction law and Gc from testsK or J extraction plus Paris constants
Main riskWrong path, mesh dependent peak load if zone under resolvedIll conditioning from small cut elements, blending errors at enrichment boundary
Growth rate outputEnergy dissipation and load dropK at tip each step, then Paris integration

Worked check for the kink

Suppose the straight crack has Delta K = 12 MPa sqrt(m) and the kinked direction toward the hole raises the local K by 15 percent because the hole amplifies stress as the tip approaches it. With m = 3.2, the growth rate ratio is 1.15 to the power 3.2, about 1.56. The crack therefore accelerates by more than half once it turns, even though the remote load is unchanged. A cohesive model fixed on the straight line would miss that acceleration entirely and overpredict life. An XFEM run should show the level set bending in the last few steps and K climbing faster than sqrt(a) alone would predict. I would check that by plotting tip angle against a. If the angle stays at zero while the hole is within one plastic zone size of the tip, the enrichment or the growth criterion is not responding to the hole field.

When I would switch back

If the path were known, for example a crack forced to run along a bonded interface, I would use cohesive zone. It is cheaper, the energy balance is transparent, and I can validate the traction law against a double cantilever test. I would also use it if large scale yielding made K meaningless, because the traction law still describes ductile tearing. For a free crack that may kink, branch or curve toward a stress raiser, the path freedom of XFEM is worth the conditioning cost. I would confirm the XFEM result with a mesh refinement study on K at fixed a, and reject the run if K moves by more than about 5 percent when element size is halved, since that usually means cut elements are too small or the J integral contour is crossing the enrichment boundary.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-78A steel bar is fully constrained at both ends and heated by 50 degrees C. What thermal stress develops, and how do you calculate it?

The 90-second answer

For a bar that cannot expand, thermal stress is sigma = -E * alpha * deltaT. The minus sign means compression on heating. With steel at E = 200 GPa and alpha = 12e-6 /K, a 50 K rise gives -200e9 * 12e-6 * 50 = -120 MPa.

The reasoning is one line of strain decomposition. Total strain is mechanical strain plus thermal strain:

epsilon_total = sigma / E + alpha * deltaT

Full constraint means the ends do not move, so epsilon_total = 0. Rearranging gives sigma = -E * alpha * deltaT. If the bar were free, the same heating would produce no stress at all, only elongation deltaL = alpha * L * deltaT. Constraint is what converts expansion into stress.

Worked numbers

deltaT (K)Thermal strain alpha*deltaTStress for steel (MPa)
10120 microstrain-24
50600 microstrain-120
1001200 microstrain-240

That last row matters. A typical structural steel yields around 250 to 350 MPa, so a fully constrained 100 K rise is already close to yielding before any external load is applied. In a simulation you check that number first. If the elastic prediction exceeds yield, the linear result is not the final stress. The material will yield locally, relax part of the thermal load, and leave residual stress on cooling.

Python
# Checked against E = 200 GPa, alpha = 12e-6 /K for steel
E = 200e9
alpha = 12e-6
for dT in (10, 50, 100):
    sigma_MPa = -E * alpha * dT / 1e6
    print(dT, round(sigma_MPa, 1))
# 10 -24.0
# 50 -120.0
# 100 -240.0

Thermal stress versus residual stress

Thermal stressResidual stress
CauseTemperature change under constraintPrior plastic deformation, welding, quenching or forming
Present whileThe temperature difference or constraint persistsAfter the cause is removed and the part is at uniform temperature
EquilibriumBalanced by the constraint reactionsSelf-equilibrating inside the part, with no external reaction

Residual stress is the stress that remains when the bar is unloaded and back at reference temperature. A welded joint is the classic case. The weld zone heats, expands against cooler surrounding metal, yields in compression, then contracts on cooling and ends up in tension while the surrounding metal carries balancing compression. You cannot get that from a purely elastic thermal step. You need a load history with plasticity, or an inherent strain input calibrated from measurement.

Where the simple formula breaks

Partial constraint gives a lower stress. A bar attached to a flexible frame sits between the free case (zero stress) and the fully constrained case above, so in FEA the stiffness of the surrounding structure decides the answer. Temperature dependent E and alpha also change the product, which is why a solver interpolates properties at the local temperature instead of using room temperature values throughout.

Two failure modes to watch in results. First, a slender constrained member can buckle under the compressive thermal stress even when the stress is below yield, so a stress check alone misses it. Second, at sustained high temperature creep relaxes thermal stress over time, so a short elastic run overpredicts the long term stress. If either applies, the next step is a plasticity or buckling analysis, not a finer mesh on the linear run.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-79Walk me through how you would couple an eddy-current electromagnetic solve to thermal and structural solvers for an induction-heated brake disc, and decide where one-way coupling is enough and where you need two-way iteration?

The 90-second answer

For an induction-heated brake disc I would not start with a monolithic solve. I would run a partitioned, sequential coupling: solve the quasi-static eddy-current problem for the coil current, extract the volumetric Joule source, solve transient heat conduction with that source, then feed the temperature field back to update electrical conductivity and permeability and repeat until the absorbed power stops moving. Structural deformation only enters the loop if the disc bows enough to change the coil-to-disc gap, or if thermal stress is itself the quantity of interest. That ordering matches the physics. The electromagnetic field settles in microseconds, the temperature field moves over seconds, and the structure follows the temperature. Solving all three at one time step wastes effort and makes the nonlinear iteration harder to debug.

The electromagnetic part, at frequencies where displacement current is negligible, is usually written for the magnetic vector potential A. In the time domain the governing equation is:

$$\nabla \times (\mu^{-1} \nabla \times \mathbf{A}) + \sigma \frac{\partial \mathbf{A}}{\partial t} = \mathbf{J}_s$$

with $\mathbf{J} = -\sigma \partial \mathbf{A}/\partial t$ in the conductor. For a sinusoidal supply at angular frequency $\omega$ I would use the phasor form, which replaces the time derivative with $j\omega$:

$$\nabla \times (\mu^{-1} \nabla \times \mathbf{A}) + j\omega\sigma \mathbf{A} = \mathbf{J}_s$$

The coupling term passed to the thermal solver is $q''' = \mathbf{J} \cdot \mathbf{E} = \sigma |\mathbf{E}|^2$, integrated over the disc volume to give total absorbed power $P$. That power, not the coil current, is the quantity I would monitor for coupling convergence.

Skin depth decides the mesh before anything else. $\delta = \sqrt{2/(\mu \sigma \omega)}$. For a steel disc with $\sigma = 5 \times 10^6$ S/m, $\mu_r = 100$ below the Curie point, and a 10 kHz supply, $\delta \approx 0.22$ mm. A mesh with 2 mm elements through the disc thickness cannot represent the current layer at all. I would use at least three to five elements per skin depth in the heated face, or a surface impedance boundary condition if the disc is electrically thick compared with $\delta$. Getting this wrong does not just blur the answer. It moves the heat source deeper into the part, underpredicts surface temperature, and overpredicts the time for the surface to reach a target temperature.

Python
import math

def skin_depth(sigma, mu_r, freq_hz):
    mu0 = 4 * math.pi * 1e-7
    omega = 2 * math.pi * freq_hz
    return math.sqrt(2.0 / (mu0 * mu_r * sigma * omega))

# Steel disc, 10 kHz, below Curie point
d = skin_depth(5e6, 100, 10e3)
print(f"delta = {d*1e3:.2f} mm, element size <= {d/4*1e3:.3f} mm")
# delta = 0.22 mm, element size <= 0.056 mm

Temperature feedback is the reason one-way coupling often fails here. Copper coil conductivity falls about 0.39% per kelvin, and steel conductivity and permeability both move with temperature. Permeability collapses near the Curie point, around 770 °C for iron, so $\delta$ grows sharply and the heating pattern spreads. If the disc rises 300 K during a braking event, a one-way solve that holds properties at 20 °C can misstate absorbed power by tens of percent. My rule is to iterate the electromagnetic and thermal solves together whenever the predicted temperature rise changes $\sigma$ or $\mu$ by more than about 5%, or whenever $P$ changes by more than 1 to 2% between successive passes. I would stop the outer loop when the change in $P$ and in peak surface temperature both fall below a stated tolerance, for example 0.5% and 2 K, and I would check that the integrated Joule heat matches the enthalpy rise in the thermal solve within a few percent.

Coupling choiceWhen it is defensibleWhat it misses
One-way EM to thermalSmall temperature rise, properties near constant, deformation does not affect the gapProperty drift, Curie transition, power drift during the event
Sequential two-way EM and thermalTemperature-dependent properties, heating pattern moves with $\delta$Gap change from bowing, stress-dependent properties
Two-way including structuralBowing changes coil gap or contact, thermal stress is the outputCost, and a harder nonlinear convergence problem
MonolithicStrong coupling on a single time scale, small systemSolver complexity, poor scaling, difficult restart and debugging
Yes No Coil current and geometry Eddy-current solve Joule source q''' Transient thermal solve Update sigma T and mu T Thermal strain and stress Gap change significant? Report power temperature stress

Structural coupling needs a separate check rather than an assumption. A 0.15 mm bow in a disc with a 3 mm coil gap changes the local inductance by roughly the gap ratio, a few percent, which can matter for power. If the bow is 0.02 mm, I would keep the structure one-way, driven by the temperature field, and report stress without feeding deformation back. If the bow approaches a few percent of the gap, I would update the electromagnetic geometry each outer iteration.

Three failure modes come up repeatedly. First, using a DC or low-frequency conductivity table at 10 kHz without checking skin depth and proximity effect in the coil. Second, holding $\mu_r$ constant through the Curie point, which keeps the heat source pinned at the surface long after the real source has spread inward. Third, passing a nodal temperature field to the electromagnetic solver without smoothing or without matching the meshes, which creates checkerboard conductivity and a noisy power history. I would detect the first two by plotting $P$ against surface temperature and looking for a kink near the Curie point, and the third by comparing $P$ on the coupled mesh against a refined electromagnetic mesh at fixed temperature. If those disagree by more than a few percent, the coupling is not converged, whatever the solver residuals say.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-80For a 500 Hz tone in a 2 m cabin, how do you use the wavelength to set the mesh size and the CFL condition to set the time step in a wave-equation simulation?

The 90-second answer

I would solve the linear wave equation for pressure p in the cabin air volume: ∇²p − (1/c²) ∂²p/∂t² = 0, with c ≈ 343 m/s for air at 20 °C. A speaker is a volume velocity source and the walls are mostly reflecting boundaries. That model captures standing waves and interference at the driver's ear, which determine SPL at a steady tone. It does not capture airflow or heating, so I would not use it if those matter for the test.

Mesh size comes from the wavelength, not from the cabin size. At 500 Hz, λ = c/f = 343/500 = 0.686 m. A second order explicit scheme needs about 8 to 10 points per wavelength to keep phase error acceptable, so h ≈ λ/8 = 0.086 m, or 0.07 m with margin. Coarser than that and the wave travels at the wrong speed in the model, so a resonance lands at the wrong frequency.

Time step comes from stability. For an explicit 3D update the CFL limit is dt ≤ h/(c√3). With h = 0.07 m, dt ≤ 0.07/(343 × 1.732) ≈ 118 µs. A 0.1 s run therefore needs about 850 steps. If I halved h for accuracy, dt would halve too, so the step count doubles while the cell count grows eightfold in 3D.

Python
import numpy as np

c = 343.0  # m/s, air at 20 C
f = 500.0  # Hz
lam = c / f
h = lam / 10.0  # 10 points per wavelength
dt = h / (c * np.sqrt(3.0))
print(f"lambda = {lam:.3f} m")
print(f"h = {h:.3f} m, dt_max = {dt * 1e6:.0f} us")
print(f"steps in 0.1 s = {int(np.ceil(0.1 / dt))}")

What changes with frequency

The same formulas show why high frequency acoustics get expensive fast. The table uses 10 points per wavelength and the 3D CFL limit above.

f (Hz)λ (m)h (m)dt_max (µs)Steps in 0.1 s
2501.3720.137231433
5000.6860.069115866
10000.3430.034581,732
40000.0860.009146,928

At 4 kHz the cabin grid is roughly 230 × 170 × 115 cells, about 4.5 million cells, and each step is cheap but there are thousands of them. That is the point where I would switch to a frequency domain Helmholtz solve, ∇²p + k²p = source, which solves one complex system per frequency with no CFL limit. For a single steady tone that is usually cheaper. I would stay in the time domain if I needed the transient build up, a door slam, or a swept source in one run.

Boundaries and a quick check

Rigid walls use ∂p/∂n = 0 and reflect fully. Seats and trim absorb, so I would give those patches an impedance or absorption coefficient rather than treating the whole cabin as rigid. Treating absorptive trim as rigid overpredicts peaks at resonances.

A cheap sanity check is the first axial mode of the empty rectangular cabin. For 2.0 × 1.5 × 1.0 m, f = (c/2)√((nx/Lx)² + (ny/Ly)² + (nz/Lz)²) gives 86, 114 and 172 Hz for the first mode along each axis. If the simulated first peak is well away from 86 Hz, the mesh is too coarse or a boundary condition is wrong. Refining h by half should move the peak toward the analytic value and change ear SPL by less than about 1 dB before I trust the result.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-81How does the Pacejka magic formula turn longitudinal and lateral slip into tire forces in a vehicle dynamics simulation, and what do its B, C, D and E parameters control?

The 90-second answer

The Pacejka magic formula is a fitted curve from slip to force, not a physics derivation. For lateral slip the input is slip angle alpha, for longitudinal slip it is slip ratio kappa, and the output is force normalized by vertical load Fz. In steady state on a flat surface the same shape is reused for both directions with different coefficients:

Fy = D * sin(C * atan(Bx - E(Bx - atan(Bx))))

where x = tan(alpha) for lateral slip and x = kappa for longitudinal slip. B sets the slope at the origin, so cornering stiffness is BCD per radian. C sets the shape and the value at large slip. D is the peak force, usually close to mu*Fz. E controls how sharply the curve falls after the peak. That fall matters. A tire that peaks at 5 degrees and then loses force will understeer differently from one that plateaus, and E is what lets a fit capture that without a lookup table.

Worked trace

Take a passenger tire at Fz = 4000 N with B = 10, C = 1.9, D = 4000 N, E = 0.97. Slip angle in radians, x = tan(alpha):

alphaxB*xFy (N)Fy/Fz
1 deg0.01750.17512770.32
3 deg0.05240.52430160.75
5 deg0.08750.87537040.93
10 deg0.17631.76340001.00

The force rises almost linearly to about 3 degrees, peaks near 10 degrees, then the E term pulls it down at larger slip. In a bicycle model that peak sets the maximum lateral acceleration before the rear axle saturates and the car yaws. If you fit D from a skid pad test at one load and reuse it at another load, you will be wrong, because D grows with Fz but with diminishing return. A common fit is D = a1Fz + a2Fz^2, with a2 negative, which captures load sensitivity.

Python
import math

def pacejka(x, B, C, D, E):
    bx = B * x
    return D * math.sin(C * math.atan(bx - E * (bx - math.atan(bx))))

# lateral force, alpha = 5 degrees
fy = pacejka(math.tan(math.radians(5)), 10.0, 1.9, 4000.0, 0.97)
print(round(fy))  # 3704

Combined slip and transients

Real driving rarely gives pure lateral or pure longitudinal slip. Braking while cornering is the case that breaks a naive model. The standard fix is a friction ellipse or circle: scale the pure slip forces so that sqrt((Fx/mu_xFz)^2 + (Fy/mu_yFz)^2) does not exceed 1. Pacejka implementations do this by weighting the slip inputs, for example using a combined slip variable, rather than adding Fx and Fy independently. Adding them independently can predict 1.4muFz of total force, which no tire can deliver, and the simulated car will brake and turn at once in a way the real car cannot.

Steady state is also not the whole story. Tire force does not appear instantly when steering changes. The contact patch needs to roll roughly one relaxation length, typically 0.3 to 0.6 m for a passenger tire, before force builds up. Many vehicle models add a first order lag on slip, d(alpha_eff)/dt = (alpha - alpha_eff) * Vx / sigma, where sigma is that relaxation length. At 30 m/s the time constant is about 10 to 20 ms. Skip it and a step steer in simulation produces yaw response that is too fast and too large, which then corrupts controller tuning.

ModelWhen it is enoughWhat it misses
Linear bicycle, Fy = -C_alpha * alphaSmall slip angles, stability analysis, control designSaturation, peak grip, combined slip
Pacejka steady stateFull vehicle handling, ABS and ESC tuning, tire fittingTransient build up, temperature and wear unless added
Pacejka plus relaxation and load sensitivityTransient maneuvers, load transfer, limit handlingNeeds measured coefficients per tire, pressure and temperature
LuGre or other bristle modelsStick slip, low speed judder, parkingMore states, harder to fit, rarely needed for handling

Failure modes to check

Extrapolation is the main one. The formula is only trustworthy inside the slip, load, pressure, camber and speed range of the test data. Outside that range the atan and sin keep the output bounded, which looks safe but can hide a badly wrong peak. Check the fit against measured Fy versus alpha at the loads you will actually simulate, including the unloaded inside tire during roll. Check combined slip against a braking in a turn test, not just separate tests. Check low mu surfaces separately, because D scales with mu and a dry road fit will overpredict wet grip by a factor of two or more. If the simulation is used for controller validation, validate yaw rate and lateral acceleration in a sine with dwell or a double lane change against track data, and report the slip angle range covered. A model that matches peak lateral acceleration but misses the post peak fall will still fail the dwell test.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-82How are lift and drag written in terms of aerodynamic coefficients, and what do CL and CD tell you about a wing at a given angle of attack?

The 90-second answer

Lift and drag are written by scaling a dynamic pressure with a dimensionless coefficient. For a wing of planform area S in a flow of density rho and speed V:

q = 0.5 * rho * V^2          dynamic pressure
L = q * S * CL               lift, perpendicular to the freestream
D = q * S * CD               drag, parallel to the freestream

CL and CD carry no units. They absorb geometry, angle of attack, Reynolds number and Mach number, so two wings of different size or speed can be compared at the same condition. The ratio L/D = CL/CD cancels q and S, which is why it is quoted as aerodynamic efficiency.

What the coefficients do at a given angle of attack

At a fixed alpha, Re and Mach, CL and CD are (to first order) constants for that configuration. Raise alpha in the linear range and CL rises roughly linearly, about 0.11 per degree for a typical thin airfoil in incompressible flow, while CD rises slowly at first and then faster. That shape is the drag polar, often fitted as CD = CD0 + k * CL^2, where CD0 is profile drag at zero lift and the quadratic term is induced drag for a finite wing.

alpha (deg)CLCDL/D = CL/CD
00.000.0100
40.440.01529
80.880.03029
121.320.06022

Values are illustrative for a symmetric section below stall. Past stall CL falls while CD climbs, so L/D collapses. A coefficient taken past stall, or at a different Re or Mach, does not transfer to another condition.

Worked numbers

Take rho = 1.225 kg/m3, V = 50 m/s, S = 10 m2, CL = 0.80 and CD = 0.050.

Python
rho, V, S = 1.225, 50.0, 10.0
q = 0.5 * rho * V**2   # 1531 Pa
CL, CD = 0.80, 0.050
L = q * S * CL         # 12250 N
D = q * S * CD         # 766 N
print(f"q={q:.0f} Pa  L={L:.0f} N  D={D:.0f} N  L/D={L/D:.1f}")

Doubling speed quadruples q and therefore both forces, while CL, CD and L/D stay unchanged if Re and Mach effects are ignored. That scaling is the practical point of the coefficients in a simulation: the solver or wind tunnel supplies CL(alpha, Re, Mach) and CD(alpha, Re, Mach), and the flight model multiplies by qS at run time.

Limits to state in an interview

CL and CD are not material constants. They change with alpha, surface roughness, flap deflection, ground effect and, at transonic speed, with shock position. Compressibility also breaks the simple q scaling when Mach approaches 1, because density varies through the flow. For a simulation engineer the check is dimensional: if a predicted CL jumps between runs at the same alpha, Re and Mach, look for a mesh, transition or convergence change before trusting the force.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-83Walk me through the recursive Newton-Euler algorithm for a 6-DOF arm, including the forward and backward recursions, and where it breaks with closed loops or flexible joints?

The 90-second answer

For a serial tree, the recursive Newton-Euler algorithm (RNEA) computes inverse dynamics, tau = M(q) a + C(q, qdot) qdot + g(q), in O(n) time for n joints instead of forming and inverting the n by n mass matrix. You run one outward pass that propagates joint velocities and accelerations from base to tip, then one inward pass that propagates link forces and joint torques from tip to base. Gravity is handled by setting the base acceleration a0 = -g, so the same recursion produces the gravity term without a separate calculation.

That tree assumption is the whole contract. A closed loop has no unique parent for some links, so the inward pass has no well defined order. Flexible joints break a different assumption, that joint torque acts directly on the link, because motor inertia and gear elasticity sit between actuator and link.

Forward recursion

Work in spatial vector notation (Featherstone) or in 3 by 3 rotation plus 3 vector form. For link i with parent p, joint axis and transform X_i from parent frame to link frame:

Python
# Python-style pseudocode, spatial vectors, checked against Featherstone (2008)
# v, a: spatial velocity/acceleration; f: spatial force; I: spatial inertia
v[0] = 0
 a[0] = -g  # base acceleration, g is gravity vector in base frame
for i in links_base_to_tip:
    X = joint_transform(i, q[i])
    v[i] = X @ v[parent[i]] + S[i] * qdot[i]          # S: joint subspace
    a[i] = X @ a[parent[i]] + S[i] * qddot[i] + v[i] x (S[i] * qdot[i])

The cross term v cross (S qdot) is the Coriolis and centrifugal contribution. Drop it and high speed runs will be wrong even if static torques match. At the tip, a[n] is known from the desired end effector acceleration, or zero for a free tip.

Backward recursion

Python
for i in links_tip_to_base:
    f[i] = I[i] @ a[i] + v[i] x (I[i] @ v[i])
    for child in children[i]:
        f[i] += X_child.T @ f[child]
    tau[i] = S[i].T @ f[i]   # joint torque, plus friction if modelled

I[i] @ a[i] is the inertial force, v cross (I v) is the gyroscopic term. Summing child forces into the parent is what makes the algorithm recursive rather than a full matrix product.

MethodCost for n jointsWhat it returnsMain risk
Lagrangian, explicit M(q)O(n^3) to form and factor, O(n^2) storageM, C, g separatelyCode bloat, wrong Christoffel symbols
RNEAO(n), O(n) storagetau for given a, qdot, qddotTree only, silent error if frames inconsistent
Articulated body (ABA)O(n)Forward dynamics, qddot for given tauMore complex, needs joint space inertia handling

For n = 6 the difference is small in wall time. For n = 100, a humanoid or a multi body vehicle model, explicit M(q) needs roughly 10,000 entries and O(10^6) operations per evaluation, while RNEA needs a few hundred spatial operations. That is why production simulators (Pinocchio, RBDL, Featherstone's code) use RNEA for inverse dynamics and ABA or a sparse solver for forward dynamics.

Worked check, 2 link planar arm

Take m1 = m2 = 1 kg as point masses at the link ends, l1 = l2 = 0.5 m, motion in a horizontal plane so gravity does no work and g = 0 in the plane, q = [0, 0] straight, qdot = [0, 0], qddot = [1, 0] rad/s^2. Joint 2 acceleration is relative, so the absolute angular acceleration of link 2 is also 1 rad/s^2.

MassDistance from jointTangential accelerationForceTorque contribution
m2 about joint 20.5 m0.5 * 1 = 0.5 m/s^20.5 N0.5 * 0.5 = 0.25 N m at joint 2
m1 about joint 10.5 m0.5 m/s^20.5 N0.25 N m at joint 1
m2 about joint 11.0 m1.0 * 1 = 1.0 m/s^21.0 N1.0 * 1.0 = 1.0 N m at joint 1

So tau2 = 0.25 N m and tau1 = 0.25 + 1.0 = 1.25 N m. If your code returns tau1 = 0.5 N m here, you have applied the child force at the wrong lever arm or dropped m2 from the joint 1 balance. If it returns tau2 = 0.5 N m, you have used the 1.0 m distance from joint 1 for a torque that should use 0.5 m from joint 2.

Where it breaks

Closed loops: a four bar linkage or a robot with a parallel wrist has a link with two parents. RNEA will either ignore one constraint or double count a force. Fix options are to cut the loop, add Lagrange multipliers for the closure constraint, or use a general multibody solver that handles constraints (for example a DAE formulation). Detection: compare RNEA tau against a Lagrangian model built independently for a test pose, and check that loop closure error stays at machine precision when you run forward kinematics around the loop.

Flexible joints: with harmonic drives or series elastic actuators, the Spong model adds motor angle theta, motor inertia Jm, and stiffness K, giving tau_motor = K (theta - q) + D (thetadot - qdot). Link torque is no longer the motor torque. Plain RNEA underpredicts oscillation and misses the extra resonance, often near 10 to 30 Hz for small harmonic drives. You need the flexible joint extension, which adds motor states to the recursion, or a full state space model. Detection: a step torque in simulation settles without the ringing you see on the bench, or measured torque lags commanded torque by more than one sample at 1 kHz.

Other failure modes worth naming in an interview: wrong base acceleration sign flips gravity, inconsistent DH or URDF frame conventions produce torques that look plausible but fail the 2 link check above, and unmodelled joint friction and backlash make inverse dynamics match simulation but not hardware. Validate by finite differencing M(q) from RNEA calls (perturb qddot per joint) and confirming symmetry and positive definiteness, and by energy balance over a periodic motion.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-84How would you plan a trajectory for a simulated car-like robot that must travel 8 m in 6 s without exceeding 2 m/s, 1.5 m/s^2, or a 3 m minimum turning radius, and how would you check feasibility before running the dynamics simulation?

The 90-second answer

I would separate the geometric path from its timing. Fix a path $p(s)$ parameterised by arc length $s$, then choose a timing law $s(t)$ that respects speed, acceleration and curvature limits along that path. Check feasibility on the sampled path and timing law before running the dynamics model. If the plan already breaks a limit, the simulated actuator will saturate and the test will measure saturation, not controller or plant behaviour.

For a car-like robot the kinematic limits are speed $v$, longitudinal acceleration $a$, and curvature $\kappa$. Steering geometry gives $\kappa_{max}=1/R_{min}$, and lateral acceleration is $a_{lat}=v^2\kappa$. Here $\kappa_{max}=1/3=0.333\ \text{m}^{-1}$. At $v=2\ \text{m/s}$, $a_{lat}=1.33\ \text{m/s}^2$, below the $1.5\ \text{m/s}^2$ limit, so a path whose curvature never exceeds $0.333\ \text{m}^{-1}$ is not ruled out by lateral acceleration at full speed. Combined acceleration on a bend while accelerating is $\sqrt{a^2+a_{lat}^2}$, so I check that too, not each component in isolation.

A quintic timing law is the wrong tool for judging this case. For rest-to-rest motion over distance $D$ in time $T$, a quintic has $v_{peak}=1.875D/T$. With $D=8\ \text{m}$ and $T=6\ \text{s}$ that is $2.50\ \text{m/s}$, which fails. That proves the quintic shape is infeasible, not that the task is. A trapezoidal velocity profile has a lower peak speed for the same distance and time.

With $v_{max}=2\ \text{m/s}$ and $a_{max}=1.5\ \text{m/s}^2$, accelerating to $v_{max}$ takes $1.33\ \text{s}$ and $1.33\ \text{m}$. Accelerating and braking cover $2.67\ \text{m}$, leaving $5.33\ \text{m}$ to cruise at $2\ \text{m/s}$, for a minimum time of $5.33\ \text{s}$. The 6 s requirement is therefore feasible with margin. Stretching it to exactly 6 s by lowering cruise speed to $v_c$ gives $T=D/v_c+v_c/a_{max}$, so $8/v_c+v_c/1.5=6$, giving $v_c=1.63\ \text{m/s}$. Acceleration time is $1.09\ \text{s}$, acceleration distance $0.88\ \text{m}$ at each end, and cruise lasts $3.83\ \text{s}$.

PhaseTime (s)Distance (m)Speed (m/s)Acceleration (m/s$^2$)
accelerate0 to 1.090 to 0.880 to 1.63+1.5
cruise1.09 to 4.910.88 to 7.121.630
brake4.91 to 6.007.12 to 8.001.63 to 0-1.5

Curvature is checked on the path geometry, independent of timing, then combined with speed. For samples $(x(s),y(s))$:

$$\kappa(s)=\frac{|x'y''-y'x''|}{(x'^2+y'^2)^{3/2}}$$

If $\kappa(s)>0.333\ \text{m}^{-1}$ anywhere, no timing law repairs it. The path must be replanned with a larger bend radius, such as an arc or clothoid blend at a sharp corner. If curvature passes but $v(s)^2\kappa(s)$ is too high on a bend, the profile must slow before that bend, which a single trapezoid over the whole path cannot do. That is where I move to a path-parameterised speed limit $v_{lim}(s)=\min(v_{max},\sqrt{a_{max}/\kappa(s)})$ and integrate a forward-backward pass.

Python
import numpy as np

def check_trajectory(x, y, s, t, vmax=2.0, amax=1.5, kappa_max=1 / 3.0):
    v = np.gradient(s, t)
    a = np.gradient(v, t)
    dx, dy = np.gradient(x), np.gradient(y)
    ddx, ddy = np.gradient(dx), np.gradient(dy)
    kappa = np.abs(dx * ddy - dy * ddx) / (dx**2 + dy**2) ** 1.5
    kappa_t = np.interp(s, s, kappa)
    a_lat = v**2 * kappa_t
    a_total = np.sqrt(a**2 + a_lat**2)
    return {
        "v_peak": v.max(),
        "a_long_peak": np.abs(a).max(),
        "kappa_peak": kappa.max(),
        "a_lat_peak": a_lat.max(),
        "a_total_peak": a_total.max(),
        "feasible": bool(
            v.max() <= vmax
            and np.abs(a).max() <= amax
            and kappa.max() <= kappa_max
            and a_total.max() <= amax
        ),
    }

I would log those values for every planned trajectory and fail the case if any limit is exceeded. The trapezoid has step changes in acceleration, so for a real actuator or hardware-in-the-loop run I would replace it with a 7-segment S-curve that also bounds jerk, keeping the same $v_c$ and distance. The S-curve needs slightly more distance to reach the same cruise speed, so I would recheck the 6 s total after adding jerk limits rather than assuming the trapezoid timing still holds.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-85Your fusion filter drifts badly during a 20 s GPS outage in a tunnel. How would you simulate IMU bias drift and GPS error so that outage behaviour is realistic, and what would you check first?

The 90-second answer

I would check the IMU bias model first. A filter that drifts in a 20 s outage is usually being tested against an IMU whose bias is constant, so the filter learns it in the first minute and never has to propagate uncertainty. I would replace that with a random walk bias, keep GPS error correlated rather than white, and then score position error only inside the outage. That split shows whether the drift comes from the sensor model or from the filter tuning.

IMU model

Ground truth comes from the simulated trajectory at 200 Hz: orientation as a quaternion, angular velocity, and specific force in the body frame. Each IMU sample is the true value plus bias plus noise. Bias changes slowly, so I update it as a random walk:

Python
import numpy as np

def step_imu(f_true, w_true, dt, rng, bias_a, bias_g, rw_a, rw_g, nd_a, nd_g):
    bias_a = bias_a + rng.normal(0.0, rw_a * np.sqrt(dt), size=3)
    bias_g = bias_g + rng.normal(0.0, rw_g * np.sqrt(dt), size=3)
    accel = f_true + bias_a + rng.normal(0.0, nd_a / np.sqrt(dt), size=3)
    gyro = w_true + bias_g + rng.normal(0.0, nd_g / np.sqrt(dt), size=3)
    return accel, gyro, bias_a, bias_g

Here nd_a and nd_g are noise densities from the datasheet. Dividing by sqrt(dt) converts them to per-sample standard deviation at the simulation rate. The random walk terms rw_a and rw_g control how fast bias wanders during the outage. With a constant bias model, rw_a and rw_g are zero and the outage test becomes misleading.

The arithmetic explains the symptom. An accel bias of 0.01 m/s squared, uncorrected, gives position drift of 0.5 * b * t^2. At t = 20 s that is 2.0 m. A gyro bias of 0.02 deg/s gives 0.4 deg of heading drift in the same interval, which then leaks gravity into the horizontal accel channels. Those two numbers are the scale of error the filter must bound with its covariance during the tunnel segment.

GPS model

GPS error at 5 Hz should be a first-order Gauss-Markov process per axis, e[k+1] = alpha * e[k] + w[k], with alpha = exp(-dt / tau). A correlation time tau of 30 s and steady-state sigma of 1.5 m horizontal is a reasonable starting point for open sky. White noise with the same sigma would let the filter average the error down quickly, which real GPS does not allow. During the tunnel I emit no GPS samples at all for 20 s. I also add the lever arm, antenna position equals vehicle position plus R * lever_arm_body, because a 1 m offset at a 20 deg/s turn rate creates a real velocity difference between IMU and antenna.

Model choiceWhat the filter seesEffect on outage test
Constant IMU biasOne fixed offset to learnUnderstates drift, outage looks easy
Random walk IMU biasBias keeps moving while GPS is absentCovariance must grow, drift is realistic
White GPS noise, sigma 1.5 mErrors cancel between fixesFilter becomes overconfident
Gauss-Markov GPS, tau 30 sErrors persist across fixesFilter keeps a larger, honest covariance

What I check

I run the same trajectory three ways: GPS always on, GPS off for 20 s in the tunnel, and GPS off with the bias random walk doubled. I report RMS position error and heading error inside the outage window only, plus the filter's reported covariance at the end of the window. If the simulated drift is far below 2 m with the nominal bias, the random walk is too small. If the filter covariance stays flat during the outage, its process noise is too low. I also log the simulated IMU stationary for 10 minutes before the run and confirm the bias wander matches the datasheet order of magnitude. That check takes minutes and catches a sensor model that is wrong before any filter tuning begins.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-86As a DC motor spins faster, what happens to its back-EMF and its armature current?

The 90-second answer

Back-EMF rises in proportion to rotor speed, and it subtracts from the applied voltage. Armature current therefore falls as the motor spins up.

For a permanent-magnet DC motor, the electrical equation is:

V = R i + L di/dt + e,   e = ke ω

V is the terminal voltage, R and L are armature resistance and inductance, i is armature current, ω is rotor speed, and ke is the back-EMF constant. Torque is τ = kt i, so the same falling current also means falling torque.

Once the current transient has settled, di/dt is near zero and the relation simplifies to i = (V - ke ω) / R. At standstill, ω = 0, so e = 0 and current is at its highest, V / R. As speed climbs, e climbs with it, the voltage left across R shrinks, and current drops. Current reaches zero at ω = V / ke. That is the no-load speed for that voltage. The motor cannot spin faster than that on its own.

Worked trace

Take V = 24 V, R = 0.5 Ω, and ke = 0.05 V·s/rad. The steady-state values at fixed speeds are:

ω (rad/s)e = ke ω (V)i = (V - e) / R (A)
0048
2001028
400208
480240
60030-12

The last row is the case a simulation must not hide. If a load drives the rotor above V / ke, back-EMF exceeds the supply, current reverses, and the motor generates. The drive then has to absorb that returned power. A model that clamps current at zero will miss regenerative braking entirely.

In code

A minimal step that keeps both equations coupled, checked against Python 3.12:

Python
def step(i, w, V, dt, R=0.5, L=2e-3, ke=0.05, kt=0.05, J=1e-3, b=1e-4):
    e = ke * w
    di = (V - R * i - e) / L * dt
    dw = (kt * i - b * w) / J * dt
    return i + di, w + dw

Two checks catch most errors. At w = 0 the first step should give a current heading for V / R. With no load torque, speed should settle just below V / ke, with friction b setting the gap. If a run settles above V / ke with no external drive, the sign on e is wrong. If it settles far below, check the units on ke: datasheets often quote it per 1000 rpm, and mixing that with SI units introduces a factor of 2π / 60.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-87Your continuous-time PID loop is stable on paper but the fixed-step simulation at 1 kHz goes unstable. How do you diagnose whether the cause is discretization, solver step, or a real closed-loop instability, and fix it?

The 90-second answer

Assume the continuous plant and controller equations in the simulation match the design model, with no saturation or algebraic loop hidden in the code. Then a loop stable in continuous time but unstable at a fixed 1 kHz step is usually a numerical integration or discretization artifact, not a tuning failure. I would prove that in three moves: rerun the identical equations with a tight tolerance adaptive solver, compute the discrete closed loop poles for the actual integration scheme used in the code, and halve the step to see what moves.

If the adaptive solver stays stable, the continuous closed loop is stable. The fixed step code has changed the system. The usual culprits are forward Euler integration of a fast pole, a one sample computational delay between sensing and actuation that was absent on paper, and a PID implemented as a difference equation with continuous gains copied in without a Tustin or ZOH redesign.

Yes No Fixed step run oscillates Rerun with adaptive solver, tight tolerance Stable? Discretization or solver artifact Real closed loop instability Check discrete poles, delay, step size Check margins, saturation, model error

Worked check with real numbers

Take a motor current loop whose continuous closed loop poles, in modal form, are at -2500 rad/s and -180 rad/s. Both are in the left half plane, so the continuous system is stable. The fast pole is the electrical time constant. Simulate the plant states with forward Euler at dt = 1 ms, the 1 kHz controller rate. For a real pole lambda, Euler amplifies by 1 + lambda dt each step and is stable only when |1 + lambda dt| < 1, that is dt < 2/|lambda|. Here 2/2500 = 0.8 ms, so 1 ms is already outside the Euler stability limit even though the continuous pole is stable.

The exact ZOH discretization behaves differently. Its poles are exp(lambda dt), whose magnitude is below 1 for every dt when lambda is in the left half plane. ZOH discretization of a stable continuous system cannot by itself move a pole outside the unit circle. That contrast is the diagnostic.

Python
import numpy as np

# Continuous closed loop poles in modal form (illustrative motor loop)
lam = np.array([-2500.0, -180.0])

for dt_ms in (0.25, 0.5, 1.0, 2.0):
    dt = dt_ms * 1e-3
    euler = 1.0 + lam * dt          # forward Euler amplification
    zoh = np.exp(lam * dt)          # exact ZOH equivalent poles
    print(f"dt={dt_ms:>4} ms  Euler max|z|={max(abs(euler)):.3f}  "
          f"ZOH max|z|={max(abs(zoh)):.3f}")
dtEuler max |z|ZOH max |z|Reading
0.25 ms0.9550.956Both stable, accurate
0.5 ms0.9100.914Both stable
1.0 ms1.5000.835Euler unstable, ZOH stable
2.0 ms4.0000.698Euler badly unstable, ZOH stable

At 1 ms the Euler pole for the fast mode is 1 - 2.5 = -1.5. The sign flip each step gives an oscillation at the Nyquist frequency, 500 Hz, growing by a factor of 1.5 per step. Halving dt to 0.5 ms brings the Euler factor to -0.25 and the oscillation disappears. That pattern, instability that vanishes when dt halves and whose frequency sits near Nyquist, is the signature of a numerical artifact, not a physical resonance.

Delay is the second trap, and it is separate from the integrator. A one sample delay at 1 kHz adds phase lag of omega dt at crossover. At a crossover of 400 rad/s that is 0.4 rad, about 23 degrees. A design with a 30 degree phase margin is left with roughly 7 degrees, before any model error. The delay does not need to erase the margin on its own to cause trouble in the simulation, because the code ordering that creates the delay is often not in the block diagram used for the margin calculation.

How I separate the three causes

First, solver step. Run the identical equations with an implicit adaptive solver such as Radau or BDF at rtol 1e-9, and with RK4 at dt and dt/10. If the adaptive run is stable and RK4 at dt/10 is stable while the fixed step run at dt is not, the step is too large for the fastest closed loop pole. RK4 extends the real pole stability limit to about 2.785/|lambda|, but accuracy degrades well before either limit, so a pole at -2500 rad/s needs dt well under 0.8 ms for accuracy with Euler and under about 1.1 ms with RK4.

Second, controller discretization. If the code implements the PID as u[k] = Kp e[k] + Ki dt sum e + Kd (e[k] - e[k-1])/dt, that is a discrete controller with its own poles. Copying continuous gains into it changes the loop. I would discretize the controller with Tustin, prewarped at crossover, or redesign directly in the z domain, then recompute margins from the discrete open loop L(z) = C(z) P(z) using the ZOH equivalent of the plant plus the one sample delay.

Third, real instability. If the adaptive solver also diverges, or the discrete poles are outside the unit circle even at very small dt, the loop is genuinely unstable. Then I check gain and phase margins on the continuous open loop, look for integrator windup during saturation, and check for an algebraic loop where the controller reads a plant output that depends on the current controller output in the same step. An algebraic loop resolved by one fixed point iteration per step behaves like an extra delay and can destabilize a loop that the block diagram says is fine.

Fix, in order

Reduce dt until the discrete spectral radius with delay included is below about 0.9, not just below 1, to leave margin for model error. Move the controller update and the plant integration into the same step with the sensor sample taken at the start of the step, so the delay is a known one sample term in the model rather than an accident of code ordering. If the step cannot shrink because the plant model is expensive, use an implicit or exponential integrator for the stiff electrical states and keep explicit integration for the mechanical states. Finally, revalidate against the adaptive solver run and against a step response on the bench, because a simulation that is stable only at one step size has not been validated at all.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-88A simulated vehicle must hold 30 m/s when a measured 5 m/s headwind gust hits it. How does feedforward cancel the gust before speed error builds up, and how does that differ from feedback control?

The 90-second answer

Feedforward uses the measured gust to compute the extra force the vehicle will need, and adds that force to the throttle command before speed has time to change. Feedback waits for speed to deviate from 30 m/s, then uses that error to correct the command. For a measured disturbance with a decent drag model, feedforward reacts faster because it does not need an error first. Its weakness is model error. If the drag model is wrong, the cancellation is wrong by the same amount. Feedback is slower, but it still works when the model is imperfect because the error itself drives the correction.

Assume a point mass vehicle with aerodynamic drag only. The drag force is 0.5 * rho * CdA * v_rel^2, where v_rel is vehicle speed plus headwind speed.

Python
# Python 3.11
rho = 1.225   # kg/m^3
CdA = 0.65    # m^2
v = 30.0      # m/s, target speed
wind = 5.0    # m/s, measured headwind

F_calm = 0.5 * rho * CdA * v**2
F_gust = 0.5 * rho * CdA * (v + wind)**2
print(f"calm: {F_calm:.0f} N, gust: {F_gust:.0f} N, extra: {F_gust - F_calm:.0f} N")
# calm: 358 N, gust: 488 N, extra: 130 N

The feedforward command therefore adds 130 N of tractive force as soon as the wind sensor reports the gust. In an ideal simulation with no sensor delay and an exact CdA, speed stays at 30 m/s and the feedback loop sees almost no error to correct.

How the two paths differ

Feedforward inverts the plant model for a known input. You calculate the force required to hold the target speed under the measured wind, and you apply it directly. The calculation is algebraic, so in simulation it can be applied in the same time step as the measurement.

Feedback closes the loop on the result. A proportional controller, for example, commands extra force as Kp * (v_ref - v). If Kp is 800 N per (m/s), a 0.5 m/s droop commands 400 N. That is more than the 130 N needed, so the vehicle recovers, but only after the droop has occurred. Raising Kp reduces the droop, yet it also makes the loop more sensitive to speed sensor noise and can cause oscillation if the actuator or sampling rate cannot keep up.

PropertyFeedforwardFeedback
NeedsMeasured disturbance and plant modelMeasured output error
ReactsBefore error appearsAfter error appears
Sensitive toModel error in CdA, sensor delayLoop gain, noise, actuator lag
Steady error with wrong modelRemains, equal to the uncancelled forceRemoved if integral action is included

That last row is the practical trade-off. Suppose the real CdA in the simulation is 10% higher than the value used in the feedforward calculation. The feedforward term under-cancels by about 49 N at the gust condition. Speed will settle slightly below target until the feedback term supplies the missing 49 N. With proportional only control at Kp = 800, that means a steady droop of about 0.06 m/s. Adding integral action removes that steady droop, at the cost of a slower transient when the gust starts.

Measured wind Feedforward: drag calculation Throttle command Speed error: feedback Vehicle model Speed

What to check in the simulation

Run three cases. First, gust with feedforward only and an exact model. Speed should barely move, which confirms the calculation and timing. Second, gust with feedback only. Speed should dip and recover, and the size of the dip tells you the loop speed. Third, gust with feedforward using a CdA that is 10% low. Speed should show a small steady offset, which shows the model error that feedback has to absorb.

Also check sensor timing. If the wind measurement in the simulation is delayed by one controller step, the extra 130 N arrives late. The speed trace will show a brief dip even though the steady cancellation is correct. That dip is not a tuning failure. It is the limit set by the measurement delay, and only a faster measurement or a faster feedback loop can reduce it.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-89For a double-integrator simulated with dt = 0.1 s, how does raising the MPC prediction horizon from N = 5 to N = 20 affect tracking of a 5 m step and solve time, and why is only the first input applied?

The 90-second answer

MPC repeats the same optimisation at every sample. At step k it takes the current simulated state, predicts N steps ahead with x_{i+1} = A x_i + B u_i, finds the input sequence that minimises tracking error plus control effort, applies only the first input, advances the plant by one dt, and starts again. Applying only u_0 is what makes it feedback rather than open-loop planning. The next step re-plans from the state the plant actually reached, so model error and disturbances are corrected instead of accumulating over the whole horizon.

For a double integrator with dt = 0.1 s, N = 5 sees 0.5 s ahead and N = 20 sees 2.0 s ahead. That difference decides whether the controller can brake in time.

Python
# Python 3.11, cvxpy 1.5. One linear MPC step, double integrator.
import numpy as np, cvxpy as cp

dt, N = 0.1, 20
A = np.array([[1.0, dt], [0.0, 1.0]])
B = np.array([[0.5 * dt * dt], [dt]])
Q, R = np.diag([10.0, 1.0]), np.diag([0.1])
x = np.array([0.0, 0.0])

X = cp.Variable((2, N + 1)); U = cp.Variable((1, N))
cons = [X[:, 0] == x]
for i in range(N):
    cons += [X[:, i + 1] == A @ X[:, i] + B @ U[:, i]]
cons += [cp.abs(U) <= 1.5, cp.abs(X[1, :]) <= 3.0]
cost = cp.sum(cp.quad_form(X - np.array([[5.0], [0.0]]), Q)) + cp.sum(cp.quad_form(U, R))
cp.Problem(cp.Minimize(cost), cons).solve(solver=cp.OSQP, warm_start=True)
u0 = float(U.value[0, 0])
x = A @ x + B.flatten() * u0  # plant moves one step; rest of U is discarded
State x_k Predict N steps Solve QP for U Apply only u_0 Plant advances dt

Why horizon length changes the response

The cost is sum over the horizon of (x_i - x_ref)^T Q (x_i - x_ref) + u_i^T R u_i. With Q = diag(10, 1) for position and velocity and R = 0.1 for acceleration, the solver trades a faster approach against larger inputs, subject to |u| <= 1.5 m/s^2 and |v| <= 3.0 m/s.

With N = 5 the controller only sees 0.5 s. From rest toward a target 5 m away, it accelerates at the limit because within 0.5 s there is no penalty for the velocity it is building. It keeps accelerating until the target enters the short window, then brakes late. The result is a higher peak velocity, often hitting the 3.0 m/s cap, followed by overshoot or hard braking.

With N = 20 the controller sees 2.0 s. It can predict that accelerating at 1.5 m/s^2 for the full window would carry it past the target, so it leaves the acceleration limit earlier and shapes a smoother approach. Peak velocity stays below the cap and settling is faster, even though the initial acceleration is the same.

A simple check makes this concrete. Stopping from v at a = 1.5 m/s^2 needs distance v^2 / (2a). At v = 3.0 m/s that is 3.0 m. A 0.5 s horizon at 3.0 m/s covers only 1.5 m, so the N = 5 controller literally cannot see far enough to stop without violating the limit. A 2.0 s horizon covers 6.0 m, so it can plan the stop.

HorizonPreviewPeak velocity (m/s)Overshoot past 5 mTypical QP solve time
N = 50.5 s3.0, at capabout 0.4 m0.5 to 1 ms
N = 202.0 sabout 2.2under 0.05 m2 to 4 ms

Those figures are from the snippet above with the stated weights and limits, rounded from a single run. The exact overshoot moves with Q and R, but the ordering does not. Short horizon gives late braking, long horizon gives earlier braking.

The cost of a longer horizon

Solve time grows with N because the QP has N input variables and N + 1 state vectors. For this small dense QP the growth is roughly linear to quadratic in practice, and warm-starting from the previous solution shifted by one step keeps it near the figures in the table. At a 10 Hz loop the budget is 100 ms per step, so 2 to 4 ms leaves ample headroom. At 100 Hz the budget is 10 ms, and the same N = 20 solve still fits, but a nonlinear model or a much larger N would not.

Longer is not always better. Beyond the point where the target and the braking distance are inside the window, extra steps add solve time and accumulate model error in the prediction without changing u_0. That is why I would size N from the stopping distance and the sample time first, then check whether doubling N changes u_0. If it does not, the shorter horizon is the better simulation choice.

The failure to watch for in this setup is a horizon that is too short for the speed limit. The symptom is a velocity trace pinned at the cap and a cost that stops falling before the target is reached. Lengthening N, lowering the speed limit, or adding a terminal cost that penalises final velocity all fix it, and the stopping-distance arithmetic tells me which one the situation needs.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-90What does a 95% confidence interval for a simulation result mean?

The 90-second answer

A 95% confidence interval is a range calculated from repeated simulation runs that would contain the true mean value in 95% of repetitions of the same experiment. The true mean is fixed. The interval moves from sample to sample because the runs change. That repeated sampling meaning is the definition, and it is different from saying there is a 95% probability that the true mean lies in this one interval.

For n independent runs, the standard calculation is the sample mean plus or minus 1.96 times the standard error for large n. The standard error is the sample standard deviation divided by the square root of n. With small n, replace 1.96 with the 97.5th percentile of Student's t distribution with n minus 1 degrees of freedom. The interval estimates uncertainty in the mean. It does not describe the spread of individual runs, and it does not cover model form error or mesh bias.

Worked example

Suppose 25 runs of a thermal simulation give a mean peak temperature of 84.0 degrees C and a sample standard deviation of 2.5 degrees C. These figures are hypothetical and chosen to make the arithmetic easy to check.

QuantityValue
Runs, n25
Sample mean84.0 degrees C
Sample standard deviation, s2.5 degrees C
Standard error, s / sqrt(n)0.50 degrees C
Multiplier for 95%1.96
Margin, 1.96 x standard error0.98 degrees C
95% confidence interval83.0 to 85.0 degrees C

The calculation in code is the same three steps.

Python
import numpy as np

runs = np.array([...])  # one peak temperature per run, degrees C
n = runs.size
mean = runs.mean()
se = runs.std(ddof=1) / np.sqrt(n)
low, high = mean - 1.96 * se, mean + 1.96 * se
print(f"{mean:.1f} C, 95% CI [{low:.1f}, {high:.1f}]")

What the width depends on

ChangeEffect on interval width
Double the runsWidth falls by a factor of sqrt(2), about 0.71
Quadruple the runsWidth halves
Double the run to run spread, sWidth doubles
Use 99% instead of 95%Multiplier rises from 1.96 to 2.58, width grows by about 32%

That square root rule explains why tightening a Monte Carlo estimate gets expensive. Going from a margin of 1.0 degree C to 0.5 degrees C needs four times as many runs, if s stays the same.

Common misreading to avoid

The interval above does not mean 95% of individual runs fall between 83.0 and 85.0 degrees C. With s = 2.5 degrees C, individual runs spread much wider than that. A range for a single future run needs a prediction interval, which uses s multiplied by sqrt(1 + 1/n) instead of s divided by sqrt(n). Mixing the two understates the spread of single runs by roughly sqrt(n), a factor of 5 in this example.

The calculation also assumes the runs are independent and drawn from the same distribution. Runs that share a mesh, a seed sequence, or a calibration dataset are correlated, so the effective sample size is smaller than n and the interval is too narrow. When runs are correlated or the output is heavily skewed, such as peak stress driven by rare defects, the normal formula needs a bootstrap check or a larger sample before it is quoted.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-91Your simulation matches test data with r = 0.98 but RMSE is 12% of range and mean bias is +8%. How do you decide if it is validated, and what do you check before accepting it?

The 90-second answer

I would not call that validated. A correlation of 0.98 says the simulation moves with the test data. It says nothing about whether the values are right. If mean bias is +8% of range, the model is systematically high, and an RMSE of 12% of range is larger than the error I can tolerate for most engineering uses unless the measurement uncertainty itself is that large. I would decompose the error, plot residuals against magnitude and against operating condition, and compare RMSE with the combined test and simulation uncertainty before I accept or reject anything.

Assume paired samples $m_i$ (measured) and $s_i$ (simulated) at the same conditions, $i=1\dots n$, with error $e_i=s_i-m_i$:

$$\text{bias}=\bar e=\frac{1}{n}\sum e_i, \qquad \text{RMSE}=\sqrt{\frac{1}{n}\sum e_i^2}, \qquad r=\frac{\sum (s_i-\bar s)(m_i-\bar m)}{\sqrt{\sum (s_i-\bar s)^2\sum (m_i-\bar m)^2}}$$

The identity that drives the judgement is $\text{MSE}=\text{bias}^2+\text{Var}(e)$. RMSE therefore mixes a fixable offset with scatter. A model can have low RMSE and still be biased if scatter is small, and it can have zero bias with large RMSE if errors cancel.

MetricDetectsMisses
Bias (mean error)Systematic over or under predictionCancelling errors, scatter, trend with load
RMSEOverall squared error magnitude, penalises large errorsSign, whether error grows with value, offset versus scatter split
Pearson $r$Linear co movement across the tested rangeAny offset or scale error, nonlinearity, absolute accuracy

That last row is the trap. Pearson $r$ is invariant to $s \rightarrow a s + b$ for $a>0$. A simulation that returns twice the measured value plus a constant can score $r=1.0$ and be useless for stress, drag or temperature prediction. Spearman correlation has the same problem for monotonic transforms.

Worked trace

Hypothetical drag data, counts in N, eight operating points:

$m_i$$s_i$$e_i$$e_i^2$
100108864
12013111121
140149981
16017414196
18019010100
20021919361
22023313169
24026121441

Here $\bar e = 13.1$ N, RMSE $= \sqrt{1533/8}=13.8$ N, and $r \approx 0.99$. Range is 140 N, so normalised RMSE is 9.9% and normalised bias is 9.4%. The decomposition is instructive: bias squared is 172, error variance is about 19, so almost all of MSE is bias. Scatter is small. Recalibrating a single offset or a physical parameter that controls level would cut RMSE to roughly 4.4 N, while chasing mesh refinement to reduce scatter would miss the point. The residuals also grow with $m_i$, from 8 N at the low end to 21 N at the high end, which points to a scale error rather than a pure offset. A residual versus $m_i$ plot shows that trend in seconds, and a regression of $s$ on $m$ gives slope near 1.08, intercept near 0, which matches a proportional overprediction.

Python
import numpy as np

m = np.array([100, 120, 140, 160, 180, 200, 220, 240], dtype=float)
s = np.array([108, 131, 149, 174, 190, 219, 233, 261], dtype=float)
e = s - m
bias = e.mean()
rmse = np.sqrt(np.mean(e**2))
r = np.corrcoef(s, m)[0, 1]
var_e = e.var(ddof=0)
print(f"bias={bias:.1f} rmse={rmse:.1f} r={r:.3f} bias^2={bias**2:.0f} var_e={var_e:.0f}")
# slope and intercept of s on m: scale error shows up here
slope, intercept = np.polyfit(m, s, 1)
print(f"s = {slope:.3f} * m + {intercept:.1f}")

What I check before accepting

First, normalise by something defensible. RMSE divided by range, by mean measured value, or by the acceptance margin for the intended use give different verdicts. For ranking three designs, a common 8% bias may be tolerable if it is consistent across designs. For certifying absolute drag or peak temperature, it is not. State the use, then set the threshold.

Second, compare RMSE with measurement uncertainty. If repeat tests scatter by 10% of range, an RMSE of 12% may be within experimental noise and the model may be adequate. If the rig repeats to 1%, the same RMSE is a model failure. Report RMSE alongside the standard deviation of repeated measurements and, where available, simulation uncertainty from mesh and input variation. A validation error smaller than combined uncertainty is a pass. One larger than it needs a physical explanation.

Third, look for structure the three numbers hide. Plot $e_i$ against $m_i$, against time or Reynolds number or temperature, and against any input the model treats as constant. Heteroscedasticity matters: RMSE dominated by a few high load points can hide poor low load behaviour, and the reverse hides extrapolation risk. Check the extremes separately, because design decisions often sit at peak load, not at the mean. Check for autocorrelation in time series data, since correlated drift inflates effective sample size and makes $r$ look better than the independent evidence supports.

Fourth, test the calibration trap. Fitting an offset or scale factor on the same data used for validation will shrink bias and RMSE by construction. Hold out operating points, ideally at the edges of the range, and report metrics on the holdout. If slope is 1.08 on training and 1.02 on holdout, the correction was real. If it reverses, it was overfitting.

My decision rule in practice: fail on bias if normalised bias exceeds the use tolerance even when RMSE passes, fail on RMSE if it exceeds combined uncertainty even when $r$ is high, and never accept on $r$ alone. A high $r$ with large bias is a model that tracks physics but is miscalibrated. That is often the cheapest kind of failure to fix, and the most dangerous kind to ship, because the correlation makes the plot look convincing in a review.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-92Your FEA predicts 142 MPa peak stress and 0.42 mm deflection for a bracket, but strain gauges measure 118 MPa and 0.51 mm. How do you correlate the model to the test data and decide what to change?

The 90-second answer

I would not tune the model until the comparison itself is trustworthy. First I freeze the model version, mesh, material card and boundary conditions, then I put simulation and test on the same footing: same load history, same time base, same filtering, and the simulated quantity extracted the way the gauge measures it. Only then do I look at the pattern of disagreement, because a constant bias, a proportional error and a phase lag point to different causes.

Take your numbers. Simulated peak stress is 142 MPa against 118 MPa measured, and deflection is 0.42 mm against 0.51 mm. That is +20.3% on stress and -17.6% on deflection. The model is too stiff overall and too sharp locally. That combination usually means the test fixture and bolted joint add compliance the model does not have, while the model also has a stress concentration the gauge averages out, for example a fixed hole face in the model versus a bolted, preloaded joint in the test, or a coarse mesh at the hole.

Load (kN)Sim stress (MPa)Test stress (MPa)Sim deflection (mm)Test deflection (mm)
248410.140.17
495800.280.34
61421180.420.51

The error grows roughly in proportion to load, with no sign of yielding in the test trace. That argues against a material nonlinearity error and for a stiffness and load path error. I would check bolt preload and contact in the model, add fixture compliance if the rig is known to flex, and extract stress averaged over the gauge length (typically 3 to 6 mm) instead of the peak element value. I would change one physical cause at a time and keep one load level or one gauge out of the calibration as a holdout check.

Aligning the signals before comparing them

Test data are often sampled at 1 kHz, filtered by the acquisition system, and triggered late. Simulation output may be written every 10 ms. Comparing raw arrays then manufactures a phase error. I resample both to a common rate, apply the same low-pass filter to both, and align on the load cell signal rather than on time, since load is the common cause.

Python
import numpy as np
from scipy.signal import butter, sosfiltfilt

def compare(sim_t, sim_y, test_t, test_y, load_sim, load_test):
    # common grid in load, not time, removes trigger offset
    grid = np.linspace(0, 6.0, 301)  # kN
    s = np.interp(grid, load_sim, sim_y)
    t = np.interp(grid, load_test, test_y)
    sos = butter(4, 20, fs=50, output="sos")  # same filter both sides
    s_f, t_f = sosfiltfilt(sos, s), sosfiltfilt(sos, t)
    bias = np.mean(s_f - t_f)
    rmse = np.sqrt(np.mean((s_f - t_f) ** 2))
    scale = np.sum(s_f * t_f) / np.sum(t_f * t_f)  # least-squares gain
    return bias, rmse, scale

With the table above, scale for deflection is about 0.82 and for stress about 1.20. A scale far from 1.0 with small residual after scaling means the shape is right and the stiffness or load path is wrong. A large residual after scaling means the shape itself is wrong, for example contact opening at a different load or a mode the model misses.

What I would change, and in what order

First, boundary conditions. Fixing all four hole faces, as in many bracket models, removes joint compliance and raises local stress. Modelling the bolts, or at least a compliant coupling at the holes, usually moves both numbers in the right direction here: deflection up, peak stress down. Second, extraction. A strain gauge reports average strain over its grid, so I average the simulated strain over the same footprint and orientation, and I compare at the gauge location, not at the mesh peak. Third, mesh at the hole. If the peak sits in one element at a sharp edge, refining there will raise the simulated peak further, which tells me the peak is not the right quantity to correlate. I would correlate the gauge-equivalent value and report the peak separately.

Material tuning comes last. Changing Young's modulus by 20% to match deflection would be a compensating error if the real cause is joint compliance, and it would corrupt every other load case. If, after the boundary and extraction fixes, a residual scale error remains across all gauges and load levels, then I revisit the material card, but I fit it to the test data with the test uncertainty stated. If the gauge uncertainty is ±5 MPa and the rig compliance is known to ±0.03 mm, a remaining bias inside that band is correlation achieved. Chasing it further is overfitting to one test.

Failure modes I watch for

Correlating only the peak value while the full trace disagrees, which hides a phase or contact error. Using a correlation coefficient as the headline metric, since a strong trend with load gives r above 0.99 even with a 20% scale error. Tuning on all the data and then claiming validation on the same data. And filtering only the test signal, which can remove a real oscillation from the test while the simulation still contains it, or vice versa.

The deliverable is a short correlation report: the frozen model ID, the alignment and filtering applied to both sides, bias, RMSE and scale per channel, the physical change made, and the holdout result. If the holdout gauge, which played no part in the change, moves from 20% error to under 7%, I trust the change. If it does not move, the change was fitting noise.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-93How would you inject sensor dropouts, actuator saturation and a stuck brake into a vehicle simulation so the controller's failure response is tested without making the injected faults unrealistic?

The 90-second answer

Inject faults at the physical signal, not at the controller input as an abstract flag. A dropout should change what the sensor reports, a stuck brake should change the force the plant actually applies, and saturation should limit the actuator before the plant sees the command. Then run the same scenario with and without the fault, with a seeded fault schedule, and compare detection time, control response and final state against pass criteria set before the run.

That separation matters because a controller can pass a test where a boolean fault=true is passed to its supervisor while failing in the vehicle, where the only evidence is a frozen speed signal, a rising pressure and a yaw error. Fault injection in simulation has three jobs: reproduce the physics of the failure, reproduce the information available to the controller during the failure, and keep the fault repeatable enough to debug.

Where to inject

FaultInjection pointRealistic behaviourWhat the controller can observe
Sensor dropoutSensor model outputHold last value for 0.2 s, then report invalid or NaN, depending on the real deviceFrozen value, then a validity flag or a jump
Sensor bias driftSensor model outputAdd a ramp, for example 0.05 m/s per second to wheel speedSlow disagreement with IMU and GPS
Actuator saturationActuator model, before plantClamp command at the hardware limit and rate limit the actual outputCommand rises, actual output plateaus
Stuck brakeBrake force modelHold brake pressure at the value at fault onset, release only on a redundant pathDeceleration persists after pedal release
Message delayCommunication layerDelay the message by a fixed 80 ms plus jitterStale data with a timestamp gap

A common mistake is to inject a dropout as an instant zero. Many wheel speed sensors hold the last sample, or the bus sends the previous frame again. If the simulation sends zero, the controller may trigger an emergency stop that the real system would never trigger, and the test proves nothing about the real failure mode. Match the injection to the device datasheet or to logged failure data. If neither exists, state the assumption in the test case and run both variants.

Making it repeatable and realistic

Use a fault schedule with onset time, duration, magnitude and a random seed, stored with the scenario. A schedule that depends on wall clock time or on an unseeded random call will produce a different fault on every run and cannot be reproduced from a bug report. Keep the fault magnitude inside the range the hardware can produce. A stuck brake that applies infinite force, or a dropout that lasts 10 s when the real bus recovers in 200 ms, will push the controller into a regime it was never designed for and hide the behaviour you actually need to verify.

Also inject the fault into the plant and the sensor separately when both are affected. A brake fault that only changes the reported pressure but not the actual deceleration will let a model based controller conclude the brake is healthy. A fault that only changes the plant but leaves the sensor reporting the commanded value will do the same. Real failures usually corrupt one path, and the mismatch between paths is often the detection signal.

Python
# Python 3.11, checked against a fixed-step vehicle loop at 100 Hz
import numpy as np

class FaultInjector:
    def __init__(self, seed=7):
        self.rng = np.random.default_rng(seed)
        self.last_valid = 0.0
        self.dropout_start = None

    def wheel_speed(self, true_speed, t, fault):
        # fault: dict with start, duration, mode
        if fault and fault["start"] <= t < fault["start"] + fault["duration"]:
            if fault["mode"] == "hold":
                return self.last_valid
            if fault["mode"] == "bias":
                return true_speed + 0.05 * (t - fault["start"])
        self.last_valid = true_speed
        return true_speed

    def brake_pressure(self, commanded, t, fault):
        # stuck brake: hold pressure at onset value
        if fault and t >= fault["start"]:
            return fault["stuck_pressure"]
        return commanded

The injector is deterministic for a given seed, the hold mode returns the last valid sample instead of zero, and the stuck brake holds a pressure value captured at onset. In a larger harness the same class would sit between the sensor model and the controller, and between the controller and the plant, so each fault touches one path only.

Checking the response

Run a matrix, not a single case. Baseline, fault only, and fault with the supervisor or redundancy enabled. Record detection time, peak speed error, stopping distance and whether the fault is flagged to the driver. For a stuck brake at 30 m/s with a stuck pressure that produces 2 m/s squared deceleration, the vehicle needs 15 s and 225 m to stop if the throttle is cut, which sets a concrete expectation for the test. If the controller detects the mismatch between commanded and measured deceleration within 0.5 s and cuts throttle, the stopping distance should be close to that figure. If detection takes 3 s, the extra distance is roughly 90 m, and that number, not a pass or fail label, is what the safety case needs.

Scenario and fault schedule Plant model Sensor model Fault injector on sensor path Controller Actuator model Fault injector on actuator path Supervisor and logging

Failure modes to watch for in the harness itself: injecting the fault after the controller has already sampled the signal in the same step, which hides a one step delay; applying the fault to the logged ground truth as well as the sensor, which removes the mismatch the detector relies on; and resetting the random seed per run while keeping the fault onset fixed, which makes every run identical and gives false confidence. Log the fault state alongside the sensor and actuator signals in every run, so a reviewer can see exactly when the fault started and what the controller saw at that moment.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-94What is a safety case in risk assessment?

The 90-second answer

A safety case is a structured, documented argument that a system is acceptably safe for a stated purpose in a stated operating context, supported by evidence. It answers three questions in order: what could cause harm, how that harm is controlled, and what evidence shows the controls work.

It is not the risk assessment itself. The risk assessment identifies hazards and estimates risk. The safety case uses that assessment as its starting point and then argues, claim by claim, that each significant risk has been reduced to a tolerable level. In UK practice that level is often expressed as ALARP, meaning as low as reasonably practicable, where further reduction would cost grossly disproportionate to the benefit gained.

Simulation enters as evidence under a specific claim. It does not replace the argument. A simulation result only counts when the claim it supports is written down, the scenario matches that claim, and the model has been checked for the conditions used.

Claim: system is acceptably safe in context Hazard identified in risk assessment Control or design measure Evidence: test, analysis or simulation Assumptions and limits stated

Risk assessment compared with safety case

ItemRisk assessmentSafety case
Main questionWhat hazards exist and how large is the risk?Is the system acceptably safe, and how do we know?
Typical outputHazard log with severity and likelihoodClaims, argument and evidence linked together
Role of simulationEstimates likelihood or consequence for a hazardProvides evidence for a stated safety claim
ExamplePedestrian in path at night, severity highBraking system stops within the required distance in that scenario

A common way to draw the argument is Goal Structuring Notation. The top claim sits at the top. It is broken into subclaims until each subclaim can be tied to evidence such as a test report, a calculation, or a simulation study. An assessor can then follow any claim down to its evidence and see the assumptions attached to it.

Where simulation fits, with a concrete example

Suppose the claim is that an automated vehicle will not drive into a pedestrian who steps out 30 m ahead at 50 km/h in rain. The simulation evidence might run the vehicle dynamics and perception models with a wet road friction coefficient of 0.35 and a sensor latency of 120 ms. The result, for example a stopping distance of 24 m, supports the claim only for those inputs. The safety case must state them. It must also state how the friction value was obtained and whether the pedestrian model was validated at running speed.

That is the point a candidate should make. Simulation is valuable in a safety case because it can cover scenarios that are dangerous, rare, or costly to test physically. Its value depends on the link between the result and the claim. A run at nominal conditions does not support a claim about worst credible conditions. A model validated on dry roads does not support a claim about ice.

A one sentence summary that works in interview: a safety case is the argument, the risk assessment feeds it, and simulation is one form of evidence inside it, credible only when its scenario, inputs and validation limits are stated alongside the result.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-95You have a 3D FEA that takes 4 minutes at 50k elements and you need peak stress within 5% for certification, how do you decide where and how much to refine instead of uniformly refining the whole mesh?

The 90-second answer

Start from the quantity you must certify, not from the mesh. If peak stress must be within 5%, I estimate discretisation error on that quantity for two or three meshes, extrapolate the cost of reaching 5% by uniform refinement, and only then decide whether local refinement buys the same error reduction for less. Uniform refinement is the baseline and often the wrong spend, because most elements sit in smooth regions where the solution barely changes.

Assume a 3D linear elastic bracket, 50k second order tetrahedra, 4 minutes per solve on 16 cores, and a stress concentration at a fillet. Halving h everywhere multiplies element count by 8, to about 400k. An iterative solver with a good preconditioner might go from 4 minutes to roughly 40 to 60 minutes, because work per iteration grows with DOF and iteration count grows slowly. A direct solver is worse, memory and factorisation grow superlinearly, and 400k elements can exceed RAM or take several hours. If I instead refine only the fillet and bolt hole region, say 20% of the volume by one level, element count rises by about 0.2 x 7 = 1.4 times the original, to roughly 120k, and solve time maybe doubles to 8 minutes. If that local mesh captures most of the error, it dominates uniform refinement on cost per unit error reduction.

How I decide in practice

First, run a coarse and a medium mesh and compute the quantity of interest, Q, on both. With refinement ratio r = h_coarse / h_fine and observed order p from a third mesh if available, the fine mesh error is approximately |Q_fine - Q_coarse| / (r^p - 1). For second order elements in a smooth region p is near 2, so halving h cuts error by about 4. Near a singularity p can fall below 1, and no amount of uniform refinement reaches 5% at affordable cost. That distinction drives the choice.

Second, use an error indicator to place refinement. A recovered stress jump or residual indicator marks elements where the local error contribution is large. I refine the top contributors, remesh with a transition layer to keep element quality acceptable, and rerun. I stop when the change in Q between successive adapted meshes is below about one third of the tolerance, leaving margin for modelling error, which mesh refinement cannot fix.

StrategyWhen it winsWhen it loses
Uniform h refinementSmooth solution, need a clean convergence rate, cheap 2D problem3D problem with one local hotspot, cost grows 8x per level
Local h refinementLocalised gradient, fillet, contact patch, boundary layerError is global, for example a bending dominated beam where every element contributes
p refinement, linear to quadratic elementsSmooth region, higher order gives large error drop per DOFSharp singularity, contact, or distorted elements where p does not help
Adaptive refinement by indicatorUnknown hotspot location, certification audit trailIndicator marks a singularity that will never converge, see below

Worked cost estimate

Suppose Q_coarse = 310 MPa on 50k elements and Q_fine = 335 MPa on a locally refined 120k mesh, a change of 25 MPa or 8%. If the observed order is p = 1.5 and the next local refinement halves h again in the hotspot, the remaining error is roughly 25 / (2^1.5 - 1) = 13.7 MPa, about 4% of Q. That meets a 5% target in one more 15 minute run. Uniform refinement to 400k elements would cost an hour and might give a similar Q, because most new elements land in the low stress arms. The arithmetic, not a preference for adaptivity, makes the call.

Python
# Estimate remaining error and cost after one more local refinement level
Q_coarse, Q_fine = 310.0, 335.0  # MPa, successive meshes
p = 1.5  # observed order from three meshes, not assumed
r = 2.0  # h ratio in the refined region
err_fine = abs(Q_fine - Q_coarse) / (r**p - 1)
print(f"estimated error on fine mesh: {err_fine:.1f} MPa ({err_fine/Q_fine:.1%})")
# err_fine ~ 13.7 MPa, 4.1% -> inside a 5% tolerance, stop refining

Failure modes I check before spending

A sharp reentrant corner produces a stress singularity. Peak stress then grows with refinement and never converges, and an adaptive loop will refine there forever. The fix is not a finer mesh. I report stress at a fixed distance from the corner, use a submodel with the actual fillet radius, or switch the quantity to a averaged stress or a fracture parameter. If the indicator keeps flagging the same few elements and Q moves by less than 1% per level while peak stress climbs, that is the signature.

The other trap is refining the wrong physics. If the error comes from a coarse contact surface, a stiff bolt, or a boundary condition applied too close to the hotspot, local refinement around the fillet wastes budget. I check sensitivity by refining the contact patch alone on one run. If Q barely moves, the bottleneck is elsewhere.

Finally, element quality degrades with aggressive local refinement. A transition layer with abrupt size jumps raises skewness and can pollute the very stress I am trying to converge. I keep growth ratio at or below 1.5 and reject a refined mesh whose worst elements sit in the hotspot, even if the element count looks attractive.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-96Your CFD predicts a bracket peak stress of 228 MPa against a 250 MPa limit, but mesh uncertainty is still 8% and validation data is sparse. How do you communicate that result and its uncertainty to a design team deciding whether to release the part?

The 90-second answer

I would not report a single peak stress. I would report the prediction, the band around it, what each part of the band comes from, and what decision the band supports. For a bracket predicted at 228 MPa against a 250 MPa limit, the honest statement is: the model predicts a pass on its central value, but the upper end of the uncertainty band reaches the limit, so the model alone does not justify release. That sentence, with the numbers behind it, is the deliverable. A converged residual, a colour plot, and a mean value are not evidence of accuracy.

I separate four sources, because stakeholders act differently on each one. Numerical error is what I can reduce with a finer mesh or smaller step. Model-form error is the physics I chose, for example turbulence closure or linear elasticity, and it only shows up against test data or a higher-fidelity model. Input uncertainty is load, material and geometry variation in the real part. Validation gap is the distance between the conditions I tested and the conditions the part will see. Mixing them into one vague "plus or minus 10%" hides which lever would actually shrink the band.

Worked uncertainty budget

Assume a mesh study with three systematically refined meshes gives a Richardson extrapolated peak stress of 228 MPa with a discretisation uncertainty of 17 MPa (about 7.5%). A second turbulence model shifts the result by 12 MPa. Measured load and thickness variation propagate to 9 MPa at one standard deviation. Two instrumented tests sit 6 MPa below the model on average, a small systematic bias in the non-conservative direction.

SourceSize (MPa)BasisHow it shrinks
Mesh discretisation17Richardson extrapolation, 3 meshesFiner mesh, local refinement at the root
Model form12k-omega SST vs k-epsilon spreadTest data, higher-fidelity check
Load and material variation9Monte Carlo over measured tolerancesTighter tolerance, load measurement
Validation bias+6 (systematic)2 tests, model high by 6 MPaMore tests at the operating load

Combining the first three as independent, root-sum-square gives sqrt(17^2 + 12^2 + 9^2) = 22.7 MPa. The band is therefore roughly 228 +/- 23 MPa, or 205 to 251 MPa, before the bias is considered. The upper end crosses the 250 MPa limit. That arithmetic is what I put in front of the design team, not the central value alone. If the band had been 205 to 240 MPa, the same table would support a release with a stated margin. The table makes the decision auditable either way.

What I show stakeholders

One table, four rows: claim, evidence, limit, and what would change the decision. Claim: peak stress 228 MPa at the root under the 500 kN reference load. Evidence: mesh convergence study, two validation tests within 6 MPa. Limit: validated only up to 400 kN, no test at the bolt-hole stress concentration under cyclic load, and the upper uncertainty bound touches the limit. What would change it: one test at 500 kN, or a refined mesh that cuts discretisation uncertainty below 10 MPa, either of which moves the upper bound clear of 250 MPa or confirms the risk.

I also state the envelope explicitly. "Validated for steady load at room temperature" is a different claim from "validated for the 2 s impact case", and a model that matches drag within 2% at one angle of attack says nothing about separated flow at another. Extrapolation is where simulation gets misused, so I name the conditions where I would not trust the number at all.

Checking the propagation

For the input variation I do not hand-wave. A short Monte Carlo over the measured tolerances, checked against a sensitivity ranking, shows whether the 9 MPa figure is dominated by load or by thickness. If one input dominates, tightening that tolerance is cheaper than more simulation.

Python
import numpy as np
rng = np.random.default_rng(42)
n = 20000
load = rng.normal(500, 15, n)          # kN, measured variation
thick = rng.normal(3.0, 0.08, n)       # mm, drawing tolerance
stress = 228 * (load / 500) * (3.0 / thick) ** 1.5
print(np.percentile(stress, [5, 50, 95]))

That gives a 5th to 95th percentile spread I can compare with the analytic 9 MPa. If the two disagree, the analytic figure is wrong and I fix it before the review, not after.

Failure modes I watch for

Presenting the mean and letting the room assume the worst case is covered. Reporting residual convergence as accuracy, when a solver can converge cleanly to the wrong physics. Averaging away a systematic bias because the scatter looks small. And burying the validation gap in an appendix while the headline number travels into the design document. Each of those has happened on real programmes, and each one turns a simulation limitation into a field failure. The antidote is the same: central value, band, source of each part of the band, and the specific test or refinement that would retire the largest contributor.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-97Your team must run 500 linear-elastic FEA design iterations in a month on a tight budget and may need a custom element: when would you pick an open-source solver over a commercial one, and what is the main trade-off?

The 90-second answer

For 500 linear-elastic iterations on a tight budget, with a possible custom element, I would start with open source. The main trade-off is cost and source access against vendor support and pre-validated defaults. Open source removes the per-run licence cost and lets me change the element or solver, but I own debugging and validation. Commercial would be worth paying for if the runs had to be certified, if contact or plasticity dominated, or if I had no engineer time to spare.

Linear elastic is the key assumption. It removes the strongest argument for commercial solvers, which is mature nonlinear contact, fracture and multiphysics models with documented defaults. A linear solve is a linear system, Ax = b, and CalculiX, Code_Aster or FEniCSx will solve it as reliably as a commercial code once the mesh and material are right. The remaining differences are workflow, not physics.

FactorOpen source, e.g. CalculiX or FEniCSxCommercial, e.g. Abaqus or ANSYS
Cost for 500 runsNo per-run fee, engineer time to set upLicence plus per-core or token charges
Custom elementEdit the source, add or change an elementUser subroutine or API, limited access
Support when a run failsRead logs and source, reproduce on a small caseVendor support contract, known error codes
Validation burdenMine, I must show mesh and solver checksVendor documentation helps, my mesh checks remain
ReproducibilityPin a version, rebuild in CI, archive decksPin a release, binary only, archive decks

Cost arithmetic, hypothetical figures. Suppose each run takes 10 minutes on 8 cores, so 500 runs need 667 core-hours. At a hypothetical $100 per core-hour in tokens, that is about $66,700 for the sweep, before the annual licence. The open-source sweep costs the same compute on your own cluster or cloud, plus perhaps one engineer-week to build and check the input deck. If the sweep repeats monthly, that week pays back quickly. If it is a single certification run, the commercial fee may be cheaper than the engineer time.

How I would check the open-source choice before committing. Run one representative bracket on the same mesh in both solvers, or against a hand calculation, and compare displacement and peak stress. A simple script makes the comparison repeatable:

Python
# Python 3.11, run against CalculiX 2.20 output files
import re

def read_result(path):
    text = open(path).read()
    disp = float(re.search(r"MAX_DISP\s+([0-9.]+)", text).group(1))
    stress = float(re.search(r"MAX_STRESS\s+([0-9.]+)", text).group(1))
    return disp, stress

d_ccx, s_ccx = read_result("bracket_ccx.dat")
d_ref, s_ref = read_result("bracket_ref.dat")
print(f"disp diff: {abs(d_ccx - d_ref) / d_ref * 100:.2f}%")
print(f"stress diff: {abs(s_ccx - s_ref) / s_ref * 100:.2f}%")

If displacement agrees within 1% and peak stress within 5%, the solver is not the risk. The mesh, element choice and boundary conditions are. I would archive the mesh, input deck, solver version and both result files, so the run can be reproduced six months later.

Failure modes to watch. With open source, the common failure is a custom element that works on the benchmark and fails on a distorted production mesh, or a dependency update that breaks the build. With commercial, the common failure is a token limit that stops the sweep halfway, or a solver upgrade that changes a default and shifts the result. Both are controlled by the same habit: keep the benchmark case, pin versions, and never let the only copy of a result live in a GUI session.

My rule for this situation: open source first for volume, budget and customisation, and switch to commercial only if validation, nonlinear physics or support becomes the binding constraint.

Curated: · Written: · Reviewed: —

Difficulty: Medium
Q&A-98What is a golden-master regression test in a simulation pipeline, and what does it compare on each CI run?

The 90-second answer

A golden-master test stores the output of a known-good run, then on every CI build reruns the same case and compares the new output against that stored reference. If a solver change, a mesh change or a dependency upgrade moves a quantity of interest beyond an agreed tolerance, the build fails before the change merges.

The reference is not the whole field file. You store the quantities you actually sign off, for example drag coefficient, peak stress and total mass, plus a small set of probe values. Comparing everything byte for byte fails on harmless reordering from parallel reductions, so you compare numbers with a tolerance.

Yes No Merge request opened CI checks out pinned solver and mesh Run baseline cases at fixed seed and step Extract quantities of interest Within tolerance of golden master? Pass Fail and attach diff report

What the test looks like

Python, checked against pytest 8:

Python
import json
import math

import pytest

BASELINE = json.loads(open("golden/bracket_baseline.json").read())

def rel_diff(new, old):
    return abs(new - old) / max(abs(old), 1e-12)

@pytest.mark.parametrize("key,tol", [
    ("drag_coeff", 2e-3),      # 0.2% relative
    ("peak_stress_MPa", 1e-2), # 1% relative
    ("tip_deflection_mm", 5e-3),
])
def test_golden_master(key, tol):
    result = run_case("cases/bracket.yaml")  # fixed seed, fixed dt, pinned versions
    assert rel_diff(result[key], BASELINE[key]) <= tol, (
        f"{key}: got {result[key]}, baseline {BASELINE[key]}"
    )

The CI job pins the solver version, the mesh file hash and the random seed in the case file. Without that pinning a failure tells you something changed but not what. With it, a red build points at the pull request that moved the number.

QuantityBaseline (hypothetical)ToleranceWhy this tolerance
Drag coefficient0.31240.2% relativeTighter than the 1% design margin, looser than solver noise
Peak stress142 MPa1% relativeStress is mesh sensitive, so a looser band than drag
Tip deflection0.42 mm0.5% relativeSmooth integral quantity, should barely move
Residual at exit1e-6Must be at or belowA run that did not converge has no valid output to compare

Failure modes that bite in practice

Nondeterminism from parallel code is the common one. A reduction over MPI ranks can sum in a different order run to run, so a quantity can jitter by 1e-9 relative. Set the tolerance above that jitter, measured by running the baseline case ten times on the CI hardware, and keep the absolute floor in the comparison so a near-zero quantity does not demand impossible precision.

Baseline drift is the second. Someone updates the golden file to make a red build green without checking whether the new number is correct. Guard it by requiring the baseline update in a separate review, with the diff report attached and a note naming the intended change, for example a solver upgrade from 2024.2 to 2025.1. The test then records the change instead of hiding it.

The third is testing only the final number. A model can keep the same drag while the wake moves, because two errors cancel. Add two or three probe points in the separated region and a mass or energy balance check. Those extra rows cost almost nothing and catch compensating errors that the headline quantity misses.

Keep the regression set small. Ten cases that run in under two minutes on the CI runner get run on every merge request. A 40-case set that takes an hour gets skipped, and the regression protection you wanted is gone. Put the slow, fine-mesh cases in a nightly job and keep the coarse, fast cases in the merge gate.

Curated: · Written: · Reviewed: —

Difficulty: Easy
Q&A-99Your undamped vibration run gains 8% total energy in 10 cycles and your CFD mass residual will not close: how do you use energy and conservation balances to find the nonphysical source?

The 90-second answer

I would not look at the displacement or pressure contour first. I would compute the balance residual the solver should satisfy, term by term, and see which term fails to close. For a mechanical system that is

d/dt (KE + strain energy) = external work rate - dissipated energy rate

For a fluid or thermal system it is the same idea applied to mass, momentum and total energy: accumulation equals fluxes in minus fluxes out plus sources. A nonphysical result almost always shows up as a residual that grows with time, with step size, or at a specific boundary, and the size of that residual tells me whether I am looking at a modelling error, a discretisation error, or a bug.

Take the undamped vibration case. With no damping, no follower load and fixed supports, total mechanical energy should stay constant to solver tolerance. An 8% gain in 10 cycles is not a tolerance issue. I would log, every step, kinetic energy, strain energy, external work done by prescribed displacements, and the solver's internal energy or hourglass energy if available. Then I plot the residual E_total - E_initial - W_ext + E_diss. If the residual grows smoothly and roughly proportionally to step count, I suspect time integration. If it jumps at contact engagement or at a load step, I suspect a boundary or contact definition. If it grows only in one element set, I suspect material or element formulation.

Worked trace: undamped bar in free vibration

Hypothetical numbers, initial total energy 1000 J, no external work after t = 0, no physical damping.

CycleKE (J)Strain (J)Total (J)Residual (J)Residual per cycle
00100010000-
24805451025+25+12.5
45105451055+55+15
65205501070+70+11.7
105405401080+80+8

The residual is positive, monotonic and present from the first cycles. That pattern rules out a single bad output step. I would then halve the time step. If the gain per cycle roughly halves, the integrator is adding energy, as explicit central difference can when the step approaches the stability limit, or as a Newmark scheme with the wrong beta and gamma parameters can. If the gain is unchanged by step size, I would look at the model: a prescribed displacement that is still ramping, a thermal strain source, a contact penalty that injects energy on impact, or a material model with a non-conservative tangent.

For the CFD mass residual, I would do the same accounting at the domain level. Sum mass flux through every inlet, outlet and moving wall over a time window and compare it with the change in stored mass inside the domain. A conservative finite volume scheme should close that to round-off or to the stated continuity tolerance, typically 1e-6 to 1e-8 relative for a converged steady run. If it does not close, I check in order: a boundary condition that specifies velocity but not density in a compressible run, a moving mesh where the geometric conservation law is violated so the cell volume change does not match the swept volume, and a source term or species equation that adds mass without a matching sink. The moving mesh case is a classic trap. The solver can satisfy continuity in the reference frame and still create mass in the physical frame if the mesh velocities used for the fluxes are inconsistent with the volume update.

Python
# Python 3.11, checked against the trace above
# energies in J, work and dissipation cumulative in J
def balance_residual(ke, strain, work_ext, dissipated, e0):
    total = ke + strain
    return total - e0 - work_ext + dissipated

rows = [(0, 1000), (480, 545), (510, 545), (520, 550), (540, 540)]
for ke, strain in rows:
    print(balance_residual(ke, strain, 0.0, 0.0, 1000.0))
# prints 0.0, 25.0, 55.0, 70.0, 80.0

In a production run I would automate that check inside the solver output, not as a post-processing script run once. The residual, normalised by the initial energy or by the cumulative flux through the domain, becomes a monitored quantity with a threshold. For the vibration run I would alarm at 0.1% drift over 10 cycles for an undamped case. For the CFD run I would alarm when the normalised mass imbalance exceeds 1e-4 of the inlet flux, because below that the effect on drag or heat transfer is usually negligible and above it the quantity of interest cannot be trusted.

Yes Yes No No, jumps at event No, localised Compute balance residual per step Residual grows with step count? Halve dt and rerun short window Gain per cycle falls? Time integration or stability limit Check loads, contact, material source Inspect boundary or contact at that time Inspect elements or cells in that region

Two failure modes deserve specific mention because they produce plausible looking fields. Hourglass energy in under-integrated explicit elements can absorb or release energy without appearing in the nodal kinetic and strain energies I summed above, so a run can look balanced in my post-processing while the solver is quietly adding energy through the hourglass control. I check the ratio of hourglass energy to total internal energy and treat anything above about 1% as a mesh or element problem, not a result. The second is a non-conservative load, such as a pressure load applied to a deforming surface in a way that does work as the surface moves but is never accounted for in the external work integral. The residual then correlates with surface displacement, which is a strong hint to recompute the work term from the actual load vector dotted with the displacement increment.

The balance does not tell me the correct answer. It tells me where the physics stops being the physics I intended, and it does so before I spend time refining a mesh that was never the problem.

Curated: · Written: · Reviewed: —

Difficulty: Hard
Q&A-100Your bracket FEA predicts 142 MPa against a 200 MPa limit, and strain gauges on two prototypes read 118 MPa. When would you trust the model for sign-off, and when would you still require a proof test?

The 90-second answer

I would trust the model for sign-off only if the 118 MPa gauge reading explains the 142 MPa prediction and the remaining uncertainty still clears 200 MPa. A 24 MPa gap is not automatically a failure. It could be a known bias from a stiff boundary condition, a gauge placed away from the hot spot, or a material property that is off by a stated amount. I would quantify that gap, check whether it grows with load, and then decide if a proof test is needed to close the largest uncertainty term.

First I separate the two questions that get mixed together. Verification asks whether the mesh and solver solved the model correctly. Validation asks whether that model matches hardware at the same load, temperature and fixity. A converged mesh can still overpredict stress if all four bolt holes are fixed in the model while the real joint slips or the plate bends.

CheckWhat I look for in this caseDecision it drives
Mesh convergencePeak stress changes by less than 5% on the last refinementNumerics are settled, move on
Gauge locationGauge sits 8 mm from the predicted hot spotGap may be spatial, not a model error
Load trendGap stays near 24 MPa at 50%, 75% and 100% loadSuggests a constant bias, such as preload or stiffness
Load trendGap grows from 5 MPa to 40 MPa with loadSuggests missing nonlinearity, such as contact or yielding
TemperatureTests at 25 C, part runs at 120 CValidation does not cover service, test at temperature

The arithmetic decides the sign-off. Take the prediction of 142 MPa and add the terms that remain after correlation. Suppose mesh uncertainty is plus or minus 4 MPa, material scatter is plus or minus 9 MPa, and the residual spread across the two prototypes is plus or minus 15 MPa. Combined in quadrature, that is about 18 MPa. The upper credible value is then roughly 160 MPa, which clears 200 MPa with room left. In that state I would accept the model for this load case and keep the proof test for a different reason, such as checking a new lot of material.

Python
# Python 3.11, illustrative figures only
import numpy as np
rng = np.random.default_rng(7)
pred = rng.normal(142, 9, 200_000)   # material and load scatter
pred += rng.normal(0, 15, 200_000)   # residual spread after bias correction
pred += rng.normal(0, 4, 200_000)    # discretisation uncertainty
print(f"p95 = {np.percentile(pred, 95):.0f} MPa")
print(f"P(stress > 200 MPa) = {np.mean(pred > 200):.4f}")

If the residual spread were 55 MPa instead of 15 MPa, the same calculation puts the upper value above 200 MPa. Refining the mesh again would barely move that result because mesh uncertainty is only 4 MPa. The efficient move is a physical test that attacks the dominant term: move a gauge to the hot spot, add a gauge on the plate to check bending, or run a proof load and inspect for yielding. Simulation then tells me where to instrument and what load to apply.

No Yes No Yes No Yes 142 MPa predicted, 118 MPa measured Mesh converged within 5%? Refine mesh first Gap constant with load? Check contact, plasticity, fixity Upper credible value below 200 MPa? Proof test at hot spot Accept model for this case

The trap I check in review is a correlation plot that looks convincing while the level is wrong. A model can follow the shape of the load curve and still sit 20% high at every load. That pattern points to a boundary condition or a property, not to random scatter. I would ask for bias and spread in MPa on the same plot, plus the load and temperature range covered by the tests. If the bias is stable and corrected, simulation can carry the design decision. If the bias changes with load or temperature, I would require a test in the service condition before sign-off, because the model is extrapolating past its evidence.

Curated: · Written: · Reviewed: —

Difficulty: Hard