UpSkill Sprint Consulting logoUpSkill Sprint Consulting
Data Analytics · Advanced · Interactive

Hierarchical Data Analysis for Steel Charpy Testing

Choose and validate models for heat → pipe → specimen data without pretending repeated measurements are independent evidence.

75 minutesFlagship engineering case studyExcel · Minitab · Python · R

Start with your own data

Scenario Configurator — describe your data structure

Name the units and variables exactly as they appear in your project. The guide will translate your structure into an analysis path, warn you about invalid replication, and recommend a primary model plus sensitivity checks.

Build your analysis scenario

Choose after defining the levels below.

1. Build the level structure What: The chain of units that contains your observations. How: Start with the broadest independent unit and end with the unit represented by each data row. Why: The hierarchy determines which observations share information and which random or correlation terms may be needed.

Add as many levels as the real data require. Put the broadest independent unit first and the row-level unit last.

What: Adds another unit beneath the current lowest level. How: Add every real sampling or repeated-measurement level; there is no fixed limit. Why: Omitting a level can hide dependence and understate uncertainty.

2. Add predictors What: Inputs, exposures, or controls that may explain Y. How: Add each predictor separately and assign it to the level where its value truly changes. Why: Predictors at different levels have different independent sample sizes and interpretations.

Each predictor can vary at a different level. “Upper level only” is valid; select the first level.

What: Creates another explanatory-variable row. How: Add all candidate predictors, blockers, and random-slope candidates you plan to evaluate. Why: The tool checks their combined complexity and measurement levels.
What: Runs the model-selection logic. How: Review all fields first, then select this button. Why: It generates ranked methods, structural warnings, and validity checks from your entries.What: Restores the original heat → pipe → Charpy specimen example. How: Use it to discard the current configuration and start again. Why: It provides a known example for learning or troubleshooting.

Quick-pick — which strategy fits your situation?

Orientation

Learning objectives

This lesson takes you from a raw specimen table to a defensible engineering conclusion. It is designed for analysts who must explain not only what the model says, but why the evidence deserves trust.

Diagnose the designMap every variable to the level where it changes.
Choose the analysisMatch the model to the question, hierarchy, and heat count.
Defend the conclusionValidate uncertainty, influence, overlap, and engineering meaning.

By the end, you will be able to:

  • Identify the independent experimental unit and the measurement unit.
  • Classify variables as heat-, pipe-, test-set-, or specimen-level.
  • Explain pseudoreplication using ICC, design effect, and effective sample size.
  • Select aggregation, cluster-robust, GEE, mixed-model, Bayesian, or bootstrap methods.
  • Validate a three-level model and communicate limitations responsibly.
  • Implement a defensible workflow in Excel, Minitab, Python, or R.
Prerequisites: basic regression, averages, standard deviation, confidence intervals, and the idea that correlation does not prove causation. Mixed-model experience is not required.
Deliverable: a complete analysis plan, a validated model comparison, and a reporting statement suitable for an engineering review.

Case question

A steel mill wants to know whether heat-level calcium and sulfur are associated with transverse base-metal Charpy energy after accounting for product dimensions and rolling conditions. Each heat supplies several pipes, and each pipe supplies three specimens. The temptation is to run ordinary regression on every specimen row. This lesson shows why that shortcut can be badly misleading—and what to do instead.

Foundation 1

Why ordinary regression fails

If calcium and sulfur are measured once per heat, repeating those values on every pipe or specimen does not create more independent chemistry observations.

Central rule: the effective sample size for a heat-level chemistry effect is driven primarily by the number of independent heats—not the number of pipes or Charpy specimens.

The fastest way to understand the problem

What changes?

Calcium and sulfur change from heat to heat. Exit temperature may change by pipe. Charpy energy changes by specimen.

What repeats?

The same heat chemistry is copied into every lower-level row. Repetition improves precision about that heat, but it does not create another independent heat.

What does naïve OLS assume?

After accounting for predictors, every residual is independent. Specimens from the same pipe and heat rarely satisfy that assumption.

What goes wrong?

Coefficient estimates may look plausible, while standard errors, p-values, and confidence intervals become too optimistic.

Key terminology

Terms used throughout the lesson
TermPlain meaningPractical interpretation
Experimental unitThe smallest unit independently exposed to the condition of interest.For heat chemistry, usually the heat.
Measurement unitThe unit on which a result is recorded.A Charpy specimen can be a measurement unit without being independent.
Nested dataLower-level units belong to one higher-level unit.Specimens are within pipes; pipes are within heats.
Crossed factorA factor appears across many clusters.Lab, machine, operator, or test date may cross heats.
PseudoreplicationRepeated measurements are treated as independent replicates.It usually makes standard errors too small and evidence look stronger.
Fixed effectA systematic average association to estimate.Expected Charpy change per 10 ppm Ca, controlling for other variables.
Random effectCluster-to-cluster deviation represented by a distribution.Each heat can have its own baseline.
ICCShare of total variance associated with a cluster.High ICC means observations within a heat are strongly alike.
Partial poolingCluster estimates borrow strength from the full population.Noisy heat effects shrink toward the overall average.
Marginal effectAn average association across the population of heats.Often targeted by GEE or cluster-robust inference.
Conditional effectAn association for observations sharing the same modeled random effects.Often reported from a mixed-effects model.
Random slopeThe effect of a predictor is allowed to differ by cluster.It needs within-cluster variation in that predictor and enough clusters.
Singular fitA random-effect variance is estimated near zero or correlations hit a boundary.The proposed random structure may be more complex than the data support.

Core formulas

Intraclass correlation
ICCheat = σ²heat / (σ²heat + σ²pipe + σ²residual)
σ²heat
between-heat variance, J²
σ²pipe
pipe-within-heat variance, J²
σ²residual
specimen-level variance, J²

Use: quantify how similar results are within heat. Do not use: as proof that the hierarchy is causal or complete.

Design-effect approximation
DE = 1 + (m̄ − 1)ρ
m̄
average observations per cluster
ρ
intraclass correlation, 0 to 1

Use: teach how clustering reduces independent information in a simple one-cluster-level setting. Do not use: as an exact substitute for a three-level variance model, especially with unequal cluster sizes.

Approximate effective sample size
neff ≈ n / DE
n
raw number of rows
neff
approximate information-equivalent count

This is an intuition aid. For a predictor that changes only across heats, the distinct heat count remains the key replication count.

Three-level mixed model
Yhpk = β₀ + β₁Xh + β₂Zhp + uh + vhp + εhpk
Y
Charpy energy, J
X
heat-level predictor
Z
pipe-level predictor
u, v, ε
heat, pipe, and specimen deviations

Use when the hierarchy and cluster counts support variance estimation. Random effects are usually assumed mean-zero, mutually independent, and approximately normal unless another structure is specified.

Important nuance: “effective sample size” is not one universal number. It depends on the estimand, model, ICC structure, balance, and predictor level. Use the design-effect calculation for intuition; use design-respecting model-based uncertainty for conclusions.

Foundation 2

The eight-gate analysis workflow

A mixed model is not the first step. The first step is proving that the data structure, estimand, and model are aligned.

Define the engineering decision

Write the decision before opening software: estimation, prediction, process understanding, screening, or causal change. Define the response precisely—average Charpy, minimum individual energy, probability of meeting a requirement, or another endpoint.

Gate: Could two reviewers read the question and identify the same response, population, contrast, and decision threshold?

Map the hierarchy and every variable

Create one row per specimen, but record the level where each predictor truly changes. Mark heat, slab, coil/pipe, test set, specimen, and crossed factors such as laboratory or machine.

Gate: No “heat-level” variable may have multiple unexplained values within a heat.

Count independent information

Count distinct heats for heat-level effects, distinct pipes for pipe-level effects, and specimens for specimen-level variation. Compute the residual degrees of freedom for any aggregated model: n independent units − p estimated parameters.

Gate: If independent clusters are scarce relative to model complexity, restrict the model or remain descriptive.

Audit comparability and overlap

Cross-tab chemistry ranges against grade, rolling practice, slab thickness, OD, gauge, test temperature, orientation, specimen size, and production period. A coefficient cannot separate effects where the data contain no overlap.

Gate: The contrast of interest must be supported inside the observed data region.

Explore at the correct levels

Plot heat means against heat predictors; pipe means against pipe predictors; and within-pipe specimen spread separately. Use connected or faceted plots to reveal clusters rather than hiding them.

Gate: Data errors, impossible units, missingness patterns, and influential clusters have been investigated.

Fit a primary model and planned sensitivities

Choose one primary estimand and model. Predefine complementary checks such as heat aggregation, cluster-robust covariance, mixed effects, grouped cross-validation, or cluster bootstrap.

Gate: Every model answers a named question; no method is included merely because software offers it.

Validate assumptions and stability

Check convergence, singularity, residual form, variance structure, multicollinearity, nonlinear effects, cluster influence, and sensitivity to exclusions and engineering definitions.

Gate: The conclusion survives reasonable analysis choices—or instability is clearly reported.

Translate evidence into an engineering statement

Report the contrast, effect size, interval, observed range, practical threshold, population, confounding limits, and whether the result is association or causation.

Gate: A decision-maker can act without reading the software output.

Decision point

Select the method from the question and data

Methods are complementary—not interchangeable
MethodBest fitImportant caution
Descriptive onlyVery few independent heats or severe confoundingDo not report inferential p-values.
OLS / GLMOne-level independent observations; choose Gaussian, logistic, count, or ordinal family to match YInvalid when residuals remain clustered or repeated.
Heat-level aggregationSimple heat-level association with adequate heatsLoses pipe/specimen detail; weighting needs justification.
Weighted least squaresAggregated means with meaningfully different, estimable precisionsWeights must represent inverse variance—not merely larger row counts.
Fixed-effects / blocked modelWithin-group contrasts while absorbing stable group differencesCannot estimate a predictor that is constant within the absorbed group.
Cluster-robust SEPopulation-average association with many independent clustersUse an appropriate finite-sample correction; not a cure for few heats.
GEEMarginal or population-average effectsRequires enough clusters and a chosen working correlation.
Mixed-effects modelNested variance, cluster-specific effects, unbalanced dataCheck convergence, singularity, and random-effect support.
Generalized mixed modelBinary, count, or ordinal outcomes with nested or crossed dependenceChoose the link and distribution from the response—not convenience.
Longitudinal / repeated modelOrdered measurements over time or positionExchangeable correlation may be wrong; inspect lag and time structure.
Crossed-effects modelFactors such as lab, operator, machine, or batch cross multiple groupsDo not force crossed factors into a false nesting hierarchy.
Bayesian hierarchyComplex hierarchy or sparse cells with defensible priorsReport prior sensitivity and posterior predictive checks.
GAM / nonlinear hierarchyEngineering-supported curvature or thresholdsControl flexibility and validate on unseen groups.
Survival / frailty modelTime-to-failure outcomes with censoring and clusteringOrdinary regression of observed failure times mishandles censoring.
Cluster bootstrapInterval sensitivity check with a reasonable number of heatsResample whole heats; bootstrapping cannot create missing information.

What each method estimates

Simple

Heat aggregation

Answers a between-heat question using one row per heat. Transparent and auditable, but lower-level variation is summarized.

Marginal

GEE or robust covariance

Targets the average population association while protecting uncertainty against within-heat correlation under stated conditions.

Conditional

Mixed effects

Models conditional means and partitions variation across heat, pipe, and specimen levels. It requires enough structure to estimate those components.

Your configured recommendation appears at the top of this lesson. Use this table to understand the alternatives and their assumptions. The configurator is intentionally conservative: group-count cutoffs are screening rules, not universal laws; complexity, leverage, balance, and small-sample corrections still matter.

Complete case study

From 486 specimen rows to one defensible conclusion

A fictional X65 dataset contains 36 independent heats, 2–7 pipes per heat, and three full-size transverse base-metal Charpy specimens per pipe tested at −5°C. The imbalance is intentional: real mill datasets are rarely perfectly balanced.

Units: Ca and S are stored as ppm (for example, 22 ppm)—not ambiguous decimal fractions. Orientation, specimen size, location, and temperature are separate fields.
Preview of the downloadable fictional dataset
HeatPipeSpecimenCa (ppm)S (ppm)Exit temp (°C)Charpy (J)
36 heatsIndependent units for Ca and S
162 pipes2–7 pipes nested within each heat
486 specimensThree measurements nested within each pipe

Step 1: define the question and estimand

10 ppm
Primary contrast
Estimate the average difference in base-metal Charpy energy associated with a 10 ppm higher heat-level Ca value, adjusted for S and mean exit temperature, within the ranges represented by these fictional data.

This is an observational between-heat association. It is not a causal claim and it is not a probability-of-passing model. The response is average Charpy energy in joules—not the minimum specimen result.

Step 2: classify each variable

  1. Heat: Ca, S, chemistry, caster, melting practice.
  2. Pipe: OD, gauge, rolling practice, exit and coiling temperatures.
  3. Test set: test temperature, orientation, specimen size, location.
  4. Specimen: specimen number and energy.

Step 3: validate the data structure

Mandatory pre-model checks
AuditExpected resultWhy it matters
Distinct Heat IDs36Defines the independent replication for chemistry effects.
Pipes within heat2–7; 162 totalConfirms imbalance and nested structure.
Specimens per pipeExactly 3Detects missing or duplicate specimens.
Ca values within heatOne unique valueVerifies Ca is truly heat-level.
Ca observed range12–36 ppmDefines the no-extrapolation region.
S observed range7–24 ppmDefines the no-extrapolation region.
Charpy observed range124–217 JFlags impossible units and supports context.

Step 4: quantify clustering without overstating it

Assume the fitted three-level variance model estimates heat ICC = 0.38. The average cluster contains 13.5 specimens because 486 ÷ 36 = 13.5.

Design effect
DE = 1 + (13.5 − 1)(0.38) = 5.75
Information-equivalent row count
neff ≈ 486 ÷ 5.75 = 84.5 rows

This approximation shows how correlation erodes the apparent information in 486 rows. It does not turn 84.5 into the sample size for Ca. Because Ca changes only between heats, the Ca association is supported by 36 independent Ca-bearing units.

Step 5: build the transparent heat-level sensitivity model

Aggregate to one row per heat and fit:

Mean Charpyh = β₀ + β₁(Cah) + β₂(Sh) + β₃(Mean exit temperatureh) + εh

There are 36 rows and four estimated parameters, including the intercept, so the residual degrees of freedom are:

Residual df
36 independent heats − 4 estimated parameters = 32
Reproducible heat-level sensitivity result from the supplied fictional dataset
TermEstimateSEApprox. 95% CIEngineering reading
Ca, per 1 ppm−1.03 J0.34−1.72 to −0.3310 ppm higher Ca corresponds to about 10.3 J lower mean energy.
S, per 1 ppm−2.39 J0.48−3.36 to −1.42Association is conditional on Ca and mean exit temperature.
Mean exit temperature, per 1°C−0.26 J0.14−0.55 to 0.03The interval includes zero; important effects in either direction must be judged against engineering limits.
Why not celebrate the p-values? The data are synthetic and the coefficients were embedded for teaching. In real historical data, model form, overlap, confounding, measurement error, influential heats, and selection processes determine whether such precision is credible.

Step 6: compare complementary analyses

Triangulation plan
AnalysisPurposeAgreement to seekFailure signal
Heat-level OLSTransparent between-heat sensitivity modelDirection and practical magnitudeOne heat drives the coefficient
Three-level mixed modelUse all rows and partition heat/pipe/specimen varianceSimilar fixed-effect contrast with valid convergenceSingular fit or unstable variance terms
Cluster-robust covarianceMarginal uncertainty checkInterval tells the same practical storyLarge small-sample sensitivity
Heat cluster bootstrapDistribution-free sensitivity at the heat levelMedian and percentile interval broadly agreeErratic or highly skewed coefficient distribution
Leave-one-heat-outInfluence analysisConclusion remains stableDirection or decision changes after one omission

Step 7: make the engineering interpretation

Defensible example statement: “Within this fictional 36-heat dataset, and after adjustment for sulfur and heat-mean exit temperature, a 10 ppm higher calcium value was associated with an estimated 10.3 J lower heat-average Charpy energy. The approximate 95% interval for the 10 ppm contrast was 3.3 to 17.2 J lower. This is an observational between-heat association within the 12–36 ppm Ca range; it does not establish that changing calcium would cause the predicted energy change.”

Before using the statement operationally, confirm that grade, product dimensions, rolling practice, test temperature, slab thickness, specimen size, orientation, and production period either overlap sufficiently, are controlled appropriately, or define a deliberately restricted population.

Three-heat mini-example: three heats can demonstrate the hierarchy, but an intercept plus Ca and S uses all three heat-level degrees of freedom and leaves zero residual degrees of freedom. It cannot support standard errors, confidence intervals, p-values, ICC claims, or a dependable cluster bootstrap.

Interactive laboratory

See why more rows are not always more evidence

Change the design. The lab calculates raw observations, design effect, and approximate effective sample size. It also explains why adding independent heats is usually more valuable for a heat-level chemistry effect.

Compare two ways to spend the next 36 tests

Variable-level challenge

Select the level where each variable normally changes. Your goal is to recognize when a column repeated down a spreadsheet is still a higher-level variable.

Select a variable, choose its level, then check your answer.

Evidence quality

Model validation and sensitivity checks

A coefficient table is the beginning of validation, not the end. Each diagnostic below tests a different way the conclusion could fail.

Residual behavior

  • Residual versus fitted
  • Normal Q–Q plot
  • Residuals by heat and pipe
  • Heteroscedasticity and transformations

Cluster influence

  • Leave-one-heat-out coefficients
  • Heat-level influence measures
  • Random-effect distribution
  • Influential rolling practices

Model structure

  • Convergence and singular fit
  • Random intercept versus slope
  • Crossed lab/machine effects
  • Nonlinearity and interactions

Engineering sensitivity

  • Raw versus size-normalized energy
  • Mean versus minimum individual result
  • Weighting choices
  • Missing-data and exclusion rules
Steel-specific confounding: chemistry, grade, rolling practice, product dimensions, slab thickness, test temperature, specimen size, and time may move together. A sophisticated model cannot repair a complete lack of overlap.

Diagnostic action matrix

Do not merely create the plot—decide what you will do with it
CheckAcceptable patternWarning patternResponse
Residuals vs fittedRoughly random band around zeroCurve, funnel, or groupsRevisit nonlinearity, variance structure, interactions, or omitted groups.
Q–Q plotMost points near the reference lineSevere tails or multiple regimesInspect records; consider robust sensitivity or a better response model.
Residuals by heatComparable centres and spreadsPersistent heat patternsCheck omitted heat-level drivers and random structure.
Leave-one-heat-outContrast and decision remain stableSign, magnitude, or decision flipsInvestigate leverage; report fragility and collect supporting heats.
CollinearityPredictors have useful independent overlapCa and practice or grade nearly determine each otherRestrict scope, combine scientifically, or redesign collection; do not interpret isolated coefficients.
SingularityVariance terms estimable away from boundariesVariance near zero or correlation ±1Simplify the random structure with written justification.
Grouped validationPerformance holds on unseen heatsRandom-row validation looks good but unseen-heat performance collapsesUse grouped cross-validation and reduce leakage.

Minimum sensitivity set

  • Primary analysis fitted exactly as planned.
  • One-row-per-heat model compared with the hierarchical result.
  • Every heat removed once; effect contrast and interval retained.
  • Exclusion and missing-data rules varied within defensible limits.
  • Raw and normalized Charpy definitions compared only where scientifically appropriate.
  • Product, grade, practice, and time overlap visualized.
  • Prediction assessed with entire heats held out—not random specimen rows.

Execution

Statistics Implementation

Software does not choose the experimental unit for you. Complete the hierarchy map and estimand first; then use the playbook that matches your environment.

Excel: prepare and audit the hierarchy

Excel Functions

  1. Convert the specimen table to an Excel Table with Ctrl+T; name it CharpyData.
  2. Keep explicit identifiers: Heat_ID, Pipe_ID, Specimen_ID. Never infer nesting from row order.
  3. Create a PivotTable: Insert → PivotTable. Put Heat then Pipe in Rows; place Charpy in Values as Average, Standard Deviation, and Count.
  4. Build a heat summary with one row per heat. Use the functions below to audit counts and calculate transparent summaries.
  5. Plot heat-average Charpy versus Ca and label influential heats. Use the chart for exploration, not clustered inference.
  6. Export the clean long table as CSV for a mixed model in Minitab, Python, or R.
Excel functions used in this lesson
PurposeExample formulaWhat to verify
Heat mean=AVERAGEIFS(CharpyData[Charpy_J],CharpyData[Heat_ID],A2)Response definition and exclusions are consistent.
Specimen rows per heat=COUNTIFS(CharpyData[Heat_ID],A2)Do not call this the number of independent chemistry observations.
Unique pipes per heat=COUNTA(UNIQUE(FILTER(CharpyData[Pipe_ID],CharpyData[Heat_ID]=A2)))Available in Microsoft 365.
Within-heat SD=STDEV.S(FILTER(CharpyData[Charpy_J],CharpyData[Heat_ID]=A2))This mixes pipe and specimen variation unless pipe means are separated.
Ca consistency=COUNTA(UNIQUE(FILTER(CharpyData[Ca_ppm],CharpyData[Heat_ID]=A2)))Must equal 1 if Ca is heat-level.
Lower-tail review=PERCENTILE.INC(FILTER(CharpyData[Charpy_J],CharpyData[Heat_ID]=A2),0.10)Do not substitute a percentile for a specification rule.

Excel Use Cases

Heat-level sensitivity: create one row per heat with AVERAGEIFS, verify chemistry is constant with UNIQUE, then fit the transparent regression to those independent heat rows. Lower-tail review: use PERCENTILE.INC only as a descriptive screen and keep specification pass/fail rules separate.

Excel boundary: Analysis ToolPak regression assumes independent residuals and does not directly fit a three-level mixed model. It is suitable for the one-row-per-heat sensitivity analysis, not naïve specimen-level inference.

Minitab Navigation

Minitab: mixed-effects workflow
  1. Open the long-format dataset with one row per specimen. Store Heat and Pipe as categorical identifiers; store Ca, S, temperatures, OD, and gauge as numeric columns.
  2. Verify nesting with Stat → Tables → Cross Tabulation and Chi-Square: each Pipe ID should map to one Heat ID.
  3. Explore the response with Graph → Boxplot → One Y, With Groups. Graph Charpy by Heat and then by Pipe.
  4. For a mixed model, use Stat → ANOVA → Mixed Effects Model → Fit Mixed Effects Model. Menu wording can vary by release.
  5. Enter Charpy_J as the response. Add scientifically justified fixed terms such as centred Ca, centred S, centred exit temperature, and required product controls.
  6. Specify Heat and Pipe-within-Heat as random terms only if the design supports their variance estimation. Do not add random slopes for heat-level Ca because Ca does not vary within a heat.
  7. Under Graphs, request four-in-one residual plots and residuals versus relevant predictors. Under Results, request the model summary, fixed-effect table, and variance components.
  8. Review warnings first. Then inspect variance components, fixed-effect contrasts with confidence intervals, residual plots, and unusual observations.
  9. Use Predict only for combinations represented by the fitted design. State whether prediction is for a new observation, pipe, or heat.
Output fields that matter: convergence status, variance components, fixed-effect estimate and interval for a meaningful contrast, residual degrees of freedom method, residual diagnostics, and any unusual observations. A low p-value does not override a singular fit or confounded design.

Exam Tips

ASQ and real-work connection: identify the experimental unit before selecting a method, distinguish replication from repeated measurement, and never let a large row count disguise a small number of independent groups. On an exam, these cues point to blocking, nested factors, repeated measures, or a hierarchical model; at work, they determine whether the uncertainty and engineering conclusion are defensible.
Python: complete analysis skeleton
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("hierarchical_charpy_practice.csv")
required = {"heat_id","pipe_id","charpy_j","ca_ppm","s_ppm","exit_temp_c"}
assert required.issubset(df.columns)

# Verify heat-level predictors are constant within heat.
assert df.groupby("heat_id")["ca_ppm"].nunique().max() == 1
assert df.groupby("heat_id")["s_ppm"].nunique().max() == 1

# Heat-level sensitivity model: one independent row per heat.
heat = df.groupby("heat_id", as_index=False).agg(
    charpy_mean_j=("charpy_j", "mean"),
    ca_ppm=("ca_ppm", "first"), s_ppm=("s_ppm", "first"),
    pipes=("pipe_id", "nunique"))
heat_fit = smf.ols("charpy_mean_j ~ ca_ppm + s_ppm", data=heat).fit()

# Marginal sensitivity: cluster-robust covariance by heat.
robust = smf.ols(
    "charpy_j ~ ca_ppm + s_ppm + exit_temp_c", data=df
).fit(cov_type="cluster", cov_kwds={
    "groups": df["heat_id"], "use_correction": True
})

# Random heat intercept plus pipe-within-heat variance component.
# pipe_id must be globally unique, as it is in the practice dataset.
mixed = smf.mixedlm(
    "charpy_j ~ ca_ppm + s_ppm + exit_temp_c", df,
    groups="heat_id", re_formula="1",
    vc_formula={"pipe": "0 + C(pipe_id)"}
).fit(reml=True)

print(f"rows={len(df)}, heats={df.heat_id.nunique()}, "
      f"pipes={df.pipe_id.nunique()}")
print(heat_fit.summary())
print(robust.summary())
print(mixed.summary())
R: nested mixed model and checks
library(readr)
library(dplyr)
library(lme4)
library(lmerTest)

d <- read_csv("hierarchical_charpy_practice.csv")
stopifnot(max(tapply(d$ca_ppm, d$heat_id, function(x) n_distinct(x))) == 1)

m <- lmer(charpy_j ~ ca_ppm + s_ppm + exit_temp_c +
          (1 | heat_id/pipe_id), data = d, REML = TRUE)
summary(m)
isSingular(m)
plot(m)
qqnorm(resid(m)); qqline(resid(m))

# Leave one entire heat out at a time.
loo <- lapply(unique(d$heat_id), function(h) {
  fit <- lm(charpy_j ~ ca_ppm + s_ppm + exit_temp_c,
            data = filter(d, heat_id != h))
  c(omitted_heat = h, ca = coef(fit)["ca_ppm"])
})
do.call(rbind, loo)
Correct cluster-bootstrap pattern
# Each sampled heat occurrence receives a NEW bootstrap cluster ID.
import numpy as np

rng = np.random.default_rng(42)
heat_ids = df["heat_id"].unique()
boot_coefs = []

for b in range(2000):
    sampled = rng.choice(heat_ids, len(heat_ids), replace=True)
    pieces = []
    for instance, heat_id in enumerate(sampled):
        part = df.loc[df.heat_id.eq(heat_id)].copy()
        part["boot_heat_id"] = f"b{instance}"  # preserves multiplicity
        pieces.append(part)
    boot = pd.concat(pieces, ignore_index=True)
    bh = boot.groupby("boot_heat_id", as_index=False).agg(
        charpy_mean_j=("charpy_j", "mean"),
        ca_ppm=("ca_ppm", "first"), s_ppm=("s_ppm", "first"))
    if bh[["ca_ppm", "s_ppm"]].drop_duplicates().shape[0] > 3:
        fit = smf.ols("charpy_mean_j ~ ca_ppm + s_ppm", bh).fit()
        boot_coefs.append(fit.params["ca_ppm"])

print(np.quantile(boot_coefs, [0.025, 0.5, 0.975]))

Decision language

When you see this, it means this

Interpretation guide
When you see thisIt means thisAction
High heat ICCResults from the same heat are strongly correlated.Model heat clustering; do not count specimens as independent chemistry replicates.
Singular mixed-model fitThe proposed random structure may exceed what the data support.Simplify with engineering justification; do not hide the warning.
Large leave-one-heat-out changeOne heat strongly influences the conclusion.Investigate data quality and report sensitivity.
OLS and mixed-model SE differClustering or variance structure affects uncertainty.Use the design-respecting result.
No overlap across practicesPractice and chemistry effects are confounded.Restrict conclusions or collect better-balanced data.
Interval includes zero but excludes large harmNo clear direction, yet practically important harm may be unlikely.Discuss engineering bounds, not only “not significant.”
Random-row accuracy exceeds grouped-by-heat accuracyThe original validation leaked heat-specific information.Use grouped folds and report new-heat performance.
Random heat variance is near zeroAfter fixed effects, little additional heat-level variance was estimated.Check singularity and whether the random term is supported; do not conclude heats are identical.
Ca coefficient changes sharply after adding practiceThe unadjusted result was sensitive to practice composition.Show both models, inspect overlap, and narrow the claim.
Confidence interval is narrow but outside historical rangeThe numerical prediction is extrapolation despite apparent precision.Do not use it as validated evidence; collect supporting data.
Reporting template: “After controlling for product dimensions, test temperature, and rolling practice, a 10 ppm increase in heat-level Ca was associated with an estimated X J change in average Charpy energy (95% interval Y to Z J). This is a heat-level observational association and does not establish causation.”

Failure prevention

Common mistakes, warning signs, and corrections

Calculation error: using specimen count as heat-level n

Why wrong: repeated Ca and S values do not create independent chemistry contrasts. Recognize it: the same predictor value appears on many rows with the same Heat ID. Prevent it: count distinct heats, show the hierarchy, and use cluster-aware inference.

Interpretation error: association becomes causation

Why wrong: grade, practice, dimensions, and time may jointly influence chemistry and Charpy. Recognize it: words such as “caused,” “improved,” or “reduced” appear in an observational result. Prevent it: use “was associated with” and state the design limits.

Assumption error: bootstrap will rescue three heats

Why wrong: resampling cannot create new independent information. Recognize it: thousands of bootstrap draws are used to disguise a single-digit cluster count. Prevent it: keep the analysis descriptive or collect more heats.

Software-output error: ignoring convergence or singular-fit warnings

Why wrong: parameters may sit on a boundary or be poorly identified. Recognize it: warnings, near-zero variances, correlations near ±1, or unstable estimates. Prevent it: inspect warnings first and simplify with engineering justification.

Weighting error: calling inverse-variance WLS automatically optimal

Why wrong: estimated variances can be noisy and may weight large clusters in unintended ways. Recognize it: weights are applied without a variance model or sensitivity check. Prevent it: define the estimand, justify weights, and compare unweighted and defensibly weighted results.

Data error: mixing ppm, wt%, and mass fraction

Why wrong: unit errors change a value by factors of 100 or 10,000. Recognize it: a column called “Ca” contains decimals without units. Prevent it: use names such as Ca_ppm. Remember: 22 ppm = 0.0022 wt% = 0.000022 mass fraction.

Engineering error: mixing incompatible Charpy definitions

Why wrong: base metal, weld, fusion line, HAZ, orientation, specimen size, and test temperature represent different populations. Recognize it: the same response column silently combines them. Prevent it: standardize or stratify definitions before modeling.

Validation error: splitting specimen rows at random

Why wrong: specimens from one heat can enter both training and validation sets, leaking heat-specific information. Recognize it: unusually strong validation performance that drops on a new production period. Prevent it: group cross-validation by Heat ID.

Exam trap: random intercept versus random slope

A heat-level Ca value cannot support a within-heat Ca slope because Ca does not vary inside a heat. A random Ca slope by heat is therefore not identified from this design. Random slopes require within-cluster predictor variation.

Apply the workflow

Engineering review challenge

Scenario: 120 Charpy specimens came from 5 heats. Ca and S are measured once per heat. Exit temperature varies by pipe. A colleague fits specimen-level OLS with Ca, S, and exit temperature, reports p = 0.002 for Ca, and recommends changing the calcium target.

Your review

  1. Identify the experimental unit for Ca.
  2. Calculate the heat-level residual df for an intercept + Ca + S model.
  3. Explain why the reported p-value is suspect.
  4. State what analysis is defensible now.
  5. State what new data would materially improve the decision.

Reviewer standard

  • Names the correct independent unit
  • Shows the df calculation
  • Separates descriptive from inferential claims
  • Explains why a mixed model cannot create heats
  • Recommends a better data design

Take it to work

Field checklist for hierarchical engineering data

  • Match the analysis unit to the level at which the predictor varies.
  • Heat-level chemistry needs independent heats.
  • Pipe and specimen replication estimate lower-level variation but do not replace heats.
  • Use descriptive, marginal, and hierarchical methods according to the goal.
  • Check convergence, influence, overlap, missingness, and engineering definitions.
  • Cluster bootstrap resamples whole heats and needs a reasonable number of them.
  • Report effect size, uncertainty, practical meaning, range, and causal limits.
Remember this: count the units that received or carry the predictor—not the rows in the spreadsheet.

One-page decision rule

Level → n → model
First: identify the level where the predictor changes. Second: count independent units at that level. Third: choose a model whose uncertainty respects the resulting dependence. If overlap is absent or independent units are too few, stop at a descriptive conclusion.

Pre-release analysis checklist

  • The engineering response and decision threshold are defined.
  • Heat, pipe, test-set, specimen, and crossed factors are mapped.
  • Distinct independent units—not rows—are counted for every key predictor.
  • Units and chemistry conversions are explicit.
  • Grade, practice, dimensions, temperature, specimen size, and time overlap are reviewed.
  • The primary estimand and model are named before interpretation.
  • Convergence, singularity, residuals, influence, and grouped validation are checked.
  • Effect size and uncertainty are translated into a meaningful engineering contrast.
  • Extrapolation and causal limitations are stated.
  • The analysis can be reproduced from the dataset, code, and decision log.

Suggested next lesson: Building and validating mixed-effects models in Minitab, Python, and R.

References and further study

  • Pinheiro, J. C. & Bates, D. M. Mixed-Effects Models in S and S-PLUS. Springer.
  • Gelman, A. & Hill, J. Data Analysis Using Regression and Multilevel/Hierarchical Models. Cambridge University Press.
  • West, B. T., Welch, K. B. & Galecki, A. T. Linear Mixed Models: A Practical Guide Using Statistical Software. CRC Press.
  • Official documentation for Minitab mixed-effects models, Python statsmodels MixedLM, and R lme4.

Knowledge check

Check your understanding

Comprehension quiz

Pick the strongest answer, then submit. Explanations appear after you submit.

1. What is the primary independent unit for a heat-level Ca effect?
2. With m̄ = 10 and ICC = 0.40, what is the design effect?
3. Which method directly estimates nested variance components?
4. What must a heat-level cluster bootstrap resample?
5. Ca occurs only in one rolling practice. What is the safest conclusion?
← Back to Data Analytics lessons