Solutions · 1. Dimensional analysis: the Buckingham Pi theorem and Taylor’s estimate of the Trinity yield
Worked solutions to the three exercises of Lecture 1. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
try: # use the installed package, or the copy in this repository
import engthink
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engthink" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engthink.git"], check=True)
import engthink
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engthink import (constants_benchmarks, divide_spatial, dynamic_optimality, emergence_verification,
greedy_heuristic_search, information_streams, invariants_complexity, reductions_constraints,
representation_scaling)
from engthink.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
heading("Demonstration 1: Exact rational nullspaces and grid-sweep compression across CANONICAL_DIM_MATRICES")
g_pts = 10
print(f"{'Physical System':30s} | {'n':>2s} | {'rank':>4s} | {'p=n-r':>5s} | {'Sweep Gain':>11s} | {'Primitive Integer Pi Basis'}")
print("-" * 110)
for key, spec in constants_benchmarks.CANONICAL_DIM_MATRICES.items():
res = representation_scaling.buckingham_pi_nullspace(spec["matrix"], spec["variables"])
n_v = len(spec["variables"])
r_d = res["rank"]
p_g = res["n_pi_groups"]
# Independent input sweep compression for predicting 1 target variable: G^(n-1) -> G^(p-1) = G^r:
sweep_gain = g_pts ** r_d
groups_str = " ; ".join(res["formatted_groups"])
print(f"{key:30s} | {n_v:2d} | {r_d:4d} | {p_g:5d} | {sweep_gain:9,d}x | {groups_str}")
assert res["nullspace_residual"] == 0.0
assert p_g == n_v - r_d
blast_res = representation_scaling.buckingham_pi_nullspace(
constants_benchmarks.CANONICAL_DIM_MATRICES["taylor_blast_wave"]["matrix"],
constants_benchmarks.CANONICAL_DIM_MATRICES["taylor_blast_wave"]["variables"],
)
assert blast_res["n_pi_groups"] == 1
assert blast_res["pi_exponents"].tolist() == [[5, -2, -1, 1]]
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Use representation_scaling.buckingham_pi_nullspace on (T_period, L, m, g) and CANONICAL_DIM_MATRICES['capillary_droplet_oscillation'], and verify numerical invariance of the capillary -groups across SI, CGS, and Imperial (slug, ft, s) unit systems.
heading("Exercise 1: Pendulum mass independence, capillary droplets and multi-unit invariance")
# (a) Simple pendulum variables: [T_period (s), L (m), m (kg), g (m/s^2)] over [M, L, T]:
d_pend = np.array([
[0, 0, 1, 0], # M: only m has mass
[0, 1, 0, 1], # L
[1, 0, 0, -2], # T
], dtype=int)
pend_res = representation_scaling.buckingham_pi_nullspace(d_pend, ["T_period", "L", "m", "g"])
print("Pendulum Pi group:", pend_res["formatted_groups"], "| Exponents:", pend_res["pi_exponents"].tolist())
assert pend_res["n_pi_groups"] == 1
assert pend_res["pi_exponents"][0, 2] == 0 # Mass m strictly has exponent 0
# (b) Capillary droplet oscillation: [omega, R, rho, sigma, mu] over [M, L, T]:
cap_spec = constants_benchmarks.CANONICAL_DIM_MATRICES["capillary_droplet_oscillation"]
cap_res = representation_scaling.buckingham_pi_nullspace(cap_spec["matrix"], cap_spec["variables"])
print("Capillary Droplet Pi groups:", cap_res["formatted_groups"])
# Verify exact numerical invariance of Pi_1 and Pi_2 across SI -> CGS -> Imperial (slug, ft, s):
val_si = np.array([1250.0, 1.2e-3, 998.0, 0.0728, 1.00e-3]) # [rad/s, m, kg/m^3, N/m (kg/s^2), Pa*s (kg/(m*s))]
# Unit conversion multipliers for base dimensions (M_scale, L_scale, T_scale):
unit_systems = {
"SI (kg, m, s)": (1.0, 1.0, 1.0),
"CGS (g, cm, s)": (1000.0, 100.0, 1.0),
"Imperial (slug, ft, s)": (1.0 / 14.5939029, 1.0 / 0.3048, 1.0),
}
pi_evals = {}
for sys_name, (m_sc, l_sc, t_sc) in unit_systems.items():
base_scales = np.array([m_sc, l_sc, t_sc])
var_scales = np.prod(base_scales[:, None] ** cap_spec["matrix"], axis=0)
val_converted = val_si * var_scales
pis = np.array([np.prod(val_converted ** exp_row) for exp_row in cap_res["pi_exponents"]])
pi_evals[sys_name] = pis
print(f" {sys_name:24s} -> Pi values = {pis}")
assert np.allclose(pi_evals["SI (kg, m, s)"], pi_evals["CGS (g, cm, s)"], rtol=1e-14)
assert np.allclose(pi_evals["SI (kg, m, s)"], pi_evals["Imperial (slug, ft, s)"], rtol=1e-14)
Exercise 1: Pendulum mass independence, capillary droplets and multi-unit invariance
====================================================================================
Pendulum Pi group: ['T_period^2 * g / (L)'] | Exponents: [[2, -1, 0, 1]]
Capillary Droplet Pi groups: ['sigma / (omega^2 * R^3 * rho)', 'mu / (omega * R^2 * rho)']
SI (kg, m, s) -> Pi values = [0.027017 0.00055667]
CGS (g, cm, s) -> Pi values = [0.027017 0.00055667]
Imperial (slug, ft, s) -> Pi values = [0.027017 0.00055667]
Explanation. Because mass appears only in column m of the pendulum matrix ([0, 0, 1, 0]), forces , proving without solving Newton’s ODE that is independent of mass even at large amplitudes . For capillary droplets, scaling base units multiplies by , which cancels identically via .
Exercise 2¶
Problem. Audit (a) omitting gravity in free-surface ship hull scaling (1:25 tow-tank test of a ship cruising at ), and (b) adding a redundant Force row (Force = M L T^-2) to a 4-variable Hookean spring-mass matrix where naive fails.
heading("Exercise 2: Missing Froude number in ship wave drag and redundant base dimensions (rank < m)")
# (a) Ship drag WITHOUT gravity g: [F_drag, rho, U, L, mu] vs WITH gravity g: [F_drag, rho, U, L, mu, g]
d_ship_no_g = np.array([
[1, 1, 0, 0, 1], # M
[1, -3, 1, 1, -1], # L
[-2, 0, -1, 0, -1], # T
], dtype=int)
d_ship_with_g = np.column_stack([d_ship_no_g, [0, 1, -2]])
res_no_g = representation_scaling.buckingham_pi_nullspace(d_ship_no_g, ["F", "rho", "U", "L", "mu"])
res_with_g = representation_scaling.buckingham_pi_nullspace(d_ship_with_g, ["F", "rho", "U", "L", "mu", "g"])
l_ship, u_ship, g_acc = 150.0, 10.0, 9.81
l_tow = l_ship / 25.0 # 6.0 m tow-tank model in same water (nu_m == nu_p)
u_tow_re_only = u_ship * (l_ship / l_tow) # Matching Re alone demands 250 m/s
u_tow_froude = u_ship * math.sqrt(l_tow / l_ship) # Matching Fr = U/sqrt(g*L) demands 2.0 m/s
fr_ship = u_ship / math.sqrt(g_acc * l_ship)
fr_re_mistake = u_tow_re_only / math.sqrt(g_acc * l_tow)
print("Without g groups :", res_no_g["formatted_groups"])
print("With g groups :", res_with_g["formatted_groups"])
print(f"1:25 Tow Tank: Re-matching speed = {u_tow_re_only:.1f} m/s (Fr = {fr_re_mistake:.2f} vs ship Fr = {fr_ship:.3f})")
print(f"Froude-matched tow speed = {u_tow_froude:.2f} m/s (William Froude's residual-wave-drag law)")
# (b) Redundant 4th row [M, L, T, Force] for spring oscillator (omega [T^-1], m [M], k_spring [Force * L^-1], A_amp [L])
# Expressing k_spring as Force^1 * L^-1 while m is M^1 — Wait: if Force is related via Newton F = M L T^-2,
# writing each column in [M, L, T, (M+L-2T linear combo)] creates rank 3 < m = 4
d_3row = np.array([
[0, 1, 1, 0], # M: [omega, m, k_spring, x0] -> wait: let's include g or damping c [M T^-1]
[0, 0, 0, 1], # L
[-1, 0, -2, 0], # T
], dtype=int)
# Row 4 is a redundant linear combination (e.g. Energy-dimension row = 1*M + 2*L - 2*T):
d_redundant_4x4 = np.vstack([d_3row, d_3row[0] + 2 * d_3row[1] - 2 * d_3row[2]])
naive_n_minus_m = d_redundant_4x4.shape[1] - d_redundant_4x4.shape[0]
red_res = representation_scaling.buckingham_pi_nullspace(d_redundant_4x4, ["omega", "m", "k_s", "x0"])
print(f"\nRedundant 4x4 matrix: naive (n - m) = {naive_n_minus_m} groups, TRUE rank = {red_res['rank']} -> {red_res['n_pi_groups']} Pi group: {red_res['formatted_groups']}")
assert res_no_g["n_pi_groups"] == 2 and res_with_g["n_pi_groups"] == 3
assert fr_re_mistake > 100.0 * fr_ship
assert naive_n_minus_m == 0 and red_res["rank"] == 3 and red_res["n_pi_groups"] == 1
Exercise 2: Missing Froude number in ship wave drag and redundant base dimensions (rank < m)
============================================================================================
Without g groups : ['rho * U^2 * L^2 / (F)', 'mu^2 / (F * rho)']
With g groups : ['rho * U^2 * L^2 / (F)', 'mu^2 / (F * rho)', 'F * g^2 / (rho * U^6)']
1:25 Tow Tank: Re-matching speed = 250.0 m/s (Fr = 32.59 vs ship Fr = 0.261)
Froude-matched tow speed = 2.00 m/s (William Froude's residual-wave-drag law)
Redundant 4x4 matrix: naive (n - m) = 0 groups, TRUE rank = 3 -> 1 Pi group: ['k_s / (omega^2 * m)']
Explanation. Omitting silently assumes surface gravity waves carry zero energy, and leads to towing a model at ( against 0.26 for the ship); matching gives . In part (b), Buckingham’s theorem is , never ; linearly dependent dimensional rows reduce , which exact RREF detects automatically.
Exercise 3¶
Problem. Implement nondimensional_data_collapse_fitter(dim_matrix, data_columns, target_col=0, var_names=None) that isolates target_col into (exponent +1) by placing repeating basis variables before target_col, computes all input , and fits in log space. Test on synthetic multi-fluid convective heat-transfer data governed by Dittus–Boelter .
heading("Exercise 3: Implement it yourself — automated Buckingham-Pi power-law data fitter")
def nondimensional_data_collapse_fitter(
dim_matrix: np.ndarray,
data_columns: np.ndarray,
target_col: int = 0,
var_names: list[str] | None = None,
) -> dict:
"""Isolate target_col in a dimensionless output Pi group and fit Pi_out = C * prod(Pi_k^alpha_k)."""
d_mat = np.asarray(dim_matrix, dtype=int)
x_data = np.asarray(data_columns, dtype=float)
m_dims, n_vars = d_mat.shape
if x_data.ndim != 2 or x_data.shape[1] != n_vars or np.any(x_data <= 0.0):
raise ValueError("data_columns must be strictly positive of shape (n_samples, n_vars).")
names = [f"v{j}" for j in range(n_vars)] if var_names is None else list(var_names)
# Permute target_col to the LAST column so pivot selection picks repeating variables from non-target columns first:
other_cols = [c for c in range(n_vars) if c != target_col]
perm = other_cols + [target_col]
inv_perm = np.argsort(perm)
res_p = representation_scaling.buckingham_pi_nullspace(d_mat[:, perm], [names[c] for c in perm])
if (n_vars - 1) not in res_p["free_columns"]:
raise ValueError("target_col cannot be made dimensionless by the remaining variables")
pi_exp_perm = res_p["pi_exponents"].astype(float)
# Last row corresponds to free column (n_vars - 1) == target_col; normalize so target_col has exponent +1.0:
out_row_p = pi_exp_perm[-1] / pi_exp_perm[-1, -1]
in_rows_p = pi_exp_perm[:-1]
out_exp_orig = out_row_p[inv_perm]
in_exps_orig = in_rows_p[:, inv_perm]
log_x = np.log(x_data)
log_pi_out = log_x @ out_exp_orig
log_pi_in = log_x @ in_exps_orig.T # Shape (n_samples, p - 1)
design = np.column_stack([np.ones(x_data.shape[0]), log_pi_in])
coeffs, _, _, _ = np.linalg.lstsq(design, log_pi_out, rcond=None)
pred_log_out = design @ coeffs
ss_res = float(np.sum((log_pi_out - pred_log_out) ** 2))
ss_tot = float(np.sum((log_pi_out - np.mean(log_pi_out)) ** 2))
r2_log = 1.0 - ss_res / max(ss_tot, 1.0e-30)
# Implied dimensional power-law exponents on original variables: h ~ C * prod_{j != target} q_j^beta_j
implied_var_exponents = -out_exp_orig.copy()
implied_var_exponents[target_col] = 0.0
for k_idx, alpha_k in enumerate(coeffs[1:]):
implied_var_exponents += alpha_k * in_exps_orig[k_idx]
return {
"prefactor_C": float(math.exp(coeffs[0])),
"pi_alphas": coeffs[1:],
"out_pi_exponents": out_exp_orig,
"in_pi_exponents": in_exps_orig,
"implied_variable_exponents": implied_var_exponents,
"r2_log_space": r2_log,
}
# Test on 7-variable Convective Heat Transfer: Nu = h*D/k = 0.023 * Re^0.80 * Pr^0.40
# Implies h = 0.023 * D^(-0.20) * k^(0.60) * rho^(0.80) * U^(0.80) * mu^(-0.40) * cp^(0.40)
conv = constants_benchmarks.CANONICAL_DIM_MATRICES["convective_heat_transfer"]
rng_ht = np.random.default_rng(17)
n_samp = 240
D_v = 10.0 ** rng_ht.uniform(-2.0, -0.3, size=n_samp)
k_v = 10.0 ** rng_ht.uniform(-1.6, 1.8, size=n_samp)
rho_v = 10.0 ** rng_ht.uniform(0.0, 3.1, size=n_samp)
U_v = 10.0 ** rng_ht.uniform(-0.3, 1.4, size=n_samp)
mu_v = 10.0 ** rng_ht.uniform(-4.8, -1.5, size=n_samp)
cp_v = 10.0 ** rng_ht.uniform(2.9, 3.7, size=n_samp)
re_v = rho_v * U_v * D_v / mu_v
pr_v = cp_v * mu_v / k_v
h_v = (k_v / D_v) * (0.023 * (re_v ** 0.80) * (pr_v ** 0.40))
data_7d = np.column_stack([h_v, D_v, k_v, rho_v, U_v, mu_v, cp_v])
fit_ht = nondimensional_data_collapse_fitter(conv["matrix"], data_7d, target_col=0, var_names=conv["variables"])
expected_var_exps = np.array([0.0, -0.20, 0.60, 0.80, 0.80, -0.40, 0.40])
print(f"Recovered prefactor C : {fit_ht['prefactor_C']:.6f} (Exact Dittus-Boelter = 0.023000)")
print(f"Log-space collapse R^2 : {fit_ht['r2_log_space']:.12f}")
print("Recovered variable exponents :", np.round(fit_ht["implied_variable_exponents"], 6))
print("Exact Dittus-Boelter exponents :", expected_var_exps)
assert np.isclose(fit_ht["prefactor_C"], 0.023, rtol=1e-10)
assert np.allclose(fit_ht["implied_variable_exponents"], expected_var_exps, atol=1e-10)
assert fit_ht["r2_log_space"] > 1.0 - 1.0e-12
Exercise 3: Implement it yourself — automated Buckingham-Pi power-law data fitter
=================================================================================
Recovered prefactor C : 0.023000 (Exact Dittus-Boelter = 0.023000)
Log-space collapse R^2 : 1.000000000000
Recovered variable exponents : [ 0. -0.2 0.6 0.8 0.8 -0.4 0.4]
Exact Dittus-Boelter exponents : [ 0. -0.2 0.6 0.8 0.8 -0.4 0.4]
Summary. By permuting target_col to the rightmost column before rational RREF, automatically isolates the target physical quantity (recovering Nusselt number ) while span the dimensionless predictors. Regressing in 2-D space instead of raw 6-D variable space enforces exact physical unit consistency even when experimental data are noisy or scarce.