Analyzers Module#

Result analysis and monitoring components:

  • Analyzer: Base class for analysis components

  • Best: Tracks best solutions found (feasible best, infeasible best, Pareto front of (f, CV))

  • Convergence: Monitors optimization progress; publishes a converged event using std or improv mode

  • Sensitivity: Estimates per-dimension importance via rank correlation; enables sensitivity-aware perturbations in Nearby

  • Restart: Detects stagnation (no improvement within patience evaluations) and triggers multi-start restarts; pairs with CMAES for IPOP-CMA-ES

  • Splitter: Adaptive hierarchical box-decomposition of the search space; publishes new_split and identifies the best leaf box. Resolution scales with the evaluation budget (leaf_size / min_leaf_size / max_leaves); split_rule and cut_rule select the cut, legacy=True restores the fixed-resolution tree

  • Archive: Opt-in bounded top-K of the shared result stream, ranked by penalty and unfiltered by who; the query layer heuristics warm-start from

  • FailureModel: Opt-in shared model of failure regions (“poison zones”: crashes, NaN, timeouts) — p_fail(x) / in_poison(x) from a kernel classifier with an adaptive bandwidth and a success prior; with filter=True the strategy answers candidates in a zone as failed without evaluating them (no budget), so each arm’s own failure handling applies. CMAES(failure_aware=True) and TrustRegionQuadratic(failure_aware=True) add arm-specific handling (DISCOVERY §71)

Analyzers#

Analyzers, just like heuristics, listen to events and change their internal state based on local and global data. They can emit events on their own and they are accessible via the analyzer() method of the strategy.

Archive#

A bounded, shared top-K of the whole result stream — the query layer the population heuristics need in order to warm-start from points somebody else paid for (planning/DESIGN_warm_start_2026-09-10.md §2).

What the store offers today is either too little or too much: Results only replays the last n rows as floats, Best collapses to a single incumbent, and Splitter.root.results is a complete but unsorted, unbounded list[Result]. This analyzer keeps the K best results seen so far, ranked by the constraint handler’s ordering (rank_key(), the one Best uses) and not filtered by ``who`` — an arm that asks for a seed gets the best points in the run, whoever produced them.

Cost: one heap operation per result, O(log K). Queries are O(K log K) and are made a handful of times per run, so they are deliberately simple.

Note

This analyzer is opt-in: initialize() does not add it. Ship it via StrategySpec.analyzers (or add_analyzer) so a run without warm-started arms keeps exactly the modules — and the event-bus registration order — it had before.

class panobbgo.analyzers.archive.Archive(strategy, k: int = 256, name: str | None = None)[source]#

Bases: Analyzer

Bounded top-K of the shared result stream, ranked by the constraint handler’s ordering (rank_key).

With a time-varying handler (time_invariant is False, e.g. dynamic penalty or augmented Lagrangian) the retained entries are re-ranked under the current ordering before a batch or a query whenever the number of results has changed since the last re-rank (the time these handlers move with), so the heap order does not go stale; which results were admitted earlier still reflects the ordering at the time.

Thread-safety: results arrive on the event-bus thread, queries come from heuristics on the main thread; one lock covers every read and write of the heap.

Parameters:
  • strategy (StrategyBase) – the owning strategy.

  • k – how many results to retain (default DEFAULT_K).

  • name (str) – optional module name; defaults to "Archive".

  • strategy

  • name

@type strategy: StrategyBase

K: int#
diverse_k(k: int, *, pool: int = 4, box: Any = None) → List[Result][source]#

k well-separated good results: greedy max–min over the top pool*k.

The incumbent is always the first pick; each further pick maximises the minimum distance to everything picked so far, measured in box-normalised coordinates so the selection does not depend on the units of a dimension. This is the selector that hands a second arm a spread rather than a cluster around one basin.

on_new_results(results: Iterable[Result]) → None[source]#

Fold every result into the bounded top-K. O(log K) per result (plus an O(K) re-rank per batch for a time-varying handler).

penalty_of(r: Result) → float[source]#

Scalar penalty value of r, inf when it cannot be evaluated.

A magnitude, not the ranking: with a lexicographic handler it can order two results differently from top_k().

per_leaf_best(k: int) → List[Result][source]#

Best point of each of the k best Splitter leaves.

Returns [] when no Splitter is registered — the only selector that depends on a second analyzer, and the only one that can hand out points from different basins by construction.

property results: List[Result]#

Every retained result, best first.

top_k(k: int, *, box: Any = None, exclude_who: Any = None, fx_max: float | None = None) → List[Result][source]#

The k best retained results, best first.

Parameters:
  • box – restrict to results inside this region — either a Box (anything with a contains method) or a (dim, 2) array of bounds.

  • exclude_who – a who tag, or an iterable of them, to skip. Matching is by heuristic name, so "PSO" also drops "PSO:1a2b…".

  • fx_max – keep only results whose scalar penalty (penalty_of()) is <= fx_max.

panobbgo.analyzers.archive.DEFAULT_K = 256#

Default number of results retained.

Failure model#

A shared estimate of where evaluations fail (“poison zones”, planning/DESIGN_roadmap_2026-09-26.md §4 D): regions of the box where the objective crashes, returns NaN or times out. Every heuristic can ask it, and the strategy can use it to answer a candidate in such a region without evaluating it.

The model (v0)#

A kernel classifier with an adaptive (balloon) bandwidth and a success prior, on box-normalised coordinates \(u \in [0, 1]^d\), from every labelled point the run has seen (a result with a finite value is a success; a crash, a timed-out NaN placeholder or any non-finite value is a failure):

\[p_{\mathrm{fail}}(u) = \frac{\sum_i w_i y_i}{\sum_i w_i + \alpha}, \qquad w_i = \exp\!\left(-\tfrac12 \lVert u - u_i \rVert^2 / h(u)^2\right), \qquad h(u) = \min\bigl(h_n,\ r_k(u)\bigr)\]

with \(y_i = 1\) for a failure, \(r_k(u)\) the distance to the \(k\)-th nearest labelled point (\(k = d + 1\), at least 3) and the cap \(h_n = 2\,(k / (n V_d))^{1/d}\), twice the expected distance to the \(k\)-th neighbour among \(n\) uniform points (\(V_d\) the volume of the unit ball). The choices, each for one of the requirements:

  • Unexplored is not poisoned — beyond the data’s own scale. \(\alpha\) (prior, default 1) is a pseudo-count of success, so a zone needs several failures close together: \(p \ge 1/2\) needs a failure weight of at least \(1 + \alpha\) plus the success weight; with all \(k\) neighbours failed, \(p \approx 0.6\) (d = 2) to 0.8 (d = 5); one isolated failure gives \(p < 1 / (1 + \alpha)\) (below the threshold) anywhere but on the point itself. Further than a few \(h_n\) from every failure all failure weights vanish and \(p \to 0\). Within that reach the estimate is a smoothed \(k\)-nearest-neighbour vote, and it does extrapolate: a point whose nearest labelled points are all failures is marked even where nothing has been evaluated (deeper inside a half-space than any failure, or, early in a run, around a first cluster of failures). That is the price of a model that also recognises a zone it has sampled sparsely; the “whole box” guard below bounds it.

  • Sharp where the data are dense. The bandwidth is the distance to the \(k\)-th neighbour, so near a converging search (thousands of points within \(10^{-3}\) of an optimum on the boundary of a failure region) the boundary is resolved at the scale of the search, not at the scale of the box.

  • Deterministic failures. A point within repeat_tol (Euclidean, in normalised units) of a known failure has \(p = 1\): evaluating it again would fail again.

  • Cheap. A query of \(m\) points costs the distances to the failures, \(O(m\, n_{\mathrm{fail}} d)\) (the repeat rule reuses them); only the queries within reach of a failure also compute the distances to the successes, \(O(m' n_{\mathrm{ok}} d)\). Points are stored in growing buffers (amortised \(O(d)\) per result). The guard below costs N_PROBES queries, amortised and exact near its threshold (FailureModel.poisoned_share()). No spatial index: at the budgets measured a one-point query takes 0.03 ms (d = 2, n = 200) to 0.06 ms (d = 10, n = 1000) and 0.3 ms at n = 10 000, one guard evaluation 1 ms to 110 ms (laptop, 2026-09-27); a KD-tree would pay off beyond that. With no failure at all p_fail() returns zeros without touching anything else, so a run without failures is bit-identical with the model on.

  • Never the whole box. in_poison() is p >= threshold (default 0.5), and it is disarmed (False everywhere) while the share of a fixed set of probe points in the box that it would mark exceeds max_share (default 0.5, the largest failure share the FailureRegion families use).

Alternatives considered and not chosen for v0 (DISCOVERY §71): a half-space fit (logistic / linear SVM on the failures) extrapolates a zone into unexplored territory — exactly right for a half-space, wrong for a ball or boxes, and against “unexplored is not poisoned”; a GP classifier is too expensive to query on every proposal; an axis-aligned tree is a natural v1 for half-spaces along one variable.

The proposal filter#

With filter=True the strategy’s main loop (_filter_poisoned()) passes every candidate through reject(): a candidate in a poison zone is not evaluated and costs no budget; the heuristic that proposed it is told, by the predicted_failures event, that it failed — which each heuristic answers with its own failure handling (on_failed_evaluations: CMA-ES ranks it last, the DE family loses the trial, the trust region shrinks, a solver bridge answers inf). The candidate is answered, not resampled: the heuristic’s sampling distribution is not changed, and a CMA-ES generation sees the rejected offspring exactly as it would see a real failure, only for free. Liveness: after max_rejects consecutive rejections of one heuristic’s candidates, its next candidate is evaluated whatever the model says (which also lets the model correct itself); a heuristic without an on_failed_evaluations hook (it refills only on new results, like Random) gets on_new_results([]) for its rejected candidates, so rejections never drain its queue.

The model only learns from evaluated points; a rejected candidate is not a failure the model has seen.

class panobbgo.analyzers.failure_model.FailureModel(strategy: Any, filter: bool = False, threshold: float = 0.5, prior: float = 1.0, k: int | None = None, repeat_tol: float = 1e-09, max_share: float = 0.5, max_rejects: int = 10, name: str | None = None)[source]#

Bases: Analyzer

Shared failure-region model: p_fail(x) / in_poison(x) from observed failures and successes.

Opt-in: add it to a strategy (StrategySpec.analyzers); nothing in a strategy without it changes. Thread-safety: results arrive on the event-bus thread, queries come from the main loop and from heuristics; one lock covers the labelled data.

Parameters:
  • strategy (StrategyBase) – The owning strategy.

  • filter – Reject candidates in poison zones in the strategy’s main loop (see the module docstring). False (default): the model only answers queries.

  • threshold – in_poison() is p_fail >= threshold.

  • prior – The success pseudo-count \(\alpha\).

  • k – Neighbour rank of the adaptive bandwidth; None: max(3, d + 1).

  • repeat_tol – Euclidean distance (normalised units) within which a point repeats a known failure.

  • max_share – Largest share of the box in_poison() may mark before it is disarmed.

  • max_rejects – Consecutive rejections of one heuristic’s candidates after which its next candidate passes.

  • name (str) – Module name; defaults to "FailureModel".

  • strategy

  • name

@type strategy: StrategyBase

add_failure(x: Any, kind: str = 'crash') → None[source]#

Record a failed evaluation at x (also the entry point for tests and other drivers).

add_success(x: Any) → None[source]#

Record a successful evaluation at x.

property armed: bool#

False while the model would mark more than max_share of the box (or knows no failure).

in_poison(x: Any) → Any[source]#

p_fail(x) >= threshold while armed, else False; a bool or a bool array like p_fail().

kinds: Dict[str, int]#

"crash", "timeout", "nan" -> count.

Type:

Failure kinds seen

property n_fail: int#
property n_ok: int#
n_rejected#

Diagnostics.

on_failed_evaluations(points: List[Any]) → None[source]#

A crashed evaluation (no result) is a failure at its point.

on_new_results(results: List[Any]) → None[source]#

Label every result: finite value -> success; timed out / non-finite -> failure.

p_fail(x: Any) → Any[source]#

Estimated probability that evaluating x fails: a float for one point, an array for m x d.

poisoned_share() → float[source]#

Share of the fixed probe points the model marks (p >= threshold), before the guard.

Computed lazily, on the first query after the data changed, and amortised: exactly on every change (a new failure or success) while the last share is above SHARE_NEAR * max_share (close to the guard) or the model knows at most SHARE_EXACT_UP_TO failures; otherwise only once the failures or the labelled points have grown by 10 %. New successes can raise the share as well as lower it (they shrink the bandwidths h_n and r_k), so a share cached far below the guard can lag the exact one; that lag is what the SHARE_NEAR band absorbs. The guard is therefore not a hard guarantee between recomputes, only near the threshold: tested on a half-box failure region sampled uniformly and then by successes only (tests/test_failure_model.py). One evaluation costs N_PROBES queries.

reject(points: List[Any]) → List[bool][source]#

Which of points (candidates, in order) the filter rejects; updates the per-heuristic streaks.

A candidate of a heuristic whose last max_rejects candidates were all rejected passes (liveness; see the module docstring). Returns all False without any work while the model knows no failure.

panobbgo.analyzers.failure_model.H_FACTOR = 2.0#

The bandwidth cap is H_FACTOR times the expected k-th neighbour distance of n uniform points.

panobbgo.analyzers.failure_model.N_PROBES = 256#

Probe points of the “never the whole box” guard.

panobbgo.analyzers.failure_model.SHARE_EXACT_UP_TO = 50#

FailureModel.poisoned_share() is recomputed on every new failure up to this many, then every +10 %.

panobbgo.analyzers.failure_model.SHARE_NEAR = 0.8#

Above SHARE_NEAR * max_share the guard’s share is recomputed exactly on every data change.

class panobbgo.analyzers.best.Best(strategy)[source]#

Bases: Analyzer

Listens on all results, does accounting for “best” results, manages a pareto front of good points and emits the following events:

  • new_best: when a new “best” point,

  • new_min: a point with smallest objective function value,

  • new_cv: one with a smaller cv, or

  • new_pareto: when a best point on the pareto front of the objective value and constraint violation

    has been found.

Note

Pareto: Once the constraint violation is zero, only the objective function value is considered and future results with a positive constraint violation are ignored.

The best point (pareto) is available via the best attribute. There is also cv, min and pareto.

_images/pareto-front.png

This is an example of how several pareto fronts progress during the optimization.#

Parameters:

@type strategy: StrategyBase

property best#

Currently best Result.

Note

At the moment, this is pareto but might change.

property cv#

The point with currently minimal constraint violation, likely 0.0. If there are several points with the same minimal constraint violation, the value of the objective function is a secondary selection argument.

property min#

The point, with currently smallest objective function value.

on_new_cv(cv)[source]#

Report progress when a new constraint violation minimum is found.

on_new_min(min)[source]#

Report progress when a new global minimum is found.

on_new_pareto(pareto)[source]#
on_new_pareto_front(front)[source]#

Report progress when a new pareto front is found.

on_new_results(results)[source]#
on_refresh_best(candidates)[source]#

Handle a refresh_best event, which suggests candidate points that might be better than current best due to changed criteria (e.g. updated constraint weights).

property pareto#
property pareto_front#

This is the list of points building the current pareto front.

Note

This is a shallow copy.

class panobbgo.analyzers.convergence.Convergence(strategy, window_size=None, threshold=None, mode=None, min_evaluations=None)[source]#

Bases: Analyzer

Analyzes the progress of the optimization to detect convergence or stagnation.

It listens to new_results events and tracks the history of the best objective function values. If the improvement over a specified window of evaluations is below a threshold, or if the standard deviation of the best values in the window is small enough, it publishes a converged event.

Configuration parameters: a keyword argument wins; otherwise the strategy.config attribute in parentheses is used when it exists and is not None; otherwise the default. 0 / 0.0 are honoured.

  • window_size (convergence_window_size, int >= 1): Number of recent best values to consider (default: 50).

  • min_evaluations (convergence_min_evaluations, int): Minimum number of evaluations before checking convergence (default: window_size).

  • threshold (convergence_threshold, float): Threshold for relative improvement or std dev (default: 1e-6).

  • mode (convergence_mode, str): ‘std’ (standard deviation), ‘improv’ (relative improvement), or ‘slope’ (linear regression slope) (default: ‘std’).

  • (convergence_require_feasibility, bool): only converge on a feasible incumbent (default: False).

Events published: - converged: When convergence criteria are met.

The event carries reason (str) and stats (dict) with details.

Parameters:

@type strategy: StrategyBase

on_new_results(results)[source]#

Listen to all results to detect stagnation (no improvement for many evaluations).

panobbgo.analyzers.splitter.CUT_RULES = ('mean', 'median')#

Where along the chosen dimension the cut goes. "mean" is the historical point; "median" cuts through the middle order statistic. See Splitter.Box._split_point().

panobbgo.analyzers.splitter.DEFAULT_CUT_RULE = 'mean'#

The default cut. "mean", and the reasoning that said otherwise was wrong, so it is written down here rather than repeated.

The observation was real: Random at d = 5 (Rosenbrock, 2500 evaluations) builds a tree of depth 60 — the Box.MAX_DEPTH cap — holding 61 leaves against a target of 101, with a single leaf of ~1300 points. The diagnosis — “the mean is dragged towards the stragglers of a contracting cloud, so each cut only peels a few points off” — was not: a median cut produces the identical depth 60 / 61 leaves / 1301-point leaf on the same spec. The chain is Random’s own doing: it samples only inside the current best leaf, so every point lands in one leaf, that leaf splits, the child holding the best point becomes the next target and the sibling is never visited again. Depth then grows once per split whatever the cut rule is. Fixing it means changing the heuristic or the depth cap, not the geometry.

What the median does change was then measured, paired, 3 seeds (42/7/1234, MA-BBOB standard battery, dims 2 and 5 at 500·d, instances 0-2): Random −0.0145 (1/3 seeds), RegionUCB +0.0327 (3/3) — one inside the ±0.03 null floor and negative, the other barely outside it, mean +0.009. No mandate. And it carries one concrete structural regression: on Blocks_uniform_cj_warm2 at d = 5 the median cut reaches MAX_DEPTH with a 423-point leaf where the mean stays at depth 52 with no leaf above 36.

So "median" ships opt-in — it is genuinely the better geometry (see Splitter.Box._split_point()) and RegionUCB, the one consumer that reads every leaf, is the case worth revisiting on a 12-seed roster.

panobbgo.analyzers.splitter.DEFAULT_SPLIT_RULE = 'widest'#

a paired 3-seed screen (42/7/1234, MA-BBOB standard battery, dims 2 and 5 at 500·d, instances 0-2, seed_name shared) put "value" minus "widest", both on the budget-scaled resolution, at +0.001 for Random, +0.024 for RegionUCB, 0.000 for the reference portfolio and −0.000 for the archive_leaf portfolio — every one of them inside the ±0.03 null floor, every CI straddling zero, and it costs ~8% more analyzer time per result. The whole measured gain of this change is the resolution (+0.048 / +0.014 / 0.000 / +0.042 against the legacy tree). "value" ships opt-in so a 12-seed roster can revisit RegionUCB, which is the only consumer that reads more than one leaf per decision.

Type:

The default split rule. "widest", deliberately

panobbgo.analyzers.splitter.LEAF_FILL = 0.67#

Measured mean leaf population divided by the split threshold. A leaf splits at limit points and each child inherits the parent’s points it contains, so a leaf holds between limit/2 and limit points. The realised mean is ≈0.67·limit — measured over uniform and contracting point clouds at (dim, budget) ∈ {(2,1000), (5,2500), (10,5000), (20,10000)}, where it stayed in 0.59 … 0.72 for both split rules and for the legacy threshold of 250. Used to turn a target leaf population into the split threshold; a mis-calibration only scales the leaf count, it cannot break the tree.

panobbgo.analyzers.splitter.LEAF_SIZE = 25#

Target mean number of results per leaf. The tree’s resolution is max_eval / LEAF_SIZE leaves, i.e. it grows with the budget instead of being pinned to the dimension (planning/DESIGN_meta_level_2026-09-10.md §1: the old limit = max(20, max_eval/dim**2) settles at ≈1.3·dim² leaves whatever the budget is — 5 leaves at d = 2, and the root cannot split before evaluation 250 of 1000). 25 is the smallest population for which a leaf’s best is a statistic rather than a single draw, and it puts the d = 2 tree at ~40 leaves, the resolution the consumers (Random, RegionUCB, Archive.per_leaf_best) are written for.

panobbgo.analyzers.splitter.MAX_LEAVES = 512#

Hard cap on the number of leaves. Everything in the analyzer that is not O(1) per result is O(#leaves) per split (_new_box’s scans, leafs.remove), so the tree costs O(L²) over a run; 512 keeps that below a millisecond-scale contribution on the dispatcher thread at every (dim, budget) in the plan of record.

panobbgo.analyzers.splitter.SPLIT_RULES = ('widest', 'value')#

How the split dimension is chosen. "widest" is the historical rule (widest dimension the results differ in, function values ignored); "value" scores each candidate dimension by how strongly the objective separates across the prospective cut. See Splitter.Box._split_dim().

class panobbgo.analyzers.splitter.Splitter(strategy, split_rule=None, cut_rule=None, leaf_size=None, min_leaf_size=None, max_leaves=None, legacy=False, name=None)[source]#

Bases: Analyzer

Manages a tree of splits. Each split in this tree is a box, which partitions the search space into smaller boxes and can have children. Boxes without children are leafs.

The goal for this splitter is to balance between the depth level of splits and the number of points inside such a box.

A heuristic can build upon this hierarchy to investigate interesting subregions.

Parameters:
  • strategy (StrategyBase) – the owning strategy.

  • split_rule – "widest" (default, see DEFAULT_SPLIT_RULE) or "value"; see SPLIT_RULES.

  • leaf_size – target mean number of results per leaf (default LEAF_SIZE). The resolution of the tree is max_eval / leaf_size leaves.

  • min_leaf_size – floor on the split threshold, so a leaf is never cut before it holds enough points to say anything. Default 2 * dim + 2 — the number of points a linear trend in dim variables needs, plus a margin.

  • max_leaves – cap on the number of leaves (default MAX_LEAVES); it raises the split threshold rather than refusing splits, so the partition stays a proper kd-tree.

  • cut_rule – "mean" (default, see DEFAULT_CUT_RULE; measured in DISCOVERY §39) or "median" — where along the chosen dimension the cut falls.

  • legacy – True restores the pre-2026-09-10 analyzer exactly — limit = max(20, max_eval / dim**2), split_rule = "widest" and cut_rule = "mean". Every other knob is ignored. Kept so both trees are runnable from one code base and a measurement can be paired.

  • strategy

  • name (str)

@type strategy: StrategyBase

class Box(parent, splitter, box)[source]#

Bases: object

Used by Splitter, therefore nested.

Most important routine is split().

Note

In the future, this might be refactored to allow different splitting methods.

MAX_DEPTH = 60#

A box deeper than this is never split again. Depth grows by one per split, so the bound is generous for any real search; it exists only so a pathological point cloud cannot deepen the tree without end.

add_result(result)[source]#

Registers and adds a new Result. In particular, it adds the given result to the current box and it’s children (also all descendents).

If the current box is a leaf and too big, the split() routine is called.

Note

box += result is fine, too.

contains(point)[source]#

true, if given point is inside this box (including boundaries).

property fx#

Function value of best point in this particular box.

get_child_boxes(point)[source]#

returns all immediate child boxes, which contain given point.

property leaf#

returns true, if this box is a leaf. i.e. no children

property log_volume#

Returns the logarithmic volume of this box.

property ranges#

Gives back a vector with all the ranges of this box, i.e. upper - lower bound.

property results#

The results in this box, in arrival order.

A leaf and the root hold their list; any other box drops it when it is split and recomputes it on demand (Splitter._results_in()). len(box) never rebuilds it.

split(dim=None)[source]#

Arguments:

- ``dim``: Dimension, along which to split. (default: `None`, and calculated)
property volume#

Returns the volume of the box.

Note

Currently, the exponential of log_volume

get_box(point)[source]#

return “leftmost” leaf box, where given point is contained in

get_leaf(result)[source]#

returns the leaf box, where given result is currently sitting in

on_new_results(results)[source]#
on_new_split(box, children, dim)[source]#
on_refresh_best(candidates)[source]#

Called when the definition of “best” changes (e.g. ALM parameter update). We need to re-evaluate the local best for all leaf boxes and update the global best box.

target_leaves()[source]#

Leaf count this configuration aims at — max_eval / leaf_size, clipped, and re-derived from the realised integer threshold so it matches what a run actually builds.

class panobbgo.analyzers.Archive(strategy, k: int = 256, name: str | None = None)[source]#

Bases: Analyzer

Bounded top-K of the shared result stream, ranked by the constraint handler’s ordering (rank_key).

With a time-varying handler (time_invariant is False, e.g. dynamic penalty or augmented Lagrangian) the retained entries are re-ranked under the current ordering before a batch or a query whenever the number of results has changed since the last re-rank (the time these handlers move with), so the heap order does not go stale; which results were admitted earlier still reflects the ordering at the time.

Thread-safety: results arrive on the event-bus thread, queries come from heuristics on the main thread; one lock covers every read and write of the heap.

Parameters:
  • strategy (StrategyBase) – the owning strategy.

  • k – how many results to retain (default DEFAULT_K).

  • name (str) – optional module name; defaults to "Archive".

  • strategy

  • name

@type strategy: StrategyBase

diverse_k(k: int, *, pool: int = 4, box: Any = None) → List[Result][source]#

k well-separated good results: greedy max–min over the top pool*k.

The incumbent is always the first pick; each further pick maximises the minimum distance to everything picked so far, measured in box-normalised coordinates so the selection does not depend on the units of a dimension. This is the selector that hands a second arm a spread rather than a cluster around one basin.

on_new_results(results: Iterable[Result]) → None[source]#

Fold every result into the bounded top-K. O(log K) per result (plus an O(K) re-rank per batch for a time-varying handler).

penalty_of(r: Result) → float[source]#

Scalar penalty value of r, inf when it cannot be evaluated.

A magnitude, not the ranking: with a lexicographic handler it can order two results differently from top_k().

per_leaf_best(k: int) → List[Result][source]#

Best point of each of the k best Splitter leaves.

Returns [] when no Splitter is registered — the only selector that depends on a second analyzer, and the only one that can hand out points from different basins by construction.

property results: List[Result]#

Every retained result, best first.

top_k(k: int, *, box: Any = None, exclude_who: Any = None, fx_max: float | None = None) → List[Result][source]#

The k best retained results, best first.

Parameters:
  • box – restrict to results inside this region — either a Box (anything with a contains method) or a (dim, 2) array of bounds.

  • exclude_who – a who tag, or an iterable of them, to skip. Matching is by heuristic name, so "PSO" also drops "PSO:1a2b…".

  • fx_max – keep only results whose scalar penalty (penalty_of()) is <= fx_max.

class panobbgo.analyzers.Best(strategy)[source]#

Bases: Analyzer

Listens on all results, does accounting for “best” results, manages a pareto front of good points and emits the following events:

  • new_best: when a new “best” point,

  • new_min: a point with smallest objective function value,

  • new_cv: one with a smaller cv, or

  • new_pareto: when a best point on the pareto front of the objective value and constraint violation

    has been found.

Note

Pareto: Once the constraint violation is zero, only the objective function value is considered and future results with a positive constraint violation are ignored.

The best point (pareto) is available via the best attribute. There is also cv, min and pareto.

_images/pareto-front.png

This is an example of how several pareto fronts progress during the optimization.#

Parameters:

@type strategy: StrategyBase

property best#

Currently best Result.

Note

At the moment, this is pareto but might change.

property cv#

The point with currently minimal constraint violation, likely 0.0. If there are several points with the same minimal constraint violation, the value of the objective function is a secondary selection argument.

property min#

The point, with currently smallest objective function value.

on_new_cv(cv)[source]#

Report progress when a new constraint violation minimum is found.

on_new_min(min)[source]#

Report progress when a new global minimum is found.

on_new_pareto(pareto)[source]#
on_new_pareto_front(front)[source]#

Report progress when a new pareto front is found.

on_new_results(results)[source]#
on_refresh_best(candidates)[source]#

Handle a refresh_best event, which suggests candidate points that might be better than current best due to changed criteria (e.g. updated constraint weights).

property pareto#
property pareto_front#

This is the list of points building the current pareto front.

Note

This is a shallow copy.

class panobbgo.analyzers.Convergence(strategy, window_size=None, threshold=None, mode=None, min_evaluations=None)[source]#

Bases: Analyzer

Analyzes the progress of the optimization to detect convergence or stagnation.

It listens to new_results events and tracks the history of the best objective function values. If the improvement over a specified window of evaluations is below a threshold, or if the standard deviation of the best values in the window is small enough, it publishes a converged event.

Configuration parameters: a keyword argument wins; otherwise the strategy.config attribute in parentheses is used when it exists and is not None; otherwise the default. 0 / 0.0 are honoured.

  • window_size (convergence_window_size, int >= 1): Number of recent best values to consider (default: 50).

  • min_evaluations (convergence_min_evaluations, int): Minimum number of evaluations before checking convergence (default: window_size).

  • threshold (convergence_threshold, float): Threshold for relative improvement or std dev (default: 1e-6).

  • mode (convergence_mode, str): ‘std’ (standard deviation), ‘improv’ (relative improvement), or ‘slope’ (linear regression slope) (default: ‘std’).

  • (convergence_require_feasibility, bool): only converge on a feasible incumbent (default: False).

Events published: - converged: When convergence criteria are met.

The event carries reason (str) and stats (dict) with details.

Parameters:

@type strategy: StrategyBase

on_new_results(results)[source]#

Listen to all results to detect stagnation (no improvement for many evaluations).

class panobbgo.analyzers.FailureModel(strategy: Any, filter: bool = False, threshold: float = 0.5, prior: float = 1.0, k: int | None = None, repeat_tol: float = 1e-09, max_share: float = 0.5, max_rejects: int = 10, name: str | None = None)[source]#

Bases: Analyzer

Shared failure-region model: p_fail(x) / in_poison(x) from observed failures and successes.

Opt-in: add it to a strategy (StrategySpec.analyzers); nothing in a strategy without it changes. Thread-safety: results arrive on the event-bus thread, queries come from the main loop and from heuristics; one lock covers the labelled data.

Parameters:
  • strategy (StrategyBase) – The owning strategy.

  • filter – Reject candidates in poison zones in the strategy’s main loop (see the module docstring). False (default): the model only answers queries.

  • threshold – in_poison() is p_fail >= threshold.

  • prior – The success pseudo-count \(\alpha\).

  • k – Neighbour rank of the adaptive bandwidth; None: max(3, d + 1).

  • repeat_tol – Euclidean distance (normalised units) within which a point repeats a known failure.

  • max_share – Largest share of the box in_poison() may mark before it is disarmed.

  • max_rejects – Consecutive rejections of one heuristic’s candidates after which its next candidate passes.

  • name (str) – Module name; defaults to "FailureModel".

  • strategy

  • name

@type strategy: StrategyBase

add_failure(x: Any, kind: str = 'crash') → None[source]#

Record a failed evaluation at x (also the entry point for tests and other drivers).

add_success(x: Any) → None[source]#

Record a successful evaluation at x.

property armed: bool#

False while the model would mark more than max_share of the box (or knows no failure).

in_poison(x: Any) → Any[source]#

p_fail(x) >= threshold while armed, else False; a bool or a bool array like p_fail().

kinds: Dict[str, int]#

"crash", "timeout", "nan" -> count.

Type:

Failure kinds seen

property n_fail: int#
property n_ok: int#
n_rejected#

Diagnostics.

on_failed_evaluations(points: List[Any]) → None[source]#

A crashed evaluation (no result) is a failure at its point.

on_new_results(results: List[Any]) → None[source]#

Label every result: finite value -> success; timed out / non-finite -> failure.

p_fail(x: Any) → Any[source]#

Estimated probability that evaluating x fails: a float for one point, an array for m x d.

poisoned_share() → float[source]#

Share of the fixed probe points the model marks (p >= threshold), before the guard.

Computed lazily, on the first query after the data changed, and amortised: exactly on every change (a new failure or success) while the last share is above SHARE_NEAR * max_share (close to the guard) or the model knows at most SHARE_EXACT_UP_TO failures; otherwise only once the failures or the labelled points have grown by 10 %. New successes can raise the share as well as lower it (they shrink the bandwidths h_n and r_k), so a share cached far below the guard can lag the exact one; that lag is what the SHARE_NEAR band absorbs. The guard is therefore not a hard guarantee between recomputes, only near the threshold: tested on a half-box failure region sampled uniformly and then by successes only (tests/test_failure_model.py). One evaluation costs N_PROBES queries.

reject(points: List[Any]) → List[bool][source]#

Which of points (candidates, in order) the filter rejects; updates the per-heuristic streaks.

A candidate of a heuristic whose last max_rejects candidates were all rejected passes (liveness; see the module docstring). Returns all False without any work while the model knows no failure.

class panobbgo.analyzers.Restart(strategy, patience=None, improvement_threshold=1e-06, max_restarts=10, restart_strategy='random')[source]#

Bases: Analyzer

Detects search stagnation and publishes restart events.

Listens to new_results, tracks the best result of the current epoch (the stretch since the last restart), and fires a restart event when no sufficient improvement on it is found within patience evaluations. The epoch best is reset on every restart: a fresh basin is judged on its own progress, not on whether it already beats the global incumbent (which it almost never can within patience evaluations — all max_restarts would fire back to back). As at the start of the run, the first result of a new epoch establishes its baseline. That result is simply the next one to arrive — possibly a point proposed before the restart and still in flight, i.e. from the old basin. It is not filtered out: an old-basin baseline is at worst a bit too good, so the new basin gets patience evaluations to beat it rather than to beat itself, which is the pre-epoch behaviour for those few evaluations and no worse.

Configuration parameters:

  • patience (int): Evaluations without improvement before restart (default: 5 * dim).

  • improvement_threshold (float): Minimum relative improvement to reset counter (default: 1e-6).

  • max_restarts (int): Stop restarting after this many (default: 10).

  • restart_strategy (str): How to pick the new center. One of:

    • "random" — uniform draw inside the box (default).

    • "diverse" — uniform draw inside the box, picked from 20 candidates to maximize the minimum distance to previous restart centers. Strong coverage signal once a few restarts have fired.

    • "sphere" — Gaussian draw centered at the box centre with std = ranges / 6 (clipped to the box). Useful when the optimum is expected to lie inside the box rather than near its boundary; biases the restart cloud toward the centroid.

Events published:

  • restart(center=ndarray, reason=str): Suggested new center for search.

Parameters:

@type strategy: StrategyBase

SUPPORTED_RESTART_STRATEGIES = ('random', 'diverse', 'sphere')#
on_new_results(results)[source]#
property restart_count: int#

Number of restarts triggered so far.

class panobbgo.analyzers.Sensitivity(strategy, min_samples=None, update_interval=50, method='spearman')[source]#

Bases: Analyzer

Estimates per-dimension sensitivity from evaluation history.

Listens to new_results events, accumulates X and y, and periodically computes importance scores for each dimension.

"spearman" only needs the order of the results, and takes it from the constraint handler’s ranking key (rank_key, the ordering Best uses). "partial" regresses on magnitudes, so it uses the scalar get_penalty_value surrogate. Both are recorded when a result arrives; with a time-varying handler they reflect the ordering at that time.

Configuration parameters:

  • min_samples (int): Minimum evaluations before first analysis (default: 10 * dim).

  • update_interval (int): Recompute every N new results (default: 50).

  • method (str): "spearman" (rank correlation) or "partial" (partial correlation).

Events published:

  • new_sensitivity(importance=ndarray): Array of shape (dim,), values in [0, 1].

Parameters:

@type strategy: StrategyBase

property importance: ndarray | None#

Current importance scores, or None if not yet computed.

on_new_results(results)[source]#
class panobbgo.analyzers.Splitter(strategy, split_rule=None, cut_rule=None, leaf_size=None, min_leaf_size=None, max_leaves=None, legacy=False, name=None)[source]#

Bases: Analyzer

Manages a tree of splits. Each split in this tree is a box, which partitions the search space into smaller boxes and can have children. Boxes without children are leafs.

The goal for this splitter is to balance between the depth level of splits and the number of points inside such a box.

A heuristic can build upon this hierarchy to investigate interesting subregions.

Parameters:
  • strategy (StrategyBase) – the owning strategy.

  • split_rule – "widest" (default, see DEFAULT_SPLIT_RULE) or "value"; see SPLIT_RULES.

  • leaf_size – target mean number of results per leaf (default LEAF_SIZE). The resolution of the tree is max_eval / leaf_size leaves.

  • min_leaf_size – floor on the split threshold, so a leaf is never cut before it holds enough points to say anything. Default 2 * dim + 2 — the number of points a linear trend in dim variables needs, plus a margin.

  • max_leaves – cap on the number of leaves (default MAX_LEAVES); it raises the split threshold rather than refusing splits, so the partition stays a proper kd-tree.

  • cut_rule – "mean" (default, see DEFAULT_CUT_RULE; measured in DISCOVERY §39) or "median" — where along the chosen dimension the cut falls.

  • legacy – True restores the pre-2026-09-10 analyzer exactly — limit = max(20, max_eval / dim**2), split_rule = "widest" and cut_rule = "mean". Every other knob is ignored. Kept so both trees are runnable from one code base and a measurement can be paired.

  • strategy

  • name (str)

@type strategy: StrategyBase

class Box(parent, splitter, box)[source]#

Bases: object

Used by Splitter, therefore nested.

Most important routine is split().

Note

In the future, this might be refactored to allow different splitting methods.

MAX_DEPTH = 60#

A box deeper than this is never split again. Depth grows by one per split, so the bound is generous for any real search; it exists only so a pathological point cloud cannot deepen the tree without end.

add_result(result)[source]#

Registers and adds a new Result. In particular, it adds the given result to the current box and it’s children (also all descendents).

If the current box is a leaf and too big, the split() routine is called.

Note

box += result is fine, too.

contains(point)[source]#

true, if given point is inside this box (including boundaries).

property fx#

Function value of best point in this particular box.

get_child_boxes(point)[source]#

returns all immediate child boxes, which contain given point.

property leaf#

returns true, if this box is a leaf. i.e. no children

property log_volume#

Returns the logarithmic volume of this box.

property ranges#

Gives back a vector with all the ranges of this box, i.e. upper - lower bound.

property results#

The results in this box, in arrival order.

A leaf and the root hold their list; any other box drops it when it is split and recomputes it on demand (Splitter._results_in()). len(box) never rebuilds it.

split(dim=None)[source]#

Arguments:

- ``dim``: Dimension, along which to split. (default: `None`, and calculated)
property volume#

Returns the volume of the box.

Note

Currently, the exponential of log_volume

get_box(point)[source]#

return “leftmost” leaf box, where given point is contained in

get_leaf(result)[source]#

returns the leaf box, where given result is currently sitting in

on_new_results(results)[source]#
on_new_split(box, children, dim)[source]#
on_refresh_best(candidates)[source]#

Called when the definition of “best” changes (e.g. ALM parameter update). We need to re-evaluate the local best for all leaf boxes and update the global best box.

target_leaves()[source]#

Leaf count this configuration aims at — max_eval / leaf_size, clipped, and re-derived from the realised integer threshold so it matches what a run actually builds.