labplan
labplan is a small Python package for planning a measurement,
fitting a model to the results, and keeping a record of what was
done. It works with any instrument or experiment whose readings you
can predict with a Python function of some unknown numbers (the
parameters) and the settings you measure at. It helps with four
questions:
- Before measuring: can the measurements I plan pin down the numbers I care about, and how large will the error bars be? Which settings are worth the instrument time, and how many repeats do I need for a target error bar? How should the measurements be shared among the settings, and how close does a plan come to the best one possible?
- After measuring: what are the fitted numbers, and their error bars? Are the readings consistent with the model and their stated errors? Do the residuals wander in a pattern the model misses? What is the error bar of anything computed from them, such as a predicted reading, also when it is far from a straight line in them? And, reading the calibration backwards, which setting produced a new reading, and how sure is that? What if the settings themselves have error bars, as when a sensor is calibrated against a reference instrument, perhaps with errors that move together with those of the readings? The readings can come straight from an instrument's exported text table.
- If the model may be wrong: how wide a band around the prediction still covers new measurements at a chosen rate?
- Later: can anyone trace what was fitted, to exactly which data, with which software, and when?
When a planned measurement cannot separate the parameters, the package says so instead of returning numbers: the planner reports it, and the fit and the design tool stop with an error message that explains why.
Contents
- A short guide to the words used here
- Install
- Examples (each with the output it prints)
- Tutorials (complete scripts, from data to result)
- What is in the package
- When it refuses, and why
- How the results are checked
- Corrections in earlier versions
- Limits
- Where it comes from
- Citing, support and license
A short guide to the words used here
- Model -- your prediction function
f(theta, x). It takes the parameterstheta(the unknown numbers, such as a gain and an offset) and the settingsx(what you set on the instrument, one row per measurement), and returns the predicted readings. - Error bar -- the one-standard-deviation ("1-sigma")
uncertainty of a number.
sigmasare the error bars of the individual readings;sigmain results are the error bars of the fitted parameters. - Design -- the list of settings you plan to measure at.
- Information matrix -- a table that measures how strongly the
readings of a design respond to each parameter, weighted by the
reading error bars. In formula form it is
J^T W J, whereJholds the slopes of each prediction with respect to each parameter andW = diag(1/sigma^2). Its inverse is the covariance of the parameters: the diagonal holds the squared error bars, the rest says how the parameter errors move together. The planner and the fit use this same formula, which is why the planned error bars and the fitted ones agree when the model describes the data (see the checks below). - Slopes (Jacobian) -- how much each prediction changes per unit
change of each parameter.
labplancomputes them numerically by default, or uses exact ones you supply. - Propagation of uncertainty -- turning the error bars (and covariance) of the parameters into the error bar of something computed from them, to first order: exact when that quantity is a straight-line function of the parameters, approximate otherwise.
- Identifiable -- the design can tell the parameters apart. It cannot when some combination of parameters changes nothing the design can see (for example, two parameters that only ever appear added together).
- Condition number -- how close the information matrix is to
"cannot tell apart"; large means barely identifiable.
labplancomputes it after rescaling the matrix so that the units of the parameters do not matter, and treats a design as not identifiable above 1e10. - D-optimal design -- choosing the settings that make the determinant of the information matrix largest, which shrinks the joint uncertainty of all parameters.
- Weights: the share of all measurements spent at each candidate setting (0.25 means a quarter of them). A design with repeats is a set of weights.
- D-efficiency: how good a design is next to the best weights on the same candidates, as a number from 0 to 1. A design with D-efficiency 0.9 needs 1/0.9 = 1.11 times as many measurements as the best one to make the determinant of the information matrix as large.
- Chi-squared (chi2) -- the sum over all readings of ((reading - prediction) / sigma) squared. Divided by the degrees of freedom (number of readings minus number of parameters) it should be near 1 when the model and the stated reading errors agree.
- p-value: here, the probability that chi2 would come out at least as large as it did if the model and the stated reading errors were right. A very small p-value means one of them is wrong.
- Residuals and runs: the residuals are the differences
reading - prediction. Ordered by the setting, a run is a block of residuals with the same sign. A model that misses a bend or a drift leaves long runs, so too few runs is a warning sign. - Inverse prediction: reading a calibration curve backwards. A
new reading
y0is turned into the settingx0at which the model predictsy0; its error bar counts both the error of the new reading and the uncertainty of the calibration. - Errors in both coordinates ("errors in variables"): the settings are not known exactly either, for example because they are the readings of a reference instrument. The fit then also estimates the true settings, each within its own error bar.
- Correlation (of two errors): a number from -1 to 1 that says how much two errors tend to move together. 0 means they are independent; 0.5 means that when one error is positive, the other tends to be positive too.
- Monte Carlo propagation: finding the error bar of a computed number by drawing many random sets of parameters with the right error bars and correlations, computing the number for each set, and looking at how the results spread. It needs no straight-line approximation, only enough draws.
- Conformal prediction -- a way to put a band around predictions
from held-out data alone, without trusting the model. The
calibration scores are the absolute errors
|measured - predicted|on measurements not used in the fit. alpha is the allowed miss rate (0.1 means a 90 % band). The guarantee needs the calibration data and the new measurement to be exchangeable: drawn the same way, in any order. - sha256 digest -- a 64-character fingerprint of the exact data arrays. Any change to the data changes it.
Install
pip install labplan
It needs Python 3.9 or newer and NumPy 1.22 or newer, and nothing
else. The package has no built-in units: settings, readings, error
bars and parameters are in whatever units your model uses, and
results come back in those units. Settings x are an (n, d) array,
one row per measurement; a 1-D array is read as one setting per
measurement. Parameters are in the order of param_names.
Runnable worked examples live in examples/:
01_plan_then_fit.py plans, simulates, fits and records a
calibration of a first-order low-pass filter (it picks 6 of 25
candidate frequencies and asks for 14 repeats of that sweep to reach
an error bar of 5 Hz on the corner frequency), and
02_conformal_certificate.py wraps a conformal band around a
deliberately wrong straight-line model and measures its coverage
over 300 simulated rounds (0.899, against the exact 0.9000 for its
79 calibration points). Three longer tutorials, also in examples/,
are described in Tutorials below.
Examples
Each example below runs as written, and the output shown is what it printed with labplan 0.7.0 (a test checks this). The model, the numbers and the noise are illustrative; the random numbers come from fixed seeds, so the output is repeatable.
1. Before measuring: will this design work, and how well?
import numpy as np
from labplan import Model, information
# A sensor whose reading is a straight line in the setting x:
# reading = gain * x + offset. All numbers here are illustrative.
line = Model("sensor line",
lambda th, x: th[0] * x[:, 0] + th[1],
param_names=("gain", "offset"),
reference="illustrative straight-line sensor model")
x_planned = np.linspace(0.5, 5.0, 12) # 12 planned settings
plan = information(line, theta=[2.0, 0.0], x=x_planned, sigmas=0.05)
print("identifiable:", plan["identifiable"])
for name, s in plan["sigma"].items():
print(f"expected error bar on {name}: {s:.5f}")
identifiable: True
expected error bar on gain: 0.01022
expected error bar on offset: 0.03160
theta is your best guess of the parameters (from a datasheet or a
previous calibration); the answer is computed there. sigmas=0.05
says each reading will have an error bar of 0.05. Every Model
needs a reference string saying where the model comes from.
2. Choose the settings, and count the repeats
import numpy as np
from labplan import Model, design, information, repeats_for
line = Model("sensor line",
lambda th, x: th[0] * x[:, 0] + th[1],
param_names=("gain", "offset"),
reference="illustrative straight-line sensor model")
candidates = np.linspace(0.5, 5.0, 12)
pick = design(line, [2.0, 0.0], candidates, n_pick=4, sigmas=0.05)
print("chosen settings:", candidates[pick["indices"]])
plan = information(line, [2.0, 0.0], candidates, sigmas=0.05)
r, predicted = repeats_for({"gain": 0.002}, plan)
print("repeats of the 12-point sweep needed:", r)
print(f"predicted error bar on gain: {predicted['gain']:.5f}")
chosen settings: [5. 0.5 0.90909091 4.59090909]
repeats of the 12-point sweep needed: 27
predicted error bar on gain: 0.00197
design picks settings one at a time, each time the candidate that
adds the most information, and lists them in the order picked. For a
straight line the ends of the range are the most informative, so it
takes those first. repeats_for uses the rule that repeating a
whole design r times divides every error bar by sqrt(r): here
0.01022 / 0.002 = 5.1, squared 26.1, rounded up to 27.
3. After measuring: fit the model
import numpy as np
from labplan import Model, fit
line = Model("sensor line",
lambda th, x: th[0] * x[:, 0] + th[1],
param_names=("gain", "offset"),
reference="illustrative straight-line sensor model")
x = np.linspace(0.5, 5.0, 12)
# Simulated measurements: true gain 2.0, offset 0.1, noise 0.05.
rng = np.random.default_rng(1)
y = 2.0 * x + 0.1 + 0.05 * rng.standard_normal(x.size)
res = fit(line, x, y, theta0=[1.0, 0.0], sigmas=0.05)
for name in line.param_names:
print(f"{name} = {res.values[name]:.4f} +/- {res.sigma[name]:.4f}")
print(f"chi2 = {res.chi2:.2f} for {res.chi2_dof} degrees of freedom")
gain = 2.0005 +/- 0.0102
offset = 0.1104 +/- 0.0316
chi2 = 4.10 for 10 degrees of freedom
The fitted error bars are the ones example 1 planned for the same
settings (0.0102 and 0.0316). theta0 is the starting guess. If you
leave out sigmas, the error bars are estimated from the scatter of
the residuals (the differences between the readings and the fitted
predictions) instead, and chi2 is None.
4. A design that cannot work is refused
import numpy as np
from labplan import Model, information, fit
# Two parameters that only ever appear as their sum: no measurement
# can tell them apart.
bad = Model("sum only", lambda th, x: (th[0] + th[1]) * x[:, 0],
param_names=("a", "b"),
reference="illustrative degenerate model")
x = np.linspace(0.5, 5.0, 12)
plan = information(bad, [1.0, 2.0], x, sigmas=0.1)
print("identifiable:", plan["identifiable"], "| error bars:", plan["sigma"])
try:
fit(bad, x, 3.0 * x, [1.0, 2.0], sigmas=0.1)
except ValueError as err:
print("fit refused:", err)
identifiable: False | error bars: None
fit refused: these measurements cannot tell the parameters apart (singular or near-singular information matrix): some combination of parameters changes nothing the design can see. Measure settings that respond differently to each parameter -- `information` shows which designs work before you spend the instrument time
5. Keep a record of the fit
import json
import numpy as np
from labplan import Model, fit, audit_record
line = Model("sensor line",
lambda th, x: th[0] * x[:, 0] + th[1],
param_names=("gain", "offset"),
reference="illustrative straight-line sensor model")
x = np.linspace(0.5, 5.0, 12)
rng = np.random.default_rng(1)
y = 2.0 * x + 0.1 + 0.05 * rng.standard_normal(x.size)
res = fit(line, x, y, theta0=[1.0, 0.0], sigmas=0.05)
rec = audit_record(res, operator="bench 2", note="illustrative run")
print(sorted(rec))
print(rec["data_sha256"][:16], "...")
print("survives JSON round trip:", json.loads(json.dumps(rec)) == rec)
['chi2', 'chi2_dof', 'condition_number', 'covariance', 'data_sha256', 'model', 'model_reference', 'model_units', 'n_points', 'note', 'operator', 'parameters', 'record', 'software', 'timestamp_utc']
dbf50525b0aff6ea ...
survives JSON round trip: True
The record is a plain dictionary: model name, reference and units
note (the model's units, empty here), each value with its error bar, the covariance, chi2, the number of points,
the condition number, the sha256 digest of the fitted data (settings,
readings and reading errors), the labplan and NumPy versions, a UTC
timestamp, the operator and a note. report_text(rec) turns it into
readable lines for a logbook. (The example prints only part of the
record because the timestamp changes on every run.)
6. A band that holds even if the model is wrong
import numpy as np
from labplan import conformal_quantile, conformal_interval, coverage_exact
# Absolute errors |measured - predicted| on 39 held-out measurements
# (simulated here; in practice they come from your own data).
rng = np.random.default_rng(3)
scores = np.abs(0.1 * rng.standard_normal(39))
q = conformal_quantile(scores, alpha=0.1) # aim: 90 % coverage
lo, hi = conformal_interval(np.array([4.2, 5.0]), q)
print(f"half-width q = {q:.4f}")
print("intervals:", np.round(lo, 4), "to", np.round(hi, 4))
print("exact coverage for n = 39:", coverage_exact(39, 0.1))
try:
conformal_quantile(scores[:5], alpha=0.1)
except ValueError as err:
print("refused:", err)
half-width q = 0.2041
intervals: [3.9959 4.7959] to [4.4041 5.2041]
exact coverage for n = 39: 0.9
refused: 5 calibration scores cannot certify level 0.9: the required rank 6 exceeds n. Collect at least 9 calibration measurements, or lower the confidence
q is the k-th smallest score, with k = ceil((n + 1)(1 - alpha)).
A new measurement that is exchangeable with the calibration
measurements then lands within q of its prediction with probability
at least 1 - alpha, whatever the model and whatever the noise. For
scores without ties that probability is exactly
k / (n + 1), which coverage_exact returns. The guarantee is an
average over many calibration sets and new points, not a promise for
each single setting.
7. Save and load measurements
import os, tempfile
import numpy as np
from labplan import save_measurements_csv, load_measurements_csv
x = np.array([[0.5], [1.0], [1.5]])
y = np.array([1.1, 2.1, 3.1])
path = os.path.join(tempfile.mkdtemp(), "run.csv")
save_measurements_csv(path, x, y, sigmas=0.05)
print(open(path).read())
x2, y2, s2 = load_measurements_csv(path)
print(np.array_equal(x, x2), np.array_equal(y, y2), s2)
x1,y,sigma
0.5,1.1,0.05
1.0,2.1,0.05
1.5,3.1,0.05
True True [0.05 0.05 0.05]
Columns are the settings x1, x2, ..., the reading y and, if
given, the reading error sigma. Values are written in full
precision (repr), so they read back as the identical numbers.
8. Error bars of predictions and derived numbers
import numpy as np
from labplan import Model, fit, propagate
line = Model("sensor line",
lambda th, x: th[0] * x[:, 0] + th[1],
param_names=("gain", "offset"),
reference="illustrative straight-line sensor model")
x = np.linspace(0.5, 5.0, 12)
rng = np.random.default_rng(1)
y = 2.0 * x + 0.1 + 0.05 * rng.standard_normal(x.size)
res = fit(line, x, y, theta0=[1.0, 0.0], sigmas=0.05)
# The predicted reading at settings 2.5 and 7.0 (7.0 is outside the
# measured range, so its error bar is larger).
pred = propagate(lambda th: line.predict(th, [2.5, 7.0]),
res.theta, res.cov)
print("predictions:", np.round(pred["value"], 4),
"+/-", np.round(pred["sigma"], 4))
# The setting at which the sensor reads 5.0: x = (5.0 - offset) / gain.
x5 = propagate(lambda th: (5.0 - th[1]) / th[0], res.theta, res.cov)
print(f"setting for a reading of 5.0: {x5['value']:.4f} +/- {x5['sigma']:.4f}")
predictions: [ 5.1116 14.114 ] +/- [0.0147 0.0458]
setting for a reading of 5.0: 2.4442 +/- 0.0074
propagate(func, theta, cov) takes any function of the parameters
and returns its value, error bar and covariance, using the
parameter covariance (and so the correlation between gain and
offset, which a simple "add the error bars" rule would miss). The
predictions are straight-line functions of the parameters, so their
error bars are exact; the setting (5.0 - offset) / gain is not, so
its error bar is the usual first-order approximation. Pass
information(...)["cov"] instead of res.cov to get the planned
error bar of a derived number before measuring.
9. Better picks by swapping, and repeats of a chosen design
import numpy as np
from labplan import Model, design, repeats_for
decay = Model("decay with background",
lambda th, x: th[0] * np.exp(-x[:, 0] / th[1]) + th[2],
param_names=("amplitude", "tau", "background"),
reference="illustrative exponential decay with background")
guess = [1.0, 1.0, 0.2]
candidates = np.linspace(0.0, 3.0, 31) # 0.0, 0.1, ..., 3.0
greedy = design(decay, guess, candidates, n_pick=3, sigmas=0.01)
swapped = design(decay, guess, candidates, n_pick=3, sigmas=0.01,
exchange=True)
for name, out in (("greedy", greedy), ("exchange", swapped)):
print(f"{name:8s} settings {np.sort(candidates[out['indices']])}"
f" error bar on tau {out['sigma']['tau']:.4f}")
r, predicted = repeats_for({"tau": 0.01}, swapped)
print("repeats of the 3-point exchange design for tau +/- 0.01:", r)
greedy settings [0. 1.1 3. ] error bar on tau 0.0481
exchange settings [0. 0.8 3. ] error bar on tau 0.0451
repeats of the 3-point exchange design for tau +/- 0.01: 21
The greedy picks are made one at a time and never revisited.
exchange=True then tries replacing each chosen setting by each
unused one and keeps the best swap, until no swap increases the
information determinant. Here it moves the middle setting from 1.1
to 0.8; for this example, checking all 4495 possible triples one
by one finds the same best triple (a test asserts this). The output of design can be
passed straight to repeats_for.
10. Exact slopes, and a parameter that starts at zero
import numpy as np
from labplan import Model, information
# A Gaussian pulse, with times written in seconds: center t0, width w.
def pulse(th, x):
return th[0] * np.exp(-0.5 * ((x[:, 0] - th[1]) / th[2]) ** 2)
def pulse_slopes(th, x): # d(pulse)/d(A, t0, w), by hand
u = (x[:, 0] - th[1]) / th[2]
e = np.exp(-0.5 * u ** 2)
return np.column_stack([e, th[0] * e * u / th[2],
th[0] * e * u ** 2 / th[2]])
numeric = Model("pulse", pulse, ("A", "t0", "w"),
reference="illustrative Gaussian pulse")
exact = Model("pulse", pulse, ("A", "t0", "w"),
reference="illustrative Gaussian pulse", jac=pulse_slopes)
t = np.linspace(-3e-9, 3e-9, 25) # 25 samples from -3 ns to 3 ns
guess = [1.0, 0.0, 1e-9] # center exactly zero, width 1 ns
diff = np.abs(exact.jacobian(guess, t) - numeric.numeric_jacobian(guess, t))
print("largest slope difference / largest slope:",
f"{diff.max() / np.abs(exact.jacobian(guess, t)).max():.1e}")
for m in (numeric, exact):
s = information(m, guess, t, sigmas=0.01)["sigma"]["t0"]
print(f"planned error bar on t0 ({'exact' if m.jac else 'numeric'} slopes): {s:.6e} s")
largest slope difference / largest slope: 3.1e-07
planned error bar on t0 (numeric slopes): 5.311778e-12 s
planned error bar on t0 (exact slopes): 5.311777e-12 s
jac= gives the model exact slopes, which information, design
and fit then use; numeric_jacobian always computes the numerical
ones, so you can compare the two once, as here, to catch a mistake
in the hand-written slopes. The numerical slopes are also good here,
although the center t0 is exactly zero and there is no natural
step size for it (see "Corrections" below: version 0.1.1 printed
6.686976e-12 s, 26 % too large, for the numeric line).
11. Are the readings consistent with the model?
import numpy as np
from labplan import Model, fit, goodness_of_fit
line = Model("sensor line",
lambda th, x: th[0] * x[:, 0] + th[1],
param_names=("gain", "offset"),
reference="illustrative straight-line sensor model")
x = np.linspace(0.5, 5.0, 12)
rng = np.random.default_rng(1)
y = 2.0 * x + 0.1 + 0.05 * rng.standard_normal(x.size) # true error 0.05
for stated in (0.05, 0.02): # the second is understated
res = fit(line, x, y, theta0=[1.0, 0.0], sigmas=stated)
g = goodness_of_fit(res)
print(f"sigmas={stated}: chi2 = {g['chi2']:.2f} for {g['dof']} "
f"degrees of freedom, p = {g['p_value']:.3g}, "
f"Birge ratio = {g['birge_ratio']:.2f}")
# A curved response fitted with a straight line, with the right errors:
y_curved = 2.0 * x + 0.1 + 0.05 * x ** 2 + 0.05 * rng.standard_normal(x.size)
g = goodness_of_fit(fit(line, x, y_curved, [1.0, 0.0], sigmas=0.05))
print(f"curved data: chi2 = {g['chi2']:.1f}, p = {g['p_value']:.2g}")
sigmas=0.05: chi2 = 4.10 for 10 degrees of freedom, p = 0.943, Birge ratio = 0.64
sigmas=0.02: chi2 = 25.62 for 10 degrees of freedom, p = 0.00429, Birge ratio = 1.60
curved data: chi2 = 49.0, p = 4e-07
goodness_of_fit needs a fit made with sigmas. Its p_value is
the probability of a chi2 at least this large if the model and the
stated errors are both right. With the true reading error (0.05) the
fit is unremarkable. With an error stated 2.5 times too small, chi2 is
6.25 times larger and p falls to 0.4 %. A straight line fitted to
readings that bend gives p = 4e-07 although the errors are right. The
test cannot say which of the two is wrong, only that something is.
p_value_low (also returned) is the opposite tail: a tiny value
means the readings agree better than their errors allow, so the
errors are probably overstated. The Birge ratio sqrt(chi2 / dof) is
the factor by which the stated errors would have to change for chi2
to equal its degrees of freedom. You can also call
goodness_of_fit(chi2=..., dof=...) with numbers from any other fit.
12. Read an instrument's exported table
import os, tempfile
from labplan import Model, fit, load_columns
# A sweep as an instrument might export it (illustrative numbers):
# a comment line, a header, semicolons, decimal commas, extra columns.
export = """# leakage sweep, bench 2
Time (s);Bias (V);Current (A);Current error (A);Status
0;0,5;1,04E-12;5E-14;OK
2;1,0;2,01E-12;5E-14;OK
4;1,5;3,05E-12;5E-14;OK
6;2,0;3,98E-12;5E-14;OK
8;2,5;5,02E-12;5E-14;OK
"""
path = os.path.join(tempfile.mkdtemp(), "sweep.csv")
with open(path, "w") as fh:
fh.write(export)
x, y, s = load_columns(path, x="Bias (V)", y="Current (A)",
sigma="Current error (A)", decimal=",")
print("bias:", x[:, 0], " current:", y)
leak = Model("leakage", lambda th, x: th[0] * x[:, 0] + th[1],
param_names=("G", "I0"),
reference="illustrative ohmic leakage with an offset current",
units={"G": "S", "I0": "A"})
res = fit(leak, x, y, theta0=[0.0, 0.0], sigmas=s)
print(f"G = {res.values['G']:.4e} +/- {res.sigma['G']:.1e} S")
# A cell the instrument marked as overload is refused, not skipped:
with open(path, "a") as fh:
fh.write("10;3,0;OVLD;5E-14;OVERLOAD\n")
try:
load_columns(path, x="Bias (V)", y="Current (A)", decimal=",")
except ValueError as err:
print("refused:", err)
bias: [0.5 1. 1.5 2. 2.5] current: [1.04e-12 2.01e-12 3.05e-12 3.98e-12 5.02e-12]
G = 1.9860e-12 +/- 3.2e-14 S
refused: line 8, column 'Current (A)': 'OVLD' is not a number
load_columns reads the columns you name from a delimited text file
with a header row: comma, tab, semicolon or space separated (found
from the header, or given with delimiter=), with . or , as the
decimal mark. Comment lines (starting with #) and blank lines are
skipped, and skip_rows= skips a preamble that is not marked as
comment. Other columns may hold anything and are not read. Every
value it returns was read as a finite number from the cell you named.
An empty cell, text such as OVLD, nan or inf, or a row with
the wrong number of fields stops it with the line number, because
skipping such rows silently would change the data you fit. The
result (x, y, sigmas) goes straight into fit.
13. Read the calibration backwards: which setting gave this reading?
import numpy as np
from labplan import Model, fit, inverse_predict
line = Model("sensor line",
lambda th, x: th[0] * x[:, 0] + th[1],
param_names=("gain", "offset"),
reference="illustrative straight-line sensor model")
x = np.linspace(0.5, 5.0, 12)
rng = np.random.default_rng(1)
y = 2.0 * x + 0.1 + 0.05 * rng.standard_normal(x.size)
res = fit(line, x, y, theta0=[1.0, 0.0], sigmas=0.05)
# An unknown gives the reading 5.0 (error bar 0.05): which setting?
out = inverse_predict(line, res, reading=5.0, bracket=(0.5, 5.0),
reading_sigma=0.05)
print(f"setting = {out['value']:.4f} +/- {out['sigma']:.4f}")
print(f" from the reading: {out['sigma_from_reading']:.4f}, "
f"from the calibration: {out['sigma_from_parameters']:.4f}")
# A reading the calibrated range does not reach is refused:
try:
inverse_predict(line, res, reading=12.0, bracket=(0.5, 5.0))
except ValueError as err:
print("refused:", err)
setting = 2.4442 +/- 0.0261
from the reading: 0.0250, from the calibration: 0.0074
refused: the model does not reach the reading 12 for settings between 0.5 and 5 (there it runs from 1.11061 to 10.1129); widen the bracket, or check the reading
inverse_predict (new in 0.4.0) solves f(theta, x0) = reading for
x0 inside the bracket you give, normally the calibrated range. The
error bar is first order: u(x0)^2 = (u(y0)^2 + a^T C a) / s^2, with
s the slope of the curve at x0 and a the slopes with respect to
the parameters. For a straight line this is the propagation-of-error
formula of the NIST/SEMATECH e-Handbook of Statistical Methods,
section 2.3.6.7.3. The two parts show what limits the result: here the
reading (0.0250) far more than the calibration (0.0074), so repeating
the reading of the unknown would help, and recalibrating would not.
The value is the setting example 8 found with propagate; the error
bar is larger because it now includes the reading's own error. Pass
an array of readings to get the covariance of several unknowns (they
share the calibration, so their errors are correlated), or
theta= and cov= from information to plan before calibrating. A
reading that the model reaches twice in the bracket (a peak), a curve
that is flat there, and a curve that bends so much within one error
bar that the first-order error bar is unreliable are refused.
14. Do the residuals wander? The runs test
import numpy as np
from labplan import Model, fit, goodness_of_fit, runs_test
line = Model("sensor line",
lambda th, x: th[0] * x[:, 0] + th[1],
param_names=("gain", "offset"),
reference="illustrative straight-line sensor model")
x = np.linspace(0.5, 5.0, 24)
rng = np.random.default_rng(2)
# Readings that bend a little, with errors stated 3 times too large:
y = 2.0 * x + 0.1 + 0.05 * x ** 2 + 0.05 * rng.standard_normal(x.size)
res = fit(line, x, y, theta0=[1.0, 0.0], sigmas=0.15)
print(f"chi2 test: p = {goodness_of_fit(res)['p_value']:.3f}")
r = runs_test(y - line.predict(res.theta, x), order=x)
print(f"signs: {r['n_positive']} +, {r['n_negative']} -, "
f"{r['runs']} runs (expected {r['expected_runs']:.2f} "
f"+/- {r['sigma_runs']:.2f}), p = {r['p_value']:.4f}")
chi2 test: p = 0.994
signs: 9 +, 15 -, 5 runs (expected 12.25 +/- 2.24), p = 0.0010
The readings bend a little, and their stated errors are 3 times too
large, so chi2 is small and its test sees nothing wrong (p = 0.994).
The residuals of the straight line, ordered by x, tell another
story: positive at both ends and negative in the middle, they form
only 5 runs where about 12 are expected. runs_test (new in 0.4.0)
gives the probability of so few runs if the signs were in random order
(the runs test of A. Wald and J. Wolfowitz, Ann. Math. Statist. 11,
147 (1940)), computed exactly. p_value_high is the opposite tail
(signs that alternate too often). For residuals of a fit the signs are
not exactly independent; in the tests this made the test more
cautious, not less: on 4000 seeded correct straight-line fits each
with 12 and with 30 readings it raised a false alarm at the 5 % level
in 0.7 % and 2.8 % of them (3.6 % for 30 independent random signs,
where the exact test, whose runs come in whole numbers, stays at or
below 5 %).
15. Settings with error bars too: fit both coordinates
import numpy as np
from labplan import Model, fit, fit_xy, goodness_of_fit
# Pearson's data with York's weights (1 / error bar squared), as
# tabulated by C. A. Cantrell, Atmos. Chem. Phys. 8, 5477 (2008).
x = np.array([0.0, 0.9, 1.8, 2.6, 3.3, 4.4, 5.2, 6.1, 6.5, 7.4])
y = np.array([5.9, 5.4, 4.4, 4.6, 3.5, 3.7, 2.8, 2.8, 2.4, 1.5])
wx = np.array([1000, 1000, 500, 800, 200, 80, 60, 20, 1.8, 1.0])
wy = np.array([1, 1.8, 4, 8, 20, 20, 70, 70, 100, 500.0])
line = Model("line", lambda th, x: th[0] + th[1] * x[:, 0],
param_names=("intercept", "slope"),
reference="straight line; Pearson-York test data")
res = fit_xy(line, x, y, theta0=[5.0, -0.5], sigmas=1 / np.sqrt(wy),
x_sigmas=1 / np.sqrt(wx))
for name in line.param_names:
print(f"{name} = {res.values[name]:.5f} +/- {res.sigma[name]:.5f}")
g = goodness_of_fit(res)
print(f"chi2 = {g['chi2']:.2f} for {g['dof']} degrees of freedom, "
f"p = {g['p_value']:.3f}")
# The same data with x taken as exact:
naive = fit(line, x, y, theta0=[5.0, -0.5], sigmas=1 / np.sqrt(wy))
print(f"x taken as exact: slope = {naive.values['slope']:.5f}")
intercept = 5.47991 +/- 0.29497
slope = -0.48053 +/- 0.05799
chi2 = 11.87 for 8 degrees of freedom, p = 0.157
x taken as exact: slope = -0.61081
fit_xy (new in 0.5.0) fits the model and, at the same time, the true
settings, each allowed to move within its error bar x_sigmas. This is
a classic test case: the slope and intercept are the values Cantrell's
review lists in its "Williamson-York" row (-0.48053 and
5.4799), and the error bars and chi2 are those of York's formulas
(the tests repeat York's iteration step by step). Taking x as exact
gives a slope of -0.61081 (also in Cantrell's table), far outside the
error bar. The result goes into goodness_of_fit, propagate,
inverse_predict and audit_record like any fit; res.x_adjusted
holds the fitted true settings. A setting whose error bar is 0 is
taken as exact.
16. Share the measurements, and rate any design
import numpy as np
from labplan import (Model, design, design_efficiency, design_weights,
repeats_for)
decay = Model("decay with background",
lambda th, x: th[0] * np.exp(-x[:, 0] / th[1]) + th[2],
param_names=("amplitude", "tau", "background"),
reference="illustrative exponential decay with background")
guess = [1.0, 1.0, 0.2]
candidates = np.linspace(0.0, 3.0, 31) # 0.0, 0.1, ..., 3.0
def between(low, high): # rounds each bound outward, never inward
return (f"{np.floor(low * 1e5) / 1e5:.5f} to "
f"{np.ceil(high * 1e5) / 1e5:.5f}")
best = design_weights(decay, guess, candidates, sigmas=0.01, n_total=12)
used = best["weights"] > 0.001
print("best shares:", np.round(best["weights"][used], 3),
"at", candidates[used])
c = best["counts"]
print("12 measurements:", c[c > 0], "at", candidates[c > 0],
"| D-efficiency",
between(best["counts_efficiency_low"], best["counts_efficiency_high"]))
for exchange in (False, True):
pick = design(decay, guess, candidates, n_pick=3, sigmas=0.01,
exchange=exchange)
counts = np.bincount(pick["indices"], minlength=candidates.size)
eff = design_efficiency(decay, guess, candidates, counts, sigmas=0.01)
print(f"design(exchange={exchange}):".ljust(23),
candidates[counts > 0], "| D-efficiency",
between(eff["efficiency_low"], eff["efficiency_high"]))
r, predicted = repeats_for({"tau": 0.01}, best)
print("measurements in all for tau +/- 0.01:", r)
best shares: [0.333 0.248 0.085 0.333] at [0. 0.8 0.9 3. ]
12 measurements: [4 3 1 4] at [0. 0.8 0.9 3. ] | D-efficiency 0.99999 to 1.00000
design(exchange=False): [0. 1.1 3. ] | D-efficiency 0.97134 to 0.97135
design(exchange=True): [0. 0.8 3. ] | D-efficiency 0.99991 to 0.99992
measurements in all for tau +/- 0.01: 62
design_weights (new in 0.6.0) finds the best share of the
measurements for each candidate setting, repeats allowed. For this
decay the best design spends a third of the measurements at 0, a
third at 3 and a third near 0.843: with settings 0, t and 3 the
determinant is largest at t = 1 - 3 e^-3 / (1 - e^-3) = 0.8428 (a test
works this out and checks it). On a grid in steps of 0.1 that third is
shared by 0.8 and 0.9. n_total=12 turns the shares into whole
numbers of measurements.
design_efficiency rates any design against the best shares on the
same candidates, with proven lower and upper bounds. The three
settings that design picks one at a time (example 9) reach 0.97134,
so they need about 1.03 times as many measurements as the best design
for the same determinant; after the swaps, 0.99991. The lower bound
needs no search: for any design, the largest variance of the
predicted reading over the candidates (in units of its error, times
the number of measurements) is at least the number of parameters p,
equals p only for a best design, and p divided by it is a lower
bound on the D-efficiency. The output of design_weights goes into
repeats_for like a plan, and r is then the number of measurements
in all: 62 here, against 3 x 21 = 63 for the repeated three-point
design of example 9.
17. Errors of settings and readings that move together
import numpy as np
from labplan import Model, fit_xy, goodness_of_fit
# Pearson's data with York's weights, as in example 15, now with the
# error of each setting correlated with the error of its reading
# (correlation 0.5 for every point; illustrative).
x = np.array([0.0, 0.9, 1.8, 2.6, 3.3, 4.4, 5.2, 6.1, 6.5, 7.4])
y = np.array([5.9, 5.4, 4.4, 4.6, 3.5, 3.7, 2.8, 2.8, 2.4, 1.5])
wx = np.array([1000, 1000, 500, 800, 200, 80, 60, 20, 1.8, 1.0])
wy = np.array([1, 1.8, 4, 8, 20, 20, 70, 70, 100, 500.0])
line = Model("line", lambda th, x: th[0] + th[1] * x[:, 0],
param_names=("intercept", "slope"),
reference="straight line; Pearson-York test data")
for r in (0.0, 0.5):
res = fit_xy(line, x, y, theta0=[5.0, -0.5], sigmas=1 / np.sqrt(wy),
x_sigmas=1 / np.sqrt(wx), xy_correlation=r)
g = goodness_of_fit(res)
print(f"r = {r}: slope = {res.values['slope']:.5f} "
f"+/- {res.sigma['slope']:.5f}, intercept = "
f"{res.values['intercept']:.5f}, chi2 = {g['chi2']:.2f}")
r = 0.0: slope = -0.48053 +/- 0.05799, intercept = 5.47991, chi2 = 11.87
r = 0.5: slope = -0.49288 +/- 0.06297, intercept = 5.53437, chi2 = 9.57
xy_correlation (new in 0.7.0) is the correlation between the error
of each setting and the error of its reading. It arises, for example,
when both coordinates are computed from one shared measured number,
such as two signals divided by the same reference signal. It is one
number for all measurements, one per measurement, or one per setting
column and measurement; 0 (the default) gives the fit of example 15
exactly. For a straight line the result is York's line with his
correlation r_i: the tests run York's iteration with correlation
(D. York et al., Am. J. Phys. 72, 367 (2004), in the form listed by
C. M. Wehr and S. R. Saleska, Biogeosciences 14, 17 (2017), Appendix
A) on these data and agree with the line above to 3e-11 of an error
bar. Inside, the fit subtracts c x from each reading, with
c = r sigma_y / sigma_x; that removes the correlation exactly
(the error of y - c x is independent of the error of x), so the
fit is otherwise the one of example 15.
18. Error bars without the straight-line approximation
import numpy as np
from labplan import propagate, propagate_mc
# An amplifier gain measured as 20 dB +/- 3 dB (illustrative numbers),
# and the same gain as a plain voltage ratio, 10^(g / 20).
ratio = lambda th: 10 ** (th[0] / 20)
first = propagate(ratio, [20.0], [[3.0 ** 2]])
mc = propagate_mc(ratio, [20.0], [[3.0 ** 2]])
print(f"first order: {first['value']:.2f} +/- {first['sigma']:.2f}")
print(f"Monte Carlo: {mc['value']:.2f} +/- {mc['sigma']:.2f}, "
f"95 % interval {mc['low']:.2f} to {mc['high']:.2f}")
print(f"({mc['n_draws']} draws, seed {mc['seed']})")
first order: 10.00 +/- 3.45
Monte Carlo: 10.61 +/- 3.78, 95 % interval 5.08 to 19.68
(100000 draws, seed 0)
propagate_mc (new in 0.7.0) takes the same func, theta and
cov as propagate, draws 100000 parameter sets (by default) from
the Gaussian distribution with that mean and covariance, and reports
the mean, the standard deviation and the interval that holds the
computed number with 95 % probability, 2.5 % on each side (the Monte
Carlo method of JCGM 101:2008, the first supplement to the GUM). The
ratio here is a lognormal quantity, so the exact answers are known:
mean 10.61, standard deviation 3.78 and interval 5.08 to 19.68. The
first-order error bar of propagate, 3.45, is 8.6 % too small and
says nothing about the lopsided interval. The value has a random
error of about sigma / sqrt(n_draws) (0.012 here). seed=0 (the
default) makes the result repeatable; seed=None draws fresh random
numbers.
Tutorials
Three complete scripts in examples/ go from raw data
(simulated with a fixed seed, so the output is repeatable) to a final
result with error bars. Each runs in well under a second, and a test
checks that it still prints exactly what is shown here.
tutorial_calibration_curve.py
calibrates an illustrative pressure sensor with a curved response
(V = c0 + c1 P + c2 P^2, 11 reference pressures from 0 to 100 kPa),
plans how well an unknown will be read before calibrating, checks the
calibration with chi-squared and the runs test, and then reads an
unknown (5 readings, true pressure 50 kPa) off the curve:
planned error bar at 50 kPa from one reading: 0.0161 kPa
fitted c0 = 0.09988 +/- 0.00046 V
fitted c1 = 0.039960 +/- 2.1e-05 V/kPa
fitted c2 = 9.9567e-06 +/- 2e-07 V/kPa^2
chi2 = 6.93 for 8 degrees of freedom, p = 0.544
runs of residual signs: 8 (expected 6.5), p = 0.911
unknown: mean reading 2.12274 V +/- 0.00027 V (5 readings)
pressure = 49.9988 +/- 0.0094 kPa
from the reading noise: 0.0066 kPa
from the calibration curve: 0.0067 kPa
tutorial_decay_on_background.py
measures a 10 mV decay with a time constant near 1 ns on a steady 1 V
level, in seconds and volts. It plans how many traces to average for
an error bar of 10 ps on the time constant, fits the averaged trace,
checks the fit and reports the decay rate 1/tau with its error bar.
labplan 0.3.0 refused this model at the natural first guess
tau = 1e-9 s (see Corrections):
planned error bar on tau from one trace: 3.57e-11 s
traces to average for tau +/- 1e-11 s: 13
A = 0.0101 +/- 5.9e-05 V
tau = 9.9383e-10 +/- 9.8e-12 s
B = 0.999993 +/- 1.3e-05 V
chi2 = 150.0 for 197 degrees of freedom, p = 0.995
runs of residual signs: 105 (expected 101.0), p = 0.740
decay rate 1/tau = 1.006e+09 +/- 9.9e+06 1/s
tutorial_errors_in_both.py
(new in 0.5.0) calibrates an illustrative temperature sensor
(V = c0 + c1 T, about 4 mV/K) against a reference thermometer whose
15 readings have error bars of 0.05 K, as large in effect as the
sensor's own 0.2 mV. Fitted as if the reference were exact, the error
bars are too small by a factor of about 1.4 and chi2 is too large
(on average twice its degrees of freedom); fit_xy counts both
errors. The script then reads an unknown (5 readings, true
temperature 50 degC) off the calibration:
reference points: 15, from 10.0 to 80.0 degC
x exact: c1 = 4.0003 +/- 0.0024 mV/K, chi2 = 20.8 for 13 dof, p = 0.076
x and y: c1 = 4.0004 +/- 0.0034 mV/K, chi2 = 10.4 for 13 dof, p = 0.66
reference temperatures moved by 0.59 error bars (rms), at most 1.25
unknown: mean reading 212.051 mV +/- 0.089 mV (5 readings)
temperature = 50.013 +/- 0.029 degC
from the reading noise: 0.022 degC
from the calibration: 0.019 degC
In this run the first chi2 (p = 0.076) would not by itself have raised an alarm; the error bars would still have been too small. Knowing the reference's error bar, and fitting with it, is what fixes them.
What is in the package
The model
Model(name, f, param_names, reference, units="", jac=None)-- your prediction functionf(theta, x)with a name, one name per parameter, and a requiredreference(a paper, a manual, your own derivation note).unitsis an optional note, free text or a dictionary such as{"fc": "Hz"}, that is copied into fit results, audit records and text reports.jacis an optional functionjac(theta, x)returning the exact slopes as an(n, p)array (one column per parameter); when given it replaces the numerical slopes everywhere.Model.predict(theta, x)evaluatesfwith shape and finiteness checks.Model.jacobian(theta, x)gives the slope of each prediction with respect to each parameter: fromjacif the model has one, otherwise fromModel.numeric_jacobian(theta, x).Model.numeric_jacobian(theta, x)computes the slopes by central differences (it nudges one parameter a small step up and down and divides the change in the predictions by the distance between the two parameter values). The step is 1e-6 times the parameter's size. When that is too small to change the predictions measurably (a parameter that is zero, or tiny compared with the rest of the prediction), it uses the step of version 0.1.0 instead: 1e-6 times the larger of the parameter's size and 1e-3. Since 0.2.0 that fallback step is checked against a step 10 times smaller; while the two disagree by more than 1e-6 of the largest slope (plus an allowance for rounding), the smaller step is taken, at most 8 times. Since 0.4.0, when that fallback step reaches or crosses zero and the model returns values that are not finite there (a time constant of 1e-9 s, say), it is divided by 10 until they are finite, at most 8 times, and then checked the same way. Since 0.7.0, when the step finally used changes the predictions so little that rounding could make up more than 1e-4 of the slopes (a detuning of 0 Hz in a model whose times are in seconds, say), the step is multiplied by 10, at most 16 times, until it changes them by more than 1e-8 of their size; those slopes are used if a step 10 times larger again gives the same slopes within 1e-6, and the earlier slopes are kept otherwise.rel_step(default 1e-6) must be a positive number.Model.n_paramscounts the parameters.
Planning
information(model, theta, x, sigmas=None)-- the information matrix of a planned design at your guessed parameters, whether it is identifiable, its condition number, the expected error bar of each parameter and the covariance. Withoutsigmasthe error bars are per unit reading error.design(model, theta, candidates, n_pick, sigmas=None, exchange=False)-- picksn_pickof the candidate settings, one at a time, each time taking the candidate that makes the determinant of the information matrix largest (greedy D-optimal selection; F. Pukelsheim, Optimal Design of Experiments, SIAM (2006)). Withexchange=Trueit then swaps one chosen setting for one unused setting while that increases the determinant (the exchange idea of V. V. Fedorov, Theory of Optimal Experiments, Academic Press (1972)). Returns the chosen indices (in pick order, a swapped-in setting taking the place of the one it replaced), the information matrix,identifiable, the condition number, the error bars and the covariance; the result can be passed torepeats_for. Since 0.4.0 the candidates are scored in batches, 9 to 24 times faster for 400 to 3000 candidates (medians of 7 runs on a shared 2-CPU machine). The batches use the same arithmetic and the same LAPACK routine as one candidate at a time; the tests find the same picks as the 0.3.0 loops, and since 0.5.0 they compare the information matrices to 1e-12 of their largest entry rather than digit for digit, because batched and single LAPACK calls are not guaranteed to round alike on every processor.repeats_for(target_sigma, plan)-- the number of repeatsrof a planned design needed to bring every error bar down to a target, from the rule thatrrepeats divide the error bars bysqrt(r). The target is one number for all parameters, or a dictionary{name: target}. Returnsrand the error bars atrrepeats.planis the output ofinformation,design,design_weights(thenris the number of measurements in all) ordesign_efficiency.design_weights(model, theta, candidates, sigmas=None, n_total=None, tol=1e-6, max_iter=10000)(new in 0.6.0): the best share of the measurements for each candidate setting, repeats allowed: the weightsw_i(adding up to 1) that make the determinant of the information per measurement,M = sum_i w_i J_i J_i^T / sigma_i^2, largest. Returnsweights,max_variance(the largestd_i = J_i^T M^-1 J_i / sigma_i^2, the variance of the predicted reading at candidateiin units of its error, times the number of measurements),efficiency_bound(p / max_variance, a proven lower bound on the D-efficiency of the weights),n_iter, andfisher,identifiable,condition_number,sigmaandcovasinformationgives them forM: the error bars for one measurement spread by the weights, soNmeasurements givesigma / sqrt(N). Withn_total, alsocounts, whole numbers of measurements per candidate that add up ton_total, with boundscounts_efficiency_lowandcounts_efficiency_high. The weights are found by alternating the multiplicative updatew_i <- w_i d_i / pand a "vertex exchange" step that moves the best amount of weight from the support point with the smallestd_ito the candidate with the largest; the search stops when the largestd_iis at mostp (1 + tol). The counts are the weights timesn_totalrounded down, filled up one measurement at a time where it helps most and then improved by moving single measurements while that helps.design_efficiency(model, theta, candidates, counts, sigmas=None, tol=1e-6, max_iter=10000)(new in 0.6.0): how close the design withcounts[i]measurements at candidateicomes to the best weights on the same candidates. Returns proven boundsefficiency_lowandefficiency_highon its D-efficiency, its ownmax_variance,n_total, the plan of the design (fisher,identifiable,condition_number,sigma,cov, as frominformation) and the best weights underbest. For the picks ofdesign, passnp.bincount(result["indices"], minlength=len(candidates)). Why the bounds hold:sum_i w_i d_i = pfor any weights (a trace identity), so the largestd_iis at leastp; at the best weights it equalsp(J. Kiefer and J. Wolfowitz, Canadian Journal of Mathematics 12, 363 (1960)); and by the inequality of the arithmetic and geometric means applied to the eigenvalues ofM^-1 M*(withM*the best), the D-efficiency is at leastp / max_i d_i. A design that cannot identify the parameters gets 0. See example 16.
Error bars of derived numbers
propagate(func, theta, cov)-- the value, error bar and covariance offunc(theta)(one number or an array of numbers computed from the parameters), by first-order propagationJ C J^T, whereCis the parameter covariance andJholds the numerical slopes offunc. Use the covariance of a fit, or of a plan for the error bars you should expect. Values and error bars come back as plain numbers whenfuncreturns one number. Since 0.3.0 a covariance that is not positive semidefinite (one that would give some combination of parameters a negative variance) is refused.propagate_mc(func, theta, cov, n_draws=100000, seed=0, level=0.95)(new in 0.7.0): the same question answered without the straight-line approximation, by the Monte Carlo method of JCGM 101:2008. It drawsn_drawsparameter vectors from the Gaussian distribution with meanthetaand covariancecov, callsfuncon each, and returnsvalue(the mean),sigma(the standard deviation),cov, andlowandhigh, the(1 - level)/2and(1 + level)/2quantiles of the results (an interval with equal probability outside it on each side), withn_draws,seedandlevel. The value has a random error of aboutsigma / sqrt(n_draws). The same seed gives the same numbers. See example 18.
Fitting
fit(model, x, y, theta0, sigmas=None, max_iter=200, tol=1e-12)-- weighted least squares by the Levenberg-Marquardt method (a standard step-by-step search that adjusts the parameters until the weighted sum of squared differences between readings and predictions stops decreasing), written in NumPy. Withsigmas, the covariance is the inverse information matrix and chi2 is reported; without them, the covariance is scaled by the residual scatter (chi2 / degrees of freedom), which needs at least one more reading than parameters. The search stops when a step changes the weighted sum of squares by at mosttoltimes (one unit + the sum) and moves no parameter by more than 1e-10 times (1 + the largest parameter). Withsigmasthe unit is 1; without them, since 0.3.0, it is the residual variance (at most 1), so the result no longer depends on the units of the readings (see Corrections).FitResult-- whatfitreturns:valuesandsigma(dictionaries by parameter name),thetaandcov(arrays),chi2,chi2_dof,n_points,condition_number,n_iter,model_name,reference,units(the model's note),data_digest(the sha256 of the settings, readings and reading errors) and, since 0.5.0,x_adjusted(the fitted true settings offit_xy;Noneforfit) and, since 0.7.0,xy_correlation(the correlations afit_xywas given;Noneotherwise).fit_xy(model, x, y, theta0, sigmas, x_sigmas, max_iter=200, tol=1e-12, xy_correlation=None)(new in 0.5.0): the fit when the settings have error bars too.x_sigmasis one number, one per measurement, or an(n, d)array; 0 marks an exact setting. It minimizes the sum of the squared reading residuals and the squared setting adjustments, each in units of its error bar, over the parameters and the true settings (the maximum-likelihood fit for independent Gaussian errors). For a straight line this is the line of D. York et al., Am. J. Phys. 72, 367 (2004). The covariance is first order, as forfit; with the true settings eliminated it is the inverse ofsum a_i a_i^T / (sigma_y,i^2 + sum_k s_ik^2 sigma_x,ik^2), witha_ithe slopes with respect to the parameters ands_ikthose with respect to the settings ("effective variance"). chi2 is the minimum sum, forn - pdegrees of freedom. The slopes with respect to the settings are central differences with a step of 1e-6 of the setting; where that step is zero or does not change the predictions by more than 1e-8 of their size, 1e-6 of the larger of the setting and the largest setting in its column (since 0.6.0; before, the second step was used for every setting, see Corrections). Since 0.7.0 that second step is checked against a step 10 times smaller and reduced while the two disagree, asModel.numeric_jacobiandoes for a parameter at zero.xy_correlation(new in 0.7.0) is the correlation between the error of each setting and the error of its reading: one number, one per measurement, or an(n, d)array, 0 where a setting is exact; the squares of one measurement's correlations must add up to less than 1 (the errors of different settings stay independent of each other). The fit then minimizes the sum with the full covariance of each measurement's errors; for a straight line that is York's line with his correlationr_i. See examples 15 and 17 and the third tutorial.goodness_of_fit(result)orgoodness_of_fit(chi2=..., dof=...)(new in 0.3.0): the chi-squared test. It returnschi2,dof,reduced_chi2(chi2 / dof),p_value(probability of a chi2 at least this large if the model and the stated errors are right),p_value_low(probability of one at most this large) andbirge_ratio(sqrt(chi2 / dof); R. T. Birge, Phys. Rev. 40, 207 (1932)). The probabilities are the regularized incomplete gamma functionsQ(dof/2, chi2/2)andP(dof/2, chi2/2), computed by the series and continued fraction of Press et al., Numerical Recipes, 3rd ed. (2007), section 6.2, so that small values keep their full relative precision. See example 11.runs_test(residuals, order=None)(new in 0.4.0): the runs test of Wald and Wolfowitz on the signs of the residuals, sorted byorder(normally the settings). Returnsruns,n_positive,n_negative,n_zero(zero residuals have no sign and are left out),expected_runs,sigma_runs,p_value(probability of this few runs or fewer when the signs are in random order) andp_value_high(this many or more). See example 14.
Reading a calibration backwards
inverse_predict(model, result, reading, bracket, reading_sigma=0.0, theta=None, cov=None, n_scan=1001, max_slope_change=0.1, full_cov=True)(new in 0.4.0): the settingx0at which the model predictsreading, searched inbracket = (low, high)(scanned atn_scanpoints, then refined by bisection), with its error bar from the reading's own errorreading_sigmaand from the parameter covariance (ofresult, ortheta=andcov=). Returnsvalue,sigma,cov(for several readings),slope(df/dxatx0),sigma_from_reading,sigma_from_parametersandslope_change. The settings must be one number per measurement. See example 13. Since 0.5.0 all readings are solved together (the model is evaluated for all of them in one call at each step), 54 to 63 times faster for 100 to 1000 readings than 0.4.0 (medians of 5 to 7 interleaved runs on a shared 2-CPU machine);full_cov=Falseskips the covariance between readings (covis thenNone), so that a series of 10000 readings needs memory for 10000 numbers, not for 10000 x 10000.
When the model may be wrong (split conformal prediction)
conformal_quantile(scores, alpha=0.1)-- the half-widthqfrom held-out absolute errors.conformal_interval(prediction, q)--prediction - qandprediction + q.coverage_exact(n, alpha)-- the exact coveragek / (n + 1)for scores without ties; it always lies between1 - alphaand1 - alpha + 1/(n + 1).alphais read as the decimal number you typed:kis computed so thatalpha=0.7means exactly 7/10 (see Corrections below). Since 0.5.0 a decimal of up to 8 significant digits (or a value that differs from one only by floating-point rounding, such as1 - 0.9) is read exactly at everyn. Since 0.7.0 every alpha is read as an exact number andkis computed in whole numbers: a decimal of up to 8 significant digits as before; otherwise a fraction with a denominator of at most 10^6, if alpha is that fraction up to rounding (1/3,2/7); otherwise the decimal that Python prints for it (repr), which is the number as typed for a decimal of up to 15 significant digits (0.099999999999).
Records
audit_record(result, operator="", note="")-- a JSON-ready dictionary describing one fit (see example 5), including the model's units note undermodel_units. For a fit byfit_xyit has one more key,fit_method(since 0.5.0), and its digest also coversx_sigmas.report_text(record)-- the same record as readable text. Records written by 0.1.x, which have nomodel_units, still render.save_measurements_csv(path, x, y, sigmas=None)andload_measurements_csv(path)-- a plain CSV file of measurements; loading returns(x, y, sigmas), withsigmasNonewhen the file has no sigma column.load_columns(path, x, y, sigma=None, delimiter=None, decimal=".", comment="#", skip_rows=0, header=True, encoding="utf-8-sig")(new in 0.3.0): reads the named columns (header names, or positions counted from 0) of any delimited text table, such as an instrument's or a spreadsheet's export, and returns(x, y, sigmas)likeload_measurements_csv.xcan be one column or a list of columns.skip_rowsmust be a whole number (since 0.6.0). The defaultencodingalso removes the byte-order mark that some spreadsheet programs write. See example 12.__version__-- the package version.
Each function's docstring (help(labplan.fit), for example) gives
its inputs and conventions.
When it refuses, and why
labplan raises an error instead of guessing when:
- a
Modelhas an empty name, a prediction function (orjac) that cannot be called, missing or repeated parameter names, or areferenceshorter than 8 characters; jacreturns an array of the wrong shape or values that are not finite;- the prediction function returns the wrong number of values, or values that are not finite (infinite or NaN);
thetahas the wrong number of entries, or settings, readings or reading errors are not finite, or reading errors are not positive, or there is neither one reading error for all readings nor one per reading (since 0.2.0 the message says so, instead of NumPy's broadcasting error);- the design cannot tell the parameters apart (condition number above
1e10 after rescaling, or a parameter that no reading responds to):
fitrefuses;designrefuses when even the full candidate list cannot;informationdoes not raise but reportsidentifiable: Falsewith no error bars, and also does so when there are fewer settings than parameters; fitgets fewer readings than parameters, or, withoutsigmas, no spare reading to estimate the scatter from;fitdoes not converge withinmax_itersteps (aRuntimeError), or gets amax_iterbelow 1 or a negativetol(since 0.3.0);designis asked for fewer picks than parameters or more picks than candidates, or (since 0.3.0) for a number of picks that is not a whole number, such as 2.5, which 0.2.0 silently cut to 2;design_weightsanddesign_efficiency(new in 0.6.0) get candidates that even all together cannot identify the parameters, atolthat is not a positive number, or amax_iterthat is not a whole number of at least 1;design_weightsalso ann_totalthat is not a whole number of at least the number of parameters, anddesign_efficiencycountsthat are not one whole number>= 0per candidate, or that are all 0. When the search does not reachtolwithinmax_iterrounds,design_weightsraises aRuntimeErrorthat gives the efficiency reached;repeats_forgets a plan that is not identifiable (no number of repeats can fix that), an unknown parameter name, a target that is not positive, or (since 0.3.0, with a clear message) an empty dictionary of targets;conformal_quantilegets negative or non-finite scores, an alpha outside 0 to 1, or too few scores for the level (the message names the minimum);coverage_exactrefuses the same levels;conformal_intervalrefuses a negative or non-finiteq;inverse_predictfinds no setting in the bracket at which the model reaches the reading (the message gives the range the model covers there), finds more than one (narrow the bracket to one branch), finds the model flat at the solution or equal to the reading over a whole range, or finds that the slopedf/dxchanges by more thanmax_slope_change(10 %) within one error bar of the solution; or gets a bracket that is not two finite numbers with low < high, a reading that is not finite, a negativereading_sigma, aFitResultof another model, both a result andtheta=/cov=, a covariance thatpropagatewould refuse, or (since 0.5.0) afull_covthat is notTrueorFalse;fit_xygets no reading errorssigmas(without them the balance between the two kinds of error is unknown),x_sigmasof the wrong shape, negative or not finite, or a model whose prediction for one measurement changes when the settings of another one change (it is checked once, by moving one row's settings); since 0.7.0 also anxy_correlationof the wrong shape, not finite, not 0 where a setting is exact, or with squares that add up to 1 or more for one measurement (such errors have no valid covariance); and it refuses everythingfitrefuses withsigmas;runs_testgets residuals that are not finite or not a 1-D array, anorderof the wrong length, fewer than 2 nonzero residuals, or residuals that all have the same sign (no runs to count);Model.numeric_jacobiangets arel_stepthat is not a finite positive number (since 0.4.0; 0.3.0 failed with anUnboundLocalError), andcoverage_exactgets annthat is not a whole number (since 0.4.0; 0.3.0 cut 29.9 to 29);propagategets no covariance (None, as from a plan that is not identifiable), one of the wrong size, one that is not symmetric or has a negative diagonal, one that is not positive semidefinite (since 0.3.0), or afuncthat cannot be called, returns non-finite values, or returns an array with more than one dimension (a table instead of a list of numbers);propagate_mc(new in 0.7.0) refuses whatpropagaterefuses, ann_drawsthat is not a whole number or that leaves fewer than 10 draws beyond each end of the interval (fewer than20 / (1 - level), so 400 for 0.95), aleveloutside 0 to 1, aseedthat is not a whole number>= 0orNone, and afuncthat is not finite at some draw (the message gives the parameters) or returns a different number of values there;audit_recordgets an operator or note that is not text, orreport_textgets something that is not an audit record;goodness_of_fitgets a fit made withoutsigmas(it has no chi2), zero degrees of freedom, a negative or non-finite chi2, adofthat is not a whole number, or both a fit and numbers;- a measurement file is empty, has an unexpected header, has no data rows, has a row with the wrong number of values, or has a value that is not a number;
load_columnsis asked for a column name that is not in the header (the message lists the names that are), a name that appears twice, a position outside the table, the same column twice, or (since 0.6.0) askip_rowsthat is not a whole number>= 0(0.5.0 cut 2.7 to 2 without a word); or finds a row with a different number of fields than the header, an empty cell, text, NaN or infinity in a requested column, a reading error that is not positive, a header in which more than one of comma, tab and semicolon occurs (passdelimiter=), a.in a number whendecimal=","(a thousands separator?), or no data rows. Each message names the line.
How the results are checked
170 automated tests run on every push and pull request, on Python 3.9,
3.10, 3.11, 3.12, 3.13 and 3.14, and once more on Python 3.9 with the
oldest NumPy the package allows (1.22.0, with pytest 7.0.0). Since
0.5.0 the source distribution includes the files the tests read
(CITATION.cff, examples/), so the suite also runs from it. The
numerical checks compare against a formula, an identity or seeded
simulation computed in the test itself, not against numbers stored
from an earlier run. What the tests assert:
Planning and fitting
- On noiseless straight-line data with reading error 0.05, the fit
recovers both parameters to 1e-8, chi2 is below 1e-12 with 10
degrees of freedom, the covariance matches the textbook formula
sigma^2 (X^T X)^-1(NumPyallclosewith relative tolerance 1e-6 and absolute 1e-15), and the planned error bars frominformationequal the fitted ones to 1 part in 10^6. - In 400 seeded simulated experiments (reading error 0.2), the spread of the fitted parameters matches the reported error bars within 15 %.
- A nonlinear model (exponential decay) is fitted from a poor start and recovers both parameters to 1e-6 on noiseless data.
- A model whose two parameters only appear as a sum is reported not
identifiable by
information(the smallest singular value of the rescaled matrix is below 1e-10 of the largest), and is refused byfitand bydesign. - The same RC charging model written with its time constant in seconds (1e-9) and in nanoseconds (1) gives the same planned error bars to 1 part in 10^6 and the same noiseless fit (values to 1 part in 10^6), and the slopes of a model that divides by a 1e-9 parameter are finite and match the exact derivative to 1 part in 10^6 (added in 0.1.1; see below).
- A parameter near zero still gets usable slopes: for the straight
line with slope 1e-12, 1e-300 or 0 (intercept 1),
Model.jacobianmatches the exact slopes to 1 part in 10^6, and a noiseless fit of a flat line (true slope 0) recovers both parameters to 1e-8 with the textbook covariance (relative tolerance 1e-6; added in 0.1.1). - Repeating a design 9 times divides every planned error bar by 3, to
1 part in 10^9; the
rthatrepeats_forreturns meets the target andr - 1repeats would not, and equalsceil((sigma / target)^2)for the largest ratio, with the predicted error barssigma / sqrt(r)(relative 1e-12). - Without
sigmas, the fitted covariance equals the ordinary least-squares formulas^2 (X^T X)^-1withs^2= residual sum of squares / (n - p), and the values equalnp.linalg.lstsq(relative tolerances 1e-6 and 1e-8).informationwithoutsigmasgives error bars exactly 1/0.05 of those withsigmas=0.05(relative 1e-12), and fewer settings than parameters are reported not identifiable. - Slopes of an exponential decay match the exact derivatives to relative 1e-6 (added in 0.2.0).
Slopes: parameters at zero and exact slopes (added in 0.2.0)
- A Gaussian pulse written in seconds with center
t0 = 0and width 1 ns: every column of the numerical slopes matches the exact derivative to 1e-5 of the column's largest value; the planned error bars match the exact(J^T W J)^-1to relative 1e-5, and equal those of the same model written in nanoseconds to relative 1e-5; a noiseless fit in seconds reports the exact error bar ont0to relative 1e-5. (With 0.1.1 the slope oft0was 31 % off and its planned error bar 26 % too large; this test fails on 0.1.1.) - Where the 0.1.0 fallback step was already accurate (a slope of 0 or 1e-300 beside an intercept of 1, a phase of 0 in a sine, a rate of 0 in an exponential), the slopes are bit-for-bit the central difference with step 1e-9, recomputed by hand in the test; and a model that loses digits in its own arithmetic does not get worse slopes than that step gave.
- With
jac=,jacobianreturns exactly the supplied array, the numerical slopes agree with it to 1e-5 of the largest slope, the planned covariance equals the exact(J^T W J)^-1to relative 1e-9 (entries compared on the scalesqrt(C_ii C_jj)), and a noiseless fit recovers the amplitude to 1e-9 and the width to 1 part in 10^9. Wrong shapes, non-finite values and a non-callablejacare refused.
Error bars of derived numbers (added in 0.2.0)
propagateof straight-line predictions at three settings equals the closed formA C A^T(relative 1e-6); at setting 0 it equals the offset's own error bar.- For a product
a bit equals the textbook first-order formulab^2 C_aa + a^2 C_bb + 2 a b C_ab(relative 1e-6). - In 300 seeded simulated fits (reading error 0.2) the scatter of
4 gain + offsetmatches the propagated error bar within 15 %. - Propagating with the planned covariance equals propagating with the covariance of a noiseless fit (relative 1e-6).
Design
designreturns 5 distinct picks from 15 candidates, and their information determinant is at least that of each of 30 random 5-point subsets.- Asked for 2 picks on the straight line, it returns the pair with the largest determinant among all 105 pairs, found by checking each one; asked for 4 of 12 settings on a line, its first two picks are the two ends.
- With
exchange=True, on 24 seeded problems (a decay with background, 3 to 5 picks from 12 candidates) the result has the largest determinant of all subsets, found by checking each one, in all 24 cases, while the greedy picks alone miss it in 6; the result is never worse than the greedy one, no single swap improves it, and the returned information matrix belongs to the returned indices; for example 9 above, the exchange triple is the best of all 4495 triples and the greedy triple is not (added in 0.2.0). - A
designresult gives the same error bars and covariance asinformationon the chosen settings (relative 1e-9), andrepeats_forreturns the samerfor either (added in 0.2.0; it was refused in 0.1.1). - The identity
det(A + g g^T) = det(A) (1 + g^T A^-1 g), which explains why each greedy pick can only add information, holds to 1 part in 10^9 on 20 random matrices. (This checks the identity, not thedesignfunction.)
Conformal prediction
conformal_quantileequals thek-th smallest score, compared with==, for alpha 0.05, 0.1 and 0.25.coverage_exact(29, 0.1)lies between1 - alphaand1 - alpha + 1/(n + 1), and 4000 seeded simulated trials hit it within 4 binomial standard deviations.- Too few scores, alpha outside 0 to 1 and negative scores are
refused;
conformal_intervalgivesprediction -/+ q. - For every alpha from 0.001 to 0.999 in steps of 0.001 and every n
from 1 to 120,
coverage_exactequalsk / (n + 1)withkcomputed in exact fractions from the decimal alpha, and refuses exactly when thatkexceeds n; for alpha 0.01, 0.05, 0.1, 0.2, 0.3 and 0.45 the minimum number of scores named in the refusal is the exact one (added in 0.2.0). - For n from 1 to 199 and six levels of alpha,
coverage_exactlies between1 - alphaand1 - alpha + 1/(n + 1).
Records and files
- An audit record is unchanged, compared with
==, afterjson.dumpsandjson.loads; its digest is the fit's; changing one reading by 1e-9 changes the digest;report_textcontains the expected lines and refuses a non-record. - The model's units note (text or a dictionary) reaches the fit
result and the audit record, survives the JSON round trip and
appears in
report_text; a record without it (as written by 0.1.x) still renders (added in 0.2.0). - Saving and loading a CSV file with 3 setting columns and sigmas
gives back identical arrays (
np.array_equal); a file with 1 setting column and no sigmas loads back with the right shape andsigmasNone; a wrong header is refused. Awkward values (1/3, 1e-300, -2.5e17, pi) come back identical, and an empty file, a file with no data rows, a row of the wrong length, a non-number, a negative sigma and a non-finite reading are each refused. - The version in the package matches
pyproject.tomlandCITATION.cff, and every name in__all__exists.
Added in 0.3.0
- A straight line fitted without
sigmasto readings scaled by 1, 1e-3, 1e-6, 1e-9, 1e-12 and 1e-15 gives the values ofnp.linalg.lstsqto 1e-6 of their standard errors and the error bars ofs^2 (X^T X)^-1to relative 1e-6, at every scale (0.2.0 was 1.3 standard errors off at 1e-12; this test fails on 0.2.0). Noiseless lines and exponential decays at scales 1, 1e-6 and 1e-12 still converge to the truth (relative 1e-12 and 1e-9). A weighted fit of the same small readings equals weighted least squares fromnp.linalg.lstsq. propagateaccepts a fitted covariance and gives the closed forma C a^T(relative 1e-6), but refuses the same covariance copied to 3 significant digits (it has a negative eigenvalue; 0.2.0 returned an error bar of 0) and a covariance with a correlation of 2. It accepts a parameter held fixed (zero variance and covariances) and a planned covariance with condition number 4e9, just inside the limit.goodness_of_fit: for every number of degrees of freedom from 1 to 80 and twelve values of chi2 from 1e-8 to 1200,p_valueequals the closed form computed in the test with the standard library (the finite Poisson sum for even degrees of freedom;erfcplus the recurrenceQ(a + 1, x) = Q(a, x) + x^a e^-x / Gamma(a + 1)for odd ones) to relative 1e-12, andp_value + p_value_low = 1. Small lower tails match-expm1(-chi2/2)(2 degrees of freedom) anderf(sqrt(chi2/2))(1 degree of freedom) to relative 1e-13.p_value_lowequals Simpson's-rule integration of the chi-squared density to 1e-10 for 20 cases, andp_valuematches the fraction of 20000 seeded chi-squared draws above three quantiles within 4.5 binomial standard errors. For 400 seeded straight-line fits with correct Gaussian errors the p-values are uniform: each tenth of (0, 1) holds 40 of them within 4.5 binomial standard deviations, and their mean is 1/2 within 4.5 standard errors.load_columnsreads a commented, comma-separated export with a quoted text column and a blank line back to the numbers typed into it (np.array_equal), and agrees exactly withnp.genfromtxton the same file; tab, semicolon and space separated tables agree with the written numbers and withnp.genfromtxt; a semicolon file with decimal commas and a byte-order mark is read correctly; a file written bysave_measurements_csvreads back identically; a preamble is skipped withskip_rows, and a file without a header is read by column positions. Each refusal in the list above fires with the expected message.
Added in 0.4.0
- A decay of 10 on a background of 1000, with its time constant
tau = 1e-9written in seconds (samples fromt = 0): the slopes match the exact derivatives to 1e-5 of each column's largest value, the planned error bars match the exact(J^T W J)^-1to relative 1e-5, and a fit from that guess equals the fit with exact slopes to 1e-4 of an error bar (0.3.0 refused all three; this test fails on 0.3.0). Where the fallback step already gave finite values the slopes are unchanged bit for bit. Arel_stepof 0, a negative, NaN, infinite or non-numeric one, and a fractionalnincoverage_exactare refused. design(greedy, and withexchange=True) returns the same indices and the same information matrix (compared with==in 0.4.0, to 1e-12 of the largest entry since 0.5.0) as the 0.3.0 loops, kept in the test as the reference, on 21 problems (a decay, a Gaussian peak with a sloped background and a plane in two settings, with 2 to 8 picks from 9 to 60 candidates, including exact ties from repeated candidates), also when the batches are cut to 7 candidates.inverse_predicton a straight line equals the NIST/SEMATECH e-Handbook formula (section 2.3.6.7.3), typed into the test, for the value (relative 1e-12) and the error bar (relative 1e-7), and the covariance of three readings equals the closed form. On an exponential decay with background it equals the closed-form inverse-tau ln((y - B) / A)and the error bar from its partial derivatives (relative 1e-6). For 20000 seeded replicate calibrations (least squares done in the test with NumPy) followed by a new reading, the scatter of the inverse values matches the planned error bar within 3 %. On a saturating response the first-order error bar matches seeded simulation within 2 % where it is accepted; where it is refused (the slope changes by 65 % within one error bar) the simulated scatter is more than 25 % larger. Each refusal fires.runs_test: for every n1 and n2 from 1 to 7 the tail probabilities, the mean and the variance of the number of runs equal the counts over all arrangements of the signs (relative 1e-12); for n1, n2 up to 900 and 700 the tails equal exact integer arithmetic (relative 1e-9). On 4000 seeded sets of random signs and of residuals of correct straight-line fits the false-alarm rate at the 5 % level is at most 5 % plus 4.5 binomial standard errors; on curved readings fitted with a line and errors stated 3 times too large, chi-squared gives p = 0.994 while the runs test gives p = 0.001.- The two tutorials run and print exactly the output shown in their
docstrings and in this README; their results agree with the values
used to simulate the data within 3 error bars, and their printed
numbers agree with each other (error bar parts adding in
quadrature, the repeat count, the error bar of
1/tau).
Added in 0.5.0
fit_xyon Pearson's data with York's weights (as tabulated by Cantrell, 2008): slope and intercept equal the values Cantrell's Table 2 gives in its "Williamson-York" row (-0.48053 and 5.4799, to the printed digits), and equal York's iteration, written out in the test from the equations as Cantrell gives them, to 1e-6 of an error bar (measured: 4e-10); the error bars equal York's standard errors at the adjusted points (relative 1e-7) and, rounded, the values printed by the R package bfsl (0.29497 and 0.05799, chi2 11.87 on 8 degrees of freedom, p = 0.1573). The ordinary weighted fit of the same data gives Cantrell's "Std Lst-Sqrs w/wgts" row (-0.61081 and 6.1001).- For a straight line, the minimum chi2 of
fit_xyequals the closed formsum (y - a - b x)^2 / (sigma_y^2 + b^2 sigma_x^2)(relative 1e-10) and the fitted settings equal the hand-derivedx + b sigma_x^2 r / (sigma_y^2 + b^2 sigma_x^2). For an exponential decay with errors in the times, the gradient of the minimized sum, computed in the test with exact derivatives, is zero at the solution (below 1e-5 in units of the error bars), and the covariance equals the effective-variance formula built from exact derivatives (1e-6 ofsqrt(C_ii C_jj)). In 300 seeded data sets the scatter of the fitted slope matches its error bar within 15 %, the mean slope is the truth within 4.5 standard errors and chi2 averagesn - p, whilefiton the same data is biased low by more than 10 standard errors. Exact settings give the result offit(1e-6 of an error bar), an exact second setting column is left as it is, and the fit is the same in seconds and in nanoseconds. Every refusal fires. - The conformal rank at large
n: for alpha = 0.0001 and n = 109998 (and for the first failingnof alpha 0.001, 0.0001, 0.1234, 0.05 and 0.1),coverage_exactandconformal_quantileuse the rank of exact rational arithmetic (this test fails on 0.4.0); for 193 alphas, including 1/3,1 - 0.9and alphas within 1e-9 of 0.1, and everynup to 2000, the rank equals that of 0.4.0. inverse_predictfor 40 readings of four models (a quadratic, an exponential decay, a saturating response and a logarithm) equals the 0.4.0 loop, kept in the test, within tolerances derived from the rounding of the model (the solution within2 x 64 eps F / |slope|for predictions of sizeF; slopes, error bars and covariances within twice the resulting relative bound); readings exactly on a scan point give that point; every refusal gives the 0.4.0 message for the same reading;full_cov=Falsegives the same values and slopes and error bars within the rounding bound of the different summation order; scanning the readings in small blocks gives the same numbers, compared with==.- The test of the batched
designagainst the 0.3.0 loops now compares the information matrices to 1e-12 of their largest entry (and would accept different picks only for a tie within 1e-9 in the log-determinant), instead of digit for digit. - The new tutorial prints exactly the output shown above and in its
docstring; the unknown is within 3 error bars of its simulated
value, the error bar parts add in quadrature, the reading part
equals
0.2 / sqrt(5) / c1, and the ratio of the two error bars onc1and the two chi2 values agree with the effective-variance factor1 + (c1 u_T / u_V)^2.
Added in 0.6.0
design_weightsfor polynomials of degree 1 to 5 on [-1, 1] gives the classical best design, equal weights1/(m + 1)at -1, 1 and the roots of the derivative of the Legendre polynomialP_m(each weight within 1e-6, less than 1e-6 elsewhere). The test does not take that design on trust: it checks with its own code, on 20001 points of [-1, 1], that the largestd(x)there equals the number of parameters, which proves it best. On a plain grid the line and the quadratic get 1/2 at the ends and 1/3 at -1, 0 and 1 (within 1e-9).- An exponential decay
A exp(-t / tau)gets half of the measurements att = 0and half att = tau, and the decay on a background gets thirds at 0, at1 - 3 e^-3 / (1 - e^-3)and at 3 (fortau = 1on [0, 3]); both are worked out by hand in the tests and proven best there in the same way. - For a decay on a background, a Gaussian peak and a quadratic
surface in two settings,
sum_i w_i d_i = p(relative 1e-8, withd_irecomputed in the test), the largestd_iis at mostp (1 + tol), andfisher,sigmaandcovare those ofM. The weights do not change when the parameters and settings are written in seconds or nanoseconds or all reading errors are scaled (1e-6); with exactlypcandidates they are1/pwhatever the reading errors. - For 300 random designs on 21 candidates for a quadratic, whose best
design is known exactly, the bounds of
design_efficiencycontain the exact D-efficiency (designs that cannot identify the parameters get 0); the same for the picks ofdesign. - In 24 small problems (4 models, 5 to 8 candidates,
n_totalfromptop + 5) thecountsare as good as the best of all multisets of measurements, found by checking each one. That does not prove the rounding is always best; its bounds are reported. - For the line with exact slopes and reading error 0.05,
repeats_foron the best weights returns 25 measurements for a target of 0.01, and 13 measurements at each end give error bars of0.05 / sqrt(26)(relative 1e-9). fit_xyon a logarithmic response with settings from 2e-3 to 1e3 and from 1e-3 to 1e3: the gradient of the minimized sum, computed in the test with exact derivatives, is zero at the solution (below 1e-5 in units of the error bars), and the covariance equals the effective-variance formula built from exact derivatives (this test fails on 0.5.0, which stopped at a gradient of 0.009 for the first set and refused the second).- The refusal of
conformal_quantilenames the level to enough digits (0.9999 for alpha = 0.0001), andload_columnsrefuses askip_rowsof 2.7 (both fail on 0.5.0). - Every Python example in this README runs and prints exactly the output shown below it (16 tests; before 0.6.0 only the tutorials were checked this way).
Added in 0.7.0
fit_xywithxy_correlationon Pearson's data with York's weights and correlations 0.5, -0.7 and a spread from -0.9 to 0.9: slope and intercept equal York's iteration with correlation, written out in the test from the algorithm listed by Wehr and Saleska (2017, Appendix A), to 1e-6 of an error bar (measured: 2e-9 at most); the error bars equal York's at the adjusted points (relative 1e-7; measured 6e-10), and chi2 equals the closed formsum (y - a - b x)^2 / (sigma_y^2 + b^2 sigma_x^2 - 2 b r sigma_x sigma_y)(relative 1e-10; measured 5e-15). For a plane in two settings, each with its own correlation, chi2 and the fitted settings equal the closed form worked out by hand in the test. For an exponential decay with errors in the times, the gradient of the correlated sum, computed in the test with exact derivatives and the inverse 2 x 2 covariance of each measurement, is zero at the solution (below 1e-5 of an error bar; measured 6e-10), and the covariance equals the effective-variance formula with the correlation term (measured 1.7e-9). In 200 seeded data sets with correlation 0.6 the scatter of the slope is 1.046 times its error bar and chi2 averages 12.83 for 13 degrees of freedom; leaving the correlation out gives 5.59. Correlation 0 gives the earlier fit exactly, digest included, and every refusal fires.propagate_mc: for linear functions the result is the linear map of the result for the parameters themselves (relative 1e-12) and agrees withpropagatewithin the random error; for the product of two correlated Gaussian parameters the mean and variance are the exact ones from the moments of a Gaussian, and forexpof a Gaussian the mean, standard deviation and both interval ends are the exact lognormal ones, each within 4.5 standard errors of the draws (measured: at most 1.25). A parameter with zero variance stays fixed, the same seed repeats the result, and every refusal fires.- The three corrections below, each with a test that fails on 0.6.0:
the conformal rank for long decimals and fractions (against exact
rational arithmetic, for 400 random decimals of 9 to 15 digits at
nup to 1e7, and for 1/3 atn= 600000001); the slopes of a fringeA cos(2 pi df t + 0.3) + 0.5atdf = 0Hz with times in seconds over 1 ms, 10 us, 0.1 us and 1 ns (slopes within 1e-6 of the exact ones, measured 1e-8; planned and fitted covariances within 1e-6, measured 6e-9); andfit_xyfor a saturating response with settings at zero (gradient below 1e-5 of an error bar, measured 3e-9). A parameter whose first derivative is really zero (it enters asth^3) keeps its zero slopes and is still refused. - README examples 17 and 18 print exactly what is shown (18 example tests in all).
Every refusal listed in "When it refuses, and why" is checked to
fire, including a fit that does not converge within max_iter steps
(a RuntimeError) and a parameter that no reading responds to (an
all-zero slope column: information reports it not identifiable,
fit and design refuse). A Model whose units note is a
dictionary can be hashed (used as a dictionary key or in a set), and
equal models hash equally.
Corrections in earlier versions
0.7.0 fixed three wrong answers.
- Slopes for a parameter at zero whose natural size is large. For
a parameter at zero the numerical slopes use a step of 1e-9 in the
parameter's own units. Since 0.2.0 that step was checked against
smaller ones, but never against larger ones. For a detuning
dfof 0 Hz in a fringeA cos(2 pi df t + 0.3) + 0.5with times in seconds, a step of 1e-9 Hz moves the phase by about 6e-14 over 10 us, close to rounding. Over 1 ms the slope was 1e-4 wrong and over 10 us 1.2 % wrong (planned error bar ondf709.16 Hz instead of 710.85 Hz). Over 0.1 us the slope was rounding only: the plan was refused as not identifiable, andfitreturned an error bar ondfof 42751 Hz instead of 71085 Hz (40 % too small) and one onAof 0.00190 instead of 0.00321. 0.7.0 enlarges the step in such cases (seeModel.numeric_jacobianabove) and gives the exact values to 1e-8. Slopes whose rounding error stays below 1e-4 are unchanged, bit for bit (the tests of earlier versions check this), and so is every README example and tutorial. fit_xyslopes at settings near zero. Where a setting is at or near zero, the slopedf/dxused a step of 1e-6 of the largest setting in its column, unchecked. For a responsea + b x / (x + 0.01)with settings from 0 to 1000 that step is a tenth of the bend. On the data of the new test 0.6.0 gave a = 1.02852766 +/- 0.01717228 and b = 1.97405205 +/- 0.01803276, chi2 = 12.816825; 0.7.0 gives a = 1.02850360 +/- 0.01714371 and b = 1.97407688 +/- 0.01800382, chi2 = 12.816822, at which the gradient of the minimized sum, computed with exact derivatives, is zero to 3e-9 of an error bar (0.6.0: 0.003). The values moved by 0.0014 of an error bar and the old error bars were 0.16 % and 0.17 % too large. The step is now checked against smaller ones, as for parameters.- The conformal rank for an alpha with more than 8 significant
digits. Such an alpha used the rule of 0.4.0, which read
alpha = 0.099999999999as 0.1: forn = 9it returnedk = 9andcoverage_exact(9, 0.099999999999)= 0.9, below the promised 1 - alpha = 0.900000000001 (and the same at everyn + 1that is a multiple of 10). Foralpha = 1/3the rank was one too small fromnof about 5e8. Since 0.7.0 every alpha is read as an exact number (see "When the model may be wrong" above), son = 9is refused for that alpha andcoverage_exact(19, 0.099999999999)is 0.95. Decimals of up to 8 digits, 1/3, 2/3 and 1/7 give the same rank as before at everynup to 2000 (a test checks this).
0.6.0 fixed one wrong answer.
fit_xyused too large a step for the slopes with respect to settings spread over many decades. The slopedf/dxof every setting was taken with a step of 1e-6 of the largest setting in its column. For settings from 2e-3 to 1e3 that step is 1e-3, half the smallest setting, so the slopes there were wrong and the fit stopped where the minimized sum is not at its minimum. For a responsea + b log(x)with 13 such settings, each with a 5 % error (the data of the new test), 0.5.0 returned a = 0.99719970 +/- 0.00896739 and b = 0.49912153 +/- 0.00221872, chi2 = 10.286626; 0.6.0 returns a = 0.99716394 +/- 0.00890988 and b = 0.49913337 +/- 0.00219089, chi2 = 10.286532. The values moved by 0.004 and 0.005 of an error bar, the fitted settings by up to 0.006 of theirs, and the old error bars were 0.6 % and 1.3 % too large. An independent fit of the same sum with exact derivatives (SciPy'sleast_squares, run outside the test suite) agrees with 0.6.0 to 3e-10 of an error bar. With settings from 1e-3 the step reached zero,log(0)is not finite, and 0.5.0 refused the fit. Since 0.6.0 the step is 1e-6 of each setting, and the old step is kept only where that does not resolve the change, asModel.numeric_jacobiandoes for parameters. Other fits change only at the level of the search's stopping rule: on the Pearson-York data, 20 seeded decays with errors in the times and a two-setting model, by at most 7e-8 of an error bar (values) and 1.5e-9 (relative, error bars).
Also in 0.6.0: the refusal of conformal_quantile printed the level
to 3 digits, so any alpha below 0.0005 said "cannot certify level 1"
(alpha = 0.0001 now says 0.9999); and load_columns(skip_rows=2.7)
silently skipped 2 lines, and now refuses, as design has refused
n_pick=2.5 since 0.3.0.
0.5.0 fixed one wrong answer.
- The conformal rank was one too small for some alphas at large n.
The rank
k = ceil((n + 1)(1 - alpha))took any product within 1e-9 (relative) above an integer to be that integer, to undo the binary rounding of a decimal alpha. For largenthat tolerance is larger than the true fraction: for alpha = 0.0001 (a 99.99 % band) and n = 109998 calibration scores, (n + 1)(1 - alpha) is 109988.0001, sokshould be 109989, but 0.4.0 used 109988.coverage_exactthen returned 0.99989999909, below the promised 1 - alpha = 0.9999, andconformal_quantilereturned the score one rank too low. With alpha = 0.001 the first suchnis 1001998. Since 0.5.0 a decimal alpha of up to 8 significant digits (also when it was computed, as1 - 0.9) is read exactly andkis computed in integer arithmetic;coverage_exact(109998, 0.0001)is now 0.99990909. For every alpha andnthe earlier tests covered (alpha 0.001 to 0.999,nup to 3000) the rank is unchanged. The error was at most one rank, so the coverage was too low by at most 1/(n + 1), but the guarantee is stated exactly, so it was wrong.
Also in 0.5.0: the source distribution left out CITATION.cff and
examples/, so one test failed and three were skipped when the suite
was run from it; it now includes them.
0.4.0 fixed one wrong refusal.
- A small parameter whose effect is small next to the largest
reading could be refused as "non-finite". For a parameter whose
relative step is too small to show next to the largest prediction,
the slopes fall back to the 0.1.0 step
1e-6 * max(|theta|, 1e-3), which is 1e-9 for any parameter below 1e-3. For a time constant of 1e-9 s that step is the parameter itself:tau - h = 0. A decay of 10 on a background of 1000 (any amplitude below about 1/73 of the background) withtau = 1e-9and samples fromt = 0then divided 0 by 0, andinformation,designandfitstopped with "the forward function returned non-finite predictions; check theta and x", although the model is finite at thattau. 0.4.0 divides such a step by 10 until the model is finite and then checks it as before: the planned error bar ontauis 1.4189183e-10 s, equal to the exact value from the analytic slopes to 6e-9 relative. Results that 0.3.0 could compute are unchanged.
Also in 0.4.0: Model.numeric_jacobian(rel_step=0) (or a negative
step) failed with an UnboundLocalError and now explains the
problem; coverage_exact(29.9, 0.1) returned the answer for n = 29
and now refuses.
0.3.0 fixed two wrong answers.
- A fit without
sigmascould stop too early when the readings are small numbers in their own units. Withoutsigmasthe quantity being minimized is the sum of squared residuals, in the readings' units squared. The search stopped once a step changed it by less thantol * (1 + sum), and that fixed 1 is enormous for readings of order 1e-12 (a current of a few picoamperes written in amperes): every change was below it, and the fit stopped after its first, still damped, step. For a straight line through 12 such readings (gain 2e-12 A/V, noise 5e-14 A) 0.2.0 returned gain 1.99116e-12 and offset 1.35943e-13 after 1 step, 1.30 and 1.15 standard errors away from the least-squares answer (2.00051e-12 and 1.10355e-13), with error bars about 10 % too large (7.18e-15 instead of 6.54e-15 on the gain). With readings of order 1e-9 and relative noise 1e-5 it stopped 0.60 standard errors off. 0.3.0 measures the change in units of the residual variance (at most 1) and gives the least-squares answer to 1e-6 of a standard error at every scale tested. Fits withsigmasare unchanged bit for bit; fits without them whose residual variance is below 1 may take a step or two more and then change far below their error bars (in 300 random straight-line fits with readings from 1e-3 to 1e3, 253 gave identical results and the largest change was 3.4e-6 of a standard error, the size of the rounding differences betweenfitandnp.linalg.lstsqthemselves). If you used 0.2.0 or earlier withoutsigmason readings much smaller than 1, please re-run those fits. propagatereturned an error bar of 0 for an invalid covariance. A covariance that is not positive semidefinite gives some combination of parameters a negative variance. That happens, for example, when the covariance of a strongly correlated fit is copied to a few digits: a line measured at settings 100 to 101 has slope and offset correlated at -0.999995, and its covariance rounded to 3 significant digits has a negative eigenvalue. With it, the error bar of the predicted reading at 100.5 came out as 0.0 (the right value is 0.0144), with a negative variance in the returnedcov. Such a matrix is now refused with an explanation.
0.2.0 fixed three wrong answers.
- Slopes for a parameter at zero. When a parameter was exactly zero (or too small for its relative step to show), 0.1.1 used a fixed step of 1e-9 in the parameter's own units, which can be far too large. For a Gaussian pulse written in seconds, with center 0 and width 1 ns, that step equals the width: the slope with respect to the center was 31 % wrong, and both the planned and the fitted error bar on the center came out as 6.687e-12 s instead of the exact 5.312e-12 s (26 % too large). The step is now checked against a 10 times smaller one and reduced while they disagree; 0.2.0 gives 5.312e-12 s. Where the fixed step was already accurate the slopes are unchanged, bit for bit. If you used 0.1.x with a parameter at or near zero whose natural size is far from 1 in its units, please re-run those results.
repeats_forrefused the output ofdesignwith the message "the plan is not identifiable", becausedesigndid not reportidentifiable. It now does (and also returnscov).- Conformal rank for some alpha. In binary floating point
1 - 0.7is slightly more than 0.3, so for alpha = 0.7 and n = 9 the rankceil(10 * 0.3)came out as 4 instead of 3:conformal_quantilereturned the 4th smallest score andcoverage_exact(9, 0.7)returned 0.4 instead of 0.3. In a scan of all alphas 0.001 to 0.999 (steps of 0.001) and n up to 3000 this happened for 255 of the 999 alphas (3595 alpha/n pairs), none of them 0.01, 0.02, 0.05, 0.1, 0.2 or 0.25. In every case the rank was one too large, so the band was slightly wider than needed, never narrower.
0.1.1 fixed a unit-dependence in the derivative step. In 0.1.0,
Model.jacobian (used by information, design and fit) never
used a step smaller than 1e-9 in absolute terms. For a parameter
smaller than 1e-3 in its own units that step was too coarse, and for
a time constant of 1e-9 s it was as large as the parameter itself.
The planned error bars then depended on the units the parameter was
written in, a noiseless fit could stop away from the truth (0.987 and
0.938 ns instead of 1 and 1 ns in the new test's model), and a model
that divides by such a parameter was refused as non-finite. The step
is now 1e-6 times the parameter's size, falling back to the 0.1.0
step only when that relative step is too small to change the
predictions measurably (a parameter that is exactly zero, or one that
is tiny next to the rest of the prediction, such as a slope of 1e-12
beside an offset of 1). Results for parameters of size 1e-3 or more
do not change. If you used 0.1.0 with parameters smaller than 1e-3
in their own units, please re-run those results.
Also in 0.1.1: CI now runs Python 3.10 (claimed but not tested before) and the oldest allowed NumPy. The 0.1.0 release notes said the tests recompute the greedy rule (they do not; the checks are the ones listed above) and that planner and fit agree exactly (the tests assert 1 part in 10^6).
The full history is in CHANGELOG.md.
Limits
- The error bars assume independent, Gaussian ("bell-curve") reading
errors. For a model that is not a straight-line function of its
parameters, they come from a linear approximation around the
guessed or fitted parameters and are approximate; the planned error
bars also depend on how good your guess is. Errors that are
correlated from one reading to the next (a drifting baseline shared
by all readings, say) are not supported:
sigmasis one error bar per reading, not a covariance matrix. Allowing one would change the rules forsigmasin every function that takes it (planning, design, fitting, files), and is left for a later release. Onlyfit_xy(since 0.7.0) takes a correlation, between the error of a setting and that of its own reading. - Unless you give
jac, slopes are computed by finite differences, not exact derivatives. For a parameter at zero the step is found by shrinking a 1e-9 step until two successive steps agree, and (since 0.7.0) by enlarging it when rounding swamps it; both assume the model is smooth in that parameter. A step whose rounding error is below 1e-4 of the slopes is not enlarged (that keeps earlier results unchanged), so such slopes can carry an error of up to about that size, and an enlarged step is used only when a step 10 times larger agrees with it. When in doubt, write the parameter in units where its natural size is near 1, or givejac. labplancannot check a hand-writtenjac; a wrong one gives wrong error bars. Compare it once withModel.numeric_jacobian, as in example 10.propagateis first order: exact for straight-line functions of the parameters, an approximation otherwise that is good when the function is close to a straight line within about one error bar.propagate_mc(since 0.7.0) needs no such approximation, but it assumes that the parameters are Gaussian with the given covariance (for a fit of a model that is not a straight line in its parameters, that is itself the first-order description), and its answers carry a random error that shrinks only like1 / sqrt(n_draws). It callsfunconce per draw, which is slow for an expensivefunc. A quantity whose mean does not exist in theory (1 / awhenacan reach zero) still gets a finite average from the draws; check that the interval makes sense. Both refuse a covariance that is not positive semidefinite, but they cannot tell when a valid one was rounded: copy covariances at full precision.goodness_of_fitassumes independent Gaussian reading errors of the stated size. Its chi-squared distribution is exact for models that are straight-line functions of their parameters and approximate otherwise. A small p-value says that the model or the stated errors are wrong, not which one, and a large one does not prove the model right: with few readings or large errors the test has little power.designis a greedy heuristic: it adds the best single setting at each step and does not prove that the chosen set is the best possible.exchange=Trueimproves it until no single swap helps, which in the tests reached the best subset every time, but that is still not a proof. Since 0.6.0design_efficiencygives proven bounds on how close any design comes to the best one on the same candidates (example 16). Each swap pass tries every chosen setting against every unused one; since 0.4.0 these are scored in batches (3000 candidates take a fraction of a second), but the work still grows with the number of picks times the number of candidates for every pass. It picks each candidate at most once; userepeats_forto repeat the whole design, ordesign_weights(since 0.6.0) to share measurements among the candidates with repeats.design_weightsanddesign_efficiencyjudge a design by the determinant only (the joint uncertainty of all parameters). The design that is best for the error bar of one parameter, or of one predicted reading, can be different; check such error bars withinformationorpropagate. Searching for that design is not included: it can need fewer settings than parameters, where the information matrix cannot be inverted and the search and its proof of optimality work differently. For a model that is not a straight-line function of its parameters the answer depends on the guessed parameters, as forinformation. "Best" means best among the candidates you give: the best setting can lie between two candidates, and on a fine grid its weight is then shared between neighbors (0.8 and 0.9 in example 16).tollimits the efficiency, not the weights: near the best design the determinant is flat, so weights that are withintolin efficiency can differ from the best weights by more thantol. The whole numberscountscome from rounding and are not proven best (their efficiency bounds are returned). Each round of the search costs about the number of candidates times the square of the number of parameters; on a 2-CPU machine a quartic on 2001 candidates took 0.6 s and a polynomial of degree 5 on 501 candidates 1.2 s (medians of 3 runs).inverse_predictneeds settings that are one number per measurement and a bracket in which the model reaches the reading exactly once. It scans the bracket atn_scanpoints, so two crossings closer together than the scan spacing are not seen (no scan can rule them out without knowing how fast the model can turn back; narrow the bracket or raisen_scan). Its error bar is first order, likepropagate; it refuses when the slope changes by more than 10 % within one error bar, and below that the error bar can still be a few percent too small where the curve bends (in the tests the simulated scatter was 1.014 times the error bar at a slope change of 10.5 %).fit_xyassumes Gaussian errors in every reading and every setting, independent from one measurement to the next. Since 0.7.0 the error of a setting may be correlated with that of its own reading (xy_correlation), but the errors of two settings of one measurement must stay independent of each other (a full covariance per measurement is not taken). Its error bars are first order, like those offit, and its chi2 follows the chi-squared distribution only approximately for a model that is not a straight line in its parameters and settings. With large setting errors on a curved model, the fitted true settings can be biased; check with simulation when the setting errors are not small next to the curvature. Its slopes with respect to the settings are finite differences with a step of 1e-6 of each setting; a setting at or very near zero gets 1e-6 of the largest setting in its column instead, checked against smaller steps since 0.7.0. That check assumes the model is smooth there; for a model with a kink at zero (such asabs(x)) no finite difference is right, andfit_xycannot tell. Each measurement's prediction must depend only on its own row of settings. The work grows with the number of measurements times the number of setting columns (there is one unknown per uncertain setting).inverse_predictreturns, by default, the full covariance of all readings, which needs memory forn x nnumbers: passfull_cov=Falsefor long series.runs_testlooks only at the signs, so it needs enough residuals to have power (with 10 residuals, 5 of each sign, the smallest possiblep_valueis 2/252 = 0.008). For residuals of a fit it is approximate (the residuals are not exactly independent); in the tests that made it more cautious, not less.- The conformal guarantee is an average over calibration sets and new
measurements, not a promise at each setting, and it needs the
calibration data to be exchangeable with the new measurement:
calibration data from last month's instrument state do not certify
next month's drift. The tighter bound
1 - alpha + 1/(n + 1)assumes scores without ties. Since 0.7.0 everyalphais read as an exact number and the rank is exact for it. But a floating-point number cannot say which number you meant:1/3and the decimal0.3333333333333333are the same float, andlabplanreads it as 1/3 (a fraction with a denominator of at most 10^6 comes before a long decimal). If you meant the long decimal, the rank for it can be one larger at somen; the coverage for 1/3 then still holds, but falls short of your decimal by less than 1e-16 (and by at most 1e-15 for any alpha read as a fraction). save_measurements_csvandload_measurements_csvuselabplan's own CSV layout (x1, ..., y, sigma). Other delimited text tables are read withload_columns(since 0.3.0), which needs one header line (or none), one row per line (no line breaks inside quoted fields) and names given exactly as in the header. It does not read binary instrument formats or spreadsheet files (.xlsx); export those as text first.- No physics ships with the package. Your model and its
referencecarry the physics.
Where it comes from
Nine research packages in this organization -- covering color-center
spins, squeezed light, spin-squeezed clocks, Raman maps, single-photon
emitters, superconducting detectors, band structure, semiconductor
heterostructures and photonic fabrication -- each grew the same
planning-and-calibration loop for its own physics. labplan is that
loop extracted and generalized into one package that depends only on
NumPy.
The statistics are standard. Weighted least squares and the
information matrix are textbook material (e.g. Cox & Hinkley,
Theoretical Statistics (1974); any statistics text under
"Cramer-Rao bound"). D-optimal design follows F. Pukelsheim, Optimal
Design of Experiments, SIAM (2006), and the swap refinement the
exchange idea of V. V. Fedorov, Theory of Optimal Experiments,
Academic Press (1972). The check that best weights have a largest
variance function equal to the number of parameters is the
equivalence theorem of J. Kiefer and J. Wolfowitz, "The equivalence
of two extremum problems", Canadian Journal of Mathematics 12,
363-366 (1960). The chi-squared test computes the regularized
incomplete gamma functions (NIST Digital Library of Mathematical
Functions, chapter 8) by the series and continued fraction of W. H.
Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery,
Numerical Recipes, 3rd ed., Cambridge University Press (2007),
section 6.2; the Birge ratio is from R. T. Birge, Phys. Rev. 40, 207
(1932). The runs test is A. Wald and J. Wolfowitz, "On a test whether
two samples are from the same population", Ann. Math. Statist. 11,
147-162 (1940), doi:10.1214/aoms/1177731909. The straight-line case of
inverse_predict is the propagation-of-error formula of the
NIST/SEMATECH e-Handbook of Statistical Methods, section 2.3.6.7.3
(https://itl.nist.gov/div898/handbook/mpc/section3/mpc3673.htm). The
straight-line case of fit_xy is D. York et al., "Unified
equations for the slope,
intercept, and standard errors of the best straight line", Am. J.
Phys. 72, 367-375 (2004), doi:10.1119/1.1632486; its test data and
reference values are from C. A. Cantrell, "Technical Note: Review of
methods for linear least-squares fitting of data and application to
atmospheric chemistry problems", Atmos. Chem. Phys. 8, 5477-5487
(2008) (https://acp.copernicus.org/articles/8/5477/2008/), Tables 1
and 2. York's equations with a correlation between the errors of x
and y, used in the tests of xy_correlation, are taken from the
algorithm listed in C. M. Wehr and S. R. Saleska, "The long-solved
problem of the best-fit straight line: application to isotopic
mixing lines", Biogeosciences 14, 17-29 (2017), Appendix A
(https://bg.copernicus.org/articles/14/17/2017/), which cites York et
al. (2004), eqs. (13).
First-order propagation of uncertainty with
covariances is the "law of propagation of uncertainty" of JCGM
100:2008, Evaluation of measurement data -- Guide to the expression
of uncertainty in measurement (sections 5.1.2 and 5.2). The Monte
Carlo method of propagate_mc is that of JCGM 101:2008, Evaluation
of measurement data -- Supplement 1 to the "Guide to the expression
of uncertainty in measurement" -- Propagation of distributions using
a Monte Carlo method: a multivariate Gaussian input (clause 6.4.8)
and the probabilistically symmetric coverage interval between the
(1 - p)/2 and (1 + p)/2 quantiles (clauses 3.15 and 5.3.3). Split
conformal prediction follows Vovk, Gammerman and Shafer, Algorithmic
Learning in a Random World, Springer (2005); Lei et al., J. Am. Stat.
Assoc. 113, 1094 (2018); and Angelopoulos and Bates,
arXiv:2107.07511.
Citing, support and license
If labplan helps your work, please cite it with the concept DOI
10.5281/zenodo.22826765,
which always resolves to the latest release.
CITATION.cff has the details.
Written and maintained by Tanvir Mahmud Mahim (Department of Electrical and Electronic Engineering, BRAC University), who reviews every change and takes the final decision on scope and releases. Design questions are discussed in the open in issues and pull requests. Usage questions and bug reports are welcome in the issue tracker. A docstring that leaves a unit or a convention unclear counts as a documentation bug, not user error. The standing rule of CONTRIBUTING.md binds the maintainer exactly as it binds contributors: a change that touches the statistics arrives with a test, and a claim arrives with its source. While the version is below 1.0 the programming interface may still change between minor versions; such changes are called out in the release notes.
Licensed under Apache-2.0.
Metadata
Release files for labplan 0.7.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| labplan-0.7.0.tar.gz | 238.8 kB | With provenance | Details for labplan-0.7.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| labplan-0.7.0-py3-none-any.whl | Python 3 | none | any | Details for labplan-0.7.0-py3-none-any.whl |
Total release size: 337.4 kB
Release files / labplan-0.7.0.tar.gz
| Download URL | labplan-0.7.0.tar.gz |
|---|---|
| Size | 238.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
775c3fe3109923481212b4fb601cbeee94cd96d0d8770de477e6f78a0e4cdeb1
|
|
BLAKE2b-256 checksum How to use checksums |
2c6b7c45b11600c65209080a61aef379d7f247d5f1a54b351dc1a661c42deacb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logRelease files / labplan-0.7.0-py3-none-any.whl
| Download URL | labplan-0.7.0-py3-none-any.whl |
|---|---|
| Size | 98.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b882d7268148f896fc003539a9db448f45d9084cb349562f9aad42744bad14de
|
|
BLAKE2b-256 checksum How to use checksums |
5799cfd7d768d2fe9eb576b2c88e8baf11c2648a1e190ce509b7620f54356f5a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logSecurity for labplan 0.7.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for labplan-0.7.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.