# optimize

Python reference for `nagasim.optimize.optimize`.

`nagasim.optimize.optimize`

```python
optimize(layout, factors, response: str, goal: str = 'min', constraints = (), budget: int = 300, replications_per_point: int = 5, method: str = 'auto', seed: int = 0, confidence: float = 0.95, indifference: float | None = None, workers: int = 1, run_length = None, warmup = None, max_replications_per_point = None, select_top: int = 3, on_progress = None, should_stop = None, evaluator = None, warm_start_points: list[dict] | None = None, pool = None, min_improvement: float = _MIN_IMPROVEMENT, record_logs = None, objectives = None, logic = None, controllers = None, log_level = None, statistic: str = 'mean', penalties = (), holdout: int = 0, holdout_seed: int | None = None, baseline: bool = False)
```

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
----------
layout : dict or str
    The model, or a path to it.
factors : list of Factor
    What to vary: an override path, a kind and bounds.
response : str
    The KPI key to optimise.
goal : {"min", "max"}, default "min"
    Direction of the response.
constraints : sequence, default ()
    Feasibility conditions on other KPIs.
budget : int, default 300
    Hard cap on replications.
replications_per_point : int, default 5
    Replications of each evaluated point.
method : {"auto", "pattern", "optuna", "optuna-gp", "optuna-nsga2"}, default "auto"
    ``"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.
objectives : sequence of (kpi, goal), optional
    The objectives of ``"optuna-nsga2"`` (at least two) instead of
    *response*/*goal*; ``best`` is then the front's winner on the first.
seed : int, default 0
    Seed of replication 0.
confidence : float, default 0.95
    Level of the intervals used to accept a move.
indifference : float, optional
    The difference below which two points count as equal in the selection.
workers : int, default 1
    Process-pool size.
run_length, warmup : optional
    Fall back to the model's own settings.
max_replications_per_point : int, optional
    Cap for the extra replications of an ambiguous comparison.
select_top : int, default 3
    Points the final selection compares.
on_progress, should_stop : callable, optional
    As in `nagasim.api.run_model`.
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.
warm_start_points : list of dict, optional
    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.
pool : ProcessPoolExecutor, optional
    A pool the caller owns (best built with `nagasim.api.new_pool`).
min_improvement : float, default 0.01
    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".
record_logs : bool, optional
    As in `nagasim.api.run_model`.
log_level : str, optional
    The level every point runs at (D1395); by default the lowest that records the
    response, the constraints, the objectives and the penalties.
statistic : str, default "mean"
    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).
penalties : sequence of (kpi, weight), default ()
    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, default 0
    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``.
baseline : bool, default False
    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.

Returns
-------
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
