Skip to content

optimize

Python reference for nagasim.optimize.optimize.

Search the factor space for the best response within a replication budget.

The winner is confirmed with ranking and selection (select_best).

The built-in method (method="auto" or "pattern", no extra dependency) works in these steps:

  1. Seed the search with a Latin hypercube of about 10 * n_factors points, bounded by the budget, each run for replications_per_point replications on the same seeds as every other point (common random numbers, so differences between points have low variance).
  2. Take the best of them as the incumbent: feasibility first, then the mean.
  3. Try the 2n coordinate neighbours of the incumbent at each factor's own current step (a fraction of its range, rounded for integer factors and clipped to the bounds).
  4. A neighbour replaces the incumbent only if it wins: it is feasible where the incumbent is not, or a paired-t interval on the per-replication differences, at confidence, excludes 0 in its favour.
  5. An ambiguous challenger (better mean, interval straddling 0) gets more replications, and so does the incumbent on the same seeds, up to max_replications_per_point, then is retested once.
  6. The winning factor's step doubles only when the gain is at least min_improvement of the objective's own size; an axis whose neighbours beat nothing is halved, and a full sweep with no move halves every axis. The search converges when every factor's step is below its own grid unit.
  7. Finally select_best (KN) runs over the top select_top distinct points on whatever budget is left, for a statistically defensible winner.

Every point is cached on its rounded coordinates, so an integer factor never pays for the same point twice, and history records each evaluation. The budget is a hard cap: an evaluation that would exceed it is not run.

Parameters:

Name Type Description Default
layout dict or str

The model, or a path to it.

required
factors list of Factor

What to vary: an override path, a kind and bounds.

required
response str

The KPI key to optimise.

required
goal ('min', 'max')

Direction of the response.

"min"
constraints sequence

Feasibility conditions on other KPIs.

()
budget int

Hard cap on replications.

300
replications_per_point int

Replications of each evaluated point.

5
method ('auto', 'pattern', 'optuna', 'optuna-gp', 'optuna-nsga2')

"optuna" runs optuna's TPE sampler instead (optional dependency, imported lazily) and finishes with the same selection step. "optuna-gp" uses optuna's Gaussian-process sampler, better on small budgets and smooth responses; it needs torch, and without it the search falls back to multivariate TPE (result.sampler says which ran). "optuna-nsga2" is multi-objective over objectives and returns the non-dominated set in result.pareto instead of one confirmed winner.

"auto"
objectives sequence of (kpi, goal)

The objectives of "optuna-nsga2" (at least two) instead of response/goal; best is then the front's winner on the first.

None
seed int

Seed of replication 0.

0
confidence float

Level of the intervals used to accept a move.

0.95
indifference float

The difference below which two points count as equal in the selection.

None
workers int

Process-pool size.

1
run_length optional

Fall back to the model's own settings.

None
warmup optional

Fall back to the model's own settings.

None
max_replications_per_point int

Cap for the extra replications of an ambiguous comparison.

None
select_top int

Points the final selection compares.

3
on_progress callable

As in nagasim.api.run_model.

None
should_stop callable

As in nagasim.api.run_model.

None
evaluator optional

Replaces the internal evaluator, for a caller that needs its own response KPIs (as nagasim.calibrate does) or wants the cached per-replication values afterwards. It carries its own budget, so budget then only sizes the search's internal splits.

None
warm_start_points list of dict

Evaluated first, through the same gate as every other point, so they are simulated rather than trusted and count in budget. nagasim.surrogate.Surrogate.suggest proposes such points.

None
pool ProcessPoolExecutor

A pool the caller owns (best built with nagasim.api.new_pool).

None
min_improvement float

How much better a move must be, as a fraction of the objective's size, to count as a success: below it the point is still taken but the step does not widen and no replications are bought to settle it. 0 restores "any significant gain is a success".

0.01
record_logs bool

As in nagasim.api.run_model.

None
log_level str

The level every point runs at (D1395); by default the lowest that records the response, the constraints, the objectives and the penalties.

None
statistic str

The objective's statistic over a point's replications: "mean", or a percentile such as "p95" to optimise the tail (a makespan that must hold on 19 days in 20). A percentile has no t interval, so a move is accepted on a paired bootstrap interval of the difference (same seeds), and the final step tops the best points up to equal replications instead of KN selection, whose guarantee is about means (selection.guaranteed is then False).

"mean"
penalties sequence of (kpi, weight)

A composite objective: response's statistic plus weight x mean(kpi) for each pair with goal "min", minus it with goal "max", in the response's units ([("slot/Bay/Overflows", 30)] charges 30 time units per overflow): a positive weight always makes a point worse, a negative one rewards the KPI. Constraints stay separate.

()
holdout int

Replications on seeds the search never used (from holdout_seed, default seed + 1000000) for the final candidates and the baseline: the holdout frame, with each one's paired difference from the baseline when there is one. They are not counted in budget nor in budget_used.

0
baseline bool

Evaluate the model's own factor values first (trial 0 of every method, current_point), so the search knows where it starts and the holdout compares against it.

False

Returns:

Type Description
OptimizationResult

best (factor values), best_mean, history and the selection outcome; holdout and baseline when asked for.

See Also

nagasim.experiments.run_scenarios : Compare points you name yourself. nagasim.calibrate.calibrate : Search for parameters that reproduce observations.

Examples:

>>> from pathlib import Path
>>> import nagasim
>>> from nagasim.optimize import Factor, optimize
>>> path = Path(nagasim.__file__).parent / "models" / "single_server.json"
>>> factor = Factor(path="blocks.process_1.params.dist_params.rate",
...                 kind="continuous", low=1.1, high=2.0, name="rate")
>>> found = optimize(str(path), [factor], response="system/Avg Queue Length", goal="min",
...                  budget=12, replications_per_point=2, run_length=200, warmup=20, seed=0)
>>> 1.1 <= found.best["rate"] <= 2.0
True