Optimization API
cb.decision and cb.Optimization are in cimba. Settings and result
types are in cimba.optimize. For explanations see
Optimization; for recipes, Find the best parameters.
Decisions
- cimba.decision(low, high, *, step=None, log=False)
Return a
Decision: the inclusive range aParammay take in an optimization.low < high, both finite.stepmust be positive and dividehigh - lowexactly.log=Trueneedslow > 0and can’t be combined withstep. Invalid arguments raiseValueError.
The annotation of the field receiving the decision sets the domain:
Field |
Values |
|---|---|
|
Reals in |
|
Integers in |
|
|
Decisions can only be assigned to Param fields of models in the tree
(otherwise TypeError). A plain Experiment raises
ModelDefinitionError if any decision remains. Domain errors that depend
on the field type are raised, with the field’s path, when the study is
created.
- class cimba.Decision
One search dimension, identified by the object. Fields assigned the same object always take the same value and must have the same type.
- map(function)
A decision on the same dimension whose value is
function(value). Mapped decisions can be mapped again and are valid keys forOptimum; the result is validated against the receiving field.
A candidate is a mapping from each original (unmapped) decision to a
value in its domain, on its step lattice. initial, evaluate and
experiment take candidates.
Optimization
- class cimba.Optimization(model, *, minimize=None, maximize=None, replications=32, window=None, seed=0)
A search over the decisions in
model. Creating it snapshots and validates the configuration; later changes to the model don’t affect it. The model must contain at least one decision and no sweeps.- Parameters:
minimize – Objective to minimize. Give exactly one of
minimizeandmaximize.maximize – Objective to maximize. Reported values keep its sign.
replications – Search trials per candidate (≥ 1).
window – The measurement
Window; defaultWindow.until_idle().seed – Base seed (≥ 0) for every random stream of the study.
The objective is called once per batch with its
Resultsand must return real numbers that broadcast to(points, replications). Scalars and(points,)arrays are rejected withOptimizationError. Values of failed trials are ignored; a non-finite value of a successful trial marks that trial failed ("objective is not finite").- run(*, evaluations=None, optimizer=None, initial=None, finalists=5, validation=None, workers=None, input_memory=1 << 30, on_failure='reject', progress=None)
Search, select a finalist on fresh seeds, estimate it on independent seeds, and return an
Optimum.- Parameters:
evaluations – Maximum distinct candidates simulated in the search. Must cover the initial population. Cached candidates are free. The search stops before a generation that might exceed it.
optimizer – A
DifferentialEvolution;Noneuses the defaults.initial – Candidates that replace the first members of the initial population (at most the population size).
finalists – Maximum candidates re-run for selection (≥ 1).
validation – Replications for selection and for the estimate (≥ 2). Default
max(100, 4 * replications).workers – Worker threads;
Noneuses every logical CPU.input_memory – Byte limit for generated input rows, as in
Experiment.run().on_failure –
"reject","ignore"or"raise"(below).progress – Called with a
Progressafter each evolved generation; a truthy return stops the search.
Repeated runs reuse the study’s cache of simulated candidates.
- evaluate(candidates, *, workers=None, input_memory=1 << 30, on_failure='reject')
Evaluate candidates on the search seeds as one batch, reusing the cache. Returns a tuple of
Evaluation, in order.
- experiment(values)
A plain
Experimentat one candidate, with the study’s saved configuration, seed, replications and window. The model is left unchanged. Its trials are the search trials of that candidate.
- describe()
One dict per field of the saved model:
instance,field,kind,domain,sourceandobjective.
Policy |
Effect on a candidate with failed trials |
|---|---|
|
Excluded from the search and from the finalists. |
|
Scored on its successful trials; rejected if none succeeded. |
|
|
The policy applies to search, selection and estimation. OptimizationError
is raised if the whole initial population or every finalist is rejected, or
if the chosen candidate fails its estimation trials.
Differential evolution
- class cimba.optimize.DifferentialEvolution(*, popsize=15, mutation=(0.5, 1.0), recombination=0.7, strategy='best1bin', tol=0.01, atol=0.0, maxiter=1000, init='latinhypercube')
Settings for SciPy’s
differential_evolution, with SciPy’s meanings.- Parameters:
popsize – Population per decision (≥ 1), or
"fill". With D decisions the population ismax(5, D * popsize)(at least 6 forrand2strategies; rounded up to a power of two forsobol).mutation – In
[0, 2), or an increasing pair for dithering.recombination – Crossover probability in
[0, 1].strategy –
best1,best2,rand1,rand2,randtobest1orcurrenttobest1, followed bybinorexp.tol – Relative convergence tolerance (≥ 0).
atol – Absolute convergence tolerance (≥ 0). The search has converged when the population’s energies have a standard deviation of at most
atol + tol * abs(mean).maxiter – Maximum evolved generations (≥ 0).
init –
"latinhypercube","random","sobol"or"halton".
popsize="fill"resolves once per run tomax(15, ceil(256 * W / (D * R)))for W workers and R replications, recorded inmeta.optimizer.popsize.Cimba supplies the bounds, integrality, random generator, callback and a vectorized objective, and always uses
updating="deferred",workers=1andpolish=False: each generation is evaluated as one native batch.
Results
- class cimba.optimize.Optimum
The result of
run().best[decision]returns a chosen value; mapped decisions are valid keys.- values
Read-only mapping from decisions to chosen values.
- results
Full
Resultsof the estimation run, including input records and captured entities.
- history
Every search proposal, by generation, including cache hits.
- batches
One row per native runner call.
- meta
Read-only run metadata (below), by key or attribute.
- apply()
Replace every decision in the model with its chosen value.
- class cimba.optimize.Estimate
nsuccessful trials,mean,std(ddof=1) and the 95% Student-t intervallower,upper(NaN with fewer than two trials).
- class cimba.optimize.Evaluation
One candidate’s
values, read-only per-trialsamplesandfailedarrays, failurereasonsandestimate.
- class cimba.optimize.Finalist
values,search_mean,selection(anEstimate) andselection_mean.differenceis ananalysis.Comparisonof this finalist minus the chosen one on the selection trials, at confidence1 - 0.05 / max(1, F - 1)for F finalists.rejectedreports a failure under the policy;indistinguishableis true when the interval contains zero.
- class cimba.optimize.Progress
generation, simulatedevaluationsso far, andbest, the best acceptedEvaluation.
history and batches are sequences of rows with to_table(), which
returns a list of dicts ready for pandas.DataFrame.
Table |
Fields |
|---|---|
|
|
|
|
Memory chunking or input extension can split one batch into several native calls; the extra rows carry only native work. A generation made only of cache hits has history rows but no batch row.
meta holds evaluations, generations, trials (per phase),
wall_time, stop_reason (converged, budget, maxiter or
progress), compile, optimizer (resolved settings),
population_size, numpy_version, scipy_version, workers,
on_failure, replications, validation, seed,
selection_seed and estimation_seed.
Seeds
Search replication r uses trial_seed(seed, r), the seed of a common
seeded Experiment. Selection and estimation use
trial_seed(selection_seed, r) and trial_seed(estimation_seed, r).
Those base seeds, and DE’s own generator, are drawn from
inputs.trace_rng(seed, tag) with the tags "cimba.optimize.selection",
"cimba.optimize.estimation" and "cimba.optimize.de". NumPy’s global
random state is never used.
Errors
Exception |
Raised when |
|---|---|
|
invalid decision bounds, DE settings or candidate mappings. |
|
a decision is assigned to a field that isn’t a |
|
the model has no decisions, contains sweeps, or a decision doesn’t fit its field (message names the field). |
|
invalid study or run arguments. |
|
the objective returns the wrong shape or type, or every candidate is rejected (see failure policies). |
|
a trial fails and |