Estimate#
Parameter estimation on Monte-Carlo sweeps: laws, hidden terms, fractions.
Given results y_i = f(x_i) produced by tinto.runners.mc() over a
swept parameter (graph size n, palette size k, scheduler probability
p, …), this module answers two questions:
Does
ffollow a given law, or does it hide an extra term? —wls()fits an arbitrary linear basis by weighted least squares (affinea*x + bis just the default basis), andtest_extra_term()runs a likelihood-ratio test against the same model augmented by a suspect termc*g(x)(typicallyg(x) = x*log x, orx**-3for a hidden1/k**3).If the law holds, what are the exact coefficients? —
simplest_in()returns the simplest fraction inside an interval (Stern-Brocot), andrecover()turns a fitted coefficient and its error bar into the simplest compatible fraction.
Everything hinges on one input: a correct per-point error bar sigma_i.
For a mean estimated over n_trials replicas this is the standard error of
the mean, sigma_i = sqrt(var_i / n_trials) — see
tinto.experiments.Experiment.fit(), which assembles it from the
var already returned by tinto.runners.mc(). The fit is run with
absolute_sigma=True semantics: the sigma_i are trusted as given and
the covariance is not rescaled, so the goodness-of-fit (chi2,
pvalue) stays meaningful.
The basis is deliberately generic. f(n) affine laws use the default
affine_basis(); an inverse-power law such as
f(k) = n*(1/k + 1/(3*k**2)) uses power_basis() with exponents
[-1, -2]. The fraction machinery then applies to each coefficient
unchanged.
Reading the outputs (consolidated from the reference recipe):
chi2_red~ 1 (withinsqrt(2/dof)) when the model is right and thesigma_iare correct;>> 1means a hidden term or under-estimatedsigma_i;<< 1means over-estimatedsigma_i.pvalueoffit()is the global goodness-of-fit; tiny means something is hiding.t = c/scoftest_extra_term()is the signal-to-noise of the suspect term:|t| <~ 2no evidence,|t| >~ 3the term is real.
- tinto.estimate.affine_basis(var='n')[source]#
Return the affine basis
[x, 1]— dominant term first.The linear term comes first (the leading behaviour of the laws this module hunts), the constant second, so the fitted coefficients read
[slope, intercept]. Each column carries a__name__(var and"1") so thatbasis_names()— and thereforetinto.experiments.Experiment.report()— labels the coefficients automatically.- Parameters:
var (
str, default=’n’) – Symbol used to name the linear column."n"matches the usual graph-size sweep.
Examples
>>> import numpy as np >>> b = affine_basis() >>> len(b) 2 >>> [f.__name__ for f in b] ['n', '1'] >>> x = np.array([0.0, 1.0, 2.0]) >>> b[0](x).tolist() [0.0, 1.0, 2.0] >>> b[1](x).tolist() [1.0, 1.0, 1.0] >>> [f.__name__ for f in affine_basis(var="k")] ['k', '1']
- tinto.estimate.basis_names(basis=None, var='n')[source]#
Best-effort coefficient names for a linear basis.
Reads the
__name__attached to each basis column (the built-inaffine_basis()andpower_basis()set meaningful ones). Anonymous columns — a barelambdawhose__name__is"<lambda>", or anything without one — fall back to a positional"c<i>".- Parameters:
basis (list of callables, optional) – The basis to name.
Noneis treated as the affine default and returns[var, "1"](dominant term first, matchingaffine_basis()).var (
str, default=’n’) – Variable symbol used for the affine default’s linear term.
- Returns:
One name per basis column, aligned with the fitted coefficients.
- Return type:
list of
str
Examples
>>> basis_names() ['n', '1'] >>> basis_names(power_basis([-1, -2])) ['n^-1', 'n^-2'] >>> basis_names(affine_basis(var="k")) ['k', '1']
A custom basis of anonymous lambdas gets positional names:
>>> basis_names([lambda v: v, lambda v: v * v]) ['c0', 'c1']
- tinto.estimate.fit(x, y, sigma, basis=None)[source]#
Fit
yon a linear basis and report goodness-of-fit.Thin wrapper around
wls()that defaults to the affine basis and packages the per-coefficient error bars and the chi-square statistics into a single dict.- Parameters:
x (array_like) – See
wls().y (array_like) – See
wls().sigma (array_like) – See
wls().basis (list of callables, optional) – Defaults to
affine_basis()(a*x + b).
- Returns:
beta(coefficients),cov(covariance),sigma_beta(sqrt(diag(cov))),chi2,dof,chi2_red(chi2 / dof),pvalue(stats.chi2.sf(chi2, dof)), andresid(normalized residuals).- Return type:
Examples
Affine fit (the default basis), exact data:
>>> import numpy as np >>> x = np.array([0.0, 1.0, 2.0, 3.0]) >>> y = 2 * x + 1 >>> r = fit(x, y, np.ones_like(x)) >>> np.round(r["beta"], 6).tolist() [2.0, 1.0] >>> r["dof"] 2 >>> bool(r["chi2_red"] < 1e-20) True >>> round(r["pvalue"], 6) 1.0
Inverse-power fit
f(k) = n*(1/k + 1/(3*k**2))withn = 10; dividing the coefficients bynrecovers1and1/3:>>> k = np.array([3.0, 4.0, 5.0, 6.0]) >>> n = 10 >>> y = n * (1 / k) + n / (3 * k**2) >>> r = fit(k, y, np.ones_like(k), power_basis([-1, -2])) >>> [round(float(b) / n, 6) for b in r["beta"]] [1.0, 0.333333]
- tinto.estimate.fit_fractions(x, y, sigma, basis=None, k=2, max_chi2_red=5.0, max_denominator=64, resolution=1.0)[source]#
Recover exact fractions coefficient by coefficient (anchor & refit).
A single joint fit gives unbiased coefficients but leaves the sub-leading ones noisy and correlated with the leading ones, so
recover()often collapses a busy fraction (say-7/27) onto a simpler neighbour (-1/4). This routine peels the coefficients off one at a time instead:jointly fit every still-free coefficient (never one in isolation — fitting a term alone biases it by the terms you drop),
anchor the one most confidently a simple fraction (smallest denominator, then smallest relative error), fixing it to that exact value,
refit the remaining free coefficients jointly — the anchored term’s contribution is subtracted from
yand its correlated degree of freedom is gone, so the others tighten honestly,repeat until no free coefficient lands cleanly on a fraction.
A coefficient is anchored only if its precision actually resolves its denominator: fractions with denominator at most
qare spaced by about1/q**2, so the confidence interval must be narrower than that grid,k*sigma*q**2 < resolution. This is what tells a well-determined busy fraction (a slope of8/27, tiny relative error) apart from an under-determined one of the same denominator (a sub-leading-7/27whose error bar spans several competing fractions): the former is anchored, the latter is left free. The check is deliberately conservative — anchoring a wrong fraction would bias every later refit — so when the data cannot resolve a coefficient it staysNoneand its float estimate is returned instead.- Parameters:
x (array_like) – See
wls().y (array_like) – See
wls().sigma (array_like) – See
wls().basis (list of callables, optional) – Defaults to
affine_basis().k (
float, default=2) – Confidence half-width in error bars, forwarded torecover().max_chi2_red (
float, default=5.0) – If a refit’s reduced chi-square exceeds this, peeling stops (the model is judged incomplete on the remaining terms).max_denominator (
int, default=64) – A candidate fraction with a larger denominator is never anchored.resolution (
float, default=1.0) – Resolution budget: a denominator-qfraction is anchored only ifk*sigma*q**2 < resolution. Smaller is stricter.
- Returns:
fractions(list aligned with basis: aFractionfor anchored coefficients,Nonefor those left free),beta(full coefficient vector, anchored entries as exact floats),sigma_beta(0for anchored, fitted error for free),order(basis indices in the order they were anchored), the final-modelchi2,dof,chi2_red,pvalue, andresid(normalized residuals(y - model) / sigmaof the final anchored model, observed minus predicted — inspect them, e.g. viatinto.experiments.Experiment.residuals(), to tell noise from leftover structure).- Return type:
Examples
On a clean affine law both coefficients are recovered exactly:
>>> import numpy as np >>> x = np.arange(10.0, 60.0) >>> y = (2 / 3) * x - 1 / 3 >>> r = fit_fractions(x, y, np.full_like(x, 1e-3)) >>> r["fractions"] [Fraction(2, 3), Fraction(-1, 3)]
- tinto.estimate.fractions_table(results, names=None)[source]#
Render a
{label: fit_fractions result}mapping as a table.Pure formatter for the output of
fit_fractions()(one entry per series, as produced bytinto.experiments.Experiment.fit_fractions()). Knows nothing aboutExperiment: it consumes only the result dicts, so it stays trivially testable and reusable.One row per label; one column per coefficient, named by names. An anchored coefficient shows
value -> fraction; a free one showsvalue +/- error. Two trailing columns reportchi2_redandpvalue, and a finalfitcolumn carries the_health()verdict (ok/check/high/low) — the whole point being that a fraction recovered under ahighfit is not to be trusted, and acheckdeserves a second look.- Parameters:
results (mapping) –
{label: result}where each result is a dict as returned byfit_fractions()(keysfractions,beta,sigma_beta,chi2_red,pvalue,dof).names (list of
str, optional) – Coefficient names, aligned with the basis. Defaults to positionalc0, c1, ...inferred from the first result’s length. Usebasis_names()to derive them from a basis.
- Returns:
Printable (aligned ASCII) and notebook-displayable (HTML) table.
- Return type:
_FractionTable
Examples
>>> import numpy as np >>> x = np.arange(10.0, 60.0) >>> y = (2 / 3) * x - 1 / 3 >>> results = {"clean": fit_fractions(x, y, np.full_like(x, 1e-3))} >>> table = fractions_table(results, names=basis_names()) >>> table.headers ['campaign', 'n', '1', 'chi2_red', 'pvalue', 'fit'] >>> print(table) campaign | n | 1 | chi2_red | pvalue | fit ---------+---------------+-----------------+----------+--------+---- clean | 0.6667 -> 2/3 | -0.3333 -> -1/3 | 0.00 | 1 | low
The HTML rendering Jupyter would show upgrades the typography (a real
χ²,→, and a colouredfitglyph):>>> html = table._repr_html_() >>> "<table>" in html and "χ²<sub>red</sub>" in html and "→" in html True
- tinto.estimate.power_basis(exponents, var='n')[source]#
Return a basis of pure powers
v ** e, one column per exponent.Useful for inverse-power laws:
power_basis([-1, -2])spans{1/n, 1/n**2}, the natural basis forf(k) = a/k + b/k**2.Each column carries a
__name__of the form"<var>^<e>"(read bybasis_names()) so the fitted coefficients label themselves.- Parameters:
exponents (iterable of numbers) – Real exponents; one basis column
v -> v ** eis produced per entry, in order.var (
str, default=’n’) – Symbol used to name the columns.
Examples
>>> import numpy as np >>> b = power_basis([-1, -2]) >>> [f.__name__ for f in b] ['n^-1', 'n^-2'] >>> [f.__name__ for f in power_basis([-1, -2], var="k")] ['k^-1', 'k^-2'] >>> x = np.array([1.0, 2.0, 4.0]) >>> b[0](x).tolist() [1.0, 0.5, 0.25] >>> b[1](x).tolist() [1.0, 0.25, 0.0625]
- tinto.estimate.recover(value, sigma_abs, chi2_red=1.0, k=2, max_chi2_red=5.0, rescale_small=False)[source]#
Simplest fraction compatible with a fitted coefficient.
Returns the simplest fraction inside
value +/- k*sigma_abs. Thechi2_redof the parent fit acts as a guard: a model that fits badly (chi2_redabove max_chi2_red) is rejected outright, since a hidden term makes fraction recovery meaningless.The reference recipe additionally shrinks the interval by
sqrt(chi2_red)whenchi2_red < 1(the symptom of over-estimatedsigma_i). That is off by default here: with few sweep pointschi2_redfluctuates widely (its spread issqrt(2/dof)), so a value below 1 is usually sampling noise, not inflated error bars — and shrinking then wrongly excludes the true simple fraction. Enable rescale_small only when you know thesigma_iare inflated (e.g. a forgotten/n_trials); the right fix is to correct them at the source.- Parameters:
value (
float) – Fitted coefficient.sigma_abs (
float) – Its (absolute) error bar, e.g.sigma_beta[i]fromfit().chi2_red (
float, default=1.0) – Reduced chi-square of the parent fit, used by the max_chi2_red guard and (if rescale_small) the shrink factor.k (
float, default=2) – Half-width of the confidence interval, in error bars.max_chi2_red (
float, default=5.0) – Above this, the model is deemed wrong and the call raises.rescale_small (
bool, default=False) – WhenTrueandchi2_red < 1, shrink the interval bysqrt(chi2_red).
- Return type:
- Raises:
ValueError – If
chi2_redexceeds max_chi2_red.
Examples
>>> recover(0.6667, 0.001) Fraction(2, 3) >>> recover(0.296269, 0.000077) Fraction(8, 27)
A badly fitting model is rejected rather than mined for a fraction:
>>> recover(0.5, 0.001, 100.0) Traceback (most recent call last): ... ValueError: chi2_red exceeds max_chi2_red: hidden structure, model rejected
Opting into the shrink reproduces the reference behaviour:
>>> recover(0.5, 0.1, chi2_red=0.25, rescale_small=True) Fraction(1, 2)
- tinto.estimate.simplest_in(lo, hi)[source]#
Return the simplest fraction inside
[lo, hi](Stern-Brocot).“Simplest” = smallest denominator, then smallest numerator. Handles the sign cases that a naive continued-fraction search gets wrong: an interval straddling zero returns
0, a fully negative interval is handled by symmetry.- Parameters:
- Return type:
Examples
>>> simplest_in(0.66, 0.67) Fraction(2, 3) >>> simplest_in(0.2, 0.4) Fraction(1, 3) >>> simplest_in(1.5, 2.5) Fraction(2, 1)
Zero is the simplest fraction of all, so any interval containing it returns it; negative intervals work by symmetry:
>>> simplest_in(-0.1, 0.1) Fraction(0, 1) >>> simplest_in(-0.67, -0.66) Fraction(-2, 3)
- tinto.estimate.test_extra_term(x, y, sigma, g, name='g', basis=None)[source]#
Likelihood-ratio test for a suspect extra term
c*g(x).Fits the basis model (default affine) and the same model augmented by one column
g(x), then compares them. Under the null hypothesisc = 0the drop in chi-squaredchi2 = chi2_0 - chi2_1follows a chi-square law with one degree of freedom (dchi2 ~= t**2).- Parameters:
x (array_like) – See
wls().y (array_like) – See
wls().sigma (array_like) – See
wls().g (callable) – The suspect term
g(x) -> column. E.g.lambda v: v*np.log(v)for a hiddenx*log x, orlambda v: v**-3for a1/k**3.name (
str, default=’g’) – Label echoed back in the result, for readability.basis (list of callables, optional) – The null model basis. Defaults to
affine_basis().
- Returns:
name,c(fitted coefficient of g),sc(its error bar),t(c / sc, the signal-to-noise),dchi2, andpvalue(stats.chi2.sf(dchi2, 1)).- Return type:
Examples
On exactly affine data the suspect
x*log xterm is not detected (t~ 0):>>> import numpy as np >>> x = np.array([1.0, 2.0, 3.0, 4.0]) >>> y = 2 * x + 1 >>> sigma = np.ones_like(x) >>> res = test_extra_term(x, y, sigma, lambda v: v * np.log(v), "xlogx") >>> res["name"] 'xlogx' >>> bool(abs(res["t"]) < 1e-6) True
Inject a real term and it is recovered:
>>> y2 = 2 * x + 1 + 0.5 * (x * np.log(x)) >>> res2 = test_extra_term(x, y2, sigma, lambda v: v * np.log(v)) >>> round(res2["c"], 6) 0.5
- tinto.estimate.wls(x, y, sigma, basis)[source]#
Weighted least squares of
yon a linear basis.Minimizes
sum(((X @ beta - y) / sigma) ** 2)whereXis the design matrix whose columns aref(x)for eachfin basis. The covariance isinv(A.T @ A)withA = X / sigma— i.e.absolute_sigma=Truesemantics: the sigma are trusted and the covariance is not rescaled by the reduced chi-square.- Parameters:
x (array_like) – Abscissae, measured values, and per-point error bars (same length).
sigmamust be strictly positive.y (array_like) – Abscissae, measured values, and per-point error bars (same length).
sigmamust be strictly positive.sigma (array_like) – Abscissae, measured values, and per-point error bars (same length).
sigmamust be strictly positive.basis (list of callables) – Each
f(x) -> columnbuilds one column of the design matrix.
- Returns:
beta (
numpy.ndarray) – Fitted coefficients, one per basis column.cov (
numpy.ndarray) – Covariance matrix of beta.chi2 (
float) – Weighted sum of squared residuals.dof (
int) – Degrees of freedom,len(x) - len(basis).resid (
numpy.ndarray) – Normalized residuals in the usual convention(y - X @ beta) / sigma(observed minus predicted): a point above the fit gets a positive residual. The sign is irrelevant to chi2 (squared) but matters when the residuals are inspected or plotted.
Examples
On exactly affine data the slope and intercept are recovered and the residual chi-square is zero:
>>> import numpy as np >>> x = np.array([0.0, 1.0, 2.0, 3.0]) >>> y = 2 * x + 1 >>> sigma = np.ones_like(x) >>> beta, cov, chi2, dof, resid = wls(x, y, sigma, [np.ones_like, lambda v: v]) >>> np.round(beta, 6).tolist() [1.0, 2.0] >>> bool(chi2 < 1e-20) True >>> dof 2