Validation and uncertainty of a discovered law#

A discovered equation is a nonlinear regression model and can be checked like one. This example fits the Arrhenius law to noisy rate constants, inspects the residuals (normality, autocorrelation, heteroscedasticity), and computes Wald, profile-likelihood and bootstrap intervals of the parameters (Bates and Watts, 1988) and the prediction band of the model.

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.analysis import confidence_intervals, prediction_intervals, residual_diagnostics

rng = np.random.default_rng(4)
T = np.sort(rng.uniform(300, 420, 40))
k = 3.0e6 * np.exp(-6000 / T) * (1 + 0.06 * rng.normal(size=40))
X = T.reshape(-1, 1)

Fitting the structure and checking the residuals#

arr = eq.Equation.from_string("1e6*exp(-5000/T)", feature_names=["T"]).refit(X, k, restarts=5, random_state=0)
print(arr)
diag = residual_diagnostics(k, arr.predict(X), order=T)
print({key: round(v, 3) for key, v in diag.items()})
2.644e+06 * exp(-5946 / T)
{'mean': -0.001, 'std': 0.054, 'skewness': 1.104, 'kurtosis': 3.228, 'shapiro_p': 0.0, 'durbin_watson': 2.966, 'ljung_box_q': 21.925, 'ljung_box_p': 0.015, 'breusch_pagan_lm': 15.988, 'breusch_pagan_p': 0.0}

Parameter intervals and the prediction band#

for method in ("wald", "profile", "bootstrap"):
    print(method)
    print(confidence_intervals(arr, X, k, method=method, n_boot=200).round(3))
yhat, lo, hi = prediction_intervals(arr, X, k, X, kind="prediction")
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
eq.viz.plot_prediction_band(T, k, yhat, lo, hi, ax=axs[0], label="95 % prediction band")
axs[0].set_xlabel("T (K)")
axs[0].set_ylabel("rate constant k")
cis = {m: confidence_intervals(arr, X, k, method=m, n_boot=200) for m in ("wald", "profile", "bootstrap")}
names = ["$k_0$", "$E/R$"]
for j in range(len(names)):
    for i, (m, ci) in enumerate(cis.items()):
        v, lo_, hi_ = ci.loc[j, "value"], ci.loc[j, "lower"], ci.loc[j, "upper"]
        axs[1].errorbar([i + 4 * j], [v / abs(v)], yerr=[[(v - lo_) / abs(v)], [(hi_ - v) / abs(v)]], fmt="o", color=eq.viz.OKABE_ITO[i], capsize=4, label=m if j == 0 else None)
axs[1].set_xticks([1, 5])
axs[1].set_xticklabels(names)
axs[1].set_ylabel("interval / estimate")
axs[1].legend(frameon=False, fontsize=8)
fig.tight_layout()
eq.viz.plot_residuals(k, arr.predict(X))
  • plot 33 validation uncertainty
  • plot 33 validation uncertainty
wald
  parameter        value           se       lower        upper
0   theta_0  2644082.551  1027943.107  563120.524  4725044.578
1   theta_1    -5946.444      159.587   -6269.511    -5623.377
profile
  parameter        value           se        lower        upper
0   theta_0  2644082.551  1027943.107  1239837.260  5957979.299
1   theta_1    -5946.444      159.587    -6280.221    -5635.845
bootstrap
  parameter        value           se        lower        upper
0   theta_0  2644082.551  1018950.251  1362181.312  5168841.609
1   theta_1    -5946.444      146.802    -6227.769    -5675.302

<Figure size 800x320 with 2 Axes>

Parameter study: sample size and interval width#

ns = [10, 20, 40, 80, 160]
width = []
for n in ns:
    Tn = np.sort(rng.uniform(300, 420, n))
    kn = 3.0e6 * np.exp(-6000 / Tn) * (1 + 0.06 * rng.normal(size=n))
    an = arr.refit(Tn.reshape(-1, 1), kn)
    ci = confidence_intervals(an, Tn.reshape(-1, 1), kn, method="profile")
    width.append(float((ci.upper - ci.lower).iloc[1]))
print("samples", ns, "profile interval width of E/R", np.round(width, 1).tolist())
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.loglog(ns, width, "o-", color="#285780", label="profile interval of E/R")
ax.loglog(ns, width[0] * np.sqrt(ns[0] / np.array(ns)), color="#6B7785", ls="--", label="$1/\\sqrt{N}$")
ax.set_xlabel("number of measurements")
ax.set_ylabel("interval width")
ax.legend(frameon=False, fontsize=8)
plt.show()
plot 33 validation uncertainty
samples [10, 20, 40, 80, 160] profile interval width of E/R [767.7, 813.1, 587.5, 441.4, 221.3]

Total running time of the script: (0 minutes 0.956 seconds)

Gallery generated by Sphinx-Gallery