Experiments#

High-level experiment API built on top of tinto.runners.

This module consolidates the notebook boilerplate of parameter sweeps + Monte-Carlo aggregation + plotting into a single Experiment object. The design is deliberately thin: the heavy lifting stays in tinto.runners and the Config/Graph/scheduler/solver stack, while Experiment adds three amenities:

Matplotlib and tqdm are imported lazily; neither is a hard dependency.

class tinto.experiments.Experiment(name: str | None = None, iterator: Iterator | ProductIterator | None = None, **params: Any)[source]#

Bases: object

High-level entry point binding sweeps to a Monte-Carlo runner.

An Experiment bundles one or more campaigns. Each campaign pairs a name, an optional Iterator (or ProductIterator) sweeping one or several parameters, and a dict of fixed keyword arguments forwarded to the runner. Combining experiments with + (or sum()) concatenates their campaigns; run() executes every campaign sequentially and stores the per-replica moments under results.

Parameters:
  • name (str, optional) – Campaign label, used as key in results and as plot legend.

  • iterator (Iterator or ProductIterator, optional) – Sweep definition. If None, the campaign is a single point (useful only when combined with others).

  • **params (keyword arguments) – Runner arguments that stay fixed across the sweep (typically starter, scheduler, solver, n_trials).

Examples

A minimal 1-D sweep evaluated with an injected dummy runner:

>>> def dummy(n):
...     return {"steps": (float(n), 0.0, 0.0), "activations": (0.0, 0.0, 0.0)}
>>> exp = Experiment("demo", iterator=Iterator("n", [1, 2, 3]))
>>> _ = exp.run(runner=dummy, progress=False)
>>> exp.results["demo"]["axes"]
('n',)
>>> exp.results["demo"]["data"][(2,)]["steps"]
(2.0, 0.0, 0.0)

Two campaigns combined with + keep distinct entries in results:

>>> a = Experiment("A", iterator=Iterator("n", [1]))
>>> b = Experiment("B", iterator=Iterator("n", [2]))
>>> sorted((a + b).to_dict_keys())
['A', 'B']
_infer_x(x, hue, selected)[source]#

Resolve an omitted x when the selected campaigns leave no ambiguity.

Collects every axis appearing in the selected campaigns, drops hue if present, and returns the unique remaining axis if any. Otherwise leaves x untouched.

_select(campaign)[source]#

Return an ordered {name: camp} dict filtered by campaign.

campaign is None (all), a string (one), or an iterable of strings (a subset). Unknown names are dropped silently.

_xy_sigma(metric, x, hue, campaign)[source]#

Yield (label, xs, ys, sigma) for each selected series.

Pulls the per-point mean and variance via series() and derives the standard error of the mean sigma_i = sqrt(var_i / (n_trials - 1)). Shared by fit() and fit_fractions().

fit(metric: str = 'steps', basis=None, x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None) → dict[source]#

Fit a law to a metric’s mean across campaigns, with error bars.

Convenience bridge to tinto.estimate. For each series (same {label: ...} selection as series()/plot()), it pulls the per-point mean and variance, derives the standard error of the mean sigma_i = sqrt(var_i / (n_trials - 1)) (the n_trials / (n_trials - 1) term turns the population variance returned by tinto.runners.mc() into the unbiased estimate), and runs tinto.estimate.fit().

The default basis is affine (a*x + b); pass a custom basis such as tinto.estimate.power_basis() for inverse-power laws f(k) = a/k + b/k**2. The fitted coefficients can then be turned into exact fractions with tinto.estimate.recover().

Parameters:
Returns:

{label: fit_dict} with the same labels as series(), each value being the dict returned by tinto.estimate.fit().

Return type:

dict

Raises:

ValueError – If a selected campaign has no recorded n_trials (e.g. it was run with a custom runner that does not take it).

Examples

A dummy runner with exactly affine means and unit variance: the fit recovers the slope and intercept.

>>> import numpy as np
>>> def dummy(n, n_trials):
...     return {"steps": (2.0 * n + 1, 1.0, 0.0),
...             "activations": (0.0, 1.0, 0.0)}
>>> exp = Experiment("demo", iterator=Iterator("n", [1, 2, 3]), n_trials=100)
>>> _ = exp.run(runner=dummy, progress=False)
>>> r = exp.fit(metric="steps")
>>> np.round(r["demo"]["beta"], 6).tolist()
[2.0, 1.0]
>>> r["demo"]["dof"]
1
fit_fractions(metric: str = 'steps', basis=None, x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None, **kwargs) → dict[source]#

Recover exact fractions for a metric’s law, coefficient by coefficient.

Same (x, y, sigma) assembly as fit(), but forwarded to tinto.estimate.fit_fractions(), which jointly fits, anchors the surest coefficient as a fraction, and refits the rest (see that function for the anchor-and-refit rationale). Extra keyword arguments (k, max_denominator, resolution, …) pass straight through.

Parameters:
Returns:

{label: result} with the same labels as series(), each value the dict returned by tinto.estimate.fit_fractions().

Return type:

dict

Examples

>>> def dummy(n, n_trials):
...     return {"steps": ((2 / 3) * n - 1 / 3, 1.0, 0.0),
...             "activations": (0.0, 1.0, 0.0)}
>>> exp = Experiment("demo", iterator=Iterator("n", range(10, 60)), n_trials=10**6)
>>> _ = exp.run(runner=dummy, progress=False)
>>> exp.fit_fractions(metric="steps")["demo"]["fractions"]
[Fraction(2, 3), Fraction(-1, 3)]
plot(metric: str = 'steps', stat: str = 'mean', x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None, scale: str = 'linear', ax=None, **plot_kwargs)[source]#

Light matplotlib rendering of a metric across campaigns.

Thin wrapper around series(): pulls the {label: (xs, ys)} dict and renders one line per entry on ax.

Parameters:
  • metric (str, default=’steps’) – Key into the runner’s output dict ("steps" or "activations" when using tinto.runners.mc()).

  • stat (str, default=’mean’) – One of "mean", "var", "m3"; indexes the 3-tuple returned by the runner.

  • x (str, optional) – Name of the parameter to place on the x-axis. When omitted, inferred from the selected campaigns: if exactly one axis (excluding hue) appears, it is used. Campaigns missing the resolved axis are skipped.

  • hue (str, optional) – Name of a second parameter to use as series. If None, each campaign contributes a single line.

  • campaign (str, iterable of strings, or None,) – default=``None`` Restrict to a subset of campaigns. See series().

  • scale (str, default=’linear’) – One of "linear", "logx", "logy", "loglog". Applied via set_xscale() / set_yscale() after the lines are drawn.

  • ax (matplotlib.axes.Axes, optional) – Existing axes. Created via matplotlib.pyplot.gca() when None.

  • **plot_kwargs (keyword arguments) – Forwarded to matplotlib.axes.Axes.plot(). User kwargs take precedence over the ones set internally (notably label), so passing label="foo" overrides the auto-generated labels — shared across every series, which produces a duplicated legend when more than one line is drawn. For per-series customization, prefer series() + a manual matplotlib loop.

Returns:

The axes drawn on.

Return type:

matplotlib.axes.Axes

Examples

>>> import matplotlib.pyplot as plt
>>> def dummy(n):
...     return {"steps": (float(n), 0.0, 0.0), "activations": (0.0, 0.0, 0.0)}
>>> exp = Experiment("demo", iterator=Iterator("n", [1, 2, 3]))
>>> _ = exp.run(runner=dummy, progress=False)
>>> fig, ax = plt.subplots()
>>> _ = exp.plot(x="n", ax=ax)
>>> ax.get_xlabel(), ax.get_ylabel()
('n', 'steps (mean)')
>>> len(ax.lines)
1
>>> plt.close(fig)

Cartesian-product campaigns light up multiple series via hue:

>>> def dummy2(n, kind):
...     return {"steps": (float(n) + {"a": 0.0, "b": 1.0}[kind], 0.0, 0.0),
...             "activations": (0.0, 0.0, 0.0)}
>>> exp2 = Experiment(
...     "multi",
...     iterator=Iterator("n", [1, 2]) * Iterator("kind", ["a", "b"]),
... )
>>> _ = exp2.run(runner=dummy2, progress=False)
>>> fig, ax = plt.subplots()
>>> _ = exp2.plot(x="n", hue="kind", ax=ax)
>>> len(ax.lines)
2
>>> plt.close(fig)

When x is omitted it is inferred from the campaign axes. Passing hue alone is enough to disambiguate a 2-D campaign:

>>> fig, ax = plt.subplots()
>>> _ = exp.plot(ax=ax)
>>> _ = exp2.plot(hue="kind", ax=ax)
>>> [line.get_label() for line in ax.lines]
['demo', 'multi / kind=a', 'multi / kind=b']
>>> plt.close(fig)

Ambiguous axes (two candidates, no hue), explicit x not in axes, hue not in axes, or a 2-D campaign with x but no hue, all skip silently:

>>> fig, ax = plt.subplots()
>>> _ = exp2.plot(ax=ax)
>>> _ = exp.plot(x="unknown", ax=ax)
>>> _ = exp.plot(x="n", hue="unknown", ax=ax)
>>> _ = exp2.plot(x="n", ax=ax)
>>> len(ax.lines)
0
>>> plt.close(fig)

Filter to one campaign and pick a log-log scale. When ax is omitted, matplotlib.pyplot.gca() is used:

>>> bis = Experiment("bis", iterator=Iterator("n", [1, 2, 3, 4]))
>>> both = (exp + bis).run(runner=dummy, progress=False)
>>> ax = both.plot(x="n", campaign="bis", scale="loglog")
>>> ax.get_xscale(), ax.get_yscale()
('log', 'log')
>>> len(ax.lines)
1
>>> plt.close("all")

Plot kwargs take precedence over the auto-generated label:

>>> fig, ax = plt.subplots()
>>> _ = exp.plot(x="n", label="override", color="red", ax=ax)
>>> ax.lines[0].get_label()
'override'
>>> plt.close(fig)
report(metric: str = 'steps', basis=None, names=None, x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None, **kwargs)[source]#

Tabulate recovered fractions across campaigns, ready to display.

Runs fit_fractions() and hands the result to tinto.estimate.fractions_table(), which returns a table that prints as aligned ASCII in a terminal and renders as HTML in a notebook (Jupyter calls its _repr_html_ automatically — the same .auto spirit as tqdm, with no environment sniffing). Each row shows, per coefficient, either value -> fraction (anchored) or value +/- error (left free), plus chi2_red, pvalue and a one-word fit verdict; a high verdict means the fractions are not to be trusted.

Coefficient names default to tinto.estimate.basis_names() applied to basis — ["1", "x"] for the affine default, ["x^-1", "x^-2"] for power_basis([-1, -2]), positional c0, c1, ... for an anonymous custom basis. Override with names.

Parameters:
Returns:

Printable / notebook-displayable table.

Return type:

tinto.estimate._FractionTable

Examples

>>> def dummy(n, n_trials):
...     return {"steps": ((2 / 3) * n - 1 / 3, 1.0, 0.0),
...             "activations": (0.0, 1.0, 0.0)}
>>> exp = Experiment("demo", iterator=Iterator("n", range(10, 60)), n_trials=10**6)
>>> _ = exp.run(runner=dummy, progress=False)
>>> print(exp.report())
campaign | n             | 1               | chi2_red | pvalue | fit
---------+---------------+-----------------+----------+--------+----
demo     | 0.6667 -> 2/3 | -0.3333 -> -1/3 | 0.00     | 1      | low
residuals(metric: str = 'steps', basis=None, normalize: bool = True, x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None) → dict[source]#

Per-series fit residuals, for eyeballing noise vs. leftover structure.

Same (x, y, sigma) assembly as fit(), then returns the residuals of the linear basis fit (affine by default). The whole point is to look: under a correct model the normalized residuals are iid N(0, 1) scatter, whereas a trend, curvature, or a run of same-sign points across x betrays a missing term that the scalar chi2_red only hints at.

Residuals follow the usual convention y - model (observed minus predicted), so a point above the fit reads positive and the plotted curvature matches the data’s: a concave law shows a concave (∩) residual, not an inverted one.

Normalized residuals (y - model) / sigma are the right thing to plot: they are dimensionless and weighted by each point’s error bar, so heteroscedastic sigma_i do not distort the picture. Pass normalize=False for raw residuals y - model in the metric’s own units. Note both the sign convention and the weighted fit (small-sigma points dominate the line) shape what you see — with a strongly n-dependent sigma the fitted line tilts toward the low-n end.

Caution

Residuals are an exploratory tool. Choosing a new basis term because you saw it in the residuals and then testing that same term on the same data is double-dipping: the resulting pvalue/t are optimistic. Confirm a term either on fresh data or by checking that its coefficient lands on a clean, stable fraction — not by the in-sample fit improving (it always does).

Parameters:
  • metric (see fit().)

  • basis (see fit().)

  • x (see fit().)

  • hue (see fit().)

  • campaign (see fit().)

  • normalize (bool, default=True) – Return (y - model) / sigma when True, else y - model.

Returns:

{label: (xs, resid)} with the same labels as series(); xs and resid are plain Python lists, sorted by x. Plot one with plt.plot(*exp.residuals()[label], "o").

Return type:

dict

Examples

On exactly affine data the residuals vanish (pure-noise limit):

>>> import numpy as np
>>> def dummy(n, n_trials):
...     return {"steps": (2.0 * n + 1, 1.0, 0.0),
...             "activations": (0.0, 1.0, 0.0)}
>>> exp = Experiment("demo", iterator=Iterator("n", [1, 2, 3]), n_trials=100)
>>> _ = exp.run(runner=dummy, progress=False)
>>> xs, res = exp.residuals()["demo"]
>>> xs
[1, 2, 3]
>>> bool(np.allclose(res, 0.0))
True
property results: dict#

Structured per-campaign result dict filled by run().

run(runner: Callable | None = None, progress: bool = True) → Experiment[source]#

Execute every campaign sequentially and fill results.

Parameters:
  • runner (callable, optional) – Function called with the per-point parameters and returning a dict {metric: (mean, var, m3)}. Defaults to tinto.runners.mc().

  • progress (bool, default=True) – Show a tqdm progress bar when tqdm is installed. Silently ignored otherwise.

Returns:

Self, for chaining.

Return type:

Experiment

Examples

With the default runner (tinto.runners.mc()) on a small line-graph campaign with no sweep:

>>> from tinto.graphs import line
>>> from tinto.configs import make as make_config
>>> from tinto.starters import from_graph
>>> from tinto.schedulers import shuffled
>>> from tinto.solvers import make as make_solver
>>> from tinto.io import set_seed
>>> set_seed(0)
>>> Config = make_config()
>>> starter = from_graph(Config, color=0)(line(5))
>>> exp = Experiment(
...     "bare",
...     starter=starter,
...     scheduler=shuffled(),
...     solver=make_solver(),
...     n_trials=5,
... )
>>> _ = exp.run()
>>> sorted(exp.results["bare"]["data"][()].keys())
['activations', 'steps']

results raises if accessed before run():

>>> Experiment("untouched").results
Traceback (most recent call last):
    ...
RuntimeError: Experiment.run() must be called before accessing results.
series(metric: str = 'steps', stat: str = 'mean', x: str | None = None, hue: str | None = None, campaign: str | Iterable[str] | None = None) → dict[str, tuple[list, list]][source]#

Extract {label: (xs, ys)} without any plotting.

Same selection logic as plot(): campaigns missing x, a hue not in the axes, or a 2-D campaign without a hue are skipped. Labels are campaign_name for 1-D campaigns, "{campaign_name} / {hue}={hue_value}" for 2-D campaigns split by hue.

When x is omitted, it is inferred from the selected campaigns: if exactly one axis (excluding hue) appears across them, it is used. If zero or more than one, the call behaves as if x was unknown (empty result).

Parameters:
  • metric (see plot().)

  • stat (see plot().)

  • x (see plot().)

  • hue (see plot().)

  • campaign (str, iterable of strings, or None,) – default=``None`` Filter on campaign name(s). None keeps all, a string keeps one, an iterable keeps a subset. Unknown names are dropped silently.

Returns:

Insertion-ordered mapping {label: (xs, ys)}. Both xs and ys are plain Python lists, sorted by x.

Return type:

dict

Examples

>>> def dummy(n):
...     return {"steps": (float(n), 0.0, 0.0), "activations": (float(n * 2), 0.0, 0.0)}
>>> a = Experiment("A", iterator=Iterator("n", [1, 2, 3]))
>>> b = Experiment("B", iterator=Iterator("n", [1, 2, 3]))
>>> exp = (a + b).run(runner=dummy, progress=False)
>>> exp.series(x="n", metric="steps")
{'A': ([1, 2, 3], [1.0, 2.0, 3.0]), 'B': ([1, 2, 3], [1.0, 2.0, 3.0])}

Selecting a single campaign:

>>> exp.series(x="n", metric="activations", campaign="A")
{'A': ([1, 2, 3], [2.0, 4.0, 6.0])}

Or a subset. Unknown names silently drop:

>>> exp.series(x="n", campaign=["B", "ghost"])
{'B': ([1, 2, 3], [1.0, 2.0, 3.0])}

With hue on a cartesian-product campaign, labels combine campaign name and hue value:

>>> def dummy2(n, kind):
...     return {"steps": (float(n) + {"a": 0.0, "b": 1.0}[kind], 0.0, 0.0),
...             "activations": (0.0, 0.0, 0.0)}
>>> prod = Experiment(
...     "P", iterator=Iterator("n", [1, 2]) * Iterator("kind", ["a", "b"])
... )
>>> _ = prod.run(runner=dummy2, progress=False)
>>> prod.series(x="n", hue="kind")
{'P / kind=a': ([1, 2], [1.0, 2.0]), 'P / kind=b': ([1, 2], [2.0, 3.0])}

x is inferred when unambiguous, so passing it is optional on simple 1-D campaigns:

>>> exp.series() == exp.series(x="n")
True
to_csv(target) → None[source]#

Write flat CSV rows (one per data point) to target.

Columns: campaign, then every axis seen in any campaign (empty cells when absent), then {metric}_{stat} for steps and activations × mean, var, m3.

Parameters:

target (path-like or text stream) – Opened file path (string / Path) or any object exposing a .write() method (io.StringIO, an opened file, …).

Examples

>>> import io
>>> def dummy(n):
...     return {"steps": (float(n), 0.0, 0.0), "activations": (float(n+1), 0.0, 0.0)}
>>> exp = Experiment("demo", iterator=Iterator("n", [1, 2]))
>>> _ = exp.run(runner=dummy, progress=False)
>>> buf = io.StringIO()
>>> exp.to_csv(buf)
>>> header, *rows = buf.getvalue().splitlines()
>>> header
'campaign,n,steps_mean,steps_var,steps_m3,activations_mean,activations_var,activations_m3'
>>> len(rows)
2
>>> rows[0]
'demo,1,1.0,0.0,0.0,2.0,0.0,0.0'

Two campaigns sharing the same axis keep a single column for it:

>>> combined = exp + Experiment("bis", iterator=Iterator("n", [3]))
>>> _ = combined.run(runner=dummy, progress=False)
>>> buf = io.StringIO()
>>> combined.to_csv(buf)
>>> buf.getvalue().splitlines()[0].split(",").count("n")
1

A filesystem path is also accepted:

>>> import tempfile
>>> from pathlib import Path
>>> with tempfile.TemporaryDirectory() as td:
...     path = Path(td) / "out.csv"
...     exp.to_csv(path)
...     "steps_mean" in path.read_text()
True
to_dict() → dict[source]#

Return a deep copy of the internal result dict.

Examples

>>> def dummy(n):
...     return {"steps": (float(n), 0.0, 0.0), "activations": (0.0, 0.0, 0.0)}
>>> exp = Experiment("demo", iterator=Iterator("n", [1, 2]))
>>> d = exp.run(runner=dummy, progress=False).to_dict()
>>> d["demo"]["data"][(1,)]["steps"]
(1.0, 0.0, 0.0)
to_dict_keys()[source]#
class tinto.experiments.Iterator(parameter: str, values: Iterable[Any], name: str | None = None, process: Callable[[Any], Any] | None = None)[source]#

Bases: object

One-dimensional parameter sweep.

Yields, at each step, a triplet (kwargs, display_names, display_values) where kwargs is a single-entry dict ready to be passed as keyword arguments to the runner, and the two tuples carry the display metadata used by Experiment.plot() and Experiment.to_csv(). For a 1-D iterator both tuples have length one; for a ProductIterator obtained via * they have one entry per dimension.

Parameters:
  • parameter (str) – Keyword argument name the runner expects.

  • values (iterable) – Raw values to sweep. Stored as a list.

  • name (str, optional) – Human-readable axis label for plots. Defaults to parameter.

  • process (callable, optional) – Maps each raw value to the object actually passed to the runner (e.g. build a Starter from an integer n). Defaults to identity.

Examples

>>> it = Iterator("n", [1, 2, 3])
>>> len(it)
3
>>> list(it) == [
...     ({"n": 1}, ("n",), (1,)),
...     ({"n": 2}, ("n",), (2,)),
...     ({"n": 3}, ("n",), (3,)),
... ]
True

A custom name and process let the display label decouple from the runner keyword:

>>> it2 = Iterator("n", [2, 4], name="$n$", process=lambda v: v * 10)
>>> [kwargs for (kwargs, _, _) in it2]
[{'n': 20}, {'n': 40}]
>>> [names for (_, names, _) in it2]
[('$n$',), ('$n$',)]
class tinto.experiments.ProductIterator(iterators: Iterable)[source]#

Bases: object

Cartesian product of Iterator (and/or ProductIterator) instances.

Yields the same triplet as Iterator but with one entry per dimension, in left-to-right order. The rightmost dimension varies fastest (standard itertools.product() behavior).

Parameters:

iterators (list of Iterator or ProductIterator) – Dimensions of the product. Stored flat: passing a ProductIterator in the list merges its inner iterators.

Examples

>>> it_n = Iterator("n", [1, 2])
>>> it_p = Iterator("p", [0.1, 0.5])
>>> prod = it_n * it_p
>>> len(prod)
4
>>> [values for (_, _, values) in prod]
[(1, 0.1), (1, 0.5), (2, 0.1), (2, 0.5)]

Multiplication chains without nesting:

>>> prod3 = it_n * it_p * Iterator("k", [10])
>>> [it.parameter for it in prod3.iterators]
['n', 'p', 'k']
>>> len(prod3)
4

Direct construction with a nested ProductIterator in the list flattens it transparently:

>>> nested = ProductIterator([prod, Iterator("w", [0])])
>>> [it.parameter for it in nested.iterators]
['n', 'p', 'w']
class tinto.experiments._Campaign(name: str | None, iterator: Iterator | ProductIterator | None, params: dict = <factory>)[source]#

Bases: object

Internal record holding one campaign’s inputs.

iterator: Iterator | ProductIterator | None#
name: str | None#
params: dict#